content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
/* * Copyright (C) 2021, Alashov Berkeli * All rights reserved. */ package tm.alashow.datmusic.fcm import android.annotation.SuppressLint import android.app.Application import com.google.android.gms.tasks.OnCompleteListener import com.google.firebase.messaging.FirebaseMessaging import com.google.firebase.messaging.FirebaseMessagingService as FirebaseService import com.google.firebase.messaging.RemoteMessage import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.MainScope import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import tm.alashow.base.inititializer.AppInitializer import tm.alashow.base.util.RemoteLogger import tm.alashow.datmusic.data.interactors.RegisterFcmToken import tm.alashow.datmusic.notifications.AppNotification import tm.alashow.datmusic.notifications.notify @SuppressLint("MissingFirebaseInstanceTokenRefresh") @AndroidEntryPoint class FirebaseMessagingService : FirebaseService() { override fun onMessageReceived(remoteMessage: RemoteMessage) { when { remoteMessage.data.isNotEmpty() -> notify(AppNotification.fromRemoteMessage(remoteMessage)) else -> super.onMessageReceived(remoteMessage) } } } class FcmTokenRegistrator @Inject constructor( private val registerFcmToken: RegisterFcmToken, ) : AppInitializer, CoroutineScope by MainScope() { override fun init(application: Application) { FirebaseMessaging.getInstance().token.addOnCompleteListener( OnCompleteListener { task -> if (!task.isSuccessful) return@OnCompleteListener val token = task.result ?: return@OnCompleteListener launch { registerFcmToken(RegisterFcmToken.Params(token)) .catch { RemoteLogger.exception(it) } .collect() } } ) } }
app/src/main/kotlin/tm/alashow/datmusic/fcm/FirebaseMessagingService.kt
575275947
/* * Copyright (C) 2022 Block, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.cash.zipline.loader import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertTrue import kotlinx.coroutines.runBlocking import okio.IOException import platform.Foundation.NSURLSession /** * This tests our Kotlin/Native URLSessionZiplineHttpClient. Unfortunately this test is not enabled * by default as we don't have an equivalent to MockWebServer for Kotlin/Native. */ class URLSessionZiplineHttpClientTest { var enabled = false @Test fun happyPath(): Unit = runBlocking { if (!enabled) return@runBlocking val httpClient = URLSessionZiplineHttpClient(NSURLSession.sharedSession) val download = httpClient.download("https://squareup.com/robots.txt") println(download.utf8()) } @Test fun connectivityFailure(): Unit = runBlocking { if (!enabled) return@runBlocking val httpClient = URLSessionZiplineHttpClient(NSURLSession.sharedSession) val exception = assertFailsWith<IOException> { httpClient.download("https://198.51.100.1/robots.txt") // Unreachable IP address. } assertTrue("The request timed out." in exception.message!!, exception.message) } @Test fun nonSuccessfulResponseCode(): Unit = runBlocking { if (!enabled) return@runBlocking val httpClient = URLSessionZiplineHttpClient(NSURLSession.sharedSession) val exception = assertFailsWith<IOException> { httpClient.download("https://squareup.com/.well-known/404") } assertEquals( "failed to fetch https://squareup.com/.well-known/404: 404", exception.message, ) } }
zipline-loader/src/nativeTest/kotlin/app/cash/zipline/loader/URLSessionZiplineHttpClientTest.kt
2215816280
package at.hschroedl.fluentast.ast.expression import org.eclipse.jdt.core.dom.AST import org.eclipse.jdt.core.dom.SingleMemberAnnotation class FluentSingleMemberAnnotation internal constructor(private val name: String, private val expression: FluentExpression) : FluentAnnotation() { override fun build(ast: AST): SingleMemberAnnotation { val annotation = ast.newSingleMemberAnnotation() annotation.typeName = FluentName(name).build(ast) annotation.value = expression.build(ast) return annotation } }
core/src/main/kotlin/at.hschroedl.fluentast/ast/expression/SingleMemberAnnotation.kt
1719623135
package com.rm.translateit.api.translation.source.wiki.response internal data class DetailsResponse( var description: String = "", var url: String = "" )
api/src/main/kotlin/com/rm/translateit/api/translation/source/wiki/response/DetailsResponse.kt
367754696
package com.infinum.dbinspector.data.sources.memory.pagination import com.infinum.dbinspector.shared.BaseTest import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.koin.core.module.Module @DisplayName("CursorPaginator tests") internal class CursorPaginatorTest : BaseTest() { override fun modules(): List<Module> = listOf() @Test fun `New instance has no page count`() { val expected = 0 val paginator = CursorPaginator() assertEquals(expected, paginator.pageCount) } @Test fun `Less rows than page size sets one page count`() { val given = 1 val pageSize = 10 val expected = 1 val paginator = CursorPaginator() paginator.setPageCount(given, pageSize) assertEquals(expected, paginator.pageCount) } @Test fun `No rows sets zero page count`() { val given = 0 val pageSize = 10 val expected = 0 val paginator = CursorPaginator() paginator.setPageCount(given, pageSize) assertEquals(expected, paginator.pageCount) } @Test fun `More rows than page size sets greater than one page count`() { val given = 20 val pageSize = 10 val expected = 2 val paginator = CursorPaginator() paginator.setPageCount(given, pageSize) assertEquals(expected, paginator.pageCount) } @Test fun `Zero page size passed is coerced to at least one and sets zero page count`() { val given = 0 val pageSize = 0 val expected = 0 val paginator = CursorPaginator() paginator.setPageCount(given, pageSize) assertEquals(expected, paginator.pageCount) } @Test fun `Negative row count is coerced to at least zero and sets zero page count`() { val given = -1 val pageSize = 1 val expected = 0 val paginator = CursorPaginator() paginator.setPageCount(given, pageSize) assertEquals(expected, paginator.pageCount) } @Test fun `Negative row count is coerced to zero and negative page size is coerced to one also sets zero page count`() { val given = -1 val pageSize = -1 val expected = 0 val paginator = CursorPaginator() paginator.setPageCount(given, pageSize) assertEquals(expected, paginator.pageCount) } @Test fun `Null current page sets null next page`() { val given: Int? = null val expected: Int? = null val paginator = CursorPaginator() val actual = paginator.nextPage(given) assertEquals(expected, actual) assertNull(actual) } @Test fun `Zero page count sets null next page`() { val given = 1 val expected: Int? = null val paginator = CursorPaginator() paginator.pageCount = 0 val actual = paginator.nextPage(given) assertEquals(expected, actual) assertNull(actual) } @Test fun `Current page is last sets null next page`() { val given = 1 val expected: Int? = null val paginator = CursorPaginator() paginator.pageCount = 1 val actual = paginator.nextPage(given) assertEquals(expected, actual) assertNull(actual) } @Test fun `Current page is not last increments next page`() { val given = 1 val expected = 2 val paginator = CursorPaginator() paginator.pageCount = 3 val actual = paginator.nextPage(given) assertEquals(expected, actual) assertNotNull(actual) } @Test fun `Negative current page is coerced to at least zero`() { val given = -1 val expected = 1 val paginator = CursorPaginator() paginator.pageCount = 2 val actual = paginator.nextPage(given) assertEquals(expected, actual) assertNotNull(actual) } @Test fun `Row count smaller than page size returns correct boundary`() { val given = 1 val pageSize = 10 val rowCount = 5 val expected = Paginator.Boundary( startRow = 0, endRow = 5 ) val paginator = CursorPaginator() val actual = paginator.boundary(given, pageSize, rowCount) assertEquals(expected, actual) } @Test fun `Equal page size and row count returns correct boundary`() { val given = 1 val pageSize = 10 val rowCount = 10 val expected = Paginator.Boundary( startRow = 0, endRow = 10 ) val paginator = CursorPaginator() val actual = paginator.boundary(given, pageSize, rowCount) assertEquals(expected, actual) } @Test fun `Row count larger than page size returns correct boundary`() { val given = 1 val pageSize = 10 val rowCount = 15 val expected = Paginator.Boundary( startRow = 0, endRow = 10 ) val paginator = CursorPaginator() val actual = paginator.boundary(given, pageSize, rowCount) assertEquals(expected, actual) } @Test fun `Null page returns correct boundary`() { val given: Int? = null val pageSize = 10 val rowCount = 15 val expected = Paginator.Boundary( startRow = 0, endRow = 10 ) val paginator = CursorPaginator() val actual = paginator.boundary(given, pageSize, rowCount) assertEquals(expected, actual) } @Test fun `Negative row count and page size returns correct boundary`() { val given = -1 val pageSize = -10 val rowCount = 15 val expected = Paginator.Boundary( startRow = 0, endRow = 1 ) val paginator = CursorPaginator() val actual = paginator.boundary(given, pageSize, rowCount) assertEquals(expected, actual) } }
dbinspector/src/test/kotlin/com/infinum/dbinspector/data/sources/memory/pagination/CursorPaginatorTest.kt
120419712
/* * Copyright (c) 2017. Toshi Inc * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.toshi.view.adapter import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import com.toshi.R import com.toshi.model.network.token.ERCToken import com.toshi.model.network.token.Token import com.toshi.view.adapter.viewholder.TokenType import com.toshi.view.adapter.viewholder.TokensViewHolder class TokenAdapter( private val tokenType: TokenType ) : BaseCompoundableAdapter<TokensViewHolder, Token>() { var tokenListener: ((Token) -> Unit)? = null var ERC721Listener: ((ERCToken) -> Unit)? = null override fun compoundableBindViewHolder(viewHolder: RecyclerView.ViewHolder, adapterIndex: Int) { val typedHolder = viewHolder as TokensViewHolder onBindViewHolder(typedHolder, adapterIndex) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TokensViewHolder { val itemView = LayoutInflater.from(parent.context).inflate(R.layout.list_item__token, parent, false) return TokensViewHolder(tokenType, itemView) } override fun onBindViewHolder(holder: TokensViewHolder, position: Int) { val token = safelyAt(position) ?: throw AssertionError("No user at $position") holder.setToken(token, tokenListener, ERC721Listener) } }
app/src/main/java/com/toshi/view/adapter/TokenAdapter.kt
604521292
/* * Copyright (c) 2018. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.diagram /** * Created by pdvrieze on 07/01/17. */ interface HasExtent { val leftExtent: Double //get() = 0.0 val rightExtent: Double //get() = 0.0 val topExtent: Double //get() = 0.0 val bottomExtent: Double //get() = 0.0 }
PE-common/src/commonMain/kotlin/nl/adaptivity/diagram/HasExtent.kt
3030989323
package de.westnordost.streetcomplete.data.osm.mapdata open class MutableMapData() : MapData { constructor(other: Iterable<Element>) : this() { addAll(other) } protected val nodesById: MutableMap<Long, Node> = mutableMapOf() protected val waysById: MutableMap<Long, Way> = mutableMapOf() protected val relationsById: MutableMap<Long, Relation> = mutableMapOf() override var boundingBox: BoundingBox? = null override val nodes get() = nodesById.values override val ways get() = waysById.values override val relations get() = relationsById.values override fun getNode(id: Long) = nodesById[id] override fun getWay(id: Long) = waysById[id] override fun getRelation(id: Long) = relationsById[id] fun addAll(elements: Iterable<Element>) { elements.forEach(this::add) } fun add(element: Element) { when(element) { is Node -> nodesById[element.id] = element is Way -> waysById[element.id] = element is Relation -> relationsById[element.id] = element } } override fun iterator(): Iterator<Element> { return (nodes.asSequence() + ways.asSequence() + relations.asSequence()).iterator() } }
app/src/main/java/de/westnordost/streetcomplete/data/osm/mapdata/MutableMapData.kt
211874761
package com.szymongrochowiak.androidkotlinstarterpack.ui.common.activities.base import android.os.Bundle import com.hannesdorfmann.mosby3.mvp.MvpActivity import com.hannesdorfmann.mosby3.mvp.MvpBasePresenter import com.hannesdorfmann.mosby3.mvp.MvpView import com.szymongrochowiak.androidkotlinstarterpack.StarterPackApplication /** * @author Szymon Grochowiak */ abstract class BaseActivity<V : MvpView, P : MvpBasePresenter<V>> : MvpActivity<V, P>() { protected abstract fun injectDependencies() override fun onCreate(savedInstanceState: Bundle?) { injectDependencies() super.onCreate(savedInstanceState) } protected fun getDaggerApplicationComponent() = (application as StarterPackApplication).daggerComponent }
app/src/main/java/com/szymongrochowiak/androidkotlinstarterpack/ui/common/activities/base/BaseActivity.kt
2592728705
package jeb.cfg import java.util.* import kotlin.Boolean as KBoolean import kotlin.String as KString sealed class Json<out T : Any>(protected open val value: T, private val cmp: (T, T) -> KBoolean = { value, other -> value == other }) { class String(override public val value: KString) : Json<KString>(value) { override fun toString(): KString = "\"$value\"" } class Integer(override public val value: Int) : Json<Int>(value) { override fun toString() = value.toString() } object True : Json.Boolean(true) object False : Json.Boolean(false) class Object(private val fields: LinkedHashMap<KString, Json<Any>>) : Json<LinkedHashMap<KString, Json<Any>>>(fields, Json.Object.compareValue) { operator fun get(key: KString) = fields[key] override fun toString(): KString = fields.map { "\"${it.key}\":${it.value.toString()}" }. joinToString(",", "{", "}") companion object { val compareValue: (LinkedHashMap<KString, Json<Any>>, LinkedHashMap<KString, Json<Any>>) -> kotlin.Boolean = { fields, other -> fields.keys.zip(other.keys).all { it.first == it.second && fields[it.first] == fields[it.first] } } } } class Array(private val items: List<Json<Any>>) : Json<List<Json<Any>>>(items, compareValue), List<Json<Any>> by items { override fun toString(): KString = items.joinToString(",", "[", "]") inline fun <reified T> toListOf(): List<T> { return map { it.value as T } } companion object { val compareValue: (List<Json<*>>, List<Json<*>>) -> kotlin.Boolean = { value, other -> value.zip(value).all { it.first == it.second } } } } open class Boolean(value: KBoolean) : Json<KBoolean>(value) { override fun toString() = value.toString() } override fun equals(other: Any?): kotlin.Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false @Suppress("UNCHECKED_CAST") val otherValue = (other as Json<T>).value return cmp(value, otherValue) } override fun hashCode(): Int { return value.hashCode() } } fun Any.toJson(): Json<Any> { return when (this) { is KString -> Json.String(this) is Int -> Json.Integer(this) is KBoolean -> if (this) Json.True else Json.False is List<*> -> Json.Array(this.map { it!!.toJson() }) else -> throw IllegalStateException("Could not render to json instances of ${this.javaClass}") } }
src/main/kotlin/jeb/cfg/values.kt
3975188648
package com.recurly.androidsdk.data.network import com.recurly.androidsdk.data.model.tokenization.ErrorRecurly import com.recurly.androidsdk.data.model.tokenization.TokenizationRequest import com.recurly.androidsdk.data.model.tokenization.TokenizationResponse import com.recurly.androidsdk.data.network.core.RetrofitHelper import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class TokenService { private val retrofit = RetrofitHelper.getRetrofit() /** * @param TokenizationRequest * @return TokenizationResponse * * If the api call succeeds the response will a TokenizationResponse * * If the api call fails the response will be an empty Response Object with everything set * on empty * */ suspend fun getToken(request: TokenizationRequest): TokenizationResponse { return withContext(Dispatchers.IO) { val response = retrofit.create(RecurlyApiClient::class.java).recurlyTokenization( first_name = request.firstName, last_name = request.lastName, company = request.company, address1 = request.addressOne, address2 = request.addressTwo, city = request.city, state = request.state, postal_code = request.postalCode, country = request.country, phone = request.phone, vat_number = request.vatNumber, tax_identifier = request.taxIdentifier, tax_identifier_type = request.taxIdentifierType, number = request.cardNumber, month = request.expirationMonth, year = request.expirationYear, cvv = request.cvvCode, version = request.sdkVersion, key = request.publicKey, deviceId = request.deviceId, sessionId = request.sessionId ) response.body() ?: TokenizationResponse( "", "", ErrorRecurly( "", "", emptyList(), emptyList() ) ) } } }
AndroidSdk/src/main/java/com/recurly/androidsdk/data/network/TokenService.kt
3526191547
package com.boardgamegeek.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.core.widget.doAfterTextChanged import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.recyclerview.widget.RecyclerView import com.boardgamegeek.R import com.boardgamegeek.databinding.FragmentNewPlayLocationsBinding import com.boardgamegeek.databinding.RowNewPlayLocationBinding import com.boardgamegeek.entities.LocationEntity import com.boardgamegeek.extensions.fadeIn import com.boardgamegeek.extensions.fadeOut import com.boardgamegeek.extensions.inflate import com.boardgamegeek.ui.adapter.AutoUpdatableAdapter import com.boardgamegeek.ui.viewmodel.NewPlayViewModel import kotlin.properties.Delegates class NewPlayLocationsFragment : Fragment() { private var _binding: FragmentNewPlayLocationsBinding? = null private val binding get() = _binding!! private val viewModel by activityViewModels<NewPlayViewModel>() private val adapter: LocationsAdapter by lazy { LocationsAdapter(viewModel) } @Suppress("RedundantNullableReturnType") override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = FragmentNewPlayLocationsBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.recyclerView.setHasFixedSize(true) binding.recyclerView.adapter = adapter viewModel.locations.observe(viewLifecycleOwner) { adapter.locations = it binding.recyclerView.fadeIn() if (it.isEmpty()) { if (binding.filterEditText.text.isNullOrBlank()) { binding.emptyView.setText(R.string.empty_new_play_locations) } else { binding.emptyView.setText(R.string.empty_new_play_locations_filter) } binding.emptyView.fadeIn() } else { binding.emptyView.fadeOut() } } binding.filterEditText.doAfterTextChanged { viewModel.filterLocations(it.toString()) } binding.next.setOnClickListener { viewModel.setLocation(binding.filterEditText.text.toString()) } } override fun onResume() { super.onResume() (activity as? AppCompatActivity)?.supportActionBar?.setSubtitle(R.string.title_location) } override fun onDestroyView() { super.onDestroyView() _binding = null } private class LocationsAdapter(private val viewModel: NewPlayViewModel) : RecyclerView.Adapter<LocationsAdapter.LocationsViewHolder>(), AutoUpdatableAdapter { var locations: List<LocationEntity> by Delegates.observable(emptyList()) { _, oldValue, newValue -> autoNotify(oldValue, newValue) { old, new -> old.name == new.name } } override fun getItemCount() = locations.size override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LocationsViewHolder { return LocationsViewHolder(parent.inflate(R.layout.row_new_play_location)) } override fun onBindViewHolder(holder: LocationsViewHolder, position: Int) { holder.bind(locations.getOrNull(position)) } inner class LocationsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val binding = RowNewPlayLocationBinding.bind(itemView) fun bind(location: LocationEntity?) { location?.let { l -> binding.nameView.text = l.name itemView.setOnClickListener { viewModel.setLocation(l.name) } } } } } }
app/src/main/java/com/boardgamegeek/ui/NewPlayLocationsFragment.kt
2749486142
package utils import java.security.MessageDigest fun String.sha512() : String{ val bytes : ByteArray = MessageDigest.getInstance("SHA-512") .digest(this.toByteArray()) return bytes.toHex() } fun ByteArray.toHex() : String{ val sb = StringBuilder() this.forEach { value -> val hexInt = value.toInt() and (0xFF) val hexString = Integer.toHexString(hexInt) if(hexString.length == 1){ sb.append("0") } sb.append(hexString) } return sb.toString() } fun String.salt() : String{ val pwdSalt = "biu-gO82nx_d" + this +"_8dnx0%sdc" val pwdInSha = pwdSalt.sha512() return pwdInSha } fun main(args: Array<String>) { println("Renran4".salt()) //=> cfe3d11e25d864f9c5370ac839062c83e014ae261b5d7f8029348c448939780b5f3136f5974bf4d9219d6e742069ddf7860ecc1ca6b9e27d7b5ca3d259b4c5fc println("594szw".salt()) //=> 54c57e3b29df8a913897885eb7706a70c41776ba20bfddadab21bf728b2be84966344b92f47fed2ceac37df8a3be9dd2d856cdf064a3df6beb984c8a83ecb349 }
AdvancedJ/src/main/kotlin/utils/SecurityUtil.kt
3905904697
package gargoyle.ct.util.util import java.util.* operator fun ResourceBundle.get(key: String, def: String? = null): String? = if (containsKey(key)) getString(key) else def
util/src/main/kotlin/gargoyle/ct/util/util/RBUtil.kt
951549146
package org.mifos.mobile.models.register import com.google.gson.annotations.SerializedName /** * Created by dilpreet on 31/7/17. */ data class UserVerify ( @SerializedName("requestId") var requestId: String? = null, @SerializedName("authenticationToken") var authenticationToken: String? = null )
app/src/main/java/org/mifos/mobile/models/register/UserVerify.kt
2589338938
package com.morayl.footprintktx import android.util.Log /** * LogPriority of Logcat. * When you choose [LogPriority.ERROR] or [LogPriority.ASSERT] logcat-log could become red. */ enum class LogPriority(val value: Int) { VERBOSE(Log.VERBOSE), DEBUG(Log.DEBUG), INFO(Log.INFO), WARN(Log.WARN), ERROR(Log.ERROR), ASSERT(Log.ASSERT) }
footprint-ktx/src/main/java/com/morayl/footprintktx/LogPriority.kt
3561239582
// This file was automatically generated from serializers.md by Knit tool. Do not edit. package example.exampleSerializer11 import kotlinx.serialization.* import kotlinx.serialization.json.* import kotlinx.serialization.encoding.* import kotlinx.serialization.descriptors.* @Serializable @SerialName("Color") private class ColorSurrogate(val r: Int, val g: Int, val b: Int) { init { require(r in 0..255 && g in 0..255 && b in 0..255) } } object ColorSerializer : KSerializer<Color> { override val descriptor: SerialDescriptor = ColorSurrogate.serializer().descriptor override fun serialize(encoder: Encoder, value: Color) { val surrogate = ColorSurrogate((value.rgb shr 16) and 0xff, (value.rgb shr 8) and 0xff, value.rgb and 0xff) encoder.encodeSerializableValue(ColorSurrogate.serializer(), surrogate) } override fun deserialize(decoder: Decoder): Color { val surrogate = decoder.decodeSerializableValue(ColorSurrogate.serializer()) return Color((surrogate.r shl 16) or (surrogate.g shl 8) or surrogate.b) } } @Serializable(with = ColorSerializer::class) class Color(val rgb: Int) fun main() { val green = Color(0x00ff00) println(Json.encodeToString(green)) }
guide/example/example-serializer-11.kt
1232374878
package com.mercadopago.android.px.model import android.os.Parcel import com.mercadopago.android.px.internal.util.KParcelable import com.mercadopago.android.px.internal.util.parcelableCreator import com.mercadopago.android.px.model.internal.Text data class DiscountDescription( val title: Text, val subtitle: Text?, val badge: TextUrl?, val summary: Text, val description: Text, val legalTerms: TextUrl ): KParcelable { constructor(parcel: Parcel) : this( parcel.readParcelable(Text::class.java.classLoader)!!, parcel.readParcelable(Text::class.java.classLoader), parcel.readParcelable(TextUrl::class.java.classLoader), parcel.readParcelable(Text::class.java.classLoader)!!, parcel.readParcelable(Text::class.java.classLoader)!!, parcel.readParcelable(TextUrl::class.java.classLoader)!!) { } override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeParcelable(title, flags) parcel.writeParcelable(subtitle, flags) parcel.writeParcelable(badge, flags) parcel.writeParcelable(summary, flags) parcel.writeParcelable(description, flags) parcel.writeParcelable(legalTerms, flags) } companion object { @JvmField val CREATOR = parcelableCreator(::DiscountDescription) } }
px-services/src/main/java/com/mercadopago/android/px/model/DiscountDescription.kt
4004471437
package com.osacky.flank.gradle.integration import com.google.common.truth.Truth.assertThat import org.gradle.testkit.runner.GradleRunner import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder class FlankGradlePluginIntegrationTest { @get:Rule var testProjectRoot = TemporaryFolder() val minSupportGradleVersion = "5.5" val oldVersion = "5.3.1" fun writeBuildGradle(build: String) { val file = testProjectRoot.newFile("build.gradle") file.writeText(build) } @Test fun testLowGradleVersionFailsBuild() { writeBuildGradle( """plugins { | id "com.osacky.fladle" |}""".trimMargin() ) val result = GradleRunner.create() .withProjectDir(testProjectRoot.root) .withPluginClasspath() .withGradleVersion(oldVersion) .buildAndFail() assertThat(result.output).contains("Fladle requires at minimum version Gradle 5.5. Detected version Gradle 5.3.1") } @Test fun testGradleSixZero() { writeBuildGradle( """plugins { | id "com.osacky.fladle" |}""".trimMargin() ) val result = GradleRunner.create() .withProjectDir(testProjectRoot.root) .withPluginClasspath() .withGradleVersion("6.0") .build() assertThat(result.output).contains("SUCCESS") } @Test fun testMinSupportedGradleVersionWorks() { writeBuildGradle( """plugins { | id "com.osacky.fladle" |}""".trimMargin() ) GradleRunner.create() .withProjectDir(testProjectRoot.root) .withPluginClasspath() .withGradleVersion(minSupportGradleVersion) .build() } @Test fun testMissingServiceAccountWithProjectId() { writeBuildGradle( """plugins { | id "com.osacky.fladle" |} | |fladle { | projectId = "foo-project" | debugApk = "foo" | instrumentationApk = "fakeInstrument.apk" |}""".trimMargin() ) GradleRunner.create() .withProjectDir(testProjectRoot.root) .withPluginClasspath() .withGradleVersion(minSupportGradleVersion) .withArguments("printYml") .build() } @Test fun testMissingServiceAccountFailsBuild() { writeBuildGradle( """plugins { | id "com.osacky.fladle" |} | |fladle { | debugApk = "foo" |}""".trimMargin() ) val result = GradleRunner.create() .withProjectDir(testProjectRoot.root) .withPluginClasspath() .withGradleVersion(minSupportGradleVersion) .withArguments("printYml") .buildAndFail() assertThat(result.output).contains("ServiceAccountCredentials in fladle extension not set. https://github.com/runningcode/fladle#serviceaccountcredentials") } @Test fun testMissingApkFailsBuild() { writeBuildGradle( """plugins { | id "com.osacky.fladle" |} |fladle { | serviceAccountCredentials = project.layout.projectDirectory.file("foo") |} |""".trimMargin() ) testProjectRoot.newFile("foo").writeText("{}") val result = GradleRunner.create() .withProjectDir(testProjectRoot.root) .withPluginClasspath() .withGradleVersion(minSupportGradleVersion) .withArguments("runFlank") .buildAndFail() assertThat(result.output).contains("debugApk must be specified") } @Test fun testMissingInstrumentationApkFailsBuild() { writeBuildGradle( """plugins { id "com.osacky.fladle" } fladle { serviceAccountCredentials = project.layout.projectDirectory.file("foo") debugApk = "test-debug.apk" } """.trimIndent() ) testProjectRoot.newFile("foo").writeText("{}") val result = GradleRunner.create() .withProjectDir(testProjectRoot.root) .withPluginClasspath() .withGradleVersion(minSupportGradleVersion) .withArguments("runFlank") .buildAndFail() assertThat(result.output).contains("Must specify either a instrumentationApk file or a roboScript file.") } @Test fun testSpecifyingBothInstrumenationAndRoboscriptFailsBuild() { writeBuildGradle( """plugins { id "com.osacky.fladle" } fladle { serviceAccountCredentials = project.layout.projectDirectory.file("foo") debugApk = "test-debug.apk" instrumentationApk = "instrumenation-debug.apk" roboScript = "foo.script" } """.trimIndent() ) testProjectRoot.newFile("foo").writeText("{}") val result = GradleRunner.create() .withProjectDir(testProjectRoot.root) .withPluginClasspath() .withGradleVersion(minSupportGradleVersion) .withArguments("printYml") .buildAndFail() assertThat(result.output).contains("Both instrumentationApk file and roboScript file were specified, but only one is expected.") } }
buildSrc/src/test/java/com/osacky/flank/gradle/integration/FlankGradlePluginIntegrationTest.kt
4000634988
package com.herolynx.elepantry.ext.google.drive import android.app.Activity import android.net.Uri import com.google.api.services.drive.Drive import com.herolynx.elepantry.core.Result import com.herolynx.elepantry.core.log.debug import com.herolynx.elepantry.core.net.asInputStream import com.herolynx.elepantry.core.ui.WebViewUtils import com.herolynx.elepantry.drive.CloudResource import com.herolynx.elepantry.ext.android.AppManager import com.herolynx.elepantry.ext.android.Storage import com.herolynx.elepantry.resources.core.model.Resource import org.funktionale.tries.Try import rx.Observable import java.io.InputStream class GoogleDriveResource( private val metaInfo: Resource, private val drive: Drive ) : CloudResource { override fun preview(activity: Activity, beforeAction: () -> Unit, afterAction: () -> Unit): Try<Result> { if (AppManager.isAppInstalled(activity, GoogleDrive.APP_PACKAGE_NAME)) { return WebViewUtils.openLink(activity, metaInfo.downloadLink) } else { return download(activity, beforeAction, afterAction) } } override fun download(activity: Activity, beforeAction: () -> Unit, afterAction: () -> Unit): Try<Result> = Try { Storage.downloadAndOpen( activity = activity, fileName = metaInfo.uuid(), download = { outputStream -> debug("[GoogleDrive][Download] Downloading - resource: $metaInfo") drive.files().get(metaInfo.id).executeMediaAndDownloadTo(outputStream) -1L }, beforeAction = beforeAction, afterAction = afterAction ) Result(true) } override fun thumbnail(): Observable<InputStream> = Uri.parse(metaInfo.thumbnailLink) .asInputStream() override fun metaInfo(): Resource = metaInfo }
app/src/main/java/com/herolynx/elepantry/ext/google/drive/GoogleDriveResource.kt
3374376480
package com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.repository.IFilePropertiesContainerRepository import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId import com.lasthopesoftware.bluewater.client.connection.libraries.ProvideLibraryConnections import com.lasthopesoftware.bluewater.shared.UrlKeyHolder import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise import com.namehillsoftware.handoff.promises.Promise /** * Created by david on 3/7/16. */ class CachedFilePropertiesProvider(private val libraryConnections: ProvideLibraryConnections, private val filePropertiesContainerRepository: IFilePropertiesContainerRepository, private val filePropertiesProvider: ProvideLibraryFileProperties) : ProvideLibraryFileProperties { override fun promiseFileProperties(libraryId: LibraryId, serviceFile: ServiceFile): Promise<Map<String, String>> { return libraryConnections.promiseLibraryConnection(libraryId) .eventually { connectionProvider -> connectionProvider?.urlProvider?.baseUrl ?.let { url -> UrlKeyHolder(url, serviceFile) } ?.let { urlKeyHolder -> filePropertiesContainerRepository.getFilePropertiesContainer(urlKeyHolder) } ?.let { filePropertiesContainer -> filePropertiesContainer.properties.toPromise() } ?: filePropertiesProvider.promiseFileProperties(libraryId, serviceFile) } } }
projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/browsing/items/media/files/properties/CachedFilePropertiesProvider.kt
1885857756
package org.metplus.cruncher.persistence import org.metplus.cruncher.job.JobsRepository import org.metplus.cruncher.persistence.model.* import org.metplus.cruncher.resume.ResumeRepository import org.metplus.cruncher.settings.SettingsRepository import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.SpringBootConfiguration import org.springframework.context.annotation.Bean import org.springframework.data.mongodb.repository.config.EnableMongoRepositories @SpringBootConfiguration @EnableMongoRepositories(basePackages = ["org.metplus.cruncher.persistence"]) open class TestConfig { @Bean open fun getSettingsRepository(@Autowired repo: SettingsRepositoryMongo) : SettingsRepository = SettingsRepositoryImpl(repo) @Bean open fun getJobRepository(@Autowired repo: JobRepositoryMongo) : JobsRepository = JobRepositoryImpl(repo) @Bean open fun getResumeRepository(@Autowired repo: ResumeRepositoryMongo) : ResumeRepository = ResumeRepositoryImpl(repo) }
persistence/src/test/kotlin/org/metplus/cruncher/persistence/TestConfig.kt
217264149
package io.github.flank.gradle.utils import io.github.flank.gradle.SimpleFlankExtension import io.github.flank.gradle.tasks.CopySmallAppTask import org.gradle.api.Project fun Project.getSmallAppTask(): CopySmallAppTask = tasks.maybeCreate("copySmallApp", CopySmallAppTask::class.java).apply { pluginJar.setFrom( zipTree( SimpleFlankExtension::class.java.classLoader.getResource("small-app.apk")!! .path .split("!") .first())) }
src/main/kotlin/io/github/flank/gradle/utils/smallAppUtils.kt
2473388919
/* * Copyright (C) 2014-2020 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.amaze.filemanager.database.typeconverters import androidx.room.TypeConverter import com.amaze.filemanager.fileoperations.filesystem.OpenMode /** [TypeConverter] for [OpenMode] objects to database columns. */ object OpenModeTypeConverter { /** * Convert given [OpenMode] to integer constant for database storage. */ @JvmStatic @TypeConverter fun fromOpenMode(from: OpenMode): Int { return from.ordinal } /** * Convert value in database to [OpenMode]. */ @JvmStatic @TypeConverter fun fromDatabaseValue(from: Int): OpenMode { return OpenMode.getOpenMode(from) } }
app/src/main/java/com/amaze/filemanager/database/typeconverters/OpenModeTypeConverter.kt
4050603913
/* * Copyright 2022, TeamDev. All rights reserved. * * 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 * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.internal.gradle.javadoc import java.io.File import org.gradle.api.JavaVersion import org.gradle.api.Project import org.gradle.api.tasks.javadoc.Javadoc import org.gradle.external.javadoc.StandardJavadocDocletOptions /** * Javadoc processing settings. * * This type is named with `Config` suffix to avoid its confusion with the standard `Javadoc` type. */ @Suppress("unused") object JavadocConfig { /** * Link to the documentation for Java 11 Standard Library API. * * OpenJDK SE 11 is used for the reference. */ private const val standardLibraryAPI = "https://cr.openjdk.java.net/~iris/se/11/latestSpec/api/" @Suppress("MemberVisibilityCanBePrivate") // opened to be visible from docs. val tags = listOf( JavadocTag("apiNote", "API Note"), JavadocTag("implSpec", "Implementation Requirements"), JavadocTag("implNote", "Implementation Note") ) val encoding = Encoding("UTF-8") fun applyTo(project: Project) { val javadocTask = project.tasks.javadocTask() discardJavaModulesInLinks(javadocTask) val docletOptions = javadocTask.options as StandardJavadocDocletOptions configureDoclet(docletOptions) } /** * Discards using of Java 9 modules in URL links generated by javadoc for our codebase. * * This fixes navigation to classes through the search results. * * The issue appeared after migration to Java 11. When javadoc is generated for a project * that does not declare Java 9 modules, search results contain broken links with appended * `undefined` prefix to the URL. This `undefined` was meant to be a name of a Java 9 module. * * See: [Issue #334](https://github.com/SpineEventEngine/config/issues/334) */ private fun discardJavaModulesInLinks(javadoc: Javadoc) { // We ask `Javadoc` task to modify "search.js" and override a method, responsible for // the formation of URL prefixes. We can't specify the option "--no-module-directories", // because it leads to discarding of all module prefixes in generated links. That means, // links to the types from the standard library would not work, as they are declared // within modules since Java 9. val discardModulePrefix = """ getURLPrefix = function(ui) { return ""; }; """.trimIndent() javadoc.doLast { val destinationDir = javadoc.destinationDir!!.absolutePath val searchScript = File("$destinationDir/search.js") searchScript.appendText(discardModulePrefix) } } private fun configureDoclet(docletOptions: StandardJavadocDocletOptions) { docletOptions.encoding = encoding.name reduceParamWarnings(docletOptions) registerCustomTags(docletOptions) linkStandardLibraryAPI(docletOptions) } /** * Configures `javadoc` tool to avoid numerous warnings for missing `@param` tags. * * As suggested by Stephen Colebourne: * [https://blog.joda.org/2014/02/turning-off-doclint-in-jdk-8-javadoc.html] * * See also: * [https://github.com/GPars/GPars/blob/master/build.gradle#L268] */ private fun reduceParamWarnings(docletOptions: StandardJavadocDocletOptions) { if (JavaVersion.current().isJava8Compatible) { docletOptions.addStringOption("Xdoclint:none", "-quiet") } } /** * Registers custom [tags] for the passed doclet options. */ fun registerCustomTags(docletOptions: StandardJavadocDocletOptions) { docletOptions.tags = tags.map { it.toString() } } /** * Links the documentation for Java 11 Standard Library API. * * This documentation is used to be referenced to when navigating to the types from the * standard library (`String`, `List`, etc.). * * OpenJDK SE 11 is used for the reference. */ private fun linkStandardLibraryAPI(docletOptions: StandardJavadocDocletOptions) { docletOptions.addStringOption("link", standardLibraryAPI) } }
buildSrc/src/main/kotlin/io/spine/internal/gradle/javadoc/JavadocConfig.kt
3565147764
package io.gitlab.arturbosch.detekt.rules.style import io.gitlab.arturbosch.detekt.rules.setupKotlinEnvironment import io.gitlab.arturbosch.detekt.test.assertThat import io.gitlab.arturbosch.detekt.test.compileAndLintWithContext import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe class UseIfEmptyOrIfBlankSpec : Spek({ setupKotlinEnvironment() val env: KotlinCoreEnvironment by memoized() val subject by memoized { UseIfEmptyOrIfBlank() } describe("report UseIfEmptyOrIfBlank rule") { it("String.isBlank") { val code = """ class Api(val name: String) fun test(api: Api) { val name = if (api.name.isBlank()) "John" else api.name } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) assertThat(findings).hasSourceLocation(4, 29) assertThat(findings[0]).hasMessage("This 'isBlank' call can be replaced with 'ifBlank'") } it("String.isNotBlank") { val code = """ class Api(val name: String) fun test(api: Api) { val name = if (api.name.isNotBlank()) api.name else "John" } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) assertThat(findings).hasSourceLocation(4, 29) assertThat(findings[0]).hasMessage("This 'isNotBlank' call can be replaced with 'ifBlank'") } it("String.isEmpty") { val code = """ class Api(val name: String) fun test(api: Api) { val name = if (api.name.isEmpty()) "John" else api.name } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) assertThat(findings).hasSourceLocation(4, 29) assertThat(findings[0]).hasMessage("This 'isEmpty' call can be replaced with 'ifEmpty'") } it("String.isNotEmpty") { val code = """ class Api(val name: String) fun test(api: Api) { val name = if (api.name.isNotEmpty()) api.name else "John" } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) assertThat(findings).hasSourceLocation(4, 29) assertThat(findings[0]).hasMessage("This 'isNotEmpty' call can be replaced with 'ifEmpty'") } it("List.isEmpty") { val code = """ fun test(list: List<Int>): List<Int> { return if (list.isEmpty()) { listOf(1) } else { list } } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) } it("List.isNotEmpty") { val code = """ fun test(list: List<Int>): List<Int> { return if (list.isNotEmpty()) { list } else { listOf(1) } } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) } it("Set.isEmpty") { val code = """ fun test(set: Set<Int>): Set<Int> { return if (set.isEmpty()) { setOf(1) } else { set } } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) } it("Set.isNotEmpty") { val code = """ fun test(set: Set<Int>): Set<Int> { return if (set.isNotEmpty()) { set } else { setOf(1) } } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) } it("Map.isEmpty") { val code = """ fun test(map: Map<Int, Int>): Map<Int, Int> { return if (map.isEmpty()) { mapOf(1 to 2) } else { map } } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) } it("Map.isNotEmpty") { val code = """ fun test(map: Map<Int, Int>): Map<Int, Int> { return if (map.isNotEmpty()) { map } else { mapOf(1 to 2) } } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) } it("Collection.isEmpty") { val code = """ fun test(collection: Collection<Int>): Collection<Int> { return if (collection.isEmpty()) { listOf(1) } else { collection } } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) } it("Collection.isNotEmpty") { val code = """ fun test(collection: Collection<Int>): Collection<Int> { return if (collection.isNotEmpty()) { collection } else { listOf(1) } } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) } it("implicit receiver") { val code = """ fun String.test(): String { return if (isBlank()) { "foo" } else { this } } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) } it("default value block is not single statement") { val code = """ fun test(list: List<Int>): List<Int> { return if (list.isEmpty()) { println() listOf(1) } else { list } } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) } it("!isEmpty") { val code = """ fun test(list: List<Int>): List<Int> { return if (!list.isEmpty()) { // list.isNotEmpty() list } else { listOf(1) } } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) assertThat(findings[0]).hasMessage("This 'isEmpty' call can be replaced with 'ifEmpty'") } it("!isNotEmpty") { val code = """ fun test(list: List<Int>): List<Int> { return if (!list.isNotEmpty()) { // list.isEmpty() listOf(1) } else { list } } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) assertThat(findings[0]).hasMessage("This 'isNotEmpty' call can be replaced with 'ifEmpty'") } } describe("does not report UseIfEmptyOrIfBlank rule") { it("String.isNullOrBlank") { val code = """ class Api(val name: String?) fun test(api: Api) { val name = if (api.name.isNullOrBlank()) "John" else api.name } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("List.isNullOrEmpty") { val code = """ fun test2(list: List<Int>): List<Int> { return if (list.isNullOrEmpty()) { listOf(1) } else { list } } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("Array.isEmpty") { val code = """ fun test(arr: Array<String>): Array<String> { return if (arr.isEmpty()) { arrayOf("a") } else { arr } } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("Array.isNotEmpty") { val code = """ fun test(arr: Array<String>): Array<String> { return if (arr.isNotEmpty()) { arr } else { arrayOf("a") } } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("IntArray.isEmpty") { val code = """ fun test(arr: IntArray): IntArray { return if (arr.isEmpty()) { intArrayOf(1) } else { arr } } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("IntArray.isNotEmpty") { val code = """ fun test(arr: IntArray): IntArray { return if (arr.isNotEmpty()) { arr } else { intArrayOf(1) } } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("else if") { val code = """ fun test(list: List<Int>, b: Boolean): List<Int> { return if (list.isEmpty()) { listOf(1) } else if (b) { listOf(2) } else { list } } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("no else") { val code = """ fun test(list: List<Int>) { if (list.isEmpty()) { listOf(1) } } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("not self value") { val code = """ fun test(list: List<Int>): List<Int> { return if (list.isEmpty()) { listOf(1) } else { list + list } } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("self value block is not single statement") { val code = """ fun test(list: List<Int>): List<Int> { return if (list.isEmpty()) { listOf(1) } else { println() list } } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("condition is binary expression") { val code = """ fun test(list: List<Int>): List<Int> { return if (list.isEmpty() == true) { listOf(1) } else { list } } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } } })
detekt-rules-style/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/UseIfEmptyOrIfBlankSpec.kt
3967653445
package net.nemerosa.ontrack.kdsl.spec.extension.av import net.nemerosa.ontrack.kdsl.spec.Build /** * Launches an auto versioning check for this build */ fun Build.autoVersioningCheck() { connector.post( "/extension/auto-versioning/build/$id/check" ) }
ontrack-kdsl/src/main/java/net/nemerosa/ontrack/kdsl/spec/extension/av/AutoVersioningBuildExtensions.kt
4160706742
package timber.log import android.os.Build import android.util.Log import com.google.common.truth.ThrowableSubject import java.net.ConnectException import java.net.UnknownHostException import java.util.ArrayList import java.util.concurrent.CountDownLatch import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import org.robolectric.shadows.ShadowLog import com.google.common.truth.Truth.assertThat import org.junit.Assert.assertTrue import org.junit.Assert.fail import org.robolectric.shadows.ShadowLog.LogItem @RunWith(RobolectricTestRunner::class) @Config(manifest = Config.NONE) class TimberTest { @Before @After fun setUpAndTearDown() { Timber.uprootAll() } // NOTE: This class references the line number. Keep it at the top so it does not change. @Test fun debugTreeCanAlterCreatedTag() { Timber.plant(object : Timber.DebugTree() { override fun createStackElementTag(element: StackTraceElement): String? { return super.createStackElementTag(element) + ':'.toString() + element.lineNumber } }) Timber.d("Test") assertLog() .hasDebugMessage("TimberTest:38", "Test") .hasNoMoreMessages() } @Test fun recursion() { val timber = Timber.asTree() assertThrows<IllegalArgumentException> { Timber.plant(timber) }.hasMessageThat().isEqualTo("Cannot plant Timber into itself.") assertThrows<IllegalArgumentException> { @Suppress("RemoveRedundantSpreadOperator") // Explicitly calling vararg overload. Timber.plant(*arrayOf(timber)) }.hasMessageThat().isEqualTo("Cannot plant Timber into itself.") } @Test fun treeCount() { // inserts trees and checks if the amount of returned trees matches. assertThat(Timber.treeCount).isEqualTo(0) for (i in 1 until 50) { Timber.plant(Timber.DebugTree()) assertThat(Timber.treeCount).isEqualTo(i) } Timber.uprootAll() assertThat(Timber.treeCount).isEqualTo(0) } @Test fun forestReturnsAllPlanted() { val tree1 = Timber.DebugTree() val tree2 = Timber.DebugTree() Timber.plant(tree1) Timber.plant(tree2) assertThat(Timber.forest()).containsExactly(tree1, tree2) } @Test fun forestReturnsAllTreesPlanted() { val tree1 = Timber.DebugTree() val tree2 = Timber.DebugTree() Timber.plant(tree1, tree2) assertThat(Timber.forest()).containsExactly(tree1, tree2) } @Test fun uprootThrowsIfMissing() { assertThrows<IllegalArgumentException> { Timber.uproot(Timber.DebugTree()) }.hasMessageThat().startsWith("Cannot uproot tree which is not planted: ") } @Test fun uprootRemovesTree() { val tree1 = Timber.DebugTree() val tree2 = Timber.DebugTree() Timber.plant(tree1) Timber.plant(tree2) Timber.d("First") Timber.uproot(tree1) Timber.d("Second") assertLog() .hasDebugMessage("TimberTest", "First") .hasDebugMessage("TimberTest", "First") .hasDebugMessage("TimberTest", "Second") .hasNoMoreMessages() } @Test fun uprootAllRemovesAll() { val tree1 = Timber.DebugTree() val tree2 = Timber.DebugTree() Timber.plant(tree1) Timber.plant(tree2) Timber.d("First") Timber.uprootAll() Timber.d("Second") assertLog() .hasDebugMessage("TimberTest", "First") .hasDebugMessage("TimberTest", "First") .hasNoMoreMessages() } @Test fun noArgsDoesNotFormat() { Timber.plant(Timber.DebugTree()) Timber.d("te%st") assertLog() .hasDebugMessage("TimberTest", "te%st") .hasNoMoreMessages() } @Test fun debugTreeTagGeneration() { Timber.plant(Timber.DebugTree()) Timber.d("Hello, world!") assertLog() .hasDebugMessage("TimberTest", "Hello, world!") .hasNoMoreMessages() } internal inner class ThisIsAReallyLongClassName { fun run() { Timber.d("Hello, world!") } } @Config(sdk = [25]) @Test fun debugTreeTagTruncation() { Timber.plant(Timber.DebugTree()) ThisIsAReallyLongClassName().run() assertLog() .hasDebugMessage("TimberTest\$ThisIsAReall", "Hello, world!") .hasNoMoreMessages() } @Config(sdk = [26]) @Test fun debugTreeTagNoTruncation() { Timber.plant(Timber.DebugTree()) ThisIsAReallyLongClassName().run() assertLog() .hasDebugMessage("TimberTest\$ThisIsAReallyLongClassName", "Hello, world!") .hasNoMoreMessages() } @Suppress("ObjectLiteralToLambda") // Lambdas != anonymous classes. @Test fun debugTreeTagGenerationStripsAnonymousClassMarker() { Timber.plant(Timber.DebugTree()) object : Runnable { override fun run() { Timber.d("Hello, world!") object : Runnable { override fun run() { Timber.d("Hello, world!") } }.run() } }.run() assertLog() .hasDebugMessage("TimberTest\$debugTreeTag", "Hello, world!") .hasDebugMessage("TimberTest\$debugTreeTag", "Hello, world!") .hasNoMoreMessages() } @Suppress("ObjectLiteralToLambda") // Lambdas != anonymous classes. @Test fun debugTreeTagGenerationStripsAnonymousClassMarkerWithInnerSAMLambda() { Timber.plant(Timber.DebugTree()) object : Runnable { override fun run() { Timber.d("Hello, world!") Runnable { Timber.d("Hello, world!") }.run() } }.run() assertLog() .hasDebugMessage("TimberTest\$debugTreeTag", "Hello, world!") .hasDebugMessage("TimberTest\$debugTreeTag", "Hello, world!") .hasNoMoreMessages() } @Suppress("ObjectLiteralToLambda") // Lambdas != anonymous classes. @Test fun debugTreeTagGenerationStripsAnonymousClassMarkerWithOuterSAMLambda() { Timber.plant(Timber.DebugTree()) Runnable { Timber.d("Hello, world!") object : Runnable { override fun run() { Timber.d("Hello, world!") } }.run() }.run() assertLog() .hasDebugMessage("TimberTest", "Hello, world!") .hasDebugMessage("TimberTest\$debugTreeTag", "Hello, world!") .hasNoMoreMessages() } // NOTE: this will fail on some future version of Kotlin when lambdas are compiled using invokedynamic // Fix will be to expect the tag to be "TimberTest" as opposed to "TimberTest\$debugTreeTag" @Test fun debugTreeTagGenerationStripsAnonymousLambdaClassMarker() { Timber.plant(Timber.DebugTree()) val outer = { Timber.d("Hello, world!") val inner = { Timber.d("Hello, world!") } inner() } outer() assertLog() .hasDebugMessage("TimberTest\$debugTreeTag", "Hello, world!") .hasDebugMessage("TimberTest\$debugTreeTag", "Hello, world!") .hasNoMoreMessages() } @Test fun debugTreeTagGenerationForSAMLambdasUsesClassName() { Timber.plant(Timber.DebugTree()) Runnable { Timber.d("Hello, world!") Runnable { Timber.d("Hello, world!") }.run() }.run() assertLog() .hasDebugMessage("TimberTest", "Hello, world!") .hasDebugMessage("TimberTest", "Hello, world!") .hasNoMoreMessages() } private class ClassNameThatIsReallyReallyReallyLong { init { Timber.i("Hello, world!") } } @Test fun debugTreeGeneratedTagIsLoggable() { Timber.plant(object : Timber.DebugTree() { private val MAX_TAG_LENGTH = 23 override fun log(priority: Int, tag: String?, message: String, t: Throwable?) { try { assertTrue(Log.isLoggable(tag, priority)) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { assertTrue(tag!!.length <= MAX_TAG_LENGTH) } } catch (e: IllegalArgumentException) { fail(e.message) } super.log(priority, tag, message, t) } }) ClassNameThatIsReallyReallyReallyLong() assertLog() .hasInfoMessage("TimberTest\$ClassNameTha", "Hello, world!") .hasNoMoreMessages() } @Test fun debugTreeCustomTag() { Timber.plant(Timber.DebugTree()) Timber.tag("Custom").d("Hello, world!") assertLog() .hasDebugMessage("Custom", "Hello, world!") .hasNoMoreMessages() } @Test fun messageWithException() { Timber.plant(Timber.DebugTree()) val datThrowable = truncatedThrowable(NullPointerException::class.java) Timber.e(datThrowable, "OMFG!") assertExceptionLogged(Log.ERROR, "OMFG!", "java.lang.NullPointerException") } @Test fun exceptionOnly() { Timber.plant(Timber.DebugTree()) Timber.v(truncatedThrowable(IllegalArgumentException::class.java)) assertExceptionLogged(Log.VERBOSE, null, "java.lang.IllegalArgumentException", "TimberTest", 0) Timber.i(truncatedThrowable(NullPointerException::class.java)) assertExceptionLogged(Log.INFO, null, "java.lang.NullPointerException", "TimberTest", 1) Timber.d(truncatedThrowable(UnsupportedOperationException::class.java)) assertExceptionLogged(Log.DEBUG, null, "java.lang.UnsupportedOperationException", "TimberTest", 2) Timber.w(truncatedThrowable(UnknownHostException::class.java)) assertExceptionLogged(Log.WARN, null, "java.net.UnknownHostException", "TimberTest", 3) Timber.e(truncatedThrowable(ConnectException::class.java)) assertExceptionLogged(Log.ERROR, null, "java.net.ConnectException", "TimberTest", 4) Timber.wtf(truncatedThrowable(AssertionError::class.java)) assertExceptionLogged(Log.ASSERT, null, "java.lang.AssertionError", "TimberTest", 5) } @Test fun exceptionOnlyCustomTag() { Timber.plant(Timber.DebugTree()) Timber.tag("Custom").v(truncatedThrowable(IllegalArgumentException::class.java)) assertExceptionLogged(Log.VERBOSE, null, "java.lang.IllegalArgumentException", "Custom", 0) Timber.tag("Custom").i(truncatedThrowable(NullPointerException::class.java)) assertExceptionLogged(Log.INFO, null, "java.lang.NullPointerException", "Custom", 1) Timber.tag("Custom").d(truncatedThrowable(UnsupportedOperationException::class.java)) assertExceptionLogged(Log.DEBUG, null, "java.lang.UnsupportedOperationException", "Custom", 2) Timber.tag("Custom").w(truncatedThrowable(UnknownHostException::class.java)) assertExceptionLogged(Log.WARN, null, "java.net.UnknownHostException", "Custom", 3) Timber.tag("Custom").e(truncatedThrowable(ConnectException::class.java)) assertExceptionLogged(Log.ERROR, null, "java.net.ConnectException", "Custom", 4) Timber.tag("Custom").wtf(truncatedThrowable(AssertionError::class.java)) assertExceptionLogged(Log.ASSERT, null, "java.lang.AssertionError", "Custom", 5) } @Test fun exceptionFromSpawnedThread() { Timber.plant(Timber.DebugTree()) val datThrowable = truncatedThrowable(NullPointerException::class.java) val latch = CountDownLatch(1) object : Thread() { override fun run() { Timber.e(datThrowable, "OMFG!") latch.countDown() } }.start() latch.await() assertExceptionLogged(Log.ERROR, "OMFG!", "java.lang.NullPointerException", "TimberTest\$exceptionFro") } @Test fun nullMessageWithThrowable() { Timber.plant(Timber.DebugTree()) val datThrowable = truncatedThrowable(NullPointerException::class.java) Timber.e(datThrowable, null) assertExceptionLogged(Log.ERROR, "", "java.lang.NullPointerException") } @Test fun chunkAcrossNewlinesAndLimit() { Timber.plant(Timber.DebugTree()) Timber.d( 'a'.repeat(3000) + '\n'.toString() + 'b'.repeat(6000) + '\n'.toString() + 'c'.repeat(3000)) assertLog() .hasDebugMessage("TimberTest", 'a'.repeat(3000)) .hasDebugMessage("TimberTest", 'b'.repeat(4000)) .hasDebugMessage("TimberTest", 'b'.repeat(2000)) .hasDebugMessage("TimberTest", 'c'.repeat(3000)) .hasNoMoreMessages() } @Test fun nullMessageWithoutThrowable() { Timber.plant(Timber.DebugTree()) Timber.d(null as String?) assertLog().hasNoMoreMessages() } @Test fun logMessageCallback() { val logs = ArrayList<String>() Timber.plant(object : Timber.DebugTree() { override fun log(priority: Int, tag: String?, message: String, t: Throwable?) { logs.add("$priority $tag $message") } }) Timber.v("Verbose") Timber.tag("Custom").v("Verbose") Timber.d("Debug") Timber.tag("Custom").d("Debug") Timber.i("Info") Timber.tag("Custom").i("Info") Timber.w("Warn") Timber.tag("Custom").w("Warn") Timber.e("Error") Timber.tag("Custom").e("Error") Timber.wtf("Assert") Timber.tag("Custom").wtf("Assert") assertThat(logs).containsExactly( // "2 TimberTest Verbose", // "2 Custom Verbose", // "3 TimberTest Debug", // "3 Custom Debug", // "4 TimberTest Info", // "4 Custom Info", // "5 TimberTest Warn", // "5 Custom Warn", // "6 TimberTest Error", // "6 Custom Error", // "7 TimberTest Assert", // "7 Custom Assert" // ) } @Test fun logAtSpecifiedPriority() { Timber.plant(Timber.DebugTree()) Timber.log(Log.VERBOSE, "Hello, World!") Timber.log(Log.DEBUG, "Hello, World!") Timber.log(Log.INFO, "Hello, World!") Timber.log(Log.WARN, "Hello, World!") Timber.log(Log.ERROR, "Hello, World!") Timber.log(Log.ASSERT, "Hello, World!") assertLog() .hasVerboseMessage("TimberTest", "Hello, World!") .hasDebugMessage("TimberTest", "Hello, World!") .hasInfoMessage("TimberTest", "Hello, World!") .hasWarnMessage("TimberTest", "Hello, World!") .hasErrorMessage("TimberTest", "Hello, World!") .hasAssertMessage("TimberTest", "Hello, World!") .hasNoMoreMessages() } @Test fun formatting() { Timber.plant(Timber.DebugTree()) Timber.v("Hello, %s!", "World") Timber.d("Hello, %s!", "World") Timber.i("Hello, %s!", "World") Timber.w("Hello, %s!", "World") Timber.e("Hello, %s!", "World") Timber.wtf("Hello, %s!", "World") assertLog() .hasVerboseMessage("TimberTest", "Hello, World!") .hasDebugMessage("TimberTest", "Hello, World!") .hasInfoMessage("TimberTest", "Hello, World!") .hasWarnMessage("TimberTest", "Hello, World!") .hasErrorMessage("TimberTest", "Hello, World!") .hasAssertMessage("TimberTest", "Hello, World!") .hasNoMoreMessages() } @Test fun isLoggableControlsLogging() { Timber.plant(object : Timber.DebugTree() { @Suppress("OverridingDeprecatedMember") // Explicitly testing deprecated variant. override fun isLoggable(priority: Int): Boolean { return priority == Log.INFO } }) Timber.v("Hello, World!") Timber.d("Hello, World!") Timber.i("Hello, World!") Timber.w("Hello, World!") Timber.e("Hello, World!") Timber.wtf("Hello, World!") assertLog() .hasInfoMessage("TimberTest", "Hello, World!") .hasNoMoreMessages() } @Test fun isLoggableTagControlsLogging() { Timber.plant(object : Timber.DebugTree() { override fun isLoggable(tag: String?, priority: Int): Boolean { return "FILTER" == tag } }) Timber.tag("FILTER").v("Hello, World!") Timber.d("Hello, World!") Timber.i("Hello, World!") Timber.w("Hello, World!") Timber.e("Hello, World!") Timber.wtf("Hello, World!") assertLog() .hasVerboseMessage("FILTER", "Hello, World!") .hasNoMoreMessages() } @Test fun logsUnknownHostExceptions() { Timber.plant(Timber.DebugTree()) Timber.e(truncatedThrowable(UnknownHostException::class.java), null) assertExceptionLogged(Log.ERROR, "", "UnknownHostException") } @Test fun tagIsClearedWhenNotLoggable() { Timber.plant(object : Timber.DebugTree() { override fun isLoggable(tag: String?, priority: Int): Boolean { return priority >= Log.WARN } }) Timber.tag("NotLogged").i("Message not logged") Timber.w("Message logged") assertLog() .hasWarnMessage("TimberTest", "Message logged") .hasNoMoreMessages() } @Test fun logsWithCustomFormatter() { Timber.plant(object : Timber.DebugTree() { override fun formatMessage(message: String, vararg args: Any?): String { return String.format("Test formatting: $message", *args) } }) Timber.d("Test message logged. %d", 100) assertLog() .hasDebugMessage("TimberTest", "Test formatting: Test message logged. 100") } private fun <T : Throwable> truncatedThrowable(throwableClass: Class<T>): T { val throwable = throwableClass.newInstance() val stackTrace = throwable.stackTrace val traceLength = if (stackTrace.size > 5) 5 else stackTrace.size throwable.stackTrace = stackTrace.copyOf(traceLength) return throwable } private fun Char.repeat(number: Int) = toString().repeat(number) private fun assertExceptionLogged( logType: Int, message: String?, exceptionClassname: String, tag: String? = null, index: Int = 0 ) { val logs = getLogs() assertThat(logs).hasSize(index + 1) val log = logs[index] assertThat(log.type).isEqualTo(logType) assertThat(log.tag).isEqualTo(tag ?: "TimberTest") if (message != null) { assertThat(log.msg).startsWith(message) } assertThat(log.msg).contains(exceptionClassname) // We use a low-level primitive that Robolectric doesn't populate. assertThat(log.throwable).isNull() } private fun assertLog(): LogAssert { return LogAssert(getLogs()) } private fun getLogs() = ShadowLog.getLogs().filter { it.tag != ROBOLECTRIC_INSTRUMENTATION_TAG } private inline fun <reified T : Throwable> assertThrows(body: () -> Unit): ThrowableSubject { try { body() } catch (t: Throwable) { if (t is T) { return assertThat(t) } throw t } throw AssertionError("Expected body to throw ${T::class.java.name} but completed successfully") } private class LogAssert internal constructor(private val items: List<LogItem>) { private var index = 0 fun hasVerboseMessage(tag: String, message: String): LogAssert { return hasMessage(Log.VERBOSE, tag, message) } fun hasDebugMessage(tag: String, message: String): LogAssert { return hasMessage(Log.DEBUG, tag, message) } fun hasInfoMessage(tag: String, message: String): LogAssert { return hasMessage(Log.INFO, tag, message) } fun hasWarnMessage(tag: String, message: String): LogAssert { return hasMessage(Log.WARN, tag, message) } fun hasErrorMessage(tag: String, message: String): LogAssert { return hasMessage(Log.ERROR, tag, message) } fun hasAssertMessage(tag: String, message: String): LogAssert { return hasMessage(Log.ASSERT, tag, message) } private fun hasMessage(priority: Int, tag: String, message: String): LogAssert { val item = items[index++] assertThat(item.type).isEqualTo(priority) assertThat(item.tag).isEqualTo(tag) assertThat(item.msg).isEqualTo(message) return this } fun hasNoMoreMessages() { assertThat(items).hasSize(index) } } private companion object { private const val ROBOLECTRIC_INSTRUMENTATION_TAG = "MonitoringInstr" } }
timber/src/test/java/timber/log/TimberTest.kt
563334464
package com.nextcloud.client.etm.pages import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import com.nextcloud.client.etm.EtmBaseFragment import com.owncloud.android.R import com.owncloud.android.databinding.FragmentEtmMigrationsBinding import java.util.Locale class EtmMigrations : EtmBaseFragment() { private var _binding: FragmentEtmMigrationsBinding? = null private val binding get() = _binding!! override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = FragmentEtmMigrationsBinding.inflate(inflater, container, false) return binding.root } override fun onResume() { super.onResume() showStatus() } fun showStatus() { val builder = StringBuilder() val status = vm.migrationsStatus.toString().toLowerCase(Locale.US) builder.append("Migration status: $status\n") val lastMigratedVersion = if (vm.lastMigratedVersion >= 0) { vm.lastMigratedVersion.toString() } else { "never" } builder.append("Last migrated version: $lastMigratedVersion\n") builder.append("Migrations:\n") vm.migrationsInfo.forEach { val migrationStatus = if (it.applied) { "applied" } else { "pending" } builder.append(" - ${it.id} ${it.description} - $migrationStatus\n") } binding.etmMigrationsText.text = builder.toString() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.fragment_etm_migrations, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.etm_migrations_delete -> { onDeleteMigrationsClicked(); true } else -> super.onOptionsItemSelected(item) } } private fun onDeleteMigrationsClicked() { vm.clearMigrations() showStatus() } override fun onDestroyView() { super.onDestroyView() _binding = null } }
app/src/main/java/com/nextcloud/client/etm/pages/EtmMigrations.kt
3397324990
package com.beust.kobalt.internal import com.beust.kobalt.Args import com.beust.kobalt.AsciiArt import com.beust.kobalt.api.* import com.beust.kobalt.misc.kobaltLog import java.util.concurrent.ConcurrentHashMap /** * Record timings and statuses for tasks and projects and display them at the end of the build. */ class BuildListeners : IBuildListener, IBuildReportContributor { class ProfilerInfo(val taskName: String, val durationMillis: Long) class ProjectInfo(val projectName: String, var durationMillis: Long = 0, var shortMessage: String? = null, var longMessage: String? = null) private val startTimes = ConcurrentHashMap<String, Long>() private val timings = arrayListOf<ProfilerInfo>() private val projectInfos = hashMapOf<String, ProjectInfo>() private var hasFailures = false private val args: Args get() = Kobalt.INJECTOR.getInstance(Args::class.java) private var buildStartTime: Long? = null // IBuildListener override fun taskStart(project: Project, context: KobaltContext, taskName: String) { startTimes.put(taskName, System.currentTimeMillis()) if (! projectInfos.containsKey(project.name)) { projectInfos.put(project.name, ProjectInfo(project.name)) } } // IBuildListener override fun taskEnd(project: Project, context: KobaltContext, taskName: String, info: IBuildListener.TaskEndInfo) { val success = info.success if (! success) hasFailures = true startTimes[taskName]?.let { val taskTime = System.currentTimeMillis() - it timings.add(ProfilerInfo(taskName, taskTime)) projectInfos[project.name]?.let { it.durationMillis += taskTime if (info.shortMessage != null && it.shortMessage == null) it.shortMessage = info.shortMessage if (info.longMessage != null && it.longMessage == null) it.longMessage = info.longMessage } } } private val projectStatuses = arrayListOf<Pair<Project, String>>() // IBuildListener override fun projectStart(project: Project, context: KobaltContext) { if (buildStartTime == null) buildStartTime = System.currentTimeMillis() } // IBuildListener override fun projectEnd(project: Project, context: KobaltContext, status: ProjectBuildStatus) { val shortMessage = projectInfos[project.name]?.shortMessage val statusText = status.toString() + (if (shortMessage != null) " ($shortMessage)" else "") projectStatuses.add(Pair(project, statusText)) } // IBuildReportContributor override fun generateReport(context: KobaltContext) { fun formatMillis(millis: Long, format: String) = String.format(format, millis.toDouble() / 1000) fun formatMillisRight(millis: Long, length: Int) = formatMillis(millis, "%1\$$length.2f") fun formatMillisLeft(millis: Long, length: Int) = formatMillis(millis, "%1\$-$length.2f") fun millisToSeconds(millis: Long) = (millis.toDouble() / 1000).toInt() val profiling = args.profiling if (profiling) { kobaltLog(1, "\n" + AsciiArt.horizontalSingleLine + " Timings (in seconds)") timings.sortedByDescending { it.durationMillis }.forEach { kobaltLog(1, formatMillisRight(it.durationMillis, 10) + " " + it.taskName) } kobaltLog(1, "\n") } // Calculate the longest short message so we can create a column long enough to contain it val width = 12 + (projectInfos.values.map { it.shortMessage?.length ?: 0 }.maxBy { it } ?: 0) fun col1(s: String) = String.format(" %1\$-30s", s) fun col2(s: String) = String.format(" %1\$-${width}s", s) fun col3(s: String) = String.format(" %1\$-8s", s) // Only print the build report if there is more than one project and at least one of them failed if (timings.any()) { // if (timings.size > 1 && hasFailures) { val line = listOf(col1("Project"), col2("Build status"), col3("Time")) .joinToString(AsciiArt.verticalBar) val table = StringBuffer() table.append(AsciiArt.logBox(listOf(line), AsciiArt.bottomLeft2, AsciiArt.bottomRight2, indent = 10) + "\n") projectStatuses.forEach { pair -> val projectName = pair.first.name val cl = listOf(col1(projectName), col2(pair.second), col3(formatMillisLeft(projectInfos[projectName]!!.durationMillis, 8))) .joinToString(AsciiArt.verticalBar) table.append(" " + AsciiArt.verticalBar + " " + cl + " " + AsciiArt.verticalBar + "\n") } table.append(" " + AsciiArt.lowerBox(line.length)) kobaltLog(1, table.toString()) // } } val buildTime = if (buildStartTime != null) millisToSeconds(System.currentTimeMillis() - buildStartTime!!) else 0 // BUILD SUCCESSFUL / FAILED message val message = if (hasFailures) { String.format("BUILD FAILED", buildTime) } else if (! args.sequential) { val sequentialBuildTime = ((projectInfos.values.sumByDouble { it.durationMillis.toDouble() }) / 1000) .toInt() String.format("PARALLEL BUILD SUCCESSFUL (%d SECONDS), sequential build would have taken %d seconds", buildTime, sequentialBuildTime) } else { String.format("BUILD SUCCESSFUL (%d SECONDS)", buildTime) } kobaltLog(1, message) } }
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/internal/BuildListeners.kt
2490675328
package de.fabmax.binparse import java.util.* import kotlin.text.Regex /** * Created by max on 15.11.2015. */ abstract class FieldDefFactory { companion object { private val decimalRegex = Regex("([0-9]*)|(0x[0-9a-fA-F]*)|(0b[01]*)") private val parserFactories = HashMap<String, FieldDefFactory>() init { parserFactories.put("int", IntDef.Factory(0, null)) parserFactories.put("bit", IntDef.Factory(1, IntDef.Signedness.UNSIGNED)) parserFactories.put("u08", IntDef.Factory(8, IntDef.Signedness.UNSIGNED)) parserFactories.put("u16", IntDef.Factory(16, IntDef.Signedness.UNSIGNED)) parserFactories.put("u32", IntDef.Factory(32, IntDef.Signedness.UNSIGNED)) parserFactories.put("u64", IntDef.Factory(64, IntDef.Signedness.UNSIGNED)) parserFactories.put("i08", IntDef.Factory(8, IntDef.Signedness.SIGNED)) parserFactories.put("i16", IntDef.Factory(16, IntDef.Signedness.SIGNED)) parserFactories.put("i32", IntDef.Factory(32, IntDef.Signedness.SIGNED)) parserFactories.put("i64", IntDef.Factory(64, IntDef.Signedness.SIGNED)) parserFactories.put("string", StringDef.Factory(null)) parserFactories.put("utf-8", StringDef.Factory(Charsets.UTF_8)) parserFactories.put("array", ArrayDef.Factory()) parserFactories.put("select", SelectDef.Factory()) } fun createParser(definition: Item): FieldDef<*> { try { val fac = parserFactories[definition.value] ?: throw IllegalArgumentException("Unknown type: " + definition.value) val parser = fac.createParser(definition) addQualifiers(definition, parser) return parser } catch (e: Exception) { throw IllegalArgumentException("Failed to create parser for " + definition.identifier + ": " + definition.value, e) } } fun addParserFactory(typeName: String, factory: FieldDefFactory) { if (parserFactories.containsKey(typeName)) { throw IllegalArgumentException("Type name is already registered") } parserFactories.put(typeName, factory) } fun isType(name: String): Boolean { return parserFactories.containsKey(name) } private fun addQualifiers(definition: Item, fieldDef: FieldDef<*>) { val qualifiers = definition.childrenMap["_qualifiers"] ?: return qualifiers.value.splitToSequence('|').forEach { val q = it.trim() if (Field.QUALIFIERS.contains(q)) { fieldDef.qualifiers.add(q) } else { throw IllegalArgumentException("Invalid / unknown qualifier: $q") } } } internal fun parseDecimal(string: String): Long? { if (string.matches(decimalRegex)) { if (string.startsWith("0x")) { return java.lang.Long.parseLong(string.substring(2), 16); } else if (string.startsWith("0b")) { return java.lang.Long.parseLong(string.substring(2), 1); } else { return java.lang.Long.parseLong(string); } } else { return null } } internal fun getItem(items: Map<String, Item>, name: String): Item { val item = items[name] ?: throw IllegalArgumentException("Missing attribute \"$name\""); return item; } } abstract fun createParser(definition: Item): FieldDef<*>; }
src/main/kotlin/de/fabmax/binparse/FieldDefFactory.kt
1409158655
package mixit.model data class Credential(val email: String, val token: String)
src/main/kotlin/mixit/model/Credential.kt
1799696649
// // (C) Copyright 2017-2019 Martin E. Nordberg III // Apache 2.0 License // package i.katydid.vdom.elements.text import i.katydid.vdom.builders.KatydidPhrasingContentBuilderImpl import i.katydid.vdom.elements.KatydidHtmlElementImpl import o.katydid.vdom.builders.KatydidAttributesContentBuilder import o.katydid.vdom.types.EDirection //--------------------------------------------------------------------------------------------------------------------- /** * Virtual node for a <br> element. */ internal class KatydidBr<Msg>( phrasingContent: KatydidPhrasingContentBuilderImpl<Msg>, selector: String?, key: Any?, accesskey: Char?, contenteditable: Boolean?, dir: EDirection?, draggable: Boolean?, hidden: Boolean?, lang: String?, spellcheck: Boolean?, style: String?, tabindex: Int?, title: String?, translate: Boolean?, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) : KatydidHtmlElementImpl<Msg>(selector, key, accesskey, contenteditable, dir, draggable, hidden, lang, spellcheck, style, tabindex, title, translate) { init { phrasingContent.attributesContent(this).defineAttributes() this.freeze() } //// override val nodeName = "BR" } //---------------------------------------------------------------------------------------------------------------------
Katydid-VDOM-JS/src/main/kotlin/i/katydid/vdom/elements/text/KatydidBr.kt
2207040384
/* * 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.view import android.content.Context import android.content.res.TypedArray import android.graphics.Rect import android.support.annotation.Keep import android.support.annotation.StyleableRes import android.support.design.widget.AppBarLayout import android.support.design.widget.CoordinatorLayout import android.support.v4.view.ViewCompat import android.util.AttributeSet import android.util.TypedValue import android.view.View import android.widget.TextView import de.vanita5.twittnuker.R import de.vanita5.twittnuker.extension.* class AppBarChildBehavior( context: Context, attrs: AttributeSet? = null ) : CoordinatorLayout.Behavior<View>(context, attrs) { private val appBarId: Int private val toolbarId: Int private val dependencyViewId: Int private val targetViewId: Int private val alignmentRule: Int private val marginTop: Int private val marginBottom: Int private val marginLeft: Int private val marginRight: Int private val marginStart: Int private val marginEnd: Int private val transformation: ChildTransformation private val dependencyRect = Rect() private val layoutRect = Rect() private val thisRect = Rect() private val targetRect = Rect() private val tempLocation = IntArray(2) init { val a = context.obtainStyledAttributes(attrs, R.styleable.AppBarChildBehavior) appBarId = a.getResourceIdOrThrow(R.styleable.AppBarChildBehavior_behavior_appBarId, "appBarId") toolbarId = a.getResourceIdOrThrow(R.styleable.AppBarChildBehavior_behavior_toolbarId, "toolbarId") dependencyViewId = a.getResourceIdOrThrow(R.styleable.AppBarChildBehavior_behavior_dependencyViewId, "dependencyViewId") targetViewId = a.getResourceIdOrThrow(R.styleable.AppBarChildBehavior_behavior_targetViewId, "targetViewId") alignmentRule = a.getIntegerOrThrow(R.styleable.AppBarChildBehavior_behavior_alignmentRule, "alignmentRule") marginTop = a.getDimensionPixelSize(R.styleable.AppBarChildBehavior_behavior_marginTop, 0) marginBottom = a.getDimensionPixelSize(R.styleable.AppBarChildBehavior_behavior_marginBottom, 0) marginLeft = a.getDimensionPixelSize(R.styleable.AppBarChildBehavior_behavior_marginLeft, 0) marginRight = a.getDimensionPixelSize(R.styleable.AppBarChildBehavior_behavior_marginRight, 0) marginStart = a.getDimensionPixelSize(R.styleable.AppBarChildBehavior_behavior_marginStart, 0) marginEnd = a.getDimensionPixelSize(R.styleable.AppBarChildBehavior_behavior_marginEnd, 0) transformation = a.getTransformation(R.styleable.AppBarChildBehavior_behavior_childTransformation) a.recycle() } override fun layoutDependsOn(parent: CoordinatorLayout, child: View, dependency: View): Boolean { return dependency.id == dependencyViewId } override fun onLayoutChild(parent: CoordinatorLayout, child: View, layoutDirection: Int): Boolean { val target = parent.findViewById<View>(targetViewId) val dependency = parent.getDependencies(child).first() dependency.getFrameRelatedTo(dependencyRect, parent) layoutRect.layoutRelatedTo(child, parent, dependencyRect, layoutDirection) child.layout(layoutRect.left, layoutRect.top, layoutRect.right, layoutRect.bottom) child.getFrameRelatedTo(thisRect, parent) target.getFrameRelatedTo(targetRect, parent) transformation.onChildLayoutChanged(child, dependency, target) return true } override fun onDependentViewChanged(parent: CoordinatorLayout, child: View, dependency: View): Boolean { val appBar = parent.findViewById<View>(appBarId) val target = parent.findViewById<View>(targetViewId) val toolbar = parent.findViewById<View>(toolbarId) val behavior = (appBar.layoutParams as CoordinatorLayout.LayoutParams).behavior as AppBarLayout.Behavior toolbar.getLocationOnScreen(tempLocation) val offset = behavior.topAndBottomOffset val percent = offset / (tempLocation[1] + toolbar.height - appBar.height).toFloat() transformation.onTargetChanged(child, thisRect, target, targetRect, percent, offset) return true } internal fun Rect.layoutRelatedTo(view: View, parent: CoordinatorLayout, frame: Rect, layoutDirection: Int) { val verticalRule = alignmentRule and VERTICAL_MASK val horizontalRule = alignmentRule and HORIZONTAL_MASK set(0, 0, view.measuredWidth, view.measuredHeight) when (verticalRule) { ALIGNMENT_CENTER_VERTICAL -> { offsetTopTo(frame.centerY() - view.measuredHeight / 2 + marginTop - marginBottom) } 0, ALIGNMENT_TOP -> { offsetTopTo(frame.top + marginTop) } ALIGNMENT_BOTTOM -> { offsetBottomTo(frame.bottom - marginBottom) } ALIGNMENT_ABOVE -> { offsetBottomTo(frame.top + marginTop - marginBottom) } ALIGNMENT_BELOW -> { offsetTopTo(frame.bottom + marginTop - marginBottom) } ALIGNMENT_ABOVE_CENTER -> { offsetBottomTo(frame.centerY() + marginTop - marginBottom) } ALIGNMENT_BELOW_CENTER -> { offsetTopTo(frame.centerY() + marginTop - marginBottom) } else -> { throw IllegalArgumentException("Illegal alignment flag ${Integer.toHexString(alignmentRule)}") } } when (horizontalRule) { ALIGNMENT_CENTER_HORIZONTAL -> { offsetLeftTo(frame.centerX() - view.measuredWidth / 2 + absoluteMarginLeft(layoutDirection) - absoluteMarginRight(layoutDirection)) } 0, ALIGNMENT_LEFT -> { offsetLeftTo(frame.left + absoluteMarginLeft(layoutDirection)) } ALIGNMENT_RIGHT -> { offsetRightTo(frame.right - absoluteMarginRight(layoutDirection)) } ALIGNMENT_TO_LEFT_OF -> { offsetRightTo(frame.left + absoluteMarginLeft(layoutDirection) - absoluteMarginRight(layoutDirection)) } ALIGNMENT_TO_RIGHT_OF -> { offsetLeftTo(frame.right + absoluteMarginLeft(layoutDirection) - absoluteMarginRight(layoutDirection)) } ALIGNMENT_TO_LEFT_OF_CENTER -> { offsetRightTo(frame.centerX() + absoluteMarginLeft(layoutDirection) - absoluteMarginRight(layoutDirection)) } ALIGNMENT_TO_RIGHT_OF_CENTER -> { offsetLeftTo(frame.centerX() + absoluteMarginLeft(layoutDirection) - absoluteMarginRight(layoutDirection)) } ALIGNMENT_START -> { offsetStartTo(frame.getStart(layoutDirection) + relativeMarginStart(layoutDirection), layoutDirection) } ALIGNMENT_END -> { offsetEndTo(frame.getEnd(layoutDirection) - relativeMarginEnd(layoutDirection), layoutDirection) } ALIGNMENT_TO_START_OF -> { offsetEndTo(frame.getStart(layoutDirection) + relativeMarginStart(layoutDirection) - relativeMarginEnd(layoutDirection), layoutDirection) } ALIGNMENT_TO_END_OF -> { offsetStartTo(frame.getEnd(layoutDirection) + relativeMarginStart(layoutDirection) - relativeMarginEnd(layoutDirection), layoutDirection) } ALIGNMENT_TO_START_OF_CENTER -> { offsetEndTo(frame.centerX() + relativeMarginStart(layoutDirection) - relativeMarginEnd(layoutDirection), layoutDirection) } ALIGNMENT_TO_END_OF_CENTER -> { offsetStartTo(frame.centerX() + relativeMarginStart(layoutDirection) - relativeMarginEnd(layoutDirection), layoutDirection) } else -> { throw IllegalArgumentException("Illegal alignment flag ${Integer.toHexString(alignmentRule)}") } } left = left.coerceAtLeast(absoluteMarginLeft(layoutDirection) - frame.left) right = right.coerceAtMost(parent.measuredWidth - absoluteMarginRight(layoutDirection) - frame.left) // tempRect.top = tempRect.top.coerceAtLeast(marginTop - frame.top) // tempRect.bottom = tempRect.bottom.coerceAtLeast(parent.measuredHeight - marginBottom - frame.top) } private fun absoluteMarginLeft(layoutDirection: Int): Int { if (marginStart == 0 && marginEnd == 0) return marginLeft if (layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL) { return marginEnd } else { return marginStart } } private fun absoluteMarginRight(layoutDirection: Int): Int { if (marginStart == 0 && marginEnd == 0) return marginRight if (layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL) { return marginStart } else { return marginEnd } } private fun relativeMarginStart(layoutDirection: Int): Int { if (marginStart != 0) { if (layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL) { return -marginStart } else { return marginStart } } else { if (layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL) { return marginRight } else { return marginLeft } } } private fun relativeMarginEnd(layoutDirection: Int): Int { if (marginEnd != 0) { if (layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL) { return -marginEnd } else { return marginEnd } } else { if (layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL) { return marginLeft } else { return marginRight } } } interface ChildTransformation { fun onChildLayoutChanged(child: View, dependency: View, target: View) {} fun onTargetChanged(child: View, frame: Rect, target: View, targetFrame: Rect, percent: Float, offset: Int) } open class ScaleTransformation : ChildTransformation { override fun onTargetChanged(child: View, frame: Rect, target: View, targetFrame: Rect, percent: Float, offset: Int) { child.pivotX = child.width.toFloat() child.pivotY = child.height.toFloat() child.scaleX = 1 - (frame.width() - targetFrame.width()) * percent / frame.width() child.scaleY = 1 - (frame.height() - targetFrame.height()) * percent / frame.height() child.translationX = (targetFrame.right - frame.right) * percent child.translationY = -offset - (frame.bottom - offset - targetFrame.bottom) * percent } } @Keep open class TextViewTransformation : ChildTransformation { private var sourceSize: Float = Float.NaN private var destSize: Float = Float.NaN private var viewLaidOut: Boolean = false override fun onChildLayoutChanged(child: View, dependency: View, target: View) { if (viewLaidOut) return child as TextView target as TextView sourceSize = child.textSize destSize = target.textSize viewLaidOut = true } override fun onTargetChanged(child: View, frame: Rect, target: View, targetFrame: Rect, percent: Float, offset: Int) { child as TextView child.pivotX = child.width.toFloat() child.pivotY = child.height.toFloat() child.translationX = (targetFrame.left - frame.left) * percent child.translationY = -offset - (frame.bottom - offset - targetFrame.bottom) * percent child.setTextSize(TypedValue.COMPLEX_UNIT_PX, sourceSize + (destSize - sourceSize) * percent) } } companion object { private const val HORIZONTAL_MASK: Int = 0x0000FFFF private const val VERTICAL_MASK: Int = 0xFFFF0000.toInt() private const val HORIZONTAL_RELATIVE_FLAG: Int = 0x00001000 const val ALIGNMENT_LEFT: Int = 0x00000001 const val ALIGNMENT_RIGHT: Int = 0x00000002 const val ALIGNMENT_TO_LEFT_OF: Int = 0x00000004 const val ALIGNMENT_TO_RIGHT_OF: Int = 0x00000008 const val ALIGNMENT_TO_LEFT_OF_CENTER: Int = 0x00000010 const val ALIGNMENT_TO_RIGHT_OF_CENTER: Int = 0x00000020 const val ALIGNMENT_CENTER_HORIZONTAL: Int = ALIGNMENT_LEFT or ALIGNMENT_RIGHT const val ALIGNMENT_START: Int = ALIGNMENT_LEFT or HORIZONTAL_RELATIVE_FLAG const val ALIGNMENT_END: Int = ALIGNMENT_RIGHT or HORIZONTAL_RELATIVE_FLAG const val ALIGNMENT_TO_START_OF: Int = ALIGNMENT_TO_LEFT_OF or HORIZONTAL_RELATIVE_FLAG const val ALIGNMENT_TO_END_OF: Int = ALIGNMENT_TO_RIGHT_OF or HORIZONTAL_RELATIVE_FLAG const val ALIGNMENT_TO_START_OF_CENTER: Int = ALIGNMENT_TO_LEFT_OF_CENTER or HORIZONTAL_RELATIVE_FLAG const val ALIGNMENT_TO_END_OF_CENTER: Int = ALIGNMENT_TO_RIGHT_OF_CENTER or HORIZONTAL_RELATIVE_FLAG const val ALIGNMENT_TOP: Int = 0x00010000 const val ALIGNMENT_BOTTOM: Int = 0x00020000 const val ALIGNMENT_ABOVE: Int = 0x00040000 const val ALIGNMENT_BELOW: Int = 0x00080000 const val ALIGNMENT_ABOVE_CENTER: Int = 0x00100000 const val ALIGNMENT_BELOW_CENTER: Int = 0x00200000 const val ALIGNMENT_CENTER_VERTICAL: Int = ALIGNMENT_TOP or ALIGNMENT_BOTTOM private fun TypedArray.getIntegerOrThrow(@StyleableRes index: Int, name: String): Int { if (!hasValue(index)) { throw IllegalArgumentException("$name required") } return getInteger(index, 0) } private fun TypedArray.getResourceIdOrThrow(@StyleableRes index: Int, name: String): Int { if (!hasValue(index)) { throw IllegalArgumentException("$name required") } return getResourceId(index, 0) } private fun TypedArray.getTransformation(@StyleableRes index: Int): ChildTransformation { val className = getString(index) ?: return ScaleTransformation() return Class.forName(className).newInstance() as ChildTransformation } } }
twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/view/AppBarChildBehavior.kt
1864174683
/* * Copyright (c) 2019 by Nicolas Märchy * * This file is part of Sporttag PSA. * * Sporttag PSA 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. * * Sporttag PSA 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 Sporttag PSA. If not, see <http://www.gnu.org/licenses/>. * * Diese Datei ist Teil von Sporttag PSA. * * Sporttag PSA ist Freie Software: Sie können es unter den Bedingungen * der GNU General Public License, wie von der Free Software Foundation, * Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren * veröffentlichten Version, weiterverbreiten und/oder modifizieren. * * Sporttag PSA wird in der Hoffnung, dass es nützlich sein wird, aber * OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite * Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. * Siehe die GNU General Public License für weitere Details. * * Sie sollten eine Kopie der GNU General Public License zusammen mit diesem * Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>. * * */ package ch.schulealtendorf.psa.dto.group /** * Data class representing a coach of a class. * * @author nmaerchy <[email protected]> * @since 2.0.0 */ data class CoachDto( val id: Int, val name: String ) { companion object fun toBuilder() = Builder(this) class Builder internal constructor( private val dto: CoachDto ) { private var name = dto.name fun setName(name: String): Builder { this.name = name return this } fun build() = dto.copy(name = name) } }
app/dto/src/main/kotlin/ch/schulealtendorf/psa/dto/group/CoachDto.kt
1118163884
package de.vanita5.twittnuker.activity import android.accounts.AccountManager import android.app.Dialog import android.content.DialogInterface import android.content.Intent import android.os.Bundle import android.support.v4.app.FragmentActivity import android.support.v7.app.AlertDialog import de.vanita5.twittnuker.R import de.vanita5.twittnuker.constant.IntentConstants.EXTRA_INTENT import de.vanita5.twittnuker.extension.applyTheme import de.vanita5.twittnuker.extension.model.isAccountValid import de.vanita5.twittnuker.extension.onShow import de.vanita5.twittnuker.fragment.BaseDialogFragment import de.vanita5.twittnuker.model.util.AccountUtils import de.vanita5.twittnuker.util.support.removeAccountSupport class InvalidAccountAlertActivity : FragmentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val df = InvalidAccountAlertDialogFragment() df.show(supportFragmentManager, "invalid_account_alert") } class InvalidAccountAlertDialogFragment : BaseDialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val builder = AlertDialog.Builder(context) builder.setTitle(R.string.title_error_invalid_account) builder.setMessage(R.string.message_error_invalid_account) builder.setPositiveButton(android.R.string.ok) { _, _ -> val am = AccountManager.get(context) AccountUtils.getAccounts(am).filter { !am.isAccountValid(it) }.forEach { account -> am.removeAccountSupport(account) } val intent = activity.intent.getParcelableExtra<Intent>(EXTRA_INTENT) if (intent != null) { activity.startActivity(intent) } } builder.setNegativeButton(android.R.string.cancel) { _, _ -> } val dialog = builder.create() dialog.onShow { it.applyTheme() } return dialog } override fun onDismiss(dialog: DialogInterface?) { super.onDismiss(dialog) if (!activity.isFinishing) { activity.finish() } } override fun onCancel(dialog: DialogInterface?) { super.onCancel(dialog) if (!activity.isFinishing) { activity.finish() } } } }
twittnuker/src/main/kotlin/de/vanita5/twittnuker/activity/InvalidAccountAlertActivity.kt
1227883036
package net.semlang.parser.test import net.semlang.api.* import net.semlang.api.Function import net.semlang.parser.* import net.semlang.validator.ValidationResult import net.semlang.validator.validate import org.junit.Assert.assertEquals import org.junit.Test import java.io.File class PartialParsingTest { @Test fun testCanDoValidationWithPartialParsingError() { val sourceFile = File("../../semlang-parser-tests/partialParsing/partiallyValid.sem") val parsingResult = parseFile(sourceFile) when (parsingResult) { is ParsingResult.Success -> { throw IllegalStateException("Should have had a parsing error from the parsing result") } is ParsingResult.Failure -> { val functionIds = parsingResult.partialContext.functions.map(Function::id).map(EntityId::toString).toSet() // For some reason, "bar" stays there // assertEquals(setOf("foo", "baz"), functionIds) val validationResult = validate(parsingResult, ModuleName("a", "b"), CURRENT_NATIVE_MODULE_VERSION, listOf()) when (validationResult) { is ValidationResult.Success -> { throw AssertionError("Should have failed validation") } is ValidationResult.Failure -> { // Intended result } } } } } @Test fun testCanDoValidationWithPartialParsingError2() { val sourceFile = File("../../semlang-parser-tests/partialParsing/partiallyValid2.sem") val parsingResult = parseFile(sourceFile) when (parsingResult) { is ParsingResult.Success -> { throw IllegalStateException("Should have had a parsing error from the parsing result") } is ParsingResult.Failure -> { val functionIds = parsingResult.partialContext.functions.map(Function::id).map(EntityId::toString).toSet() // assertEquals(setOf("bar"), functionIds) val validationResult = validate(parsingResult, ModuleName("a", "b"), CURRENT_NATIVE_MODULE_VERSION, listOf()) when (validationResult) { is ValidationResult.Success -> { throw AssertionError("Should have failed validation") } is ValidationResult.Failure -> { // Intended result } } } } } @Test fun testCanDoValidationWithPartialParsingError3() { val sourceFile = File("../../semlang-parser-tests/partialParsing/partiallyValid3.sem") val parsingResult = parseFile(sourceFile) when (parsingResult) { is ParsingResult.Success -> { throw IllegalStateException("Should have had a parsing error from the parsing result") } is ParsingResult.Failure -> { val structIds = parsingResult.partialContext.structs.map(UnvalidatedStruct::id).map(EntityId::toString).toSet() // assertEquals(setOf("bar"), structIds) val functionIds = parsingResult.partialContext.functions.map(Function::id).map(EntityId::toString).toSet() assertEquals(setOf<String>(), functionIds) val validationResult = validate(parsingResult, ModuleName("a", "b"), CURRENT_NATIVE_MODULE_VERSION, listOf()) when (validationResult) { is ValidationResult.Success -> { throw AssertionError("Should have failed validation") } is ValidationResult.Failure -> { // Intended result } } } } } }
kotlin/semlang-parser/src/test/kotlin/partialParsingTest.kt
1053620807
package com.bl_lia.kirakiratter.data.repository.datasource.translation import com.bl_lia.kirakiratter.domain.value_object.Translation import io.reactivex.Single class ApiTranslationDataStore( val translationService: GoogleTranslationService ) : TranslationDataStore { override fun translate(key: String, sourceLang: String, targetLang: String, query: String): Single<List<Translation>> { return translationService.translate(key, sourceLang, targetLang, query) .map { response -> response.data.translations } } }
app/src/main/kotlin/com/bl_lia/kirakiratter/data/repository/datasource/translation/ApiTranslationDataStore.kt
3653363332
package com.stripe.android.model internal object PaymentIntentFixtures { private val PARSER = com.stripe.android.model.parsers.PaymentIntentJsonParser() const val KEY_ID = "7c4debe3f4af7f9d1569a2ffea4343c2566826ee" private val PI_SUCCEEDED_JSON = org.json.JSONObject( """ { "id": "pi_1IRg6VCRMbs6F", "object": "payment_intent", "amount": 1099, "canceled_at": null, "cancellation_reason": null, "capture_method": "automatic", "client_secret": "pi_1IRg6VCRMbs6F_secret_7oH5g4v8GaCrHfsGYS6kiSnwF", "confirmation_method": "automatic", "created": 1614960135, "currency": "usd", "description": "Example PaymentIntent", "last_payment_error": null, "livemode": false, "next_action": null, "payment_method": "pm_1IJs3ZCRMbs", "payment_method_types": ["card"], "receipt_email": null, "setup_future_usage": null, "shipping": null, "source": null, "status": "succeeded" } """.trimIndent() ) val PI_SUCCEEDED = requireNotNull(PARSER.parse(PI_SUCCEEDED_JSON)) val PI_REQUIRES_MASTERCARD_3DS2_JSON = org.json.JSONObject( """ { "id": "pi_1ExkUeAWhjPjYwPiXph9ouXa", "object": "payment_intent", "amount": 2000, "amount_capturable": 0, "amount_received": 0, "application": null, "application_fee_amount": null, "canceled_at": null, "cancellation_reason": null, "capture_method": "automatic", "charges": { "object": "list", "data": [], "has_more": false, "total_count": 0, "url": "/v1/charges?payment_intent=pi_1ExkUeAWhjPjYwPiXph9ouXa" }, "client_secret": "pi_1ExkUeAWhjPjYwPiXph9ouXa_secret_nGTdfGlzL9Uop59wN55LraiC7", "confirmation_method": "manual", "created": 1563498160, "currency": "usd", "customer": "cus_FSfpeeEUO3TDOJ", "description": "Example PaymentIntent", "invoice": null, "last_payment_error": null, "livemode": true, "next_action": { "type": "use_stripe_sdk", "use_stripe_sdk": { "type": "stripe_3ds2_fingerprint", "three_d_secure_2_source": "src_1ExkUeAWhjPjYwPiLWUvXrSA", "directory_server_name": "mastercard", "server_transaction_id": "34b16ea1-1206-4ee8-84d2-d292bc73c2ae", "three_ds_method_url": "https://secure5.arcot.com/content-server/api/tds2/txn/browser/v1/tds-method", "three_ds_optimizations": "", "directory_server_encryption": { "directory_server_id": "A000000004", "key_id": "7c4debe3f4af7f9d1569a2ffea4343c2566826ee", "algorithm": "RSA", "certificate": "-----BEGIN CERTIFICATE-----\nMIIFtTCCA52gAwIBAgIQJqSRaPua/6cpablmVDHWUDANBgkqhkiG9w0BAQsFADB6\nMQswCQYDVQQGEwJVUzETMBEGA1UEChMKTWFzdGVyQ2FyZDEoMCYGA1UECxMfTWFz\ndGVyQ2FyZCBJZGVudGl0eSBDaGVjayBHZW4gMzEsMCoGA1UEAxMjUFJEIE1hc3Rl\nckNhcmQgM0RTMiBBY3F1aXJlciBTdWIgQ0EwHhcNMTgxMTIwMTQ1MzIzWhcNMjEx\nMTIwMTQ1MzIzWjBxMQswCQYDVQQGEwJVUzEdMBsGA1UEChMUTWFzdGVyQ2FyZCBX\nb3JsZHdpZGUxGzAZBgNVBAsTEmdhdGV3YXktZW5jcnlwdGlvbjEmMCQGA1UEAxMd\nM2RzMi5kaXJlY3RvcnkubWFzdGVyY2FyZC5jb20wggEiMA0GCSqGSIb3DQEBAQUA\nA4IBDwAwggEKAoIBAQCFlZjqbbL9bDKOzZFawdbyfQcezVEUSDCWWsYKw/V6co9A\nGaPBUsGgzxF6+EDgVj3vYytgSl8xFvVPsb4ZJ6BJGvimda8QiIyrX7WUxQMB3hyS\nBOPf4OB72CP+UkaFNR6hdlO5ofzTmB2oj1FdLGZmTN/sj6ZoHkn2Zzums8QAHFjv\nFjspKUYCmms91gpNpJPUUztn0N1YMWVFpFMytahHIlpiGqTDt4314F7sFABLxzFr\nDmcqhf623SPV3kwQiLVWOvewO62ItYUFgHwle2dq76YiKrUv1C7vADSk2Am4gqwv\n7dcCnFeM2AHbBFBa1ZBRQXosuXVw8ZcQqfY8m4iNAgMBAAGjggE+MIIBOjAOBgNV\nHQ8BAf8EBAMCAygwCQYDVR0TBAIwADAfBgNVHSMEGDAWgBSakqJUx4CN/s5W4wMU\n/17uSLhFuzBIBggrBgEFBQcBAQQ8MDowOAYIKwYBBQUHMAGGLGh0dHA6Ly9vY3Nw\nLnBraS5pZGVudGl0eWNoZWNrLm1hc3RlcmNhcmQuY29tMCgGA1UdEQQhMB+CHTNk\nczIuZGlyZWN0b3J5Lm1hc3RlcmNhcmQuY29tMGkGA1UdHwRiMGAwXqBcoFqGWGh0\ndHA6Ly9jcmwucGtpLmlkZW50aXR5Y2hlY2subWFzdGVyY2FyZC5jb20vOWE5MmEy\nNTRjNzgwOGRmZWNlNTZlMzAzMTRmZjVlZWU0OGI4NDViYi5jcmwwHQYDVR0OBBYE\nFHxN6+P0r3+dFWmi/+pDQ8JWaCbuMA0GCSqGSIb3DQEBCwUAA4ICAQAtwW8siyCi\nmhon1WUAUmufZ7bbegf3cTOafQh77NvA0xgVeloELUNCwsSSZgcOIa4Zgpsa0xi5\nfYxXsPLgVPLM0mBhTOD1DnPu1AAm32QVelHe6oB98XxbkQlHGXeOLs62PLtDZd94\n7pm08QMVb+MoCnHLaBLV6eKhKK+SNrfcxr33m0h3v2EMoiJ6zCvp8HgIHEhVpleU\n8H2Uo5YObatb/KUHgtp2z0vEfyGhZR7hrr48vUQpfVGBABsCV0aqUkPxtAXWfQo9\n1N9B7H3EIcSjbiUz5vkj9YeDSyJIi0Y/IZbzuNMsz2cRi1CWLl37w2fe128qWxYq\nY/k+Y4HX7uYchB8xPaZR4JczCvg1FV2JrkOcFvElVXWSMpBbe2PS6OMr3XxrHjzp\nDyM9qvzge0Ai9+rq8AyGoG1dP2Ay83Ndlgi42X3yl1uEUW2feGojCQQCFFArazEj\nLUkSlrB2kA12SWAhsqqQwnBLGSTp7PqPZeWkluQVXS0sbj0878kTra6TjG3U+KqO\nJCj8v6G380qIkAXe1xMHHNQ6GS59HZMeBPYkK2y5hmh/JVo4bRfK7Ya3blBSBfB8\nAVWQ5GqVWklvXZsQLN7FH/fMIT3y8iE1W19Ua4whlhvn7o/aYWOkHr1G2xyh8BHj\n7H63A2hjcPlW/ZAJSTuBZUClAhsNohH2Jg==\n-----END CERTIFICATE-----\n", "root_certificate_authorities": ["-----BEGIN CERTIFICATE-----\nMIIFxzCCA6+gAwIBAgIQFsjyIuqhw80wNMjXU47lfjANBgkqhkiG9w0BAQsFADB8\nMQswCQYDVQQGEwJVUzETMBEGA1UEChMKTWFzdGVyQ2FyZDEoMCYGA1UECxMfTWFz\ndGVyQ2FyZCBJZGVudGl0eSBDaGVjayBHZW4gMzEuMCwGA1UEAxMlUFJEIE1hc3Rl\nckNhcmQgSWRlbnRpdHkgQ2hlY2sgUm9vdCBDQTAeFw0xNjA3MTQwNzI0MDBaFw0z\nMDA3MTUwODEwMDBaMHwxCzAJBgNVBAYTAlVTMRMwEQYDVQQKEwpNYXN0ZXJDYXJk\nMSgwJgYDVQQLEx9NYXN0ZXJDYXJkIElkZW50aXR5IENoZWNrIEdlbiAzMS4wLAYD\nVQQDEyVQUkQgTWFzdGVyQ2FyZCBJZGVudGl0eSBDaGVjayBSb290IENBMIICIjAN\nBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAxZF3nCEiT8XFFaq+3BPT0cMDlWE7\n6IBsdx27w3hLxwVLog42UTasIgzmysTKpBc17HEZyNAqk9GrCHo0Oyk4JZuXHoW8\n0goZaR2sMnn49ytt7aGsE1PsfVup8gqAorfm3IFab2/CniJJNXaWPgn94+U/nsoa\nqTQ6j+6JBoIwnFklhbXHfKrqlkUZJCYaWbZRiQ7nkANYYM2Td3N87FmRanmDXj5B\nG6lc9o1clTC7UvRQmNIL9OdDDZ8qlqY2Fi0eztBnuo2DUS5tGdVy8SgqPM3E12ft\nk4EdlKyrWmBqFcYwGx4AcSJ88O3rQmRBMxtk0r5vhgr6hDCGq7FHK/hQFP9LhUO9\n1qxWEtMn76Sa7DPCLas+tfNRVwG12FBuEZFhdS/qKMdIYUE5Q6uwGTEvTzg2kmgJ\nT3sNa6dbhlYnYn9iIjTh0dPGgiXap1Bhi8B9aaPFcHEHSqW8nZUINcrwf5AUi+7D\n+q/AG5ItiBtQTCaaFm74gv51yutzwgKnH9Q+x3mtuK/uwlLCslj9DeXgOzMWFxFg\nuuwLGX39ktDnetxNw3PLabjHkDlGDIfx0MCQakM74sTcuW8ICiHvNA7fxXCnbtjs\ny7at/yXYwAd+IDS51MA/g3OYVN4M+0pG843Re6Z53oODp0Ymugx0FNO1NxT3HO1h\nd7dXyjAV/tN/GGcCAwEAAaNFMEMwDgYDVR0PAQH/BAQDAgGGMBIGA1UdEwEB/wQI\nMAYBAf8CAQEwHQYDVR0OBBYEFNSlUaqS2hGLFMT/EXrhHeEx+UqxMA0GCSqGSIb3\nDQEBCwUAA4ICAQBLqIYorrtVz56F6WOoLX9CcRjSFim7gO873a3p7+62I6joXMsM\nr0nd9nRPcEwduEloZXwFgErVUQWaUZWNpue0mGvU7BUAgV9Tu0J0yA+9srizVoMv\nx+o4zTJ3Vu5p5aTf1aYoH1xYVo5ooFgl/hI/EXD2lo/xOUfPKXBY7twfiqOziQmT\nGBuqPRq8h3dQRlXYxX/rzGf80SecIT6wo9KavDkjOmJWGzzHsn6Ryo6MEClMaPn0\nte87ukNN740AdPhTvNeZdWlwyqWAJpsv24caEckjSpgpoIZOjc7PAcEVQOWFSxUe\nsMk4Jz5bVZa/ABjzcp+rsq1QLSJ5quqHwWFTewChwpw5gpw+E5SpKY6FIHPlTdl+\nqHThvN8lsKNAQg0qTdEbIFZCUQC0Cl3Ti3q/cXv8tguLJNWvdGzB600Y32QHclMp\neyabT4/QeOesqpx6Da70J2KvLT1j6Ch2BsKSzeVLahrjnoPrdgiIYYBOgeA3T8SE\n1pgagt56R7nIkRQbtesoRKi+NfC7pPb/G1VUsj/cREAHH1i1UKa0aCsIiANfEdQN\n5Ok6wtFJJhp3apAvnVkrZDfOG5we9bYzvGoI7SUnleURBJ+N3ihjARfL4hDeeRHh\nYyLkM3kEyEkrJBL5r0GDjicxM+aFcR2fCBAkv3grT5kz4kLcvsmHX+9DBw==\n-----END CERTIFICATE-----\n\n"] } } }, "on_behalf_of": null, "payment_method": "pm_1ExkUWAWhjPjYwPiBMVId8xT", "payment_method_options": { "card": { "request_three_d_secure": "automatic" } }, "payment_method_types": ["card"], "receipt_email": "[email protected]", "review": null, "setup_future_usage": null, "shipping": { "address": { "city": "San Francisco", "country": "US", "line1": "123 Market St", "line2": "#345", "postal_code": "94107", "state": "CA" }, "carrier": null, "name": "Fake Name", "phone": "(555) 555-5555", "tracking_number": null }, "source": null, "statement_descriptor": null, "status": "requires_action", "transfer_data": null, "transfer_group": null } """.trimIndent() ) val PI_REQUIRES_MASTERCARD_3DS2 = PARSER.parse(PI_REQUIRES_MASTERCARD_3DS2_JSON)!! val PI_REQUIRES_AMEX_3DS2 = PARSER.parse( org.json.JSONObject( """ { "id": "pi_1EceMnCRMbs6FrXfCXdF8dnx", "object": "payment_intent", "amount": 1000, "amount_capturable": 0, "amount_received": 0, "application": null, "application_fee_amount": null, "canceled_at": null, "cancellation_reason": null, "capture_method": "automatic", "charges": { "object": "list", "data": [], "has_more": false, "total_count": 0, "url": "/v1/charges?payment_intent=pi_1EceMnCRMbs6FrXfCXdF8dnx" }, "client_secret": "pi_1EceMnCRMbs6FrXfCXdF8dnx_secret_vew0L3IGaO0x9o0eyRMGzKr0k", "confirmation_method": "automatic", "created": 1558469721, "currency": "usd", "customer": null, "description": null, "invoice": null, "last_payment_error": null, "livemode": false, "metadata": {}, "next_action": { "type": "use_stripe_sdk", "use_stripe_sdk": { "type": "stripe_3ds2_fingerprint", "three_d_secure_2_source": "src_1EceOlCRMbs6FrXf2hqrI1g5", "directory_server_name": "american_express", "server_transaction_id": "e64bb72f-60ac-4845-b8b6-47cfdb0f73aa", "three_ds_method_url": "", "directory_server_encryption": { "directory_server_id": "A000000025", "certificate": "-----BEGIN CERTIFICATE-----\nMIIE0TCCA7mgAwIBAgIUXbeqM1duFcHk4dDBwT8o7Ln5wX8wDQYJKoZIhvcNAQEL\nBQAwXjELMAkGA1UEBhMCVVMxITAfBgNVBAoTGEFtZXJpY2FuIEV4cHJlc3MgQ29t\ncGFueTEsMCoGA1UEAxMjQW1lcmljYW4gRXhwcmVzcyBTYWZla2V5IElzc3Vpbmcg\nQ0EwHhcNMTgwMjIxMjM0OTMxWhcNMjAwMjIxMjM0OTMwWjCB0DELMAkGA1UEBhMC\nVVMxETAPBgNVBAgTCE5ldyBZb3JrMREwDwYDVQQHEwhOZXcgWW9yazE\/MD0GA1UE\nChM2QW1lcmljYW4gRXhwcmVzcyBUcmF2ZWwgUmVsYXRlZCBTZXJ2aWNlcyBDb21w\nYW55LCBJbmMuMTkwNwYDVQQLEzBHbG9iYWwgTmV0d29yayBUZWNobm9sb2d5IC0g\nTmV0d29yayBBUEkgUGxhdGZvcm0xHzAdBgNVBAMTFlNESy5TYWZlS2V5LkVuY3J5\ncHRLZXkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDSFF9kTYbwRrxX\nC6WcJJYio5TZDM62+CnjQRfggV3GMI+xIDtMIN8LL\/jbWBTycu97vrNjNNv+UPhI\nWzhFDdUqyRfrY337A39uE8k1xhdDI3dNeZz6xgq8r9hn2NBou78YPBKidpN5oiHn\nTxcFq1zudut2fmaldaa9a4ZKgIQo+02heiJfJ8XNWkoWJ17GcjJ59UU8C1KF\/y1G\nymYO5ha2QRsVZYI17+ZFsqnpcXwK4Mr6RQKV6UimmO0nr5++CgvXfekcWAlLV6Xq\njuACWi3kw0haepaX\/9qHRu1OSyjzWNcSVZ0On6plB5Lq6Y9ylgmxDrv+zltz3MrT\nK7txIAFFAgMBAAGjggESMIIBDjAMBgNVHRMBAf8EAjAAMCEGA1UdEQQaMBiCFlNE\nSy5TYWZlS2V5LkVuY3J5cHRLZXkwRQYJKwYBBAGCNxQCBDgeNgBBAE0ARQBYAF8A\nUwBBAEYARQBLAEUAWQAyAF8ARABTAF8ARQBOAEMAUgBZAFAAVABJAE8ATjAOBgNV\nHQ8BAf8EBAMCBJAwHwYDVR0jBBgwFoAU7k\/rXuVMhTBxB1zSftPgmLFuDIgwRAYD\nVR0fBD0wOzA5oDegNYYzaHR0cDovL2FtZXhzay5jcmwuY29tLXN0cm9uZy1pZC5u\nZXQvYW1leHNhZmVrZXkuY3JsMB0GA1UdDgQWBBQHclVTo5nwZGH8labJ2F2P45xi\nfDANBgkqhkiG9w0BAQsFAAOCAQEAWY6b77VBoGLs3k5vOqSU7QRqT+4v6y77T8LA\nBKrSZ58DiVZWVyDSxyftQUiRRgFHt2gTN0yfJTP50Fyp84nCEWC0tugZ4iIhgPss\nHzL+4\/u4eG\/MTzK2ESxvPgr6YHajyuU+GXA89u8+bsFrFmojOjhTgFKli7YUeV\/0\nxoiYZf2utlns800ofJrcrfiFoqE6PvK4Od0jpeMgfSKv71nK5ihA1+wTk76ge1fs\nPxL23hEdRpWW11ofaLfJGkLFXMM3\/LHSXWy7HhsBgDELdzLSHU4VkSv8yTOZxsRO\nByxdC5v3tXGcK56iQdtKVPhFGOOEBugw7AcuRzv3f1GhvzAQZg==\n-----END CERTIFICATE-----", "key_id": "7c4debe3f4af7f9d1569a2ffea4343c2566826ee" } } }, "on_behalf_of": null, "payment_method": "pm_1EceOkCRMbs6FrXft9sFxCTG", "payment_method_types": [ "card" ], "receipt_email": null, "review": null, "shipping": null, "source": null, "statement_descriptor": null, "status": "requires_action", "transfer_data": null, "transfer_group": null } """.trimIndent() ) )!! val PI_REQUIRES_3DS1 = PARSER.parse( org.json.JSONObject( """ { "id": "pi_1EceMnCRMbs6FrXfCXdF8dnx", "object": "payment_intent", "amount": 1000, "amount_capturable": 0, "amount_received": 0, "application": null, "application_fee_amount": null, "canceled_at": null, "cancellation_reason": null, "capture_method": "automatic", "charges": { "object": "list", "data": [], "has_more": false, "total_count": 0, "url": "/v1/charges?payment_intent=pi_1EceMnCRMbs6FrXfCXdF8dnx" }, "client_secret": "pi_1EceMnCRMbs6FrXfCXdF8dnx_secret_vew0L3IGaO0x9o0eyRMGzKr0k", "confirmation_method": "automatic", "created": 1558469721, "currency": "usd", "customer": null, "description": null, "invoice": null, "last_payment_error": null, "livemode": false, "metadata": {}, "next_action": { "type": "use_stripe_sdk", "use_stripe_sdk": { "type": "three_d_secure_redirect", "stripe_js": "https://hooks.stripe.com/3d_secure_2_eap/begin_test/src_1Ecve7CRMbs6FrXfm8AxXMIh/src_client_secret_F79yszOBAiuaZTuIhbn3LPUW" } }, "on_behalf_of": null, "payment_method": "pm_1Ecve6CRMbs6FrXf08xsGeHv", "payment_method_types": [ "card" ], "receipt_email": null, "review": null, "shipping": null, "source": null, "statement_descriptor": null, "status": "requires_action", "transfer_data": null, "transfer_group": null } """.trimIndent() ) )!! val PI_REQUIRES_REDIRECT = PARSER.parse( org.json.JSONObject( """ { "id": "pi_1EZlvVCRMbs6FrXfKpq2xMmy", "object": "payment_intent", "amount": 1000, "amount_capturable": 0, "amount_received": 0, "application": null, "application_fee_amount": null, "canceled_at": null, "cancellation_reason": null, "capture_method": "automatic", "charges": { "object": "list", "data": [], "has_more": false, "total_count": 0, "url": "/v1/charges?payment_intent=pi_1EZlvVCRMbs6FrXfKpq2xMmy" }, "client_secret": "pi_1EZlvVCRMbs6FrXfKpq2xMmy_secret_cmhLfbSA54n4", "confirmation_method": "automatic", "created": 1557783797, "currency": "usd", "customer": null, "description": null, "invoice": null, "last_payment_error": null, "livemode": false, "metadata": {}, "next_action": { "redirect_to_url": { "return_url": "stripe://deeplink", "url": "https://hooks.stripe.com/3d_secure_2_eap/begin_test/src_1Ecaz6CRMbs6FrXfuYKBRSUG/src_client_secret_F6octeOshkgxT47dr0ZxSZiv" }, "type": "redirect_to_url" }, "on_behalf_of": null, "payment_method": "pm_1Ecaz6CRMbs6FrXfQs3wNGwB", "payment_method_types": [ "card" ], "receipt_email": null, "review": null, "shipping": null, "source": null, "statement_descriptor": null, "status": "requires_action", "transfer_data": null, "transfer_group": null } """.trimIndent() ) )!! val PI_REQUIRES_PAYMENT_METHOD = PARSER.parse( org.json.JSONObject( """ { "id": "pi_1F7J1aCRMbs6FrXfaJcvbxF6", "object": "payment_intent", "amount": 1099, "canceled_at": null, "cancellation_reason": null, "capture_method": "manual", "client_secret": "pi_1F7J1aCRMbs6FrXfaJcvbxF6_secret_mIuDLsSfoo1m6s", "confirmation_method": "automatic", "created": 1565775850, "currency": "usd", "description": "Example PaymentIntent", "livemode": false, "next_action": null, "payment_method": null, "payment_method_types": [ "card", "link" ], "receipt_email": null, "setup_future_usage": null, "shipping": null, "source": null, "status": "requires_payment_method", "link_funding_sources": [ "CARD", "BANK_ACCOUNT" ] } """.trimIndent() ) )!! val PI_REQUIRES_PAYMENT_METHOD_WITHOUT_LINK = PARSER.parse( org.json.JSONObject( """ { "id": "pi_1F7J1aCRMbs6FrXfaJcvbxF6", "object": "payment_intent", "amount": 1099, "canceled_at": null, "cancellation_reason": null, "capture_method": "manual", "client_secret": "pi_1F7J1aCRMbs6FrXfaJcvbxF6_secret_mIuDLsSfoo1m6s", "confirmation_method": "automatic", "created": 1565775850, "currency": "usd", "description": "Example PaymentIntent", "livemode": false, "next_action": null, "payment_method": null, "payment_method_types": [ "card" ], "receipt_email": null, "setup_future_usage": null, "shipping": null, "source": null, "status": "requires_payment_method" } """.trimIndent() ) )!! val PI_REQUIRES_PAYMENT_METHOD_CARD_SFU_SET = PARSER.parse( org.json.JSONObject( """ { "id": "pi_1F7J1aCRMbs6FrXfaJcvbxF6", "object": "payment_intent", "amount": 1099, "canceled_at": null, "cancellation_reason": null, "capture_method": "manual", "client_secret": "pi_1F7J1aCRMbs6FrXfaJcvbxF6_secret_mIuDLsSfoo1m6s", "confirmation_method": "automatic", "created": 1565775850, "currency": "usd", "description": "Example PaymentIntent", "livemode": false, "next_action": null, "payment_method": null, "payment_method_types": [ "card" ], "payment_method_options": { "card": { "setup_future_usage": null } }, "receipt_email": null, "setup_future_usage": null, "shipping": null, "source": null, "status": "requires_payment_method" } """.trimIndent() ) )!! val PI_WITH_LAST_PAYMENT_ERROR = PARSER.parse( org.json.JSONObject( """ { "id": "pi_1F7J1aCRMbs6FrXfaJcvbxF6", "object": "payment_intent", "amount": 1000, "canceled_at": null, "cancellation_reason": null, "capture_method": "manual", "client_secret": "pi_1F7J1aCRMbs6FrXfaJcvbxF6_secret_mIuDLsSfoo1m6s", "confirmation_method": "automatic", "created": 1565775850, "currency": "usd", "description": "Example PaymentIntent", "last_payment_error": { "code": "payment_intent_authentication_failure", "doc_url": "https://stripe.com/docs/error-codes/payment-intent-authentication-failure", "message": "The provided PaymentMethod has failed authentication. You can provide payment_method_data or a new PaymentMethod to attempt to fulfill this PaymentIntent again.", "payment_method": { "id": "pm_1F7J1bCRMbs6FrXfQKsYwO3U", "object": "payment_method", "billing_details": { "address": { "city": null, "country": null, "line1": null, "line2": null, "postal_code": null, "state": null }, "email": null, "name": null, "phone": null }, "card": { "brand": "visa", "checks": { "address_line1_check": null, "address_postal_code_check": null, "cvc_check": null }, "country": null, "exp_month": 8, "exp_year": 2020, "funding": "credit", "generated_from": null, "last4": "3220", "three_d_secure_usage": { "supported": true }, "wallet": null }, "created": 1565775851, "customer": null, "livemode": false, "metadata": {}, "type": "card" }, "type": "invalid_request_error" }, "livemode": false, "next_action": null, "payment_method": null, "payment_method_types": [ "card" ], "receipt_email": null, "setup_future_usage": null, "shipping": null, "source": null, "status": "requires_payment_method" } """.trimIndent() ) )!! val CANCELLED = PARSER.parse( org.json.JSONObject( """ { "id": "pi_1FCpMECRMbs6FrXfVulorSf5", "object": "payment_intent", "amount": 4000, "amount_capturable": 0, "amount_received": 0, "application": null, "application_fee_amount": null, "canceled_at": 1567091866, "cancellation_reason": "abandoned", "capture_method": "automatic", "charges": { "object": "list", "data": [], "has_more": false, "total_count": 0, "url": "/v1/charges?payment_intent=pi_1FCpMECRMbs6FrXfVulorSf5" }, "client_secret": "pi_1FCpMECRMbs6FrXfVulorSf5_secret_oSppt5A", "confirmation_method": "manual", "created": 1567091778, "currency": "usd", "customer": "cus_FWhpaTLIPWLhpJ", "description": "Example PaymentIntent", "invoice": null, "last_payment_error": null, "livemode": false, "metadata": null, "next_action": null, "on_behalf_of": null, "payment_method": null, "payment_method_options": { "card": { "request_three_d_secure": "automatic" } }, "payment_method_types": [ "card" ], "receipt_email": null, "review": null, "setup_future_usage": null, "shipping": { "address": { "city": "San Francisco", "country": "US", "line1": "123 Market St", "line2": "#345", "postal_code": "94107", "state": "CA" }, "carrier": null, "name": "Fake Name", "phone": "(555) 555-5555", "tracking_number": null }, "source": null, "statement_descriptor": null, "statement_descriptor_suffix": null, "status": "canceled", "transfer_data": null, "transfer_group": null } """.trimIndent() ) )!! val PAYMENT_INTENT_WITH_CANCELED_3DS1_SOURCE = PARSER.parse( org.json.JSONObject( """ { "id": "pi_1FeqH9CRMbs6FrXfcqqpoC2H", "object": "payment_intent", "amount": 1099, "canceled_at": null, "cancellation_reason": null, "capture_method": "manual", "client_secret": "pi_1FeqH9CRMbs6FrXfcqqpoC2H_secret_DHYkuHTGq", "confirmation_method": "automatic", "created": 1573768491, "currency": "usd", "description": "Example PaymentIntent", "last_payment_error": { "message": "The PaymentMethod on this PaymentIntent was previously used without being attached to a Customer or was detached from a Customer, and may not be used again. You can try confirming again with a new PaymentMethod.", "payment_method": { "id": "pm_1FeqHBCRMbs6FrXfsDE5NFJH", "object": "payment_method", "billing_details": { "address": { "city": null, "country": null, "line1": null, "line2": null, "postal_code": null, "state": null }, "email": null, "name": null, "phone": null }, "card": { "brand": "visa", "checks": { "address_line1_check": null, "address_postal_code_check": null, "cvc_check": null }, "country": "US", "exp_month": 1, "exp_year": 2025, "funding": "credit", "generated_from": null, "last4": "3063", "three_d_secure_usage": { "supported": true }, "wallet": null }, "created": 1573768493, "customer": null, "livemode": false, "metadata": {}, "type": "card" }, "type": "invalid_request_error" }, "livemode": false, "next_action": null, "payment_method": null, "payment_method_types": [ "card" ], "receipt_email": null, "setup_future_usage": null, "shipping": null, "source": null, "status": "requires_payment_method" } """.trimIndent() ) ) val EXPANDED_PAYMENT_METHOD_JSON = org.json.JSONObject( """ { "id": "pi_1GSTxJCRMbs", "object": "payment_intent", "amount": 1099, "canceled_at": null, "cancellation_reason": null, "capture_method": "automatic", "client_secret": "pi_1GSTxJCRMbs_secret_NqmhRfE9f", "confirmation_method": "automatic", "created": 1585599093, "currency": "usd", "description": "Example PaymentIntent", "last_payment_error": null, "livemode": false, "payment_method": { "id": "pm_1GSTxOCRMbs6FrXfYCosDqyr", "object": "payment_method", "billing_details": { "address": { "city": null, "country": null, "line1": null, "line2": null, "postal_code": null, "state": null }, "email": null, "name": null, "phone": null }, "card": { "brand": "visa", "checks": { "address_line1_check": null, "address_postal_code_check": null, "cvc_check": null }, "country": "IE", "exp_month": 1, "exp_year": 2025, "funding": "credit", "generated_from": null, "last4": "3238", "three_d_secure_usage": { "supported": true }, "wallet": null }, "created": 1585599098, "customer": null, "livemode": false, "metadata": {}, "type": "card" }, "payment_method_types": ["card"], "receipt_email": null, "setup_future_usage": null, "shipping": { "address": { "city": "San Francisco", "country": "US", "line1": "123 Market St", "line2": "#345", "postal_code": "94107", "state": "CA" }, "carrier": "Fedex", "name": "Jenny Rosen", "phone": null, "tracking_number": "12345" }, "source": null, "status": "requires_action" } """.trimIndent() ) val PI_WITH_SHIPPING_JSON = org.json.JSONObject( """ { "id": "pi_1GYda2CRMbs", "object": "payment_intent", "amount": 1099, "canceled_at": null, "cancellation_reason": null, "capture_method": "automatic", "client_secret": "pi_1GYda2CRMbs_secret_Z2zduomY0", "confirmation_method": "automatic", "created": 1587066058, "currency": "usd", "description": "Example PaymentIntent", "last_payment_error": null, "livemode": false, "next_action": null, "payment_method": { "id": "pm_1GYda7CRMbs6FrX", "object": "payment_method", "billing_details": { "address": { "city": "San Francisco", "country": "US", "line1": "123 Market St", "line2": "#345", "postal_code": "94107", "state": "CA" }, "email": null, "name": "Jenny Rosen", "phone": null }, "card": { "brand": "visa", "checks": { "address_line1_check": null, "address_postal_code_check": null, "cvc_check": null }, "country": "US", "exp_month": 12, "exp_year": 2025, "funding": "credit", "generated_from": null, "last4": "4242", "three_d_secure_usage": { "supported": true }, "wallet": { "dynamic_last4": "4242", "google_pay": {}, "type": "google_pay" } }, "created": 1587066063, "customer": null, "livemode": false, "metadata": {}, "type": "card" }, "payment_method_types": ["card"], "receipt_email": null, "setup_future_usage": null, "shipping": { "address": { "city": "San Francisco", "country": "US", "line1": "123 Market St", "line2": "#345", "postal_code": "94107", "state": "CA" }, "carrier": "UPS", "name": "Jenny Rosen", "phone": "1-800-555-1234", "tracking_number": "12345" }, "source": null, "status": "succeeded" } """.trimIndent() ) val PI_WITH_SHIPPING = PARSER.parse(PI_WITH_SHIPPING_JSON)!! val PI_OFF_SESSION = PARSER.parse( PI_WITH_SHIPPING_JSON )!!.copy( setupFutureUsage = StripeIntent.Usage.OffSession ) val OXXO_REQUIRES_ACTION_JSON = org.json.JSONObject( """ { "id": "pi_1IcuwoL32KlRo", "object": "payment_intent", "amount": 1099, "canceled_at": null, "cancellation_reason": null, "capture_method": "automatic", "client_secret": "pi_1IcuwoL32KlRo_secret_KC0YoHfna465TDVW", "confirmation_method": "automatic", "created": 1617638802, "currency": "mxn", "description": "Example PaymentIntent", "last_payment_error": null, "livemode": false, "next_action": { "oxxo_display_details": { "expires_after": 1617944399, "hosted_voucher_url": "https:\/\/payments.stripe.com\/oxxo\/voucher\/test_YWNjdF8xSWN1c1VMMzJLbFJvdDAxLF9KRlBtckVBMERWM0lBZEUyb", "number": "12345678901234657890123456789012" }, "type": "oxxo_display_details" }, "payment_method": { "id": "pm_1IcuwoL32KlRot01", "object": "payment_method", "billing_details": { "address": { "city": null, "country": null, "line1": null, "line2": null, "postal_code": null, "state": null }, "email": "[email protected]", "name": "Jenny Rosen", "phone": null }, "created": 1617638802, "customer": null, "livemode": false, "oxxo": {}, "type": "oxxo" }, "payment_method_types": ["card", "oxxo"], "receipt_email": null, "setup_future_usage": null, "shipping": null, "source": null, "status": "requires_action" } """.trimIndent() ) val OXXO_REQUIES_ACTION = requireNotNull(PARSER.parse(OXXO_REQUIRES_ACTION_JSON)) val ALIPAY_REQUIRES_ACTION_JSON = org.json.JSONObject( """ { "id": "pi_1HDEFVKlwPmebFhpCobFP55H", "object": "payment_intent", "amount": 100, "canceled_at": null, "cancellation_reason": null, "capture_method": "automatic", "client_secret": "pi_1HDEFVKlwPmebFhpCobFP55H_secret_XW8sADccCxtusewAwn5z9kAiw", "confirmation_method": "automatic", "created": 1596740133, "currency": "usd", "description": "Example PaymentIntent", "last_payment_error": null, "livemode": true, "next_action": { "alipay_handle_redirect": { "native_data": "_input_charset=utf-8&app_pay=Y&currency=USD&forex_biz=FP&notify_url=https%3A%2F%2Fhooks.stripe.com%2Falipay%2Falipay%2Fhook%2F6255d30b067c8f7a162c79c654483646%2Fsrc_1HDEFWKlwPmebFhp6tcpln8T&out_trade_no=src_1HDEFWKlwPmebFhp6tcpln8T&partner=2088621828244481&payment_type=1&product_code=NEW_WAP_OVERSEAS_SELLER&return_url=https%3A%2F%2Fhooks.stripe.com%2Fadapter%2Falipay%2Fredirect%2Fcomplete%2Fsrc_1HDEFWKlwPmebFhp6tcpln8T%2Fsrc_client_secret_S6H9mVMKK6qxk9YxsUvbH55K&secondary_merchant_id=acct_1EqOyCKlwPmebFhp&secondary_merchant_industry=5734&secondary_merchant_name=Yuki-Test&sendFormat=normal&service=create_forex_trade_wap&sign=b691876a7f0bd889530f54a271d314d5&sign_type=MD5&subject=Yuki-Test&supplier=Yuki-Test&timeout_rule=20m&total_fee=1.00", "native_url": null, "return_url": "example://return_url", "url": "https://hooks.stripe.com/redirect/authenticate/src_1HDEFWKlwPmebFhp6tcpln8T?client_secret=src_client_secret_S6H9mVMKK6qxk9YxsUvbH55K" }, "type": "alipay_handle_redirect" }, "payment_method": { "id": "pm_1HDEFVKlwPmebFhpKYYkSm8H", "object": "payment_method", "alipay": {}, "billing_details": { "address": { "city": null, "country": null, "line1": null, "line2": null, "postal_code": null, "state": null }, "email": null, "name": null, "phone": null }, "created": 1596740133, "customer": null, "livemode": true, "type": "alipay" }, "payment_method_types": [ "alipay" ], "receipt_email": null, "setup_future_usage": null, "shipping": null, "source": null, "status": "requires_action" } """.trimIndent() ) val ALIPAY_REQUIRES_ACTION = PARSER.parse(ALIPAY_REQUIRES_ACTION_JSON)!! val ALIPAY_TEST_MODE_JSON = org.json.JSONObject( """ { "id": "pi_1HDEFVKlwPmebFhpCobFP55H", "object": "payment_intent", "amount": 100, "canceled_at": null, "cancellation_reason": null, "capture_method": "automatic", "client_secret": "pi_1HDEFVKlwPmebFhpCobFP55H_secret_XW8sADccCxtusewAwn5z9kAiw", "confirmation_method": "automatic", "created": 1596740133, "currency": "usd", "description": "Example PaymentIntent", "last_payment_error": null, "livemode": true, "next_action": { "alipay_handle_redirect": { "native_data": null, "native_url": null, "return_url": "example://return_url", "url": "https://hooks.stripe.com/redirect/authenticate/src_1HDEFWKlwPmebFhp6tcpln8T?client_secret=src_client_secret_S6H9mVMKK6qxk9YxsUvbH55K" }, "type": "alipay_handle_redirect" }, "payment_method": { "id": "pm_1HDEFVKlwPmebFhpKYYkSm8H", "object": "payment_method", "alipay": {}, "billing_details": { "address": { "city": null, "country": null, "line1": null, "line2": null, "postal_code": null, "state": null }, "email": null, "name": null, "phone": null }, "created": 1596740133, "customer": null, "livemode": false, "type": "alipay" }, "payment_method_types": [ "alipay" ], "receipt_email": null, "setup_future_usage": null, "shipping": null, "source": null, "status": "requires_action" } """.trimIndent() ) val ALIPAY_TEST_MODE = PARSER.parse(ALIPAY_TEST_MODE_JSON)!! val PI_REQUIRES_BLIK_AUTHORIZE_JSON = org.json.JSONObject( """ { "id": "pi_1IVmwXFY0qyl6XeWwxGWA04D", "object": "payment_intent", "amount": 1099, "amount_capturable": 0, "amount_received": 0, "amount_subtotal": 1099, "application": null, "application_fee_amount": null, "canceled_at": null, "cancellation_reason": null, "capture_method": "automatic", "charges": { "object": "list", "data": [ ], "has_more": false, "total_count": 0, "url": "/v1/charges?payment_intent=pi_1IVmwXFY0qyl6XeWwxGWA04D" }, "client_secret": "pi_1IVmwXFY0qyl6XeWwxGWA04D_secret_4U8cSCdPefr8LHtPsKvA3mcQz", "confirmation_method": "automatic", "created": 1615939737, "currency": "pln", "customer": null, "description": null, "invoice": null, "last_payment_error": null, "livemode": false, "metadata": { }, "next_action": { "type": "blik_authorize" }, "on_behalf_of": null, "payment_method": "pm_1IVnI3FY0qyl6XeWxJFdBh2g", "payment_method_options": { "blik": { } }, "payment_method_types": [ "blik" ], "receipt_email": null, "review": null, "setup_future_usage": null, "shipping": null, "source": null, "statement_descriptor": null, "statement_descriptor_suffix": null, "status": "requires_action", "total_details": { "amount_discount": 0, "amount_tax": 0 }, "transfer_data": null, "transfer_group": null } """.trimIndent() ) val PI_REQUIRES_BLIK_AUTHORIZE = PARSER.parse(PI_REQUIRES_BLIK_AUTHORIZE_JSON)!! private val PI_REQUIRES_WECHAT_PAY_AUTHORIZE_JSON = org.json.JSONObject( """ { "id": "pi_1IlJH7BNJ02ErVOjm37T3OUt", "object": "payment_intent", "amount": 1099, "amount_capturable": 0, "amount_received": 0, "application": null, "application_fee_amount": null, "canceled_at": null, "cancellation_reason": null, "capture_method": "automatic", "charges": { "object": "list", "data": [ ], "has_more": false, "total_count": 0, "url": "/v1/charges?payment_intent=pi_1IlJH7BNJ02ErVOjm37T3OUt" }, "client_secret": "pi_1IlJH7BNJ02ErVOjm37T3OUt_secret_vgMExmjvESdtPqddHOSSSDip2", "confirmation_method": "automatic", "created": 1619638941, "currency": "usd", "customer": null, "description": null, "invoice": null, "last_payment_error": null, "livemode": false, "metadata": { }, "next_action": { "type": "wechat_pay_redirect_to_android_app", "wechat_pay_redirect_to_android_app": { "app_id": "wx65997d6307c3827d", "nonce_str": "some_random_string", "package": "Sign=WXPay", "partner_id": "wx65997d6307c3827d", "prepay_id": "test_transaction", "sign": "8B26124BABC816D7140034DDDC7D3B2F1036CCB2D910E52592687F6A44790D5E", "timestamp": "1619638941" } }, "on_behalf_of": null, "payment_method": "pm_1IlJH7BNJ02ErVOjxKQu1wfH", "payment_method_options": { "wechat_pay": { } }, "payment_method_types": [ "wechat_pay" ], "receipt_email": null, "review": null, "setup_future_usage": null, "shipping": null, "source": null, "statement_descriptor": null, "statement_descriptor_suffix": null, "status": "requires_action", "transfer_data": null, "transfer_group": null } """.trimIndent() ) val PI_REQUIRES_WECHAT_PAY_AUTHORIZE = PARSER.parse(PI_REQUIRES_WECHAT_PAY_AUTHORIZE_JSON)!! }
paymentsheet/src/test/java/com/stripe/android/model/PaymentIntentFixtures.kt
3816099608
package com.stripe.android.financialconnections.example.data.model import com.google.gson.annotations.SerializedName data class CreateLinkAccountSessionResponse( @SerializedName("client_secret") val clientSecret: String, @SerializedName("las_id") val lasId: String, @SerializedName("publishable_key") val publishableKey: String )
financial-connections-example/src/main/java/com/stripe/android/financialconnections/example/data/model/CreateLinkAccountSessionResponse.kt
711647021
/* * Copyright 2019 Peter Kenji Yamanaka * * 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.pyamsoft.padlock.uicommon import android.app.Activity import android.app.PendingIntent import android.content.Context import android.content.Intent import android.provider.Settings import androidx.annotation.CheckResult object UsageAccessRequestDelegate { private const val REQUEST_CODE_USAGE_ACCESS = 123 private val INTENT: Intent = Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS) @JvmStatic fun launchUsageAccessActivity(activity: Activity) { activity.startActivity(INTENT) } @JvmStatic @CheckResult fun pendingIntent(context: Context): PendingIntent { return PendingIntent.getActivity(context, REQUEST_CODE_USAGE_ACCESS, INTENT, 0) } }
padlock/src/main/java/com/pyamsoft/padlock/uicommon/UsageAccessRequestDelegate.kt
1919821286
package expo.modules.kotlin.records import com.facebook.react.bridge.Dynamic import expo.modules.kotlin.allocators.ObjectConstructor import expo.modules.kotlin.allocators.ObjectConstructorFactory import expo.modules.kotlin.exception.FieldCastException import expo.modules.kotlin.exception.RecordCastException import expo.modules.kotlin.exception.exceptionDecorator import expo.modules.kotlin.recycle import expo.modules.kotlin.types.TypeConverter import expo.modules.kotlin.types.TypeConverterProvider import kotlin.reflect.KClass import kotlin.reflect.KType import kotlin.reflect.full.findAnnotation import kotlin.reflect.full.memberProperties import kotlin.reflect.jvm.javaField // TODO(@lukmccall): create all converters during initialization class RecordTypeConverter<T : Record>( private val converterProvider: TypeConverterProvider, val type: KType, ) : TypeConverter<T>(type.isMarkedNullable) { private val objectConstructorFactory = ObjectConstructorFactory() override fun convertNonOptional(value: Dynamic): T = exceptionDecorator({ cause -> RecordCastException(type, cause) }) { val jsMap = value.asMap() val kClass = type.classifier as KClass<*> val instance = getObjectConstructor(kClass.java).construct() kClass .memberProperties .map { property -> val filedInformation = property.findAnnotation<Field>() ?: return@map val jsKey = filedInformation.key.takeUnless { it == "" } ?: property.name if (!jsMap.hasKey(jsKey)) { // TODO(@lukmccall): handle required keys return@map } jsMap.getDynamic(jsKey).recycle { val javaField = property.javaField!! val elementConverter = converterProvider.obtainTypeConverter(property.returnType) val casted = exceptionDecorator({ cause -> FieldCastException(property.name, property.returnType, type, cause) }) { elementConverter.convert(this) } javaField.isAccessible = true javaField.set(instance, casted) } } @Suppress("UNCHECKED_CAST") return instance as T } private fun <T> getObjectConstructor(clazz: Class<T>): ObjectConstructor<T> { return objectConstructorFactory.get(clazz) } }
packages/expo-modules-core/android/src/main/java/expo/modules/kotlin/records/RecordTypeConverter.kt
122023286
/* * Copyright (c) 2020 Vimeo (https://vimeo.com) * * 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 com.vimeo.networking2.account import com.vimeo.networking2.VimeoAccount /** * An [AccountStore] that caches the stored account for fast retrieval and delegates actual storage to another * [AccountStore]. * * @param actualAccountStore The store which will be used to persist the account outside the lifecycle of this * in-memory cache. */ class CachingAccountStore(private val actualAccountStore: AccountStore) : AccountStore { private var vimeoAccount: VimeoAccount? = null override fun loadAccount(): VimeoAccount? { return vimeoAccount ?: actualAccountStore.loadAccount().also { vimeoAccount = it } } override fun storeAccount(vimeoAccount: VimeoAccount) { this.vimeoAccount = vimeoAccount actualAccountStore.storeAccount(vimeoAccount) } override fun removeAccount() { vimeoAccount = null actualAccountStore.removeAccount() } }
api-core/src/main/java/com/vimeo/networking2/account/CachingAccountStore.kt
1606928186
/* * This file is part of MythicDrops, licensed under the MIT License. * * Copyright (C) 2019 Richard Harrah * * 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 com.tealcube.minecraft.bukkit.mythicdrops.api.weight interface IdentityWeighted { val identityWeight: Double }
src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/api/weight/IdentityWeighted.kt
3903183475
package com.xenoage.zong.core.music.annotation import com.xenoage.zong.core.music.format.Positioning /** * A fermata. */ class Fermata : Annotation { /** The positioning of the fermata, or null (default position) */ var positioning: Positioning? = null }
core/src/com/xenoage/zong/core/music/annotation/Fermata.kt
3504664301
package com.github.kittinunf.fuel.core import com.github.kittinunf.fuel.core.requests.DefaultBody import com.github.kittinunf.fuel.test.MockHttpTestCase import com.github.kittinunf.fuel.util.decodeBase64 import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.Test import org.mockserver.model.BinaryBody import java.io.ByteArrayInputStream import java.net.URLConnection import java.util.Random class BodyRepresentationTest : MockHttpTestCase() { private val manager: FuelManager by lazy { FuelManager() } @Test fun emptyBodyRepresentation() { assertThat( DefaultBody.from({ ByteArrayInputStream(ByteArray(0)) }, { 0L }).asString("(unknown)"), equalTo("(empty)") ) } @Test fun unknownBytesRepresentation() { val bytes = ByteArray(555 - 16) .also { Random().nextBytes(it) } .let { ByteArray(16).plus(it) } mock.chain( request = mock.request().withMethod(Method.GET.value).withPath("/bytes"), response = mock.response().withBody(BinaryBody(bytes, null)).withHeader("Content-Type", "") ) val (_, response, _) = manager.request(Method.GET, mock.path("bytes")).responseString() assertThat( response.body().asString(response[Headers.CONTENT_TYPE].lastOrNull()), equalTo("(555 bytes of (unknown))") ) } @Test fun guessContentType() { val decodedImage = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVQYV2NgYAAAAAMAAWgmWQ0AAAAASUVORK5CYII=".decodeBase64()!! assertThat( DefaultBody .from({ ByteArrayInputStream(decodedImage) }, { decodedImage.size.toLong() }) .asString(URLConnection.guessContentTypeFromStream(ByteArrayInputStream(decodedImage))), equalTo("(${decodedImage.size} bytes of image/png)") ) } @Test fun bytesRepresentationOfOctetStream() { val contentTypes = listOf("application/octet-stream") val content = ByteArray(555 - 16) .also { Random().nextBytes(it) } .let { ByteArray(16).plus(it) } contentTypes.forEach { contentType -> assertThat( DefaultBody .from({ ByteArrayInputStream(content) }, { content.size.toLong() }) .asString(contentType), equalTo("(555 bytes of $contentType)") ) } } @Test fun bytesRepresentationOfMedia() { val contentTypes = listOf( "image/bmp", "image/gif", "image/jpeg", "image/png", "image/tiff", "image/webp", "image/x-icon", "audio/aac", "audio/midi", "audio/x-midi", "audio/ogg", "audio/wav", "audio/webm", "audio/3gpp", "audio/3gpp2", "video/mpeg", "video/ogg", "video/webm", "video/x-msvideo", "video/3gpp", "video/3gpp2", "font/otf", "font/ttf", "font/woff", "font/woff2" ) val content = ByteArray(555 - 16) .also { Random().nextBytes(it) } .let { ByteArray(16).plus(it) } contentTypes.forEach { contentType -> assertThat( DefaultBody .from({ ByteArrayInputStream(content) }, { content.size.toLong() }) .asString(contentType), equalTo("(555 bytes of $contentType)") ) } } @Test fun textRepresentationOfYaml() { val contentTypes = listOf("application/x-yaml", "text/yaml") val content = "language: c\n" contentTypes.forEach { contentType -> assertThat( DefaultBody .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() }) .asString(contentType), equalTo(content) ) } } @Test fun textRepresentationOfXml() { val contentTypes = listOf("application/xml", "application/xhtml+xml", "application/vnd.fuel.test+xml", "image/svg+xml") val content = "<html xmlns=\"http://www.w3.org/1999/xhtml\"/>" contentTypes.forEach { contentType -> assertThat( DefaultBody .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() }) .asString(contentType), equalTo(content) ) } } @Test fun textRepresentationOfScripts() { val contentTypes = listOf("application/javascript", "application/typescript", "application/vnd.coffeescript") val content = "function test()" contentTypes.forEach { contentType -> assertThat( DefaultBody .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() }) .asString(contentType), equalTo(content) ) } } @Test fun textRepresentationOfJson() { val contentTypes = listOf("application/json") val content = "{ \"foo\": 42 }" contentTypes.forEach { contentType -> assertThat( DefaultBody .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() }) .asString(contentType), equalTo(content) ) } } @Test fun textRepresentationOfJsonWithUtf8Charset() { val contentTypes = listOf("application/json;charset=utf-8", "application/json; charset=utf-8") val content = "{ \"foo\": 42 }" contentTypes.forEach { contentType -> assertThat( DefaultBody .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() }) .asString(contentType), equalTo(content) ) } } @Test fun textRepresentationOfCsv() { val contentTypes = listOf("text/csv") val content = "function test()" contentTypes.forEach { contentType -> assertThat( DefaultBody .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() }) .asString(contentType), equalTo(content) ) } } @Test fun textRepresentationOfCsvWithUtf16beCharset() { val contentTypes = listOf("application/csv; charset=utf-16be", "application/csv;charset=utf-16be") val content = String("hello,world!".toByteArray(Charsets.UTF_16BE)) contentTypes.forEach { contentType -> assertThat( DefaultBody .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() }) .asString(contentType), equalTo("hello,world!") ) } } @Test fun textRepresentationOfTextTypes() { val contentTypes = listOf("text/csv", "text/html", "text/calendar", "text/plain", "text/css") val content = "maybe invalid but we don't care" contentTypes.forEach { contentType -> assertThat( DefaultBody .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() }) .asString(contentType), equalTo(content) ) } } }
fuel/src/test/kotlin/com/github/kittinunf/fuel/core/BodyRepresentationTest.kt
1018380939
package org.moire.ultrasonic.di import androidx.room.Room import org.koin.android.ext.koin.androidContext import org.koin.android.viewmodel.dsl.viewModel import org.koin.core.qualifier.named import org.koin.dsl.module import org.moire.ultrasonic.activity.ServerSettingsModel import org.moire.ultrasonic.data.ActiveServerProvider import org.moire.ultrasonic.data.AppDatabase import org.moire.ultrasonic.data.MIGRATION_1_2 import org.moire.ultrasonic.util.Util const val SP_NAME = "Default_SP" val appPermanentStorage = module { single(named(SP_NAME)) { Util.getPreferences(androidContext()) } single { Room.databaseBuilder( androidContext(), AppDatabase::class.java, "ultrasonic-database" ) .addMigrations(MIGRATION_1_2) .fallbackToDestructiveMigrationOnDowngrade() .build() } single { get<AppDatabase>().serverSettingDao() } viewModel { ServerSettingsModel(get(), get(), androidContext()) } single { ActiveServerProvider(get(), androidContext()) } }
ultrasonic/src/main/kotlin/org/moire/ultrasonic/di/AppPermanentStorageModule.kt
937791977
package com.kamer.orny.utils import android.content.Context fun Context.installStetho() {}
app/src/release/kotlin/com/kamer/orny/utils/LibrariesExt.kt
4255513707
/* * 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.animation.demos.layoutanimation import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.EnterExitState import androidx.compose.animation.ExitTransition import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.animation.core.MutableTransitionState import androidx.compose.animation.core.Spring import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.spring import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.slideInVertically import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Button import androidx.compose.material.FloatingActionButton import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Favorite import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp /* * This demo shows how to create a custom enter/exit animation for children of AnimatedVisibility * using `AnimatedVisibilityScope.transition` combined with different `Enter/ExitTransition` * for children of `AnimatedVisibility` using `Modifier.animateEnterExit`. * * APIs used: * - MutableTransitionState * - EnterExitState * - AnimatedVisibility * - AnimatedVisibilityScope * - Modifier.animateEnterExit */ @Preview @OptIn(ExperimentalAnimationApi::class) @Composable fun AnimateEnterExitDemo() { Box { Column(Modifier.fillMaxSize()) { Spacer(Modifier.size(40.dp)) val mainContentVisible = remember { MutableTransitionState(true) } Button( modifier = Modifier.align(Alignment.CenterHorizontally), onClick = { mainContentVisible.targetState = !mainContentVisible.targetState }, ) { Text("Toggle Visibility") } Spacer(Modifier.size(40.dp)) AnimatedVisibility( visibleState = mainContentVisible, modifier = Modifier.fillMaxSize(), enter = fadeIn(), exit = fadeOut() ) { Box { Column(Modifier.fillMaxSize()) { colors.forEachIndexed { index, color -> // Creates a custom enter/exit animation on scale using // `AnimatedVisibilityScope.transition` val scale by transition.animateFloat { enterExitState -> when (enterExitState) { EnterExitState.PreEnter -> 0.9f EnterExitState.Visible -> 1.0f EnterExitState.PostExit -> 0.5f } } val staggeredSpring = remember { spring<IntOffset>( stiffness = Spring.StiffnessLow * (1f - index * 0.2f) ) } Box( Modifier.weight(1f).animateEnterExit( // Staggered slide-in from bottom, while the parent // AnimatedVisibility fades in everything (including this child) enter = slideInVertically( initialOffsetY = { it }, animationSpec = staggeredSpring ), // No built-in exit transition will be applied. It'll be // faded out by parent AnimatedVisibility while scaling down // by the scale animation. exit = ExitTransition.None ).fillMaxWidth().padding(5.dp).graphicsLayer { scaleX = scale scaleY = scale }.clip(RoundedCornerShape(20.dp)).background(color) ) {} } } // This gets faded in/out by the parent AnimatedVisibility FloatingActionButton( onClick = {}, modifier = Modifier.align(Alignment.BottomEnd).padding(20.dp), backgroundColor = MaterialTheme.colors.primary ) { Icon(Icons.Default.Favorite, contentDescription = null) } } } } } } private val colors = listOf( Color(0xffff6f69), Color(0xffffcc5c), Color(0xff2a9d84), Color(0xff264653) )
compose/animation/animation/integration-tests/animation-demos/src/main/java/androidx/compose/animation/demos/layoutanimation/AnimateEnterExitDemo.kt
581198576
/* * 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.wear.watchface.complications.data import android.content.ComponentName import android.content.Context import android.graphics.Color import android.graphics.drawable.Icon import android.support.wearable.complications.ComplicationData import android.support.wearable.complications.ComplicationData.Companion.IMAGE_STYLE_ICON import androidx.test.core.app.ApplicationProvider import com.google.common.truth.Truth.assertThat import java.time.Instant import org.junit.Test import org.junit.runner.RunWith @RunWith(SharedRobolectricTestRunner::class) @Suppress("NewApi") class PlaceholderTest { val text = "text".complicationText val title = "title".complicationText val contentDescription = "description".complicationText val icon = Icon.createWithContentUri("someuri") val monochromaticImage = MonochromaticImage.Builder(icon).build() val smallImage = SmallImage.Builder(icon, SmallImageType.ICON).build() val resources = ApplicationProvider.getApplicationContext<Context>().resources @Test fun placeholder_shortText() { val placeholderShortText = NoDataComplicationData( ShortTextComplicationData.Builder(ComplicationText.PLACEHOLDER, contentDescription) .setTitle(ComplicationText.PLACEHOLDER) .setMonochromaticImage(MonochromaticImage.PLACEHOLDER) .setSmallImage(SmallImage.PLACEHOLDER) .build() ).toWireFormatRoundTrip().placeholder as ShortTextComplicationData assertThat(placeholderShortText.text).isEqualTo(ComplicationText.PLACEHOLDER) assertThat(placeholderShortText.title).isEqualTo(ComplicationText.PLACEHOLDER) assertThat(placeholderShortText.monochromaticImage) .isEqualTo(MonochromaticImage.PLACEHOLDER) assertThat(placeholderShortText.smallImage).isEqualTo(SmallImage.PLACEHOLDER) assertThat(placeholderShortText.contentDescription!!.getTextAt(resources, Instant.EPOCH)) .isEqualTo("description") assertThat(placeholderShortText.hasPlaceholderFields()).isTrue() } @Test fun normal_shortText() { val placeholderShortText = NoDataComplicationData( ShortTextComplicationData.Builder(text, contentDescription) .setTitle(title) .setMonochromaticImage(monochromaticImage) .setSmallImage(smallImage) .build() ).toWireFormatRoundTrip().placeholder as ShortTextComplicationData assertThat(placeholderShortText.text.getTextAt(resources, Instant.EPOCH)).isEqualTo( text.getTextAt(resources, Instant.EPOCH) ) assertThat(placeholderShortText.title!!.getTextAt(resources, Instant.EPOCH)).isEqualTo( title.getTextAt(resources, Instant.EPOCH) ) assertThat(placeholderShortText.monochromaticImage).isEqualTo(monochromaticImage) assertThat(placeholderShortText.smallImage).isEqualTo(smallImage) assertThat(placeholderShortText.hasPlaceholderFields()).isFalse() } @Test fun absent_shortText() { val placeholderShortText = NoDataComplicationData( ShortTextComplicationData.Builder(ComplicationText.PLACEHOLDER, contentDescription) .build() ).toWireFormatRoundTrip().placeholder as ShortTextComplicationData assertThat(placeholderShortText.title).isNull() assertThat(placeholderShortText.monochromaticImage).isNull() assertThat(placeholderShortText.smallImage).isNull() } @Test fun placeholder_longText() { val placeholderLongText = NoDataComplicationData( LongTextComplicationData.Builder(ComplicationText.PLACEHOLDER, contentDescription) .setTitle(ComplicationText.PLACEHOLDER) .setMonochromaticImage(MonochromaticImage.PLACEHOLDER) .setSmallImage(SmallImage.PLACEHOLDER) .build() ).toWireFormatRoundTrip().placeholder as LongTextComplicationData assertThat(placeholderLongText.text).isEqualTo(ComplicationText.PLACEHOLDER) assertThat(placeholderLongText.title).isEqualTo(ComplicationText.PLACEHOLDER) assertThat(placeholderLongText.monochromaticImage) .isEqualTo(MonochromaticImage.PLACEHOLDER) assertThat(placeholderLongText.smallImage).isEqualTo(SmallImage.PLACEHOLDER) assertThat(placeholderLongText.contentDescription!!.getTextAt(resources, Instant.EPOCH)) .isEqualTo("description") assertThat(placeholderLongText.hasPlaceholderFields()).isTrue() } @Test fun normal_longText() { val placeholderLongText = NoDataComplicationData( LongTextComplicationData.Builder(text, contentDescription) .setTitle(title) .setMonochromaticImage(monochromaticImage) .setSmallImage(smallImage) .build() ).toWireFormatRoundTrip().placeholder as LongTextComplicationData assertThat(placeholderLongText.text.getTextAt(resources, Instant.EPOCH)).isEqualTo( text.getTextAt(resources, Instant.EPOCH) ) assertThat(placeholderLongText.title!!.getTextAt(resources, Instant.EPOCH)).isEqualTo( title.getTextAt(resources, Instant.EPOCH) ) assertThat(placeholderLongText.monochromaticImage).isEqualTo(monochromaticImage) assertThat(placeholderLongText.smallImage).isEqualTo(smallImage) assertThat(placeholderLongText.hasPlaceholderFields()).isFalse() } @Test fun absent_longText() { val placeholderLongText = NoDataComplicationData( LongTextComplicationData.Builder(ComplicationText.PLACEHOLDER, contentDescription) .build() ).toWireFormatRoundTrip().placeholder as LongTextComplicationData assertThat(placeholderLongText.title).isNull() assertThat(placeholderLongText.monochromaticImage).isNull() assertThat(placeholderLongText.smallImage).isNull() } @Test fun placeholder_rangedValue() { val placeholderRangedValue = NoDataComplicationData( RangedValueComplicationData.Builder( value = RangedValueComplicationData.PLACEHOLDER, min = 1f, max = 10f, contentDescription ) .setText(ComplicationText.PLACEHOLDER) .setTitle(ComplicationText.PLACEHOLDER) .setMonochromaticImage(MonochromaticImage.PLACEHOLDER) .setSmallImage(SmallImage.PLACEHOLDER) .build() ).toWireFormatRoundTrip().placeholder as RangedValueComplicationData assertThat(placeholderRangedValue.value).isEqualTo(RangedValueComplicationData.PLACEHOLDER) assertThat(placeholderRangedValue.text).isEqualTo(ComplicationText.PLACEHOLDER) assertThat(placeholderRangedValue.title).isEqualTo(ComplicationText.PLACEHOLDER) assertThat(placeholderRangedValue.monochromaticImage) .isEqualTo(MonochromaticImage.PLACEHOLDER) assertThat(placeholderRangedValue.smallImage).isEqualTo(SmallImage.PLACEHOLDER) assertThat(placeholderRangedValue.contentDescription!!.getTextAt(resources, Instant.EPOCH)) .isEqualTo("description") assertThat(placeholderRangedValue.hasPlaceholderFields()).isTrue() } @Test fun normal_rangedValue() { val placeholderRangedValue = NoDataComplicationData( RangedValueComplicationData.Builder(value = 7f, min = 1f, max = 10f, contentDescription) .setText(text) .setTitle(title) .setMonochromaticImage(monochromaticImage) .setSmallImage(smallImage) .build() ).toWireFormatRoundTrip().placeholder as RangedValueComplicationData assertThat(placeholderRangedValue.text!!.getTextAt(resources, Instant.EPOCH)).isEqualTo( text.getTextAt(resources, Instant.EPOCH) ) assertThat(placeholderRangedValue.title!!.getTextAt(resources, Instant.EPOCH)).isEqualTo( title.getTextAt(resources, Instant.EPOCH) ) assertThat(placeholderRangedValue.monochromaticImage).isEqualTo(monochromaticImage) assertThat(placeholderRangedValue.smallImage).isEqualTo(smallImage) assertThat(placeholderRangedValue.value).isEqualTo(7f) assertThat(placeholderRangedValue.min).isEqualTo(1f) assertThat(placeholderRangedValue.max).isEqualTo(10f) assertThat(placeholderRangedValue.hasPlaceholderFields()).isFalse() } @Test fun titleAbsent_rangedValue() { val placeholderRangedValue = NoDataComplicationData( RangedValueComplicationData.Builder( value = RangedValueComplicationData.PLACEHOLDER, min = 1f, max = 10f, contentDescription ) .setText(ComplicationText.PLACEHOLDER) .build() ).toWireFormatRoundTrip().placeholder as RangedValueComplicationData assertThat(placeholderRangedValue.text).isEqualTo(ComplicationText.PLACEHOLDER) assertThat(placeholderRangedValue.title).isNull() assertThat(placeholderRangedValue.monochromaticImage).isNull() assertThat(placeholderRangedValue.smallImage).isNull() } @OptIn(ComplicationExperimental::class) @Test fun placeholder_goalProgress() { val placeholderGoalProgress = NoDataComplicationData( GoalProgressComplicationData.Builder( value = GoalProgressComplicationData.PLACEHOLDER, targetValue = 10000f, contentDescription ) .setText(ComplicationText.PLACEHOLDER) .setTitle(ComplicationText.PLACEHOLDER) .setMonochromaticImage(MonochromaticImage.PLACEHOLDER) .setSmallImage(SmallImage.PLACEHOLDER) .build() ).toWireFormatRoundTrip().placeholder as GoalProgressComplicationData assertThat(placeholderGoalProgress.value).isEqualTo(RangedValueComplicationData.PLACEHOLDER) assertThat(placeholderGoalProgress.text).isEqualTo(ComplicationText.PLACEHOLDER) assertThat(placeholderGoalProgress.title).isEqualTo(ComplicationText.PLACEHOLDER) assertThat(placeholderGoalProgress.monochromaticImage) .isEqualTo(MonochromaticImage.PLACEHOLDER) assertThat(placeholderGoalProgress.smallImage).isEqualTo(SmallImage.PLACEHOLDER) assertThat(placeholderGoalProgress.contentDescription!!.getTextAt(resources, Instant.EPOCH)) .isEqualTo("description") assertThat(placeholderGoalProgress.hasPlaceholderFields()).isTrue() } @OptIn(ComplicationExperimental::class) @Test fun normal_goalProgress() { val placeholderGoalProgress = NoDataComplicationData( GoalProgressComplicationData.Builder( value = 1200f, targetValue = 10000f, contentDescription ) .setText(text) .setTitle(title) .setMonochromaticImage(monochromaticImage) .setSmallImage(smallImage) .build() ).toWireFormatRoundTrip().placeholder as GoalProgressComplicationData assertThat(placeholderGoalProgress.text!!.getTextAt(resources, Instant.EPOCH)).isEqualTo( text.getTextAt(resources, Instant.EPOCH) ) assertThat(placeholderGoalProgress.title!!.getTextAt(resources, Instant.EPOCH)).isEqualTo( title.getTextAt(resources, Instant.EPOCH) ) assertThat(placeholderGoalProgress.monochromaticImage).isEqualTo(monochromaticImage) assertThat(placeholderGoalProgress.smallImage).isEqualTo(smallImage) assertThat(placeholderGoalProgress.value).isEqualTo(1200f) assertThat(placeholderGoalProgress.targetValue).isEqualTo(10000f) assertThat(placeholderGoalProgress.hasPlaceholderFields()).isFalse() } @OptIn(ComplicationExperimental::class) @Test fun placeholder_weightedElements() { val placeholderWeightedElements = NoDataComplicationData( WeightedElementsComplicationData.Builder( elements = WeightedElementsComplicationData.PLACEHOLDER, contentDescription ) .setText(ComplicationText.PLACEHOLDER) .setTitle(ComplicationText.PLACEHOLDER) .setMonochromaticImage(MonochromaticImage.PLACEHOLDER) .setSmallImage(SmallImage.PLACEHOLDER) .build() ).toWireFormatRoundTrip().placeholder as WeightedElementsComplicationData assertThat(placeholderWeightedElements.elements) .isEqualTo(WeightedElementsComplicationData.PLACEHOLDER) assertThat(placeholderWeightedElements.text).isEqualTo(ComplicationText.PLACEHOLDER) assertThat(placeholderWeightedElements.title).isEqualTo(ComplicationText.PLACEHOLDER) assertThat(placeholderWeightedElements.monochromaticImage) .isEqualTo(MonochromaticImage.PLACEHOLDER) assertThat(placeholderWeightedElements.smallImage).isEqualTo(SmallImage.PLACEHOLDER) assertThat(placeholderWeightedElements.contentDescription!! .getTextAt(resources, Instant.EPOCH)).isEqualTo("description") assertThat(placeholderWeightedElements.hasPlaceholderFields()).isTrue() } @OptIn(ComplicationExperimental::class) @Test fun normal_weightedElements() { val weightedElements = NoDataComplicationData( WeightedElementsComplicationData.Builder( elements = listOf( WeightedElementsComplicationData.Element(0.5f, Color.RED), WeightedElementsComplicationData.Element(1f, Color.GREEN), WeightedElementsComplicationData.Element(2f, Color.BLUE), ), contentDescription ) .setText(text) .setTitle(title) .setMonochromaticImage(monochromaticImage) .setSmallImage(smallImage) .build() ).toWireFormatRoundTrip().placeholder as WeightedElementsComplicationData assertThat(weightedElements.elements).isEqualTo( listOf( WeightedElementsComplicationData.Element(0.5f, Color.RED), WeightedElementsComplicationData.Element(1f, Color.GREEN), WeightedElementsComplicationData.Element(2f, Color.BLUE), ) ) assertThat(weightedElements.text).isEqualTo(text) assertThat(weightedElements.title).isEqualTo(title) assertThat(weightedElements.monochromaticImage).isEqualTo(monochromaticImage) assertThat(weightedElements.smallImage).isEqualTo(smallImage) assertThat(weightedElements.contentDescription!!.getTextAt(resources, Instant.EPOCH)) .isEqualTo("description") assertThat(weightedElements.hasPlaceholderFields()).isFalse() } @Test fun placeholder_monochromaticImage() { val placeholderMonochromaticImage = NoDataComplicationData( MonochromaticImageComplicationData.Builder( MonochromaticImage.PLACEHOLDER, contentDescription ).build() ).toWireFormatRoundTrip().placeholder as MonochromaticImageComplicationData assertThat(placeholderMonochromaticImage.monochromaticImage) .isEqualTo(MonochromaticImage.PLACEHOLDER) assertThat( placeholderMonochromaticImage.contentDescription!!.getTextAt(resources, Instant.EPOCH) ).isEqualTo("description") assertThat(placeholderMonochromaticImage.hasPlaceholderFields()).isTrue() } @Test fun normal_monochromaticImage() { val placeholderMonochromaticImage = NoDataComplicationData( MonochromaticImageComplicationData.Builder( monochromaticImage, contentDescription ).build() ).toWireFormatRoundTrip().placeholder as MonochromaticImageComplicationData assertThat(placeholderMonochromaticImage.monochromaticImage).isEqualTo(monochromaticImage) assertThat(placeholderMonochromaticImage.hasPlaceholderFields()).isFalse() } @Test fun placeholder_smallImage() { val placeholderSmallImage = NoDataComplicationData( SmallImageComplicationData.Builder(SmallImage.PLACEHOLDER, contentDescription).build() ).toWireFormatRoundTrip().placeholder as SmallImageComplicationData assertThat(placeholderSmallImage.smallImage).isEqualTo(SmallImage.PLACEHOLDER) assertThat(placeholderSmallImage.contentDescription!!.getTextAt(resources, Instant.EPOCH)) .isEqualTo("description") assertThat(placeholderSmallImage.hasPlaceholderFields()).isTrue() } @Test fun normal_smallImage() { val placeholderSmallImage = NoDataComplicationData( SmallImageComplicationData.Builder(smallImage, contentDescription).build() ).toWireFormatRoundTrip().placeholder as SmallImageComplicationData assertThat(placeholderSmallImage.smallImage).isEqualTo(smallImage) assertThat(placeholderSmallImage.hasPlaceholderFields()).isFalse() } @Test fun placeholder_photoImage() { val placeholderPhotoImage = NoDataComplicationData( PhotoImageComplicationData.Builder( PhotoImageComplicationData.PLACEHOLDER, contentDescription ).build() ).toWireFormatRoundTrip().placeholder as PhotoImageComplicationData assertThat(placeholderPhotoImage.photoImage) .isEqualTo(PhotoImageComplicationData.PLACEHOLDER) assertThat(placeholderPhotoImage.contentDescription!!.getTextAt(resources, Instant.EPOCH)) .isEqualTo("description") assertThat(placeholderPhotoImage.hasPlaceholderFields()).isTrue() } @Test fun normal_photoImage() { val placeholderPhotoImage = NoDataComplicationData( PhotoImageComplicationData.Builder(icon, contentDescription).build() ).toWireFormatRoundTrip().placeholder as PhotoImageComplicationData assertThat(placeholderPhotoImage.photoImage).isEqualTo(icon) assertThat(placeholderPhotoImage.hasPlaceholderFields()).isFalse() } @Test fun wireLongTextWithPlaceholder_toApi() { val timelineEntry = ComplicationData.Builder(ComplicationData.TYPE_NO_DATA) .setPlaceholder( ComplicationData.Builder(ComplicationData.TYPE_LONG_TEXT) .setLongText(ComplicationText.PLACEHOLDER.toWireComplicationText()) .build() ) .build() timelineEntry.timelineStartEpochSecond = 100 timelineEntry.timelineEndEpochSecond = 1000 val wireLongTextComplication = WireComplicationDataBuilder( ComplicationType.LONG_TEXT.toWireComplicationType() ) .setEndDateTimeMillis(1650988800000) .setDataSource(ComponentName("a", "b")) .setLongText( android.support.wearable.complications.ComplicationText.plainText("longText") ) .setIcon(icon) .setSmallImageStyle(IMAGE_STYLE_ICON) .setContentDescription( android.support.wearable.complications.ComplicationText.plainText("test") ) .build() wireLongTextComplication.setTimelineEntryCollection(listOf(timelineEntry)) val apiLongTextComplicationData = wireLongTextComplication.toApiComplicationData() assertThat(apiLongTextComplicationData.type).isEqualTo(ComplicationType.LONG_TEXT) apiLongTextComplicationData as LongTextComplicationData assertThat(apiLongTextComplicationData.text.isPlaceholder()).isFalse() val noDataComplicationData = apiLongTextComplicationData.asWireComplicationData().timelineEntries!!.first() .toApiComplicationData() assertThat(noDataComplicationData.type).isEqualTo(ComplicationType.NO_DATA) noDataComplicationData as NoDataComplicationData val placeholder = noDataComplicationData.placeholder!! assertThat(placeholder.type).isEqualTo(ComplicationType.LONG_TEXT) placeholder as LongTextComplicationData assertThat(placeholder.text.isPlaceholder()).isTrue() } } fun NoDataComplicationData.toWireFormatRoundTrip() = asWireComplicationData().toApiComplicationData() as NoDataComplicationData
wear/watchface/watchface-complications-data/src/test/java/androidx/wear/watchface/complications/data/PlaceholderTest.kt
2521354003
package com.wealthfront.magellan.sample.migration.tide import android.content.Context import android.graphics.drawable.Drawable import android.os.Looper.getMainLooper import androidx.test.core.app.ApplicationProvider import com.bumptech.glide.RequestBuilder import com.bumptech.glide.RequestManager import com.wealthfront.magellan.sample.migration.TestSampleApplication import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.ArgumentMatchers.anyString import org.mockito.Mock import org.mockito.Mockito.verify import org.mockito.Mockito.`when` import org.mockito.MockitoAnnotations.initMocks import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows.shadowOf import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(application = TestSampleApplication::class) class HelpViewTest { @Mock lateinit var screen: HelpScreen @Mock lateinit var glideRequest: RequestManager @Mock lateinit var drawableRequest: RequestBuilder<Drawable> private lateinit var helpView: HelpView private lateinit var context: Context @Before fun setup() { initMocks(this) context = ApplicationProvider.getApplicationContext() helpView = HelpView(context, screen).apply { glideBuilder = glideRequest } `when`(glideRequest.load(anyString())).thenReturn(drawableRequest) } @Test fun fetchesDogPicOnShow() { helpView.setDogPic("https://dailybeagle.com/latest-picture") shadowOf(getMainLooper()).idle() verify(drawableRequest).into(helpView.binding.dogImage) } }
magellan-sample-migration/src/test/java/com/wealthfront/magellan/sample/migration/tide/HelpViewTest.kt
3850500157
/* * 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.lua.psi import com.intellij.ide.plugins.PluginManagerCore import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.project.Project import com.intellij.openapi.roots.FileIndexFacade import com.intellij.openapi.util.Key import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.util.SmartList import com.tang.intellij.lua.ext.ILuaFileResolver import com.tang.intellij.lua.project.LuaSourceRootManager import java.io.File /** * * Created by tangzx on 2017/1/4. */ object LuaFileUtil { val pluginFolder: File? get() { val descriptor = PluginManagerCore.getPlugin(PluginId.getId("com.tang")) return descriptor?.path } val pluginVirtualDirectory: VirtualFile? get() { val descriptor = PluginManagerCore.getPlugin(PluginId.getId("com.tang")) if (descriptor != null) { val pluginPath = descriptor.path val url = VfsUtil.pathToUrl(pluginPath.absolutePath) return VirtualFileManager.getInstance().findFileByUrl(url) } return null } var PREDEFINED_KEY = Key.create<Boolean>("lua.lib.predefined") fun fileEquals(f1: VirtualFile?, f2: VirtualFile?): Boolean { return if (f1 == null || f2 == null) false else f1.path == f2.path } fun getAllAvailablePathsForMob(shortPath: String?, file: VirtualFile): List<String> { val list = SmartList<String>() val fullPath = file.canonicalPath val extensions = LuaFileManager.getInstance().extensions if (fullPath != null) { for (ext in extensions) { if (!fullPath.endsWith(ext)) { continue } list.add(fullPath.substring(0, fullPath.length - ext.length)) } } if (shortPath != null) { for (ext in extensions) { if (!shortPath.endsWith(ext)) { continue } val path = shortPath.substring(0, shortPath.length - ext.length) list.add(path) if (path.indexOf('/') != -1) list.add(path.replace('/', '.')) } } return list } fun findFile(project: Project, shortUrl: String?): VirtualFile? { var fixedShortUrl = shortUrl ?: return null // "./x.lua" => "x.lua" if (fixedShortUrl.startsWith("./") || fixedShortUrl.startsWith(".\\")) { fixedShortUrl = fixedShortUrl.substring(2) } val extensions = LuaFileManager.getInstance().extensions return ILuaFileResolver.findLuaFile(project, fixedShortUrl, extensions) } fun getShortPath(project: Project, file: VirtualFile): String { return VfsUtil.urlToPath(getShortUrl(project, file)) } private fun getShortUrl(project: Project, file: VirtualFile): String { val fileFullUrl = file.url var fileShortUrl = fileFullUrl val roots = LuaSourceRootManager.getInstance(project).getSourceRoots() for (root in roots) { val sourceRootUrl = root.url if (fileFullUrl.startsWith(sourceRootUrl)) { fileShortUrl = fileFullUrl.substring(sourceRootUrl.length + 1) break } } return fileShortUrl } private fun getSourceRoot(project: Project, file: VirtualFile): VirtualFile? { val fileFullUrl = file.url val roots = LuaSourceRootManager.getInstance(project).getSourceRoots() for (root in roots) { val sourceRootUrl = root.url if (fileFullUrl.startsWith(sourceRootUrl)) { return root } } return null } fun getPluginVirtualFile(path: String): String? { val directory = pluginVirtualDirectory if (directory != null) { var fullPath = directory.path + "/classes/" + path if (File(fullPath).exists()) return fullPath fullPath = directory.path + "/" + path if (File(fullPath).exists()) return fullPath } return null } fun asRequirePath(project: Project, file: VirtualFile): String? { val root = getSourceRoot(project, file) ?: return null val list = mutableListOf<String>() var item = file while (item != root) { if (item.isDirectory) list.add(item.name) else list.add(FileUtil.getNameWithoutExtension(item.name)) item = item.parent } if (list.isEmpty()) return null list.reverse() return list.joinToString(".") } fun isStdLibFile(file: VirtualFile, project: Project): Boolean { return file.getUserData(PREDEFINED_KEY) != null || FileIndexFacade.getInstance(project).isInLibraryClasses(file) } }
src/main/java/com/tang/intellij/lua/psi/LuaFileUtil.kt
829764131
package csense.android.exampleApp.fragments import android.graphics.* import android.support.v7.widget.* import android.view.* import com.commonsense.android.kotlin.system.logging.* import com.commonsense.android.kotlin.views.* import com.commonsense.android.kotlin.views.databinding.adapters.* import com.commonsense.android.kotlin.views.databinding.fragments.* import com.commonsense.android.kotlin.views.extensions.* import com.commonsense.android.kotlin.views.features.* import com.commonsense.android.kotlin.views.features.SectionRecyclerTransaction.* import csense.android.exampleApp.R import csense.android.exampleApp.databinding.* /** * Created by Kasper Tvede on 31-05-2017. */ open class SimpleRecyclerDemo : BaseDatabindingFragment<DemoRecyclerSimpleViewBinding>() { override fun getInflater(): InflateBinding<DemoRecyclerSimpleViewBinding> = DemoRecyclerSimpleViewBinding::inflate private val adapter by lazy { context?.let { DefaultDataBindingRecyclerAdapter(it) } } override fun useBinding() { val adapter = adapter ?: return val context = context ?: return adapter.clear() for (section in 0 until 10) { for (i in 0 until 10) { adapter.add(SimpleListItemRender("First text is good text", section) { val transaction = Builder(adapter).apply { hideSection(section) hideSection(section + 1) hideSection(section + 2) }.build() transaction.applySafe() showSnackbar(binding.root, R.string.app_name, R.string.app_name, 5000, onAction = { transaction.resetSafe { logWarning("omg failure! list changed outside of modification") } }) }, section) adapter.add(SimpleListImageItemRender(Color.BLUE, section), section) adapter.add(SimpleListItemRender("Whats up test ?", section) {}, section) adapter.add(SimpleListImageItemRender(Color.RED, section), section) } } binding.demoRecyclerSimpleViewRecyclerview.setup(adapter, LinearLayoutManager(context)) binding.demoRecyclerSimpleViewReset.setOnclickAsync { for (i in 0 until adapter.sectionCount) { adapter.showSection(i) } } } } fun setColorUsingBackground(view: View, section: Int) { val color = Color.rgb(section % 20 + 80, section % 50 + 50, section % 100 + 20) view.setBackgroundColor(color) } open class SimpleListItemRender(text: String, private val section: Int, private val callback: () -> Unit) : BaseRenderModel<String, SimpleListItemBinding>(text, SimpleListItemBinding::class.java) { override fun renderFunction(view: SimpleListItemBinding, model: String, viewHolder: BaseViewHolderItem<SimpleListItemBinding>) { view.simpleListText.text = "$model section - $section" view.root.setOnclickAsync { callback() } setColorUsingBackground(view.root, section) } override fun getInflaterFunction(): ViewInflatingFunction<SimpleListItemBinding> { return SimpleListItemBinding::inflate } } class SimpleListImageItemRender(color: Int, val section: Int) : BaseRenderModel<Int, SimpleListImageItemBinding>(color, SimpleListImageItemBinding::class.java) { override fun renderFunction(view: SimpleListImageItemBinding, model: Int, viewHolder: BaseViewHolderItem<SimpleListImageItemBinding>) { view.simpleListItemImageImage.colorFilter = PorterDuffColorFilter(model, PorterDuff.Mode.ADD) setColorUsingBackground(view.root, section) } override fun getInflaterFunction(): ViewInflatingFunction<SimpleListImageItemBinding> = SimpleListImageItemBinding::inflate }
app/src/main/kotlin/csense/android/exampleApp/fragments/SimpleRecyclerDemo.kt
3169650051
// Copyright (c) 2017, Daniel Andersen ([email protected]) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // 3. The name of the author may not be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /** * Represents a company recommendation. Extends Recommendation. */ package dk.etiktak.backend.model.recommendation import dk.etiktak.backend.model.company.Company import javax.persistence.* @Entity @DiscriminatorValue("Company") class CompanyRecommendation : Recommendation() { @ManyToOne(optional = true) @JoinColumn(name = "company_id") var company = Company() }
src/main/kotlin/dk/etiktak/backend/model/recommendation/CompanyRecommendation.kt
2953168365
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * 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 com.vk.api.sdk.internal import android.net.Uri interface HttpMultipartEntry { class File : HttpMultipartEntry { var fileUri: Uri var fileName: String? = null constructor(fileUri: Uri) { this.fileUri = fileUri this.fileName = fileUri.lastPathSegment } constructor(fileUri: Uri, fileName: String) { this.fileUri = fileUri this.fileName = fileName } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is HttpMultipartEntry.File) return false val that = other as HttpMultipartEntry.File? return fileUri == that!!.fileUri } override fun hashCode(): Int { return fileUri.hashCode() } override fun toString(): String { return "File{fileUri='$fileUri'}" } } class Text(var textValue: String) : HttpMultipartEntry { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is HttpMultipartEntry.Text) return false val that = other as HttpMultipartEntry.Text? return textValue == that!!.textValue } override fun hashCode(): Int { return textValue.hashCode() } override fun toString(): String { return "Text{" + "textValue='" + textValue + '\''.toString() + '}'.toString() } } }
core/src/main/java/com/vk/api/sdk/internal/HttpMultipartEntry.kt
4064888611
package nsync.synchronization import commons.Server import commons.Signal import commons.SignalBus import mu.KLogging import nsync.* import java.nio.file.Path /** * The SyncServer is responsible to process fileChanges events and decide * whether to propagate then to storage layer or not and to keep the indexes * updated. */ class SyncServer(bus: SignalBus) : Server(bus, listOf(FileDeleted::class, FileModified::class)) { private companion object : KLogging() private fun relativePath(folder: SyncFolder, file: Path) = folder.fileRelativePath(file) override suspend fun handle(msg: Signal<*>) { when (msg) { is FileModified -> this.fileChanged(msg.payload) is FileDeleted -> this.fileDeleted(msg.payload) } } /** * Notifies that a file has changed. * * Updates the index and decide whether to notify or not the storage layer. */ private suspend fun fileChanged(file: LocalFile) { } private suspend fun fileDeleted(file: LocalFile) { } }
src/main/kotlin/nsync/synchronization/SyncServer.kt
3706168959
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * 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. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.prettyCards.dto import com.google.gson.annotations.SerializedName import com.vk.dto.common.id.UserId import kotlin.String /** * @param ownerId - Owner ID of edited pretty card * @param cardId - Card ID of edited pretty card */ data class PrettyCardsEditResponse( @SerializedName("owner_id") val ownerId: UserId, @SerializedName("card_id") val cardId: String )
api/src/main/java/com/vk/sdk/api/prettyCards/dto/PrettyCardsEditResponse.kt
140613701
package tk.zielony.carbonsamples import android.os.Bundle import tk.zielony.carbonsamples.animation.ImageFadeActivity import tk.zielony.carbonsamples.animation.PathAnimationActivity import tk.zielony.carbonsamples.animation.RippleActivity import tk.zielony.carbonsamples.animation.WidgetAnimationsActivity @SampleAnnotation(titleId = R.string.animationsActivity_title, layoutId = R.layout.activity_samplelist) class AnimationsActivity : SampleListActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) initToolbar() setItems(listOf( "Carbon adds easy visibility animations, brightness/saturation fade for images, backports the touch ripple and the circular reveal animation", SampleActivityItem(WidgetAnimationsActivity::class.java), SampleActivityItem(ImageFadeActivity::class.java), SampleActivityItem(RippleActivity::class.java), SampleActivityItem(PathAnimationActivity::class.java) )) } }
samples/src/main/java/tk/zielony/carbonsamples/AnimationsActivity.kt
2427038060
package de.westnordost.streetcomplete.quests.tactile_paving import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.quests.AYesNoQuestAnswerFragment class TactilePavingForm : AYesNoQuestAnswerFragment<Boolean>() { override val contentLayoutResId = R.layout.quest_tactile_paving override fun onClick(answer: Boolean) { applyAnswer(answer) } }
app/src/main/java/de/westnordost/streetcomplete/quests/tactile_paving/TactilePavingForm.kt
2384333375
package de.westnordost.streetcomplete.quests.oneway import android.util.Log import de.westnordost.osmapi.map.data.BoundingBox import de.westnordost.osmapi.map.data.Element import de.westnordost.osmapi.map.data.LatLon import de.westnordost.osmapi.map.data.Way import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.ElementGeometry import de.westnordost.streetcomplete.data.osm.OsmElementQuestType import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder import de.westnordost.streetcomplete.data.osm.download.MapDataWithGeometryHandler import de.westnordost.streetcomplete.data.osm.download.OverpassMapDataDao import de.westnordost.streetcomplete.data.osm.tql.FiltersParser import de.westnordost.streetcomplete.quests.oneway.data.TrafficFlowSegment import de.westnordost.streetcomplete.quests.oneway.data.TrafficFlowSegmentsDao import de.westnordost.streetcomplete.quests.oneway.data.WayTrafficFlowDao class AddOneway( private val overpassMapDataDao: OverpassMapDataDao, private val trafficFlowSegmentsDao: TrafficFlowSegmentsDao, private val db: WayTrafficFlowDao ) : OsmElementQuestType<OnewayAnswer> { private val tagFilters = " ways with highway ~ " + "trunk|trunk_link|primary|primary_link|secondary|secondary_link|tertiary|tertiary_link|" + "unclassified|residential|living_street|pedestrian|track|road" + " and !oneway and junction != roundabout and area != yes" + " and (access !~ private|no or (foot and foot !~ private|no)) " override val commitMessage = "Add whether this road is a one-way road, this road was marked as likely oneway by improveosm.org" override val icon = R.drawable.ic_quest_oneway override val hasMarkersAtEnds = true private val filter by lazy { FiltersParser().parse(tagFilters) } override fun getTitle(tags: Map<String, String>) = R.string.quest_oneway_title override fun isApplicableTo(element: Element) = filter.matches(element) && db.isForward(element.id) != null override fun download(bbox: BoundingBox, handler: MapDataWithGeometryHandler): Boolean { val trafficDirectionMap: Map<Long, List<TrafficFlowSegment>> try { trafficDirectionMap = trafficFlowSegmentsDao.get(bbox) } catch (e: Exception) { Log.e("AddOneway", "Unable to download traffic metadata", e) return false } if (trafficDirectionMap.isEmpty()) return true val query = "way(id:${trafficDirectionMap.keys.joinToString(",")}); out meta geom;" overpassMapDataDao.getAndHandleQuota(query) { element, geometry -> fun handle(element: Element, geometry: ElementGeometry?) { if(geometry == null) return // filter the data as ImproveOSM data may be outdated or catching too much if (!filter.matches(element)) return val way = element as? Way ?: return val segments = trafficDirectionMap[way.id] ?: return /* exclude rings because the driving direction can then not be determined reliably from the improveosm data and the quest should stay simple, i.e not require the user to input it in those cases. Additionally, whether a ring-road is a oneway or not is less valuable information (for routing) and many times such a ring will actually be a roundabout. Oneway information on roundabouts is superfluous. See #1320 */ if(way.nodeIds.last() == way.nodeIds.first()) return /* only create quest if direction can be clearly determined and is the same direction for all segments belonging to one OSM way (because StreetComplete cannot split ways up) */ val isForward = isForward(geometry.polylines[0], segments) ?: return db.put(way.id, isForward) handler.handle(element, geometry) } handle(element, geometry) } return true } /** returns true if all given [trafficFlowSegments] point forward in relation to the * direction of the OSM [way] and false if they all point backward. * * If the segments point into different directions or their direction cannot be * determined. returns null. */ private fun isForward(way: List<LatLon>,trafficFlowSegments: List<TrafficFlowSegment>): Boolean? { var result: Boolean? = null for (segment in trafficFlowSegments) { val fromPositionIndex = findClosestPositionIndexOf(way, segment.fromPosition) val toPositionIndex = findClosestPositionIndexOf(way, segment.toPosition) if (fromPositionIndex == -1 || toPositionIndex == -1) return null if (fromPositionIndex == toPositionIndex) return null val forward = fromPositionIndex < toPositionIndex if (result == null) { result = forward } else if (result != forward) { return null } } return result } private fun findClosestPositionIndexOf(positions: List<LatLon>, latlon: LatLon): Int { var shortestDistance = 1.0 var result = -1 var index = 0 for (pos in positions) { val distance = Math.hypot( pos.longitude - latlon.longitude, pos.latitude - latlon.latitude ) if (distance < 0.00005 && distance < shortestDistance) { shortestDistance = distance result = index } index++ } return result } override fun createForm() = AddOnewayForm() override fun applyAnswerTo(answer: OnewayAnswer, changes: StringMapChangesBuilder) { if (!answer.isOneway) { changes.add("oneway", "no") } else { changes.add("oneway", if (db.isForward(answer.wayId)!!) "yes" else "-1") } } override fun cleanMetadata() { db.deleteUnreferenced() } }
app/src/main/java/de/westnordost/streetcomplete/quests/oneway/AddOneway.kt
108845767
package com.reactnative.scenarios import android.app.Activity import android.app.Application import android.os.Bundle import android.content.Context import com.facebook.react.bridge.Promise; abstract class Scenario( protected val context: Context ): Application.ActivityLifecycleCallbacks { open fun run(promise: Promise) { } /** * Returns a throwable with the message as the current classname */ protected fun generateException(): Throwable = RuntimeException(javaClass.simpleName) /* Activity lifecycle callback overrides */ protected fun registerActivityLifecycleCallbacks() { (context.applicationContext as Application).registerActivityLifecycleCallbacks(this) } override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {} override fun onActivityStarted(activity: Activity) {} override fun onActivityResumed(activity: Activity) {} override fun onActivityPaused(activity: Activity) {} override fun onActivityStopped(activity: Activity) {} override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {} override fun onActivityDestroyed(activity: Activity) {} }
test/react-native/features/fixtures/reactnative/scenarios/Scenario.kt
3641645203
package org.stepik.android.domain.download.interactor import io.reactivex.Observable import org.stepic.droid.persistence.model.DownloadItem import org.stepik.android.domain.download.repository.DownloadRepository import javax.inject.Inject class DownloadsInteractor @Inject constructor( private val downloadRepository: DownloadRepository ) { fun fetchDownloadItems(): Observable<DownloadItem> = downloadRepository.getDownloads() }
app/src/main/java/org/stepik/android/domain/download/interactor/DownloadsInteractor.kt
1620664282
package com.ucsoftworks.leafdb.android import android.database.Cursor import com.ucsoftworks.leafdb.wrapper.ILeafDbCursor /** * Created by Pasenchuk Victor on 25/08/2017 */ internal class LeafDbAndroidCursor(private val cursor: Cursor) : ILeafDbCursor { override val empty: Boolean get() = !cursor.moveToNext() override val isClosed: Boolean get() = cursor.isClosed override fun close() { cursor.close() } override fun moveToNext() = cursor.moveToNext() override fun getString(index: Int): String = cursor.getString(index) override fun getLong(index: Int): Long = cursor.getLong(index) override fun getDouble(index: Int): Double = cursor.getDouble(index) }
leafdb-android/src/main/java/com/ucsoftworks/leafdb/android/LeafDbAndroidCursor.kt
1800219781
package eu.kanade.tachiyomi.ui.catalogue import android.view.View import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.source.online.LoginSource import eu.kanade.tachiyomi.ui.base.holder.BaseFlexibleViewHolder import eu.kanade.tachiyomi.ui.base.holder.SlicedHolder import eu.kanade.tachiyomi.util.getRound import eu.kanade.tachiyomi.util.gone import eu.kanade.tachiyomi.util.visible import io.github.mthli.slice.Slice import kotlinx.android.synthetic.main.catalogue_main_controller_card_item.* class SourceHolder(view: View, override val adapter: CatalogueAdapter, val showButtons: Boolean) : BaseFlexibleViewHolder(view, adapter), SlicedHolder { override val slice = Slice(card).apply { setColor(adapter.cardBackground) } override val viewToSlice: View get() = card init { source_browse.setOnClickListener { adapter.browseClickListener.onBrowseClick(adapterPosition) } source_latest.setOnClickListener { adapter.latestClickListener.onLatestClick(adapterPosition) } if(!showButtons) { source_browse.gone() source_latest.gone() } } fun bind(item: SourceItem) { val source = item.source setCardEdges(item) // Set source name title.text = source.name // Set circle letter image. itemView.post { image.setImageDrawable(image.getRound(source.name.take(1).toUpperCase(), false)) } // If source is login, show only login option if (source is LoginSource && !source.isLogged()) { source_browse.setText(R.string.login) source_latest.gone() } else { source_browse.setText(R.string.browse) if (source.supportsLatest && showButtons) { source_latest.visible() } else { source_latest.gone() } } } }
app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/SourceHolder.kt
1024581662
package nl.sugcube.dirtyarrows.bow.ability import nl.sugcube.dirtyarrows.DirtyArrows import nl.sugcube.dirtyarrows.bow.BowAbility import nl.sugcube.dirtyarrows.bow.DefaultBow import nl.sugcube.dirtyarrows.util.createExplosion import nl.sugcube.dirtyarrows.util.showSmokeParticle import org.bukkit.Material import org.bukkit.entity.Arrow import org.bukkit.entity.Player import org.bukkit.event.entity.ProjectileHitEvent import org.bukkit.inventory.ItemStack /** * Shoots arrows that explode on impact. * * @author SugarCaney */ open class ExplodingBow(plugin: DirtyArrows) : BowAbility( plugin = plugin, type = DefaultBow.EXPLODING, canShootInProtectedRegions = false, protectionRange = 5.0, costRequirements = listOf(ItemStack(Material.TNT, 1)), description = "Explosive arrows." ) { /** * The power of the explosion. TNT is 4.0 for reference. */ val power = config.getDouble("$node.power").toFloat() /** * Whether the explosion can set blocks on fire. */ val setOnFire = config.getBoolean("$node.set-on-fire") /** * Whether to break the broken blocks. */ val breakBlocks = config.getBoolean("$node.break-blocks") init { check(power >= 0.0) { "$node.power cannot be negative, got <$power>" } } override fun land(arrow: Arrow, player: Player, event: ProjectileHitEvent) { arrow.location.createExplosion(power = power, setFire = setOnFire, breakBlocks = breakBlocks) } override fun particle(tickNumber: Int) = arrows.forEach { it.showSmokeParticle() } }
src/main/kotlin/nl/sugcube/dirtyarrows/bow/ability/ExplodingBow.kt
506832159
package org.walleth.kethereum.android import android.os.Parcel import android.os.Parcelable import org.kethereum.extensions.hexToBigInteger import org.kethereum.extensions.toHexString import org.kethereum.model.Address import org.kethereum.model.ChainId import org.kethereum.model.Transaction import org.kethereum.model.createTransactionWithDefaults import org.komputing.khex.model.HexString import java.math.BigInteger class TransactionParcel(val transaction: Transaction) : Parcelable { constructor(parcel: Parcel) : this(createTransactionWithDefaults( chain = ChainId(HexString(parcel.readString()!!).hexToBigInteger()), value = BigInteger(parcel.readString()), from = Address(parcel.readString()!!), txHash = parcel.readValue(null) as String?, to = (parcel.readValue(null) as String?)?.let { Address(it) }, nonce = (parcel.readValue(null) as String?)?.let { BigInteger(it) }, creationEpochSecond = parcel.readValue(null) as Long?, gasPrice = BigInteger(parcel.readString()), gasLimit = BigInteger(parcel.readString()), input = parcel.createByteArray()!!)) override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeString(transaction.chain!!.toHexString()) dest.writeString(transaction.value.toString()) dest.writeString(transaction.from?.hex) dest.writeValue(transaction.txHash) dest.writeValue(transaction.to?.hex) dest.writeValue(transaction.nonce?.toString()) dest.writeValue(transaction.creationEpochSecond) dest.writeString(transaction.gasPrice.toString()) dest.writeString(transaction.gasLimit.toString()) dest.writeByteArray(transaction.input) } override fun describeContents() = 0 companion object CREATOR : Parcelable.Creator<TransactionParcel> { override fun createFromParcel(parcel: Parcel) = TransactionParcel(parcel) override fun newArray(size: Int): Array<TransactionParcel?> = arrayOfNulls(size) } }
app/src/main/java/org/walleth/kethereum/android/TransactionParcel.kt
4072648206
package info.nightscout.androidaps.database.embedments data class InsulinConfiguration( var insulinLabel: String, var insulinEndTime: Long, // DIA before [milliseconds] var peak: Long // [milliseconds] )
database/src/main/java/info/nightscout/androidaps/database/embedments/InsulinConfiguration.kt
4266576727
package info.nightscout.androidaps.plugins.iob.iobCobCalculator.data import android.content.Context import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.core.R import info.nightscout.androidaps.database.entities.Carbs import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries import info.nightscout.androidaps.plugins.general.overview.graphExtensions.Scale import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import java.util.* import javax.inject.Inject import kotlin.math.min class AutosensData(injector: HasAndroidInjector) : DataPointWithLabelInterface { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var sp: SP @Inject lateinit var rh: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var dateUtil: DateUtil inner class CarbsInPast { var time: Long var carbs: Double var min5minCarbImpact = 0.0 var remaining: Double constructor(t: Carbs, isAAPSOrWeighted: Boolean) { time = t.timestamp carbs = t.amount remaining = t.amount val profile = profileFunction.getProfile(t.timestamp) if (isAAPSOrWeighted && profile != null) { val maxAbsorptionHours = sp.getDouble(R.string.key_absorption_maxtime, Constants.DEFAULT_MAX_ABSORPTION_TIME) val sens = profile.getIsfMgdl(t.timestamp) val ic = profile.getIc(t.timestamp) min5minCarbImpact = t.amount / (maxAbsorptionHours * 60 / 5) * sens / ic aapsLogger.debug( LTag.AUTOSENS, """Min 5m carbs impact for ${carbs}g @${dateUtil.dateAndTimeString(t.timestamp)} for ${maxAbsorptionHours}h calculated to $min5minCarbImpact ISF: $sens IC: $ic""" ) } else { min5minCarbImpact = sp.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact) } } internal constructor(other: CarbsInPast) { time = other.time carbs = other.carbs min5minCarbImpact = other.min5minCarbImpact remaining = other.remaining } override fun toString(): String = String.format(Locale.ENGLISH, "CarbsInPast: time: %s carbs: %.02f min5minCI: %.02f remaining: %.2f", dateUtil.dateAndTimeString(time), carbs, min5minCarbImpact, remaining) } var time = 0L var bg = 0.0 // mgdl var chartTime: Long = 0 var pastSensitivity = "" var deviation = 0.0 var validDeviation = false var activeCarbsList: MutableList<CarbsInPast> = ArrayList() var absorbed = 0.0 var carbsFromBolus = 0.0 var cob = 0.0 var bgi = 0.0 var delta = 0.0 var avgDelta = 0.0 var avgDeviation = 0.0 var autosensResult = AutosensResult() var slopeFromMaxDeviation = 0.0 var slopeFromMinDeviation = 999.0 var usedMinCarbsImpact = 0.0 var failOverToMinAbsorptionRate = false // Oref1 var absorbing = false var mealCarbs = 0.0 var mealStartCounter = 999 var type = "" var uam = false var extraDeviation: MutableList<Double> = ArrayList() override fun toString(): String { return String.format( Locale.ENGLISH, "AutosensData: %s pastSensitivity=%s delta=%.02f avgDelta=%.02f bgi=%.02f deviation=%.02f avgDeviation=%.02f absorbed=%.02f carbsFromBolus=%.02f cob=%.02f autosensRatio=%.02f slopeFromMaxDeviation=%.02f slopeFromMinDeviation=%.02f activeCarbsList=%s", dateUtil.dateAndTimeString(time), pastSensitivity, delta, avgDelta, bgi, deviation, avgDeviation, absorbed, carbsFromBolus, cob, autosensResult.ratio, slopeFromMaxDeviation, slopeFromMinDeviation, activeCarbsList.toString() ) } fun cloneCarbsList(): MutableList<CarbsInPast> { val newActiveCarbsList: MutableList<CarbsInPast> = ArrayList() for (c in activeCarbsList) { newActiveCarbsList.add(CarbsInPast(c)) } return newActiveCarbsList } // remove carbs older than timeframe fun removeOldCarbs(toTime: Long, isAAPSOrWeighted: Boolean) { val maxAbsorptionHours: Double = if (isAAPSOrWeighted) sp.getDouble(R.string.key_absorption_maxtime, Constants.DEFAULT_MAX_ABSORPTION_TIME) else sp.getDouble(R.string.key_absorption_cutoff, Constants.DEFAULT_MAX_ABSORPTION_TIME) var i = 0 while (i < activeCarbsList.size) { val c = activeCarbsList[i] if (c.time + maxAbsorptionHours * 60 * 60 * 1000L < toTime) { activeCarbsList.removeAt(i--) if (c.remaining > 0) cob -= c.remaining aapsLogger.debug(LTag.AUTOSENS, "Removing carbs at " + dateUtil.dateAndTimeString(toTime) + " after " + maxAbsorptionHours + "h > " + c.toString()) } i++ } } fun deductAbsorbedCarbs() { var ac = absorbed var i = 0 while (i < activeCarbsList.size && ac > 0) { val c = activeCarbsList[i] if (c.remaining > 0) { val sub = min(ac, c.remaining) c.remaining -= sub ac -= sub } i++ } } // ------- DataPointWithLabelInterface ------ var scale: Scale? = null override fun getX(): Double = chartTime.toDouble() override fun getY(): Double = scale!!.transform(cob) override fun setY(y: Double) {} override val label: String = "" override val duration = 0L override val shape = PointsWithLabelGraphSeries.Shape.COB_FAIL_OVER override val size = 0.5f override fun color(context: Context?): Int { return rh.gac(context,R.attr.cobColor) } init { injector.androidInjector().inject(this) } }
core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/data/AutosensData.kt
946077655
package expo.modules.securestore import expo.modules.core.Promise import org.json.JSONException import java.security.GeneralSecurityException import javax.crypto.Cipher import javax.crypto.spec.GCMParameterSpec // Interface used to pass encryption/decryption logic fun interface EncryptionCallback { @Throws(GeneralSecurityException::class, JSONException::class) fun run( promise: Promise, cipher: Cipher, gcmParameterSpec: GCMParameterSpec, postEncryptionCallback: PostEncryptionCallback? ): Any }
packages/expo-secure-store/android/src/main/java/expo/modules/securestore/EncryptionCallback.kt
3234534427
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions open class FailedToConnectException(message: String? = null) : Exception("Failed to connect: ${message ?: ""}")
omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/FailedToConnectException.kt
3184826281
package tr.xip.scd.tensuu.student.ui.feature.main import android.annotation.SuppressLint import android.view.MenuItem import io.realm.Realm import io.realm.SyncUser import tr.xip.scd.tensuu.common.ui.mvp.SafeViewMvpPresenter import tr.xip.scd.tensuu.realm.model.* import tr.xip.scd.tensuu.realm.util.RealmUtils.syncedRealm import tr.xip.scd.tensuu.student.R import tr.xip.scd.tensuu.student.ui.feature.local.Credentials class StudentPresenter : SafeViewMvpPresenter<StudentView>() { private var realm: Realm? = null private var student: Student? = null override fun detachView(retainInstance: Boolean) { super.detachView(retainInstance) realm?.close() } fun init() { if (SyncUser.currentUser() != null) { realm = syncedRealm() val student = realm!!.where(Student::class.java) .equalTo(StudentFields.SSID, Credentials.id) .equalTo(StudentFields.PASSWORD, Credentials.password) .findFirst() if (student != null) { load() } else { goToLogin() } } else { goToLogin() } } private fun load() { if (realm == null) return student = realm!!.where(Student::class.java) .equalTo(StudentFields.SSID, Credentials.id) .equalTo(StudentFields.PASSWORD, Credentials.password) .findFirst() if (student != null) { view?.setName(student?.fullName ?: "?") view?.setSsid(student?.ssid) view?.setGrade(student?.grade) view?.setFloor(student?.floor) setPoints() setAdapter() /* Notify for the initial state */ view?.notifyDateChanged() } else { view?.showToast("Couldn't find student") view?.die() } } private fun setPoints() { if (realm == null) return val period = realm!!.where(Period::class.java).findFirst()!! var query = realm!!.where(Point::class.java) .equalTo(PointFields.TO.SSID, student?.ssid) if (period.start != 0L && period.end != 0L) { query = query .greaterThanOrEqualTo(PointFields.TIMESTAMP, period.start) .lessThanOrEqualTo(PointFields.TIMESTAMP, period.end) } view?.setPoints( 100 + query.sum(PointFields.AMOUNT).toInt() ).toString() } private fun setAdapter() { if (realm == null) return val period = realm!!.where(Period::class.java).findFirst()!! var query = realm!!.where(Point::class.java).equalTo(PointFields.TO.SSID, student?.ssid) if (period.start != 0L && period.end != 0L) { query = query .greaterThan(PointFields.TIMESTAMP, period.start) .lessThan(PointFields.TIMESTAMP, period.end) } view?.setAdapter(PointsAdapter(query.findAll())) } fun onDataChanged() { setPoints() view?.setFlipperChild( if (view?.getAdapter()?.itemCount == 0) { StudentActivity.FLIPPER_NO_POINTS } else { StudentActivity.FLIPPER_CONTENT } ) } fun onSignedOut() { Credentials.logout() view?.startLoginActivity() view?.die() } @SuppressLint("SimpleDateFormat") fun onOptionsItemSelected(item: MenuItem?) { when (item?.itemId) { R.id.action_sign_out -> { view?.showSignOutDialog() } } } fun goToLogin() { view?.startLoginActivity() view?.die() } }
app-student/src/main/java/tr/xip/scd/tensuu/student/ui/feature/main/StudentPresenter.kt
296507924
package com.auth0.android.request.internal import android.text.TextUtils import android.util.Log import androidx.annotation.VisibleForTesting import com.auth0.android.Auth0Exception import com.auth0.android.authentication.AuthenticationException import com.auth0.android.authentication.ParameterBuilder import com.auth0.android.callback.Callback import com.auth0.android.provider.* import com.auth0.android.provider.IdTokenVerificationOptions import com.auth0.android.provider.IdTokenVerifier import com.auth0.android.request.AuthenticationRequest import com.auth0.android.request.Request import com.auth0.android.result.Credentials import java.util.* internal open class BaseAuthenticationRequest( private val request: Request<Credentials, AuthenticationException>, private val clientId: String, baseURL: String) : AuthenticationRequest { private companion object { private val TAG = BaseAuthenticationRequest::class.java.simpleName private const val ERROR_VALUE_ID_TOKEN_VALIDATION_FAILED = "Could not verify the ID token" } private var _currentTimeInMillis: Long? = null @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) internal var validateClaims = false @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) internal var idTokenVerificationLeeway: Int? = null @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) internal var idTokenVerificationIssuer: String = baseURL @set:VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) internal var currentTimeInMillis: Long get() = if (_currentTimeInMillis != null) _currentTimeInMillis!! else System.currentTimeMillis() set(value) { _currentTimeInMillis = value } /** * Sets the 'grant_type' parameter * * @param grantType grant type * @return itself */ override fun setGrantType(grantType: String): AuthenticationRequest { addParameter(ParameterBuilder.GRANT_TYPE_KEY, grantType) return this } /** * Sets the 'connection' parameter. * * @param connection name of the connection * @return itself */ override fun setConnection(connection: String): AuthenticationRequest { addParameter(ParameterBuilder.CONNECTION_KEY, connection) return this } /** * Sets the 'realm' parameter. A realm identifies the host against which the authentication will be made, and usually helps to know which username and password to use. * * @param realm name of the realm * @return itself */ override fun setRealm(realm: String): AuthenticationRequest { addParameter(ParameterBuilder.REALM_KEY, realm) return this } /** * Sets the 'scope' parameter. * * @param scope a scope value * @return itself */ override fun setScope(scope: String): AuthenticationRequest { addParameter(ParameterBuilder.SCOPE_KEY, scope) return this } /** * Sets the 'audience' parameter. * * @param audience an audience value * @return itself */ override fun setAudience(audience: String): AuthenticationRequest { addParameter(ParameterBuilder.AUDIENCE_KEY, audience) return this } override fun validateClaims(): AuthenticationRequest { this.validateClaims = true return this } override fun withIdTokenVerificationLeeway(leeway: Int): AuthenticationRequest { this.idTokenVerificationLeeway = leeway return this } override fun withIdTokenVerificationIssuer(issuer: String): AuthenticationRequest { this.idTokenVerificationIssuer = issuer return this } override fun addParameters(parameters: Map<String, String>): AuthenticationRequest { request.addParameters(parameters) return this } override fun addParameter(name: String, value: String): AuthenticationRequest { request.addParameter(name, value) return this } override fun addHeader(name: String, value: String): AuthenticationRequest { request.addHeader(name, value) return this } override fun start(callback: Callback<Credentials, AuthenticationException>) { warnClaimValidation() request.start(object : Callback<Credentials, AuthenticationException> { override fun onSuccess(result: Credentials) { if(validateClaims) { try { verifyClaims(result.idToken) } catch (e: AuthenticationException) { callback.onFailure(e) return } } callback.onSuccess(result) } override fun onFailure(error: AuthenticationException) { callback.onFailure(error) } }) } @Throws(Auth0Exception::class) override fun execute(): Credentials { warnClaimValidation() val credentials = request.execute() if(validateClaims) { verifyClaims(credentials.idToken) } return credentials } @JvmSynthetic @Throws(Auth0Exception::class) override suspend fun await(): Credentials { warnClaimValidation() val credentials = request.await() if(validateClaims) { verifyClaims(credentials.idToken) } return credentials } /** * Used to verify the claims from the ID Token. * * @param idToken - The ID Token obtained through authentication * @throws AuthenticationException - This is a exception wrapping around [TokenValidationException] */ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) internal fun verifyClaims(idToken: String) { try { if (TextUtils.isEmpty(idToken)) { throw IdTokenMissingException() } val decodedIdToken: Jwt = try { Jwt(idToken) } catch (error: Exception) { throw UnexpectedIdTokenException(error) } val options = IdTokenVerificationOptions( idTokenVerificationIssuer, clientId, null ) options.clockSkew = idTokenVerificationLeeway options.clock = Date(currentTimeInMillis) IdTokenVerifier().verify(decodedIdToken, options, false) } catch (e: TokenValidationException) { throw AuthenticationException(ERROR_VALUE_ID_TOKEN_VALIDATION_FAILED, e) } } private fun warnClaimValidation() { if(!validateClaims) { Log.e(TAG, "The request is made without validating claims. Enable claim validation by calling AuthenticationRequest#validateClaims()") } } }
auth0/src/main/java/com/auth0/android/request/internal/BaseAuthenticationRequest.kt
3087816608
package com.keenencharles.unsplash.models import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class UserStats( var username: String? = null, var downloads: UserStat? = null, var views: UserStat? = null, var likes: UserStat? = null ) : Parcelable
androidunsplash/src/main/java/com/keenencharles/unsplash/models/UserStats.kt
2724103414
/* * Copyright (c) 2022. Adventech <[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 app.ss.storage.db.entity import androidx.room.Entity import androidx.room.PrimaryKey import app.ss.models.SSBibleVerses @Entity(tableName = "reads") data class ReadEntity( @PrimaryKey val index: String, val id: String, val date: String, val title: String, val content: String, val bible: List<SSBibleVerses> )
common/storage/src/main/java/app/ss/storage/db/entity/ReadEntity.kt
2740300965
/* * 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.crdt import com.google.common.truth.Truth.assertThat import kotlin.test.assertFailsWith import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 /** Tests for [CrdtCount]. */ @RunWith(JUnit4::class) class CrdtCountTest { lateinit var alice: CrdtCount lateinit var bob: CrdtCount @Before fun setup() { alice = CrdtCount() bob = CrdtCount() } @Test fun countInitializesToZero() { assertThat(alice.consumerView).isEqualTo(0) } @Test fun canApplyAnIncrementOp() { assertTrue( alice.applyOperation(CrdtCount.Operation.Increment("alice", VersionMap("alice" to 1))) ) assertThat(alice.consumerView).isEqualTo(1) } @Test fun canApplyAnIncrementOp_withPlusEquals() { alice.forActor("alice") += 5 assertThat(alice.consumerView).isEqualTo(5) } @Test fun canApplyTwoIncrementOps_fromDifferentActors() { assertTrue( alice.applyOperation(CrdtCount.Operation.Increment("alice", VersionMap("alice" to 1))) ) assertTrue( alice.applyOperation(CrdtCount.Operation.Increment("bob", VersionMap("bob" to 1))) ) assertThat(alice.consumerView).isEqualTo(2) } @Test fun canApplyTwoIncrementOps_fromSameActor() { assertTrue( alice.applyOperation(CrdtCount.Operation.Increment("alice", VersionMap("alice" to 1))) ) assertTrue( alice.applyOperation(CrdtCount.Operation.Increment("alice", VersionMap("alice" to 2))) ) assertThat(alice.consumerView).isEqualTo(2) } @Test fun canNotApplyTwoIncrementOps_fromSameActor_withSameVersions() { assertTrue( alice.applyOperation(CrdtCount.Operation.Increment("alice", VersionMap("alice" to 1))) ) assertFalse( alice.applyOperation(CrdtCount.Operation.Increment("alice", VersionMap("alice" to 1))) ) assertThat(alice.consumerView).isEqualTo(1) } @Test fun canApplyAMultiincrementOp() { assertTrue( alice.applyOperation( CrdtCount.Operation.MultiIncrement("alice", VersionMap("alice" to 1), 10) ) ) assertThat(alice.consumerView).isEqualTo(10) } @Test fun mergesTwoCounts_withIncrementsFromDifferentActors() { alice.forActor("alice") += 7 bob.forActor("bob") += 13 // merge bob into alice val results = alice.merge(bob.data) assertThat(alice.consumerView).isEqualTo(20) assertThat(results.modelChange).isInstanceOf(CrdtChange.Operations::class.java) assertThat((results.modelChange as CrdtChange.Operations)[0]) .isEqualTo(CrdtCount.Operation.MultiIncrement("bob", VersionMap("bob" to 1), 13)) assertThat(results.otherChange).isInstanceOf(CrdtChange.Operations::class.java) assertThat((results.otherChange as CrdtChange.Operations)[0]) .isEqualTo(CrdtCount.Operation.MultiIncrement("alice", VersionMap("alice" to 1), 7)) bob.applyChanges(results.otherChange) assertThat(bob.consumerView).isEqualTo(20) } @Test fun mergesTwoCounts_withIncrementsFromTheSameActor() { alice.forActor("alice") += 7 bob.merge(alice.data) bob.forActor("alice") += 13 // merge bob into alice val results = alice.merge(bob.data) assertThat(alice.consumerView).isEqualTo(20) assertThat(results.modelChange).isInstanceOf(CrdtChange.Operations::class.java) assertThat((results.modelChange as CrdtChange.Operations)[0]) .isEqualTo(CrdtCount.Operation.MultiIncrement("alice", VersionMap("alice" to 2), 13)) assertThat(results.otherChange).isInstanceOf(CrdtChange.Operations::class.java) // We already merged alice into bob. assertThat((results.otherChange as CrdtChange.Operations)).isEmpty() bob.applyChanges(results.otherChange) assertThat(bob.consumerView).isEqualTo(20) } @Test fun throwsOnDivergentModels() { assertTrue( alice.applyOperation(CrdtCount.Operation.MultiIncrement("alice", VersionMap("alice" to 1), 7)) ) assertTrue( bob.applyOperation(CrdtCount.Operation.MultiIncrement("alice", VersionMap("alice" to 1), 13)) ) assertFailsWith<CrdtException> { alice.merge(bob.data) } } @Test fun throwsOnApparentDecrement() { assertTrue( alice.applyOperation(CrdtCount.Operation.MultiIncrement("alice", VersionMap("alice" to 1), 7)) ) assertTrue( bob.applyOperation(CrdtCount.Operation.Increment("alice", VersionMap("alice" to 1))) ) assertTrue( bob.applyOperation(CrdtCount.Operation.MultiIncrement("alice", VersionMap("alice" to 2), 3)) ) assertFailsWith<CrdtException> { alice.merge(bob.data) } } @Test fun mergesSeveralActors() { alice.forActor("a") += 6 alice.forActor("c") += 12 alice.forActor("d") += 22 // Two increments for 'e' on alice trumps the single increment on bob. alice.forActor("e") += 4 alice.forActor("e") += 13 bob.forActor("b") += 5 // Vice versa for 'c'. bob.forActor("c") += 12 bob.forActor("c") += 6 bob.forActor("d") += 22 bob.forActor("e") += 4 val results = alice.merge(bob.data) assertThat(alice.consumerView).isEqualTo(68) bob.applyChanges(results.otherChange) assertThat(bob.consumerView).isEqualTo(68) } }
javatests/arcs/core/crdt/CrdtCountTest.kt
999345193
// 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.core.script.ucache import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.JavaSdkType import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.kotlin.idea.core.script.configuration.utils.ScriptClassRootsStorage import org.jetbrains.kotlin.idea.core.script.scriptingWarnLog import org.jetbrains.kotlin.idea.util.application.runReadAction import java.nio.file.Path class ScriptSdksBuilder( val project: Project, private val sdks: MutableMap<SdkId, Sdk?> = mutableMapOf(), private val remove: Sdk? = null ) { private val defaultSdk by lazy { getScriptDefaultSdk() } fun build(): ScriptSdks { val nonIndexedClassRoots = mutableSetOf<VirtualFile>() val nonIndexedSourceRoots = mutableSetOf<VirtualFile>() val nonIndexedSdks = sdks.values.filterNotNullTo(mutableSetOf()) runReadAction { for (module in ModuleManager.getInstance(project).modules.filter { !it.isDisposed }) { ProgressManager.checkCanceled() if (nonIndexedSdks.isEmpty()) break nonIndexedSdks.remove(ModuleRootManager.getInstance(module).sdk) } nonIndexedSdks.forEach { nonIndexedClassRoots.addAll(it.rootProvider.getFiles(OrderRootType.CLASSES)) nonIndexedSourceRoots.addAll(it.rootProvider.getFiles(OrderRootType.SOURCES)) } } return ScriptSdks(sdks, nonIndexedClassRoots, nonIndexedSourceRoots) } @Deprecated("Don't use, used only from DefaultScriptingSupport for saving to storage") fun addAll(other: ScriptSdksBuilder) { sdks.putAll(other.sdks) } fun addAll(other: ScriptSdks) { sdks.putAll(other.sdks) } // add sdk by home path with checking for removed sdk fun addSdk(sdkId: SdkId): Sdk? { val canonicalPath = sdkId.homeDirectory ?: return addDefaultSdk() return addSdk(Path.of(canonicalPath)) } fun addSdk(javaHome: Path?): Sdk? { if (javaHome == null) return addDefaultSdk() return sdks.getOrPut(SdkId(javaHome)) { getScriptSdkByJavaHome(javaHome) ?: defaultSdk } } private fun getScriptSdkByJavaHome(javaHome: Path): Sdk? { // workaround for mismatched gradle wrapper and plugin version val javaHomeVF = try { VfsUtil.findFile(javaHome, true) } catch (e: Throwable) { null } ?: return null return runReadAction { ProjectJdkTable.getInstance() }.allJdks .find { it.homeDirectory == javaHomeVF } ?.takeIf { it.canBeUsedForScript() } } fun addDefaultSdk(): Sdk? = sdks.getOrPut(SdkId.default) { defaultSdk } fun addSdkByName(sdkName: String) { val sdk = runReadAction { ProjectJdkTable.getInstance() }.allJdks .find { it.name == sdkName } ?.takeIf { it.canBeUsedForScript() } ?: defaultSdk ?: return val homePath = sdk.homePath ?: return sdks[SdkId(homePath)] = sdk } private fun getScriptDefaultSdk(): Sdk? { val projectSdk = ProjectRootManager.getInstance(project).projectSdk?.takeIf { it.canBeUsedForScript() } if (projectSdk != null) return projectSdk val allJdks = runReadAction { ProjectJdkTable.getInstance() }.allJdks val anyJavaSdk = allJdks.find { it.canBeUsedForScript() } if (anyJavaSdk != null) { return anyJavaSdk } scriptingWarnLog( "Default Script SDK is null: " + "projectSdk = ${ProjectRootManager.getInstance(project).projectSdk}, " + "all sdks = ${allJdks.joinToString("\n")}" ) return null } private fun Sdk.canBeUsedForScript() = this != remove && sdkType is JavaSdkType fun toStorage(storage: ScriptClassRootsStorage) { storage.sdks = sdks.values.mapNotNullTo(mutableSetOf()) { it?.name } storage.defaultSdkUsed = sdks.containsKey(SdkId.default) } fun fromStorage(storage: ScriptClassRootsStorage) { storage.sdks.forEach { addSdkByName(it) } if (storage.defaultSdkUsed) { addDefaultSdk() } } }
plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/ucache/ScriptSdksBuilder.kt
3531677028
/* * 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.data import arcs.core.common.Referencable import arcs.core.crdt.CrdtModel import arcs.core.crdt.CrdtModelType import arcs.core.crdt.CrdtSet import arcs.core.crdt.CrdtSet.Data import arcs.core.crdt.CrdtSet.IOperation import arcs.core.type.Tag import arcs.core.type.Type import kotlin.reflect.KClass /** Extension function to wrap any type in a collection type. */ fun <T : Type> T?.collectionOf(): CollectionType<T>? = if (this == null) null else CollectionType(this) /** [Type] representation of a collection. */ data class CollectionType<T : Type>( val collectionType: T ) : Type, Type.TypeContainer<T>, EntitySchemaProviderType, CrdtModelType<Data<Referencable>, IOperation<Referencable>, Set<Referencable>> { override val tag = Tag.Collection override val containedType: T get() = collectionType override val entitySchema: Schema? get() = (collectionType as? EntitySchemaProviderType)?.entitySchema override val crdtModelDataClass: KClass<*> = CrdtSet.DataImpl::class override fun createCrdtModel(): CrdtModel<Data<Referencable>, IOperation<Referencable>, Set<Referencable>> { return CrdtSet() } override fun toStringWithOptions(options: Type.ToStringOptions): String { return if (options.pretty) { "${collectionType.toStringWithOptions(options)} Collection" } else { "[${collectionType.toStringWithOptions(options)}]" } } }
java/arcs/core/data/CollectionType.kt
3956040863
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class OptionalStringEntityImpl: OptionalStringEntity, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } @JvmField var _data: String? = null override val data: String? get() = _data override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: OptionalStringEntityData?): ModifiableWorkspaceEntityBase<OptionalStringEntity>(), OptionalStringEntity.Builder { constructor(): this(OptionalStringEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity OptionalStringEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field OptionalStringEntity#entitySource should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } override var data: String? get() = getEntityData().data set(value) { checkModificationAllowed() getEntityData().data = value changedProperty.add("data") } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override fun getEntityData(): OptionalStringEntityData = result ?: super.getEntityData() as OptionalStringEntityData override fun getEntityClass(): Class<OptionalStringEntity> = OptionalStringEntity::class.java } } class OptionalStringEntityData : WorkspaceEntityData<OptionalStringEntity>() { var data: String? = null override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<OptionalStringEntity> { val modifiable = OptionalStringEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): OptionalStringEntity { val entity = OptionalStringEntityImpl() entity._data = data entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return OptionalStringEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as OptionalStringEntityData if (this.data != other.data) return false if (this.entitySource != other.entitySource) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as OptionalStringEntityData if (this.data != other.data) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + data.hashCode() return result } }
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/OptionalStringEntityImpl.kt
1418329150
/* * 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.storage import arcs.core.crdt.CrdtSet import arcs.core.crdt.VersionMap import arcs.core.data.Capability.Ttl import arcs.core.data.CollectionType import arcs.core.data.EntityType import arcs.core.data.FieldType import arcs.core.data.RawEntity import arcs.core.data.RawEntity.Companion.UNINITIALIZED_TIMESTAMP import arcs.core.data.ReferenceType import arcs.core.data.Schema import arcs.core.data.SchemaFields import arcs.core.data.util.ReferencablePrimitive import arcs.core.data.util.toReferencable import arcs.core.storage.driver.RamDiskDriverProvider import arcs.core.storage.keys.RamDiskStorageKey import arcs.core.storage.referencemode.ReferenceModeStorageKey import arcs.core.storage.testutil.testDriverFactory import arcs.core.storage.testutil.testStorageEndpointManager import arcs.core.storage.testutil.testWriteBackProvider import arcs.core.util.testutil.LogRule import arcs.jvm.util.JvmTime import arcs.jvm.util.testutil.FakeTime import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.Job import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 typealias CollectionStore<T> = ActiveStore<CrdtSet.Data<T>, CrdtSet.Operation<T>, Set<T>> @Suppress("EXPERIMENTAL_API_USAGE") @RunWith(JUnit4::class) class RawReferenceTest { @get:Rule val log = LogRule() private val collectionKey = RamDiskStorageKey("friends") private val backingKey = RamDiskStorageKey("people") private val dereferencer = RawEntityDereferencer( Person.SCHEMA, testStorageEndpointManager() ) private val dummyRef = RawReference( id = "reference_id", storageKey = backingKey, version = VersionMap("alice" to 1), _creationTimestamp = 12345L, _expirationTimestamp = 67890L, isHardReference = true ) @Before fun setup() { DefaultDriverFactory.update(RamDiskDriverProvider()) } @Test fun dereference() = runBlocking { val refModeKey = ReferenceModeStorageKey(backingKey, collectionKey) val options = StoreOptions( storageKey = refModeKey, type = CollectionType(EntityType(Person.SCHEMA)) ) val store: CollectionStore<RawEntity> = ActiveStore( options, this, testDriverFactory, ::testWriteBackProvider, null, JvmTime ) val addPeople = listOf( CrdtSet.Operation.Add( "bob", VersionMap("bob" to 1), Person("Sundar", 51).toRawEntity() ), CrdtSet.Operation.Add( "bob", VersionMap("bob" to 2), Person("Jason", 35).toRawEntity() ), CrdtSet.Operation.Add( "bob", VersionMap("bob" to 3), Person("Watson", 6).toRawEntity() ) ) store.onProxyMessage(ProxyMessage.Operations(addPeople, 1)) log("Setting up direct store to collection of references") val collectionOptions = StoreOptions( storageKey = collectionKey, type = CollectionType(ReferenceType(EntityType(Person.SCHEMA))) ) @Suppress("UNCHECKED_CAST") val directCollection: CollectionStore<RawReference> = ActiveStore( collectionOptions, this, testDriverFactory, ::testWriteBackProvider, null, JvmTime ) val job = Job() val me = directCollection.on { if (it is ProxyMessage.ModelUpdate<*, *, *>) job.complete() } directCollection.onProxyMessage(ProxyMessage.SyncRequest(me)) directCollection.idle() job.join() val collectionItems = (directCollection as DirectStore).getLocalData() assertThat(collectionItems.values).hasSize(3) val expectedPeople = listOf( Person("Sundar", 51), Person("Jason", 35), Person("Watson", 6) ).associateBy { it.hashCode().toString() } collectionItems.values.values.forEach { val ref = it.value ref.dereferencer = dereferencer val expectedPerson = expectedPeople[ref.id] ?: error("Bad reference: $ref") val dereferenced = ref.dereference() val actualPerson = requireNotNull(dereferenced).toPerson() assertThat(actualPerson).isEqualTo(expectedPerson) } } @Test fun ensureTimestampsAreSet() { val ref = RawReference("reference_id", backingKey, null) assertThat(ref.creationTimestamp).isEqualTo(UNINITIALIZED_TIMESTAMP) assertThat(ref.expirationTimestamp).isEqualTo(UNINITIALIZED_TIMESTAMP) ref.ensureTimestampsAreSet(FakeTime(10), Ttl.Minutes(1)) assertThat(ref.creationTimestamp).isEqualTo(10) assertThat(ref.expirationTimestamp).isEqualTo(60010) // Calling again doesn't change the value. ref.ensureTimestampsAreSet(FakeTime(20), Ttl.Minutes(2)) assertThat(ref.creationTimestamp).isEqualTo(10) assertThat(ref.expirationTimestamp).isEqualTo(60010) } @Test fun equalAndHashAreConsistent_sameValue() { // Exact same values. val ref = dummyRef.copy() assertThat(ref).isEqualTo(dummyRef) assertThat(ref.hashCode()).isEqualTo(dummyRef.hashCode()) } @Test fun equalAndHashAreConsistent_differentVersion() { // Only differ in version, which should be counted in equal and hashcode. val ref = dummyRef.copy(version = VersionMap("bob" to 1)) assertThat(ref).isNotEqualTo(dummyRef) assertThat(ref.hashCode()).isNotEqualTo(dummyRef.hashCode()) } @Test fun equalAndHashAreConsistent_differentId() { // Only differ in id, which should be counted in equal and hashcode. val ref = dummyRef.copy(id = "reference_id_2") assertThat(ref).isNotEqualTo(dummyRef) assertThat(ref.hashCode()).isNotEqualTo(dummyRef.hashCode()) } @Test fun equalAndHashAreConsistent_differentStorageKey() { // Only differ in storage key, which should be counted in equal and hashcode. val ref = dummyRef.copy(storageKey = collectionKey) assertThat(ref).isNotEqualTo(dummyRef) assertThat(ref.hashCode()).isNotEqualTo(dummyRef.hashCode()) } @Test fun equalAndHashAreConsistent_differentIsHardReference() { // Only differ in isHardReference, which should be counted in equal and hashcode. val ref = dummyRef.copy(isHardReference = false) assertThat(ref).isNotEqualTo(dummyRef) assertThat(ref.hashCode()).isNotEqualTo(dummyRef.hashCode()) } @Test fun equalAndHashAreConsistent_differentCreationTimestamp() { // Only differ in creationTimestamp , which should be counted in equal and hashcode. val ref = dummyRef.copy(_creationTimestamp = 3333L) assertThat(ref).isNotEqualTo(dummyRef) assertThat(ref.hashCode()).isNotEqualTo(dummyRef.hashCode()) } @Test fun equalAndHashAreConsistent_differentExpirationTimestamp() { // Only differ in expirationTimestamp , which should be counted in equal and hashcode. val ref = dummyRef.copy(_expirationTimestamp = 67999L) assertThat(ref).isNotEqualTo(dummyRef) assertThat(ref.hashCode()).isNotEqualTo(dummyRef.hashCode()) } private data class Person( val name: String, val age: Int ) { fun toRawEntity(): RawEntity = RawEntity( id = "${hashCode()}", singletons = mapOf( "name" to name.toReferencable(), "age" to age.toDouble().toReferencable() ), collections = emptyMap() ) companion object { val SCHEMA = Schema( emptySet(), SchemaFields( singletons = mapOf( "name" to FieldType.Text, "age" to FieldType.Number ), collections = emptyMap() ), "abcdef" ) } } @Suppress("UNCHECKED_CAST") private fun RawEntity.toPerson() = Person( name = requireNotNull(singletons["name"] as? ReferencablePrimitive<String>).value, age = requireNotNull(singletons["age"] as? ReferencablePrimitive<Double>).value.toInt() ) }
javatests/arcs/core/storage/RawReferenceTest.kt
2367290607
/* * 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.sdk.wasm object WasmRuntimeClient { fun <T : WasmEntity> singletonClear( particle: WasmParticleImpl, singleton: WasmSingletonImpl<T> ) = singletonClear(particle.toAddress(), singleton.toAddress()) fun <T : WasmEntity> singletonSet( particle: WasmParticleImpl, singleton: WasmSingletonImpl<T>, encoded: NullTermByteArray ) = singletonSet( particle.toAddress(), singleton.toAddress(), encoded.bytes.toWasmAddress() ) fun <T : WasmEntity> collectionRemove( particle: WasmParticleImpl, collection: WasmCollectionImpl<T>, encoded: NullTermByteArray ) = collectionRemove( particle.toAddress(), collection.toAddress(), encoded.bytes.toWasmAddress() ) fun <T : WasmEntity> collectionClear( particle: WasmParticleImpl, collection: WasmCollectionImpl<T> ) = collectionClear(particle.toAddress(), collection.toAddress()) fun <T : WasmEntity> collectionStore( particle: WasmParticleImpl, collection: WasmCollectionImpl<T>, encoded: NullTermByteArray ): String? { val wasmId = collectionStore( particle.toAddress(), collection.toAddress(), encoded.bytes.toWasmAddress() ) return wasmId.toNullableKString()?.let { _free(wasmId); it } } fun log(msg: String) = arcs.sdk.wasm.log(msg) fun onRenderOutput(particle: WasmParticleImpl, template: String?, model: NullTermByteArray?) = onRenderOutput( particle.toAddress(), template.toWasmNullableString(), model?.bytes?.toWasmAddress() ?: 0 ) fun serviceRequest( particle: WasmParticleImpl, call: String, encoded: NullTermByteArray, tag: String ) = serviceRequest( particle.toAddress(), call.toWasmString(), encoded.bytes.toWasmAddress(), tag.toWasmString() ) fun resolveUrl(url: String): String { val r: WasmString = resolveUrl(url.toWasmString()) val resolved = r.toKString() _free(r) return resolved } }
java/arcs/sdk/wasm/WasmRuntimeClient.kt
3290636075
package com.brianegan.bansa.todoList import com.brianegan.bansa.Reducer import com.github.andrewoma.dexx.kollection.toImmutableList val applicationReducer = Reducer <ApplicationState>{ state, action -> when (action) { is INIT -> ApplicationState() is ADD -> if (state.newTodoMessage.length > 0) { state.copy( newTodoMessage = "", todos = state.todos.plus(Todo(action.message))) } else { state } is REMOVE -> state.copy( todos = state.todos.filter({ it.id.equals(action.id) }).toImmutableList()) is TOGGLE_TODO -> state.copy( todos = state.todos.map({ if (it.id.equals(action.id)) { it.copy(completed = action.completed) } else { it } }).toImmutableList()) is UPDATE_NEW_TODO_MESSAGE -> state.copy( newTodoMessage = action.message) else -> state } }
examples/todoList/src/main/kotlin/com/brianegan/bansa/todoList/applicationReducer.kt
741271802
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.codegen import org.gradle.kotlin.dsl.support.loggerFor import org.gradle.kotlin.dsl.support.compileToDirectory import org.gradle.kotlin.dsl.support.zipTo import com.google.common.annotations.VisibleForTesting import org.gradle.api.internal.file.temp.TemporaryFileProvider import java.io.File @VisibleForTesting fun generateApiExtensionsJar( temporaryFileProvider: TemporaryFileProvider, outputFile: File, gradleJars: Collection<File>, gradleApiMetadataJar: File, onProgress: () -> Unit ) { ApiExtensionsJarGenerator( temporaryFileProvider, gradleJars, gradleApiMetadataJar, onProgress ).generate(outputFile) } private class ApiExtensionsJarGenerator( val temporaryFileProvider: TemporaryFileProvider, val gradleJars: Collection<File>, val gradleApiMetadataJar: File, val onProgress: () -> Unit = {} ) { fun generate(outputFile: File) { val tempDir = tempDirFor(outputFile) compileExtensionsTo(tempDir) zipTo(outputFile, tempDir) } private fun tempDirFor(outputFile: File): File = temporaryFileProvider.createTemporaryDirectory(outputFile.nameWithoutExtension, outputFile.extension).apply { deleteOnExit() } private fun compileExtensionsTo(outputDir: File) { compileKotlinApiExtensionsTo( outputDir, sourceFilesFor(outputDir), classPath = gradleJars ) onProgress() } private fun sourceFilesFor(outputDir: File) = gradleApiExtensionsSourceFilesFor(outputDir) + builtinPluginIdExtensionsSourceFileFor(outputDir) private fun gradleApiExtensionsSourceFilesFor(outputDir: File) = writeGradleApiKotlinDslExtensionsTo(outputDir, gradleJars, gradleApiMetadataJar).also { onProgress() } private fun builtinPluginIdExtensionsSourceFileFor(outputDir: File) = generatedSourceFile(outputDir, "BuiltinPluginIdExtensions.kt").apply { writeBuiltinPluginIdExtensionsTo(this, gradleJars) onProgress() } private fun generatedSourceFile(outputDir: File, fileName: String) = File(outputDir, sourceFileName(fileName)).apply { parentFile.mkdirs() } private fun sourceFileName(fileName: String) = "$packageDir/$fileName" private val packageDir = kotlinDslPackagePath } internal fun compileKotlinApiExtensionsTo( outputDirectory: File, sourceFiles: Collection<File>, classPath: Collection<File>, logger: org.slf4j.Logger = loggerFor<ApiExtensionsJarGenerator>() ) { val success = compileToDirectory( outputDirectory, "gradle-api-extensions", sourceFiles, logger, classPath = classPath ) if (!success) { throw IllegalStateException( "Unable to compile Gradle Kotlin DSL API Extensions Jar\n" + "\tFrom:\n" + sourceFiles.joinToString("\n\t- ", prefix = "\t- ", postfix = "\n") + "\tSee compiler logs for details." ) } }
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/codegen/ApiExtensionsJar.kt
1009188648
package ru.ifmo.rain.adsl enum class Subsystems { CONTAINER_BASE_CLASS LAYOUTS PROPERTIES UI_CLASS LISTENER_HELPERS }
src/ru/ifmo/rain/adsl/Subsystems.kt
707448833
package ${package}.days import nl.jstege.adventofcode.aoccommon.utils.DayTester class Day01Test : DayTester(Day01())
aoc-archetype/src/main/resources/archetype-resources/src/test/kotlin/days/Day01Test.kt
3398643272
package nl.jstege.adventofcode.aoc2016.days import nl.jstege.adventofcode.aoccommon.days.Day import nl.jstege.adventofcode.aoccommon.utils.extensions.highestOneBit import nl.jstege.adventofcode.aoccommon.utils.extensions.log import nl.jstege.adventofcode.aoccommon.utils.extensions.pow import kotlin.math.max /** * * @author Jelle Stege */ class Day19 : Day(title = "An Elephant Named Joseph") { override fun first(input: Sequence<String>): Any { return input.first().toInt().let { 2 * (it - it.highestOneBit()) + 1 } } override fun second(input: Sequence<String>): Any { return input.first().toInt().let { i -> (3 pow log(i, 3)).let { p -> i - p + max(i - 2 * p, 0) } } } }
aoc-2016/src/main/kotlin/nl/jstege/adventofcode/aoc2016/days/Day19.kt
4014397704
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.core.layers.models.attention import com.kotlinnlp.simplednn.core.arrays.AugmentedArray import com.kotlinnlp.simplednn.core.functionalities.activations.ActivationFunction import com.kotlinnlp.simplednn.core.functionalities.activations.SoftmaxBase import com.kotlinnlp.simplednn.core.layers.Layer import com.kotlinnlp.simplednn.core.layers.LayerType import com.kotlinnlp.simplednn.core.layers.helpers.RelevanceHelper import com.kotlinnlp.simplednn.core.layers.models.attention.attentionmechanism.AttentionMechanismLayer import com.kotlinnlp.simplednn.core.layers.models.attention.attentionmechanism.AttentionMechanismLayerParameters import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray import com.kotlinnlp.simplednn.simplemath.ndarray.Shape import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory /** * The Attention Layer Structure. * * @property inputArrays the input arrays of the layer * @param inputType the input array type (default Dense) * @param params the parameters which connect the input to the output * @param activation the activation function of the layer (default SoftmaxBase) * @property dropout the probability of dropout */ internal class AttentionLayer<InputNDArrayType : NDArray<InputNDArrayType>>( val inputArrays: List<AugmentedArray<InputNDArrayType>>, inputType: LayerType.Input, val attentionArrays: List<AugmentedArray<DenseNDArray>>, override val params: AttentionMechanismLayerParameters, activation: ActivationFunction? = SoftmaxBase() ) : Layer<InputNDArrayType>( inputArray = AugmentedArray(params.inputSize), // empty array (it should not be used) inputType = inputType, outputArray = AugmentedArray(values = DenseNDArrayFactory.zeros(Shape(inputArrays.first().size))), params = params, activationFunction = activation, dropout = 0.0 ) { /** * The helper which executes the forward */ override val forwardHelper = AttentionForwardHelper(layer = this) /** * The helper which executes the backward */ override val backwardHelper = AttentionBackwardHelper(layer = this) /** * The helper which calculates the relevance */ override val relevanceHelper: RelevanceHelper? = null /** * The attention mechanism. */ internal val attentionMechanism = AttentionMechanismLayer( inputArrays = this.attentionArrays, inputType = inputType, params = this.params, activation = SoftmaxBase() ).apply { setParamsErrorsCollector([email protected]()) } /** * The attention scores. */ val attentionScores: AugmentedArray<DenseNDArray> get() = this.attentionMechanism.outputArray /** * The attention matrix. */ val attentionMatrix: AugmentedArray<DenseNDArray> get() = this.attentionMechanism.attentionMatrix /** * Essential requirements. */ init { require(this.inputArrays.isNotEmpty()) { "The input array cannot be empty." } require(this.attentionArrays.isNotEmpty()) { "The attention array cannot be empty." } require(this.inputArrays.size == attentionArrays.size) { "The input array must have the same length of the attention array." } this.inputArrays.first().size.let { inputSize -> this.inputArrays.forEach { require(it.size == inputSize) } } } }
src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/attention/AttentionLayer.kt
2036443495
package org.wordpress.android.ui interface ScrollableViewInitializedListener { fun onScrollableViewInitialized(containerId: Int) }
WordPress/src/main/java/org/wordpress/android/ui/ScrollableViewInitializedListener.kt
2756538180
// 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.caches.resolve import org.jetbrains.kotlin.analyzer.ModuleInfo import org.jetbrains.kotlin.analyzer.PlatformAnalysisParameters import org.jetbrains.kotlin.analyzer.ResolverForModuleFactory import org.jetbrains.kotlin.analyzer.ResolverForProject import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.context.ProjectContext import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.descriptors.PackageFragmentProvider import org.jetbrains.kotlin.extensions.ApplicationExtensionDescriptor import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.IdeaModuleInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.LibraryInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.SdkInfo import org.jetbrains.kotlin.idea.caches.resolve.BuiltInsCacheKey import org.jetbrains.kotlin.platform.IdePlatformKind import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.resolve.TargetEnvironment import org.jetbrains.kotlin.storage.StorageManager interface IdePlatformKindResolution { val kind: IdePlatformKind fun getKeyForBuiltIns(moduleInfo: ModuleInfo, sdkInfo: SdkInfo?, stdlibInfo: LibraryInfo?): BuiltInsCacheKey fun createBuiltIns( moduleInfo: IdeaModuleInfo, projectContext: ProjectContext, resolverForProject: ResolverForProject<IdeaModuleInfo>, sdkDependency: SdkInfo?, stdlibDependency: LibraryInfo? ): KotlinBuiltIns fun createResolverForModuleFactory( settings: PlatformAnalysisParameters, environment: TargetEnvironment, platform: TargetPlatform ): ResolverForModuleFactory fun createKlibPackageFragmentProvider( moduleInfo: ModuleInfo, storageManager: StorageManager, languageVersionSettings: LanguageVersionSettings, moduleDescriptor: ModuleDescriptor ): PackageFragmentProvider? = null companion object : ApplicationExtensionDescriptor<IdePlatformKindResolution>( "org.jetbrains.kotlin.idePlatformKindResolution", IdePlatformKindResolution::class.java ) { private val CACHED_RESOLUTION_SUPPORT by lazy { val allPlatformKinds = IdePlatformKind.ALL_KINDS val groupedResolution = getInstances().groupBy { it.kind }.mapValues { it.value.single() } for (kind in allPlatformKinds) { if (kind !in groupedResolution) { throw IllegalStateException( "Resolution support for the platform '$kind' is missing. " + "Implement 'IdePlatformKindResolution' for it." ) } } groupedResolution } fun getResolution(kind: IdePlatformKind): IdePlatformKindResolution { return CACHED_RESOLUTION_SUPPORT[kind] ?: error("Unknown platform $this") } } } val IdePlatformKind.resolution: IdePlatformKindResolution get() = IdePlatformKindResolution.getResolution(this)
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/caches/resolve/IdePlatformKindResolution.kt
2311402871
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.kotlin import com.intellij.psi.* import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.asJava.elements.KtLightElement import org.jetbrains.kotlin.asJava.elements.KtLightMethod import org.jetbrains.kotlin.asJava.elements.isGetter import org.jetbrains.kotlin.asJava.elements.isSetter import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.utils.SmartList import org.jetbrains.uast.* import org.jetbrains.uast.kotlin.psi.UastKotlinPsiParameter @ApiStatus.Internal open class KotlinUMethod( psi: PsiMethod, final override val sourcePsi: KtDeclaration?, givenParent: UElement? ) : KotlinAbstractUElement(givenParent), UMethod, UAnchorOwner, PsiMethod by psi { constructor( psi: KtLightMethod, givenParent: UElement? ) : this(psi, getKotlinMemberOrigin(psi), givenParent) override val uastParameters: List<UParameter> by lz { fun parameterOrigin(psiParameter: PsiParameter?): KtElement? = when (psiParameter) { is KtLightElement<*, *> -> psiParameter.kotlinOrigin is UastKotlinPsiParameter -> psiParameter.ktParameter else -> null } val lightParams = psi.parameterList.parameters val receiver = receiverTypeReference ?: return@lz lightParams.map { KotlinUParameter(it, parameterOrigin(it), this) } val receiverLight = lightParams.firstOrNull() ?: return@lz emptyList() val uParameters = SmartList<UParameter>(KotlinReceiverUParameter(receiverLight, receiver, this)) lightParams.drop(1).mapTo(uParameters) { KotlinUParameter(it, parameterOrigin(it), this) } uParameters } override val psi: PsiMethod = unwrap<UMethod, PsiMethod>(psi) override val javaPsi = psi override fun getSourceElement() = sourcePsi ?: this private val kotlinOrigin = getKotlinMemberOrigin(psi.originalElement) ?: sourcePsi override fun getContainingFile(): PsiFile? { kotlinOrigin?.containingFile?.let { return it } return unwrapFakeFileForLightClass(psi.containingFile) } override fun getNameIdentifier() = UastLightIdentifier(psi, kotlinOrigin) override val uAnnotations: List<UAnnotation> by lz { // NB: we can't use sourcePsi.annotationEntries directly due to annotation use-site targets. The given `psi` as a light element, // which spans regular function, property accessors, etc., is already built with targeted annotation. baseResolveProviderService.getPsiAnnotations(psi) .mapNotNull { (it as? KtLightElement<*, *>)?.kotlinOrigin as? KtAnnotationEntry } .map { baseResolveProviderService.baseKotlinConverter.convertAnnotation(it, this) } } protected val receiverTypeReference by lz { when (sourcePsi) { is KtCallableDeclaration -> sourcePsi is KtPropertyAccessor -> sourcePsi.property else -> null }?.receiverTypeReference } override val uastAnchor: UIdentifier? by lz { val identifierSourcePsi = when (val sourcePsi = sourcePsi) { is PsiNameIdentifierOwner -> sourcePsi.nameIdentifier is KtObjectDeclaration -> sourcePsi.getObjectKeyword() is KtPropertyAccessor -> sourcePsi.namePlaceholder else -> sourcePsi?.navigationElement } KotlinUIdentifier(nameIdentifier, identifierSourcePsi, this) } override val uastBody: UExpression? by lz { if (kotlinOrigin?.canAnalyze() != true) return@lz null // EA-137193 val bodyExpression = when (sourcePsi) { is KtFunction -> sourcePsi.bodyExpression is KtPropertyAccessor -> sourcePsi.bodyExpression is KtProperty -> when { psi is KtLightMethod && psi.isGetter -> sourcePsi.getter?.bodyExpression psi is KtLightMethod && psi.isSetter -> sourcePsi.setter?.bodyExpression else -> null } else -> null } ?: return@lz null wrapExpressionBody(this, bodyExpression) } override val returnTypeReference: UTypeReferenceExpression? by lz { (sourcePsi as? KtCallableDeclaration)?.typeReference?.let { KotlinUTypeReferenceExpression(it, this) { javaPsi.returnType ?: UastErrorType } } } companion object { fun create( psi: KtLightMethod, givenParent: UElement? ): UMethod { val kotlinOrigin = psi.kotlinOrigin return when { kotlinOrigin is KtConstructor<*> -> KotlinConstructorUMethod(kotlinOrigin.containingClassOrObject, psi, givenParent) kotlinOrigin is KtParameter && kotlinOrigin.getParentOfType<KtClass>(true)?.isAnnotation() == true -> KotlinUAnnotationMethod(psi, givenParent) else -> KotlinUMethod(psi, givenParent) } } } }
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/declarations/KotlinUMethod.kt
3125758157
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.introduce.introduceParameter import com.intellij.codeInsight.template.impl.TemplateManagerImpl import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.editor.impl.DocumentMarkupModel import com.intellij.openapi.editor.markup.EffectType import com.intellij.openapi.editor.markup.HighlighterTargetArea import com.intellij.openapi.editor.markup.MarkupModel import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.ui.JBColor import com.intellij.ui.NonFocusableCheckBox import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.psi.unifier.toRange import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinValVar import org.jetbrains.kotlin.idea.refactoring.introduce.AbstractKotlinInplaceIntroducer import org.jetbrains.kotlin.idea.refactoring.introduce.introduceVariable.KotlinInplaceVariableIntroducer import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext import org.jetbrains.kotlin.psi.psiUtil.getValueParameterList import org.jetbrains.kotlin.psi.psiUtil.getValueParameters import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.typeUtil.supertypes import java.awt.Color import javax.swing.JCheckBox class KotlinInplaceParameterIntroducer( val originalDescriptor: IntroduceParameterDescriptor, val parameterType: KotlinType, val suggestedNames: Array<out String>, project: Project, editor: Editor ) : AbstractKotlinInplaceIntroducer<KtParameter>( null, originalDescriptor.originalRange.elements.single() as KtExpression, originalDescriptor.occurrencesToReplace.map { it.elements.single() as KtExpression }.toTypedArray(), INTRODUCE_PARAMETER, project, editor ) { companion object { private val LOG = Logger.getInstance(KotlinInplaceParameterIntroducer::class.java) } enum class PreviewDecorator { FOR_ADD() { override val textAttributes: TextAttributes = with(TextAttributes()) { effectType = EffectType.ROUNDED_BOX effectColor = JBColor.RED this } }, FOR_REMOVAL() { override val textAttributes: TextAttributes = with(TextAttributes()) { effectType = EffectType.STRIKEOUT effectColor = Color.BLACK this } }; protected abstract val textAttributes: TextAttributes fun applyToRange(range: TextRange, markupModel: MarkupModel) { markupModel.addRangeHighlighter( range.startOffset, range.endOffset, 0, textAttributes, HighlighterTargetArea.EXACT_RANGE ) } } private inner class Preview(addedParameter: KtParameter?, currentName: String?) { private val _rangesToRemove = ArrayList<TextRange>() var addedRange: TextRange? = null private set var text: String = "" private set val rangesToRemove: List<TextRange> get() = _rangesToRemove init { val templateState = TemplateManagerImpl.getTemplateState(myEditor) val currentType = if (templateState?.template != null) { templateState.getVariableValue(KotlinInplaceVariableIntroducer.TYPE_REFERENCE_VARIABLE_NAME)?.text } else null val builder = StringBuilder() with(descriptor) { (callable as? KtFunction)?.receiverTypeReference?.let { receiverTypeRef -> builder.append(receiverTypeRef.text).append('.') if (!descriptor.withDefaultValue && receiverTypeRef in parametersToRemove) { _rangesToRemove.add(TextRange(0, builder.length)) } } builder.append(callable.name) val parameters = callable.getValueParameters() builder.append("(") for (i in parameters.indices) { val parameter = parameters[i] val parameterText = if (parameter == addedParameter) { val parameterName = currentName ?: parameter.name val parameterType = currentType ?: parameter.typeReference!!.text descriptor = descriptor.copy(newParameterName = parameterName!!, newParameterTypeText = parameterType) val modifier = if (valVar != KotlinValVar.None) "${valVar.keywordName} " else "" val defaultValue = if (withDefaultValue) { " = ${if (newArgumentValue is KtProperty) newArgumentValue.name else newArgumentValue.text}" } else "" "$modifier$parameterName: $parameterType$defaultValue" } else parameter.text builder.append(parameterText) val range = TextRange(builder.length - parameterText.length, builder.length) if (parameter == addedParameter) { addedRange = range } else if (!descriptor.withDefaultValue && parameter in parametersToRemove) { _rangesToRemove.add(range) } if (i < parameters.lastIndex) { builder.append(", ") } } builder.append(")") if (addedRange == null) { LOG.error("Added parameter not found: ${callable.getElementTextWithContext()}") } } text = builder.toString() } } private var descriptor = originalDescriptor private var replaceAllCheckBox: JCheckBox? = null init { initFormComponents { addComponent(previewComponent) val defaultValueCheckBox = NonFocusableCheckBox(KotlinBundle.message("checkbox.text.introduce.default.value")) defaultValueCheckBox.isSelected = descriptor.withDefaultValue defaultValueCheckBox.addActionListener { descriptor = descriptor.copy(withDefaultValue = defaultValueCheckBox.isSelected) updateTitle(variable) } addComponent(defaultValueCheckBox) val occurrenceCount = descriptor.occurrencesToReplace.size if (occurrenceCount > 1) { val replaceAllCheckBox = NonFocusableCheckBox( KotlinBundle.message("checkbox.text.replace.all.occurrences.0", occurrenceCount)) replaceAllCheckBox.isSelected = true addComponent(replaceAllCheckBox) [email protected] = replaceAllCheckBox } } } override fun getActionName() = "IntroduceParameter" override fun checkLocalScope() = descriptor.callable override fun getVariable() = originalDescriptor.callable.getValueParameters().lastOrNull() override fun suggestNames(replaceAll: Boolean, variable: KtParameter?) = suggestedNames override fun createFieldToStartTemplateOn(replaceAll: Boolean, names: Array<out String>): KtParameter { return runWriteAction { with(descriptor) { val parameterList = callable.getValueParameterList() ?: (callable as KtClass).createPrimaryConstructorParameterListIfAbsent() val parameter = KtPsiFactory(myProject).createParameter("$newParameterName: $newParameterTypeText") parameterList.addParameter(parameter) } } } override fun deleteTemplateField(psiField: KtParameter) { if (psiField.isValid) { (psiField.parent as? KtParameterList)?.removeParameter(psiField) } } override fun isReplaceAllOccurrences() = replaceAllCheckBox?.isSelected ?: true override fun setReplaceAllOccurrences(allOccurrences: Boolean) { replaceAllCheckBox?.isSelected = allOccurrences } override fun getComponent() = myWholePanel override fun updateTitle(addedParameter: KtParameter?, currentName: String?) { val preview = Preview(addedParameter, currentName) val document = previewEditor.document runWriteAction { document.setText(preview.text) } val markupModel = DocumentMarkupModel.forDocument(document, myProject, true) markupModel.removeAllHighlighters() preview.rangesToRemove.forEach { PreviewDecorator.FOR_REMOVAL.applyToRange(it, markupModel) } preview.addedRange?.let { PreviewDecorator.FOR_ADD.applyToRange(it, markupModel) } revalidate() } override fun getRangeToRename(element: PsiElement): TextRange { if (element is KtProperty) return element.nameIdentifier!!.textRange.shiftRight(-element.startOffset) return super.getRangeToRename(element) } override fun createMarker(element: PsiElement): RangeMarker { if (element is KtProperty) return super.createMarker(element.nameIdentifier) return super.createMarker(element) } override fun performIntroduce() { getDescriptorToRefactor(isReplaceAllOccurrences).performRefactoring() } private fun getDescriptorToRefactor(replaceAll: Boolean): IntroduceParameterDescriptor { val originalRange = expr.toRange() return descriptor.copy( originalRange = originalRange, occurrencesToReplace = if (replaceAll) occurrences.map { it.toRange() } else listOf(originalRange), argumentValue = expr!! ) } fun switchToDialogUI() { stopIntroduce(myEditor) KotlinIntroduceParameterDialog( myProject, myEditor, getDescriptorToRefactor(true), myNameSuggestions.toTypedArray(), listOf(parameterType) + parameterType.supertypes(), KotlinIntroduceParameterHelper.Default ).show() } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinInplaceParameterIntroducer.kt
4266484839
package sample import kotlin.test.Test import kotlin.test.assertTrue object Obj { @Test fun myTest() {} }
plugins/kotlin/idea/tests/testData/gradle/testRunConfigurations/multiplatformTestsInObject/src/commonTest/kotlin/sample/SampleTests.kt
3410196275
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.nowinandroid.core.data.repository import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand import com.google.samples.apps.nowinandroid.core.model.data.UserData import kotlinx.coroutines.flow.Flow interface UserDataRepository { /** * Stream of [UserData] */ val userDataStream: Flow<UserData> /** * Sets the user's currently followed topics */ suspend fun setFollowedTopicIds(followedTopicIds: Set<String>) /** * Toggles the user's newly followed/unfollowed topic */ suspend fun toggleFollowedTopicId(followedTopicId: String, followed: Boolean) /** * Sets the user's currently followed authors */ suspend fun setFollowedAuthorIds(followedAuthorIds: Set<String>) /** * Toggles the user's newly followed/unfollowed author */ suspend fun toggleFollowedAuthorId(followedAuthorId: String, followed: Boolean) /** * Updates the bookmarked status for a news resource */ suspend fun updateNewsResourceBookmark(newsResourceId: String, bookmarked: Boolean) /** * Sets the desired theme brand. */ suspend fun setThemeBrand(themeBrand: ThemeBrand) /** * Sets the desired dark theme config. */ suspend fun setDarkThemeConfig(darkThemeConfig: DarkThemeConfig) /** * Sets whether the user has completed the onboarding process. */ suspend fun setShouldHideOnboarding(shouldHideOnboarding: Boolean) }
core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/repository/UserDataRepository.kt
3640475018
/* * AdelaideTransaction.kt * * Copyright 2018 Google * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.transit.adelaide import au.id.micolous.metrodroid.multi.Parcelize import au.id.micolous.metrodroid.transit.en1545.* import au.id.micolous.metrodroid.transit.intercode.IntercodeTransaction import au.id.micolous.metrodroid.util.ImmutableByteArray @Parcelize open class AdelaideTransaction (override val parsed: En1545Parsed): En1545Transaction() { override val lookup: En1545Lookup get() = AdelaideLookup constructor(data: ImmutableByteArray) : this(En1545Parser.parse(data, IntercodeTransaction.tripFieldsLocal)) }
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/adelaide/AdelaideTransaction.kt
1238422167
package de.visorapp.visor import android.hardware.Camera import android.hardware.camera2.CameraCharacteristics import android.hardware.camera2.CameraManager import android.os.Build import android.os.Bundle import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import androidx.preference.DropDownPreference import androidx.preference.PreferenceFragmentCompat import kotlin.math.max class SettingsActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.settings_activity) supportFragmentManager .beginTransaction() .replace(R.id.settings, SettingsFragment()) .commit() supportActionBar?.setDisplayHomeAsUpEnabled(true) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { super.onBackPressed() return true } } return super.onOptionsItemSelected(item) } class SettingsFragment : PreferenceFragmentCompat() { override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.root_preferences, rootKey) initPreviewResolutionWidth() initCameraChooser() } private fun initCameraChooser() { val visorSurface = VisorSurface.getInstance() val numberOfCameras = Camera.getNumberOfCameras() var entryValues: MutableList<CharSequence> = ArrayList() var entries: MutableList<CharSequence> = ArrayList() val manager: CameraManager var haveMain = false var haveSelfie = false if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { manager = context?.getSystemService(CAMERA_SERVICE) as CameraManager manager.cameraIdList.forEach { val cameraCharacteristics = manager.getCameraCharacteristics(it) entryValues.add(it) if (!haveMain && cameraCharacteristics.get(CameraCharacteristics.LENS_FACING) == Camera.CameraInfo.CAMERA_FACING_FRONT) { entries.add(resources.getString(R.string.main_camera)) haveMain = true } else if (!haveSelfie && cameraCharacteristics.get(CameraCharacteristics.LENS_FACING) == Camera.CameraInfo.CAMERA_FACING_BACK) { entries.add(resources.getString(R.string.selfie_camera)) haveSelfie = true } else entries.add(resources.getString(R.string.wide_or_other_camera)) } } else { entryValues = MutableList(numberOfCameras) { i -> i.toString() } entries = entryValues } val cameraIdPreference = findPreference<DropDownPreference>(resources.getString(R.string.key_preference_camera_id)) if (cameraIdPreference != null) { cameraIdPreference.entries = entries.toTypedArray() cameraIdPreference.entryValues = entryValues.toTypedArray() cameraIdPreference.setValueIndex(visorSurface.preferredCameraId) } } private fun initPreviewResolutionWidth() { val visorSurface = VisorSurface.getInstance() val availablePreviewWidths: Array<CharSequence>? = visorSurface.availablePreviewWidths val previewResolutionPreference = findPreference<DropDownPreference>(resources.getString(R.string.key_preference_preview_resolution)) if (previewResolutionPreference != null && availablePreviewWidths != null) { previewResolutionPreference.entries = availablePreviewWidths previewResolutionPreference.entryValues = availablePreviewWidths val currentPreviewWidth = visorSurface.cameraPreviewWidth val currentIndex = max(0, availablePreviewWidths.indexOf(currentPreviewWidth.toString())) previewResolutionPreference.setValueIndex(currentIndex) } } } }
app/src/main/java/de/visorapp/visor/SettingsActivity.kt
2133340971
// "Opt in for 'A' in containing file 'newFileAnnotationWithPackage.kt'" "true" // COMPILER_ARGUMENTS: -opt-in=kotlin.RequiresOptIn // WITH_STDLIB package p @RequiresOptIn annotation class A @A fun f() {} fun g() { <caret>f() }
plugins/kotlin/idea/tests/testData/quickfix/optIn/newFileAnnotationWithPackage.kt
267497062
// 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.roots import com.intellij.conversion.* import com.intellij.conversion.impl.ConversionContextImpl import com.intellij.openapi.roots.ExternalProjectSystemRegistry import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.impl.libraries.ApplicationLibraryTable import com.intellij.openapi.roots.impl.libraries.LibraryEx import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.roots.libraries.LibraryKindRegistry import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar import com.intellij.openapi.roots.libraries.PersistentLibraryKind import com.intellij.openapi.vfs.JarFileSystem import com.intellij.openapi.vfs.VirtualFile import org.jdom.Element import org.jetbrains.jps.model.JpsElement import org.jetbrains.jps.model.JpsElementFactory import org.jetbrains.jps.model.java.JavaResourceRootType import org.jetbrains.jps.model.java.JavaSourceRootType import org.jetbrains.jps.model.module.JpsModuleSourceRootType import org.jetbrains.jps.model.module.JpsTypedModuleSourceRoot import org.jetbrains.jps.model.serialization.facet.JpsFacetSerializer import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer.* import org.jetbrains.kotlin.config.getFacetPlatformByConfigurationElement import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.platforms.KotlinJavaScriptStdlibDetectorFacility import org.jetbrains.kotlin.idea.base.platforms.KotlinJvmStdlibDetectorFacility import org.jetbrains.kotlin.idea.base.projectStructure.getMigratedSourceRootTypeWithProperties import org.jetbrains.kotlin.idea.facet.KotlinFacetType import org.jetbrains.kotlin.platform.CommonPlatforms import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.isCommon import org.jetbrains.kotlin.platform.js.JsPlatforms import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.utils.PathUtil import java.util.* private val rootTypesToMigrate: List<JpsModuleSourceRootType<*>> = listOf( JavaSourceRootType.SOURCE, JavaSourceRootType.TEST_SOURCE, JavaResourceRootType.RESOURCE, JavaResourceRootType.TEST_RESOURCE ) // TODO(dsavvinov): review how it behaves in HMPP environment private val PLATFORM_TO_STDLIB_DETECTORS: Map<TargetPlatform, (Array<VirtualFile>) -> Boolean> = mapOf( JvmPlatforms.unspecifiedJvmPlatform to { roots: Array<VirtualFile> -> KotlinJvmStdlibDetectorFacility.getStdlibJar(roots.toList()) != null }, JsPlatforms.defaultJsPlatform to { roots: Array<VirtualFile> -> KotlinJavaScriptStdlibDetectorFacility.getStdlibJar(roots.toList()) != null }, CommonPlatforms.defaultCommonPlatform to { roots: Array<VirtualFile> -> roots.any { PathUtil.KOTLIN_STDLIB_COMMON_JAR_PATTERN.matcher(it.name).matches() } } ) internal class KotlinNonJvmSourceRootConverterProvider : ConverterProvider() { sealed class LibInfo { class ByXml( private val element: Element, private val conversionContext: ConversionContext, private val moduleSettings: ModuleSettings ) : LibInfo() { override val explicitKind: PersistentLibraryKind<*>? get() = LibraryKindRegistry.getInstance().findKindById(element.getAttributeValue("type")) as? PersistentLibraryKind<*> override fun getRoots(): Array<VirtualFile> { val contextImpl = conversionContext as? ConversionContextImpl ?: return VirtualFile.EMPTY_ARRAY val classRoots = contextImpl.getClassRootUrls(element, moduleSettings) val jarFileSystem = JarFileSystem.getInstance() return classRoots .map { if (it.startsWith(JarFileSystem.PROTOCOL_PREFIX)) { jarFileSystem.findFileByPath(it.substring(JarFileSystem.PROTOCOL_PREFIX.length)) } else { null } } .filter(Objects::nonNull) .toArray{ arrayOfNulls<VirtualFile>(it) } } } class ByLibrary(private val library: Library) : LibInfo() { override val explicitKind: PersistentLibraryKind<*>? get() = (library as? LibraryEx)?.kind override fun getRoots(): Array<VirtualFile> = library.getFiles(OrderRootType.CLASSES) } abstract val explicitKind: PersistentLibraryKind<*>? abstract fun getRoots(): Array<VirtualFile> val stdlibPlatform: TargetPlatform? by lazy { val roots = getRoots() for ((platform, detector) in PLATFORM_TO_STDLIB_DETECTORS) { if (detector.invoke(roots)) { return@lazy platform } } return@lazy null } } class ConverterImpl(private val context: ConversionContext) : ProjectConverter() { private val projectLibrariesByName by lazy { context.projectLibrariesSettings.projectLibraries.groupBy { it.getAttributeValue(NAME_ATTRIBUTE) } } private fun findGlobalLibrary(name: String) = ApplicationLibraryTable.getApplicationTable().getLibraryByName(name) private fun findProjectLibrary(name: String) = projectLibrariesByName[name]?.firstOrNull() private fun createLibInfo(orderEntryElement: Element, moduleSettings: ModuleSettings): LibInfo? { return when (orderEntryElement.getAttributeValue("type")) { MODULE_LIBRARY_TYPE -> { orderEntryElement.getChild(LIBRARY_TAG)?.let { LibInfo.ByXml(it, context, moduleSettings) } } LIBRARY_TYPE -> { val libraryName = orderEntryElement.getAttributeValue(NAME_ATTRIBUTE) ?: return null when (orderEntryElement.getAttributeValue(LEVEL_ATTRIBUTE)) { LibraryTablesRegistrar.PROJECT_LEVEL -> findProjectLibrary(libraryName)?.let { LibInfo.ByXml(it, context, moduleSettings) } LibraryTablesRegistrar.APPLICATION_LEVEL -> findGlobalLibrary(libraryName)?.let { LibInfo.ByLibrary(it) } else -> null } } else -> null } } override fun createModuleFileConverter(): ConversionProcessor<ModuleSettings> { return object : ConversionProcessor<ModuleSettings>() { private fun ModuleSettings.detectPlatformByFacet(): TargetPlatform? { return getFacetElement(KotlinFacetType.ID) ?.getChild(JpsFacetSerializer.CONFIGURATION_TAG) ?.getFacetPlatformByConfigurationElement() } private fun detectPlatformByDependencies(moduleSettings: ModuleSettings): TargetPlatform? { var hasCommonStdlib = false moduleSettings.orderEntries .asSequence() .mapNotNull { createLibInfo(it, moduleSettings) } .forEach { val stdlibPlatform = it.stdlibPlatform if (stdlibPlatform != null) { if (stdlibPlatform.isCommon()) { hasCommonStdlib = true } else { return stdlibPlatform } } } return if (hasCommonStdlib) CommonPlatforms.defaultCommonPlatform else null } private fun ModuleSettings.detectPlatform(): TargetPlatform { return detectPlatformByFacet() ?: detectPlatformByDependencies(this) ?: JvmPlatforms.unspecifiedJvmPlatform } private fun ModuleSettings.getSourceFolderElements(): List<Element> { val rootManagerElement = getComponentElement(ModuleSettings.MODULE_ROOT_MANAGER_COMPONENT) ?: return emptyList() return rootManagerElement .getChildren(CONTENT_TAG) .flatMap { it.getChildren(SOURCE_FOLDER_TAG) } } private fun ModuleSettings.isExternalModule(): Boolean { return when { rootElement.getAttributeValue(ExternalProjectSystemRegistry.EXTERNAL_SYSTEM_ID_KEY) != null -> true rootElement.getAttributeValue(ExternalProjectSystemRegistry.IS_MAVEN_MODULE_KEY)?.toBoolean() ?: false -> true else -> false } } override fun isConversionNeeded(settings: ModuleSettings): Boolean { if (settings.isExternalModule()) return false val hasMigrationRoots = settings.getSourceFolderElements().any { loadSourceRoot(it).rootType in rootTypesToMigrate } if (!hasMigrationRoots) { return false } val targetPlatform = settings.detectPlatform() return (!targetPlatform.isJvm()) } override fun process(settings: ModuleSettings) { for (sourceFolder in settings.getSourceFolderElements()) { val contentRoot = sourceFolder.parent as? Element ?: continue val oldSourceRoot = loadSourceRoot(sourceFolder) val (newRootType, data) = oldSourceRoot.getMigratedSourceRootTypeWithProperties() ?: continue val url = sourceFolder.getAttributeValue(URL_ATTRIBUTE)!! @Suppress("UNCHECKED_CAST") val newSourceRoot = JpsElementFactory.getInstance().createModuleSourceRoot(url, newRootType, data) as? JpsTypedModuleSourceRoot<JpsElement> ?: continue contentRoot.removeContent(sourceFolder) saveSourceRoot(contentRoot, url, newSourceRoot) } } } } } override fun getConversionDescription() = KotlinBundle.message("roots.description.text.update.source.roots.for.non.jvm.modules.in.kotlin.project") override fun createConverter(context: ConversionContext) = ConverterImpl(context) }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/roots/KotlinNonJvmSourceRootConverterProvider.kt
1988988509
package client import server.X @X("") class Client { }
plugins/kotlin/idea/tests/testData/findUsages/kotlin/findClassUsages/kotlinClassAllUsages2.1.kt
1165388642
package info.deskchan.MessageData.DeskChan import info.deskchan.core.MessageData /** * Say phrase by the character with specific intent * * If response is requested, phrase will be sent as response. Phrase will be sent to DeskChan:say otherwise. * * @property intent Intent for phrase. If provided more than one, as much phrases as intents count will be generated. * @property characterImage Emotion sprite name for character to use when saying phrase. Sprite will be selected by character system if no name provided. * @property priority Priority for message * @property tags Tags to filter phrase */ @MessageData.Tag("DeskChan:request-say") @MessageData.RequiresResponse class RequestSay : MessageData { private var intent: Any fun getIntent() = intent /** Set intents list for phrase. As much phrases as intents count will be generated. **/ fun setIntent(value: Collection<String>) { intent = value.toMutableList() } /** Set intent for phrase. **/ fun setIntent(value: Any){ intent = value.toString() } var characterImage: String? = null var priority: Long? = null set(value){ priority = java.lang.Long.max(value?: 0L, 0L) } var tags: Map<String, String>? = null constructor(intent: String){ this.intent = intent } constructor(intent: String, characterImage: String) : this(intent) { this.characterImage = characterImage } constructor(intent: String, characterImage: Say.Sprite) : this(intent) { this.characterImage = characterImage.toString() } constructor(intents: Collection<String>){ this.intent = intents } constructor(intent: Collection<String>, characterImage: String) : this(intent) { this.characterImage = characterImage } constructor(text: Collection<String>, characterImage: Say.Sprite) : this(text) { this.characterImage = characterImage.toString() } fun setCharacterImage(characterImage: Say.Sprite){ this.characterImage = characterImage.toString() } companion object { val ResponseFormat: Map<String, Any>? = null } }
src/main/kotlin/info/deskchan/MessageData/DeskChan/RequestSay.kt
353115651
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.layout import com.intellij.configurationStore.serialize import com.intellij.ui.dumpComponentBounds import com.intellij.ui.getComponentKey import com.intellij.ui.layout.migLayout.patched.* import com.intellij.util.xmlb.SkipDefaultsSerializationFilter import net.miginfocom.layout.* import org.yaml.snakeyaml.DumperOptions import org.yaml.snakeyaml.Yaml import org.yaml.snakeyaml.introspector.Property import org.yaml.snakeyaml.nodes.NodeTuple import org.yaml.snakeyaml.nodes.Tag import org.yaml.snakeyaml.representer.Representer import java.awt.Container import java.awt.Rectangle private val filter by lazy { object : Representer() { private val emptyLC = LC() private val emptyAC = AC() private val emptyCC = CC() private val emptyDimConstraint = DimConstraint() private val emptyBoundSize = BoundSize.NULL_SIZE private val xmlSerializationFilter = SkipDefaultsSerializationFilter(emptyAC, emptyCC, emptyDimConstraint, emptyBoundSize, UnitValue(Float.MIN_VALUE * Math.random().toFloat(), UnitValue.CM, "") /* no default value, some unique unit value */) override fun representJavaBeanProperty(bean: Any, property: Property, propertyValue: Any?, customTag: Tag?): NodeTuple? { if (propertyValue == null || property.name == "animSpec") { return null } if (bean is Rectangle && (!property.isWritable || property.name == "size" || property.name == "location")) { return null } if (bean is BoundSize && property.name == "unset") { return null } if (bean is UnitValue) { if (property.name == "unitString") { if (propertyValue != "px" && bean.value != 0f) { throw RuntimeException("Only px must be used") } return null } if (property.name == "unit" && bean.value != 0f) { if (propertyValue != UnitValue.PIXEL) { throw RuntimeException("Only px must be used") } return null } if (property.name == "operation" && propertyValue == 100) { // ignore static operation return null } } val emptyBean = when (bean) { is AC -> emptyAC is CC -> emptyCC is DimConstraint -> emptyDimConstraint is BoundSize -> emptyBoundSize is LC -> emptyLC else -> null } if (emptyBean != null) { val oldValue = property.get(emptyBean) if (oldValue == propertyValue) { return null } if (propertyValue is DimConstraint && propertyValue.serialize(xmlSerializationFilter) == null) { return null } } return super.representJavaBeanProperty(bean, property, propertyValue, customTag) } } } private fun dumpCellBounds(layout: MigLayout): Any { val gridField = MigLayout::class.java.getDeclaredField("grid") gridField.isAccessible = true return MigLayoutTestUtil.getRectangles(gridField.get(layout) as Grid) } @Suppress("UNCHECKED_CAST") internal fun serializeLayout(component: Container, isIncludeCellBounds: Boolean = true): String { val layout = component.layout as MigLayout val componentConstrains = LinkedHashMap<String, Any>() val componentToConstraints = layout.getComponentConstraints() for ((index, c) in component.components.withIndex()) { componentConstrains.put(getComponentKey(c, index), componentToConstraints.get(c)!!) } val dumperOptions = DumperOptions() dumperOptions.isAllowReadOnlyProperties = true dumperOptions.lineBreak = DumperOptions.LineBreak.UNIX val yaml = Yaml(filter, dumperOptions) return yaml.dump(linkedMapOf( "layoutConstraints" to layout.layoutConstraints, "rowConstraints" to layout.rowConstraints, "columnConstraints" to layout.columnConstraints, "componentConstrains" to componentConstrains, "cellBounds" to if (isIncludeCellBounds) dumpCellBounds(layout) else null, "componentBounds" to dumpComponentBounds(component) )) .replace("constaints", "constraints") .replace(" !!net.miginfocom.layout.CC", "") .replace(" !!net.miginfocom.layout.AC", "") .replace(" !!net.miginfocom.layout.LC", "") }
platform/platform-tests/testSrc/com/intellij/ui/layout/migLayoutDebugDumper.kt
46634150
package de.nicidienase.chaosflix.common.mediadata.entities.streaming import android.os.Parcel import android.os.Parcelable import androidx.annotation.Keep import com.fasterxml.jackson.annotation.JsonIgnoreProperties import kotlin.collections.HashMap @Keep @JsonIgnoreProperties(ignoreUnknown = true) data class Room( var slug: String, var schedulename: String, var thumb: String, var link: String, var display: String, var talks: Map<String, StreamEvent>?, var streams: List<Stream> ) : Parcelable { private constructor(input: Parcel) : this( slug = input.readString() ?: "", schedulename = input.readString() ?: "", thumb = input.readString() ?: "", link = input.readString() ?: "", display = input.readString() ?: "", talks = readMap(input), streams = input.createTypedArrayList<Stream>(Stream.CREATOR)?.filterNotNull() ?: emptyList()) override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeString(slug) dest.writeString(schedulename) dest.writeString(thumb) dest.writeString(link) dest.writeString(display) val talkKeys = talks?.keys?.toTypedArray() dest.writeStringArray(talkKeys) val talks = talkKeys?.map { talks?.get(it) }?.toTypedArray() dest.writeTypedArray(talks, 0) dest.writeTypedList(streams) } companion object CREATOR : Parcelable.Creator<Room> { override fun createFromParcel(`in`: Parcel): Room { return Room(`in`) } override fun newArray(size: Int): Array<Room?> { return arrayOfNulls(size) } fun readMap(input: Parcel): MutableMap<String, StreamEvent>? { val keys = input.createStringArray() val urls = input.createTypedArray(StreamEvent.CREATOR) if (keys == null || urls == null) { return null } val result = HashMap<String, StreamEvent>() for (i in 0 until keys.size - 1) { val key = keys[i] val value = urls[i] if (key != null && value != null) { result.put(key, value) } } return result } val dummyObject: Room get() { val dummy = Room( "dummy_room", "Dummy Room", "https://static.media.ccc.de/media/unknown.png", "", "Dummy Room", HashMap(), ArrayList()) dummy.streams = listOf(Stream.dummyObject) return dummy } } }
common/src/main/java/de/nicidienase/chaosflix/common/mediadata/entities/streaming/Room.kt
2560031577