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
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddTypeAnnotationToValueParameterFix.kt
1
3603
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.project.builtIns import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtCollectionLiteralExpression import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class AddTypeAnnotationToValueParameterFix(element: KtParameter) : KotlinQuickFixAction<KtParameter>(element) { private val typeNameShort: String? val typeName: String? init { val defaultValue = element.defaultValue var type = defaultValue?.getType(defaultValue.analyze(BodyResolveMode.PARTIAL)) if (type != null && KotlinBuiltIns.isArrayOrPrimitiveArray(type)) { if (element.hasModifier(KtTokens.VARARG_KEYWORD)) { type = if (KotlinBuiltIns.isPrimitiveArray(type)) element.builtIns.getArrayElementType(type) else type.arguments.singleOrNull()?.type } else if (defaultValue is KtCollectionLiteralExpression) { val builtIns = element.builtIns val elementType = builtIns.getArrayElementType(type) if (KotlinBuiltIns.isPrimitiveType(elementType)) { type = builtIns.getPrimitiveArrayKotlinTypeByPrimitiveKotlinType(elementType) } } } typeNameShort = type?.let { IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(it) } typeName = type?.let { IdeDescriptorRenderers.SOURCE_CODE.renderType(it) } } override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean { val element = element ?: return false return element.typeReference == null && typeNameShort != null } override fun getFamilyName() = KotlinBundle.message("fix.add.type.annotation.family") override fun getText() = element?.let { KotlinBundle.message("fix.add.type.annotation.text", typeNameShort.toString(), it.name.toString()) } ?: "" override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return if (typeName != null) { element.typeReference = KtPsiFactory(element).createType(typeName) ShortenReferences.DEFAULT.process(element) } } companion object Factory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): AddTypeAnnotationToValueParameterFix? { val element = Errors.VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION.cast(diagnostic).psiElement if (element.defaultValue == null) return null return AddTypeAnnotationToValueParameterFix(element) } } }
apache-2.0
0227e885ea0db49d6fcb1d3e68857bda
47.053333
158
0.725784
4.928865
false
false
false
false
mdaniel/intellij-community
python/src/com/jetbrains/python/console/actions/ShowCommandQueueAction.kt
3
2247
// 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.jetbrains.python.console.actions import com.intellij.execution.runners.ExecutionUtil import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.ToggleAction import com.intellij.openapi.project.DumbAware import com.jetbrains.python.PyBundle import com.jetbrains.python.console.PyConsoleUtil import com.jetbrains.python.console.PydevConsoleRunner.CONSOLE_COMMUNICATION_KEY import com.jetbrains.python.console.PythonConsoleView import icons.PythonIcons import javax.swing.Icon /*** * Action for showing the CommandQueue window */ class ShowCommandQueueAction(private val consoleView: PythonConsoleView) : ToggleAction(PyBundle.message("python.console.command.queue.show.action.text"), PyBundle.message("python.console.command.queue.show.action.description"), emptyQueueIcon), DumbAware { companion object { private val emptyQueueIcon = PythonIcons.Python.CommandQueue private val notEmptyQueueIcon = ExecutionUtil.getLiveIndicator(emptyQueueIcon) @JvmStatic fun isCommandQueueIcon(icon: Icon): Boolean = icon == emptyQueueIcon || icon == notEmptyQueueIcon } override fun update(e: AnActionEvent) { super.update(e) val communication = consoleView.file.getCopyableUserData(CONSOLE_COMMUNICATION_KEY) communication?.let { if (PyConsoleUtil.isCommandQueueEnabled(consoleView.project)) { e.presentation.isEnabled = true if (PyConsoleUtil.isCommandQueueEmpty(communication)) { e.presentation.icon = emptyQueueIcon } else { e.presentation.icon = notEmptyQueueIcon } } else { e.presentation.icon = emptyQueueIcon e.presentation.isEnabled = false } } } override fun isSelected(e: AnActionEvent): Boolean { return consoleView.isShowQueue } override fun setSelected(e: AnActionEvent, state: Boolean) { consoleView.isShowQueue = state if (state) { consoleView.showQueue() } else { consoleView.restoreQueueWindow(false) } } }
apache-2.0
34db7c5a030100ebb8548c8cc6e16c3b
33.584615
158
0.737428
4.661826
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/serialonly/MRTUltralightTransitData.kt
1
2192
/* * MRTUltralightTransitData.kt * * Copyright 2018 Google * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.transit.serialonly import au.id.micolous.metrodroid.card.ultralight.UltralightCard import au.id.micolous.metrodroid.card.ultralight.UltralightCardTransitFactory import au.id.micolous.metrodroid.multi.Parcelize import au.id.micolous.metrodroid.transit.TransitIdentity import au.id.micolous.metrodroid.util.NumberUtils /** * MRT Ultralight cards. */ private const val NAME = "MRT Ultralight" private fun formatSerial(sn: Int) = "0001 ${NumberUtils.formatNumber(sn.toLong(), " ", 4, 4, 4)}" private fun getSerial(card: UltralightCard) = card.getPage(15).data.byteArrayToInt() @Parcelize data class MRTUltralightTransitData(private val mSerial: Int) : SerialOnlyTransitData() { constructor(card: UltralightCard) : this(mSerial = getSerial(card)) override val serialNumber get() = formatSerial(mSerial) override val cardName get() = NAME override val reason // The first 16 pages are readable but they don't change as the card is used. // Other pages are password-locked get() = Reason.LOCKED } class MRTUltralightTransitFactory : UltralightCardTransitFactory { override fun parseTransitIdentity(card: UltralightCard) = TransitIdentity( NAME, formatSerial(getSerial(card))) override fun parseTransitData(card: UltralightCard) = MRTUltralightTransitData(card) override fun check(card: UltralightCard) = card.getPage(3).data.byteArrayToInt() == 0x204f2400 }
gpl-3.0
7158a188b939b176567e1ba3c7762f11
34.934426
97
0.750456
4.239845
false
false
false
false
team401/SnakeSkin
SnakeSkin-Core/src/main/kotlin/org/snakeskin/state/TickedActionManager.kt
1
1231
package org.snakeskin.state import org.snakeskin.executor.ExceptionHandlingRunnable import org.snakeskin.executor.IExecutorTaskHandle import org.snakeskin.executor.impl.NullExecutorTaskHandle import org.snakeskin.measure.time.TimeMeasureSeconds import org.snakeskin.runtime.SnakeskinRuntime import org.snakeskin.utility.Ticker class TickedActionManager(condition: () -> Boolean, val actionRunnable: () -> Unit, timeThreshold: TimeMeasureSeconds, override val rate: TimeMeasureSeconds): IStateActionManager { private var handle: IExecutorTaskHandle = NullExecutorTaskHandle private val executor = SnakeskinRuntime.primaryExecutor override val asyncTransition = false private val ticker = Ticker(condition, timeThreshold, rate) private val exRunnable = ExceptionHandlingRunnable { synchronized(this) { if (ticker.check()) { actionRunnable() } } } override fun startAction() { ticker.reset() handle = executor.schedulePeriodicTask(exRunnable, rate) } override fun stopAction() { handle.stopTask(false) } override fun awaitDone() { synchronized(this) {} //Unblocks as soon as lock is free } }
gpl-3.0
ff70d14e4048789cda3cfb45b703130e
32.297297
180
0.723802
4.904382
false
false
false
false
JavaEden/Orchid-Core
plugins/OrchidSearch/src/main/kotlin/com/eden/orchid/search/SearchIndexGenerator.kt
2
4456
package com.eden.orchid.search import com.eden.common.json.JSONElement import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.generators.OrchidGenerator import com.eden.orchid.api.generators.emptyModel import com.eden.orchid.api.indexing.OrchidIndex import com.eden.orchid.api.options.annotations.BooleanDefault import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.render.RenderService import com.eden.orchid.api.resources.resource.JsonResource import com.eden.orchid.api.theme.pages.OrchidPage import com.eden.orchid.api.theme.pages.OrchidReference import com.eden.orchid.impl.generators.ExternalIndexGenerator @Description("Generates index files to connect your site to others.", name = "Indices") class SearchIndexGenerator : OrchidGenerator<OrchidGenerator.Model>(GENERATOR_KEY, Stage.META) { companion object { const val GENERATOR_KEY = "indices" } @Option @Description("A list of generator keys whose pages are considered in this taxonomy.") lateinit var includeFrom: Array<String> @Option @Description("A list of generator keys whose pages are ignored by this taxonomy.") lateinit var excludeFrom: Array<String> @Option @BooleanDefault(false) @Description("Whether to create a JSON file for each page in your site, with a path of the page plus .json") var createSinglePageIndexFiles: Boolean = false override fun startIndexing(context: OrchidContext): Model { return emptyModel() } override fun startGeneration(context: OrchidContext, model: Model) { generateSiteIndexFiles(context) if(createSinglePageIndexFiles) { generatePageIndexFiles(context) } } private fun generateSiteIndexFiles(context: OrchidContext) { val indices = OrchidIndex(null, "index") // Render an page for each generator's individual index val enabledGeneratorKeys = context.getGeneratorKeys(includeFrom, excludeFrom) context.index.allIndexedPages.filter { it.key in enabledGeneratorKeys }.forEach { (key, value) -> if(key === ExternalIndexGenerator.GENERATOR_KEY) return@forEach // don't create search indices for externally-indexed pages val jsonElement = JSONElement(value.first.toJSON(true, false)) val reference = OrchidReference(context, "meta/$key.index.json") val resource = JsonResource(reference, jsonElement) val page = OrchidPage(resource, RenderService.RenderMode.RAW, "index", null) page.reference.isUsePrettyUrl = false context.render(page) indices.addToIndex(indices.ownKey + "/" + page.reference.path, page) } // Render full composite index page val compositeJsonElement = JSONElement(context.index.toJSON(true, false)) val compositeReference = OrchidReference(context, "meta/all.index.json") val compositeIndexResource = JsonResource(compositeReference, compositeJsonElement) val compositeIndexPage = OrchidPage(compositeIndexResource, RenderService.RenderMode.RAW, "index", null) compositeIndexPage.reference.isUsePrettyUrl = false context.render(compositeIndexPage) indices.addToIndex(indices.ownKey + "/" + compositeIndexPage.reference.path, compositeIndexPage) // Render an index of all indices, so individual index pages can be found for (page in indices.allPages) { page.data = HashMap() } val indexResource = JsonResource(OrchidReference(context, "meta/index.json"), JSONElement(indices.toJSON(false, false))) val indicesPage = OrchidPage(indexResource, RenderService.RenderMode.RAW, "index", null) indicesPage.reference.isUsePrettyUrl = false context.render(indicesPage) } private fun generatePageIndexFiles(context: OrchidContext) { context.index.allPages.forEach { page -> val jsonElement = JSONElement(page.toJSON(true, true)) val reference = OrchidReference(page.reference) val resource = JsonResource(reference, jsonElement) val pageIndex = OrchidPage(resource, RenderService.RenderMode.RAW, "pageIndex", null) pageIndex.reference.isUsePrettyUrl = false pageIndex.reference.outputExtension = "json" context.render(pageIndex) } } }
mit
d458a343f0f7e150f23b9d741e9e1deb
44.469388
135
0.719928
4.584362
false
false
false
false
anitaa1990/DeviceInfo-Sample
deviceinfo/src/main/java/com/an/deviceinfo/userapps/UserApps.kt
1
697
package com.an.deviceinfo.userapps import org.json.JSONObject import java.io.Serializable class UserApps : Serializable { var appName: String? = null var packageName: String? = null var versionName: String? = null var versionCode: Int = 0 fun toJSON(): JSONObject? { val jsonObject = JSONObject() try { jsonObject.put("appName", appName) jsonObject.put("packageName", packageName) jsonObject.put("versionName", versionName) jsonObject.put("versionCode", versionCode) return jsonObject } catch (e: Exception) { e.printStackTrace() return null } } }
apache-2.0
821354b73168ee9e18b352710cea9960
21.483871
54
0.605452
4.874126
false
false
false
false
iPoli/iPoli-android
app/src/test/java/io/ipoli/android/TimeSpek.kt
1
3685
package io.ipoli.android import io.ipoli.android.common.datetime.Time import io.ipoli.android.common.datetime.TimeOfDay import org.amshove.kluent.`should be equal to` import org.amshove.kluent.`should be false` import org.amshove.kluent.`should be true` import org.amshove.kluent.`should be` import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it /** * Created by Venelin Valkov <[email protected]> * on 11/30/17. */ class TimeSpek : Spek({ describe("Time") { describe("is between") { it("should include startDate time") { val result = Time.atHours(9).isBetween(Time.atHours(9), Time.atHours(10)) result.`should be true`() } it("should include end time") { val result = Time.atHours(9).isBetween(Time.atHours(8), Time.atHours(9)) result.`should be true`() } it("should be inside time interval") { val result = Time.atHours(9).isBetween(Time.atHours(8), Time.atHours(10)) result.`should be true`() } it("should be outside time interval") { val result = Time.atHours(7).isBetween(Time.atHours(8), Time.atHours(10)) result.`should be false`() } it("should wrap around 00:00") { val result1 = Time.atHours(23).isBetween(Time.atHours(22), Time.atHours(9)) val result2 = Time.atHours(6).isBetween(Time.atHours(22), Time.atHours(9)) val result3 = Time.atHours(21).isBetween(Time.atHours(22), Time.atHours(9)) val result4 = Time.atHours(10).isBetween(Time.atHours(22), Time.atHours(9)) result1.`should be true`() result2.`should be true`() result3.`should be false`() result4.`should be false`() } it("should be inside interval when all times are same") { val result = Time.atHours(23).isBetween(Time.atHours(23), Time.atHours(23)) result.`should be true`() } it("should be outside interval when startDate & end times are same") { val result = Time.atHours(22).isBetween(Time.atHours(23), Time.atHours(23)) result.`should be false`() } } describe("minutes between") { it("should have 0 minutes between same times") { Time.atHours(22).minutesTo(Time.atHours(22)).`should be equal to`(0) } it("should have 1 minute between times") { Time.atHours(22).minutesTo(Time.at(22, 1)).`should be equal to`(1) } it("should have 120 minutes to midnight") { Time.atHours(22).minutesTo(Time.atHours(0)).`should be equal to`(120) } it("should have 240 minutes to 2 a.m.") { Time.atHours(22).minutesTo(Time.atHours(2)).`should be equal to`(240) } } describe("toTimeOfDay") { it("should be morning at 9:00") { Time.atHours(9).timeOfDay.`should be`(TimeOfDay.MORNING) } it("should be afternoon at 13:00") { Time.atHours(13).timeOfDay.`should be`(TimeOfDay.AFTERNOON) } it("should be evening at 18:00") { Time.atHours(18).timeOfDay.`should be`(TimeOfDay.EVENING) } it("should be night at 22:00") { Time.atHours(22).timeOfDay.`should be`(TimeOfDay.NIGHT) } } } })
gpl-3.0
abef07bc52815913d3562f6aa1f2ed2f
34.442308
91
0.553867
3.920213
false
false
false
false
GunoH/intellij-community
plugins/performanceTesting/src/com/jetbrains/performancePlugin/utils/errors/ToDirectoryWritingErrorCollector.kt
2
1698
package com.jetbrains.performancePlugin.utils.errors import com.intellij.openapi.diagnostic.ExceptionWithAttachments import com.intellij.openapi.diagnostic.Logger import com.intellij.util.ExceptionUtil import com.intellij.util.io.createDirectories import com.intellij.util.io.outputStream import com.intellij.util.io.write import java.nio.file.Path import java.util.concurrent.atomic.AtomicInteger class ToDirectoryWritingErrorCollector( private val presentableName: String, private val directory: Path, private val limitOfErrors: Int ) : ErrorCollector { private val logger = Logger.getInstance("error-collector-$presentableName") private val nextErrorId = AtomicInteger() override fun addError(error: Throwable) { val errorId = nextErrorId.incrementAndGet() if (errorId > limitOfErrors) { throw RuntimeException("Too many errors reported for $presentableName") } val errorHome = directory.resolve("error-$errorId") errorHome.createDirectories() logger.warn("Error #$errorId has been collected. Details will be saved to $errorHome. Message: ${error.message ?: error.javaClass.name}") errorHome.resolve("stacktrace.txt").write(ExceptionUtil.getThrowableText(error)) if (error is ExceptionWithAttachments) { for (attachment in error.attachments) { val attachmentPath = errorHome.resolve(attachment.path) attachmentPath.outputStream().use { os -> attachment.openContentStream().copyTo(os) } } } } override fun <T> runCatchingError(computation: () -> T): T? = runCatching(computation).onFailure { addError(it) }.getOrNull() override val numberOfErrors get() = nextErrorId.get() }
apache-2.0
df8f7fa0579ec7d7de5b0c2bac6e76bf
35.148936
141
0.749117
4.398964
false
false
false
false
GunoH/intellij-community
plugins/settings-sync/tests/com/intellij/settingsSync/SettingsSyncPluginManagerTest.kt
2
8607
package com.intellij.settingsSync import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.SettingsCategory import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.util.Disposer import com.intellij.settingsSync.plugins.PluginManagerProxy import com.intellij.settingsSync.plugins.SettingsSyncPluginManager import com.intellij.settingsSync.plugins.SettingsSyncPluginsState import com.intellij.settingsSync.plugins.SettingsSyncPluginsState.PluginData import com.intellij.testFramework.LightPlatformTestCase import com.intellij.testFramework.replaceService class SettingsSyncPluginManagerTest : LightPlatformTestCase() { private lateinit var pluginManager: SettingsSyncPluginManager private lateinit var testPluginManager: TestPluginManager private val quickJump = TestPluginDescriptor( "QuickJump", listOf(TestPluginDependency("com.intellij.modules.platform", isOptional = false)) ) private val typengo = TestPluginDescriptor( "codeflections.typengo", listOf(TestPluginDependency("com.intellij.modules.platform", isOptional = false)) ) private val ideaLight = TestPluginDescriptor( "color.scheme.IdeaLight", listOf(TestPluginDependency("com.intellij.modules.lang", isOptional = false)) ) private val git4idea = TestPluginDescriptor( "git4idea", listOf(TestPluginDependency("com.intellij.modules.platform", isOptional = false)), bundled = true ) override fun setUp() { super.setUp() SettingsSyncSettings.getInstance().syncEnabled = true testPluginManager = TestPluginManager() ApplicationManager.getApplication().replaceService(PluginManagerProxy::class.java, testPluginManager, testRootDisposable) pluginManager = SettingsSyncPluginManager() Disposer.register(testRootDisposable, pluginManager) } fun `test install missing plugins`() { pluginManager.pushChangesToIde(state { quickJump(enabled = false) typengo(enabled = true) ideaLight(enabled = true, category = SettingsCategory.UI) }) val installedPluginIds = testPluginManager.installer.installedPluginIds // NB: quickJump should be skipped because it is disabled assertEquals(2, installedPluginIds.size) assertTrue(installedPluginIds.containsAll(listOf(typengo.idString, ideaLight.idString))) } fun `test do not install when plugin sync is disabled`() { SettingsSyncSettings.getInstance().setCategoryEnabled(SettingsCategory.PLUGINS, false) try { pluginManager.pushChangesToIde(state { quickJump(enabled = false) typengo(enabled = true) ideaLight(enabled = true, category = SettingsCategory.UI) }) val installedPluginIds = testPluginManager.installer.installedPluginIds // IdeaLight is a UI plugin, it doesn't fall under PLUGINS category assertEquals(1, installedPluginIds.size) assertTrue(installedPluginIds.contains(ideaLight.idString)) } finally { SettingsSyncSettings.getInstance().setCategoryEnabled(SettingsCategory.PLUGINS, true) } } fun `test do not install UI plugin when UI category is disabled`() { SettingsSyncSettings.getInstance().setCategoryEnabled(SettingsCategory.UI, false) try { pluginManager.pushChangesToIde(state { quickJump(enabled = false) typengo(enabled = true) ideaLight(enabled = true, category = SettingsCategory.UI) }) val installedPluginIds = testPluginManager.installer.installedPluginIds // IdeaLight is a UI plugin, it doesn't fall under PLUGINS category assertEquals(1, installedPluginIds.size) assertTrue(installedPluginIds.contains(typengo.idString)) } finally { SettingsSyncSettings.getInstance().setCategoryEnabled(SettingsCategory.UI, true) } } fun `test disable installed plugin`() { testPluginManager.addPluginDescriptors(pluginManager, quickJump) pluginManager.updateStateFromIdeOnStart(null) assertPluginManagerState { quickJump(enabled = true) } pluginManager.pushChangesToIde(state { quickJump(enabled = false) typengo(enabled = true) ideaLight(enabled = true, category = SettingsCategory.UI) }) assertFalse(quickJump.isEnabled) assertIdeState { quickJump(enabled = false) } } fun `test disable two plugins at once`() { // install two plugins testPluginManager.addPluginDescriptors(pluginManager, quickJump, typengo) pluginManager.pushChangesToIde(state { quickJump(enabled = false) typengo(enabled = false) }) assertFalse(quickJump.isEnabled) assertFalse(typengo.isEnabled) } fun `test update state from IDE`() { testPluginManager.addPluginDescriptors(pluginManager, quickJump, typengo, git4idea) pluginManager.updateStateFromIdeOnStart(null) assertPluginManagerState { quickJump(enabled = true) typengo(enabled = true) } testPluginManager.disablePlugin(git4idea.pluginId) assertPluginManagerState { quickJump(enabled = true) typengo(enabled = true) git4idea(enabled = false) } testPluginManager.disablePlugin(typengo.pluginId) testPluginManager.enablePlugin(git4idea.pluginId) assertPluginManagerState { quickJump(enabled = true) typengo(enabled = false) } } fun `test do not remove entries about disabled plugins which are not installed`() { testPluginManager.addPluginDescriptors(pluginManager, typengo, git4idea) val savedState = state { quickJump(enabled = false) typengo(enabled = true) git4idea(enabled = true) } pluginManager.updateStateFromIdeOnStart(savedState) assertPluginManagerState { quickJump(enabled = false) typengo(enabled = true) // git4idea is removed because existing bundled enabled plugin is the default state } } fun `test push settings to IDE`() { testPluginManager.addPluginDescriptors(pluginManager, quickJump, typengo, git4idea) pluginManager.updateStateFromIdeOnStart(null) pluginManager.pushChangesToIde(state { quickJump(enabled = false) git4idea(enabled = false) }) assertIdeState { quickJump(enabled = false) typengo(enabled = true) git4idea(enabled = false) } pluginManager.pushChangesToIde(state { quickJump(enabled = false) }) // no entry for the bundled git4idea plugin => it is enabled assertIdeState { quickJump(enabled = false) typengo(enabled = true) git4idea(enabled = true) } } private fun assertPluginManagerState(build: StateBuilder.() -> Unit) { val expectedState = state(build) assertState(expectedState.plugins, pluginManager.state.plugins) } private fun assertIdeState(build: StateBuilder.() -> Unit) { val expectedState = state(build) val actualState = PluginManagerProxy.getInstance().getPlugins().associate { plugin -> plugin.pluginId to PluginData(plugin.isEnabled) } assertState(expectedState.plugins, actualState) } private fun assertState(expectedStates: Map<PluginId, PluginData>, actualStates: Map<PluginId, PluginData>) { fun stringifyStates(states: Map<PluginId, PluginData>) = states.entries .sortedBy { it.key } .joinToString { (id, data) -> "$id: ${enabledOrDisabled(data.enabled)}" } if (expectedStates.size != actualStates.size) { assertEquals("Expected and actual states have different number of elements", stringifyStates(expectedStates), stringifyStates(actualStates)) } for ((expectedId, expectedData) in expectedStates) { val actualData = actualStates[expectedId] assertNotNull("Record for plugin $expectedId not found", actualData) assertEquals("Plugin $expectedId has incorrect state", expectedData.enabled, actualData!!.enabled) } } private fun enabledOrDisabled(value: Boolean?) = if (value == null) "null" else if (value) "enabled" else "disabled" private fun state(build: StateBuilder.() -> Unit): SettingsSyncPluginsState { val builder = StateBuilder() builder.build() return SettingsSyncPluginsState(builder.states) } private class StateBuilder { val states = mutableMapOf<PluginId, PluginData>() operator fun TestPluginDescriptor.invoke( enabled: Boolean, category: SettingsCategory = SettingsCategory.PLUGINS): Pair<PluginId, PluginData> { val pluginData = PluginData(enabled, category) states[pluginId] = pluginData return this.pluginId to pluginData } } }
apache-2.0
66dd87eb61533ae6ebff22b7991cc935
33.15873
125
0.73022
4.70071
false
true
false
false
mihkels/graphite-client-kotlin
graphite-sender/src/main/kotlin/com/mihkels/gobblin/gobblin/BashExecuteService.kt
1
1617
package com.mihkels.gobblin.gobblin import com.mihkels.graphite.bash.BashExecutor import com.mihkels.graphite.client.GraphiteMetric import mu.KLogging import org.springframework.stereotype.Service import java.time.Instant @Service class BashExecuteService( private val executorSettings: ScriptExecutorSettings, private val bashExecutor: BashExecutor, private val metricsCreator: MetricsCreator ) { companion object: KLogging() fun executeService(): List<GraphiteMetric> { val collectedOutput = mutableListOf<GraphiteMetric>() bashExecutor.runDirectory(executorSettings.scriptDirectory, {output, scriptName -> collectedOutput.add(metricsCreator.createMetric(output, cleanupFallbackName(scriptName))) }) return collectedOutput } private fun cleanupFallbackName(fullScriptPath: String): String { val startPosition = fullScriptPath.lastIndexOf("/") + 1 val endPositon = fullScriptPath.lastIndexOf(".") - 1 return fullScriptPath.substring(startPosition..endPositon).replace("_", ".") } } @Service class MetricsCreator { fun createMetric(inputLine: String, fallbackName: String): GraphiteMetric { val metricGroups = inputLine.replace("\n", "").split(" ") val metricName = if (metricGroups.size == 3) metricGroups[0] else fallbackName return if (metricGroups.size >= 2) { GraphiteMetric(metricName, metricGroups[1], metricGroups[2].toLong()) } else { GraphiteMetric(metricName, metricGroups[0], Instant.now().toEpochMilli()) } } }
mit
4d969aa55145a231ca614a406c09ba4c
34.152174
101
0.706246
4.491667
false
false
false
false
RoyaAoki/Megumin
common/src/main/java/com/sqrtf/common/api/ApiClient.kt
1
4198
package com.sqrtf.common.api import android.annotation.SuppressLint import android.content.Context import android.util.Log import com.franmontiel.persistentcookiejar.PersistentCookieJar import com.franmontiel.persistentcookiejar.cache.SetCookieCache import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor import okhttp3.OkHttpClient import okhttp3.ResponseBody import retrofit2.Converter import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import java.lang.IllegalStateException import okhttp3.ConnectionSpec import okhttp3.TlsVersion import android.os.Build import javax.net.ssl.SSLContext /** * Created by roya on 2017/5/22. */ object ApiClient { private var instance: ApiService? = null private var retrofit: Retrofit? = null private var cookieJar: PersistentCookieJar? = null fun init(context: Context, server: String) { instance = create(context, server) } fun deinit() { cookieJar?.clear() cookieJar = null retrofit = null instance = null } fun getInstance(): ApiService { if (instance != null) { return instance as ApiService } throw IllegalStateException("ApiClient Not being initialized") } fun converterErrorBody(error: ResponseBody): MessageResponse? { if (retrofit == null) { throw IllegalStateException("ApiClient Not being initialized") } val errorConverter: Converter<ResponseBody, MessageResponse> = (retrofit as Retrofit).responseBodyConverter(MessageResponse::class.java, arrayOfNulls<Annotation>(0)) try { return errorConverter.convert(error) } catch (e: Throwable) { return null } } @SuppressLint("ObsoleteSdkInt") private fun OkHttpClient.Builder.enableTls12OnPreLollipop(): OkHttpClient.Builder { if (Build.VERSION.SDK_INT in 16..21) { try { val sc = SSLContext.getInstance("TLSv1.2") sc.init(null, null, null) this.sslSocketFactory(Tls12SocketFactory(sc.socketFactory)) val cs = ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) .tlsVersions(TlsVersion.TLS_1_2) .supportsTlsExtensions(true) .build() val specs = ArrayList<ConnectionSpec>() specs.add(cs) specs.add(ConnectionSpec.COMPATIBLE_TLS) specs.add(ConnectionSpec.CLEARTEXT) this.connectionSpecs(specs) } catch (exc: Exception) { Log.e("OkHttpTLSCompat", "Error while setting TLS 1.2", exc) } } return this } private fun create(context: Context, server: String): ApiService { cookieJar = PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(context)) val okHttp = OkHttpClient.Builder() .followRedirects(true) .followSslRedirects(true) .retryOnConnectionFailure(true) .cookieJar(cookieJar) .addInterceptor { val request = it.request() val response = it.proceed(request) val body = response.body() val bodyString = body?.string() Log.i("TAG", response.toString() + " Body:" + bodyString) response.newBuilder() .headers(response.headers()) .body(ResponseBody.create(body?.contentType(), bodyString)) .build() } .enableTls12OnPreLollipop() .build() retrofit = Retrofit.Builder() .client(okHttp) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(server) .build() return (retrofit as Retrofit).create(ApiService::class.java) } }
mit
333e9d532e56fc1613564f6142c1d4c0
32.584
120
0.611243
5.240949
false
false
false
false
AntonovAlexander/activecore
hwast/src/hw_dim_static.kt
1
1359
/* * hw_dim_static.kt * * Created on: 05.06.2019 * Author: Alexander Antonov <[email protected]> * License: See LICENSE file for details */ package hwast class hw_dim_static() : ArrayList<hw_dim_range_static>() { constructor(imm_value : String) : this() { // TODO: compute width according to value val new_range = hw_dim_range_static(31, 0) add(new_range) } constructor(msb: Int, lsb: Int) : this() { val new_range = hw_dim_range_static(msb, lsb) add(new_range) } constructor(width: Int) : this() { val new_range = hw_dim_range_static(width-1, 0) add(new_range) } fun add(msb: Int, lsb: Int) { add(hw_dim_range_static(msb, lsb)) } fun GetPower(): Int { var ret_val: Int = 0 for (dimrange in this) { if (dimrange.msb != dimrange.lsb) continue else ret_val++ } return ret_val; } fun isSingle(): Boolean { if (size == 0) return true if (size == 1) { if (get(0).GetWidth() == 1) return true } return false; } fun Print() { print("dimensions:") for (dim_range_static in this) { print(" [" + dim_range_static.msb + ":" + dim_range_static.lsb + "]") } print("\n") } }
apache-2.0
774b1812f96db5e3a28fd341fa7dc170
22.859649
81
0.522443
3.431818
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/platform/mixin/folding/MixinFoldingSettings.kt
1
993
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.folding import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage @State(name = "MixinFoldingSettings", storages = [Storage("minecraft_dev.xml")]) class MixinFoldingSettings : PersistentStateComponent<MixinFoldingSettings.State> { data class State( var foldTargetDescriptors: Boolean = true, var foldObjectCasts: Boolean = false ) private var state = State() override fun getState(): State = this.state override fun loadState(state: State) { this.state = state } companion object { val instance: MixinFoldingSettings get() = ServiceManager.getService(MixinFoldingSettings::class.java) } }
mit
d3187e84040ed55405e22a289f4abbef
24.461538
83
0.724068
4.534247
false
false
false
false
lucasgcampos/kotlin-for-android-developers
KotlinAndroid/app/src/main/java/com/lucasgcampos/kotlinandroid/ui/adapters/ForecastListAdapter.kt
1
1903
package com.lucasgcampos.kotlinandroid.ui.adapters import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.lucasgcampos.kotlinandroid.R import com.lucasgcampos.kotlinandroid.domain.model.Forecast import com.lucasgcampos.kotlinandroid.domain.model.ForecastList import com.lucasgcampos.kotlinandroid.extensions.ctx import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.adapter_forecast.view.* import java.text.DateFormat import java.util.* class ForecastListAdapter(val weekForecast: ForecastList, val itemClick: (Forecast) -> Unit): RecyclerView.Adapter<ForecastListAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.ctx).inflate(R.layout.adapter_forecast, parent, false) return ViewHolder(view, itemClick) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bindForecast(weekForecast[position]) } override fun getItemCount() = weekForecast.size() class ViewHolder(view: View, val itemClick: (Forecast) -> Unit) : RecyclerView.ViewHolder(view) { fun bindForecast(forecast: Forecast) { with(forecast) { Picasso.with(itemView.ctx).load(iconUrl).into(itemView.icon) itemView.date.text = convertDate(date.toLong()) itemView.description.text = description itemView.maxTemperature.text = "${high}º" itemView.minTemperature.text = "${low}º" itemView.setOnClickListener { itemClick(this) } } } private fun convertDate(date: Long): String { val df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault()) return df.format(date) } } }
mit
cf382e989601174f2924c421a92d2cda
37.02
150
0.709627
4.400463
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/readinglist/ReadingListSyncBehaviorDialogs.kt
1
4201
package org.wikipedia.readinglist import android.app.Activity import android.content.DialogInterface import androidx.appcompat.app.AlertDialog import org.wikipedia.R import org.wikipedia.WikipediaApp import org.wikipedia.analytics.LoginFunnel import org.wikipedia.databinding.DialogWithCheckboxBinding import org.wikipedia.events.ReadingListsEnableSyncStatusEvent import org.wikipedia.login.LoginActivity import org.wikipedia.page.LinkMovementMethodExt import org.wikipedia.readinglist.sync.ReadingListSyncAdapter import org.wikipedia.settings.Prefs import org.wikipedia.settings.SettingsActivity.Companion.newIntent import org.wikipedia.util.FeedbackUtil.showAndroidAppFAQ import org.wikipedia.util.StringUtil object ReadingListSyncBehaviorDialogs { private var PROMPT_LOGIN_TO_SYNC_DIALOG_SHOWING = false fun detectedRemoteTornDownDialog(activity: Activity) { AlertDialog.Builder(activity) .setCancelable(false) .setTitle(R.string.reading_list_turned_sync_off_dialog_title) .setMessage(R.string.reading_list_turned_sync_off_dialog_text) .setPositiveButton(R.string.reading_list_turned_sync_off_dialog_ok, null) .setNegativeButton(R.string.reading_list_turned_sync_off_dialog_settings ) { _: DialogInterface?, _: Int -> activity.startActivity(newIntent(activity)) } .show() } @JvmStatic fun promptEnableSyncDialog(activity: Activity) { if (!Prefs.shouldShowReadingListSyncEnablePrompt() || Prefs.isSuggestedEditsHighestPriorityEnabled()) { return } val binding = DialogWithCheckboxBinding.inflate(activity.layoutInflater) binding.dialogMessage.text = StringUtil.fromHtml(activity.getString(R.string.reading_list_prompt_turned_sync_on_dialog_text)) binding.dialogMessage.movementMethod = LinkMovementMethodExt { _: String -> showAndroidAppFAQ(activity) } AlertDialog.Builder(activity) .setCancelable(false) .setTitle(R.string.reading_list_prompt_turned_sync_on_dialog_title) .setView(binding.root) .setPositiveButton(R.string.reading_list_prompt_turned_sync_on_dialog_enable_syncing ) { _: DialogInterface, _: Int -> ReadingListSyncAdapter.setSyncEnabledWithSetup() } .setNegativeButton(R.string.reading_list_prompt_turned_sync_on_dialog_no_thanks, null) .setOnDismissListener { Prefs.shouldShowReadingListSyncEnablePrompt(!binding.dialogCheckbox.isChecked) WikipediaApp.getInstance().bus.post(ReadingListsEnableSyncStatusEvent()) } .show() } @JvmStatic fun promptLogInToSyncDialog(activity: Activity) { if (!Prefs.shouldShowReadingListSyncEnablePrompt() || PROMPT_LOGIN_TO_SYNC_DIALOG_SHOWING) { return } val binding = DialogWithCheckboxBinding.inflate(activity.layoutInflater) binding.dialogMessage.text = StringUtil.fromHtml(activity.getString(R.string.reading_lists_login_reminder_text_with_link)) binding.dialogMessage.movementMethod = LinkMovementMethodExt { _: String -> showAndroidAppFAQ(activity) } AlertDialog.Builder(activity) .setCancelable(false) .setTitle(R.string.reading_list_login_reminder_title) .setView(binding.root) .setPositiveButton(R.string.reading_list_preference_login_or_signup_to_enable_sync_dialog_login ) { _: DialogInterface, _: Int -> val loginIntent = LoginActivity.newIntent(activity, LoginFunnel.SOURCE_READING_MANUAL_SYNC) activity.startActivity(loginIntent) } .setNegativeButton(R.string.reading_list_prompt_turned_sync_on_dialog_no_thanks, null) .setOnDismissListener { PROMPT_LOGIN_TO_SYNC_DIALOG_SHOWING = false Prefs.shouldShowReadingListSyncEnablePrompt(!binding.dialogCheckbox.isChecked) } .show() PROMPT_LOGIN_TO_SYNC_DIALOG_SHOWING = true } }
apache-2.0
3865cdbde1b5460261bed471f7978d26
51.5125
133
0.690788
4.611416
false
false
false
false
komu/scratch
src/main/kotlin/plots/Plot.kt
1
643
package plots import jetbrains.letsPlot.export.ggsave import jetbrains.letsPlot.geom.geom_histogram import jetbrains.letsPlot.ggplot import jetbrains.letsPlot.label.ggtitle import java.util.* fun main() { // Plot example val rand = Random() val data = mapOf<String, Any>( "x" to List(500) { rand.nextGaussian() } + List(500) { rand.nextGaussian() + 1.0 }, "c" to List(500) { "A" } + List(500) { "B" } ) val geom = geom_histogram(alpha = 0.3, size = 0.0) { x = "x"; fill = "c" } val p = ggplot(data) + geom + ggtitle("The normal distribution") ggsave(p, "normal-distribution.png") }
mit
d139cd2c1e86e120c26c2e19e73b2e6c
25.791667
91
0.623639
3.091346
false
false
false
false
dahlstrom-g/intellij-community
json/src/com/intellij/jsonpath/ui/JsonPathEvaluateFileView.kt
7
2060
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.jsonpath.ui import com.intellij.json.JsonLanguage import com.intellij.json.json5.Json5Language import com.intellij.json.psi.JsonFile import com.intellij.openapi.project.Project import com.intellij.openapi.util.ModificationTracker import com.intellij.psi.PsiAnchor import com.intellij.psi.util.PsiModificationTracker import com.intellij.util.ui.components.BorderLayoutPanel import com.intellij.util.ui.update.MergingUpdateQueue import com.intellij.util.ui.update.Update internal class JsonPathEvaluateFileView(project: Project, jsonFile: JsonFile) : JsonPathEvaluateView(project) { private val expressionHighlightingQueue: MergingUpdateQueue = MergingUpdateQueue("JSONPATH_EVALUATE", 1000, true, null, this) private val fileAnchor: PsiAnchor = PsiAnchor.create(jsonFile) private val jsonChangeTrackers: List<ModificationTracker> = listOf(JsonLanguage.INSTANCE, Json5Language.INSTANCE).map { PsiModificationTracker.getInstance(project).forLanguage(it) } @Volatile private var previousModificationCount: Long = 0 init { val content = BorderLayoutPanel() content.addToTop(searchWrapper) content.addToCenter(resultWrapper) setContent(content) initToolbar() val messageBusConnection = this.project.messageBus.connect(this) messageBusConnection.subscribe(PsiModificationTracker.TOPIC, PsiModificationTracker.Listener { expressionHighlightingQueue.queue(Update.create(this@JsonPathEvaluateFileView) { detectChangesInJson() }) }) } private fun detectChangesInJson() { val count = previousModificationCount val newCount = jsonChangeTrackers.sumOf { it.modificationCount } if (newCount != count) { previousModificationCount = newCount // some JSON documents have been changed resetExpressionHighlighting() } } public override fun getJsonFile(): JsonFile? { return fileAnchor.retrieve() as? JsonFile } }
apache-2.0
17388bbfbffb66ebd83fd65c7d77207f
36.472727
127
0.782524
4.587973
false
false
false
false
dahlstrom-g/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/codeVision/ui/renderers/painters/CodeVisionListPainter.kt
4
5114
package com.intellij.codeInsight.codeVision.ui.renderers.painters import com.intellij.codeInsight.codeVision.CodeVisionEntry import com.intellij.codeInsight.codeVision.ui.model.CodeVisionListData import com.intellij.codeInsight.codeVision.ui.model.ProjectCodeVisionModel import com.intellij.codeInsight.codeVision.ui.model.RangeCodeVisionModel import com.intellij.codeInsight.codeVision.ui.renderers.providers.painter import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.editor.markup.TextAttributes import java.awt.Dimension import java.awt.Graphics import java.awt.Point import java.awt.Rectangle class CodeVisionListPainter( private val delimiterPainter: ICodeVisionGraphicPainter = DelimiterPainter(), theme: CodeVisionTheme? = null ) : ICodeVisionEntryBasePainter<CodeVisionListData?> { val theme = theme ?: CodeVisionTheme() var loadingPainter = CodeVisionStringPainter("Loading...") private fun getRelativeBounds( editor: Editor, state: RangeCodeVisionModel.InlayState, value: CodeVisionListData? ): Map<CodeVisionEntry, Rectangle> { val map = HashMap<CodeVisionEntry, Rectangle>() value ?: return map var x = theme.left val y = 0 val delimiterWidth = delimiterPainter.size(editor, state).width for ((index, it) in value.visibleLens.withIndex()) { val painter = it.painter() val size = painter.size(editor, state, it) map[it] = Rectangle(x, y, size.width, size.height) x += size.width if (index < value.visibleLens.size - 1) { x += delimiterWidth } } val moreEntry = value.projectModel.moreEntry x += delimiterWidth val size = moreEntry.painter().size(editor, state, moreEntry) map[moreEntry] = Rectangle(x, y, size.width, size.height) return map } override fun paint( editor: Editor, textAttributes: TextAttributes, g: Graphics, value: CodeVisionListData?, point: Point, state: RangeCodeVisionModel.InlayState, hovered: Boolean ) { var x = point.x + theme.left val y = point.y + theme.top + (editor as EditorImpl).ascent if (value == null || value.visibleLens.isEmpty()) { loadingPainter.paint(editor, textAttributes, g, Point(x, y), state, hovered) return } val relativeBounds = getRelativeBounds(editor, state, value) val delimiterWidth = delimiterPainter.size(editor, state).width for ((index, it) in value.visibleLens.withIndex()) { val painter = it.painter() val size = relativeBounds[it] ?: continue painter.paint(editor, textAttributes, g, it, Point(x, y), state, value.isHoveredEntry(it)) x += size.width if (index < value.visibleLens.size - 1 || hovered) { delimiterPainter.paint(editor, textAttributes, g, Point(x, y), state, false) x += delimiterWidth } } if (hovered) { val moreEntry = value.projectModel.moreEntry moreEntry.painter().paint( editor, textAttributes, g, moreEntry, Point(x, y), state, value.isHoveredEntry(moreEntry) ) } } override fun size( editor: Editor, state: RangeCodeVisionModel.InlayState, value: CodeVisionListData? ): Dimension { if (value == null) { return loadingSize(editor, state) } val moreEntry = value.projectModel.moreEntry val settingsWidth = moreEntry.painter().size(editor, state, moreEntry).width val list = value.visibleLens.map { it.painter().size(editor, state, it).width } return if (value.visibleLens.isEmpty()) { loadingSize(editor, state) } else { val delimiterWidth = delimiterPainter.size(editor, state).width Dimension( list.sum() + (delimiterWidth * list.size - 1) + theme.left + theme.right + settingsWidth, editor.lineHeight + theme.top + theme.bottom ) } } private fun loadingSize(editor: Editor, state: RangeCodeVisionModel.InlayState) = Dimension( loadingPainter.size(editor, state).width + theme.left + theme.right, editor.lineHeight + theme.top + theme.bottom ) private fun isHovered(x: Int, y: Int, size: Rectangle): Boolean { return x >= size.x && x <= (size.x + size.width) } fun hoveredEntry(editor: Editor, state: RangeCodeVisionModel.InlayState, value: CodeVisionListData?, x: Int, y: Int): CodeVisionEntry? { val relativeBounds = getRelativeBounds(editor, state, value) for (entry in relativeBounds) { if (isHovered(x, y, entry.value)) { return if (entry.key.providerId == ProjectCodeVisionModel.MORE_PROVIDER_ID) { value?.let { if (it.isMoreLensActive()) entry.key else { null } } } else entry.key } } return null } fun hoveredEntryBounds( editor: Editor, state: RangeCodeVisionModel.InlayState, value: CodeVisionListData?, element: CodeVisionEntry ): Rectangle? = getRelativeBounds(editor, state, value)[element] }
apache-2.0
e0a2a8fee45380b0cda7ca0db124fb83
29.628743
138
0.675401
4.12087
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/itemviewholder/DlgContextMenu.kt
1
27349
package jp.juggler.subwaytooter.itemviewholder import android.annotation.SuppressLint import android.app.Dialog import android.content.res.ColorStateList import android.view.Gravity import android.view.View import android.view.ViewGroup import android.view.WindowManager import android.widget.Button import android.widget.ImageButton import android.widget.LinearLayout import android.widget.TextView import androidx.appcompat.widget.AppCompatButton import androidx.core.content.ContextCompat import jp.juggler.subwaytooter.ActMain import jp.juggler.subwaytooter.ActText import jp.juggler.subwaytooter.R import jp.juggler.subwaytooter.action.* import jp.juggler.subwaytooter.actmain.nextPosition import jp.juggler.subwaytooter.api.entity.* import jp.juggler.subwaytooter.column.Column import jp.juggler.subwaytooter.column.ColumnType import jp.juggler.subwaytooter.databinding.DlgContextMenuBinding import jp.juggler.subwaytooter.dialog.DlgListMember import jp.juggler.subwaytooter.dialog.DlgQRCode import jp.juggler.subwaytooter.pref.PrefB import jp.juggler.subwaytooter.pref.PrefI import jp.juggler.subwaytooter.span.MyClickableSpan import jp.juggler.subwaytooter.table.FavMute import jp.juggler.subwaytooter.table.SavedAccount import jp.juggler.subwaytooter.table.UserRelation import jp.juggler.subwaytooter.util.* import jp.juggler.util.* import org.jetbrains.anko.allCaps import org.jetbrains.anko.backgroundDrawable import java.util.* @SuppressLint("InflateParams") internal class DlgContextMenu( val activity: ActMain, private val column: Column, private val whoRef: TootAccountRef?, private val status: TootStatus?, private val notification: TootNotification? = null, private val contentTextView: TextView? = null, ) : View.OnClickListener, View.OnLongClickListener { // companion object { // private val log = LogCategory("DlgContextMenu") // } private val accessInfo = column.accessInfo private val relation: UserRelation private val dialog: Dialog private val views = DlgContextMenuBinding.inflate(activity.layoutInflater) // private fun <T : View> fv(@IdRes id: Int): T = viewRoot.findViewById(id) // // private val btnGroupStatusCrossAccount: Button = fv(R.id.btnGroupStatusCrossAccount) // private val llGroupStatusCrossAccount: View = fv(R.id.llGroupStatusCrossAccount) // private val btnGroupStatusAround: Button = fv(R.id.btnGroupStatusAround) // private val llGroupStatusAround: View = fv(R.id.llGroupStatusAround) // private val btnGroupStatusByMe: Button = fv(R.id.btnGroupStatusByMe) // private val llGroupStatusByMe: View = fv(R.id.llGroupStatusByMe) // private val btnGroupStatusExtra: Button = fv(R.id.btnGroupStatusExtra) // private val llGroupStatusExtra: View = fv(R.id.llGroupStatusExtra) // private val btnGroupUserCrossAccount: Button = fv(R.id.btnGroupUserCrossAccount) // private val llGroupUserCrossAccount: View = fv(R.id.llGroupUserCrossAccount) // private val btnGroupUserExtra: Button = fv(R.id.btnGroupUserExtra) // private val llGroupUserExtra: View = fv(R.id.llGroupUserExtra) init { val columnType = column.type val who = whoRef?.get() val status = this.status this.relation = when { who == null -> UserRelation() accessInfo.isPseudo -> UserRelation.loadPseudo(accessInfo.getFullAcct(who)) else -> UserRelation.load(accessInfo.db_id, who.id) } this.dialog = Dialog(activity) dialog.setContentView(views.root) dialog.setCancelable(true) dialog.setCanceledOnTouchOutside(true) views.root.scan { v -> when (v) { is Button -> v.setOnClickListener(this) is ImageButton -> v.setOnClickListener(this) } } arrayOf( views.btnBlock, views.btnFollow, views.btnMute, views.btnProfile, views.btnQuoteAnotherAccount, views.btnQuoteTootBT, views.btnSendMessage, ).forEach { it.setOnLongClickListener(this) } val accountList = SavedAccount.loadAccountList(activity) val accountListNonPseudo = ArrayList<SavedAccount>() for (a in accountList) { if (!a.isPseudo) { accountListNonPseudo.add(a) // if( a.host.equalsIgnoreCase( access_info.host ) ){ // account_list_non_pseudo_same_instance.add( a ); // } } } if (status == null) { views.llStatus.visibility = View.GONE views.llLinks.visibility = View.GONE } else { val statusByMe = accessInfo.isMe(status.account) if (PrefB.bpLinksInContextMenu(activity.pref) && contentTextView != null) { var insPos = 0 fun addLinkButton(span: MyClickableSpan, caption: String) { val b = AppCompatButton(activity) val lp = LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) b.layoutParams = lp b.backgroundDrawable = ContextCompat.getDrawable(activity, R.drawable.btn_bg_transparent_round6dp) b.gravity = Gravity.START or Gravity.CENTER_VERTICAL b.minHeight = (activity.density * 32f + 0.5f).toInt() b.minimumHeight = (activity.density * 32f + 0.5f).toInt() val padLr = (activity.density * 8f + 0.5f).toInt() val padTb = (activity.density * 4f + 0.5f).toInt() b.setPaddingRelative(padLr, padTb, padLr, padTb) b.text = caption b.allCaps = false b.setOnClickListener { dialog.dismissSafe() span.onClick(contentTextView) } views.llLinks.addView(b, insPos++) } val dc = status.decoded_content for (span in dc.getSpans(0, dc.length, MyClickableSpan::class.java)) { val caption = span.linkInfo.text when (caption.firstOrNull()) { '@', '#' -> addLinkButton(span, caption) else -> addLinkButton(span, span.linkInfo.url) } } } views.btnStatusHistory.vg(status.time_edited_at > 0L && columnType != ColumnType.STATUS_HISTORY) ?.text = activity.getString(R.string.edit_history) + "\n" + TootStatus.formatTime(activity, status.time_edited_at, bAllowRelative = false) views.llLinks.vg(views.llLinks.childCount > 1) views.btnGroupStatusByMe.vg(statusByMe) views.btnQuoteTootBT.vg(status.reblogParent != null) views.btnBoostWithVisibility.vg(!accessInfo.isPseudo && !accessInfo.isMisskey) views.btnReportStatus.vg(!(statusByMe || accessInfo.isPseudo)) val applicationName = status.application?.name if (statusByMe || applicationName == null || applicationName.isEmpty()) { views.btnMuteApp.visibility = View.GONE } else { views.btnMuteApp.text = activity.getString(R.string.mute_app_of, applicationName) } val canPin = status.canPin(accessInfo) views.btnProfileUnpin.vg(canPin && status.pinned) views.btnProfilePin.vg(canPin && !status.pinned) } val bShowConversationMute = when { status == null -> false accessInfo.isMe(status.account) -> true notification != null && TootNotification.TYPE_MENTION == notification.type -> true else -> false } val muted = status?.muted ?: false views.btnConversationMute.vg(bShowConversationMute) ?.setText( when { muted -> R.string.unmute_this_conversation else -> R.string.mute_this_conversation } ) views.llNotification.vg(notification != null) val colorButtonAccent = PrefI.ipButtonFollowingColor(activity.pref).notZero() ?: activity.attrColor(R.attr.colorImageButtonAccent) val colorButtonError = PrefI.ipButtonFollowRequestColor(activity.pref).notZero() ?: activity.attrColor(R.attr.colorRegexFilterError) val colorButtonNormal = activity.attrColor(R.attr.colorImageButton) fun showRelation(relation: UserRelation) { // 被フォロー状態 // Styler.setFollowIconとは異なり細かい状態を表示しない views.ivFollowedBy.vg(relation.followed_by) // フォロー状態 // Styler.setFollowIconとは異なりミュートやブロックを表示しない views.btnFollow.setImageResource( when { relation.getRequested(who) -> R.drawable.ic_follow_wait relation.getFollowing(who) -> R.drawable.ic_follow_cross else -> R.drawable.ic_follow_plus } ) views.btnFollow.imageTintList = ColorStateList.valueOf( when { relation.getRequested(who) -> colorButtonError relation.getFollowing(who) -> colorButtonAccent else -> colorButtonNormal } ) // ミュート状態 views.btnMute.imageTintList = ColorStateList.valueOf( when (relation.muting) { true -> colorButtonAccent else -> colorButtonNormal } ) // ブロック状態 views.btnBlock.imageTintList = ColorStateList.valueOf( when (relation.blocking) { true -> colorButtonAccent else -> colorButtonNormal } ) } if (accessInfo.isPseudo) { // 疑似アカミュートができたのでアカウントアクションを表示する showRelation(relation) views.llAccountActionBar.visibility = View.VISIBLE views.ivFollowedBy.vg(false) views.btnFollow.setImageResource(R.drawable.ic_follow_plus) views.btnFollow.imageTintList = ColorStateList.valueOf(activity.attrColor(R.attr.colorImageButton)) views.btnNotificationFrom.visibility = View.GONE } else { showRelation(relation) } val whoApiHost = getUserApiHost() val whoApDomain = getUserApDomain() views.llInstance .vg(whoApiHost.isValid) ?.let { val tvInstanceActions: TextView = views.tvInstanceActions tvInstanceActions.text = activity.getString(R.string.instance_actions_for, whoApDomain.pretty) // 疑似アカウントではドメインブロックできない // 自ドメインはブロックできない views.btnDomainBlock.vg( !(accessInfo.isPseudo || accessInfo.matchHost(whoApiHost)) ) views.btnDomainTimeline.vg( PrefB.bpEnableDomainTimeline(activity.pref) && !accessInfo.isPseudo && !accessInfo.isMisskey ) } if (who == null) { views.btnCopyAccountId.visibility = View.GONE views.btnOpenAccountInAdminWebUi.visibility = View.GONE views.btnOpenInstanceInAdminWebUi.visibility = View.GONE views.btnReportUser.visibility = View.GONE } else { views.btnCopyAccountId.visibility = View.VISIBLE views.btnCopyAccountId.text = activity.getString(R.string.copy_account_id, who.id.toString()) views.btnOpenAccountInAdminWebUi.vg(!accessInfo.isPseudo) views.btnOpenInstanceInAdminWebUi.vg(!accessInfo.isPseudo) views.btnReportUser.vg(!(accessInfo.isPseudo || accessInfo.isMe(who))) views.btnStatusNotification.vg(!accessInfo.isPseudo && accessInfo.isMastodon && relation.following) ?.text = when (relation.notifying) { true -> activity.getString(R.string.stop_notify_posts_from_this_user) else -> activity.getString(R.string.notify_posts_from_this_user) } } if (accessInfo.isPseudo) { views.btnProfile.visibility = View.GONE views.btnSendMessage.visibility = View.GONE views.btnEndorse.visibility = View.GONE } views.btnEndorse.text = when (relation.endorsed) { false -> activity.getString(R.string.endorse_set) else -> activity.getString(R.string.endorse_unset) } if (columnType != ColumnType.FOLLOW_REQUESTS) { views.btnFollowRequestOK.visibility = View.GONE views.btnFollowRequestNG.visibility = View.GONE } if (columnType != ColumnType.FOLLOW_SUGGESTION) { views.btnDeleteSuggestion.visibility = View.GONE } if (accountListNonPseudo.isEmpty()) { views.btnFollowFromAnotherAccount.visibility = View.GONE views.btnSendMessageFromAnotherAccount.visibility = View.GONE } if (accessInfo.isPseudo || who == null || !relation.getFollowing(who) || relation.following_reblogs == UserRelation.REBLOG_UNKNOWN ) { views.btnHideBoost.visibility = View.GONE views.btnShowBoost.visibility = View.GONE } else if (relation.following_reblogs == UserRelation.REBLOG_SHOW) { views.btnHideBoost.visibility = View.VISIBLE views.btnShowBoost.visibility = View.GONE } else { views.btnHideBoost.visibility = View.GONE views.btnShowBoost.visibility = View.VISIBLE } when { who == null -> { views.btnHideFavourite.visibility = View.GONE views.btnShowFavourite.visibility = View.GONE } FavMute.contains(accessInfo.getFullAcct(who)) -> { views.btnHideFavourite.visibility = View.GONE views.btnShowFavourite.visibility = View.VISIBLE } else -> { views.btnHideFavourite.visibility = View.VISIBLE views.btnShowFavourite.visibility = View.GONE } } views.btnListMemberAddRemove.visibility = View.VISIBLE updateGroup(views.btnGroupStatusCrossAccount, views.llGroupStatusCrossAccount) updateGroup(views.btnGroupUserCrossAccount, views.llGroupUserCrossAccount) updateGroup(views.btnGroupStatusAround, views.llGroupStatusAround) updateGroup(views.btnGroupStatusByMe, views.llGroupStatusByMe) updateGroup(views.btnGroupStatusExtra, views.llGroupStatusExtra) updateGroup(views.btnGroupUserExtra, views.llGroupUserExtra) } fun show() { val window = dialog.window if (window != null) { val lp = window.attributes lp.width = (0.5f + 280f * activity.density).toInt() lp.height = WindowManager.LayoutParams.WRAP_CONTENT window.attributes = lp } dialog.show() } private fun getUserApiHost(): Host = when (val whoHost = whoRef?.get()?.apiHost) { Host.UNKNOWN -> Host.parse(column.instanceUri) Host.EMPTY, null -> accessInfo.apiHost else -> whoHost } private fun getUserApDomain(): Host = when (val whoHost = whoRef?.get()?.apDomain) { Host.UNKNOWN -> Host.parse(column.instanceUri) Host.EMPTY, null -> accessInfo.apDomain else -> whoHost } private fun updateGroup(btn: Button, group: View, toggle: Boolean = false): Boolean { if (btn.visibility != View.VISIBLE) { group.vg(false) return true } when { PrefB.bpAlwaysExpandContextMenuItems(activity.pref) -> { group.vg(true) btn.background = null } toggle -> group.vg(group.visibility != View.VISIBLE) else -> btn.setOnClickListener(this) } val iconId = if (group.visibility == View.VISIBLE) { R.drawable.ic_arrow_drop_up } else { R.drawable.ic_arrow_drop_down } val iconColor = activity.attrColor(R.attr.colorTimeSmall) val drawable = createColoredDrawable(activity, iconId, iconColor, 1f) btn.setCompoundDrawablesRelativeWithIntrinsicBounds(drawable, null, null, null) return true } private fun onClickUpdateGroup(v: View): Boolean = when (v.id) { R.id.btnGroupStatusCrossAccount -> updateGroup( views.btnGroupStatusCrossAccount, views.llGroupStatusCrossAccount, toggle = true ) R.id.btnGroupUserCrossAccount -> updateGroup( views.btnGroupUserCrossAccount, views.llGroupUserCrossAccount, toggle = true ) R.id.btnGroupStatusAround -> updateGroup( views.btnGroupStatusAround, views.llGroupStatusAround, toggle = true ) R.id.btnGroupStatusByMe -> updateGroup( views.btnGroupStatusByMe, views.llGroupStatusByMe, toggle = true ) R.id.btnGroupStatusExtra -> updateGroup( views.btnGroupStatusExtra, views.llGroupStatusExtra, toggle = true ) R.id.btnGroupUserExtra -> updateGroup( views.btnGroupUserExtra, views.llGroupUserExtra, toggle = true ) else -> false } private fun ActMain.onClickUserAndStatus( v: View, pos: Int, who: TootAccount, status: TootStatus, ): Boolean { when (v.id) { R.id.btnAroundAccountTL -> clickAroundAccountTL(accessInfo, pos, who, status) R.id.btnAroundLTL -> clickAroundLTL(accessInfo, pos, who, status) R.id.btnAroundFTL -> clickAroundFTL(accessInfo, pos, who, status) R.id.btnReportStatus -> userReportForm(accessInfo, who, status) else -> return false } return true } @Suppress("ComplexMethod") private fun ActMain.onClickUser( v: View, pos: Int, who: TootAccount, whoRef: TootAccountRef, ): Boolean { when (v.id) { R.id.btnReportUser -> userReportForm(accessInfo, who) R.id.btnFollow -> clickFollow(pos, accessInfo, whoRef, relation) R.id.btnMute -> clickMute(accessInfo, who, relation) R.id.btnBlock -> clickBlock(accessInfo, who, relation) R.id.btnAccountText -> launchActText(ActText.createIntent(activity, accessInfo, who)) R.id.btnProfile -> userProfileLocal(pos, accessInfo, who) R.id.btnSendMessage -> mention(accessInfo, who) R.id.btnAccountWebPage -> openCustomTab(who.url) R.id.btnFollowRequestOK -> followRequestAuthorize(accessInfo, whoRef, true) R.id.btnDeleteSuggestion -> userSuggestionDelete(accessInfo, who) R.id.btnFollowRequestNG -> followRequestAuthorize(accessInfo, whoRef, false) R.id.btnFollowFromAnotherAccount -> followFromAnotherAccount(pos, accessInfo, who) R.id.btnSendMessageFromAnotherAccount -> mentionFromAnotherAccount(accessInfo, who) R.id.btnOpenProfileFromAnotherAccount -> userProfileFromAnotherAccount( pos, accessInfo, who ) R.id.btnNickname -> clickNicknameCustomize(accessInfo, who) R.id.btnAccountQrCode -> DlgQRCode.open( activity, whoRef.decoded_display_name, who.getUserUrl() ) R.id.btnDomainBlock -> clickDomainBlock(accessInfo, who) R.id.btnOpenTimeline -> who.apiHost.valid()?.let { timelineLocal(pos, it) } R.id.btnDomainTimeline -> who.apiHost.valid() ?.let { timelineDomain(pos, accessInfo, it) } R.id.btnAvatarImage -> openAvatarImage(who) R.id.btnQuoteName -> quoteName(who) R.id.btnHideBoost -> userSetShowBoosts(accessInfo, who, false) R.id.btnShowBoost -> userSetShowBoosts(accessInfo, who, true) R.id.btnHideFavourite -> clickHideFavourite(accessInfo, who) R.id.btnShowFavourite -> clickShowFavourite(accessInfo, who) R.id.btnListMemberAddRemove -> DlgListMember(activity, who, accessInfo).show() R.id.btnInstanceInformation -> serverInformation(pos, getUserApiHost()) R.id.btnProfileDirectory -> serverProfileDirectoryFromInstanceInformation( column, getUserApiHost() ) R.id.btnEndorse -> userEndorsement(accessInfo, who, !relation.endorsed) R.id.btnCopyAccountId -> who.id.toString().copyToClipboard(activity) R.id.btnOpenAccountInAdminWebUi -> openBrowser("https://${accessInfo.apiHost.ascii}/admin/accounts/${who.id}") R.id.btnOpenInstanceInAdminWebUi -> openBrowser("https://${accessInfo.apiHost.ascii}/admin/instances/${who.apDomain.ascii}") R.id.btnNotificationFrom -> clickNotificationFrom(pos, accessInfo, who) R.id.btnStatusNotification -> clickStatusNotification(accessInfo, who, relation) R.id.btnQuoteUrlAccount -> openPost(who.url?.notEmpty()) R.id.btnShareUrlAccount -> shareText(who.url?.notEmpty()) else -> return false } return true } private fun ActMain.onClickStatus(v: View, pos: Int, status: TootStatus): Boolean { when (v.id) { R.id.btnBoostWithVisibility -> clickBoostWithVisibility(accessInfo, status) R.id.btnStatusWebPage -> openCustomTab(status.url) R.id.btnText -> launchActText(ActText.createIntent(this, accessInfo, status)) R.id.btnFavouriteAnotherAccount -> favouriteFromAnotherAccount(accessInfo, status) R.id.btnBookmarkAnotherAccount -> bookmarkFromAnotherAccount(accessInfo, status) R.id.btnBoostAnotherAccount -> boostFromAnotherAccount(accessInfo, status) R.id.btnReactionAnotherAccount -> reactionFromAnotherAccount(accessInfo, status) R.id.btnReplyAnotherAccount -> replyFromAnotherAccount(accessInfo, status) R.id.btnQuoteAnotherAccount -> quoteFromAnotherAccount(accessInfo, status) R.id.btnQuoteTootBT -> quoteFromAnotherAccount(accessInfo, status.reblogParent) R.id.btnConversationAnotherAccount -> conversationOtherInstance(pos, status) R.id.btnDelete -> clickStatusDelete(accessInfo, status) R.id.btnRedraft -> statusRedraft(accessInfo, status) R.id.btnStatusEdit -> statusEdit(accessInfo, status) R.id.btnMuteApp -> appMute(status.application) R.id.btnBoostedBy -> clickBoostBy(pos, accessInfo, status, ColumnType.BOOSTED_BY) R.id.btnFavouritedBy -> clickBoostBy(pos, accessInfo, status, ColumnType.FAVOURITED_BY) R.id.btnTranslate -> CustomShare.invokeStatusText( CustomShareTarget.Translate, activity, accessInfo, status ) R.id.btnQuoteUrlStatus -> openPost(status.url?.notEmpty()) R.id.btnShareUrlStatus -> shareText(status.url?.notEmpty()) R.id.btnConversationMute -> conversationMute(accessInfo, status) R.id.btnProfilePin -> statusPin(accessInfo, status, true) R.id.btnProfileUnpin -> statusPin(accessInfo, status, false) R.id.btnStatusHistory -> openStatusHistory(pos, accessInfo, status) else -> return false } return true } private fun ActMain.onClickOther(v: View) { when (v.id) { R.id.btnNotificationDelete -> notificationDeleteOne(accessInfo, notification) R.id.btnCancel -> dialog.cancel() } } override fun onClick(v: View) { if (onClickUpdateGroup(v)) return // ダイアログを閉じない操作 dialog.dismissSafe() val pos = activity.nextPosition(column) val status = this.status val whoRef = this.whoRef val who = whoRef?.get() if (status != null && activity.onClickStatus(v, pos, status)) return if (whoRef != null && who != null) { when { activity.onClickUser(v, pos, who, whoRef) -> return status != null && activity.onClickUserAndStatus(v, pos, who, status) -> return } } activity.onClickOther(v) } override fun onLongClick(v: View): Boolean { val whoRef = this.whoRef val who = whoRef?.get() with(activity) { val pos = nextPosition(column) when (v.id) { // events don't close dialog R.id.btnMute -> userMuteFromAnotherAccount(who, accessInfo) R.id.btnBlock -> userBlockFromAnotherAccount(who, accessInfo) R.id.btnQuoteAnotherAccount -> quoteFromAnotherAccount(accessInfo, status) R.id.btnQuoteTootBT -> quoteFromAnotherAccount(accessInfo, status?.reblogParent) // events close dialog before action R.id.btnFollow -> { dialog.dismissSafe() followFromAnotherAccount(pos, accessInfo, who) } R.id.btnProfile -> { dialog.dismissSafe() userProfileFromAnotherAccount(pos, accessInfo, who) } R.id.btnSendMessage -> { dialog.dismissSafe() mentionFromAnotherAccount(accessInfo, who) } else -> return false } } return true } }
apache-2.0
e75d2b87fef4e7bf2c660252802a9e00
39.462481
136
0.59361
4.527592
false
false
false
false
ThePreviousOne/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/data/source/online/ParsedOnlineSource.kt
1
7171
package eu.kanade.tachiyomi.data.source.online import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.source.model.MangasPage import eu.kanade.tachiyomi.data.source.model.Page import eu.kanade.tachiyomi.util.asJsoup import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element /** * A simple implementation for sources from a website using Jsoup, an HTML parser. */ abstract class ParsedOnlineSource() : OnlineSource() { /** * Parse the response from the site and fills [page]. * * @param response the response from the site. * @param page the page object to be filled. */ override fun popularMangaParse(response: Response, page: MangasPage) { val document = response.asJsoup() for (element in document.select(popularMangaSelector())) { Manga.create(id).apply { popularMangaFromElement(element, this) page.mangas.add(this) } } popularMangaNextPageSelector()?.let { selector -> page.nextPageUrl = document.select(selector).first()?.absUrl("href") } } /** * Returns the Jsoup selector that returns a list of [Element] corresponding to each manga. */ abstract protected fun popularMangaSelector(): String /** * Fills [manga] with the given [element]. Most sites only show the title and the url, it's * totally safe to fill only those two values. * * @param element an element obtained from [popularMangaSelector]. * @param manga the manga to fill. */ abstract protected fun popularMangaFromElement(element: Element, manga: Manga) /** * Returns the Jsoup selector that returns the <a> tag linking to the next page, or null if * there's no next page. */ abstract protected fun popularMangaNextPageSelector(): String? /** * Parse the response from the site and fills [page]. * * @param response the response from the site. * @param page the page object to be filled. * @param query the search query. */ override fun searchMangaParse(response: Response, page: MangasPage, query: String, filters: List<Filter>) { val document = response.asJsoup() for (element in document.select(searchMangaSelector())) { Manga.create(id).apply { searchMangaFromElement(element, this) page.mangas.add(this) } } searchMangaNextPageSelector()?.let { selector -> page.nextPageUrl = document.select(selector).first()?.absUrl("href") } } /** * Returns the Jsoup selector that returns a list of [Element] corresponding to each manga. */ abstract protected fun searchMangaSelector(): String /** * Fills [manga] with the given [element]. Most sites only show the title and the url, it's * totally safe to fill only those two values. * * @param element an element obtained from [searchMangaSelector]. * @param manga the manga to fill. */ abstract protected fun searchMangaFromElement(element: Element, manga: Manga) /** * Returns the Jsoup selector that returns the <a> tag linking to the next page, or null if * there's no next page. */ abstract protected fun searchMangaNextPageSelector(): String? /** * Parse the response from the site for latest updates and fills [page]. */ override fun latestUpdatesParse(response: Response, page: MangasPage) { val document = response.asJsoup() for (element in document.select(latestUpdatesSelector())) { Manga.create(id).apply { latestUpdatesFromElement(element, this) page.mangas.add(this) } } latestUpdatesNextPageSelector()?.let { selector -> page.nextPageUrl = document.select(selector).first()?.absUrl("href") } } /** * Returns the Jsoup selector similar to [popularMangaSelector], but for latest updates. */ abstract protected fun latestUpdatesSelector(): String /** * Fills [manga] with the given [element]. For latest updates. */ abstract protected fun latestUpdatesFromElement(element: Element, manga: Manga) /** * Returns the Jsoup selector that returns the <a> tag, like [popularMangaNextPageSelector]. */ abstract protected fun latestUpdatesNextPageSelector(): String? /** * Parse the response from the site and fills the details of [manga]. * * @param response the response from the site. * @param manga the manga to fill. */ override fun mangaDetailsParse(response: Response, manga: Manga) { mangaDetailsParse(response.asJsoup(), manga) } /** * Fills the details of [manga] from the given [document]. * * @param document the parsed document. * @param manga the manga to fill. */ abstract protected fun mangaDetailsParse(document: Document, manga: Manga) /** * Parse the response from the site and fills the chapter list. * * @param response the response from the site. * @param chapters the list of chapters to fill. */ override fun chapterListParse(response: Response, chapters: MutableList<Chapter>) { val document = response.asJsoup() for (element in document.select(chapterListSelector())) { Chapter.create().apply { chapterFromElement(element, this) chapters.add(this) } } } /** * Returns the Jsoup selector that returns a list of [Element] corresponding to each chapter. */ abstract protected fun chapterListSelector(): String /** * Fills [chapter] with the given [element]. * * @param element an element obtained from [chapterListSelector]. * @param chapter the chapter to fill. */ abstract protected fun chapterFromElement(element: Element, chapter: Chapter) /** * Parse the response from the site and fills the page list. * * @param response the response from the site. * @param pages the list of pages to fill. */ override fun pageListParse(response: Response, pages: MutableList<Page>) { pageListParse(response.asJsoup(), pages) } /** * Fills [pages] from the given [document]. * * @param document the parsed document. * @param pages the list of pages to fill. */ abstract protected fun pageListParse(document: Document, pages: MutableList<Page>) /** * Parse the response from the site and returns the absolute url to the source image. * * @param response the response from the site. */ override fun imageUrlParse(response: Response): String { return imageUrlParse(response.asJsoup()) } /** * Returns the absolute url to the source image from the document. * * @param document the parsed document. */ abstract protected fun imageUrlParse(document: Document): String }
apache-2.0
ff893fb097154c5243476cc3647de7f2
32.985782
111
0.648306
4.871603
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/sns/src/main/kotlin/com/kotlin/sns/SubscribeTextSMS.kt
1
1964
// snippet-sourcedescription:[SubscribeTextSMS.kt demonstrates how to subscribe to an Amazon Simple Notification Service (Amazon SNS) text endpoint.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-keyword:[Amazon Simple Notification Service] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.sns // snippet-start:[sns.kotlin.SubscribeTextSMS.import] import aws.sdk.kotlin.services.sns.SnsClient import aws.sdk.kotlin.services.sns.model.SubscribeRequest import kotlin.system.exitProcess // snippet-end:[sns.kotlin.SubscribeTextSMS.import] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main(args: Array<String>) { val usage = """ Usage: <topicArn> <phoneNumber> Where: topicArn - The ARN of the topic to publish. phoneNumber - A mobile phone number that receives notifications (for example, +1XXX5550100). """ if (args.size != 2) { println(usage) exitProcess(0) } val topicArn = args[0] val phoneNumber = args[1] subTextSNS(topicArn, phoneNumber) } // snippet-start:[sns.kotlin.SubscribeTextSMS.main] suspend fun subTextSNS(topicArnVal: String?, phoneNumber: String?) { val request = SubscribeRequest { protocol = "sms" endpoint = phoneNumber returnSubscriptionArn = true topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.subscribe(request) println("The subscription Arn is ${result.subscriptionArn}") } } // snippet-end:[sns.kotlin.SubscribeTextSMS.main]
apache-2.0
76d5ff929d6bd5b9b869f730b88fea04
29.677419
149
0.674644
4.08316
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/util/CharacterGroup.kt
1
14250
package jp.juggler.util import android.text.SpannableStringBuilder import android.util.SparseBooleanArray import android.util.SparseIntArray import java.util.ArrayList import java.util.regex.Pattern object CharacterGroup { // Tokenizerが終端に達したことを示す const val END = -1 // 文字コードから文字列を作る private fun c2s(tmp: CharArray, c: Char): String { tmp[0] = c return String(tmp, 0, 1) } private fun i2s(tmp: CharArray, c: Int): String { tmp[0] = c.toChar() return String(tmp, 0, 1) } private val mapWhitespace = SparseBooleanArray().apply { intArrayOf( 0x0009, // HORIZONTAL TABULATION 0x000A, // LINE FEED 0x000B, // VERTICAL TABULATION 0x000C, // FORM FEED 0x000D, // CARRIAGE RETURN 0x001C, // FILE SEPARATOR 0x001D, // GROUP SEPARATOR 0x001E, // RECORD SEPARATOR 0x001F, // UNIT SEPARATOR 0x0020, 0x0085, // next line (latin-1) 0x00A0, //非区切りスペース 0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, //非区切りスペース 0x2008, 0x2009, 0x200A, 0x200B, 0x200C, 0x200D, 0x2028, // line separator 0x2029, // paragraph separator 0x202F, //非区切りスペース 0x205F, 0x2060, 0x3000, 0x3164, 0xFEFF ).forEach { put(it, true) } } // 空白とみなす文字なら真 fun isWhitespace(cp: Int): Boolean = mapWhitespace.get(cp, false) internal val reWhitespace by lazy { val quotedKeys = Pattern.quote( StringBuilder().apply { val size = mapWhitespace.size() ensureCapacity(size) for (i in 0 until size) { append(mapWhitespace.keyAt(i).toChar()) } }.toString() ) "[$quotedKeys]+".asciiPattern() } internal val reNotWhitespace by lazy { val quotedKeys = Pattern.quote( StringBuilder().apply { val size = mapWhitespace.size() ensureCapacity(size) for (i in 0 until size) { append(mapWhitespace.keyAt(i).toChar()) } }.toString() ) "[^$quotedKeys]+".asciiPattern() } private fun SparseBooleanArray.keys() = (0 until size()).map { keyAt(it) } internal val reWhitespaceBeforeLineFeed by lazy { val whitespaces = mapWhitespace.keys() .map { it.toChar() } .filter { it != '\n' } .joinToString("") "[$whitespaces]+\n".asciiPattern() } // 文字列のリストからグループIDを決定する private fun findGroupId(list: Array<String>): Int { // グループのIDは、グループ中の文字(長さ1)のunicode値の最小 var id = Integer.MAX_VALUE for (s in list) { if (s.length == 1) { val c = s[0].code if (c < id) id = c } } if (id == Integer.MAX_VALUE) error("missing group id") return id } // 文字列からグループIDを調べるマップ // 文字数1: unicode => group_id private val map1 = SparseIntArray() // 文字数2: unicode 二つを合成した数値 => group_id。半角カナ+濁音など private val map2 = SparseIntArray() // ユニコード文字を正規化する。 // 簡易版なので全ての文字には対応していない fun getUnifiedCharacter(c: Char): Char { val v1 = map1[c.code] return if (v1 != 0) v1.toChar() else c } // グループをmapに登録する private fun addGroup(list: Array<String>) { val group_id = findGroupId(list) // 文字列からグループIDを調べるマップを更新 for (s in list) { val map: SparseIntArray val key: Int val v1 = s[0].code if (s.length == 1) { map = map1 key = v1 } else { map = map2 val v2 = s[1].code key = v1 or (v2 shl 16) } val old = map.get(key) if (old != 0 && old != group_id) error("group conflict: $s") map.put(key, group_id) } } // 入力された文字列から 文字,グループ,終端 のどれかを順に列挙する class Tokenizer { internal var text: CharSequence = "" internal var end: Int = 0 var offset: Int = 0 internal fun reset(text: CharSequence, start: Int, end: Int): Tokenizer { this.text = text this.offset = start this.end = end return this } // returns END or group_id or UTF-16 character operator fun next(): Int { var pos = offset // 空白を読み飛ばす while (pos < end && isWhitespace(text[pos].code)) ++pos // 終端までの文字数 val remain = end - pos if (remain <= 0) { // 空白を読み飛ばしたら終端になった // 終端の場合、末尾の空白はoffsetに含めない return END } val v1 = text[pos].code // グループに登録された文字を長い順にチェック var check_len = if (remain > 2) 2 else remain while (check_len > 0) { val group_id = when (check_len) { 1 -> map1.get(v1) else -> map2.get(v1 or (text[pos + 1].code shl 16)) } if (group_id != 0) { this.offset = pos + check_len return group_id } --check_len } this.offset = pos + 1 return v1 } } init { val tmp = CharArray(1) val array2 = arrayOf("", "") val array4 = arrayOf("", "", "", "") // 数字 for (i in 0..8) { array2[0] = c2s(tmp, '0' + i) array2[1] = c2s(tmp, '0' + i) addGroup(array2) } // 英字 for (i in 0..25) { array4[0] = c2s(tmp, 'a' + i) array4[1] = c2s(tmp, 'A' + i) array4[2] = c2s(tmp, 'a' + i) array4[3] = c2s(tmp, 'A' + i) addGroup(array4) } // ハイフン addGroup( arrayOf( i2s(tmp, 0x002D), // ASCIIのハイフン i2s(tmp, 0x30FC), // 全角カナの長音 Shift_JIS由来 i2s(tmp, 0x2010), i2s(tmp, 0x2011), i2s(tmp, 0x2013), i2s(tmp, 0x2014), i2s(tmp, 0x2015), // 全角カナのダッシュ Shift_JIS由来 i2s(tmp, 0x2212), i2s(tmp, 0xFF0d), // 全角カナの長音 MS932由来 i2s(tmp, 0xFF70) // 半角カナの長音 MS932由来 ) ) addGroup(arrayOf("!", "!")) addGroup(arrayOf(""", "\"")) addGroup(arrayOf("#", "#")) addGroup(arrayOf("$", "$")) addGroup(arrayOf("%", "%")) addGroup(arrayOf("&", "&")) addGroup(arrayOf("'", "'")) addGroup(arrayOf("(", "(")) addGroup(arrayOf(")", ")")) addGroup(arrayOf("*", "*")) addGroup(arrayOf("+", "+")) addGroup(arrayOf(",", ",", "、", "、")) addGroup(arrayOf(".", ".", "。", "。")) addGroup(arrayOf("/", "/")) addGroup(arrayOf(":", ":")) addGroup(arrayOf(";", ";")) addGroup(arrayOf("<", "<")) addGroup(arrayOf("=", "=")) addGroup(arrayOf(">", ">")) addGroup(arrayOf("?", "?")) addGroup(arrayOf("@", "@")) addGroup(arrayOf("[", "[")) addGroup(arrayOf("\", "\\", "¥")) addGroup(arrayOf("]", "]")) addGroup(arrayOf("^", "^")) addGroup(arrayOf("_", "_")) addGroup(arrayOf("`", "`")) addGroup(arrayOf("{", "{")) addGroup(arrayOf("|", "|", "¦")) addGroup(arrayOf("}", "}")) addGroup(arrayOf("・", "・", "・")) addGroup(arrayOf("「", "「", "「")) addGroup(arrayOf("」", "」", "」")) // チルダ addGroup( arrayOf( "~", i2s(tmp, 0x301C), i2s(tmp, 0xFF5E) ) ) // 半角カナの濁音,半濁音は2文字になる addGroup(arrayOf("ガ", "が", "ガ")) addGroup(arrayOf("ギ", "ぎ", "ギ")) addGroup(arrayOf("グ", "ぐ", "グ")) addGroup(arrayOf("ゲ", "げ", "ゲ")) addGroup(arrayOf("ゴ", "ご", "ゴ")) addGroup(arrayOf("ザ", "ざ", "ザ")) addGroup(arrayOf("ジ", "じ", "ジ")) addGroup(arrayOf("ズ", "ず", "ズ")) addGroup(arrayOf("ゼ", "ぜ", "ゼ")) addGroup(arrayOf("ゾ", "ぞ", "ゾ")) addGroup(arrayOf("ダ", "だ", "ダ")) addGroup(arrayOf("ヂ", "ぢ", "ヂ")) addGroup(arrayOf("ヅ", "づ", "ヅ")) addGroup(arrayOf("デ", "で", "デ")) addGroup(arrayOf("ド", "ど", "ド")) addGroup(arrayOf("バ", "ば", "バ")) addGroup(arrayOf("ビ", "び", "ビ")) addGroup(arrayOf("ブ", "ぶ", "ブ")) addGroup(arrayOf("ベ", "べ", "ベ")) addGroup(arrayOf("ボ", "ぼ", "ボ")) addGroup(arrayOf("パ", "ぱ", "パ")) addGroup(arrayOf("ピ", "ぴ", "ピ")) addGroup(arrayOf("プ", "ぷ", "プ")) addGroup(arrayOf("ペ", "ぺ", "ペ")) addGroup(arrayOf("ポ", "ぽ", "ポ")) addGroup(arrayOf("ヴ", "う゛", "ヴ")) addGroup(arrayOf("あ", "ア", "ア", "ぁ", "ァ", "ァ")) addGroup(arrayOf("い", "イ", "イ", "ぃ", "ィ", "ィ")) addGroup(arrayOf("う", "ウ", "ウ", "ぅ", "ゥ", "ゥ")) addGroup(arrayOf("え", "エ", "エ", "ぇ", "ェ", "ェ")) addGroup(arrayOf("お", "オ", "オ", "ぉ", "ォ", "ォ")) addGroup(arrayOf("か", "カ", "カ")) addGroup(arrayOf("き", "キ", "キ")) addGroup(arrayOf("く", "ク", "ク")) addGroup(arrayOf("け", "ケ", "ケ")) addGroup(arrayOf("こ", "コ", "コ")) addGroup(arrayOf("さ", "サ", "サ")) addGroup(arrayOf("し", "シ", "シ")) addGroup(arrayOf("す", "ス", "ス")) addGroup(arrayOf("せ", "セ", "セ")) addGroup(arrayOf("そ", "ソ", "ソ")) addGroup(arrayOf("た", "タ", "タ")) addGroup(arrayOf("ち", "チ", "チ")) addGroup(arrayOf("つ", "ツ", "ツ", "っ", "ッ", "ッ")) addGroup(arrayOf("て", "テ", "テ")) addGroup(arrayOf("と", "ト", "ト")) addGroup(arrayOf("な", "ナ", "ナ")) addGroup(arrayOf("に", "ニ", "ニ")) addGroup(arrayOf("ぬ", "ヌ", "ヌ")) addGroup(arrayOf("ね", "ネ", "ネ")) addGroup(arrayOf("の", "ノ", "ノ")) addGroup(arrayOf("は", "ハ", "ハ")) addGroup(arrayOf("ひ", "ヒ", "ヒ")) addGroup(arrayOf("ふ", "フ", "フ")) addGroup(arrayOf("へ", "ヘ", "ヘ")) addGroup(arrayOf("ほ", "ホ", "ホ")) addGroup(arrayOf("ま", "マ", "マ")) addGroup(arrayOf("み", "ミ", "ミ")) addGroup(arrayOf("む", "ム", "ム")) addGroup(arrayOf("め", "メ", "メ")) addGroup(arrayOf("も", "モ", "モ")) addGroup(arrayOf("や", "ヤ", "ヤ", "ゃ", "ャ", "ャ")) addGroup(arrayOf("ゆ", "ユ", "ユ", "ゅ", "ュ", "ュ")) addGroup(arrayOf("よ", "ヨ", "ヨ", "ょ", "ョ", "ョ")) addGroup(arrayOf("ら", "ラ", "ラ")) addGroup(arrayOf("り", "リ", "リ")) addGroup(arrayOf("る", "ル", "ル")) addGroup(arrayOf("れ", "レ", "レ")) addGroup(arrayOf("ろ", "ロ", "ロ")) addGroup(arrayOf("わ", "ワ", "ワ")) addGroup(arrayOf("を", "ヲ", "ヲ")) addGroup(arrayOf("ん", "ン", "ン")) } } // 末尾の空白や開業を取り除く fun SpannableStringBuilder.removeEndWhitespaces(): SpannableStringBuilder { var pos = length while (pos > 0 && CharacterGroup.isWhitespace(codePointBefore(pos))) { // whitespaces are always 1 == Character.charCount(c) --pos } if (pos < length) delete(pos, length) return this } // 行末の空白を除去。連続する改行を2つまでに制限する。 fun SpannableStringBuilder.neatSpaces(): SpannableStringBuilder { // 行末の空白を除去 val m = CharacterGroup.reWhitespaceBeforeLineFeed.matcher(this) val matchList = ArrayList<Pair<Int, Int>>() while (m.find()) { matchList.add(Pair(m.start(), m.end())) } for (pair in matchList.reversed()) { delete(pair.first, pair.second - 1) } // 連続する改行をまとめる var previousBrCount = 0 for (i in this.indices.reversed()) { val c = this[i] if (c != '\n') { previousBrCount = 0 } else if (++previousBrCount >= 3) { delete(i, i + 1) } } return this }
apache-2.0
b4c31f731fdf4ca36885a5669ccee572
29.336609
81
0.446056
3.233773
false
false
false
false
gituser9/InvoiceManagement
app/src/main/java/com/user/invoicemanagement/model/dto/ClosedInvoice.kt
1
848
package com.user.invoicemanagement.model.dto import com.raizlabs.android.dbflow.annotation.Column import com.raizlabs.android.dbflow.annotation.OneToMany import com.raizlabs.android.dbflow.annotation.PrimaryKey import com.raizlabs.android.dbflow.annotation.Table import com.raizlabs.android.dbflow.kotlinextensions.from import com.raizlabs.android.dbflow.kotlinextensions.oneToMany import com.raizlabs.android.dbflow.kotlinextensions.select import com.raizlabs.android.dbflow.kotlinextensions.where @Table(database = DbflowDatabase::class) class ClosedInvoice { @PrimaryKey(autoincrement = true) var id: Long = 0 @Column var savedDate: Long = 0 @get:OneToMany(methods = arrayOf(OneToMany.Method.ALL)) var factories by oneToMany { select from OldProductFactory::class where (OldProductFactory_Table.invoiceId.eq(id)) } }
mit
f1fb064001c032c14b98fc23c0d9bf95
35.913043
120
0.808962
4.156863
false
false
false
false
paplorinc/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/psiElementMapping.kt
2
6099
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.java import com.intellij.openapi.util.registry.Registry import com.intellij.psi.* import com.intellij.psi.impl.source.tree.java.PsiLiteralExpressionImpl import org.jetbrains.uast.* import org.jetbrains.uast.internal.ClassSet import org.jetbrains.uast.internal.UElementToPsiElementMapping private val checkCanConvert = Registry.`is`("uast.java.use.psi.type.precheck") internal fun canConvert(psiCls: Class<out PsiElement>, targets: Array<out Class<out UElement>>): Boolean { if (!checkCanConvert) return true if (targets.size == 1) { // checking the most popular cases before looking up in hashtable when (targets.single()) { UElement::class.java -> uElementClassSet.contains(psiCls) ULiteralExpression::class.java -> uLiteralClassSet.contains(psiCls) UCallExpression::class.java -> uCallClassSet.contains(psiCls) } } return conversionMapping.canConvert(psiCls, targets) } private val conversionMapping = UElementToPsiElementMapping( UClass::class.java to ClassSet(PsiClass::class.java), UMethod::class.java to ClassSet(PsiMethod::class.java), UClassInitializer::class.java to ClassSet(PsiClassInitializer::class.java), UEnumConstant::class.java to ClassSet(PsiEnumConstant::class.java), ULocalVariable::class.java to ClassSet(PsiLocalVariable::class.java), UParameter::class.java to ClassSet(PsiParameter::class.java), UField::class.java to ClassSet(PsiField::class.java), UVariable::class.java to ClassSet(PsiVariable::class.java), UAnnotation::class.java to ClassSet(PsiAnnotation::class.java), UBlockExpression::class.java to ClassSet(PsiCodeBlock::class.java, PsiBlockStatement::class.java, PsiSynchronizedStatement::class.java), UImportStatement::class.java to ClassSet(PsiImportStatementBase::class.java), USimpleNameReferenceExpression::class.java to ClassSet(PsiIdentifier::class.java, PsiReferenceExpression::class.java, PsiJavaCodeReferenceElement::class.java), UIdentifier::class.java to ClassSet(PsiIdentifier::class.java), UNamedExpression::class.java to ClassSet(PsiNameValuePair::class.java), UCallExpression::class.java to ClassSet( PsiArrayInitializerMemberValue::class.java, PsiAnnotation::class.java, PsiNewExpression::class.java, PsiMethodCallExpression::class.java, PsiAssertStatement::class.java, PsiArrayInitializerExpression::class.java ), UTypeReferenceExpression::class.java to ClassSet(PsiTypeElement::class.java), UBinaryExpression::class.java to ClassSet( PsiAssignmentExpression::class.java, PsiBinaryExpression::class.java ), UIfExpression::class.java to ClassSet(PsiConditionalExpression::class.java, PsiIfStatement::class.java), UObjectLiteralExpression::class.java to ClassSet(PsiNewExpression::class.java), UQualifiedReferenceExpression::class.java to ClassSet(PsiMethodCallExpression::class.java, PsiReferenceExpression::class.java, PsiJavaCodeReferenceElement::class.java), UPolyadicExpression::class.java to ClassSet(PsiPolyadicExpression::class.java), UParenthesizedExpression::class.java to ClassSet(PsiParenthesizedExpression::class.java), UPrefixExpression::class.java to ClassSet(PsiPrefixExpression::class.java), UPostfixExpression::class.java to ClassSet(PsiPostfixExpression::class.java), ULiteralExpression::class.java to ClassSet(PsiLiteralExpressionImpl::class.java), UCallableReferenceExpression::class.java to ClassSet(PsiMethodReferenceExpression::class.java), UThisExpression::class.java to ClassSet(PsiThisExpression::class.java), USuperExpression::class.java to ClassSet(PsiSuperExpression::class.java), UBinaryExpressionWithType::class.java to ClassSet(PsiInstanceOfExpression::class.java, PsiTypeCastExpression::class.java), UClassLiteralExpression::class.java to ClassSet(PsiClassObjectAccessExpression::class.java), UArrayAccessExpression::class.java to ClassSet(PsiArrayAccessExpression::class.java), ULambdaExpression::class.java to ClassSet(PsiLambdaExpression::class.java), USwitchExpression::class.java to ClassSet(PsiSwitchExpression::class.java, PsiSwitchStatement::class.java), UDeclarationsExpression::class.java to ClassSet(PsiDeclarationStatement::class.java, PsiExpressionListStatement::class.java), ULabeledExpression::class.java to ClassSet(PsiLabeledStatement::class.java), UWhileExpression::class.java to ClassSet(PsiWhileStatement::class.java), UDoWhileExpression::class.java to ClassSet(PsiDoWhileStatement::class.java), UForExpression::class.java to ClassSet(PsiForStatement::class.java), UForEachExpression::class.java to ClassSet(PsiForeachStatement::class.java), UBreakExpression::class.java to ClassSet(PsiBreakStatement::class.java), UContinueExpression::class.java to ClassSet(PsiContinueStatement::class.java), UReturnExpression::class.java to ClassSet(PsiReturnStatement::class.java), UThrowExpression::class.java to ClassSet(PsiThrowStatement::class.java), UTryExpression::class.java to ClassSet(PsiTryStatement::class.java), UastEmptyExpression::class.java to ClassSet(PsiEmptyStatement::class.java), UExpressionList::class.java to ClassSet(PsiSwitchLabelStatementBase::class.java), UExpression::class.java to ClassSet(PsiExpressionStatement::class.java), USwitchClauseExpression::class.java to ClassSet(PsiSwitchLabelStatementBase::class.java) ) val uElementClassSet = ClassSet(*conversionMapping.baseMapping.flatMap { it.value.initialClasses.asIterable() }.toTypedArray()) val uLiteralClassSet: ClassSet = conversionMapping[ULiteralExpression::class.java] val uCallClassSet: ClassSet = conversionMapping[UCallExpression::class.java]
apache-2.0
8030b4e8e4709b7aed6601eb24e1ff84
56.537736
140
0.765699
4.634498
false
false
false
false
Displee/RS2-Cache-Library
src/main/kotlin/com/displee/cache/index/Index.kt
1
12496
package com.displee.cache.index import com.displee.cache.CacheLibrary import com.displee.cache.ProgressListener import com.displee.cache.index.archive.Archive import com.displee.cache.index.archive.ArchiveSector import com.displee.compress.CompressionType import com.displee.compress.compress import com.displee.compress.decompress import com.displee.io.impl.InputBuffer import com.displee.io.impl.OutputBuffer import com.displee.util.generateCrc import com.displee.util.generateWhirlpool import java.io.RandomAccessFile open class Index(origin: CacheLibrary, id: Int, val raf: RandomAccessFile) : ReferenceTable(origin, id) { var crc = 0 var whirlpool: ByteArray? = null var compressionType: CompressionType = CompressionType.NONE private var cached = false protected var closed = false val info get() = "Index[id=" + id + ", archives=" + archives.size + ", compression=" + compressionType + "]" init { init() } protected open fun init() { if (id < 0 || id >= 255) { return } val archiveSector = origin.index255?.readArchiveSector(id) ?: return val archiveSectorData = archiveSector.data crc = archiveSectorData.generateCrc() whirlpool = archiveSectorData.generateWhirlpool() read(InputBuffer(archiveSector.decompress())) compressionType = archiveSector.compressionType } fun cache() { check(!closed) { "Index is closed." } if (cached) { return } archives.values.forEach { try { archive(it.id, it.xtea, false) } catch (t: Throwable) { t.printStackTrace() } } cached = true } fun unCache() { for (archive in archives()) { archive.restore() } cached = false } @JvmOverloads open fun update(listener: ProgressListener? = null): Boolean { check(!closed) { "Index is closed." } val flaggedArchives = flaggedArchives() var i = 0.0 flaggedArchives.forEach { i++ it.revision++ it.unFlag() listener?.notify((i / flaggedArchives.size) * 0.80, "Repacking archive ${it.id}...") val compressed = it.write().compress(it.compressionType ?: CompressionType.GZIP, it.xtea, it.revision) it.crc = compressed.generateCrc(length = compressed.size - 2) it.whirlpool = compressed.generateWhirlpool(length = compressed.size - 2) val written = writeArchiveSector(it.id, compressed) check(written) { "Unable to write data to archive sector. Your cache may be corrupt." } if (origin.clearDataAfterUpdate) { it.restore() } } listener?.notify(0.85, "Updating checksum table for index $id...") if (flaggedArchives.isNotEmpty() && !flagged()) { flag() } if (flagged()) { unFlag() revision++ val indexData = write().compress(compressionType) crc = indexData.generateCrc() whirlpool = indexData.generateWhirlpool() val written = origin.index255?.writeArchiveSector(this.id, indexData) ?: false check(written) { "Unable to write data to checksum table. Your cache may be corrupt." } } listener?.notify(1.0, "Successfully updated index $id.") return true } fun readArchiveSector(id: Int): ArchiveSector? { check(!closed) { "Index is closed." } synchronized(origin.mainFile) { try { if (origin.mainFile.length() < INDEX_SIZE * id + INDEX_SIZE) { return null } val sectorData = ByteArray(SECTOR_SIZE) raf.seek(id.toLong() * INDEX_SIZE) raf.read(sectorData, 0, INDEX_SIZE) val bigSector = id > 65535 val buffer = InputBuffer(sectorData) val archiveSector = ArchiveSector(bigSector, buffer.read24BitInt(), buffer.read24BitInt()) if (archiveSector.size < 0 || archiveSector.position <= 0 || archiveSector.position > origin.mainFile.length() / SECTOR_SIZE) { return null } var read = 0 var chunk = 0 val sectorHeaderSize = if (bigSector) SECTOR_HEADER_SIZE_BIG else SECTOR_HEADER_SIZE_SMALL val sectorDataSize = if (bigSector) SECTOR_DATA_SIZE_BIG else SECTOR_DATA_SIZE_SMALL while (read < archiveSector.size) { if (archiveSector.position == 0) { return null } var requiredToRead = archiveSector.size - read if (requiredToRead > sectorDataSize) { requiredToRead = sectorDataSize } origin.mainFile.seek(archiveSector.position.toLong() * SECTOR_SIZE) origin.mainFile.read(buffer.raw(), 0, requiredToRead + sectorHeaderSize) buffer.offset = 0 archiveSector.read(buffer) if (!isIndexValid(archiveSector.index) || id != archiveSector.id || chunk != archiveSector.chunk) { return null } else if (archiveSector.nextPosition < 0 || archiveSector.nextPosition > origin.mainFile.length() / SECTOR_SIZE) { return null } val bufferData = buffer.raw() for (i in 0 until requiredToRead) { archiveSector.data[read++] = bufferData[i + sectorHeaderSize] } archiveSector.position = archiveSector.nextPosition chunk++ } return archiveSector } catch (exception: Exception) { exception.printStackTrace() } } return null } fun writeArchiveSector(id: Int, data: ByteArray): Boolean { check(!closed) { "Index is closed." } synchronized(origin.mainFile) { return try { var position: Int var archive: Archive? = null var archiveSector: ArchiveSector? = readArchiveSector(id) if (this.id != 255) { archive = archive(id, null, true) } var overWrite = this.id == 255 && archiveSector != null || archive?.new == false val sectorData = ByteArray(SECTOR_SIZE) val bigSector = id > 65535 if (overWrite) { if (INDEX_SIZE * id + INDEX_SIZE > raf.length()) { return false } raf.seek(id.toLong() * INDEX_SIZE) raf.read(sectorData, 0, INDEX_SIZE) val buffer = InputBuffer(sectorData) buffer.offset += 3 position = buffer.read24BitInt() if (position <= 0 || position > origin.mainFile.length() / SECTOR_SIZE) { return false } } else { position = ((origin.mainFile.length() + (SECTOR_SIZE - 1)) / SECTOR_SIZE).toInt() if (position == 0) { position = 1 } archiveSector = ArchiveSector(bigSector, data.size, position, id, indexToWrite(this.id)) } archiveSector ?: return false val buffer = OutputBuffer(6) buffer.write24BitInt(data.size) buffer.write24BitInt(position) raf.seek(id.toLong() * INDEX_SIZE) raf.write(buffer.array(), 0, INDEX_SIZE) var written = 0 var chunk = 0 val archiveHeaderSize = if (bigSector) SECTOR_HEADER_SIZE_BIG else SECTOR_HEADER_SIZE_SMALL val archiveDataSize = if (bigSector) SECTOR_DATA_SIZE_BIG else SECTOR_DATA_SIZE_SMALL while (written < data.size) { var currentPosition = 0 if (overWrite) { origin.mainFile.seek(position.toLong() * SECTOR_SIZE) origin.mainFile.read(sectorData, 0, archiveHeaderSize) archiveSector.read(InputBuffer(sectorData)) currentPosition = archiveSector.nextPosition if (archiveSector.id != id || archiveSector.chunk != chunk || !isIndexValid(archiveSector.index)) { return false } if (currentPosition < 0 || origin.mainFile.length() / SECTOR_SIZE < currentPosition) { return false } } if (currentPosition == 0) { overWrite = false currentPosition = ((origin.mainFile.length() + (SECTOR_SIZE - 1)) / SECTOR_SIZE).toInt() if (currentPosition == 0) { currentPosition++ } if (currentPosition == position) { currentPosition++ } } if (data.size - written <= archiveDataSize) { currentPosition = 0 } archiveSector.chunk = chunk archiveSector.position = currentPosition origin.mainFile.seek(position.toLong() * SECTOR_SIZE) origin.mainFile.write(archiveSector.write(), 0, archiveHeaderSize) var length = data.size - written if (length > archiveDataSize) { length = archiveDataSize } origin.mainFile.write(data, written, length) written += length position = currentPosition chunk++ } true } catch (t: Throwable) { t.printStackTrace() false } } } fun fixCRCs(update: Boolean) { check(!closed) { "Index is closed." } if (is317()) { return } val archiveIds = archiveIds() var flag = false for (i in archiveIds) { val sector = readArchiveSector(i) ?: continue val correctCRC = sector.data.generateCrc(length = sector.data.size - 2) val archive = archive(i) ?: continue val currentCRC = archive.crc if (currentCRC == correctCRC) { continue } println("Incorrect CRC in index $id -> archive $i, current_crc=$currentCRC, correct_crc=$correctCRC") archive.flag() flag = true } val sectorData = origin.index255?.readArchiveSector(id)?.data ?: return val indexCRC = sectorData.generateCrc() if (crc != indexCRC) { flag = true } if (flag && update) { update() } else if (!flag) { println("No invalid CRCs found.") return } unCache() } /** * Clear the archives. */ fun clear() { archives.clear() crc = 0 whirlpool = ByteArray(WHIRLPOOL_SIZE) } fun close() { if (closed) { return } raf.close() closed = true } fun flaggedArchives(): Array<Archive> { return archives.values.filter { it.flagged() }.toTypedArray() } protected open fun isIndexValid(index: Int): Boolean { return this.id == index } protected open fun indexToWrite(index: Int): Int { return index } override fun toString(): String { return "Index $id" } companion object { const val INDEX_SIZE = 6 const val SECTOR_HEADER_SIZE_SMALL = 8 const val SECTOR_DATA_SIZE_SMALL = 512 const val SECTOR_HEADER_SIZE_BIG = 10 const val SECTOR_DATA_SIZE_BIG = 510 const val SECTOR_SIZE = 520 const val WHIRLPOOL_SIZE = 64 } }
mit
be31b7eabc1a878959ae017ea2d671ea
38.295597
143
0.519686
4.862257
false
false
false
false
nick-rakoczy/Conductor
conductor-engine/src/main/java/urn/conductor/ssh/DownloadGavHandler.kt
1
2029
package urn.conductor.ssh import urn.conductor.Engine import urn.conductor.stdlib.xml.DownloadGav import urn.conductor.stdlib.xml.Metadata import java.io.InputStreamReader import java.net.URL class DownloadGavHandler : TransportComplexElementHandler<DownloadGav> { override fun getHostRef(element: DownloadGav): String = element.hostRef override fun getIdentityRef(element: DownloadGav): String = element.identityRef override val handles: Class<DownloadGav> get() = DownloadGav::class.java override fun process(element: DownloadGav, engine: Engine, processChild: (Any) -> Unit, transport: HostTransport) { val baseUrl = element.baseUrl.let(engine::interpolate).trimEnd('/') val groupPath = element.groupId.let(engine::interpolate).replace('.', '/') val artifact = element.artifactId.let(engine::interpolate) val version = element.version.let(engine::interpolate) val packagePath = "$baseUrl/$groupPath/$artifact/$version" val classifier = element.classifier?.let(engine::interpolate) val packaging = element.packaging.let(engine::interpolate) val url = if (element.isSnapshot && element.version.endsWith("-SNAPSHOT")) { val metadataUrl = element.run { "$packagePath/maven-metadata.xml" } val metadata: Metadata = metadataUrl.let(::URL).openStream().use { InputStreamReader(it).use { engine.jaxbReader.unmarshal(it) as Metadata } } metadata.versioning.snapshotVersions.snapshotVersion.find { it.extension == element.packaging }.let { "$packagePath/$artifact-$it".let { if (classifier != null) { "$it-$classifier" } else { it } }.let { "$it.$packaging" } } } else { element.run { "$packagePath/$artifact-$version".let { if (classifier != null) { "$it-$classifier" } else { it } }.let { "$it.$packaging" } } } url.let(engine::interpolate).let(::URL).openStream().use { transport.useSftpChannel { this.put(it, element.path.let(engine::interpolate)) } } } }
gpl-3.0
76c5be3bac7f4b782a03661708ec0fce
29.757576
116
0.691966
3.584806
false
false
false
false
RuneSuite/client
api/src/main/java/org/runestar/client/api/util/RgbFlaggedColorModel.kt
1
2236
package org.runestar.client.api.util import java.awt.Transparency import java.awt.image.ColorModel import java.awt.image.DataBuffer import java.awt.image.DirectColorModel import java.awt.image.Raster import java.awt.image.SampleModel import java.awt.image.WritableRaster /** * A 24 bit RGB [ColorModel] which treats all pixel values as opaque except for [transparentFlag] which is fully * transparent */ data class RgbFlaggedColorModel(val transparentFlag: Int) : ColorModel( RGB.pixelSize, intArrayOf(8, 8, 8, 0), RGB.colorSpace, true, false, Transparency.BITMASK, DataBuffer.TYPE_INT ) { private companion object { @JvmField val RGB = DirectColorModel(24, 0xFF0000, 0xFF00, 0xFF) } override fun getAlpha(pixel: Int): Int = if (pixel == transparentFlag) 0 else 255 override fun getRed(pixel: Int): Int = RGB.getRed(pixel) override fun getGreen(pixel: Int): Int = RGB.getGreen(pixel) override fun getBlue(pixel: Int): Int = RGB.getBlue(pixel) override fun createCompatibleSampleModel(w: Int, h: Int) = RGB.createCompatibleSampleModel(w, h) override fun createCompatibleWritableRaster(w: Int, h: Int) = RGB.createCompatibleWritableRaster(w, h) override fun isCompatibleRaster(raster: Raster?) = RGB.isCompatibleRaster(raster) override fun isCompatibleSampleModel(sm: SampleModel?) = RGB.isCompatibleSampleModel(sm) override fun getDataElement(components: IntArray?, offset: Int) = RGB.getDataElement(components, offset) override fun getDataElements(components: IntArray?, offset: Int, obj: Any?) = RGB.getDataElements(components, offset, obj) override fun getDataElements(rgb: Int, pixel: Any?) = RGB.getDataElements(rgb, pixel) override fun getComponents(pixel: Int, components: IntArray?, offset: Int) = RGB.getComponents(pixel, components, offset) override fun getComponents(pixel: Any?, components: IntArray?, offset: Int) = RGB.getComponents(pixel, components, offset) override fun coerceData(raster: WritableRaster?, isAlphaPremultiplied: Boolean) = RGB.coerceData(raster, isAlphaPremultiplied) override fun getAlphaRaster(raster: WritableRaster?) = RGB.getAlphaRaster(raster) }
mit
949b9fe8f05b81c27fc688474f16ca1b
37.568966
130
0.741055
3.978648
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/conversion/copy/KotlinFilePasteProvider.kt
1
3576
// 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.conversion.copy import com.intellij.ide.PasteProvider import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.LangDataKeys import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.ide.CopyPasteManager import com.intellij.psi.JavaDirectoryService import com.intellij.psi.PsiDocumentManager import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.IncorrectOperationException import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory import java.awt.datatransfer.DataFlavor class KotlinFilePasteProvider : PasteProvider { override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT override fun isPastePossible(dataContext: DataContext): Boolean = true override fun performPaste(dataContext: DataContext) { val text = CopyPasteManager.getInstance().getContents<String>(DataFlavor.stringFlavor) ?: return val project = CommonDataKeys.PROJECT.getData(dataContext) val ideView = LangDataKeys.IDE_VIEW.getData(dataContext) if (project == null || ideView == null || ideView.directories.isEmpty()) return val ktFile = KtPsiFactory(project).createFile(text) val fileName = (ktFile.declarations.firstOrNull()?.name ?: return) + ".kt" val directory = ideView.getOrChooseDirectory() ?: return project.executeWriteCommand(KotlinBundle.message("create.kotlin.file")) { val file = try { directory.createFile(fileName) } catch (e: IncorrectOperationException) { return@executeWriteCommand } val documentManager = PsiDocumentManager.getInstance(project) val document = documentManager.getDocument(file) if (document != null) { document.setText(text) documentManager.commitDocument(document) val qualifiedName = JavaDirectoryService.getInstance()?.getPackage(directory)?.qualifiedName if (qualifiedName != null && file is KtFile) { file.packageFqName = FqName(qualifiedName) } OpenFileDescriptor(project, file.virtualFile).navigate(true) } } } override fun isPasteEnabled(dataContext: DataContext): Boolean { val project = CommonDataKeys.PROJECT.getData(dataContext) val ideView = LangDataKeys.IDE_VIEW.getData(dataContext) if (project == null || ideView == null || ideView.directories.isEmpty()) return false val text = CopyPasteManager.getInstance().getContents<String>(DataFlavor.stringFlavor) ?: return false //todo: KT-25329, to remove these heuristics if (text.contains(";\n") || ((text.contains("public interface") || text.contains("public class")) && !text.contains("fun ")) ) return false //Optimisation for Java. Kotlin doesn't need that... val file = KtPsiFactory(project).createFile(text) return !PsiTreeUtil.hasErrorElements(file) } }
apache-2.0
0029f9db407def0044b0cf78c89591d9
47.986301
158
0.712808
5.001399
false
false
false
false
googlemaps/android-places-demos
demo-kotlin/app/src/gms/java/com/example/placesdemo/programmatic_autocomplete/PlacePredictionAdapter.kt
1
2830
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.example.placesdemo.programmatic_autocomplete import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.ViewHolder import com.example.placesdemo.R import com.example.placesdemo.programmatic_autocomplete.PlacePredictionAdapter.PlacePredictionViewHolder import com.google.android.libraries.places.api.model.AutocompletePrediction import java.util.* /** * A [RecyclerView.Adapter] for a [com.google.android.libraries.places.api.model.AutocompletePrediction]. */ class PlacePredictionAdapter : RecyclerView.Adapter<PlacePredictionViewHolder>() { private val predictions: MutableList<AutocompletePrediction> = ArrayList() var onPlaceClickListener: ((AutocompletePrediction) -> Unit)? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PlacePredictionViewHolder { val inflater = LayoutInflater.from(parent.context) return PlacePredictionViewHolder( inflater.inflate(R.layout.place_prediction_item, parent, false)) } override fun onBindViewHolder(holder: PlacePredictionViewHolder, position: Int) { val place = predictions[position] holder.setPrediction(place) holder.itemView.setOnClickListener { onPlaceClickListener?.invoke(place) } } override fun getItemCount(): Int { return predictions.size } fun setPredictions(predictions: List<AutocompletePrediction>?) { this.predictions.clear() this.predictions.addAll(predictions!!) notifyDataSetChanged() } class PlacePredictionViewHolder(itemView: View) : ViewHolder(itemView) { private val title: TextView = itemView.findViewById(R.id.text_view_title) private val address: TextView = itemView.findViewById(R.id.text_view_address) fun setPrediction(prediction: AutocompletePrediction) { title.text = prediction.getPrimaryText(null) address.text = prediction.getSecondaryText(null) } } interface OnPlaceClickListener { fun onPlaceClicked(place: AutocompletePrediction) } }
apache-2.0
984b1bf19e0cdfd28e4d107a8d957d35
38.319444
105
0.745936
4.631751
false
false
false
false
Kotlin/kotlinx.coroutines
reactive/kotlinx-coroutines-rx3/test/IntegrationTest.kt
1
4722
/* * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.rx3 import io.reactivex.rxjava3.core.* import kotlinx.coroutines.* import kotlinx.coroutines.flow.consumeAsFlow import org.junit.Test import org.junit.runner.* import org.junit.runners.* import kotlin.coroutines.* import kotlin.test.* @RunWith(Parameterized::class) class IntegrationTest( private val ctx: Ctx, private val delay: Boolean ) : TestBase() { enum class Ctx { MAIN { override fun invoke(context: CoroutineContext): CoroutineContext = context.minusKey(Job) }, DEFAULT { override fun invoke(context: CoroutineContext): CoroutineContext = Dispatchers.Default }, UNCONFINED { override fun invoke(context: CoroutineContext): CoroutineContext = Dispatchers.Unconfined }; abstract operator fun invoke(context: CoroutineContext): CoroutineContext } companion object { @Parameterized.Parameters(name = "ctx={0}, delay={1}") @JvmStatic fun params(): Collection<Array<Any>> = Ctx.values().flatMap { ctx -> listOf(false, true).map { delay -> arrayOf(ctx, delay) } } } @Test fun testEmpty(): Unit = runBlocking { val observable = rxObservable<String>(ctx(coroutineContext)) { if (delay) delay(1) // does not send anything } assertFailsWith<NoSuchElementException> { observable.awaitFirst() } assertEquals("OK", observable.awaitFirstOrDefault("OK")) assertNull(observable.awaitFirstOrNull()) assertEquals("ELSE", observable.awaitFirstOrElse { "ELSE" }) assertFailsWith<NoSuchElementException> { observable.awaitLast() } assertFailsWith<NoSuchElementException> { observable.awaitSingle() } var cnt = 0 observable.collect { cnt++ } assertEquals(0, cnt) } @Test fun testSingle() = runBlocking { val observable = rxObservable(ctx(coroutineContext)) { if (delay) delay(1) send("OK") } assertEquals("OK", observable.awaitFirst()) assertEquals("OK", observable.awaitFirstOrDefault("OK")) assertEquals("OK", observable.awaitFirstOrNull()) assertEquals("OK", observable.awaitFirstOrElse { "ELSE" }) assertEquals("OK", observable.awaitLast()) assertEquals("OK", observable.awaitSingle()) var cnt = 0 observable.collect { assertEquals("OK", it) cnt++ } assertEquals(1, cnt) } @Test fun testNumbers() = runBlocking<Unit> { val n = 100 * stressTestMultiplier val observable = rxObservable(ctx(coroutineContext)) { for (i in 1..n) { send(i) if (delay) delay(1) } } assertEquals(1, observable.awaitFirst()) assertEquals(1, observable.awaitFirstOrDefault(0)) assertEquals(1, observable.awaitFirstOrNull()) assertEquals(1, observable.awaitFirstOrElse { 0 }) assertEquals(n, observable.awaitLast()) assertFailsWith<IllegalArgumentException> { observable.awaitSingle() } checkNumbers(n, observable) val channel = observable.openSubscription() ctx(coroutineContext) checkNumbers(n, channel.consumeAsFlow().asObservable()) channel.cancel() } @Test fun testCancelWithoutValue() = runTest { val job = launch(Job(), start = CoroutineStart.UNDISPATCHED) { rxObservable<String> { hang { } }.awaitFirst() } job.cancel() job.join() } @Test fun testEmptySingle() = runTest(unhandled = listOf({e -> e is NoSuchElementException})) { expect(1) val job = launch(Job(), start = CoroutineStart.UNDISPATCHED) { rxObservable<String> { yield() expect(2) // Nothing to emit }.awaitFirst() } job.join() finish(3) } @Test fun testObservableWithTimeout() = runTest { val observable = rxObservable<Int> { expect(2) withTimeout(1) { delay(100) } } try { expect(1) observable.awaitFirstOrNull() } catch (e: CancellationException) { expect(3) } finish(4) } private suspend fun checkNumbers(n: Int, observable: Observable<Int>) { var last = 0 observable.collect { assertEquals(++last, it) } assertEquals(n, last) } }
apache-2.0
37ee75e2f14942e882963e29136dddf2
30.271523
114
0.59424
4.91875
false
true
false
false
benoitletondor/EasyBudget
Android/EasyBudget/app/src/main/java/com/benoitletondor/easybudgetapp/view/settings/backup/BackupSettingsActivity.kt
1
19409
/* * Copyright 2022 Benoit LETONDOR * * 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.benoitletondor.easybudgetapp.view.settings.backup import android.content.Intent import android.os.Bundle import android.text.format.DateUtils import android.view.MenuItem import android.view.View import androidx.activity.viewModels import androidx.lifecycle.lifecycleScope import com.benoitletondor.easybudgetapp.R import com.benoitletondor.easybudgetapp.databinding.ActivityBackupSettingsBinding import com.benoitletondor.easybudgetapp.helper.BaseActivity import com.benoitletondor.easybudgetapp.helper.launchCollect import com.google.android.material.dialog.MaterialAlertDialogBuilder import dagger.hilt.android.AndroidEntryPoint import java.util.* import kotlin.system.exitProcess @AndroidEntryPoint class BackupSettingsActivity : BaseActivity<ActivityBackupSettingsBinding>() { private val viewModel: BackupSettingsViewModel by viewModels() override fun createBinding(): ActivityBackupSettingsBinding = ActivityBackupSettingsBinding.inflate(layoutInflater) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setSupportActionBar(binding.toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) lifecycleScope.launchCollect(viewModel.cloudBackupStateFlow) { cloudBackupState -> when (cloudBackupState) { BackupCloudStorageState.NotAuthenticated -> { binding.backupSettingsCloudStorageNotAuthenticatedState.visibility = View.VISIBLE binding.backupSettingsCloudStorageAuthenticatingState.visibility = View.GONE binding.backupSettingsCloudStorageNotActivatedState.visibility = View.GONE } BackupCloudStorageState.Authenticating -> { binding.backupSettingsCloudStorageNotAuthenticatedState.visibility = View.GONE binding.backupSettingsCloudStorageAuthenticatingState.visibility = View.VISIBLE binding.backupSettingsCloudStorageNotActivatedState.visibility = View.GONE } is BackupCloudStorageState.NotActivated -> { binding.backupSettingsCloudStorageNotAuthenticatedState.visibility = View.GONE binding.backupSettingsCloudStorageAuthenticatingState.visibility = View.GONE binding.backupSettingsCloudStorageNotActivatedState.visibility = View.VISIBLE binding.backupSettingsCloudStorageEmail.text = cloudBackupState.currentUser.email binding.backupSettingsCloudStorageLogoutButton.visibility = View.VISIBLE binding.backupSettingsCloudStorageBackupSwitch.visibility = View.VISIBLE binding.backupSettingsCloudStorageBackupSwitchDescription.visibility = View.VISIBLE binding.backupSettingsCloudStorageBackupSwitchDescription.text = getString( R.string.backup_settings_cloud_backup_status, getString(R.string.backup_settings_cloud_backup_status_disabled), ) binding.backupSettingsCloudStorageBackupSwitch.isChecked = false binding.backupSettingsCloudStorageActivatedDescription.visibility = View.GONE binding.backupSettingsCloudLastUpdate.visibility = View.GONE binding.backupSettingsCloudBackupCta.visibility = View.GONE binding.backupSettingsCloudRestoreCta.visibility = View.GONE binding.backupSettingsCloudStorageRestoreDescription.visibility = View.GONE binding.backupSettingsCloudStorageRestoreExplanation.visibility = View.GONE binding.backupSettingsCloudStorageDeleteTitle.visibility = View.GONE binding.backupSettingsCloudStorageDeleteExplanation.visibility = View.GONE binding.backupSettingsCloudDeleteCta.visibility = View.GONE binding.backupSettingsCloudBackupLoadingProgress.visibility = View.GONE } is BackupCloudStorageState.Activated -> { binding.backupSettingsCloudStorageNotAuthenticatedState.visibility = View.GONE binding.backupSettingsCloudStorageAuthenticatingState.visibility = View.GONE binding.backupSettingsCloudStorageNotActivatedState.visibility = View.VISIBLE binding.backupSettingsCloudStorageEmail.text = cloudBackupState.currentUser.email binding.backupSettingsCloudStorageLogoutButton.visibility = View.VISIBLE binding.backupSettingsCloudStorageBackupSwitchDescription.visibility = View.VISIBLE binding.backupSettingsCloudStorageBackupSwitchDescription.text = getString( R.string.backup_settings_cloud_backup_status, getString(R.string.backup_settings_cloud_backup_status_activated), ) binding.backupSettingsCloudStorageBackupSwitch.visibility = View.VISIBLE binding.backupSettingsCloudStorageBackupSwitch.isChecked = true binding.backupSettingsCloudStorageActivatedDescription.visibility = View.VISIBLE showLastUpdateDate(cloudBackupState.lastBackupDate) binding.backupSettingsCloudLastUpdate.visibility = View.VISIBLE if (cloudBackupState.backupNowAvailable) { binding.backupSettingsCloudBackupCta.visibility = View.VISIBLE } else { binding.backupSettingsCloudBackupCta.visibility = View.GONE } if (cloudBackupState.restoreAvailable) { binding.backupSettingsCloudStorageRestoreDescription.visibility = View.VISIBLE binding.backupSettingsCloudStorageRestoreExplanation.visibility = View.VISIBLE binding.backupSettingsCloudRestoreCta.visibility = View.VISIBLE binding.backupSettingsCloudStorageDeleteTitle.visibility = View.VISIBLE binding.backupSettingsCloudStorageDeleteExplanation.visibility = View.VISIBLE binding.backupSettingsCloudDeleteCta.visibility = View.VISIBLE } else { binding.backupSettingsCloudRestoreCta.visibility = View.GONE binding.backupSettingsCloudStorageRestoreDescription.visibility = View.GONE binding.backupSettingsCloudStorageRestoreExplanation.visibility = View.GONE binding.backupSettingsCloudStorageDeleteTitle.visibility = View.GONE binding.backupSettingsCloudStorageDeleteExplanation.visibility = View.GONE binding.backupSettingsCloudDeleteCta.visibility = View.GONE } binding.backupSettingsCloudBackupLoadingProgress.visibility = View.GONE } is BackupCloudStorageState.BackupInProgress -> { binding.backupSettingsCloudStorageNotAuthenticatedState.visibility = View.GONE binding.backupSettingsCloudStorageAuthenticatingState.visibility = View.GONE binding.backupSettingsCloudStorageNotActivatedState.visibility = View.VISIBLE binding.backupSettingsCloudStorageEmail.text = cloudBackupState.currentUser.email binding.backupSettingsCloudStorageLogoutButton.visibility = View.GONE binding.backupSettingsCloudStorageBackupSwitch.visibility = View.GONE binding.backupSettingsCloudStorageBackupSwitchDescription.visibility = View.GONE binding.backupSettingsCloudStorageActivatedDescription.visibility = View.GONE binding.backupSettingsCloudLastUpdate.visibility = View.GONE binding.backupSettingsCloudBackupCta.visibility = View.GONE binding.backupSettingsCloudRestoreCta.visibility = View.GONE binding.backupSettingsCloudStorageRestoreDescription.visibility = View.GONE binding.backupSettingsCloudStorageRestoreExplanation.visibility = View.GONE binding.backupSettingsCloudStorageDeleteTitle.visibility = View.GONE binding.backupSettingsCloudStorageDeleteExplanation.visibility = View.GONE binding.backupSettingsCloudDeleteCta.visibility = View.GONE binding.backupSettingsCloudBackupLoadingProgress.visibility = View.VISIBLE } is BackupCloudStorageState.RestorationInProgress -> { binding.backupSettingsCloudStorageNotAuthenticatedState.visibility = View.GONE binding.backupSettingsCloudStorageAuthenticatingState.visibility = View.GONE binding.backupSettingsCloudStorageNotActivatedState.visibility = View.VISIBLE binding.backupSettingsCloudStorageEmail.text = cloudBackupState.currentUser.email binding.backupSettingsCloudStorageLogoutButton.visibility = View.GONE binding.backupSettingsCloudStorageBackupSwitch.visibility = View.GONE binding.backupSettingsCloudStorageBackupSwitchDescription.visibility = View.GONE binding.backupSettingsCloudStorageActivatedDescription.visibility = View.GONE binding.backupSettingsCloudLastUpdate.visibility = View.GONE binding.backupSettingsCloudBackupCta.visibility = View.GONE binding.backupSettingsCloudRestoreCta.visibility = View.GONE binding.backupSettingsCloudStorageRestoreDescription.visibility = View.GONE binding.backupSettingsCloudStorageRestoreExplanation.visibility = View.GONE binding.backupSettingsCloudStorageDeleteTitle.visibility = View.GONE binding.backupSettingsCloudStorageDeleteExplanation.visibility = View.GONE binding.backupSettingsCloudDeleteCta.visibility = View.GONE binding.backupSettingsCloudBackupLoadingProgress.visibility = View.VISIBLE } is BackupCloudStorageState.DeletionInProgress -> { binding.backupSettingsCloudStorageNotAuthenticatedState.visibility = View.GONE binding.backupSettingsCloudStorageAuthenticatingState.visibility = View.GONE binding.backupSettingsCloudStorageNotActivatedState.visibility = View.VISIBLE binding.backupSettingsCloudStorageEmail.text = cloudBackupState.currentUser.email binding.backupSettingsCloudStorageLogoutButton.visibility = View.GONE binding.backupSettingsCloudStorageBackupSwitch.visibility = View.GONE binding.backupSettingsCloudStorageBackupSwitchDescription.visibility = View.GONE binding.backupSettingsCloudStorageActivatedDescription.visibility = View.GONE binding.backupSettingsCloudLastUpdate.visibility = View.GONE binding.backupSettingsCloudBackupCta.visibility = View.GONE binding.backupSettingsCloudRestoreCta.visibility = View.GONE binding.backupSettingsCloudStorageRestoreDescription.visibility = View.GONE binding.backupSettingsCloudStorageRestoreExplanation.visibility = View.GONE binding.backupSettingsCloudStorageDeleteTitle.visibility = View.GONE binding.backupSettingsCloudStorageDeleteExplanation.visibility = View.GONE binding.backupSettingsCloudDeleteCta.visibility = View.GONE binding.backupSettingsCloudBackupLoadingProgress.visibility = View.VISIBLE } } } lifecycleScope.launchCollect(viewModel.backupNowErrorEventFlow) { MaterialAlertDialogBuilder(this) .setTitle(R.string.backup_now_error_title) .setMessage(R.string.backup_now_error_message) .setPositiveButton(android.R.string.ok, null) } lifecycleScope.launchCollect(viewModel.previousBackupAvailableEventFlow) { lastBackupDate -> MaterialAlertDialogBuilder(this) .setTitle(R.string.backup_already_exist_title) .setMessage( getString( R.string.backup_already_exist_message, lastBackupDate.formatLastBackupDate() ) ) .setPositiveButton(R.string.backup_already_exist_positive_cta) { _, _ -> viewModel.onRestorePreviousBackupButtonPressed() } .setNegativeButton(R.string.backup_already_exist_negative_cta) { _, _ -> viewModel.onIgnorePreviousBackupButtonPressed() } .show() } lifecycleScope.launchCollect(viewModel.restorationErrorEventFlow) { MaterialAlertDialogBuilder(this) .setTitle(R.string.backup_restore_error_title) .setMessage(R.string.backup_restore_error_message) .setPositiveButton(android.R.string.ok, null) } lifecycleScope.launchCollect(viewModel.appRestartEventFlow) { val intent = packageManager.getLaunchIntentForPackage(packageName) finishAffinity() startActivity(intent) exitProcess(0) } lifecycleScope.launchCollect(viewModel.restoreConfirmationDisplayEventFlow) { lastBackupDate -> MaterialAlertDialogBuilder(this) .setTitle(R.string.backup_restore_confirmation_title) .setMessage( getString( R.string.backup_restore_confirmation_message, lastBackupDate.formatLastBackupDate() ) ) .setPositiveButton(R.string.backup_restore_confirmation_positive_cta) { _, _ -> viewModel.onRestoreBackupConfirmationConfirmed() } .setNegativeButton(R.string.backup_restore_confirmation_negative_cta) { _, _ -> viewModel.onRestoreBackupConfirmationCancelled() } .show() } lifecycleScope.launchCollect(viewModel.authenticationConfirmationDisplayEventFlow) { MaterialAlertDialogBuilder(this) .setTitle(R.string.backup_settings_not_authenticated_privacy_title) .setMessage(R.string.backup_settings_not_authenticated_privacy_message) .setPositiveButton(R.string.backup_settings_not_authenticated_privacy_positive_cta) { _, _ -> viewModel.onAuthenticationConfirmationConfirmed(this) } .setNegativeButton(R.string.backup_settings_not_authenticated_privacy_negative_cta) { _, _ -> viewModel.onAuthenticationConfirmationCancelled() } .show() } lifecycleScope.launchCollect(viewModel.deleteConfirmationDisplayEventFlow) { MaterialAlertDialogBuilder(this) .setTitle(R.string.backup_wipe_data_confirmation_title) .setMessage(R.string.backup_wipe_data_confirmation_message) .setPositiveButton(R.string.backup_wipe_data_confirmation_positive_cta) { _, _ -> viewModel.onDeleteBackupConfirmationConfirmed() } .setNegativeButton(R.string.backup_wipe_data_confirmation_negative_cta) { _, _ -> viewModel.onDeleteBackupConfirmationCancelled() } .show() } lifecycleScope.launchCollect(viewModel.backupDeletionErrorEventFlow) { MaterialAlertDialogBuilder(this) .setTitle(R.string.backup_wipe_data_error_title) .setMessage(R.string.backup_wipe_data_error_message) .setPositiveButton(android.R.string.ok, null) .show() } binding.backupSettingsCloudStorageAuthenticateButton.setOnClickListener { viewModel.onAuthenticateButtonPressed() } binding.backupSettingsCloudStorageLogoutButton.setOnClickListener { viewModel.onLogoutButtonPressed() } binding.backupSettingsCloudStorageBackupSwitch.setOnCheckedChangeListener { _, checked -> if( checked ) { viewModel.onBackupActivated() } else { viewModel.onBackupDeactivated() } } binding.backupSettingsCloudBackupCta.setOnClickListener { viewModel.onBackupNowButtonPressed() } binding.backupSettingsCloudRestoreCta.setOnClickListener { viewModel.onRestoreButtonPressed() } binding.backupSettingsCloudDeleteCta.setOnClickListener { viewModel.onDeleteBackupButtonPressed() } } private fun showLastUpdateDate(lastBackupDate: Date?) { binding.backupSettingsCloudLastUpdate.text = if( lastBackupDate != null ) { val timeFormatted = DateUtils.getRelativeDateTimeString( this, lastBackupDate.time, DateUtils.MINUTE_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, DateUtils.FORMAT_SHOW_TIME ) getString(R.string.backup_last_update_date, timeFormatted) } else { getString(R.string.backup_last_update_date, getString(R.string.backup_last_update_date_never)) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { finish() return true } } return super.onOptionsItemSelected(item) } @Deprecated("Deprecated in Java") override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) viewModel.handleActivityResult(requestCode, resultCode, data) } private fun Date.formatLastBackupDate(): String { return DateUtils.formatDateTime( this@BackupSettingsActivity, this.time, DateUtils.FORMAT_SHOW_TIME or DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_YEAR ) } }
apache-2.0
324fd55cb1c56a694ffc59f6580eb222
54.139205
119
0.662579
5.713571
false
false
false
false
leafclick/intellij-community
plugins/stats-collector/test/com/intellij/stats/completion/PerformanceTests.kt
1
3147
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.stats.completion import com.intellij.codeInsight.completion.LightFixtureCompletionTestCase import com.intellij.openapi.application.ApplicationManager import com.intellij.stats.network.service.RequestService import com.intellij.stats.network.service.ResponseData import com.intellij.stats.sender.StatisticSenderImpl import com.intellij.stats.storage.FilePathProvider import com.intellij.testFramework.UsefulTestCase import com.intellij.testFramework.replaceService import org.mockito.Mockito.* import org.picocontainer.MutablePicoContainer import java.io.File import java.util.concurrent.atomic.AtomicBoolean class PerformanceTests : LightFixtureCompletionTestCase() { private lateinit var pathProvider: FilePathProvider private val runnable = "interface Runnable { void run(); void notify(); void wait(); void notifyAll(); }" private val text = """ class Test { public void run() { Runnable r = new Runnable() { public void run() {} }; r<caret> } } """ override fun setUp() { super.setUp() val container = ApplicationManager.getApplication().picoContainer as MutablePicoContainer pathProvider = container.getComponentInstance(FilePathProvider::class.java.name) as FilePathProvider CompletionTrackerInitializer.isEnabledInTests = true } override fun tearDown() { CompletionTrackerInitializer.isEnabledInTests = false try { super.tearDown() } finally { CompletionLoggerProvider.getInstance().dispose() val statsDir = pathProvider.getStatsDataDirectory() statsDir.deleteRecursively() } } fun `test do not block EDT on data send`() { myFixture.configureByText("Test.java", text) myFixture.addClass(runnable) val requestService = slowRequestService() val file = pathProvider.getUniqueFile() file.writeText("Some existing data to send") val app = ApplicationManager.getApplication() app.replaceService(FilePathProvider::class.java, pathProvider, testRootDisposable) app.replaceService(RequestService::class.java, requestService, testRootDisposable) val sender = StatisticSenderImpl() val isSendFinished = AtomicBoolean(false) val lock = Object() app.executeOnPooledThread { synchronized(lock, { lock.notify() }) sender.sendStatsData("") isSendFinished.set(true) } synchronized(lock, { lock.wait() }) myFixture.type('.') myFixture.completeBasic() myFixture.type("xx") UsefulTestCase.assertFalse(isSendFinished.get()) } private fun slowRequestService(): RequestService { return mock(RequestService::class.java).apply { `when`(postZipped(anyString(), any() ?: File("."))).then { Thread.sleep(10000) ResponseData(200) } } } }
apache-2.0
6e5df4b8a03132ea4d2a3f8aca90a886
33.582418
140
0.684461
5.092233
false
true
false
false
chromeos/video-composition-sample
VideoCompositionSample/src/main/java/dev/chromeos/videocompositionsample/presentation/tools/extensions/BundleExtension.kt
1
1171
/* * Copyright (c) 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("unused") package dev.chromeos.videocompositionsample.presentation.tools.extensions import android.os.Bundle fun Bundle?.putStringBuild(key: String, value: String?): Bundle? { if (this == null) return null this.putString(key, value) return this } fun Bundle?.putIntBuild(key: String, value: Int): Bundle? { if (this == null) return null this.putInt(key, value) return this } fun Bundle?.putBooleanBuild(key: String, value: Boolean): Bundle? { if (this == null) return null this.putBoolean(key, value) return this }
apache-2.0
490a13d3c4ecf4b4d818f0bebb2df110
29.051282
75
0.717336
3.903333
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/casts/intersectionTypeSmartcast.kt
5
432
interface A { fun foo(): Any? } interface B { fun foo(): String } fun bar(x: Any?): String { if (x is A) { val k = x.foo() if (k != "OK") return "fail 1" } if (x is B) { val k = x.foo() if (k.length != 2) return "fail 2" } if (x is A && x is B) { return x.foo() } return "fail 4" } fun box(): String = bar(object : A, B { override fun foo() = "OK" })
apache-2.0
4641e3dd7c0858f4e286153d99a7cad1
15.037037
68
0.444444
2.899329
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/codegen/kclass/kclass0.kt
1
2681
package codegen.kclass.kclass0 import kotlin.test.* import kotlin.reflect.KClass @Test fun runTest() { main(emptyArray<String>()) } fun main(args: Array<String>) { checkClass(Any::class, "kotlin.Any", "Any", Any(), null) checkClass(Int::class, "kotlin.Int", "Int", 42, "17") checkClass(String::class, "kotlin.String", "String", "17", 42) checkClass(RootClass::class, "codegen.kclass.kclass0.RootClass", "RootClass", RootClass(), Any()) checkClass(RootClass.Nested::class, "codegen.kclass.kclass0.RootClass.Nested", "Nested", RootClass.Nested(), Any()) class Local { val captured = args inner class Inner } checkClass(Local::class, null, "Local", Local(), Any()) checkClass(Local.Inner::class, null, "Inner", Local().Inner(), Any()) val obj = object : Any() { val captured = args inner class Inner val innerKClass = Inner::class } checkClass(obj::class, null, null, obj, Any()) checkClass(obj.innerKClass, null, "Inner", obj.Inner(), Any()) // Interfaces: checkClass(Comparable::class, "kotlin.Comparable", "Comparable", 42, Any()) checkClass(Interface::class, "codegen.kclass.kclass0.Interface", "Interface", object : Interface {}, Any()) checkInstanceClass(Any(), Any::class) checkInstanceClass(42, Int::class) assert(42::class == Int::class) checkReifiedClass<Int>(Int::class) checkReifiedClass<Int?>(Int::class) checkReifiedClass2<Int>(Int::class) checkReifiedClass2<Int?>(Int::class) checkReifiedClass<Any>(Any::class) checkReifiedClass2<Any>(Any::class) checkReifiedClass2<Any?>(Any::class) checkReifiedClass<Local>(Local::class) checkReifiedClass2<Local>(Local::class) checkReifiedClass<RootClass>(RootClass::class) checkReifiedClass2<RootClass>(RootClass::class) } class RootClass { class Nested } interface Interface fun checkClass( clazz: KClass<*>, expectedQualifiedName: String?, expectedSimpleName: String?, expectedInstance: Any, expectedNotInstance: Any? ) { assert(clazz.qualifiedName == expectedQualifiedName) assert(clazz.simpleName == expectedSimpleName) assert(clazz.isInstance(expectedInstance)) if (expectedNotInstance != null) assert(!clazz.isInstance(expectedNotInstance)) } fun checkInstanceClass(instance: Any, clazz: KClass<*>) { assert(instance::class == clazz) } inline fun <reified T> checkReifiedClass(expectedClass: KClass<*>) { assert(T::class == expectedClass) } inline fun <reified T> checkReifiedClass2(expectedClass: KClass<*>) { checkReifiedClass<T>(expectedClass) checkReifiedClass<T?>(expectedClass) }
apache-2.0
4041199d67144279a2e8a298d44334fa
31.301205
119
0.688549
3.781382
false
false
false
false
smmribeiro/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/util/cs.kt
9
2462
// 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. @file:JvmName("CompileStaticUtil") package org.jetbrains.plugins.groovy.lang.psi.util import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiElement import com.intellij.psi.PsiMember import com.intellij.psi.PsiReference import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.parentsOfType import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMember import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.* import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil.isEnumConstant fun isCompileStatic(e: PsiElement): Boolean { val containingMember = PsiTreeUtil.getParentOfType(e, PsiMember::class.java, false) return containingMember != null && isCompileStatic(containingMember) } /** * Returns `@POJO` annotation or `null` if this annotation is absent or has no effect */ fun getPOJO(typedef : GrTypeDefinition): PsiAnnotation? { // we are interested in static compilation here, not in static typechecker val inCSContext = typedef.parentsOfType<GrMember>(true).any { it.hasAnnotation(GROOVY_TRANSFORM_COMPILE_STATIC) } if (inCSContext) { return typedef.getAnnotation(GROOVY_TRANSFORM_STC_POJO) } else { return null } } fun isCompileStatic(member: PsiMember): Boolean { return CachedValuesManager.getProjectPsiDependentCache(member, ::isCompileStaticInner) } private fun isCompileStaticInner(member: PsiMember): Boolean { val annotation = getCompileStaticAnnotation(member) if (annotation != null) return checkForPass(annotation) val enclosingMember = PsiTreeUtil.getParentOfType(member, PsiMember::class.java, true) return enclosingMember != null && isCompileStatic(enclosingMember) } fun getCompileStaticAnnotation(member: PsiMember): PsiAnnotation? { val list = member.modifierList ?: return null return list.findAnnotation(GROOVY_TRANSFORM_COMPILE_STATIC) ?: list.findAnnotation(GROOVY_TRANSFORM_TYPE_CHECKED) } fun checkForPass(annotation: PsiAnnotation): Boolean { val value = annotation.findAttributeValue("value") return value == null || value is PsiReference && isEnumConstant(value, "PASS", GROOVY_TRANSFORM_TYPE_CHECKING_MODE) }
apache-2.0
0558f88814f6226db3dce8cbb9d08794
42.964286
158
0.795288
4.215753
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/search/usagesSearch/operators/InvokeOperatorReferenceSearcher.kt
2
3224
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.search.usagesSearch.operators import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.search.SearchRequestCollector import com.intellij.psi.search.SearchScope import com.intellij.util.Processor import org.jetbrains.kotlin.idea.references.KtInvokeFunctionReference import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions import org.jetbrains.kotlin.idea.util.application.getService import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.psiUtil.isExtensionDeclaration import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance import org.jetbrains.uast.UMethod import org.jetbrains.uast.UastContext import org.jetbrains.uast.convertOpt class InvokeOperatorReferenceSearcher( targetFunction: PsiElement, searchScope: SearchScope, consumer: Processor<in PsiReference>, optimizer: SearchRequestCollector, options: KotlinReferencesSearchOptions ) : OperatorReferenceSearcher<KtCallExpression>(targetFunction, searchScope, consumer, optimizer, options, wordsToSearch = emptyList()) { private val callArgumentsSize: Int? init { val uastContext = targetFunction.project.getService<UastContext>() callArgumentsSize = when { uastContext != null -> { val uMethod = uastContext.convertOpt<UMethod>(targetDeclaration, null) val uastParameters = uMethod?.uastParameters if (uastParameters != null) { val isStableNumberOfArguments = uastParameters.none { uParameter -> @Suppress("UElementAsPsi") uParameter.uastInitializer != null || uParameter.isVarArgs } if (isStableNumberOfArguments) { val numberOfArguments = uastParameters.size when { targetFunction.isExtensionDeclaration() -> numberOfArguments - 1 else -> numberOfArguments } } else { null } } else { null } } else -> null } } override fun processPossibleReceiverExpression(expression: KtExpression) { val callExpression = expression.parent as? KtCallExpression ?: return processReferenceElement(callExpression) } override fun isReferenceToCheck(ref: PsiReference) = ref is KtInvokeFunctionReference override fun extractReference(element: KtElement): PsiReference? { val callExpression = element as? KtCallExpression ?: return null if (callArgumentsSize != null && callArgumentsSize != callExpression.valueArguments.size) { return null } return callExpression.references.firstIsInstance<KtInvokeFunctionReference>() } }
apache-2.0
0c927065f0019cdbf0d5821b27c41f93
40.346154
158
0.680211
5.767442
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/repl/src/org/jetbrains/kotlin/console/CommandHistory.kt
6
1028
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.console import com.intellij.openapi.util.TextRange class CommandHistory { class Entry( val entryText: String, val rangeInHistoryDocument: TextRange ) private val entries = arrayListOf<Entry>() var processedEntriesCount: Int = 0 private set val listeners = arrayListOf<HistoryUpdateListener>() operator fun get(i: Int) = entries[i] fun addEntry(entry: Entry) { entries.add(entry) listeners.forEach { it.onNewEntry(entry) } } fun lastUnprocessedEntry(): Entry? = if (processedEntriesCount < size) { get(processedEntriesCount) } else { null } fun entryProcessed() { processedEntriesCount++ } val size: Int get() = entries.size } interface HistoryUpdateListener { fun onNewEntry(entry: CommandHistory.Entry) }
apache-2.0
125a075e2c61dd75d0fd67e68927538a
24.097561
158
0.679961
4.26556
false
false
false
false
smmribeiro/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/settings/pandoc/PandocSettingsPanel.kt
1
5201
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.settings.pandoc import com.intellij.openapi.fileChooser.FileChooser import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.fileChooser.FileChooserFactory import com.intellij.openapi.project.Project import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.vfs.VfsUtil import com.intellij.ui.IdeBorderFactory import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBTextField import com.intellij.util.ui.GridBag import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import org.intellij.plugins.markdown.MarkdownBundle import java.awt.GridBagConstraints import java.awt.GridBagLayout import java.io.File import javax.swing.BoxLayout import javax.swing.JButton import javax.swing.JPanel internal class PandocSettingsPanel(private val project: Project): JPanel(GridBagLayout()) { private val executablePathSelector = TextFieldWithBrowseButton() private val testButton = JButton(MarkdownBundle.message("markdown.settings.pandoc.executable.test")) private val infoPanel = JPanel().apply { layout = BoxLayout(this, BoxLayout.Y_AXIS) } private val imagesPathSelector = TextFieldWithBrowseButton() private val settings get() = PandocSettings.getInstance(project) val executablePath get() = executablePathSelector.text.takeIf { it.isNotEmpty() } val imagesPath get() = imagesPathSelector.text.takeIf { it.isNotEmpty() } init { val gb = GridBag().apply { defaultAnchor = GridBagConstraints.WEST defaultFill = GridBagConstraints.HORIZONTAL nextLine().next() } add( JBLabel(MarkdownBundle.message("markdown.settings.pandoc.executable.label")), gb.insets(JBUI.insetsRight(UIUtil.DEFAULT_HGAP)) ) add(executablePathSelector, gb.next().fillCellHorizontally().weightx(1.0).insets(0, 0, 1, 0)) add(testButton, gb.next()) gb.nextLine().next() add(infoPanel, gb.next().insets(4, 4, 0, 0)) gb.nextLine().next() add( JBLabel(MarkdownBundle.message("markdown.settings.pandoc.resource.path.label")), gb.insets(JBUI.insetsRight(UIUtil.DEFAULT_HGAP)) ) add(imagesPathSelector, gb.next().coverLine().insets(0, 0, 1, 0)) testButton.addActionListener { infoPanel.removeAll() val path = executablePath ?: PandocExecutableDetector.detect() val labelText = when (val detectedVersion = PandocExecutableDetector.obtainPandocVersion(project, path)) { null -> MarkdownBundle.message("markdown.settings.pandoc.executable.error.msg", path) else -> MarkdownBundle.message("markdown.settings.pandoc.executable.success.msg", detectedVersion) } infoPanel.add(JBLabel(labelText).apply { border = IdeBorderFactory.createEmptyBorder(JBUI.insetsBottom(4)) }) } setupFileChooser( browser = executablePathSelector, descriptor = FileChooserDescriptor(true, false, true, true, false, false), defaultValue = { settings.pathToPandoc } ) setupFileChooser( browser = imagesPathSelector, descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor(), defaultValue = { settings.pathToImages } ) reset() } private fun setupFileChooser(browser: TextFieldWithBrowseButton, descriptor: FileChooserDescriptor, defaultValue: () -> String?) { defaultValue()?.takeIf { it.isNotEmpty() }?.let { imagesPathSelector.text = it } browser.addActionListener { val lastFile = browser.text.takeIf { it.isNotEmpty() }?.let { VfsUtil.findFileByIoFile(File(it), false) } val files = FileChooser.chooseFiles(descriptor, project, lastFile) if (files.size == 1) { browser.text = files.first().presentableUrl } } FileChooserFactory.getInstance().installFileCompletion( browser.textField, descriptor, true, browser ) } fun apply() { settings.pathToPandoc = executablePath settings.pathToImages = imagesPath } fun isModified(): Boolean { return executablePath != settings.pathToPandoc || imagesPath != settings.pathToImages } private fun updateExecutablePathSelectorEmptyText() { val detectedPath = PandocExecutableDetector.detect() if (detectedPath.isNotEmpty()) { (executablePathSelector.textField as JBTextField).emptyText.text = MarkdownBundle.message( "markdown.settings.pandoc.executable.auto", detectedPath ) } else { (executablePathSelector.textField as JBTextField).emptyText.text = MarkdownBundle.message( "markdown.settings.pandoc.executable.default.error.msg" ) } } fun reset() { when (val path = settings.pathToPandoc) { null -> { executablePathSelector.text = "" updateExecutablePathSelectorEmptyText() } else -> { executablePathSelector.text = path } } imagesPathSelector.text = settings.pathToImages ?: "" } }
apache-2.0
6769573a7eab882067044198fe4bb06f
37.242647
158
0.728706
4.538394
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/hierarchy/calls/callers/kotlinProperty/main0.kt
13
808
open class KBase { open var name = "" } class KA: KBase() { override var <caret>name = "A" fun foo(s: String): String = "A: $s" } fun packageFun(s: String): String = KBase().name + KA().name val packageVal = KBase().name + KA().name class KClient { init { KBase().name = "" KA().name = "" } companion object { val a = KBase().name + KA().name } var bar: String get() = KBase().name + KA().name set(value: String) { KBase().name = value KA().name = value } fun bar() { fun localFun() = KBase().name + KA().name val s = KBase().name + KA().name } } object KClientObj { val a = KBase().name + KA().name init { KBase().name = "" KA().name = "" } }
apache-2.0
967c4bd63648de139954606f221f58b5
17.386364
60
0.47896
3.219124
false
false
false
false
smmribeiro/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/details/FullCommitDetailsListPanel.kt
1
5219
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.log.ui.details import com.intellij.openapi.Disposable import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.runInEdt import com.intellij.openapi.diff.DiffBundle import com.intellij.openapi.progress.* import com.intellij.openapi.progress.impl.CoreProgressManager import com.intellij.openapi.progress.util.ProgressWindow import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.changes.Change import com.intellij.openapi.vcs.changes.ui.SimpleChangesBrowser import com.intellij.ui.OnePixelSplitter import com.intellij.ui.SimpleTextAttributes import com.intellij.ui.components.JBLoadingPanel import com.intellij.util.Consumer import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.ui.JBUI import com.intellij.util.ui.components.BorderLayoutPanel import com.intellij.vcs.log.VcsCommitMetadata import com.intellij.vcs.log.VcsLogBundle import com.intellij.vcs.log.data.SingleTaskController import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.NonNls import java.awt.BorderLayout import javax.swing.JPanel @ApiStatus.Experimental abstract class FullCommitDetailsListPanel( project: Project, parent: Disposable, modalityState: ModalityState ) : BorderLayoutPanel() { companion object { @NonNls private const val DETAILS_SPLITTER = "Full.Commit.Details.List.Splitter" } private val changesBrowserWithLoadingPanel = ChangesBrowserWithLoadingPanel(project, parent) private val changesLoadingController = ChangesLoadingController(project, parent, modalityState, changesBrowserWithLoadingPanel, ::loadChanges) private val commitDetails = CommitDetailsListPanel(project, parent).apply { border = JBUI.Borders.empty() } init { val detailsSplitter = OnePixelSplitter(true, DETAILS_SPLITTER, 0.67f) detailsSplitter.firstComponent = changesBrowserWithLoadingPanel detailsSplitter.secondComponent = commitDetails addToCenter(detailsSplitter) } fun commitsSelected(selectedCommits: List<VcsCommitMetadata>) { commitDetails.setCommits(selectedCommits) changesLoadingController.request(selectedCommits) } @RequiresBackgroundThread @Throws(VcsException::class) protected abstract fun loadChanges(commits: List<VcsCommitMetadata>): List<Change> } private class ChangesBrowserWithLoadingPanel(project: Project, disposable: Disposable) : JPanel(BorderLayout()) { private val changesBrowser = SimpleChangesBrowser(project, false, false) .also { it.hideViewerBorder() } private val changesBrowserLoadingPanel = JBLoadingPanel(BorderLayout(), disposable, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS).apply { add(changesBrowser, BorderLayout.CENTER) } init { add(changesBrowserLoadingPanel) } fun startLoading() { changesBrowserLoadingPanel.startLoading() changesBrowser.viewer.setEmptyText(DiffBundle.message("diff.count.differences.status.text", 0)) } fun stopLoading(changes: List<Change>) { changesBrowserLoadingPanel.stopLoading() changesBrowser.setChangesToDisplay(changes) } fun setErrorText(@NlsContexts.StatusText error: String) { changesBrowser.setChangesToDisplay(emptyList()) changesBrowser.viewer.emptyText.setText(error, SimpleTextAttributes.ERROR_ATTRIBUTES) } } private class ChangesLoadingController( private val project: Project, disposable: Disposable, private val modalityState: ModalityState, private val changesBrowser: ChangesBrowserWithLoadingPanel, private val loader: (List<VcsCommitMetadata>) -> List<Change> ) : SingleTaskController<List<VcsCommitMetadata>, List<Change>>( VcsLogBundle.message("loading.commit.changes"), Consumer { changes -> runInEdt(modalityState = modalityState) { changesBrowser.stopLoading(changes) } }, disposable ) { override fun startNewBackgroundTask(): SingleTask { runInEdt(modalityState = modalityState) { changesBrowser.startLoading() } val task: Task.Backgroundable = object : Task.Backgroundable(project, VcsLogBundle.message("loading.commit.changes")) { override fun run(indicator: ProgressIndicator) { var result: List<Change>? = null try { val request = popRequest() ?: return result = loader(request) } catch (e: ProcessCanceledException) { throw e } catch (e: VcsException) { runInEdt(modalityState = modalityState) { changesBrowser.setErrorText(e.message) } } finally { taskCompleted(result ?: emptyList()) } } } val indicator = EmptyProgressIndicator() val future = (ProgressManager.getInstance() as CoreProgressManager).runProcessWithProgressAsynchronously(task, indicator, null) return SingleTaskImpl(future, indicator) } override fun cancelRunningTasks(requests: List<List<VcsCommitMetadata>>) = true }
apache-2.0
802b7c3ef6c8a677952912ec970595d5
36.285714
140
0.770837
4.79247
false
false
false
false
jotomo/AndroidAPS
danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_24_CIR_CF_Array.kt
1
1529
package info.nightscout.androidaps.danars.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danars.encryption.BleEncryption import javax.inject.Inject class DanaRS_Packet_Bolus_Get_24_CIR_CF_Array( injector: HasAndroidInjector ) : DanaRS_Packet(injector) { @Inject lateinit var danaPump: DanaPump init { opCode = BleEncryption.DANAR_PACKET__OPCODE_BOLUS__GET_24_CIR_CF_ARRAY aapsLogger.debug(LTag.PUMPCOMM, "New message") } override fun handleMessage(data: ByteArray) { danaPump.units = byteArrayToInt(getBytes(data, DATA_START, 1)) for (i in 0 .. 23) { val cir = byteArrayToInt(getBytes(data, DATA_START + 1 + 2 * i, 2)).toDouble() val cf = if (danaPump.units == DanaPump.UNITS_MGDL) byteArrayToInt(getBytes(data, DATA_START + 1 + 48 + 2 * i, 2)).toDouble() else byteArrayToInt(getBytes(data, DATA_START + 1 + 48 + 2 * i, 2)) / 100.0 danaPump.cir24[i] = cir danaPump.cf24[i] = cf aapsLogger.debug(LTag.PUMPCOMM, "$i: CIR: $cir CF: $cf") } if (danaPump.units < 0 || danaPump.units > 1) failed = true aapsLogger.debug(LTag.PUMPCOMM, "Pump units: " + if (danaPump.units == DanaPump.UNITS_MGDL) "MGDL" else "MMOL") } override fun getFriendlyName(): String { return "BOLUS__GET_24_ CIR_CF_ARRAY" } }
agpl-3.0
cb95c503a42bbfd6109e5f61575994cf
38.230769
119
0.64552
3.784653
false
false
false
false
kickstarter/android-oss
app/src/test/java/com/kickstarter/viewmodels/UpdateViewModelTest.kt
1
14090
package com.kickstarter.viewmodels import android.content.Intent import android.net.Uri import android.util.Pair import com.kickstarter.KSRobolectricTestCase import com.kickstarter.libs.MockCurrentUser import com.kickstarter.libs.RefTag import com.kickstarter.libs.models.OptimizelyFeature import com.kickstarter.libs.utils.NumberUtils import com.kickstarter.mock.MockExperimentsClientType import com.kickstarter.mock.factories.ProjectFactory.project import com.kickstarter.mock.factories.UpdateFactory import com.kickstarter.mock.factories.UserFactory.creator import com.kickstarter.mock.services.MockApiClient import com.kickstarter.models.Update import com.kickstarter.services.ApiClientType import com.kickstarter.ui.IntentKey import okhttp3.Request import org.junit.Test import rx.Observable import rx.observers.TestSubscriber import rx.schedulers.TestScheduler import java.util.concurrent.TimeUnit class UpdateViewModelTest : KSRobolectricTestCase() { private val defaultIntent = Intent() .putExtra(IntentKey.PROJECT, project()) .putExtra(IntentKey.UPDATE, UpdateFactory.update()) @Test fun testOpenProjectExternally_whenProjectUrlIsPreview() { val environment = environment() val vm = UpdateViewModel.ViewModel(environment) val openProjectExternally = TestSubscriber<String>() vm.outputs.openProjectExternally().subscribe(openProjectExternally) // Start the intent with a project and update. vm.intent(defaultIntent) val url = "https://www.kickstarter.com/projects/smithsonian/smithsonian-anthology-of-hip-hop-and-rap?token=beepboop" val projectRequest: Request = Request.Builder() .url(url) .build() vm.inputs.goToProjectRequest(projectRequest) openProjectExternally.assertValue("$url&ref=update") } @Test fun testUpdateViewModel_LoadsWebViewUrl() { val vm = UpdateViewModel.ViewModel(environment()) val update = UpdateFactory.update() val anotherUpdateUrl = "https://kck.str/projects/param/param/posts/next-id" val anotherUpdateRequest: Request = Request.Builder() .url(anotherUpdateUrl) .build() val webViewUrl = TestSubscriber<String>() vm.outputs.webViewUrl().subscribe(webViewUrl) // Start the intent with a project and update. vm.intent(defaultIntent) // Initial update's url emits. webViewUrl.assertValues(update.urls()?.web()?.update()) // Make a request for another update. vm.inputs.goToUpdateRequest(anotherUpdateRequest) // New update url emits. webViewUrl.assertValues(update.urls()?.web()?.update(), anotherUpdateUrl) } @Test fun testUpdateViewModel_StartCommentsActivity() { val environment = environment() val vm = UpdateViewModel.ViewModel(environment) val update = UpdateFactory.update() val commentsRequest: Request = Request.Builder() .url("https://kck.str/projects/param/param/posts/id/comments") .build() val startRootCommentsActivity = TestSubscriber<Update>() vm.outputs.startRootCommentsActivity().subscribe(startRootCommentsActivity) // Start the intent with a project and update. vm.intent( Intent() .putExtra(IntentKey.PROJECT, project()) .putExtra(IntentKey.UPDATE, update) ) vm.inputs.goToCommentsRequest(commentsRequest) startRootCommentsActivity.assertValue(update) } @Test fun testUpdateViewModel_StartProjectActivity() { val environment = environment() val vm = UpdateViewModel.ViewModel(environment) val startProjectActivity = TestSubscriber<Uri>() vm.outputs.startProjectActivity() .map<Uri> { it.first } .subscribe(startProjectActivity) // Start the intent with a project and update. vm.intent(defaultIntent) val url = "https://www.kickstarter.com/projects/smithsonian/smithsonian-anthology-of-hip-hop-and-rap" val projectRequest: Request = Request.Builder() .url(url) .build() vm.inputs.goToProjectRequest(projectRequest) startProjectActivity.assertValues(Uri.parse(url)) } @Test fun testUpdateViewModel_whenFeatureFlagOn_shouldEmitProjectPage() { val user = MockCurrentUser() val mockExperimentsClientType: MockExperimentsClientType = object : MockExperimentsClientType() { override fun isFeatureEnabled(feature: OptimizelyFeature.Key): Boolean { return true } } val environment = environment().toBuilder() .currentUser(user) .optimizely(mockExperimentsClientType) .build() val vm = UpdateViewModel.ViewModel(environment) val startProjectActivity = TestSubscriber<Pair<Uri, RefTag>>() vm.outputs.startProjectActivity().subscribe(startProjectActivity) // Start the intent with a project and update. vm.intent(defaultIntent) val url = "https://www.kickstarter.com/projects/smithsonian/smithsonian-anthology-of-hip-hop-and-rap" val projectRequest: Request = Request.Builder() .url(url) .build() vm.inputs.goToProjectRequest(projectRequest) startProjectActivity.assertValueCount(1) assertEquals(startProjectActivity.onNextEvents[0].first, Uri.parse(url)) assertEquals(startProjectActivity.onNextEvents[0].second, RefTag.update()) } @Test fun testUpdateViewModel_StartShareIntent() { val vm = UpdateViewModel.ViewModel(environment()) val creator = creator().toBuilder().id(278438049L).build() val project = project().toBuilder().creator(creator).build() val updatesUrl = "https://www.kck.str/projects/" + project.creator() .param() + "/" + project.param() + "/posts" val id = 15 val web = Update.Urls.Web.builder() .update("$updatesUrl/$id") .likes("$updatesUrl/likes") .build() val update = UpdateFactory.update() .toBuilder() .id(id.toLong()) .projectId(project.id()) .urls(Update.Urls.builder().web(web).build()) .build() val startShareIntent = TestSubscriber<Pair<Update, String>>() vm.outputs.startShareIntent().subscribe(startShareIntent) // Start the intent with a project and update. vm.intent( Intent() .putExtra(IntentKey.PROJECT, project()) .putExtra(IntentKey.UPDATE, update) ) vm.inputs.shareIconButtonClicked() val expectedShareUrl = "https://www.kck.str/projects/" + project.creator().param() + "/" + project.param() + "/posts/" + id + "?ref=android_update_share" startShareIntent.assertValue(Pair.create(update, expectedShareUrl)) } @Test fun testUpdateViewModel_UpdateSequence() { val initialUpdate = UpdateFactory.update().toBuilder().sequence(1).build() val anotherUpdate = UpdateFactory.update().toBuilder().sequence(2).build() val anotherUpdateRequest: Request = Request.Builder() .url("https://kck.str/projects/param/param/posts/id") .build() val apiClient: ApiClientType = object : MockApiClient() { override fun fetchUpdate( projectParam: String, updateParam: String ): Observable<Update> { return Observable.just(anotherUpdate) } } val environment = environment().toBuilder().apiClient(apiClient).build() val vm = UpdateViewModel.ViewModel(environment) val updateSequence = TestSubscriber<String>() vm.outputs.updateSequence().subscribe(updateSequence) // Start the intent with a project and update. vm.intent( Intent() .putExtra(IntentKey.PROJECT, project()) .putExtra(IntentKey.UPDATE, initialUpdate) ) // Initial update's sequence number emits. updateSequence.assertValues(NumberUtils.format(initialUpdate.sequence())) vm.inputs.goToUpdateRequest(anotherUpdateRequest) // New sequence should emit for new update page. updateSequence.assertValues( NumberUtils.format(initialUpdate.sequence()), NumberUtils.format(anotherUpdate.sequence()) ) } @Test fun testUpdateViewModel_WebViewUrl() { val vm = UpdateViewModel.ViewModel(environment()) val update = UpdateFactory.update() val webViewUrl = TestSubscriber<String>() vm.outputs.webViewUrl().subscribe(webViewUrl) // Start the intent with a project and update. vm.intent( Intent() .putExtra(IntentKey.PROJECT, project()) .putExtra(IntentKey.UPDATE, update) ) // Initial update index url emits. webViewUrl.assertValues(update.urls()?.web()?.update()) } @Test fun testUpdateViewModel_DeepLinkPost() { val postId = "3254626" val update = UpdateFactory.update().toBuilder().sequence(2).build() val apiClient: ApiClientType = object : MockApiClient() { override fun fetchUpdate( projectParam: String, updateParam: String ): Observable<Update> { return Observable.just(update) } } val environment = environment().toBuilder().apiClient(apiClient).build() val vm = UpdateViewModel.ViewModel(environment) val webViewUrl = TestSubscriber<String>() vm.outputs.webViewUrl().subscribe(webViewUrl) // Start the intent with a project and update. vm.intent( Intent() .putExtra(IntentKey.PROJECT, project()) .putExtra(IntentKey.UPDATE_POST_ID, postId) ) // Initial update index url emits. webViewUrl.assertValues(update.urls()?.web()?.update()) } @Test fun testUpdateViewModel_DeepLinkComment() { val postId = "3254626" val update = UpdateFactory.update() val apiClient: ApiClientType = object : MockApiClient() { override fun fetchUpdate( projectParam: String, updateParam: String ): Observable<Update> { return Observable.just(update) } } val testScheduler = TestScheduler() val environment = environment().toBuilder().apiClient(apiClient).scheduler(testScheduler).build() val vm = UpdateViewModel.ViewModel(environment) val startRootCommentsActivity = TestSubscriber<Update>() vm.outputs.startRootCommentsActivity().subscribe(startRootCommentsActivity) val webViewUrl = TestSubscriber<String>() vm.outputs.webViewUrl().subscribe(webViewUrl) val deepLinkToRootComment = TestSubscriber<Boolean>() vm.hasCommentsDeepLinks().subscribe(deepLinkToRootComment) // Start the intent with a project and update. vm.intent( Intent() .putExtra(IntentKey.PROJECT, project()) .putExtra(IntentKey.UPDATE_POST_ID, postId) .putExtra(IntentKey.IS_UPDATE_COMMENT, true) ) // Initial update index url emits. webViewUrl.assertValues(update.urls()?.web()?.update()) deepLinkToRootComment.assertValue(true) vm.inputs.goToCommentsActivity() testScheduler.advanceTimeBy(2, TimeUnit.SECONDS) startRootCommentsActivity.assertValue(update) startRootCommentsActivity.assertValueCount(1) } @Test fun testUpdateViewModel_DeepLinkCommentThread() { val postId = "3254626" val commentableId = "Q29tbWVudC0zMzU2MTY4Ng" val update = UpdateFactory.update() val apiClient: ApiClientType = object : MockApiClient() { override fun fetchUpdate( projectParam: String, updateParam: String ): Observable<Update> { return Observable.just(update) } } val testScheduler = TestScheduler() val environment = environment().toBuilder().apiClient(apiClient).scheduler(testScheduler).build() val vm = UpdateViewModel.ViewModel(environment) val startRootCommentsActivityToDeepLinkThreadActivity = TestSubscriber<Pair<String, Update>>() vm.outputs.startRootCommentsActivityToDeepLinkThreadActivity() .subscribe(startRootCommentsActivityToDeepLinkThreadActivity) val webViewUrl = TestSubscriber<String>() vm.outputs.webViewUrl().subscribe(webViewUrl) val deepLinkToThreadActivity = TestSubscriber<Pair<String, Boolean>>() vm.deepLinkToThreadActivity().subscribe(deepLinkToThreadActivity) // Start the intent with a project and update. vm.intent( Intent() .putExtra(IntentKey.PROJECT, project()) .putExtra(IntentKey.UPDATE_POST_ID, postId) .putExtra(IntentKey.IS_UPDATE_COMMENT, true) .putExtra(IntentKey.COMMENT, commentableId) ) // Initial update index url emits. webViewUrl.assertValues(update.urls()?.web()?.update()) deepLinkToThreadActivity.assertValue(Pair.create(commentableId, true)) vm.inputs.goToCommentsActivityToDeepLinkThreadActivity(commentableId) testScheduler.advanceTimeBy(2, TimeUnit.SECONDS) startRootCommentsActivityToDeepLinkThreadActivity.assertValue( Pair.create( commentableId, update ) ) startRootCommentsActivityToDeepLinkThreadActivity.assertValueCount(1) } }
apache-2.0
7637088d17a822adc769e716ec272132
37.184282
118
0.646203
5.032143
false
true
false
false
devjn/GithubSearch
ios/src/main/kotlin/com/github/devjn/githubsearch/ui/BaseSearchController.kt
1
6183
package com.github.devjn.githubsearch.ui import android.util.Log import apple.coregraphics.c.CoreGraphics.CGRectMake import apple.foundation.NSOperationQueue import apple.foundation.enums.NSQualityOfService import apple.uikit.* import apple.uikit.enums.NSTextAlignment import apple.uikit.enums.UIActivityIndicatorViewStyle import apple.uikit.enums.UITableViewCellSeparatorStyle import apple.uikit.protocol.UISearchBarDelegate import apple.uikit.protocol.UISearchControllerDelegate import apple.uikit.protocol.UISearchResultsUpdating import com.github.devjn.githubsearch.model.entities.GitData import com.github.devjn.githubsearch.service.GitHubApi import com.github.devjn.githubsearch.model.entities.GitObject import com.github.devjn.githubsearch.service.GithubService import io.reactivex.Single import io.reactivex.disposables.CompositeDisposable import io.reactivex.ios.schedulers.IOSSchedulers import io.reactivex.schedulers.Schedulers import org.moe.natj.general.Pointer import org.moe.natj.general.ann.Generated import org.moe.natj.general.ann.NInt import org.moe.natj.objc.ann.Selector /** * Created by @author Jahongir on 13-May-17 * [email protected] * BaseSearchController */ abstract class BaseSearchController<T : GitObject> : UITableViewController, UISearchControllerDelegate, UISearchResultsUpdating, UISearchBarDelegate { @Selector("navigation") external fun navigation(): UINavigationItem protected lateinit var searchController: UISearchController open val TAG = BaseSearchController::class.java.simpleName!! val CELL_IDENTIFIER: String val type: Int protected val data: ArrayList<T> = ArrayList() protected val gitHubApi = GithubService.createService(GitHubApi::class.java) protected var disposables: CompositeDisposable = CompositeDisposable() protected var lastGitData: GitData<T>? = null protected var lastQuery = "" private var operationQueue: NSOperationQueue protected constructor(peer: Pointer, type: Int) : super(peer) { this.type = type this.CELL_IDENTIFIER = if (type == TYPE_USERS) "userCell" else "repositoryCell" operationQueue = NSOperationQueue.alloc().init() operationQueue.setQualityOfService(NSQualityOfService.Background) } protected fun initViews(controller: BaseSearchController<T>) { initSearchBar(controller) activityIndicator() } protected fun initSearchBar(controller: BaseSearchController<T>) { this.searchController = UISearchController.alloc().initWithSearchResultsController(null) this.searchController.setSearchResultsUpdater(controller) this.searchController.setDelegate(controller) this.searchController.searchBar().setDelegate(controller) this.searchController.setHidesNavigationBarDuringPresentation(false) this.searchController.setDimsBackgroundDuringPresentation(true) this.navigationItem().setTitleView(searchController.searchBar()) this.setDefinesPresentationContext(true) } fun search(query: String) { val api: Single<GitData<T>> = (if (type == TYPE_USERS) gitHubApi.getUsers(query) else gitHubApi.getRepositories(query)) as Single<GitData<T>> disposables.add(api.subscribeOn(Schedulers.io()) .observeOn(IOSSchedulers.mainThread()) .doOnSubscribe { showProgress(true) } .doFinally { showProgress(false) } .subscribe({ gitData -> data.clear() gitData.items?.let { data.addAll(it) } lastGitData = gitData this.tableView().reloadData() Log.e(TAG, "Loaded data") }, { e -> Log.e(TAG, "Error while getting data", e) })); } override fun viewDidUnload() { disposables.clear() super.viewDidUnload() } override fun tableViewNumberOfRowsInSection(tableView: UITableView, @NInt section: Long) = data.size.toLong() @Selector("setNavigation:") external fun setNavigation_unsafe(value: UINavigationItem?) @Generated fun setNavigation(value: UINavigationItem?) { val __old = navigation() if (value != null) { org.moe.natj.objc.ObjCRuntime.associateObjCObject(this, value) } setNavigation_unsafe(value) if (__old != null) { org.moe.natj.objc.ObjCRuntime.dissociateObjCObject(this, __old) } } private var indicator = UIActivityIndicatorView.alloc()!! fun activityIndicator() { indicator.initWithFrame(CGRectMake(0.0, 0.0, 48.0, 48.0)) indicator.setActivityIndicatorViewStyle(UIActivityIndicatorViewStyle.Gray) indicator.setCenter(this.view().center()) this.view().addSubview(indicator) } fun showProgress(show: Boolean) { if (show) { indicator.startAnimating() indicator.setBackgroundColor(UIColor.whiteColor()) } else { indicator.stopAnimating() indicator.setHidesWhenStopped(true) } } object TableViewHelper { fun showEmptyMessage(message: String, viewController: UITableViewController) { val messageLabel = UILabel.alloc().initWithFrame(CGRectMake(0.0, 0.0, viewController.view().bounds().size().width(), viewController.view().bounds().size().height())) messageLabel.setText(message) messageLabel.setTextColor(UIColor.blackColor()) messageLabel.setNumberOfLines(0) messageLabel.setTextAlignment(NSTextAlignment.Center) // messageLabel.sizeToFit() viewController.tableView().setBackgroundView(messageLabel) viewController.tableView().setSeparatorStyle(UITableViewCellSeparatorStyle.None) } fun restore(viewController: UITableViewController) { viewController.tableView().setBackgroundView(null) viewController.tableView().setSeparatorStyle(UITableViewCellSeparatorStyle.SingleLine) } } companion object { const val TYPE_USERS = 0 const val TYPE_REPOSITORIES = 1 } }
apache-2.0
23900df91961a0fe50e4ed4838abec3a
35.809524
177
0.70338
4.57661
false
false
false
false
alibaba/p3c
eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/StyleExtractor.kt
2
10451
package com.alibaba.smartfox.eclipse.ui.pmd import net.sourceforge.pmd.util.StringUtil import org.eclipse.swt.SWT import org.eclipse.swt.custom.StyleRange import org.eclipse.swt.widgets.Display import java.util.ArrayList import java.util.LinkedList /** * @author Brian Remedios */ open class StyleExtractor(private var syntaxData: SyntaxData?) { private val commentOffsets: MutableList<IntArray> init { commentOffsets = LinkedList<IntArray>() } fun syntax(theSyntax: SyntaxData?) { syntaxData = theSyntax } /** * Refreshes the offsets for all multiline comments in the parent * StyledText. The parent StyledText should call this whenever its text is * modified. Note that this code doesn't ignore comment markers inside * strings. * @param text the text from the StyledText */ fun refreshMultilineComments(text: String) { // Clear any stored offsets commentOffsets.clear() if (syntaxData != null) { // Go through all the instances of COMMENT_START var pos = text.indexOf(syntaxData!!.multiLineCommentStart!!) while (pos > -1) { // offsets[0] holds the COMMENT_START offset // and COMMENT_END holds the ending offset val offsets = IntArray(2) offsets[0] = pos // Find the corresponding end comment. pos = text.indexOf(syntaxData!!.multiLineCommentEnd!!, pos) // If no corresponding end comment, use the end of the text offsets[1] = if (pos == -1) text.length - 1 else pos + syntaxData!!.multiLineCommentEnd!!.length - 1 pos = offsets[1] // Add the offsets to the collection commentOffsets.add(offsets) pos = text.indexOf(syntaxData!!.multiLineCommentStart!!, pos) } } } /** * Checks to see if the specified section of text begins inside a multiline * comment. Returns the index of the closing comment, or the end of the line * if the whole line is inside the comment. Returns -1 if the line doesn't * begin inside a comment. * @param start the starting offset of the text * @param length the length of the text * @return int */ private fun getBeginsInsideComment(start: Int, length: Int): Int { // Assume section doesn't being inside a comment var index = -1 // Go through the multiline comment ranges var i = 0 val n = commentOffsets.size while (i < n) { val offsets = commentOffsets[i] // If starting offset is past range, quit if (offsets[0] > start + length) { break } // Check to see if section begins inside a comment if (offsets[0] <= start && offsets[1] >= start) { // It does; determine if the closing comment marker is inside // this section index = if (offsets[1] > start + length) start + length else offsets[1] + syntaxData!!.multiLineCommentEnd!!.length - 1 } i++ } return index } private fun isDefinedVariable(text: String): Boolean { return StringUtil.isNotEmpty(text) } private fun atMultiLineCommentStart(text: String, position: Int): Boolean { return text.indexOf(syntaxData!!.multiLineCommentStart!!, position) == position } private fun atStringStart(text: String, position: Int): Boolean { return text.indexOf(syntaxData!!.stringStart!!, position) == position } private fun atVarnameReference(text: String, position: Int): Boolean { return syntaxData!!.varnameReference != null && text.indexOf(syntaxData!!.varnameReference!!, position) == position } private fun atSingleLineComment(text: String, position: Int): Boolean { return syntaxData!!.comment != null && text.indexOf(syntaxData!!.comment!!, position) == position } private fun getKeywordEnd(lineText: String, start: Int): Int { val length = lineText.length val buf = StringBuilder(length) var i = start // Call any consecutive letters a word while (i < length && Character.isLetter(lineText[i])) { buf.append(lineText[i]) i++ } return if (syntaxData!!.isKeyword(buf.toString())) i else 0 - i } /** * Chop up the text into individual lines starting from offset and then * determine the required styles for each. Ensures the offset is properly * accounted for in each. * @param text * @param offset * @param length * @return */ fun stylesFor(text: String, offset: Int, length: Int, lineSeparator: String): List<StyleRange> { if (syntaxData == null) { return emptyList() } val content = text.substring(offset, offset + length) val lines = content.split(lineSeparator.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() val styles = ArrayList<StyleRange>() val separatorLength = lineSeparator.length var currentOffset = offset for (line in lines) { val lineLength = line.length val lineStyles = lineStylesFor(line, 0, lineLength) for (sr in lineStyles) { sr.start += currentOffset } styles.addAll(lineStyles) currentOffset += lineLength + separatorLength } return styles } fun lineStylesFor(lineText: String, lineOffset: Int, length: Int): List<StyleRange> { val styles = ArrayList<StyleRange>() var start = 0 // Check if line begins inside a multiline comment val mlIndex = getBeginsInsideComment(lineOffset, lineText.length) if (mlIndex > -1) { // Line begins inside multiline comment; create the range styles.add(StyleRange(lineOffset, mlIndex - lineOffset, COMMENT_COLOR, COMMENT_BACKGROUND)) start = mlIndex } // Do punctuation, single-line comments, and keywords while (start < length) { // Check for multiline comments that begin inside this line if (atMultiLineCommentStart(lineText, start)) { // Determine where comment ends var endComment = lineText.indexOf(syntaxData!!.multiLineCommentEnd!!, start) // If comment doesn't end on this line, extend range to end of // line if (endComment == -1) { endComment = length } else { endComment += syntaxData!!.multiLineCommentEnd!!.length } styles.add(StyleRange(lineOffset + start, endComment - start, COMMENT_COLOR, COMMENT_BACKGROUND)) start = endComment } else if (atStringStart(lineText, start)) { // Determine where comment ends var endString = lineText.indexOf(syntaxData!!.stringEnd!!, start + 1) // If string doesn't end on this line, extend range to end of // line if (endString == -1) { endString = length } else { endString += syntaxData!!.stringEnd!!.length } styles.add(StyleRange(lineOffset + start, endString - start, STRING_COLOR, COMMENT_BACKGROUND)) start = endString } else if (atSingleLineComment(lineText, start)) { // line comments styles.add(StyleRange(lineOffset + start, length - start, COMMENT_COLOR, COMMENT_BACKGROUND)) start = length } else if (atVarnameReference(lineText, start)) { // variable // references val buf = StringBuilder() var i = start + syntaxData!!.varnameReference!!.length // Call any consecutive letters a word while (i < length && Character.isLetter(lineText[i])) { buf.append(lineText[i]) i++ } // See if the word is a variable if (isDefinedVariable(buf.toString())) { // It's a keyword; create the StyleRange styles.add(StyleRange(lineOffset + start, i - start, REFERENCED_VAR_COLOR, null, SWT.BOLD)) } // Move the marker to the last char (the one that wasn't a // letter) // so it can be retested in the next iteration through the loop start = i } else if (syntaxData!!.isPunctuation(lineText[start])) { // Add range for punctuation styles.add(StyleRange(lineOffset + start, 1, PUNCTUATION_COLOR, null)) ++start } else if (Character.isLetter(lineText[start])) { val kwEnd = getKeywordEnd(lineText, start) // is a keyword if (kwEnd > start) { styles.add(StyleRange(lineOffset + start, kwEnd - start, KEYWORD_COLOR, null)) } // Move the marker to the last char (the one that wasn't a // letter) // so it can be retested in the next iteration through the loop start = Math.abs(kwEnd) } else { ++start // It's nothing we're interested in; advance the marker }// Check for punctuation } return styles } companion object { private val COMMENT_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_DARK_GREEN) private val REFERENCED_VAR_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_DARK_GREEN) private val UNREFERENCED_VAR_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW) private val COMMENT_BACKGROUND = Display.getCurrent().getSystemColor(SWT.COLOR_WHITE) private val PUNCTUATION_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_BLACK) private val KEYWORD_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_DARK_MAGENTA) private val STRING_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_BLUE) } }
apache-2.0
4c45e9dc65bcd07fefb13a6c427a735b
37.003636
116
0.583963
4.796237
false
false
false
false
kohesive/kohesive-iac
model-aws/src/main/kotlin/uy/kohesive/iac/model/aws/proxy/ReferenceExploder.kt
1
3774
package uy.kohesive.iac.model.aws.proxy import java.util.* import kotlin.collections.ArrayList fun explodeReference(str: String): List<ResourceNode> { val stack = Stack<ResourceNode>() fun isWithinUnresolvedReference() = stack.filter { it.isReferenceNode() }.any { it.isUnresolved() } var i = 0 while (i < str.length) { val currentNode: ResourceNode? = if (stack.empty()) null else stack.peek() val nextRefStart = str.indexOf("{{kohesive:", i) val nextRefEnd = str.indexOf("}}", i) // Start new reference if (nextRefStart == i) { // We need to figure out the type of reference val refTypeStart = nextRefStart + "{{kohesive:".length val refTypeEnd = str.indexOf(":", refTypeStart) val refType = ReferenceType.fromString(str.substring( startIndex = refTypeStart, endIndex = refTypeEnd )) // Push the new reference node to the stack val referenceNode = ResourceNode.forReferenceType(refType) stack.push(referenceNode) i = refTypeEnd + 1 } else if (nextRefEnd == i && isWithinUnresolvedReference()) { // Pop the arguments (reference parts) and assign them as reference children val referenceArguments = ArrayList<ResourceNode>() while (true) { val node = stack.peek() if (node.isReferenceNode() && node.isUnresolved()) { for (referenceNode in referenceArguments) { node.insertChild(referenceNode) } break } else { referenceArguments.add(stack.pop()) } } i += 2 } else { if (str[i] == ':' && isWithinUnresolvedReference()) { if (i != nextRefStart - 1) { stack.push(ResourceNode.StringLiteralNode()) } i++; continue } // Must be a string literal val stringNode = currentNode as? ResourceNode.StringLiteralNode ?: ResourceNode.StringLiteralNode().apply { stack.push(this) } stringNode.append(str[i++]) } } return stack } sealed class ResourceNode( val arity: Int ) { companion object { fun forReferenceType(refType: ReferenceType) = when (refType) { ReferenceType.Ref -> RefNode() ReferenceType.RefProperty -> RefPropertyNode() ReferenceType.Var -> VariableNode() ReferenceType.Map -> MapNode() ReferenceType.Implicit -> ImplicitNode() } } class StringLiteralNode : ResourceNode(0) { private val value: StringBuffer = StringBuffer() fun append(c: Char) = value.append(c) fun value() = value.toString() override fun toString() = "\"$value\"" } class ImplicitNode : ResourceNode(1) class VariableNode : ResourceNode(1) class RefNode : ResourceNode(2) class RefPropertyNode : ResourceNode(3) class MapNode : ResourceNode(3) val children = ArrayList<ResourceNode>() fun isReferenceNode() = arity > 0 fun isUnresolved() = children.size < arity fun insertChild(childNode: ResourceNode, index: Int = 0) { if (children.size + 1 > arity) { throw IllegalStateException("Max children count reached for ${ this::class.simpleName }") } children.add(index, childNode) } override fun toString() = "${ this::class.simpleName }: (${children.joinToString(", ")})" }
mit
9ed2633fd416d288989851245f988d94
32.105263
101
0.558294
4.882277
false
false
false
false
siosio/intellij-community
platform/vcs-impl/src/com/intellij/vcs/commit/CommitModeManager.kt
1
6878
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.commit import com.intellij.application.subscribe import com.intellij.ide.ApplicationInitializedListener import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationManager.getApplication import com.intellij.openapi.application.ConfigImportHelper.isNewUser import com.intellij.openapi.application.runInEdt import com.intellij.openapi.components.service import com.intellij.openapi.options.advanced.AdvancedSettings import com.intellij.openapi.options.advanced.AdvancedSettingsChangeListener import com.intellij.openapi.project.Project import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.registry.RegistryValue import com.intellij.openapi.util.registry.RegistryValueListener import com.intellij.openapi.vcs.* import com.intellij.openapi.vcs.ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED import com.intellij.openapi.vcs.impl.VcsEP import com.intellij.openapi.vcs.impl.VcsInitObject import com.intellij.openapi.vcs.impl.VcsStartupActivity import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.messages.Topic import com.intellij.vcs.commit.NonModalCommitUsagesCollector.logStateChanged import java.util.* private val TOGGLE_COMMIT_UI = "vcs.non.modal.commit.toggle.ui" private val isToggleCommitUi get() = AdvancedSettings.getBoolean(TOGGLE_COMMIT_UI) private val isForceNonModalCommit get() = Registry.get("vcs.force.non.modal.commit") private val appSettings get() = VcsApplicationSettings.getInstance() internal fun AnActionEvent.getProjectCommitMode(): CommitMode? = project?.let { CommitModeManager.getInstance(it).getCurrentCommitMode() } internal class NonModalCommitCustomization : ApplicationInitializedListener { override fun componentsInitialized() { if (!isNewUser()) return PropertiesComponent.getInstance().setValue(KEY, true) appSettings.COMMIT_FROM_LOCAL_CHANGES = true logStateChanged(null) } companion object { private const val KEY = "NonModalCommitCustomization.IsApplied" internal fun isNonModalCustomizationApplied(): Boolean = PropertiesComponent.getInstance().isTrueValue(KEY) } } class CommitModeManager(private val project: Project) { class MyStartupActivity : VcsStartupActivity { override fun runActivity(project: Project) { runInEdt { if (project.isDisposed) return@runInEdt val commitModeManager = getInstance(project) commitModeManager.subscribeToChanges() commitModeManager.updateCommitMode() } } override fun getOrder(): Int = VcsInitObject.MAPPINGS.order + 50 } private var commitMode: CommitMode = CommitMode.PendingCommitMode @RequiresEdt fun updateCommitMode() { if (project.isDisposed) return val newCommitMode = getNewCommitMode() if (commitMode == newCommitMode) return commitMode = newCommitMode project.messageBus.syncPublisher(COMMIT_MODE_TOPIC).commitModeChanged() } private fun getNewCommitMode(): CommitMode { val activeVcses = ProjectLevelVcsManager.getInstance(project).allActiveVcss val singleVcs = activeVcses.singleOrNull() if (activeVcses.isEmpty()) return CommitMode.PendingCommitMode if (singleVcs != null && singleVcs.isWithCustomLocalChanges) { return CommitMode.ExternalCommitMode(singleVcs) } if (isNonModalInSettings() && canSetNonModal()) { return CommitMode.NonModalCommitMode(isToggleCommitUi) } return CommitMode.ModalCommitMode } fun getCurrentCommitMode(): CommitMode { return commitMode } internal fun canSetNonModal(): Boolean { if (isForceNonModalCommit.asBoolean()) return true val activeVcses = ProjectLevelVcsManager.getInstance(project).allActiveVcss return activeVcses.isNotEmpty() && activeVcses.all { it.type == VcsType.distributed } } private fun subscribeToChanges() { if (project.isDisposed) return isForceNonModalCommit.addListener(object : RegistryValueListener { override fun afterValueChanged(value: RegistryValue) = updateCommitMode() }, project) getApplication().messageBus.connect(project).subscribe(AdvancedSettingsChangeListener.TOPIC, object : AdvancedSettingsChangeListener { override fun advancedSettingChanged(id: String, oldValue: Any, newValue: Any) { if (id == TOGGLE_COMMIT_UI) { updateCommitMode() } } }) SETTINGS.subscribe(project, object : SettingsListener { override fun settingsChanged() = updateCommitMode() }) VcsEP.EP_NAME.addChangeListener(Runnable { updateCommitMode() }, project) project.messageBus.connect().subscribe(VCS_CONFIGURATION_CHANGED, VcsListener { runInEdt { updateCommitMode() } }) } companion object { @JvmField val SETTINGS: Topic<SettingsListener> = Topic(SettingsListener::class.java, Topic.BroadcastDirection.TO_DIRECT_CHILDREN, true) @JvmField val COMMIT_MODE_TOPIC: Topic<CommitModeListener> = Topic(CommitModeListener::class.java, Topic.BroadcastDirection.NONE, true) @JvmStatic fun getInstance(project: Project): CommitModeManager = project.service() @JvmStatic fun setCommitFromLocalChanges(project: Project?, value: Boolean) { val oldValue = appSettings.COMMIT_FROM_LOCAL_CHANGES if (oldValue == value) return appSettings.COMMIT_FROM_LOCAL_CHANGES = value logStateChanged(project) getApplication().messageBus.syncPublisher(SETTINGS).settingsChanged() } fun isNonModalInSettings(): Boolean = isForceNonModalCommit.asBoolean() || appSettings.COMMIT_FROM_LOCAL_CHANGES } interface SettingsListener : EventListener { fun settingsChanged() } interface CommitModeListener : EventListener { @RequiresEdt fun commitModeChanged() } } sealed class CommitMode { abstract fun useCommitToolWindow(): Boolean open fun hideLocalChangesTab(): Boolean = false open fun disableDefaultCommitAction(): Boolean = false object PendingCommitMode : CommitMode() { override fun useCommitToolWindow(): Boolean { // Enable 'Commit' toolwindow before vcses are activated return CommitModeManager.isNonModalInSettings() } } object ModalCommitMode : CommitMode() { override fun useCommitToolWindow(): Boolean = false } data class NonModalCommitMode(val isToggleMode: Boolean) : CommitMode() { override fun useCommitToolWindow(): Boolean = true } data class ExternalCommitMode(val vcs: AbstractVcs) : CommitMode() { override fun useCommitToolWindow(): Boolean = true override fun hideLocalChangesTab(): Boolean = true override fun disableDefaultCommitAction(): Boolean = true } }
apache-2.0
360de7ce19274c29c8b6a511f1a083fc
35.983871
140
0.766938
4.813156
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/conversion/copy/ConvertJavaCopyPasteProcessor.kt
1
14590
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.conversion.copy import com.intellij.codeInsight.editorActions.CopyPastePostProcessor import com.intellij.codeInsight.editorActions.TextBlockTransferableData import com.intellij.openapi.diagnostic.ControlFlowException import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.util.Ref import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.ThrowableComputable import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.* import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.actions.JavaToKotlinAction import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference import org.jetbrains.kotlin.idea.codeInsight.KotlinCopyPasteReferenceProcessor import org.jetbrains.kotlin.idea.codeInsight.KotlinReferenceData import org.jetbrains.kotlin.idea.configuration.ExperimentalFeatures import org.jetbrains.kotlin.idea.core.util.range import org.jetbrains.kotlin.idea.core.util.start import org.jetbrains.kotlin.idea.editor.KotlinEditorOptions import org.jetbrains.kotlin.idea.j2k.IdeaJavaToKotlinServices import org.jetbrains.kotlin.idea.statistics.ConversionType import org.jetbrains.kotlin.idea.statistics.J2KFusCollector import org.jetbrains.kotlin.idea.util.ImportInsertHelper import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.idea.util.module import org.jetbrains.kotlin.j2k.* import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import java.awt.datatransfer.Transferable import kotlin.system.measureTimeMillis class ConvertJavaCopyPasteProcessor : CopyPastePostProcessor<TextBlockTransferableData>() { @Suppress("PrivatePropertyName") private val LOG = Logger.getInstance(ConvertJavaCopyPasteProcessor::class.java) override fun extractTransferableData(content: Transferable): List<TextBlockTransferableData> { try { if (content.isDataFlavorSupported(CopiedJavaCode.DATA_FLAVOR)) { return listOf(content.getTransferData(CopiedJavaCode.DATA_FLAVOR) as TextBlockTransferableData) } } catch (e: Throwable) { if (e is ControlFlowException) throw e LOG.error(e) } return listOf() } override fun collectTransferableData( file: PsiFile, editor: Editor, startOffsets: IntArray, endOffsets: IntArray ): List<TextBlockTransferableData> { if (file !is PsiJavaFile) return listOf() return listOf(CopiedJavaCode(file.getText()!!, startOffsets, endOffsets)) } override fun processTransferableData( project: Project, editor: Editor, bounds: RangeMarker, caretOffset: Int, indented: Ref<in Boolean>, values: List<TextBlockTransferableData> ) { if (DumbService.getInstance(project).isDumb) return if (!KotlinEditorOptions.getInstance().isEnableJavaToKotlinConversion) return val data = values.single() as CopiedJavaCode val document = editor.document val targetFile = PsiDocumentManager.getInstance(project).getPsiFile(document) as? KtFile ?: return val useNewJ2k = checkUseNewJ2k(targetFile) val targetModule = targetFile.module if (isNoConversionPosition(targetFile, bounds.startOffset)) return data class Result( val text: String?, val referenceData: Collection<KotlinReferenceData>, val explicitImports: Set<FqName>, val converterContext: ConverterContext? ) val dataForConversion = DataForConversion.prepare(data, project) fun doConversion(): Result { val result = dataForConversion.elementsAndTexts.convertCodeToKotlin(project, targetModule, useNewJ2k) val referenceData = buildReferenceData(result.text, result.parseContext, dataForConversion.importsAndPackage, targetFile) val text = if (result.textChanged) result.text else null return Result(text, referenceData, result.importsToAdd, result.converterContext) } fun insertImports( bounds: TextRange, referenceData: Collection<KotlinReferenceData>, explicitImports: Collection<FqName> ): TextRange? { if (referenceData.isEmpty() && explicitImports.isEmpty()) return bounds PsiDocumentManager.getInstance(project).commitAllDocuments() val rangeMarker = document.createRangeMarker(bounds) rangeMarker.isGreedyToLeft = true rangeMarker.isGreedyToRight = true KotlinCopyPasteReferenceProcessor().processReferenceData(project, editor, targetFile, bounds.start, referenceData.toTypedArray()) runWriteAction { explicitImports.forEach { fqName -> targetFile.resolveImportReference(fqName).firstOrNull()?.let { ImportInsertHelper.getInstance(project).importDescriptor(targetFile, it) } } } return rangeMarker.range } var conversionResult: Result? = null fun doConversionAndInsertImportsIfUnchanged(): Boolean { conversionResult = doConversion() if (conversionResult!!.text != null) return false insertImports( bounds.range ?: return true, conversionResult!!.referenceData, conversionResult!!.explicitImports ) return true } val textLength = data.startOffsets.indices.sumBy { data.endOffsets[it] - data.startOffsets[it] } // if the text to convert is short enough, try to do conversion without permission from user and skip the dialog if nothing converted if (textLength < 1000 && doConversionAndInsertImportsIfUnchanged()) return fun convert() { if (conversionResult == null && doConversionAndInsertImportsIfUnchanged()) return val (text, referenceData, explicitImports) = conversionResult!! text!! // otherwise we should get true from doConversionAndInsertImportsIfUnchanged and return above val boundsAfterReplace = runWriteAction { val startOffset = bounds.startOffset document.replaceString(startOffset, bounds.endOffset, text) val endOffsetAfterCopy = startOffset + text.length editor.caretModel.moveToOffset(endOffsetAfterCopy) TextRange(startOffset, endOffsetAfterCopy) } val newBounds = insertImports(boundsAfterReplace, referenceData, explicitImports) PsiDocumentManager.getInstance(project).commitAllDocuments() runPostProcessing(project, targetFile, newBounds, conversionResult?.converterContext, useNewJ2k) conversionPerformed = true } if (confirmConvertJavaOnPaste(project, isPlainText = false)) { val conversionTime = measureTimeMillis { convert() } J2KFusCollector.log( ConversionType.PSI_EXPRESSION, ExperimentalFeatures.NewJ2k.isEnabled, conversionTime, dataForConversion.elementsAndTexts.linesCount(), filesCount = 1 ) } } private fun buildReferenceData( text: String, parseContext: ParseContext, importsAndPackage: String, targetFile: KtFile ): Collection<KotlinReferenceData> { var blockStart: Int? = null var blockEnd: Int? = null val fileText = buildString { append(importsAndPackage) val (contextPrefix, contextSuffix) = when (parseContext) { ParseContext.CODE_BLOCK -> "fun ${generateDummyFunctionName(text)}() {\n" to "\n}" ParseContext.TOP_LEVEL -> "" to "" } append(contextPrefix) blockStart = length append(text) blockEnd = length append(contextSuffix) } val dummyFile = KtPsiFactory(targetFile.project).createAnalyzableFile("dummy.kt", fileText, targetFile) val startOffset = blockStart!! val endOffset = blockEnd!! return KotlinCopyPasteReferenceProcessor().collectReferenceData(dummyFile, intArrayOf(startOffset), intArrayOf(endOffset)).map { it.copy(startOffset = it.startOffset - startOffset, endOffset = it.endOffset - startOffset) } } private fun generateDummyFunctionName(convertedCode: String): String { var i = 0 while (true) { val name = "dummy$i" if (convertedCode.indexOf(name) < 0) return name i++ } } companion object { @get:TestOnly var conversionPerformed: Boolean = false } } internal class ConversionResult( val text: String, val parseContext: ParseContext, val importsToAdd: Set<FqName>, val textChanged: Boolean, val converterContext: ConverterContext? ) internal fun ElementAndTextList.convertCodeToKotlin(project: Project, targetModule: Module?, useNewJ2k: Boolean): ConversionResult { val converter = J2kConverterExtension.extension(useNewJ2k).createJavaToKotlinConverter( project, targetModule, ConverterSettings.defaultSettings, IdeaJavaToKotlinServices ) val inputElements = toList().filterIsInstance<PsiElement>() val (results, _, converterContext) = ProgressManager.getInstance().runProcessWithProgressSynchronously( ThrowableComputable<Result, Exception> { runReadAction { converter.elementsToKotlin(inputElements) } }, JavaToKotlinAction.title, false, project ) val importsToAdd = LinkedHashSet<FqName>() var resultIndex = 0 val convertedCodeBuilder = StringBuilder() val originalCodeBuilder = StringBuilder() var parseContext: ParseContext? = null this.process(object : ElementsAndTextsProcessor { override fun processElement(element: PsiElement) { val originalText = element.text originalCodeBuilder.append(originalText) val result = results[resultIndex++] if (result != null) { convertedCodeBuilder.append(result.text) if (parseContext == null) { // use parse context of the first converted element as parse context for the whole text parseContext = result.parseContext } importsToAdd.addAll(result.importsToAdd) } else { // failed to convert element to Kotlin, insert "as is" convertedCodeBuilder.append(originalText) } } override fun processText(string: String) { originalCodeBuilder.append(string) convertedCodeBuilder.append(string) } }) val convertedCode = convertedCodeBuilder.toString() val originalCode = originalCodeBuilder.toString() return ConversionResult( convertedCode, parseContext ?: ParseContext.CODE_BLOCK, importsToAdd, convertedCode != originalCode, converterContext ) } internal fun isNoConversionPosition(file: KtFile, offset: Int): Boolean { if (offset == 0) return false val token = file.findElementAt(offset - 1) ?: return true if (token !is PsiWhiteSpace && token.endOffset != offset) return true // pasting into the middle of token for (element in token.parentsWithSelf) { when (element) { is PsiComment -> return element.node.elementType == KtTokens.EOL_COMMENT || offset != element.endOffset is KtStringTemplateEntryWithExpression -> return false is KtStringTemplateExpression -> return true } } return false } internal fun confirmConvertJavaOnPaste(project: Project, isPlainText: Boolean): Boolean { if (KotlinEditorOptions.getInstance().isDonTShowConversionDialog) return true val dialog = KotlinPasteFromJavaDialog(project, isPlainText) dialog.show() return dialog.isOK } fun ElementAndTextList.linesCount() = toList() .filterIsInstance<PsiElement>() .sumBy { StringUtil.getLineBreakCount(it.text) } fun checkUseNewJ2k(targetFile: KtFile): Boolean { if (targetFile is KtCodeFragment) return false return ExperimentalFeatures.NewJ2k.isEnabled } fun runPostProcessing( project: Project, file: KtFile, bounds: TextRange?, converterContext: ConverterContext?, useNewJ2k: Boolean ) { val postProcessor = J2kConverterExtension.extension(useNewJ2k).createPostProcessor(formatCode = true) if (useNewJ2k) { ProgressManager.getInstance().runProcessWithProgressSynchronously( { val processor = J2kConverterExtension.extension(useNewJ2k).createWithProgressProcessor( ProgressManager.getInstance().progressIndicator!!, emptyList(), postProcessor.phasesCount ) AfterConversionPass(project, postProcessor) .run( file, converterContext, bounds ) { phase, description -> processor.updateState(0, phase, description) } }, KotlinBundle.message("copy.text.convert.java.to.kotlin"), true, project ) } else { AfterConversionPass(project, postProcessor) .run( file, converterContext, bounds ) } }
apache-2.0
5fd9cec0d77745607675568572e5ba33
37.397368
158
0.66902
5.391722
false
false
false
false
siosio/intellij-community
platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/timeline/comment/SubmittableTextFieldModelBase.kt
1
2256
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.collaboration.ui.codereview.timeline.comment import com.intellij.collaboration.ui.SimpleEventListener import com.intellij.lang.Language import com.intellij.openapi.application.runUndoTransparentWriteAction import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.impl.DocumentImpl import com.intellij.openapi.fileTypes.PlainTextLanguage import com.intellij.openapi.project.Project import com.intellij.ui.LanguageTextField import com.intellij.util.EventDispatcher abstract class SubmittableTextFieldModelBase( final override val project: Project?, initialText: String, language: Language = PlainTextLanguage.INSTANCE, ) : SubmittableTextFieldModel { private val listeners = EventDispatcher.create(SimpleEventListener::class.java) final override val document: Document = LanguageTextField.createDocument( initialText, language, project, LanguageTextField.SimpleDocumentCreator() ) override val content: SubmittableTextFieldModelContent = SubmittableTextFieldModelContentImpl(document as DocumentImpl) override var isBusy = false set(value) { field = value listeners.multicaster.eventOccurred() } override var error: Throwable? = null set(value) { field = value listeners.multicaster.eventOccurred() } override fun addStateListener(listener: SimpleEventListener) { listeners.addListener(listener) } } private class SubmittableTextFieldModelContentImpl(private val document: DocumentImpl) : SubmittableTextFieldModelContent { override var text: String get() = document.text set(value) { runWriteAction { document.setText(value) } } override var isReadOnly: Boolean get() = !document.isWritable set(value) { document.setReadOnly(value) } override var isAcceptSlashR: Boolean get() = document.acceptsSlashR() set(value) { document.setAcceptSlashR(value) } override fun clear() { runUndoTransparentWriteAction { document.setText("") } } }
apache-2.0
1185265d76708698fcc0b9375864391e
29.093333
140
0.761082
4.680498
false
false
false
false
siosio/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/WorkspaceBuilderChangeLog.kt
1
6120
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.storage.impl import com.intellij.openapi.diagnostic.logger import com.intellij.workspaceModel.storage.WorkspaceEntity internal typealias ChangeLog = MutableMap<EntityId, ChangeEntry> class WorkspaceBuilderChangeLog { var modificationCount: Long = 0 internal val changeLog: ChangeLog = LinkedHashMap() internal fun clear() { modificationCount++ changeLog.clear() } internal fun <T : WorkspaceEntity> addReplaceEvent(entityId: EntityId, copiedData: WorkspaceEntityData<T>, addedChildren: List<Pair<ConnectionId, ChildEntityId>>, removedChildren: Set<Pair<ConnectionId, ChildEntityId>>, parentsMapRes: Map<ConnectionId, ParentEntityId?>) { modificationCount++ val existingChange = changeLog[entityId] val replaceEvent = ChangeEntry.ReplaceEntity(copiedData, addedChildren, removedChildren.toList(), parentsMapRes) val makeReplaceEvent = { replaceEntity: ChangeEntry.ReplaceEntity<*> -> val removedChildrenSet = removedChildren val addedChildrenSet = addedChildren.toSet() val newAddedChildren = (replaceEntity.newChildren.toSet() - removedChildrenSet + (addedChildrenSet - replaceEntity.removedChildren.toSet())).toList() val newRemovedChildren = (replaceEntity.removedChildren.toSet() - addedChildrenSet + (removedChildrenSet - replaceEntity.newChildren.toSet())).toList() val newChangedParents = replaceEntity.modifiedParents + parentsMapRes ChangeEntry.ReplaceEntity(copiedData, newAddedChildren, newRemovedChildren, newChangedParents) } if (existingChange == null) { changeLog[entityId] = replaceEvent } else { when (existingChange) { is ChangeEntry.AddEntity<*> -> changeLog[entityId] = ChangeEntry.AddEntity(copiedData, entityId.clazz) is ChangeEntry.RemoveEntity -> LOG.error("Trying to update removed entity. Skip change event. $copiedData") is ChangeEntry.ChangeEntitySource<*> -> changeLog[entityId] = ChangeEntry.ReplaceAndChangeSource.from(replaceEvent, existingChange) is ChangeEntry.ReplaceEntity<*> -> changeLog[entityId] = makeReplaceEvent(existingChange) is ChangeEntry.ReplaceAndChangeSource<*> -> { val newReplaceEvent = makeReplaceEvent(existingChange.dataChange) changeLog[entityId] = ChangeEntry.ReplaceAndChangeSource.from(newReplaceEvent, existingChange.sourceChange) } }.let { } } } internal fun <T : WorkspaceEntity> addAddEvent(pid: EntityId, pEntityData: WorkspaceEntityData<T>) { modificationCount++ // XXX: This check should exist, but some tests fails with it. //if (targetEntityId in it) LOG.error("Trying to add entity again. ") changeLog[pid] = ChangeEntry.AddEntity(pEntityData, pid.clazz) } internal fun <T : WorkspaceEntity> addChangeSourceEvent(entityId: EntityId, copiedData: WorkspaceEntityData<T>) { modificationCount++ val existingChange = changeLog[entityId] val changeSourceEvent = ChangeEntry.ChangeEntitySource(copiedData) if (existingChange == null) { changeLog[entityId] = changeSourceEvent } else { when (existingChange) { is ChangeEntry.AddEntity<*> -> changeLog[entityId] = ChangeEntry.AddEntity(copiedData, entityId.clazz) is ChangeEntry.RemoveEntity -> LOG.error("Trying to update removed entity. Skip change event. $copiedData") is ChangeEntry.ChangeEntitySource<*> -> changeLog[entityId] = changeSourceEvent is ChangeEntry.ReplaceEntity<*> -> changeLog[entityId] = ChangeEntry.ReplaceAndChangeSource.from(existingChange, changeSourceEvent) is ChangeEntry.ReplaceAndChangeSource<*> -> changeLog[entityId] = ChangeEntry.ReplaceAndChangeSource.from(existingChange.dataChange, changeSourceEvent) }.let { } } } internal fun addRemoveEvent(removedEntityId: EntityId) { modificationCount++ val existingChange = changeLog[removedEntityId] val removeEvent = ChangeEntry.RemoveEntity(removedEntityId) if (existingChange == null) { changeLog[removedEntityId] = removeEvent } else { when (existingChange) { is ChangeEntry.AddEntity<*> -> changeLog.remove(removedEntityId) is ChangeEntry.ChangeEntitySource<*> -> changeLog[removedEntityId] = removeEvent is ChangeEntry.ReplaceEntity<*> -> changeLog[removedEntityId] = removeEvent is ChangeEntry.ReplaceAndChangeSource<*> -> changeLog[removedEntityId] = removeEvent is ChangeEntry.RemoveEntity -> Unit } } } companion object { val LOG = logger<WorkspaceBuilderChangeLog>() } } internal sealed class ChangeEntry { data class AddEntity<E : WorkspaceEntity>(val entityData: WorkspaceEntityData<E>, val clazz: Int) : ChangeEntry() data class RemoveEntity(val id: EntityId) : ChangeEntry() data class ChangeEntitySource<E : WorkspaceEntity>(val newData: WorkspaceEntityData<E>) : ChangeEntry() data class ReplaceEntity<E : WorkspaceEntity>( val newData: WorkspaceEntityData<E>, val newChildren: List<Pair<ConnectionId, ChildEntityId>>, val removedChildren: List<Pair<ConnectionId, ChildEntityId>>, val modifiedParents: Map<ConnectionId, ParentEntityId?> ) : ChangeEntry() data class ReplaceAndChangeSource<E : WorkspaceEntity>( val dataChange: ReplaceEntity<E>, val sourceChange: ChangeEntitySource<E>, ) : ChangeEntry() { companion object { fun <T : WorkspaceEntity> from(dataChange: ReplaceEntity<T>, sourceChange: ChangeEntitySource<*>): ReplaceAndChangeSource<T> { return ReplaceAndChangeSource(dataChange, sourceChange as ChangeEntitySource<T>) } } } }
apache-2.0
d11dbedb7adc27732db8b7808b7e3867
45.363636
157
0.700327
4.766355
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/KotlinInlineTypeAliasHandler.kt
1
1634
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.inline import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.refactoring.HelpID import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtTypeAlias class KotlinInlineTypeAliasHandler : KotlinInlineActionHandler() { override val helpId: String? get() = HelpID.INLINE_VARIABLE override val refactoringName: String get() = KotlinBundle.message("title.inline.type.alias") override fun canInlineKotlinElement(element: KtElement): Boolean = element is KtTypeAlias override fun inlineKotlinElement(project: Project, editor: Editor?, element: KtElement) { val typeAlias = element as? KtTypeAlias ?: return if (!checkSources(project, editor, element)) return typeAlias.name ?: return typeAlias.getTypeReference() ?: return val dialog = KotlinInlineTypeAliasDialog( element, editor?.findSimpleNameReference(), editor = editor, ) if (!ApplicationManager.getApplication().isUnitTestMode) { dialog.show() } else { try { dialog.doAction() } finally { dialog.close(DialogWrapper.OK_EXIT_CODE, true) } } } }
apache-2.0
f049c365ef568ad2a15fc9ea9c775eff
36.136364
158
0.700734
4.777778
false
false
false
false
JetBrains/kotlin-native
Interop/Runtime/src/jvm/kotlin/kotlinx/cinterop/JvmNativeMem.kt
3
4525
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kotlinx.cinterop import org.jetbrains.kotlin.konan.util.nativeMemoryAllocator import sun.misc.Unsafe private val NativePointed.address: Long get() = this.rawPtr private enum class DataModel(val pointerSize: Long) { _32BIT(4), _64BIT(8) } private val dataModel: DataModel = when (System.getProperty("sun.arch.data.model")) { null -> TODO() "32" -> DataModel._32BIT "64" -> DataModel._64BIT else -> throw IllegalStateException() } // Must be only used in interop, contains host pointer size, not target! @PublishedApi internal val pointerSize: Int = dataModel.pointerSize.toInt() @PublishedApi internal object nativeMemUtils { fun getByte(mem: NativePointed) = unsafe.getByte(mem.address) fun putByte(mem: NativePointed, value: Byte) = unsafe.putByte(mem.address, value) fun getShort(mem: NativePointed) = unsafe.getShort(mem.address) fun putShort(mem: NativePointed, value: Short) = unsafe.putShort(mem.address, value) fun getInt(mem: NativePointed) = unsafe.getInt(mem.address) fun putInt(mem: NativePointed, value: Int) = unsafe.putInt(mem.address, value) fun getLong(mem: NativePointed) = unsafe.getLong(mem.address) fun putLong(mem: NativePointed, value: Long) = unsafe.putLong(mem.address, value) fun getFloat(mem: NativePointed) = unsafe.getFloat(mem.address) fun putFloat(mem: NativePointed, value: Float) = unsafe.putFloat(mem.address, value) fun getDouble(mem: NativePointed) = unsafe.getDouble(mem.address) fun putDouble(mem: NativePointed, value: Double) = unsafe.putDouble(mem.address, value) fun getNativePtr(mem: NativePointed): NativePtr = when (dataModel) { DataModel._32BIT -> getInt(mem).toLong() DataModel._64BIT -> getLong(mem) } fun putNativePtr(mem: NativePointed, value: NativePtr) = when (dataModel) { DataModel._32BIT -> putInt(mem, value.toInt()) DataModel._64BIT -> putLong(mem, value) } fun getByteArray(source: NativePointed, dest: ByteArray, length: Int) { unsafe.copyMemory(null, source.address, dest, byteArrayBaseOffset, length.toLong()) } fun putByteArray(source: ByteArray, dest: NativePointed, length: Int) { unsafe.copyMemory(source, byteArrayBaseOffset, null, dest.address, length.toLong()) } fun getCharArray(source: NativePointed, dest: CharArray, length: Int) { unsafe.copyMemory(null, source.address, dest, charArrayBaseOffset, length.toLong() * 2) } fun putCharArray(source: CharArray, dest: NativePointed, length: Int) { unsafe.copyMemory(source, charArrayBaseOffset, null, dest.address, length.toLong() * 2) } fun zeroMemory(dest: NativePointed, length: Int): Unit = unsafe.setMemory(dest.address, length.toLong(), 0) fun copyMemory(dest: NativePointed, length: Int, src: NativePointed) = unsafe.copyMemory(src.address, dest.address, length.toLong()) @Suppress("NON_PUBLIC_CALL_FROM_PUBLIC_INLINE") inline fun <reified T> allocateInstance(): T { return unsafe.allocateInstance(T::class.java) as T } internal fun allocRaw(size: Long, align: Int): NativePtr { val address = unsafe.allocateMemory(size) if (address % align != 0L) TODO(align.toString()) return address } internal fun freeRaw(mem: NativePtr) { unsafe.freeMemory(mem) } fun alloc(size: Long, align: Int) = interpretOpaquePointed(nativeMemoryAllocator.alloc(size, align)) fun free(mem: NativePtr) = nativeMemoryAllocator.free(mem) private val unsafe = with(Unsafe::class.java.getDeclaredField("theUnsafe")) { isAccessible = true return@with this.get(null) as Unsafe } private val byteArrayBaseOffset = unsafe.arrayBaseOffset(ByteArray::class.java).toLong() private val charArrayBaseOffset = unsafe.arrayBaseOffset(CharArray::class.java).toLong() }
apache-2.0
4265cc9ee59bb2d720cce975d6d25ac6
36.708333
104
0.706519
4.036574
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/SafeAccessToIfThenIntention.kt
1
4558
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions.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.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.idea.inspections.ComplexRedundantLetInspection import org.jetbrains.kotlin.idea.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.intentions.branchedTransformations.convertToIfNotNullExpression import org.jetbrains.kotlin.idea.intentions.branchedTransformations.introduceValueForCondition import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isStableSimpleExpression import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsStatement import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class SafeAccessToIfThenIntention : SelfTargetingRangeIntention<KtSafeQualifiedExpression>( KtSafeQualifiedExpression::class.java, KotlinBundle.lazyMessage("replace.safe.access.expression.with.if.expression") ), LowPriorityAction { override fun applicabilityRange(element: KtSafeQualifiedExpression): TextRange? { if (element.selectorExpression == null) return null return element.operationTokenNode.textRange } override fun applyTo(element: KtSafeQualifiedExpression, editor: Editor?) { val receiver = KtPsiUtil.safeDeparenthesize(element.receiverExpression) val selector = element.selectorExpression!! val receiverIsStable = receiver.isStableSimpleExpression() val psiFactory = KtPsiFactory(element) val dotQualified = psiFactory.createExpressionByPattern("$0.$1", receiver, selector) val elseClause = if (element.isUsedAsStatement(element.analyze())) null else psiFactory.createExpression("null") var ifExpression = element.convertToIfNotNullExpression(receiver, dotQualified, elseClause) var isAssignment = false val binaryExpression = (ifExpression.parent as? KtParenthesizedExpression)?.parent as? KtBinaryExpression val right = binaryExpression?.right if (right != null && binaryExpression.operationToken == KtTokens.EQ) { val replaced = binaryExpression.replaced(psiFactory.createExpressionByPattern("$0 = $1", ifExpression.text, right)) ifExpression = replaced.findDescendantOfType()!! isAssignment = true } val isRedundantLetCallRemoved = ifExpression.removeRedundantLetCallIfPossible(editor) if (!receiverIsStable) { val valueToExtract = when { isAssignment -> ((ifExpression.then as? KtBinaryExpression)?.left as? KtDotQualifiedExpression)?.receiverExpression isRedundantLetCallRemoved -> { val context = ifExpression.analyze(BodyResolveMode.PARTIAL) val descriptor = (ifExpression.condition as? KtBinaryExpression)?.left?.getResolvedCall(context)?.resultingDescriptor ifExpression.then?.findDescendantOfType<KtNameReferenceExpression> { it.getReferencedNameAsName() == descriptor?.name && it.getResolvedCall(context)?.resultingDescriptor == descriptor } } else -> (ifExpression.then as? KtDotQualifiedExpression)?.receiverExpression } if (valueToExtract != null) ifExpression.introduceValueForCondition(valueToExtract, editor) } } private fun KtIfExpression.removeRedundantLetCallIfPossible(editor: Editor?): Boolean { val callExpression = (then as? KtQualifiedExpression)?.callExpression ?: return false if (callExpression.calleeExpression?.text != "let") return false val redundantLetInspection = ComplexRedundantLetInspection() if (!redundantLetInspection.isApplicable(callExpression)) return false redundantLetInspection.applyTo(callExpression, project, editor) return true } }
apache-2.0
62767fbb829e29ea645742cc51925691
53.915663
158
0.749671
5.62716
false
false
false
false
vovagrechka/fucking-everything
phizdets/phizdetsc/src/org/jetbrains/kotlin/js/resolve/diagnostics/JsExternalChecker.kt
1
11049
/* * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.js.resolve.diagnostics import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.diagnostics.DiagnosticSink import org.jetbrains.kotlin.js.PredefinedAnnotation import org.jetbrains.kotlin.js.translate.utils.AnnotationsUtils import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqNameUnsafe import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.checkers.SimpleDeclarationChecker import org.jetbrains.kotlin.resolve.descriptorUtil.* import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.utils.singletonOrEmptyList object JsExternalChecker : SimpleDeclarationChecker { val DEFINED_EXTENRALLY_PROPERTY_NAMES = setOf(FqNameUnsafe("kotlin.js.noImpl"), FqNameUnsafe("kotlin.js.definedExternally")) override fun check(declaration: KtDeclaration, descriptor: DeclarationDescriptor, diagnosticHolder: DiagnosticSink, bindingContext: BindingContext) { if (!AnnotationsUtils.isNativeObject(descriptor)) return if (!DescriptorUtils.isTopLevelDeclaration(descriptor)) { if (isDirectlyExternal(declaration, descriptor) && descriptor !is PropertyAccessorDescriptor) { diagnosticHolder.report(ErrorsJs.NESTED_EXTERNAL_DECLARATION.on(declaration)) } } if (DescriptorUtils.isAnnotationClass(descriptor)) { diagnosticHolder.report(ErrorsJs.WRONG_EXTERNAL_DECLARATION.on(declaration, "annotation class")) } else if (descriptor is ClassDescriptor && descriptor.isData) { diagnosticHolder.report(ErrorsJs.WRONG_EXTERNAL_DECLARATION.on(declaration, "data class")) } else if (descriptor is PropertyAccessorDescriptor && isDirectlyExternal(declaration, descriptor)) { diagnosticHolder.report(ErrorsJs.WRONG_EXTERNAL_DECLARATION.on(declaration, "property accessor")) } else if (descriptor is ClassDescriptor && descriptor.isInner) { diagnosticHolder.report(ErrorsJs.WRONG_EXTERNAL_DECLARATION.on(declaration, "inner class")) } else if (isPrivateMemberOfExternalClass(descriptor)) { diagnosticHolder.report(ErrorsJs.WRONG_EXTERNAL_DECLARATION.on(declaration, "private member of class")) } if (descriptor !is PropertyAccessorDescriptor && descriptor.isExtension) { val target = when (descriptor) { is FunctionDescriptor -> "extension function" is PropertyDescriptor -> "extension property" else -> "extension member" } diagnosticHolder.report(ErrorsJs.WRONG_EXTERNAL_DECLARATION.on(declaration, target)) } if (descriptor is ClassDescriptor && descriptor.kind != ClassKind.ANNOTATION_CLASS) { val superClasses = (descriptor.getSuperClassNotAny().singletonOrEmptyList() + descriptor.getSuperInterfaces()).toMutableSet() if (descriptor.kind == ClassKind.ENUM_CLASS || descriptor.kind == ClassKind.ENUM_ENTRY) { superClasses.removeAll { it.fqNameUnsafe == KotlinBuiltIns.FQ_NAMES._enum } } if (superClasses.any { !AnnotationsUtils.isNativeObject(it) && it.fqNameSafe != KotlinBuiltIns.FQ_NAMES.throwable }) { diagnosticHolder.report(ErrorsJs.EXTERNAL_TYPE_EXTENDS_NON_EXTERNAL_TYPE.on(declaration)) } } if (descriptor is FunctionDescriptor && descriptor.isInline) { diagnosticHolder.report(ErrorsJs.INLINE_EXTERNAL_DECLARATION.on(declaration)) } if (descriptor is CallableMemberDescriptor && descriptor.isNonAbstractMemberOfInterface() && !descriptor.isNullableProperty() ) { diagnosticHolder.report(ErrorsJs.NON_ABSTRACT_MEMBER_OF_EXTERNAL_INTERFACE.on(declaration)) } checkBody(declaration, descriptor, diagnosticHolder, bindingContext) checkDelegation(declaration, descriptor, diagnosticHolder) checkAnonymousInitializer(declaration, diagnosticHolder) checkEnumEntry(declaration, diagnosticHolder) checkConstructorPropertyParam(declaration, descriptor, diagnosticHolder) } private fun checkBody( declaration: KtDeclaration, descriptor: DeclarationDescriptor, diagnosticHolder: DiagnosticSink, bindingContext: BindingContext ) { if (declaration is KtProperty && descriptor is PropertyAccessorDescriptor) return if (declaration is KtDeclarationWithBody && !declaration.hasValidExternalBody(bindingContext)) { diagnosticHolder.report(ErrorsJs.WRONG_BODY_OF_EXTERNAL_DECLARATION.on(declaration.bodyExpression!!)) } else if (declaration is KtDeclarationWithInitializer && declaration.initializer?.isDefinedExternallyExpression(bindingContext) == false ) { diagnosticHolder.report(ErrorsJs.WRONG_INITIALIZER_OF_EXTERNAL_DECLARATION.on(declaration.initializer!!)) } if (declaration is KtCallableDeclaration) { for (defaultValue in declaration.valueParameters.mapNotNull { it.defaultValue }) { if (!defaultValue.isDefinedExternallyExpression(bindingContext)) { diagnosticHolder.report(ErrorsJs.WRONG_DEFAULT_VALUE_FOR_EXTERNAL_FUN_PARAMETER.on(defaultValue)) } } } } private fun checkDelegation(declaration: KtDeclaration, descriptor: DeclarationDescriptor, diagnosticHolder: DiagnosticSink) { if (descriptor !is MemberDescriptor || !DescriptorUtils.isEffectivelyExternal(descriptor)) return if (declaration is KtClassOrObject) { for (superTypeEntry in declaration.superTypeListEntries) { when (superTypeEntry) { is KtSuperTypeCallEntry -> { diagnosticHolder.report(ErrorsJs.EXTERNAL_DELEGATED_CONSTRUCTOR_CALL.on(superTypeEntry.valueArgumentList!!)) } is KtDelegatedSuperTypeEntry -> { diagnosticHolder.report(ErrorsJs.EXTERNAL_DELEGATION.on(superTypeEntry)) } } } } else if (declaration is KtSecondaryConstructor) { val delegationCall = declaration.getDelegationCall() if (!delegationCall.isImplicit) { diagnosticHolder.report(ErrorsJs.EXTERNAL_DELEGATED_CONSTRUCTOR_CALL.on(delegationCall)) } } else if (declaration is KtProperty && descriptor !is PropertyAccessorDescriptor) { declaration.delegate?.let { delegate -> diagnosticHolder.report(ErrorsJs.EXTERNAL_DELEGATION.on(delegate)) } } } private fun checkAnonymousInitializer(declaration: KtDeclaration, diagnosticHolder: DiagnosticSink) { if (declaration !is KtClassOrObject) return for (anonymousInitializer in declaration.getAnonymousInitializers()) { diagnosticHolder.report(ErrorsJs.EXTERNAL_ANONYMOUS_INITIALIZER.on(anonymousInitializer)) } } private fun checkEnumEntry(declaration: KtDeclaration, diagnosticHolder: DiagnosticSink) { if (declaration !is KtEnumEntry) return declaration.getBody()?.let { diagnosticHolder.report(ErrorsJs.EXTERNAL_ENUM_ENTRY_WITH_BODY.on(it)) } } private fun checkConstructorPropertyParam( declaration: KtDeclaration, descriptor: DeclarationDescriptor, diagnosticHolder: DiagnosticSink ) { if (descriptor !is PropertyDescriptor || declaration !is KtParameter) return val containingClass = descriptor.containingDeclaration as ClassDescriptor if (containingClass.isData || DescriptorUtils.isAnnotationClass(containingClass)) return diagnosticHolder.report(ErrorsJs.EXTERNAL_CLASS_CONSTRUCTOR_PROPERTY_PARAMETER.on(declaration)) } private fun isDirectlyExternal(declaration: KtDeclaration, descriptor: DeclarationDescriptor): Boolean { if (declaration is KtProperty && descriptor is PropertyAccessorDescriptor) return false return declaration.hasModifier(KtTokens.EXTERNAL_KEYWORD) || AnnotationsUtils.hasAnnotation(descriptor, PredefinedAnnotation.NATIVE) } private fun isPrivateMemberOfExternalClass(descriptor: DeclarationDescriptor): Boolean { if (descriptor is PropertyAccessorDescriptor && descriptor.visibility == descriptor.correspondingProperty.visibility) return false if (descriptor !is MemberDescriptor || descriptor.visibility != Visibilities.PRIVATE) return false val containingDeclaration = descriptor.containingDeclaration as? ClassDescriptor ?: return false return AnnotationsUtils.isNativeObject(containingDeclaration) } private fun CallableMemberDescriptor.isNonAbstractMemberOfInterface() = modality != Modality.ABSTRACT && DescriptorUtils.isInterface(containingDeclaration) && this !is PropertyAccessorDescriptor private fun CallableMemberDescriptor.isNullableProperty() = this is PropertyDescriptor && TypeUtils.isNullableType(type) private fun KtDeclarationWithBody.hasValidExternalBody(bindingContext: BindingContext): Boolean { if (!hasBody()) return true val body = bodyExpression!! return if (!hasBlockBody()) { body.isDefinedExternallyExpression(bindingContext) } else if (body is KtBlockExpression) { val statement = body.statements.singleOrNull() ?: return false statement.isDefinedExternallyExpression(bindingContext) } else { false } } private fun KtExpression.isDefinedExternallyExpression(bindingContext: BindingContext): Boolean { val descriptor = getResolvedCall(bindingContext)?.resultingDescriptor as? PropertyDescriptor ?: return false val container = descriptor.containingDeclaration as? PackageFragmentDescriptor ?: return false return DEFINED_EXTENRALLY_PROPERTY_NAMES.any { container.fqNameUnsafe == it.parent() && descriptor.name == it.shortName() } } }
apache-2.0
b048b15109c86d00397ab0fc75be65a9
49.683486
138
0.708842
5.488823
false
false
false
false
Leifzhang/AndroidRouter
kspCompiler/src/main/java/com/kronos/ksp/compiler/Const.kt
2
1014
package com.kronos.ksp.compiler object Const { const val KEY_MODULE_NAME = "ROUTER_MODULE_NAME" const val DEFAULT_APP_MODULE = "main_app" // System interface const val ACTIVITY = "android.app.Activity" const val FRAGMENT = "android.app.Fragment" const val FRAGMENT_V4 = "android.support.v4.app.Fragment" const val SERVICE = "android.app.Service" const val PARCELABLE = "android.os.Parcelable" const val RUNNABLE = "com.kronos.router.RouterCallback" const val INTERCEPTOR_CLASS = "com.kronos.router.interceptor.Interceptor" // Java type private const val LANG = "java.lang" const val BYTE = "$LANG.Byte" const val SHORT = "$LANG.Short" const val INTEGER = "$LANG.Integer" const val LONG = "$LANG.Long" const val FLOAT = "$LANG.Float" const val DOUBLE = "$LANG.Double" const val BOOLEAN = "$LANG.Boolean" const val CHAR = "$LANG.Character" const val STRING = "$LANG.String" const val SERIALIZABLE = "java.io.Serializable" }
mit
80d1b8010ade6d727e224b2f311f3b65
32.833333
77
0.68146
3.70073
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/inspections/AddKotlinLibQuickFix.kt
2
6895
// 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.inspections import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.DependencyScope import com.intellij.openapi.roots.ExternalLibraryDescriptor import com.intellij.openapi.roots.ProjectRootManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinJvmBundle import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout import org.jetbrains.kotlin.idea.configuration.findApplicableConfigurator import org.jetbrains.kotlin.idea.facet.getRuntimeLibraryVersion import org.jetbrains.kotlin.idea.projectConfiguration.LibraryJarDescriptor import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory import org.jetbrains.kotlin.idea.util.createIntentionForFirstParentOfType import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtImportDirective class AddReflectionQuickFix(element: KtElement) : AddKotlinLibQuickFix(element, LibraryJarDescriptor.REFLECT_JAR, DependencyScope.COMPILE) { override fun getText() = KotlinJvmBundle.message("classpath.add.reflection") override fun getFamilyName() = text override fun getLibraryDescriptor(module: Module) = MavenExternalLibraryDescriptor.create( "org.jetbrains.kotlin", "kotlin-reflect", getRuntimeLibraryVersion(module) ?: KotlinPluginLayout.standaloneCompilerVersion ) companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic) = diagnostic.createIntentionForFirstParentOfType(::AddReflectionQuickFix) } } class AddScriptRuntimeQuickFix(element: KtElement) : AddKotlinLibQuickFix( element, LibraryJarDescriptor.SCRIPT_RUNTIME_JAR, DependencyScope.COMPILE ) { override fun getText() = KotlinJvmBundle.message("classpath.add.script.runtime") override fun getFamilyName() = text override fun getLibraryDescriptor(module: Module) = MavenExternalLibraryDescriptor.create( "org.jetbrains.kotlin", "kotlin-script-runtime", getRuntimeLibraryVersion(module) ?: KotlinPluginLayout.standaloneCompilerVersion ) companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtElement>? = diagnostic.createIntentionForFirstParentOfType(::AddScriptRuntimeQuickFix) } } class AddTestLibQuickFix(element: KtElement) : AddKotlinLibQuickFix(element, LibraryJarDescriptor.TEST_JAR, DependencyScope.TEST) { override fun getText() = KotlinJvmBundle.message("classpath.add.kotlin.test") override fun getFamilyName() = text override fun getLibraryDescriptor(module: Module) = MavenExternalLibraryDescriptor.create( "org.jetbrains.kotlin", "kotlin-test", getRuntimeLibraryVersion(module) ?: KotlinPluginLayout.standaloneCompilerVersion ) companion object : KotlinSingleIntentionActionFactory() { private val KOTLIN_TEST_UNRESOLVED = setOf( "Asserter", "assertFailsWith", "currentStackTrace", "failsWith", "todo", "assertEquals", "assertFails", "assertNot", "assertNotEquals", "assertNotNull", "assertNull", "assertTrue", "expect", "fail", "fails" ) override fun createAction(diagnostic: Diagnostic): IntentionAction? { val unresolvedReference = Errors.UNRESOLVED_REFERENCE.cast(diagnostic) if (PsiTreeUtil.getParentOfType(diagnostic.psiElement, KtImportDirective::class.java) != null) return null val unresolvedText = unresolvedReference.a.text if (unresolvedText in KOTLIN_TEST_UNRESOLVED) { val ktFile = (diagnostic.psiElement.containingFile as? KtFile) ?: return null val exactImportFqName = FqName("kotlin.test.$unresolvedText") val kotlinTestAllUnder = FqName("kotlin.test") var hasExactImport = false var hasKotlinTestAllUnder = false for (importDirective in ktFile.importDirectives.filter { it.text.contains("kotlin.test.") }) { if (importDirective.importedFqName == exactImportFqName) { hasExactImport = true break } if (importDirective.importedFqName == kotlinTestAllUnder && importDirective.isAllUnder) { hasKotlinTestAllUnder = true break } } if (hasExactImport || hasKotlinTestAllUnder) { return diagnostic.createIntentionForFirstParentOfType(::AddTestLibQuickFix) } } return null } } } abstract class AddKotlinLibQuickFix( element: KtElement, private val libraryJarDescriptor: LibraryJarDescriptor, private val scope: DependencyScope ) : KotlinQuickFixAction<KtElement>(element) { protected abstract fun getLibraryDescriptor(module: Module): MavenExternalLibraryDescriptor class MavenExternalLibraryDescriptor private constructor( groupId: String, artifactId: String, version: String ): ExternalLibraryDescriptor(groupId, artifactId, version, version) { companion object { fun create(groupId: String, artifactId: String, version: IdeKotlinVersion): MavenExternalLibraryDescriptor { val artifactVersion = version.artifactVersion return MavenExternalLibraryDescriptor(groupId, artifactId, artifactVersion) } } override fun getLibraryClassesRoots(): List<String> = emptyList() } override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val module = ProjectRootManager.getInstance(project).fileIndex.getModuleForFile(element.containingFile.virtualFile) ?: return val configurator = findApplicableConfigurator(module) configurator.addLibraryDependency(module, element, getLibraryDescriptor(module), libraryJarDescriptor, scope) } override fun getElementToMakeWritable(currentFile: PsiFile): PsiElement? = null }
apache-2.0
d711c06394137b7c8d96023b9577e32b
44.368421
158
0.732705
5.547064
false
true
false
false
siosio/intellij-community
platform/vcs-impl/src/com/intellij/util/ui/JButtonAction.kt
1
2490
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.ui import com.intellij.openapi.actionSystem.ActionToolbar import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.Presentation import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.actionSystem.ex.CustomComponentAction import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.util.NlsActions.ActionDescription import com.intellij.openapi.util.NlsActions.ActionText import javax.swing.Icon import javax.swing.JButton import javax.swing.JComponent abstract class JButtonAction(text: @ActionText String?, @ActionDescription description: String? = null, icon: Icon? = null) : DumbAwareAction(text, description, icon), CustomComponentAction { override fun createCustomComponent(presentation: Presentation, place: String): JComponent { val button = createButton() button.addActionListener { val dataContext = ActionToolbar.getDataContextFor(button) val action = this@JButtonAction val event = AnActionEvent.createFromInputEvent(null, place, presentation, dataContext) if (ActionUtil.lastUpdateAndCheckDumb(action, event, true)) { ActionUtil.performActionDumbAwareWithCallbacks(action, event) } } updateButtonFromPresentation(button, presentation) return button } protected open fun createButton(): JButton = JButton().configureForToolbar() protected fun JButton.configureForToolbar(): JButton = apply { isFocusable = false font = JBUI.Fonts.toolbarFont() putClientProperty("ActionToolbar.smallVariant", true) } protected fun updateButtonFromPresentation(e: AnActionEvent) { val button = UIUtil.findComponentOfType(e.presentation.getClientProperty(CustomComponentAction.COMPONENT_KEY), JButton::class.java) if (button != null) updateButtonFromPresentation(button, e.presentation) } protected open fun updateButtonFromPresentation(button: JButton, presentation: Presentation) { button.isEnabled = presentation.isEnabled button.isVisible = presentation.isVisible button.text = presentation.getText(true) button.icon = presentation.icon button.mnemonic = presentation.mnemonic button.displayedMnemonicIndex = presentation.displayedMnemonicIndex button.toolTipText = presentation.description } }
apache-2.0
b737ba30063ac695cbe4aefce00a4dad
41.948276
140
0.786345
5.071283
false
false
false
false
kivensolo/UiUsingListView
library/network/src/main/java/com/zeke/reactivehttp/base/BaseReactiveViewModel.kt
1
1754
package com.zeke.reactivehttp.base import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.zeke.reactivehttp.viewmodel.* import kotlinx.coroutines.CoroutineScope /** * @Author: leavesC * @Date: 2020/7/24 0:43 * @Desc: * Hold UI Data(内部持有LiveData). * ViewModel中持有 数据源对象(Repository的概念),并通过它执行具体逻辑. * * 用户数据的承载体和处理者,包含了多个和网络请求事件相关的 LiveData 用于驱动界面层的 UI 变化, * 和 BaseReactiveActivity 之间依靠 IViewModelActionEvent 接口来联系。 */ open class BaseReactiveViewModel : ViewModel(), IViewModelActionEvent { val TAG: String = javaClass.simpleName override val lifecycleSupportedScope: CoroutineScope get() = viewModelScope override val showLoadingEventLD = MutableLiveData<ShowLoadingEvent>() override val dismissLoadingEventLD = MutableLiveData<DismissLoadingEvent>() override val showToastEventLD = MutableLiveData<ShowToastEvent>() override val finishViewEventLD = MutableLiveData<FinishViewEvent>() } open class BaseReactiveAndroidViewModel(application: Application) : AndroidViewModel(application), IViewModelActionEvent { override val lifecycleSupportedScope: CoroutineScope get() = viewModelScope override val showLoadingEventLD = MutableLiveData<ShowLoadingEvent>() override val dismissLoadingEventLD = MutableLiveData<DismissLoadingEvent>() override val showToastEventLD = MutableLiveData<ShowToastEvent>() override val finishViewEventLD = MutableLiveData<FinishViewEvent>() }
gpl-2.0
96692e483462744385a7660b16ae24b6
29.826923
79
0.794632
4.512676
false
false
false
false
BijoySingh/Quick-Note-Android
base/src/main/java/com/maubis/scarlet/base/support/database/MigrationUtils.kt
1
3263
package com.maubis.scarlet.base.support.database import android.content.Context import com.google.gson.Gson import com.maubis.scarlet.base.config.ApplicationBase import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppPreferences import com.maubis.scarlet.base.config.CoreConfig.Companion.notesDb import com.maubis.scarlet.base.core.note.NoteMeta import com.maubis.scarlet.base.core.note.Reminder import com.maubis.scarlet.base.core.note.getReminder import com.maubis.scarlet.base.note.reminders.ReminderJob import com.maubis.scarlet.base.note.saveWithoutSync import com.maubis.scarlet.base.settings.sheet.sUIUseGridView import com.maubis.scarlet.base.support.ui.Theme import com.maubis.scarlet.base.support.ui.sThemeLabel import com.maubis.scarlet.base.support.utils.getLastUsedAppVersionCode import com.maubis.scarlet.base.support.utils.maybeThrow import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import java.io.File import java.util.* const val KEY_MIGRATE_DEFAULT_VALUES = "KEY_MIGRATE_DEFAULT_VALUES" const val KEY_MIGRATE_REMINDERS = "KEY_MIGRATE_REMINDERS" const val KEY_MIGRATE_IMAGES = "KEY_MIGRATE_IMAGES" const val KEY_MIGRATE_TO_GDRIVE_DATABASE = "KEY_MIGRATE_TO_GDRIVE_DATABASE_v2" class Migrator(val context: Context) { fun start() { runTask(key = KEY_MIGRATE_REMINDERS) { val notes = notesDb.getAll() for (note in notes) { val legacyReminder = note.getReminder() if (legacyReminder !== null) { val reminder = Reminder(0, legacyReminder.alarmTimestamp, legacyReminder.interval) if (legacyReminder.alarmTimestamp < Calendar.getInstance().timeInMillis) { continue } val meta = NoteMeta() val uid = ReminderJob.scheduleJob(note.uuid, reminder) reminder.uid = uid if (uid == -1) { continue } meta.reminderV2 = reminder note.meta = Gson().toJson(meta) note.saveWithoutSync(context) } } } runTask(KEY_MIGRATE_IMAGES) { File(context.cacheDir, "images").renameTo(File(context.filesDir, "images")) } runTaskIf( getLastUsedAppVersionCode() == 0, KEY_MIGRATE_DEFAULT_VALUES) { sThemeLabel = Theme.DARK.name sUIUseGridView = true } runTask(KEY_MIGRATE_TO_GDRIVE_DATABASE) { GlobalScope.launch { val remoteDatabaseState = ApplicationBase.instance.remoteDatabaseState() ApplicationBase.instance.notesDatabase().getAll().forEach { remoteDatabaseState.notifyInsert(it) {} } ApplicationBase.instance.tagsDatabase().getAll().forEach { remoteDatabaseState.notifyInsert(it) {} } ApplicationBase.instance.foldersDatabase().getAll().forEach { remoteDatabaseState.notifyInsert(it) {} } } } } private fun runTask(key: String, task: () -> Unit) { if (sAppPreferences.get(key, false)) { return } try { task() } catch (exception: Exception) { maybeThrow(exception) } sAppPreferences.put(key, true) } private fun runTaskIf(condition: Boolean, key: String, task: () -> Unit) { if (!condition) { return } runTask(key, task) } }
gpl-3.0
2806d3e372640df1c7d4dc62a1fdb72c
31.969697
92
0.690775
3.879905
false
false
false
false
vovagrechka/fucking-everything
attic/pizdatron/src/fekjs/pizdatron/pizdatron.kt
1
3604
package fekjs.pizdatron import fekjs.* import fekjs.node.* import org.w3c.dom.events.Event @JsName("(require('electron').app)") external object app { fun on(event: String, block: Function<*>) fun quit() } fun app.onReady(block: () -> Unit) = on("ready", block) fun app.onActivate(block: () -> Unit) = on("activate", block) fun app.onWindowAllClosed(block: () -> Unit) = on("window-all-closed", block) @JsName("(require('electron').BrowserWindow)") external class BrowserWindow(opts: BrowserWindowOpts? = null) { val webContents: WebContents fun loadURL(url: String) fun maximize() fun on(eventName: String, block: Function<*>) } fun BrowserWindow.onClosed(block: () -> Unit) = on("closed", block) fun BrowserWindow.onPageTitleUpdated(block: (e: Event, title: String) -> Unit) = on("page-title-updated", block) external interface WebContents { fun openDevTools() fun send(channel: String, payload: Any?) } class BrowserWindowOpts( val width: Int = 800, val height: Int = 600, val webPreferences: WebPreferences? = null ) class WebPreferences( val zoomFactor: Double = 1.0 ) @JsName("(require('electron').ipcMain)") external object ipcMain { fun on(channel: String, block: (event: IPCMainEvent, payload: Any?) -> Unit) } external interface IPCMainEvent { val sender: WebContents var returnValue: Any? } @JsName("(require('electron').ipcRenderer)") external object ipcRenderer { fun on(channel: String, block: (event: IPCRenderEvent, payload: Any?) -> Unit) fun sendSync(channel: String, payload: Any?) fun send(channel: String, payload: Any?) } external interface IPCRenderEvent class PizdatronRenderProcess { init { console.log("got sync", ipcRenderer.sendSync("synchronous-message", "ping")) ipcRenderer.on("asynchronous-reply") {event: IPCRenderEvent, payload: Any? -> console.log("got async", payload) } ipcRenderer.send("asynchronous-message", "ping") } } class PizdatronMainProcess { var win: BrowserWindow? = null init { app.onReady { createWindow() ipcMain.on("asynchronous-message") {event: IPCMainEvent, payload: Any? -> console.log("got async", payload) event.sender.send("asynchronous-reply", "pong") } ipcMain.on("synchronous-message") {event: IPCMainEvent, payload: Any? -> console.log("got sync", payload) event.returnValue = "pong" } } app.onWindowAllClosed { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform != "darwin") { app.quit() } } app.onActivate { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (win == null) { createWindow() } } } fun createWindow() { win = BrowserWindow(BrowserWindowOpts(webPreferences = WebPreferences(zoomFactor = 1.25)))-{o-> o.maximize() o.loadURL(url.format(URLObject( pathname = path.join(__dirname, "fekjs/pizdatron/pizdaindex.html"), protocol = "file:", slashes = true ))) o.webContents.openDevTools() o.onClosed { win = null } } } }
apache-2.0
cd27eb1068dd48bbf62cdcebfbf78af6
23.684932
112
0.600999
3.943107
false
false
false
false
JetBrains/kotlin-native
backend.native/tests/framework/multiple/framework2/second.kt
4
637
/* * Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ @file:Suppress("UNUSED") package multiple interface I2 { fun getFortyTwo(): Int } fun getFortyTwoFrom(i2: I2): Int = i2.getFortyTwo() fun getI2() = object : I2 { override fun getFortyTwo(): Int = 42 } class C fun isUnit(obj: Any?): Boolean = (obj === Unit) /* // Disabled for now to avoid depending on platform libs. fun getAnonymousObject() = object : platform.darwin.NSObject() {} class NamedObject : platform.darwin.NSObject() fun getNamedObject() = NamedObject() */
apache-2.0
33832c0b9093f1b41bd7dfb77cd20eff
21
101
0.697017
3.25
false
false
false
false
jwren/intellij-community
platform/core-api/src/com/intellij/openapi/application/coroutines.kt
1
4586
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:ApiStatus.Experimental package com.intellij.openapi.application import com.intellij.openapi.project.Project import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.asContextElement import org.jetbrains.annotations.ApiStatus import kotlin.coroutines.CoroutineContext /** * Suspends until it's possible to obtain the read lock and then * runs the [action] holding the lock **without** preventing write actions. * See [constrainedReadAction] for semantic details. * * @see readActionBlocking */ suspend fun <T> readAction(action: () -> T): T { return constrainedReadAction(action = action) } /** * Suspends until it's possible to obtain the read lock in smart mode and then * runs the [action] holding the lock **without** preventing write actions. * See [constrainedReadAction] for semantic details. * * @see smartReadActionBlocking */ suspend fun <T> smartReadAction(project: Project, action: () -> T): T { return constrainedReadAction(ReadConstraint.inSmartMode(project), action = action) } /** * Runs given [action] under [read lock][com.intellij.openapi.application.Application.runReadAction] * **without** preventing write actions. * * The function suspends if at the moment of calling it's not possible to acquire the read lock, * or if [constraints] are not [satisfied][ReadConstraint.isSatisfied]. * If the write action happens while the [action] is running, then the [action] is canceled, * and the function suspends until its possible to acquire the read lock, and then the [action] is tried again. * * Since the [action] might me executed several times, it must be idempotent. * The function returns when given [action] was completed fully. * To support cancellation, the [action] must regularly invoke [com.intellij.openapi.progress.ProgressManager.checkCanceled]. * * @see constrainedReadActionBlocking */ suspend fun <T> constrainedReadAction(vararg constraints: ReadConstraint, action: () -> T): T { return readActionSupport().executeReadAction(constraints.toList(), blocking = false, action) } /** * Suspends until it's possible to obtain the read lock and then * runs the [action] holding the lock and **preventing** write actions. * See [constrainedReadActionBlocking] for semantic details. * * @see readAction */ suspend fun <T> readActionBlocking(action: () -> T): T { return constrainedReadActionBlocking(action = action) } /** * Suspends until it's possible to obtain the read lock in smart mode and then * runs the [action] holding the lock and **preventing** write actions. * See [constrainedReadActionBlocking] for semantic details. * * @see smartReadAction */ suspend fun <T> smartReadActionBlocking(project: Project, action: () -> T): T { return constrainedReadActionBlocking(ReadConstraint.inSmartMode(project), action = action) } /** * Runs given [action] under [read lock][com.intellij.openapi.application.Application.runReadAction] * **preventing** write actions. * * The function suspends if at the moment of calling it's not possible to acquire the read lock, * or if [constraints] are not [satisfied][ReadConstraint.isSatisfied]. * If the write action happens while the [action] is running, then the [action] is **not** canceled, * meaning the [action] will block pending write actions until finished. * * The function returns when given [action] was completed fully. * To support cancellation, the [action] must regularly invoke [com.intellij.openapi.progress.ProgressManager.checkCanceled]. * * @see constrainedReadAction */ suspend fun <T> constrainedReadActionBlocking(vararg constraints: ReadConstraint, action: () -> T): T { return readActionSupport().executeReadAction(constraints.toList(), blocking = true, action) } private fun readActionSupport() = ApplicationManager.getApplication().getService(ReadActionSupport::class.java) /** * The code [without][ModalityState.any] context modality state must only perform pure UI operations, * it must not access any PSI, VFS, project model, or indexes. */ fun ModalityState.asContextElement(): CoroutineContext = coroutineSupport().asContextElement(this) /** * @return UI dispatcher which dispatches within the [context modality state][asContextElement]. */ @Suppress("unused") // unused receiver val Dispatchers.EDT: CoroutineContext get() = coroutineSupport().edtDispatcher() private fun coroutineSupport() = ApplicationManager.getApplication().getService(CoroutineSupport::class.java)
apache-2.0
dad0ed642cf028d38b992f9866219768
41.859813
125
0.762102
4.443798
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddIsToWhenConditionFix.kt
3
1625
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtWhenConditionWithExpression import org.jetbrains.kotlin.psi.psiUtil.endOffset class AddIsToWhenConditionFix( expression: KtWhenConditionWithExpression, private val referenceText: String ) : KotlinQuickFixAction<KtWhenConditionWithExpression>(expression) { override fun getText(): String = KotlinBundle.message("fix.add.is.to.when", referenceText) override fun getFamilyName(): String = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val expression = element ?: return val replaced = expression.replaced(KtPsiFactory(expression).createWhenCondition("is ${expression.text}")) editor?.caretModel?.moveToOffset(replaced.endOffset) } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtWhenConditionWithExpression>? { val element = diagnostic.psiElement.parent as? KtWhenConditionWithExpression ?: return null return AddIsToWhenConditionFix(element, element.text) } } }
apache-2.0
da9c99802878fc3cbb885f321fce92de
45.457143
158
0.777846
4.909366
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/structuralsearch/countFilter/maxWhenConditionWithExpression.kt
3
374
fun foo(): Int { fun f() {} <warning descr="SSR">when (1) { in 1..10 -> f() in 11..20 -> f() }</warning> val x1 = when { else -> 1 } val x2 = <warning descr="SSR">when { 1 < 2 -> 3 else -> 1 }</warning> val x3 = when { 1 < 3 -> 1 2 > 1 -> 4 else -> 1 } return x1 + x2 + x3 }
apache-2.0
32aa32a85bc109b922bd5cdd635790a4
14.625
40
0.368984
3.196581
false
false
false
false
spinnaker/clouddriver
clouddriver-sql/src/main/kotlin/com/netflix/spinnaker/clouddriver/sql/SqlTaskRepository.kt
1
11366
/* * 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.clouddriver.sql import com.fasterxml.jackson.databind.ObjectMapper import com.netflix.spinnaker.clouddriver.core.ClouddriverHostname import com.netflix.spinnaker.clouddriver.data.task.DefaultTaskStatus import com.netflix.spinnaker.clouddriver.data.task.Task import com.netflix.spinnaker.clouddriver.data.task.TaskRepository import com.netflix.spinnaker.clouddriver.data.task.TaskState import com.netflix.spinnaker.clouddriver.data.task.TaskState.FAILED import com.netflix.spinnaker.clouddriver.data.task.TaskState.STARTED import com.netflix.spinnaker.kork.sql.routing.withPool import de.huxhorn.sulky.ulid.ULID import java.time.Clock import org.jooq.Condition import org.jooq.DSLContext import org.jooq.Record import org.jooq.Select import org.jooq.impl.DSL import org.jooq.impl.DSL.field import org.jooq.impl.DSL.sql import org.slf4j.LoggerFactory class SqlTaskRepository( private val jooq: DSLContext, private val mapper: ObjectMapper, private val clock: Clock, private val poolName: String ) : TaskRepository { private val log = LoggerFactory.getLogger(javaClass) init { log.info("Using ${javaClass.simpleName} with pool $poolName") } override fun create(phase: String, status: String): Task { return create(phase, status, ulid.nextULID()) } override fun create(phase: String, status: String, clientRequestId: String): Task { var task = SqlTask(ulid.nextULID(), ClouddriverHostname.ID, clientRequestId, clock.millis(), mutableSetOf(), this) val historyId = ulid.nextULID() withPool(poolName) { jooq.transactional { ctx -> val existingTask = getByClientRequestId(clientRequestId) if (existingTask != null) { task = existingTask as SqlTask addToHistory(ctx, historyId, existingTask.id, FAILED, phase, "Duplicate of $clientRequestId") } else { val pairs = mapOf( field("id") to task.id, field("owner_id") to task.ownerId, field("request_id") to task.requestId, field("created_at") to task.startTimeMs, field("saga_ids") to mapper.writeValueAsString(task.sagaIds) ) ctx.insertInto(tasksTable, *pairs.keys.toTypedArray()).values(*pairs.values.toTypedArray()).execute() addToHistory(ctx, historyId, task.id, STARTED, phase, status) } } // TODO(rz): So janky and bad. task.refresh(true) } return task } fun updateSagaIds(task: Task) { return withPool(poolName) { jooq.transactional { ctx -> ctx.update(tasksTable) .set(field("saga_ids"), mapper.writeValueAsString(task.sagaIds)) .where(field("id").eq(task.id)) .execute() } } } override fun get(id: String): Task? { return retrieveInternal(id) } override fun getByClientRequestId(clientRequestId: String): Task? { return withPool(poolName) { jooq.read { it.select(field("id")) .from(tasksTable) .where(field("request_id").eq(clientRequestId)) .fetchOne("id", String::class.java) ?.let { taskId -> retrieveInternal(taskId) } } } } override fun list(): MutableList<Task> { return withPool(poolName) { jooq.read { runningTaskIds(it, false).let { taskIds -> retrieveInternal(field("id").`in`(*taskIds), field("task_id").`in`(*taskIds)).toMutableList() } } } } override fun listByThisInstance(): MutableList<Task> { return withPool(poolName) { jooq.read { runningTaskIds(it, true).let { taskIds -> retrieveInternal(field("id").`in`(*taskIds), field("task_id").`in`(*taskIds)).toMutableList() } } } } internal fun addResultObjects(results: List<Any>, task: Task) { val resultIdPairs = results.map { ulid.nextULID() to it }.toMap() withPool(poolName) { jooq.transactional { ctx -> ctx.select(taskStatesFields) .from(taskStatesTable) .where(field("task_id").eq(task.id)) .orderBy(field("created_at").asc()) .limit(1) .fetchTaskStatus() ?.run { ensureUpdateable() } resultIdPairs.forEach { result -> ctx.insertInto(taskResultsTable, listOf(field("id"), field("task_id"), field("body"))) .values( listOf( result.key, task.id, mapper.writeValueAsString(result.value) ) ) .execute() } } } } internal fun updateCurrentStatus(task: Task, phase: String, status: String) { val historyId = ulid.nextULID() withPool(poolName) { jooq.transactional { ctx -> val state = selectLatestState(ctx, task.id) addToHistory(ctx, historyId, task.id, state?.state ?: STARTED, phase, status.take(MAX_STATUS_LENGTH)) } } } private fun addToHistory(ctx: DSLContext, id: String, taskId: String, state: TaskState, phase: String, status: String) { ctx .insertInto( taskStatesTable, listOf(field("id"), field("task_id"), field("created_at"), field("state"), field("phase"), field("status")) ) .values(listOf(id, taskId, clock.millis(), state.toString(), phase, status)) .execute() } internal fun updateState(task: Task, state: TaskState) { val historyId = ulid.nextULID() withPool(poolName) { jooq.transactional { ctx -> selectLatestState(ctx, task.id)?.let { addToHistory(ctx, historyId, task.id, state, it.phase, it.status) } } } } internal fun retrieveInternal(taskId: String): Task? { return retrieveInternal(field("id").eq(taskId), field("task_id").eq(taskId)).firstOrNull() } private fun retrieveInternal(condition: Condition, relationshipCondition: Condition? = null): Collection<Task> { val tasks = mutableSetOf<Task>() // TODO: AWS Aurora enforces REPEATABLE_READ on replicas. Kork's dataSourceConnectionProvider sets READ_COMMITTED // on every connection acquire - need to change this so running on !aurora will behave consistently. // REPEATABLE_READ is correct here. withPool(poolName) { jooq.transactional { ctx -> /** * (select id as task_id, owner_id, request_id, created_at, saga_ids, null as body, null as state, null as phase, null as status from tasks_copy where id = '01D2H4H50VTF7CGBMP0D6HTGTF') * UNION ALL * (select task_id, null as owner_id, null as request_id, null as created_at, null as saga_ids, null as body, state, phase, status from task_states_copy where task_id = '01D2H4H50VTF7CGBMP0D6HTGTF') * UNION ALL * (select task_id, null as owner_id, null as request_id, null as created_at, null as saga_ids, body, null as state, null as phase, null as status from task_results_copy where task_id = '01D2H4H50VTF7CGBMP0D6HTGTF') */ tasks.addAll( ctx .select( field("id").`as`("task_id"), field("owner_id"), field("request_id"), field("created_at"), field("saga_ids"), field(sql("null")).`as`("body"), field(sql("null")).`as`("state"), field(sql("null")).`as`("phase"), field(sql("null")).`as`("status") ) .from(tasksTable) .where(condition) .unionAll( ctx .select( field("task_id"), field(sql("null")).`as`("owner_id"), field(sql("null")).`as`("request_id"), field(sql("null")).`as`("created_at"), field(sql("null")).`as`("saga_ids"), field(sql("null")).`as`("body"), field("state"), field("phase"), field("status") ) .from(taskStatesTable) .where(relationshipCondition ?: condition) ) .unionAll( ctx .select( field("task_id"), field(sql("null")).`as`("owner_id"), field(sql("null")).`as`("request_id"), field(sql("null")).`as`("created_at"), field(sql("null")).`as`("saga_ids"), field("body"), field(sql("null")).`as`("state"), field(sql("null")).`as`("phase"), field(sql("null")).`as`("status") ) .from(taskResultsTable) .where(relationshipCondition ?: condition) ) .fetchTasks() ) } } return tasks } private fun selectLatestState(ctx: DSLContext, taskId: String): DefaultTaskStatus? { return withPool(poolName) { ctx.select(taskStatesFields) .from(taskStatesTable) .where(field("task_id").eq(taskId)) .orderBy(field("created_at").desc()) .limit(1) .fetchTaskStatus() } } /** * Since task statuses are insert-only, we first need to find the most * recent status record for each task ID and the filter that result set * down to the ones that are running. */ private fun runningTaskIds(ctx: DSLContext, thisInstance: Boolean): Array<String> { return withPool(poolName) { val baseQuery = ctx.select(field("a.task_id")) .from(taskStatesTable.`as`("a")) .innerJoin( ctx.select(field("task_id"), DSL.max(field("created_at")).`as`("created")) .from(taskStatesTable) .groupBy(field("task_id")) .asTable("b") ).on(sql("a.task_id = b.task_id and a.created_at = b.created")) val select = if (thisInstance) { baseQuery .innerJoin(tasksTable.`as`("t")).on(sql("a.task_id = t.id")) .where( field("t.owner_id").eq(ClouddriverHostname.ID) .and(field("a.state").eq(TaskState.STARTED.toString())) ) } else { baseQuery.where(field("a.state").eq(TaskState.STARTED.toString())) } select .fetch("a.task_id", String::class.java) .toTypedArray() } } private fun Select<out Record>.fetchTasks() = TaskMapper(this@SqlTaskRepository, mapper).map(fetch().intoResultSet()) private fun Select<out Record>.fetchTaskStatuses() = TaskStatusMapper().map(fetch().intoResultSet()) private fun Select<out Record>.fetchTaskStatus() = fetchTaskStatuses().firstOrNull() companion object { private val ulid = ULID() private val MAX_STATUS_LENGTH = 10_000 } }
apache-2.0
e4bd4a4dbd06acac0bdeb5d4e41b9a2e
33.865031
224
0.600915
4.127088
false
false
false
false
h0tk3y/better-parse
src/commonMain/kotlin/com/github/h0tk3y/betterParse/combinators/Separated.kt
1
4862
package com.github.h0tk3y.betterParse.combinators import com.github.h0tk3y.betterParse.lexer.TokenMatchesSequence import com.github.h0tk3y.betterParse.parser.* @Suppress("UNCHECKED_CAST") public class SeparatedCombinator<T, S>( public val termParser: Parser<T>, public val separatorParser: Parser<S>, public val acceptZero: Boolean ) : Parser<Separated<T, S>> { override fun tryParse(tokens: TokenMatchesSequence, fromPosition: Int): ParseResult<Separated<T, S>> { val termMatches = mutableListOf<T>() val separatorMatches = mutableListOf<S>() val first = termParser.tryParse(tokens, fromPosition) return when (first) { is ErrorResult -> if (acceptZero) ParsedValue(Separated(emptyList(), emptyList()), fromPosition) else first is Parsed -> { termMatches.add(first.value) var nextPosition = first.nextPosition loop@ while (true) { val separator = separatorParser.tryParse(tokens, nextPosition) when (separator) { is ErrorResult -> break@loop is Parsed -> { val nextTerm = termParser.tryParse(tokens, separator.nextPosition) when (nextTerm) { is ErrorResult -> break@loop is Parsed -> { separatorMatches.add(separator.value) termMatches.add(nextTerm.value) nextPosition = nextTerm.nextPosition } } } } } ParsedValue(Separated(termMatches, separatorMatches), nextPosition) } } } } /** A list of [terms] separated by [separators], which is either empty (both `terms` and `separators`) or contains one * more term than there are separators. */ public class Separated<T, S>( public val terms: List<T>, public val separators: List<S> ) { init { require(terms.size == separators.size + 1 || terms.isEmpty() && separators.isEmpty()) } /** Returns the result of reducing [terms] and [separators] with [function], starting from the left and processing * current result (initially, `terms[0]`), `separators[i]` and `terms[i + 1]` at each step for `i` in `0 until * terms.size`. * @throws [NoSuchElementException] if [terms] are empty */ public fun reduce(function: (T, S, T) -> T): T { if (terms.isEmpty()) throw NoSuchElementException() var result = terms.first() for (i in separators.indices) result = function(result, separators[i], terms[i + 1]) return result } /** Returns the result of reducing [terms] and [separators] with [function], starting from the right and processing * `terms[i]`, `separators[i]` and current result (initially, `terms.last()`) at each step for `i` in `terms.size - 1 downTo 0`. * @throws [NoSuchElementException] if [terms] are empty */ public fun reduceRight(function: (T, S, T) -> T): T { if (terms.isEmpty()) throw NoSuchElementException() var result = terms.last() for (i in separators.indices.reversed()) result = function(terms[i], separators[i], result) return result } } /** Parses a chain of [term]s separated by [separator], also accepting no matches at all if [acceptZero] is true. */ public inline fun <reified T, reified S> separated( term: Parser<T>, separator: Parser<S>, acceptZero: Boolean = false ): Parser<Separated<T, S>> = SeparatedCombinator(term, separator, acceptZero) /** Parses a chain of [term]s separated by [separator], also accepting no matches at all if [acceptZero] is true, and returning * only matches of [term]. */ public inline fun <reified T, reified S> separatedTerms( term: Parser<T>, separator: Parser<S>, acceptZero: Boolean = false ): Parser<List<T>> = separated(term, separator, acceptZero) map { it.terms } /** Parses a chain of [term]s separated by [operator] and reduces the result with [Separated.reduce]. */ public inline fun <reified T, reified S> leftAssociative( term: Parser<T>, operator: Parser<S>, noinline transform: (T, S, T) -> T ): Parser<T> = separated(term, operator) map { it.reduce(transform) } /** Parses a chain of [term]s separated by [operator] and reduces the result with [Separated.reduceRight]. */ public inline fun <reified T, reified S> rightAssociative( term: Parser<T>, operator: Parser<S>, noinline transform: (T, S, T) -> T ): Parser<T> = separated(term, operator) map { it.reduceRight(transform) }
apache-2.0
99e62687fcffec5ad9b38befb5f9a79b
42.410714
132
0.605101
4.341071
false
false
false
false
mbenz95/lpCounter
app/src/main/kotlin/benzm/yugiohlifepointcounter/viewmodels/CustomSettingsViewModel.kt
1
2269
package benzm.yugiohlifepointcounter.viewmodels import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.databinding.BaseObservable import android.databinding.Bindable import android.databinding.Observable import android.databinding.ObservableField import android.os.Bundle import android.preference.PreferenceManager import android.view.View import android.widget.Button import android.widget.Toast import benzm.yugiohlifepointcounter.ARG_SETTINGS import benzm.yugiohlifepointcounter.BR import benzm.yugiohlifepointcounter.GameActivity2Player import models.Duration import models.InitialSettings import models.RoundType import java.io.Serializable class CustomSettingsViewModel(@Transient var context: Context, val initialSettings: InitialSettings): Serializable { val player1Name: ObservableField<String> = ObservableField(initialSettings.player1Name) val player1Lp: ObservableField<String> = ObservableField(initialSettings.player1Lp.toString()) val player1RoundTime: ObservableField<String> = ObservableField(initialSettings.roundDurationPlayer1.toString()) val player2Name: ObservableField<String?> = ObservableField(initialSettings.player2Name) val player2Lp: ObservableField<String?> = ObservableField(initialSettings.player2Lp.toString()) val player2RoundTime: ObservableField<String?> = ObservableField(initialSettings.roundDurationPlayer2.toString()) val numPlayers: ObservableField<String> = ObservableField(initialSettings.numPlayer.toString()) // as string because its stored that way in the spinner fun okButtonClicked(view: View) { val gameIntent = Intent(context, GameActivity2Player::class.java) //load initialSettings val settings = InitialSettings( numPlayers.get().toInt(), player1Name.get(), player1Lp.get().toInt(), player2Name.get(), player2Lp.get()?.toInt(), null, null, null, null, Duration.parse(player1RoundTime.get()), Duration.parse(player2RoundTime.get()!!), //todo remove !! null, null, RoundType.DUEL) gameIntent.putExtra(ARG_SETTINGS, settings) context.startActivity(gameIntent) } }
mit
05797e6064dd4aa54b9bf8c8e4ef922a
45.326531
155
0.769061
4.493069
false
false
false
false
hazuki0x0/YuzuBrowser
module/search/src/main/java/jp/hazuki/yuzubrowser/search/presentation/widget/SearchSimpleIconView.kt
1
4251
/* * Copyright (C) 2017-2019 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.search.presentation.widget import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color import android.graphics.ColorFilter import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import android.util.AttributeSet import android.util.TypedValue import android.view.Gravity import androidx.appcompat.widget.AppCompatTextView import androidx.core.graphics.BlendModeColorFilterCompat.createBlendModeColorFilterCompat import androidx.core.graphics.BlendModeCompat import jp.hazuki.yuzubrowser.core.utility.extensions.convertDpToPx import jp.hazuki.yuzubrowser.search.R import jp.hazuki.yuzubrowser.search.domain.getIdentityColor import jp.hazuki.yuzubrowser.search.domain.randomColor import jp.hazuki.yuzubrowser.search.model.provider.SearchUrl class SearchSimpleIconView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : AppCompatTextView(context, attrs, defStyleAttr) { init { gravity = Gravity.CENTER setBackgroundResource(R.drawable.oval_icon_background) val a = context.theme.obtainStyledAttributes(attrs, R.styleable.SearchSimpleIconView, 0, 0) val symbolSize = a.getFloat(R.styleable.SearchSimpleIconView_symbolSize, 14f) a.recycle() setTextSize(TypedValue.COMPLEX_UNIT_DIP, symbolSize) } fun setSearchUrl(searchUrl: SearchUrl?) { setBackgroundResource(R.drawable.oval_icon_background) if (searchUrl == null) { text = "" setIconColor(randomColor) return } if (searchUrl.color != 0) { setIconColor(searchUrl.color) } else { if (searchUrl.title.isNotEmpty()) { setIconColor(searchUrl.title.getIdentityColor()) } else { setIconColor(randomColor) } } text = if (searchUrl.title.isNotEmpty()) String(Character.toChars(searchUrl.title.codePointAt(0))) else "" } fun setFavicon(favicon: Bitmap) { text = "" val padding = context.convertDpToPx(3) background = PaddingDrawable(BitmapDrawable(resources, favicon), padding) } private fun setIconColor(color: Int) { background.colorFilter = createBlendModeColorFilterCompat(color, BlendModeCompat.SRC_ATOP) if (isColorLight(color)) { setTextColor(Color.BLACK) } else { setTextColor(Color.WHITE) } } private fun isColorLight(color: Int): Boolean { val lightness = (0.299 * Color.red(color) + 0.587 * Color.green(color) + 0.114 * Color.blue(color)) / 255 return lightness > 0.7 } private class PaddingDrawable( private val drawable: Drawable, private val padding: Int ) : Drawable() { override fun setBounds(left: Int, top: Int, right: Int, bottom: Int) { super.setBounds(left, top, right, bottom) drawable.setBounds(left + padding, top + padding, right - padding, bottom - padding) } override fun getIntrinsicWidth() = drawable.intrinsicWidth override fun getIntrinsicHeight() = drawable.intrinsicHeight override fun draw(canvas: Canvas) { drawable.draw(canvas) } override fun setAlpha(alpha: Int) { drawable.alpha = alpha } override fun getOpacity() = drawable.opacity override fun setColorFilter(colorFilter: ColorFilter?) { drawable.colorFilter = colorFilter } } }
apache-2.0
9ba3b16e8148286032367ce8c71cc553
33.282258
113
0.686191
4.484177
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/problem/httpws/service/auth/CookieLogin.kt
1
2703
package org.evomaster.core.problem.httpws.service.auth import org.evomaster.client.java.controller.api.dto.CookieLoginDto import org.evomaster.core.problem.rest.ContentType import org.evomaster.core.problem.rest.HttpVerb import java.net.URLEncoder /** * Created by arcuri82 on 24-Oct-19. */ class CookieLogin( /** * The id of the user */ val username: String, /** * The password of the user. * This must NOT be hashed. */ val password: String, /** * The name of the field in the body payload containing the username */ val usernameField: String, /** * The name of the field in the body payload containing the password */ val passwordField: String, /** * The URL of the endpoint, e.g., "/login" */ val loginEndpointUrl: String, /** * The HTTP verb used to send the data. * Usually a "POST". */ val httpVerb: HttpVerb, /** * The encoding type used to specify how the data is sent */ val contentType: ContentType ) { companion object { fun fromDto(dto: CookieLoginDto) = CookieLogin( dto.username, dto.password, dto.usernameField, dto.passwordField, dto.loginEndpointUrl, HttpVerb.valueOf(dto.httpVerb.toString()), ContentType.valueOf(dto.contentType.toString()) ) } private fun encoded(s: String) = URLEncoder.encode(s, "UTF-8") fun payload(): String { return when (contentType) { ContentType.X_WWW_FORM_URLENCODED -> "${encoded(usernameField)}=${encoded(username)}&${encoded(passwordField)}=${encoded(password)}" ContentType.JSON -> """ {"$usernameField": "$username", "$passwordField": "$password"} """.trimIndent() else -> throw IllegalStateException("Currently not supporting $contentType for auth") } } /** * @return whether the specified [loginEndpointUrl] is a complete url, i.e., start with http/https protocol */ fun isFullUrlSpecified() = loginEndpointUrl.startsWith("https://")|| loginEndpointUrl.startsWith("http://") /** * @return a complete URL based on [baseUrl] and [loginEndpointUrl] */ fun getUrl(baseUrl: String) : String{ if (isFullUrlSpecified()) return loginEndpointUrl return baseUrl.run { if (!endsWith("/")) "$this/" else this} + loginEndpointUrl.run { if (startsWith("/")) this.drop(1) else this } } }
lgpl-3.0
557be2bb25698089a798179cee5bdf9d
27.765957
139
0.578246
4.636364
false
false
false
false
fvoichick/ColoredPlayerNames
src/main/kotlin/org/sfinnqs/cpn/PlayerColors.kt
1
6884
/** * ColoredPlayerNames - A Bukkit plugin for changing name colors * Copyright (C) 2019 sfinnqs * * This file is part of ColoredPlayerNames. * * ColoredPlayerNames is free software; you can redistribute it and/or modify it * under the terms of version 3 of the GNU General Public License as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; if not, see <https://www.gnu.org/licenses>. */ package org.sfinnqs.cpn import org.bukkit.ChatColor import org.bukkit.ChatColor.RESET import org.bukkit.OfflinePlayer import org.bukkit.entity.Player import org.bukkit.scoreboard.Scoreboard import java.util.* import java.util.concurrent.ThreadLocalRandom import java.util.concurrent.atomic.AtomicReference class PlayerColors(private val config: CpnConfig, private val board: Scoreboard? = null) { private val playerColors = mutableMapOf<Player, ChatColor>() private val counts = EnumMap<ChatColor, Int>(ChatColor::class.java) private val lastColors = mutableMapOf<Player, ChatColor>() private val teamNames = mutableMapOf<String, UUID>() private val replacementsRef = AtomicReference<Map<String, String>>(emptyMap()) val replacements: Map<String, String> get() = replacementsRef.get() operator fun get(player: Player) = playerColors[player] operator fun set(player: Player, color: ChatColor?) { // Update counts val oldColor = if (color == null) playerColors.remove(player) else playerColors.put(player, color) if (oldColor != null) counts.merge(oldColor, -1, Int::plus) if (color != null) counts.merge(color, 1, Int::plus) // Update display name val displayName = getDisplayName(player) player.setDisplayName(displayName) player.setPlayerListName(displayName) // Update replacements val newReplacements = playerColors.keys.associate { it.name to getDisplayName(it) } replacementsRef.set(newReplacements) // Update lastColors if (color != null) lastColors[player] = color val name = player.name if (board == null) return // Set player's scoreboard to board val playerBoard = player.scoreboard val teamName = getTeamName(player) if (playerBoard != board) { val team = playerBoard.getEntryTeam(name) if (team == null || team.name == teamName) { player.scoreboard = board } else { ColoredPlayerNames.logger.warning { "Player \"$name\" is currently on team \"${team.name}\". For full CPN functionality, please remove them from this team or turn off scoreboard in the configuration." } return } } // Update scoreboard with color if (color == null) { board.getTeam(teamName)?.unregister() } else { val team = board.getTeam(teamName) ?: board.registerNewTeam(teamName) team.displayName = displayName team.color = color team.setCanSeeFriendlyInvisibles(false) team.addEntry(name) } } fun count(color: ChatColor) = counts[color] ?: 0 fun getDisplayName(player: Player): String { val color = playerColors[player] val name = player.name return if (color == null) name else color.toString() + name + RESET } fun changeColor(player: Player) { val newColor = pickColor(player) set(player, newColor) } fun availableColors(player: Player): Set<ChatColor> { val result = EnumSet.noneOf(ChatColor::class.java) result.addAll(possibleColors(player, true).keys) result.addAll(possibleColors(player, false).keys) return result } private fun pickColor(player: Player): ChatColor? { val staticColor = config.getStaticColor(player) if (staticColor != null) return staticColor val colors = possibleColors(player) val lastColor = lastColors[player] if (colors.size >= 2) colors.remove(lastColor) val weightSum = colors.values.sum() if (weightSum <= 0.0) return null val randomVal = ThreadLocalRandom.current().nextDouble(weightSum) var accumulation = 0.0 for (entry in colors) { accumulation += entry.value if (accumulation >= randomVal) return entry.key } return null } private fun possibleColors(player: Player, posWeightsOnly: Boolean = true): MutableMap<ChatColor, Double> { val weights = config.weights val posWeights = if (posWeightsOnly) weights.filterValues { it >= 0 } else weights val playerColor = playerColors[player] val updatedCounts = posWeights.keys.associateWith { if (it == playerColor) count(it) - 1 else count(it) } val lowestCount = updatedCounts.values.min() val filtered = posWeights.filterKeys { updatedCounts[it] == lowestCount } val result = EnumMap<ChatColor, Double>(ChatColor::class.java) result.putAll(filtered) return result } private fun getTeamName(player: OfflinePlayer): String { val preferred = TEAM_PREFIX + player.name if (preferred.length <= MAX_TEAM_NAME_LENGTH) return preferred val clipped = preferred.substring(0, MAX_TEAM_NAME_LENGTH) val result = getAvailableName(player.uniqueId, clipped) teamNames[result] = player.uniqueId return result } private tailrec fun getAvailableName(uuid: UUID, possible: String): String { val uuidForName = teamNames[possible] return if (uuidForName == null || uuidForName == uuid) possible else getAvailableName(uuid, nextName(possible)) } private companion object { private fun nextName(name: String): String { val firstPart = name.substring(0, name.lastIndex) return when (val lastChar = name.last()) { in '0'..'8' -> firstPart + (lastChar + 1) '9' -> { nextName(firstPart) + '0' } else -> firstPart + '0' } } private const val TEAM_PREFIX = "__CPN__" private const val MAX_TEAM_NAME_LENGTH = 16 } }
mit
e1a35e217c0b781db54360e2d844a95e
34.302564
184
0.620424
4.574086
false
false
false
false
JimSeker/saveData
SupportPrefenceDemo_kt/app/src/main/java/edu/cs4730/supportprefencedemo_kt/MainFragment.kt
1
2697
package edu.cs4730.supportprefencedemo_kt import android.view.LayoutInflater import android.view.ViewGroup import android.os.Bundle import android.widget.Toast import android.app.Activity import android.content.Context import androidx.preference.PreferenceManager import android.view.View import androidx.fragment.app.Fragment import java.lang.ClassCastException /** * Main fragment to do most of the work. */ class MainFragment : Fragment() { private var mListener: OnFragmentInteractionListener? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val myView = inflater.inflate(R.layout.fragment_main, container, false) //either will have the mainactivity change the fragment to a preferencefragmentcompat. myView.findViewById<View>(R.id.button2) .setOnClickListener { mListener!!.onFragmentInteraction(1) } myView.findViewById<View>(R.id.button3) .setOnClickListener { mListener!!.onFragmentInteraction(2) } return myView } override fun onResume() { super.onResume() prefs } /* * Get the preferences for the game */ val prefs: Unit get() { val useSensor: Boolean val useSwipe: Boolean //Toast.makeText(getApplicationContext(), "Get prefs", Toast.LENGTH_SHORT).show(); val prefs = PreferenceManager.getDefaultSharedPreferences(requireContext()) useSensor = prefs.getBoolean("sensorPref", false) useSwipe = prefs.getBoolean("swipePref", true) Toast.makeText(requireContext(), "Sensor is $useSensor", Toast.LENGTH_SHORT).show() val text = prefs.getString("textPref", "") Toast.makeText(requireContext(), "Text is $text", Toast.LENGTH_SHORT).show() val list = prefs.getString("list_preference", "") Toast.makeText(requireContext(), "List $list", Toast.LENGTH_SHORT).show() } override fun onAttach(context: Context) { super.onAttach(context) val activity: Activity? = activity mListener = try { activity as OnFragmentInteractionListener? } catch (e: ClassCastException) { throw ClassCastException( activity.toString() + " must implement OnFragmentInteractionListener" ) } } override fun onDetach() { super.onDetach() mListener = null } interface OnFragmentInteractionListener { fun onFragmentInteraction(which: Int) } }
apache-2.0
4e7e271d77f61b4ec797763b42d4f66a
33.151899
95
0.652206
5.013011
false
false
false
false
wiryls/HomeworkCollectionOfMYLS
2017.AndroidApplicationDevelopment/ODES/app/src/main/java/com/myls/odes/application/AnApplication.kt
1
1230
package com.myls.odes.application import android.app.Application import android.util.Log import com.myls.odes.data.RoomInfo import com.myls.odes.data.Settings import com.myls.odes.data.UserList import com.myls.odes.utility.Storage /** * Created by myls on 12/7/17. * * 用于绑定 Model 的引用到整个程序 * * 注意事项: * [Don't Store Data in the Application Object] * (http://www.developerphil.com/dont-store-data-in-the-application-object/) * [Application] * (https://developer.android.com/reference/android/app/Application.html) */ class AnApplication : Application() { lateinit var saver: Storage lateinit var settings: Settings lateinit var userlist: UserList lateinit var roominfo: RoomInfo override fun onCreate() { super.onCreate() saver = Storage(this) settings = saver.get() userlist = saver.get() roominfo = saver.get() Log.d(TAG, "Create") } override fun onLowMemory() { Log.d(TAG, "LowMemory") saver.put(settings) saver.put(userlist) saver.put(roominfo) super.onLowMemory() } companion object { val TAG = AnApplication::class.java.canonicalName!! } }
mit
ad3f3288f4edad1a1340aed4132e6f50
22.92
76
0.666388
3.668712
false
false
false
false
google/private-compute-libraries
javatests/com/google/android/libraries/pcc/chronicle/api/policy/capabilities/CapabilityTest.kt
1
47331
/* * 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. */ /* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package com.google.android.libraries.pcc.chronicle.api.policy.capabilities import com.google.android.libraries.pcc.chronicle.api.policy.annotation.Annotation import com.google.android.libraries.pcc.chronicle.api.policy.annotation.AnnotationParam import com.google.android.libraries.pcc.chronicle.api.policy.capabilities.Capability.Encryption import com.google.android.libraries.pcc.chronicle.api.policy.capabilities.Capability.Persistence import com.google.android.libraries.pcc.chronicle.api.policy.capabilities.Capability.Queryable import com.google.android.libraries.pcc.chronicle.api.policy.capabilities.Capability.Range import com.google.android.libraries.pcc.chronicle.api.policy.capabilities.Capability.Shareable import com.google.android.libraries.pcc.chronicle.api.policy.capabilities.Capability.Ttl import com.google.common.truth.Truth.assertThat import kotlin.test.assertFailsWith import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class CapabilityTest { @Test fun compare_capabilityPersistence() { assertThat(Persistence.UNRESTRICTED.isEquivalent(Persistence.UNRESTRICTED)).isTrue() assertThat(Persistence.UNRESTRICTED.isEquivalent(Persistence.ON_DISK)).isFalse() assertThat(Persistence.UNRESTRICTED.isLessStrict(Persistence.UNRESTRICTED)).isFalse() assertThat(Persistence.UNRESTRICTED.isSameOrLessStrict(Persistence.IN_MEMORY)).isTrue() assertThat(Persistence.UNRESTRICTED.isLessStrict(Persistence.IN_MEMORY)).isTrue() assertThat(Persistence.UNRESTRICTED.isLessStrict(Persistence.NONE)).isTrue() assertThat(Persistence.ON_DISK.isEquivalent(Persistence.ON_DISK)).isTrue() assertThat(Persistence.ON_DISK.isEquivalent(Persistence.IN_MEMORY)).isFalse() assertThat(Persistence.ON_DISK.isLessStrict(Persistence.IN_MEMORY)).isTrue() assertThat(Persistence.ON_DISK.isSameOrLessStrict(Persistence.IN_MEMORY)).isTrue() assertThat(Persistence.IN_MEMORY.isEquivalent(Persistence.IN_MEMORY)).isTrue() assertThat(Persistence.IN_MEMORY.isEquivalent(Persistence.NONE)).isFalse() assertThat(Persistence.IN_MEMORY.isStricter(Persistence.ON_DISK)).isTrue() assertThat(Persistence.IN_MEMORY.isLessStrict(Persistence.ON_DISK)).isFalse() assertThat(Persistence.IN_MEMORY.isSameOrLessStrict(Persistence.ON_DISK)).isFalse() assertThat(Persistence.NONE.isEquivalent(Persistence.NONE)).isTrue() assertThat(Persistence.NONE.isEquivalent(Persistence.UNRESTRICTED)).isFalse() assertThat(Persistence.NONE.isStricter(Persistence.UNRESTRICTED)).isTrue() } @Test fun compare_capabilityTtl() { val ttl3Days = Ttl.Days(3) val ttl10Hours = Ttl.Hours(10) assertThat(ttl3Days.isEquivalent(ttl3Days)).isTrue() assertThat(ttl3Days.isEquivalent(ttl10Hours)).isFalse() assertThat(ttl3Days.isLessStrict(ttl10Hours)).isTrue() assertThat(ttl3Days.isSameOrLessStrict(ttl10Hours)).isTrue() assertThat(ttl3Days.isStricter(ttl10Hours)).isFalse() assertThat(ttl3Days.isSameOrStricter(ttl10Hours)).isFalse() assertThat(ttl3Days.isEquivalent(ttl10Hours)).isFalse() assertThat(ttl10Hours.isStricter(ttl3Days)).isTrue() assertThat(ttl10Hours.isEquivalent(Ttl.Minutes(600))).isTrue() val ttl300Minutes = Ttl.Minutes(300) assertThat(ttl300Minutes.isEquivalent(Ttl.Minutes(300))).isTrue() assertThat(ttl300Minutes.isEquivalent(ttl3Days)).isFalse() assertThat(ttl300Minutes.isEquivalent(Ttl.Hours(5))).isTrue() assertThat(ttl300Minutes.isSameOrStricter(ttl10Hours)).isTrue() assertThat(ttl300Minutes.isStricter(ttl10Hours)).isTrue() assertThat(ttl3Days.isSameOrLessStrict(ttl300Minutes)).isTrue() assertThat(ttl3Days.isLessStrict(ttl300Minutes)).isTrue() val ttlInfinite = Ttl.Infinite() assertThat(ttlInfinite.isEquivalent(ttlInfinite)).isTrue() assertThat(ttlInfinite.isSameOrLessStrict(ttlInfinite)).isTrue() assertThat(ttlInfinite.isSameOrStricter(ttlInfinite)).isTrue() assertThat(ttlInfinite.isStricter(ttlInfinite)).isFalse() assertThat(ttlInfinite.isLessStrict(ttlInfinite)).isFalse() assertThat(ttl3Days.isStricter(ttlInfinite)).isTrue() assertThat(ttlInfinite.isStricter(ttl3Days)).isFalse() assertThat(ttlInfinite.isLessStrict(ttl3Days)).isTrue() assertThat(ttl3Days.isLessStrict(ttlInfinite)).isFalse() assertThat(ttlInfinite.isEquivalent(ttl3Days)).isFalse() assertThat(ttlInfinite.isEquivalent(ttl300Minutes)).isFalse() assertThat(ttl300Minutes.isEquivalent(ttlInfinite)).isFalse() assertThat(ttlInfinite.isLessStrict(ttl300Minutes)).isTrue() assertThat(ttl300Minutes.isLessStrict(ttlInfinite)).isFalse() } @Test fun compare_capabilityEncryption() { val encrypted = Encryption(true) val nonEncrypted = Encryption(false) assertThat(encrypted.isEquivalent(encrypted)).isTrue() assertThat(nonEncrypted.isEquivalent(nonEncrypted)).isTrue() assertThat(nonEncrypted.isEquivalent(encrypted)).isFalse() assertThat(encrypted.isStricter(encrypted)).isFalse() assertThat(encrypted.isSameOrStricter(encrypted)).isTrue() assertThat(encrypted.isSameOrStricter(nonEncrypted)).isTrue() assertThat(nonEncrypted.isLessStrict(encrypted)).isTrue() } @Test fun compare_capabilityQueryable() { val queryable = Queryable(true) val nonQueryable = Queryable(false) assertThat(queryable.isEquivalent(queryable)).isTrue() assertThat(nonQueryable.isEquivalent(nonQueryable)).isTrue() assertThat(nonQueryable.isEquivalent(queryable)).isFalse() assertThat(queryable.isStricter(queryable)).isFalse() assertThat(queryable.isSameOrStricter(queryable)).isTrue() assertThat(queryable.isSameOrStricter(nonQueryable)).isTrue() assertThat(nonQueryable.isLessStrict(queryable)).isTrue() } @Test fun compare_capabilityShareable() { val shareable = Shareable(true) val nonShareable = Shareable(false) assertThat(shareable.isEquivalent(shareable)).isTrue() assertThat(nonShareable.isEquivalent(nonShareable)).isTrue() assertThat(nonShareable.isEquivalent(shareable)).isFalse() assertThat(shareable.isStricter(shareable)).isFalse() assertThat(shareable.isSameOrStricter(shareable)).isTrue() assertThat(shareable.isSameOrStricter(nonShareable)).isTrue() assertThat(nonShareable.isLessStrict(shareable)).isTrue() } @Test fun compare_capability_incompatible() { assertFailsWith<IllegalArgumentException> { Persistence.ON_DISK.compare(Ttl.Hours(1)) } assertFailsWith<IllegalArgumentException> { Ttl.Hours(1).compare(Shareable(true)) } assertFailsWith<IllegalArgumentException> { Shareable(true).compare(Queryable.ANY) } assertFailsWith<IllegalArgumentException> { Encryption(false).compare(Persistence.ANY) } } @Test fun compare_capabilityRange_unsupported() { assertFailsWith<UnsupportedOperationException> { Persistence.ON_DISK.toRange().compare(Persistence.ANY) } assertFailsWith<UnsupportedOperationException> { Ttl.ANY.toRange().compare(Range(Ttl.Hours(1), Ttl.Minutes(30))) } assertFailsWith<UnsupportedOperationException> { Queryable.ANY.compare(Queryable(true).toRange()) } assertFailsWith<UnsupportedOperationException> { Encryption.ANY.compare(Encryption(true).toRange()) } assertFailsWith<UnsupportedOperationException> { Shareable.ANY.compare(Shareable(true).toRange()) } } @Test fun isEquivalent_rangesPersistence() { assertThat(Persistence.ANY.isEquivalent(Persistence.ANY)).isTrue() assertThat(Persistence.ANY.isEquivalent(Persistence.ON_DISK.toRange())).isFalse() assertThat(Persistence.ON_DISK.toRange().isEquivalent(Persistence.ANY)).isFalse() assertThat(Persistence.ON_DISK.toRange().isEquivalent(Persistence.ON_DISK.toRange())).isTrue() assertThat(Persistence.ON_DISK.toRange().isEquivalent(Persistence.IN_MEMORY.toRange())) .isFalse() assertThat( Range(Persistence.ON_DISK, Persistence.NONE).isEquivalent( Range(Persistence.IN_MEMORY, Persistence.NONE) ) ).isFalse() assertThat( Range(Persistence.ON_DISK, Persistence.IN_MEMORY).isEquivalent( Range(Persistence.ON_DISK, Persistence.IN_MEMORY) ) ).isTrue() } @Test fun isEquivalent_rangesTtl() { assertThat(Ttl.ANY.isEquivalent(Ttl.ANY)).isTrue() assertThat(Ttl.ANY.isEquivalent(Ttl.Hours(1).toRange())).isFalse() assertThat(Ttl.ANY.isEquivalent(Ttl.Infinite().toRange())).isFalse() assertThat(Ttl.Infinite().toRange().isEquivalent(Ttl.Infinite().toRange())).isTrue() assertThat(Ttl.Infinite().toRange().isEquivalent(Ttl.ANY)).isFalse() assertThat(Ttl.Hours(2).toRange().isEquivalent(Ttl.Minutes(120).toRange())).isTrue() assertThat(Range(Ttl.Hours(2), Ttl.Minutes(2)).isEquivalent(Ttl.Minutes(100).toRange())) .isFalse() assertThat( Range(Ttl.Hours(2), Ttl.Minutes(2)).isEquivalent(Range(Ttl.Minutes(100), Ttl.Hours(1))) ).isFalse() assertThat(Range(Ttl.Days(2), Ttl.Days(2)).isEquivalent(Ttl.Hours(48).toRange())).isTrue() assertThat(Range(Ttl.Days(2), Ttl.Hours(24)).isEquivalent(Range(Ttl.Hours(48), Ttl.Days(1)))) .isTrue() } @Test fun isEquivalent_rangesEncryption() { assertThat(Encryption.ANY.isEquivalent(Encryption.ANY)).isTrue() assertThat(Encryption.ANY.isEquivalent(Encryption(true).toRange())).isFalse() assertThat(Encryption.ANY.isEquivalent(Encryption(false).toRange())).isFalse() assertThat(Encryption(false).toRange().isEquivalent(Encryption.ANY)).isFalse() assertThat(Encryption(true).toRange().isEquivalent(Encryption.ANY)).isFalse() assertThat(Encryption(false).toRange().isEquivalent(Encryption(true).toRange())).isFalse() assertThat(Encryption(true).toRange().isEquivalent(Encryption(false).toRange())).isFalse() assertThat(Encryption(false).toRange().isEquivalent(Encryption(false).toRange())).isTrue() assertThat(Encryption(true).toRange().isEquivalent(Encryption(true).toRange())).isTrue() } @Test fun isEquivalent_rangesQueryable() { assertThat(Queryable.ANY.isEquivalent(Queryable.ANY)).isTrue() assertThat(Queryable.ANY.isEquivalent(Queryable(true).toRange())).isFalse() assertThat(Queryable.ANY.isEquivalent(Queryable(false).toRange())).isFalse() assertThat(Queryable(false).toRange().isEquivalent(Queryable.ANY)).isFalse() assertThat(Queryable(true).toRange().isEquivalent(Queryable.ANY)).isFalse() assertThat(Queryable(false).toRange().isEquivalent(Queryable(true).toRange())).isFalse() assertThat(Queryable(true).toRange().isEquivalent(Queryable(false).toRange())).isFalse() assertThat(Queryable(false).toRange().isEquivalent(Queryable(false).toRange())).isTrue() assertThat(Queryable(true).toRange().isEquivalent(Queryable(true).toRange())).isTrue() } @Test fun isEquivalent_rangesShareable() { assertThat(Shareable.ANY.isEquivalent(Shareable.ANY)).isTrue() assertThat(Shareable.ANY.isEquivalent(Shareable(true).toRange())).isFalse() assertThat(Shareable.ANY.isEquivalent(Shareable(false).toRange())).isFalse() assertThat(Shareable(false).toRange().isEquivalent(Shareable.ANY)).isFalse() assertThat(Shareable(true).toRange().isEquivalent(Shareable.ANY)).isFalse() assertThat(Shareable(false).toRange().isEquivalent(Shareable(true).toRange())).isFalse() assertThat(Shareable(true).toRange().isEquivalent(Shareable(false).toRange())).isFalse() assertThat(Shareable(false).toRange().isEquivalent(Shareable(false).toRange())).isTrue() assertThat(Shareable(true).toRange().isEquivalent(Shareable(true).toRange())).isTrue() } @Test fun isEquivalent_rangeAndCapabilityPersistence() { assertThat(Persistence.ANY.isEquivalent(Persistence.ON_DISK)).isFalse() assertThat(Persistence.ANY.isEquivalent(Persistence.NONE)).isFalse() assertThat(Persistence.ANY.isEquivalent(Persistence.UNRESTRICTED)).isFalse() assertThat(Persistence.ON_DISK.toRange().isEquivalent(Persistence.ON_DISK)).isTrue() assertThat(Persistence.ON_DISK.toRange().isEquivalent(Persistence.IN_MEMORY)).isFalse() assertThat(Persistence.UNRESTRICTED.toRange().isEquivalent(Persistence.UNRESTRICTED)).isTrue() assertThat(Persistence.UNRESTRICTED.toRange().isEquivalent(Persistence.ON_DISK)).isFalse() } @Test fun isEquivalent_rangeAndCapabilityTtl() { assertThat(Ttl.ANY.isEquivalent(Ttl.Hours(1).toRange())).isFalse() assertThat(Range(Ttl.Days(2), Ttl.Days(2)).isEquivalent(Ttl.Hours(48))).isTrue() assertThat(Ttl.Hours(2).toRange().isEquivalent(Ttl.Minutes(120))).isTrue() assertThat(Range(Ttl.Hours(2), Ttl.Minutes(2)).isEquivalent(Ttl.Minutes(100))).isFalse() assertThat(Ttl.ANY.isEquivalent(Ttl.Infinite())).isFalse() assertThat(Ttl.Infinite().toRange().isEquivalent(Ttl.Infinite())).isTrue() } @Test fun isEquivalent_rangeAndCapabilityEncryption() { assertThat(Encryption.ANY.isEquivalent(Encryption(true))).isFalse() assertThat(Encryption.ANY.isEquivalent(Encryption(false))).isFalse() assertThat(Encryption(false).toRange().isEquivalent(Encryption(true))).isFalse() assertThat(Encryption(true).toRange().isEquivalent(Encryption(false))).isFalse() assertThat(Encryption(false).toRange().isEquivalent(Encryption(false))).isTrue() assertThat(Encryption(true).toRange().isEquivalent(Encryption(true))).isTrue() } @Test fun isEquivalent_rangeAndCapabilityQueryable() { assertThat(Queryable.ANY.isEquivalent(Queryable(true))).isFalse() assertThat(Queryable.ANY.isEquivalent(Queryable(false))).isFalse() assertThat(Queryable(false).toRange().isEquivalent(Queryable(true))).isFalse() assertThat(Queryable(true).toRange().isEquivalent(Queryable(false))).isFalse() assertThat(Queryable(false).toRange().isEquivalent(Queryable(false))).isTrue() assertThat(Queryable(true).toRange().isEquivalent(Queryable(true))).isTrue() } @Test fun isEquivalent_rangeAndCapabilityShareable() { assertThat(Shareable.ANY.isEquivalent(Shareable(true))).isFalse() assertThat(Shareable.ANY.isEquivalent(Shareable(false))).isFalse() assertThat(Shareable(false).toRange().isEquivalent(Shareable(true))).isFalse() assertThat(Shareable(true).toRange().isEquivalent(Shareable(false))).isFalse() assertThat(Shareable(false).toRange().isEquivalent(Shareable(false))).isTrue() assertThat(Shareable(true).toRange().isEquivalent(Shareable(true))).isTrue() } @Test fun isEquivalent_capabilityAndRangePersistence() { assertThat(Persistence.ON_DISK.isEquivalent(Persistence.ANY)).isFalse() assertThat(Persistence.ON_DISK.isEquivalent(Persistence.ON_DISK.toRange())).isTrue() assertThat(Persistence.ON_DISK.isEquivalent(Persistence.IN_MEMORY.toRange())).isFalse() assertThat(Persistence.ON_DISK.isEquivalent(Range(Persistence.IN_MEMORY, Persistence.NONE))) .isFalse() } @Test fun isEquivalent_capabilityAndRangeTtl() { assertThat(Ttl.Hours(1).isEquivalent(Ttl.ANY)).isFalse() assertThat(Ttl.Hours(2).isEquivalent(Ttl.Minutes(120).toRange())).isTrue() assertThat(Ttl.Hours(2).isEquivalent(Ttl.Minutes(100).toRange())).isFalse() assertThat(Ttl.Hours(2).isEquivalent(Range(Ttl.Minutes(100), Ttl.Hours(1)))).isFalse() } @Test fun isEquivalent_capabilityAndRangeEncryption() { assertThat(Encryption(false).isEquivalent(Encryption.ANY)).isFalse() assertThat(Encryption(true).isEquivalent(Encryption.ANY)).isFalse() assertThat(Encryption(false).isEquivalent(Encryption(false).toRange())).isTrue() assertThat(Encryption(false).isEquivalent(Encryption(true).toRange())).isFalse() assertThat(Encryption(true).isEquivalent(Encryption(false).toRange())).isFalse() assertThat(Encryption(true).isEquivalent(Encryption(true).toRange())).isTrue() } @Test fun isEquivalent_capabilityAndRangeQueryable() { assertThat(Queryable(false).isEquivalent(Queryable.ANY)).isFalse() assertThat(Queryable(true).isEquivalent(Queryable.ANY)).isFalse() assertThat(Queryable(false).isEquivalent(Queryable(false).toRange())).isTrue() assertThat(Queryable(false).isEquivalent(Queryable(true).toRange())).isFalse() assertThat(Queryable(true).isEquivalent(Queryable(false).toRange())).isFalse() assertThat(Queryable(true).isEquivalent(Queryable(true).toRange())).isTrue() } @Test fun isEquivalent_capabilityAndRangeShareable() { assertThat(Shareable(false).isEquivalent(Shareable.ANY)).isFalse() assertThat(Shareable(true).isEquivalent(Shareable.ANY)).isFalse() assertThat(Shareable(false).isEquivalent(Shareable(false).toRange())).isTrue() assertThat(Shareable(false).isEquivalent(Shareable(true).toRange())).isFalse() assertThat(Shareable(true).isEquivalent(Shareable(false).toRange())).isFalse() assertThat(Shareable(true).isEquivalent(Shareable(true).toRange())).isTrue() } @Test fun contains_capabilityPersistence() { assertThat(Persistence.ON_DISK.contains(Persistence.ON_DISK)).isTrue() assertThat(Persistence.IN_MEMORY.contains(Persistence.ON_DISK)).isFalse() assertThat(Persistence.IN_MEMORY.contains(Persistence.IN_MEMORY)).isTrue() assertThat(Persistence.ON_DISK.contains(Persistence.UNRESTRICTED)).isFalse() assertThat(Persistence.UNRESTRICTED.contains(Persistence.ON_DISK)).isFalse() assertThat(Persistence.UNRESTRICTED.contains(Persistence.NONE)).isFalse() assertThat(Persistence.UNRESTRICTED.contains(Persistence.UNRESTRICTED)).isTrue() assertThat(Persistence.NONE.contains(Persistence.IN_MEMORY)).isFalse() assertThat(Persistence.NONE.contains(Persistence.NONE)).isTrue() } @Test fun contains_rangePersistence() { assertThat(Persistence.ON_DISK.toRange().contains(Persistence.ON_DISK.toRange())).isTrue() assertThat( Range(Persistence.ON_DISK, Persistence.IN_MEMORY).contains(Persistence.ON_DISK.toRange()) ) .isTrue() assertThat( Range(Persistence.ON_DISK, Persistence.IN_MEMORY).contains(Persistence.IN_MEMORY.toRange()) ) .isTrue() assertThat( Range(Persistence.ON_DISK, Persistence.IN_MEMORY) .contains(Persistence.UNRESTRICTED.toRange()) ) .isFalse() assertThat(Range(Persistence.ON_DISK, Persistence.IN_MEMORY).contains(Persistence.ANY)) .isFalse() assertThat(Persistence.ANY.contains(Persistence.ON_DISK.toRange())).isTrue() assertThat(Persistence.ANY.contains(Persistence.ON_DISK.toRange())).isTrue() assertThat(Persistence.ANY.contains(Range(Persistence.ON_DISK, Persistence.IN_MEMORY))).isTrue() } @Test fun contains_capabilityAndRangePersistence() { assertThat(Persistence.ON_DISK.contains(Persistence.ON_DISK.toRange())).isTrue() assertThat(Persistence.ON_DISK.contains(Range(Persistence.ON_DISK, Persistence.IN_MEMORY))) .isFalse() assertThat(Persistence.IN_MEMORY.contains(Range(Persistence.ON_DISK, Persistence.IN_MEMORY))) .isFalse() assertThat(Persistence.UNRESTRICTED.contains(Range(Persistence.ON_DISK, Persistence.IN_MEMORY))) .isFalse() assertThat(Persistence.UNRESTRICTED.contains(Persistence.UNRESTRICTED.toRange())).isTrue() assertThat(Persistence.NONE.contains(Persistence.NONE.toRange())).isTrue() assertThat(Persistence.ON_DISK.contains(Persistence.ANY)).isFalse() assertThat(Persistence.IN_MEMORY.contains(Persistence.ANY)).isFalse() assertThat(Persistence.NONE.contains(Persistence.ANY)).isFalse() assertThat(Persistence.UNRESTRICTED.contains(Persistence.ANY)).isFalse() } @Test fun contains_rangeAndCapabilityPersistence() { assertThat(Persistence.ON_DISK.toRange().contains(Persistence.ON_DISK)).isTrue() assertThat(Range(Persistence.ON_DISK, Persistence.IN_MEMORY).contains(Persistence.ON_DISK)) .isTrue() assertThat(Range(Persistence.ON_DISK, Persistence.IN_MEMORY).contains(Persistence.IN_MEMORY)) .isTrue() assertThat(Range(Persistence.ON_DISK, Persistence.IN_MEMORY).contains(Persistence.UNRESTRICTED)) .isFalse() assertThat(Range(Persistence.ON_DISK, Persistence.IN_MEMORY).contains(Persistence.NONE)) .isFalse() assertThat(Persistence.ANY.contains(Persistence.UNRESTRICTED)).isTrue() assertThat(Persistence.ANY.contains(Persistence.ON_DISK)).isTrue() assertThat(Persistence.ANY.contains(Persistence.IN_MEMORY)).isTrue() assertThat(Persistence.ANY.contains(Persistence.NONE)).isTrue() } @Test fun contains_capabilityTtl() { assertThat( Range(Ttl.Hours(10), Ttl.Hours(3)).contains(Range(Ttl.Hours(10), Ttl.Hours(3))) ).isTrue() assertThat( Range(Ttl.Hours(10), Ttl.Hours(3)).contains(Range(Ttl.Hours(8), Ttl.Hours(6))) ).isTrue() assertThat( Range(Ttl.Hours(10), Ttl.Hours(3)).contains(Range(Ttl.Hours(8), Ttl.Hours(2))) ).isFalse() assertThat( Range(Ttl.Infinite(), Ttl.Hours(3)).contains(Range(Ttl.Hours(8), Ttl.Hours(3))) ).isTrue() assertThat( Range(Ttl.Hours(8), Ttl.Hours(3)).contains(Range(Ttl.Infinite(), Ttl.Hours(3))) ).isFalse() assertThat( Range(Ttl.Minutes(240), Ttl.Minutes(5)).contains(Range(Ttl.Hours(4), Ttl.Hours(3))) ).isTrue() assertThat( Range(Ttl.Minutes(100), Ttl.Minutes(50)).contains(Range(Ttl.Hours(8), Ttl.Hours(3))) ).isFalse() assertThat( Range(Ttl.Days(5), Ttl.Days(2)).contains(Range(Ttl.Days(4), Ttl.Days(2))) ).isTrue() assertThat( Range(Ttl.Minutes(3 * 24 * 60), Ttl.Minutes(24 * 60)).contains( Range(Ttl.Hours(40), Ttl.Hours(30)) ) ).isTrue() assertThat(Ttl.ANY.contains(Ttl.Infinite())).isTrue() assertThat(Ttl.ANY.contains(Range(Ttl.Infinite(), Ttl.Hours(3)))).isTrue() assertThat(Ttl.ANY.contains(Range(Ttl.Days(300), Ttl.Days(60)))).isTrue() assertThat(Ttl.ANY.contains(Range(Ttl.Hours(3), Ttl.Minutes(1)))).isTrue() assertThat(Ttl.ANY.contains(Range(Ttl.Minutes(30), Ttl.Minutes(10)))).isTrue() assertThat(Range(Ttl.Infinite(), Ttl.Hours(3)).contains(Ttl.ANY)).isFalse() assertThat(Range(Ttl.Days(300), Ttl.Days(60)).contains(Ttl.ANY)).isFalse() assertThat(Range(Ttl.Hours(3), Ttl.Minutes(1)).contains(Ttl.ANY)).isFalse() assertThat(Range(Ttl.Minutes(30), Ttl.Minutes(10)).contains(Ttl.ANY)).isFalse() } @Test fun contains_rangeTtl() {} @Test fun contains_capabilityAndRangeTtl() {} @Test fun contains_rangeAndCapabilityTtl() {} @Test fun contains_capabilityEncryption() { assertThat(Encryption(false).contains(Encryption(false))).isTrue() assertThat(Encryption(false).contains(Encryption(true))).isFalse() assertThat(Encryption(true).contains(Encryption(false))).isFalse() assertThat(Encryption(true).contains(Encryption(true))).isTrue() } @Test fun contains_rangeEncryption() { assertThat(Encryption.ANY.contains(Encryption.ANY)).isTrue() assertThat(Encryption.ANY.contains(Encryption(false).toRange())).isTrue() assertThat(Encryption.ANY.contains(Encryption(true).toRange())).isTrue() assertThat(Encryption(false).toRange().contains(Encryption(false).toRange())).isTrue() assertThat(Encryption(false).toRange().contains(Encryption(true).toRange())).isFalse() assertThat(Encryption(false).toRange().contains(Encryption.ANY)).isFalse() assertThat(Encryption(true).toRange().contains(Encryption.ANY)).isFalse() assertThat(Encryption(true).toRange().contains(Encryption(false).toRange())).isFalse() assertThat(Encryption(true).toRange().contains(Encryption(true).toRange())).isTrue() } @Test fun contains_capabilityAndRangeEncryption() { assertThat(Encryption(false).contains(Encryption.ANY)).isFalse() assertThat(Encryption(false).contains(Encryption(true).toRange())).isFalse() assertThat(Encryption(true).contains(Encryption.ANY)).isFalse() assertThat(Encryption(true).contains(Encryption(false).toRange())).isFalse() assertThat(Encryption(false).contains(Encryption(false).toRange())).isTrue() assertThat(Encryption(true).contains(Encryption(true).toRange())).isTrue() } @Test fun contains_rangeAndCapabilityEncryption() { assertThat(Encryption.ANY.contains(Encryption(false))).isTrue() assertThat(Encryption.ANY.contains(Encryption(true))).isTrue() assertThat(Encryption(false).toRange().contains(Encryption(false))).isTrue() assertThat(Encryption(false).toRange().contains(Encryption(true))).isFalse() assertThat(Encryption(true).toRange().contains(Encryption(false))).isFalse() assertThat(Encryption(true).toRange().contains(Encryption(true))).isTrue() } @Test fun contains_capabilityQueryable() { assertThat(Queryable(false).contains(Queryable(false))).isTrue() assertThat(Queryable(false).contains(Queryable(true))).isFalse() assertThat(Queryable(true).contains(Queryable(false))).isFalse() assertThat(Queryable(true).contains(Queryable(true))).isTrue() } @Test fun contains_rangeQueryable() { assertThat(Queryable.ANY.contains(Queryable.ANY)).isTrue() assertThat(Queryable.ANY.contains(Queryable(false).toRange())).isTrue() assertThat(Queryable.ANY.contains(Queryable(true).toRange())).isTrue() assertThat(Queryable(false).toRange().contains(Queryable(false).toRange())).isTrue() assertThat(Queryable(false).toRange().contains(Queryable(true).toRange())).isFalse() assertThat(Queryable(false).toRange().contains(Queryable.ANY)).isFalse() assertThat(Queryable(true).toRange().contains(Queryable.ANY)).isFalse() assertThat(Queryable(true).toRange().contains(Queryable(false).toRange())).isFalse() assertThat(Queryable(true).toRange().contains(Queryable(true).toRange())).isTrue() } @Test fun contains_capabilityAndRangeQueryable() { assertThat(Queryable(false).contains(Queryable.ANY)).isFalse() assertThat(Queryable(false).contains(Queryable(true).toRange())).isFalse() assertThat(Queryable(true).contains(Queryable.ANY)).isFalse() assertThat(Queryable(true).contains(Queryable(false).toRange())).isFalse() assertThat(Queryable(false).contains(Queryable(false).toRange())).isTrue() assertThat(Queryable(true).contains(Queryable(true).toRange())).isTrue() } @Test fun contains_rangeAndCapabilityQueryable() { assertThat(Queryable.ANY.contains(Queryable(false))).isTrue() assertThat(Queryable.ANY.contains(Queryable(true))).isTrue() assertThat(Queryable(false).toRange().contains(Queryable(false))).isTrue() assertThat(Queryable(false).toRange().contains(Queryable(true))).isFalse() assertThat(Queryable(true).toRange().contains(Queryable(false))).isFalse() assertThat(Queryable(true).toRange().contains(Queryable(true))).isTrue() } @Test fun contains_capabilityShareable() { assertThat(Shareable(false).contains(Shareable(false))).isTrue() assertThat(Shareable(false).contains(Shareable(true))).isFalse() assertThat(Shareable(true).contains(Shareable(false))).isFalse() assertThat(Shareable(true).contains(Shareable(true))).isTrue() } @Test fun contains_rangeShareable() { assertThat(Shareable.ANY.contains(Shareable.ANY)).isTrue() assertThat(Shareable.ANY.contains(Shareable(false).toRange())).isTrue() assertThat(Shareable.ANY.contains(Shareable(true).toRange())).isTrue() assertThat(Shareable(false).toRange().contains(Shareable(false).toRange())).isTrue() assertThat(Shareable(false).toRange().contains(Shareable(true).toRange())).isFalse() assertThat(Shareable(false).toRange().contains(Shareable.ANY)).isFalse() assertThat(Shareable(true).toRange().contains(Shareable.ANY)).isFalse() assertThat(Shareable(true).toRange().contains(Shareable(false).toRange())).isFalse() assertThat(Shareable(true).toRange().contains(Shareable(true).toRange())).isTrue() } @Test fun contains_capabilityAndRangeShareable() { assertThat(Shareable(false).contains(Shareable.ANY)).isFalse() assertThat(Shareable(false).contains(Shareable(true).toRange())).isFalse() assertThat(Shareable(true).contains(Shareable.ANY)).isFalse() assertThat(Shareable(true).contains(Shareable(false).toRange())).isFalse() assertThat(Shareable(false).contains(Shareable(false).toRange())).isTrue() assertThat(Shareable(true).contains(Shareable(true).toRange())).isTrue() } @Test fun contains_rangeAndCapabilityShareable() { assertThat(Shareable.ANY.contains(Shareable(false))).isTrue() assertThat(Shareable.ANY.contains(Shareable(true))).isTrue() assertThat(Shareable(false).toRange().contains(Shareable(false))).isTrue() assertThat(Shareable(false).toRange().contains(Shareable(true))).isFalse() assertThat(Shareable(true).toRange().contains(Shareable(false))).isFalse() assertThat(Shareable(true).toRange().contains(Shareable(true))).isTrue() } @Test fun init_capabilityRangeIncompatible_fail() { assertFailsWith<IllegalArgumentException> { Range(Persistence.ON_DISK, Encryption(false)) } assertFailsWith<IllegalArgumentException> { Range(Ttl.Days(1), Persistence.ON_DISK) } assertFailsWith<IllegalArgumentException> { Range(Ttl.Days(10), Queryable(false)) } assertFailsWith<IllegalArgumentException> { Range(Encryption(false), Shareable(false)) } assertFailsWith<IllegalArgumentException> { Range(Queryable(false), Shareable(true)) } assertFailsWith<IllegalArgumentException> { Range(Encryption(true), Encryption(false)) } } @Test fun init_capabilityRangeInvalid_fail() { assertFailsWith<IllegalArgumentException> { Range(Persistence.ON_DISK, Persistence.UNRESTRICTED) } assertFailsWith<IllegalArgumentException> { Range(Ttl.Minutes(1), Ttl.Hours(1)) } assertFailsWith<IllegalArgumentException> { Range(Queryable(true), Queryable(false)) } assertFailsWith<IllegalArgumentException> { Range(Encryption(true), Encryption(false)) } assertFailsWith<IllegalArgumentException> { Range(Shareable(true), Shareable(false)) } } @Test fun isCompatible_capability() { // Persistence capabilities are compatible. assertThat(Persistence.ON_DISK.isCompatible(Persistence.ON_DISK)).isTrue() assertThat(Persistence.ON_DISK.isCompatible(Persistence.IN_MEMORY)).isTrue() assertThat(Persistence.UNRESTRICTED.isCompatible(Persistence.ON_DISK)).isTrue() // Ttl capabilities are compatible. assertThat(Ttl.Hours(3).isCompatible(Ttl.Infinite())).isTrue() assertThat(Ttl.Hours(3).isCompatible(Ttl.Minutes(33))).isTrue() // Encryption capabilities are compatible. assertThat(Encryption(true).isCompatible(Encryption(false))).isTrue() assertThat(Encryption(false).isCompatible(Encryption(true))).isTrue() // Queryable capabilities are compatible. assertThat(Queryable(true).isCompatible(Queryable(false))).isTrue() assertThat(Queryable(false).isCompatible(Queryable(true))).isTrue() // Shareable capabilities are compatible. assertThat(Shareable(true).isCompatible(Shareable(false))).isTrue() assertThat(Shareable(false).isCompatible(Shareable(true))).isTrue() // Incompatible capabilities. assertThat(Persistence.UNRESTRICTED.isCompatible(Ttl.Infinite())).isFalse() assertThat(Queryable(false).isCompatible(Encryption(false))).isFalse() assertThat(Shareable(false).isCompatible(Ttl.Infinite())).isFalse() assertThat(Shareable(false).isCompatible(Queryable(true))).isFalse() } @Test fun isCompatible_capabilityRanges_compatible() { assertThat(Persistence.ANY.isCompatible(Persistence.ANY)).isTrue() assertThat(Persistence.ANY.isCompatible(Range(Persistence.ON_DISK, Persistence.NONE))).isTrue() assertThat(Ttl.ANY.isCompatible(Range(Ttl.Days(2), Ttl.Hours(1)))).isTrue() assertThat(Encryption.ANY.isCompatible(Encryption.ANY)).isTrue() assertThat(Shareable.ANY.isCompatible(Shareable.ANY)).isTrue() assertThat(Queryable.ANY.isCompatible(Queryable.ANY)).isTrue() } @Test fun isCompatible_capabilityRanges_incompatible() { assertThat(Ttl.ANY.isCompatible(Range(Persistence.ON_DISK, Persistence.NONE))).isFalse() assertThat(Encryption.ANY.isCompatible(Range(Ttl.Days(2), Ttl.Hours(1)))).isFalse() assertThat(Shareable.ANY.isCompatible(Encryption.ANY)).isFalse() assertThat(Queryable.ANY.isCompatible(Shareable.ANY)).isFalse() assertThat(Persistence.ANY.isCompatible(Queryable.ANY)).isFalse() } @Test fun isCompatible_rangeWithCapability_compatible() { assertThat(Persistence.ANY.isCompatible(Persistence.ON_DISK)).isTrue() assertThat(Ttl.ANY.isCompatible(Ttl.Days(5))).isTrue() assertThat(Encryption.ANY.isCompatible(Encryption(false))).isTrue() assertThat(Shareable.ANY.isCompatible(Shareable(true))).isTrue() assertThat(Queryable.ANY.isCompatible(Queryable(true))).isTrue() } @Test fun isCompatible_capabilityWithRange_compatible() { assertThat(Persistence.ON_DISK.isCompatible(Persistence.ANY)).isTrue() assertThat(Ttl.Days(5).isCompatible(Ttl.ANY)).isTrue() assertThat(Encryption(false).isCompatible(Encryption.ANY)).isTrue() assertThat(Shareable(false).isCompatible(Shareable.ANY)).isTrue() assertThat(Queryable(true).isCompatible(Queryable.ANY)).isTrue() } @Test fun isCompatible_rangeWithCapability_incompatible() { assertThat(Queryable.ANY.isCompatible(Persistence.ON_DISK)).isFalse() assertThat(Persistence.ANY.isCompatible(Ttl.Days(5))).isFalse() assertThat(Ttl.ANY.isCompatible(Encryption(false))).isFalse() assertThat(Encryption.ANY.isCompatible(Shareable(true))).isFalse() assertThat(Shareable.ANY.isCompatible(Queryable(true))).isFalse() } @Test fun isCompatible_capabilityWithRange_incompatible() { assertThat(Queryable(true).isCompatible(Persistence.ANY)).isFalse() assertThat(Persistence.ON_DISK.isCompatible(Ttl.ANY)).isFalse() assertThat(Ttl.Days(5).isCompatible(Encryption.ANY)).isFalse() assertThat(Encryption(false).isCompatible(Shareable.ANY)).isFalse() assertThat(Shareable(false).isCompatible(Queryable.ANY)).isFalse() } // Tests for fromAnnotations methods. @Test fun fromAnnotations_persistence_errorMultiple() { assertThat( assertFailsWith<IllegalArgumentException> { Persistence.fromAnnotations( listOf( Annotation.createCapability("onDisk"), Annotation.createCapability("inMemory") ) ) } ).hasMessageThat().contains("Containing multiple persistence capabilities") } @Test fun fromAnnotations_persistence_errorParams() { assertThat( assertFailsWith<IllegalArgumentException> { Persistence.fromAnnotations( listOf( Annotation( name = "onDisk", params = mapOf("invalid" to AnnotationParam.Str("param")) ) ) ) } ).hasMessageThat().contains("Unexpected parameter") assertThat( assertFailsWith<IllegalArgumentException> { Persistence.fromAnnotations( listOf( Annotation( name = "inMemory", params = mapOf("invalid" to AnnotationParam.Str("param")) ) ) ) } ).hasMessageThat().contains("Unexpected parameter") } @Test fun fromAnnotations_persistence_empty() { assertThat(Persistence.fromAnnotations(emptyList<Annotation>())).isNull() assertThat( Persistence.fromAnnotations(listOf(Annotation("something"), Annotation("else"))) ).isNull() } @Test fun fromAnnotations_persistence_ok() { assertThat( Persistence.fromAnnotations(listOf(Annotation("onDisk"), Annotation("other"))) ).isEqualTo(Persistence.ON_DISK) // Two persistence annotations that represent the same Capability. assertThat( Persistence.fromAnnotations(listOf(Annotation("onDisk"), Annotation("persistent"))) ).isEqualTo(Persistence.ON_DISK) assertThat( Persistence.fromAnnotations(listOf(Annotation("a"), Annotation("inMemory"), Annotation("b"))) ).isEqualTo(Persistence.IN_MEMORY) } @Test fun fromAnnotations_ttl_errorMultiple() { assertThat( assertFailsWith<IllegalArgumentException> { Ttl.fromAnnotations( listOf(Annotation.createTtl("30d"), Annotation.createTtl("5 hours")) ) } ).hasMessageThat().contains("Containing multiple ttl capabilities") } @Test fun fromAnnotations_ttl_errorNoParams() { assertThat( assertFailsWith<IllegalArgumentException> { Ttl.fromAnnotations(listOf(Annotation("ttl"))) } ).hasMessageThat().contains("missing 'value' parameter") } @Test fun fromAnnotations_ttl_errorMultipleParams() { assertThat( assertFailsWith<IllegalArgumentException> { Ttl.fromAnnotations( listOf( Annotation( "ttl", mapOf("value" to AnnotationParam.Str("2h"), "x" to AnnotationParam.Str("y")) ) ) ) } ).hasMessageThat().contains("Unexpected parameter for Ttl Capability annotation") } @Test fun fromAnnotations_ttl_invalid() { assertThat( assertFailsWith<IllegalArgumentException> { Ttl.fromAnnotations(listOf(Annotation.createTtl("foo"))) } ).hasMessageThat().isEqualTo("Invalid TTL foo.") assertThat( assertFailsWith<IllegalArgumentException> { Ttl.fromAnnotations(listOf(Annotation.createTtl("200years"))) } ).hasMessageThat().isEqualTo("Invalid TTL 200years.") assertThat( assertFailsWith<IllegalArgumentException> { Ttl.fromAnnotations(listOf(Annotation.createTtl("124"))) } ).hasMessageThat().isEqualTo("Invalid TTL 124.") } @Test fun fromAnnotations_ttl_empty() { assertThat(Ttl.fromAnnotations(emptyList<Annotation>())).isNull() assertThat( Ttl.fromAnnotations(listOf(Annotation("something"), Annotation("else"))) ).isNull() } @Test fun fromAnnotations_ttl_ok() { assertThat( Ttl.fromAnnotations( listOf(Annotation("something"), Annotation.createTtl("30d"), Annotation("else")) ) ).isEqualTo(Ttl.Days(30)) } @Test fun fromAnnotations_encryption_empty() { assertThat(Encryption.fromAnnotations(emptyList<Annotation>())).isNull() assertThat(Encryption.fromAnnotations(listOf(Annotation("something"), Annotation("else")))) .isNull() } @Test fun fromAnnotations_encryption_ok() { assertThat( Encryption.fromAnnotations( listOf(Annotation("something"), Annotation("encrypted"), Annotation("else")) ) ).isEqualTo(Encryption(true)) } @Test fun fromAnnotations_encryptionMultiple_invalid() { assertThat( assertFailsWith<IllegalArgumentException> { Encryption.fromAnnotations( listOf(Annotation("encrypted"), Annotation.createCapability("encrypted")) ) } ) .hasMessageThat() .contains("Containing multiple encryption capabilities") } @Test fun fromAnnotations_encryption_unexpectedParam() { assertThat( assertFailsWith<IllegalArgumentException> { Encryption.fromAnnotations( listOf(Annotation("encrypted", mapOf("foo" to AnnotationParam.Str("bar")))) ) } ) .hasMessageThat() .contains("Unexpected parameter for Encryption annotation") } @Test fun fromAnnotations_queryable_empty() { assertThat(Queryable.fromAnnotations(emptyList<Annotation>())).isNull() assertThat(Queryable.fromAnnotations(listOf(Annotation("something"), Annotation("else")))) .isNull() } @Test fun fromAnnotations_queryable_ok() { assertThat( Queryable.fromAnnotations( listOf(Annotation("something"), Annotation("queryable"), Annotation("else")) ) ) .isEqualTo(Queryable(true)) } @Test fun fromAnnotations_queryableMultiple_invalid() { assertThat( assertFailsWith<IllegalArgumentException> { Queryable.fromAnnotations( listOf(Annotation("queryable"), Annotation.createCapability("queryable")) ) } ) .hasMessageThat() .contains("Containing multiple queryable capabilities") } @Test fun fromAnnotations_queryable_unexpectedParam() { assertThat( assertFailsWith<IllegalArgumentException> { Queryable.fromAnnotations( listOf(Annotation("queryable", mapOf("foo" to AnnotationParam.Str("bar")))) ) } ) .hasMessageThat() .contains("Unexpected parameter for Queryable annotation") } @Test fun fromAnnotations_shareable_empty() { assertThat(Shareable.fromAnnotations(emptyList<Annotation>())).isNull() assertThat(Shareable.fromAnnotations(listOf(Annotation("something"), Annotation("else")))) .isNull() } @Test fun fromAnnotations_shareable_ok() { assertThat( Shareable.fromAnnotations( listOf(Annotation("something"), Annotation("shareable"), Annotation("else")) ) ) .isEqualTo(Shareable(true)) } @Test fun fromAnnotations_shareableMultiple_invalid() { assertThat( assertFailsWith<IllegalArgumentException> { Shareable.fromAnnotations( listOf(Annotation("shareable"), Annotation.createCapability("shareable")) ) } ) .hasMessageThat() .contains("Containing multiple shareable capabilities") assertThat( assertFailsWith<IllegalArgumentException> { Shareable.fromAnnotations( listOf(Annotation("shareable"), Annotation.createCapability("shareable")) ) } ) .hasMessageThat() .contains("Containing multiple shareable capabilities") assertThat( assertFailsWith<IllegalArgumentException> { Shareable.fromAnnotations( listOf(Annotation("tiedToRuntime"), Annotation.createCapability("shareable")) ) } ) .hasMessageThat() .contains("Containing multiple shareable capabilities") assertThat( assertFailsWith<IllegalArgumentException> { Shareable.fromAnnotations( listOf(Annotation("tiedToRuntime"), Annotation.createCapability("tiedToRuntime")) ) } ) .hasMessageThat() .contains("Containing multiple shareable capabilities") } @Test fun fromAnnotations_shareable_unexpectedParam() { assertThat( assertFailsWith<IllegalArgumentException> { Shareable.fromAnnotations( listOf(Annotation("shareable", mapOf("foo" to AnnotationParam.Str("bar")))) ) } ) .hasMessageThat() .contains("Unexpected parameter for Shareable annotation") } // Ttl tests @Test fun fromString_ttl_invalid() { assertFailsWith<IllegalArgumentException> { Ttl.fromString("invalid") } assertFailsWith<IllegalArgumentException> { Ttl.fromString("123") } assertFailsWith<IllegalArgumentException> { Ttl.fromString("day") } assertFailsWith<IllegalArgumentException> { Ttl.fromString(" ") } assertFailsWith<IllegalArgumentException> { Ttl.fromString("-10 hours") } assertFailsWith<IllegalArgumentException> { Ttl.fromString("infinite") } assertFailsWith<IllegalArgumentException> { Ttl.fromString("-1") } assertFailsWith<IllegalArgumentException> { Ttl.fromString("0") } assertFailsWith<NumberFormatException> { Ttl.fromString("9999999999days") } } @Test fun fromString_ttlDays_ok() { assertThat(Ttl.fromString("12d")).isEqualTo(Ttl.Days(12)) assertThat(Ttl.fromString(" 12d ")).isEqualTo(Ttl.Days(12)) assertThat(Ttl.fromString("12 d")).isEqualTo(Ttl.Days(12)) assertThat(Ttl.fromString("12day")).isEqualTo(Ttl.Days(12)) assertThat(Ttl.fromString("12 day")).isEqualTo(Ttl.Days(12)) assertThat(Ttl.fromString("12days")).isEqualTo(Ttl.Days(12)) assertThat(Ttl.fromString("12 days")).isEqualTo(Ttl.Days(12)) } @Test fun fromString_ttlHours_ok() { assertThat(Ttl.fromString("8h")).isEqualTo(Ttl.Hours(8)) assertThat(Ttl.fromString(" 8h ")).isEqualTo(Ttl.Hours(8)) assertThat(Ttl.fromString("8 h")).isEqualTo(Ttl.Hours(8)) assertThat(Ttl.fromString("8hour")).isEqualTo(Ttl.Hours(8)) assertThat(Ttl.fromString("8 hour")).isEqualTo(Ttl.Hours(8)) assertThat(Ttl.fromString("8hours")).isEqualTo(Ttl.Hours(8)) assertThat(Ttl.fromString("8 hours")).isEqualTo(Ttl.Hours(8)) } @Test fun fromString_ttlMinutes_ok() { assertThat(Ttl.fromString("45m")).isEqualTo(Ttl.Minutes(45)) assertThat(Ttl.fromString(" 45m ")).isEqualTo(Ttl.Minutes(45)) assertThat(Ttl.fromString("45 m")).isEqualTo(Ttl.Minutes(45)) assertThat(Ttl.fromString("45minute")).isEqualTo(Ttl.Minutes(45)) assertThat(Ttl.fromString("45 minute")).isEqualTo(Ttl.Minutes(45)) assertThat(Ttl.fromString("45minutes")).isEqualTo(Ttl.Minutes(45)) assertThat(Ttl.fromString("45 minutes")).isEqualTo(Ttl.Minutes(45)) } @Test fun init_ttl_fail() { assertFailsWith<IllegalArgumentException> { Ttl.Days(0) } assertFailsWith<IllegalArgumentException> { Ttl.Days(-1) } assertFailsWith<IllegalArgumentException> { Ttl.Days(-5) } assertFailsWith<IllegalArgumentException> { Ttl.Hours(0) } assertFailsWith<IllegalArgumentException> { Ttl.Hours(-1) } assertFailsWith<IllegalArgumentException> { Ttl.Hours(-5) } assertFailsWith<IllegalArgumentException> { Ttl.Minutes(0) } assertFailsWith<IllegalArgumentException> { Ttl.Minutes(-1) } assertFailsWith<IllegalArgumentException> { Ttl.Minutes(-5) } } @Test fun ttl_infinite_millisAndMinutes() { assertThat(Ttl.Infinite().millis).isEqualTo(-1) assertThat(Ttl.Infinite().minutes).isEqualTo(-1) } @Test fun ttl_minutes_millisAndMinutes() { val minutes5 = Ttl.Minutes(5) assertThat(minutes5.millis).isEqualTo(5 * 60 * 1000) assertThat(minutes5.minutes).isEqualTo(5) } @Test fun ttl_hours_millisAndMinutes() { val hours3 = Ttl.Hours(3) assertThat(hours3.millis).isEqualTo(3 * 60 * 60 * 1000) assertThat(hours3.minutes).isEqualTo(3 * 60) } @Test fun ttl_days_millisAndMinutes() { val days4 = Ttl.Days(4) assertThat(days4.millis).isEqualTo(4 * 24 * 60 * 60 * 1000) assertThat(days4.minutes).isEqualTo(4 * 24 * 60) } }
apache-2.0
0f27af78a312231c5f94d4f42ae37516
41.950091
100
0.725846
4.410679
false
true
false
false
gradle/gradle
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/accessors/GradleType.kt
3
3383
/* * Copyright 2018 the original author or authors. * * 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.gradle.kotlin.dsl.accessors import org.gradle.api.Action import org.gradle.api.NamedDomainObjectContainer import org.gradle.api.NamedDomainObjectProvider import org.gradle.api.artifacts.ConfigurablePublishArtifact import org.gradle.api.artifacts.Configuration import org.gradle.api.artifacts.Dependency import org.gradle.api.artifacts.DependencyConstraint import org.gradle.api.artifacts.ExternalModuleDependency import org.gradle.api.artifacts.PublishArtifact import org.gradle.api.artifacts.dsl.ArtifactHandler import org.gradle.api.artifacts.dsl.DependencyConstraintHandler import org.gradle.api.artifacts.dsl.DependencyHandler import org.gradle.api.plugins.ExtensionAware import org.gradle.api.plugins.ExtensionContainer import org.gradle.api.provider.Provider import org.gradle.api.tasks.TaskProvider import org.gradle.kotlin.dsl.support.bytecode.genericTypeOf import org.gradle.kotlin.dsl.support.bytecode.internalName internal object GradleType { val artifactHandler = classOf<ArtifactHandler>() val configurablePublishArtifact = classOf<ConfigurablePublishArtifact>() val dependencyConstraintHandler = classOf<DependencyConstraintHandler>() val dependencyConstraint = classOf<DependencyConstraint>() val dependencyHandler = classOf<DependencyHandler>() val dependency = classOf<Dependency>() val externalModuleDependency = classOf<ExternalModuleDependency>() val namedDomainObjectContainer = classOf<NamedDomainObjectContainer<*>>() val configuration = classOf<Configuration>() val namedDomainObjectProvider = classOf<NamedDomainObjectProvider<*>>() val containerOfConfiguration = genericTypeOf(namedDomainObjectContainer, configuration) val providerOfConfiguration = genericTypeOf(namedDomainObjectProvider, configuration) val publishArtifact = classOf<PublishArtifact>() val provider = classOf<Provider<*>>() } internal object GradleTypeName { val action = Action::class.internalName val artifactHandler = ArtifactHandler::class.internalName val externalModuleDependency = ExternalModuleDependency::class.internalName val dependencyHandler = DependencyHandler::class.internalName val dependencyConstraintHandler = DependencyConstraintHandler::class.internalName val extensionAware = ExtensionAware::class.internalName val extensionContainer = ExtensionContainer::class.internalName val namedDomainObjectProvider = NamedDomainObjectProvider::class.internalName val taskProvider = TaskProvider::class.internalName val namedWithTypeMethodDescriptor = "(Ljava/lang/String;Ljava/lang/Class;)L$namedDomainObjectProvider;" val namedTaskWithTypeMethodDescriptor = "(Ljava/lang/String;Ljava/lang/Class;)L$taskProvider;" }
apache-2.0
4ae8c6a297e0a4551413570a2036d86e
33.876289
107
0.803133
4.938686
false
true
false
false
facebook/fresco
imagepipeline/src/main/java/com/facebook/imagepipeline/producers/DecodeProducer.kt
1
20785
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.imagepipeline.producers import com.facebook.common.internal.ImmutableMap import com.facebook.common.internal.Supplier import com.facebook.common.logging.FLog import com.facebook.common.memory.ByteArrayPool import com.facebook.common.references.CloseableReference import com.facebook.common.util.ExceptionWithNoStacktrace import com.facebook.common.util.UriUtil import com.facebook.imageformat.DefaultImageFormats import com.facebook.imagepipeline.common.ImageDecodeOptions import com.facebook.imagepipeline.core.CloseableReferenceFactory import com.facebook.imagepipeline.decoder.DecodeException import com.facebook.imagepipeline.decoder.ImageDecoder import com.facebook.imagepipeline.decoder.ProgressiveJpegConfig import com.facebook.imagepipeline.decoder.ProgressiveJpegParser import com.facebook.imagepipeline.image.CloseableBitmap import com.facebook.imagepipeline.image.CloseableImage import com.facebook.imagepipeline.image.CloseableStaticBitmap import com.facebook.imagepipeline.image.EncodedImage import com.facebook.imagepipeline.image.ImmutableQualityInfo import com.facebook.imagepipeline.image.QualityInfo import com.facebook.imagepipeline.producers.JobScheduler.JobRunnable import com.facebook.imagepipeline.request.ImageRequest import com.facebook.imagepipeline.systrace.FrescoSystrace.traceSection import com.facebook.imagepipeline.transcoder.DownsampleUtil import com.facebook.imageutils.BitmapUtil import java.lang.Exception import java.util.HashMap import java.util.concurrent.Executor import javax.annotation.concurrent.GuardedBy /** * Decodes images. * * Progressive JPEGs are decoded progressively as new data arrives. */ class DecodeProducer( val byteArrayPool: ByteArrayPool, val executor: Executor, val imageDecoder: ImageDecoder, val progressiveJpegConfig: ProgressiveJpegConfig, val downsampleEnabled: Boolean, val downsampleEnabledForNetwork: Boolean, val decodeCancellationEnabled: Boolean, val inputProducer: Producer<EncodedImage?>, val maxBitmapSize: Int, val closeableReferenceFactory: CloseableReferenceFactory, val reclaimMemoryRunnable: Runnable?, val recoverFromDecoderOOM: Supplier<Boolean> ) : Producer<CloseableReference<CloseableImage>> { override fun produceResults( consumer: Consumer<CloseableReference<CloseableImage>>, context: ProducerContext ) = traceSection("DecodeProducer#produceResults") { val imageRequest = context.imageRequest val progressiveDecoder = if (!UriUtil.isNetworkUri(imageRequest.sourceUri)) { LocalImagesProgressiveDecoder( consumer, context, this.decodeCancellationEnabled, this.maxBitmapSize) } else { val jpegParser = ProgressiveJpegParser(this.byteArrayPool) NetworkImagesProgressiveDecoder( consumer, context, jpegParser, this.progressiveJpegConfig, this.decodeCancellationEnabled, this.maxBitmapSize) } this.inputProducer.produceResults(progressiveDecoder, context) } private abstract inner class ProgressiveDecoder( consumer: Consumer<CloseableReference<CloseableImage>>, private val producerContext: ProducerContext, decodeCancellationEnabled: Boolean, maxBitmapSize: Int ) : DelegatingConsumer<EncodedImage?, CloseableReference<CloseableImage>>(consumer) { private val TAG = "ProgressiveDecoder" private val producerListener: ProducerListener2 = producerContext.producerListener private val imageDecodeOptions: ImageDecodeOptions = producerContext.imageRequest.imageDecodeOptions /** @return true if producer is finished */ @get:Synchronized @GuardedBy("this") private var isFinished: Boolean = false private val jobScheduler: JobScheduler protected var lastScheduledScanNumber = 0 private fun maybeIncreaseSampleSize(encodedImage: EncodedImage) { if (encodedImage.imageFormat !== DefaultImageFormats.JPEG) { return } val pixelSize = BitmapUtil.getPixelSizeForBitmapConfig(imageDecodeOptions.bitmapConfig) val sampleSize = DownsampleUtil.determineSampleSizeJPEG(encodedImage, pixelSize, MAX_BITMAP_SIZE) encodedImage.sampleSize = sampleSize } public override fun onNewResultImpl(newResult: EncodedImage?, @Consumer.Status status: Int) = traceSection("DecodeProducer#onNewResultImpl") { val isLast = isLast(status) if (isLast) { if (newResult == null) { val cacheHit = producerContext.getExtra<Boolean>(ProducerConstants.EXTRA_CACHED_VALUE_FOUND) == true if (!producerContext.imagePipelineConfig.experiments.cancelDecodeOnCacheMiss || producerContext.lowestPermittedRequestLevel == ImageRequest.RequestLevel.FULL_FETCH || cacheHit) { handleError(ExceptionWithNoStacktrace("Encoded image is null.")) return } } else if (!newResult.isValid) { handleError(ExceptionWithNoStacktrace("Encoded image is not valid.")) return } } if (!updateDecodeJob(newResult, status)) { return } val isPlaceholder = statusHasFlag(status, IS_PLACEHOLDER) if (isLast || isPlaceholder || producerContext.isIntermediateResultExpected) { jobScheduler.scheduleJob() } } override fun onProgressUpdateImpl(progress: Float) { super.onProgressUpdateImpl(progress * 0.99f) } public override fun onFailureImpl(t: Throwable) { handleError(t) } public override fun onCancellationImpl() { handleCancellation() } /** Updates the decode job. */ protected open fun updateDecodeJob(ref: EncodedImage?, @Consumer.Status status: Int): Boolean = jobScheduler.updateJob(ref, status) /** Performs the decode synchronously. */ private fun doDecode( encodedImage: EncodedImage, @Consumer.Status status: Int, lastScheduledScanNumber: Int ) { // do not run for partial results of anything except JPEG var status = status if (encodedImage.imageFormat !== DefaultImageFormats.JPEG && isNotLast(status)) { return } if (isFinished || !EncodedImage.isValid(encodedImage)) { return } val imageFormat = encodedImage.imageFormat val imageFormatStr = if (imageFormat != null) { imageFormat.name } else { "unknown" } val encodedImageSize = encodedImage.width.toString() + "x" + encodedImage.height val sampleSize = encodedImage.sampleSize.toString() val isLast = isLast(status) val isLastAndComplete = isLast && !statusHasFlag(status, IS_PARTIAL_RESULT) val isPlaceholder = statusHasFlag(status, IS_PLACEHOLDER) val resizeOptions = producerContext.imageRequest.resizeOptions val requestedSizeStr = if (resizeOptions != null) { resizeOptions.width.toString() + "x" + resizeOptions.height } else { "unknown" } try { val queueTime = jobScheduler.queuedTime val requestUri = producerContext.imageRequest.sourceUri.toString() val length = if (isLastAndComplete || isPlaceholder) encodedImage.size else getIntermediateImageEndOffset(encodedImage) val quality = if (isLastAndComplete || isPlaceholder) ImmutableQualityInfo.FULL_QUALITY else qualityInfo producerListener.onProducerStart(producerContext, PRODUCER_NAME) var image: CloseableImage? = null try { image = try { internalDecode(encodedImage, length, quality) } catch (e: DecodeException) { val failedEncodedImage = e.encodedImage FLog.w( TAG, "%s, {uri: %s, firstEncodedBytes: %s, length: %d}", e.message, requestUri, failedEncodedImage.getFirstBytesAsHexString( DECODE_EXCEPTION_MESSAGE_NUM_HEADER_BYTES), failedEncodedImage.size) throw e } if (encodedImage.sampleSize != EncodedImage.DEFAULT_SAMPLE_SIZE) { status = status or IS_RESIZING_DONE } } catch (e: Exception) { val extraMap = getExtraMap( image, queueTime, quality, isLast, imageFormatStr, encodedImageSize, requestedSizeStr, sampleSize) producerListener.onProducerFinishWithFailure(producerContext, PRODUCER_NAME, e, extraMap) handleError(e) return } val extraMap = getExtraMap( image, queueTime, quality, isLast, imageFormatStr, encodedImageSize, requestedSizeStr, sampleSize) producerListener.onProducerFinishWithSuccess(producerContext, PRODUCER_NAME, extraMap) setImageExtras(encodedImage, image, lastScheduledScanNumber) handleResult(image, status) } finally { EncodedImage.closeSafely(encodedImage) } } /** This does not close the encodedImage * */ private fun internalDecode( encodedImage: EncodedImage, length: Int, quality: QualityInfo ): CloseableImage? { val recover = reclaimMemoryRunnable != null && recoverFromDecoderOOM.get() val image = try { imageDecoder.decode(encodedImage, length, quality, imageDecodeOptions) } catch (e: OutOfMemoryError) { if (!recover) { throw e } // NULLSAFE_FIXME[Nullable Dereference] reclaimMemoryRunnable!!.run() System.gc() // Now we retry only once imageDecoder.decode(encodedImage, length, quality, imageDecodeOptions) } return image } private fun setImageExtras( encodedImage: EncodedImage, image: CloseableImage?, lastScheduledScanNumber: Int ) { producerContext.setExtra(ProducerContext.ExtraKeys.ENCODED_WIDTH, encodedImage.width) producerContext.setExtra(ProducerContext.ExtraKeys.ENCODED_HEIGHT, encodedImage.height) producerContext.setExtra(ProducerContext.ExtraKeys.ENCODED_SIZE, encodedImage.size) if (image is CloseableBitmap) { val bitmap = image.underlyingBitmap val config = if (bitmap == null) null else bitmap.config producerContext.setExtra("bitmap_config", config.toString()) } image?.setImageExtras(producerContext.extras) producerContext.setExtra(ProducerContext.ExtraKeys.LAST_SCAN_NUMBER, lastScheduledScanNumber) } private fun getExtraMap( image: CloseableImage?, queueTime: Long, quality: QualityInfo, isFinal: Boolean, imageFormatName: String, encodedImageSize: String, requestImageSize: String, sampleSize: String ): Map<String, String>? { if (!producerListener.requiresExtraMap(producerContext, PRODUCER_NAME)) { return null } val queueStr = queueTime.toString() val qualityStr = quality.isOfGoodEnoughQuality.toString() val finalStr = isFinal.toString() var nonFatalErrorStr: String? = null if (image != null) { val nonFatalError = image.extras[NON_FATAL_DECODE_ERROR] if (nonFatalError != null) { nonFatalErrorStr = nonFatalError.toString() } } return if (image is CloseableStaticBitmap) { val bitmap = image.underlyingBitmap checkNotNull(bitmap) val sizeStr = bitmap.width.toString() + "x" + bitmap.height // We need this because the copyOf() utility method doesn't have a proper overload method // for all these parameters val tmpMap: MutableMap<String, String> = HashMap(8) tmpMap[EXTRA_BITMAP_SIZE] = sizeStr tmpMap[JobScheduler.QUEUE_TIME_KEY] = queueStr tmpMap[EXTRA_HAS_GOOD_QUALITY] = qualityStr tmpMap[EXTRA_IS_FINAL] = finalStr tmpMap[ENCODED_IMAGE_SIZE] = encodedImageSize tmpMap[EXTRA_IMAGE_FORMAT_NAME] = imageFormatName tmpMap[REQUESTED_IMAGE_SIZE] = requestImageSize tmpMap[SAMPLE_SIZE] = sampleSize tmpMap[EXTRA_BITMAP_BYTES] = bitmap.byteCount.toString() + "" if (nonFatalErrorStr != null) { tmpMap[NON_FATAL_DECODE_ERROR] = nonFatalErrorStr } ImmutableMap.copyOf(tmpMap) } else { val tmpMap: MutableMap<String, String> = HashMap(7) tmpMap[JobScheduler.QUEUE_TIME_KEY] = queueStr tmpMap[EXTRA_HAS_GOOD_QUALITY] = qualityStr tmpMap[EXTRA_IS_FINAL] = finalStr tmpMap[ENCODED_IMAGE_SIZE] = encodedImageSize tmpMap[EXTRA_IMAGE_FORMAT_NAME] = imageFormatName tmpMap[REQUESTED_IMAGE_SIZE] = requestImageSize tmpMap[SAMPLE_SIZE] = sampleSize if (nonFatalErrorStr != null) { tmpMap[NON_FATAL_DECODE_ERROR] = nonFatalErrorStr } ImmutableMap.copyOf(tmpMap) } } /** * Finishes if not already finished and `shouldFinish` is specified. * * If just finished, the intermediate image gets released. */ private fun maybeFinish(shouldFinish: Boolean) { synchronized(this@ProgressiveDecoder) { if (!shouldFinish || isFinished) { return } consumer.onProgressUpdate(1.0f) isFinished = true } jobScheduler.clearJob() } /** Notifies consumer of new result and finishes if the result is final. */ private fun handleResult(decodedImage: CloseableImage?, @Consumer.Status status: Int) { val decodedImageRef: CloseableReference<CloseableImage>? = closeableReferenceFactory.create(decodedImage) try { maybeFinish(isLast(status)) consumer.onNewResult(decodedImageRef, status) } finally { CloseableReference.closeSafely(decodedImageRef) } } /** Notifies consumer about the failure and finishes. */ private fun handleError(t: Throwable) { maybeFinish(true) consumer.onFailure(t) } /** Notifies consumer about the cancellation and finishes. */ private fun handleCancellation() { maybeFinish(true) consumer.onCancellation() } protected abstract fun getIntermediateImageEndOffset(encodedImage: EncodedImage): Int protected abstract val qualityInfo: QualityInfo init { val job = JobRunnable { encodedImage, status -> if (encodedImage != null) { val request = producerContext.imageRequest producerContext.setExtra( ProducerContext.ExtraKeys.IMAGE_FORMAT, encodedImage.imageFormat.name) encodedImage.source = request.sourceUri?.toString() if (downsampleEnabled || !statusHasFlag(status, IS_RESIZING_DONE)) { if (downsampleEnabledForNetwork || !UriUtil.isNetworkUri(request.sourceUri)) { encodedImage.sampleSize = DownsampleUtil.determineSampleSize( request.rotationOptions, request.resizeOptions, encodedImage, maxBitmapSize) } } if (producerContext.imagePipelineConfig.experiments.downsampleIfLargeBitmap) { maybeIncreaseSampleSize(encodedImage) } doDecode(encodedImage, status, lastScheduledScanNumber) } } jobScheduler = JobScheduler(executor, job, imageDecodeOptions.minDecodeIntervalMs) producerContext.addCallbacks( object : BaseProducerContextCallbacks() { override fun onIsIntermediateResultExpectedChanged() { if (producerContext.isIntermediateResultExpected) { jobScheduler.scheduleJob() } } override fun onCancellationRequested() { if (decodeCancellationEnabled) { handleCancellation() } } }) } } private inner class LocalImagesProgressiveDecoder( consumer: Consumer<CloseableReference<CloseableImage>>, producerContext: ProducerContext, decodeCancellationEnabled: Boolean, maxBitmapSize: Int ) : ProgressiveDecoder(consumer, producerContext, decodeCancellationEnabled, maxBitmapSize) { @Synchronized override fun updateDecodeJob( encodedImage: EncodedImage?, @Consumer.Status status: Int ): Boolean = if (isNotLast(status)) { false } else { super.updateDecodeJob(encodedImage, status) } override fun getIntermediateImageEndOffset(encodedImage: EncodedImage): Int = encodedImage.size override val qualityInfo: QualityInfo protected get() = ImmutableQualityInfo.of(0, false, false) } private inner class NetworkImagesProgressiveDecoder( consumer: Consumer<CloseableReference<CloseableImage>>, producerContext: ProducerContext, val progressiveJpegParser: ProgressiveJpegParser, val progressiveJpegConfig: ProgressiveJpegConfig, decodeCancellationEnabled: Boolean, maxBitmapSize: Int ) : ProgressiveDecoder(consumer, producerContext, decodeCancellationEnabled, maxBitmapSize) { @Synchronized override fun updateDecodeJob( encodedImage: EncodedImage?, @Consumer.Status status: Int ): Boolean { if (encodedImage == null) { return false } val ret = super.updateDecodeJob(encodedImage, status) if ((isNotLast(status) || statusHasFlag(status, IS_PARTIAL_RESULT)) && !statusHasFlag(status, IS_PLACEHOLDER) && EncodedImage.isValid(encodedImage) && encodedImage.imageFormat === DefaultImageFormats.JPEG) { if (!this.progressiveJpegParser.parseMoreData(encodedImage)) { return false } val scanNum = this.progressiveJpegParser.bestScanNumber if (scanNum <= lastScheduledScanNumber) { // We have already decoded this scan, no need to do so again return false } if (scanNum < progressiveJpegConfig.getNextScanNumberToDecode(lastScheduledScanNumber) && !this.progressiveJpegParser.isEndMarkerRead) { // We have not reached the minimum scan set by the configuration and there // are still more scans to be read (the end marker is not reached) return false } lastScheduledScanNumber = scanNum } return ret } override fun getIntermediateImageEndOffset(encodedImage: EncodedImage): Int = this.progressiveJpegParser.bestScanEndOffset override val qualityInfo: QualityInfo protected get() = progressiveJpegConfig.getQualityInfo(this.progressiveJpegParser.bestScanNumber) init { lastScheduledScanNumber = 0 } } companion object { const val PRODUCER_NAME = "DecodeProducer" private const val DECODE_EXCEPTION_MESSAGE_NUM_HEADER_BYTES = 10 // In recent versions of Android you cannot draw bitmap that is bigger than 100MB bytes: // https://web.archive.org/web/20191017003524/https://chromium.googlesource.com/android_tools/+/refs/heads/master/sdk/sources/android-25/android/view/DisplayListCanvas.java private const val MAX_BITMAP_SIZE = 100 * 1_024 * 1_024 // 100 MB // keys for extra map const val EXTRA_BITMAP_SIZE = ProducerConstants.EXTRA_BITMAP_SIZE const val EXTRA_HAS_GOOD_QUALITY = ProducerConstants.EXTRA_HAS_GOOD_QUALITY const val EXTRA_IS_FINAL = ProducerConstants.EXTRA_IS_FINAL const val EXTRA_IMAGE_FORMAT_NAME = ProducerConstants.EXTRA_IMAGE_FORMAT_NAME const val EXTRA_BITMAP_BYTES = ProducerConstants.EXTRA_BYTES const val ENCODED_IMAGE_SIZE = ProducerConstants.ENCODED_IMAGE_SIZE const val REQUESTED_IMAGE_SIZE = ProducerConstants.REQUESTED_IMAGE_SIZE const val SAMPLE_SIZE = ProducerConstants.SAMPLE_SIZE const val NON_FATAL_DECODE_ERROR = ProducerConstants.NON_FATAL_DECODE_ERROR } }
mit
41a29de935dcbb7978f7982fe9e3c6ff
38.36553
176
0.666971
4.898657
false
false
false
false
faruktoptas/FancyShowCaseView
app/src/main/java/me/toptas/fancyshowcasesample/MainActivity.kt
1
13985
/* * Copyright (c) 2018. Faruk Toptaş * * 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 me.toptas.fancyshowcasesample import android.content.Intent import android.graphics.Color import android.os.Bundle import android.text.Html import android.text.Spanned import android.util.TypedValue import android.view.Gravity import android.view.Menu import android.view.MenuItem import android.view.View import android.view.animation.Animation import android.view.animation.AnimationUtils import android.widget.ImageView import android.widget.RelativeLayout import android.widget.Toast import androidx.core.content.res.ResourcesCompat import kotlinx.android.synthetic.main.activity_main.* import me.toptas.fancyshowcase.FancyShowCaseView import me.toptas.fancyshowcase.FocusShape import me.toptas.fancyshowcase.listener.DismissListener import me.toptas.fancyshowcase.listener.OnViewInflateListener class MainActivity : BaseActivity() { private var mFancyShowCaseView: FancyShowCaseView? = null private var mClickListener: View.OnClickListener = View.OnClickListener { mFancyShowCaseView?.hide() mFancyShowCaseView = null } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btn_simple.setOnClickListener { FancyShowCaseView.Builder(this) .title("No Focus") .build() .show() } //Shows a FancyShowCaseView that focus on a vie btn_focus.setOnClickListener { FancyShowCaseView.Builder(this) .focusOn(it) .title("Circle Focus on View") .build() .show() } // Set title with spanned val spanned: Spanned = Html.fromHtml("<font color='#ff0000'>Spanned</font>") btn_spanned.setOnClickListener { FancyShowCaseView.Builder(this) .focusOn(it) .title(spanned) .enterAnimation(null) .exitAnimation(null) .enableAutoTextPosition() .build() .show() } // Set title size btn_title_size.setOnClickListener { FancyShowCaseView.Builder(this) .focusOn(it) .title("Title size") .titleSize(48, TypedValue.COMPLEX_UNIT_SP) .build() .show() } // Set title typeface btn_title_typeface.setOnClickListener { val typeface = ResourcesCompat.getFont(this, R.font.pacifico_regular) FancyShowCaseView.Builder(this) .focusOn(it) .title("Title typeface") .typeface(typeface) .build() .show() } //Shows a FancyShowCaseView with rounded rect focus shape btn_rounded_rect.setOnClickListener { FancyShowCaseView.Builder(this) .focusOn(it) .focusShape(FocusShape.ROUNDED_RECTANGLE) .roundRectRadius(90) .title("Focus on View") .build() .show() } //Shows a FancyShowCaseView that focus on a view btn_focus_dismiss_on_focus_area.setOnClickListener { if (FancyShowCaseView.isVisible(this)) { Toast.makeText(this, "Clickable button", Toast.LENGTH_SHORT).show() FancyShowCaseView.hideCurrent(this) } else { FancyShowCaseView.Builder(this) .focusOn(findViewById(R.id.btn_focus_dismiss_on_focus_area)) .enableTouchOnFocusedView(true) .title("Focus on View \n(dismiss on focus area)") .build() .show() } } //Shows a FancyShowCaseView with rounded rect focus shape btn_rounded_rect_dismiss_on_focus_area.setOnClickListener { if (FancyShowCaseView.isVisible(this)) { Toast.makeText(this, "Clickable button", Toast.LENGTH_SHORT).show() FancyShowCaseView.hideCurrent(this) } else { FancyShowCaseView.Builder(this) .focusOn(it) .focusShape(FocusShape.ROUNDED_RECTANGLE) .focusRectSizeFactor(1.5) .roundRectRadius(90) .enableTouchOnFocusedView(true) .title("Focus on View \n(dismiss on focus area)") .build() .show() } } //Shows FancyShowCaseView with focusCircleRadiusFactor 1.5 and title gravity btn_focus2.setOnClickListener { FancyShowCaseView.Builder(this) .focusOn(it) .focusCircleRadiusFactor(1.5) .title("Focus on View with larger circle") .focusBorderColor(Color.GREEN) .titleStyle(0, Gravity.BOTTOM or Gravity.CENTER) .build() .show() } //Shows FancyShowCaseView at specific position (round rectangle shape) btn_rect_position.setOnClickListener { FancyShowCaseView.Builder(this) .title("Focus on larger view") .focusRectAtPosition(260, 85, 480, 80) .focusRectSizeFactor(1.5) .roundRectRadius(60) .dismissListener(object : DismissListener { override fun onDismiss(id: String?) { } override fun onSkipped(id: String?) { } }) .build() .show() } //Shows a FancyShowCaseView that focuses on a larger view btn_focus_rect_color.setOnClickListener { FancyShowCaseView.Builder(this) .focusOn(it) .title("Focus on larger view") .focusShape(FocusShape.ROUNDED_RECTANGLE) .roundRectRadius(50) .focusBorderSize(5) .focusBorderColor(Color.RED) .titleStyle(0, Gravity.TOP) .build() .show() } //Shows a FancyShowCaseView that has dashed rectangle border btn_focus_dashed_rect.setOnClickListener { FancyShowCaseView.Builder(this) .focusOn(it) .title("Focus with dashed line") .focusShape(FocusShape.ROUNDED_RECTANGLE) .roundRectRadius(50) .focusBorderSize(10) .focusDashedBorder(10.0f, 10.0f) .focusBorderColor(Color.RED) .titleStyle(0, Gravity.TOP) .build() .show() } //Shows a FancyShowCaseView that has dashed circle border btn_focus_dashed_circle.setOnClickListener { FancyShowCaseView.Builder(this) .focusOn(it) .title("Focus with dashed line") .focusShape(FocusShape.CIRCLE) .roundRectRadius(50) .focusBorderSize(10) .focusDashedBorder(10.0f, 10.0f) .focusBorderColor(Color.RED) .titleStyle(0, Gravity.TOP) .build() .show() } //Shows a FancyShowCaseView with background color and title style btn_background_color.setOnClickListener { FancyShowCaseView.Builder(this) .focusOn(it) .backgroundColor(Color.parseColor("#AAff0000")) .title("Background color and title style can be changed") .titleStyle(R.style.MyTitleStyle, Gravity.TOP or Gravity.CENTER) .build() .show() } //Shows a FancyShowCaseView with border color btn_border_color.setOnClickListener { FancyShowCaseView.Builder(this) .focusOn(it) .title("Focus border color can be changed") .titleStyle(R.style.MyTitleStyle, Gravity.TOP or Gravity.CENTER) .focusBorderColor(Color.GREEN) .focusBorderSize(10) .build() .show() } //Shows a FancyShowCaseView with custom enter, exit animations btn_anim.setOnClickListener { val enterAnimation = AnimationUtils.loadAnimation(this, R.anim.slide_in_top) val exitAnimation = AnimationUtils.loadAnimation(this, R.anim.slide_out_bottom) val fancyShowCaseView = FancyShowCaseView.Builder(this) .focusOn(it) .title("Custom enter and exit animations.") .enterAnimation(enterAnimation) .exitAnimation(exitAnimation) .build() fancyShowCaseView.show() exitAnimation.setAnimationListener(object : Animation.AnimationListener { override fun onAnimationStart(animation: Animation) { } override fun onAnimationEnd(animation: Animation) { fancyShowCaseView.removeView() } override fun onAnimationRepeat(animation: Animation) { } }) } //Shows a FancyShowCaseView view custom view inflation btn_custom_view.setOnClickListener { mFancyShowCaseView = FancyShowCaseView.Builder(this) .focusOn(it) .enableTouchOnFocusedView(true) .customView(R.layout.layout_my_custom_view_arrow, object : OnViewInflateListener { override fun onViewInflated(view: View) { val image = (view as RelativeLayout).findViewById<ImageView>(R.id.iv_custom_view) val params = image.layoutParams as RelativeLayout.LayoutParams image.post { params.leftMargin = mFancyShowCaseView!!.focusCenterX - image.width / 2 params.topMargin = mFancyShowCaseView!!.focusCenterY - mFancyShowCaseView!!.focusHeight - image.height image.layoutParams = params } view.findViewById<View>(R.id.btn_action_1).setOnClickListener(mClickListener) } }) .closeOnTouch(false) .build() mFancyShowCaseView?.show() } btn_custom_view2.setOnClickListener { startActivity(Intent(this, AnimatedActivity::class.java)) } btn_no_anim.setOnClickListener { mFancyShowCaseView = FancyShowCaseView.Builder(this) .focusOn(it) .disableFocusAnimation() .build() mFancyShowCaseView?.show() } btn_queue.setOnClickListener { startActivity(Intent(this, QueueActivity::class.java)) } btn_custom_queue.setOnClickListener { startActivity(Intent(this, CustomQueueActivity::class.java)) } btn_another_activity.setOnClickListener { startActivity(Intent(this, SecondActivity::class.java)) } btn_recycler_view.setOnClickListener { startActivity(Intent(this, RecyclerViewActivity::class.java)) } btn_scaled_view.setOnClickListener { FancyShowCaseView.Builder(this) .focusOn(it) .title("Focus on Scaled View") .build() .show() } btn_focus_delay.setOnClickListener { FancyShowCaseView.Builder(this) .title("Focus with delay") .focusOn(it) .delay(1000) .build() .show() } btn_show_once.setOnClickListener { FancyShowCaseView.Builder(this) .focusOn(it) .title("Clean storage to see this again") .showOnce("id0") .build() .show() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_main, menu) return super.onCreateOptionsMenu(menu) } /** * Shows a FancyShowCaseView that focuses to ActionBar items * * @param item actionbar item to focus * @return true */ override fun onOptionsItemSelected(item: MenuItem): Boolean { FancyShowCaseView.Builder(this) .focusOn(findViewById(item.itemId)) .title("Focus on Actionbar items") .build() .show() return true } }
apache-2.0
2ed95fb1307faeb42727d5777d9649ef
36.092838
134
0.539188
5.086941
false
false
false
false
nsnikhil/Notes
app/src/main/java/com/nrs/nsnik/notes/data/NoteEntity.kt
1
5231
/* * Notes Copyright (C) 2018 Nikhil Soni * This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. * This is free software, and you are welcome to redistribute it * under certain conditions; type `show c' for details. * * The hypothetical commands `show w' and `show c' should show the appropriate * parts of the General Public License. Of course, your program's commands * might be different; for a GUI interface, you would use an "about box". * * You should also get your employer (if you work as a programmer) or school, * if any, to sign a "copyright disclaimer" for the program, if necessary. * For more information on this, and how to apply and follow the GNU GPL, see * <http://www.gnu.org/licenses/>. * * The GNU General Public License does not permit incorporating your program * into proprietary programs. If your program is a subroutine library, you * may consider it more useful to permit linking proprietary applications with * the library. If this is what you want to do, use the GNU Lesser General * Public License instead of this License. But first, please read * <http://www.gnu.org/philosophy/why-not-lgpl.html>. */ package com.nrs.nsnik.notes.data import androidx.room.Entity import androidx.room.Ignore import androidx.room.PrimaryKey import androidx.room.TypeConverters import com.nrs.nsnik.notes.model.CheckListObject import com.twitter.serial.serializer.CollectionSerializers import com.twitter.serial.serializer.CoreSerializers import com.twitter.serial.serializer.ObjectSerializer import com.twitter.serial.serializer.SerializationContext import com.twitter.serial.stream.SerializerInput import com.twitter.serial.stream.SerializerOutput import java.io.Serializable import java.util.* @Entity open class NoteEntity : Serializable { @PrimaryKey(autoGenerate = true) var uid: Int = 0 var title: String? = null @Ignore var noteContent: String? = null var fileName: String? = null var folderName: String? = null var pinned: Int = 0 var locked: Int = 0 @TypeConverters(DateConverter::class) var dateModified: Date? = null var color: String? = null @Ignore var imageList: List<String>? = null @Ignore var audioList: List<String>? = null @Ignore var checkList: List<CheckListObject>? = null @Ignore var hasReminder: Int = 0 companion object { @Ignore val SERIALIZER: ObjectSerializer<NoteEntity> = NoteEntityObjectSerializer() class NoteEntityObjectSerializer : ObjectSerializer<NoteEntity>() { override fun serializeObject(context: SerializationContext, output: SerializerOutput<out SerializerOutput<*>>, noteEntity: NoteEntity) { val abc = DateConverter() output.writeInt(noteEntity.uid) output.writeString(noteEntity.title) output.writeString(noteEntity.noteContent) output.writeString(noteEntity.fileName) output.writeString(noteEntity.folderName) output.writeInt(noteEntity.pinned) output.writeInt(noteEntity.locked) output.writeObject(SerializationContext.ALWAYS_RELEASE, noteEntity.dateModified, CoreSerializers.DATE) output.writeString(noteEntity.color) output.writeObject(SerializationContext.ALWAYS_RELEASE, noteEntity.imageList, CollectionSerializers.getListSerializer(CoreSerializers.STRING)) output.writeObject(SerializationContext.ALWAYS_RELEASE, noteEntity.audioList, CollectionSerializers.getListSerializer(CoreSerializers.STRING)) output.writeObject(SerializationContext.ALWAYS_RELEASE, noteEntity.checkList, CollectionSerializers.getListSerializer(CheckListObject.SERIALIZER)) output.writeInt(noteEntity.hasReminder) } override fun deserializeObject(context: SerializationContext, input: SerializerInput, versionNumber: Int): NoteEntity? { val noteEntity = NoteEntity() noteEntity.uid = input.readInt() noteEntity.title = input.readString() noteEntity.noteContent = input.readString() noteEntity.fileName = input.readString() noteEntity.folderName = input.readString() noteEntity.pinned = input.readInt() noteEntity.locked = input.readInt() noteEntity.dateModified = input.readObject(SerializationContext.ALWAYS_RELEASE, CoreSerializers.DATE) noteEntity.color = input.readString() noteEntity.imageList = input.readObject(SerializationContext.ALWAYS_RELEASE, CollectionSerializers.getListSerializer(CoreSerializers.STRING)) noteEntity.audioList = input.readObject(SerializationContext.ALWAYS_RELEASE, CollectionSerializers.getListSerializer(CoreSerializers.STRING)) noteEntity.checkList = input.readObject(SerializationContext.ALWAYS_RELEASE, CollectionSerializers.getListSerializer(CheckListObject.SERIALIZER)) noteEntity.hasReminder = input.readInt() return noteEntity } } } }
gpl-3.0
cd81b80d6f068a6753c5da8f8d4782b2
44.094828
162
0.70866
4.755455
false
false
false
false
jayrave/falkon
falkon-iterable-utils/src/main/kotlin/com/jayrave/falkon/iterables/IterableBackedIterable.kt
1
854
package com.jayrave.falkon.iterables /** * To expose items from an iterable in a different form */ class IterableBackedIterable<T, out R> private constructor( private val iterable: Iterable<T>, private val transformer: (T) -> R) : Iterable<R> { override fun iterator(): Iterator<R> = IteratorBackedIterator() private inner class IteratorBackedIterator : Iterator<R> { private val iterator by lazy { iterable.iterator() } override fun hasNext() = iterator.hasNext() override fun next(): R = transformer.invoke(iterator.next()) } companion object { fun <T> create(iterable: Iterable<T>) = IterableBackedIterable(iterable, { it }) fun <T, R> create( iterable: Iterable<T>, transformer: (T) -> R ) = IterableBackedIterable(iterable, transformer) } }
apache-2.0
51f0d4a6442f4f29decad606c11a3b36
30.666667
88
0.651054
4.357143
false
false
false
false
the4thfloor/Msync
app/src/main/java/eu/the4thfloor/msync/ui/NotificationPermissionsActivity.kt
1
1865
/* * Copyright 2017 Ralph Bergmann * * 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 eu.the4thfloor.msync.ui import android.Manifest import android.app.Activity import android.content.pm.PackageManager import androidx.core.app.ActivityCompat import eu.the4thfloor.msync.utils.checkSelfPermission import eu.the4thfloor.msync.utils.createSyncJobs class NotificationPermissionsActivity : Activity() { override fun onStart() { super.onStart() // check calendar permissions if (checkSelfPermission(Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR), 0) } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { 0 -> { if (grantResults.size == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) { createSyncJobs(true) } } } finish() } }
apache-2.0
c9aa330a7c7cbb11de51ee0fa871aa6e
34.188679
142
0.695442
4.721519
false
false
false
false
arcao/Geocaching4Locus
app/src/main/java/com/arcao/geocaching4locus/update/UpdateActivity.kt
1
2721
package com.arcao.geocaching4locus.update import android.app.Activity import android.os.Bundle import com.arcao.geocaching4locus.R import com.arcao.geocaching4locus.authentication.LoginActivity import com.arcao.geocaching4locus.base.AbstractActionBarActivity import com.arcao.geocaching4locus.base.util.exhaustive import com.arcao.geocaching4locus.base.util.showLocusMissingError import com.arcao.geocaching4locus.base.util.withObserve import com.arcao.geocaching4locus.error.ErrorActivity import org.koin.androidx.viewmodel.ext.android.viewModel import timber.log.Timber class UpdateActivity : AbstractActionBarActivity() { private val viewModel by viewModel<UpdateViewModel>() private val loginActivity = registerForActivityResult(LoginActivity.Contract) { success -> if (success) { viewModel.processIntent(intent) } else { setResult(Activity.RESULT_CANCELED) finish() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel.progress.withObserve(this, ::handleProgress) viewModel.action.withObserve(this, ::handleAction) if (savedInstanceState == null) { viewModel.processIntent(intent) } } @Suppress("IMPLICIT_CAST_TO_ANY") fun handleAction(action: UpdateAction) { when (action) { UpdateAction.SignIn -> loginActivity.launch(null) is UpdateAction.Error -> { Timber.d("UpdateAction.Error intent: %s", intent) startActivity(action.intent) setResult(Activity.RESULT_CANCELED) finish() } is UpdateAction.Finish -> { Timber.d("UpdateAction.Finish intent: %s", intent) setResult(Activity.RESULT_OK, action.intent) finish() } UpdateAction.Cancel -> { setResult(Activity.RESULT_CANCELED) finish() } UpdateAction.LocusMapNotInstalled -> { showLocusMissingError() setResult(Activity.RESULT_CANCELED) finish() } UpdateAction.PremiumMembershipRequired -> { startActivity(ErrorActivity.IntentBuilder(this).message(R.string.error_premium_feature).build()) setResult(Activity.RESULT_CANCELED) finish() } }.exhaustive } override fun onProgressCancel(requestId: Int) { viewModel.cancelProgress() } companion object { const val PARAM_CACHE_ID = "cacheId" const val PARAM_SIMPLE_CACHE_ID = "simpleCacheId" } }
gpl-3.0
b2b3b4957cd779dd8aecdd27c9a72cf4
33.884615
112
0.639838
4.790493
false
false
false
false
FantAsylum/Floor--13
core/src/com/floor13/game/core/map/Map.kt
1
1484
package com.floor13.game.core.map import com.floor13.game.core.Item import com.floor13.game.core.creatures.Creature import com.floor13.game.core.Position class Map private constructor(val tiles: Array<Array<Tile>>) { constructor(width: Int, height: Int) : this(Array(width, { Array(height, { Ground() as Tile })})) val width: Int get() = tiles.size val height: Int get() = tiles.get(0)?.size ?: 0 private val exploredTiles = mutableSetOf<Position>() operator fun get(x: Int, y: Int) = tiles[x][y] operator fun get(position: Position) = tiles[position.x][position.y] operator fun set(x: Int, y: Int, tile: Tile) { tiles[x][y] = tile } operator fun set(position: Position, tile: Tile) { tiles[position.x][position.y] = tile } fun getTilesWithIndices() = tiles.withIndex().flatMap { (x, row) -> row.withIndex().map { (y, tile) -> TileWithIndices(x, y, tile) } } fun updateExplored(fov: List<Position>) { exploredTiles.addAll(fov) } fun isExplored(x: Int, y: Int) = exploredTiles.contains(Position(x, y)) } data class TileWithIndices(val x: Int, val y: Int, val tile: Tile) abstract class Tile( var creature: Creature? = null, val items: MutableList<Item> = mutableListOf() ) { open val isPassable = creature == null } class Ground: Tile() class Wall: Tile() { override val isPassable = false } class Door(var opened: Boolean = false): Tile() { override val isPassable: Boolean get() = opened && super.isPassable }
mit
0e39fbe9445b273ff1a192105d0442fe
25.035088
90
0.682615
3.085239
false
false
false
false
arcao/Geocaching4Locus
app/src/main/java/com/arcao/geocaching4locus/settings/widget/PoweredByPreference.kt
1
1659
package com.arcao.geocaching4locus.settings.widget import android.content.Context import android.util.AttributeSet import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.core.content.res.TypedArrayUtils import androidx.core.view.doOnLayout import androidx.core.view.updateLayoutParams import androidx.preference.Preference import androidx.preference.PreferenceViewHolder import androidx.preference.R class PoweredByPreference @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = TypedArrayUtils.getAttr( context, R.attr.preferenceStyle, android.R.attr.preferenceStyle ) ) : Preference(context, attrs, defStyleAttr) { init { widgetLayoutResource = com.arcao.geocaching4locus.R.layout.preference_powered_by_widget } override fun onBindViewHolder(holder: PreferenceViewHolder) { super.onBindViewHolder(holder) (holder.findViewById(android.R.id.icon) as? ImageView)?.let { imageView -> imageView.maxWidth = Integer.MAX_VALUE imageView.maxHeight = Integer.MAX_VALUE } (holder.findViewById(android.R.id.summary) as? TextView)?.let { textView -> textView.maxHeight = Integer.MAX_VALUE } holder.findViewById(android.R.id.title)?.let { view -> view.doOnLayout { holder.findViewById(android.R.id.widget_frame)?.updateLayoutParams<ViewGroup.MarginLayoutParams> { topMargin = view.height } } } } }
gpl-3.0
cc020b8cc62ab84ce311beb10ec409de
33.5625
114
0.682339
4.713068
false
false
false
false
coil-kt/coil
coil-base/src/main/java/coil/decode/DecodeResult.kt
1
934
package coil.decode import android.graphics.drawable.Drawable /** * The result of [Decoder.decode]. * * @param drawable The decoded [Drawable]. * @param isSampled 'true' if [drawable] is sampled (i.e. loaded into memory at less than its * original size). * * @see Decoder */ class DecodeResult( val drawable: Drawable, val isSampled: Boolean, ) { fun copy( drawable: Drawable = this.drawable, isSampled: Boolean = this.isSampled, ) = DecodeResult( drawable = drawable, isSampled = isSampled ) override fun equals(other: Any?): Boolean { if (this === other) return true return other is DecodeResult && drawable == other.drawable && isSampled == other.isSampled } override fun hashCode(): Int { var result = drawable.hashCode() result = 31 * result + isSampled.hashCode() return result } }
apache-2.0
2ca99011af901e4198d93c233f4a9f63
22.948718
93
0.616702
4.169643
false
false
false
false
siosio/kotlin-jsr352-jsl
src/main/kotlin/siosio/jsr352/jsl/Flow.kt
1
475
package siosio.jsr352.jsl class Flow(val name: String, val next: String? = null) : Element { private val elemens: ElementHolder = ElementHolder() internal fun addStep(step: Step) { elemens.add(step) } override fun build(): String { val sb = StringBuilder() sb.append("<flow id='${name}' ${next?.let { "next='${it}'" } ?: ""}>") sb.append(elemens.build()) sb.append("</flow>") return sb.toString() } }
mit
199e9128815f0b68162d4b916f1d125e
22.75
78
0.568421
3.769841
false
false
false
false
robedmo/vlc-android
vlc-android/src/org/videolan/vlc/gui/DiffUtilAdapter.kt
1
2381
package org.videolan.vlc.gui import android.support.annotation.WorkerThread import android.support.v7.util.DiffUtil import android.support.v7.widget.RecyclerView import android.util.Log import kotlinx.coroutines.experimental.android.UI import kotlinx.coroutines.experimental.channels.Channel import kotlinx.coroutines.experimental.channels.actor import kotlinx.coroutines.experimental.launch import kotlinx.coroutines.experimental.newSingleThreadContext import java.util.* abstract class DiffUtilAdapter<D, VH : RecyclerView.ViewHolder> : RecyclerView.Adapter<VH>() { protected var dataset: List<D> = listOf() @Volatile private var last = dataset private val diffCallback by lazy(LazyThreadSafetyMode.NONE) { createCB() } private val updateActor = actor<List<D>>(newSingleThreadContext("vlc-updater"), capacity = Channel.CONFLATED) { for (list in channel) internalUpdate(list) } protected abstract fun onUpdateFinished() fun update (list: List<D>) { last = list updateActor.offer(list) } @WorkerThread private suspend fun internalUpdate(list: List<D>) { Log.d("dua", "old list ${dataset.size} -> ${list.size}") val finalList = prepareList(list) val result = DiffUtil.calculateDiff(diffCallback.apply { update(dataset, finalList) }, detectMoves()) launch(UI) { dataset = finalList result.dispatchUpdatesTo(this@DiffUtilAdapter) onUpdateFinished() }.join() } open protected fun prepareList(list: List<D>) : List<D> = ArrayList(list) fun peekLast() = last fun hasPendingUpdates() = updateActor.isFull open protected fun detectMoves() = false open protected fun createCB() = DiffCallback<D>() open class DiffCallback<D> : DiffUtil.Callback() { lateinit var oldList: List<D> lateinit var newList: List<D> fun update(oldList: List<D>, newList: List<D>) { this.oldList = oldList this.newList = newList } override fun getOldListSize() = oldList.size override fun getNewListSize() = newList.size override fun areContentsTheSame(oldItemPosition : Int, newItemPosition : Int) = true override fun areItemsTheSame(oldItemPosition : Int, newItemPosition : Int) = oldList[oldItemPosition] == newList[newItemPosition] } }
gpl-2.0
710289e990ef8cc109b6e5fde68234f1
34.029412
137
0.698446
4.526616
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/discord/webhook/WebhookSendRepostExecutor.kt
1
4972
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.discord.webhook import dev.kord.common.entity.Snowflake import dev.kord.common.entity.optional.Optional import dev.kord.common.entity.optional.optional import dev.kord.rest.json.request.EmbedImageRequest import dev.kord.rest.json.request.EmbedRequest import dev.kord.rest.json.request.EmbedThumbnailRequest import dev.kord.rest.json.request.WebhookExecuteRequest import dev.kord.rest.service.RestClient import net.perfectdreams.loritta.common.utils.Color 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.discord.declarations.WebhookCommand import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options.LocalizedApplicationCommandOptions import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments import net.perfectdreams.loritta.cinnamon.discord.utils.toKordColor class WebhookSendRepostExecutor(loritta: LorittaBot) : CinnamonSlashCommandExecutor(loritta) { inner class Options : LocalizedApplicationCommandOptions(loritta) { val webhookUrl = string("webhook_url", WebhookCommand.I18N_PREFIX.Options.WebhookUrl.Text) val messageUrl = string("message_url", WebhookCommand.I18N_PREFIX.Options.MessageUrl.Text) val username = optionalString("username", WebhookCommand.I18N_PREFIX.Options.Username.Text) val avatarUrl = optionalString("avatar_url", WebhookCommand.I18N_PREFIX.Options.AvatarUrl.Text) val embedTitle = optionalString("embed_title", WebhookCommand.I18N_PREFIX.Options.EmbedTitle.Text) val embedDescription = optionalString("embed_description", WebhookCommand.I18N_PREFIX.Options.EmbedDescription.Text) val embedImageUrl = optionalString("embed_image_url", WebhookCommand.I18N_PREFIX.Options.EmbedImageUrl.Text) val embedThumbnailUrl = optionalString("embed_thumbnail_url", WebhookCommand.I18N_PREFIX.Options.EmbedThumbnailUrl.Text) val embedColor = optionalString("embed_color", WebhookCommand.I18N_PREFIX.Options.EmbedThumbnailUrl.Text) } override val options = Options() override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) { context.deferChannelMessageEphemerally() // Defer the message ephemerally because we don't want users looking at the webhook URL val webhookUrl = args[options.webhookUrl] val messageUrl = args[options.messageUrl] val username = args[options.username] val avatarUrl = args[options.avatarUrl] val matcher = WebhookCommandUtils.messageUrlRegex.find(messageUrl) ?: context.failEphemerally( context.i18nContext.get( WebhookCommand.I18N_PREFIX.InvalidMessageUrl ) ) val retrievedMessage = WebhookCommandUtils.getMessageOrFail(context, rest.channel, Snowflake(matcher.groupValues[2].toLong()), Snowflake(matcher.groupValues[3].toLong()) ) // Embed Stuff val embedTitle = args[options.embedTitle] val embedDescription = args[options.embedDescription] val embedImageUrl = args[options.embedImageUrl] val embedThumbnailUrl = args[options.embedThumbnailUrl] val embedColor = args[options.embedColor] WebhookCommandUtils.sendMessageViaWebhook(context, webhookUrl) { val embed = if (embedTitle != null || embedDescription != null || embedImageUrl != null || embedThumbnailUrl != null) { EmbedRequest( title = embedTitle?.optional() ?: Optional(), description = embedDescription?.optional() ?: Optional(), image = embedImageUrl?.let { EmbedImageRequest(it) }?.optional() ?: Optional(), thumbnail = embedThumbnailUrl?.let { EmbedThumbnailRequest(it) }?.optional() ?: Optional(), color = embedColor?.let { try { Color.fromString(it) } catch (e: IllegalArgumentException) { context.failEphemerally(context.i18nContext.get(WebhookCommand.I18N_PREFIX.InvalidEmbedColor)) } }?.toKordColor()?.optional() ?: Optional() ) } else null WebhookExecuteRequest( content = WebhookCommandUtils.cleanUpRetrievedMessageContent(retrievedMessage).optional(), username = username?.optional() ?: Optional(), avatar = avatarUrl?.optional() ?: Optional(), embeds = if (embed != null) listOf(embed).optional() else Optional() ) } } }
agpl-3.0
276158b176d0a0ceba474b103c7f4e4f
52.473118
136
0.708568
4.893701
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/utils/CachedUserInfo.kt
1
1401
package net.perfectdreams.loritta.morenitta.utils class CachedUserInfo( val id: Long, val name: String, val discriminator: String, val avatarId: String? ) { val avatarUrl: String? get() { return if (avatarId != null) { val extension = if (avatarId.startsWith("a_")) { // Avatares animados no Discord começam com "_a" "gif" } else { "png" } "https://cdn.discordapp.com/avatars/${id}/${avatarId}.${extension}" } else null } val defaultAvatarUrl: String get() { val avatarId = id % 5 return "https://cdn.discordapp.com/embed/avatars/$avatarId.png" } val effectiveAvatarUrl: String get() { return avatarUrl ?: defaultAvatarUrl } /** * Gets the effective avatar URL in the specified [format] * * @see getEffectiveAvatarUrl */ fun getEffectiveAvatarUrl(format: ImageFormat) = getEffectiveAvatarUrl(format, 128) /** * Gets the effective avatar URL in the specified [format] and [ímageSize] * * @see getEffectiveAvatarUrlInFormat */ fun getEffectiveAvatarUrl(format: ImageFormat, imageSize: Int): String { val extension = format.extension return if (avatarId != null) { "https://cdn.discordapp.com/avatars/$id/$avatarId.${extension}?size=$imageSize" } else { val avatarId = id % 5 // This only exists in png AND doesn't have any other sizes "https://cdn.discordapp.com/embed/avatars/$avatarId.png" } } }
agpl-3.0
d812d145d35d8fd86c484d71d5e254ed
24.454545
101
0.681916
3.614987
false
false
false
false
appnexus/mobile-sdk-android
tests/AppNexusSDKTestApp/app/src/androidTest/java/appnexus/com/appnexussdktestapp/functional/native/NativeImpressionTest.kt
1
11044
/* * Copyright 2019 APPNEXUS 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 appnexus.com.appnexussdktestapp.functional.native import android.content.Intent import android.os.Handler import android.os.Looper import android.view.View import android.view.View.GONE import android.view.View.VISIBLE import androidx.test.espresso.Espresso import androidx.test.espresso.IdlingPolicies import androidx.test.espresso.IdlingRegistry import androidx.test.espresso.assertion.ViewAssertions import androidx.test.espresso.matcher.ViewMatchers import androidx.test.rule.ActivityTestRule import androidx.test.runner.AndroidJUnit4 import appnexus.com.appnexussdktestapp.NativeImpressionActivity import appnexus.com.appnexussdktestapp.R import com.appnexus.opensdk.SDKSettings import com.appnexus.opensdk.XandrAd import com.microsoft.appcenter.espresso.Factory import org.hamcrest.CoreMatchers.not import org.junit.* import org.junit.Assert.assertFalse import org.junit.runner.RunWith import java.util.concurrent.TimeUnit /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class NativeImpressionTest { @get:Rule var reportHelper = Factory.getReportHelper() @Rule @JvmField var mActivityTestRule = ActivityTestRule(NativeImpressionActivity::class.java, false, false) lateinit var nativeActivity: NativeImpressionActivity @Before fun setup() { XandrAd.reset() XandrAd.init(123, null, false, null) IdlingPolicies.setMasterPolicyTimeout(1, TimeUnit.MINUTES) IdlingPolicies.setIdlingResourceTimeout(1, TimeUnit.MINUTES) var intent = Intent() mActivityTestRule.launchActivity(intent) nativeActivity = mActivityTestRule.activity IdlingRegistry.getInstance().register(nativeActivity.idlingResource) } @After fun destroy() { IdlingRegistry.getInstance().unregister(nativeActivity.idlingResource) reportHelper.label("Stopping App") } /* * Test for Default Native Impression firing method. * */ @Test fun nativeAdImpressionTest() { Assert.assertFalse(nativeActivity.didLogImpression) nativeActivity.shouldDisplay = false nativeActivity.triggerAdLoad("17982237", creativeId = 182426521) Thread.sleep(1000) var count = 0 while (count < 5 && !nativeActivity.didLogImpression) { Thread.sleep(1000) count++ } Assert.assertTrue(nativeActivity.didLogImpression) nativeActivity.changeVisibility(GONE) nativeActivity.attachNative() Thread.sleep(5000) Espresso.onView(ViewMatchers.withId(R.id.title)) .check(ViewAssertions.matches(not(ViewMatchers.isDisplayed()))) Espresso.onView(ViewMatchers.withId(R.id.description)) .check(ViewAssertions.matches(not(ViewMatchers.isDisplayed()))) Espresso.onView(ViewMatchers.withId(R.id.icon)) .check(ViewAssertions.matches(not(ViewMatchers.isDisplayed()))) Espresso.onView(ViewMatchers.withId(R.id.image)) .check(ViewAssertions.matches(not(ViewMatchers.isDisplayed()))) Assert.assertTrue(nativeActivity.didLogImpression) nativeActivity.changeVisibility(VISIBLE) Espresso.onView(ViewMatchers.withId(R.id.title)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Espresso.onView(ViewMatchers.withId(R.id.description)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Espresso.onView(ViewMatchers.withId(R.id.icon)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Espresso.onView(ViewMatchers.withId(R.id.image)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Assert.assertTrue(nativeActivity.didLogImpression) } /* * Test for Native Viewable Impression firing method. * */ @Test fun nativeAdImpressionTestViewableImpression() { XandrAd.init(10094, null, false, null) Assert.assertFalse(nativeActivity.didLogImpression) nativeActivity.shouldDisplay = false nativeActivity.triggerAdLoad("17982237", creativeId = 182426521) Thread.sleep(1000) Assert.assertFalse(nativeActivity.didLogImpression) nativeActivity.changeVisibility(GONE) nativeActivity.attachNative() Thread.sleep(5000) Espresso.onView(ViewMatchers.withId(R.id.title)) .check(ViewAssertions.matches(not(ViewMatchers.isDisplayed()))) Espresso.onView(ViewMatchers.withId(R.id.description)) .check(ViewAssertions.matches(not(ViewMatchers.isDisplayed()))) Espresso.onView(ViewMatchers.withId(R.id.icon)) .check(ViewAssertions.matches(not(ViewMatchers.isDisplayed()))) Espresso.onView(ViewMatchers.withId(R.id.image)) .check(ViewAssertions.matches(not(ViewMatchers.isDisplayed()))) Assert.assertFalse(nativeActivity.didLogImpression) // The Impression isn't fired yet nativeActivity.changeVisibility(VISIBLE) Espresso.onView(ViewMatchers.withId(R.id.title)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Espresso.onView(ViewMatchers.withId(R.id.description)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Espresso.onView(ViewMatchers.withId(R.id.icon)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Espresso.onView(ViewMatchers.withId(R.id.image)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) var count = 0 while (count < 5 && !nativeActivity.didLogImpression) { Thread.sleep(1000) count++ } Assert.assertTrue(nativeActivity.didLogImpression) } /* * Test for Native Impression firing method. * */ @Test fun nativeAdImpressionTestWithAttachedToDummyView() { Assert.assertFalse(nativeActivity.didLogImpression) nativeActivity.shouldDisplay = false nativeActivity.shouldAttachToDummy = true nativeActivity.triggerAdLoad("17982237", creativeId = 182426521) Thread.sleep(1000) var count = 0 while (count < 5 && !nativeActivity.didLogImpression) { Thread.sleep(1000) count++ } // New native method changes (BEGIN TO RENDER) Assert.assertTrue(nativeActivity.didLogImpression) nativeActivity.attachNative() Thread.sleep(1000) Espresso.onView(ViewMatchers.withId(R.id.title)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Assert.assertTrue(nativeActivity.didLogImpression) } /* * Test for Default Native Impression firing method. * */ @Test fun nativeAdImpressionTestAttachViewLater() { Assert.assertFalse(nativeActivity.didLogImpression) nativeActivity.shouldDisplay = false nativeActivity.triggerAdLoad("17982237", creativeId = 182426521) Assert.assertFalse(nativeActivity.didLogImpression) nativeActivity.attachNative() Thread.sleep(1000) Espresso.onView(ViewMatchers.withId(R.id.title)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Espresso.onView(ViewMatchers.withId(R.id.description)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Thread.sleep(5000) Espresso.onView(ViewMatchers.withId(R.id.icon)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Espresso.onView(ViewMatchers.withId(R.id.image)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Assert.assertTrue(nativeActivity.didLogImpression) } /* * Test for ONE_PX vs Default Native Impression firing method. * ONE_PX is preferred over Default Native Impression. * */ @Test fun nativeAdDefaultImpressionTestWhenOnePxEnabled() { XandrAd.init(10094, null, false, null) Assert.assertFalse(nativeActivity.didLogImpression) nativeActivity.shouldDisplay = false nativeActivity.triggerAdLoad("17982237", creativeId = 182426521) Assert.assertFalse(nativeActivity.didLogImpression) Handler(Looper.getMainLooper()).post({ nativeActivity.mainLayout.visibility = View.GONE }) nativeActivity.attachNative() Thread.sleep(1000) Assert.assertFalse(nativeActivity.didLogImpression) Handler(Looper.getMainLooper()).post({ nativeActivity.mainLayout.visibility = View.VISIBLE }) Thread.sleep(1000) Espresso.onView(ViewMatchers.withId(R.id.title)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Espresso.onView(ViewMatchers.withId(R.id.description)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Thread.sleep(5000) Espresso.onView(ViewMatchers.withId(R.id.icon)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Espresso.onView(ViewMatchers.withId(R.id.image)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Assert.assertTrue(nativeActivity.didLogImpression) } /* * Test for ONE_PX vs Default Native Impression firing method. * ONE_PX is preferred over Default Native Impression. * */ @Test fun nativeAdDefaultImpressionTestWhenOnePxEnabledWithAttachedView() { XandrAd.init(10094, null, false, null) Assert.assertFalse(nativeActivity.didLogImpression) nativeActivity.shouldDisplay = true nativeActivity.triggerAdLoad("17982237", creativeId = 182426521) Assert.assertFalse(nativeActivity.didLogImpression) Thread.sleep(1000) Espresso.onView(ViewMatchers.withId(R.id.title)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Espresso.onView(ViewMatchers.withId(R.id.description)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Assert.assertTrue(nativeActivity.didLogImpression) Thread.sleep(5000) Espresso.onView(ViewMatchers.withId(R.id.icon)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Espresso.onView(ViewMatchers.withId(R.id.image)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) } }
apache-2.0
1f426e36a52b83afa7c2330d676d10d2
40.208955
96
0.704998
4.52623
false
true
false
false
the-obsidian/ObsidianPermissions
src/main/kotlin/gg/obsidian/obsidianpermissions/models/GroupMembershipTable.kt
1
1824
package gg.obsidian.obsidianpermissions.models import gg.obsidian.obsidianpermissions.Plugin import org.bukkit.entity.Player import java.util.* class GroupMembershipTable(val plugin: Plugin) { fun getPlayerGroupMemberships(player: Player): Set<GroupMembership> { val results = HashSet<GroupMembership>() val query = plugin.database.find(GroupMembership::class.java) .where() .eq("playerUUID", player.uniqueId) .query() if (query != null) { results.addAll(query.findList()) } return results } fun getPlayerGroups(player: Player): Set<Group> { return getPlayerGroupMemberships(player) .map { plugin.configuration.getGroup(it.groupName) } .filter { it != null } .map { it!! } .toHashSet() } fun addPlayerToGroup(player: Player, groupName: String): Boolean { if (plugin.groupMembershipTable.playerInGroup(player, groupName)) return false val gm = GroupMembership( groupName, player.uniqueId, player.name ) plugin.database.save(gm) return true } fun removePlayerFromGroup(player: Player, groupName: String): Boolean { getPlayerGroupMemberships(player) .filter { it.groupName.equals(groupName) } .forEach { plugin.database.delete(it) } return true } fun playerInGroup(player: Player, groupName: String): Boolean { val query = plugin.database.find(GroupMembership::class.java) .where() .eq("playerUUID", player.uniqueId) .eq("groupName", groupName) .query() return query.findRowCount() > 0 } }
mit
ec2a6943df55c37780d2226218caf1e1
31
86
0.589364
4.8
false
false
false
false
rpandey1234/kotlin-koans
src/ii_collections/_15_AllAnyAndOtherPredicates.kt
1
1122
package ii_collections fun example2(list: List<Int>) { val isZero: (Int) -> Boolean = { it == 0 } val hasZero: Boolean = list.any(isZero) val allZeros: Boolean = list.all(isZero) val numberOfZeros: Int = list.count(isZero) val firstPositiveNumber: Int? = list.firstOrNull { it > 0 } } fun Customer.isFrom(city: City): Boolean { // Return true if the customer is from the given city return this.city == city } fun Shop.checkAllCustomersAreFrom(city: City): Boolean { // Return true if all customers are from the given city return customers.all { it.city == city } } fun Shop.hasCustomerFrom(city: City): Boolean { // Return true if there is at least one customer from the given city return customers.any { it.city == city } } fun Shop.countCustomersFrom(city: City): Int { // Return the number of customers from the given city return customers.count { it.city == city } } fun Shop.findAnyCustomerFrom(city: City): Customer? { // Return a customer who lives in the given city, or null if there is none return customers.firstOrNull { it.city == city } }
mit
52a672058060c326f49eb28acd957b87
27.769231
78
0.686275
3.80339
false
false
false
false
Shynixn/PetBlocks
petblocks-bukkit-plugin/src/test/java/unittest/DependencyServiceTest.kt
1
9571
package unittest import com.github.shynixn.petblocks.api.business.enumeration.PluginDependency import com.github.shynixn.petblocks.api.business.service.DependencyService import com.github.shynixn.petblocks.bukkit.logic.business.service.DependencyServiceImpl import com.github.shynixn.petblocks.core.logic.business.extension.cast import org.bukkit.Bukkit import org.bukkit.Server import org.bukkit.command.ConsoleCommandSender import org.bukkit.conversations.Conversation import org.bukkit.conversations.ConversationAbandonedEvent import org.bukkit.permissions.Permission import org.bukkit.permissions.PermissionAttachment import org.bukkit.permissions.PermissionAttachmentInfo import org.bukkit.plugin.Plugin import org.bukkit.plugin.PluginDescriptionFile import org.bukkit.plugin.PluginManager import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.mockito.Mockito import java.util.logging.Logger /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ class DependencyServiceTest { /** * Given * 2 installed plugin dependencies * When * checkForInstalledDependencies is called * Then * Message should be called once per dependency. */ @Test fun checkForInstalledDependencies_TwoInstalledDependencies_ShouldCallMessageOncePerDependency() { // Arrange val consoleSender = MockedConsoleSender() val classUnderTest = createWithDependencies(consoleSender) // Act classUnderTest.checkForInstalledDependencies() // Assert Assertions.assertEquals(4, consoleSender.messageCounter) } /** * Given * no installed plugin dependencies * When * checkForInstalledDependencies is called * Then * Message should not be called. */ @Test fun checkForInstalledDependencies_NoInstalledDependencies_ShouldNotCallMessage() { // Arrange val consoleSender = MockedConsoleSender() val classUnderTest = createWithDependencies(consoleSender, false) // Act classUnderTest.checkForInstalledDependencies() // Assert Assertions.assertEquals(0, consoleSender.messageCounter) } /** * Given * installed plugin dependencies * When * getVersion is called * Then * version should be returned. */ @Test fun getVersion_InstalledDependencies_ShouldReturnVersion() { // Arrange val version = "1.0" val dependency = PluginDependency.HEADDATABASE val classUnderTest = createWithDependencies() // Act val actualDependency = classUnderTest.getVersion(dependency) // Assert Assertions.assertEquals(version, actualDependency) } /** * Given * no installed plugin dependencies * When * getVersion is called * Then * Exception should be thrown. */ @Test fun getVersion_NoInstalledDependencies_ShouldThrowException() { // Arrange val dependency = PluginDependency.HEADDATABASE val classUnderTest = createWithDependencies(null, false) // Act Assertions.assertThrows(IllegalArgumentException::class.java) { classUnderTest.getVersion(dependency) } } /** * Given * installed plugin dependencies * When * isInstalled is called * Then * True should be returned. */ @Test fun isInstalled_InstalledDependencies_ShouldReturnTrue() { // Arrange val dependency = PluginDependency.HEADDATABASE val classUnderTest = createWithDependencies() // Act val actual = classUnderTest.isInstalled(dependency) // Assert Assertions.assertTrue(actual) } /** * Given * no installed plugin dependencies * When * isInstalled is called * Then * False should be returned. */ @Test fun isInstalled_InstalledDependencies_ShouldReturnFalse() { // Arrange val dependency = PluginDependency.HEADDATABASE val classUnderTest = createWithDependencies(null, false) // Act val actual = classUnderTest.isInstalled(dependency) // Assert Assertions.assertFalse(actual) } companion object { fun createWithDependencies(consoleCommandSender: ConsoleCommandSender? = null, shouldInstallDependencies: Boolean = true): DependencyService { val plugin = Mockito.mock(Plugin::class.java) val server = Mockito.mock(Server::class.java) val pluginManager = Mockito.mock(PluginManager::class.java) Mockito.`when`(server.logger).thenReturn(Logger.getGlobal()) if (Bukkit.getServer().cast<Server?>() == null) { Bukkit.setServer(server) } Mockito.`when`(plugin.server).thenReturn(server) Mockito.`when`(plugin.description).thenReturn(PluginDescriptionFile("Custom", "1.0", "")) Mockito.`when`(server.pluginManager).thenReturn(pluginManager) if (shouldInstallDependencies) { Mockito.`when`(pluginManager.getPlugin(Mockito.anyString())).thenReturn(plugin) } if (consoleCommandSender == null) { Mockito.`when`(server.consoleSender).thenReturn(MockedConsoleSender()) } else { Mockito.`when`(server.consoleSender).thenReturn(consoleCommandSender) } return DependencyServiceImpl(plugin) } } private class MockedConsoleSender : ConsoleCommandSender { override fun acceptConversationInput(p0: String) { throw IllegalArgumentException() } override fun sendRawMessage(p0: String) { throw IllegalArgumentException() } override fun removeAttachment(p0: PermissionAttachment) { throw IllegalArgumentException() } override fun hasPermission(p0: String): Boolean { throw IllegalArgumentException() } override fun hasPermission(p0: Permission): Boolean { throw IllegalArgumentException() } override fun abandonConversation(p0: Conversation) { throw IllegalArgumentException() } override fun abandonConversation(p0: Conversation, p1: ConversationAbandonedEvent) { throw IllegalArgumentException() } var messageCounter = 0 override fun sendMessage(p0: String) { messageCounter++ } override fun sendMessage(p0: Array<out String>) { throw IllegalArgumentException() } override fun beginConversation(p0: Conversation): Boolean { throw IllegalArgumentException() } override fun isPermissionSet(p0: String): Boolean { throw IllegalArgumentException() } override fun isPermissionSet(p0: Permission): Boolean { throw IllegalArgumentException() } override fun addAttachment(p0: Plugin, p1: String, p2: Boolean): PermissionAttachment { throw IllegalArgumentException() } override fun addAttachment(p0: Plugin): PermissionAttachment { throw IllegalArgumentException() } override fun addAttachment(p0: Plugin, p1: String, p2: Boolean, p3: Int): PermissionAttachment { throw IllegalArgumentException() } override fun addAttachment(p0: Plugin, p1: Int): PermissionAttachment { throw IllegalArgumentException() } override fun getName(): String { throw IllegalArgumentException() } override fun isOp(): Boolean { throw IllegalArgumentException() } override fun getEffectivePermissions(): MutableSet<PermissionAttachmentInfo> { throw IllegalArgumentException() } override fun isConversing(): Boolean { throw IllegalArgumentException() } override fun getServer(): Server { throw IllegalArgumentException() } override fun recalculatePermissions() { throw IllegalArgumentException() } override fun setOp(p0: Boolean) { throw IllegalArgumentException() } } }
apache-2.0
b0864527f3a1addcf32dbc014ff2f576
30.695364
150
0.661059
5.293695
false
true
false
false
Dreamersoul/FastHub
app/src/main/java/com/fastaccess/ui/modules/repos/extras/branches/BranchesFragment.kt
1
4107
package com.fastaccess.ui.modules.repos.extras.branches import android.content.Context import android.os.Bundle import android.support.v4.widget.SwipeRefreshLayout import android.view.View import com.fastaccess.R import com.fastaccess.data.dao.BranchesModel import com.fastaccess.helper.BundleConstant import com.fastaccess.helper.Bundler import com.fastaccess.provider.rest.loadmore.OnLoadMore import com.fastaccess.ui.adapter.BranchesAdapter import com.fastaccess.ui.base.BaseFragment import com.fastaccess.ui.modules.repos.extras.branches.pager.BranchesPagerListener import com.fastaccess.ui.widgets.StateLayout import com.fastaccess.ui.widgets.recyclerview.DynamicRecyclerView /** * Created by Kosh on 06 Jul 2017, 9:48 PM */ class BranchesFragment : BaseFragment<BranchesMvp.View, BranchesPresenter>(), BranchesMvp.View { val recycler: DynamicRecyclerView by lazy { view!!.findViewById<DynamicRecyclerView>(R.id.recycler) } val refresh: SwipeRefreshLayout by lazy { view!!.findViewById<SwipeRefreshLayout>(R.id.refresh) } val stateLayout: StateLayout by lazy { view!!.findViewById<StateLayout>(R.id.stateLayout) } private var onLoadMore: OnLoadMore<Boolean>? = null private var branchCallback: BranchesPagerListener? = null val adapter by lazy { BranchesAdapter(presenter.branches, presenter) } override fun onAttach(context: Context) { super.onAttach(context) if (parentFragment is BranchesPagerListener) { branchCallback = parentFragment as BranchesPagerListener } else branchCallback = context as BranchesPagerListener } override fun onDetach() { branchCallback = null super.onDetach() } override fun fragmentLayout(): Int = R.layout.small_grid_refresh_list override fun providePresenter(): BranchesPresenter = BranchesPresenter() override fun onNotifyAdapter(branches: ArrayList<BranchesModel>, page: Int) { hideProgress() if (page == 1) adapter.insertItems(branches) else adapter.addItems(branches) } override fun onBranchSelected(item: BranchesModel?) { branchCallback?.onItemSelect(item!!) } override fun getLoadMore(): OnLoadMore<Boolean> { if (onLoadMore == null) { onLoadMore = OnLoadMore(presenter) } return onLoadMore!! } override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) { getLoadMore().initialize(presenter.currentPage, presenter.previousTotal) stateLayout.setEmptyText(R.string.no_branches) refresh.setOnRefreshListener { presenter.onCallApi(1, null) } recycler.setEmptyView(stateLayout, refresh) stateLayout.setOnReloadListener { presenter.onCallApi(1, null) } recycler.adapter = adapter recycler.addOnScrollListener(getLoadMore()) recycler.addDivider() if (savedInstanceState == null) { presenter.onFragmentCreated(arguments) } } override fun showProgress(resId: Int) { refresh.isRefreshing = true stateLayout.showProgress() } override fun hideProgress() { refresh.isRefreshing = false stateLayout.hideProgress() stateLayout.showReload(adapter.itemCount) } override fun showMessage(titleRes: Int, msgRes: Int) { hideProgress() super.showMessage(titleRes, msgRes) } override fun showMessage(titleRes: String, msgRes: String) { hideProgress() super.showMessage(titleRes, msgRes) } override fun showErrorMessage(msgRes: String) { hideProgress() super.showErrorMessage(msgRes) } companion object { fun newInstance(login: String, repoId: String, branch: Boolean): BranchesFragment { val fragment = BranchesFragment() fragment.arguments = Bundler.start() .put(BundleConstant.ID, repoId) .put(BundleConstant.EXTRA, login) .put(BundleConstant.EXTRA_TYPE, branch) .end() return fragment } } }
gpl-3.0
ecbcad52c0cef36b71f28a720789f8f3
35.035088
106
0.696859
4.848878
false
false
false
false
jdinkla/groovy-java-ray-tracer
src/main/kotlin/net/dinkla/raytracer/samplers/Sampler.kt
1
6184
package net.dinkla.raytracer.samplers import net.dinkla.raytracer.math.Point2D import net.dinkla.raytracer.math.Point3D import net.dinkla.raytracer.math.Random import java.util.ArrayList class Sampler(protected var sampler: IGenerator, protected var numSamples: Int, protected var numSets: Int) { protected var shuffledIndices: ArrayList<Int> protected var samples: ArrayList<Point2D> protected var diskSamples: ArrayList<Point2D> protected var hemisphereSamples: ArrayList<Point3D> protected var sphereSamples: ArrayList<Point3D> protected var count: Int = 0 protected var jump: Int = 0 init { count = 0 jump = 0 shuffledIndices = ArrayList() diskSamples = ArrayList() hemisphereSamples = ArrayList() sphereSamples = ArrayList() setupShuffledIndices() samples = ArrayList() samples.ensureCapacity(numSamples * numSets) sampler.generateSamples(numSamples, numSets, samples) } fun setupShuffledIndices() { shuffledIndices = ArrayList() shuffledIndices.ensureCapacity(numSamples * numSets) // Create temporary array val indices = ArrayList<Int>() for (j in 0 until numSamples) { indices.add(j) } for (p in 0 until numSets) { Random.randomShuffle(indices) shuffledIndices.addAll(indices) // for (int j = 0; j < indices.size(); j++) { // shuffledIndices.add(indices.get(j)); // } } } fun shuffleSamples() { } fun sampleUnitSquare(): Point2D { if (count % numSamples == 0) { jump = Random.randInt(numSets) * numSamples } val index1 = jump + count++ % numSamples val index2 = jump + shuffledIndices[index1] return samples[index2] } fun sampleUnitDisk(): Point2D { if (count % numSamples == 0) { jump = Random.randInt(numSets) * numSamples } return diskSamples[jump + shuffledIndices[jump + count++ % numSamples]] } fun sampleHemisphere(): Point3D { if (count % numSamples == 0) { jump = Random.randInt(numSets) * numSamples } return hemisphereSamples[jump + shuffledIndices[jump + count++ % numSamples]] } fun sampleSphere(): Point3D { if (count % numSamples == 0) { jump = Random.randInt(numSets) * numSamples } return sphereSamples[jump + shuffledIndices[jump + count++ % numSamples]] } fun sampleOneSet(): Point2D { return samples[count++ % numSamples] } fun mapSamplesToUnitDisk() { val size = samples.size var r: Double var phi: Double diskSamples = ArrayList(size) for (p in samples) { val sp = Point2D(2.0 * p.x - 1.0, 2.0 * p.y - 1.0) if (sp.x > -sp.y) { // sectors 1 and 2 if (sp.x > sp.y) { // sector 1 r = sp.x phi = sp.y / sp.x } else { // sector 2 r = sp.y phi = 2 - sp.x / sp.y } } else { // sectors 3 and 4 if (sp.x < sp.y) { // sector 3 r = -sp.x phi = 4 + sp.y / sp.x } else { // sector 4 r = -sp.y if (sp.y != 0.0) // avoid division by zero at origin phi = 6 - sp.x / sp.y else phi = 0.0 } } phi *= Math.PI / 4.0 diskSamples.add(Point2D(r * Math.cos(phi), r * Math.sin(phi))) } } fun mapSamplesToHemiSphere(exp: Double) { val size = samples.size hemisphereSamples = ArrayList(numSamples * numSets) for (sample in samples) { val cos_phi = Math.cos(2.0 * Math.PI * sample.x) val sin_phi = Math.sin(2.0 * Math.PI * sample.x) val cos_theta = Math.pow(1.0 - sample.y, 1.0 / (exp + 1.0)) val sin_theta = Math.sqrt(1.0 - cos_theta * cos_theta) val pu = sin_theta * cos_phi val pv = sin_theta * sin_phi hemisphereSamples.add(Point3D(pu, pv, cos_theta)) } } fun mapSamplesToSphere() { var x: Double var y: Double var z: Double var r: Double var phi: Double sphereSamples = ArrayList(numSamples * numSets) for (j in 0 until numSamples * numSets) { val p = samples[j] z = 1.0 - 2.0 * p.x r = Math.sqrt(1.0 - z * z) phi = 2.0 * Math.PI * p.y x = r * Math.cos(phi) y = r * Math.sin(phi) sphereSamples.add(Point3D(x, y, z)) } } companion object { fun shuffleXCoordinates(numSamples: Int, numSets: Int, samples: MutableList<Point2D>) { for (p in 0 until numSets) { for (i in 0 until numSamples - 1) { val target = Random.randInt(numSamples) + p * numSamples val source = i + p * numSamples + 1 val temp = samples[source].x samples[source] = Point2D(samples[target].x, samples[source].y) samples[target] = Point2D(temp, samples[target].y) } } } fun shuffleYCoordinates(numSamples: Int, numSets: Int, samples: MutableList<Point2D>) { for (p in 0 until numSets) { for (i in 0 until numSamples - 1) { val target = Random.randInt(numSamples) + p * numSamples val source = i + p * numSamples + 1 val temp = samples[i + p * numSamples + 1].y samples[source] = Point2D(samples[source].x, samples[target].y) samples[target] = Point2D(samples[target].x, temp) } } } } }
apache-2.0
baca1a9fe310d2c8b0920cda665b6e07
32.79235
109
0.508732
4.10897
false
false
false
false
tmarsteel/compiler-fiddle
src/compiler/binding/expression/BoundMemberAccessExpression.kt
1
2973
/* * 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.binding.expression import compiler.ast.Executable import compiler.ast.expression.MemberAccessExpression import compiler.binding.BoundExecutable import compiler.binding.context.CTContext import compiler.binding.type.BaseTypeReference import compiler.reportings.Reporting class BoundMemberAccessExpression( override val context: CTContext, override val declaration: MemberAccessExpression, val valueExpression: BoundExpression<*>, val isNullSafeAccess: Boolean, val memberName: String ) : BoundExpression<MemberAccessExpression> { /** * The type of this expression. Is null before semantic anylsis phase 2 is finished; afterwards is null if the * type could not be determined or [memberName] denotes a function. */ override var type: BaseTypeReference? = null private set override val isGuaranteedToThrow = false // member accessor CAN throw, but must not ALWAYS do so override fun semanticAnalysisPhase1() = valueExpression.semanticAnalysisPhase1() override fun semanticAnalysisPhase2(): Collection<Reporting> { val reportings = mutableSetOf<Reporting>() reportings.addAll(valueExpression.semanticAnalysisPhase2()) val valueType = valueExpression.type if (valueType != null) { if (valueType.isNullable && !isNullSafeAccess) { reportings.add(Reporting.unsafeObjectTraversal(valueExpression, declaration.accessOperatorToken)) // TODO: set the type of this expression nullable } else if (!valueType.isNullable && isNullSafeAccess) { reportings.add(Reporting.superfluousSafeObjectTraversal(valueExpression, declaration.accessOperatorToken)) } } // TODO: resolve member // TODO: what about FQNs? return reportings } override fun findReadsBeyond(boundary: CTContext): Collection<BoundExecutable<Executable<*>>> { return valueExpression.findReadsBeyond(boundary) } override fun findWritesBeyond(boundary: CTContext): Collection<BoundExecutable<Executable<*>>> { return valueExpression.findWritesBeyond(boundary) } }
lgpl-3.0
56f6de8d3c077268c1b0fd438c7ba167
39.739726
122
0.730912
4.857843
false
false
false
false
google/chromeosnavigationdemo
app/src/main/java/com/emilieroberts/chromeosnavigationdemo/AdaptableDemoViewModel.kt
1
1386
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.emilieroberts.chromeosnavigationdemo import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class AdaptableDemoViewModel : ViewModel() { var inPhotoViewer: Boolean = false private val photoIdToShow: MutableLiveData<Int> = MutableLiveData() private val fileSourceSelected: MutableLiveData<FileSource> = MutableLiveData() fun setCurrentPhotoId(imageId: Int) { photoIdToShow.value = imageId } fun getCurrentPhotoId() = photoIdToShow fun setFileSource (fileSource: FileSource) { fileSourceSelected.value = fileSource } fun getFileSource(): MutableLiveData<FileSource> { if (fileSourceSelected.value == null) fileSourceSelected.value = FileSource.LOCAL return fileSourceSelected } }
apache-2.0
5ecc326723b74ed32f9d296526f8248f
32.02381
89
0.743146
4.589404
false
false
false
false
HerbLuo/shop-api
src/main/java/cn/cloudself/model/AppSliderEntity.kt
1
1004
package cn.cloudself.model import javax.persistence.* /** * @author HerbLuo * @version 1.0.0.d * * * change logs: * 2017/3/28 HerbLuo 首次创建 */ @Entity @Table(name = "app_slider", schema = "shop") data class AppSliderEntity( @get:Id @get:Column(name = "id", nullable = false) var id: Int = 0, @get:Basic @get:Column(name = "enabled", nullable = false) var enabled: Byte = 0, @get:Basic @get:Column(name = "imgSrc", nullable = false, length = 128) var imgSrc: String? = null, @get:Basic @get:Column(name = "itemId", nullable = true) var itemId: Int? = null, @get:Basic @get:Column(name = "link", nullable = true, length = 255) var link: String? = null, @get:Basic @get:Column(name = "category", nullable = true) var category: Int? = null, @get:Basic @get:Column(name = "shopId", nullable = true) var shopId: Int? = null )
mit
33f681e241ce454a1d547492694faa5b
25.918919
68
0.555221
3.376271
false
false
false
false
npryce/krouton
src/main/kotlin/com/natpryce/krouton/http4k/routing.kt
1
3577
package com.natpryce.krouton.http4k import com.natpryce.krouton.PathTemplate import com.natpryce.krouton.monitoredPath import com.natpryce.krouton.parse import com.natpryce.krouton.splitPath import com.natpryce.krouton.toUrlTemplate import org.http4k.core.Filter import org.http4k.core.HttpHandler import org.http4k.core.Method import org.http4k.core.NoOp import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.UriTemplate import org.http4k.core.then import org.http4k.routing.RoutedRequest import org.http4k.routing.RoutedResponse /** * A route might map a request and some data parsed from that request to a response. */ typealias Route<T> = (Request, T) -> Response? /** * The capability to describe its routing as URL templates (a subset of RFC 6570) */ interface ReportsUrlTemplates { fun urlTemplates(): List<String> } /** * A Krouton handler that dispatches to the first element of the `routes` that matches the request, * and invokes `handlerIfNoMatch` if none of them match. */ data class Router<in T, out ROUTE : Route<T>>( val routes: List<ROUTE>, val handlerIfNoMatch: (Request, T) -> Response ) : (Request, T) -> Response { override fun invoke(request: Request, t: T): Response = routes.firstNonNull { it(request, t) } ?: handlerIfNoMatch(request, t) } /** * Returns the URL templates of all `routes` if they can report their routing rule as a URL template */ fun <T, ROUTE> Router<T, ROUTE>.urlTemplates() where ROUTE : Route<T>, ROUTE : ReportsUrlTemplates = routes.flatMap { it.urlTemplates() } /** * A ResourceRouter is an HttpHandler that can route the request to one of its ResourceRoutes */ data class ResourceRouter(val router: Router<List<String>, ResourceRoute>) : HttpHandler, ReportsUrlTemplates { constructor(routes: List<ResourceRoute>, handlerIfNoMatch: HttpHandler) : this(Router(routes, { rq, _ -> handlerIfNoMatch(rq) })) override fun invoke(request: Request): Response { return router(request, splitPath(request.uri.path)) } override fun urlTemplates() = router.urlTemplates() } /** * Apply a filter to all path route handlers in an application */ fun ResourceRouter.withFilter(newFilter: Filter) = copy(router = router.copy(routes = router.routes.map { it.copy(filter = newFilter.then(it.filter)) })) /** * A ResourceRoute that uses Krouton PathTemplates to match paths. */ data class PathParsingRoute<T>( private val pathTemplate: PathTemplate<T>, private val handler: (Request, T) -> Response, internal val filter: Filter = Filter.NoOp ) : Route<List<String>>, ReportsUrlTemplates { override fun invoke(request: Request, path: List<String>): Response? = pathTemplate.parse(path)?.let { parsed -> val filteredHandler = filter { request -> handler(request, parsed) } val template = UriTemplate.from(pathTemplate.monitoredPath(parsed)) RoutedResponse(filteredHandler(RoutedRequest(request, template)), template) } override fun urlTemplates() = listOf(pathTemplate.toUrlTemplate()) } typealias ResourceRoute = PathParsingRoute<*> fun <T> methodHandler(requiredMethod: Method, handler: (Request, T) -> Response): (Request, T) -> Response? = fun(request: Request, t: T) = if (request.method == requiredMethod) handler(request, t) else null private inline fun <T, U> List<T>.firstNonNull(f: (T) -> U?): U? { forEach { t -> f(t)?.let { return it } } return null }
apache-2.0
7f9af083d554b3f857d4ca7a895a3e83
31.518182
109
0.704221
3.75341
false
false
false
false
wuseal/JsonToKotlinClass
src/main/kotlin/wu/seal/jsontokotlin/interceptor/annotations/logansquare/AddLoganSquareAnnotationInterceptor.kt
1
1317
package wu.seal.jsontokotlin.interceptor.annotations.logansquare import wu.seal.jsontokotlin.model.classscodestruct.Annotation import wu.seal.jsontokotlin.model.codeannotations.LoganSquarePropertyAnnotationTemplate import wu.seal.jsontokotlin.model.codeelements.KPropertyName import wu.seal.jsontokotlin.interceptor.IKotlinClassInterceptor import wu.seal.jsontokotlin.model.classscodestruct.KotlinClass import wu.seal.jsontokotlin.model.classscodestruct.DataClass class AddLoganSquareAnnotationInterceptor : IKotlinClassInterceptor<KotlinClass> { override fun intercept(kotlinClass: KotlinClass): KotlinClass { if (kotlinClass is DataClass) { val addLoganSquareAnnotationProperties = kotlinClass.properties.map { val camelCaseName = KPropertyName.makeLowerCamelCaseLegalName(it.originName) it.copy(annotations = LoganSquarePropertyAnnotationTemplate(it.originName).getAnnotations(),name = camelCaseName) } val classAnnotationString = "@JsonObject" val classAnnotation = Annotation.fromAnnotationString(classAnnotationString) return kotlinClass.copy(properties = addLoganSquareAnnotationProperties,annotations = listOf(classAnnotation)) } else { return kotlinClass } } }
gpl-3.0
1c5b50f85430e47e00290541a37dec35
40.15625
130
0.769932
5.310484
false
false
false
false
orbit/orbit
src/orbit-server/src/test/kotlin/orbit/server/AddressableManagerTests.kt
1
8182
/* Copyright (C) 2015 - 2020 Electronic Arts Inc. All rights reserved. This file is part of the Orbit Project <https://www.orbit.cloud>. See license in LICENSE. */ package orbit.server import io.kotlintest.shouldBe import io.kotlintest.shouldNotBe import io.micrometer.core.instrument.Metrics import io.micrometer.core.instrument.simple.SimpleMeterRegistry import kotlinx.coroutines.runBlocking import orbit.server.mesh.AddressableManager import orbit.server.mesh.ClusterManager import orbit.server.mesh.LeaseDuration import orbit.server.mesh.NodeDirectory import orbit.server.mesh.local.LocalAddressableDirectory import orbit.server.mesh.local.LocalNodeDirectory import orbit.shared.addressable.AddressableReference import orbit.shared.addressable.Key import orbit.shared.addressable.NamespacedAddressableReference import orbit.shared.mesh.NodeCapabilities import orbit.shared.mesh.NodeId import orbit.shared.mesh.NodeInfo import orbit.shared.mesh.NodeLease import orbit.shared.mesh.NodeStatus import orbit.util.time.Clock import orbit.util.time.Timestamp import org.junit.Before import org.junit.BeforeClass import org.junit.Test class AddressableManagerTests { lateinit var clusterManager: ClusterManager private val clock: Clock = Clock() private val nodeDirectory: NodeDirectory = LocalNodeDirectory(clock) private val addressableDirectory = LocalAddressableDirectory(clock) private lateinit var addressableManager: AddressableManager private fun join(namespace: String = "test", addressableType: String = "testActor"): NodeInfo { return runBlocking { clusterManager.joinCluster( namespace, NodeCapabilities(listOf(addressableType)), nodeStatus = NodeStatus.ACTIVE ) } } companion object { @BeforeClass @JvmStatic fun SetupClass() { Metrics.globalRegistry.add(SimpleMeterRegistry()) } } @Before fun BeforeTest() { initialize() } fun initialize(nodeLeaseDurationSeconds: Long = 10L) { val config = OrbitServerConfig(nodeLeaseDuration = LeaseDuration(nodeLeaseDurationSeconds)) clock.resetToNow() LocalNodeDirectory.clear() LocalAddressableDirectory.clear() clusterManager = ClusterManager(config, clock, nodeDirectory) addressableManager = AddressableManager( addressableDirectory, clusterManager, clock, config ) } private suspend fun iterateTest( test: suspend () -> Unit ) { repeat(100) { test() LocalAddressableDirectory.clear() } } @Test fun `Addressable is placed on available node`() { runBlocking { val address = AddressableReference("testActor", Key.StringKey("a")) val node = join("test") val placedNode = addressableManager.locateOrPlace("test", address) placedNode shouldBe node.id } } @Test fun `Addressable should be placed only on node in namespace`() { runBlocking { val address = AddressableReference("testActor", Key.StringKey("a")) val nodes = mapOf( 1 to join("test"), 2 to join("test2") ) iterateTest { addressableManager.locateOrPlace("test", address) shouldBe nodes[1]!!.id } } } @Test fun `Addressable should be placed only on node with matching capability`() { runBlocking { val address = AddressableReference("testActor", Key.StringKey("a")) val nodes = mapOf( 1 to join(addressableType = "testActor"), 2 to join(addressableType = "invalidActor") ) iterateTest { addressableManager.locateOrPlace("test", address) shouldBe nodes[1]!!.id } } } @Test fun `Addressable should not be placed on removed node`() { runBlocking { val address = AddressableReference("testActor", Key.StringKey("a")) val nodes = mapOf( 1 to join(), 2 to join() ) nodeDirectory.remove(nodes[1]!!.id) clusterManager.tick() iterateTest { addressableManager.locateOrPlace("test", address) shouldBe nodes[2]!!.id } } } @Test fun `Addressable should not be placed on a draining node`() { runBlocking { val address = AddressableReference("testActor", Key.StringKey("a")) val nodes = mapOf( 1 to join(), 2 to join() ) clusterManager.updateNode(nodes[1]!!.id) { it!!.copy( nodeStatus = NodeStatus.DRAINING ) } iterateTest { addressableManager.locateOrPlace("test", address) shouldBe nodes[2]!!.id } } } @Test fun `Addressable should be replaced from expired node`() { runBlocking { val address = AddressableReference("testActor", Key.StringKey("a")) val nodes = mapOf( 1 to join(), 2 to join() ) clusterManager.updateNode(nodes[1]!!.id) { it!!.copy( lease = NodeLease.expired ) } iterateTest { addressableManager.locateOrPlace("test", address) shouldBe nodes[2]!!.id } } } @Test fun `Ineligible nodes are not included in placement`() { runBlocking { val address = AddressableReference("testActor", Key.StringKey("a")) val nodes = mapOf( 1 to join("test"), 2 to join("test"), 3 to join("test") ) iterateTest { addressableManager.locateOrPlace("test", address, listOf(nodes[2]!!.id, nodes[3]!!.id)) shouldBe nodes[1]!!.id } } } @Test fun `Abandoning an addressable lease should remove it from addressable directory`() { runBlocking { val address = AddressableReference("testActor", Key.StringKey("a")) val node = join("test") addressableManager.locateOrPlace("test", address) addressableDirectory.get(NamespacedAddressableReference("test", address)) shouldNotBe null addressableManager.abandonLease(address, node.id) shouldBe true addressableDirectory.get(NamespacedAddressableReference("test", address)) shouldBe null } } @Test fun `Abandoning an addressable lease not assigned to node is ignored`() { runBlocking { val address = AddressableReference("testActor", Key.StringKey("a")) join("test") addressableManager.locateOrPlace("test", address) val node2 = join("test") addressableManager.abandonLease(address, node2.id) shouldBe false } } @Test fun `Abandoning a non-existant addressable lease is ignored`() { runBlocking { val address = AddressableReference("testActor", Key.StringKey("a")) addressableManager.abandonLease(address, NodeId("node", "test")) shouldBe false } } @Test fun `Abandoning an expired lease doesn't remove from directory`() { runBlocking { val address = AddressableReference("testActor", Key.StringKey("a")) join("test") addressableManager.locateOrPlace("test", address) val reference = NamespacedAddressableReference("test", address) val lease = addressableDirectory.get(reference)!! addressableDirectory.compareAndSet(reference, lease, lease.copy(expiresAt = Timestamp(0, 0))) addressableManager.abandonLease(address, NodeId("node", "test")) shouldBe false addressableDirectory.get(reference) shouldNotBe null } } }
bsd-3-clause
3e6c407a73d157c942535dd82bb1a824
31.59761
126
0.606331
4.952785
false
true
false
false
laurencegw/jenjin
jenjin-core/src/main/kotlin/com/binarymonks/jj/core/utils/NamedArray.kt
1
1319
package com.binarymonks.jj.core.utils import com.badlogic.gdx.utils.Array import com.badlogic.gdx.utils.ObjectMap class NamedArray<T> : Array<T>() { private val nameMap: ObjectMap<String, T> = ObjectMap() fun add(name: String, item: T) { add(item) nameMap.put(name, item) } fun get(name: String): T? { return nameMap[name] } fun removeName(name: String): Boolean { val removed = nameMap.remove(name) return removeValue(removed, true) } override fun removeAll(array: Array<out T>?, identity: Boolean): Boolean { return super.removeAll(array, identity) } override fun removeValue(value: T, identity: Boolean): Boolean { removeFromMap(value) return super.removeValue(value, identity) } override fun clear() { super.clear() } override fun pop(): T { val popped = super.pop() removeFromMap(popped) return popped } override fun removeIndex(index: Int) : T{ val removed = super.removeIndex(index) removeFromMap(removed) return removed } private fun removeFromMap(value: T) { for (entry in nameMap) { if (entry.value == value) { nameMap.remove(entry.key) } } } }
apache-2.0
4f22dfa3b20a0766f314c9239619bdb5
22.157895
78
0.595148
3.99697
false
false
false
false