content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package net.nemerosa.ontrack.service import net.nemerosa.ontrack.common.BaseException import net.nemerosa.ontrack.it.AbstractDSLTestJUnit4Support import net.nemerosa.ontrack.model.structure.NameDescription import net.nemerosa.ontrack.model.support.ApplicationLogEntry import net.nemerosa.ontrack.model.support.ApplicationLogEntryFilter import net.nemerosa.ontrack.model.support.ApplicationLogService import net.nemerosa.ontrack.model.support.Page import org.junit.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.test.annotation.DirtiesContext import org.springframework.transaction.annotation.Transactional import java.util.* import kotlin.test.assertFailsWith import kotlin.test.assertTrue @DirtiesContext class ApplicationLogServiceIT : AbstractDSLTestJUnit4Support() { @Autowired private lateinit var sampleService: SampleService @Autowired private lateinit var applicationLogService: ApplicationLogService @Test fun `Errors must be logged even when transaction is rolled back`() { // ID of the test val uuid = UUID.randomUUID().toString() // We expect a failure assertFailsWith<SampleServiceException> { sampleService.run(uuid) } // ... but the error must be logged val filter = ApplicationLogEntryFilter().withText(uuid) val entries = asAdmin { applicationLogService.getLogEntries(filter, Page(count = 1)) } assertTrue(entries.isNotEmpty(), "Log entry was found") } interface SampleService { fun run(uuid: String) } class SampleServiceInitialException : BaseException("Sample message") class SampleServiceException : BaseException("Sample message") open class SampleServiceImpl( private val applicationLogService: ApplicationLogService ) : SampleService { @Transactional override fun run(uuid: String) { applicationLogService.log( ApplicationLogEntry.error( SampleServiceInitialException(), NameDescription.nd("sample", "Sample error"), "Error $uuid" ) ) throw SampleServiceException() } } @Configuration class ApplicationLogServiceITConfiguration( private val applicationLogService: ApplicationLogService ) { @Bean fun sampleService(): SampleService = SampleServiceImpl(applicationLogService) } }
ontrack-service/src/test/java/net/nemerosa/ontrack/service/ApplicationLogServiceIT.kt
478117496
package graphql.schema /** * A special type to allow a object/interface types to reference itself. It's replaced with the real type * object when the schema is build. */ class GraphQLTypeReference(override val name: String) : GraphQLType, GraphQLOutputType, GraphQLInputType, TypeReference fun typeRef(name: String) = GraphQLTypeReference(name)
src/main/kotlin/graphql/schema/GraphQLTypeReference.kt
1926845142
package io.github.vjames19.kotlinmicroserviceexample.blog.api.jooby import io.restassured.response.* import org.jooby.Status /** * Created by victor.reventos on 6/13/17. */ inline fun <reified T> Response.As(): T { return this.`as`(T::class.java) } inline fun <reified T> ExtractableResponse<*>.As(): T { return this.`as`(T::class.java) } inline fun <reified T> ValidatableResponseOptions<*, *>.As(): T { return extract().As<T>() } fun <T : ValidatableResponseOptions<T, R>?, R> ValidatableResponseOptions<T, R>.statusCode(status: Status): T where R : ResponseOptions<R>, R : ResponseBody<R> { return statusCode(status.value()) }
jooby-api/src/test/kotlin/io/github/vjames19/kotlinmicroserviceexample/blog/api/jooby/RestAssuredUtils.kt
586589114
package net.blakelee.coinprofits.tools import android.content.Context import android.content.res.Resources import android.graphics.Paint import android.graphics.Rect import android.graphics.Typeface import java.text.NumberFormat val Int.dp: Float get() = (this / Resources.getSystem().displayMetrics.density + 0.5f) val Int.px: Float get() = (this * Resources.getSystem().displayMetrics.density + 0.5f) //Round to ceil fun textDim(text: String, context: Context, textSize: Float = 16f): Int { val bounds = Rect() val textPaint = Paint() textPaint.typeface = Typeface.DEFAULT textPaint.textSize = textSize textPaint.getTextBounds(text, 0, text.length, bounds) return bounds.width() * context.resources.displayMetrics.density.toInt() } fun decimalFormat(number: Double): String { val format = NumberFormat.getInstance() val splitter = "%f".format(number).split("\\.") format.minimumFractionDigits = 2 if (number > 1) format.maximumFractionDigits = 2 else { var places = 0 if (splitter[0].length > 2) for(char in splitter[0]) { if (char != '0' && places >= 2) { break } places++ } else { places = 2 } format.maximumFractionDigits = places } return format.format(number) }
app/src/main/java/net/blakelee/coinprofits/tools/Utils.kt
425884222
@file:Suppress("NOTHING_TO_INLINE") package io.dico.parcels2.storage import io.dico.parcels2.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlinx.coroutines.Job import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.channels.SendChannel import kotlinx.coroutines.launch import org.joda.time.DateTime import java.util.UUID import kotlin.coroutines.CoroutineContext typealias DataPair = Pair<ParcelId, ParcelDataHolder?> typealias PrivilegePair<TAttach> = Pair<TAttach, PrivilegesHolder> interface Storage { val name: String val isConnected: Boolean fun init(): Job fun shutdown(): Job fun getWorldCreationTime(worldId: ParcelWorldId): Deferred<DateTime?> fun setWorldCreationTime(worldId: ParcelWorldId, time: DateTime): Job fun getPlayerUuidForName(name: String): Deferred<UUID?> fun updatePlayerName(uuid: UUID, name: String): Job fun readParcelData(parcel: ParcelId): Deferred<ParcelDataHolder?> fun transmitParcelData(parcels: Sequence<ParcelId>): ReceiveChannel<DataPair> fun transmitAllParcelData(): ReceiveChannel<DataPair> fun getOwnedParcels(user: PlayerProfile): Deferred<List<ParcelId>> fun getNumParcels(user: PlayerProfile): Deferred<Int> fun setParcelData(parcel: ParcelId, data: ParcelDataHolder?): Job fun setParcelOwner(parcel: ParcelId, owner: PlayerProfile?): Job fun setParcelOwnerSignOutdated(parcel: ParcelId, outdated: Boolean): Job fun setLocalPrivilege(parcel: ParcelId, player: PlayerProfile, privilege: Privilege): Job fun setParcelOptionsInteractConfig(parcel: ParcelId, config: InteractableConfiguration): Job fun transmitAllGlobalPrivileges(): ReceiveChannel<PrivilegePair<PlayerProfile>> fun readGlobalPrivileges(owner: PlayerProfile): Deferred<PrivilegesHolder?> fun setGlobalPrivilege(owner: PlayerProfile, player: PlayerProfile, privilege: Privilege): Job fun getChannelToUpdateParcelData(): SendChannel<Pair<ParcelId, ParcelDataHolder>> } class BackedStorage internal constructor(val b: Backing) : Storage, CoroutineScope { override val name get() = b.name override val isConnected get() = b.isConnected override val coroutineContext: CoroutineContext get() = b.coroutineContext override fun init() = launch { b.init() } override fun shutdown() = launch { b.shutdown() } override fun getWorldCreationTime(worldId: ParcelWorldId): Deferred<DateTime?> = b.launchFuture { b.getWorldCreationTime(worldId) } override fun setWorldCreationTime(worldId: ParcelWorldId, time: DateTime): Job = b.launchJob { b.setWorldCreationTime(worldId, time) } override fun getPlayerUuidForName(name: String): Deferred<UUID?> = b.launchFuture { b.getPlayerUuidForName(name) } override fun updatePlayerName(uuid: UUID, name: String): Job = b.launchJob { b.updatePlayerName(uuid, name) } override fun readParcelData(parcel: ParcelId) = b.launchFuture { b.readParcelData(parcel) } override fun transmitParcelData(parcels: Sequence<ParcelId>) = b.openChannel<DataPair> { b.transmitParcelData(it, parcels) } override fun transmitAllParcelData() = b.openChannel<DataPair> { b.transmitAllParcelData(it) } override fun getOwnedParcels(user: PlayerProfile) = b.launchFuture { b.getOwnedParcels(user) } override fun getNumParcels(user: PlayerProfile) = b.launchFuture { b.getNumParcels(user) } override fun setParcelData(parcel: ParcelId, data: ParcelDataHolder?) = b.launchJob { b.setParcelData(parcel, data) } override fun setParcelOwner(parcel: ParcelId, owner: PlayerProfile?) = b.launchJob { b.setParcelOwner(parcel, owner) } override fun setParcelOwnerSignOutdated(parcel: ParcelId, outdated: Boolean): Job = b.launchJob { b.setParcelOwnerSignOutdated(parcel, outdated) } override fun setLocalPrivilege(parcel: ParcelId, player: PlayerProfile, privilege: Privilege) = b.launchJob { b.setLocalPrivilege(parcel, player, privilege) } override fun setParcelOptionsInteractConfig(parcel: ParcelId, config: InteractableConfiguration) = b.launchJob { b.setParcelOptionsInteractConfig(parcel, config) } override fun transmitAllGlobalPrivileges(): ReceiveChannel<PrivilegePair<PlayerProfile>> = b.openChannel { b.transmitAllGlobalPrivileges(it) } override fun readGlobalPrivileges(owner: PlayerProfile): Deferred<PrivilegesHolder?> = b.launchFuture { b.readGlobalPrivileges(owner) } override fun setGlobalPrivilege(owner: PlayerProfile, player: PlayerProfile, privilege: Privilege) = b.launchJob { b.setGlobalPrivilege(owner, player, privilege) } override fun getChannelToUpdateParcelData(): SendChannel<Pair<ParcelId, ParcelDataHolder>> = b.openChannelForWriting { b.setParcelData(it.first, it.second) } }
src/main/kotlin/io/dico/parcels2/storage/Storage.kt
2804293417
/* * 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 com.intellij.testGuiFramework.testCases import com.intellij.testGuiFramework.fixtures.JDialogFixture import com.intellij.testGuiFramework.framework.Timeouts import com.intellij.testGuiFramework.framework.Timeouts.seconds05 import com.intellij.testGuiFramework.impl.* import com.intellij.testGuiFramework.impl.GuiTestUtilKt.ignoreComponentLookupException import com.intellij.testGuiFramework.impl.GuiTestUtilKt.waitProgressDialogUntilGone import com.intellij.testGuiFramework.launcher.GuiTestOptions import com.intellij.testGuiFramework.remote.transport.MessageType import com.intellij.testGuiFramework.remote.transport.RestartIdeAndResumeContainer import com.intellij.testGuiFramework.remote.transport.RestartIdeCause import com.intellij.testGuiFramework.remote.transport.TransportMessage import org.fest.swing.exception.WaitTimedOutError import java.io.File import javax.swing.JDialog open class PluginTestCase : GuiTestCase() { val getEnv: String by lazy { File(System.getenv("WEBSTORM_PLUGINS") ?: throw IllegalArgumentException("WEBSTORM_PLUGINS env variable isn't specified")).absolutePath } fun findPlugin(pluginName: String): String { val f = File(getEnv) return f.listFiles { _, name -> name.startsWith(pluginName) }[0].toString() } fun installPluginAndRestart(installPluginsFunction: () -> Unit) { if (guiTestRule.getTestName() == GuiTestOptions.resumeTestName && GuiTestOptions.resumeInfo == PLUGINS_INSTALLED) { } else { //if plugins are not installed yet installPluginsFunction() //send restart message and resume this test to the server GuiTestThread.client?.send(TransportMessage(MessageType.RESTART_IDE_AND_RESUME, RestartIdeAndResumeContainer(RestartIdeCause.PLUGIN_INSTALLED))) ?: throw Exception( "Unable to get the client instance to send message.") //wait until IDE is going to restart GuiTestUtilKt.waitUntil("IDE will be closed", timeout = Timeouts.defaultTimeout) { false } } } fun installPlugins(vararg pluginNames: String) { welcomeFrame { actionLink("Configure").click() popupMenu("Plugins").clickSearchedItem() dialog("Plugins") { button("Install JetBrains plugin...").click() dialog("Browse JetBrains Plugins ") browsePlugins@ { pluginNames.forEach { [email protected](it) } button("Close").click() } button("OK") ensureButtonOkHasPressed(this@PluginTestCase) } message("IDE and Plugin Updates") { button("Postpone").click() } } } fun installPluginFromDisk(pluginPath: String, pluginName: String) { welcomeFrame { actionLink("Configure").click() popupMenu("Plugins").clickSearchedItem() pluginDialog { showInstalledPlugins() if (isPluginInstalled(pluginName).not()) { showInstallPluginFromDiskDialog() installPluginFromDiskDialog { setPath(pluginPath) clickOk() ignoreComponentLookupException { dialog(title = "Warning", timeout = seconds05) { message("Warning") { button("OK").click() } } } } } button("OK").click() ignoreComponentLookupException { dialog(title = "IDE and Plugin Updates", timeout = seconds05) { button("Postpone").click() } } } } } private fun ensureButtonOkHasPressed(guiTestCase: GuiTestCase) { val dialogTitle = "Plugins" try { GuiTestUtilKt.waitUntilGone(robot = guiTestCase.robot(), timeout = seconds05, matcher = GuiTestUtilKt.typeMatcher( JDialog::class.java) { it.isShowing && it.title == dialogTitle }) } catch (timeoutError: WaitTimedOutError) { with(guiTestCase) { val dialog = JDialogFixture.find(guiTestCase.robot(), dialogTitle) with(dialog) { button("OK").clickWhenEnabled() } } } } private fun JDialogFixture.installPlugin(pluginName: String) { table(pluginName).cell(pluginName).click() button("Install").click() waitProgressDialogUntilGone(robot(), "Downloading Plugins") println("$pluginName plugin has been installed") } companion object { const val PLUGINS_INSTALLED = "PLUGINS_INSTALLED" } }
platform/testGuiFramework/src/com/intellij/testGuiFramework/testCases/PluginTestCase.kt
3872707238
/* * Copyright (c) 2019 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.materialstudies.owl.ui.mycourses import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.findNavController import androidx.navigation.fragment.FragmentNavigatorExtras import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.materialstudies.owl.R import com.materialstudies.owl.databinding.CourseItemBinding import com.materialstudies.owl.model.Course import com.materialstudies.owl.model.CourseDiff import com.materialstudies.owl.model.CourseId import com.materialstudies.owl.util.ShapeAppearanceTransformation class MyCoursesAdapter : ListAdapter<Course, MyCourseViewHolder>(CourseDiff) { private object onClick : CourseViewClick { override fun onClick(view: View, courseId: CourseId) { val extras = FragmentNavigatorExtras( view to "shared_element" ) val action = MyCoursesFragmentDirections.actionMycoursesToLearn(courseId) view.findNavController().navigate(action, extras) } } private val shapeTransform = ShapeAppearanceTransformation(R.style.ShapeAppearance_Owl_SmallComponent) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyCourseViewHolder { return MyCourseViewHolder( CourseItemBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun onBindViewHolder(holder: MyCourseViewHolder, position: Int) { holder.bind(getItem(position), shapeTransform, onClick) } } interface CourseViewClick { fun onClick(view: View, courseId: CourseId) } class MyCourseViewHolder( private val binding: CourseItemBinding ) : RecyclerView.ViewHolder(binding.root) { fun bind( course: Course, imageTransform: ShapeAppearanceTransformation, onClick: CourseViewClick ) { binding.run { this.course = course this.clickHandler = onClick Glide.with(courseImage) .load(course.thumbUrl) .placeholder(R.drawable.stroked_course_image_placeholder) .transform(imageTransform) .into(courseImage) executePendingBindings() } } }
Owl/app/src/main/java/com/materialstudies/owl/ui/mycourses/MyCoursesAdapter.kt
1697179241
package com.soywiz.korge.ui import com.soywiz.kmem.* import com.soywiz.korge.annotations.* import com.soywiz.korge.render.* import com.soywiz.korge.view.* import com.soywiz.korma.geom.* @KorgeExperimental inline fun Container.uiVerticalList( provider: UIVerticalList.Provider, width: Double = 256.0, block: @ViewDslMarker Container.(UIVerticalList) -> Unit = {} ): UIVerticalList = UIVerticalList(provider, width) .addTo(this).also { block(it) } @KorgeExperimental open class UIVerticalList(provider: Provider, width: Double = 200.0) : UIView(width) { interface Provider { val numItems: Int val fixedHeight: Double? fun getItemY(index: Int): Double = (fixedHeight ?: 20.0) * index fun getItemHeight(index: Int): Double fun getItemView(index: Int): View } private var dirty = false private val viewsByIndex = LinkedHashMap<Int, View>() private val lastArea = Rectangle() private val lastPoint = Point() private val tempRect = Rectangle() private val tempPoint = Point() var provider: Provider = provider set(value) { field = value dirty = true updateList() } init { updateList() addUpdater { updateList() } } override fun renderInternal(ctx: RenderContext) { updateList() super.renderInternal(ctx) } private fun getIndexAtY(y: Double): Int { val index = y / (provider.fixedHeight?.toDouble() ?: 20.0) return index.toInt() } fun invalidateList() { dirty = true removeChildren() viewsByIndex.clear() updateList() } private val tempTransform = Matrix.Transform() fun updateList() { if (parent == null) return val area = getVisibleWindowArea(tempRect) val point = globalXY(tempPoint) val numItems = provider.numItems if (area != lastArea || point != lastPoint) { dirty = false lastArea.copyFrom(area) lastPoint.copyFrom(point) //val nheight = provider.fixedHeight?.toDouble() ?: 20.0 //val nItems = (area.height / nheight).toIntCeil() //println(nItems) //removeChildren() //val fromIndex = (startIndex).clamp(0, numItems - 1) //val toIndex = (startIndex + nItems).clamp(0, numItems - 1) //println("----") //println("point=$point") val transform = parent!!.globalMatrix.toTransform(tempTransform) //println("transform=${transform.scaleAvg}") val fromIndex = getIndexAtY((-point.y + tempRect.top) / transform.scaleY).clamp(0, numItems - 1) var toIndex = fromIndex for (index in fromIndex until numItems) { val view = viewsByIndex.getOrPut(index) { val itemHeight = provider.getItemHeight(index) provider.getItemView(index) .also { addChild(it) } .position(0.0, provider.getItemY(index)) .size(width, itemHeight.toDouble()) } toIndex = index //val localViewY = view.localToGlobalY(0.0, view.height) if (view.localToRenderY(0.0, view.height) >= area.bottom) { //println("localViewY=localViewY, globalY=${view.localToGlobalY(0.0, view.height)}") break } } //println("area=$area, point=$point, nItems=${toIndex - fromIndex}, fromIndex=$fromIndex, toIndex=$toIndex, globalBounds=${this.globalBounds}") val removeIndices = viewsByIndex.keys.filter { it !in fromIndex .. toIndex }.toSet() viewsByIndex.forEach { (index, view) -> if (index in removeIndices) { view.removeFromParent() } } for (index in removeIndices) viewsByIndex.remove(index) } setSize(width, provider.getItemY(numItems - 1) + provider.getItemHeight(numItems - 1)) //println("height=$height") } }
korge/src/commonMain/kotlin/com/soywiz/korge/ui/UIVerticalList.kt
2445147554
package com.karumi.ui.view import com.github.salomonbrys.kodein.Kodein import com.karumi.R import org.junit.Test class HideViewsActivityTest : AcceptanceTest<HideViewsActivity>(HideViewsActivity::class.java) { override val ignoredViews: List<Int> = listOf(R.id.view1) @Test fun showsActivityWithViewsInside() { val activity = startActivity() compareScreenshot(activity) } override val testDependencies = Kodein.Module(allowSilentOverride = true) { } }
shot-consumer/app/src/androidTest/java/com/karumi/ui/view/HideViewsActivityTest.kt
158668353
/** * Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information) * This program comes with ABSOLUTELY NO WARRANTY; * This is free software, and you are welcome to redistribute it under certain conditions. * * For more information, refer to the LICENSE file in this repositories root directory */ package ink.abb.pogo.scraper.tasks import POGOProtos.Networking.Responses.CatchPokemonResponseOuterClass.CatchPokemonResponse import POGOProtos.Networking.Responses.DiskEncounterResponseOuterClass import POGOProtos.Networking.Responses.EncounterResponseOuterClass import POGOProtos.Networking.Responses.EncounterResponseOuterClass.EncounterResponse.Status import ink.abb.pogo.api.cache.MapPokemon import ink.abb.pogo.scraper.Bot import ink.abb.pogo.scraper.Context import ink.abb.pogo.scraper.Settings import ink.abb.pogo.scraper.Task import ink.abb.pogo.scraper.util.Log import ink.abb.pogo.scraper.util.directions.getAltitude import ink.abb.pogo.scraper.util.pokemon.* import java.util.concurrent.atomic.AtomicInteger class CatchOneNearbyPokemon : Task { override fun run(bot: Bot, ctx: Context, settings: Settings) { // STOP WALKING ctx.pauseWalking.set(true) val pokemon = ctx.api.map.getPokemon(ctx.api.latitude, ctx.api.longitude, settings.initialMapSize).filter { !ctx.blacklistedEncounters.contains(it.encounterId) && it.inRange } val hasPokeballs = ctx.api.inventory.hasPokeballs /*Pokeball.values().forEach { Log.yellow("${it.ballType}: ${ctx.api.cachedInventories.itemBag.getItem(it.ballType).count}") }*/ if (!hasPokeballs) { ctx.pauseWalking.set(false) return } if (pokemon.isNotEmpty()) { val catchablePokemon = pokemon.first() if (settings.obligatoryTransfer.contains(catchablePokemon.pokemonId) && settings.desiredCatchProbabilityUnwanted == -1.0 || settings.neverCatchPokemon.contains(catchablePokemon.pokemonId)) { ctx.blacklistedEncounters.add(catchablePokemon.encounterId) Log.normal("Found pokemon ${catchablePokemon.pokemonId}; blacklisting because it's unwanted") ctx.pauseWalking.set(false) return } Log.green("Found pokemon ${catchablePokemon.pokemonId}") ctx.api.setLocation(ctx.lat.get(), ctx.lng.get(), getAltitude(ctx.lat.get(), ctx.lng.get(), ctx)) val encounter = catchablePokemon.encounter() val encounterResult = encounter.toBlocking().first().response val wasFromLure = catchablePokemon.encounterKind == MapPokemon.EncounterKind.DISK if ((encounterResult is DiskEncounterResponseOuterClass.DiskEncounterResponse && encounterResult.result == DiskEncounterResponseOuterClass.DiskEncounterResponse.Result.SUCCESS) || (encounterResult is EncounterResponseOuterClass.EncounterResponse && encounterResult.status == Status.ENCOUNTER_SUCCESS)) { val pokemonData = if (encounterResult is DiskEncounterResponseOuterClass.DiskEncounterResponse) { encounterResult.pokemonData } else if (encounterResult is EncounterResponseOuterClass.EncounterResponse) { encounterResult.wildPokemon.pokemonData } else { // TODO ugly null }!! Log.green("Encountered pokemon ${catchablePokemon.pokemonId} " + "with CP ${pokemonData.cp} and IV ${pokemonData.getIvPercentage()}%") // TODO wrong parameters val (shouldRelease, reason) = pokemonData.shouldTransfer(settings, hashMapOf<String, Int>(), AtomicInteger(0)) val desiredCatchProbability = if (shouldRelease) { Log.yellow("Using desired_catch_probability_unwanted because $reason") settings.desiredCatchProbabilityUnwanted } else { settings.desiredCatchProbability } if (desiredCatchProbability == -1.0) { ctx.blacklistedEncounters.add(catchablePokemon.encounterId) Log.normal("CP/IV of encountered pokemon ${catchablePokemon.pokemonId} turns out to be too low; blacklisting encounter") ctx.pauseWalking.set(false) return } val isBallCurved = (Math.random() < settings.desiredCurveRate) val captureProbability = if (encounterResult is DiskEncounterResponseOuterClass.DiskEncounterResponse) { encounterResult.captureProbability } else if (encounterResult is EncounterResponseOuterClass.EncounterResponse) { encounterResult.captureProbability } else { // TODO ugly null }!! // TODO: Give settings object to the catch function instead of the seperate values val catch = catchablePokemon.catch( captureProbability, ctx.api.inventory, desiredCatchProbability, isBallCurved, !settings.neverUseBerries, settings.randomBallThrows, settings.waitBetweenThrows, -1) val catchResult = catch.toBlocking().first() if (catchResult == null) { // prevent trying it in the next iteration ctx.blacklistedEncounters.add(catchablePokemon.encounterId) Log.red("No Pokeballs in your inventory; blacklisting Pokemon") ctx.pauseWalking.set(false) return } val result = catchResult.response // TODO: temp fix for server timing issues regarding GetMapObjects ctx.blacklistedEncounters.add(catchablePokemon.encounterId) if (result.status == CatchPokemonResponse.CatchStatus.CATCH_SUCCESS) { ctx.pokemonStats.first.andIncrement if (wasFromLure) { ctx.luredPokemonStats.andIncrement } var message = "Caught a " if (settings.displayIfPokemonFromLure) { if (wasFromLure) message += "lured " else message += "wild " } message += "${catchablePokemon.pokemonId} with CP ${pokemonData.cp} and IV" + " (${pokemonData.individualAttack}-${pokemonData.individualDefense}-${pokemonData.individualStamina}) ${pokemonData.getIvPercentage()}%" if (settings.displayPokemonCatchRewards) { message += ": [${result.captureAward.xpList.sum()}x XP, ${result.captureAward.candyList.sum()}x " + "Candy, ${result.captureAward.stardustList.sum()}x Stardust]" } Log.cyan(message) ctx.server.newPokemon(catchablePokemon.latitude, catchablePokemon.longitude, pokemonData) ctx.server.sendProfile() } else { Log.red("Capture of ${catchablePokemon.pokemonId} failed with status : ${result.status}") if (result.status == CatchPokemonResponse.CatchStatus.CATCH_ERROR) { Log.red("Blacklisting pokemon to prevent infinite loop") } } } else { if (encounterResult is DiskEncounterResponseOuterClass.DiskEncounterResponse) { Log.red("Encounter failed with result: ${encounterResult.result}") if (encounterResult.result == DiskEncounterResponseOuterClass.DiskEncounterResponse.Result.ENCOUNTER_ALREADY_FINISHED) { ctx.blacklistedEncounters.add(catchablePokemon.encounterId) } } else if (encounterResult is EncounterResponseOuterClass.EncounterResponse) { Log.red("Encounter failed with result: ${encounterResult.status}") if (encounterResult.status == Status.ENCOUNTER_CLOSED) { ctx.blacklistedEncounters.add(catchablePokemon.encounterId) } } if ((encounterResult is DiskEncounterResponseOuterClass.DiskEncounterResponse && encounterResult.result == DiskEncounterResponseOuterClass.DiskEncounterResponse.Result.POKEMON_INVENTORY_FULL) || (encounterResult is EncounterResponseOuterClass.EncounterResponse && encounterResult.status == Status.POKEMON_INVENTORY_FULL)) { Log.red("Inventory is full, temporarily disabling catching of pokemon") ctx.pokemonInventoryFullStatus.set(true) } } ctx.pauseWalking.set(false) } } }
src/main/kotlin/ink/abb/pogo/scraper/tasks/CatchOneNearbyPokemon.kt
1306638849
package com.egenvall.namestats.network import com.egenvall.namestats.model.NameInfo import rx.Observable interface Repository { fun getDetails(name: String): Observable<NameInfo> }
NameStats/app/src/main/java/com/egenvall/namestats/network/Repository.kt
447274327
/* * The MIT License (MIT) * * Copyright (c) 2016 yuriel<[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package dev.yuriel.mahjan.group import dev.yuriel.mahjan.actor.OppoTilePlaceHolderActor /** * Created by yuriel on 8/8/16. */ class OpposideGroup: TileGroup<OppoTilePlaceHolderActor>() { override fun getOrigin(): Pair<Float, Float> = Pair(0F, 0F) override fun factory(position: Int, isTsumo: Boolean) = OppoTilePlaceHolderActor(position, isTsumo) }
app/src/main/java/dev/yuriel/mahjan/group/OpposideGroup.kt
1089994444
package net.dean.jraw.meta import java.io.File object ReadmeBadgeUpdater { fun update(overview: EndpointOverview, readme: File): Boolean { var replaced = false readme.writeText(readme.readLines().joinToString("\n") { if (it.startsWith("[![API coverage]")) { replaced = true url(overview.completionPercentage(decimals = 0)) } else { it } } + '\n') // add a newline at the end of the file return replaced } private fun url(percent: String) = "[![API coverage](https://img.shields.io/badge/API_coverage-$percent%25-9C27B0.svg)]" + "(https://github.com/thatJavaNerd/JRAW/blob/master/ENDPOINTS.md)" }
meta/src/main/kotlin/net/dean/jraw/meta/ReadmeBadgeUpdater.kt
1290663732
package app.cash.sqldelight.core.lang.psi import app.cash.sqldelight.core.lang.SqlDelightQueriesFile import app.cash.sqldelight.core.psi.SqlDelightStmtIdentifier import app.cash.sqldelight.core.psi.SqlDelightStmtIdentifierClojure import com.alecstrong.sql.psi.core.SqlAnnotationHolder import com.alecstrong.sql.psi.core.SqlParser import com.alecstrong.sql.psi.core.SqlParserDefinition import com.alecstrong.sql.psi.core.psi.SqlAnnotatedElement import com.alecstrong.sql.psi.core.psi.SqlIdentifier import com.alecstrong.sql.psi.core.psi.SqlTypes import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.lang.LanguageParserDefinitions import com.intellij.lang.PsiBuilderFactory import com.intellij.lang.parser.GeneratedParserUtilBase import com.intellij.psi.PsiElement import com.intellij.psi.impl.GeneratedMarkerVisitor import com.intellij.psi.impl.source.tree.TreeElement abstract class StmtIdentifierMixin( node: ASTNode, ) : ASTWrapperPsiElement(node), SqlDelightStmtIdentifier, SqlDelightStmtIdentifierClojure, SqlAnnotatedElement { override fun getName() = identifier()?.text override fun setName(name: String): PsiElement { val parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(language) as SqlParserDefinition var builder = PsiBuilderFactory.getInstance().createBuilder( project, node, parserDefinition.createLexer(project), language, name, ) builder = GeneratedParserUtilBase.adapt_builder_( SqlTypes.IDENTIFIER, builder, SqlParser(), SqlParser.EXTENDS_SETS_, ) GeneratedParserUtilBase.ErrorState.get(builder).currentFrame = GeneratedParserUtilBase.Frame() SqlParser.identifier_real(builder, 0) val element = builder.treeBuilt (element as TreeElement).acceptTree(GeneratedMarkerVisitor()) node.replaceChild(identifier()!!.node, element) return this } override fun annotate(annotationHolder: SqlAnnotationHolder) { if (name != null && (containingFile as SqlDelightQueriesFile).sqlStatements() .filterNot { it.identifier == this } .any { it.identifier.name == name } ) { annotationHolder.createErrorAnnotation(this, "Duplicate SQL identifier") } } override fun identifier() = children.filterIsInstance<SqlIdentifier>().singleOrNull() }
sqldelight-compiler/src/main/kotlin/app/cash/sqldelight/core/lang/psi/StmtIdentifierMixin.kt
1935177265
package tornadofx import javafx.geometry.Point2D import javafx.geometry.Point3D typealias Vector2D = Point2D fun Point2D(value: Double): Point2D = Point2D(value, value) fun Vector2D(value: Double): Vector2D = Vector2D(value, value) operator fun Point2D.plus(other: Point2D): Point2D = this.add(other) operator fun Point2D.plus(value: Double): Point2D = this.add(value, value) operator fun Double.plus(point: Point2D): Point2D = point.add(this, this) operator fun Point2D.minus(other: Point2D): Point2D = this.subtract(other) operator fun Point2D.minus(value: Double): Point2D = this.subtract(value, value) operator fun Point2D.times(factor: Double): Point2D = this.multiply(factor) operator fun Double.times(point: Point2D): Point2D = point.multiply(this) operator fun Point2D.div(divisor: Double): Point2D = this.multiply(1.0 / divisor) operator fun Point2D.unaryMinus(): Point2D = this.multiply(-1.0) infix fun Point2D.dot(other: Point2D): Double = this.dotProduct(other) infix fun Point2D.cross(other: Point2D): Point3D = this.crossProduct(other) infix fun Point2D.angle(other: Point2D): Double = this.angle(other) infix fun Point2D.distance(other: Point2D): Double = this.distance(other) infix fun Point2D.midPoint(other: Point2D): Point2D = this.midpoint(other) /** * Returns the squared length of the vector/point. */ fun Point2D.magnitude2(): Double = this.x * this.x + this.y * this.y typealias Vector3D = Point3D fun Point3D(value: Double): Point3D = Point3D(value, value, value) fun Point3D(point: Point2D, z: Double): Point3D = Point3D(point.x, point.y, z) fun Point3D(x: Double, point: Point2D): Point3D = Point3D(x, point.x, point.y) fun Vector3D(value: Double): Vector3D = Vector3D(value, value, value) fun Vector3D(point: Point2D, z: Double): Vector3D = Vector3D(point.x, point.y, z) fun Vector3D(x: Double, point: Point2D): Vector3D = Vector3D(x, point.x, point.y) operator fun Point3D.plus(other: Point3D): Point3D = this.add(other) operator fun Point3D.plus(value: Double): Point3D = this.add(value, value, value) operator fun Double.plus(point: Point3D): Point3D = point.add(this, this, this) operator fun Point3D.minus(other: Point3D): Point3D = this.subtract(other) operator fun Point3D.minus(value: Double): Point3D = this.subtract(value, value, value) operator fun Point3D.times(factor: Double): Point3D = this.multiply(factor) operator fun Double.times(point: Point3D): Point3D = point.multiply(this) operator fun Point3D.div(divisor: Double): Point3D = this.multiply(1.0 / divisor) operator fun Point3D.unaryMinus(): Point3D = this.multiply(-1.0) infix fun Point3D.dot(other: Point3D): Double = this.dotProduct(other) infix fun Point3D.cross(other: Point3D): Point3D = this.crossProduct(other) infix fun Point3D.angle(other: Point3D): Double = this.angle(other) infix fun Point3D.distance(other: Point3D): Double = this.distance(other) infix fun Point3D.midPoint(other: Point3D): Point3D = this.midpoint(other) /** * Returns the squared length of the vector/point. */ fun Point3D.magnitude2(): Double = this.x * this.x + this.y * this.y + this.z * this.z // All them swizzles... :P val Point2D.xx: Point2D get() = Point2D(this.x, this.x) val Point2D.xy: Point2D get() = Point2D(this.x, this.y) val Point2D.yx: Point2D get() = Point2D(this.y, this.x) val Point2D.yy: Point2D get() = Point2D(this.y, this.y) val Point2D.xxx: Point3D get() = Point3D(this.x, this.x, this.x) val Point2D.xxy: Point3D get() = Point3D(this.x, this.x, this.y) val Point2D.xyx: Point3D get() = Point3D(this.x, this.y, this.x) val Point2D.xyy: Point3D get() = Point3D(this.x, this.y, this.y) val Point2D.yxx: Point3D get() = Point3D(this.y, this.x, this.x) val Point2D.yxy: Point3D get() = Point3D(this.y, this.x, this.y) val Point2D.yyx: Point3D get() = Point3D(this.y, this.y, this.x) val Point2D.yyy: Point3D get() = Point3D(this.y, this.y, this.y) val Point3D.xx: Point2D get() = Point2D(this.x, this.x) val Point3D.yx: Point2D get() = Point2D(this.y, this.x) val Point3D.zx: Point2D get() = Point2D(this.z, this.x) val Point3D.xy: Point2D get() = Point2D(this.x, this.y) val Point3D.yy: Point2D get() = Point2D(this.y, this.y) val Point3D.zy: Point2D get() = Point2D(this.z, this.y) val Point3D.xz: Point2D get() = Point2D(this.x, this.z) val Point3D.yz: Point2D get() = Point2D(this.y, this.z) val Point3D.zz: Point2D get() = Point2D(this.z, this.z) val Point3D.xxx: Point3D get() = Point3D(this.x, this.x, this.x) val Point3D.yxx: Point3D get() = Point3D(this.y, this.x, this.x) val Point3D.zxx: Point3D get() = Point3D(this.z, this.x, this.x) val Point3D.xyx: Point3D get() = Point3D(this.x, this.y, this.x) val Point3D.yyx: Point3D get() = Point3D(this.y, this.y, this.x) val Point3D.zyx: Point3D get() = Point3D(this.z, this.y, this.x) val Point3D.xzx: Point3D get() = Point3D(this.x, this.z, this.x) val Point3D.yzx: Point3D get() = Point3D(this.y, this.z, this.x) val Point3D.zzx: Point3D get() = Point3D(this.z, this.z, this.x) val Point3D.xxy: Point3D get() = Point3D(this.x, this.x, this.y) val Point3D.yxy: Point3D get() = Point3D(this.y, this.x, this.y) val Point3D.zxy: Point3D get() = Point3D(this.z, this.x, this.y) val Point3D.xyy: Point3D get() = Point3D(this.x, this.y, this.y) val Point3D.yyy: Point3D get() = Point3D(this.y, this.y, this.y) val Point3D.zyy: Point3D get() = Point3D(this.z, this.y, this.y) val Point3D.xzy: Point3D get() = Point3D(this.x, this.z, this.y) val Point3D.yzy: Point3D get() = Point3D(this.y, this.z, this.y) val Point3D.zzy: Point3D get() = Point3D(this.z, this.z, this.y) val Point3D.xxz: Point3D get() = Point3D(this.x, this.x, this.z) val Point3D.yxz: Point3D get() = Point3D(this.y, this.x, this.z) val Point3D.zxz: Point3D get() = Point3D(this.z, this.x, this.z) val Point3D.xyz: Point3D get() = Point3D(this.x, this.y, this.z) val Point3D.yyz: Point3D get() = Point3D(this.y, this.y, this.z) val Point3D.zyz: Point3D get() = Point3D(this.z, this.y, this.z) val Point3D.xzz: Point3D get() = Point3D(this.x, this.z, this.z) val Point3D.yzz: Point3D get() = Point3D(this.y, this.z, this.z) val Point3D.zzz: Point3D get() = Point3D(this.z, this.z, this.z)
src/main/java/tornadofx/VectorMath.kt
612137085
package com.pennapps.labs.pennmobile.classes import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName class GSRBookingResult { @SerializedName("results") @Expose private val results: Boolean? = null @SerializedName("detail") @Expose private val detail: String? = null @SerializedName("error") @Expose private val error: String? = null fun getDetail(): String? { return detail } fun getResults(): Boolean? { return results } fun getError(): String? { return error } }
PennMobile/src/main/java/com/pennapps/labs/pennmobile/classes/GSRBookingResult.kt
2145942268
/* * 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.sample.ui.photo.pexels import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.GridItemSpan import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.rememberLazyGridState import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.unit.dp import androidx.paging.LoadState import androidx.paging.PagingData import androidx.paging.compose.collectAsLazyPagingItems import com.github.panpf.sketch.request.DisplayRequest import com.github.panpf.sketch.request.PauseLoadWhenScrollingDrawableDecodeInterceptor import com.github.panpf.sketch.sample.R import com.github.panpf.sketch.sample.R.color import com.github.panpf.sketch.sample.R.drawable import com.github.panpf.sketch.sample.image.ImageType.LIST import com.github.panpf.sketch.sample.image.setApplySettings import com.github.panpf.sketch.sample.model.Photo import com.github.panpf.sketch.sample.ui.common.compose.AppendState import com.github.panpf.sketch.stateimage.IconStateImage import com.github.panpf.sketch.stateimage.ResColor import com.github.panpf.sketch.stateimage.saveCellularTrafficError import com.github.panpf.tools4a.toast.ktx.showLongToast import com.google.accompanist.swiperefresh.SwipeRefresh import com.google.accompanist.swiperefresh.SwipeRefreshState import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.launch @Composable fun PhotoListContent( photoPagingFlow: Flow<PagingData<Photo>>, restartImageFlow: Flow<Any>, reloadFlow: Flow<Any>, onClick: (items: List<Photo>, photo: Photo, index: Int) -> Unit ) { val lazyPagingItems = photoPagingFlow.collectAsLazyPagingItems() val scope = rememberCoroutineScope() LaunchedEffect(key1 = reloadFlow) { scope.launch { reloadFlow.collect { lazyPagingItems.refresh() } } } val context = LocalContext.current LaunchedEffect(key1 = reloadFlow) { scope.launch { restartImageFlow.collect { // todo Look for ways to actively discard the old state redraw, and then listen for restartImageFlow to perform the redraw context.showLongToast("You need to scroll through the list manually to see the changes") } } } SwipeRefresh( state = SwipeRefreshState(lazyPagingItems.loadState.refresh is LoadState.Loading), onRefresh = { lazyPagingItems.refresh() } ) { val lazyGridState = rememberLazyGridState() if (lazyGridState.isScrollInProgress) { DisposableEffect(Unit) { PauseLoadWhenScrollingDrawableDecodeInterceptor.scrolling = true onDispose { PauseLoadWhenScrollingDrawableDecodeInterceptor.scrolling = false } } } LazyVerticalGrid( columns = GridCells.Adaptive(minSize = 100.dp), state = lazyGridState, contentPadding = PaddingValues(dimensionResource(id = R.dimen.grid_divider)), horizontalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.grid_divider)), verticalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.grid_divider)), ) { items( count = lazyPagingItems.itemCount, key = { lazyPagingItems.peek(it)?.diffKey ?: "" }, contentType = { 1 } ) { index -> val item = lazyPagingItems[index] item?.let { PhotoContent(index, it) { photo, index -> onClick(lazyPagingItems.itemSnapshotList.items, photo, index) } } } if (lazyPagingItems.itemCount > 0) { item( key = "AppendState", span = { GridItemSpan(this.maxLineSpan) }, contentType = 2 ) { AppendState(lazyPagingItems.loadState.append) { lazyPagingItems.retry() } } } } } } @Composable fun PhotoContent( index: Int, photo: Photo, onClick: (photo: Photo, index: Int) -> Unit ) { val modifier = Modifier .fillMaxWidth() .aspectRatio(1f) .clickable { onClick(photo, index) } val configBlock: (DisplayRequest.Builder.() -> Unit) = { setApplySettings(LIST) placeholder(IconStateImage(drawable.ic_image_outline, ResColor(color.placeholder_bg))) error(IconStateImage(drawable.ic_error, ResColor(color.placeholder_bg))) { saveCellularTrafficError( IconStateImage(drawable.ic_signal_cellular, ResColor(color.placeholder_bg)) ) } crossfade() resizeApplyToDrawable() } when (index % 3) { 0 -> { com.github.panpf.sketch.compose.AsyncImage( imageUri = photo.listThumbnailUrl, modifier = modifier, contentScale = ContentScale.Crop, contentDescription = "", configBlock = configBlock ) } 1 -> { com.github.panpf.sketch.compose.SubcomposeAsyncImage( imageUri = photo.listThumbnailUrl, modifier = modifier, contentScale = ContentScale.Crop, contentDescription = "", configBlock = configBlock ) } else -> { Image( painter = com.github.panpf.sketch.compose.rememberAsyncImagePainter( imageUri = photo.listThumbnailUrl, configBlock = configBlock ), modifier = modifier, contentScale = ContentScale.Crop, contentDescription = "" ) } } }
sample/src/main/java/com/github/panpf/sketch/sample/ui/photo/pexels/PhotoList.kt
1540713864
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * 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 de.vanita5.twittnuker.extension.text.twitter import android.support.test.InstrumentationRegistry import android.support.test.runner.AndroidJUnit4 import com.twitter.Extractor import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import de.vanita5.twittnuker.model.ParcelableStatus import de.vanita5.twittnuker.model.ParcelableUserMention import de.vanita5.twittnuker.test.R import de.vanita5.twittnuker.util.JsonSerializer @RunWith(AndroidJUnit4::class) class ExtractorExtensionsTest { private val extractor = Extractor() private lateinit var inReplyTo: ParcelableStatus @Before fun setUp() { val context = InstrumentationRegistry.getContext() // This is a tweet by @t_deyarmin, mentioning @nixcraft inReplyTo = context.resources.openRawResource(R.raw.parcelable_status_848051071444410368).use { JsonSerializer.parse(it, ParcelableStatus::class.java) } } @Test fun testExtractReplyTextAndMentionsReplyToAll() { // This reply to all users, which is the normal case extractor.extractReplyTextAndMentions("@t_deyarmin @nixcraft @mariotaku lol", inReplyTo).let { Assert.assertEquals("lol", it.replyText) Assert.assertTrue("extraMentions.isEmpty()", it.extraMentions.isEmpty()) Assert.assertTrue("excludedMentions.isEmpty()", it.excludedMentions.isEmpty()) Assert.assertTrue("replyToOriginalUser", it.replyToOriginalUser) } } @Test fun testExtractReplyTextAndMentionsReplyToAllExtraMentions() { // This reply to all users, which is the normal case extractor.extractReplyTextAndMentions("@t_deyarmin @nixcraft @mariotaku @TwidereProject lol", inReplyTo).let { Assert.assertEquals("@TwidereProject lol", it.replyText) Assert.assertTrue("extraMentions.containsAll(TwidereProject)", it.extraMentions.entitiesContainsAll("TwidereProject")) Assert.assertTrue("excludedMentions.isEmpty()", it.excludedMentions.isEmpty()) Assert.assertTrue("replyToOriginalUser", it.replyToOriginalUser) } } @Test fun testExtractReplyTextAndMentionsReplyToAllSuffixMentions() { // This reply to all users, which is the normal case extractor.extractReplyTextAndMentions("@t_deyarmin @nixcraft @mariotaku lol @TwidereProject", inReplyTo).let { Assert.assertEquals("lol @TwidereProject", it.replyText) Assert.assertTrue("extraMentions.containsAll(TwidereProject)", it.extraMentions.entitiesContainsAll("TwidereProject")) Assert.assertTrue("excludedMentions.isEmpty()", it.excludedMentions.isEmpty()) Assert.assertTrue("replyToOriginalUser", it.replyToOriginalUser) } } @Test fun testExtractReplyTextAndMentionsAuthorOnly() { // This reply removed @nixcraft and replying to author only extractor.extractReplyTextAndMentions("@t_deyarmin lol", inReplyTo).let { Assert.assertEquals("lol", it.replyText) Assert.assertTrue("extraMentions.isEmpty()", it.extraMentions.isEmpty()) Assert.assertTrue("excludedMentions.containsAll(nixcraft, mariotaku)", it.excludedMentions.mentionsContainsAll("nixcraft", "mariotaku")) Assert.assertTrue("replyToOriginalUser", it.replyToOriginalUser) } } @Test fun testExtractReplyTextAndMentionsAuthorOnlyExtraMentions() { // This reply removed @nixcraft and replying to author only extractor.extractReplyTextAndMentions("@t_deyarmin @TwidereProject lol", inReplyTo).let { Assert.assertEquals("@TwidereProject lol", it.replyText) Assert.assertTrue("extraMentions.containsAll(TwidereProject)", it.extraMentions.entitiesContainsAll("TwidereProject")) Assert.assertTrue("excludedMentions.containsAll(nixcraft, mariotaku)", it.excludedMentions.mentionsContainsAll("nixcraft", "mariotaku")) Assert.assertTrue("replyToOriginalUser", it.replyToOriginalUser) } } @Test fun testExtractReplyTextAndMentionsAuthorOnlySuffixMention() { // This reply removed @nixcraft and replying to author only extractor.extractReplyTextAndMentions("@t_deyarmin lol @TwidereProject", inReplyTo).let { Assert.assertEquals("lol @TwidereProject", it.replyText) Assert.assertTrue("extraMentions.containsAll(TwidereProject)", it.extraMentions.entitiesContainsAll("TwidereProject")) Assert.assertTrue("excludedMentions.containsAll(nixcraft, mariotaku)", it.excludedMentions.mentionsContainsAll("nixcraft", "mariotaku")) Assert.assertTrue("replyToOriginalUser", it.replyToOriginalUser) } } @Test fun testExtractReplyTextAndMentionsNoAuthor() { // This reply removed author @t_deyarmin extractor.extractReplyTextAndMentions("@nixcraft lol", inReplyTo).let { Assert.assertEquals("@nixcraft lol", it.replyText) Assert.assertTrue("extraMentions.isEmpty()", it.extraMentions.isEmpty()) Assert.assertTrue("excludedMentions.isEmpty()", it.excludedMentions.isEmpty()) Assert.assertFalse("replyToOriginalUser", it.replyToOriginalUser) } } @Test fun testExtractReplyTextAndMentionsNoAuthorExtraMentions() { // This reply removed author @t_deyarmin extractor.extractReplyTextAndMentions("@nixcraft @TwidereProject lol", inReplyTo).let { Assert.assertEquals("@nixcraft @TwidereProject lol", it.replyText) Assert.assertTrue("extraMentions.containsAll(TwidereProject)", it.extraMentions.entitiesContainsAll("TwidereProject")) Assert.assertTrue("excludedMentions.isEmpty()", it.excludedMentions.isEmpty()) Assert.assertFalse("replyToOriginalUser", it.replyToOriginalUser) } } @Test fun testExtractReplyTextAndMentionsNoAuthorTextOnly() { // This reply removed author @t_deyarmin extractor.extractReplyTextAndMentions("lol", inReplyTo).let { Assert.assertEquals("lol", it.replyText) Assert.assertTrue("extraMentions.isEmpty()", it.extraMentions.isEmpty()) Assert.assertTrue("excludedMentions.isEmpty()", it.excludedMentions.isEmpty()) Assert.assertFalse("replyToOriginalUser", it.replyToOriginalUser) } } @Test fun testExtractReplyTextAndMentionsNoAuthorEmptyText() { // This reply removed author @t_deyarmin extractor.extractReplyTextAndMentions("", inReplyTo).let { Assert.assertEquals("", it.replyText) Assert.assertTrue("extraMentions.isEmpty()", it.extraMentions.isEmpty()) Assert.assertTrue("excludedMentions.isEmpty()", it.excludedMentions.isEmpty()) Assert.assertFalse("replyToOriginalUser", it.replyToOriginalUser) } } private fun List<Extractor.Entity>.entitiesContainsAll(vararg screenNames: String): Boolean { return all { entity -> screenNames.any { expectation -> expectation.equals(entity.value, ignoreCase = true) } } } private fun List<ParcelableUserMention>.mentionsContainsAll(vararg screenNames: String): Boolean { return all { mention -> screenNames.any { expectation -> expectation.equals(mention.screen_name, ignoreCase = true) } } } }
twittnuker/src/androidTest/kotlin/de/vanita5/twittnuker/extension/text/twitter/ExtractorExtensionsTest.kt
3187218392
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * 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 de.vanita5.twittnuker.util import android.content.Context import android.content.SharedPreferences import android.net.Uri import android.os.Bundle import android.support.v4.app.FragmentActivity import org.mariotaku.kpreferences.get import de.vanita5.twittnuker.constant.IntentConstants.EXTRA_URI import de.vanita5.twittnuker.constant.phishingLinksWaringKey import de.vanita5.twittnuker.fragment.PhishingLinkWarningDialogFragment import de.vanita5.twittnuker.model.UserKey class DirectMessageOnLinkClickHandler( context: Context, manager: MultiSelectManager?, preferences: SharedPreferences ) : OnLinkClickHandler(context, manager, preferences) { override fun openLink(accountKey: UserKey?, link: String) { if (manager != null && manager.isActive) return if (!hasShortenedLinks(link)) { super.openLink(accountKey, link) return } if (context is FragmentActivity && preferences[phishingLinksWaringKey]) { val fm = context.supportFragmentManager val fragment = PhishingLinkWarningDialogFragment() val args = Bundle() args.putParcelable(EXTRA_URI, Uri.parse(link)) fragment.arguments = args fragment.show(fm, "phishing_link_warning") } else { super.openLink(accountKey, link) } } private fun hasShortenedLinks(link: String): Boolean { for (shortLinkService in SHORT_LINK_SERVICES) { if (link.contains(shortLinkService)) return true } return false } companion object { private val SHORT_LINK_SERVICES = arrayOf("bit.ly", "ow.ly", "tinyurl.com", "goo.gl", "k6.kz", "is.gd", "tr.im", "x.co", "weepp.ru") } }
twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/DirectMessageOnLinkClickHandler.kt
3431356601
/** * 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 net.cleverdesk.cleverdesk import net.cleverdesk.cleverdesk.database.DatabaseObject import net.cleverdesk.cleverdesk.plugin.Page import net.cleverdesk.cleverdesk.plugin.Plugin import net.cleverdesk.cleverdesk.plugin.Response import net.cleverdesk.cleverdesk.ui.Alert import net.cleverdesk.cleverdesk.ui.UI import net.cleverdesk.cleverdesk.ui.form.InputField /** * Created by schulerlabor on 22.06.16. */ public open class Configuration(override val plugin: Plugin, override val name: String) : DatabaseObject(), Page { public fun refreshContent() { plugin.database?.download(this, this) plugin.database?.upload(this) } @Database public var content: MutableMap<String, String?> = mutableMapOf() @Database public var identifer: String = name override val indices: Map<String, Any?>? get() = mutableMapOf(Pair("identifer", identifer)) override fun response(user: User?, request: UIRequest): Response { if (request.attributes.size > 0) { refreshContent() content.putAll(request.attributes as Map<out String, String?>) plugin.database?.upload(this) refreshContent() return Alert("Saved") } refreshContent() val ui = UI() for (key in content.keys) { val field = InputField() field.label = key field.value = content.get(key) field.identifer = key ui.addComponent(field) } return ui } }
src/main/java/net/cleverdesk/cleverdesk/Configuration.kt
2464855010
package com.stripe.android internal object ApiKeyFixtures { const val FAKE_PUBLISHABLE_KEY = "pk_test_123" const val DEFAULT_PUBLISHABLE_KEY = "pk_test_vOo1umqsYxSrP5UXfOeL3ecm" const val CONNECTED_ACCOUNT_PUBLISHABLE_KEY = "pk_test_fdjfCYpGSwAX24KUEiuaAAWX" const val FAKE_EPHEMERAL_KEY = "ek_test_123" const val FAKE_SECRET_KEY = "sk_test_123" const val FPX_PUBLISHABLE_KEY = "pk_test_gQDRnExb8Jjs2Dk6RiQ09RSg007c7pKhDT" const val AU_BECS_DEBIT_PUBLISHABLE_KEY = "pk_test_Bfx5IwoTeK7kUbfS15dcgTrs00beFpWwto" const val KLARNA_PUBLISHABLE_KEY = "pk_test_8JUGw3jTOFqWQOt5nr2pjzF9" const val BACS_PUBLISHABLE_KEY = "pk_test_z6Ct4bpx0NUjHii0rsi4XZBf00jmM8qA28" const val SOFORT_PUBLISHABLE_KEY = "pk_test_vOo1umqsYxSrP5UXfOeL3ecm" const val P24_PUBLISHABLE_KEY = "pk_test_vOo1umqsYxSrP5UXfOeL3ecm" const val BANCONTACT_PUBLISHABLE_KEY = "pk_test_vOo1umqsYxSrP5UXfOeL3ecm" const val GIROPAY_PUBLISHABLE_KEY = "pk_test_vOo1umqsYxSrP5UXfOeL3ecm" const val EPS_PUBLISHABLE_KEY = "pk_test_vOo1umqsYxSrP5UXfOeL3ecm" const val OXXO_PUBLISHABLE_KEY = "pk_test_bjqpeDIsfh4Bnwok0rtnrS7200PY7PLRfb" const val ALIPAY_PUBLISHABLE_KEY = "pk_test_vOo1umqsYxSrP5UXfOeL3ecm" const val CB_PUBLISHABLE_KEY = "pk_test_51Gsr5VLtxFHECmaoeyWTxRKLZZiks5QKbg5H0IeGd8yt7OzQhA7807thLrHayMOeDRmJv3ara1VYy6AvBXAnUGcB00QAZheC0Z" const val GRABPAY_PUBLISHABLE_KEY = "pk_test_TP0eh0buhedbg787icFUy83H00i9fh4Auj" const val PAYPAL_PUBLISHABLE_KEY = "pk_test_vOo1umqsYxSrP5UXfOeL3ecm" const val AFTERPAY_PUBLISHABLE_KEY = "pk_test_vOo1umqsYxSrP5UXfOeL3ecm" const val UPI_PUBLISHABLE_KEY = "pk_test_51H7wmsBte6TMTRd4gph9Wm7gnQOKJwdVTCj30AhtB8MhWtlYj6v9xDn1vdCtKYGAE7cybr6fQdbQQtgvzBihE9cl00tOnrTpL9" const val NETBANKING_PUBLISHABLE_KEY = "pk_test_51H7wmsBte6TMTRd4gph9Wm7gnQOKJwdVTCj30AhtB8MhWtlYj6v9xDn1vdCtKYGAE7cybr6fQdbQQtgvzBihE9cl00tOnrTpL9" const val BLIK_PUBLISHABLE_KEY = "pk_test_ErsyMEOTudSjQR8hh0VrQr5X008sBXGOu6" const val WECHAT_PAY_PUBLISHABLE_KEY = "pk_test_h0JFD5q63mLThM5JVSbrREmR" }
paymentsheet/src/test/java/com/stripe/android/ApiKeyFixtures.kt
3507394893
package org.softeg.slartus.forpdaplus.domain_qms import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch import ru.softeg.slartus.qms.api.models.QmsCount import org.softeg.slartus.forpdaplus.core.interfaces.Parser import ru.softeg.slartus.qms.api.repositories.QmsCountRepository import ru.softeg.slartus.qms.api.QmsService import org.softeg.slartus.forpdaplus.core_lib.coroutines.AppIOScope import javax.inject.Inject class QmsCountRepositoryImpl @Inject constructor( private val qmsService: QmsService, private val qmsCountParser: Parser<QmsCount> ) : QmsCountRepository { private val _countFlow = MutableStateFlow<Int?>(null) override val countFlow: Flow<Int?> get() = _countFlow.asStateFlow() init { AppIOScope().launch { qmsCountParser.data .drop(1) .distinctUntilChanged() .collect { item -> setCount(item.count ?: 0) } } } override suspend fun load() { qmsService.getQmsCount(qmsCountParser.id) } override suspend fun setCount(count: Int) { _countFlow.emit(count) } }
qms/qms-data/src/main/java/org/softeg/slartus/forpdaplus/domain_qms/QmsCountRepositoryImpl.kt
3954698807
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.window import android.os.Build import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.testutils.assertAgainstGolden import androidx.compose.ui.GOLDEN_UI import androidx.compose.ui.Modifier import androidx.compose.ui.background import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.test.captureToImage import androidx.compose.ui.test.isDialog import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.unit.dp import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import androidx.test.filters.SdkSuppress import androidx.test.screenshot.AndroidXScreenshotTestRule import androidx.test.screenshot.matchers.MSSIMMatcher import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @LargeTest @RunWith(AndroidJUnit4::class) @SdkSuppress(minSdkVersion = Build.VERSION_CODES.O) class DialogScreenshotTest { @get:Rule val rule = createComposeRule() @get:Rule val screenshotRule = AndroidXScreenshotTestRule(GOLDEN_UI) @Test fun dialogWithNoElevation() { rule.setContent { Dialog(onDismissRequest = {}) { Box( Modifier .graphicsLayer(shape = RoundedCornerShape(percent = 15), clip = true) .size(200.dp) .background(Color(0xFFA896B0)) ) } } rule.onNode(isDialog()) .captureToImage() .assertAgainstGolden(screenshotRule, "dialogWithNoElevation") } @Test fun dialogWithElevation() { rule.setContent { Dialog(onDismissRequest = {}) { val elevation = with(LocalDensity.current) { 8.dp.toPx() } Box( Modifier .graphicsLayer( shadowElevation = elevation, shape = RoundedCornerShape(percent = 15), clip = true ) .size(200.dp) .background(Color(0xFFA896B0)) ) } } rule.onNode(isDialog()) .captureToImage() .assertAgainstGolden( screenshotRule, "dialogWithElevation", matcher = MSSIMMatcher(threshold = 0.999) ) } }
compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/window/DialogScreenshotTest.kt
4236036680
package com.mysdk import com.mysdk.PrivacySandboxThrowableParcelConverter import com.mysdk.PrivacySandboxThrowableParcelConverter.toThrowableParcel import com.mysdk.RequestConverter.fromParcelable import com.mysdk.ResponseConverter.toParcelable import kotlin.Array import kotlin.BooleanArray import kotlin.CharArray import kotlin.DoubleArray import kotlin.FloatArray import kotlin.IntArray import kotlin.LongArray import kotlin.String import kotlin.Unit import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch public class MySecondInterfaceStubDelegate internal constructor( public val `delegate`: MySecondInterface, ) : IMySecondInterface.Stub() { public override fun doIntStuff(x: IntArray, transactionCallback: IListIntTransactionCallback): Unit { @OptIn(DelicateCoroutinesApi::class) val job = GlobalScope.launch(Dispatchers.Main) { try { val result = delegate.doIntStuff(x.toList()) transactionCallback.onSuccess(result.toIntArray()) } catch (t: Throwable) { transactionCallback.onFailure(toThrowableParcel(t)) } } val cancellationSignal = TransportCancellationCallback() { job.cancel() } transactionCallback.onCancellable(cancellationSignal) } public override fun doCharStuff(x: CharArray, transactionCallback: IListCharTransactionCallback): Unit { @OptIn(DelicateCoroutinesApi::class) val job = GlobalScope.launch(Dispatchers.Main) { try { val result = delegate.doCharStuff(x.toList()) transactionCallback.onSuccess(result.toCharArray()) } catch (t: Throwable) { transactionCallback.onFailure(toThrowableParcel(t)) } } val cancellationSignal = TransportCancellationCallback() { job.cancel() } transactionCallback.onCancellable(cancellationSignal) } public override fun doFloatStuff(x: FloatArray, transactionCallback: IListFloatTransactionCallback): Unit { @OptIn(DelicateCoroutinesApi::class) val job = GlobalScope.launch(Dispatchers.Main) { try { val result = delegate.doFloatStuff(x.toList()) transactionCallback.onSuccess(result.toFloatArray()) } catch (t: Throwable) { transactionCallback.onFailure(toThrowableParcel(t)) } } val cancellationSignal = TransportCancellationCallback() { job.cancel() } transactionCallback.onCancellable(cancellationSignal) } public override fun doLongStuff(x: LongArray, transactionCallback: IListLongTransactionCallback): Unit { @OptIn(DelicateCoroutinesApi::class) val job = GlobalScope.launch(Dispatchers.Main) { try { val result = delegate.doLongStuff(x.toList()) transactionCallback.onSuccess(result.toLongArray()) } catch (t: Throwable) { transactionCallback.onFailure(toThrowableParcel(t)) } } val cancellationSignal = TransportCancellationCallback() { job.cancel() } transactionCallback.onCancellable(cancellationSignal) } public override fun doDoubleStuff(x: DoubleArray, transactionCallback: IListDoubleTransactionCallback): Unit { @OptIn(DelicateCoroutinesApi::class) val job = GlobalScope.launch(Dispatchers.Main) { try { val result = delegate.doDoubleStuff(x.toList()) transactionCallback.onSuccess(result.toDoubleArray()) } catch (t: Throwable) { transactionCallback.onFailure(toThrowableParcel(t)) } } val cancellationSignal = TransportCancellationCallback() { job.cancel() } transactionCallback.onCancellable(cancellationSignal) } public override fun doBooleanStuff(x: BooleanArray, transactionCallback: IListBooleanTransactionCallback): Unit { @OptIn(DelicateCoroutinesApi::class) val job = GlobalScope.launch(Dispatchers.Main) { try { val result = delegate.doBooleanStuff(x.toList()) transactionCallback.onSuccess(result.toBooleanArray()) } catch (t: Throwable) { transactionCallback.onFailure(toThrowableParcel(t)) } } val cancellationSignal = TransportCancellationCallback() { job.cancel() } transactionCallback.onCancellable(cancellationSignal) } public override fun doShortStuff(x: IntArray, transactionCallback: IListShortTransactionCallback): Unit { @OptIn(DelicateCoroutinesApi::class) val job = GlobalScope.launch(Dispatchers.Main) { try { val result = delegate.doShortStuff(x.map { it.toShort() }.toList()) transactionCallback.onSuccess(result.map { it.toInt() }.toIntArray()) } catch (t: Throwable) { transactionCallback.onFailure(toThrowableParcel(t)) } } val cancellationSignal = TransportCancellationCallback() { job.cancel() } transactionCallback.onCancellable(cancellationSignal) } public override fun doStringStuff(x: Array<String>, transactionCallback: IListStringTransactionCallback): Unit { @OptIn(DelicateCoroutinesApi::class) val job = GlobalScope.launch(Dispatchers.Main) { try { val result = delegate.doStringStuff(x.toList()) transactionCallback.onSuccess(result.toTypedArray()) } catch (t: Throwable) { transactionCallback.onFailure(toThrowableParcel(t)) } } val cancellationSignal = TransportCancellationCallback() { job.cancel() } transactionCallback.onCancellable(cancellationSignal) } public override fun doValueStuff(x: Array<ParcelableRequest>, transactionCallback: IListResponseTransactionCallback): Unit { @OptIn(DelicateCoroutinesApi::class) val job = GlobalScope.launch(Dispatchers.Main) { try { val result = delegate.doValueStuff(x.map { fromParcelable(it) }.toList()) transactionCallback.onSuccess(result.map { toParcelable(it) }.toTypedArray()) } catch (t: Throwable) { transactionCallback.onFailure(toThrowableParcel(t)) } } val cancellationSignal = TransportCancellationCallback() { job.cancel() } transactionCallback.onCancellable(cancellationSignal) } }
privacysandbox/tools/tools-apicompiler/src/test/test-data/fullfeaturedsdk/output/com/mysdk/MySecondInterfaceStubDelegate.kt
1756113578
package com.ridocula.restdroid.models import android.os.Parcel import android.os.Parcelable /** * Created by tbaxter on 6/11/17. */ data class Header( val id: String, val parentId: String, val type: Type, val key: String, val value: String ) : Parcelable { enum class Type { Request { override fun toString() = "Request" }, Response { override fun toString() = "Response" }; abstract override fun toString(): String } constructor(source: Parcel) : this( source.readString(), source.readString(), Type.values()[source.readInt()], source.readString(), source.readString() ) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) { writeString(id) writeString(parentId) writeInt(type.ordinal) writeString(key) writeString(value) } companion object { @JvmField val CREATOR: Parcelable.Creator<Header> = object : Parcelable.Creator<Header> { override fun createFromParcel(source: Parcel): Header = Header(source) override fun newArray(size: Int): Array<Header?> = arrayOfNulls(size) } } }
app/src/main/java/com/ridocula/restdroid/models/Header.kt
187039595
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material3 import androidx.compose.foundation.interaction.InteractionSource import androidx.compose.foundation.interaction.PressInteraction import androidx.compose.ui.geometry.Offset import kotlinx.coroutines.flow.map /** * Adapts an [InteractionSource] from one component to another by mapping any interactions by a * given offset. Namely used for the pill indicator in [NavigationBarItem] and [NavigationRailItem]. */ internal class MappedInteractionSource( underlyingInteractionSource: InteractionSource, private val delta: Offset ) : InteractionSource { private val mappedPresses = mutableMapOf<PressInteraction.Press, PressInteraction.Press>() override val interactions = underlyingInteractionSource.interactions.map { interaction -> when (interaction) { is PressInteraction.Press -> { val mappedPress = mapPress(interaction) mappedPresses[interaction] = mappedPress mappedPress } is PressInteraction.Cancel -> { val mappedPress = mappedPresses.remove(interaction.press) if (mappedPress == null) { interaction } else { PressInteraction.Cancel(mappedPress) } } is PressInteraction.Release -> { val mappedPress = mappedPresses.remove(interaction.press) if (mappedPress == null) { interaction } else { PressInteraction.Release(mappedPress) } } else -> interaction } } private fun mapPress(press: PressInteraction.Press): PressInteraction.Press = PressInteraction.Press(press.pressPosition - delta) }
compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/MappedInteractionSource.kt
841014077
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.compiler.plugins.kotlin.debug import com.sun.jdi.Location import com.sun.jdi.event.LocatableEvent import junit.framework.TestCase fun List<LocatableEvent>.assertTrace(expected: String) { val actual = compressRunsWithoutLinenumber(this) .filter { (!it.location().method().isSynthetic) } .map { it.location().formatAsExpectation() } expected.lines().forEachIndexed { index, expectedLine -> TestCase.assertEquals(expectedLine, actual[index]) } } /* Compresses runs of the same, linenumber-less location in the log: specifically removes locations without linenumber, that would otherwise print as byte offsets. This avoids overspecifying code generation strategy in debug tests. */ fun compressRunsWithoutLinenumber( loggedItems: List<LocatableEvent>, ): List<LocatableEvent> { var current = "" return loggedItems.filter { val location = it.location() val result = location.lineNumber() != -1 || current != location.formatAsExpectation() if (result) current = location.formatAsExpectation() result } } private fun Location.formatAsExpectation(): String { val synthetic = if (method().isSynthetic) " (synthetic)" else "" return "${sourceName()}:${lineNumber()} ${method().name()}$synthetic" }
compose/compiler/compiler-hosted/integration-tests/src/test/java/androidx/compose/compiler/plugins/kotlin/debug/LocatableEventExtensions.kt
2016416726
// Copyright 2015-present 650 Industries. All rights reserved. package host.exp.exponent import host.exp.exponent.analytics.EXL import host.exp.expoview.BuildConfig import java.lang.reflect.Constructor import java.lang.reflect.Field import java.lang.reflect.InvocationTargetException import java.lang.reflect.Method // TODO: add type checking in DEBUG class RNObject { private val className: String // Unversioned private var clazz: Class<*>? = null // Versioned private var instance: Any? = null // Versioned // We ignore the version of clazz constructor(clazz: Class<*>?) { className = removeVersionFromClass(clazz) } constructor(className: String) { this.className = className } private constructor(obj: Any?) { assign(obj) className = removeVersionFromClass(clazz) } val isNull: Boolean get() = instance == null val isNotNull: Boolean get() = instance != null // required for "unversioned" flavor check fun loadVersion(version: String): RNObject { try { clazz = if (version == UNVERSIONED || BuildConfig.FLAVOR == "unversioned") { if (className.startsWith("host.exp.exponent")) { Class.forName("versioned.$className") } else { Class.forName(className) } } else { Class.forName("abi${version.replace('.', '_')}.$className") } } catch (e: ClassNotFoundException) { EXL.e(TAG, e) } return this } fun assign(obj: Any?) { if (obj != null) { clazz = obj.javaClass } instance = obj } fun get(): Any? { return instance } fun rnClass(): Class<*>? { return clazz } fun version(): String { return versionForClassname(clazz!!.name) } fun construct(vararg args: Any?): RNObject { try { instance = getConstructorWithArgumentClassTypes(clazz, *objectsToJavaClassTypes(*args)).newInstance(*args) } catch (e: NoSuchMethodException) { EXL.e(TAG, e) } catch (e: InvocationTargetException) { EXL.e(TAG, e) } catch (e: InstantiationException) { EXL.e(TAG, e) } catch (e: IllegalAccessException) { EXL.e(TAG, e) } return this } fun call(name: String, vararg args: Any?): Any? { return callWithReceiver(instance, name, *args) } fun callRecursive(name: String, vararg args: Any?): RNObject? { val result = call(name, *args) ?: return null return wrap(result) } fun callStatic(name: String, vararg args: Any?): Any? { return callWithReceiver(null, name, *args) } fun callStaticRecursive(name: String, vararg args: Any?): RNObject? { val result = callStatic(name, *args) ?: return null return wrap(result) } fun setField(name: String, value: Any) { setFieldWithReceiver(instance, name, value) } fun setStaticField(name: String, value: Any) { setFieldWithReceiver(null, name, value) } private fun callWithReceiver(receiver: Any?, name: String, vararg args: Any?): Any? { try { return getMethodWithArgumentClassTypes(clazz, name, *objectsToJavaClassTypes(*args)).invoke(receiver, *args) } catch (e: IllegalAccessException) { EXL.e(TAG, e) e.printStackTrace() } catch (e: InvocationTargetException) { EXL.e(TAG, e) e.printStackTrace() } catch (e: NoSuchMethodException) { EXL.e(TAG, e) e.printStackTrace() } catch (e: NoSuchMethodError) { EXL.e(TAG, e) e.printStackTrace() } catch (e: Throwable) { EXL.e(TAG, "Runtime exception in RNObject when calling method $name: $e") } return null } private fun setFieldWithReceiver(receiver: Any?, name: String, value: Any) { try { getFieldWithType(clazz, name, value.javaClass)[receiver] = value } catch (e: IllegalAccessException) { EXL.e(TAG, e) e.printStackTrace() } catch (e: NoSuchFieldException) { EXL.e(TAG, e) e.printStackTrace() } catch (e: NoSuchMethodError) { EXL.e(TAG, e) e.printStackTrace() } catch (e: Throwable) { EXL.e(TAG, "Runtime exception in RNObject when setting field $name: $e") } } fun onHostResume(one: Any?, two: Any?) { call("onHostResume", one, two) } fun onHostPause() { call("onHostPause") } fun onHostDestroy() { call("onHostDestroy") } companion object { private val TAG = RNObject::class.java.simpleName const val UNVERSIONED = "UNVERSIONED" @JvmStatic fun wrap(obj: Any): RNObject { return RNObject(obj) } fun versionedEnum(sdkVersion: String, className: String, value: String): Any { return try { RNObject(className).loadVersion(sdkVersion).rnClass()!!.getDeclaredField(value)[null] } catch (e: IllegalAccessException) { EXL.e(TAG, e) throw IllegalStateException("Unable to create enum: $className.value", e) } catch (e: NoSuchFieldException) { EXL.e(TAG, e) throw IllegalStateException("Unable to create enum: $className.value", e) } } fun versionForClassname(classname: String): String { return if (classname.startsWith("abi")) { val abiVersion = classname.split(".").toTypedArray()[0] abiVersion.substring(3) } else { UNVERSIONED } } private fun removeVersionFromClass(clazz: Class<*>?): String { val name = clazz!!.name return if (name.startsWith("abi")) { name.substring(name.indexOf('.') + 1) } else name } private fun objectsToJavaClassTypes(vararg objects: Any?): Array<Class<*>?> { val classes: Array<Class<*>?> = arrayOfNulls(objects.size) for (i in objects.indices) { if (objects[i] != null) { classes[i] = objects[i]!!::class.java } } return classes } // Allow types that are too specific so that we don't have to specify exact classes @Throws(NoSuchMethodException::class) private fun getMethodWithArgumentClassTypes(clazz: Class<*>?, name: String, vararg argumentClassTypes: Class<*>?): Method { val methods = clazz!!.methods for (i in methods.indices) { val method = methods[i] if (method.name != name) { continue } val currentMethodParameterTypes = method.parameterTypes if (currentMethodParameterTypes.size != argumentClassTypes.size) { continue } var isValid = true for (j in currentMethodParameterTypes.indices) { if (!isAssignableFrom(currentMethodParameterTypes[j], argumentClassTypes[j])) { isValid = false break } } if (!isValid) { continue } return method } throw NoSuchMethodException() } // Allow boxed -> unboxed assignments private fun isAssignableFrom(methodParameterClassType: Class<*>, argumentClassType: Class<*>?): Boolean { if (argumentClassType == null) { // There's not really a good way to handle this. return true } if (methodParameterClassType.isAssignableFrom(argumentClassType)) { return true } if (methodParameterClassType == Boolean::class.javaPrimitiveType && (argumentClassType == java.lang.Boolean::class.java || argumentClassType == Boolean::class.java)) { return true } else if (methodParameterClassType == Byte::class.javaPrimitiveType && (argumentClassType == java.lang.Byte::class.java || argumentClassType == Byte::class.java)) { return true } else if (methodParameterClassType == Char::class.javaPrimitiveType && (argumentClassType == java.lang.Character::class.java || argumentClassType == Char::class.java)) { return true } else if (methodParameterClassType == Float::class.javaPrimitiveType && (argumentClassType == java.lang.Float::class.java || argumentClassType == Float::class.java)) { return true } else if (methodParameterClassType == Int::class.javaPrimitiveType && (argumentClassType == java.lang.Integer::class.java || argumentClassType == Int::class.java)) { return true } else if (methodParameterClassType == Long::class.javaPrimitiveType && (argumentClassType == java.lang.Long::class.java || argumentClassType == Long::class.java)) { return true } else if (methodParameterClassType == Short::class.javaPrimitiveType && (argumentClassType == java.lang.Short::class.java || argumentClassType == Short::class.java)) { return true } else if (methodParameterClassType == Double::class.javaPrimitiveType && (argumentClassType == java.lang.Double::class.java || argumentClassType == Double::class.java)) { return true } return false } // Allow types that are too specific so that we don't have to specify exact classes @Throws(NoSuchMethodException::class) private fun getConstructorWithArgumentClassTypes(clazz: Class<*>?, vararg argumentClassTypes: Class<*>?): Constructor<*> { val constructors = clazz!!.constructors for (i in constructors.indices) { val constructor = constructors[i] val currentConstructorParameterTypes = constructor.parameterTypes if (currentConstructorParameterTypes.size != argumentClassTypes.size) { continue } var isValid = true for (j in currentConstructorParameterTypes.indices) { if (!isAssignableFrom(currentConstructorParameterTypes[j], argumentClassTypes[j])) { isValid = false break } } if (!isValid) { continue } return constructor } throw NoSuchMethodError() } @Throws(NoSuchFieldException::class) private fun getFieldWithType(clazz: Class<*>?, name: String, type: Class<*>): Field { val fields = clazz!!.fields for (i in fields.indices) { val field = fields[i] if (field.name != name) { continue } val currentFieldType = field.type if (isAssignableFrom(currentFieldType, type)) { return field } } throw NoSuchFieldException() } } }
android/expoview/src/main/java/host/exp/exponent/RNObject.kt
24476844
package br.com.wakim.mvp_starter.injection import javax.inject.Scope /** * A scoping annotation to permit dependencies conform to the life of the * [ConfigPersistentComponent] */ @MustBeDocumented @Scope @Retention(AnnotationRetention.RUNTIME) annotation class ConfigPersistent
app/src/main/kotlin/br/com/wakim/mvp_starter/injection/ConfigPersistent.kt
3617416131
package utils enum class Direction { UP, LEFT, RIGHT, DOWN }
src/main/kotlin/utils/Direction.kt
1825289475
package com.gh0u1l5.wechatmagician.util import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.os.Build import android.os.Bundle import android.os.Parcelable import java.io.Serializable object IPCUtil { fun Intent.putExtra(name: String, value: Any): Intent { return when (value) { is Boolean -> putExtra(name, value) is BooleanArray -> putExtra(name, value) is Bundle -> putExtra(name, value) is Byte -> putExtra(name, value) is ByteArray -> putExtra(name, value) is Char -> putExtra(name, value) is CharArray -> putExtra(name, value) is CharSequence -> putExtra(name, value) is Double -> putExtra(name, value) is DoubleArray -> putExtra(name, value) is Float -> putExtra(name ,value) is FloatArray -> putExtra(name, value) is Int -> putExtra(name, value) is IntArray -> putExtra(name, value) is Long -> putExtra(name, value) is LongArray -> putExtra(name, value) is Short -> putExtra(name, value) is ShortArray -> putExtra(name, value) is String -> putExtra(name, value) is Parcelable -> putExtra(name, value) is Serializable -> putExtra(name, value) else -> throw Error("Intent.putExtra(): Unknown type: ${value::class.java}") } } fun Context.getProtectedSharedPreferences(name: String, mode: Int): SharedPreferences { return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { getSharedPreferences(name, mode) } else { createDeviceProtectedStorageContext().getSharedPreferences(name, mode) } } }
app/src/main/kotlin/com/gh0u1l5/wechatmagician/util/IPCUtil.kt
1292847096
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.macros import com.intellij.openapi.Disposable import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.VfsUtil import com.intellij.testFramework.builders.ModuleFixtureBuilder import com.intellij.testFramework.fixtures.impl.TempDirTestFixtureImpl import org.intellij.lang.annotations.Language import org.rust.TestProject import org.rust.cargo.RsWithToolchainTestBase import org.rust.cargo.project.model.cargoProjects import org.rust.fileTree import org.rust.fileTreeFromText import org.rust.lang.core.psi.RsMacroCall import org.rust.lang.core.psi.ext.childrenOfType import org.rust.lang.core.psi.ext.expansion import org.rust.openapiext.fullyRefreshDirectory import org.rust.openapiext.pathAsPath class RsMacroExpansionCachingToolchainTest : RsWithToolchainTestBase() { private val dirFixture = TempDirTestFixtureImpl() private var macroExpansionServiceDisposable: Disposable? = null override val disableMissedCacheAssertions: Boolean get() = false override fun setUp() { dirFixture.setUp() super.setUp() } override fun tearDown() { try { macroExpansionServiceDisposable?.let { Disposer.dispose(it) } } finally { super.tearDown() dirFixture.tearDown() } } override fun tuneFixture(moduleBuilder: ModuleFixtureBuilder<*>) { moduleBuilder.addContentRoot(dirFixture.tempDirPath) } private fun doNothing(): (p: TestProject) -> Unit = {} private fun touchFile(path: String): (p: TestProject) -> Unit = { p -> val file = p.file(path) runWriteAction { VfsUtil.saveText(file, VfsUtil.loadText(file) + " ") } } private fun replaceInFile(path: String, find: String, replace: String): (p: TestProject) -> Unit = { p -> val file = p.file(path) runWriteAction { VfsUtil.saveText(file, VfsUtil.loadText(file).replace(find, replace)) } } private fun List<RsMacroCall>.collectStamps(): Map<String, Long> = associate { val expansion = it.expansion ?: error("failed to expand macro ${it.path.referenceName.orEmpty()}!") it.path.referenceName.orEmpty() to expansion.file.virtualFile.timeStamp } private fun checkReExpanded(action: (p: TestProject) -> Unit, @Language("Rust") code: String, vararg names: String) { val p = fileTree { toml("Cargo.toml", """ [package] name = "hello" version = "0.1.0" authors = [] """) dir("src", fileTreeFromText(code)) }.create(project, dirFixture.getFile(".")!!) attachCargoProjectAndExpandMacros(p, clearCacheBeforeDispose = false) myFixture.openFileInEditor(p.file("src/main.rs")) val oldStamps = myFixture.file.childrenOfType<RsMacroCall>().collectStamps() macroExpansionServiceDisposable?.let { Disposer.dispose(it) } // also save super.tearDown() action(p) fullyRefreshDirectory(p.root) super.setUp() attachCargoProjectAndExpandMacros(p, clearCacheBeforeDispose = true) myFixture.openFileInEditor(p.file("src/main.rs")) val changed = myFixture.file.childrenOfType<RsMacroCall>().collectStamps().entries .filter { oldStamps[it.key] != it.value } .map { it.key } check(changed == names.toList()) { "Expected to re-expand ${names.asList()}, re-expanded $changed instead" } } private fun attachCargoProjectAndExpandMacros(p: TestProject, clearCacheBeforeDispose: Boolean) { macroExpansionServiceDisposable = project.macroExpansionManager.setUnitTestExpansionModeAndDirectory( MacroExpansionScope.WORKSPACE, "mocked", clearCacheBeforeDispose ) check(project.cargoProjects.attachCargoProject(p.file("Cargo.toml").pathAsPath)) } fun `test re-open project without changes`() = checkReExpanded(doNothing(), """ //- main.rs macro_rules! foo { ($ i:ident) => { mod $ i {} } } macro_rules! bar { ($ i:ident) => { mod $ i {} } } foo!(a); bar!(a); """) fun `test touch definition at separate file`() = checkReExpanded(touchFile("src/foo.rs"), """ //- foo.rs macro_rules! foo { ($ i:ident) => { mod $ i {} } } //- bar.rs macro_rules! bar { ($ i:ident) => { mod $ i {} } } //- main.rs #[macro_use] mod foo; #[macro_use] mod bar; foo!(a); bar!(a); """) fun `test touch usage at separate file`() = checkReExpanded(touchFile("src/main.rs"), """ //- def.rs macro_rules! foo { ($ i:ident) => { mod $ i {} } } //- main.rs #[macro_use] mod def; foo!(a); """) fun `test edit usage at same file`() = checkReExpanded(replaceInFile("src/main.rs", "aaa", "aab"), """ //- main.rs macro_rules! foo { ($ i:ident) => { mod $ i {} } } foo!(aaa); """, "foo") fun `test edit usage at separate file`() = checkReExpanded(replaceInFile("src/main.rs", "aaa", "aab"), """ //- def.rs macro_rules! foo { ($ i:ident) => { mod $ i {} } } //- main.rs #[macro_use] mod def; foo!(aaa); """, "foo") fun `test edit definition at same file`() = checkReExpanded(replaceInFile("src/main.rs", "aaa", "aab"), """ //- main.rs macro_rules! foo { ($ i:ident) => { fn $ i() { aaa; } } } foo!(a); """, "foo") fun `test edit definition at separate file`() = checkReExpanded(replaceInFile("src/def.rs", "aaa", "aab"), """ //- def.rs macro_rules! foo { ($ i:ident) => { fn $ i() { aaa; } } } //- main.rs #[macro_use] mod def; foo!(a); """, "foo") }
src/test/kotlin/org/rust/lang/core/macros/RsMacroExpansionCachingToolchainTest.kt
1469882546
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.maps.android.compose.widgets import android.graphics.Point import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.EnterTransition import androidx.compose.animation.ExitTransition import androidx.compose.animation.core.MutableTransitionState import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment.Companion.End import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shadow import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.google.android.gms.maps.model.LatLng import com.google.maps.android.compose.CameraPositionState import com.google.maps.android.ktx.utils.sphericalDistance import kotlinx.coroutines.delay public val DarkGray: Color = Color(0xFF3a3c3b) private val defaultWidth: Dp = 65.dp private val defaultHeight: Dp = 50.dp /** * A scale bar composable that shows the current scale of the map in feet and meters when zoomed in * to the map, changing to miles and kilometers, respectively, when zooming out. * * Implement your own observer on camera move events using [CameraPositionState] and pass it in * as [cameraPositionState]. */ @Composable public fun ScaleBar( modifier: Modifier = Modifier, width: Dp = defaultWidth, height: Dp = defaultHeight, cameraPositionState: CameraPositionState, textColor: Color = DarkGray, lineColor: Color = DarkGray, shadowColor: Color = Color.White, ) { Box( modifier = modifier .size(width = width, height = height) ) { var horizontalLineWidthMeters by remember { mutableStateOf(0) } Canvas( modifier = Modifier.fillMaxSize(), onDraw = { // Get width of canvas in meters val upperLeftLatLng = cameraPositionState.projection?.fromScreenLocation(Point(0, 0)) ?: LatLng(0.0, 0.0) val upperRightLatLng = cameraPositionState.projection?.fromScreenLocation(Point(0, size.width.toInt())) ?: LatLng(0.0, 0.0) val canvasWidthMeters = upperLeftLatLng.sphericalDistance(upperRightLatLng) val eightNinthsCanvasMeters = (canvasWidthMeters * 8 / 9).toInt() horizontalLineWidthMeters = eightNinthsCanvasMeters val oneNinthWidth = size.width / 9 val midHeight = size.height / 2 val oneThirdHeight = size.height / 3 val twoThirdsHeight = size.height * 2 / 3 val strokeWidth = 4f val shadowStrokeWidth = strokeWidth + 3 // Middle horizontal line shadow (drawn under main lines) drawLine( color = shadowColor, start = Offset(oneNinthWidth, midHeight), end = Offset(size.width, midHeight), strokeWidth = shadowStrokeWidth, cap = StrokeCap.Round ) // Top vertical line shadow (drawn under main lines) drawLine( color = shadowColor, start = Offset(oneNinthWidth, oneThirdHeight), end = Offset(oneNinthWidth, midHeight), strokeWidth = shadowStrokeWidth, cap = StrokeCap.Round ) // Bottom vertical line shadow (drawn under main lines) drawLine( color = shadowColor, start = Offset(oneNinthWidth, midHeight), end = Offset(oneNinthWidth, twoThirdsHeight), strokeWidth = shadowStrokeWidth, cap = StrokeCap.Round ) // Middle horizontal line drawLine( color = lineColor, start = Offset(oneNinthWidth, midHeight), end = Offset(size.width, midHeight), strokeWidth = strokeWidth, cap = StrokeCap.Round ) // Top vertical line drawLine( color = lineColor, start = Offset(oneNinthWidth, oneThirdHeight), end = Offset(oneNinthWidth, midHeight), strokeWidth = strokeWidth, cap = StrokeCap.Round ) // Bottom vertical line drawLine( color = lineColor, start = Offset(oneNinthWidth, midHeight), end = Offset(oneNinthWidth, twoThirdsHeight), strokeWidth = strokeWidth, cap = StrokeCap.Round ) } ) Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.SpaceAround ) { var metricUnits = "m" var metricDistance = horizontalLineWidthMeters if (horizontalLineWidthMeters > METERS_IN_KILOMETER) { // Switch from meters to kilometers as unit metricUnits = "km" metricDistance /= METERS_IN_KILOMETER.toInt() } var imperialUnits = "ft" var imperialDistance = horizontalLineWidthMeters.toDouble().toFeet() if (imperialDistance > FEET_IN_MILE) { // Switch from ft to miles as unit imperialUnits = "mi" imperialDistance = imperialDistance.toMiles() } ScaleText( modifier = Modifier.align(End), textColor = textColor, shadowColor = shadowColor, text = "${imperialDistance.toInt()} $imperialUnits" ) ScaleText( modifier = Modifier.align(End), textColor = textColor, shadowColor = shadowColor, text = "$metricDistance $metricUnits" ) } } } /** * An animated scale bar that appears when the zoom level of the map changes, and then disappears * after [visibilityDurationMillis]. This composable wraps [ScaleBar] with visibility animations. * * Implement your own observer on camera move events using [CameraPositionState] and pass it in * as [cameraPositionState]. */ @Composable public fun DisappearingScaleBar( modifier: Modifier = Modifier, width: Dp = defaultWidth, height: Dp = defaultHeight, cameraPositionState: CameraPositionState, textColor: Color = DarkGray, lineColor: Color = DarkGray, shadowColor: Color = Color.White, visibilityDurationMillis: Int = 3_000, enterTransition: EnterTransition = fadeIn(), exitTransition: ExitTransition = fadeOut(), ) { val visible = remember { MutableTransitionState(true) } LaunchedEffect(key1 = cameraPositionState.position.zoom) { // Show ScaleBar visible.targetState = true delay(visibilityDurationMillis.toLong()) // Hide ScaleBar after timeout period visible.targetState = false } AnimatedVisibility( visibleState = visible, modifier = modifier, enter = enterTransition, exit = exitTransition ) { ScaleBar( width = width, height = height, cameraPositionState = cameraPositionState, textColor = textColor, lineColor = lineColor, shadowColor = shadowColor ) } } @Composable private fun ScaleText( modifier: Modifier = Modifier, text: String, textColor: Color = DarkGray, shadowColor: Color = Color.White, ) { Text( text = text, fontSize = 12.sp, color = textColor, textAlign = TextAlign.End, modifier = modifier, style = MaterialTheme.typography.h4.copy( shadow = Shadow( color = shadowColor, offset = Offset(2f, 2f), blurRadius = 1f ) ) ) } /** * Converts [this] value in meters to the corresponding value in feet * @return [this] meters value converted to feet */ internal fun Double.toFeet(): Double { return this * CENTIMETERS_IN_METER / CENTIMETERS_IN_INCH / INCHES_IN_FOOT } /** * Converts [this] value in feet to the corresponding value in miles * @return [this] feet value converted to miles */ internal fun Double.toMiles(): Double { return this / FEET_IN_MILE } private const val CENTIMETERS_IN_METER: Double = 100.0 private const val METERS_IN_KILOMETER: Double = 1000.0 private const val CENTIMETERS_IN_INCH: Double = 2.54 private const val INCHES_IN_FOOT: Double = 12.0 private const val FEET_IN_MILE: Double = 5280.0
maps-compose-widgets/src/main/java/com/google/maps/android/compose/widgets/ScaleBar.kt
2125639120
package me.keegan.snap import android.app.Application import com.parse.Parse class SnapApplication : Application() { override fun onCreate() { super.onCreate() Parse.initialize(Parse.Configuration.Builder(this) .applicationId("APPLICATION_ID") .clientKey("YOUR_CLIENT_KEY") .server("http://localhost:1337/parse/") .build() ) } }
app/src/main/java/me/keegan/snap/SnapApplication.kt
2032139538
/* * Copyright (C) 2016 - 2020 Brian Wernick * * 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.devbrackets.android.recyclerext.adapter import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.ViewHolder import com.devbrackets.android.recyclerext.adapter.header.HeaderApi import com.devbrackets.android.recyclerext.adapter.header.HeaderCore import com.devbrackets.android.recyclerext.adapter.header.HeaderDataGenerator.HeaderData /** * A RecyclerView adapter that adds support for dynamically placing headers in the view. * * @param <H> The Header [ViewHolder] * @param <C> The Child or content [ViewHolder] */ abstract class HeaderListAdapter<T, H : ViewHolder, C : ViewHolder>( items: List<T> = emptyList() ) : ListAdapter<T, ViewHolder>(items), HeaderApi<H, C> { /** * Contains the base processing for the header adapters */ protected lateinit var core: HeaderCore /** * Initializes the non-super components for the Adapter */ protected fun init() { core = HeaderCore(this) } init { init() } /** * Called to display the header information with the `firstChildPosition` being the * position of the first child after this header. * * @param holder The ViewHolder which should be updated * @param firstChildPosition The position of the child immediately after this header */ abstract fun onBindHeaderViewHolder(holder: H, firstChildPosition: Int) /** * Called to display the child information with the `childPosition` being the * position of the child, excluding headers. * * @param holder The ViewHolder which should be updated * @param childPosition The position of the child */ abstract fun onBindChildViewHolder(holder: C, childPosition: Int) /** * This method shouldn't be used directly, instead use * [onCreateHeaderViewHolder] and * [onCreateChildViewHolder] * * @param parent The parent ViewGroup for the ViewHolder * @param viewType The type for the ViewHolder * @return The correct ViewHolder for the specified viewType */ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return core.onCreateViewHolder(parent, viewType) } /** * This method shouldn't be used directly, instead use * [onBindHeaderViewHolder] and * [onBindChildViewHolder] * * @param holder The ViewHolder to update * @param position The position to update the `holder` with */ @Suppress("UNCHECKED_CAST") override fun onBindViewHolder(holder: ViewHolder, position: Int) { val viewType = getItemViewType(position) val childPosition = getChildPosition(position) if (viewType and HeaderApi.HEADER_VIEW_TYPE_MASK != 0) { onBindHeaderViewHolder(holder as H, childPosition) return } onBindChildViewHolder(holder as C, childPosition) } override var headerData: HeaderData get() = core.headerData set(headerData) { core.headerData = headerData } override var autoUpdateHeaders: Boolean get() = core.autoUpdateHeaders set(autoUpdateHeaders) { core.setAutoUpdateHeaders(this, autoUpdateHeaders) } /** * Retrieves the view type for the specified position. * * @param adapterPosition The position to determine the view type for * @return The type of ViewHolder for the `adapterPosition` */ override fun getItemViewType(adapterPosition: Int): Int { return core.getItemViewType(adapterPosition) } /** * When the RecyclerView is attached a data observer is registered * in order to determine when to re-calculate the headers * * @param recyclerView The RecyclerView that was attached */ override fun onAttachedToRecyclerView(recyclerView: RecyclerView) { super.onAttachedToRecyclerView(recyclerView) core.registerObserver(this) } /** * When the RecyclerView is detached the registered data observer * will be unregistered. See [.onAttachedToRecyclerView] * for more information * * @param recyclerView The RecyclerView that has been detached */ override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) { super.onDetachedFromRecyclerView(recyclerView) core.unregisterObserver(this) } /** * Returns the total number of items in the data set hold by the adapter, this includes * both the Headers and the Children views * * * **NOTE:** [.getChildCount] should be overridden instead of this method * * @return The total number of items in this adapter. */ override fun getItemCount(): Int { return core.itemCount } override fun getHeaderViewType(childPosition: Int): Int { return HeaderApi.HEADER_VIEW_TYPE_MASK } override fun getChildViewType(childPosition: Int): Int { return 0 } override fun getChildCount(headerId: Long): Int { return core.getChildCount(headerId) } override val childCount: Int get() = super.getItemCount() override fun getHeaderId(childPosition: Int): Long { return RecyclerView.NO_ID } override fun getChildPosition(adapterPosition: Int): Int { return core.getChildPosition(adapterPosition) } override fun getChildIndex(adapterPosition: Int): Int? { return core.getChildIndex(adapterPosition) } override fun getAdapterPositionForChild(childPosition: Int): Int { return core.getAdapterPositionForChild(childPosition) } override fun getHeaderPosition(headerId: Long): Int { return core.getHeaderPosition(headerId) } override fun showHeaderAsChild(enabled: Boolean) { core.showHeaderAsChild(enabled) } override val customStickyHeaderViewId: Int get() = 0 }
library/src/main/kotlin/com/devbrackets/android/recyclerext/adapter/HeaderListAdapter.kt
3001677194
/* Copyright 2017-2020 Charles Korn. 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 batect.os import batect.testutils.createForEachTest import batect.testutils.equalTo import batect.testutils.on import batect.testutils.runForEachTest import batect.utils.Json import com.google.common.jimfs.Configuration import com.google.common.jimfs.Jimfs import com.natpryce.hamkrest.assertion.assertThat import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.mock import kotlinx.serialization.json.JsonLiteral import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.util.Properties object SystemInfoSpec : Spek({ describe("a system info provider") { val nativeMethods = mock<NativeMethods> { on { getUserName() } doReturn "awesome-user" } val systemProperties by createForEachTest { val properties = Properties() properties.setProperty("java.vm.vendor", "Awesome JVMs, Inc.") properties.setProperty("java.vm.name", "Best JVM Ever") properties.setProperty("java.version", "1.2.3") properties.setProperty("os.name", "Best OS Ever") properties.setProperty("os.arch", "x86") properties.setProperty("os.version", "4.5.6") properties.setProperty("user.home", "/some/home/dir") properties.setProperty("java.io.tmpdir", "/some/temp/dir") properties.setProperty("line.separator", "some-long-line-separator") properties } val fileSystem by createForEachTest { Jimfs.newFileSystem(Configuration.unix()) } on("getting the JVM version") { val jvmVersion by runForEachTest { SystemInfo(nativeMethods, fileSystem, systemProperties).jvmVersion } it("returns a formatted string containing the details of the JVM") { assertThat(jvmVersion, equalTo("Awesome JVMs, Inc. Best JVM Ever 1.2.3")) } } on("getting the OS version") { val osVersion by runForEachTest { SystemInfo(nativeMethods, fileSystem, systemProperties).osVersion } it("returns a formatted string containing the details of the OS") { assertThat(osVersion, equalTo("Best OS Ever 4.5.6 (x86)")) } } describe("getting the operating system and whether that OS is supported") { on("when running on OS X") { beforeEachTest { systemProperties.setProperty("os.name", "Mac OS X") systemProperties.setProperty("java.io.tmpdir", "/var/folders/tf/abc123/T/") } val systemInfo by runForEachTest { SystemInfo(nativeMethods, fileSystem, systemProperties) } it("returns that the operating system is Mac OS X") { assertThat(systemInfo.operatingSystem, equalTo(OperatingSystem.Mac)) } it("returns that the operating system is supported") { assertThat(systemInfo.isSupportedOperatingSystem, equalTo(true)) } it("returns that the temporary directory is '/tmp'") { assertThat(systemInfo.tempDirectory, equalTo(fileSystem.getPath("/tmp"))) } } on("when running on Linux") { beforeEachTest { systemProperties.setProperty("os.name", "Linux") systemProperties.setProperty("java.io.tmpdir", "/tmp") } val systemInfo by runForEachTest { SystemInfo(nativeMethods, fileSystem, systemProperties) } it("returns that the operating system is Linux") { assertThat(systemInfo.operatingSystem, equalTo(OperatingSystem.Linux)) } it("returns that the operating system is supported") { assertThat(systemInfo.isSupportedOperatingSystem, equalTo(true)) } it("returns that the temporary directory is '/tmp'") { assertThat(systemInfo.tempDirectory, equalTo(fileSystem.getPath("/tmp"))) } } on("when running on Windows") { beforeEachTest { systemProperties.setProperty("os.name", "Windows 10") systemProperties.setProperty("java.io.tmpdir", "C:\\some-temp-dir") } val systemInfo by runForEachTest { SystemInfo(nativeMethods, fileSystem, systemProperties) } it("returns that the operating system is Windows") { assertThat(systemInfo.operatingSystem, equalTo(OperatingSystem.Windows)) } it("returns that the operating system is supported") { assertThat(systemInfo.isSupportedOperatingSystem, equalTo(true)) } it("returns that the temporary directory is the value of the 'java.io.tmpdir' system property") { assertThat(systemInfo.tempDirectory, equalTo(fileSystem.getPath("C:\\some-temp-dir"))) } } on("when running on another operating system") { beforeEachTest { systemProperties.setProperty("os.name", "Something else") } val systemInfo by runForEachTest { SystemInfo(nativeMethods, fileSystem, systemProperties) } it("returns that the operating system is unknown") { assertThat(systemInfo.operatingSystem, equalTo(OperatingSystem.Other)) } it("returns that the operating system is not supported") { assertThat(systemInfo.isSupportedOperatingSystem, equalTo(false)) } } } on("getting the home directory") { val homeDir by runForEachTest { SystemInfo(nativeMethods, fileSystem, systemProperties).homeDirectory } it("returns the user's home directory") { assertThat(homeDir, equalTo(fileSystem.getPath("/some/home/dir"))) } } on("getting the current user name") { val userName by runForEachTest { SystemInfo(nativeMethods, fileSystem, systemProperties).userName } it("returns the ID given by the `id -un` command") { assertThat(userName, equalTo("awesome-user")) } } on("getting the line separator") { val lineSeparator by runForEachTest { SystemInfo(nativeMethods, fileSystem, systemProperties).lineSeparator } it("returns the system's line separator") { assertThat(lineSeparator, equalTo("some-long-line-separator")) } } on("serializing system info") { val json by runForEachTest { Json.parser.toJson(SystemInfo.serializer(), SystemInfo(nativeMethods, fileSystem, systemProperties)).jsonObject } it("only includes the expected fields") { assertThat(json.keys, equalTo(setOf("operatingSystem", "jvmVersion", "osVersion", "homeDirectory", "lineSeparator", "tempDirectory", "userName"))) } it("includes the operating system") { assertThat(json["operatingSystem"], equalTo(JsonLiteral("Other"))) } it("includes the JVM version") { assertThat(json["jvmVersion"], equalTo(JsonLiteral("Awesome JVMs, Inc. Best JVM Ever 1.2.3"))) } it("includes the operating system version") { assertThat(json["osVersion"], equalTo(JsonLiteral("Best OS Ever 4.5.6 (x86)"))) } it("includes the home directory") { assertThat(json["homeDirectory"], equalTo(JsonLiteral("/some/home/dir"))) } it("includes the line separator") { assertThat(json["lineSeparator"], equalTo(JsonLiteral("some-long-line-separator"))) } it("includes the temp directory") { assertThat(json["tempDirectory"], equalTo(JsonLiteral("/some/temp/dir"))) } it("includes the user's user name") { assertThat(json["userName"], equalTo(JsonLiteral("awesome-user"))) } } } })
app/src/unitTest/kotlin/batect/os/SystemInfoSpec.kt
3775929960
package com.exyui.android.debugbottle.components.okhttp /** * Created by yuriel on 11/14/16. */ internal const val OK_HTTP_CLIENT_CLASS = "com.squareup.okhttp.OkHttpClient" internal const val OK_HTTP_CLIENT_3_CLASS = "okhttp3.OkHttpClient" internal const val F_BREAK = " %n" internal const val F_URL = " %s" internal const val F_TIME = " in %.1fms" internal const val F_HEADERS = "%s" internal const val F_RESPONSE = F_BREAK + "Response: %d" internal const val F_BODY = "body: %s" internal const val F_BREAKER = F_BREAK + "-------------------------------------------" + F_BREAK internal const val F_REQUEST_WITHOUT_BODY = F_URL + F_TIME + F_BREAK + F_HEADERS internal const val F_RESPONSE_WITHOUT_BODY = F_RESPONSE + F_BREAK + F_HEADERS + F_BREAKER internal const val F_REQUEST_WITH_BODY = F_URL + F_TIME + F_BREAK + F_HEADERS + F_BODY + F_BREAK internal const val F_RESPONSE_WITH_BODY = F_RESPONSE + F_BREAK + F_HEADERS + F_BODY + F_BREAK + F_BREAKER
components/src/main/kotlin/com/exyui/android/debugbottle/components/okhttp/interceptor.kt
3670130466
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room import kotlin.reflect.KClass /** * Marks a method in a [Dao] annotated class as a delete method. * * The implementation of the method will delete its parameters from the database. * * All of the parameters of the Delete method must either be classes annotated with [Entity] * or collections/array of it. * * Example: * ``` * @Dao * public interface MusicDao { * @Delete * public fun deleteSongs(vararg songs: Song) * * @Delete * public fun deleteAlbumAndSongs(val album: Album, val songs: List<Song>) * } * ``` * * If the target entity is specified via [entity] then the parameters can be of arbitrary * POJO types that will be interpreted as partial entities. For example: * * ``` * @Entity * data class Playlist ( * @PrimaryKey * val playlistId: Long, * val ownerId: Long, * val name: String, * @ColumnInfo(defaultValue = "normal") * val category: String * ) * * data class OwnerIdAndCategory ( * val ownerId: Long, * val category: String * ) * * @Dao * public interface PlaylistDao { * @Delete(entity = Playlist::class) * fun deleteByOwnerIdAndCategory(varargs idCategory: OwnerIdAndCategory) * } * ``` * * @see Insert * @see Update */ @Target(AnnotationTarget.FUNCTION) @Retention(AnnotationRetention.BINARY) public annotation class Delete( /** * The target entity of the delete method. * * When this is declared, the delete method parameters are interpreted as partial entities when * the type of the parameter differs from the target. The POJO class that represents the entity * must contain a subset of the fields of the target entity. The fields value will be used to * find matching entities to delete. * * By default the target entity is interpreted by the method parameters. * * @return the target entity of the delete method or none if the method should use the * parameter type entities. */ val entity: KClass<*> = Any::class )
room/room-common/src/main/java/androidx/room/Delete.kt
648173544
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.camera2.pipe.core import android.util.Log import androidx.annotation.RequiresApi /** * This object provides a set of common log functions that are optimized for CameraPipe with * options to control which log levels are available to log at compile time via const val's. * * Log functions have been designed so that printing variables and doing string concatenation * will not occur if the log level is disabled, which leads to slightly unusual syntax: * * Log.debug { "This is a log message with a $value" } */ @RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java public object Log { public const val TAG: String = "CXCP" private const val LOG_LEVEL_DEBUG = 1 private const val LOG_LEVEL_INFO = 2 private const val LOG_LEVEL_WARN = 3 private const val LOG_LEVEL_ERROR = 4 // This indicates the lowest log level that will always log. private const val LOG_LEVEL = LOG_LEVEL_DEBUG public val DEBUG_LOGGABLE: Boolean = LOG_LEVEL <= LOG_LEVEL_DEBUG || Log.isLoggable(TAG, Log.DEBUG) public val INFO_LOGGABLE: Boolean = LOG_LEVEL <= LOG_LEVEL_INFO || Log.isLoggable(TAG, Log.INFO) public val WARN_LOGGABLE: Boolean = LOG_LEVEL <= LOG_LEVEL_WARN || Log.isLoggable(TAG, Log.WARN) public val ERROR_LOGGABLE: Boolean = LOG_LEVEL <= LOG_LEVEL_ERROR || Log.isLoggable(TAG, Log.ERROR) /** * Debug functions log noisy information related to the internals of the system. */ public inline fun debug(crossinline msg: () -> String) { if (Debug.ENABLE_LOGGING && DEBUG_LOGGABLE) Log.d(TAG, msg()) } public inline fun debug(throwable: Throwable, crossinline msg: () -> String) { if (Debug.ENABLE_LOGGING && DEBUG_LOGGABLE) Log.d(TAG, msg(), throwable) } /** * Info functions log standard, useful information about the state of the system. */ public inline fun info(crossinline msg: () -> String) { if (Debug.ENABLE_LOGGING && INFO_LOGGABLE) Log.i(TAG, msg()) } public inline fun info(throwable: Throwable, crossinline msg: () -> String) { if (Debug.ENABLE_LOGGING && INFO_LOGGABLE) Log.i(TAG, msg(), throwable) } /** * Warning functions are used when something unexpected may lead to a crash or fatal exception * later on as a result if the unusual circumstances */ public inline fun warn(crossinline msg: () -> String) { if (Debug.ENABLE_LOGGING && WARN_LOGGABLE) Log.w(TAG, msg()) } public inline fun warn(throwable: Throwable, crossinline msg: () -> String) { if (Debug.ENABLE_LOGGING && WARN_LOGGABLE) Log.w(TAG, msg(), throwable) } /** * Error functions are reserved for something unexpected that will lead to a crash or data loss. */ public inline fun error(crossinline msg: () -> String) { if (Debug.ENABLE_LOGGING && ERROR_LOGGABLE) Log.e(TAG, msg()) } public inline fun error(throwable: Throwable, crossinline msg: () -> String) { if (Debug.ENABLE_LOGGING && ERROR_LOGGABLE) Log.e(TAG, msg(), throwable) } /** * Read the stack trace of a calling method and join it to a formatted string. */ public fun readStackTrace(limit: Int = 4): String { val elements = Thread.currentThread().stackTrace // Ignore the first 3 elements, which ignores: // VMStack.getThreadStackTrace // Thread.currentThread().getStackTrace() // dumpStackTrace() return elements.drop(3).joinToString( prefix = "\n\t", separator = "\t", limit = limit, ) } }
camera/camera-camera2-pipe/src/main/java/androidx/camera/camera2/pipe/core/Log.kt
3247962645
/* * Copyright (C) 2020 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3.mockwebserver import okhttp3.HttpUrl import okhttp3.Protocol import org.junit.rules.ExternalResource import java.io.Closeable import java.io.IOException import java.net.InetAddress import java.net.Proxy import java.util.concurrent.TimeUnit import java.util.logging.Level import java.util.logging.Logger import javax.net.ServerSocketFactory import javax.net.ssl.SSLSocketFactory class MockWebServer : ExternalResource(), Closeable { val delegate = mockwebserver3.MockWebServer() val requestCount: Int by delegate::requestCount var bodyLimit: Long by delegate::bodyLimit var serverSocketFactory: ServerSocketFactory? by delegate::serverSocketFactory var dispatcher: Dispatcher = QueueDispatcher() set(value) { field = value delegate.dispatcher = value.wrap() } val port: Int get() { before() // This implicitly starts the delegate. return delegate.port } val hostName: String get() { before() // This implicitly starts the delegate. return delegate.hostName } var protocolNegotiationEnabled: Boolean by delegate::protocolNegotiationEnabled @get:JvmName("protocols") var protocols: List<Protocol> get() = delegate.protocols set(value) { delegate.protocols = value } init { delegate.dispatcher = dispatcher.wrap() } private var started: Boolean = false @Synchronized override fun before() { if (started) return try { start() } catch (e: IOException) { throw RuntimeException(e) } } @JvmName("-deprecated_port") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "port"), level = DeprecationLevel.ERROR) fun getPort(): Int = port fun toProxyAddress(): Proxy { before() // This implicitly starts the delegate. return delegate.toProxyAddress() } @JvmName("-deprecated_serverSocketFactory") @Deprecated( message = "moved to var", replaceWith = ReplaceWith( expression = "run { this.serverSocketFactory = serverSocketFactory }" ), level = DeprecationLevel.ERROR) fun setServerSocketFactory(serverSocketFactory: ServerSocketFactory) { delegate.serverSocketFactory = serverSocketFactory } fun url(path: String): HttpUrl { before() // This implicitly starts the delegate. return delegate.url(path) } @JvmName("-deprecated_bodyLimit") @Deprecated( message = "moved to var", replaceWith = ReplaceWith( expression = "run { this.bodyLimit = bodyLimit }" ), level = DeprecationLevel.ERROR) fun setBodyLimit(bodyLimit: Long) { delegate.bodyLimit = bodyLimit } @JvmName("-deprecated_protocolNegotiationEnabled") @Deprecated( message = "moved to var", replaceWith = ReplaceWith( expression = "run { this.protocolNegotiationEnabled = protocolNegotiationEnabled }" ), level = DeprecationLevel.ERROR) fun setProtocolNegotiationEnabled(protocolNegotiationEnabled: Boolean) { delegate.protocolNegotiationEnabled = protocolNegotiationEnabled } @JvmName("-deprecated_protocols") @Deprecated( message = "moved to var", replaceWith = ReplaceWith(expression = "run { this.protocols = protocols }"), level = DeprecationLevel.ERROR) fun setProtocols(protocols: List<Protocol>) { delegate.protocols = protocols } @JvmName("-deprecated_protocols") @Deprecated( message = "moved to var", replaceWith = ReplaceWith(expression = "protocols"), level = DeprecationLevel.ERROR) fun protocols(): List<Protocol> = delegate.protocols fun useHttps(sslSocketFactory: SSLSocketFactory, tunnelProxy: Boolean) { delegate.useHttps(sslSocketFactory, tunnelProxy) } fun noClientAuth() { delegate.noClientAuth() } fun requestClientAuth() { delegate.requestClientAuth() } fun requireClientAuth() { delegate.requireClientAuth() } @Throws(InterruptedException::class) fun takeRequest(): RecordedRequest { return delegate.takeRequest().unwrap() } @Throws(InterruptedException::class) fun takeRequest(timeout: Long, unit: TimeUnit): RecordedRequest? { return delegate.takeRequest(timeout, unit)?.unwrap() } @JvmName("-deprecated_requestCount") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "requestCount"), level = DeprecationLevel.ERROR) fun getRequestCount(): Int = delegate.requestCount fun enqueue(response: MockResponse) { delegate.enqueue(response.wrap()) } @Throws(IOException::class) @JvmOverloads fun start(port: Int = 0) { started = true delegate.start(port) } @Throws(IOException::class) fun start(inetAddress: InetAddress, port: Int) { started = true delegate.start(inetAddress, port) } @Synchronized @Throws(IOException::class) fun shutdown() { delegate.shutdown() } @Synchronized override fun after() { try { shutdown() } catch (e: IOException) { logger.log(Level.WARNING, "MockWebServer shutdown failed", e) } } override fun toString(): String = delegate.toString() @Throws(IOException::class) override fun close() = delegate.close() companion object { private val logger = Logger.getLogger(MockWebServer::class.java.name) } }
mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt
359003337
package theplace.parsers import com.mashape.unirest.http.Unirest import org.jsoup.Jsoup import theplace.parsers.elements.* import java.io.InputStream /** * Created by mk on 07.04.16. */ class SuperiorPicsParser : BaseParser(url = "http://forums.superiorpics.com/", title = "superiorpics") { override var isAlwaysOnePage = true override fun getAlbumPages(album: GalleryAlbum): List<GalleryAlbumPage> { return listOf(GalleryAlbumPage(url = album.url, album = album)) } override fun getAlbums(subGallery: SubGallery): List<GalleryAlbum> { var r = Unirest.get(subGallery.url).asString() var doc = Jsoup.parse(r.body) var boxes = doc.select(".content-left .box135.box-shadow-full") return boxes.map { var href = it.select("a").map { it.attr("href") }.filter { it.startsWith("http://forums.superiorpics.com") }.distinct().first() var title = it.select(".forum-box-news-title-small a").first().text() var thumb_url = it.select(".box135-thumb-wrapper img").first().attr("src") var album = GalleryAlbum( url = href, title = title, subgallery = subGallery ) album.thumb = GalleryImage( url = thumb_url, url_thumb = thumb_url, album = album ) return@map album } } override fun getGalleries_internal(): List<Gallery> { throw UnsupportedOperationException() } override fun getImages(albumPage: GalleryAlbumPage): List<GalleryImage> { var r = Unirest.get(albumPage.url).asString() var doc = Jsoup.parse(r.body) var links = doc.select(".post-content .post_inner a") return links.filter { !(it.parent().hasClass("fr-item-thumb-box") or it.parents().hasClass("signature")) }.map { var url = it.attr("href") var url_thumb = it.select("img").first()?.attr("src") if (url_thumb != null) { GalleryImage(page = albumPage, album = albumPage.album, url = url, url_thumb = url_thumb) } else { return@map null } }.filterNotNull() } override fun downloadImage(image_url: String): InputStream? { return Unirest.get("$image_url").header("referer", "$url").asBinary().body } override fun getSubGalleries(gallery: Gallery): List<SubGallery> { var r = Unirest.get(gallery.url).asString() var doc = Jsoup.parse(r.body) var links = doc.select(".alphaGender-font-paging-box-center a") var max = links.map { it.text() }.filter { "\\d+".toRegex().matches(it) }.map { it.toInt() }.max() return IntRange(1, max ?: 1).map { var newUrl = if (it != 1) "${gallery.url}/index$it.html" else gallery.url SubGallery(url = newUrl, gallery = gallery) } } }
src/main/kotlin/theplace/parsers/SuperiorPicsParser.kt
3689570482
package com.mooveit.kotlin.kotlintemplateproject.data.entity class EntityMocker { companion object Factory { fun getExternalId(): Long = 123456789 fun getMockerPet(): Pet { val pet = Pet() pet.externalId = getExternalId() pet.name = "Spike" pet.status = "available" return pet } } }
app/src/test/java/com/mooveit/kotlin/kotlintemplateproject/data/entity/EntityMocker.kt
254410020
fun withParams(x: Int, y: Int) { } fun main(args : Array<String>) { withPar<caret>() } // COMPLETION_CHAR: (
kotlin-eclipse-ui-test/testData/completion/handlers/withParamsAndBracesOnBrace.kt
2255030340
package me.proxer.app.news /** * @author Ruben Gees */ class NewsNotificationEvent
src/main/kotlin/me/proxer/app/news/NewsNotificationEvent.kt
1217691804
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.sponge.inspection import com.demonwav.mcdev.platform.sponge.util.SpongeConstants import com.demonwav.mcdev.platform.sponge.util.isValidSpongeListener import com.demonwav.mcdev.platform.sponge.util.resolveSpongeGetterTarget import com.demonwav.mcdev.util.isJavaOptional import com.intellij.codeInspection.AbstractBaseUastLocalInspectionTool import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.IntentionAndQuickFixAction import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.lang.jvm.JvmMethod import com.intellij.lang.jvm.actions.createChangeParametersActions import com.intellij.lang.jvm.actions.expectedParameter import com.intellij.lang.jvm.actions.updateMethodParametersRequest import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiClassType import com.intellij.psi.PsiFile import com.intellij.psi.PsiPrimitiveType import com.intellij.psi.PsiSubstitutor import com.intellij.psi.PsiType import com.intellij.psi.util.TypeConversionUtil import com.siyeh.ig.InspectionGadgetsFix import java.util.function.Supplier import org.jetbrains.uast.UMethod import org.jetbrains.uast.getContainingUClass class SpongeWrongGetterTypeInspection : AbstractBaseUastLocalInspectionTool() { override fun getDisplayName() = "Parameter's type is not assignable to its @Getter method return type" override fun getStaticDescription() = "@Getter requires the parameter's type to be assignable from the annotation's target method return type" override fun checkMethod( method: UMethod, manager: InspectionManager, isOnTheFly: Boolean ): Array<ProblemDescriptor>? { val parameters = method.uastParameters if (parameters.size < 2 || !method.isValidSpongeListener()) { return null } val eventClassType = parameters.first().type as? PsiClassType val resolveEventClassTypeGenerics = eventClassType?.resolveGenerics() val eventTypeSubstitutor = resolveEventClassTypeGenerics?.substitutor ?: PsiSubstitutor.EMPTY resolveEventClassTypeGenerics?.element?.let { eventTypeSubstitutor.putAll(it, eventClassType.parameters) } val problems = mutableListOf<ProblemDescriptor>() // We start at 1 because the first parameter is the event for (i in 1 until parameters.size) { val parameter = parameters[i] val getterAnnotation = parameter.findAnnotation(SpongeConstants.GETTER_ANNOTATION) ?: continue val getterMethod = getterAnnotation.resolveSpongeGetterTarget() ?: continue val getterClass = getterMethod.getContainingUClass() ?: continue val eventClass = eventClassType?.resolve() ?: continue val getterSubst = TypeConversionUtil.getSuperClassSubstitutor( getterClass.javaPsi, eventClass, eventTypeSubstitutor ) val getterReturnType = getterMethod.returnType?.let(getterSubst::substitute) ?: continue val parameterType = parameter.type if (getterReturnType.isAssignableFrom(parameterType)) { continue } if (isOptional(getterReturnType)) { val getterOptionalType = getFirstGenericType(getterReturnType) if (getterOptionalType != null && areInSameHierarchy(getterOptionalType, parameterType)) { continue } if (getterOptionalType != null && isOptional(parameterType)) { val paramOptionalType = getFirstGenericType(parameterType) if (paramOptionalType != null && areInSameHierarchy(getterOptionalType, paramOptionalType)) { continue } } } // Prefer highlighting the type, but if type is absent use the whole parameter instead val typeReference = parameter.typeReference ?: continue val location = typeReference.sourcePsi?.takeUnless { it.textRange.isEmpty } ?: continue val methodJava = method.javaPsi as JvmMethod val fixes = this.createFixes(methodJava, getterReturnType, i, manager.project) problems += manager.createProblemDescriptor( location, this.staticDescription, isOnTheFly, fixes, ProblemHighlightType.GENERIC_ERROR_OR_WARNING ) } return problems.toTypedArray() } private fun areInSameHierarchy(aType: PsiType, otherType: PsiType): Boolean = aType.isAssignableFrom(otherType) || otherType.isAssignableFrom(aType) private fun isOptional(type: PsiType): Boolean { val typeClass = type as? PsiClassType ?: return false return typeClass.isJavaOptional() && typeClass.hasParameters() } private fun getFirstGenericType(typeElement: PsiType): PsiType? = (typeElement as? PsiClassType)?.parameters?.firstOrNull() private fun createFixes( method: JvmMethod, expectedType: PsiType, paramIndex: Int, project: Project ): Array<out LocalQuickFix> { if (expectedType is PsiPrimitiveType || expectedType is PsiClassType && !isOptional(expectedType) ) { // The getter does not return an Optional, simply suggest the return type return arrayOf(Fix(method, paramIndex, expectedType)) } val elementFactory = JavaPsiFacade.getElementFactory(project) val expectedClassType = expectedType as? PsiClassType ?: return InspectionGadgetsFix.EMPTY_ARRAY val fixedClassType = if (isOptional(expectedClassType)) { val wrappedType = expectedClassType.parameters.first() val resolveResult = (wrappedType as? PsiClassType)?.resolveGenerics() ?: return InspectionGadgetsFix.EMPTY_ARRAY val element = resolveResult.element ?: return InspectionGadgetsFix.EMPTY_ARRAY elementFactory.createType(element, resolveResult.substitutor) } else { val resolvedClass = expectedClassType.resolve() ?: return InspectionGadgetsFix.EMPTY_ARRAY elementFactory.createType(resolvedClass) } // Suggest a non-Optional version too return arrayOf( Fix(method, paramIndex, expectedType), Fix(method, paramIndex, fixedClassType) ) } private class Fix( method: JvmMethod, val paramIndex: Int, val expectedType: PsiType, ) : IntentionAndQuickFixAction() { private val myText: String = "Set parameter type to ${expectedType.presentableText}" private val methodPointer = Supplier<JvmMethod?> { method } override fun applyFix(project: Project, file: PsiFile, editor: Editor?) { val changeParamsRequest = updateMethodParametersRequest(methodPointer) { actualParams -> val existingParam = actualParams[paramIndex] val newParam = expectedParameter( expectedType, existingParam.semanticNames.first(), existingParam.expectedAnnotations ) actualParams.toMutableList().also { it[paramIndex] = newParam } } val waw = createChangeParametersActions(methodPointer.get()!!, changeParamsRequest).firstOrNull() ?: return waw.invoke(project, editor, file) } override fun getName(): String = myText override fun getFamilyName(): String = myText } }
src/main/kotlin/platform/sponge/inspection/SpongeWrongGetterTypeInspection.kt
1396167562
package com.robohorse.robopojogenerator.postrocessing.common import com.robohorse.robopojogenerator.models.FrameworkVW.AutoValue import com.robohorse.robopojogenerator.models.FrameworkVW.FastJson import com.robohorse.robopojogenerator.models.FrameworkVW.FastJsonJavaRecords import com.robohorse.robopojogenerator.models.FrameworkVW.Gson import com.robohorse.robopojogenerator.models.FrameworkVW.GsonJavaRecords import com.robohorse.robopojogenerator.models.FrameworkVW.Jackson import com.robohorse.robopojogenerator.models.FrameworkVW.JacksonJavaRecords import com.robohorse.robopojogenerator.models.FrameworkVW.LoganSquare import com.robohorse.robopojogenerator.models.FrameworkVW.LoganSquareJavaRecords import com.robohorse.robopojogenerator.models.FrameworkVW.Moshi import com.robohorse.robopojogenerator.models.FrameworkVW.MoshiJavaRecords import com.robohorse.robopojogenerator.models.FrameworkVW.None import com.robohorse.robopojogenerator.models.FrameworkVW.NoneJavaRecords import com.robohorse.robopojogenerator.models.FrameworkVW.NoneLombok import com.robohorse.robopojogenerator.models.GenerationModel import com.robohorse.robopojogenerator.postrocessing.BasePostProcessor import com.robohorse.robopojogenerator.properties.ClassItem import com.robohorse.robopojogenerator.properties.annotations.PojoAnnotations import com.robohorse.robopojogenerator.properties.templates.ImportsTemplate import com.robohorse.robopojogenerator.utils.ClassGenerateHelper import com.robohorse.robopojogenerator.utils.ClassTemplateHelper internal abstract class JavaPostProcessor( generateHelper: ClassGenerateHelper, classTemplateHelper: ClassTemplateHelper ) : BasePostProcessor(generateHelper, classTemplateHelper) { override fun applyAnnotations( generationModel: GenerationModel, classItem: ClassItem ) = when (generationModel.annotationEnum) { is GsonJavaRecords, is Gson -> { generateHelper.setAnnotations( classItem, PojoAnnotations.GSON.classAnnotation, PojoAnnotations.GSON.annotation, ImportsTemplate.GSON.imports ) } is LoganSquareJavaRecords, is LoganSquare -> { generateHelper.setAnnotations( classItem, PojoAnnotations.LOGAN_SQUARE.classAnnotation, PojoAnnotations.LOGAN_SQUARE.annotation, ImportsTemplate.LOGAN_SQUARE.imports ) } is JacksonJavaRecords, is Jackson -> { generateHelper.setAnnotations( classItem, PojoAnnotations.JACKSON.classAnnotation, PojoAnnotations.JACKSON.annotation, ImportsTemplate.JACKSON.imports ) } is FastJsonJavaRecords, is FastJson -> { generateHelper.setAnnotations( classItem, PojoAnnotations.FAST_JSON.classAnnotation, PojoAnnotations.FAST_JSON.annotation, ImportsTemplate.FAST_JSON.imports ) } is AutoValue -> { generateHelper.setAnnotations( classItem, PojoAnnotations.AUTO_VALUE_GSON.classAnnotation, PojoAnnotations.AUTO_VALUE_GSON.annotation, ImportsTemplate.AUTO_VALUE_GSON.imports ) } is MoshiJavaRecords, is Moshi -> { generateHelper.setAnnotations( classItem, PojoAnnotations.MOSHI.classAnnotation, PojoAnnotations.MOSHI.annotation, ImportsTemplate.MOSHI().imports ) } is NoneLombok -> { val annotations = PojoAnnotations.Lombok(generationModel.useLombokValue) val importsTemplate = ImportsTemplate.Lombok(generationModel.useLombokValue) generateHelper.setAnnotations( classItem, annotations.classAnnotation, annotations.annotation, importsTemplate.imports ) } is None, is NoneJavaRecords -> { // NO OP } } }
generator/src/main/kotlin/com/robohorse/robopojogenerator/postrocessing/common/JavaPostProcessor.kt
3016240263
package com.handstandsam.shoppingapp.cart import com.handstandsam.shoppingapp.cart.sqldelight.Database import com.handstandsam.shoppingapp.models.Item import com.handstandsam.shoppingapp.models.ItemWithQuantity import com.squareup.sqldelight.db.SqlDriver import com.squareup.sqldelight.runtime.coroutines.asFlow import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map /** * A SqlDelight Implementation of our [ShoppingCartDao] to read and write to the Database */ class SqlDelightShoppingCartDao(sqlDriver: SqlDriver) : CoroutineScope by CoroutineScope(Dispatchers.IO), ShoppingCartDao { /** * The SqlDelight queries that were created during code generation from our .sq file */ private val itemInCartEntityQueries = Database(sqlDriver).itemInCartEntityQueries override val allItems: Flow<List<ItemWithQuantity>> get() = itemInCartEntityQueries.selectAll() .asFlow() .map { query -> query.executeAsList() .toItemWithQuantityList() } override suspend fun findByLabel(label: String): ItemWithQuantity? { return itemInCartEntityQueries.selectByLabel(label) .executeAsOneOrNull() ?.toItemWithQuantity() } override suspend fun upsert(itemWithQuantity: ItemWithQuantity) { itemInCartEntityQueries.insertOrReplace( label = itemWithQuantity.item.label, image = itemWithQuantity.item.image, link = itemWithQuantity.item.link, quantity = itemWithQuantity.quantity ) } override suspend fun remove(itemWithQuantity: ItemWithQuantity) { itemInCartEntityQueries.deleteByLabel(itemWithQuantity.item.label) } override suspend fun empty() { itemInCartEntityQueries.empty() } } /** * Extension Function converting the SqlDelight Model into our App's Model */ private fun ItemInCart.toItemWithQuantity(): ItemWithQuantity { return ItemWithQuantity( item = Item( label = label, image = image, link = link ), quantity = quantity ) } /** * Extension Function mapping the SqlDelight Model into our App's Model */ private fun List<ItemInCart>.toItemWithQuantityList(): List<ItemWithQuantity> { return this.map { it.toItemWithQuantity() } }
shopping-cart-sqldelight/src/main/java/com/handstandsam/shoppingapp/cart/SqlDelightShoppingCartDao.kt
1073140972
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.module.project.event import com.mycollab.vaadin.event.ApplicationEvent /** * @author MyCollab Ltd * @since 6.0.0 */ object RiskEvent { class GotoAdd(source: Any, val data: Any?) : ApplicationEvent(source) class GotoEdit(source: Any, val data: Any?) : ApplicationEvent(source) class GotoRead(source: Any, val data: Any?) : ApplicationEvent(source) }
mycollab-web/src/main/java/com/mycollab/module/project/event/RiskEvent.kt
407510566
/* * Copyright (c) 2017. tangzx([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.tang.intellij.test.completion /** * * Created by tangzx on 2017/4/23. */ class TestCompletion : TestCompletionBase() { fun testLocalCompletion() { myFixture.configureByFiles("testCompletion.lua") doTestWithResult(listOf("a", "b", "func1")) } fun testGlobalCompletion() { //test 1 myFixture.configureByFiles("globals.lua") myFixture.configureByText("test.lua", "<caret>") doTestWithResult(listOf("gVar1", "gVar2")) //test 2 myFixture.configureByFiles("globals.lua") myFixture.configureByText("test.lua", "gVar2.<caret>") doTestWithResult(listOf("aaa", "bbb", "ccc")) } fun testSelfCompletion() { myFixture.configureByFiles("testSelf.lua") doTestWithResult(listOf("self:aaa", "self:abb")) } fun testParamCompletion() { myFixture.configureByFiles("testParam.lua") doTestWithResult(listOf("param1", "param2")) } fun testAnnotation() { val code = "---@class MyClass\n" + "---@field public name string\n" + "local s = {}\n" + "function s:method()end\n" + "function s.staticMethod()end\n" + "---@type MyClass\n" + "local instance\n" // fields and methods myFixture.configureByText("test.lua", code + "instance.<caret>") doTestWithResult(listOf("name", "method", "staticMethod")) // methods myFixture.configureByText("test.lua", code + "instance:<caret>") doTestWithResult("method") } fun testAnnotationArray() { myFixture.configureByFiles("testAnnotationArray.lua", "class.lua") doTestWithResult(listOf("name", "age", "sayHello")) } fun testAnnotationFun() { myFixture.configureByFiles("testAnnotationFun.lua", "class.lua") doTestWithResult(listOf("name", "age", "sayHello")) } fun testAnnotationDict() { myFixture.configureByFiles("testAnnotationDict.lua", "class.lua") doTestWithResult(listOf("name", "age", "sayHello")) } fun testAnonymous() { doTest(""" --- testAnonymous.lua local function test() local v = xx() v.pp = 123 return v end local v = test() v.--[[caret]] """) { assertTrue("pp" in it) } } fun `test doc table 1`() { doTest(""" --- doc_table_test_A.lua ---@return { name:string, value:number } function getData() end --- doc_table_test_B.lua local a = getData() a.--[[caret]] """) { assertTrue("name" in it) } } }
src/test/kotlin/com/tang/intellij/test/completion/TestCompletion.kt
2743578211
package org.mapdb import io.kotlintest.should import io.kotlintest.shouldBe import org.junit.Assert.assertTrue import org.mapdb.cli.Export import org.mapdb.cli.Import import org.mapdb.db.DB import org.mapdb.io.DataInput2 import org.mapdb.io.DataInput2ByteArray import org.mapdb.io.DataOutput2ByteArray import org.mapdb.ser.Serializer import org.mapdb.ser.Serializers import org.mapdb.util.Exporter class DBCollectionTest: DBWordSpec({ for(a in adapters()){ a.name should { "wrong serializer fail on reopen"{ TT.withTempFile { f-> var db = DB.Maker.appendFile(f).make() a.open(db, "name", Serializers.INTEGER) db.close() db = DB.Maker.appendFile(f).make() TT.assertFailsWith(DBException.WrongSerializer::class) { a.open(db, "name", Serializers.LONG) } } } "use the same instance"{ val db = DB.Maker.heapSer().make() val c1 = a.open(db, "name", Serializers.INTEGER) val c2 = a.open(db, "name", Serializers.INTEGER) val c3 = a.open(db, "name", Serializers.INTEGER) assertTrue(c1===c2 && c2===c3) } "import fails on existing"{ TT.withTempFile { f -> var db = DB.Maker.appendFile(f).make() a.open(db, "name", Serializers.INTEGER) db.close() db = DB.Maker.appendFile(f).make() val input = DataInput2ByteArray(ByteArray(0)) TT.assertFailsWith(DBException.WrongConfig::class){ a.import(db, "name", Serializers.INTEGER, input ) } } } "export"{ val db1 = DB.Maker.heapSer().make() val c1 = a.open(db1, "aa", Serializers.INTEGER) for(i in 1..100) a.add(c1, i) val output = DataOutput2ByteArray() (c1 as Exporter).exportToDataOutput2(output) val input = DataInput2ByteArray(output.copyBytes()) val db2 = DB.Maker.heapSer().make() val c2 = a.import(db2, "aa", Serializers.INTEGER, input) val all = a.getAll(c2).toList() for(i in 1..100){ all[i-1] shouldBe i } } "cli export"{ TT.withTempFile { dbf -> var db = DB.Maker.appendFile(dbf).make() var c = a.open(db, "name", Serializers.INTEGER) for(i in 1..100) a.add(c, i) db.close() val outf = TT.tempNotExistFile() //export from cli Export.main(arrayOf("-d",dbf.path, "-o", outf.path, "-n","name")) outf.length() should {it>0L} db = DB.Maker.heapSer().make() val input = DataInput2ByteArray(outf.readBytes()) c = a.import(db, "name2", Serializers.INTEGER, input ) val all = a.getAll(c).toList() for(i in 1..100){ all[i-1] shouldBe i } } } "cli import"{ TT.withTempFile { dbf -> var db = DB.Maker.heapSer().make() var c = a.open(db, "name", Serializers.INTEGER) for(i in 1..100) a.add(c, i) val output = DataOutput2ByteArray() (c as Exporter).exportToDataOutput2(output) val outf = TT.tempFile() outf.writeBytes(output.copyBytes()) //import from cli Import.main(arrayOf("-d",dbf.path, "-i", outf.path, "-n","name")) dbf.length() should {it>0L} db = DB.Maker.appendFile(dbf).make() c = a.open(db, "name", Serializers.INTEGER) val all = a.getAll(c).toList() for(i in 1..100){ all[i-1] shouldBe i } } } } } }){ companion object { abstract class Adapter<C>{ abstract fun open(db: DB, name:String, serializer: Serializer<*>):C abstract fun import(db: DB, name:String, serializer: Serializer<*>, input: DataInput2):C abstract fun add(c:C, e:Any?) abstract fun getAll(c:C):Iterable<Any?> abstract val name:String } fun adapters():List<Adapter<Any>>{ /* val qAdapter = object: Adapter<LinkedFIFOQueue<Any>>() { override fun import(db: DB, name: String, serializer: Serializer<*>, input: DataInput2): LinkedFIFOQueue<Any> { return db.queue(name, serializer) .importFromDataInput2(input) .make() as LinkedFIFOQueue<Any> } override fun open(db: DB, name: String, serializer: Serializer<*>): LinkedFIFOQueue<Any> { return db.queue(name, serializer).make() as LinkedFIFOQueue<Any> } override fun add(c: LinkedFIFOQueue<Any>, e: Any?) { c.add(e) } override fun getAll(c: LinkedFIFOQueue<Any>): Iterable<Any?> { return c } override val name = "queue" } */ return emptyList() } } }
src/test/java/org/mapdb/DBCollectionTest.kt
1493992258
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. */ package com.mycollab.module.user.dao import com.mycollab.module.user.domain.SimpleBillingAccount import org.apache.ibatis.annotations.Mapper @Mapper interface BillingAccountMapperExt { val defaultAccountByDomain: SimpleBillingAccount fun getBillingAccountById(accountId: Int): SimpleBillingAccount? fun getAccountByDomain(domainName: String): SimpleBillingAccount? }
mycollab-services/src/main/java/com/mycollab/module/user/dao/BillingAccountMapperExt.kt
2995648165
package com.junnanhao.next.data.model import io.objectbox.annotation.Backlink import io.objectbox.annotation.Entity import io.objectbox.annotation.Id import io.objectbox.relation.ToMany /** * Created by jonashao on 2017/9/26. * a cluster of songs */ @Entity data class Cluster( @Id var id: Long, @Backlink val songs: ToMany<ClusterMembership> // val similar: ToMany<Map.Entry<Cluster, Double>> )
app/src/main/java/com/junnanhao/next/data/model/Cluster.kt
3610495926
package de.tum.`in`.tumcampusapp.component.other.settings import android.Manifest.permission.READ_CALENDAR import android.Manifest.permission.WRITE_CALENDAR import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.content.pm.PackageManager.PERMISSION_GRANTED import android.graphics.drawable.BitmapDrawable import android.os.Bundle import androidx.appcompat.app.AlertDialog import androidx.core.content.ContextCompat.checkSelfPermission import androidx.core.content.edit import androidx.core.os.bundleOf import androidx.preference.CheckBoxPreference import androidx.preference.ListPreference import androidx.preference.MultiSelectListPreference import androidx.preference.Preference import androidx.preference.PreferenceCategory import androidx.preference.PreferenceFragmentCompat import androidx.preference.SwitchPreferenceCompat import com.squareup.picasso.Picasso import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.api.tumonline.AccessTokenManager import de.tum.`in`.tumcampusapp.component.tumui.calendar.CalendarController import de.tum.`in`.tumcampusapp.component.ui.cafeteria.repository.CafeteriaLocalRepository import de.tum.`in`.tumcampusapp.component.ui.eduroam.SetupEduroamActivity import de.tum.`in`.tumcampusapp.component.ui.news.NewsController import de.tum.`in`.tumcampusapp.component.ui.onboarding.StartupActivity import de.tum.`in`.tumcampusapp.database.TcaDb import de.tum.`in`.tumcampusapp.di.injector import de.tum.`in`.tumcampusapp.service.SilenceService import de.tum.`in`.tumcampusapp.service.StartSyncReceiver import de.tum.`in`.tumcampusapp.utils.Const import de.tum.`in`.tumcampusapp.utils.Utils import de.tum.`in`.tumcampusapp.utils.plusAssign import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.activity_setup_eduroam.* import org.jetbrains.anko.defaultSharedPreferences import org.jetbrains.anko.notificationManager import java.util.concurrent.ExecutionException import javax.inject.Inject class SettingsFragment : PreferenceFragmentCompat(), Preference.OnPreferenceClickListener, SharedPreferences.OnSharedPreferenceChangeListener { private val compositeDisposable = CompositeDisposable() @Inject lateinit var cafeteriaLocalRepository: CafeteriaLocalRepository @Inject lateinit var newsController: NewsController override fun onAttach(context: Context) { super.onAttach(context) injector.inject(this) } override fun onCreatePreferences( savedInstanceState: Bundle?, rootKey: String? ) { setPreferencesFromResource(R.xml.settings, rootKey) populateNewsSources() setUpEmployeeSettings() // Disables silence service and logout if the app is used without TUMOnline access val silentSwitch = findPreference(Const.SILENCE_SERVICE) as? SwitchPreferenceCompat val logoutButton = findPreference(BUTTON_LOGOUT) if (!AccessTokenManager.hasValidAccessToken(context)) { if (silentSwitch != null) { silentSwitch.isEnabled = false } logoutButton.isVisible = false } // Only do these things if we are in the root of the preferences if (rootKey == null) { // Click listener for preference list entries. Used to simulate a button // (since it is not possible to add a button to the preferences screen) findPreference(BUTTON_LOGOUT).onPreferenceClickListener = this setSummary("language_preference") setSummary("card_default_campus") setSummary("silent_mode_set_to") setSummary("background_mode_set_to") } else if (rootKey == "card_cafeteria") { setSummary("card_cafeteria_default_G") setSummary("card_cafeteria_default_K") setSummary("card_cafeteria_default_W") setSummary("card_role") initCafeteriaCardSelections() } else if (rootKey == "card_mvv") { setSummary("card_stations_default_G") setSummary("card_stations_default_C") setSummary("card_stations_default_K") } else if (rootKey == "card_eduroam") { findPreference(SETUP_EDUROAM).onPreferenceClickListener = this } requireContext().defaultSharedPreferences.registerOnSharedPreferenceChangeListener(this) } private fun populateNewsSources() { val newsSourcesPreference = findPreference("card_news_sources") as? PreferenceCategory ?: return val newsSources = newsController.newsSources for (newsSource in newsSources) { val pref = CheckBoxPreference(requireContext()) pref.key = "card_news_source_" + newsSource.id pref.setDefaultValue(true) // Reserve space so that when the icon is loaded the text is not moved again pref.isIconSpaceReserved = true // Load news source icon in background and set it val url = newsSource.icon if (url.isNotBlank()) { loadNewsSourceIcon(pref, url) } pref.title = newsSource.title newsSourcesPreference.addPreference(pref) } } private fun loadNewsSourceIcon( preference: Preference, url: String ) { compositeDisposable += Single .fromCallable { Picasso.get().load(url).get() } .subscribeOn(Schedulers.io()) .map { BitmapDrawable(resources, it) } .observeOn(AndroidSchedulers.mainThread()) .subscribe(preference::setIcon, Utils::log) } /** * Disable setting for non-employees. */ private fun setUpEmployeeSettings() { val isEmployee = Utils.getSetting(requireContext(), Const.TUMO_EMPLOYEE_ID, "").isNotEmpty() val checkbox = findPreference(Const.EMPLOYEE_MODE) ?: return if (!isEmployee) { checkbox.isEnabled = false } } override fun onSharedPreferenceChanged( sharedPrefs: SharedPreferences, key: String? ) { if (key == null) { return } setSummary(key) // When newspread selection changes // deselect all newspread sources and select only the // selected source if one of all was selected before if (key == "news_newspread") { val newspreadIds = 7..13 val value = newspreadIds.any { sharedPrefs.getBoolean("card_news_source_$it", false) } val newSource = sharedPrefs.getString(key, "7") sharedPrefs.edit { newspreadIds.forEach { putBoolean("card_news_source_$it", false) } putBoolean("card_news_source_$newSource", value) } } // If the silent mode was activated, start the service. This will invoke // the service to call onHandleIntent which checks available lectures if (key == Const.SILENCE_SERVICE) { val service = Intent(requireContext(), SilenceService::class.java) if (sharedPrefs.getBoolean(key, false)) { if (!SilenceService.hasPermissions(requireContext())) { // disable until silence service permission is resolved val silenceSwitch = findPreference(Const.SILENCE_SERVICE) as SwitchPreferenceCompat silenceSwitch.isChecked = false Utils.setSetting(requireContext(), Const.SILENCE_SERVICE, false) SilenceService.requestPermissions(requireContext()) } else { requireContext().startService(service) } } else { requireContext().stopService(service) } } // If the background mode was activated, start the service. This will invoke // the service to call onHandleIntent which updates all background data if (key == Const.BACKGROUND_MODE) { if (sharedPrefs.getBoolean(key, false)) { StartSyncReceiver.startBackground(requireContext()) } else { StartSyncReceiver.cancelBackground() } } // restart app after language change if (key == "language_preference" && activity != null) { (activity as SettingsActivity).restartApp() } } private fun initCafeteriaCardSelections() { val cafeterias = cafeteriaLocalRepository .getAllCafeterias() .blockingFirst() .sortedBy { it.name } val cafeteriaByLocationName = getString(R.string.settings_cafeteria_depending_on_location) val cafeteriaNames = listOf(cafeteriaByLocationName) + cafeterias.map { it.name } val cafeteriaByLocationId = Const.CAFETERIA_BY_LOCATION_SETTINGS_ID val cafeteriaIds = listOf(cafeteriaByLocationId) + cafeterias.map { it.id.toString() } val preference = findPreference(Const.CAFETERIA_CARDS_SETTING) as MultiSelectListPreference preference.entries = cafeteriaNames.toTypedArray() preference.entryValues = cafeteriaIds.toTypedArray() preference.setOnPreferenceChangeListener { pref, newValue -> (pref as MultiSelectListPreference).values = newValue as Set<String> setCafeteriaCardsSummary(preference) false } setCafeteriaCardsSummary(preference) } private fun setSummary(key: CharSequence) { val pref = findPreference(key) if (pref is ListPreference) { val entry = pref.entry.toString() pref.summary = entry } } private fun setCafeteriaCardsSummary(preference: MultiSelectListPreference) { val values = preference.values if (values.isEmpty()) { preference.setSummary(R.string.settings_no_location_selected) } else { preference.summary = values .map { preference.findIndexOfValue(it) } .map { preference.entries[it] } .map { it.toString() } .sorted() .joinToString(", ") } } override fun onPreferenceClick( preference: Preference? ): Boolean { when (preference?.key) { SETUP_EDUROAM -> startActivity(Intent(context, SetupEduroamActivity::class.java)) BUTTON_LOGOUT -> showLogoutDialog(R.string.logout_title, R.string.logout_message) else -> return false } return true } private fun showLogoutDialog(title: Int, message: Int) { AlertDialog.Builder(requireContext()) .setTitle(title) .setMessage(message) .setPositiveButton(R.string.logout) { _, _ -> logout() } .setNegativeButton(R.string.cancel, null) .create() .apply { window?.setBackgroundDrawableResource(R.drawable.rounded_corners_background) } .show() } private fun logout() { try { clearData() } catch (e: Exception) { Utils.log(e) showLogoutDialog(R.string.logout_error_title, R.string.logout_try_again) return } startActivity(Intent(requireContext(), StartupActivity::class.java)) requireActivity().finish() } @SuppressLint("ApplySharedPref") @Throws(ExecutionException::class, InterruptedException::class) private fun clearData() { TcaDb.resetDb(requireContext()) requireContext().defaultSharedPreferences.edit().clear().commit() // Remove all notifications that are currently shown requireContext().notificationManager.cancelAll() val readCalendar = checkSelfPermission(requireActivity(), READ_CALENDAR) val writeCalendar = checkSelfPermission(requireActivity(), WRITE_CALENDAR) // Delete local calendar Utils.setSetting(requireContext(), Const.SYNC_CALENDAR, false) if (readCalendar == PERMISSION_GRANTED && writeCalendar == PERMISSION_GRANTED) { CalendarController.deleteLocalCalendar(requireContext()) } } override fun onDestroy() { compositeDisposable.dispose() super.onDestroy() } companion object { private const val BUTTON_LOGOUT = "button_logout" private const val SETUP_EDUROAM = "card_eduroam_setup" fun newInstance( key: String? ) = SettingsFragment().apply { arguments = bundleOf(ARG_PREFERENCE_ROOT to key) } } }
app/src/main/java/de/tum/in/tumcampusapp/component/other/settings/SettingsFragment.kt
3518569208
val f = { (a: Int, b: Int): Int -> a + b }
src/test/resources/org/jetbrains/pmdkotlin/deprecatedTest/LambdaSyntaxTest.kt
3611758146
package com.eden.orchid.impl.themes.functions import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.compilers.TemplateFunction import com.eden.orchid.api.indexing.IndexService import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.theme.pages.OrchidPage @Description(value = "Lookup a Page object by a query.", name = "Find") class FindFunction : TemplateFunction("find", false) { @Option @Description("The Id of an item to look up.") lateinit var itemId: String @Option @Description("The type of collection the item is expected to come from.") lateinit var collectionType: String @Option @Description("The specific Id of the given collection type where the item is expected to come from.") lateinit var collectionId: String override fun parameters() = IndexService.locateParams override fun apply(context: OrchidContext, page: OrchidPage?): Any? { return context.find(collectionType, collectionId, itemId) } }
OrchidCore/src/main/kotlin/com/eden/orchid/impl/themes/functions/FindFunction.kt
2077969918
package com.hana053.micropost.domain data class Micropost( val id: Long, val content: String, val createdAt: Long, val user: User )
app/src/main/kotlin/com/hana053/micropost/domain/Micropost.kt
1478600261
package com.intfocus.template.subject.nine.module.options import com.alibaba.fastjson.JSONObject import com.intfocus.template.model.DaoUtil import com.intfocus.template.model.callback.LoadDataCallback import com.intfocus.template.model.gen.SourceDao import com.intfocus.template.subject.nine.CollectionModelImpl import com.intfocus.template.subject.nine.module.ModuleModel /** * @author liuruilin * @data 2017/11/3 * @describe */ class OptionsModelImpl : ModuleModel<OptionsEntity> { companion object { private var INSTANCE: OptionsModelImpl? = null /** * Returns the single instance of this class, creating it if necessary. */ @JvmStatic fun getInstance(): OptionsModelImpl { return INSTANCE ?: OptionsModelImpl() .apply { INSTANCE = this } } /** * Used to force [getInstance] to create a new instance * next time it's called. */ @JvmStatic fun destroyInstance() { INSTANCE = null } } override fun analyseData(params: String, callback: LoadDataCallback<OptionsEntity>) { val data = JSONObject.parseObject(params, OptionsEntity::class.java) callback.onSuccess(data) } override fun insertDb(value: String, key: String, listItemType: Int) { val sourceDao = DaoUtil.getDaoSession()!!.sourceDao val collectionQb = sourceDao.queryBuilder() val collection = collectionQb.where(collectionQb.and(SourceDao.Properties.Key.eq(key), SourceDao.Properties.Uuid.eq(CollectionModelImpl.uuid))).unique() if (null != collection) { collection.value = value sourceDao.update(collection) if (listItemType != 0) { CollectionModelImpl.getInstance().updateCollectionData(listItemType, value) } } } }
app/src/main/java/com/intfocus/template/subject/nine/module/options/OptionsModelImpl.kt
2535058925
package com.habitrpg.wearos.habitica.ui.activities import android.app.Activity import android.content.Intent import android.content.res.ColorStateList import android.os.Bundle import android.widget.TextView import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.viewModels import androidx.core.content.ContextCompat import androidx.core.view.isVisible import androidx.lifecycle.lifecycleScope import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.databinding.ActivityTaskFormBinding import com.habitrpg.shared.habitica.models.tasks.TaskType import com.habitrpg.wearos.habitica.ui.viewmodels.TaskFormViewModel import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.launch @AndroidEntryPoint class TaskFormActivity : BaseActivity<ActivityTaskFormBinding, TaskFormViewModel>() { var taskType: TaskType? = null set(value) { field = value updateTaskTypeButton(binding.todoButton, TaskType.TODO) updateTaskTypeButton(binding.dailyButton, TaskType.DAILY) updateTaskTypeButton(binding.habitButton, TaskType.HABIT) val typeName = getString(when(value) { TaskType.HABIT -> R.string.habit TaskType.DAILY -> R.string.daily TaskType.TODO -> R.string.todo TaskType.REWARD -> R.string.reward else -> R.string.task }) binding.confirmationTitle.text = getString(R.string.new_task_x, typeName) binding.saveButton.setChipText(getString(R.string.save_task_x, typeName)) } override val viewModel: TaskFormViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { binding = ActivityTaskFormBinding.inflate(layoutInflater) super.onCreate(savedInstanceState) binding.editText.setOnClickListener { it.clearFocus() requestInput() } binding.editButton.setOnClickListener { binding.editTaskWrapper.isVisible = true binding.taskConfirmationWrapper.isVisible = false if (intent.extras?.containsKey("task_type") == true) { requestInput() } } binding.todoButton.setOnClickListener { taskType = TaskType.TODO } binding.dailyButton.setOnClickListener { taskType = TaskType.DAILY } binding.habitButton.setOnClickListener { taskType = TaskType.HABIT } binding.saveButton.setOnClickListener { binding.saveButton.isEnabled = false lifecycleScope.launch(CoroutineExceptionHandler { _, _ -> binding.saveButton.isEnabled = true binding.editTaskWrapper.isVisible = true binding.taskConfirmationWrapper.isVisible = false }) { viewModel.saveTask(binding.editText.text, taskType) val data = Intent() data.putExtra("task_type", taskType?.value) setResult(Activity.RESULT_OK, data) finish() parent.startActivity(Intent(parent, TaskListActivity::class.java).apply { putExtra("task_type", taskType?.value) }) } } if (intent.extras?.containsKey("task_type") == true) { taskType = TaskType.from(intent.getStringExtra("task_type")) binding.taskTypeHeader.isVisible = false binding.taskTypeWrapper.isVisible = false binding.header.textView.text = getString(R.string.create_task, taskType?.value) requestInput() } else { taskType = TaskType.TODO binding.header.textView.text = getString(R.string.new_task) } } private val inputResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { val input = it.data?.getStringExtra("input") if (input?.isNotBlank() == true) { binding.editTaskWrapper.isVisible = false binding.taskConfirmationWrapper.isVisible = true binding.confirmationText.text = input binding.editText.setText(input) } } private fun requestInput() { val intent = Intent(this, InputActivity::class.java).apply { putExtra("title", getString(R.string.task_title_hint)) putExtra("input", binding.editText.text.toString()) } inputResult.launch(intent) } private fun updateTaskTypeButton(button: TextView, thisType: TaskType) { if (taskType == thisType) { button.backgroundTintList = ColorStateList.valueOf(ContextCompat.getColor(this, R.color.watch_purple_10)) button.background.alpha = 100 button.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.radio_checked, 0) } else { button.backgroundTintList = ColorStateList.valueOf(ContextCompat.getColor(this, R.color.watch_purple_5)) button.background.alpha = 255 button.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.radio_unchecked, 0) } } }
wearos/src/main/java/com/habitrpg/wearos/habitica/ui/activities/TaskFormActivity.kt
451501296
/* * Copyright (C) 2019 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.core.completion import com.intellij.psi.PsiElement import com.intellij.util.ProcessingContext interface CompletionFilter { fun accepts(element: PsiElement, context: ProcessingContext): Boolean }
src/kotlin-intellij/main/uk/co/reecedunn/intellij/plugin/core/completion/CompletionFilter.kt
3519866426
package com.reactnativenavigation.options import com.reactnativenavigation.options.animations.ViewAnimationOptions import com.reactnativenavigation.options.params.Bool import com.reactnativenavigation.options.params.NullBool import com.reactnativenavigation.options.parsers.BoolParser import org.json.JSONObject open class StackAnimationOptions(json: JSONObject? = null) : LayoutAnimation { @JvmField var enabled: Bool = NullBool() @JvmField var waitForRender: Bool = NullBool() @JvmField var content = ViewAnimationOptions() @JvmField var bottomTabs = ViewAnimationOptions() @JvmField var topBar = ViewAnimationOptions() override var sharedElements = SharedElements() override var elementTransitions = ElementTransitions() init { parse(json) } fun mergeWith(other: StackAnimationOptions) { topBar.mergeWith(other.topBar) content.mergeWith(other.content) bottomTabs.mergeWith(other.bottomTabs) sharedElements.mergeWith(other.sharedElements) elementTransitions.mergeWith(other.elementTransitions) if (other.enabled.hasValue()) enabled = other.enabled if (other.waitForRender.hasValue()) waitForRender = other.waitForRender } fun mergeWithDefault(defaultOptions: StackAnimationOptions) { content.mergeWithDefault(defaultOptions.content) bottomTabs.mergeWithDefault(defaultOptions.bottomTabs) topBar.mergeWithDefault(defaultOptions.topBar) sharedElements.mergeWithDefault(defaultOptions.sharedElements) elementTransitions.mergeWithDefault(defaultOptions.elementTransitions) if (!enabled.hasValue()) enabled = defaultOptions.enabled if (!waitForRender.hasValue()) waitForRender = defaultOptions.waitForRender } fun hasEnterValue(): Boolean { return topBar.enter.hasValue() || content.enter.hasValue() || bottomTabs.enter.hasValue() || waitForRender.hasValue() } fun hasExitValue(): Boolean { return topBar.exit.hasValue() || content.exit.hasValue() || bottomTabs.exit.hasValue() || waitForRender.hasValue() } private fun parse(json: JSONObject?) { json ?: return content = ViewAnimationOptions(json.optJSONObject("content")) bottomTabs = ViewAnimationOptions(json.optJSONObject("bottomTabs")) topBar = ViewAnimationOptions(json.optJSONObject("topBar")) enabled = BoolParser.parseFirst(json, "enabled", "enable") waitForRender = BoolParser.parse(json, "waitForRender") sharedElements = SharedElements.parse(json) elementTransitions = ElementTransitions.parse(json) } }
lib/android/app/src/main/java/com/reactnativenavigation/options/StackAnimationOptions.kt
1900756353
/* * Copyright (C) 2020 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.processor.debug.frame import com.intellij.xdebugger.frame.XExecutionStack import com.intellij.xdebugger.frame.XStackFrame import uk.co.reecedunn.intellij.plugin.processor.debug.DebugSession class QueryExecutionStack(displayName: String, private val session: DebugSession) : XExecutionStack(displayName) { private var frames: List<XStackFrame>? = null override fun computeStackFrames(firstFrameIndex: Int, container: XStackFrameContainer?) { if (firstFrameIndex == 0) { frames = session.stackFrames container?.addStackFrames(frames!!, true) } else { container?.addStackFrames(frames!!.drop(firstFrameIndex), true) } } override fun getTopFrame(): XStackFrame? = frames?.firstOrNull() }
src/plugin-api/main/uk/co/reecedunn/intellij/plugin/processor/debug/frame/QueryExecutionStack.kt
1421499666
package com.reactnative.scenarios import android.content.Context import com.bugsnag.android.Bugsnag import com.facebook.react.bridge.Promise class FeatureFlagsNativeCrashScenario(context: Context): Scenario(context) { override fun run(promise: Promise) { Bugsnag.clearFeatureFlag("should_not_be_reported_1") Bugsnag.clearFeatureFlag("should_not_be_reported_2") Bugsnag.clearFeatureFlag("should_not_be_reported_3") throw generateException() } }
test/react-native/features/fixtures/reactnative/scenarios/FeatureFlagsNativeCrashScenario.kt
3792194972
package wangdaye.com.geometricweather.common.basic import android.content.Intent import android.graphics.Rect import android.os.Bundle import android.view.ViewGroup import androidx.annotation.CallSuper import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Lifecycle import wangdaye.com.geometricweather.GeometricWeather import wangdaye.com.geometricweather.common.basic.insets.FitHorizontalSystemBarRootLayout import wangdaye.com.geometricweather.common.snackbar.SnackbarContainer import wangdaye.com.geometricweather.common.utils.DisplayUtils import wangdaye.com.geometricweather.common.utils.LanguageUtils import wangdaye.com.geometricweather.settings.SettingsManager abstract class GeoActivity : AppCompatActivity() { lateinit var fitHorizontalSystemBarRootLayout: FitHorizontalSystemBarRootLayout private class KeyboardResizeBugWorkaround private constructor( activity: GeoActivity ) { private val root = activity.fitHorizontalSystemBarRootLayout private val rootParams: ViewGroup.LayoutParams private var usableHeightPrevious = 0 private fun possiblyResizeChildOfContent() { val usableHeightNow = computeUsableHeight() if (usableHeightNow != usableHeightPrevious) { val screenHeight = root.rootView.height val keyboardExpanded: Boolean if (screenHeight - usableHeightNow > screenHeight / 5) { // keyboard probably just became visible. keyboardExpanded = true rootParams.height = usableHeightNow } else { // keyboard probably just became hidden. keyboardExpanded = false rootParams.height = screenHeight } usableHeightPrevious = usableHeightNow root.setFitKeyboardExpanded(keyboardExpanded) } } private fun computeUsableHeight(): Int { val r = Rect() DisplayUtils.getVisibleDisplayFrame(root, r) return r.bottom // - r.top; --> Do not reduce the height of status bar. } companion object { // For more information, see https://issuetracker.google.com/issues/36911528 // To use this class, simply invoke assistActivity() on an Activity that already has its content view set. fun assistActivity(activity: GeoActivity) { KeyboardResizeBugWorkaround(activity) } } init { root.viewTreeObserver.addOnGlobalLayoutListener { possiblyResizeChildOfContent() } rootParams = root.layoutParams } } @CallSuper override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) fitHorizontalSystemBarRootLayout = FitHorizontalSystemBarRootLayout(this) GeometricWeather.instance.addActivity(this) LanguageUtils.setLanguage( this, SettingsManager.getInstance(this).language.locale ) DisplayUtils.setSystemBarStyle( this, window, false, !DisplayUtils.isDarkMode(this), true, !DisplayUtils.isDarkMode(this) ) } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) // decor -> fit horizontal system bar -> decor child. val decorView = window.decorView as ViewGroup val decorChild = decorView.getChildAt(0) as ViewGroup decorView.removeView(decorChild) decorView.addView(fitHorizontalSystemBarRootLayout) fitHorizontalSystemBarRootLayout.removeAllViews() fitHorizontalSystemBarRootLayout.addView(decorChild) KeyboardResizeBugWorkaround.assistActivity(this) } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) GeometricWeather.instance.setTopActivity(this) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) GeometricWeather.instance.setTopActivity(this) } @CallSuper override fun onResume() { super.onResume() GeometricWeather.instance.setTopActivity(this) } @CallSuper override fun onPause() { super.onPause() GeometricWeather.instance.checkToCleanTopActivity(this) } @CallSuper override fun onDestroy() { super.onDestroy() GeometricWeather.instance.removeActivity(this) } open val snackbarContainer: SnackbarContainer? get() = SnackbarContainer( this, findViewById<ViewGroup>(android.R.id.content).getChildAt(0) as ViewGroup, true ) fun provideSnackbarContainer(): SnackbarContainer? = snackbarContainer val isActivityCreated: Boolean get() = lifecycle.currentState.isAtLeast(Lifecycle.State.CREATED) val isActivityStarted: Boolean get() = lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED) val isActivityResumed: Boolean get() = lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED) }
app/src/main/java/wangdaye/com/geometricweather/common/basic/GeoActivity.kt
256234728
package org.stepik.android.presentation.feedback import io.reactivex.Scheduler import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.subscribeBy import org.stepic.droid.di.qualifiers.BackgroundScheduler import org.stepic.droid.di.qualifiers.MainScheduler import ru.nobird.android.domain.rx.emptyOnErrorStub import org.stepik.android.domain.feedback.interactor.FeedbackInteractor import org.stepik.android.presentation.base.PresenterBase import javax.inject.Inject class FeedbackPresenter @Inject constructor( private val feedbackInteractor: FeedbackInteractor, @BackgroundScheduler private val backgroundScheduler: Scheduler, @MainScheduler private val mainScheduler: Scheduler ) : PresenterBase<FeedbackView>() { fun sendTextFeedback(subject: String, aboutSystemInfo: String) { compositeDisposable += feedbackInteractor .createSupportEmailData(subject, aboutSystemInfo) .observeOn(mainScheduler) .subscribeOn(backgroundScheduler) .subscribeBy( onSuccess = { view?.sendTextFeedback(it) }, onError = emptyOnErrorStub ) } }
app/src/main/java/org/stepik/android/presentation/feedback/FeedbackPresenter.kt
812113258
package nl.shadowlink.tools.io import java.io.ByteArrayInputStream import java.nio.ByteBuffer /** * @author Shadow-Link */ class ByteReader( private val stream: ByteArray, private var currentOffset: Int ) { private var system = true private var sysSize = 0 fun readUInt32(): Int { var i = 0 val len = 4 var cnt = 0 val tmp = ByteArray(len) i = currentOffset while (i < currentOffset + len) { tmp[cnt] = stream[i] cnt++ i++ } var accum: Long = 0 i = 0 var shiftBy = 0 while (shiftBy < 32) { accum = accum or ((tmp[i].toInt() and 0xff).toLong() shl shiftBy) i++ shiftBy += 8 } currentOffset += 4 return accum.toInt() } fun readOffset(): Int { val value: Int val offset = readUInt32() value = if (offset == 0) { 0 } else { if (offset shr 28 != 5) { throw IllegalStateException("Expected an offset") } else { offset and 0x0fffffff } } return value } fun readVector4D(): Vector4D { val x = readFloat() val y = readFloat() val z = readFloat() val w = readFloat() return Vector4D(x, y, z, w) } fun readFloat(): Float { var accum = 0 var i = 0 var shiftBy = 0 while (shiftBy < 32) { accum = (accum.toLong() or ((stream[currentOffset + i].toInt() and 0xff).toLong() shl shiftBy)).toInt() i++ shiftBy += 8 } currentOffset += 4 return java.lang.Float.intBitsToFloat(accum) } fun readUInt16(): Int { val low = stream[currentOffset].toInt() and 0xff val high = stream[currentOffset + 1].toInt() and 0xff currentOffset += 2 return (high shl 8 or low) } fun readInt16(): Short { val ret = (stream[currentOffset + 1].toShort().toInt() shl 8 or (stream[currentOffset].toShort() .toInt() and 0xff)).toShort() currentOffset += 2 return ret } fun readDataOffset(): Int { val value: Int val offset = readUInt32() value = if (offset == 0) { 0 } else { if (offset shr 28 != 6) { } offset and 0x0fffffff } return value } /** * Returns a String from the DataInputStream with the given size till 0 * * @param data_in * @param size * @return a String of the size size */ fun readNullTerminatedString(size: Int): String { var woord = "" var gotNull = false for (i in 0 until size) { val b = readByte() if (!gotNull) { if (b.toInt() != 0) woord += Char(b.toUShort()) else gotNull = true } } return woord } fun readNullTerminatedString(): String { var sb = "" var c = Char(stream[currentOffset].toUShort()) while (c.code != 0) { // nl.shadowlink.tools.io.Message.displayMsgHigh("String: " + sb + " c: " + c); sb = sb + c currentOffset++ c = Char(stream[currentOffset].toUShort()) } return sb } fun readString(length: Int): String { var sb = "" for (i in 0 until length) { val c = Char(stream[currentOffset].toUShort()) sb += c currentOffset++ } return sb } fun toArray(bytes: Int): ByteArray { val arr = ByteArray(bytes) for (i in 0 until bytes) { arr[i] = stream[currentOffset] currentOffset++ } return arr } fun toArray(): ByteArray { return stream } fun toArray(start: Int, end: Int): ByteArray { val retSize = end - start val retStream = ByteArray(retSize) setCurrentOffset(start) for (i in 0 until retSize) { retStream[i] = stream[currentOffset] currentOffset++ } return retStream } fun readByte(): Byte { currentOffset++ return stream[currentOffset - 1] } fun getCurrentOffset(): Int { return currentOffset } fun setCurrentOffset(offset: Int) { currentOffset = offset if (!system) { currentOffset += sysSize } } fun setSysSize(size: Int) { sysSize = size } fun setSystemMemory(system: Boolean) { this.system = system } fun getByteBuffer(size: Int): ByteBuffer { val buffer = ByteArray(size) val bbuf = ByteBuffer.allocate(size) for (i in 0 until size) { buffer[i] = readByte() } bbuf.put(buffer) bbuf.rewind() return bbuf } fun readBytes(pCount: Int): ByteArray { val buffer = ByteArray(pCount) for (i in 0 until pCount) { buffer[i] = readByte() } return buffer } val inputStream: ByteArrayInputStream get() = ByteArrayInputStream(stream, currentOffset, stream.size - currentOffset) fun skipBytes(bytes: Int) { currentOffset += bytes } /** * returns if a certain flag is on * * @param flags * @param flag * @return if a flag has been set */ fun hasFlag(flags: Int, flag: Int): Boolean { return flags and flag == flag } fun moreToRead(): Int { return stream.size - currentOffset } fun unsignedInt(): Long { val i = readUInt32() return i.toLong() and 0xffffffffL } }
src/main/java/nl/shadowlink/tools/io/ByteReader.kt
2594745215
package com.github.openweather.repository import com.github.openweather.business.CurrentWeather import com.github.openweather.client.OpenWeatherClient import com.github.rest.RestRepository import org.springframework.stereotype.Repository @Repository open class CurrentWeatherRepository : RestRepository<CurrentWeather, Int> { override fun find(key: Int): CurrentWeather { return OpenWeatherClient.getCurrentWeatherByCityId(key, null).orElse(null) } fun find(key: Int, lang : String?): CurrentWeather { return OpenWeatherClient.getCurrentWeatherByCityId(key, lang).orElse(null) } fun findByCoordinates(lat : Double, lon : Double, lang : String?): CurrentWeather { return OpenWeatherClient.getCurrentWeatherByCoordinates(lat, lon, lang).orElse(null) } }
src/main/kotlin/com/github/openweather/repository/CurrentWeatherRepository.kt
2199582577
package com.ogoutay.robomocki3.kotlin import android.app.Activity import android.widget.TextView import com.ogoutay.robomocki3.BuildConfig import com.ogoutay.robomocki3.R import com.ogoutay.robomocki3.activities.MainActivity import com.ogoutay.robomocki3.managers.ExampleManager import junit.framework.Assert.assertEquals import org.joor.Reflect import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito import org.mockito.MockitoAnnotations import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config /** * Demonstrates how to mock a typed method and return something else */ @RunWith(RobolectricTestRunner::class) @Config(constants = BuildConfig::class, sdk = intArrayOf(21), packageName = BuildConfig.APPLICATION_ID) class MainActivityMockTest { companion object { private const val MOCKED_VALUE = "toto" } private lateinit var activity: Activity @Mock private lateinit var mockExampleManager: ExampleManager @Before fun setUp() { //Building the activity val activityController = Robolectric.buildActivity(MainActivity::class.java) //Mocking ExampleManager within the Activity MockitoAnnotations.initMocks(this) Mockito.`when`(mockExampleManager.serviceName).thenReturn(MOCKED_VALUE) Reflect.on(activityController.get()).set("mExampleManager", mockExampleManager) //Launching the Activity activityController.setup() activity = activityController.get() } @Test fun testMainActivity() { //Verify this method has been called Mockito.verify(mockExampleManager).serviceName //Assert the TextView has the mocked value assertEquals(MOCKED_VALUE, activity.findViewById<TextView>(R.id.textView).text) } }
app/src/test/java/com/ogoutay/robomocki3/kotlin/MainActivityMockTest.kt
2064168537
package expo.modules.manifests.core import expo.modules.jsonutils.require import org.json.JSONException import org.json.JSONObject class BareManifest(json: JSONObject) : BaseLegacyManifest(json) { /** * A UUID for this manifest. */ @Throws(JSONException::class) fun getID(): String = json.require("id") @Throws(JSONException::class) fun getCommitTimeLong(): Long = json.require("commitTime") }
packages/expo-manifests/android/src/main/java/expo/modules/manifests/core/BareManifest.kt
110677415
package info.nightscout.androidaps import android.content.Context import android.content.SharedPreferences import info.nightscout.androidaps.interaction.utils.Persistence import info.nightscout.androidaps.interaction.utils.WearUtil import info.nightscout.androidaps.testing.mockers.WearUtilMocker import info.nightscout.androidaps.testing.mocks.SharedPreferencesMock import info.nightscout.androidaps.utils.DateUtil import info.nightscout.shared.logging.AAPSLoggerTest import info.nightscout.shared.sharedPreferences.SP import org.junit.Before import org.junit.Rule import org.mockito.ArgumentMatchers import org.mockito.Mock import org.mockito.Mockito import org.mockito.junit.MockitoJUnit import org.mockito.junit.MockitoRule import java.util.* open class TestBase { @Mock lateinit var context: Context @Mock lateinit var sp: SP @Mock lateinit var dateUtil: DateUtil val aapsLogger = AAPSLoggerTest() val wearUtil: WearUtil = Mockito.spy(WearUtil()) val wearUtilMocker = WearUtilMocker(wearUtil) lateinit var persistence: Persistence private val mockedSharedPrefs: HashMap<String, SharedPreferences> = HashMap() @Before fun setup() { Mockito.doAnswer { invocation -> val key = invocation.getArgument<String>(0) if (mockedSharedPrefs.containsKey(key)) { return@doAnswer mockedSharedPrefs[key] } else { val newPrefs = SharedPreferencesMock() mockedSharedPrefs[key] = newPrefs return@doAnswer newPrefs } }.`when`(context).getSharedPreferences(ArgumentMatchers.anyString(), ArgumentMatchers.anyInt()) wearUtilMocker.prepareMockNoReal() wearUtil.aapsLogger = aapsLogger wearUtil.context = context persistence = Mockito.spy(Persistence(aapsLogger, dateUtil, sp)) } // Add a JUnit rule that will setup the @Mock annotated vars and log. // Another possibility would be to add `MockitoAnnotations.initMocks(this) to the setup method. @get:Rule val mockitoRule: MockitoRule = MockitoJUnit.rule() @Before fun setupLocale() { Locale.setDefault(Locale.ENGLISH) System.setProperty("disableFirebase", "true") } // Workaround for Kotlin nullability. // https://medium.com/@elye.project/befriending-kotlin-and-mockito-1c2e7b0ef791 // https://stackoverflow.com/questions/30305217/is-it-possible-to-use-mockito-in-kotlin fun <T> anyObject(): T { Mockito.any<T>() return uninitialized() } @Suppress("Unchecked_Cast") fun <T> uninitialized(): T = null as T }
wear/src/test/java/info/nightscout/androidaps/TestBase.kt
2356669162
package info.nightscout.androidaps.plugins.pump.medtronic import android.content.ComponentName import android.content.Context import android.content.ServiceConnection import android.os.IBinder import android.os.SystemClock import androidx.preference.Preference import dagger.android.HasAndroidInjector import info.nightscout.androidaps.activities.ErrorHelperActivity.Companion.runAlarm import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.events.EventRefreshOverview import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.interfaces.PumpSync.TemporaryBasalType import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.common.ManufacturerType import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.plugins.pump.common.PumpPluginAbstract import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus import info.nightscout.androidaps.plugins.pump.common.defs.PumpDriverState import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.plugins.pump.common.events.EventRefreshButtonState import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkPumpDevice import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkPumpInfo import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.ResetRileyLinkConfigurationTask import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.ServiceTaskExecutor import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.WakeAndTuneTask import info.nightscout.androidaps.plugins.pump.common.sync.PumpDbEntryTBR import info.nightscout.androidaps.plugins.pump.common.sync.PumpSyncEntriesCreator import info.nightscout.androidaps.plugins.pump.common.sync.PumpSyncStorage import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil import info.nightscout.androidaps.plugins.pump.common.utils.ProfileUtil import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntry import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryResult import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BasalProfile import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BasalProfile.Companion.getProfilesByHourToString import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BasalProfileEntry import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.TempBasalPair import info.nightscout.androidaps.plugins.pump.medtronic.defs.* import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType.Companion.getSettings import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicPumpConfigurationChanged import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicPumpValuesChanged import info.nightscout.androidaps.plugins.pump.medtronic.service.RileyLinkMedtronicService import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil.Companion.isSame import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.TimeChangeType import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.shared.sharedPreferences.SP import org.joda.time.LocalDateTime import java.util.* import javax.inject.Inject import javax.inject.Singleton import kotlin.math.abs import kotlin.math.floor /** * Created by andy on 23.04.18. * * @author Andy Rozman ([email protected]) */ @Singleton class MedtronicPumpPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, rxBus: RxBus, context: Context, rh: ResourceHelper, activePlugin: ActivePlugin, sp: SP, commandQueue: CommandQueue, fabricPrivacy: FabricPrivacy, private val medtronicUtil: MedtronicUtil, private val medtronicPumpStatus: MedtronicPumpStatus, private val medtronicHistoryData: MedtronicHistoryData, private val rileyLinkServiceData: RileyLinkServiceData, private val serviceTaskExecutor: ServiceTaskExecutor, dateUtil: DateUtil, aapsSchedulers: AapsSchedulers, pumpSync: PumpSync, pumpSyncStorage: PumpSyncStorage ) : PumpPluginAbstract( PluginDescription() // .mainType(PluginType.PUMP) // .fragmentClass(MedtronicFragment::class.java.name) // .pluginIcon(R.drawable.ic_veo_128) .pluginName(R.string.medtronic_name) // .shortName(R.string.medtronic_name_short) // .preferencesId(R.xml.pref_medtronic) .description(R.string.description_pump_medtronic), // PumpType.MEDTRONIC_522_722, // we default to most basic model, correct model from config is loaded later injector, rh, aapsLogger, commandQueue, rxBus, activePlugin, sp, context, fabricPrivacy, dateUtil, aapsSchedulers, pumpSync, pumpSyncStorage ), Pump, RileyLinkPumpDevice, PumpSyncEntriesCreator { private var rileyLinkMedtronicService: RileyLinkMedtronicService? = null // variables for handling statuses and history private var firstRun = true private var isRefresh = false private val statusRefreshMap: MutableMap<MedtronicStatusRefreshType, Long> = mutableMapOf() private var isInitialized = false private var lastPumpHistoryEntry: PumpHistoryEntry? = null private val busyTimestamps: MutableList<Long> = ArrayList() private var hasTimeDateOrTimeZoneChanged = false private var isBusy = false override fun onStart() { aapsLogger.debug(LTag.PUMP, deviceID() + " started. (V2.0006)") serviceConnection = object : ServiceConnection { override fun onServiceDisconnected(name: ComponentName) { aapsLogger.debug(LTag.PUMP, "RileyLinkMedtronicService is disconnected") //rileyLinkMedtronicService = null } override fun onServiceConnected(name: ComponentName, service: IBinder) { aapsLogger.debug(LTag.PUMP, "RileyLinkMedtronicService is connected") val mLocalBinder = service as RileyLinkMedtronicService.LocalBinder rileyLinkMedtronicService = mLocalBinder.serviceInstance isServiceSet = true rileyLinkMedtronicService?.verifyConfiguration() Thread { for (i in 0..19) { SystemClock.sleep(5000) aapsLogger.debug(LTag.PUMP, "Starting Medtronic-RileyLink service") if (rileyLinkMedtronicService?.setNotInPreInit() == true) { break } } }.start() } } super.onStart() } override fun updatePreferenceSummary(pref: Preference) { super.updatePreferenceSummary(pref) if (pref.key == rh.gs(R.string.key_rileylink_mac_address)) { val value = sp.getStringOrNull(R.string.key_rileylink_mac_address, null) pref.summary = value ?: rh.gs(R.string.not_set_short) } } private val logPrefix: String get() = "MedtronicPumpPlugin::" override fun initPumpStatusData() { medtronicPumpStatus.lastConnection = sp.getLong(RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, 0L) medtronicPumpStatus.lastDataTime = medtronicPumpStatus.lastConnection medtronicPumpStatus.previousConnection = medtronicPumpStatus.lastConnection //if (rileyLinkMedtronicService != null) rileyLinkMedtronicService.verifyConfiguration(); aapsLogger.debug(LTag.PUMP, "initPumpStatusData: $medtronicPumpStatus") // this is only thing that can change, by being configured pumpDescription.maxTempAbsolute = if (medtronicPumpStatus.maxBasal != null) medtronicPumpStatus.maxBasal!! else 35.0 // set first Medtronic Pump Start if (!sp.contains(MedtronicConst.Statistics.FirstPumpStart)) { sp.putLong(MedtronicConst.Statistics.FirstPumpStart, System.currentTimeMillis()) } migrateSettings() pumpSyncStorage.initStorage() this.displayConnectionMessages = false } override fun triggerPumpConfigurationChangedEvent() { rxBus.send(EventMedtronicPumpConfigurationChanged()) } private fun migrateSettings() { if ("US (916 MHz)" == sp.getString(MedtronicConst.Prefs.PumpFrequency, "US (916 MHz)")) { sp.putString(MedtronicConst.Prefs.PumpFrequency, rh.gs(R.string.key_medtronic_pump_frequency_us_ca)) } val encoding = sp.getString(MedtronicConst.Prefs.Encoding, "RileyLink 4b6b Encoding") if ("RileyLink 4b6b Encoding" == encoding) { sp.putString(MedtronicConst.Prefs.Encoding, rh.gs(R.string.key_medtronic_pump_encoding_4b6b_rileylink)) } if ("Local 4b6b Encoding" == encoding) { sp.putString(MedtronicConst.Prefs.Encoding, rh.gs(R.string.key_medtronic_pump_encoding_4b6b_local)) } } override fun hasService(): Boolean { return true } override fun onStartScheduledPumpActions() { // check status every minute (if any status needs refresh we send readStatus command) Thread { do { SystemClock.sleep(60000) if (this.isInitialized) { val statusRefresh = synchronized(statusRefreshMap) { HashMap(statusRefreshMap) } if (doWeHaveAnyStatusNeededRefreshing(statusRefresh)) { if (!commandQueue.statusInQueue()) { commandQueue.readStatus(rh.gs(R.string.scheduled_status_refresh), null) } } clearBusyQueue() } } while (serviceRunning) }.start() } override val serviceClass: Class<*> = RileyLinkMedtronicService::class.java override val pumpStatusData: PumpStatus get() = medtronicPumpStatus override fun deviceID(): String = "Medtronic" override val isFakingTempsByExtendedBoluses: Boolean = false override fun canHandleDST(): Boolean = false private var isServiceSet: Boolean = false override val rileyLinkService: RileyLinkMedtronicService? get() = rileyLinkMedtronicService override val pumpInfo: RileyLinkPumpInfo get() = RileyLinkPumpInfo( rh.gs(if (medtronicPumpStatus.pumpFrequency == "medtronic_pump_frequency_us_ca") R.string.medtronic_pump_frequency_us_ca else R.string.medtronic_pump_frequency_worldwide), if (!medtronicUtil.isModelSet) "???" else "Medtronic " + medtronicPumpStatus.medtronicDeviceType.pumpModel, medtronicPumpStatus.serialNumber ) override val lastConnectionTimeMillis: Long get() = medtronicPumpStatus.lastConnection override fun setLastCommunicationToNow() { medtronicPumpStatus.setLastCommunicationToNow() } override fun isInitialized(): Boolean { if (displayConnectionMessages) aapsLogger.debug(LTag.PUMP, "MedtronicPumpPlugin::isInitialized") return isServiceSet && isInitialized } override fun setBusy(busy: Boolean) { isBusy = busy } override fun isBusy(): Boolean { if (displayConnectionMessages) aapsLogger.debug(LTag.PUMP, "MedtronicPumpPlugin::isBusy") if (isServiceSet) { if (isBusy) return true if (busyTimestamps.size > 0) { clearBusyQueue() return busyTimestamps.size > 0 } } return false } @Synchronized private fun clearBusyQueue() { if (busyTimestamps.size == 0) { return } val deleteFromQueue: MutableSet<Long> = HashSet() for (busyTimestamp in busyTimestamps) { if (System.currentTimeMillis() > busyTimestamp) { deleteFromQueue.add(busyTimestamp) } } if (deleteFromQueue.size == busyTimestamps.size) { busyTimestamps.clear() setEnableCustomAction(MedtronicCustomActionType.ClearBolusBlock, false) } if (deleteFromQueue.size > 0) { busyTimestamps.removeAll(deleteFromQueue) } } override fun isConnected(): Boolean { if (displayConnectionMessages) aapsLogger.debug(LTag.PUMP, "MedtronicPumpPlugin::isConnected") return isServiceSet && rileyLinkMedtronicService?.isInitialized == true } override fun isConnecting(): Boolean { if (displayConnectionMessages) aapsLogger.debug(LTag.PUMP, "MedtronicPumpPlugin::isConnecting") return !isServiceSet || rileyLinkMedtronicService?.isInitialized != true } override fun getPumpStatus(reason: String) { var needRefresh = true if (firstRun) { needRefresh = initializePump() /*!isRefresh*/ } else { refreshAnyStatusThatNeedsToBeRefreshed() } if (needRefresh) rxBus.send(EventMedtronicPumpValuesChanged()) } fun resetStatusState() { firstRun = true isRefresh = true }// private val isPumpNotReachable: Boolean get() { val rileyLinkServiceState = rileyLinkServiceData.rileyLinkServiceState if (rileyLinkServiceState != RileyLinkServiceState.PumpConnectorReady && rileyLinkServiceState != RileyLinkServiceState.RileyLinkReady && rileyLinkServiceState != RileyLinkServiceState.TuneUpDevice ) { aapsLogger.debug(LTag.PUMP, "RileyLink unreachable.") return false } return rileyLinkMedtronicService?.deviceCommunicationManager?.isDeviceReachable != true } private fun refreshAnyStatusThatNeedsToBeRefreshed() { val statusRefresh = synchronized(statusRefreshMap) { HashMap(statusRefreshMap) } if (!doWeHaveAnyStatusNeededRefreshing(statusRefresh)) { return } var resetTime = false if (isPumpNotReachable) { aapsLogger.error("Pump unreachable.") medtronicUtil.sendNotification(MedtronicNotificationType.PumpUnreachable, rh, rxBus) return } medtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus) if (hasTimeDateOrTimeZoneChanged) { checkTimeAndOptionallySetTime() // read time if changed, set new time hasTimeDateOrTimeZoneChanged = false } // execute val refreshTypesNeededToReschedule: MutableSet<MedtronicStatusRefreshType> = mutableSetOf() for ((key, value) in statusRefresh) { if (value > 0 && System.currentTimeMillis() > value) { @Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") when (key) { MedtronicStatusRefreshType.PumpHistory -> { readPumpHistory() } MedtronicStatusRefreshType.PumpTime -> { checkTimeAndOptionallySetTime() refreshTypesNeededToReschedule.add(key) resetTime = true } MedtronicStatusRefreshType.BatteryStatus, MedtronicStatusRefreshType.RemainingInsulin -> { rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(key.getCommandType(medtronicUtil.medtronicPumpModel)!!) refreshTypesNeededToReschedule.add(key) resetTime = true } MedtronicStatusRefreshType.Configuration -> { rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(key.getCommandType(medtronicUtil.medtronicPumpModel)!!) resetTime = true } } } // reschedule for (refreshType2 in refreshTypesNeededToReschedule) { scheduleNextRefresh(refreshType2) } } if (resetTime) medtronicPumpStatus.setLastCommunicationToNow() } private fun doWeHaveAnyStatusNeededRefreshing(statusRefresh: Map<MedtronicStatusRefreshType, Long>): Boolean { for ((_, value) in statusRefresh) { if (value > 0 && System.currentTimeMillis() > value) { return true } } return hasTimeDateOrTimeZoneChanged } private fun setRefreshButtonEnabled(enabled: Boolean) { rxBus.send(EventRefreshButtonState(enabled)) } private fun initializePump(): Boolean { if (!isServiceSet) return false aapsLogger.info(LTag.PUMP, logPrefix + "initializePump - start") rileyLinkMedtronicService?.deviceCommunicationManager?.setDoWakeUpBeforeCommand(false) setRefreshButtonEnabled(false) if (isRefresh) { if (isPumpNotReachable) { aapsLogger.error(logPrefix + "initializePump::Pump unreachable.") medtronicUtil.sendNotification(MedtronicNotificationType.PumpUnreachable, rh, rxBus) setRefreshButtonEnabled(true) return true } medtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus) } // model (once) if (!medtronicUtil.isModelSet) { rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(MedtronicCommandType.PumpModel) } else { if (medtronicPumpStatus.medtronicDeviceType !== medtronicUtil.medtronicPumpModel) { aapsLogger.warn(LTag.PUMP, logPrefix + "Configured pump is not the same as one detected.") medtronicUtil.sendNotification(MedtronicNotificationType.PumpTypeNotSame, rh, rxBus) } } pumpState = PumpDriverState.Connected // time (1h) checkTimeAndOptionallySetTime() readPumpHistory() // remaining insulin (>50 = 4h; 50-20 = 1h; 15m) rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(MedtronicCommandType.GetRemainingInsulin) scheduleNextRefresh(MedtronicStatusRefreshType.RemainingInsulin, 10) // remaining power (1h) rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(MedtronicCommandType.GetBatteryStatus) scheduleNextRefresh(MedtronicStatusRefreshType.BatteryStatus, 20) // configuration (once and then if history shows config changes) rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(getSettings(medtronicUtil.medtronicPumpModel)) // read profile (once, later its controlled by isThisProfileSet method) basalProfiles val errorCount = rileyLinkMedtronicService?.medtronicUIComm?.invalidResponsesCount ?: 0 if (errorCount >= 5) { aapsLogger.error("Number of error counts was 5 or more. Starting tuning.") setRefreshButtonEnabled(true) serviceTaskExecutor.startTask(WakeAndTuneTask(injector)) return true } medtronicPumpStatus.setLastCommunicationToNow() setRefreshButtonEnabled(true) if (!isRefresh) { pumpState = PumpDriverState.Initialized } isInitialized = true // this.pumpState = PumpDriverState.Initialized; firstRun = false return true } private val basalProfiles: Unit get() { val medtronicUITask = rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(MedtronicCommandType.GetBasalProfileSTD) if (medtronicUITask?.responseType === MedtronicUIResponseType.Error) { rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(MedtronicCommandType.GetBasalProfileSTD) } } @Synchronized override fun isThisProfileSet(profile: Profile): Boolean { aapsLogger.debug(LTag.PUMP, "isThisProfileSet: basalInitialized=" + medtronicPumpStatus.basalProfileStatus) if (!isInitialized) return true if (medtronicPumpStatus.basalProfileStatus === BasalProfileStatus.NotInitialized) { // this shouldn't happen, but if there was problem we try again basalProfiles return isProfileSame(profile) } else if (medtronicPumpStatus.basalProfileStatus === BasalProfileStatus.ProfileChanged) { return false } return medtronicPumpStatus.basalProfileStatus !== BasalProfileStatus.ProfileOK || isProfileSame(profile) } private fun isProfileSame(profile: Profile): Boolean { var invalid = false val basalsByHour: DoubleArray? = medtronicPumpStatus.basalsByHour aapsLogger.debug( LTag.PUMP, "Current Basals (h): " + (basalsByHour?.let { getProfilesByHourToString(it) } ?: "null")) // int index = 0; if (basalsByHour == null) return true // we don't want to set profile again, unless we are sure val stringBuilder = StringBuilder("Requested Basals (h): ") stringBuilder.append(ProfileUtil.getBasalProfilesDisplayableAsStringOfArray(profile, this.pumpType)) for (basalValue in profile.getBasalValues()) { val basalValueValue = pumpDescription.pumpType.determineCorrectBasalSize(basalValue.value) val hour = basalValue.timeAsSeconds / (60 * 60) if (!isSame(basalsByHour[hour], basalValueValue)) { invalid = true } // stringBuilder.append(String.format(Locale.ENGLISH, "%.3f", basalValueValue)) // stringBuilder.append(" ") } aapsLogger.debug(LTag.PUMP, stringBuilder.toString()) if (!invalid) { aapsLogger.debug(LTag.PUMP, "Basal profile is same as AAPS one.") } else { aapsLogger.debug(LTag.PUMP, "Basal profile on Pump is different than the AAPS one.") } return !invalid } override fun lastDataTime(): Long { return if (medtronicPumpStatus.lastConnection > 0) { medtronicPumpStatus.lastConnection } else System.currentTimeMillis() } override val baseBasalRate: Double get() = medtronicPumpStatus.basalProfileForHour override val reservoirLevel: Double get() = medtronicPumpStatus.reservoirRemainingUnits override val batteryLevel: Int get() = medtronicPumpStatus.batteryRemaining override fun triggerUIChange() { rxBus.send(EventMedtronicPumpValuesChanged()) } override fun generateTempId(objectA: Any): Long { val timestamp: Long = objectA as Long return DateTimeUtil.toATechDate(timestamp) } private var bolusDeliveryType = BolusDeliveryType.Idle private enum class BolusDeliveryType { Idle, // DeliveryPrepared, // Delivering, // CancelDelivery } private fun checkTimeAndOptionallySetTime() { aapsLogger.info(LTag.PUMP, "MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Start") setRefreshButtonEnabled(false) if (isPumpNotReachable) { aapsLogger.debug(LTag.PUMP, "MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Pump Unreachable.") setRefreshButtonEnabled(true) return } medtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus) rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(MedtronicCommandType.GetRealTimeClock) var clock = medtronicUtil.pumpTime if (clock == null) { // retry rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(MedtronicCommandType.GetRealTimeClock) clock = medtronicUtil.pumpTime } if (clock == null) return val timeDiff = abs(clock.timeDifference) if (timeDiff > 20) { if (clock.localDeviceTime.year <= 2015 || timeDiff <= 24 * 60 * 60) { aapsLogger.info(LTag.PUMP, String.format(Locale.ENGLISH, "MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Time difference is %d s. Set time on pump.", timeDiff)) rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(MedtronicCommandType.SetRealTimeClock) if (clock.timeDifference == 0) { val notification = Notification(Notification.INSIGHT_DATE_TIME_UPDATED, rh.gs(R.string.pump_time_updated), Notification.INFO, 60) rxBus.send(EventNewNotification(notification)) } } else { if (clock.localDeviceTime.year > 2015) { aapsLogger.error(String.format(Locale.ENGLISH, "MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Time difference over 24h requested [diff=%d s]. Doing nothing.", timeDiff)) medtronicUtil.sendNotification(MedtronicNotificationType.TimeChangeOver24h, rh, rxBus) } } } else { aapsLogger.info(LTag.PUMP, String.format(Locale.ENGLISH, "MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Time difference is %d s. Do nothing.", timeDiff)) } scheduleNextRefresh(MedtronicStatusRefreshType.PumpTime, 0) } @Synchronized override fun deliverBolus(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult { aapsLogger.info(LTag.PUMP, "MedtronicPumpPlugin::deliverBolus - " + BolusDeliveryType.DeliveryPrepared) setRefreshButtonEnabled(false) if (detailedBolusInfo.insulin > medtronicPumpStatus.reservoirRemainingUnits) { return PumpEnactResult(injector) // .success(false) // .enacted(false) // .comment( rh.gs( R.string.medtronic_cmd_bolus_could_not_be_delivered_no_insulin, medtronicPumpStatus.reservoirRemainingUnits, detailedBolusInfo.insulin ) ) } bolusDeliveryType = BolusDeliveryType.DeliveryPrepared if (isPumpNotReachable) { aapsLogger.debug(LTag.PUMP, "MedtronicPumpPlugin::deliverBolus - Pump Unreachable.") return setNotReachable(isBolus = true, success = false) } medtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus) if (bolusDeliveryType == BolusDeliveryType.CancelDelivery) { // LOG.debug("MedtronicPumpPlugin::deliverBolus - Delivery Canceled."); return setNotReachable(isBolus = true, success = true) } // LOG.debug("MedtronicPumpPlugin::deliverBolus - Starting wait period."); val sleepTime = sp.getInt(MedtronicConst.Prefs.BolusDelay, 10) * 1000 SystemClock.sleep(sleepTime.toLong()) return if (bolusDeliveryType == BolusDeliveryType.CancelDelivery) { // LOG.debug("MedtronicPumpPlugin::deliverBolus - Delivery Canceled, before wait period."); setNotReachable(isBolus = true, success = true) } else try { bolusDeliveryType = BolusDeliveryType.Delivering // LOG.debug("MedtronicPumpPlugin::deliverBolus - Start delivery"); val responseTask = rileyLinkMedtronicService?.medtronicUIComm?.executeCommand( MedtronicCommandType.SetBolus, arrayListOf(detailedBolusInfo.insulin) ) val response = responseTask?.result as Boolean? setRefreshButtonEnabled(true) // LOG.debug("MedtronicPumpPlugin::deliverBolus - Response: {}", response); return if (response == null || !response) { PumpEnactResult(injector) // .success(bolusDeliveryType == BolusDeliveryType.CancelDelivery) // .enacted(false) // .comment(R.string.medtronic_cmd_bolus_could_not_be_delivered) } else { if (bolusDeliveryType == BolusDeliveryType.CancelDelivery) { // LOG.debug("MedtronicPumpPlugin::deliverBolus - Delivery Canceled after Bolus started."); Thread { SystemClock.sleep(2000) runAlarm(context, rh.gs(R.string.medtronic_cmd_cancel_bolus_not_supported), rh.gs(R.string.medtronic_warning), R.raw.boluserror) }.start() } val now = System.currentTimeMillis() detailedBolusInfo.timestamp = now pumpSyncStorage.addBolusWithTempId(detailedBolusInfo, true, this) // we subtract insulin, exact amount will be visible with next remainingInsulin update. medtronicPumpStatus.reservoirRemainingUnits = medtronicPumpStatus.reservoirRemainingUnits - detailedBolusInfo.insulin incrementStatistics(if (detailedBolusInfo.bolusType === DetailedBolusInfo.BolusType.SMB) MedtronicConst.Statistics.SMBBoluses else MedtronicConst.Statistics.StandardBoluses) // calculate time for bolus and set driver to busy for that time val bolusTime = (detailedBolusInfo.insulin * 42.0).toInt() val time = now + bolusTime * 1000 busyTimestamps.add(time) setEnableCustomAction(MedtronicCustomActionType.ClearBolusBlock, true) PumpEnactResult(injector).success(true) // .enacted(true) // .bolusDelivered(detailedBolusInfo.insulin) // .carbsDelivered(detailedBolusInfo.carbs) } } finally { finishAction("Bolus") bolusDeliveryType = BolusDeliveryType.Idle } // LOG.debug("MedtronicPumpPlugin::deliverBolus - End wait period. Start delivery"); } @Suppress("SameParameterValue") private fun setNotReachable(isBolus: Boolean, success: Boolean): PumpEnactResult { setRefreshButtonEnabled(true) if (isBolus) bolusDeliveryType = BolusDeliveryType.Idle return if (success) PumpEnactResult(injector).success(true).enacted(false) else PumpEnactResult(injector).success(false).enacted(false).comment(R.string.medtronic_pump_status_pump_unreachable) } override fun stopBolusDelivering() { bolusDeliveryType = BolusDeliveryType.CancelDelivery // if (isLoggingEnabled()) // LOG.warn("MedtronicPumpPlugin::deliverBolus - Stop Bolus Delivery."); } private fun incrementStatistics(statsKey: String) { var currentCount = sp.getLong(statsKey, 0L) currentCount++ sp.putLong(statsKey, currentCount) } // if enforceNew===true current temp basal is canceled and new TBR set (duration is prolonged), // if false and the same rate is requested enacted=false and success=true is returned and TBR is not changed @Synchronized override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: TemporaryBasalType): PumpEnactResult { setRefreshButtonEnabled(false) if (isPumpNotReachable) { setRefreshButtonEnabled(true) return PumpEnactResult(injector) // .success(false) // .enacted(false) // .comment(R.string.medtronic_pump_status_pump_unreachable) } medtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus) aapsLogger.info(LTag.PUMP, logPrefix + "setTempBasalAbsolute: rate: " + absoluteRate + ", duration=" + durationInMinutes) // read current TBR val tbrCurrent = readTBR() if (tbrCurrent == null) { aapsLogger.warn(LTag.PUMP, logPrefix + "setTempBasalAbsolute - Could not read current TBR, canceling operation.") finishAction("TBR") return PumpEnactResult(injector).success(false).enacted(false) .comment(R.string.medtronic_cmd_cant_read_tbr) } else { aapsLogger.info(LTag.PUMP, logPrefix + "setTempBasalAbsolute: Current Basal: duration: " + tbrCurrent.durationMinutes + " min, rate=" + tbrCurrent.insulinRate) } if (!enforceNew) { if (isSame(tbrCurrent.insulinRate, absoluteRate)) { var sameRate = true if (isSame(0.0, absoluteRate) && durationInMinutes > 0) { // if rate is 0.0 and duration>0 then the rate is not the same sameRate = false } if (sameRate) { aapsLogger.info(LTag.PUMP, logPrefix + "setTempBasalAbsolute - No enforceNew and same rate. Exiting.") finishAction("TBR") return PumpEnactResult(injector).success(true).enacted(false) } } // if not the same rate, we cancel and start new } // if TBR is running we will cancel it. if (tbrCurrent.insulinRate > 0.0 && tbrCurrent.durationMinutes > 0) { aapsLogger.info(LTag.PUMP, logPrefix + "setTempBasalAbsolute - TBR running - so canceling it.") // CANCEL val responseTask2 = rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(MedtronicCommandType.CancelTBR) val response = responseTask2?.result as Boolean? if (response == null || !response) { aapsLogger.error(logPrefix + "setTempBasalAbsolute - Cancel TBR failed.") finishAction("TBR") return PumpEnactResult(injector).success(false).enacted(false) .comment(R.string.medtronic_cmd_cant_cancel_tbr_stop_op) } else { //cancelTBRWithTemporaryId() aapsLogger.info(LTag.PUMP, logPrefix + "setTempBasalAbsolute - Current TBR cancelled.") } } // now start new TBR val responseTask = rileyLinkMedtronicService?.medtronicUIComm?.executeCommand( MedtronicCommandType.SetTemporaryBasal, arrayListOf(absoluteRate, durationInMinutes) ) val response = responseTask?.result as Boolean? aapsLogger.info(LTag.PUMP, logPrefix + "setTempBasalAbsolute - setTBR. Response: " + response) return if (response == null || !response) { finishAction("TBR") PumpEnactResult(injector).success(false).enacted(false) // .comment(R.string.medtronic_cmd_tbr_could_not_be_delivered) } else { medtronicPumpStatus.tempBasalStart = System.currentTimeMillis() medtronicPumpStatus.tempBasalAmount = absoluteRate medtronicPumpStatus.tempBasalLength = durationInMinutes val tempData = PumpDbEntryTBR(absoluteRate, true, durationInMinutes * 60, tbrType) medtronicPumpStatus.runningTBRWithTemp = tempData pumpSyncStorage.addTemporaryBasalRateWithTempId(tempData, true, this) incrementStatistics(MedtronicConst.Statistics.TBRsSet) finishAction("TBR") PumpEnactResult(injector).success(true).enacted(true) // .absolute(absoluteRate).duration(durationInMinutes) } } @Deprecated("Not used, TBRs fixed in history, should be removed.") private fun cancelTBRWithTemporaryId() { val tbrs: MutableList<PumpDbEntryTBR> = pumpSyncStorage.getTBRs() if (tbrs.size > 0 && medtronicPumpStatus.runningTBRWithTemp != null) { aapsLogger.info(LTag.PUMP, logPrefix + "cancelTBRWithTemporaryId - TBR items: ${tbrs.size}") var item: PumpDbEntryTBR? = null if (tbrs.size == 1) { item = tbrs[0] } else { for (tbr in tbrs) { if (tbr.date == medtronicPumpStatus.runningTBRWithTemp!!.date) { item = tbr break } } } if (item != null) { aapsLogger.debug(LTag.PUMP, "DD: cancelTBRWithTemporaryId: tempIdEntry=${item}") val differenceS = (System.currentTimeMillis() - item.date) / 1000 aapsLogger.debug( LTag.PUMP, "syncTemporaryBasalWithTempId " + "[date=${item.date}, " + "rate=${item.rate}, " + "duration=${differenceS} s, " + "isAbsolute=${!item.isAbsolute}, temporaryId=${item.temporaryId}, " + "pumpId=NO, pumpType=${medtronicPumpStatus.pumpType}, " + "pumpSerial=${medtronicPumpStatus.serialNumber}]" ) val result = pumpSync.syncTemporaryBasalWithTempId( timestamp = item.date, rate = item.rate, duration = differenceS * 1000L, isAbsolute = item.isAbsolute, temporaryId = item.temporaryId, type = item.tbrType, pumpId = null, pumpType = medtronicPumpStatus.pumpType, pumpSerial = medtronicPumpStatus.serialNumber ) aapsLogger.debug(LTag.PUMP, "syncTemporaryBasalWithTempId - Result: $result") } } else { aapsLogger.info(LTag.PUMP, logPrefix + "cancelTBRWithTemporaryId - TBR items: ${tbrs.size}, runningTBRWithTemp=${medtronicPumpStatus.runningTBRWithTemp}") } if (medtronicPumpStatus.runningTBRWithTemp != null) { medtronicPumpStatus.runningTBRWithTemp = null } } @Synchronized override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: TemporaryBasalType): PumpEnactResult { return if (percent == 0) { setTempBasalAbsolute(0.0, durationInMinutes, profile, enforceNew, tbrType) } else { var absoluteValue = profile.getBasal() * (percent / 100.0) absoluteValue = pumpDescription.pumpType.determineCorrectBasalSize(absoluteValue) aapsLogger.warn( LTag.PUMP, "setTempBasalPercent [MedtronicPumpPlugin] - You are trying to use setTempBasalPercent with percent other then 0% ($percent). This will start setTempBasalAbsolute, with calculated value ($absoluteValue). Result might not be 100% correct." ) setTempBasalAbsolute(absoluteValue, durationInMinutes, profile, enforceNew, tbrType) } } private fun finishAction(overviewKey: String?) { if (overviewKey != null) rxBus.send(EventRefreshOverview(overviewKey, false)) triggerUIChange() setRefreshButtonEnabled(true) } private fun readPumpHistory() { // if (isLoggingEnabled()) // LOG.error(getLogPrefix() + "readPumpHistory WIP."); readPumpHistoryLogic() scheduleNextRefresh(MedtronicStatusRefreshType.PumpHistory) if (medtronicHistoryData.hasRelevantConfigurationChanged()) { scheduleNextRefresh(MedtronicStatusRefreshType.Configuration, -1) } if (medtronicHistoryData.hasPumpTimeChanged()) { scheduleNextRefresh(MedtronicStatusRefreshType.PumpTime, -1) } if (medtronicPumpStatus.basalProfileStatus !== BasalProfileStatus.NotInitialized && medtronicHistoryData.hasBasalProfileChanged() ) { medtronicHistoryData.processLastBasalProfileChange(pumpDescription.pumpType, medtronicPumpStatus) } val previousState = pumpState if (medtronicHistoryData.isPumpSuspended()) { pumpState = PumpDriverState.Suspended aapsLogger.debug(LTag.PUMP, logPrefix + "isPumpSuspended: true") } else { if (previousState === PumpDriverState.Suspended) { pumpState = PumpDriverState.Ready } aapsLogger.debug(LTag.PUMP, logPrefix + "isPumpSuspended: false") } medtronicHistoryData.processNewHistoryData() medtronicHistoryData.finalizeNewHistoryRecords() } private fun readPumpHistoryLogic() { val debugHistory = false val targetDate: LocalDateTime? if (lastPumpHistoryEntry == null) { // first read if (debugHistory) aapsLogger.debug(LTag.PUMP, logPrefix + "readPumpHistoryLogic(): lastPumpHistoryEntry: null") val lastPumpHistoryEntryTime = lastPumpEntryTime var timeMinus36h = LocalDateTime() timeMinus36h = timeMinus36h.minusHours(36) medtronicHistoryData.setIsInInit(true) if (lastPumpHistoryEntryTime == 0L) { if (debugHistory) aapsLogger.debug(LTag.PUMP, logPrefix + "readPumpHistoryLogic(): lastPumpHistoryEntryTime: 0L") targetDate = timeMinus36h } else { // LocalDateTime lastHistoryRecordTime = DateTimeUtil.toLocalDateTime(lastPumpHistoryEntryTime); if (debugHistory) aapsLogger.debug(LTag.PUMP, logPrefix + "readPumpHistoryLogic(): lastPumpHistoryEntryTime: " + lastPumpHistoryEntryTime) //medtronicHistoryData.setLastHistoryRecordTime(lastPumpHistoryEntryTime) var lastHistoryRecordTime = DateTimeUtil.toLocalDateTime(lastPumpHistoryEntryTime) lastHistoryRecordTime = lastHistoryRecordTime.minusHours(12) // we get last 12 hours of history to // determine pump state // (we don't process that data), we process only targetDate = if (timeMinus36h.isAfter(lastHistoryRecordTime)) timeMinus36h else lastHistoryRecordTime if (debugHistory) aapsLogger.debug(LTag.PUMP, logPrefix + "readPumpHistoryLogic(): targetDate: " + targetDate) } } else { // all other reads if (debugHistory) aapsLogger.debug(LTag.PUMP, logPrefix + "readPumpHistoryLogic(): lastPumpHistoryEntry: not null - " + medtronicUtil.gsonInstance.toJson(lastPumpHistoryEntry)) medtronicHistoryData.setIsInInit(false) // we need to read 35 minutes in the past so that we can repair any TBR or Bolus values if needed targetDate = LocalDateTime(DateTimeUtil.getMillisFromATDWithAddedMinutes(lastPumpHistoryEntry!!.atechDateTime, -35)) } //aapsLogger.debug(LTag.PUMP, "HST: Target Date: " + targetDate); @Suppress("UNCHECKED_CAST") val responseTask2 = rileyLinkMedtronicService?.medtronicUIComm?.executeCommand( MedtronicCommandType.GetHistoryData, arrayListOf(/*lastPumpHistoryEntry*/ null, targetDate) as? ArrayList<Any>? ) if (debugHistory) aapsLogger.debug(LTag.PUMP, "HST: After task") val historyResult = responseTask2?.result as PumpHistoryResult? if (debugHistory) aapsLogger.debug(LTag.PUMP, "HST: History Result: " + historyResult.toString()) val latestEntry = historyResult!!.latestEntry if (debugHistory) aapsLogger.debug(LTag.PUMP, logPrefix + "Last entry: " + latestEntry) if (latestEntry == null) // no new history to read return lastPumpHistoryEntry = latestEntry sp.putLong(MedtronicConst.Statistics.LastPumpHistoryEntry, latestEntry.atechDateTime) if (debugHistory) aapsLogger.debug(LTag.PUMP, "HST: History: valid=" + historyResult.validEntries.size + ", unprocessed=" + historyResult.unprocessedEntries.size) medtronicHistoryData.addNewHistory(historyResult) medtronicHistoryData.filterNewEntries() // determine if first run, if yes determine how much of update do we need // - first run: // - get last history entry // - if not there download 1.5 days of data // - there: check if last entry is older than 1.5 days // - yes: download 1.5 days // - no: download with last entry TODO 5min // - not there: download 1.5 days // // upload all new entries to NightScout (TBR, Bolus) // determine pump status // save last entry // // - not first run: // - update to last entry TODO 5min // - save // - determine pump status } private val lastPumpEntryTime: Long get() { val lastPumpEntryTime = sp.getLong(MedtronicConst.Statistics.LastPumpHistoryEntry, 0L) return try { val localDateTime = DateTimeUtil.toLocalDateTime(lastPumpEntryTime) if (localDateTime.year != GregorianCalendar()[Calendar.YEAR]) { aapsLogger.warn(LTag.PUMP, "Saved LastPumpHistoryEntry was invalid. Year was not the same.") return 0L } lastPumpEntryTime } catch (ex: Exception) { aapsLogger.warn(LTag.PUMP, "Saved LastPumpHistoryEntry was invalid.") 0L } } private fun scheduleNextRefresh(refreshType: MedtronicStatusRefreshType, additionalTimeInMinutes: Int = 0) { when (refreshType) { MedtronicStatusRefreshType.RemainingInsulin -> { val remaining = medtronicPumpStatus.reservoirRemainingUnits val min: Int = if (remaining > 50) 4 * 60 else if (remaining > 20) 60 else 15 synchronized(statusRefreshMap) { statusRefreshMap[refreshType] = getTimeInFutureFromMinutes(min) } } MedtronicStatusRefreshType.PumpTime, MedtronicStatusRefreshType.Configuration, MedtronicStatusRefreshType.BatteryStatus, MedtronicStatusRefreshType.PumpHistory -> { synchronized(statusRefreshMap) { statusRefreshMap[refreshType] = getTimeInFutureFromMinutes(refreshType.refreshTime + additionalTimeInMinutes) } } } } private fun getTimeInFutureFromMinutes(minutes: Int): Long { return System.currentTimeMillis() + getTimeInMs(minutes) } private fun getTimeInMs(minutes: Int): Long { return minutes * 60 * 1000L } private fun readTBR(): TempBasalPair? { val responseTask = rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(MedtronicCommandType.ReadTemporaryBasal) return if (responseTask?.hasData() == true) { val tbr = responseTask.result as TempBasalPair? // we sometimes get rate returned even if TBR is no longer running if (tbr != null) { if (tbr.durationMinutes == 0) { tbr.insulinRate = 0.0 } tbr } else null } else { null } } @Synchronized override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult { aapsLogger.info(LTag.PUMP, logPrefix + "cancelTempBasal - started") if (isPumpNotReachable) { setRefreshButtonEnabled(true) return PumpEnactResult(injector) // .success(false) // .enacted(false) // .comment(R.string.medtronic_pump_status_pump_unreachable) } medtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus) setRefreshButtonEnabled(false) val tbrCurrent = readTBR() if (tbrCurrent != null) { if (tbrCurrent.insulinRate > 0.0f && tbrCurrent.durationMinutes == 0) { aapsLogger.info(LTag.PUMP, logPrefix + "cancelTempBasal - TBR already canceled.") finishAction("TBR") return PumpEnactResult(injector).success(true).enacted(false) } } else { aapsLogger.warn(LTag.PUMP, logPrefix + "cancelTempBasal - Could not read current TBR, canceling operation.") finishAction("TBR") return PumpEnactResult(injector).success(false).enacted(false) .comment(R.string.medtronic_cmd_cant_read_tbr) } val responseTask2 = rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(MedtronicCommandType.CancelTBR) val response = responseTask2?.result as Boolean? finishAction("TBR") return if (response == null || !response) { aapsLogger.info(LTag.PUMP, logPrefix + "cancelTempBasal - Cancel TBR failed.") PumpEnactResult(injector).success(false).enacted(false) // .comment(R.string.medtronic_cmd_cant_cancel_tbr) } else { aapsLogger.info(LTag.PUMP, logPrefix + "cancelTempBasal - Cancel TBR successful.") val runningTBR = medtronicPumpStatus.runningTBR // TODO if (runningTBR != null) { if (medtronicHistoryData.isTBRActive(runningTBR)) { val differenceTime = System.currentTimeMillis() - runningTBR.date //val tbrData = runningTBR val result = pumpSync.syncTemporaryBasalWithPumpId( runningTBR.date, runningTBR.rate, differenceTime, runningTBR.isAbsolute, runningTBR.tbrType, runningTBR.pumpId!!, runningTBR.pumpType, runningTBR.serialNumber ) val differenceTimeMin = floor(differenceTime / (60.0 * 1000.0)) aapsLogger.debug( LTag.PUMP, "canceling running TBR - syncTemporaryBasalWithPumpId [date=${runningTBR.date}, " + "pumpId=${runningTBR.pumpId}, rate=${runningTBR.rate} U, duration=${differenceTimeMin.toInt()}, " + "pumpSerial=${medtronicPumpStatus.serialNumber}] - Result: $result" ) } } //cancelTBRWithTemporaryId() PumpEnactResult(injector).success(true).enacted(true) // .isTempCancel(true) } } override fun manufacturer(): ManufacturerType { return ManufacturerType.Medtronic } override fun model(): PumpType { return pumpDescription.pumpType } override fun serialNumber(): String { return medtronicPumpStatus.serialNumber } @Synchronized override fun setNewBasalProfile(profile: Profile): PumpEnactResult { aapsLogger.info(LTag.PUMP, logPrefix + "setNewBasalProfile") // this shouldn't be needed, but let's do check if profile setting we are setting is same as current one if (isProfileSame(profile)) { return PumpEnactResult(injector) // .success(true) // .enacted(false) // .comment(R.string.medtronic_cmd_basal_profile_not_set_is_same) } setRefreshButtonEnabled(false) if (isPumpNotReachable) { setRefreshButtonEnabled(true) return PumpEnactResult(injector) // .success(false) // .enacted(false) // .comment(R.string.medtronic_pump_status_pump_unreachable) } medtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus) val basalProfile = convertProfileToMedtronicProfile(profile) aapsLogger.debug("Basal Profile: $basalProfile") val profileInvalid = isProfileValid(basalProfile) if (profileInvalid != null) { return PumpEnactResult(injector) // .success(false) // .enacted(false) // .comment(rh.gs(R.string.medtronic_cmd_set_profile_pattern_overflow, profileInvalid)) } val responseTask = rileyLinkMedtronicService?.medtronicUIComm?.executeCommand( MedtronicCommandType.SetBasalProfileSTD, arrayListOf(basalProfile) ) val response = responseTask?.result as Boolean? aapsLogger.info(LTag.PUMP, logPrefix + "Basal Profile was set: " + response) return if (response == null || !response) { PumpEnactResult(injector).success(false).enacted(false) // .comment(R.string.medtronic_cmd_basal_profile_could_not_be_set) } else { PumpEnactResult(injector).success(true).enacted(true) } } private fun isProfileValid(basalProfile: BasalProfile): String? { val stringBuilder = StringBuilder() if (medtronicPumpStatus.maxBasal == null) return null for (profileEntry in basalProfile.getEntries()) { if (profileEntry.rate > medtronicPumpStatus.maxBasal!!) { stringBuilder.append(profileEntry.startTime!!.toString("HH:mm")) stringBuilder.append("=") stringBuilder.append(profileEntry.rate) } } return if (stringBuilder.isEmpty()) null else stringBuilder.toString() } private fun convertProfileToMedtronicProfile(profile: Profile): BasalProfile { val basalProfile = BasalProfile(aapsLogger) for (i in 0..23) { val rate = profile.getBasalTimeFromMidnight(i * 60 * 60) val v = pumpType.determineCorrectBasalSize(rate) val basalEntry = BasalProfileEntry(v, i, 0) basalProfile.addEntry(basalEntry) } basalProfile.generateRawDataFromEntries() return basalProfile } // OPERATIONS not supported by Pump or Plugin private var customActions: List<CustomAction>? = null private val customActionWakeUpAndTune = CustomAction( R.string.medtronic_custom_action_wake_and_tune, MedtronicCustomActionType.WakeUpAndTune ) private val customActionClearBolusBlock = CustomAction( R.string.medtronic_custom_action_clear_bolus_block, MedtronicCustomActionType.ClearBolusBlock, false ) private val customActionResetRLConfig = CustomAction( R.string.medtronic_custom_action_reset_rileylink, MedtronicCustomActionType.ResetRileyLinkConfiguration, true ) override fun getCustomActions(): List<CustomAction>? { if (customActions == null) { customActions = listOf( customActionWakeUpAndTune, // customActionClearBolusBlock, // customActionResetRLConfig ) } return customActions } override fun executeCustomAction(customActionType: CustomActionType) { when (customActionType as? MedtronicCustomActionType) { MedtronicCustomActionType.WakeUpAndTune -> { if (rileyLinkMedtronicService?.verifyConfiguration() == true) { serviceTaskExecutor.startTask(WakeAndTuneTask(injector)) } else { runAlarm(context, rh.gs(R.string.medtronic_error_operation_not_possible_no_configuration), rh.gs(R.string.medtronic_warning), R.raw.boluserror) } } MedtronicCustomActionType.ClearBolusBlock -> { busyTimestamps.clear() customActionClearBolusBlock.isEnabled = false refreshCustomActionsList() } MedtronicCustomActionType.ResetRileyLinkConfiguration -> { serviceTaskExecutor.startTask(ResetRileyLinkConfigurationTask(injector)) } null -> { } } } override fun timezoneOrDSTChanged(timeChangeType: TimeChangeType) { aapsLogger.warn(LTag.PUMP, logPrefix + "Time or TimeZone changed. ") hasTimeDateOrTimeZoneChanged = true } override fun setNeutralTempAtFullHour(): Boolean { return sp.getBoolean(R.string.key_set_neutral_temps, true) } @Suppress("SameParameterValue") private fun setEnableCustomAction(customAction: MedtronicCustomActionType, isEnabled: Boolean) { if (customAction === MedtronicCustomActionType.ClearBolusBlock) { customActionClearBolusBlock.isEnabled = isEnabled } else if (customAction === MedtronicCustomActionType.ResetRileyLinkConfiguration) { customActionResetRLConfig.isEnabled = isEnabled } refreshCustomActionsList() } }
medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.kt
3843456432
package ru.ilyatrofimov.alarmebble.reciever import android.content.Context import android.content.Intent import android.preference.PreferenceManager import android.provider.AlarmClock import com.getpebble.android.kit.PebbleKit import com.getpebble.android.kit.util.PebbleDictionary import ru.ilyatrofimov.alarmebble.R import java.util.* class AlarmebbleReceiver : PebbleKit.PebbleDataReceiver(APP_UUID) { private val STATUS_OK = 0 private val STATUS_ERROR = -2 override fun receiveData(context: Context, transactionId: Int, data: PebbleDictionary) { PebbleKit.sendAckToPebble(context, transactionId) val response = PebbleDictionary() // Get current alarm app val settings = PreferenceManager.getDefaultSharedPreferences(context); val processName = settings.getString(context.getString(R.string.key_process), "") val activityName = settings.getString(context.getString(R.string.key_activity), "") // Try to start set alarm intent and prepare response for pebble try { with (Intent(AlarmClock.ACTION_SET_ALARM)) { setClassName(processName, activityName) putExtra(AlarmClock.EXTRA_HOUR, data.getInteger(0).toInt()) putExtra(AlarmClock.EXTRA_MINUTES, data.getInteger(1).toInt()) putExtra(AlarmClock.EXTRA_SKIP_UI, true) flags = Intent.FLAG_ACTIVITY_NEW_TASK if (resolveActivity(context.packageManager) != null) { context.startActivity(this) response.addInt32(0, STATUS_OK) // OK } else { response.addInt32(0, STATUS_ERROR) // Error } } } catch (e: Exception) { response.addInt32(0, STATUS_ERROR) // Error } // Send response to Pebble PebbleKit.sendDataToPebbleWithTransactionId(context, APP_UUID, response, transactionId) } /** * Not secret Pebble APP_UUID */ companion object { private val APP_UUID = UUID.fromString("e44a8ca9-2d35-4d55-b9f2-cafd12788dbf") } }
Alarmebble-Android/app/src/main/kotlin/ru/ilyatrofimov/alarmebble/reciever/AlarmebbleReceiver.kt
3168771551
package ogl_samples.tests.es300 import glm_.BYTES import glm_.glm import glm_.i import glm_.mat4x4.Mat4 import glm_.s import glm_.vec2.Vec2 import glm_.vec3.Vec3 import glm_.vec4.Vec4i import ogl_samples.framework.Compiler import ogl_samples.framework.TestA import org.lwjgl.opengl.GL11.* import org.lwjgl.opengl.GL12.GL_UNSIGNED_SHORT_4_4_4_4 import org.lwjgl.opengl.GL13.GL_TEXTURE0 import org.lwjgl.opengl.GL13.glActiveTexture import uno.buffer.bufferBig import uno.buffer.bufferOf import uno.caps.Caps.Profile import uno.glf.Vertex import uno.glf.glf import uno.glf.semantic import uno.gln.* /** * Created by GBarbieri on 30.03.2017. */ fun main(args: Array<String>) { es_300_texture_format_packed().loop() } private class es_300_texture_format_packed : TestA("es-300-texture-format-packed", Profile.ES, 3, 0) { val SHADER_SOURCE = "es-300/texture-format-packed" override var vertexCount = 8 override var vertexData = bufferOf( Vertex.pos2_tc2(Vec2(-1f, -1f), Vec2(0f, 0f)), Vertex.pos2_tc2(Vec2(-1f, 3f), Vec2(0f, 1f)), Vertex.pos2_tc2(Vec2(3f, -1f), Vec2(1f, 0f))) val viewport = arrayOf( Vec4i(0, 0, 320, 240), Vec4i(320, 0, 320, 240), Vec4i(0, 240, 320, 240), Vec4i(320, 240, 320, 240)) override fun initProgram(): Boolean { var validated = true val compiler = Compiler() val vertShaderName = compiler.create("$SHADER_SOURCE.vert") val fragShaderName = compiler.create("$SHADER_SOURCE.frag") validated = validated && compiler.check() initProgram(programName) { attach(vertShaderName, fragShaderName) "Position".attrib = semantic.attr.POSITION "Texcoord".attrib = semantic.attr.TEX_COORD "Color".fragData = semantic.frag.COLOR link() validated = validated && compiler checkProgram name Uniform.mvp = "MVP".uniform validated = validated && Uniform.mvp != -1 Uniform.diffuse = "Diffuse".uniform validated = validated && Uniform.diffuse != -1 } return validated && checkError("initProgram") } override fun initBuffer() = initArrayBuffer(vertexData) override fun initTexture(): Boolean { glPixelStorei(GL_UNPACK_ALIGNMENT, 1) initTextures2d(textureName) { val dataRGBA4 = bufferBig(Short.BYTES).putShort(0, 0xF80C.s) val dataRGBA8 = bufferBig(Int.BYTES).putInt(0, 0xCC0088FF.i) val dataBGRA4 = bufferBig(Short.BYTES).putShort(0, 0x08FC) val dataBGRA8 = bufferBig(Int.BYTES).putInt(0, 0xCCFF8800.i) at(Texture.RGBA4) { levels(base = 0, max = 0) filter(min = nearest, mag = nearest) image(GL_RGBA4, 1, 1, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, dataRGBA4) } at(Texture.RGBA4_REV) { levels(base = 0, max = 0) filter(min = nearest, mag = nearest) image(GL_RGBA8, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, dataRGBA8) } at(Texture.BGRA4) { levels(base = 0, max = 0) filter(min = nearest, mag = nearest) swizzle(r = blue, g = green, b = red, a = alpha) image(GL_RGBA4, 1, 1, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, dataBGRA4) } at(Texture.BGRA4_REV) { levels(base = 0, max = 0) filter(min = nearest, mag = nearest) swizzle(r = blue, g = green, b = red, a = alpha) image(GL_RGBA8, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, dataBGRA8) } } return checkError("initTexture") } override fun initVertexArray() = initVertexArray(glf.pos2_tc2) override fun render(): Boolean { val projection = glm.perspective(glm.PIf * 0.25f, 4f / 3f, 0.1f, 100f) val model = glm.scale(Mat4(), Vec3(3f)) val mvp = projection * view * model usingProgram(programName) { glUniform(Uniform.diffuse, semantic.sampler.DIFFUSE) glUniform(Uniform.mvp, mvp) glBindVertexArray(vertexArrayName) glActiveTexture(GL_TEXTURE0) glViewport(viewport[0]) glBindTexture(GL_TEXTURE_2D, Texture.RGBA4) glDrawArraysInstanced(vertexCount, 1) glViewport(viewport[1]) glBindTexture(GL_TEXTURE_2D, Texture.RGBA4_REV) glDrawArraysInstanced(vertexCount, 1) glViewport(viewport[2]) glBindTexture(GL_TEXTURE_2D, Texture.BGRA4) glDrawArraysInstanced(vertexCount, 1) glViewport(viewport[3]) glBindTexture(GL_TEXTURE_2D, Texture.BGRA4_REV) glDrawArraysInstanced(vertexCount, 1) } return true } }
src/main/kotlin/ogl_samples/tests/es300/es-300-texture-format-packed.kt
1988664894
/* * Copyright 2020 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire actual typealias GrpcResponse = okhttp3.Response
wire-library/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcResponse.kt
3709616825
/* * Copyright (C) 2015 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 com.squareup.wire.schema import com.squareup.wire.buildSchema import okio.Path.Companion.toPath import org.assertj.core.api.Assertions.assertThat import org.junit.Test class OptionsTest { @Test fun structuredAndUnstructuredOptions() { // From https://developers.google.com/protocol-buffers/docs/proto#options val schema = buildSchema { add( "foo.proto".toPath(), """ |import "google/protobuf/descriptor.proto"; |message FooOptions { | optional int32 opt1 = 1; | optional string opt2 = 2; |} | |extend google.protobuf.FieldOptions { | optional FooOptions foo_options = 1234; |} | |message Bar { | optional int32 a = 1 [(foo_options).opt1 = 123, (foo_options).opt2 = "baz"]; | optional int32 b = 2 [(foo_options) = { opt1: 456 opt2: "quux" }]; |} """.trimMargin() ) } val fooOptions = ProtoMember.get(Options.FIELD_OPTIONS, "foo_options") val opt1 = ProtoMember.get(ProtoType.get("FooOptions"), "opt1") val opt2 = ProtoMember.get(ProtoType.get("FooOptions"), "opt2") val bar = schema.getType("Bar") as MessageType assertThat(bar.field("a")!!.options.map) .isEqualTo(mapOf(fooOptions to mapOf(opt1 to "123", opt2 to "baz"))) assertThat(bar.field("b")!!.options.map) .isEqualTo(mapOf(fooOptions to mapOf(opt1 to "456", opt2 to "quux"))) } @Test fun textFormatCanOmitMapValueSeparator() { val schema = buildSchema { add( "foo.proto".toPath(), """ |import "google/protobuf/descriptor.proto"; |message FooOptions { | optional BarOptions bar = 2; |} |message BarOptions { | optional int32 baz = 2; |} | |extend google.protobuf.FieldOptions { | optional FooOptions foo = 1234; |} | |message Message { | optional int32 b = 2 [(foo) = { bar { baz: 123 } }]; |} """.trimMargin() ) } val foo = ProtoMember.get(Options.FIELD_OPTIONS, "foo") val bar = ProtoMember.get(ProtoType.get("FooOptions"), "bar") val baz = ProtoMember.get(ProtoType.get("BarOptions"), "baz") val message = schema.getType("Message") as MessageType assertThat(message.field("b")!!.options.map) .isEqualTo(mapOf(foo to mapOf(bar to mapOf(baz to "123")))) } @Test fun testOptionsToSchema() { val schema = buildSchema { add( "foo.proto".toPath(), """ |import "google/protobuf/descriptor.proto"; |enum FooParameterType { | NUMBER = 1; | STRING = 2; |} |enum Scheme { | UNKNOWN = 0; | HTTP = 1; | HTTPS = 2; |} | |message FooOptions { | optional string name = 1; | optional FooParameterType type = 2; | repeated Scheme schemes = 3; |} |extend google.protobuf.MessageOptions { | repeated FooOptions foo = 12345; |} | |message Message { | option (foo) = { | name: "test" | type: STRING | schemes: HTTP | schemes: HTTPS | }; | | option (foo) = { | name: "test2" | type: NUMBER | schemes: [HTTP, HTTPS] | }; | | optional int32 b = 2; |} """.trimMargin() ) } val protoFile = schema.protoFile("foo.proto") val optionElements = protoFile!!.types .first { it is MessageType && it.toElement().name == "Message" } .options.elements assertThat(optionElements[0].toSchema()) .isEqualTo( """|(foo) = { | name: "test", | type: STRING, | schemes: [ | HTTP, | HTTPS | ] |}""".trimMargin() ) val foo = ProtoMember.get(Options.MESSAGE_OPTIONS, "foo") val name = ProtoMember.get(ProtoType.get("FooOptions"), "name") val type = ProtoMember.get(ProtoType.get("FooOptions"), "type") val schemes = ProtoMember.get(ProtoType.get("FooOptions"), "schemes") val message = schema.getType("Message") as MessageType message.toElement().name assertThat(message.options.map) .isEqualTo( mapOf( foo to arrayListOf( mapOf(name to "test", type to "STRING", schemes to listOf("HTTP", "HTTPS")), mapOf(name to "test2", type to "NUMBER", schemes to listOf("HTTP", "HTTPS")) ) ) ) } @Test fun fullyQualifiedOptionFields() { val schema = buildSchema { add( "a/b/more_options.proto".toPath(), """ |syntax = "proto2"; |package a.b; | |import "google/protobuf/descriptor.proto"; | |extend google.protobuf.MessageOptions { | optional MoreOptions more_options = 17000; |} | |message MoreOptions { | extensions 100 to 200; |} """.trimMargin() ) add( "a/c/event_more_options.proto".toPath(), """ |syntax = "proto2"; |package a.c; | |import "a/b/more_options.proto"; | |extend a.b.MoreOptions { | optional EvenMoreOptions even_more_options = 100; |} | |message EvenMoreOptions { | optional string string_option = 1; |} """.trimMargin() ) add( "a/d/message.proto".toPath(), """ |syntax = "proto2"; |package a.d; | |import "a/b/more_options.proto"; |import "a/c/event_more_options.proto"; | |message Message { | option (a.b.more_options) = { | [a.c.even_more_options]: {string_option: "foo"} | }; |} """.trimMargin() ) } val moreOptionsType = ProtoType.get("a.b.MoreOptions") val evenMoreOptionsType = ProtoType.get("a.c.EvenMoreOptions") val moreOptions = ProtoMember.get(Options.MESSAGE_OPTIONS, "a.b.more_options") val evenMoreOptions = ProtoMember.get(moreOptionsType, "a.c.even_more_options") val stringOption = ProtoMember.get(evenMoreOptionsType, "string_option") val message = schema.getType("a.d.Message") as MessageType assertThat(message.options.map) .isEqualTo(mapOf(moreOptions to mapOf(evenMoreOptions to mapOf(stringOption to "foo")))) } @Test fun resolveFieldPathMatchesLeadingDotFirstSegment() { assertThat(Options.resolveFieldPath(".a.b.c.d", setOf("a", "z", "y"))) .containsExactly("a", "b", "c", "d") } @Test fun resolveFieldPathMatchesFirstSegment() { assertThat(Options.resolveFieldPath("a.b.c.d", setOf("a", "z", "y"))) .containsExactly("a", "b", "c", "d") } @Test fun resolveFieldPathMatchesMultipleSegments() { assertThat(Options.resolveFieldPath("a.b.c.d", setOf("a.b", "z.b", "y.b"))) .containsExactly("a.b", "c", "d") } @Test fun resolveFieldPathMatchesAllSegments() { assertThat(Options.resolveFieldPath("a.b.c.d", setOf("a.b.c.d", "z.b.c.d"))) .containsExactly("a.b.c.d") } @Test fun resolveFieldPathMatchesOnlySegment() { assertThat(Options.resolveFieldPath("a", setOf("a", "b"))).containsExactly("a") } @Test fun resolveFieldPathDoesntMatch() { assertThat(Options.resolveFieldPath("a.b", setOf("c", "d"))).isNull() } @Test fun mapFieldEntriesLinking() { val schema = buildSchema { add( "my_package/some_enum.proto".toPath(), """ |syntax = "proto2"; |import "google/protobuf/descriptor.proto"; |package my_package; | |enum SomeEnum { | TEST = 0 [(my_package.my_option) = { | entries: [ | { | key: 'key-1', | value: { | some_string: "value-1" | } | }, | { | value: { | some_string: "value-2" | } | }, | { | key: 'key-3', | value: { | } | }, | { | key: 'key-4', | }, | { | key: 'key-5', | value: { | some_string: "value-5", | some_int32: 5 | } | } | ] | }]; |} | |message SomeMessage { | optional string some_string = 1; | optional int32 some_int32 = 2; |} | |message MyOption { | map<string, SomeMessage> entries = 2; |} | |extend google.protobuf.EnumValueOptions { | optional MyOption my_option = 1000; |} """.trimMargin() ) } val enumType = schema.getType(ProtoType.get("my_package.SomeEnum")) as EnumType val myOption = ProtoMember.get(Options.ENUM_VALUE_OPTIONS, "my_package.my_option") val entries = ProtoMember.get(ProtoType.get("my_package.MyOption"), "entries") val someString = ProtoMember.get(ProtoType.get("my_package.SomeMessage"), "some_string") val someInt32 = ProtoMember.get(ProtoType.get("my_package.SomeMessage"), "some_int32") assertThat(enumType.constant(tag = 0)!!.options.map) .isEqualTo( mapOf( myOption to mapOf( entries to listOf( mapOf("key-1" to mapOf(someString to "value-1")), mapOf(null to mapOf(someString to "value-2")), mapOf("key-3" to mapOf()), mapOf("key-4" to null), mapOf("key-5" to mapOf(someString to "value-5", someInt32 to "5")), ) ) ) ) } @Test fun mapFieldEntriesWriting() { val path = "my_package/some_enum.proto".toPath() val schema = buildSchema { add( path, """ |syntax = "proto3"; |import "google/protobuf/descriptor.proto"; |package my_package; | |enum SomeEnum { | TEST = 0 [(my_package.my_option) = { | entries: [ | { | key: 'key-1', | value: { | some_string: "value-1" | } | }, | { | key: 'key-2', | value: { | some_string: "value-2", | some_int32: 2 | } | } | ] | }]; |} | |message SomeMessage { | string some_string = 1; | int32 some_int32 = 2; |} | |message MyOption { | map<string, SomeMessage> entries = 2; |} | |extend google.protobuf.EnumValueOptions { | MyOption my_option = 1000; |} """.trimMargin() ) } val enumType = schema.getType(ProtoType.get("my_package.SomeEnum")) as EnumType val optionElement = enumType.constant(tag = 0)!!.options.elements.first() // We do print "key" and "value" keys for map fields, even though the linked schema doesn't // know about them. val expected = """ |(my_package.my_option) = { | entries: [ | { | key: "key-1", | value: { | some_string: "value-1" | } | }, | { | key: "key-2", | value: { | some_string: "value-2", | some_int32: 2 | } | } | ] |} """.trimMargin() assertThat(optionElement.toSchema()).isEqualTo(expected) } }
wire-library/wire-schema/src/jvmTest/kotlin/com/squareup/wire/schema/OptionsTest.kt
3809133193
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.gradleTooling.builders import org.gradle.api.Task import org.gradle.api.logging.Logging import org.jetbrains.kotlin.idea.gradleTooling.* import org.jetbrains.kotlin.idea.gradleTooling.arguments.buildCachedArgsInfo import org.jetbrains.kotlin.idea.gradleTooling.arguments.buildSerializedArgsInfo import org.jetbrains.kotlin.idea.gradleTooling.reflect.KotlinCompilationOutputReflection import org.jetbrains.kotlin.idea.gradleTooling.reflect.KotlinCompilationReflection import org.jetbrains.kotlin.idea.gradleTooling.reflect.KotlinNativeCompileReflection import org.jetbrains.kotlin.idea.projectModel.KotlinCompilation import org.jetbrains.kotlin.idea.projectModel.KotlinCompilationOutput import org.jetbrains.kotlin.idea.projectModel.KotlinPlatform class KotlinCompilationBuilder(val platform: KotlinPlatform, val classifier: String?) : KotlinModelComponentBuilder<KotlinCompilationReflection, MultiplatformModelImportingContext, KotlinCompilation> { override fun buildComponent( origin: KotlinCompilationReflection, importingContext: MultiplatformModelImportingContext ): KotlinCompilationImpl? { val compilationName = origin.compilationName val kotlinGradleSourceSets = origin.sourceSets ?: return null val kotlinSourceSets = kotlinGradleSourceSets.mapNotNull { importingContext.sourceSetByName(it.name) } val compileKotlinTask = origin.compileKotlinTaskName ?.let { importingContext.project.tasks.findByName(it) } ?: return null val output = origin.compilationOutput?.let { buildCompilationOutput(it, compileKotlinTask) } ?: return null val dependencies = buildCompilationDependencies(importingContext, origin, classifier) val kotlinTaskProperties = getKotlinTaskProperties(compileKotlinTask, classifier) val nativeExtensions = origin.konanTargetName?.let(::KotlinNativeCompilationExtensionsImpl) val allSourceSets = kotlinSourceSets .flatMap { sourceSet -> importingContext.resolveAllDependsOnSourceSets(sourceSet) } .union(kotlinSourceSets) val cachedArgsInfo = if (compileKotlinTask.isCompilerArgumentAware //TODO hotfix for KTIJ-21807. // Remove after proper implementation of org.jetbrains.kotlin.gradle.tasks.KotlinNativeCompile#setupCompilerArgs && !compileKotlinTask.isKotlinNativeCompileTask //TODO hotfix for KTIJ-21807. Replace after ) buildCachedArgsInfo(compileKotlinTask, importingContext.compilerArgumentsCacheMapper) else buildSerializedArgsInfo(compileKotlinTask, importingContext.compilerArgumentsCacheMapper, logger) val associateCompilations = origin.associateCompilations.mapNotNull { associateCompilation -> KotlinCompilationCoordinatesImpl( targetName = associateCompilation.target?.targetName ?: return@mapNotNull null, compilationName = associateCompilation.compilationName ) } @Suppress("DEPRECATION_ERROR") return KotlinCompilationImpl( name = compilationName, allSourceSets = allSourceSets, declaredSourceSets = if (platform == KotlinPlatform.ANDROID) allSourceSets else kotlinSourceSets, dependencies = dependencies.map { importingContext.dependencyMapper.getId(it) }.distinct().toTypedArray(), output = output, arguments = KotlinCompilationArgumentsImpl(emptyArray(), emptyArray()), dependencyClasspath = emptyArray(), cachedArgsInfo = cachedArgsInfo, kotlinTaskProperties = kotlinTaskProperties, nativeExtensions = nativeExtensions, associateCompilations = associateCompilations.toSet() ) } companion object { private val logger = Logging.getLogger(KotlinCompilationBuilder::class.java) private val compileDependenciesBuilder = object : KotlinMultiplatformDependenciesBuilder() { override val configurationNameAccessor: String = "getCompileDependencyConfigurationName" override val scope: String = "COMPILE" } private val runtimeDependenciesBuilder = object : KotlinMultiplatformDependenciesBuilder() { override val configurationNameAccessor: String = "getRuntimeDependencyConfigurationName" override val scope: String = "RUNTIME" } private const val COMPILER_ARGUMENT_AWARE_CLASS = "org.jetbrains.kotlin.gradle.internal.CompilerArgumentAware" private const val KOTLIN_NATIVE_COMPILE_CLASS = "org.jetbrains.kotlin.gradle.tasks.AbstractKotlinNativeCompile" private fun buildCompilationDependencies( importingContext: MultiplatformModelImportingContext, compilationReflection: KotlinCompilationReflection, classifier: String? ): Set<KotlinDependency> { return LinkedHashSet<KotlinDependency>().apply { this += compileDependenciesBuilder.buildComponent(compilationReflection.gradleCompilation, importingContext) this += runtimeDependenciesBuilder.buildComponent(compilationReflection.gradleCompilation, importingContext) .onlyNewDependencies(this) val sourceSet = importingContext.sourceSetByName(compilationFullName(compilationReflection.compilationName, classifier)) this += sourceSet?.dependencies?.mapNotNull { importingContext.dependencyMapper.getDependency(it) } ?: emptySet() } } private fun buildCompilationOutput( kotlinCompilationOutputReflection: KotlinCompilationOutputReflection, compileKotlinTask: Task ): KotlinCompilationOutput? { val compilationOutputBase = KotlinCompilationOutputBuilder.buildComponent(kotlinCompilationOutputReflection) ?: return null val destinationDir = KotlinNativeCompileReflection(compileKotlinTask).destinationDir return KotlinCompilationOutputImpl(compilationOutputBase.classesDirs, destinationDir, compilationOutputBase.resourcesDir) } private val Task.isCompilerArgumentAware: Boolean get() = javaClass.classLoader.loadClassOrNull(COMPILER_ARGUMENT_AWARE_CLASS)?.isAssignableFrom(javaClass) ?: false private val Task.isKotlinNativeCompileTask: Boolean get() = javaClass.classLoader.loadClassOrNull(KOTLIN_NATIVE_COMPILE_CLASS)?.isAssignableFrom(javaClass) ?: false } }
plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/builders/KotlinCompilationBuilder.kt
2457531422
package com.bajdcc.LALR1.interpret.test import com.bajdcc.LALR1.grammar.Grammar import com.bajdcc.LALR1.grammar.runtime.RuntimeCodePage import com.bajdcc.LALR1.grammar.runtime.RuntimeException import com.bajdcc.LALR1.interpret.Interpreter import com.bajdcc.LALR1.syntax.handler.SyntaxException import com.bajdcc.util.lexer.error.RegexException import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream object TestInterpret13 { @JvmStatic fun main(args: Array<String>) { try { val codes = arrayOf("import \"sys.base\";\n" + "import \"sys.func\";\n" + "import \"sys.list\";\n" + "import \"sys.string\";\n" + "import \"sys.math\";\n" + "import \"sys.class\";\n" + "\n" + "var ctx = call g_create_context();\n" + "call g_register_class(ctx, \"shape\", lambda(this){\n" + "call g_create_property(this, \"type\", \"shape\");\n" + "call g_create_method(this, \"get_area\", lambda(this)->0);\n" + "call g_create_method(this, \"get_index\", lambda(this,i)->i);\n" + "}, g_null);\n" + "call g_register_class(ctx, \"square\", lambda(this){\n" + "call g_create_property(this, \"type\", \"square\");\n" + "call g_create_property(this, \"a\", 0);\n" + "call g_create_property(this, \"b\", 0);\n" + "call g_create_method(this, \"get_area\", lambda(this){\n" + "return call g_get_property(this, \"a\") * call g_get_property(this, \"b\");\n" + "});\n" + "call g_create_method(this, \"to_string\", lambda(this){\n" + "return \"\" + call g_get_property(this, \"type\")\n" + "+ \" a=\" + call g_get_property(this, \"a\")\n" + "+ \" b=\" + call g_get_property(this, \"b\")\n" + "+ \" area=\"\n" + "+ call g_invoke_method(this, \"get_area\");\n" + "});\n" + "}, \"shape\");\n" + "call g_register_class(ctx, \"circle\", lambda(this){\n" + "call g_create_property(this, \"type\", \"circle\");\n" + "call g_create_property(this, \"r\", 0);\n" + "call g_create_method(this, \"get_area\", lambda(this){\n" + "var r = call g_get_property(this, \"r\");\n" + "return 3.14 * r * r;\n" + "});\n" + "call g_create_method(this, \"to_string\", lambda(this){\n" + "return \"\" + call g_get_property(this, \"type\")\n" + "+ \" r=\" + call g_get_property(this, \"r\")\n" + "+ \" area=\"\n" + "+ call g_invoke_method(this, \"get_area\");\n" + "});\n" + "}, \"shape\");\n" + "\n" + "\n" + "var square = call g_create_class(ctx, \"square\");\n" + "call g_set_property(square, \"a\", 5);\n" + "call g_set_property(square, \"b\", 6);\n" + "call g_printn(\"\" + call g_get_property(square, \"type\")\n" + "+ \" a=\" + call g_get_property(square, \"a\")\n" + "+ \" b=\" + call g_get_property(square, \"b\")\n" + "+ \" area=\"\n" + "+ call g_invoke_method(square, \"get_area\"));\n" + "var circle = call g_create_class(ctx, \"circle\");\n" + "call g_set_property(circle, \"r\", 10);\n" + "call g_set_property(circle, \"s\", square);\n" + "call g_printn(\"\" + call g_get_property(circle, \"type\")\n" + "+ \" r=\" + call g_get_property(circle, \"r\")\n" + "+ \" area=\"\n" + "+ call g_invoke_method(circle, \"get_area\"));\n" + "call g_printn(call g_invoke_method(square, \"to_string\"));\n" + "call g_printn(call g_invoke_method(circle, \"to_string\"));\n" + "call g_printn(circle.\"r\");\n" + "call g_printn(circle.\"s\".\"__type__\");\n" + "call g_printn(circle.\"s\".\"a\");\n" + "call g_printn(circle.\"s\".\"b\");\n" + "call g_printn(circle.\"__type__\");\n" + "call g_printn(square.\"__type__\");\n" + "set square::\"a\" = 100;\n" + "set square::\"b\" = 120;\n" + "call g_printn(circle.\"s\".\"a\");\n" + "call g_printn(circle.\"s\".\"b\");\n" + "call g_printn(invoke circle::\"get_area\"());\n" + "call g_printn(invoke square::\"get_area\"());\n" + "call g_printn(invoke circle::\"get_index\"(1));\n" + "call g_printn(invoke square::\"get_index\"(2));\n" + "", "import \"sys.base\";\n" + "import \"sys.class\";\n" + "import \"std.base\";\n" + "var ctx = g_create_context();\n" + "g_import_std_base(ctx);\n" + "var a = g_create_class(ctx, \"list::array\");\n" + "var b = g_create_class(ctx, \"list::array\");\n" + "a.\"add\"(b);\n" + "b.\"add\"(0);\n" + "g_printn(a.\"get\"(0).\"size\"());\n" + "a.\"get\"(0).\"c\" := 2;\n" + "a.\"get\"(0).\"c\" *= 2;\n" + "a.\"get\"(0).\"c\" ++;\n" + "g_printn(a.\"get\"(0).\"c\"++);\n", "import \"sys.base\";\n" + "var move = func ~(i, x, y) {\n" + " g_printn(g_to_string(i) + \": \" + g_to_string(x) + \" -> \" + g_to_string(y));\n" + "};\n" + "var hanoi = func ~(f) {\n" + " var fk = func ~(i, a, b, c) {\n" + " if (i == 1) {\n" + " move(i, a, c);\n" + " } else {\n" + " f(i - 1, a, c, b);\n" + " move(i, a, c);\n" + " f(i - 1, b, a, c);\n" + " }\n" + " };\n" + " return fk;\n" + "};\n" + "var h = call (func ~(f) ->\n" + " call (func ~(h) -> h(h))(\n" + " lambda(x) -> lambda(i, a, b, c) ->\n" + " call (f(x(x)))(i, a, b, c)))(hanoi);\n" + "h(3, 'A', 'B', 'C');\n", "import \"sys.base\";\n" + "var c = yield ~(){throw 3;};\n" + "var b = yield ~(){\n" + "try{foreach(var k : c()){}yield 1;}\n" + "catch{\n" + " yield 4;throw 2;}};\n" + "/*g_set_debug(true);*/\n" + "try{foreach(var k : b()){g_printn(k);}}catch{g_printn(5);}\n", "import \"sys.base\";\n" + "var a = func ~(){ foreach (var i : g_range(1, 4)+1) {\n" + " foreach (var j : g_range(1, 5)+1) {\n" + " g_printn(i*j);\n" + " }\n" + "}};\n" + "g_printn(a());\n" + "g_printn(a());", "import \"sys.base\";\n" + "var b = func ~() { foreach (var j : g_range(1, 5)+1) {\n" + " g_printn(j);\n" + "}};\n" + "var a = func ~() { foreach (var i : g_range(1, 4)+1) {\n" + " b();\n" + "}};\n" + "g_printn(a());\n" + "g_printn(a());", "import \"sys.base\";\n" + "import \"sys.string\";\n" + "var a = func ~(){ foreach (var i : g_range_string(\"ertyrt\")) {\n" + " foreach (var j : g_range(1, 5)+1) {\n" + " g_printn(i);\n" + " }\n" + "}};\n" + "g_printn(a());\n" + "g_printn(a());", "import \"sys.base\";\n" + "import \"sys.string\";\n" + "var a = func ~(){ foreach (var i : g_range_string(\"ertyrt\")) {\n" + " foreach (var j : g_range(1, 5)+1) {\n" + " return i;\n" + " }\n" + "}};\n" + "g_printn(a());\n" + "g_printn(a());", "import \"sys.base\";\n" + "import \"sys.proc\";\n" + "g_proc_exec(\"" + "import \\\"user.base\\\";" + "import \\\"user.cparser\\\";" + "var code = \\\"abc\\ndef\\n\\\";" + "var s = g_new_class(\\\"clib::c::scanner\\\", [], [[\\\"init\\\", code]]);" + "while (s.\\\"next\\\"()) { g_printn(s.\\\"REPORT\\\"()); }" + "\");\n", "import \"sys.base\";\n" + "import \"sys.proc\";\n" + "g_proc_exec(\"" + "import \\\"user.base\\\";" + "import \\\"user.cparser\\\";" + "var code = \\\"abc int auto 123\\ndef 0xabcd 5.6e+78\\n+ 0x 4e 6ea 88. 7e-4\\n" + "//123\\\n/*345*/\\\n/*abc\\\ndef*/ /*\\\";" + "var s = g_new_class(\\\"clib::c::scanner\\\", [], [[\\\"init\\\", code]]);" + "var token; while (!(token := s.\\\"scan\\\"()).\\\"eof\\\"()) { g_printn(token.\\\"to_string\\\"()); }" + "g_printn(\\\"Errors: \\\" + s.\\\"ERROR\\\"());" + "\");\n") println(codes[codes.size - 1]) val interpreter = Interpreter() val grammar = Grammar(codes[codes.size - 1]) println(grammar.toString()) val page = grammar.codePage //System.out.println(page.toString()); val baos = ByteArrayOutputStream() RuntimeCodePage.exportFromStream(page, baos) val bais = ByteArrayInputStream(baos.toByteArray()) interpreter.run("test_1", bais) } catch (e: RegexException) { System.err.println() System.err.println(e.position.toString() + "," + e.message) e.printStackTrace() } catch (e: SyntaxException) { System.err.println() System.err.println(String.format("模块名:%s. 位置:%s. 错误:%s-%s(%s:%d)", e.pageName, e.position, e.message, e.info, e.fileName, e.position.line + 1)) e.printStackTrace() } catch (e: RuntimeException) { System.err.println() System.err.println(e.position.toString() + ": " + e.info) e.printStackTrace() } catch (e: Exception) { System.err.println() System.err.println(e.message) e.printStackTrace() } } }
src/main/kotlin/com/bajdcc/LALR1/interpret/test/TestInterpret13.kt
687287720
package bz.bracken.stewart.db import bz.stewart.bracken.shared.DateUtils import org.junit.Assert.assertTrue import org.junit.Test /** * Created by stew on 4/4/17. */ class DateUtilsTests { @Test fun standardWriteFormatTest(){ val v = DateUtils.standardWriteFormat() assertTrue(v.parse("2017-02-18T03:08:00.000Z").time == 1487387280000) } }
db/src/test/kotlin/bz/bracken/stewart/db/DateUtilsTests.kt
211417861
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.core.util import kotlin.math.pow import kotlin.random.Random as KotlinRandom /** * Instance of [kotlin.random.Random] to use arcs-wide. * * TODO: Consider seeding the random object ourselves. Unfortunately kotlin.system.getTimeMillis * isn't in the common kotlin library. This will mean we need to make this an `expect` and * implement it for JVM, JS, and WASM targets. Bonus points for using SecureRandom when running in * JVM. */ val Random: KotlinRandom get() = RandomBuilder(null) /** * Generator of a kotlin random class instance. * * This variable is configurable so as to make it possible for tests to make predictable 'random' * behavior possible. */ var RandomBuilder: (seed: Long?) -> KotlinRandom = fn@{ seed -> val globalRandom = globalRandomInstance @Suppress("IfThenToElvis") // Because it's more readable like this. if (globalRandom != null) { // If we've already initialized the global random instance, use it. return@fn globalRandom } else { // Looks like we need to initialize it still, so - depending on whether or not we have a // seed, either return a seeded KotlinRandom, or the default. return@fn (seed?.let { KotlinRandom(seed) } ?: KotlinRandom.Default) // Stash it as the global instance. .also { globalRandomInstance = it } } } /** Gets the next Arcs-safe random long value. */ fun KotlinRandom.nextSafeRandomLong(): Long = Random.nextLong(MAX_SAFE_LONG) /** Gets the next String of [length] that can be safely encoded in a [VersionMap]. */ fun KotlinRandom.nextVersionMapSafeString(length: Int): String { return (1..length) .map { SAFE_CHARS.random(Random) } .joinToString("") } private val MAX_SAFE_LONG = 2.0.pow(50).toLong() private var globalRandomInstance: KotlinRandom? = null /** Set of strings not allowed in [VersionMaps], entity [Id]s and [StorageKey]s. */ val FORBIDDEN_STRINGS = setOf( "{", "}", ENTRIES_SEPARATOR.toString(), ACTOR_VERSION_DELIMITER.toString() ) // Readable chars are 33 '!' to 126 '~'. However, we want to exclude the [FORBIDDEN_STRINGS]. /** Chars that are safe to use in encoding. */ val SAFE_CHARS = ('!'..'~') - FORBIDDEN_STRINGS.map { s -> s[0] }
java/arcs/core/util/random.kt
1719857059
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ui import com.intellij.openapi.util.ScalableIcon import com.intellij.util.IconUtil import org.jetbrains.annotations.ApiStatus import java.awt.* import java.awt.geom.Path2D import javax.swing.Icon @ApiStatus.Internal @ApiStatus.Experimental abstract class HoledIcon(private val icon: Icon) : RetrievableIcon, ScalableIcon { protected abstract fun copyWith(icon: Icon):Icon protected abstract fun createHole(width: Int, height: Int): Shape? protected abstract fun paintHole(g: Graphics2D, width: Int, height: Int) override fun retrieveIcon() = icon override fun getScale() = (icon as? ScalableIcon)?.scale ?: 1f override fun scale(factor: Float) = copyWith(IconUtil.scaleOrLoadCustomVersion(icon, factor)) override fun getIconWidth() = icon.iconWidth override fun getIconHeight() = icon.iconHeight override fun paintIcon(c: Component?, graphics: Graphics, x: Int, y: Int) { val width = iconWidth val height = iconHeight val g = graphics.create(x, y, width, height) try { val hole = createHole(width, height) if (hole != null) { val area = g.clip if (g is Graphics2D) { g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE) g.clip(hole) // do not allow painting outside the hole paintHole(g, width, height) } // subtract hole from old clip val path = Path2D.Float(Path2D.WIND_EVEN_ODD) path.append(area, false) path.append(hole, false) g.clip = path // safe because based on old clip } icon.paintIcon(c, g, 0, 0) } finally { g.dispose() } } }
platform/core-ui/src/ui/HoledIcon.kt
1787061529
package au.com.dius.pact.provider.junit import au.com.dius.pact.provider.junitsupport.loader.PactFolder import au.com.dius.pact.provider.junit.target.HttpTarget import au.com.dius.pact.provider.junitsupport.target.TestTarget import au.com.dius.pact.provider.junitsupport.Provider import au.com.dius.pact.provider.junitsupport.State import au.com.dius.pact.provider.junitsupport.TargetRequestFilter import com.github.restdriver.clientdriver.ClientDriverRule import com.github.restdriver.clientdriver.RestClientDriver.giveEmptyResponse import com.github.restdriver.clientdriver.RestClientDriver.onRequestTo import org.apache.http.HttpRequest import org.junit.Before import org.junit.BeforeClass import org.junit.ClassRule import org.junit.runner.RunWith import org.slf4j.LoggerFactory @RunWith(PactRunner::class) @Provider("myAwesomeService") @PactFolder("pacts") class KotlinContractTest { @TestTarget val target = HttpTarget(port = 8332) @Before fun before() { // Rest data // Mock dependent service responses // ... embeddedService.addExpectation( onRequestTo("/data").withAnyParams(), giveEmptyResponse() ) } @State("default") fun toDefaultState() { // Prepare service before interaction that require "default" state // ... LOGGER.info("Now service in default state") } @State("state 2") fun toSecondState(params: Map<*, *>) { // Prepare service before interaction that require "state 2" state // ... LOGGER.info("Now service in 'state 2' state: $params") } @TargetRequestFilter fun exampleRequestFilter(request: HttpRequest) { LOGGER.info("exampleRequestFilter called: $request") } companion object { // NOTE: this is just an example of embedded service that listens to requests, you should start here real service @ClassRule @JvmField val embeddedService = ClientDriverRule(8332) private val LOGGER = LoggerFactory.getLogger(KotlinContractTest::class.java) @BeforeClass fun setUpService() { // Run DB, create schema // Run service // ... } } }
provider/junit/src/test/kotlin/au/com/dius/pact/provider/junit/KotlinContractTest.kt
2399185835
package org.wordpress.android.util.experiments import dagger.Lazy import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.never import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoInteractions import org.mockito.kotlin.whenever import org.wordpress.android.BaseUnitTest import org.wordpress.android.fluxc.model.experiments.Assignments import org.wordpress.android.fluxc.model.experiments.Variation import org.wordpress.android.fluxc.model.experiments.Variation.Control import org.wordpress.android.fluxc.model.experiments.Variation.Treatment import org.wordpress.android.fluxc.store.AccountStore import org.wordpress.android.fluxc.store.ExperimentStore import org.wordpress.android.fluxc.store.ExperimentStore.OnAssignmentsFetched import org.wordpress.android.fluxc.utils.AppLogWrapper import org.wordpress.android.test import org.wordpress.android.testScope import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper import java.util.Date @RunWith(MockitoJUnitRunner::class) class ExPlatTest : BaseUnitTest() { @Mock lateinit var experiments: Lazy<Set<Experiment>> @Mock lateinit var experimentStore: ExperimentStore @Mock lateinit var appLog: AppLogWrapper @Mock lateinit var accountStore: AccountStore @Mock lateinit var analyticsTracker: AnalyticsTrackerWrapper private lateinit var exPlat: ExPlat private lateinit var dummyExperiment: Experiment @Before fun setUp() { exPlat = ExPlat(experiments, experimentStore, appLog, accountStore, analyticsTracker, testScope()) dummyExperiment = object : Experiment(DUMMY_EXPERIMENT_NAME, exPlat) {} whenever(accountStore.hasAccessToken()).thenReturn(true) whenever(analyticsTracker.getAnonID()).thenReturn(DUMMY_ANON_ID) setupExperiments(setOf(dummyExperiment)) } @Test fun `refreshIfNeeded fetches assignments if cache is null`() = test { setupAssignments(cachedAssignments = null, fetchedAssignments = buildAssignments()) exPlat.refreshIfNeeded() verify(experimentStore, times(1)).fetchAssignments(any(), any(), anyOrNull()) } @Test fun `refreshIfNeeded fetches assignments if cache is stale`() = test { setupAssignments(cachedAssignments = buildAssignments(isStale = true), fetchedAssignments = buildAssignments()) exPlat.refreshIfNeeded() verify(experimentStore, times(1)).fetchAssignments(any(), any(), anyOrNull()) } @Test fun `refreshIfNeeded does not fetch assignments if cache is fresh`() = test { setupAssignments(cachedAssignments = buildAssignments(isStale = false), fetchedAssignments = buildAssignments()) exPlat.refreshIfNeeded() verify(experimentStore, never()).fetchAssignments(any(), any(), anyOrNull()) } @Test fun `forceRefresh fetches assignments if cache is fresh`() = test { setupAssignments(cachedAssignments = buildAssignments(isStale = true), fetchedAssignments = buildAssignments()) exPlat.forceRefresh() verify(experimentStore, times(1)).fetchAssignments(any(), any(), anyOrNull()) } @Test fun `clear calls experiment store`() = test { exPlat.clear() verify(experimentStore, times(1)).clearCachedAssignments() } @Test fun `getVariation fetches assignments if cache is null`() = test { setupAssignments(cachedAssignments = null, fetchedAssignments = buildAssignments()) exPlat.getVariation(dummyExperiment, shouldRefreshIfStale = true) verify(experimentStore, times(1)).fetchAssignments(any(), any(), anyOrNull()) } @Test fun `getVariation fetches assignments if cache is stale`() = test { setupAssignments(cachedAssignments = buildAssignments(isStale = true), fetchedAssignments = buildAssignments()) exPlat.getVariation(dummyExperiment, shouldRefreshIfStale = true) verify(experimentStore, times(1)).fetchAssignments(any(), any(), anyOrNull()) } @Test fun `getVariation does not fetch assignments if cache is fresh`() = test { setupAssignments(cachedAssignments = buildAssignments(isStale = false), fetchedAssignments = buildAssignments()) exPlat.getVariation(dummyExperiment, shouldRefreshIfStale = true) verify(experimentStore, never()).fetchAssignments(any(), any(), anyOrNull()) } @Test fun `getVariation does not fetch assignments if cache is null but shouldRefreshIfStale is false`() = test { setupAssignments(cachedAssignments = null, fetchedAssignments = buildAssignments()) exPlat.getVariation(dummyExperiment, shouldRefreshIfStale = false) verify(experimentStore, never()).fetchAssignments(any(), any(), anyOrNull()) } @Test fun `getVariation does not fetch assignments if cache is stale but shouldRefreshIfStale is false`() = test { setupAssignments(cachedAssignments = null, fetchedAssignments = buildAssignments()) exPlat.getVariation(dummyExperiment, shouldRefreshIfStale = false) verify(experimentStore, never()).fetchAssignments(any(), any(), anyOrNull()) } @Test fun `getVariation does not return different cached assignments if active variation exists`() = test { val controlVariation = Control val treatmentVariation = Treatment("treatment") val treatmentAssignments = buildAssignments(variations = mapOf(dummyExperiment.name to treatmentVariation)) setupAssignments(cachedAssignments = null, fetchedAssignments = treatmentAssignments) val firstVariation = exPlat.getVariation(dummyExperiment, shouldRefreshIfStale = false) assertThat(firstVariation).isEqualTo(controlVariation) exPlat.forceRefresh() setupAssignments(cachedAssignments = treatmentAssignments, fetchedAssignments = treatmentAssignments) val secondVariation = exPlat.getVariation(dummyExperiment, shouldRefreshIfStale = false) assertThat(secondVariation).isEqualTo(controlVariation) } @Test fun `forceRefresh fetches assignments if experiments is not empty`() = test { setupExperiments(setOf(dummyExperiment)) exPlat.forceRefresh() verify(experimentStore, times(1)).fetchAssignments(any(), any(), anyOrNull()) } @Test fun `forceRefresh does not interact with store if experiments is empty`() = test { setupExperiments(emptySet()) exPlat.forceRefresh() verifyNoInteractions(experimentStore) } @Test fun `refreshIfNeeded does not interact with store if experiments is empty`() = test { setupExperiments(emptySet()) exPlat.refreshIfNeeded() verifyNoInteractions(experimentStore) } @Test @Suppress("SwallowedException") fun `getVariation does not interact with store if experiments is empty`() = test { setupExperiments(emptySet()) try { exPlat.getVariation(dummyExperiment, false) } catch (e: IllegalArgumentException) { // Do nothing. } finally { verifyNoInteractions(experimentStore) } } @Test @Suppress("MaxLineLength") fun `refreshIfNeeded does not interact with store if the user is not authorised and there is no anonymous id`() = test { setupExperiments(setOf(dummyExperiment)) whenever(accountStore.hasAccessToken()).thenReturn(false) whenever(analyticsTracker.getAnonID()).thenReturn(null) exPlat.refreshIfNeeded() verifyNoInteractions(experimentStore) } @Test @Suppress("MaxLineLength") fun `forceRefresh does not interact with store if the user is not authorised and there is no anonymous id`() = test { setupExperiments(setOf(dummyExperiment)) whenever(accountStore.hasAccessToken()).thenReturn(false) whenever(analyticsTracker.getAnonID()).thenReturn(null) exPlat.forceRefresh() verifyNoInteractions(experimentStore) } @Test fun `refreshIfNeeded does interact with store if the user is authorised`() = test { setupExperiments(setOf(dummyExperiment)) whenever(accountStore.hasAccessToken()).thenReturn(true) whenever(analyticsTracker.getAnonID()).thenReturn(null) exPlat.refreshIfNeeded() verify(experimentStore, times(1)).fetchAssignments(any(), any(), anyOrNull()) } @Test fun `forceRefresh does interact with store if the user is authorised`() = test { setupExperiments(setOf(dummyExperiment)) whenever(accountStore.hasAccessToken()).thenReturn(true) whenever(analyticsTracker.getAnonID()).thenReturn(null) exPlat.forceRefresh() verify(experimentStore, times(1)).fetchAssignments(any(), any(), anyOrNull()) } @Test fun `refreshIfNeeded does interact with store if there is an anonymous id`() = test { setupExperiments(setOf(dummyExperiment)) whenever(accountStore.hasAccessToken()).thenReturn(false) whenever(analyticsTracker.getAnonID()).thenReturn(DUMMY_ANON_ID) exPlat.refreshIfNeeded() verify(experimentStore, times(1)).fetchAssignments(any(), any(), anyOrNull()) } @Test fun `forceRefresh does interact with store if there is an anonymous id`() = test { setupExperiments(setOf(dummyExperiment)) whenever(accountStore.hasAccessToken()).thenReturn(false) whenever(analyticsTracker.getAnonID()).thenReturn(DUMMY_ANON_ID) exPlat.forceRefresh() verify(experimentStore, times(1)).fetchAssignments(any(), any(), anyOrNull()) } private fun setupExperiments(experiments: Set<Experiment>) { whenever(this.experiments.get()).thenReturn(experiments) } private suspend fun setupAssignments(cachedAssignments: Assignments?, fetchedAssignments: Assignments) { whenever(experimentStore.getCachedAssignments()).thenReturn(cachedAssignments) whenever(experimentStore.fetchAssignments(any(), any(), anyOrNull())) .thenReturn(OnAssignmentsFetched(fetchedAssignments)) } private fun buildAssignments( isStale: Boolean = false, variations: Map<String, Variation> = emptyMap() ): Assignments { val now = System.currentTimeMillis() val oneHourAgo = now - ONE_HOUR_IN_SECONDS * 1000 val oneHourFromNow = now + ONE_HOUR_IN_SECONDS * 1000 return if (isStale) { Assignments(variations, ONE_HOUR_IN_SECONDS, Date(oneHourAgo)) } else { Assignments(variations, ONE_HOUR_IN_SECONDS, Date(oneHourFromNow)) } } companion object { private const val ONE_HOUR_IN_SECONDS = 3600 private const val DUMMY_ANON_ID = "dummy_anon_id" private const val DUMMY_EXPERIMENT_NAME = "dummy" } }
WordPress/src/test/java/org/wordpress/android/util/experiments/ExPlatTest.kt
2008374774
package forpdateam.ru.forpda.presentation.devdb.device import moxy.InjectViewState import forpdateam.ru.forpda.common.Utils import forpdateam.ru.forpda.common.mvp.BasePresenter import forpdateam.ru.forpda.entity.remote.devdb.Device import forpdateam.ru.forpda.model.repository.devdb.DevDbRepository import forpdateam.ru.forpda.presentation.IErrorHandler import forpdateam.ru.forpda.presentation.ILinkHandler import forpdateam.ru.forpda.presentation.Screen import forpdateam.ru.forpda.presentation.TabRouter import forpdateam.ru.forpda.ui.fragments.devdb.device.posts.PostsFragment /** * Created by radiationx on 11.11.17. */ @InjectViewState class SubDevicePresenter( private val router: TabRouter, private val linkHandler: ILinkHandler ) : BasePresenter<SubDeviceView>() { fun onCommentClick(item: Device.Comment) { linkHandler.handle("https://4pda.to/forum/index.php?showuser=${item.userId}", router) } fun onPostClick(item: Device.PostItem, source: Int) { val url = if (source == PostsFragment.SRC_NEWS) { "https://4pda.to/index.php?p=${item.id}" } else { "https://4pda.to/forum/index.php?showtopic=${item.id}" } linkHandler.handle(url, router) } }
app/src/main/java/forpdateam/ru/forpda/presentation/devdb/device/SubDevicePresenter.kt
2270287201
package forpdateam.ru.forpda.model import forpdateam.ru.forpda.R import forpdateam.ru.forpda.entity.app.other.AppMenuItem import forpdateam.ru.forpda.model.interactors.other.MenuRepository import forpdateam.ru.forpda.ui.views.drawers.adapters.DrawerMenuItem object MenuMapper { fun mapToDrawer(item: AppMenuItem): DrawerMenuItem = DrawerMenuItem( getTitle(item), getIcon(item), item ) fun getTitle(item: AppMenuItem): Int = when (item.id) { MenuRepository.item_auth -> R.string.fragment_title_auth MenuRepository.item_article_list -> R.string.fragment_title_news_list MenuRepository.item_favorites -> R.string.fragment_title_favorite MenuRepository.item_qms_contacts -> R.string.fragment_title_contacts MenuRepository.item_mentions -> R.string.fragment_title_mentions MenuRepository.item_dev_db -> R.string.fragment_title_devdb MenuRepository.item_forum -> R.string.fragment_title_forum MenuRepository.item_search -> R.string.fragment_title_search MenuRepository.item_history -> R.string.fragment_title_history MenuRepository.item_notes -> R.string.fragment_title_notes MenuRepository.item_forum_rules -> R.string.fragment_title_forum_rules MenuRepository.item_settings -> R.string.activity_title_settings MenuRepository.item_other_menu -> R.string.fragment_title_other_menu MenuRepository.item_link_forum_author -> R.string.menu_item_link_forum_author MenuRepository.item_link_chat_telegram -> R.string.menu_item_link_chat_telegram MenuRepository.item_link_forum_topic -> R.string.menu_item_link_forum_topic MenuRepository.item_link_forum_faq -> R.string.menu_item_link_forum_faq MenuRepository.item_link_play_market -> R.string.menu_item_link_play_market MenuRepository.item_link_github -> R.string.menu_item_link_github MenuRepository.item_link_bitbucket -> R.string.menu_item_link_bitbucket else -> R.string.error } fun getIcon(item: AppMenuItem): Int = when (item.id) { MenuRepository.item_auth -> R.drawable.ic_person_add MenuRepository.item_article_list -> R.drawable.ic_newspaper MenuRepository.item_favorites -> R.drawable.ic_star MenuRepository.item_qms_contacts -> R.drawable.ic_contacts MenuRepository.item_mentions -> R.drawable.ic_notifications MenuRepository.item_dev_db -> R.drawable.ic_devices_other MenuRepository.item_forum -> R.drawable.ic_forum MenuRepository.item_search -> R.drawable.ic_search MenuRepository.item_history -> R.drawable.ic_history MenuRepository.item_notes -> R.drawable.ic_bookmark MenuRepository.item_forum_rules -> R.drawable.ic_book_open MenuRepository.item_settings -> R.drawable.ic_settings MenuRepository.item_other_menu -> R.drawable.ic_toolbar_hamburger MenuRepository.item_link_forum_author -> R.drawable.ic_account_circle MenuRepository.item_link_chat_telegram -> R.drawable.ic_logo_telegram MenuRepository.item_link_forum_topic -> R.drawable.ic_logo_4pda MenuRepository.item_link_forum_faq -> R.drawable.ic_logo_4pda MenuRepository.item_link_play_market -> R.drawable.ic_logo_google_play MenuRepository.item_link_github -> R.drawable.ic_logo_github_circle MenuRepository.item_link_bitbucket -> R.drawable.ic_logo_bitbucket else -> R.drawable.ic_thumb_down } }
app/src/main/java/forpdateam/ru/forpda/model/MenuMapper.kt
2362101134
package com.edwardharker.aircraftrecognition.ui import android.content.res.Resources fun Int.dpToPixels(): Int { return (this * Resources.getSystem().displayMetrics.density).toInt() } fun Int.pixelsToDp(): Int { return (this / Resources.getSystem().displayMetrics.density).toInt() }
androidcommon/src/main/kotlin/com/edwardharker/aircraftrecognition/ui/DimensionUtil.kt
139925581
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import com.intellij.psi.search.searches.ReferencesSearch import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.idea.references.KtReference import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset class ValToObjectIntention : SelfTargetingIntention<KtProperty>( KtProperty::class.java, KotlinBundle.lazyMessage("convert.to.object.declaration") ) { override fun isApplicableTo(element: KtProperty, caretOffset: Int): Boolean { if (element.isVar) return false if (!element.isTopLevel) return false val initializer = element.initializer as? KtObjectLiteralExpression ?: return false if (initializer.objectDeclaration.body == null) return false if (element.getter != null) return false if (element.annotationEntries.isNotEmpty()) return false // disable if has non-Kotlin usages return ReferencesSearch.search(element).all { it is KtReference && it.element.parent !is KtCallableReferenceExpression } } override fun applyTo(element: KtProperty, editor: Editor?) { val name = element.name ?: return val objectLiteral = element.initializer as? KtObjectLiteralExpression ?: return val declaration = objectLiteral.objectDeclaration val superTypeList = declaration.getSuperTypeList() val body = declaration.body ?: return val prefix = element.modifierList?.text?.plus(" ") ?: "" val superTypesText = superTypeList?.text?.plus(" ") ?: "" val replacementText = "${prefix}object $name: $superTypesText${body.text}" val replaced = element.replaced(KtPsiFactory(element).createDeclarationByPattern<KtObjectDeclaration>(replacementText)) editor?.caretModel?.moveToOffset(replaced.nameIdentifier?.endOffset ?: return) } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ValToObjectIntention.kt
3584111885
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo import com.intellij.openapi.project.Project import com.intellij.openapi.roots.libraries.Library import org.jetbrains.kotlin.platform.CommonPlatforms import org.jetbrains.kotlin.platform.TargetPlatform class CommonKlibLibraryInfo( project: Project, library: Library, libraryRoot: String ) : AbstractKlibLibraryInfo(project, library, libraryRoot) { override val platform: TargetPlatform get() = CommonPlatforms.defaultCommonPlatform }
plugins/kotlin/base/project-structure/src/org/jetbrains/kotlin/idea/base/projectStructure/moduleInfo/CommonKlibLibraryInfo.kt
1277056422
package dev.mfazio.pennydrop.viewmodels import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dev.mfazio.pennydrop.game.GameHandler import dev.mfazio.pennydrop.game.TurnEnd import dev.mfazio.pennydrop.game.TurnResult import dev.mfazio.pennydrop.types.Player import dev.mfazio.pennydrop.types.Slot import dev.mfazio.pennydrop.types.clear import kotlinx.coroutines.delay import kotlinx.coroutines.launch class GameViewModel : ViewModel() { private var players: List<Player> = emptyList() val slots = MutableLiveData( (1..6).map { slotNum -> Slot(slotNum, slotNum != 6) } ) val currentPlayer = MutableLiveData<Player?>() val canRoll = MutableLiveData(false) val canPass = MutableLiveData(false) val currentTurnText = MutableLiveData("") val currentStandingsText = MutableLiveData("") private var clearText = false fun startGame(playersForNewGame: List<Player>) { this.players = playersForNewGame this.currentPlayer.value = this.players.firstOrNull().apply { this?.isRolling = true } canRoll.value = true canPass.value = false slots.value?.clear() slots.notifyChange() currentTurnText.value = "The game has begun!\n" currentStandingsText.value = generateCurrentStandings(this.players) } fun roll() { slots.value?.let { currentSlots -> // Comparing against true saves us a null check val currentPlayer = players.firstOrNull { it.isRolling } if (currentPlayer != null && canRoll.value == true) { updateFromGameHandler( GameHandler.roll(players, currentPlayer, currentSlots) ) } } } fun pass() { val currentPlayer = players.firstOrNull { it.isRolling } if (currentPlayer != null && canPass.value == true) { updateFromGameHandler(GameHandler.pass(players, currentPlayer)) } } private fun updateFromGameHandler(result: TurnResult) { if (result.currentPlayer != null) { currentPlayer.value?.addPennies(result.coinChangeCount ?: 0) currentPlayer.value = result.currentPlayer this.players.forEach { player -> player.isRolling = result.currentPlayer == player } } if (result.lastRoll != null) { slots.value?.let { currentSlots -> updateSlots(result, currentSlots, result.lastRoll) } } currentTurnText.value = generateTurnText(result) currentStandingsText.value = generateCurrentStandings(this.players) canRoll.value = result.canRoll canPass.value = result.canPass if (!result.isGameOver && result.currentPlayer?.isHuman == false) { canRoll.value = false canPass.value = false playAITurn() } } private fun updateSlots( result: TurnResult, currentSlots: List<Slot>, lastRoll: Int ) { if (result.clearSlots) currentSlots.clear() currentSlots.firstOrNull { it.lastRolled }?.apply { lastRolled = false } currentSlots.getOrNull(lastRoll - 1)?.also { slot -> if (!result.clearSlots && slot.canBeFilled) slot.isFilled = true slot.lastRolled = true } slots.notifyChange() } private fun generateCurrentStandings( players: List<Player>, headerText: String = "Current Standings:" ) = players.sortedBy { it.pennies }.joinToString( separator = "\n", prefix = "$headerText\n" ) { "\t${it.playerName} - ${it.pennies} pennies" } private fun generateTurnText(result: TurnResult): String { if (clearText) currentTurnText.value = "" clearText = result.turnEnd != null val currentText = currentTurnText.value ?: "" val currentPlayerName = result.currentPlayer?.playerName ?: "???" return when { result.isGameOver -> """Game Over! |$currentPlayerName is the winner! | |${generateCurrentStandings(this.players, "Final Scores:\n")} """.trimMargin() result.turnEnd == TurnEnd.Bust -> "${ohNoPhrases.shuffled().first()} ${result.previousPlayer?.playerName} rolled a ${result.lastRoll}. They collected ${result.coinChangeCount} pennies for a total of ${result.previousPlayer?.pennies}.\n$currentText" result.turnEnd == TurnEnd.Pass -> "${result.previousPlayer?.playerName} passed. They currently have ${result.previousPlayer?.pennies} pennies.\n$currentText" result.lastRoll != null -> "$currentPlayerName rolled a ${result.lastRoll}.\n$currentText" else -> "" } } private fun playAITurn() { viewModelScope.launch { delay(1000) slots.value?.let { currentSlots -> val currentPlayer = players.firstOrNull { it.isRolling } if (currentPlayer != null && !currentPlayer.isHuman) { GameHandler.playAITurn( players, currentPlayer, currentSlots, canPass.value == true )?.let { result -> updateFromGameHandler(result) } } } } } // I added this at the request of my wife, who wanted to see a bunch of "oh no!" phrases added in. // They make me smile. private val ohNoPhrases = listOf( "Oh no!", "Bummer!", "Dang.", "Whoops.", "Ah, fiddlesticks.", "Oh, kitty cats.", "Piffle.", "Well, crud.", "Ah, cinnamon bits.", "Ooh, bad luck.", "Shucks!", "Woopsie daisy.", "Nooooooo!", "Aw, rats and bats.", "Blood and thunder!", "Gee whillikins.", "Well that's disappointing.", "I find your lack of luck disturbing.", "That stunk, huh?", "Uff da." ) // This is included because changing a single item in a list won't automatically update. private fun <T> MutableLiveData<List<T>>.notifyChange() { this.value = this.value } }
kotlin/kotlin-and-android-development-featuring-jetpack/chapter-4/app/src/main/java/dev/mfazio/pennydrop/viewmodels/GameViewModel.kt
3582820965
package edu.byu.support.client.campusLocation.model import com.google.gson.annotations.SerializedName import edu.byu.support.utils.toTitleCase /** * Created by cwoodfie on 11/28/16. */ data class RoomResponseWrapper( @SerializedName("room") val rooms: List<Room>? = null ) { data class Room( @SerializedName("@room") val room: String? = null, @SerializedName("@building") val building: String? = null ): Comparable<Room> { companion object { private const val REGEX = "[^\\d]*(\\d+)[^\\d]*" private const val REPLACEMENT = "$1" } @SerializedName("@roomDesc") val roomDesc: String? = null //Custom getter cleans up the descriptions returned get() = field?.toTitleCase() ?.replace("(?<=(Wom|M)en)(s'? | )".toRegex(), "'s ") ?.replace("Rest Room|Rrm".toRegex(), "Restroom") ?.replace("Handicapd".toRegex(), "Handicapped") ?.replace("Vesitbule|Vestibuile".toRegex(), "Vestibule") ?.replace("([Rr])[om]( |$)".toRegex(), "$1oom$2") ?.replace("Crmry ".toRegex(), "") ?.replace("(?<!\\s)\\(".toRegex(), " (") val roomValue get() = room?.let { // The parseInt will crash if the string is empty so we check for that val numberString = it.replaceFirst(REGEX.toRegex(), REPLACEMENT) if (numberString.isNotEmpty()) { Integer.parseInt(numberString) } else { null } } override fun compareTo(other: Room): Int { val returnValue = compareValues(roomValue, other.roomValue) return if (returnValue == 0) { //If the room numbers are the same, sort by string to take into account letters compareValues(room, other.room) } else returnValue } } }
support/src/main/java/edu/byu/support/client/campusLocation/model/RoomResponseWrapper.kt
2146567648
package dev.mfazio.abl.settings import android.os.Bundle import android.util.Log import android.util.TypedValue import androidx.core.content.ContextCompat import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.preference.* import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import androidx.work.workDataOf import dev.mfazio.abl.R import dev.mfazio.abl.api.services.getDefaultABLService import dev.mfazio.abl.teams.UITeam import kotlinx.coroutines.launch class SettingsFragment : PreferenceFragmentCompat() { private lateinit var favoriteTeamPreference: DropDownPreference private lateinit var favoriteTeamColorPreference: SwitchPreferenceCompat private lateinit var startingScreenPreference: DropDownPreference private lateinit var usernamePreference: EditTextPreference override fun onCreatePreferences( savedInstanceState: Bundle?, rootKey: String? ) { val ctx = preferenceManager.context val screen = preferenceManager.createPreferenceScreen(ctx) this.usernamePreference = EditTextPreference(ctx).apply { key = usernamePreferenceKey title = getString(R.string.user_name) summaryProvider = EditTextPreference.SimpleSummaryProvider.getInstance() onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue -> loadSettings(newValue?.toString()) true } } screen.addPreference(usernamePreference) this.favoriteTeamPreference = DropDownPreference(ctx).apply { key = favoriteTeamPreferenceKey title = getString(R.string.favorite_team) entries = (listOf(getString(R.string.none)) + UITeam.allTeams.map { it.teamName }).toTypedArray() entryValues = (listOf("") + UITeam.allTeams.map { it.teamId }).toTypedArray() setDefaultValue("") summaryProvider = ListPreference.SimpleSummaryProvider.getInstance() } this.favoriteTeamColorPreference = SwitchPreferenceCompat(ctx).apply { key = favoriteTeamColorsPreferenceKey title = getString(R.string.team_color_nav_bar) setDefaultValue(false) } favoriteTeamPreference.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue -> val teamId = newValue?.toString() if (favoriteTeamColorPreference.isChecked) { setNavBarColorForTeam(teamId) } if (teamId != null) { favoriteTeamPreference.icon = getIconForTeam(teamId) } saveSettings(favoriteTeam = teamId) true } screen.addPreference(favoriteTeamPreference) favoriteTeamColorPreference.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue -> val useFavoriteTeamColor = newValue as? Boolean setNavBarColorForTeam( if (useFavoriteTeamColor == true) { favoriteTeamPreference.value } else null ) saveSettings(useFavoriteTeamColor = useFavoriteTeamColor) true } screen.addPreference(favoriteTeamColorPreference) this.startingScreenPreference = DropDownPreference(ctx).apply { key = startingScreenPreferenceKey title = getString(R.string.starting_location) entries = startingScreens.keys.toTypedArray() entryValues = startingScreens.keys.toTypedArray() summaryProvider = ListPreference.SimpleSummaryProvider.getInstance() setDefaultValue(R.id.scoreboardFragment.toString()) onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue -> saveSettings(startingScreen = newValue?.toString()) true } } screen.addPreference(startingScreenPreference) val aboutCategory = PreferenceCategory(ctx).apply { key = aboutPreferenceCategoryKey title = getString(R.string.about) } screen.addPreference(aboutCategory) val aboutTheAppPreference = Preference(ctx).apply { key = aboutTheAppPreferenceKey title = getString(R.string.about_the_app) summary = getString(R.string.info_about_the_app) onPreferenceClickListener = Preference.OnPreferenceClickListener { [email protected]().navigate( R.id.aboutTheAppFragment ) true } } aboutCategory.addPreference(aboutTheAppPreference) val creditsPreference = Preference(ctx).apply { key = creditsPreferenceKey title = getString(R.string.credits) summary = getString(R.string.image_credits) onPreferenceClickListener = Preference.OnPreferenceClickListener { [email protected]().navigate( R.id.imageCreditsFragment ) true } } aboutCategory.addPreference(creditsPreference) preferenceScreen = screen } override fun onBindPreferences() { favoriteTeamPreference.icon = getIconForTeam(favoriteTeamPreference.value) } private fun getIconForTeam(teamId: String) = UITeam.fromTeamId(teamId)?.let { team -> ContextCompat.getDrawable(requireContext(), team.logoId) } private fun setNavBarColorForTeam(teamId: String?) { val color = UITeam.getTeamPalette(requireContext(), teamId) ?.dominantSwatch ?.rgb ?: getDefaultColor() activity?.window?.navigationBarColor = color } private fun getDefaultColor(): Int { val colorValue = TypedValue() activity?.theme?.resolveAttribute( R.attr.colorPrimary, colorValue, true ) return colorValue.data } private fun saveSettings( userName: String? = usernamePreference.text, favoriteTeam: String? = favoriteTeamPreference.value, useFavoriteTeamColor: Boolean? = favoriteTeamColorPreference.isChecked, startingScreen: String? = startingScreenPreference.value ) { if (userName != null) { WorkManager.getInstance(requireContext()).enqueue( OneTimeWorkRequestBuilder<SaveSettingsWorker>() .setInputData( workDataOf( SaveSettingsWorker.userNameKey to userName, SaveSettingsWorker.favoriteTeamKey to favoriteTeam, SaveSettingsWorker.favoriteTeamColorCheckKey to useFavoriteTeamColor, SaveSettingsWorker.startingScreenKey to startingScreen ) ).build() ) } } private fun loadSettings(userName: String? = null) { if (userName != null) { viewLifecycleOwner.lifecycleScope.launch { try { val apiResult = getDefaultABLService().getAppSettingsForUser(userName) with(favoriteTeamPreference) { value = apiResult.favoriteTeamId icon = getIconForTeam(apiResult.favoriteTeamId) } setNavBarColorForTeam( if (apiResult.useTeamColorNavBar) { apiResult.favoriteTeamId } else null ) favoriteTeamColorPreference.isChecked = apiResult.useTeamColorNavBar startingScreenPreference.value = apiResult.startingLocation } catch (ex: Exception) { Log.i( TAG, """Settings not found. |This may just mean they haven't been initialized yet. |""".trimMargin() ) saveSettings(userName) } } } } companion object { const val TAG = "SettingsFragment" const val aboutPreferenceCategoryKey = "aboutCategory" const val aboutTheAppPreferenceKey = "aboutTheApp" const val creditsPreferenceKey = "credits" const val favoriteTeamPreferenceKey = "favoriteTeam" const val favoriteTeamColorsPreferenceKey = "useFavoriteTeamColors" const val startingScreenPreferenceKey = "startingScreen" const val usernamePreferenceKey = "username" } }
kotlin/kotlin-and-android-development-featuring-jetpack/chapter-12/app-code/app/src/main/java/dev/mfazio/abl/settings/SettingsFragment.kt
2688858788
package net.squanchy.support.time import com.google.firebase.Timestamp import org.threeten.bp.Instant import org.threeten.bp.LocalDate import org.threeten.bp.LocalDateTime import org.threeten.bp.ZoneId import org.threeten.bp.ZonedDateTime fun Timestamp.toInstant(): Instant = Instant.ofEpochMilli(toDate().time) fun Timestamp.toZonedDateTime(zoneId: ZoneId): ZonedDateTime = toInstant().atZone(zoneId) fun Timestamp.toLocalDate(zoneId: ZoneId): LocalDate = toZonedDateTime(zoneId).toLocalDate() fun Timestamp.toLocalDateTime(zoneId: ZoneId): LocalDateTime = toZonedDateTime(zoneId).toLocalDateTime()
app/src/main/java/net/squanchy/support/time/Timestamp.kt
888655588
package io.ipoli.android.player.usecase import io.ipoli.android.common.UseCase import io.ipoli.android.player.data.Player import io.ipoli.android.player.data.Player.Rank class FindPlayerRankUseCase : UseCase<FindPlayerRankUseCase.Params, FindPlayerRankUseCase.Result> { override fun execute(parameters: Params): Result { val attrLevels = parameters.playerAttributes.map { it.value.level } val level = parameters.playerLevel return when { level >= 100 && attrLevels.all { it >= 100 } -> Result(Rank.DIVINITY, null) level >= 90 && attrLevels.all { it >= 90 } -> Result(Rank.TITAN, Rank.DIVINITY) level >= 80 && attrLevels.all { it >= 80 } -> Result(Rank.DEMIGOD, Rank.TITAN) level >= 70 && attrLevels.all { it >= 70 } -> Result(Rank.IMMORTAL, Rank.DEMIGOD) level >= 60 && attrLevels.all { it >= 60 } -> Result(Rank.LEGEND, Rank.IMMORTAL) level >= 50 && attrLevels.all { it >= 50 } -> Result(Rank.MASTER, Rank.LEGEND) level >= 40 && attrLevels.all { it >= 40 } -> Result(Rank.EXPERT, Rank.MASTER) level >= 30 && attrLevels.all { it >= 30 } -> Result(Rank.SPECIALIST, Rank.EXPERT) level >= 20 && attrLevels.all { it >= 20 } -> Result(Rank.ADEPT, Rank.SPECIALIST) level >= 10 && attrLevels.all { it >= 10 } -> Result(Rank.APPRENTICE, Rank.ADEPT) else -> Result(Rank.NOVICE, Rank.APPRENTICE) } } data class Params( val playerAttributes: Map<Player.AttributeType, Player.Attribute>, val playerLevel: Int ) data class Result(val currentRank: Rank, val nextRank: Rank?) }
app/src/main/java/io/ipoli/android/player/usecase/FindPlayerRankUseCase.kt
1727330675
import com.intellij.javascript.nodejs.PackageJsonData import com.intellij.lang.javascript.JSBundle import com.intellij.lang.javascript.linter.JSLinterGuesser import com.intellij.lang.javascript.linter.JSLinterUtil import com.intellij.notification.Notification import com.intellij.notification.NotificationAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupManager import com.intellij.openapi.ui.MessageType import com.intellij.openapi.util.Ref import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.VirtualFile import com.intellij.platform.DirectoryProjectConfigurator import com.intellij.psi.search.FilenameIndex import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.containers.ContainerUtil class TemplateLintEnabler : DirectoryProjectConfigurator { override fun configureProject(project: Project, baseDir: VirtualFile, moduleRef: Ref<Module>, newProject: Boolean) { StartupManager.getInstance(project).runWhenProjectIsInitialized { guessTemplateLint(project) } } companion object { private val LOG = Logger.getInstance(TemplateLintEnabler::class.java) fun guessTemplateLint(project: Project) { if (Registry.`is`("javascript.linters.prevent.detection")) { LOG.info("Linters detection disabled") return } LOG.debug("Detecting linters for project") val packageJsonFiles: Collection<PackageJsonData> = ContainerUtil.map(FilenameIndex.getVirtualFilesByName(project, "package.json", GlobalSearchScope.projectScope(project))) { packageJsonFile: VirtualFile? -> PackageJsonData.getOrCreate(packageJsonFile!!) } packageJsonFiles.forEach { if (enableIfDependency(it, project, TemplateLintUtil.PACKAGE_NAME)) return if (enableIfDependency(it, project, TemplateLintUtil.CLI_PACKAGE_NAME)) return } } fun enableIfDependency(pkg: PackageJsonData, project: Project, dependency: String): Boolean { if (!pkg.isDependencyOfAnyType(dependency)) return false LOG.debug("$dependency is dependency, enabling it") templateLintEnabled(project, true) notifyEnabled(project, dependency) return true } fun templateLintEnabled(project: Project, enabled: Boolean) { TemplateLintConfiguration.getInstance(project).isEnabled = enabled } fun notifyEnabled(project: Project, dependency: String) { val message = JSBundle.message("js.linter.guesser.linter.enabled.because.of.package.json.section", "TemplateLint", dependency) JSLinterUtil.NOTIFICATION_GROUP.createNotification(message, MessageType.INFO).addAction(object : NotificationAction("Disable TemplateLint") { override fun actionPerformed(e: AnActionEvent, notification: Notification) { JSLinterGuesser.LOG.info("TemplateLint disabled by user") templateLintEnabled(project, false) JSLinterUtil.NOTIFICATION_GROUP.createNotification(JSBundle.message("js.linter.guesser.linter.disabled", "TemplateLint"), MessageType.INFO).notify(project) } }).notify(project) } } }
src/main/kotlin/com/emberjs/hbs/linter/ember-template-lint/TemplateLintEnabler.kt
930157257
package com.emberjs.hbs import com.emberjs.index.EmberNameIndex import com.emberjs.lookup.EmberLookupElementBuilder import com.emberjs.resolver.EmberName import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementResolveResult.createResults import com.intellij.psi.PsiManager import com.intellij.psi.PsiPolyVariantReferenceBase import com.intellij.psi.ResolveResult import com.intellij.psi.search.ProjectScope class HbsLinkToReference(element: PsiElement, range: TextRange, val moduleName: String) : PsiPolyVariantReferenceBase<PsiElement>(element, range, true) { private val project = element.project private val scope = ProjectScope.getAllScope(project) private val psiManager: PsiManager by lazy { PsiManager.getInstance(project) } override fun getVariants(): Array<out Any> { // Collect all components from the index return EmberNameIndex.getFilteredProjectKeys(scope) { matches(it) } // Convert search results for LookupElements .map { EmberLookupElementBuilder.create(it) } .toTypedArray() } override fun multiResolve(incompleteCode: Boolean): Array<out ResolveResult> { // Collect all components from the index return EmberNameIndex.getFilteredFiles(scope) { matches(it) && it.name == moduleName } // Convert search results for LookupElements .mapNotNull { psiManager.findFile(it) } .let(::createResults) } fun matches(module: EmberName): Boolean { if (module.type == "template") return !module.name.startsWith("components/") return module.type in MODULE_TYPES } companion object { val MODULE_TYPES = arrayOf("controller", "route") } }
src/main/kotlin/com/emberjs/hbs/HbsLinkToReference.kt
2319996784
// WITH_STDLIB // PROBLEM: none class A() { fun bar(): String = null!! } fun foo(a: A) { a.bar().substring<caret>(0, a.bar().length - 5) }
plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceSubstring/withDropLast/methodCallReceiver.kt
315368617
package org.intellij.plugins.markdown.parser class DefinitionListParserTest: MarkdownParsingTestCase("parser/definitionList") { fun `test simple`() = doTest(true) fun `test multiple definitions`() = doTest(true) fun `test with paragraph before`() = doTest(true) fun `test with paragraph after`() = doTest(true) fun `test with inlines`() = doTest(true) fun `test empty line after term`() = doTest(true) fun `test two empty lines break list`() = doTest(true) fun `test single empty line between definitions`() = doTest(true) fun `test multiple empty lines between definitions`() = doTest(true) fun `test definition continuation without indent`() = doTest(true) fun `test definition continuation with indent`() = doTest(true) fun `test definition with multiline continuation`() = doTest(true) fun `test multiple definitions with multiline continuation`() = doTest(true) override fun getTestName(lowercaseFirstLetter: Boolean): String { val name = super.getTestName(lowercaseFirstLetter) return name.trimStart().replace(' ', '_') } }
plugins/markdown/test/src/org/intellij/plugins/markdown/parser/DefinitionListParserTest.kt
4167681341
package com.fuzz.android.salvage /** * Description: */ fun String?.isNullOrEmpty(): Boolean { return this == null || this.trim { it <= ' ' }.isEmpty() || this == "null" } fun String?.capitalizeFirstLetter(): String { if (this == null || this.trim { it <= ' ' }.isEmpty()) { return this ?: "" } return this.substring(0, 1).toUpperCase() + this.substring(1) } fun String?.lower(): String { if (this == null || this.trim { it <= ' ' }.isEmpty()) { return this ?: "" } return this.substring(0, 1).toLowerCase() + this.substring(1) }
salvage-processor/src/main/java/com/fuzz/android/salvage/StringUtils.kt
1954005206
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.internal.statistics.logger import com.intellij.internal.statistic.eventLog.StatisticsEventLoggerProvider import org.junit.Test import kotlin.test.assertEquals class StatisticsEventLoggerProviderTest { @Test fun testParseLogFileSize() { assertEquals(200 * 1024, StatisticsEventLoggerProvider.parseFileSize("200KB")) assertEquals(2 * 1024 * 1024, StatisticsEventLoggerProvider.parseFileSize("2MB")) assertEquals(StatisticsEventLoggerProvider.DEFAULT_MAX_FILE_SIZE_BYTES, StatisticsEventLoggerProvider.parseFileSize("MB")) assertEquals(StatisticsEventLoggerProvider.DEFAULT_MAX_FILE_SIZE_BYTES, StatisticsEventLoggerProvider.parseFileSize("15")) } }
platform/platform-tests/testSrc/com/intellij/internal/statistics/logger/StatisticsEventLoggerProviderTest.kt
4126579433
package org.jetbrains.deft interface Obj interface ObjBuilder<T : Obj>
platform/workspaceModel/storage/src/com/intellij/workspaceModel/deft/api/Obj.kt
3642007101
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.tests import io.ktor.client.plugins.* import io.ktor.client.plugins.cookies.* import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.client.tests.utils.* import io.ktor.http.* import io.ktor.util.* import kotlin.test.* @Suppress("PublicApiImplicitType") class HttpRedirectTest : ClientLoader() { private val TEST_URL_BASE = "$TEST_SERVER/redirect" @Test fun testRedirect() = clientTests { config { install(HttpRedirect) } test { client -> client.prepareGet(TEST_URL_BASE).execute { assertEquals(HttpStatusCode.OK, it.status) assertEquals("OK", it.bodyAsText()) } } } @Test fun testRedirectWithEncodedUri() = clientTests { config { install(HttpRedirect) } test { client -> client.prepareGet("$TEST_URL_BASE/encodedQuery").execute { assertEquals(HttpStatusCode.OK, it.status) assertEquals("/redirect/getWithUri?key=value1%3Bvalue2%3D%22some=thing", it.bodyAsText()) } } } @Test fun testInfinityRedirect() = clientTests { config { install(HttpRedirect) } test { client -> assertFails { client.get("$TEST_URL_BASE/infinity") } } } @Test fun testRedirectWithCookies() = clientTests(listOf("Js")) { config { install(HttpCookies) install(HttpRedirect) } test { client -> client.prepareGet("$TEST_URL_BASE/cookie").execute { assertEquals("OK", it.bodyAsText()) val token = client.plugin(HttpCookies).get(it.call.request.url)["Token"]!! assertEquals("Hello", token.value) } } } @Test @Ignore fun testCustomUrls() = clientTests(listOf("Darwin", "DarwinLegacy")) { val urls = listOf( "https://files.forgecdn.net/files/2574/880/BiblioCraft[v2.4.5][MC1.12.2].jar", "https://files.forgecdn.net/files/2611/560/Botania r1.10-356.jar", "https://files.forgecdn.net/files/2613/730/Toast Control-1.12.2-1.7.1.jar" ) config { install(HttpRedirect) } test { client -> urls.forEach { url -> client.prepareGet(url).execute { if (it.status.value >= 500) return@execute assertTrue(it.status.isSuccess(), url) } } } } @Test fun testRedirectRelative() = clientTests { test { client -> client.prepareGet("$TEST_URL_BASE/directory/redirectFile").execute { assertEquals("targetFile", it.bodyAsText()) } } } @Test fun testMultipleRedirectRelative() = clientTests { test { client -> client.prepareGet("$TEST_URL_BASE/multipleRedirects/login").execute { assertEquals("account details", it.bodyAsText()) } } } @Test fun testRedirectAbsolute() = clientTests { test { client -> client.prepareGet("$TEST_URL_BASE/directory/absoluteRedirectFile").execute { assertEquals("absoluteTargetFile", it.bodyAsText()) } } } @Test fun testRedirectHostAbsolute() = clientTests(listOf("Js")) { test { client -> client.prepareGet("$TEST_URL_BASE/directory/hostAbsoluteRedirect").execute { assertEquals("OK", it.bodyAsText()) assertEquals("$TEST_URL_BASE/get", it.call.request.url.toString()) } } } @Test fun testRedirectDisabled() = clientTests { config { followRedirects = false } test { client -> if (PlatformUtils.IS_BROWSER) return@test val response = client.get(TEST_URL_BASE) assertEquals(HttpStatusCode.Found, response.status) } } }
ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/HttpRedirectTest.kt
1543075349
package by.deniotokiari.shikimoriapi.models data class Genre( val id: Long, val name: String, val russian: String, val kind: String )
shikimoriapi/src/main/kotlin/by/deniotokiari/shikimoriapi/models/Genre.kt
2832757835