content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package handlers import communication.CommunicationProtos class SubmitRequestHandler(private val taskId: Int, private val waitDependentTask: (taskId: Int) -> Long?) { fun handle(request: CommunicationProtos.SubmitTask): Long? { val task: Task = getTask(request) ?: return null return calculate(task) } private fun calculate(task: Task): Long { var a = task.a var b = task.b var p = task.p var m = task.m var n = task.n while (n-- > 0) { b = (a * p + b) % m; a = b; } return a } private fun getTask(request: CommunicationProtos.SubmitTask): Task? { try { val a: Long = waitAndGet(request.task.a) val b: Long = waitAndGet(request.task.b) val p: Long = waitAndGet(request.task.p) val m: Long = waitAndGet(request.task.m) val n: Long = request.task.n return Task(a, b, p, m, n) } catch(e: RuntimeException) { println("Failed to wait dependent parameters") return null } } private fun waitAndGet(param: CommunicationProtos.Task.Param): Long { if (param.hasValue()) { return param.value } val result: Long = waitDependentTask(param.dependentTaskId) ?: throw RuntimeException("Dependent task waiting failed") return result } } data class Task(val a: Long, val b: Long, val p: Long, val m: Long, val n: Long)
csc/2016/vsv_1/src/handlers/SubmitRequestHandler.kt
549338969
/* * Copyright 2022 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.players.bukkit.command.profile import com.rpkit.chat.bukkit.irc.RPKIRCService import com.rpkit.core.command.RPKCommandExecutor import com.rpkit.core.command.result.* import com.rpkit.core.command.sender.RPKCommandSender import com.rpkit.core.service.Services import com.rpkit.players.bukkit.RPKPlayersBukkit import com.rpkit.players.bukkit.command.result.NoProfileSelfFailure import com.rpkit.players.bukkit.command.result.NotAPlayerFailure import com.rpkit.players.bukkit.profile.RPKProfile import com.rpkit.players.bukkit.profile.RPKProfileService import com.rpkit.players.bukkit.profile.irc.RPKIRCNick import com.rpkit.players.bukkit.profile.irc.RPKIRCProfile import com.rpkit.players.bukkit.profile.irc.RPKIRCProfileService import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfile import java.util.concurrent.CompletableFuture import java.util.logging.Level /** * Account link IRC command. * Links an IRC account to the current player. */ class ProfileLinkIRCCommand(private val plugin: RPKPlayersBukkit) : RPKCommandExecutor { class InvalidIRCNickFailure : CommandFailure() class IRCProfileAlreadyLinkedFailure(val ircProfile: RPKIRCProfile) : CommandFailure() override fun onCommand(sender: RPKCommandSender, args: Array<out String>): CompletableFuture<CommandResult> { if (sender !is RPKMinecraftProfile) { sender.sendMessage(plugin.messages.notFromConsole) return CompletableFuture.completedFuture(NotAPlayerFailure()) } if (!sender.hasPermission("rpkit.players.command.profile.link.irc")) { sender.sendMessage(plugin.messages.noPermissionProfileLinkIrc) return CompletableFuture.completedFuture(NoPermissionFailure("rpkit.players.command.profile.link.irc")) } if (args.isEmpty()) { sender.sendMessage(plugin.messages.profileLinkIrcUsage) return CompletableFuture.completedFuture(IncorrectUsageFailure()) } val nick = RPKIRCNick(args[0]) val ircService = Services[RPKIRCService::class.java] if (ircService == null) { sender.sendMessage(plugin.messages.noIrcService) return CompletableFuture.completedFuture(MissingServiceFailure(RPKIRCService::class.java)) } if (!ircService.isOnline(nick)) { sender.sendMessage(plugin.messages.profileLinkIrcInvalidNick) return CompletableFuture.completedFuture(InvalidIRCNickFailure()) } val profile = sender.profile if (profile !is RPKProfile) { sender.sendMessage(plugin.messages.noProfileSelf) return CompletableFuture.completedFuture(NoProfileSelfFailure()) } val profileService = Services[RPKProfileService::class.java] if (profileService == null) { sender.sendMessage(plugin.messages.noProfileService) return CompletableFuture.completedFuture(MissingServiceFailure(RPKProfileService::class.java)) } val ircProfileService = Services[RPKIRCProfileService::class.java] if (ircProfileService == null) { sender.sendMessage(plugin.messages.noIrcProfileService) return CompletableFuture.completedFuture(MissingServiceFailure(RPKIRCProfileService::class.java)) } return ircProfileService.getIRCProfile(nick).thenApplyAsync { ircProfile -> if (ircProfile != null && ircProfile.profile is RPKProfile) { sender.sendMessage(plugin.messages.profileLinkIrcInvalidAlreadyLinked) return@thenApplyAsync IRCProfileAlreadyLinkedFailure(ircProfile) } if (ircProfile == null) { ircProfileService.createIRCProfile(profile, nick).join() } else { ircProfile.profile = profile ircProfileService.updateIRCProfile(ircProfile).join() } sender.sendMessage(plugin.messages.profileLinkIrcValid) return@thenApplyAsync CommandSuccess }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to link IRC profile", exception) throw exception } } }
bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/command/profile/ProfileLinkIRCCommand.kt
3282095474
package net.jselby.kotgb.cpu.interpreter import net.jselby.kotgb.Gameboy import net.jselby.kotgb.cpu.CPU import net.jselby.kotgb.cpu.CPUExecutor /** * A reference CPU interpreter for the Gameboy. */ class Interpreter : CPUExecutor() { override fun execute(gameboy: Gameboy, state: CPU, approxInstructions: Int) : Int { val registers = state.registers var cycles = 0 for (i in 0 .. approxInstructions - 1) { state.before() val instructionPos = registers.pc // Read instruction at point var rawInstruction = gameboy.ram.readByte(registers.pc.toLong()).toInt() and 0xFF val is2Byte = rawInstruction == 0xCB // Check for 2-byte instructions if (is2Byte) { // Shift the previous instruction left, and add our new one rawInstruction = (rawInstruction shl 8) or (gameboy.ram.readByte(registers.pc.toLong() + 1).toInt() and 0xFF) } // Increment the program counter registers.pc += if (is2Byte) 2 else 1 // Invoke instruction val instCycles = InstructionSwitchboard.call(gameboy, rawInstruction, instructionPos) cycles += instCycles state.after(instCycles) } return cycles } }
core/src/main/kotlin/net/jselby/kotgb/cpu/interpreter/Interpreter.kt
67083586
/* Tickle Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.tickle.editor.resources import com.eclipsesource.json.JsonArray import com.eclipsesource.json.JsonObject import uk.co.nickthecoder.tickle.resources.ActorXAlignment import uk.co.nickthecoder.tickle.resources.ActorYAlignment import uk.co.nickthecoder.tickle.resources.Resources import uk.co.nickthecoder.tickle.resources.StageResource import uk.co.nickthecoder.tickle.util.JsonScene import uk.co.nickthecoder.tickle.util.JsonUtil import java.io.BufferedWriter import java.io.File import java.io.FileOutputStream import java.io.OutputStreamWriter class DesignJsonScene : JsonScene { constructor(scene: DesignSceneResource) : super(scene) constructor(file: File) : super(DesignSceneResource()) { load(file) } override fun createActorResource() = DesignActorResource() override fun load(jroot: JsonObject) { super.load(jroot) sceneResource as DesignSceneResource // Ensure it is the correct sub-class jroot.get("snapToGrid")?.let { val jgrid = it.asObject() with(sceneResource.snapToGrid) { enabled = jgrid.getBoolean("enabled", false) spacing.x = jgrid.getDouble("xSpacing", 50.0) spacing.y = jgrid.getDouble("ySpacing", 50.0) offset.x = jgrid.getDouble("xOffset", 0.0) offset.y = jgrid.getDouble("yOffset", 0.0) closeness.x = jgrid.getDouble("xCloseness", 10.0) closeness.y = jgrid.getDouble("yCloseness", 10.0) } //println("Loaded grid ${sceneResource.grid}") } jroot.get("snapToGuides")?.let { val jguides = it.asObject() with(sceneResource.snapToGuides) { enabled = jguides.getBoolean("enabled", true) closeness = jguides.getDouble("closeness", 10.0) jguides.get("x")?.let { val jx = it.asArray() jx.forEach { xGuides.add(it.asDouble()) } } jguides.get("y")?.let { val jy = it.asArray() jy.forEach { yGuides.add(it.asDouble()) } } } //println("Loaded guides ${sceneResource.guides}") } jroot.get("snapToOthers")?.let { val jothers = it.asObject() with(sceneResource.snapToOthers) { enabled = jothers.getBoolean("enabled", true) closeness.x = jothers.getDouble("xCloseness", 10.0) closeness.y = jothers.getDouble("yCloseness", 10.0) } } jroot.get("snapRotation")?.let { val jrotation = it.asObject() with(sceneResource.snapRotation) { enabled = jrotation.getBoolean("enabled", true) stepDegrees = jrotation.getDouble("step", 15.0) closeness = jrotation.getDouble("closeness", 15.0) } } } fun save(file: File) { sceneResource.file = Resources.instance.sceneDirectory.resolve(file) val jroot = JsonObject() jroot.add("director", sceneResource.directorString) JsonUtil.saveAttributes(jroot, sceneResource.directorAttributes, "directorAttributes") jroot.add("background", sceneResource.background.toHashRGB()) jroot.add("showMouse", sceneResource.showMouse) jroot.add("layout", sceneResource.layoutName) val jgrid = JsonObject() jroot.add("snapToGrid", jgrid) with((sceneResource as DesignSceneResource).snapToGrid) { jgrid.add("enabled", enabled == true) jgrid.add("xSpacing", spacing.x) jgrid.add("ySpacing", spacing.y) jgrid.add("xOffset", offset.x) jgrid.add("yOffset", offset.y) jgrid.add("xCloseness", closeness.x) jgrid.add("yCloseness", closeness.y) } val jguides = JsonObject() jroot.add("snapToGuides", jguides) with(sceneResource.snapToGuides) { jguides.add("enabled", enabled) jguides.add("closeness", closeness) val jx = JsonArray() xGuides.forEach { jx.add(it) } jguides.add("x", jx) val jy = JsonArray() yGuides.forEach { jy.add(it) } jguides.add("y", jy) } val jothers = JsonObject() jroot.add("snapToOthers", jothers) with(sceneResource.snapToOthers) { jothers.add("enabled", enabled) jothers.add("xCloseness", closeness.x) jothers.add("yCloseness", closeness.y) } val jrotation = JsonObject() jroot.add("snapRotation", jrotation) with(sceneResource.snapRotation) { jrotation.add("enabled", enabled) jrotation.add("step", stepDegrees) jrotation.add("closeness", closeness) } val jincludes = JsonArray() jroot.add("include", jincludes) sceneResource.includes.forEach { include -> jincludes.add(Resources.instance.sceneFileToPath(include)) } val jstages = JsonArray() jroot.add("stages", jstages) sceneResource.stageResources.forEach { stageName, stageResource -> jstages.add(saveStage(stageName, stageResource)) } BufferedWriter(OutputStreamWriter(FileOutputStream(file))).use { jroot.writeTo(it, Resources.instance.preferences.outputFormat.writerConfig) } } fun saveStage(stageName: String, stageResource: StageResource): JsonObject { val jstage = JsonObject() jstage.add("name", stageName) val jactors = JsonArray() jstage.add("actors", jactors) stageResource.actorResources.forEach { actorResource -> val costume = Resources.instance.costumes.find(actorResource.costumeName) val jactor = JsonObject() jactors.add(jactor) with(actorResource) { jactor.add("costume", costumeName) jactor.add("x", x) jactor.add("y", y) if (zOrder != costume?.zOrder) { // Only save zOrders which are NOT the default zOrder for the Costume. jactor.add("zOrder", zOrder) } textStyle?.let { textStyle -> jactor.add("text", text) if (textStyle.fontResource != costumeTextStyle?.fontResource) { jactor.add("font", Resources.instance.fontResources.findName(textStyle.fontResource)) } if (textStyle.halignment != costumeTextStyle?.halignment) { jactor.add("textHAlignment", textStyle.halignment.name) } if (textStyle.valignment != costumeTextStyle?.valignment) { jactor.add("textVAlignment", textStyle.valignment.name) } if (textStyle.color != costumeTextStyle?.color) { jactor.add("textColor", textStyle.color.toHashRGBA()) } if (textStyle.outlineColor != null && textStyle.outlineColor != costumeTextStyle?.outlineColor) { jactor.add("textOutlineColor", textStyle.outlineColor!!.toHashRGBA()) } } if (viewAlignmentX != ActorXAlignment.LEFT) { jactor.add("viewAlignmentX", viewAlignmentX.name) } if (viewAlignmentY != ActorYAlignment.BOTTOM) { jactor.add("viewAlignmentY", viewAlignmentY.name) } jactor.add("direction", direction.degrees) jactor.add("scaleX", scale.x) jactor.add("scaleY", scale.y) if (isSizable()) { jactor.add("sizeX", size.x) jactor.add("sizeY", size.y) jactor.add("alignmentX", sizeAlignment.x) jactor.add("alignmentY", sizeAlignment.y) } } JsonUtil.saveAttributes(jactor, actorResource.attributes) } return jstage } }
tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/resources/DesignJsonScene.kt
3530643086
package com.github.ajalt.clikt.parameters.types import com.github.ajalt.clikt.core.BadParameterValue import com.github.ajalt.clikt.parameters.arguments.argument import com.github.ajalt.clikt.parameters.options.option import com.github.ajalt.clikt.testing.TestCommand import com.github.ajalt.clikt.testing.parse import com.google.common.jimfs.Configuration import com.google.common.jimfs.Jimfs import io.kotest.assertions.throwables.shouldThrow import io.kotest.data.blocking.forAll import io.kotest.data.row import io.kotest.matchers.booleans.shouldBeFalse import io.kotest.matchers.booleans.shouldBeTrue import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldContain import org.junit.Rule import org.junit.contrib.java.lang.system.SystemOutRule import java.io.OutputStream import java.nio.file.FileSystem import java.nio.file.Files import kotlin.test.Test @Suppress("unused") @OptIn(ExperimentalStdlibApi::class) class OutputStreamTest { @get:Rule val stdout: SystemOutRule = SystemOutRule().enableLog() val fs: FileSystem = Jimfs.newFileSystem(Configuration.unix()) private fun OutputStream?.writeText(text: String) = this!!.bufferedWriter().use { it.write(text) } @Test fun `options can be outputStreams`() { class C : TestCommand() { val stream by option().outputStream(fileSystem = fs) override fun run_() { stream.writeText("bar") Files.readAllBytes(fs.getPath("foo")).decodeToString() shouldBe "bar" } } C().parse("--stream=foo") } @Test fun `passing explicit -`() { class C : TestCommand() { val stream by argument().outputStream(fileSystem = fs) override fun run_() { stream.writeText("foo") stdout.log shouldBe "foo" } } C().parse("-") } @Test fun `option and arg with defaultStdout`() { class C : TestCommand() { val option by option().outputStream(fileSystem = fs).defaultStdout() val stream by argument().outputStream(fileSystem = fs).defaultStdout() override fun run_() { option.writeText("foo") stdout.log shouldBe "foo" stdout.clearLog() stream.writeText("bar") stdout.log shouldBe "bar" } } C().parse("") } @Test fun `option outputStream is defaultStdout`() { class C : TestCommand() { val option by option().outputStream(fileSystem = fs).defaultStdout() override fun run_() { option.isCliktParameterDefaultStdout.shouldBeTrue() } } C().parse("") } @Test fun `option outputStream is not defaultStdout`() { class C : TestCommand() { val option by option().outputStream(fileSystem = fs) override fun run_() { option?.isCliktParameterDefaultStdout?.shouldBeFalse() } } C().parse("--option=foo") } @Test fun `argument outputStream is defaultStdout`() { class C : TestCommand() { val stream by argument().outputStream(fileSystem = fs).defaultStdout() override fun run_() { stream.isCliktParameterDefaultStdout.shouldBeTrue() } } C().parse("") } @Test fun `argument outputStream is not defaultStdout`() { class C : TestCommand() { val stream by argument().outputStream(fileSystem = fs) override fun run_() { stream.isCliktParameterDefaultStdout.shouldBeFalse() } } C().parse("foo") } @Test fun `createIfNotExist = false`() { class C : TestCommand(called = false) { val stream by argument().outputStream(createIfNotExist = false, fileSystem = fs) } shouldThrow<BadParameterValue> { C().parse("foo") }.message shouldContain "File \"foo\" does not exist" } @Test fun truncateExisting() = forAll( row(true, "baz"), row(false, "bar\nbaz") ) { truncateExisting, expected -> Files.write(fs.getPath("foo"), listOf("bar")) class C : TestCommand(called = true) { val stream by argument().outputStream(truncateExisting = truncateExisting, fileSystem = fs) override fun run_() { stream.writeText("baz") Files.readAllBytes(fs.getPath("foo")).decodeToString().replace("\r", "") shouldBe expected } } C().parse("foo") } }
clikt/src/jvmTest/kotlin/com/github/ajalt/clikt/parameters/types/OutputStreamTest.kt
1715816232
package com.beust.kobalt.internal import com.beust.kobalt.misc.Topological import com.beust.kobalt.misc.kobaltLog import org.assertj.core.api.Assertions.assertThat import org.testng.Assert import org.testng.annotations.Test import java.util.* class DynamicGraphTest { private fun <T> assertFreeNodesEquals(graph: DynamicGraph<T>, expected: Array<T>) { val h = HashSet(graph.freeNodes) val e = HashSet(expected.toList()) Assert.assertEquals(h, e) } private fun <T> createFactory(runNodes: ArrayList<T>, errorFunction: (T) -> Boolean) : IThreadWorkerFactory<T> { return object: IThreadWorkerFactory<T> { override fun createWorkers(nodes: Collection<T>): List<IWorker<T>> { val result = arrayListOf<IWorker<T>>() nodes.forEach { result.add(Worker(runNodes, it, errorFunction)) } return result } } } class Worker<T>(val runNodes: ArrayList<T>, val n: T, val errorFunction: (T) -> Boolean) : IWorker<T> { override val priority = 0 override val name: String get() = "[Worker " + runNodes.map { it.toString() }.joinToString(",") + "]" override fun call() : TaskResult2<T> { kobaltLog(2, "Running node $n") runNodes.add(n) return TaskResult2(errorFunction(n), value = n) } } @Test fun testExecutor() { DynamicGraph<String>().apply { addEdge("compile", "runApt") addEdge("compile", "generateVersion") val runNodes = arrayListOf<String>() val factory = createFactory(runNodes, { true }) DynamicGraphExecutor(this, factory).run() Assert.assertEquals(runNodes.size, 3) } } @Test fun transitive() { DynamicGraph<Int>().apply { addEdge(1, 2) addEdge(1, 3) addEdge(2, 4) addEdge(6, 7) assertThat(transitiveClosure(1)).isEqualTo(listOf(1, 2, 3, 4)) assertThat(transitiveClosure(2)).isEqualTo(listOf(2, 4)) assertThat(transitiveClosure(3)).isEqualTo(listOf(3)) assertThat(transitiveClosure(6)).isEqualTo(listOf(6, 7)) assertThat(transitiveClosure(7)).isEqualTo(listOf(7)) kobaltLog(1, "done") } } @Test private fun testExecutorWithSkip() { DynamicGraph<Int>().apply { // 2 and 3 depend on 1, 4 depend on 3, 10 depends on 4 // 3 will blow up, which should make 4 and 10 skipped addEdge(2, 1) addEdge(3, 1) addEdge(4, 3) addEdge(10, 4) addEdge(5, 2) arrayListOf<Int>().let { runNodes -> val factory = createFactory(runNodes, { n -> n != 3 }) val ex = DynamicGraphExecutor(this, factory) ex.run() Thread.`yield`() Assert.assertTrue(!runNodes.contains(4)) Assert.assertTrue(!runNodes.contains(10)) } } } @Test fun test8() { DynamicGraph<String>().apply { addEdge("b1", "a1") addEdge("b1", "a2") addEdge("b2", "a1") addEdge("b2", "a2") addEdge("c1", "b1") addEdge("c1", "b2") addNode("x") addNode("y") assertFreeNodesEquals(this, arrayOf("a1", "a2", "x", "y")) removeNode("a1") assertFreeNodesEquals(this, arrayOf("a2", "x", "y")) removeNode("a2") assertFreeNodesEquals(this, arrayOf("b1", "b2", "x", "y")) removeNode("b1") assertFreeNodesEquals(this, arrayOf("b2", "x", "y")) removeNode("b2") assertFreeNodesEquals(this, arrayOf("c1", "x", "y")) } } @Test fun test2() { DynamicGraph<String>().apply { addEdge("b1", "a1") addEdge("b1", "a2") addNode("x") assertFreeNodesEquals(this, arrayOf("a1", "a2", "x")) removeNode("a1") assertFreeNodesEquals(this, arrayOf("a2", "x")) removeNode("a2") assertFreeNodesEquals(this, arrayOf("b1", "x")) removeNode("b1") assertFreeNodesEquals(this, arrayOf("x")) } } @Test fun topologicalSort() { Topological<String>().apply { addEdge("b1", "a1") addEdge("b1", "a2") addEdge("b2", "a1") addEdge("b2", "a2") addEdge("c1", "b1") addEdge("c1", "b2") addNode("x") addNode("y") val sorted = sort() Assert.assertEquals(sorted, arrayListOf("a1", "a2", "x", "y", "b2", "b1", "c1")) } } @Test fun runAfter() { DynamicGraph<String>().apply { // a -> b // b -> c, d // e // Order should be: [c,d,e] [b] [a] addEdge("a", "b") addEdge("b", "c") addEdge("b", "d") addNode("e") kobaltLog(VERBOSE, dump()) Assert.assertEquals(freeNodes, setOf("c", "d", "e")) removeNode("c") kobaltLog(VERBOSE, dump()) Assert.assertEquals(freeNodes, setOf("d", "e")) removeNode("d") kobaltLog(VERBOSE, dump()) Assert.assertEquals(freeNodes, setOf("b", "e")) removeNode("e") kobaltLog(VERBOSE, dump()) Assert.assertEquals(freeNodes, setOf("b")) removeNode("b") kobaltLog(VERBOSE, dump()) Assert.assertEquals(freeNodes, setOf("a")) removeNode("a") kobaltLog(VERBOSE, dump()) Assert.assertTrue(freeNodes.isEmpty()) Assert.assertTrue(nodes.isEmpty()) } } @Test fun transitiveClosureGraphTest() { val graph = DynamicGraph<String>().apply { // a -> b // b -> c, d // e addEdge("a", "b") addEdge("b", "c") addEdge("b", "d") addNode("e") } val closure = DynamicGraph.transitiveClosureGraph("a", { s -> graph.childrenOf(s).toList() } ) assertThat(closure.value).isEqualTo("a") val ca = closure.children assertThat(ca.map { it.value }).isEqualTo(listOf("b")) val cb = ca[0].children assertThat(cb.map { it.value }).isEqualTo(listOf("d", "c")) } }
src/test/kotlin/com/beust/kobalt/internal/DynamicGraphTest.kt
801008751
package com.mizukami2005.mizukamitakamasa.qiitaclient import android.content.Context import android.support.annotation.IdRes import android.view.View import android.widget.Toast /** * Created by mizukamitakamasa on 2016/09/25. */ fun Context.toast(message: String, duration: Int = Toast.LENGTH_LONG) { Toast.makeText(this, message, duration).show() }
app/src/main/kotlin/com/mizukami2005/mizukamitakamasa/qiitaclient/extensions.kt
1888618537
package info.ccook.groundhog.splash import dagger.Subcomponent import dagger.android.AndroidInjector @Subcomponent interface SplashSubComponent : AndroidInjector<SplashActivity> { @Subcomponent.Builder abstract class Builder : AndroidInjector.Builder<SplashActivity>() }
app/src/main/java/info/ccook/groundhog/splash/SplashSubComponent.kt
635852355
package org.luxons.sevenwonders.engine.boards import org.luxons.sevenwonders.model.Age internal class Military( private val lostPointsPerDefeat: Int, private val wonPointsPerVictoryPerAge: Map<Age, Int>, ) { var nbShields = 0 private set val totalPoints get() = victoryPoints - lostPointsPerDefeat * nbDefeatTokens var victoryPoints = 0 private set var nbDefeatTokens = 0 private set internal fun addShields(nbShields: Int) { this.nbShields += nbShields } internal fun victory(age: Age) { val wonPoints = wonPointsPerVictoryPerAge[age] ?: throw UnknownAgeException(age) victoryPoints += wonPoints } internal fun defeat() { nbDefeatTokens++ } internal class UnknownAgeException(unknownAge: Age) : IllegalArgumentException(unknownAge.toString()) }
sw-engine/src/main/kotlin/org/luxons/sevenwonders/engine/boards/Military.kt
308045351
package com.bendev.networkmanager.data.network.result sealed class Result<out T: Any> { data class Success<out T : Any>(val data: T?) : Result<T>() data class Error(val error: NetworkError) : Result<Nothing>() override fun toString(): String = when (this) { is Success<*> -> "Success[data=$data]" is Error -> "Error[error=$error]" } }
app/src/main/java/com/bendev/networkmanager/data/network/result/Result.kt
361729019
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.social.profile import dev.kord.common.entity.TextInputStyle import io.github.netvl.ecoji.Ecoji import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import net.perfectdreams.discordinteraktions.common.builder.message.modify.InteractionOrFollowupMessageModifyBuilder import net.perfectdreams.discordinteraktions.common.modals.components.ModalArguments import net.perfectdreams.discordinteraktions.common.modals.components.ModalComponents import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.GuildApplicationCommandContext import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.styled import net.perfectdreams.loritta.cinnamon.discord.interactions.modals.CinnamonModalExecutor import net.perfectdreams.loritta.cinnamon.discord.interactions.modals.CinnamonModalExecutorDeclaration import net.perfectdreams.loritta.cinnamon.discord.interactions.modals.ModalContext import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.social.declarations.ProfileCommand import net.perfectdreams.loritta.cinnamon.discord.utils.ComponentExecutorIds import net.perfectdreams.loritta.cinnamon.discord.utils.getOrCreateUserProfile import net.perfectdreams.loritta.cinnamon.emotes.Emotes class ChangeAboutMeModalExecutor(loritta: LorittaBot) : CinnamonModalExecutor(loritta) { companion object : CinnamonModalExecutorDeclaration(ComponentExecutorIds.CHANGE_ABOUT_ME_MODAL_SUBMIT_EXECUTOR) { object Options : ModalComponents() { val aboutMe = textInput("about_me", TextInputStyle.Paragraph) } override val options = Options } override suspend fun onSubmit(context: ModalContext, args: ModalArguments) { val newAboutMe = args[options.aboutMe] val data = loritta.decodeDataFromComponentOnDatabase<ChangeAboutMeModalData>(context.data) val userSettings = context.loritta.pudding.users.getOrCreateUserProfile(context.user) .getProfileSettings() userSettings.setAboutMe(newAboutMe) context.sendEphemeralMessage { styled( context.i18nContext.get(ProfileCommand.ABOUT_ME_I18N_PREFIX.SuccessfullyChanged(newAboutMe)), Emotes.Tada ) } val guild = context.interaKTionsModalContext.discordInteraction.guildId.value?.let { loritta.kord.getGuild(it) } val result = loritta.profileDesignManager.createProfile( loritta, context.i18nContext, context.locale, loritta.profileDesignManager.transformUserToProfileUserInfoData(context.user), loritta.profileDesignManager.transformUserToProfileUserInfoData(context.user), guild?.let { loritta.profileDesignManager.transformGuildToProfileGuildInfoData(it) } ) val message = ProfileExecutor.createMessage(loritta, context.i18nContext, context.user, context.user, result) loritta.rest.interaction.modifyInteractionResponse( loritta.interaKTions.applicationId, data.data!!.interactionToken, InteractionOrFollowupMessageModifyBuilder().apply { message() }.toInteractionMessageResponseModifyBuilder() .toRequest() ) } }
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/social/profile/ChangeAboutMeModalExecutor.kt
2470019946
package org.owntracks.android.gms.location import com.google.android.gms.location.Priority import org.owntracks.android.location.LocationRequest fun LocationRequest.toGMSLocationRequest(): com.google.android.gms.location.LocationRequest { val gmsPriority = when (priority) { LocationRequest.PRIORITY_HIGH_ACCURACY -> Priority.PRIORITY_HIGH_ACCURACY LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY -> Priority.PRIORITY_BALANCED_POWER_ACCURACY LocationRequest.PRIORITY_LOW_POWER -> Priority.PRIORITY_LOW_POWER LocationRequest.PRIORITY_NO_POWER -> Priority.PRIORITY_LOW_POWER else -> Priority.PRIORITY_BALANCED_POWER_ACCURACY } val gmsLocationRequestBuilder = com.google.android.gms.location.LocationRequest.Builder(gmsPriority, interval) numUpdates?.run(gmsLocationRequestBuilder::setMaxUpdates) expirationDuration?.run(gmsLocationRequestBuilder::setDurationMillis) smallestDisplacement?.run(gmsLocationRequestBuilder::setMinUpdateDistanceMeters) fastestInterval?.run(gmsLocationRequestBuilder::setMinUpdateIntervalMillis) waitForAccurateLocation?.run(gmsLocationRequestBuilder::setWaitForAccurateLocation) return gmsLocationRequestBuilder.build() }
project/app/src/gms/java/org/owntracks/android/gms/location/LocationRequest.kt
2206726985
package eu.kanade.tachiyomi.ui.library import android.view.View import com.bumptech.glide.load.engine.DiskCacheStrategy import eu.davidea.flexibleadapter.FlexibleAdapter import eu.kanade.tachiyomi.data.glide.GlideApp import eu.kanade.tachiyomi.source.LocalSource import kotlinx.android.synthetic.main.catalogue_grid_item.* /** * Class used to hold the displayed data of a manga in the library, like the cover or the title. * All the elements from the layout file "item_catalogue_grid" are available in this class. * * @param view the inflated view for this holder. * @param adapter the adapter handling this holder. * @param listener a listener to react to single tap and long tap events. * @constructor creates a new library holder. */ class LibraryGridHolder( private val view: View, private val adapter: FlexibleAdapter<*> ) : LibraryHolder(view, adapter) { /** * Method called from [LibraryCategoryAdapter.onBindViewHolder]. It updates the data for this * holder with the given manga. * * @param item the manga item to bind. */ override fun onSetValues(item: LibraryItem) { // Update the title of the manga. title.text = item.manga.title // Update the unread count and its visibility. with(unread_text) { visibility = if (item.manga.unread > 0) View.VISIBLE else View.GONE text = item.manga.unread.toString() } // Update the download count and its visibility. with(download_text) { visibility = if (item.downloadCount > 0) View.VISIBLE else View.GONE text = item.downloadCount.toString() } //set local visibility if its local manga local_text.visibility = if(item.manga.source == LocalSource.ID) View.VISIBLE else View.GONE // Update the cover. GlideApp.with(view.context).clear(thumbnail) GlideApp.with(view.context) .load(item.manga) .diskCacheStrategy(DiskCacheStrategy.RESOURCE) .centerCrop() .into(thumbnail) } }
app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryGridHolder.kt
3768260916
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.handler import com.netflix.spinnaker.orca.ExecutionStatus.* import com.netflix.spinnaker.orca.events.StageComplete import com.netflix.spinnaker.orca.pipeline.model.Stage import com.netflix.spinnaker.orca.pipeline.model.SyntheticStageOwner.STAGE_AFTER import com.netflix.spinnaker.orca.pipeline.model.SyntheticStageOwner.STAGE_BEFORE import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.q.* import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.ApplicationEventPublisher import org.springframework.stereotype.Component import java.time.Clock @Component open class CompleteStageHandler @Autowired constructor( override val queue: Queue, override val repository: ExecutionRepository, private val publisher: ApplicationEventPublisher, private val clock: Clock ) : MessageHandler<CompleteStage> { override fun handle(message: CompleteStage) { message.withStage { stage -> stage.setStatus(message.status) stage.setEndTime(clock.millis()) repository.storeStage(stage) if (message.status in listOf(SUCCEEDED, FAILED_CONTINUE, SKIPPED)) { stage.startNext() } else { queue.push(CancelStage(message)) if (stage.getSyntheticStageOwner() == null) { queue.push(CompleteExecution(message)) } else { queue.push(message.copy(stageId = stage.getParentStageId())) } } publisher.publishEvent(StageComplete(this, stage)) } } override val messageType = CompleteStage::class.java private fun Stage<*>.startNext() { getExecution().let { execution -> val downstreamStages = downstreamStages() if (downstreamStages.isNotEmpty()) { downstreamStages.forEach { queue.push(StartStage(it)) } } else if (getSyntheticStageOwner() == STAGE_BEFORE) { // TODO: I'm not convinced this is a good approach, we should probably signal completion of the branch and have downstream handler no-op if other branches are incomplete parent().let { parent -> if (parent.allBeforeStagesComplete()) { if (parent.getTasks().isNotEmpty()) { queue.push(StartTask(parent, parent.getTasks().first().id)) } else if (parent.firstAfterStages().isNotEmpty()) { parent.firstAfterStages().forEach { queue.push(StartStage(it)) } } else { queue.push(CompleteStage(parent, SUCCEEDED)) } } } } else if (getSyntheticStageOwner() == STAGE_AFTER) { parent().let { parent -> queue.push(CompleteStage(parent, SUCCEEDED)) } } else { queue.push(CompleteExecution(execution)) } } } }
orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/CompleteStageHandler.kt
2117242192
/* * Copyright 2017 Pronghorn Technology 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 tech.pronghorn.server.config import tech.pronghorn.plugins.logging.LoggingPlugin import tech.pronghorn.server.ReusePort import tech.pronghorn.util.kibibytes import tech.pronghorn.util.mebibytes import java.net.InetSocketAddress import java.nio.channels.ServerSocketChannel import java.nio.channels.SocketChannel public object HttpServerConfigDefaultValues { public val workerCount = Runtime.getRuntime().availableProcessors() public const val serverName = "Pronghorn" public const val sendServerHeader = true public const val sendDateHeader = true public val reusePort = supportsReusePort() public const val listenBacklog = 128 public const val maxPipelinedRequests = 64 public val maxRequestSize = mebibytes(1) public val reusableBufferSize = kibibytes(64) public val socketReadBufferSize = getDefaultSocketReadBufferSize() public val socketWriteBufferSize = getDefaultSocketWriteBufferSize() public val useDirectByteBuffers = true private fun getDefaultSocketReadBufferSize(): Int { val tmpSocket = SocketChannel.open() val readBufferSize = tmpSocket.socket().receiveBufferSize tmpSocket.close() return readBufferSize } private fun getDefaultSocketWriteBufferSize(): Int { val tmpSocket = SocketChannel.open() val writeBufferSize = tmpSocket.socket().sendBufferSize tmpSocket.close() return writeBufferSize } private fun supportsReusePort(): Boolean { val tmpSocket = ServerSocketChannel.open() val success = ReusePort.setReusePort(tmpSocket) tmpSocket.close() return success } } /** * Configuration for a HttpServer. * @param address : The address to bind to. * @param workerCount : The number of worker threads to utilize, should likely be the number of cores available * @param sendServerHeader : If true, the Server header is automatically sent with each response * @param sendDateHeader : If true, the Date header is automatically sent with each response * @param serverName : The value to send in the Server response header if sendServerHeader is true * @param reusableBufferSize : The size of pooled read/write buffers, should be at least as large as the average expected request * @param socketReadBufferSize : The size of read buffers for client socket connections, very large or small values may be ignored by the underlying os implementation * @param socketWriteBufferSize : The size of write buffers for client socket connections, very large or small values may be ignored by the underlying os implementation * @param reusePort : If true, the SO_REUSEPORT socket option is used and each worker uses a dedicated socket * @param listenBacklog : The value for the accept queue for the server socket * @param acceptGrouping : How many connections should be accepted in a batch, usually equal to the listen backlog * @param maxPipelinedRequests : The maximum number of http requests allowed to be pipelined on a single connection * @param maxRequestSize : The maximum acceptable size of a single http request * @param useDirectByteBuffers : Whether socket read/write buffers should be direct ByteBuffers */ public open class HttpServerConfig(val address: InetSocketAddress, workerCount: Int = HttpServerConfigDefaultValues.workerCount, val sendServerHeader: Boolean = HttpServerConfigDefaultValues.sendServerHeader, val sendDateHeader: Boolean = HttpServerConfigDefaultValues.sendDateHeader, serverName: String = HttpServerConfigDefaultValues.serverName, reusableBufferSize: Int = HttpServerConfigDefaultValues.reusableBufferSize, socketReadBufferSize: Int = HttpServerConfigDefaultValues.socketReadBufferSize, socketWriteBufferSize: Int = HttpServerConfigDefaultValues.socketWriteBufferSize, reusePort: Boolean = HttpServerConfigDefaultValues.reusePort, listenBacklog: Int = HttpServerConfigDefaultValues.listenBacklog, acceptGrouping: Int = listenBacklog, maxPipelinedRequests: Int = HttpServerConfigDefaultValues.maxPipelinedRequests, maxRequestSize: Int = HttpServerConfigDefaultValues.maxRequestSize, val useDirectByteBuffers: Boolean = HttpServerConfigDefaultValues.useDirectByteBuffers) { private val logger = LoggingPlugin.get(javaClass) public val workerCount = validateWorkerCount(workerCount) public val serverName = validateServerName(serverName) public val reusableBufferSize = validateIsPositive("reusableBufferSize", reusableBufferSize, HttpServerConfigDefaultValues.reusableBufferSize) public val socketReadBufferSize = validateIsPositive("socketReadBufferSize", socketReadBufferSize, HttpServerConfigDefaultValues.socketReadBufferSize) public val socketWriteBufferSize = validateIsPositive("socketWriteBufferSize", socketWriteBufferSize, HttpServerConfigDefaultValues.socketWriteBufferSize) public val listenBacklog = validateIsPositive("listenBacklog", listenBacklog, HttpServerConfigDefaultValues.listenBacklog) public val acceptGrouping = validateIsPositive("acceptGrouping", acceptGrouping, HttpServerConfigDefaultValues.listenBacklog) public val reusePort = validateReusePort(reusePort) public val maxPipelinedRequests = validateMaxPipelinedRequests(maxPipelinedRequests) public val maxRequestSize = validateIsPositive("maxRequestSize", maxRequestSize, HttpServerConfigDefaultValues.maxRequestSize) private fun validateIsPositive(name: String, value: Int, default: Int): Int { if (value < 1) { logger.warn { "$name set to ($value), but must be greater than zero. Using default: ($default)" } return default } else { return value } } override fun toString(): String { return "HttpServerConfig: " + "address($address), " + "workerCount($workerCount), " + "serverName($serverName), " + "sendServerHeader($sendServerHeader), " + "sendDateHeader($sendDateHeader), " + "reusableBufferSize($reusableBufferSize), " + "reusePort($reusePort), " + "listenBacklog($listenBacklog), " + "acceptGrouping($acceptGrouping), " + "maxPipelinedRequests($maxPipelinedRequests), " + "maxRequestSize($maxRequestSize), " + "useDirectByteBuffers($useDirectByteBuffers)" } private fun validateWorkerCount(value: Int): Int { val availableProcessors = Runtime.getRuntime().availableProcessors() if (value < 1) { logger.warn { "workerCount value ($value) must be greater than zero, " + "using default value(${HttpServerConfigDefaultValues.workerCount})" } return HttpServerConfigDefaultValues.workerCount } else { if (value > availableProcessors) { logger.warn { "workerCount value ($value) is greater than available processors ($availableProcessors). " + "Utilizing more workers than there are available processors is not advised." } } return value } } private fun validateServerName(value: String): String { if (!Charsets.US_ASCII.newEncoder().canEncode(value)) { logger.warn { "serverName value ($value) contains non-ascii characters, this is likely to cause problems." } } return value } private fun validateReusePort(value: Boolean): Boolean { val osName = System.getProperty("os.name") ?: "Unknown" if (value && !osName.contains("Linux")) { logger.warn { "reusePort value ($value) is currently only supported on Linux, and is not supported on ($osName)." } } return value } private fun validateMaxPipelinedRequests(value: Int): Int { if (value < 1) { logger.warn { "maxPipelinedRequests value ($value) must be greater than zero. " + "To disable pipelining, use a value of 1. Using default value (${HttpServerConfigDefaultValues.maxPipelinedRequests})" } return HttpServerConfigDefaultValues.maxPipelinedRequests } else { return value } } }
src/main/kotlin/tech/pronghorn/server/config/HttpServerConfig.kt
1558065840
package library.integration.slack.services.slack import library.integration.slack.core.Slack import library.integration.slack.services.error.handling.* import mu.KotlinLogging.logger import org.springframework.stereotype.Service @Service class SlackMessageAccessor( private val slackMessageClient: SlackMessageClient, private val errorHandler: ErrorHandler ) : Slack { private val log = logger {} /** * Posts message to Slack. In case of error, it forwards the error to the Error Handler. */ override fun postMessage(slackMessage: String) { try { slackMessageClient.postMessage(SlackMessage(slackMessage)) log.debug { "Message with body [$slackMessage] has been send successful." } } catch (e: Exception) { errorHandler.handleSlackServiceErrors(e, slackMessage) } } }
library-integration-slack/src/main/kotlin/library/integration/slack/services/slack/SlackMessageAccessor.kt
4097330799
package com.chrynan.sample.util import android.content.Context typealias ApplicationContext = Context
sample/src/main/java/com/chrynan/sample/util/ApplicationContext.kt
2440489534
/* * Copyright 2016 Karl Tauber * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.devcharly.kotlin.ant import org.apache.tools.ant.taskdefs.Mkdir /****************************************************************************** DO NOT EDIT - this file was generated ******************************************************************************/ fun Ant.mkdir( dir: String? = null) { Mkdir().execute("mkdir") { task -> if (dir != null) task.setDir(project.resolveFile(dir)) } }
src/main/kotlin/com/devcharly/kotlin/ant/taskdefs/mkdir.kt
2798081413
package com.emmanuelmess.simpleaccounting.activities.views import android.view.View import android.widget.AdapterView import android.widget.AdapterView.OnItemSelectedListener import android.widget.Spinner import android.widget.SpinnerAdapter /** * Spinner Helper class that works around some common issues * with the stock Android Spinner * * A Spinner will normally call it's OnItemSelectedListener * when you use setSelection(...) in your initialization code. * This is usually unwanted behavior, and a common work-around * is to use spinner.post(...) with a Runnable to assign the * OnItemSelectedListener after layout. * * If you do not call setSelection(...) manually, the callback * may be called with the first item in the adapter you have * set. The common work-around for that is to count callbacks. * * While these workarounds usually *seem* to work, the callback * may still be called repeatedly for other reasons while the * selection hasn't actually changed. This will happen for * example, if the user has accessibility options enabled - * which is more common than you might think as several apps * use this for different purposes, like detecting which * notifications are active. * * Ideally, your OnItemSelectedListener callback should be * coded defensively so that no problem would occur even * if the callback was called repeatedly with the same values * without any user interaction, so no workarounds are needed. * * This class does that for you. It keeps track of the values * you have set with the setSelection(...) methods, and * proxies the OnItemSelectedListener callback so your callback * only gets called if the selected item's position differs * from the one you have set by code, or the first item if you * did not set it. * * This also means that if the user actually clicks the item * that was previously selected by code (or the first item * if you didn't set a selection by code), the callback will * not fire. * * To implement, replace current occurrences of: * * Spinner spinner = * (Spinner)findViewById(R.id.xxx); * * with: * * SpinnerHelper spinner = * new SpinnerHelper(findViewById(R.id.xxx)) * * SpinnerHelper proxies the (my) most used calls to Spinner * but not all of them. Should a method not be available, use: * * spinner.getSpinner().someMethod(...) * * Or just add the proxy method yourself :) * * (Quickly) Tested on devices from 2.3.6 through 4.2.2 * * @author Jorrit "Chainfire" Jongma * license WTFPL (do whatever you want with this, nobody cares) */ class SpinnerNoUnwantedOnClick(val spinner: Spinner) : OnItemSelectedListener { private var lastPosition = -1 private var proxiedItemSelectedListener: OnItemSelectedListener? = null var adapter: SpinnerAdapter get() = spinner.adapter set(adapter) { if (adapter.count > 0) { lastPosition = 0 } spinner.adapter = adapter } val count: Int get() = spinner.count val selectedItem: Any get() = spinner.selectedItem val selectedItemId: Long get() = spinner.selectedItemId val selectedItemPosition: Int get() = spinner.selectedItemPosition var isEnabled: Boolean get() = spinner.isEnabled set(enabled) { spinner.isEnabled = enabled } fun setSelection(position: Int) { lastPosition = Math.max(-1, position) spinner.setSelection(position) } fun setSelection(position: Int, animate: Boolean) { lastPosition = Math.max(-1, position) spinner.setSelection(position, animate) } fun setOnItemSelectedListener(listener: OnItemSelectedListener?) { proxiedItemSelectedListener = listener spinner.onItemSelectedListener = if (listener == null) null else this } override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { if (position != lastPosition) { lastPosition = position if (proxiedItemSelectedListener != null) { proxiedItemSelectedListener!!.onItemSelected( parent, view, position, id ) } } } override fun onNothingSelected(parent: AdapterView<*>) { if (-1 != lastPosition) { lastPosition = -1 if (proxiedItemSelectedListener != null) { proxiedItemSelectedListener!!.onNothingSelected( parent ) } } } fun getItemAtPosition(position: Int): Any = spinner.getItemAtPosition(position) fun getItemIdAtPosition(position: Int): Long = spinner.getItemIdAtPosition(position) }
SimpleAccounting/app/src/main/java/com/emmanuelmess/simpleaccounting/activities/views/SpinnerNoUnwantedOnClick.kt
536210187
package io.polymorphicpanda.kspec.engine.execution import io.polymorphicpanda.kspec.context.Context /** * @author Ranie Jade Ramiso */ interface ExecutionListener { fun executionStarted() fun executionFinished() fun exampleStarted(example: Context.Example) fun exampleIgnored(example: Context.Example) fun exampleFinished(example: Context.Example, result: ExecutionResult) fun exampleGroupStarted(group: Context.ExampleGroup) fun exampleGroupIgnored(group: Context.ExampleGroup) fun exampleGroupFinished(group: Context.ExampleGroup, result: ExecutionResult) }
kspec-engine/src/main/kotlin/io/polymorphicpanda/kspec/engine/execution/ExecutionListener.kt
3484871104
package com.lasthopesoftware.bluewater.client.playback.file.exoplayer.preparation.GivenUris.AndAnErrorOccursGettingNewRenderers import android.net.Uri import com.google.android.exoplayer2.LoadControl import com.google.android.exoplayer2.source.BaseMediaSource import com.google.android.exoplayer2.upstream.DefaultAllocator import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile import com.lasthopesoftware.bluewater.client.playback.file.exoplayer.preparation.ExoPlayerPlaybackPreparer import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture import com.namehillsoftware.handoff.promises.Promise import io.mockk.mockk import org.assertj.core.api.Assertions.assertThat import org.joda.time.Duration import org.junit.BeforeClass import org.junit.Test import org.mockito.Mockito import java.util.concurrent.ExecutionException import java.util.concurrent.TimeUnit class WhenPreparing { companion object { private var exception: Throwable? = null @BeforeClass @JvmStatic fun before() { val loadControl = Mockito.mock(LoadControl::class.java) Mockito.`when`(loadControl.allocator).thenReturn(DefaultAllocator(true, 1024)) val preparer = ExoPlayerPlaybackPreparer( mockk(relaxed = true), { mockk<BaseMediaSource>() }, loadControl, { Promise(Exception("Oops")) }, mockk(), mockk(), { Promise(mockk<Uri>()) } ) try { preparer.promisePreparedPlaybackFile(ServiceFile(1), Duration.ZERO).toFuture()[1, TimeUnit.SECONDS] } catch (ex: ExecutionException) { exception = ex.cause } } } @Test fun thenAnExceptionIsThrown() { assertThat(exception?.message).isEqualTo("Oops") } }
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/file/exoplayer/preparation/GivenUris/AndAnErrorOccursGettingNewRenderers/WhenPreparing.kt
1066214760
package com.tgirard12.kotlintalk import io.kotlintest.matchers.be import io.kotlintest.specs.StringSpec /** * https://github.com/kotlintest/kotlintest */ class KotlinTest : StringSpec() { override fun beforeAll() { super.beforeAll() } override fun beforeEach() { super.beforeEach() } init { "strings.length should return size of string" { "hello".length shouldBe 5 } listOf(3, 5, 7).forEach { "$it must be < 10" { it should be lt 10 } } } }
talk/src/test/kotlin/com/tgirard12/kotlintalk/12_Tests.kt
3409622633
package furhatos.app.quiz.flow.main import furhatos.app.quiz.flow.Parent import furhatos.app.quiz.setting.playing import furhatos.app.quiz.setting.quiz import furhatos.flow.kotlin.State import furhatos.flow.kotlin.furhat import furhatos.flow.kotlin.state import furhatos.flow.kotlin.users // End of game, announcing results val EndGame: State = state(parent = Parent) { var skipNext = false onEntry { playing = false // If multiple players, we rank the players on points and congratulate the winner. A special case is when we have a tie. if (users.playing().count() > 1) { // Sort users by score users.playing().sortedByDescending { it.quiz.score }.forEachIndexed { index, user -> // The winner(s) if (index == 0) { val highestScore = user.quiz.score val usersWithHighestScore = users.playing().filter { it.quiz.score == highestScore } // Check if we have more than one user with the highest score and if so announce a tie if (usersWithHighestScore.count() > 1) { furhat.say("Wow, we have a tie! You each have $highestScore points", async = true) delay(500) usersWithHighestScore.forEach { furhat.attend(it) delay(700) } // If a tie, we skip the next user since we've already adressed them above skipNext = true } // A single winner exists else { furhat.attend(user) furhat.say("Congratulations! You won with ${user.quiz.score} points") } } // Every other subsequent player else { if (!skipNext) { skipNext = false furhat.attend(user) furhat.say("And you got ${user.quiz.score} points") } } delay(300) } } // Only one player, we simply announce the score else { furhat.say("You got ${users.current.quiz.score} points.") } furhat.say("Thanks for playing!") // Resetting user state variables users.playing().forEach { it.quiz.playing = false it.quiz.played = true it.quiz.lastScore = it.quiz.score } delay(1000) goto(Idle) } }
Quiz/src/main/kotlin/furhatos/app/quiz/flow/main/endGame.kt
1770642023
package com.ruuvi.station.settings.ui import android.graphics.Color import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.View import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import com.ruuvi.station.util.extensions.viewModel import com.ruuvi.station.R import com.ruuvi.station.settings.domain.GatewayTestResultType import com.ruuvi.station.util.extensions.makeWebLinks import com.ruuvi.station.util.extensions.setDebouncedOnClickListener import kotlinx.android.synthetic.main.fragment_app_settings_gateway.* import kotlinx.android.synthetic.main.fragment_app_settings_gateway.settingsInfoTextView import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import org.kodein.di.Kodein import org.kodein.di.KodeinAware import org.kodein.di.android.support.closestKodein class AppSettingsGatewayFragment : Fragment(R.layout.fragment_app_settings_gateway) , KodeinAware { override val kodein: Kodein by closestKodein() private val viewModel: AppSettingsGatewayViewModel by viewModel() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupViews() observeGatewayUrl() observeDeviceId() observeTestGatewayResult() } private fun setupViews() { gatewayUrlEditText.addTextChangedListener( object: TextWatcher { override fun afterTextChanged(s: Editable?) { viewModel.setGatewayUrl(s.toString()) } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} }) deviceIdEditText.addTextChangedListener( object: TextWatcher { override fun afterTextChanged(s: Editable?) { viewModel.setDeviceId(s.toString()) } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} }) settingsInfoTextView.makeWebLinks(requireActivity(), Pair(getString(R.string.settings_gateway_details_link), getString(R.string.settings_gateway_details_link_url))) gatewayTestButton.setDebouncedOnClickListener { viewModel.testGateway() gatewayTestResultTextView.visibility = View.VISIBLE } } fun observeGatewayUrl() { lifecycleScope.launch { viewModel.observeGatewayUrl.collect { gatewayUrlEditText.setText(it) } } } fun observeDeviceId() { lifecycleScope.launch { viewModel.observeDeviceId.collect { deviceIdEditText.setText(it) } } } fun observeTestGatewayResult() { lifecycleScope.launch { viewModel.observeTestGatewayResult.collect{ when (it.type) { GatewayTestResultType.NONE -> { gatewayTestResultTextView.text = "" gatewayTestResultTextView.setTextColor(Color.DKGRAY) } GatewayTestResultType.TESTING -> { gatewayTestResultTextView.text = getString(R.string.gateway_testing) gatewayTestResultTextView.setTextColor(Color.DKGRAY) } GatewayTestResultType.SUCCESS -> { gatewayTestResultTextView.text = getString(R.string.gateway_test_success, it.code) gatewayTestResultTextView.setTextColor(Color.GREEN) } GatewayTestResultType.FAIL -> { gatewayTestResultTextView.text = getString(R.string.gateway_test_fail, it.code) gatewayTestResultTextView.setTextColor(Color.RED) } GatewayTestResultType.EXCEPTION -> { gatewayTestResultTextView.text = getString(R.string.gateway_test_exception) gatewayTestResultTextView.setTextColor(Color.RED) } } } } } companion object { fun newInstance() = AppSettingsGatewayFragment() } }
app/src/main/java/com/ruuvi/station/settings/ui/AppSettingsGatewayFragment.kt
607598013
package mil.nga.giat.mage.form.edit.dialog import android.text.Editable import android.text.Spannable import android.text.TextWatcher import android.widget.EditText import mil.nga.giat.mage.coordinate.CoordinateType import mil.nga.giat.mage.coordinate.MutableDMSLocation class DMSCoordinateTextWatcher( private val editText: EditText, private val coordinateType: CoordinateType, val onSplitCoordinates: (Pair<String, String>) -> Unit ): TextWatcher { private var span: Any = Unit override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { editText.text.setSpan(span, start, start + count, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } override fun afterTextChanged(s: Editable?) { val text = s?.toString() ?: return val start: Int = editText.text.getSpanStart(span) val end: Int = editText.text.getSpanEnd(span) val count = end - start val replacement = if (count > 0) { val replaced = text.subSequence(start, start + count) text.replaceRange(start until start + count, replaced).uppercase() } else "" if (replacement.isEmpty() || ("-" == text && start == 0 && count == 0)) { return } if ("." == replacement) { updateText() return } val coordinates = if (count > 1) splitCoordinates(text) else emptyList() if (coordinates.size == 2) { updateText() onSplitCoordinates(coordinates.zipWithNext().first()) } else { val dms = parseDMS(text, addDirection = count > 1) val selection = if (dms.lastIndex > end) { val nextDigitIndex = dms.substring(start + 1).indexOfFirst { it.isDigit() } if (nextDigitIndex != -1) { start + nextDigitIndex + 1 } else null } else null updateText(dms) selection?.let { editText.setSelection(it) } } } private fun updateText(text: String? = null) { editText.removeTextChangedListener(this) editText.text.clear() text?.let { editText.append(it) } editText.addTextChangedListener(this) } private fun parseDMS(text: String, addDirection: Boolean): String { if (text.isEmpty()) { return "" } val dms = MutableDMSLocation.parse(text, coordinateType, addDirection) val degrees = dms.degrees?.let { degrees -> "$degrees° " } ?: "" val minutes = dms.minutes?.let { minutes -> val padded = minutes.toString().padStart(2, '0') "${padded}\" " } ?: "" val seconds = dms.seconds?.let { seconds -> val padded = seconds.toString().padStart(2, '0') "${padded}\' " } ?: "" val direction = dms.direction ?: "" return "$degrees$minutes$seconds$direction" } private fun splitCoordinates(text: String): List<String> { val coordinates = mutableListOf<String>() val parsable = text.lines().joinToString().trim() // if there is a comma, split on that if (parsable.contains(',')) { return parsable.split(",").map { coordinate -> coordinate.trim() } } // Check if there are any direction letters val firstDirectionIndex = parsable.indexOfFirst { "NSEW".contains(it.uppercase()) } if (firstDirectionIndex != -1) { if (parsable.contains('-')) { // Split coordinates on dash return parsable.split("-").map { coordinate -> coordinate.trim() } } else { // No dash, split on the direction val lastDirectionIndex = parsable.indexOfLast { "NSEW".contains(it.uppercase()) } if (firstDirectionIndex == 0) { if (lastDirectionIndex != firstDirectionIndex) { return listOf( parsable.substring(0, lastDirectionIndex - 1), parsable.substring(lastDirectionIndex) ) } } else if (lastDirectionIndex == parsable.lastIndex) { if (lastDirectionIndex != firstDirectionIndex) { return listOf( parsable.substring(0, firstDirectionIndex + 1), parsable.substring(firstDirectionIndex + 1) ) } } } } // If there is one white space character split on that val parts = parsable.split(" ") if (parts.size == 2) { return parts.map { coordinate -> coordinate.trim() } } return coordinates } }
mage/src/main/java/mil/nga/giat/mage/form/edit/dialog/DMSCoordinateTextWatcher.kt
1443808099
/* * Copyright (c) 2019 David Aguiar Gonzalez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gc.david.dfm.distance.domain /** * Created by david on 16.01.17. */ interface ClearDistancesUseCase { interface Callback { fun onClear() fun onError() } fun execute(callback: Callback) }
app/src/main/java/gc/david/dfm/distance/domain/ClearDistancesUseCase.kt
2006552998
package com.fastaccess.ui.modules.repos.wiki import android.content.Intent import com.fastaccess.data.dao.wiki.WikiContentModel import com.fastaccess.data.dao.wiki.WikiSideBarModel import com.fastaccess.helper.BundleConstant import com.fastaccess.helper.Logger import com.fastaccess.helper.RxHelper import com.fastaccess.provider.rest.jsoup.JsoupProvider import com.fastaccess.ui.base.mvp.presenter.BasePresenter import io.reactivex.Observable import org.jsoup.Jsoup import org.jsoup.nodes.Document /** * Created by Kosh on 13 Jun 2017, 8:14 PM */ class WikiPresenter : BasePresenter<WikiMvp.View>(), WikiMvp.Presenter { @com.evernote.android.state.State var repoId: String? = null @com.evernote.android.state.State var login: String? = null override fun onActivityCreated(intent: Intent?) { if (intent != null) { val bundle = intent.extras repoId = bundle.getString(BundleConstant.ID) login = bundle.getString(BundleConstant.EXTRA) val page = bundle.getString(BundleConstant.EXTRA_TWO) if (!repoId.isNullOrEmpty() && !login.isNullOrEmpty()) { onSidebarClicked(WikiSideBarModel("Home", "$login/$repoId/wiki" + if (!page.isNullOrEmpty()) "/$page" else "")) } } } override fun onSidebarClicked(sidebar: WikiSideBarModel) { manageViewDisposable(RxHelper.getObservable(JsoupProvider.getWiki().getWiki(sidebar.link)) .flatMap { s -> RxHelper.getObservable(getWikiContent(s)) } .doOnSubscribe { sendToView { it.showProgress(0) } } .subscribe({ response -> sendToView { view -> view.onLoadContent(response) } }, { throwable -> onError(throwable) }, { sendToView({ it.hideProgress() }) })) } private fun getWikiContent(body: String?): Observable<WikiContentModel> { return Observable.fromPublisher { s -> val document: Document = Jsoup.parse(body, "") val wikiWrapper = document.select("#wiki-wrapper") if (wikiWrapper.isNotEmpty()) { val cloneUrl = wikiWrapper.select(".clone-url") val bottomRightBar = wikiWrapper.select(".wiki-custom-sidebar") if (cloneUrl.isNotEmpty()) { cloneUrl.remove() } if (bottomRightBar.isNotEmpty()) { bottomRightBar.remove() } val headerHtml = wikiWrapper.select(".gh-header .gh-header-meta") val revision = headerHtml.select("a.history") if (revision.isNotEmpty()) { revision.remove() } val header = "<div class='gh-header-meta'>${headerHtml.html()}</div>" val wikiContent = wikiWrapper.select(".wiki-content") val content = header + wikiContent.select(".markdown-body").html() val rightBarList = wikiContent.select(".wiki-pages").select("li") val sidebarList = arrayListOf<WikiSideBarModel>() if (rightBarList.isNotEmpty()) { rightBarList.onEach { val sidebarTitle = it.select("a").text() val sidebarLink = it.select("a").attr("href") sidebarList.add(WikiSideBarModel(sidebarTitle, sidebarLink)) } } Logger.d(header) s.onNext(WikiContentModel(content, "", sidebarList)) } else { s.onNext(WikiContentModel("<h2 align='center'>No Wiki</h4>", "", arrayListOf())) } s.onComplete() } } }
app/src/main/java/com/fastaccess/ui/modules/repos/wiki/WikiPresenter.kt
3625315511
package com.github.charbgr.cliffhanger.feature.browser.arch.interactor import com.github.charbgr.cliffhanger.domain.MovieCategory import com.github.charbgr.cliffhanger.domain.MovieCategory.NowPlaying import com.github.charbgr.cliffhanger.domain.MovieCategory.Popular import com.github.charbgr.cliffhanger.domain.MovieCategory.TopRated import com.github.charbgr.cliffhanger.domain.MovieCategory.Upcoming object MovieBrowserInteractorFactory { fun createInteractor(movieCategory: MovieCategory): MovieBrowserInteractor { return when (movieCategory) { is TopRated -> TopRatedInteractor() is NowPlaying -> NowPlayingInteractor() is Popular -> PopularInteractor() is Upcoming -> UpcomingInteractor() else -> { NanInteractor() } } } }
cliffhanger/feature-browser/src/main/kotlin/com/github/charbgr/cliffhanger/feature/browser/arch/interactor/MovieBrowserInteractorFactory.kt
263871075
package org.gradle.kotlin.dsl.resolver import org.gradle.kotlin.dsl.fixtures.FolderBasedTest import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @RunWith(Parameterized::class) class ProjectRootOfTest(private val settingsFileName: String) : FolderBasedTest() { companion object { @Parameterized.Parameters(name = "{0}") @JvmStatic fun testCases() = listOf(arrayOf("settings.gradle"), arrayOf("settings.gradle.kts")) } @Test fun `given a script file under a nested project it should return the nested project root`() { withFolders { "root" { "nested-project-root" { // a nested project is detected by the presence of a settings file withFile(settingsFileName) "sub-project" { withFile("build.gradle.kts") } } } } assertThat( projectRootOf( scriptFile = file("root/nested-project-root/sub-project/build.gradle.kts"), importedProjectRoot = folder("root")), equalTo(folder("root/nested-project-root"))) } @Test fun `given a script file under a separate project it should return the separate project root`() { withFolders { "root" { } "separate-project-root" { withFile("build.gradle.kts") } } assertThat( projectRootOf( scriptFile = file("separate-project-root/build.gradle.kts"), importedProjectRoot = folder("root"), stopAt = root), equalTo(folder("separate-project-root"))) } @Test fun `given a script file under a separate nested project it should return the separate nested project root`() { withFolders { "root" { } "separate" { "nested-project-root" { // a nested project is detected by the presence of a settings file withFile(settingsFileName) "sub-project" { withFile("build.gradle.kts") } } } } assertThat( projectRootOf( scriptFile = file("separate/nested-project-root/sub-project/build.gradle.kts"), importedProjectRoot = folder("root")), equalTo(folder("separate/nested-project-root"))) } @Test fun `given a script file under the imported project it should return the imported project root`() { withFolders { "root" { "sub-project" { withFile("build.gradle.kts") } } } assertThat( projectRootOf( scriptFile = file("root/sub-project/build.gradle.kts"), importedProjectRoot = folder("root")), equalTo(folder("root"))) } @Test fun `given a script file in buildSrc it should return the buildSrc project root`() { withFolders { "root" { "buildSrc" { withFile("build.gradle.kts") } } } assertThat( projectRootOf( scriptFile = file("root/buildSrc/build.gradle.kts"), importedProjectRoot = folder("root")), equalTo(folder("root/buildSrc"))) } }
subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/resolver/ProjectRootOfTest.kt
1964451893
package org.gtlp.ui.views import org.gtlp.ui.PWindow import org.gtlp.ui.events.IWindowEvent import org.gtlp.ui.listeners.IEventListener import org.gtlp.util.math.Vector /** * Interface for using views. * Some implementations might not use all the available variables, values or functions * to their full extent */ interface IView { /** * The parent of this [IView] */ val parent: PWindow /** * The position, z-axis used for sorting drawing order */ var pos: Vector /** * The size */ var size: Vector /** * The [IEventListener]s handling events */ val listeners: List<IEventListener> /** * Indicates whether this view should be drawn. */ var visible: Boolean /** * A tag for various use cases */ var tag: Any? /** * Method to handle events */ fun handleEvent(event: IWindowEvent) /** * The method to draw this view usually */ fun draw() /** * The method to draw this view when hovered */ fun drawHover() /** * The method to handle updates */ fun onUpdate() }
src/main/kotlin/org/gtlp/ui/views/IView.kt
210812146
/* * Copyright (c) 2021 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.article_viewer.article.detail.markdown import android.content.Context import coil.ImageLoader import coil.request.Disposable import coil.request.ImageRequest import io.noties.markwon.image.AsyncDrawable import io.noties.markwon.image.coil.CoilImagesPlugin /** * @author toastkidjp */ class CoilPluginFactory { operator fun invoke(context: Context): CoilImagesPlugin { val imageLoader = ImageLoader.Builder(context).build() return CoilImagesPlugin.create( object : CoilImagesPlugin.CoilStore { override fun load(drawable: AsyncDrawable) = ImageRequest.Builder(context) .defaults(imageLoader.defaults) .data(drawable.destination) .crossfade(true) .build() override fun cancel(disposable: Disposable) = disposable.dispose() }, imageLoader ) } }
article/src/main/java/jp/toastkid/article_viewer/article/detail/markdown/CoilPluginFactory.kt
557948234
package guru.stefma.androidartifacts import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class GradleVersionComparatorTest { @Test fun `Gradle 4dot8 is better than 4dot7`() { val betterThan = GradleVersionComparator("4.8").betterThan("4.7") assertThat(betterThan).isTrue() } @Test fun `Gradle 4dot10dot1 is better than 4dot10`() { val betterThan = GradleVersionComparator("4.10.1").betterThan("4.10") assertThat(betterThan).isTrue() } @Test fun `Gradle 4dot8 is not better than 4dot9`() { val betterThan = GradleVersionComparator("4.8").betterThan("4.9") assertThat(betterThan).isFalse() } @Test fun `Gradle 4dot9 is not better than 4dot10dot2`() { val betterThan = GradleVersionComparator("4.9").betterThan("4.10.2") assertThat(betterThan).isFalse() } @Test fun `Gradle 5dot0 is better than 4dot10dot2`() { val betterThan = GradleVersionComparator("5.0").betterThan("4.10.2") assertThat(betterThan).isTrue() } @Test fun `Gradle 4dot10dot1 is smaller than 4dot10dot2`() { val betterThan = GradleVersionComparator("4.10.1").smallerThan("4.10.2") assertThat(betterThan).isTrue() } @Test fun `Gradle 4dot6 is smaller than 4dot10dot1`() { val betterThan = GradleVersionComparator("4.6").smallerThan("4.10.1") assertThat(betterThan).isTrue() } @Test fun `Gradle 4dot10dot1 is not smaller than 4dot10`() { val betterThan = GradleVersionComparator("4.10.1").smallerThan("4.10") assertThat(betterThan).isFalse() } @Test fun `Gradle 5dot0 is not smaller than 4dot10dot2`() { val betterThan = GradleVersionComparator("5.0").smallerThan("4.10.2") assertThat(betterThan).isFalse() } }
src/test/kotlin/guru/stefma/androidartifacts/GradleVersionComparatorTest.kt
2085564406
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:OptIn(ExperimentalCoroutinesApi::class, ExperimentalHorologistComposeLayoutApi::class) package com.google.android.horologist.compose.navscaffold import androidx.compose.foundation.ScrollState import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.geometry.Rect import androidx.compose.ui.layout.boundsInWindow import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertIsFocused import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.get import androidx.navigation.NavGraphBuilder import androidx.navigation.NavHostController import androidx.test.filters.MediumTest import androidx.wear.compose.foundation.curvedComposable import androidx.wear.compose.material.AutoCenteringParams import androidx.wear.compose.material.ScalingLazyColumn import androidx.wear.compose.material.ScalingLazyListState import androidx.wear.compose.material.Text import androidx.wear.compose.material.TimeText import androidx.wear.compose.material.rememberScalingLazyListState import androidx.wear.compose.navigation.rememberSwipeDismissableNavController import com.google.android.horologist.compose.focus.RequestFocusWhenActive import com.google.android.horologist.compose.rotaryinput.rotaryWithFling import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withContext import org.junit.Assert.assertSame import org.junit.Rule import org.junit.Test @MediumTest class NavScaffoldTest { @get:Rule val composeTestRule = createComposeRule() lateinit var navController: NavHostController @Test fun testNavScaffoldScroll() = runTest { // Test that when we move between two scrollable destinations // we get the right scroll state used at the right times lateinit var aScrollState: ScalingLazyListState lateinit var bScrollState: ScalingLazyListState lateinit var cScrollState: ScalingLazyListState lateinit var navController: NavHostController fun NavGraphBuilder.scrollingList( route: String, scrollState: ScalingLazyListState ) { scalingLazyColumnComposable( route = route, scrollStateBuilder = { scrollState } ) { val focusRequester = remember { FocusRequester() } ScalingLazyColumn( modifier = Modifier .fillMaxWidth() .rotaryWithFling( focusRequester, it.scrollableState ), state = it.scrollableState, horizontalAlignment = Alignment.CenterHorizontally ) { items(11) { Text(text = "Item $it") } } RequestFocusWhenActive(focusRequester) } } composeTestRule.setContent { navController = rememberSwipeDismissableNavController() aScrollState = rememberScalingLazyListState(initialCenterItemIndex = 0) bScrollState = rememberScalingLazyListState(initialCenterItemIndex = 10) cScrollState = rememberScalingLazyListState(initialCenterItemScrollOffset = 50) WearNavScaffold( startDestination = "a", navController = navController ) { scrollingList("a", aScrollState) scrollingList("b", bScrollState) scrollingList("c", cScrollState) } } composeTestRule.awaitIdle() val aViewModel = ViewModelProvider(navController.currentBackStackEntry!!).get<NavScaffoldViewModel>() assertSame(aScrollState, aViewModel.scrollableState) withContext(Dispatchers.Main) { navController.navigate("b") } composeTestRule.awaitIdle() val bViewModel = ViewModelProvider(navController.currentBackStackEntry!!).get<NavScaffoldViewModel>() assertSame(bScrollState, bViewModel.scrollableState) withContext(Dispatchers.Main) { navController.navigate("c") } composeTestRule.awaitIdle() val cViewModel = ViewModelProvider(navController.currentBackStackEntry!!).get<NavScaffoldViewModel>() assertSame(cScrollState, cViewModel.scrollableState) } @Test fun testNavScaffoldNavigation() { // Test navigating changes the composable that is shown correctly composeTestRule.setContent { navController = rememberSwipeDismissableNavController() WearNavScaffold( startDestination = "a", navController = navController ) { scalingLazyColumnComposable( route = "a", scrollStateBuilder = { ScalingLazyListState(initialCenterItemIndex = 0) } ) { val focusRequester = remember { FocusRequester() } ScalingLazyColumn( modifier = Modifier .rotaryWithFling( focusRequester, it.scrollableState ) .fillMaxSize() .testTag("columna"), state = it.scrollableState, horizontalAlignment = Alignment.CenterHorizontally, autoCentering = AutoCenteringParams(itemIndex = 0) ) { items(100) { Text("Item $it") } } RequestFocusWhenActive(focusRequester) } scrollStateComposable( route = "b", scrollStateBuilder = { ScrollState(0) } ) { val focusRequester = remember { FocusRequester() } Column( modifier = Modifier .testTag("columnb") .fillMaxSize() .rotaryWithFling(focusRequester, it.scrollableState) .verticalScroll(it.scrollableState) ) { (1..100).forEach { i -> Text("$i") } } RequestFocusWhenActive(focusRequester) } } } val columnA = composeTestRule.onNodeWithTag("columna") val columnB = composeTestRule.onNodeWithTag("columnb") columnA.assertIsDisplayed().assertIsFocused() columnB.assertDoesNotExist() composeTestRule.runOnUiThread { navController.navigate("b") } composeTestRule.waitForIdle() columnA.assertDoesNotExist() columnB.assertIsDisplayed().assertIsFocused() composeTestRule.runOnUiThread { navController.popBackStack() } composeTestRule.waitForIdle() columnA.assertIsDisplayed().assertIsFocused() columnB.assertDoesNotExist() } @Test fun testTimeTextCanBeToggled() { // Test that timetext shows up, and via custom leading text is shown near the top of the // screen, the disappears after mode is toggled off var bounds: Rect? = null composeTestRule.setContent { navController = rememberSwipeDismissableNavController() WearNavScaffold( startDestination = "a", navController = navController, timeText = { TimeText( modifier = it, startCurvedContent = { curvedComposable { Text( modifier = Modifier .testTag("timeText") .onGloballyPositioned { bounds = it.boundsInWindow() }, text = "\uD83D\uDD23" ) } }, endLinearContent = { Text( modifier = Modifier .testTag("timeText") .onGloballyPositioned { bounds = it.boundsInWindow() }, text = "\uD83D\uDD23" ) } ) } ) { wearNavComposable( route = "a" ) { _, _ -> Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { Text( modifier = Modifier.testTag("body"), text = "Lorem Ipsum" ) } } } } composeTestRule.waitForIdle() val timeText = composeTestRule.onNodeWithTag("timeText") val body = composeTestRule.onNodeWithTag("body") // expect time text in the top 50 pixels assertThat(bounds?.bottom).isLessThan(75) timeText.assertIsDisplayed() body.assertIsDisplayed() val viewModel = ViewModelProvider(navController.currentBackStackEntry!!).get<NavScaffoldViewModel>() viewModel.timeTextMode = NavScaffoldViewModel.TimeTextMode.Off composeTestRule.waitForIdle() timeText.assertDoesNotExist() body.assertIsDisplayed() } }
compose-layout/src/androidTest/java/com/google/android/horologist/compose/navscaffold/NavScaffoldTest.kt
3312691770
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.kotlindemos.model import com.google.android.libraries.maps.model.LatLng /** * Helper to translate all given LatLngs by the same amount in one of the predefined directions. */ enum class MoveDirection(private val numLatSteps: Int, private val numLngSteps: Int) { UP(1, 0), DOWN(-1, 0), LEFT(0, -1), RIGHT(0, 1); fun getLatDistance(stepSizeDeg: Double): Double { return numLatSteps * stepSizeDeg } fun getLngDistance(stepSizeDeg: Double): Double { return numLngSteps * stepSizeDeg } companion object { private fun movePoint( oldPoint: LatLng, latMoveDistance: Double, lngMoveDistance: Double ): LatLng { return LatLng(oldPoint.latitude + latMoveDistance, oldPoint.longitude + lngMoveDistance) } fun movePointsInList( oldPoints: List<LatLng>, latMoveDistance: Double, lngMoveDistance: Double ): List<LatLng> { val newPoints = mutableListOf<LatLng>() for (oldPoint in oldPoints) { newPoints.add(movePoint(oldPoint, latMoveDistance, lngMoveDistance)) } return newPoints } fun movePointsInNestedList( oldPointLists: List<List<LatLng>>, latMoveDistance: Double, lngMoveDistance: Double ): List<List<LatLng>> { val newPointLists = mutableListOf<List<LatLng>>() for (oldPointList in oldPointLists) { newPointLists.add(movePointsInList(oldPointList, latMoveDistance, lngMoveDistance)) } return newPointLists } } }
ApiDemos/kotlin/app/src/v3/java/com/example/kotlindemos/model/MoveDirection.kt
2161923036
package fr.corenting.edcompanion.models import fr.corenting.edcompanion.models.apis.EDAPIV4.CommodityFinderResponse import org.threeten.bp.DateTimeUtils import org.threeten.bp.Instant data class CommodityFinderResult( val price: Long, val landingPad: String, val station: String, val system: String, val isPlanetary: Boolean, val quantity: Long, val distanceToArrival: Float, val distanceFromReferenceSystem: Float, val lastMarketUpdate: Instant, val pricePercentageDifference: Int ) { companion object { fun fromCommodityFinderResponse(res: CommodityFinderResponse): CommodityFinderResult { return CommodityFinderResult( res.Price, res.MaxLandingPad, res.Name, res.SystemName, res.IsPlanetary or res.IsSettlement, res.Quantity, res.DistanceToArrival, res.DistanceFromReferenceSystem, DateTimeUtils.toInstant(res.LastMarketUpdate), res.PricePercentageDifference ) } } }
app/src/main/java/fr/corenting/edcompanion/models/CommodityFinderResult.kt
1156860639
/* * Copyright 2020 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.gate.plugins.deck import com.netflix.spinnaker.kork.web.exceptions.NotFoundException import io.swagger.annotations.ApiOperation import java.util.concurrent.TimeUnit import javax.servlet.http.HttpServletResponse import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty import org.springframework.http.CacheControl import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.ExceptionHandler import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping("/plugins/deck") @ConditionalOnProperty("spinnaker.extensibility.deck-proxy.enabled", matchIfMissing = true) class DeckPluginsController( private val deckPluginService: DeckPluginService ) { @ApiOperation(value = "Retrieve a plugin manifest") @GetMapping("/plugin-manifest.json") fun getPluginManifest(): List<DeckPluginVersion> { return deckPluginService.getPluginsManifests() } @ApiOperation(value = "Retrieve a single plugin asset by version") @GetMapping("/{pluginId}/{pluginVersion}/{asset:.*}") fun getPluginAsset( @PathVariable pluginId: String, @PathVariable pluginVersion: String, @PathVariable asset: String ): ResponseEntity<String> { val pluginAsset = deckPluginService.getPluginAsset(pluginId, pluginVersion, asset) ?: throw NotFoundException("Unable to find asset for plugin version") return ResponseEntity.ok() .header("Content-Type", pluginAsset.contentType) .header( "Cache-Control", CacheControl .maxAge(30, TimeUnit.DAYS) .mustRevalidate() .cachePrivate() .headerValue ) .body(pluginAsset.content) } @ExceptionHandler(CacheNotReadyException::class) fun handleCacheNotReadyException( e: Exception, response: HttpServletResponse ) { response.sendError(HttpStatus.SERVICE_UNAVAILABLE.value(), e.message) } }
gate-plugins/src/main/kotlin/com/netflix/spinnaker/gate/plugins/deck/DeckPluginsController.kt
494935404
@file:JvmMultifileClass @file:JvmName("DialogsKt") @file:Suppress("NOTHING_TO_INLINE", "UNUSED") package kota import android.app.AlertDialog import android.app.Fragment import android.content.Context import android.content.DialogInterface import android.support.annotation.ArrayRes import android.support.annotation.StringRes @JvmOverloads inline fun Context.itemsAlert( items: Array<out CharSequence>, title: CharSequence? = null, noinline action: (dialog: DialogInterface, Int) -> Unit, noinline init: (AlertDialog.() -> Unit)? = null ): AlertDialog = AlertDialog.Builder(this) .setItems(items, DialogInterface.OnClickListener(action)) .apply { title?.let { setTitle(it) } } .create() .apply { init?.invoke(this) } @JvmOverloads inline fun Fragment.itemsAlert( items: Array<out CharSequence>, title: CharSequence? = null, noinline action: (dialog: DialogInterface, Int) -> Unit, noinline init: (AlertDialog.() -> Unit)? = null ): AlertDialog = activity.itemsAlert(items, title, action, init) @JvmOverloads inline fun Context.itemsAlert( @ArrayRes items: Int, @StringRes titleId: Int? = null, noinline action: (dialog: DialogInterface, Int) -> Unit, noinline init: (AlertDialog.() -> Unit)? = null ): AlertDialog = AlertDialog.Builder(this) .setItems(items, DialogInterface.OnClickListener(action)) .apply { titleId?.let { setTitle(it) } } .create() .apply { init?.invoke(this) } @JvmOverloads inline fun Fragment.itemsAlert( @ArrayRes items: Int, @StringRes titleId: Int? = null, noinline action: (dialog: DialogInterface, Int) -> Unit, noinline init: (AlertDialog.() -> Unit)? = null ): AlertDialog = activity.itemsAlert(items, titleId, action, init)
kota/src/dialogs/ItemsAlerts.kt
3776841699
package me.mrkirby153.KirBot.command.executors.msc import me.mrkirby153.KirBot.Bot import me.mrkirby153.KirBot.command.CommandCategory import me.mrkirby153.KirBot.command.annotations.Command import me.mrkirby153.KirBot.command.annotations.CommandDescription import me.mrkirby153.KirBot.command.args.CommandContext import me.mrkirby153.KirBot.utils.Context import me.mrkirby153.KirBot.utils.globalAdmin import me.mrkirby153.kcutils.Time import net.dv8tion.jda.api.sharding.ShardManager import javax.inject.Inject import kotlin.math.roundToLong class CommandPing @Inject constructor(private val shardManager: ShardManager){ @Command(name = "ping", category = CommandCategory.MISCELLANEOUS) @CommandDescription("Check the bot's ping") fun execute(context: Context, cmdContext: CommandContext) { val start = System.currentTimeMillis() context.channel.sendTyping().queue { val stop = System.currentTimeMillis() val adminMsg = "Ping: `${Time.format(1, stop - start)}`\nHeartbeat: `${Time.format(1, context.jda.gatewayPing)}` \nAverage across all shards (${shardManager.shards.size}): `${Time.format( 1, shardManager.averageGatewayPing.roundToLong())}`" val msg = "Pong! `${Time.format(1, stop - start)}`" context.channel.sendMessage(if(context.author.globalAdmin) adminMsg else msg).queue() } } }
src/main/kotlin/me/mrkirby153/KirBot/command/executors/msc/CommandPing.kt
264087491
@file:Suppress("NOTHING_TO_INLINE", "UNUSED") package kota import android.os.Bundle import android.os.Parcelable import java.io.Serializable inline fun bundleOf(key: String, value: Boolean): Bundle = Bundle().apply { putBoolean(key, value) } inline fun bundleOf(key: String, value: Byte): Bundle = Bundle().apply { putByte(key, value) } inline fun bundleOf(key: String, value: Char): Bundle = Bundle().apply { putChar(key, value) } inline fun bundleOf(key: String, value: Short): Bundle = Bundle().apply { putShort(key, value) } inline fun bundleOf(key: String, value: Int): Bundle = Bundle().apply { putInt(key, value) } inline fun bundleOf(key: String, value: Long): Bundle = Bundle().apply { putLong(key, value) } inline fun bundleOf(key: String, value: Float): Bundle = Bundle().apply { putFloat(key, value) } inline fun bundleOf(key: String, value: Double): Bundle = Bundle().apply { putDouble(key, value) } inline fun bundleOf(key: String, value: String): Bundle = Bundle().apply { putString(key, value) } inline fun bundleOf(key: String, value: CharSequence): Bundle = Bundle().apply { putCharSequence(key, value) } inline fun bundleOf(key: String, value: Parcelable): Bundle = Bundle().apply { putParcelable(key, value) } inline fun bundleOf(key: String, value: Serializable): Bundle = Bundle().apply { putSerializable(key, value) } inline fun bundleOf(key: String, value: BooleanArray): Bundle = Bundle().apply { putBooleanArray(key, value) } inline fun bundleOf(key: String, value: ByteArray): Bundle = Bundle().apply { putByteArray(key, value) } inline fun bundleOf(key: String, value: CharArray): Bundle = Bundle().apply { putCharArray(key, value) } inline fun bundleOf(key: String, value: DoubleArray): Bundle = Bundle().apply { putDoubleArray(key, value) } inline fun bundleOf(key: String, value: FloatArray): Bundle = Bundle().apply { putFloatArray(key, value) } inline fun bundleOf(key: String, value: IntArray): Bundle = Bundle().apply { putIntArray(key, value) } inline fun bundleOf(key: String, value: LongArray): Bundle = Bundle().apply { putLongArray(key, value) } inline fun bundleOf(key: String, value: ShortArray): Bundle = Bundle().apply { putShortArray(key, value) } inline fun bundleOf(key: String, value: Bundle): Bundle = Bundle().apply { putBundle(key, value) } inline fun bundleOf(key: String, value: Array<*>): Bundle { val bundle = Bundle() @Suppress("UNCHECKED_CAST") when { value.isArrayOf<Parcelable>() -> bundle.putParcelableArray(key, value as Array<out Parcelable>) value.isArrayOf<CharSequence>() -> bundle.putCharSequenceArray(key, value as Array<out CharSequence>) value.isArrayOf<String>() -> bundle.putStringArray(key, value as Array<out String>) else -> throw IllegalStateException("Unsupported bundle component (${value.javaClass})") } return bundle } inline fun bundleOf(vararg pairs: Pair<String, Any?>): Bundle = when { pairs.isEmpty() -> Bundle.EMPTY else -> { val bundle = Bundle() pairs.forEach { (key, value) -> when (value) { null -> bundle.putSerializable(key, null) is Boolean -> bundle.putBoolean(key, value) is Byte -> bundle.putByte(key, value) is Char -> bundle.putChar(key, value) is Short -> bundle.putShort(key, value) is Int -> bundle.putInt(key, value) is Long -> bundle.putLong(key, value) is Float -> bundle.putFloat(key, value) is Double -> bundle.putDouble(key, value) is String -> bundle.putString(key, value) is CharSequence -> bundle.putCharSequence(key, value) is Parcelable -> bundle.putParcelable(key, value) is Serializable -> bundle.putSerializable(key, value) is BooleanArray -> bundle.putBooleanArray(key, value) is ByteArray -> bundle.putByteArray(key, value) is CharArray -> bundle.putCharArray(key, value) is DoubleArray -> bundle.putDoubleArray(key, value) is FloatArray -> bundle.putFloatArray(key, value) is IntArray -> bundle.putIntArray(key, value) is LongArray -> bundle.putLongArray(key, value) is Array<*> -> @Suppress("UNCHECKED_CAST") when { value.isArrayOf<Parcelable>() -> bundle.putParcelableArray(key, value as Array<out Parcelable>) value.isArrayOf<CharSequence>() -> bundle.putCharSequenceArray(key, value as Array<out CharSequence>) value.isArrayOf<String>() -> bundle.putStringArray(key, value as Array<out String>) else -> throw IllegalStateException("Unsupported bundle component (${value.javaClass})") } is ShortArray -> bundle.putShortArray(key, value) is Bundle -> bundle.putBundle(key, value) else -> throw IllegalStateException("Unsupported bundle component (${value.javaClass})") } } bundle } }
kota/src/Bundles.kt
2839687566
package com.itsronald.twenty2020.reporting import android.util.Log import com.crashlytics.android.Crashlytics import timber.log.Timber /** * A Timber Tree that logs to crash reporting services. */ class CrashLogTree : Timber.Tree() { override fun isLoggable(priority: Int): Boolean = priority >= Log.WARN override fun log(priority: Int, tag: String?, message: String?, t: Throwable?) { // Add any additional log recipients here. if (t == null) { Crashlytics.log(priority, tag, message) } else { Crashlytics.logException(t) } } }
app/src/main/java/com/itsronald/twenty2020/reporting/CrashLogTree.kt
3545198620
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.common.compose.theme import androidx.compose.material.Colors import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.compositeOver /** * Return the fully opaque color that results from compositing [onSurface] atop [surface] with the * given [alpha]. Useful for situations where semi-transparent colors are undesirable. */ fun Colors.compositedOnSurface(alpha: Float): Color { return onSurface.copy(alpha = alpha).compositeOver(surface) } private val Slate200 = Color(0xFF81A9B3) private val Slate600 = Color(0xFF4A6572) private val Slate800 = Color(0xFF232F34) private val Orange500 = Color(0xFFF9AA33) private val Orange700 = Color(0xFFC78522) val TiviLightColors = lightColors( primary = Slate800, onPrimary = Color.White, primaryVariant = Slate600, secondary = Orange700, secondaryVariant = Orange500, onSecondary = Color.Black ) val TiviDarkColors = darkColors( primary = Slate200, onPrimary = Color.Black, secondary = Orange500, onSecondary = Color.Black ).withBrandedSurface() fun Colors.withBrandedSurface() = copy( surface = primary.copy(alpha = 0.08f).compositeOver(this.surface) )
common/ui/compose/src/main/java/app/tivi/common/compose/theme/Color.kt
1570696865
package uk.terhoeven.news.tube.mapper import org.json.JSONArray import org.json.JSONObject import uk.terhoeven.news.tube.api.* import java.util.* class ResponseMapper { fun mapStatusResponse(apiResponse: JSONArray): StatusResponse { val statuses = ArrayList<LineStatus>() for (i in 0 until apiResponse.length()) { processStatuses(statuses, apiResponse.getJSONObject(i)) } return StatusResponse(statuses) } private fun processStatuses(statuses: MutableCollection<LineStatus>, lineJson: JSONObject) { val jsonStatuses = lineJson.getJSONArray("lineStatuses") for (i in 0 until jsonStatuses.length()) { val jsonStatus = jsonStatuses.getJSONObject(i) val validity = Validity(getValidityPeriods(jsonStatus.getJSONArray("validityPeriods"))) val severity = StatusSeverity.parse(jsonStatus.getString("statusSeverityDescription")) if (severity === StatusSeverity.GOOD_SERVICE) { val line = Line.parse(lineJson.getString("id")) val lineStatus = LineStatus(line, severity, validity) statuses.add(lineStatus) } else { val line = Line.parse(jsonStatus.getString("lineId")) val reason = jsonStatus.getString("reason") val disruptionJson = jsonStatus.getJSONObject("disruption") val disruption = Disruption(disruptionJson.getString("categoryDescription"), disruptionJson.getString("description")) val lineStatus = LineStatus(line, severity, validity, reason, disruption) statuses.add(lineStatus) } } } private fun getValidityPeriods(validityPeriods: JSONArray): List<ValidityPeriod> { val validities = ArrayList<ValidityPeriod>() for (i in 0 until validityPeriods.length()) { val period = validityPeriods.getJSONObject(i) validities.add(ValidityPeriod(period.getString("fromDate"), period.getString("toDate"))) } return validities } }
src/main/java/uk/terhoeven/news/tube/mapper/ResponseMapper.kt
4177194094
package com.simplemobiletools.camera.models import android.content.ContentValues import android.net.Uri import android.os.ParcelFileDescriptor import java.io.File import java.io.OutputStream sealed class MediaOutput( open val uri: Uri?, ) { sealed interface ImageCaptureOutput sealed interface VideoCaptureOutput data class MediaStoreOutput( val contentValues: ContentValues, val contentUri: Uri, ) : MediaOutput(null), ImageCaptureOutput, VideoCaptureOutput data class OutputStreamMediaOutput( val outputStream: OutputStream, override val uri: Uri, ) : MediaOutput(uri), ImageCaptureOutput data class FileDescriptorMediaOutput( val fileDescriptor: ParcelFileDescriptor, override val uri: Uri, ) : MediaOutput(uri), VideoCaptureOutput data class FileMediaOutput( val file: File, override val uri: Uri, ) : MediaOutput(uri), VideoCaptureOutput, ImageCaptureOutput object BitmapOutput : MediaOutput(null), ImageCaptureOutput }
app/src/main/kotlin/com/simplemobiletools/camera/models/MediaOutput.kt
649026734
/* * Copyright (C) 2017. Uber Technologies * * 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.uber.rib.core /** * Router for testing that does not automatically attach to the interactor. * * @param <I> */ class FakeRouter<I : Interactor<*, *>> : Router<I> { constructor(interactor: I) : super(interactor) constructor(interactor: I, ribRefWatcher: RibRefWatcher, mainThread: Thread) : super(null, interactor, ribRefWatcher, mainThread) override fun attachToInteractor() { // do not automatically attach this } }
android/libraries/rib-test/src/main/kotlin/com/uber/rib/core/FakeRouter.kt
1298912181
package ch.yvu.teststore.common interface Model
backend/src/main/kotlin/ch/yvu/teststore/common/Model.kt
3413350745
// 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devrel.imageclassifierstep1 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.google.devrel.imageclassifierstep1", appContext.packageName) } }
ODML/ImageClassificationMobile/android/ImageClassifierStep1/app/src/androidTest/java/com/google/devrel/imageclassifierstep1/ExampleInstrumentedTest.kt
4227307746
package eu.kanade.tachiyomi.data.preference import android.content.SharedPreferences import android.support.v7.preference.PreferenceDataStore class SharedPreferencesDataStore(private val prefs: SharedPreferences) : PreferenceDataStore() { override fun getBoolean(key: String?, defValue: Boolean): Boolean { return prefs.getBoolean(key, defValue) } override fun putBoolean(key: String?, value: Boolean) { prefs.edit().putBoolean(key, value).apply() } override fun getInt(key: String?, defValue: Int): Int { return prefs.getInt(key, defValue) } override fun putInt(key: String?, value: Int) { prefs.edit().putInt(key, value).apply() } override fun getLong(key: String?, defValue: Long): Long { return prefs.getLong(key, defValue) } override fun putLong(key: String?, value: Long) { prefs.edit().putLong(key, value).apply() } override fun getFloat(key: String?, defValue: Float): Float { return prefs.getFloat(key, defValue) } override fun putFloat(key: String?, value: Float) { prefs.edit().putFloat(key, value).apply() } override fun getString(key: String?, defValue: String?): String? { return prefs.getString(key, defValue) } override fun putString(key: String?, value: String?) { prefs.edit().putString(key, value).apply() } override fun getStringSet(key: String?, defValues: MutableSet<String>?): MutableSet<String> { return prefs.getStringSet(key, defValues) } override fun putStringSet(key: String?, values: MutableSet<String>?) { prefs.edit().putStringSet(key, values).apply() } }
app/src/main/java/eu/kanade/tachiyomi/data/preference/SharedPreferencesDataStore.kt
1582437316
package eu.kanade.tachiyomi.ui.migration import android.app.Dialog import android.os.Bundle import com.afollestad.materialdialogs.MaterialDialog import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.ui.base.controller.DialogController import eu.kanade.tachiyomi.ui.catalogue.global_search.CatalogueSearchController import eu.kanade.tachiyomi.ui.catalogue.global_search.CatalogueSearchPresenter import uy.kohesive.injekt.injectLazy class SearchController( private var manga: Manga? = null ) : CatalogueSearchController(manga?.title) { private var newManga: Manga? = null override fun createPresenter(): CatalogueSearchPresenter { return SearchPresenter(initialQuery, manga!!) } override fun onSaveInstanceState(outState: Bundle) { outState.putSerializable(::manga.name, manga) outState.putSerializable(::newManga.name, newManga) super.onSaveInstanceState(outState) } override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) manga = savedInstanceState.getSerializable(::manga.name) as? Manga newManga = savedInstanceState.getSerializable(::newManga.name) as? Manga } fun migrateManga() { val target = targetController as? MigrationController ?: return val manga = manga ?: return val newManga = newManga ?: return router.popController(this) target.migrateManga(manga, newManga) } fun copyManga() { val target = targetController as? MigrationController ?: return val manga = manga ?: return val newManga = newManga ?: return router.popController(this) target.copyManga(manga, newManga) } override fun onMangaClick(manga: Manga) { newManga = manga val dialog = MigrationDialog() dialog.targetController = this dialog.showDialog(router) } override fun onMangaLongClick(manga: Manga) { // Call parent's default click listener super.onMangaClick(manga) } class MigrationDialog : DialogController() { private val preferences: PreferencesHelper by injectLazy() override fun onCreateDialog(savedViewState: Bundle?): Dialog { val prefValue = preferences.migrateFlags().getOrDefault() val preselected = MigrationFlags.getEnabledFlagsPositions(prefValue) return MaterialDialog.Builder(activity!!) .content(R.string.migration_dialog_what_to_include) .items(MigrationFlags.titles.map { resources?.getString(it) }) .alwaysCallMultiChoiceCallback() .itemsCallbackMultiChoice(preselected.toTypedArray(), { _, positions, _ -> // Save current settings for the next time val newValue = MigrationFlags.getFlagsFromPositions(positions) preferences.migrateFlags().set(newValue) true }) .positiveText(R.string.migrate) .negativeText(R.string.copy) .neutralText(android.R.string.cancel) .onPositive { _, _ -> (targetController as? SearchController)?.migrateManga() } .onNegative { _, _ -> (targetController as? SearchController)?.copyManga() } .build() } } }
app/src/main/java/eu/kanade/tachiyomi/ui/migration/SearchController.kt
3842075286
/* * Copyright (C) 2019 Moez Bhatti <[email protected]> * * This file is part of QKSMS. * * QKSMS is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QKSMS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with QKSMS. If not, see <http://www.gnu.org/licenses/>. */ package com.moez.QKSMS.feature.compose.editing import com.moez.QKSMS.model.Contact import com.moez.QKSMS.model.ContactGroup import com.moez.QKSMS.model.Conversation import com.moez.QKSMS.model.PhoneNumber import io.realm.RealmList sealed class ComposeItem { abstract fun getContacts(): List<Contact> data class New(val value: Contact) : ComposeItem() { override fun getContacts(): List<Contact> = listOf(value) } data class Recent(val value: Conversation) : ComposeItem() { override fun getContacts(): List<Contact> = value.recipients.map { recipient -> recipient.contact ?: Contact(numbers = RealmList(PhoneNumber(address = recipient.address))) } } data class Starred(val value: Contact) : ComposeItem() { override fun getContacts(): List<Contact> = listOf(value) } data class Group(val value: ContactGroup) : ComposeItem() { override fun getContacts(): List<Contact> = value.contacts } data class Person(val value: Contact) : ComposeItem() { override fun getContacts(): List<Contact> = listOf(value) } }
presentation/src/main/java/com/moez/QKSMS/feature/compose/editing/ComposeItem.kt
3098773814
package com.github.alondero.formulapedia import com.github.alondero.formulapedia.drivers.DriverResource import com.github.salomonbrys.kodein.instance import io.dropwizard.Application import io.dropwizard.setup.Environment import org.eclipse.jetty.servlets.CrossOriginFilter import java.util.* import javax.servlet.DispatcherType class FormulapediaApplication: Application<FormulapediaConfiguration>() { override fun run(configuration: FormulapediaConfiguration?, environment: Environment?) { environment?.servlets()?.addFilter("CORS", CrossOriginFilter::class.java)?.apply { setInitParameter("allowedOrigins", "*") setInitParameter("allowedHeaders", "X-Requested-With,Content-Type,Accept,Origin") setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD") // Add URL mapping addMappingForUrlPatterns(EnumSet.allOf(DispatcherType::class.java), true, "/*") } configuration?.let { val kodein = ApplicationModule() environment?.let { it.jersey().register(kodein.objectGraph.instance<DriverResource>()) } } } } fun main(args: Array<String>) { FormulapediaApplication().run(*args) }
back-end/src/main/kotlin/com/github/alondero/formulapedia/application.kt
1209427917
package org.http4k.security import dev.forkhandles.result4k.Result import dev.forkhandles.result4k.mapFailure import dev.forkhandles.result4k.resultFrom import org.http4k.core.Body import org.http4k.core.ContentType.Companion.APPLICATION_FORM_URLENCODED import org.http4k.core.ContentType.Companion.APPLICATION_JSON import org.http4k.core.Response import org.http4k.lens.Header import org.http4k.security.OAuthCallbackError.CouldNotFetchAccessToken import org.http4k.security.OAuthWebForms.responseForm import org.http4k.security.oauth.server.OAuthServerMoshi.auto import org.http4k.security.openid.IdToken fun interface AccessTokenExtractor : (Response) -> Result<AccessTokenDetails, CouldNotFetchAccessToken> /** * Extracts a standard OAuth access token from JSON or Form encoded response. */ class ContentTypeJsonOrForm : AccessTokenExtractor { override fun invoke(msg: Response) = resultFrom { Header.CONTENT_TYPE(msg) ?.let { when { APPLICATION_JSON.equalsIgnoringDirectives(it) -> with(accessTokenResponseBody(msg)) { AccessTokenDetails(toAccessToken(), id_token?.let(::IdToken)) } APPLICATION_FORM_URLENCODED.equalsIgnoringDirectives(it) -> responseForm(msg) else -> null } } ?: AccessTokenDetails(AccessToken(msg.bodyString())) }.mapFailure { CouldNotFetchAccessToken(msg.status, msg.bodyString()) } } private val accessTokenResponseBody = Body.auto<AccessTokenResponse>().toLens()
http4k-security/oauth/src/main/kotlin/org/http4k/security/AccessTokenExtractor.kt
678541847
/*************************************************************************************** * Copyright (c) 2022 Ankitects Pty Ltd <https://apps.ankiweb.net> * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 3 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ package com.ichi2.anki import android.annotation.SuppressLint import android.os.Build import androidx.annotation.VisibleForTesting import anki.backend.backendError import com.ichi2.libanki.Collection import com.ichi2.libanki.CollectionV16 import com.ichi2.libanki.Storage.collection import com.ichi2.libanki.importCollectionPackage import com.ichi2.utils.Threads import kotlinx.coroutines.* import net.ankiweb.rsdroid.Backend import net.ankiweb.rsdroid.BackendException import net.ankiweb.rsdroid.BackendFactory import net.ankiweb.rsdroid.Translations import timber.log.Timber import java.io.File object CollectionManager { /** * The currently active backend, which is created on demand via [ensureBackend], and * implicitly via [ensureOpen] and routines like [withCol]. * The backend is long-lived, and will generally only be closed when switching interface * languages or changing schema versions. A closed backend cannot be reused, and a new one * must be created. */ private var backend: Backend? = null /** * The current collection, which is opened on demand via [withCol]. If you need to * close and reopen the collection in an atomic operation, add a new method that * calls [withQueue], and then executes [ensureClosedInner] and [ensureOpenInner] inside it. * A closed collection can be detected via [withOpenColOrNull] or by checking [Collection.dbClosed]. */ private var collection: Collection? = null private var queue: CoroutineDispatcher = Dispatchers.IO.limitedParallelism(1) private val robolectric = "robolectric" == Build.FINGERPRINT @VisibleForTesting var emulateOpenFailure = false /** * Execute the provided block on a serial queue, to ensure concurrent access * does not happen. * It's important that the block is not suspendable - if it were, it would allow * multiple requests to be interleaved when a suspend point was hit. */ private suspend fun<T> withQueue(block: CollectionManager.() -> T): T { return withContext(queue) { [email protected]() } } /** * Execute the provided block with the collection, opening if necessary. * * Parallel calls to this function are guaranteed to be serialized, so you can be * sure the collection won't be closed or modified by another thread. This guarantee * does not hold if legacy code calls [getColUnsafe]. */ suspend fun <T> withCol(block: Collection.() -> T): T { return withQueue { ensureOpenInner() block(collection!!) } } /** * Execute the provided block if the collection is already open. See [withCol] for more. * Since the block may return a null value, and a null value will also be returned in the * case of the collection being closed, if the calling code needs to distinguish between * these two cases, it should wrap the return value of the block in a class (eg Optional), * instead of returning a nullable object. */ suspend fun<T> withOpenColOrNull(block: Collection.() -> T): T? { return withQueue { if (collection != null && !collection!!.dbClosed) { block(collection!!) } else { null } } } /** * Return a handle to the backend, creating if necessary. This should only be used * for routines that don't depend on an open or closed collection, such as checking * the current progress state when importing a colpkg file. While the backend is * thread safe and can be accessed concurrently, if another thread closes the collection * and you call a routine that expects an open collection, it will result in an error. */ suspend fun getBackend(): Backend { return withQueue { ensureBackendInner() backend!! } } /** * Translations provided by the Rust backend/Anki desktop code. */ val TR: Translations get() { if (backend == null) { runBlocking { ensureBackend() } } // we bypass the lock here so that translations are fast - conflicts are unlikely, // as the backend is only ever changed on language preference change or schema switch return backend!!.tr } /** * Close the currently cached backend and discard it. Useful when enabling the V16 scheduler in the * dev preferences, or if the active language changes. Saves and closes the collection if open. */ suspend fun discardBackend() { withQueue { discardBackendInner() } } /** See [discardBackend]. This must only be run inside the queue. */ private fun discardBackendInner() { ensureClosedInner() if (backend != null) { backend!!.close() backend = null } } /** * Open the backend if it's not already open. */ private suspend fun ensureBackend() { withQueue { ensureBackendInner() } } /** See [ensureBackend]. This must only be run inside the queue. */ private fun ensureBackendInner() { if (backend == null) { backend = BackendFactory.getBackend(AnkiDroidApp.instance) } } /** * If the collection is open, close it. */ suspend fun ensureClosed(save: Boolean = true) { withQueue { ensureClosedInner(save = save) } } /** See [ensureClosed]. This must only be run inside the queue. */ private fun ensureClosedInner(save: Boolean = true) { if (collection == null) { return } try { collection!!.close(save = save) } catch (exc: Exception) { Timber.e("swallowing error on close: $exc") } collection = null } /** * Open the collection, if it's not already open. * * Automatically called by [withCol]. Can be called directly to ensure collection * is loaded at a certain point in time, or to ensure no errors occur. */ suspend fun ensureOpen() { withQueue { ensureOpenInner() } } /** See [ensureOpen]. This must only be run inside the queue. */ private fun ensureOpenInner() { ensureBackendInner() if (emulateOpenFailure) { throw BackendException.BackendDbException.BackendDbLockedException(backendError {}) } if (collection == null || collection!!.dbClosed) { val path = createCollectionPath() collection = collection(AnkiDroidApp.instance, path, server = false, log = true, backend) } } /** Ensures the AnkiDroid directory is created, then returns the path to the collection file * inside it. */ fun createCollectionPath(): String { val dir = CollectionHelper.getCurrentAnkiDroidDirectory(AnkiDroidApp.instance) CollectionHelper.initializeAnkiDroidDirectory(dir) return File(dir, "collection.anki2").absolutePath } /** * Like [withQueue], but can be used in a synchronous context. * * Note: Because [runBlocking] inside [runTest] will lead to * deadlocks, this will not block when run under Robolectric, * and there is no guarantee about concurrent access. */ private fun <T> blockForQueue(block: CollectionManager.() -> T): T { return if (robolectric) { block(this) } else { runBlocking { withQueue(block) } } } fun closeCollectionBlocking(save: Boolean = true) { runBlocking { ensureClosed(save = save) } } /** * Returns a reference to the open collection. This is not * safe, as code in other threads could open or close * the collection while the reference is held. [withCol] * is a better alternative. */ fun getColUnsafe(): Collection { return logUIHangs { blockForQueue { ensureOpenInner() collection!! } } } /** Execute [block]. If it takes more than 100ms of real time, Timber an error like: > Blocked main thread for 2424ms: com.ichi2.anki.DeckPicker.onCreateOptionsMenu(DeckPicker.kt:624) */ // using TimeManager breaks a sched test that makes assumptions about the time, so we // access the time directly @SuppressLint("DirectSystemCurrentTimeMillisUsage") private fun <T> logUIHangs(block: () -> T): T { val start = System.currentTimeMillis() return block().also { val elapsed = System.currentTimeMillis() - start if (Threads.isOnMainThread && elapsed > 100) { val stackTraceElements = Thread.currentThread().stackTrace // locate the probable calling file/line in the stack trace, by filtering // out our own code, and standard dalvik/java.lang stack frames val caller = stackTraceElements.filter { val klass = it.className for ( text in listOf( "CollectionManager", "dalvik", "java.lang", "CollectionHelper", "AnkiActivity" ) ) { if (text in klass) { return@filter false } } true }.first() Timber.e("blocked main thread for %dms:\n%s", elapsed, caller) } } } /** * True if the collection is open. Unsafe, as it has the potential to race. */ fun isOpenUnsafe(): Boolean { return logUIHangs { blockForQueue { if (emulateOpenFailure) { false } else { collection?.dbClosed == false } } } } /** Use [col] as collection in tests. This collection persists only up to the next (direct or indirect) call to `ensureClosed` */ fun setColForTests(col: Collection?) { blockForQueue { if (col == null) { ensureClosedInner() } collection = col } } /** * Execute block with the collection upgraded to the latest schema. * If it was previously using the legacy schema, the collection is downgraded * again after the block completes. */ private suspend fun <T> withNewSchema(block: CollectionV16.() -> T): T { return withCol { if (BackendFactory.defaultLegacySchema) { // Temporarily update to the latest schema. discardBackendInner() BackendFactory.defaultLegacySchema = false ensureOpenInner() try { (collection!! as CollectionV16).block() } finally { BackendFactory.defaultLegacySchema = true discardBackendInner() } } else { (this as CollectionV16).block() } } } /** Upgrade from v1 to v2 scheduler. * Caller must have confirmed schema modification already. */ suspend fun updateScheduler() { withNewSchema { sched.upgradeToV2() } } /** * Replace the collection with the provided colpkg file if it is valid. */ suspend fun importColpkg(colpkgPath: String) { withQueue { ensureClosedInner() ensureBackendInner() importCollectionPackage(backend!!, createCollectionPath(), colpkgPath) } } fun setTestDispatcher(dispatcher: CoroutineDispatcher) { // note: we avoid the call to .limitedParallelism() here, // as it does not seem to be compatible with the test scheduler queue = dispatcher } }
AnkiDroid/src/main/java/com/ichi2/anki/CollectionManager.kt
3045997581
package com.baculsoft.sample.kotlinreactive.observable import android.annotation.SuppressLint import android.support.v4.content.ContextCompat import android.view.Gravity import com.baculsoft.sample.kotlinreactive.R import org.jetbrains.anko.AnkoComponent import org.jetbrains.anko.AnkoContext import org.jetbrains.anko.alignParentBottom import org.jetbrains.anko.alignParentTop import org.jetbrains.anko.appcompat.v7.toolbar import org.jetbrains.anko.backgroundColor import org.jetbrains.anko.below import org.jetbrains.anko.bottomPadding import org.jetbrains.anko.button import org.jetbrains.anko.centerInParent import org.jetbrains.anko.design.appBarLayout import org.jetbrains.anko.design.coordinatorLayout import org.jetbrains.anko.dip import org.jetbrains.anko.matchParent import org.jetbrains.anko.relativeLayout import org.jetbrains.anko.textColor import org.jetbrains.anko.textView import org.jetbrains.anko.topPadding import org.jetbrains.anko.wrapContent class ObservableUI : AnkoComponent<ObservableActivity> { @SuppressLint("NewApi") override fun createView(ui: AnkoContext<ObservableActivity>) = with(ui) { coordinatorLayout { id = R.id.content_observable backgroundColor = ContextCompat.getColor(ctx, R.color.colorPrimary) relativeLayout { appBarLayout { id = R.id.abl_observable backgroundColor = ContextCompat.getColor(ctx, R.color.colorAccent) elevation = dip(4).toFloat() toolbar { id = R.id.toolbar_observable setTitleTextColor(ContextCompat.getColor(ctx, R.color.colorPrimary)) }.lparams { width = matchParent height = wrapContent } }.lparams { alignParentTop() width = matchParent height = wrapContent } textView { id = R.id.tv_observable text = ctx.resources.getString(R.string.text_observable) textColor = ContextCompat.getColor(ctx, R.color.colorPrimaryDark) textSize = 16f gravity = Gravity.CENTER }.lparams { below(R.id.abl_observable) centerInParent() width = matchParent height = wrapContent } button { id = R.id.btn_observable text = ctx.resources.getString(R.string.btn_subscribe) textColor = ContextCompat.getColor(ctx, R.color.colorPrimaryDark) textSize = 16f topPadding = dip(16) bottomPadding = dip(16) }.lparams { alignParentBottom() width = matchParent height = wrapContent marginEnd = dip(16) marginStart = dip(16) bottomPadding = dip(8) } } } } }
app/src/main/kotlin/com/baculsoft/sample/kotlinreactive/observable/ObservableUI.kt
276877837
package org.cf.sdbg.command import org.cf.util.ClassNameUtils import picocli.CommandLine import picocli.CommandLine.ParentCommand sealed class BreakTarget data class BreakTargetMethod(val methodSignature: String) : BreakTarget() data class BreakTargetIndex(val index: Int) : BreakTarget() object BreakTargetInvalid : BreakTarget() @CommandLine.Command(name = "break", aliases = ["b"], mixinStandardHelpOptions = true, version = ["1.0"], description = ["Suspend program at specified function, instruction index, or index offset"]) class BreakCommand : DebuggerCommand() { @ParentCommand lateinit var parent: CliCommands @CommandLine.Parameters(index = "0", arity = "0..1", paramLabel = "TARGET", description = ["index-number | method | class->method | +offset | -offset"]) var target: String? = null private fun parseTarget(target: String?): BreakTarget { if (target == null) { return BreakTargetIndex(debugger.currentIndex) } val guessedType = ClassNameUtils.guessReferenceType(target) return when { target.startsWith('-') || target.startsWith('+') -> { val offset = target.toIntOrNull() ?: return BreakTargetInvalid BreakTargetIndex(debugger.currentIndex + offset) } guessedType == ClassNameUtils.ReferenceType.INTERNAL_METHOD_SIGNATURE -> BreakTargetMethod(target) guessedType == ClassNameUtils.ReferenceType.INTERNAL_METHOD_DESCRIPTOR -> { val className = debugger.executionGraph.method.className BreakTargetMethod("$className->$target") } target.toIntOrNull() != null -> BreakTargetIndex(index = target.toInt()) else -> BreakTargetInvalid } } private fun printInvalid(message: String) { parent.out.println("invalid target; $message") } override fun run() { when (val parsedTarget = parseTarget(target)) { is BreakTargetMethod -> { val method = debugger.classManager.getMethod(parsedTarget.methodSignature) if (method == null) { printInvalid("method not found") return } if (!method.hasImplementation()) { printInvalid("method has no implementation") } debugger.addBreakpoint(parsedTarget.methodSignature, 0) parent.out.println("breakpoint set for ${parsedTarget.methodSignature}") } is BreakTargetIndex -> { val method = debugger.currentMethod if (method.implementation.instructions.size < parsedTarget.index) { parent.out.println("instr size: ${method.implementation.instructions.size}") printInvalid("index out of range") return } debugger.addBreakpoint(debugger.currentMethodSignature, parsedTarget.index) parent.out.println("breakpoint set for ${debugger.currentMethodSignature} @ ${parsedTarget.index}") } is BreakTargetInvalid -> { printInvalid("unable to parse") return } } } }
sdbg/src/main/java/org/cf/sdbg/command/BreakCommand.kt
2291556335
package com.infinum.dbinspector.ui.content.shared.drop import android.os.Bundle import android.view.View import androidx.annotation.StringRes import androidx.core.os.bundleOf import androidx.fragment.app.setFragmentResult import com.infinum.dbinspector.R import com.infinum.dbinspector.databinding.DbinspectorDialogDropContentBinding import com.infinum.dbinspector.ui.Presentation.Constants.Keys.DROP_CONTENT import com.infinum.dbinspector.ui.Presentation.Constants.Keys.DROP_MESSAGE import com.infinum.dbinspector.ui.Presentation.Constants.Keys.DROP_NAME import com.infinum.dbinspector.ui.shared.base.BaseBottomSheetDialogFragment import com.infinum.dbinspector.ui.shared.base.BaseViewModel import com.infinum.dbinspector.ui.shared.delegates.viewBinding internal class DropContentDialog : BaseBottomSheetDialogFragment<Any, Any>(R.layout.dbinspector_dialog_drop_content) { companion object { fun setMessage(@StringRes drop: Int, name: String): DropContentDialog { val fragment = DropContentDialog() fragment.arguments = Bundle().apply { putInt(DROP_MESSAGE, drop) putString(DROP_NAME, name) } return fragment } } override val binding: DbinspectorDialogDropContentBinding by viewBinding( DbinspectorDialogDropContentBinding::bind ) override val viewModel: BaseViewModel<Any, Any>? = null @StringRes private var drop: Int? = null private var name: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { drop = it.getInt(DROP_MESSAGE) name = it.getString(DROP_NAME) } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) with(binding) { toolbar.setNavigationOnClickListener { dismiss() } messageView.text = drop?.let { String.format(getString(it), name.orEmpty()) } dropButton.setOnClickListener { setFragmentResult( DROP_CONTENT, bundleOf( DROP_NAME to name ) ) dismiss() } } } override fun onState(state: Any) = Unit override fun onEvent(event: Any) = Unit }
dbinspector/src/main/kotlin/com/infinum/dbinspector/ui/content/shared/drop/DropContentDialog.kt
1806755552
package com.octaldata.session import com.octaldata.domain.topics.TopicName import com.sksamuel.tabby.results.success import kotlin.time.Duration interface SubscriptionOps { suspend fun getSubscriptions(topicName: TopicName): Result<List<String>> suspend fun deleteSubscription(topicName: TopicName, subscription: String): Result<Boolean> suspend fun expireSub(topicName: TopicName, time: Duration): Result<Boolean> suspend fun expireMessages(topicName: TopicName, subscription: String, time: Duration): Result<Boolean> suspend fun skipAllMessages(topicName: TopicName, subscription: String): Result<Boolean> } object NoopSubscriptionOps : SubscriptionOps { override suspend fun deleteSubscription(topicName: TopicName, subscription: String) = false.success() override suspend fun getSubscriptions(topicName: TopicName): Result<List<String>> = Result.success(emptyList()) override suspend fun expireMessages(topicName: TopicName, subscription: String, time: Duration) = false.success() override suspend fun expireSub(topicName: TopicName, time: Duration) = false.success() override suspend fun skipAllMessages(topicName: TopicName, subscription: String) = false.success() }
streamops-session/src/main/kotlin/com/octaldata/session/SubscriptionOps.kt
1930352380
package com.octaldata.datastore import com.octaldata.datastore.pipelines.PipelineDatastore import com.octaldata.domain.DeploymentId import com.octaldata.domain.auth.UserId import com.octaldata.domain.integrations.IntegrationId import com.octaldata.domain.pipelines.Pipeline import com.octaldata.domain.pipelines.PipelineId import com.octaldata.domain.pipelines.PipelineName import com.octaldata.domain.pipelines.PipelineStatus import io.kotest.core.extensions.install import io.kotest.core.spec.style.FunSpec import io.kotest.extensions.testcontainers.JdbcTestContainerExtension import io.kotest.matchers.nulls.shouldBeNull import io.kotest.matchers.shouldBe import org.flywaydb.core.Flyway import org.testcontainers.containers.MySQLContainer import java.time.Instant class PipelineDatastoreTest : FunSpec({ val mysql = MySQLContainer<Nothing>("mysql:8.0.26").apply { startupAttempts = 1 withUrlParam("connectionTimeZone", "Z") withUrlParam("zeroDateTimeBehavior", "convertToNull") } val ds = install(JdbcTestContainerExtension(mysql)) { poolName = "myconnectionpool" maximumPoolSize = 8 idleTimeout = 10000 } Class.forName(com.mysql.jdbc.Driver::class.java.name) Flyway .configure() .dataSource(ds) .locations("classpath:changesets") .load() .migrate() val datastore = PipelineDatastore(ds) test("insert happy path") { datastore.insert( Pipeline( id = PipelineId("a"), deploymentId = DeploymentId("kafka1"), name = PipelineName("pipelinea"), status = PipelineStatus.Paused, query = "select * from foo", createdTs = Instant.ofEpochSecond(123), createdUser = UserId("samsam"), seek = "seek", integrationId = null, ) ).getOrThrow() datastore.insert( Pipeline( id = PipelineId("b"), deploymentId = DeploymentId("kafka2"), name = PipelineName("pipelineb"), status = PipelineStatus.Deleted, query = "select * from bar", createdTs = Instant.ofEpochSecond(444), createdUser = UserId("bobbob"), seek = "seek", integrationId = IntegrationId("abd"), ) ).getOrThrow() datastore.findAll().getOrThrow().toSet().shouldBe( setOf( Pipeline( id = PipelineId("a"), deploymentId = DeploymentId("kafka1"), name = PipelineName("pipelinea"), status = PipelineStatus.Paused, query = "select * from foo", createdTs = Instant.ofEpochSecond(123), createdUser = UserId("samsam"), seek = "seek", integrationId = null, ), Pipeline( id = PipelineId("b"), deploymentId = DeploymentId("kafka2"), name = PipelineName("pipelineb"), status = PipelineStatus.Deleted, query = "select * from bar", createdTs = Instant.ofEpochSecond(444), createdUser = UserId("bobbob"), seek = "seek", integrationId = IntegrationId("abd"), ) ) ) } test("get by id") { datastore.getById(PipelineId("a")).getOrThrow().shouldBe( Pipeline( id = PipelineId("a"), deploymentId = DeploymentId("kafka1"), name = PipelineName("pipelinea"), status = PipelineStatus.Paused, query = "select * from foo", createdTs = Instant.ofEpochSecond(123), createdUser = UserId("samsam"), seek = "seek", integrationId = null, ) ) } test("get by id for non existing id") { datastore.getById(PipelineId("qwerty")).getOrThrow().shouldBeNull() } })
streamops-datastore/src/test/kotlin/com/octaldata/datastore/PipelineDatastoreTest.kt
875644912
package com.sergey.spacegame.common.ecs.component import com.badlogic.ashley.core.Component import com.badlogic.ashley.core.ComponentMapper import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.google.gson.JsonObject import com.google.gson.JsonParseException import com.google.gson.JsonSerializationContext import com.google.gson.JsonSerializer import com.sergey.spacegame.common.SpaceGame import com.sergey.spacegame.common.data.VisualData import java.lang.reflect.Type /** * This component contains the visual data * * @author sergeys * * @constructor Create a new VisualComponent object * * @param regionName - the name of the texture region */ class VisualComponent(regionName: String) : ClonableComponent { /** * The texture region's name */ var regionName: String = regionName set(value) { visualData = SpaceGame.getInstance().context.createVisualData(value) field = value } /** * The visual data object used for client side rendering */ var visualData: VisualData? = SpaceGame.getInstance().context.createVisualData(regionName) private set override fun copy(): Component { return VisualComponent(regionName) } companion object MAP { @JvmField val MAPPER = ComponentMapper.getFor(VisualComponent::class.java)!! } class Adapter : JsonSerializer<VisualComponent>, JsonDeserializer<VisualComponent> { @Throws(JsonParseException::class) override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): VisualComponent { val obj = json.asJsonObject return VisualComponent(obj.get("image").asString) } override fun serialize(src: VisualComponent, typeOfSrc: Type, context: JsonSerializationContext): JsonElement { val obj = JsonObject() obj.addProperty("image", src.regionName) return obj } } }
core/src/com/sergey/spacegame/common/ecs/component/VisualComponent.kt
3218081352
/* * Copyright (c) 2017. Toshi Inc * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.toshi.keywordFinder import com.toshi.util.spannables.Keyword data class KeywordTestData( val testText: String, val expectedKeywords: List<Keyword> )
app/src/androidTest/java/com/toshi/keywordFinder/KeywordTestData.kt
1527904289
package com.octaldata.session import com.octaldata.domain.BrokerId import com.octaldata.domain.structure.SchemaField import com.octaldata.domain.topics.ExtendedTopic import com.octaldata.domain.topics.LightTopic import com.octaldata.domain.topics.Offset import com.octaldata.domain.topics.Partition import com.octaldata.domain.topics.PartitionId import com.octaldata.domain.topics.TopicConfigs import com.octaldata.domain.topics.TopicName import kotlin.math.max import kotlin.time.Duration interface TopicOps { /** * Returns just the table names for a session. This is useful for populating lists where extended * details are not needed and would result in a much longer latency fetching things we don't need. */ suspend fun topicNames(): Result<List<TopicName>> /** * Returns basic information about all topics for the topic overviw page. * It is permitted for the implementation to restrict the number of results. */ suspend fun topics(filter: String?): Result<List<LightTopic>> /** * Returns configuration information about the named topic. */ suspend fun config(topicName: TopicName): Result<TopicConfigs> suspend fun compressionType(topicName: TopicName): Result<CompressionType> /** * Returns extends details on a single topic. * May provide more information than the [topics] call. */ suspend fun topic(topicName: TopicName): Result<ExtendedTopic> suspend fun drop(topicName: TopicName): Result<Boolean> suspend fun truncate(topicName: TopicName): Result<Boolean> suspend fun create( topicName: TopicName, partitions: Int, replicationFactor: Int, retention: Long?, compacted: Boolean, ): Result<Boolean> /** * Returns a flat schema for the given [topicName]. */ suspend fun schema(topicName: TopicName): Result<List<SchemaField>> suspend fun deleteRecords(topicName: TopicName, partitions: Set<Int>, offset: Long): Result<Unit> suspend fun repartition(topicName: TopicName, count: Int): Result<Boolean> suspend fun setConfig(topicName: TopicName, key: String, value: String): Result<Boolean> suspend fun assignPartitions(topicName: TopicName, assignments: Map<PartitionId, Set<BrokerId>>): Result<Boolean> suspend fun triggerCompaction(topicName: TopicName): Result<Boolean> suspend fun expireMessagesForAllSubscriptions(topicName: TopicName, time: Duration): Result<Boolean> suspend fun insert(topicName: TopicName, req: InsertRecordRequest): Result<Boolean> /** * Returns the number of messages on each partition for this [topicName]. */ suspend fun partitionMessageDistribution(topicName: TopicName): Result<PartitionMessageDistribution> /** * Returns the partitions hosted by each broker for the given [topicName]. */ suspend fun brokerPartitionDistribution(topicName: TopicName): Result<PartitionBrokerSpread> /** * Returns the replication factor for the given topic. */ suspend fun replicationFactor(topicName: TopicName): Result<Int> /** * Sets the replication factor for a given topic. */ suspend fun setReplicationFactor(topicName: TopicName, count: Int): Result<Boolean> /** * Sets the [compressionType] for the given topic. */ suspend fun setCompression(topicName: TopicName, compressionType: String): Result<Boolean> suspend fun electLeaders( topicName: TopicName, electionType: ElectionType, ): Result<Unit> suspend fun specifyLeader( topicName: TopicName, partitionId: PartitionId, leader: BrokerId, ): Result<Unit> suspend fun partitions(topicName: TopicName): Result<List<Partition>> suspend fun count(topicName: TopicName): Result<Long> suspend fun countByPartition(topicName: TopicName): Result<Map<PartitionId, Long>> suspend fun offsets(topicName: TopicName, partitionIds: Set<PartitionId>): Result<List<TopicPartitionOffsets>> suspend fun truncatePartition(topicName: TopicName, partitionId: PartitionId): Result<Boolean> } enum class ElectionType { UNCLEAN, PREFERRED } data class PartitionMessageDistribution( val topicName: TopicName, val distributions: List<MessageDistribution>, ) data class TopicPartitionOffsets( val topicName: TopicName, val partitionId: PartitionId, val start: Offset, val end: Offset, ) { val count: Long = max(0, end.value - start.value) } data class PartitionBrokerSpread( val topicName: TopicName, val partitions: Int, val brokers: Int, val targetCount: Int, val targetPercent: Int, val distributions: List<BrokerDistribution>, ) data class MessageDistribution( val partitionId: PartitionId, val count: Long, val percentage: Int, ) data class BrokerDistribution( val brokerId: BrokerId, val count: Int, val percentage: Int, ) enum class CompressionType { Zstd, LZ4, Gzip, None, Producer, Snappy } data class Header(val name: String, val value: String) data class InsertRecordRequest( val headers: List<Header>, val partition: Int?, val keyFormat: String, val valueFormat: String, val key: String?, val value: String )
streamops-session/src/main/kotlin/com/octaldata/session/TopicOps.kt
3574208081
package antimattermod.core.Util.Gui import net.minecraft.client.Minecraft import net.minecraft.client.gui.Gui import net.minecraft.client.gui.GuiButton import net.minecraft.client.gui.inventory.GuiContainer import net.minecraft.client.renderer.Tessellator import net.minecraft.inventory.Container import net.minecraft.inventory.IInventory import net.minecraft.inventory.Slot import net.minecraft.item.ItemStack import org.lwjgl.opengl.GL11 /** * Created by kojin15. */ object GuiHelper { fun drawTexturedClear(x: Int, y: Int, u: Int, v: Int, width: Int, height: Int, alpha: Double, zLevel: Float) { GL11.glEnable(GL11.GL_BLEND) GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA) GL11.glColor4d(2.0, 2.0, 2.0, alpha) val f = 0.00390625f val f1 = 0.00390625f val tessellator = Tessellator.instance tessellator.startDrawingQuads() tessellator.addVertexWithUV((x + 0).toDouble(), (y + height).toDouble(), zLevel.toDouble(), ((u + 0).toFloat() * f).toDouble(), ((v + height).toFloat() * f1).toDouble()) tessellator.addVertexWithUV((x + width).toDouble(), (y + height).toDouble(), zLevel.toDouble(), ((u + width).toFloat() * f).toDouble(), ((v + height).toFloat() * f1).toDouble()) tessellator.addVertexWithUV((x + width).toDouble(), (y + 0).toDouble(), zLevel.toDouble(), ((u + width).toFloat() * f).toDouble(), ((v + 0).toFloat() * f1).toDouble()) tessellator.addVertexWithUV((x + 0).toDouble(), (y + 0).toDouble(), zLevel.toDouble(), ((u + 0).toFloat() * f).toDouble(), ((v + 0).toFloat() * f1).toDouble()) tessellator.draw() GL11.glDisable(GL11.GL_BLEND) } /** * ボタンの描画 * @param button 描画するボタン * @param isPush 押されているかどうか */ fun drawTextureButton(button: TextureButton?, textureU: Int, textureV: Int, alpha: Double, isPush: Boolean) { if (button != null) { when (isPush) { false -> GuiHelper.drawTexturedClear(button.xPosition, button.yPosition, textureU, textureV, button.width, button.height, alpha, button.zTLevel) true -> GuiHelper.drawTexturedClear(button.xPosition, button.yPosition, textureU + button.width, textureV, button.width, button.height, alpha, button.zTLevel) } } } } /** * 描画を変更する時のボタン */ class TextureButton(id: Int, xPosition: Int, yPosition: Int, width: Int, height: Int) : GuiButton(id, xPosition, yPosition, width, height, null) { val zTLevel: Float = zLevel override fun drawButton(minecraft: Minecraft?, x: Int, y: Int) { } } /** * 何も描画しないボタン */ class ClearButton(id: Int, xPosition: Int, yPosition: Int, width: Int, height: Int) : GuiButton(id, xPosition, yPosition, width, height, null) { override fun drawButton(minecraft: Minecraft?, x: Int, y: Int) { } } class SlotBase(inventory: IInventory, slotIndex: Int, xDisplayPosition: Int, yDisplayPosition: Int, private val canIn: Boolean, private val canOut: Boolean) : Slot(inventory, slotIndex, xDisplayPosition, yDisplayPosition) { override fun putStack(p_75215_1_: ItemStack?) { if (canIn) super.putStack(p_75215_1_) } override fun decrStackSize(p_75209_1_: Int): ItemStack? { if (canOut) { return super.decrStackSize(p_75209_1_) } else return null } }
src/main/java/antimattermod/core/Util/Gui/GuiHelper.kt
1880520399
/* * Copyright 2017-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ @file:OptIn(ExperimentalSerializationApi::class) package kotlinx.serialization.json.internal import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* import kotlinx.serialization.internal.* import kotlinx.serialization.json.* import kotlinx.serialization.modules.* import kotlin.collections.set import kotlin.jvm.* @InternalSerializationApi public fun <T> Json.writeJson(value: T, serializer: SerializationStrategy<T>): JsonElement { lateinit var result: JsonElement val encoder = JsonTreeEncoder(this) { result = it } encoder.encodeSerializableValue(serializer, value) return result } @ExperimentalSerializationApi private sealed class AbstractJsonTreeEncoder( final override val json: Json, private val nodeConsumer: (JsonElement) -> Unit ) : NamedValueEncoder(), JsonEncoder { final override val serializersModule: SerializersModule get() = json.serializersModule @JvmField protected val configuration = json.configuration private var polymorphicDiscriminator: String? = null override fun encodeJsonElement(element: JsonElement) { encodeSerializableValue(JsonElementSerializer, element) } override fun shouldEncodeElementDefault(descriptor: SerialDescriptor, index: Int): Boolean = configuration.encodeDefaults override fun composeName(parentName: String, childName: String): String = childName abstract fun putElement(key: String, element: JsonElement) abstract fun getCurrent(): JsonElement // has no tag when encoding a nullable element at root level override fun encodeNotNullMark() {} // has no tag when encoding a nullable element at root level override fun encodeNull() { val tag = currentTagOrNull ?: return nodeConsumer(JsonNull) encodeTaggedNull(tag) } override fun encodeTaggedNull(tag: String) = putElement(tag, JsonNull) override fun encodeTaggedInt(tag: String, value: Int) = putElement(tag, JsonPrimitive(value)) override fun encodeTaggedByte(tag: String, value: Byte) = putElement(tag, JsonPrimitive(value)) override fun encodeTaggedShort(tag: String, value: Short) = putElement(tag, JsonPrimitive(value)) override fun encodeTaggedLong(tag: String, value: Long) = putElement(tag, JsonPrimitive(value)) override fun encodeTaggedFloat(tag: String, value: Float) { // First encode value, then check, to have a prettier error message putElement(tag, JsonPrimitive(value)) if (!configuration.allowSpecialFloatingPointValues && !value.isFinite()) { throw InvalidFloatingPointEncoded(value, tag, getCurrent().toString()) } } override fun <T> encodeSerializableValue(serializer: SerializationStrategy<T>, value: T) { // Writing non-structured data (i.e. primitives) on top-level (e.g. without any tag) requires special output if (currentTagOrNull != null || !serializer.descriptor.carrierDescriptor(serializersModule).requiresTopLevelTag) { encodePolymorphically(serializer, value) { polymorphicDiscriminator = it } } else JsonPrimitiveEncoder(json, nodeConsumer).apply { encodeSerializableValue(serializer, value) endEncode(serializer.descriptor) } } override fun encodeTaggedDouble(tag: String, value: Double) { // First encode value, then check, to have a prettier error message putElement(tag, JsonPrimitive(value)) if (!configuration.allowSpecialFloatingPointValues && !value.isFinite()) { throw InvalidFloatingPointEncoded(value, tag, getCurrent().toString()) } } override fun encodeTaggedBoolean(tag: String, value: Boolean) = putElement(tag, JsonPrimitive(value)) override fun encodeTaggedChar(tag: String, value: Char) = putElement(tag, JsonPrimitive(value.toString())) override fun encodeTaggedString(tag: String, value: String) = putElement(tag, JsonPrimitive(value)) override fun encodeTaggedEnum( tag: String, enumDescriptor: SerialDescriptor, ordinal: Int ) = putElement(tag, JsonPrimitive(enumDescriptor.getElementName(ordinal))) override fun encodeTaggedValue(tag: String, value: Any) { putElement(tag, JsonPrimitive(value.toString())) } @SuppressAnimalSniffer // Long(Integer).toUnsignedString(long) override fun encodeTaggedInline(tag: String, inlineDescriptor: SerialDescriptor): Encoder = if (inlineDescriptor.isUnsignedNumber) object : AbstractEncoder() { override val serializersModule: SerializersModule = json.serializersModule fun putUnquotedString(s: String) = putElement(tag, JsonLiteral(s, isString = false)) override fun encodeInt(value: Int) = putUnquotedString(value.toUInt().toString()) override fun encodeLong(value: Long) = putUnquotedString(value.toULong().toString()) override fun encodeByte(value: Byte) = putUnquotedString(value.toUByte().toString()) override fun encodeShort(value: Short) = putUnquotedString(value.toUShort().toString()) } else super.encodeTaggedInline(tag, inlineDescriptor) override fun beginStructure(descriptor: SerialDescriptor): CompositeEncoder { val consumer = if (currentTagOrNull == null) nodeConsumer else { node -> putElement(currentTag, node) } val encoder = when (descriptor.kind) { StructureKind.LIST, is PolymorphicKind -> JsonTreeListEncoder(json, consumer) StructureKind.MAP -> json.selectMapMode( descriptor, { JsonTreeMapEncoder(json, consumer) }, { JsonTreeListEncoder(json, consumer) } ) else -> JsonTreeEncoder(json, consumer) } if (polymorphicDiscriminator != null) { encoder.putElement(polymorphicDiscriminator!!, JsonPrimitive(descriptor.serialName)) polymorphicDiscriminator = null } return encoder } override fun endEncode(descriptor: SerialDescriptor) { nodeConsumer(getCurrent()) } } private val SerialDescriptor.requiresTopLevelTag: Boolean get() = kind is PrimitiveKind || kind === SerialKind.ENUM internal const val PRIMITIVE_TAG = "primitive" // also used in JsonPrimitiveInput private class JsonPrimitiveEncoder( json: Json, nodeConsumer: (JsonElement) -> Unit ) : AbstractJsonTreeEncoder(json, nodeConsumer) { private var content: JsonElement? = null init { pushTag(PRIMITIVE_TAG) } override fun putElement(key: String, element: JsonElement) { require(key === PRIMITIVE_TAG) { "This output can only consume primitives with '$PRIMITIVE_TAG' tag" } require(content == null) { "Primitive element was already recorded. Does call to .encodeXxx happen more than once?" } content = element } override fun getCurrent(): JsonElement = requireNotNull(content) { "Primitive element has not been recorded. Is call to .encodeXxx is missing in serializer?" } } private open class JsonTreeEncoder( json: Json, nodeConsumer: (JsonElement) -> Unit ) : AbstractJsonTreeEncoder(json, nodeConsumer) { protected val content: MutableMap<String, JsonElement> = linkedMapOf() override fun putElement(key: String, element: JsonElement) { content[key] = element } override fun <T : Any> encodeNullableSerializableElement( descriptor: SerialDescriptor, index: Int, serializer: SerializationStrategy<T>, value: T? ) { if (value != null || configuration.explicitNulls) { super.encodeNullableSerializableElement(descriptor, index, serializer, value) } } override fun getCurrent(): JsonElement = JsonObject(content) } private class JsonTreeMapEncoder(json: Json, nodeConsumer: (JsonElement) -> Unit) : JsonTreeEncoder(json, nodeConsumer) { private lateinit var tag: String private var isKey = true override fun putElement(key: String, element: JsonElement) { if (isKey) { // writing key tag = when (element) { is JsonPrimitive -> element.content is JsonObject -> throw InvalidKeyKindException(JsonObjectSerializer.descriptor) is JsonArray -> throw InvalidKeyKindException(JsonArraySerializer.descriptor) } isKey = false } else { content[tag] = element isKey = true } } override fun getCurrent(): JsonElement { return JsonObject(content) } } private class JsonTreeListEncoder(json: Json, nodeConsumer: (JsonElement) -> Unit) : AbstractJsonTreeEncoder(json, nodeConsumer) { private val array: ArrayList<JsonElement> = arrayListOf() override fun elementName(descriptor: SerialDescriptor, index: Int): String = index.toString() override fun putElement(key: String, element: JsonElement) { val idx = key.toInt() array.add(idx, element) } override fun getCurrent(): JsonElement = JsonArray(array) } @OptIn(ExperimentalSerializationApi::class) internal inline fun <reified T : JsonElement> cast(value: JsonElement, descriptor: SerialDescriptor): T { if (value !is T) { throw JsonDecodingException( -1, "Expected ${T::class} as the serialized body of ${descriptor.serialName}, but had ${value::class}" ) } return value }
formats/json/commonMain/src/kotlinx/serialization/json/internal/TreeJsonEncoder.kt
518908769
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.network.vanilla.packet.handler.play import org.lanternpowered.server.network.NetworkContext import org.lanternpowered.server.network.packet.PacketHandler import org.lanternpowered.server.network.vanilla.packet.type.play.ClientPlayerSwingArmPacket object ClientPlayerSwingArmHandler : PacketHandler<ClientPlayerSwingArmPacket> { override fun handle(ctx: NetworkContext, packet: ClientPlayerSwingArmPacket) { val player = ctx.session.player player.resetIdleTime() player.resetOpenedSignPosition() player.interactionHandler.handleSwingArm(packet) } }
src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/handler/play/ClientPlayerSwingArmHandler.kt
2765782810
package com.github.tommykw.tv.activity import android.app.Activity import android.graphics.Bitmap import android.media.MediaMetadata import android.media.MediaPlayer import android.media.session.MediaSession import android.media.session.PlaybackState import android.net.Uri import android.os.Bundle import android.view.KeyEvent import android.widget.VideoView import com.bumptech.glide.Glide import com.bumptech.glide.request.animation.GlideAnimation import com.bumptech.glide.request.target.SimpleTarget import com.github.tommykw.tv.fragment.PlaybackOverlayFragment import com.github.tommykw.tv.R import com.github.tommykw.tv.model.Movie class PlaybackOverlayActivity : BaseActivity(), PlaybackOverlayFragment.OnPlayPauseClickedListener { private val mVideoView by lazy { findViewById(R.id.videoView) as VideoView } private var mPlaybackState = LeanbackPlaybackState.IDLE private var mSession = MediaSession(this, "LeanbackSampleApp") public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.playback_controls) loadViews() setupCallbacks() mSession.apply { setCallback(MediaSessionCallback()) setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS or MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS) isActive = true } } public override fun onDestroy() { super.onDestroy() mVideoView.suspend() } override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean { val playbackOverlayFragment = fragmentManager.findFragmentById(R.id.playback_controls_fragment) as PlaybackOverlayFragment when (keyCode) { KeyEvent.KEYCODE_MEDIA_PLAY -> { playbackOverlayFragment.togglePlayback(false) return true } KeyEvent.KEYCODE_MEDIA_PAUSE -> { playbackOverlayFragment.togglePlayback(false) return true } KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE -> { if (mPlaybackState == LeanbackPlaybackState.PLAYING) { playbackOverlayFragment.togglePlayback(false) } else { playbackOverlayFragment.togglePlayback(true) } return true } else -> return super.onKeyUp(keyCode, event) } } override fun onFragmentPlayPause(movie: Movie, position: Int, playPause: Boolean?) { mVideoView.setVideoPath(movie.videoUrl) if (position == 0 || mPlaybackState == LeanbackPlaybackState.IDLE) { setupCallbacks() mPlaybackState = LeanbackPlaybackState.IDLE } if (playPause!! && mPlaybackState != LeanbackPlaybackState.PLAYING) { mPlaybackState = LeanbackPlaybackState.PLAYING if (position > 0) { mVideoView.seekTo(position) mVideoView.start() } } else { mPlaybackState = LeanbackPlaybackState.PAUSED mVideoView.pause() } updatePlaybackState(position) updateMetadata(movie) } private fun updatePlaybackState(position: Int) { val stateBuilder = PlaybackState.Builder() .setActions(availableActions) var state = PlaybackState.STATE_PLAYING if (mPlaybackState == LeanbackPlaybackState.PAUSED) { state = PlaybackState.STATE_PAUSED } stateBuilder.setState(state, position.toLong(), 1.0f) mSession.setPlaybackState(stateBuilder.build()) } private val availableActions: Long get() { var actions = PlaybackState.ACTION_PLAY or PlaybackState.ACTION_PLAY_FROM_MEDIA_ID or PlaybackState.ACTION_PLAY_FROM_SEARCH if (mPlaybackState == LeanbackPlaybackState.PLAYING) { actions = actions or PlaybackState.ACTION_PAUSE } return actions } private fun updateMetadata(movie: Movie) { val metadataBuilder = MediaMetadata.Builder() val title = movie.title!!.replace("_", " -") metadataBuilder.putString(MediaMetadata.METADATA_KEY_DISPLAY_TITLE, title) metadataBuilder.putString(MediaMetadata.METADATA_KEY_DISPLAY_SUBTITLE, movie.description) metadataBuilder.putString(MediaMetadata.METADATA_KEY_DISPLAY_ICON_URI, movie.cardImageUrl) // And at minimum the title and artist for legacy support metadataBuilder.putString(MediaMetadata.METADATA_KEY_TITLE, title) metadataBuilder.putString(MediaMetadata.METADATA_KEY_ARTIST, movie.studio) Glide.with(this) .load(Uri.parse(movie.cardImageUrl)) .asBitmap() .into(object : SimpleTarget<Bitmap>(500, 500) { override fun onResourceReady(resource: Bitmap?, glideAnimation: GlideAnimation<in Bitmap>?) { metadataBuilder.putBitmap(MediaMetadata.METADATA_KEY_ART, resource) mSession.setMetadata(metadataBuilder.build()) } }) } private fun loadViews() { mVideoView.isFocusable = false mVideoView.isFocusableInTouchMode = false } private fun setupCallbacks() { mVideoView.setOnErrorListener { mp, what, extra -> var msg = "" if (extra == MediaPlayer.MEDIA_ERROR_TIMED_OUT) { msg = getString(R.string.video_error_media_load_timeout) } else if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) { msg = getString(R.string.video_error_server_inaccessible) } else { msg = getString(R.string.video_error_unknown_error) } mVideoView.stopPlayback() mPlaybackState = LeanbackPlaybackState.IDLE false } mVideoView.setOnPreparedListener { if (mPlaybackState == LeanbackPlaybackState.PLAYING) { mVideoView.start() } } mVideoView.setOnCompletionListener { mPlaybackState = LeanbackPlaybackState.IDLE } } public override fun onResume() { super.onResume() mSession.isActive = true } public override fun onPause() { super.onPause() if (mVideoView.isPlaying) { if (!requestVisibleBehind(true)) { stopPlayback() } } else { requestVisibleBehind(false) } } override fun onStop() { super.onStop() mSession.release() } override fun onVisibleBehindCanceled() { super.onVisibleBehindCanceled() } private fun stopPlayback() { mVideoView.stopPlayback() } enum class LeanbackPlaybackState { PLAYING, PAUSED, BUFFERING, IDLE } private inner class MediaSessionCallback : MediaSession.Callback() }
app/src/main/kotlin/com/github/tommykw/tv/activity/PlaybackOverlayActivity.kt
1492333986
// 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 com.intellij.testGuiFramework.driver import com.intellij.testGuiFramework.cellReader.ExtendedJTreeCellReader import com.intellij.testGuiFramework.cellReader.ProjectTreeCellReader import com.intellij.testGuiFramework.cellReader.SettingsTreeCellReader import com.intellij.testGuiFramework.impl.GuiRobotHolder import com.intellij.testGuiFramework.impl.GuiTestUtilKt import com.intellij.testGuiFramework.util.FinderPredicate import com.intellij.testGuiFramework.util.Predicate import org.fest.assertions.Assertions import org.fest.reflect.core.Reflection import org.fest.swing.core.MouseButton import org.fest.swing.core.Robot import org.fest.swing.driver.ComponentPreconditions import org.fest.swing.driver.JTreeDriver import org.fest.swing.driver.JTreeLocation import org.fest.swing.exception.ActionFailedException import org.fest.swing.exception.LocationUnavailableException import org.fest.swing.exception.WaitTimedOutError import org.fest.swing.timing.Timeout import org.fest.swing.util.Pair import org.fest.swing.util.Triple import java.awt.Point import java.awt.Rectangle import javax.swing.JPopupMenu import javax.swing.JTree import javax.swing.plaf.basic.BasicTreeUI import javax.swing.tree.TreePath open class ExtendedJTreeDriver(robot: Robot = GuiRobotHolder.robot) : JTreeDriver(robot) { private val DEFAULT_FIND_PATH_ATTEMPTS: Int = 3 init { val resultReader = when (javaClass.name) { "com.intellij.openapi.options.newEditor.SettingsTreeView\$MyTree" -> SettingsTreeCellReader() "com.intellij.ide.projectView.impl.ProjectViewPane\$1" -> ProjectTreeCellReader() else -> ExtendedJTreeCellReader() } this.replaceCellReader(resultReader) } fun clickPath(tree: JTree, treePath: TreePath, button: MouseButton = MouseButton.LEFT_BUTTON, times: Int = 1, attempts: Int = DEFAULT_FIND_PATH_ATTEMPTS) { val point = tree.scrollToPath(treePath) robot.click(tree, point, button, times) //check that path is selected or click it again if (!tree.checkPathIsSelected(treePath)) { if (attempts == 0) throw ExtendedJTreeException("Unable to click path in $DEFAULT_FIND_PATH_ATTEMPTS " + "attempts due to it high mutability. Maybe this path is loading async.") clickPath(tree, treePath, button, times, attempts - 1) } } fun JTree.scrollToPath(path: TreePath): Point { robot.waitForIdle() return this.scrollToMatchingPath(path).second } private fun JTree.scrollToMatchingPath(path: TreePath): Pair<Boolean, Point> { this.makeVisible(path, false) return this.scrollToPathToSelectExt(path) } private fun JTree.scrollToPathToSelectExt(path: TreePath): Pair<Boolean, Point> { val result = GuiTestUtilKt.computeOnEdt { val isSelected = this.selectionCount == 1 && this.isPathSelected(path) Pair.of(isSelected, this.scrollToTreePathExt(path)) }!! robot.waitForIdle() return result } private fun JTree.scrollToTreePathExt(path: TreePath): Point { val boundsAndCoordinates = JTreeLocation().pathBoundsAndCoordinates(this, path) this.scrollRectToVisible(boundsAndCoordinates.first as Rectangle) return boundsAndCoordinates.second!! } private fun JTree.makeVisible(path: TreePath, expandWhenFound: Boolean): Boolean { var changed = false if (path.pathCount > 1) { changed = makeParentVisible(path) } return if (!expandWhenFound) { changed } else { expandTreePath(path) waitForChildrenToShowUp(path) true } } private fun JTree.makeParentVisible(path: TreePath): Boolean { val changed = this.makeVisible(path.parentPath, true) if (changed) robot.waitForIdle() return changed } private fun JTree.expandTreePath(path: TreePath) { GuiTestUtilKt.runOnEdt { if (!isExpanded(path)) expandPath(path) } } private fun JTree.waitForChildrenToShowUp(path: TreePath) { try { GuiTestUtilKt.waitUntil( "Waiting for children are shown up", Timeout.timeout(robot.settings().timeoutToBeVisible().toLong())) { this.childCount(path) != 0 } } catch (waitTimedOutError: WaitTimedOutError) { throw LocationUnavailableException(waitTimedOutError.message!!) } } /** * @return true if the required path is selected * @return false if the incorrect path is selected * @throws ExtendedJTreeException if no one row or several ones are selected * */ private fun JTree.checkPathIsSelected(treePath: TreePath): Boolean { val selectedPaths = selectionPaths if (selectedPaths.isEmpty()) throw ExtendedJTreeException("No one row has been selected at all") if (selectedPaths.size > 1) throw ExtendedJTreeException("More than one row has been selected") val selectedPath = selectedPaths.first() return treePath.lastPathComponent == selectedPath.lastPathComponent } /** * node that has as child LoadingNode */ class LoadingNodeException(val node: Any, var treePath: TreePath?) : Exception("Meet loading node: $node (${treePath?.path?.joinToString()}") private fun JTree.childCount(path: TreePath): Int { return GuiTestUtilKt.computeOnEdt { val lastPathComponent = path.lastPathComponent model.getChildCount(lastPathComponent) }!! } fun expandPath(tree: JTree, treePath: TreePath) { // do not try to expand leaf if(tree.model.isLeaf(treePath.lastPathComponent)) return val info = tree.scrollToMatchingPathAndGetToggleInfo(treePath) if (!info.first) tree.toggleCell(info.second!!, info.third) } fun collapsePath(tree: JTree, treePath: TreePath) { // do not try to collapse leaf if(tree.model.isLeaf(treePath.lastPathComponent)) return val info = tree.scrollToMatchingPathAndGetToggleInfo(treePath) if (info.first) tree.toggleCell(info.second!!, info.third) } fun selectPath(tree: JTree, treePath: TreePath) { selectMatchingPath(tree, treePath) } private fun selectMatchingPath(tree: JTree, treePath: TreePath): Point { val info = tree.scrollToMatchingPath(treePath) robot.waitForIdle() val where = info.second!! if (!info.first) robot.click(tree, where) return where } private fun JTree.toggleCell(p: Point, toggleClickCount: Int) { if (toggleClickCount == 0) { toggleRowThroughTreeUIExt(p) robot.waitForIdle() } else { robot.click(this, p, MouseButton.LEFT_BUTTON, toggleClickCount) } } private fun JTree.toggleRowThroughTreeUIExt(p: Point) { GuiTestUtilKt.runOnEdt { if (ui !is BasicTreeUI) throw ActionFailedException.actionFailure("Can't toggle row for $ui") else this.toggleExpandState(p) } } private fun JTree.toggleExpandState(pathLocation: Point) { val path = getPathForLocation(pathLocation.x, pathLocation.y) val treeUI = ui Assertions.assertThat(treeUI).isInstanceOf(BasicTreeUI::class.java) Reflection.method("toggleExpandState").withParameterTypes(TreePath::class.java).`in`(treeUI).invoke(path) } private fun JTree.scrollToMatchingPathAndGetToggleInfo(treePath: TreePath): Triple<Boolean, Point, Int> { val result = GuiTestUtilKt.computeOnEdt { ComponentPreconditions.checkEnabledAndShowing(this) val point = scrollToTreePathExt(treePath) Triple.of(isExpanded(treePath), point, toggleClickCount) }!! robot.waitForIdle() return result } fun showPopupMenu(tree: JTree, treePath: TreePath): JPopupMenu { val info = tree.scrollToMatchingPath(treePath) robot.waitForIdle() return robot.showPopupMenu(tree, info.second!!) } fun drag(tree: JTree, treePath: TreePath) { val p = selectMatchingPath(tree, treePath) drag(tree, p) } fun drop(tree: JTree, treePath: TreePath) { drop(tree, tree.scrollToMatchingPath(treePath).second!!) } fun findPath(tree: JTree, stringPath: List<String>, predicate: FinderPredicate = Predicate.equality): TreePath { fun <T> List<T>.list2tree() = map { subList(0, indexOf(it) + 1) } lateinit var path: TreePath stringPath .list2tree() .forEach { path = ExtendedJTreePathFinder(tree).findMatchingPathByPredicate(predicate, *it.toTypedArray()) expandPath(tree, path) } return path } fun findPathToNode(tree: JTree, node: String, predicate: FinderPredicate = Predicate.equality): TreePath{ fun JTree.iterateChildren(root: Any, node: String, rootPath: TreePath, predicate: FinderPredicate): TreePath?{ for(index in 0 until this.model.getChildCount(root)){ val child = this.model.getChild(root, index) val childPath = TreePath(arrayOf(*rootPath.path, child)) if (predicate(child.toString(), node)){ return childPath } if(!this.model.isLeaf(child)) { makeVisible(childPath, true) val found = this.iterateChildren(child, node, childPath, predicate) if(found != null) return found } } return null } return tree.iterateChildren(tree.model.root, node, TreePath(tree.model.root), predicate) ?: throw LocationUnavailableException("Node `$node` not found") } fun exists(tree: JTree, pathStrings: List<String>, predicate: FinderPredicate = Predicate.equality): Boolean { return try { findPath(tree, pathStrings, predicate) true } catch (e: LocationUnavailableException){ false } } } // end of class class ExtendedJTreeException(message: String) : Exception(message)
platform/testGuiFramework/src/com/intellij/testGuiFramework/driver/ExtendedJTreeDriver.kt
4228641129
package nl.hannahsten.texifyidea.inspections.bibtex import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import nl.hannahsten.texifyidea.index.LatexIncludesIndex import nl.hannahsten.texifyidea.inspections.InsightGroup import nl.hannahsten.texifyidea.inspections.TexifyInspectionBase import nl.hannahsten.texifyidea.lang.LatexPackage import nl.hannahsten.texifyidea.psi.LatexCommands import nl.hannahsten.texifyidea.util.* import nl.hannahsten.texifyidea.util.files.document /** * @author Sten Wessel */ open class BibtexDuplicateBibliographyInspection : TexifyInspectionBase() { // Manual override to match short name in plugin.xml override fun getShortName() = InsightGroup.BIBTEX.prefix + inspectionId override val inspectionGroup = InsightGroup.LATEX override val inspectionId = "DuplicateBibliography" override fun getDisplayName() = "Same bibliography is included multiple times" override fun inspectFile(file: PsiFile, manager: InspectionManager, isOntheFly: Boolean): List<ProblemDescriptor> { // Chapterbib allows multiple bibliographies if (file.includedPackages().any { it == LatexPackage.CHAPTERBIB }) { return emptyList() } val descriptors = descriptorList() // Map each bibliography file to all the commands which include it val groupedIncludes = mutableMapOf<String, MutableList<LatexCommands>>() LatexIncludesIndex.getItemsInFileSet(file).asSequence() .filter { it.name == "\\bibliography" || it.name == "\\addbibresource" } .forEach { command -> for (fileName in command.getIncludedFiles(false).map { it.name }) { groupedIncludes.getOrPut(fileName) { mutableListOf() }.add(command) } } groupedIncludes.asSequence() .filter { (_, commands) -> commands.size > 1 } .forEach { (fileName, commands) -> for (command in commands.distinct()) { if (command.containingFile != file) continue val parameterIndex = command.requiredParameter(0)?.indexOf(fileName) ?: break if (parameterIndex < 0) break descriptors.add( manager.createProblemDescriptor( command, TextRange(parameterIndex, parameterIndex + fileName.length).shiftRight(command.commandToken.textLength + 1), "Bibliography file '$fileName' is included multiple times", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOntheFly, RemoveOtherCommandsFix(fileName, commands) ) ) } } return descriptors } /** * @author Sten Wessel */ class RemoveOtherCommandsFix(private val bibName: String, private val commandsToFix: List<LatexCommands>) : LocalQuickFix { override fun getFamilyName(): String { return "Remove other includes of $bibName" } override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val currentCommand = descriptor.psiElement as LatexCommands val documentManager = PsiDocumentManager.getInstance(project) // For all commands to be fixed, remove the matching bibName // Handle commands by descending offset, to make sure the replaceString calls work correctly for (command in commandsToFix.sortedByDescending { it.textOffset }) { val document = command.containingFile.document() ?: continue val param = command.parameterList.first() // If we handle the current command, find the first occurrence of bibName and leave it intact val firstBibIndex = if (command == currentCommand) { param.text.trimRange(1, 1).splitToSequence(',').indexOfFirst { it.trim() == bibName } } else -1 val replacement = param.text.trimRange(1, 1).splitToSequence(',') // Parameter should stay if it is at firstBibIndex or some other bibliography file .filterIndexed { i, it -> i <= firstBibIndex || it.trim() != bibName } .joinToString(",", prefix = "{", postfix = "}") // When no arguments are left, just delete the command if (replacement.trimRange(1, 1).isBlank()) { command.delete() } else { document.replaceString(param.textRange, replacement) } documentManager.doPostponedOperationsAndUnblockDocument(document) documentManager.commitDocument(document) } } } }
src/nl/hannahsten/texifyidea/inspections/bibtex/BibtexDuplicateBibliographyInspection.kt
1443776356
/* * Copyright (c) 2016. Sunghyouk Bae <[email protected]> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package debop4k.data.mybatis.kotlin.cache import debop4k.core.uninitialized import debop4k.data.mybatis.kotlin.mappers.KotlinActorMapper import debop4k.data.mybatis.kotlin.models.KotlinActor import lombok.NonNull import org.mybatis.spring.SqlSessionTemplate import org.springframework.cache.annotation.CacheConfig import org.springframework.cache.annotation.CacheEvict import org.springframework.cache.annotation.CachePut import org.springframework.cache.annotation.Cacheable import org.springframework.stereotype.Repository import org.springframework.transaction.annotation.Transactional import javax.inject.Inject /** * EhCacheActorRepository * @author [email protected] */ @Repository @Transactional @CacheConfig(cacheNames = arrayOf("kotlin-actors")) open class EhCacheActorRepository { @Inject val actorMapper: KotlinActorMapper = uninitialized() @Inject val sqlTemplate: SqlSessionTemplate = uninitialized() /** * KotlinActor id 값으로 Actor를 조회 * `@Cacheable` 은 먼저 Cache 에서 해당 Actor가 있는지 조회하고, 없다면 DB에서 읽어와서 캐시에 저장한 후 반환한다. * 캐시에 데이터가 존재한다면 캐시의 KotlinActor 를 반환하고, DB를 읽지 않는다 * @param id Actor의 identifier * * * @return 조회된 KotlinActor (없으면 NULL 반환) */ @Transactional(readOnly = true) @Cacheable(key = "#id") open fun findById(id: Int): KotlinActor { return this.actorMapper.findById(id) } @Transactional(readOnly = true) @Cacheable(key = "'firstname=' + #firstname") open fun findByFirstname(@NonNull firstname: String): KotlinActor { return this.actorMapper.findByFirstname(firstname) } @Transactional(readOnly = true) @Cacheable(key = "'firstname=' + #firstname") open fun findByFirstnameWithSqlSessionTemplate(@NonNull firstname: String): KotlinActor { return sqlTemplate.selectOne<KotlinActor>("selectActorByFirstname", firstname) } @Transactional(readOnly = true) open fun findAll(): List<KotlinActor> { return actorMapper.findAll() } /** * DB에 새로운 KotlinActor 를 추가하고, Cache에 미리 저장해둔다 * @param actor DB에 추가할 KotlinActor 정보 * * * @return 저장된 KotlinActor 정보 (발급된 Id 값이 있다) */ @CachePut(key = "#actor.id") open fun insertActor(actor: KotlinActor): KotlinActor { sqlTemplate.insert("insertActor", actor) return actor } /** * 캐시에서 해당 정보를 삭제하고, DB에서 데이터를 삭제한다. * @param id 삭제할 KotlinActor 의 identifier */ @CacheEvict(key = "#id") open fun deleteById(id: Int?) { actorMapper.deleteById(id) } }
debop4k-data-mybatis/src/test/kotlin/debop4k/data/mybatis/kotlin/cache/EhCacheActorRepository.kt
908709038
package net.ndrei.teslapoweredthingies.machines.cropcloner import net.minecraft.block.state.IBlockState import net.minecraft.init.Blocks import net.minecraft.item.ItemStack import net.minecraft.util.math.BlockPos import net.minecraft.world.World /** * Created by CF on 2017-07-15. */ object MelonPlantCloner : GenericCropClonerPlant() { override fun getDrops(world: World, pos: BlockPos, state: IBlockState) = listOf(ItemStack(Blocks.MELON_BLOCK), *super.getDrops(world, pos, state).toTypedArray()) }
src/main/kotlin/net/ndrei/teslapoweredthingies/machines/cropcloner/MelonPlantCloner.kt
2372137500
package org.rliz.cfm.recorder.common.exception import org.rliz.cfm.recorder.common.data.AbstractModel import kotlin.reflect.KClass class NotFoundException : RuntimeException { constructor(clazz: KClass<*> = AbstractModel::class, specifier: Any = "id") : super("Could not find ${clazz.simpleName} identified by $specifier") }
server/recorder/src/main/kotlin/org/rliz/cfm/recorder/common/exception/NotFoundException.kt
692583648
package com.simplecity.amp_library.ui.screens.songs.menu import android.content.Context import com.simplecity.amp_library.data.Repository import com.simplecity.amp_library.data.Repository.AlbumArtistsRepository import com.simplecity.amp_library.model.Playlist import com.simplecity.amp_library.model.Song import com.simplecity.amp_library.playback.MediaManager import com.simplecity.amp_library.ui.common.Presenter import com.simplecity.amp_library.ui.screens.drawer.NavigationEventRelay import com.simplecity.amp_library.ui.screens.drawer.NavigationEventRelay.NavigationEvent import com.simplecity.amp_library.ui.screens.songs.menu.SongMenuContract.View import com.simplecity.amp_library.utils.LogUtils import com.simplecity.amp_library.utils.RingtoneManager import com.simplecity.amp_library.utils.playlists.PlaylistManager import io.reactivex.Observable import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import javax.inject.Inject open class SongMenuPresenter @Inject constructor( private val context: Context, private val mediaManager: MediaManager, private val playlistManager: PlaylistManager, private val blacklistRepository: Repository.BlacklistRepository, private val ringtoneManager: RingtoneManager, private val albumArtistsRepository: AlbumArtistsRepository, private val albumsRepository: Repository.AlbumsRepository, private val navigationEventRelay: NavigationEventRelay ) : Presenter<View>(), SongMenuContract.Presenter { override fun createPlaylist(songs: List<Song>) { view?.presentCreatePlaylistDialog(songs) } override fun addToPlaylist(playlist: Playlist, songs: List<Song>) { playlistManager.addToPlaylist(playlist, songs) { numSongs -> view?.onSongsAddedToPlaylist(playlist, numSongs) } } override fun addToQueue(songs: List<Song>) { mediaManager.addToQueue(songs) { numSongs -> view?.onSongsAddedToQueue(numSongs) } } override fun playNext(songs: List<Song>) { mediaManager.playNext(songs) { numSongs -> view?.onSongsAddedToQueue(numSongs) } } override fun blacklist(songs: List<Song>) { blacklistRepository.addAllSongs(songs) } override fun delete(songs: List<Song>) { view?.presentDeleteDialog(songs) } override fun songInfo(song: Song) { view?.presentSongInfoDialog(song) } override fun setRingtone(song: Song) { if (RingtoneManager.requiresDialog(context)) { view?.presentRingtonePermissionDialog() } else { ringtoneManager.setRingtone(song) { view?.showRingtoneSetMessage() } } } override fun share(song: Song) { view?.shareSong(song) } override fun editTags(song: Song) { view?.presentTagEditorDialog(song) } override fun goToArtist(song: Song) { addDisposable(albumArtistsRepository.getAlbumArtists() .first(emptyList()) .flatMapObservable { Observable.fromIterable(it) } .filter { albumArtist -> albumArtist.name == song.albumArtist.name && albumArtist.albums.containsAll(song.albumArtist.albums) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { albumArtist -> navigationEventRelay.sendEvent(NavigationEvent(NavigationEvent.Type.GO_TO_ARTIST, albumArtist, true)) }, { error -> LogUtils.logException(TAG, "Failed to retrieve album artist", error) } )) } override fun goToAlbum(song: Song) { addDisposable(albumsRepository.getAlbums() .first(emptyList()) .flatMapObservable { Observable.fromIterable(it) } .filter { album -> album.id == song.albumId } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { album -> navigationEventRelay.sendEvent(NavigationEvent(NavigationEvent.Type.GO_TO_ALBUM, album, true)) }, { error -> LogUtils.logException(TAG, "Failed to retrieve album", error) } )) } override fun goToGenre(song: Song) { addDisposable(song.getGenre(context) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { genre -> navigationEventRelay.sendEvent(NavigationEvent(NavigationEvent.Type.GO_TO_GENRE, genre, true)) }, { error -> LogUtils.logException(TAG, "Failed to retrieve genre", error) } )) } override fun <T> transform(src: Single<List<T>>, dst: (List<T>) -> Unit) { addDisposable( src .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe( { items -> dst(items) }, { error -> LogUtils.logException(TAG, "Failed to transform src single", error) } ) ) } companion object { const val TAG = "SongMenuPresenter" } }
app/src/main/java/com/simplecity/amp_library/ui/screens/songs/menu/SongMenuPresenter.kt
801804313
package net.milosvasic.pussycat.android.application import net.milosvasic.pussycat.application.APPLICATION_TYPE class ApplicationTestTerminalFilesystemParams1 : ApplicationTestAbstract() { init { params = arrayOf("--terminal", "--filesystem") expectedType = APPLICATION_TYPE.CLI } }
Android/src/test/kotlin/net/milosvasic/pussycat/android/application/ApplicationTestTerminalFilesystemParams1.kt
1484927460
package com.quickblox.sample.conference.kotlin.presentation.screens.call import android.content.Context import android.util.AttributeSet import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import android.widget.LinearLayout import com.quickblox.sample.conference.kotlin.R import com.quickblox.sample.conference.kotlin.databinding.CustomCoverstionLayoutBinding import com.quickblox.sample.conference.kotlin.domain.call.entities.CallEntity import java.util.* /* * Created by Injoit in 2021-09-30. * Copyright © 2021 Quickblox. All rights reserved. */ class CustomLinearLayout : LinearLayout, ConversationItem.ConversationItemListener { private lateinit var binding: CustomCoverstionLayoutBinding private var callEntities: SortedSet<CallEntity>? = null private var conversationItemListener: ConversationItemListener? = null constructor(context: Context) : super(context) { init(context) } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { init(context) } constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { init(context) } private fun init(context: Context) { val rootView: View = inflate(context, R.layout.custom_coverstion_layout, this) binding = CustomCoverstionLayoutBinding.bind(rootView) this.orientation = VERTICAL } fun setCallEntities(callEntities: SortedSet<CallEntity>) { this.callEntities = callEntities } fun setClickListener(conversationItemListener: ConversationItemListener) { this.conversationItemListener = conversationItemListener } fun updateViews(height: Int, width: Int) { removeAllViews() when (callEntities?.size) { 1 -> { val callEntity = callEntities?.first() val view = ConversationItem(context) callEntity?.let { view.setView(it) } view.setClickListener(this) view.layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) this.addView(view) } 2 -> { callEntities?.forEach { callEntity -> val view = ConversationItem(context) view.setView(callEntity) view.setClickListener(this) view.layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height / 2) this.addView(view) } } 3 -> { callEntities?.let { callEntities -> val listCallEntities = callEntities.toList() this.addView(expandableLayout(width, height / 2, listCallEntities.get(0), listCallEntities.get(1))) val view = ConversationItem(context) listCallEntities.get(2)?.let { view.setView(it) } view.setClickListener(this) view.layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height / 2) this.addView(view) } } else -> { callEntities?.let { callEntities -> val listCallEntities = callEntities.toList() val displayScheme = calcViewTable(callEntities.size) var triple = displayScheme.first var dual = displayScheme.second val countRows = triple + dual var tmpIndex = 0 for (index in 0 .. listCallEntities.size step 3) { if (triple-- > 0) { this.addView(expandableLayout(width, height / countRows, listCallEntities[index], listCallEntities[index + 1], listCallEntities[index + 2])) } else { break } tmpIndex = index + 3 } for (index in tmpIndex .. listCallEntities.size step 2) { if (dual-- > 0) { this.addView(expandableLayout(width, height / countRows, listCallEntities[index], listCallEntities[index + 1])) } } } } } } private fun expandableLayout(width: Int, height: Int, vararg entities: CallEntity?): LinearLayout { val expandableLayout = LinearLayout(context) expandableLayout.layoutParams = LayoutParams(width, height) expandableLayout.orientation = HORIZONTAL expandableLayout.removeAllViews() entities.forEach { callEntity -> callEntity?.let { val view = ConversationItem(context) view.setView(it) view.setClickListener(this) view.layoutParams = FrameLayout.LayoutParams(width / entities.size, ViewGroup.LayoutParams.MATCH_PARENT) expandableLayout.addView(view) } } return expandableLayout } private fun calcViewTable(opponentsQuantity: Int): Pair<Int, Int> { var rowsThreeUsers = 0 var rowsTwoUsers = 0 when (opponentsQuantity % 3) { 0 -> rowsThreeUsers = opponentsQuantity / 3 1 -> { rowsTwoUsers = 2 rowsThreeUsers = (opponentsQuantity - 2) / 3 } 2 -> { rowsTwoUsers = 1 rowsThreeUsers = (opponentsQuantity - 1) / 3 } } return Pair(rowsThreeUsers, rowsTwoUsers) } override fun onItemClick(callEntity: CallEntity) { conversationItemListener?.onItemClick(callEntity) } interface ConversationItemListener { fun onItemClick(callEntity: CallEntity) } }
sample-conference-kotlin/app/src/main/java/com/quickblox/sample/conference/kotlin/presentation/screens/call/CustomLinearLayout.kt
1385548099
package org.jitsi.videobridge.octo.config import io.kotest.matchers.shouldBe import org.jitsi.ConfigTest internal class OctoConfigTest : ConfigTest() { init { context("enabled") { context("when bind address and bind port are defined in legacy config") { withLegacyConfig(legacyConfigWithBindAddressAndBindPort) { withNewConfig(newConfigOctoDisabled) { should("be true") { OctoConfig().enabled shouldBe true } } } } context("when bind address is set in legacy config but not bind port") { withLegacyConfig(legacyConfigWithBindAddressNoBindPort) { should("be false") { OctoConfig().enabled shouldBe false } context("and set as true in new config") { withNewConfig(newConfigOctoEnabled) { should("be false") { OctoConfig().enabled shouldBe false } } } } } context("when bind port is set in legacy config but not bind address") { withLegacyConfig(legacyConfigWithBindPortNoBindAddress) { withNewConfig(newConfigOctoEnabled) { should("be false") { OctoConfig().enabled shouldBe false } } } } context("when enabled is true in new config and bind address/bind port are not defined in old config") { withNewConfig(newConfigOctoEnabled) { should("be true") { OctoConfig().enabled shouldBe true } } } } context("bindAddress") { context("when the value isn't set in legacy config") { withNewConfig(newConfigBindAddress) { should("be the value from new config") { OctoConfig().bindAddress shouldBe "127.0.0.1" } } } } } } private val legacyConfigWithBindAddressAndBindPort = """ org.jitsi.videobridge.octo.BIND_ADDRESS=127.0.0.1 org.jitsi.videobridge.octo.BIND_PORT=8080 """.trimIndent() private val legacyConfigWithBindAddressNoBindPort = """ org.jitsi.videobridge.octo.BIND_ADDRESS=127.0.0.1 """.trimIndent() private val legacyConfigWithBindPortNoBindAddress = """ org.jitsi.videobridge.octo.BIND_PORT=8080 """.trimIndent() private val newConfigOctoDisabled = """ videobridge { octo { enabled=false } } """.trimIndent() private val newConfigOctoEnabled = """ videobridge { octo { enabled=true } } """.trimIndent() private val newConfigBindAddress = """ videobridge { octo { bind-address = "127.0.0.1" } } """.trimIndent()
jvb/src/test/kotlin/org/jitsi/videobridge/octo/config/OctoConfigTest.kt
1940472202
package gsonpath.util import com.sun.source.util.Trees import javax.annotation.processing.ProcessingEnvironment /** * Typically the 'com.sun.source.util.Trees' class is not allowed when making an annotation processor incremental. * A work around (found here: https://github.com/JakeWharton/butterknife/commit/3f675f4e23e59f645f5cecddde9f3b9fb1925cf8#diff-141a2db288c994f07eba0c49a2869e9bR155) * was implemented to still allow Trees to be used. */ class SunTreesProvider(private val env: ProcessingEnvironment) { private val lazyTrees: Trees by lazy { try { Trees.instance(env) } catch (ignored: IllegalArgumentException) { try { // Get original ProcessingEnvironment from Gradle-wrapped one or KAPT-wrapped one. env.javaClass.declaredFields .first { field -> field.name == "delegate" || field.name == "processingEnv" } .let { field -> field.isAccessible = true val javacEnv = field.get(env) as ProcessingEnvironment Trees.instance(javacEnv) } } catch (throwable: Throwable) { throw IllegalStateException("Unable to create Trees", throwable) } } } fun getTrees(): Trees = lazyTrees }
compiler/base/src/main/java/gsonpath/util/SunTreesProvider.kt
2409636821
package io.github.detekt.tooling.dsl import io.github.detekt.tooling.api.spec.ExtensionId import io.github.detekt.tooling.api.spec.ExtensionsSpec import io.github.detekt.tooling.internal.PluginsHolder import java.nio.file.Path @ProcessingModelDsl class ExtensionsSpecBuilder : Builder<ExtensionsSpec> { var disableDefaultRuleSets: Boolean = false var plugins: ExtensionsSpec.Plugins? = null var disabledExtensions: MutableSet<ExtensionId> = mutableSetOf() override fun build(): ExtensionsSpec = ExtensionsModel( disableDefaultRuleSets, plugins, disabledExtensions ) fun disableExtension(id: ExtensionId) { disabledExtensions.add(id) } fun fromPaths(paths: () -> Collection<Path>) { require(plugins == null) { "Plugin source already specified." } plugins = PluginsHolder(paths(), null) } fun fromClassloader(classLoader: () -> ClassLoader) { require(plugins == null) { "Plugin source already specified." } plugins = PluginsHolder(null, classLoader()) } } private data class ExtensionsModel( override val disableDefaultRuleSets: Boolean, override val plugins: ExtensionsSpec.Plugins?, override val disabledExtensions: Set<ExtensionId> ) : ExtensionsSpec
detekt-tooling/src/main/kotlin/io/github/detekt/tooling/dsl/ExtensionsSpecBuilder.kt
15314270
package com.github.pgutkowski.kgraphql.demo import com.github.pgutkowski.kgraphql.integration.QueryTest import com.github.pgutkowski.kgraphql.server.NettyServer /** * Demo application showing of tested schema, by default runs on localhost:8080 */ fun main(args : Array<String>) { val schema = QueryTest().testedSchema NettyServer.run(schema, 8080) }
src/test/kotlin/com/github/pgutkowski/kgraphql/demo/ServerDemo.kt
1222345286
package net.nemerosa.ontrack.extension.av.config /** * List of ways the auto approval is managed. */ enum class AutoApprovalMode( val displayName: String, ) { /** * Managed at client level, by Ontrack. */ CLIENT("Managed by Ontrack"), /** * Delegated to the SCM, for example by using the auto merge feature in GitHub. */ SCM("Managed by SCM"); companion object { /** * Default value for the auto approval mode when not set. */ val DEFAULT_AUTO_APPROVAL_MODE = AutoApprovalMode.CLIENT } }
ontrack-extension-auto-versioning/src/main/java/net/nemerosa/ontrack/extension/av/config/AutoApprovalMode.kt
900591388
package com.fireflysource.common.concurrent import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import java.util.concurrent.CompletableFuture class TestCompletableFuture { @Test @DisplayName("should receive the exception message.") fun testException() { CompletableFuture .runAsync { throw IllegalStateException("test_error") } .exceptionallyAccept { assertEquals("test_error", it.cause?.message) } .get() } @Test @DisplayName("should exceptionally compose successfully.") fun testExceptionCompose() { val value = CompletableFuture .supplyAsync<String> { throw IllegalStateException("test_error") } .exceptionallyCompose { CompletableFuture.supplyAsync { "ok" } } .get() assertEquals("ok", value) } }
firefly-common/src/test/kotlin/com/fireflysource/common/concurrent/TestCompletableFuture.kt
33682705
package org.tvheadend.tvhclient.ui.features.settings import android.os.Bundle import android.view.View import androidx.lifecycle.ViewModelProvider import androidx.preference.EditTextPreference import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import androidx.preference.SwitchPreference import org.tvheadend.tvhclient.R import org.tvheadend.tvhclient.ui.common.interfaces.ToolbarInterface import org.tvheadend.tvhclient.util.extensions.sendSnackbarMessage import timber.log.Timber class SettingsUserInterfaceFragment : PreferenceFragmentCompat(), Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener { private var programArtworkEnabledPreference: SwitchPreference? = null private var castMiniControllerPreference: SwitchPreference? = null private var multipleChannelTagsPreference: SwitchPreference? = null private var hoursOfEpgDataPreference: EditTextPreference? = null private var daysOfEpgDataPreference: EditTextPreference? = null lateinit var settingsViewModel: SettingsViewModel override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) settingsViewModel = ViewModelProvider(activity as SettingsActivity)[SettingsViewModel::class.java] (activity as ToolbarInterface).let { it.setTitle(getString(R.string.pref_user_interface)) it.setSubtitle("") } programArtworkEnabledPreference = findPreference("program_artwork_enabled") programArtworkEnabledPreference?.onPreferenceClickListener = this castMiniControllerPreference = findPreference("casting_minicontroller_enabled") castMiniControllerPreference?.onPreferenceClickListener = this multipleChannelTagsPreference = findPreference("multiple_channel_tags_enabled") multipleChannelTagsPreference?.onPreferenceClickListener = this hoursOfEpgDataPreference = findPreference("hours_of_epg_data_per_screen") hoursOfEpgDataPreference?.onPreferenceChangeListener = this daysOfEpgDataPreference = findPreference("days_of_epg_data") daysOfEpgDataPreference?.onPreferenceChangeListener = this } override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { addPreferencesFromResource(R.xml.preferences_ui) } override fun onPreferenceClick(preference: Preference): Boolean { when (preference.key) { "multiple_channel_tags_enabled" -> handlePreferenceMultipleChannelTagsSelected() "program_artwork_enabled" -> handlePreferenceShowArtworkSelected() "casting" -> handlePreferenceCastingSelected() } return true } private fun handlePreferenceMultipleChannelTagsSelected() { if (!settingsViewModel.isUnlocked) { context?.sendSnackbarMessage(R.string.feature_not_available_in_free_version) multipleChannelTagsPreference?.isChecked = false } } private fun handlePreferenceShowArtworkSelected() { if (!settingsViewModel.isUnlocked) { context?.sendSnackbarMessage(R.string.feature_not_available_in_free_version) programArtworkEnabledPreference?.isChecked = false } } private fun handlePreferenceCastingSelected() { if (settingsViewModel.currentServerStatus.htspVersion < 16) { context?.sendSnackbarMessage(R.string.feature_not_supported_by_server) castMiniControllerPreference?.isChecked = false } else if (!settingsViewModel.isUnlocked) { context?.sendSnackbarMessage(R.string.feature_not_available_in_free_version) castMiniControllerPreference?.isChecked = false } } override fun onPreferenceChange(preference: Preference?, newValue: Any?): Boolean { if (preference == null) return false Timber.d("Preference ${preference.key} changed, checking if it is valid") when (preference.key) { "hours_of_epg_data_per_screen" -> try { val value = Integer.valueOf(newValue as String) if (value < 1 || value > 24) { context?.sendSnackbarMessage("The value must be an integer between 1 and 24") return false } return true } catch (ex: NumberFormatException) { context?.sendSnackbarMessage("The value must be an integer between 1 and 24") return false } "days_of_epg_data" -> try { val value = Integer.valueOf(newValue as String) if (value < 1 || value > 14) { context?.sendSnackbarMessage("The value must be an integer between 1 and 14") return false } return true } catch (ex: NumberFormatException) { context?.sendSnackbarMessage("The value must be an integer between 1 and 14") return false } else -> return true } } }
app/src/main/java/org/tvheadend/tvhclient/ui/features/settings/SettingsUserInterfaceFragment.kt
1223819397
import org.junit.Test import org.junit.Ignore import org.junit.runner.RunWith import org.junit.runners.Parameterized import kotlin.test.assertEquals @RunWith(Parameterized::class) class ScrabbleScoreTest(val input: String, val expectedOutput: Int) { companion object { @JvmStatic @Parameterized.Parameters(name = "{index}: scoreWord({0})={1}") fun data() = listOf( arrayOf("", 0), arrayOf(" \t\n", 0), arrayOf("a", 1), arrayOf("f", 4), arrayOf("major", 14), arrayOf("danger", 8), arrayOf("street", 6), arrayOf("quirky", 22), arrayOf("OXYPHENBUTAZONE", 41), arrayOf("alacrity", 13), arrayOf("preview", 15) ) } @Test fun test() { assertEquals(expectedOutput, Scrabble.scoreWord(input)) } }
kotlin/scrabble-score/src/test/kotlin/ScrabbleScoreTest.kt
3844376184
package org.rust.ide.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.rust.lang.core.psi.RsBlockExpr import org.rust.lang.core.psi.RsExpr import org.rust.lang.core.psi.ext.getNextNonCommentSibling import org.rust.lang.core.psi.ext.parentOfType class UnwrapSingleExprIntention : RsElementBaseIntentionAction<RsBlockExpr>() { override fun getText() = "Remove braces from single expression" override fun getFamilyName() = text override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): RsBlockExpr? { val blockExpr = element.parentOfType<RsBlockExpr>() ?: return null val block = blockExpr.block return if (block.expr != null && block.lbrace.getNextNonCommentSibling() == block.expr) blockExpr else null } override fun invoke(project: Project, editor: Editor, ctx: RsBlockExpr) { val blockBody = ctx.block.expr ?: return val relativeCaretPosition = editor.caretModel.offset - blockBody.textOffset val offset = (ctx.replace(blockBody) as RsExpr).textOffset editor.caretModel.moveToOffset(offset + relativeCaretPosition) } }
src/main/kotlin/org/rust/ide/intentions/UnwrapSingleExprIntention.kt
4279065820
/* * Copyright 2018 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 io.plaidapp.core.util /** * Helper to force a when statement to assert all options are matched in a when statement. * * By default, Kotlin doesn't care if all branches are handled in a when statement. However, if you * use the when statement as an expression (with a value) it will force all cases to be handled. * * This helper is to make a lightweight way to say you meant to match all of them. * * Usage: * * ``` * when(sealedObject) { * is OneType -> // * is AnotherType -> // * }.exhaustive */ val <T> T.exhaustive: T get() = this
core/src/main/java/io/plaidapp/core/util/Extensions.kt
1751943885
package org.rust.lang.core.parser import com.intellij.lang.* import com.intellij.lang.parser.GeneratedParserUtilBase import com.intellij.openapi.util.Key import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.TokenSet import org.rust.lang.core.parser.RustParserDefinition.Companion.OUTER_BLOCK_DOC_COMMENT import org.rust.lang.core.parser.RustParserDefinition.Companion.OUTER_EOL_DOC_COMMENT import org.rust.lang.core.psi.RS_BLOCK_LIKE_EXPRESSIONS import org.rust.lang.core.psi.RsElementTypes import org.rust.lang.core.psi.RsElementTypes.* @Suppress("UNUSED_PARAMETER") object RustParserUtil : GeneratedParserUtilBase() { enum class PathParsingMode { COLONS, NO_COLONS, NO_TYPES } enum class BinaryMode { ON, OFF } private val STRUCT_ALLOWED: Key<Boolean> = Key("org.rust.STRUCT_ALLOWED") private val PATH_PARSING_MODE: Key<PathParsingMode> = Key("org.rust.PATH_PARSING_MODE") private val STMT_EXPR_MODE: Key<Boolean> = Key("org.rust.STMT_EXPR_MODE") private val PsiBuilder.structAllowed: Boolean get() = getUserData(STRUCT_ALLOWED) ?: true private val PsiBuilder.pathParsingMode: PathParsingMode get() = requireNotNull(getUserData(PATH_PARSING_MODE)) { "Path context is not set. Be sure to call one of `withParsingMode...` functions" } @JvmField val DOC_COMMENT_BINDER: WhitespacesAndCommentsBinder = WhitespacesBinders.leadingCommentsBinder( TokenSet.create(OUTER_BLOCK_DOC_COMMENT, OUTER_EOL_DOC_COMMENT)) // // Helpers // @JvmStatic fun checkStructAllowed(b: PsiBuilder, level: Int): Boolean = b.structAllowed @JvmStatic fun checkBraceAllowed(b: PsiBuilder, level: Int): Boolean { return b.structAllowed || b.tokenType != LBRACE } @JvmStatic fun structLiterals(b: PsiBuilder, level: Int, mode: BinaryMode, parser: Parser): Boolean = b.withContext(STRUCT_ALLOWED, mode == BinaryMode.ON) { parser.parse(this, level) } /** * Controls the difference between * * ``` * // bit and * let _ = {1} & x; * ``` * and * * ``` * // two statements: block expression {1} and unary reference expression &x * {1} & x; * ``` * * See `Restrictions::RESTRICTION_STMT_EXPR` in libsyntax */ @JvmStatic fun stmtMode(b: PsiBuilder, level: Int, mode: BinaryMode, parser: Parser): Boolean = b.withContext(STMT_EXPR_MODE, mode == BinaryMode.ON) { parser.parse(this, level) } @JvmStatic fun isCompleteBlockExpr(b: PsiBuilder, level: Int): Boolean { return isBlock(b, level) && b.getUserData(STMT_EXPR_MODE) == true } @JvmStatic fun isBlock(b: PsiBuilder, level: Int): Boolean { val m = b.latestDoneMarker ?: return false return m.tokenType in RS_BLOCK_LIKE_EXPRESSIONS || m.isBracedMacro(b) } @JvmStatic fun pathMode(b: PsiBuilder, level: Int, mode: PathParsingMode, parser: Parser): Boolean = b.withContext(PATH_PARSING_MODE, mode) { parser.parse(this, level) } @JvmStatic fun isPathMode(b: PsiBuilder, level: Int, mode: PathParsingMode): Boolean = mode == b.pathParsingMode @JvmStatic fun unpairedToken(b: PsiBuilder, level: Int): Boolean = when (b.tokenType) { LBRACE, RBRACE -> false LPAREN, RPAREN -> false LBRACK, RBRACK -> false else -> { b.advanceLexer() true } } @JvmStatic fun macroIdentifier(b: PsiBuilder, level: Int): Boolean = when (b.tokenType) { TYPE_KW, IDENTIFIER -> { b.advanceLexer() true } else -> false } @JvmStatic fun placeholderMacroToken(b: PsiBuilder, level: Int): Boolean = when (b.tokenType) { LBRACE, RBRACE -> false LPAREN, RPAREN -> false LBRACK, RBRACK -> false DOLLAR -> false else -> { b.advanceLexer() true } } @JvmStatic fun tokenAfterComplexPattern(b: PsiBuilder, level: Int): Boolean = when (b.tokenType) { LBRACE, RBRACE -> false LPAREN, RPAREN -> false LBRACK, RBRACK -> false DOLLAR -> false PLUS -> false MUL -> false else -> { b.advanceLexer() true } } @JvmStatic fun gtgteqImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, GTGTEQ, GT, GT, EQ) @JvmStatic fun gtgtImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, GTGT, GT, GT) @JvmStatic fun gteqImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, GTEQ, GT, EQ) @JvmStatic fun ltlteqImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, LTLTEQ, LT, LT, EQ) @JvmStatic fun ltltImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, LTLT, LT, LT) @JvmStatic fun lteqImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, LTEQ, LT, EQ) @JvmStatic fun ororImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, OROR, OR, OR) @JvmStatic fun andandImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, ANDAND, AND, AND) @JvmStatic fun defaultKeyword(b: PsiBuilder, level: Int): Boolean = contextualKeyword(b, "default", DEFAULT) @JvmStatic fun unionKeyword(b: PsiBuilder, level: Int): Boolean = contextualKeyword(b, "union", UNION) private @JvmStatic fun collapse(b: PsiBuilder, tokenType: IElementType, vararg parts: IElementType): Boolean { // We do not want whitespace between parts, so firstly we do raw lookup for each part, // and when we make sure that we have desired token, we consume and collapse it. parts.forEachIndexed { i, tt -> if (b.rawLookup(i) != tt) return false } val marker = b.mark() PsiBuilderUtil.advance(b, parts.size) marker.collapse(tokenType) return true } private fun <T> PsiBuilder.withContext(key: Key<T>, value: T, block: PsiBuilder.() -> Boolean): Boolean { val old = getUserData(key) putUserData(key, value) val result = block() putUserData(key, old) return result } private fun LighterASTNode.isBracedMacro(b: PsiBuilder): Boolean = tokenType == RsElementTypes.MACRO_EXPR && '{' == b.originalText.subSequence(startOffset, endOffset).find { it == '{' || it == '[' || it == '(' } private fun contextualKeyword(b: PsiBuilder, keyword: String, elementType: IElementType): Boolean { // Tricky: the token can be already remapped by some previous rule that was backtracked if ((b.tokenType == IDENTIFIER && b.tokenText == keyword && !(b.lookAhead(1)?.equals(EXCL) ?: false)) || b.tokenType == elementType) { b.remapCurrentToken(elementType) b.advanceLexer() return true } return false } }
src/main/kotlin/org/rust/lang/core/parser/RustParserUtil.kt
3278845279
package com.engineer.imitate.ui.list.adapter import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.engineer.imitate.R import com.engineer.imitate.Routes import com.engineer.imitate.util.dp2px class ImageAdapter(private var datas: List<String>) : RecyclerView.Adapter<ImageAdapter.MyHolder>() { private lateinit var mContext: Context private var option: RequestOptions = RequestOptions.circleCropTransform() private fun dp2dx(context: Context, value: Int): Float { return context.dp2px(value.toFloat()) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyHolder { mContext = parent.context val view = LayoutInflater.from(mContext) .inflate(R.layout.h_image_item, parent, false) return MyHolder(view) } override fun getItemCount(): Int { return datas.size } override fun onBindViewHolder(holder: MyHolder, position: Int) { // Glide.with(mContext).load(datas[position]) // .apply(option) // .into(holder.imageView) val index = position % Routes.IMAGES.size val res = Routes.IMAGES[index] Glide.with(mContext).load(res).into(holder.imageView) } class MyHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var imageView: ImageView = itemView.findViewById(com.engineer.imitate.R.id.image) } }
imitate/src/main/java/com/engineer/imitate/ui/list/adapter/ImageAdapter.kt
3348345706
/* * Created by Orchextra * * Copyright (C) 2017 Gigigo Mobile Services SL * * 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.gigigo.orchextra.core.data.datasources.db.persistors import java.sql.SQLException interface Persistor<T> { @Throws(SQLException::class) fun persist(data: T) }
core/src/main/java/com/gigigo/orchextra/core/data/datasources/db/persistors/Persistor.kt
1001240533
package co.nums.intellij.aem.htl.parser.complete import co.nums.intellij.aem.htl.parser.HtlParsingTestCaseBase class HtlPropertyAccessParsingTest : HtlParsingTestCaseBase("complete/simple/property_access") { fun testDotPropertyAccess() = doTest() fun testMultipleDotPropertyAccesses() = doTest() fun testBracketPropertyAccess() = doTest() fun testMultipleBracketPropertyAccesses() = doTest() fun testVariableBracketPropertyAccess() = doTest() fun testMultipleVariableBracketPropertyAccesses() = doTest() fun testExpressionBracketPropertyAccess() = doTest() fun testNumberBracketPropertyAccess() = doTest() fun testMultipleNumberBracketPropertyAccesses() = doTest() fun testMixedPropertyAccesses() = doTest() }
src/test/kotlin/co/nums/intellij/aem/htl/parser/complete/HtlPropertyAccessParsingTest.kt
2036308736
/* * Copyright (C) 2018 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.cash.sqldelight.db /** * API for creating and migrating a SQL database. */ interface SqlSchema { /** * The version of this schema. */ val version: Int /** * Use [driver] to create the schema from scratch. Assumes no existing database state. */ fun create(driver: SqlDriver): QueryResult<Unit> /** * Use [driver] to migrate from schema [oldVersion] to [newVersion]. */ fun migrate(driver: SqlDriver, oldVersion: Int, newVersion: Int): QueryResult<Unit> } /** * Represents a block of code [block] that should be executed during a migration after the migration * has finished migrating to [afterVersion]. */ class AfterVersion( internal val afterVersion: Int, internal val block: (SqlDriver) -> Unit, ) /** * Run [SqlSchema.migrate] normally but execute [callbacks] during the migration whenever * it finished upgrading to a version specified by [AfterVersion.afterVersion]. */ fun SqlSchema.migrateWithCallbacks( driver: SqlDriver, oldVersion: Int, newVersion: Int, vararg callbacks: AfterVersion, ) { var lastVersion = oldVersion // For each callback within the [oldVersion..newVersion) range, alternate between migrating // the schema and invoking each callback. callbacks.filter { it.afterVersion in oldVersion until newVersion } .sortedBy { it.afterVersion } .forEach { callback -> migrate(driver, oldVersion = lastVersion, newVersion = callback.afterVersion + 1) callback.block(driver) lastVersion = callback.afterVersion + 1 } // If there were no callbacks, or the newVersion is higher than the highest callback, // complete the migration. if (lastVersion < newVersion) { migrate(driver, lastVersion, newVersion) } }
runtime/src/commonMain/kotlin/app/cash/sqldelight/db/SqlSchema.kt
2429128257
/* * Copyright (C) 2017 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.marklogic.api import java.io.IOException class ResponseException(val statusCode: Int, val statusText: String, val response: Item?): IOException("$statusCode $statusText")
src/main/java/uk/co/reecedunn/intellij/plugin/marklogic/api/ResponseException.kt
3558303131
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.java.decompiler import com.intellij.JavaTestUtil import com.intellij.codeInsight.daemon.impl.IdentifierHighlighterPassFactory import com.intellij.codeInsight.navigation.actions.GotoDeclarationAction import com.intellij.execution.filters.LineNumbersMapping import com.intellij.ide.highlighter.ArchiveFileType import com.intellij.ide.structureView.StructureViewBuilder import com.intellij.ide.structureView.impl.java.JavaAnonymousClassesNodeProvider import com.intellij.ide.structureView.newStructureView.StructureViewComponent import com.intellij.ide.util.treeView.AbstractTreeNode import com.intellij.openapi.application.PluginPathManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx import com.intellij.openapi.fileEditor.impl.EditorHistoryManager import com.intellij.openapi.fileTypes.StdFileTypes import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.registry.RegistryValue import com.intellij.openapi.vfs.* import com.intellij.pom.Navigatable import com.intellij.psi.PsiManager import com.intellij.psi.impl.compiled.ClsFileImpl import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase import com.intellij.util.io.URLUtil class IdeaDecompilerTest : LightCodeInsightFixtureTestCase() { override fun setUp() { super.setUp() myFixture.testDataPath = "${PluginPathManager.getPluginHomePath("java-decompiler")}/plugin/testData" } override fun tearDown() { FileEditorManagerEx.getInstanceEx(project).closeAllFiles() for (file in EditorHistoryManager.getInstance(project).files) { EditorHistoryManager.getInstance(project).removeFile(file) } super.tearDown() } fun testSimple() { val file = getTestFile("${PlatformTestUtil.getRtJarPath()}!/java/lang/String.class") val decompiled = IdeaDecompiler().getText(file).toString() assertTrue(decompiled, decompiled.startsWith("${IdeaDecompiler.BANNER}package java.lang;\n")) assertTrue(decompiled, decompiled.contains("public final class String")) assertTrue(decompiled, decompiled.contains("@deprecated")) assertTrue(decompiled, decompiled.contains("private static class CaseInsensitiveComparator")) assertFalse(decompiled, decompiled.contains("/* compiled code */")) assertFalse(decompiled, decompiled.contains("synthetic")) } fun testStubCompatibility() { val visitor = MyFileVisitor(psiManager) Registry.get("decompiler.dump.original.lines").withValue(true) { VfsUtilCore.visitChildrenRecursively(getTestFile("${JavaTestUtil.getJavaTestDataPath()}/psi/cls/mirror"), visitor) VfsUtilCore.visitChildrenRecursively(getTestFile("${PlatformTestUtil.getRtJarPath()}!/java/lang"), visitor) } } fun testNavigation() { myFixture.openFileInEditor(getTestFile("Navigation.class")) doTestNavigation(11, 14, 14, 10) // to "m2()" doTestNavigation(15, 21, 14, 17) // to "int i" doTestNavigation(16, 28, 15, 13) // to "int r" } private fun doTestNavigation(line: Int, column: Int, expectedLine: Int, expectedColumn: Int) { val target = GotoDeclarationAction.findTargetElement(project, myFixture.editor, offset(line, column)) as Navigatable target.navigate(true) val expected = offset(expectedLine, expectedColumn) assertEquals(expected, myFixture.caretOffset) } private fun offset(line: Int, column: Int): Int = myFixture.editor.document.getLineStartOffset(line - 1) + column - 1 fun testHighlighting() { myFixture.openFileInEditor(getTestFile("Navigation.class")) IdentifierHighlighterPassFactory.doWithHighlightingEnabled { myFixture.editor.caretModel.moveToOffset(offset(11, 14)) // m2(): usage, declaration assertEquals(2, myFixture.doHighlighting().size) myFixture.editor.caretModel.moveToOffset(offset(14, 10)) // m2(): usage, declaration assertEquals(2, myFixture.doHighlighting().size) myFixture.editor.caretModel.moveToOffset(offset(14, 17)) // int i: usage, declaration assertEquals(2, myFixture.doHighlighting().size) myFixture.editor.caretModel.moveToOffset(offset(15, 21)) // int i: usage, declaration assertEquals(2, myFixture.doHighlighting().size) myFixture.editor.caretModel.moveToOffset(offset(15, 13)) // int r: usage, declaration assertEquals(2, myFixture.doHighlighting().size) myFixture.editor.caretModel.moveToOffset(offset(16, 28)) // int r: usage, declaration assertEquals(2, myFixture.doHighlighting().size) myFixture.editor.caretModel.moveToOffset(offset(19, 24)) // throws: declaration, m4() call assertEquals(2, myFixture.doHighlighting().size) } } fun testLineNumberMapping() { Registry.get("decompiler.use.line.mapping").withValue(true) { val file = getTestFile("LineNumbers.class") assertNull(file.getUserData(LineNumbersMapping.LINE_NUMBERS_MAPPING_KEY)) IdeaDecompiler().getText(file) val mapping = file.getUserData(LineNumbersMapping.LINE_NUMBERS_MAPPING_KEY)!! assertEquals(11, mapping.bytecodeToSource(3)) assertEquals(3, mapping.sourceToBytecode(11)) assertEquals(23, mapping.bytecodeToSource(13)) assertEquals(13, mapping.sourceToBytecode(23)) assertEquals(-1, mapping.bytecodeToSource(1000)) assertEquals(-1, mapping.sourceToBytecode(1000)) } } fun testPerformance() { val decompiler = IdeaDecompiler() val file = getTestFile("${PlatformTestUtil.getRtJarPath()}!/javax/swing/JTable.class") PlatformTestUtil.startPerformanceTest("decompiling JTable.class", 10000, { decompiler.getText(file) }).assertTiming() } fun testStructureView() { val file = getTestFile("StructureView.class") file.parent.children ; file.parent.refresh(false, true) // inner classes val editor = FileEditorManager.getInstance(project).openFile(file, false)[0] val builder = StructureViewBuilder.PROVIDER.getStructureViewBuilder(StdFileTypes.CLASS, file, project)!! val viewComponent = builder.createStructureView(editor, project) as StructureViewComponent Disposer.register(myFixture.testRootDisposable, viewComponent) viewComponent.setActionActive(JavaAnonymousClassesNodeProvider.ID, true) val treeStructure = viewComponent.treeStructure PlatformTestUtil.updateRecursively(treeStructure.rootElement as AbstractTreeNode<*>) PlatformTestUtil.assertTreeStructureEquals(treeStructure, """ StructureView.java StructureView B B() build(int): StructureView $1 class initializer StructureView() getData(): int setData(int): void data: int""".trimIndent()) } private fun getTestFile(name: String): VirtualFile { val path = if (FileUtil.isAbsolute(name)) name else "${myFixture.testDataPath}/${name}" val fs = if (path.contains(URLUtil.JAR_SEPARATOR)) StandardFileSystems.jar() else StandardFileSystems.local() return fs.refreshAndFindFileByPath(path)!! } private fun RegistryValue.withValue(testValue: Boolean, block: () -> Unit) { val currentValue = asBoolean() try { setValue(testValue) block() } finally { setValue(currentValue) } } private class MyFileVisitor(private val psiManager: PsiManager) : VirtualFileVisitor<Any>() { override fun visitFile(file: VirtualFile): Boolean { if (file.isDirectory) { println(file.path) } else if (file.fileType === StdFileTypes.CLASS && !file.name.contains('$')) { val clsFile = psiManager.findFile(file)!! val mirror = (clsFile as ClsFileImpl).mirror val decompiled = mirror.text assertTrue(file.path, decompiled.startsWith(IdeaDecompiler.BANNER) || file.name == "package-info.class") // check that no mapped line number is on an empty line val prefix = "// " decompiled.split("\n").dropLastWhile(String::isEmpty).toTypedArray().forEach { s -> val pos = s.indexOf(prefix) if (pos == 0 && prefix.length < s.length && Character.isDigit(s[prefix.length])) { fail("Incorrect line mapping in file " + file.path + " line: " + s) } } } else if (ArchiveFileType.INSTANCE == file.fileType) { val jarFile = JarFileSystem.getInstance().getRootByLocal(file) if (jarFile != null) { VfsUtilCore.visitChildrenRecursively(jarFile, this) } } return true } } }
plugins/java-decompiler/plugin/test/org/jetbrains/java/decompiler/IdeaDecompilerTest.kt
3482433501
package com.sksamuel.reactivehive.akkastream import akka.actor.ActorSystem import akka.stream.ActorMaterializer import akka.stream.Materializer import akka.stream.javadsl.Sink import akka.stream.javadsl.Source import com.sksamuel.reactivehive.BinaryType import com.sksamuel.reactivehive.BooleanType import com.sksamuel.reactivehive.DateType import com.sksamuel.reactivehive.DecimalType import com.sksamuel.reactivehive.Float32Type import com.sksamuel.reactivehive.Float64Type import com.sksamuel.reactivehive.Int16Type import com.sksamuel.reactivehive.Int32Type import com.sksamuel.reactivehive.Int64Type import com.sksamuel.reactivehive.Precision import com.sksamuel.reactivehive.Scale import com.sksamuel.reactivehive.StructField import com.sksamuel.reactivehive.StructType import com.sksamuel.reactivehive.TimestampMillisType import io.kotlintest.shouldBe import io.kotlintest.shouldNotBe import io.kotlintest.specs.FunSpec import org.apache.hadoop.conf.Configuration import org.apache.hadoop.fs.FileSystem import org.apache.hadoop.fs.Path import java.math.BigDecimal import java.math.BigInteger import java.math.MathContext import java.sql.Timestamp import java.time.Instant import java.time.LocalDate import java.util.concurrent.TimeUnit class ParquetSourceTest : FunSpec() { private val conf = Configuration() private val fs = FileSystem.getLocal(conf) private val system = ActorSystem.create("test") private val materializer: Materializer = ActorMaterializer.create(system) init { test("reading with parquet source") { val f = Source .fromGraph(ParquetSource(Path(this.javaClass.getResource("/spark.parquet").toURI()), conf)) .runWith(Sink.seq(), materializer) val struct = f.toCompletableFuture().get(1, TimeUnit.MINUTES).first() struct.schema shouldBe StructType( fields = listOf( StructField(name = "myDouble", type = Float64Type, nullable = true), StructField(name = "myLong", type = Int64Type, nullable = true), StructField(name = "myInt", type = Int32Type, nullable = true), StructField(name = "myBoolean", type = BooleanType, nullable = true), StructField(name = "myFloat", type = Float32Type, nullable = true), StructField(name = "myShort", type = Int16Type, nullable = true), StructField(name = "myDecimal", type = DecimalType(Precision(38), Scale(18)), nullable = true), StructField(name = "myBytes", type = BinaryType, nullable = true), StructField(name = "myDate", type = DateType, nullable = true), StructField(name = "myTimestamp", type = TimestampMillisType, nullable = true) ) ) struct.values[0] shouldBe 13.46 struct.values[1] shouldBe 1414 struct.values[2] shouldBe 239 struct.values[3] shouldBe true struct.values[4] shouldBe 1825.5 struct.values[5] shouldBe 12 struct.values[6] shouldBe BigDecimal(BigInteger.valueOf(727200000000000000L).multiply(BigInteger.valueOf(100)), 18, MathContext(38)) struct.values[7] shouldNotBe null struct.values[8] shouldBe LocalDate.of(3879, 10, 10) struct.values[9] shouldBe Timestamp.from(Instant.ofEpochMilli(11155523123L)) } } }
rxhive-components/rxhive-components-akkastream_2.12/src/test/kotlin/com/sksamuel/reactivehive/akkastream/ParquetSourceTest.kt
705664782
package org.pixelndice.table.pixelclient import org.pixelndice.table.pixelclient.ds.Account import org.pixelndice.table.pixelclient.ds.Campaign import org.pixelndice.table.pixelclient.ds.resource.Board var gameTag: String = "" @Synchronized get @Synchronized set var currentCampaign: Campaign = Campaign() @Synchronized get @Synchronized set val myAccount: Account = Account() @Synchronized get fun isGm(): Boolean { return myAccount.id == currentCampaign.gm.id } var currentBoard: Board? = null @Synchronized get @Synchronized set var playerBoard: Board? = null @Synchronized get @Synchronized set
src/main/kotlin/org/pixelndice/table/pixelclient/Current.kt
716078395
package org.pixelndice.table.pixelclient.connection.lobby.client import org.apache.logging.log4j.LogManager import org.pixelndice.table.pixelclient.ApplicationBus import org.pixelndice.table.pixelclient.ds.RPGGameSystem import org.pixelndice.table.pixelprotocol.ChannelCanceledException import org.pixelndice.table.pixelprotocol.Protobuf private val logger = LogManager.getLogger(State03LobbyAuthNotOk::class.java) /** * Process the negation of a lobby auth * @author Marcelo Costa Toyama */ class State03LobbyAuthNotOk : State { init { logger.debug("State03LobbyAuthNotOk constructor") } /** * Process the context */ override fun process(ctx: Context) { var packet = ctx.channel.packet if( packet != null ){ if( packet.payloadCase == Protobuf.Packet.PayloadCase.LOBBYAUTHNOK){ val game = packet.lobbyAuthNOk.game ctx.state = StateStop() ApplicationBus.post(ApplicationBus.LobbyAuthNOk(game.gm.name, game.campaign, RPGGameSystem.fromProtobuf(game.rpgGameSystem))) logger.debug("Lobby Autho Not Ok!") }else{ packet = ctx.channel.packet val message = "Expecting Lobby auth nok, instead received: $packet. IP: ${ctx.channel.address}" logger.error(message) val error = Protobuf.EndWithError.newBuilder() error.reason = message val resp = Protobuf.Packet.newBuilder() resp.endWithError = error.build() try { ctx.channel.packet = resp.build() } catch (e: ChannelCanceledException) { logger.trace("Channel in invalid state. It will be recycled in the next cycle.") } } } } }
src/main/kotlin/org/pixelndice/table/pixelclient/connection/lobby/client/State03LobbyAuthNotOk.kt
17675750
/* * Copyright (C) 2022 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.decode import android.graphics.Bitmap import android.graphics.Bitmap.Config.HARDWARE import android.graphics.Canvas import android.graphics.RectF import android.os.Build.VERSION import androidx.annotation.WorkerThread import androidx.exifinterface.media.ExifInterface import com.caverock.androidsvg.RenderOptions import com.caverock.androidsvg.SVG import com.github.panpf.sketch.Sketch import com.github.panpf.sketch.datasource.DataSource import com.github.panpf.sketch.decode.internal.appliedResize import com.github.panpf.sketch.decode.internal.getOrCreate import com.github.panpf.sketch.decode.internal.isSvg import com.github.panpf.sketch.decode.internal.logString import com.github.panpf.sketch.decode.internal.realDecode import com.github.panpf.sketch.fetch.FetchResult import com.github.panpf.sketch.request.internal.RequestContext import com.github.panpf.sketch.request.svgBackgroundColor import com.github.panpf.sketch.request.svgCss import kotlin.math.roundToInt /** * Decode svg file and convert to Bitmap */ class SvgBitmapDecoder constructor( private val sketch: Sketch, private val requestContext: RequestContext, private val dataSource: DataSource, private val useViewBoundsAsIntrinsicSize: Boolean = true, private val backgroundColor: Int?, private val css: String?, ) : BitmapDecoder { companion object { const val MODULE = "SvgBitmapDecoder" const val MIME_TYPE = "image/svg+xml" } @WorkerThread override suspend fun decode(): BitmapDecodeResult { // Currently running on a limited number of IO contexts, so this warning can be ignored @Suppress("BlockingMethodInNonBlockingContext") val svg = dataSource.newInputStream().buffered().use { SVG.getFromInputStream(it) } val imageInfo = readImageInfo(svg) return realDecode( requestContext = requestContext, dataFrom = dataSource.dataFrom, imageInfo = imageInfo, decodeFull = { decodeConfig: DecodeConfig -> realDecodeFull(imageInfo, decodeConfig, svg) }, decodeRegion = null ).appliedResize(sketch, requestContext) } private fun readImageInfo(svg: SVG): ImageInfo { val width: Int val height: Int val viewBox: RectF? = svg.documentViewBox if (useViewBoundsAsIntrinsicSize && viewBox != null) { width = viewBox.width().toInt() height = viewBox.height().toInt() } else { width = svg.documentWidth.toInt() height = svg.documentHeight.toInt() } return ImageInfo(width, height, MIME_TYPE, ExifInterface.ORIENTATION_UNDEFINED) } private fun realDecodeFull(imageInfo: ImageInfo, decodeConfig: DecodeConfig, svg: SVG): Bitmap { val svgWidth: Float val svgHeight: Float val viewBox: RectF? = svg.documentViewBox if (useViewBoundsAsIntrinsicSize && viewBox != null) { svgWidth = viewBox.width() svgHeight = viewBox.height() } else { svgWidth = svg.documentWidth svgHeight = svg.documentHeight } val inSampleSize = decodeConfig.inSampleSize?.toFloat() val dstWidth = if (inSampleSize != null) { (imageInfo.width / inSampleSize).roundToInt() } else { imageInfo.width } val dstHeight = if (inSampleSize != null) { (imageInfo.height / inSampleSize).roundToInt() } else { imageInfo.height } // Set the SVG's view box to enable scaling if it is not set. if (viewBox == null && svgWidth > 0 && svgHeight > 0) { svg.setDocumentViewBox(0f, 0f, svgWidth, svgHeight) } svg.setDocumentWidth("100%") svg.setDocumentHeight("100%") val bitmap = sketch.bitmapPool.getOrCreate( width = dstWidth, height = dstHeight, config = decodeConfig.inPreferredConfig.toSoftware(), disallowReuseBitmap = requestContext.request.disallowReuseBitmap, caller = "SvgBitmapDecoder" ) val canvas = Canvas(bitmap).apply { backgroundColor?.let { drawColor(it) } } val renderOptions = css?.let { RenderOptions().css(it) } svg.renderToCanvas(canvas, renderOptions) sketch.logger.d(MODULE) { "realDecodeFull. successful. ${bitmap.logString}. ${imageInfo}. '${requestContext.key}'" } return bitmap } /** * Convert null and [Bitmap.Config.HARDWARE] configs to [Bitmap.Config.ARGB_8888]. */ private fun Bitmap.Config?.toSoftware(): Bitmap.Config { return if (this == null || VERSION.SDK_INT >= 26 && this == HARDWARE) Bitmap.Config.ARGB_8888 else this } class Factory(val useViewBoundsAsIntrinsicSize: Boolean = true) : BitmapDecoder.Factory { override fun create( sketch: Sketch, requestContext: RequestContext, fetchResult: FetchResult ): SvgBitmapDecoder? = if ( MIME_TYPE.equals(fetchResult.mimeType, ignoreCase = true) || fetchResult.headerBytes.isSvg() ) { SvgBitmapDecoder( sketch = sketch, requestContext = requestContext, dataSource = fetchResult.dataSource, useViewBoundsAsIntrinsicSize = useViewBoundsAsIntrinsicSize, backgroundColor = requestContext.request.svgBackgroundColor, css = requestContext.request.svgCss ) } else { null } override fun toString(): String = "SvgBitmapDecoder" override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Factory) return false if (useViewBoundsAsIntrinsicSize != other.useViewBoundsAsIntrinsicSize) return false return true } override fun hashCode(): Int { return useViewBoundsAsIntrinsicSize.hashCode() } } }
sketch-svg/src/main/java/com/github/panpf/sketch/decode/SvgBitmapDecoder.kt
3477379671
package com.dhsdevelopments.rqjava class Main { companion object { @JvmStatic fun main(args: Array<String>): Unit { val conn = PotatoConnection("localhost", "/", "elias", "foo") conn.connect() conn.subscribeChannel("4e8ff1e0e1c7d80e8e4e5cea510147db", { msg -> println("From: ${msg.fromName} (${msg.from}), text: ${msg.text}") }) conn.registerCmd("as") { cmd -> println("cmd=${cmd.cmd}, args=${cmd.args}, channel=${cmd.channel}, domain=${cmd.domain}, user=${cmd.user}") conn.sendMessage(cmd.user, cmd.channel, "HTML injection by command handler", cmd.args) } } } }
contrib/rqjava/src/com/dhsdevelopments/rqjava/Main.kt
1346619904
/* * Copyright (c) 2018 NECTEC * National Electronics and Computer Technology Center, Thailand * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ffc.app.health.diagnosis import android.content.Context import ffc.android.assetAs import ffc.android.connectivityManager import ffc.api.ApiErrorException import ffc.api.FfcCentral import ffc.app.isConnected import ffc.app.util.RepoCallback import ffc.entity.gson.parseTo import ffc.entity.gson.toJson import ffc.entity.healthcare.Disease import ffc.entity.healthcare.Icd10 import org.jetbrains.anko.doAsync import retrofit2.Call import retrofit2.dsl.enqueue import retrofit2.http.GET import retrofit2.http.Query import java.io.File import java.io.IOException internal interface Diseases { fun all(res: RepoCallback<List<Disease>>.() -> Unit) fun disease(id: String, res: RepoCallback<Disease>.() -> Unit) } internal fun diseases(context: Context): Diseases = MockDiseases(context) private class ApiDisease(context: Context) : Diseases { private val localFile = File(context.filesDir, "diseases.json") private var loading = false private var tmpCallback: RepoCallback<List<Disease>>? = null private val api = FfcCentral().service<DiseaseApi>() init { if (context.connectivityManager.isConnected) { loading = true loadDisease(mutableListOf(), 1, 5000) { tmpCallback?.onFound?.invoke(it) doAsync { try { localFile.createNewFile() } catch (ignore: IOException) { //file already created } localFile.writeText(it.toJson()) } } } if (localFile.exists()) { diseases = localFile.readText().parseTo() } } fun loadDisease(disease: MutableList<Disease>, currentPage: Int, perPage: Int, onFinish: (List<Disease>) -> Unit) { api.get(currentPage, perPage).enqueue { always { tmpCallback?.always?.invoke() loading = false } onSuccess { disease.addAll(body()!!) if (currentPage == page?.last) { onFinish(disease) } else { loadDisease(disease, page!!.next, page!!.perPage, onFinish) } } onError { tmpCallback?.onFail!!.invoke(ApiErrorException(this)) } onFailure { tmpCallback?.onFail!!.invoke(it) } } } override fun all(res: RepoCallback<List<Disease>>.() -> Unit) { val callback = RepoCallback<List<Disease>>().apply(res) if (loading) { tmpCallback = callback } else { callback.always?.invoke() if (diseases.isNotEmpty()) { callback.onFound!!.invoke(diseases) } else { callback.onNotFound!!.invoke() } } } override fun disease(id: String, res: RepoCallback<Disease>.() -> Unit) { val callback = RepoCallback<Disease>().apply(res) val disease = diseases.firstOrNull { it.id == id } if (disease != null) { callback.onFound!!.invoke(disease) } else { callback.onNotFound!!.invoke() } } companion object { var diseases = listOf<Disease>() } } private class MockDiseases(val context: Context) : Diseases { init { if (diseases.isEmpty()) { diseases = context.assetAs<List<Icd10>>("lookups/Disease.json") } } override fun all(res: RepoCallback<List<Disease>>.() -> Unit) { val callback = RepoCallback<List<Disease>>().apply(res) callback.onFound!!.invoke(diseases) } override fun disease(id: String, res: RepoCallback<Disease>.() -> Unit) { val callback = RepoCallback<Disease>().apply(res) val disease = diseases.firstOrNull { it.id == id } if (disease != null) { callback.onFound!!.invoke(disease) } else { callback.onNotFound!!.invoke() } } companion object { internal var diseases: List<Disease> = listOf() } } interface DiseaseApi { @GET("diseases") fun get(@Query("page") page: Int = 1, @Query("per_page") perPage: Int = 10000): Call<List<Disease>> }
ffc/src/main/kotlin/ffc/app/health/diagnosis/Diseases.kt
483629656
package me.smr.weatherforecast.adapters import me.smr.weatherforecast.models.CitySearchResult interface SearchClickListener { fun onSearchItemClicked(item: CitySearchResult) }
app/src/main/java/me/smr/weatherforecast/adapters/SearchClickListener.kt
838459246
package com.bl_lia.kirakiratter.domain.entity import android.content.Context import android.support.annotation.StringRes import com.bl_lia.kirakiratter.R import java.util.* data class Notification( val id: Int, val type: String, val createdAt: Date, val account: Account?, val status: Status? ) { fun notifiedMessage(context: Context): String? = when (type) { "reblog" -> { context.s(R.string.notification_boost, account?.preparedDisplayName) } "favourite" -> { context.s(R.string.notification_favourite, account?.preparedDisplayName) } "follow" -> { context.s(R.string.notification_follow, account?.preparedDisplayName) } "mention" -> { context.s(R.string.notification_mention, account?.preparedDisplayName) } else -> null } private fun Context.s(@StringRes id: Int, vararg paramString: String?): String = resources.getString(id).format(*paramString) }
app/src/main/kotlin/com/bl_lia/kirakiratter/domain/entity/Notification.kt
3787465762
package com.stripe.example.activity import android.os.Bundle import android.view.View import androidx.lifecycle.Observer import com.stripe.android.model.Address import com.stripe.android.model.MandateDataParams import com.stripe.android.model.PaymentMethod import com.stripe.android.model.PaymentMethodCreateParams import com.stripe.android.payments.paymentlauncher.PaymentResult import com.stripe.example.R import com.stripe.example.databinding.CreateSepaDebitActivityBinding /** * An example integration for confirming a Payment Intent using a SEPA Debit Payment Method. * * See [SEPA Direct Debit payments](https://stripe.com/docs/payments/sepa-debit) for more * details. */ class ConfirmSepaDebitActivity : StripeIntentActivity() { private val viewBinding: CreateSepaDebitActivityBinding by lazy { CreateSepaDebitActivityBinding.inflate(layoutInflater) } private val snackbarController: SnackbarController by lazy { SnackbarController(viewBinding.coordinator) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(viewBinding.root) setTitle(R.string.launch_confirm_pm_sepa_debit) viewModel.inProgress.observe(this, { enableUi(!it) }) viewModel.status.observe(this, Observer(viewBinding.status::setText)) viewBinding.ibanInput.setText(TEST_ACCOUNT_NUMBER) viewBinding.confirmButton.setOnClickListener { val params = createPaymentMethodParams(viewBinding.ibanInput.text.toString()) .takeIf { EXISTING_PAYMENT_METHOD_ID == null } createAndConfirmPaymentIntent( "nl", params, existingPaymentMethodId = EXISTING_PAYMENT_METHOD_ID, mandateDataParams = mandateData ) } } private fun enableUi(enabled: Boolean) { viewBinding.progressBar.visibility = if (enabled) View.INVISIBLE else View.VISIBLE viewBinding.confirmButton.isEnabled = enabled } override fun onConfirmSuccess() { super.onConfirmSuccess() snackbarController.show("Confirmation succeeded.") } override fun onConfirmCanceled() { super.onConfirmCanceled() snackbarController.show("Confirmation canceled.") } override fun onConfirmError(failedResult: PaymentResult.Failed) { super.onConfirmError(failedResult) snackbarController.show("Error during confirmation: ${failedResult.throwable.message}") } private fun createPaymentMethodParams(iban: String): PaymentMethodCreateParams { return PaymentMethodCreateParams.create( PaymentMethodCreateParams.SepaDebit(iban), PaymentMethod.BillingDetails.Builder() .setAddress( Address.Builder() .setCity("San Francisco") .setCountry("US") .setLine1("123 Market St") .setLine2("#345") .setPostalCode("94107") .setState("CA") .build() ) .setEmail("[email protected]") .setName("Jenny Rosen") .setPhone("(555) 555-5555") .build() ) } private companion object { private const val TEST_ACCOUNT_NUMBER = "DE89370400440532013000" // set to an existing payment method id to use in integration private val EXISTING_PAYMENT_METHOD_ID: String? = null private val mandateData = MandateDataParams( MandateDataParams.Type.Online( ipAddress = "127.0.0.1", userAgent = "agent" ) ) } }
example/src/main/java/com/stripe/example/activity/ConfirmSepaDebitActivity.kt
1545408986
package de.reiss.bible2net.theword.events import org.greenrobot.eventbus.EventBus val eventBus: EventBus by lazy { EventBus.getDefault() } fun postMessageEvent(event: AppEventMessage) { eventBus.post(event) }
app/src/main/java/de/reiss/bible2net/theword/events/AppEventMessageBus.kt
823631649
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.watchface.complications.data import android.graphics.drawable.Icon import android.os.Build import androidx.annotation.RequiresApi import androidx.annotation.RestrictTo internal const val PLACEHOLDER_IMAGE_RESOURCE_ID = -1 internal fun createPlaceholderIcon(): Icon = Icon.createWithResource("", PLACEHOLDER_IMAGE_RESOURCE_ID) /** * A simple, monochromatic image that can be tinted by the watch face. * * A monochromatic image doesn't have to be black and white, it can have a single color associated * with the provider / brand with the expectation that the watch face may recolor it (typically * using a SRC_IN filter). * * An ambient alternative is provided that may be shown instead of the regular image while the * watch is not active. * * @property [image] The image itself * @property [ambientImage] The image to be shown when the device is in ambient mode to save power * or avoid burn in */ public class MonochromaticImage internal constructor( public val image: Icon, public val ambientImage: Icon? ) { /** * Builder for [MonochromaticImage]. * * @param [image] the [Icon] representing the image */ public class Builder(private var image: Icon) { private var ambientImage: Icon? = null /** * Sets a different image for when the device is ambient mode to save power and prevent * burn in. If no ambient variant is provided, the watch face may not show anything while * in ambient mode. */ public fun setAmbientImage(ambientImage: Icon?): Builder = apply { this.ambientImage = ambientImage } /** Constructs the [MonochromaticImage]. */ public fun build(): MonochromaticImage = MonochromaticImage(image, ambientImage) } /** Adds a [MonochromaticImage] to a builder for [WireComplicationData]. */ internal fun addToWireComplicationData(builder: WireComplicationDataBuilder) = builder.apply { setIcon(image) setBurnInProtectionIcon(ambientImage) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as MonochromaticImage if (!if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { IconHelperP.equals(image, other.image) } else { IconHelperBeforeP.equals(image, other.image) } ) return false if (!if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { IconHelperP.equals(ambientImage, other.ambientImage) } else { IconHelperBeforeP.equals(ambientImage, other.ambientImage) } ) return false return true } override fun hashCode(): Int { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { var result = IconHelperP.hashCode(image) result = 31 * result + IconHelperP.hashCode(ambientImage) result } else { var result = IconHelperBeforeP.hashCode(image) result = 31 * result + IconHelperBeforeP.hashCode(ambientImage) result } } override fun toString(): String { return "MonochromaticImage(image=$image, ambientImage=$ambientImage)" } /** @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) fun isPlaceholder() = image.isPlaceholder() /** @hide */ public companion object { /** * For use when the real data isn't available yet, this [MonochromaticImage] should be * rendered as a placeholder. It is suggested that it should be rendered with a light grey * box. * * Note a placeholder may only be used in the context of * [NoDataComplicationData.placeholder]. */ @JvmField public val PLACEHOLDER: MonochromaticImage = MonochromaticImage(createPlaceholderIcon(), null) } } /** * The type of image being provided. * * This is used to guide rendering on the watch face. */ public enum class SmallImageType { /** * Type for images that have a transparent background and are expected to be drawn * entirely within the space available, such as a launcher image. Watch faces may add padding * when drawing these images, but should never crop these images. Icons must not be recolored. */ ICON, /** * Type for images which are photos that are expected to fill the space available. Images * of this style may be cropped to fit the shape of the complication - in particular, the image * may be cropped to a circle. Photos must not be recolored. */ PHOTO } /** * An image that is expected to cover a small fraction of a watch face occupied by a single * complication. A SmallImage must not be tinted. * * An ambient alternative is provided that may be shown instead of the regular image while the * watch is not active. * * @property [image] The image itself * @property [type] The style of the image provided, to guide how it should be displayed * @property [ambientImage] The image to be shown when the device is in ambient mode to save power * or avoid burn in */ public class SmallImage internal constructor( public val image: Icon, public val type: SmallImageType, public val ambientImage: Icon? ) { /** * Builder for [SmallImage]. * * @param [image] The [Icon] representing the image * @param [type] The style of the image provided, to guide how it should be displayed */ public class Builder(private val image: Icon, private val type: SmallImageType) { private var ambientImage: Icon? = null /** * Sets a different image for when the device is ambient mode to save power and prevent * burn in. If no ambient variant is provided, the watch face may not show anything while * in ambient mode. */ public fun setAmbientImage(ambientImage: Icon?): Builder = apply { this.ambientImage = ambientImage } /** Builds a [SmallImage]. */ public fun build(): SmallImage = SmallImage(image, type, ambientImage) } /** Adds a [SmallImage] to a builder for [WireComplicationData]. */ internal fun addToWireComplicationData(builder: WireComplicationDataBuilder) = builder.apply { setSmallImage(image) setSmallImageStyle( when ([email protected]) { SmallImageType.ICON -> WireComplicationData.IMAGE_STYLE_ICON SmallImageType.PHOTO -> WireComplicationData.IMAGE_STYLE_PHOTO } ) setBurnInProtectionSmallImage(ambientImage) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as SmallImage if (type != other.type) return false if (!if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { IconHelperP.equals(image, other.image) } else { IconHelperBeforeP.equals(image, other.image) } ) return false if (!if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { IconHelperP.equals(ambientImage, other.ambientImage) } else { IconHelperBeforeP.equals(ambientImage, other.ambientImage) } ) return false return true } override fun hashCode(): Int { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { var result = IconHelperP.hashCode(image) result = 31 * result + type.hashCode() result = 31 * result + IconHelperP.hashCode(ambientImage) result } else { var result = IconHelperBeforeP.hashCode(image) result = 31 * result + type.hashCode() result = 31 * result + IconHelperBeforeP.hashCode(ambientImage) result } } override fun toString(): String { return "SmallImage(image=$image, type=$type, ambientImage=$ambientImage)" } /** @hide */ public companion object { /** * For use when the real data isn't available yet, this [SmallImage] should be rendered * as a placeholder. It is suggested that it should be rendered with a light grey box. * * Note a placeholder may only be used in the context of * [NoDataComplicationData.placeholder]. */ @JvmField public val PLACEHOLDER: SmallImage = SmallImage(createPlaceholderIcon(), SmallImageType.ICON, null) } /** @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) fun isPlaceholder() = image.isPlaceholder() } /** @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) fun Icon.isPlaceholder() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { IconHelperP.isPlaceholder(this) } else { false } @RequiresApi(Build.VERSION_CODES.P) internal class IconHelperP { companion object { fun isPlaceholder(icon: Icon): Boolean { return icon.type == Icon.TYPE_RESOURCE && icon.resId == PLACEHOLDER_IMAGE_RESOURCE_ID } fun equals(a: Icon?, b: Icon?): Boolean { if (a == null) { return b == null } if (b == null) { return false } if (a.type != b.type) return false when (a.type) { Icon.TYPE_RESOURCE -> { if (a.resId != b.resId) return false if (a.resPackage != b.resPackage) return false } Icon.TYPE_URI -> { if (a.uri.toString() != b.uri.toString()) return false } else -> { if (a != b) return false } } return true } fun hashCode(a: Icon?): Int { if (a == null) return 0 when (a.type) { Icon.TYPE_RESOURCE -> { var result = a.type.hashCode() result = 31 * result + a.resId.hashCode() result = 31 * result + a.resPackage.hashCode() return result } Icon.TYPE_URI -> { var result = a.type.hashCode() result = 31 * result + a.uri.toString().hashCode() return result } else -> return a.hashCode() } } } } internal class IconHelperBeforeP { companion object { fun equals(a: Icon?, b: Icon?): Boolean = (a == b) fun hashCode(a: Icon?): Int = a?.hashCode() ?: 0 } }
wear/watchface/watchface-complications-data/src/main/java/androidx/wear/watchface/complications/data/Image.kt
561751957