path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
756M
| is_fork
bool 2
classes | languages_distribution
stringlengths 12
2.44k
⌀ | content
stringlengths 6
6.29M
| issues
float64 0
10k
⌀ | main_language
stringclasses 128
values | forks
int64 0
54.2k
| stars
int64 0
157k
| commit_sha
stringlengths 40
40
| size
int64 6
6.29M
| name
stringlengths 1
100
| license
stringclasses 104
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/castor/PrismDIDPublicKeyTests.kt | input-output-hk | 564,174,099 | false | {"Kotlin": 818473, "Gherkin": 2965, "JavaScript": 375} | package io.iohk.atala.prism.walletsdk.castor
import io.iohk.atala.prism.protos.PublicKey
import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519KeyPair
import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519PrivateKey
import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519PublicKey
import io.iohk.atala.prism.walletsdk.castor.did.prismdid.PrismDIDPublicKey
import io.iohk.atala.prism.walletsdk.castor.did.prismdid.id
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.Ignore
import org.junit.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
class PrismDIDPublicKeyTests {
@OptIn(ExperimentalCoroutinesApi::class)
@Ignore("PrismDIDPublicKey requires Secp256k1Lib to be an interface in order to mock its result. Once that is done this test can be added back.")
@Test
fun it_should_parse_proto_toPrismDIDPublicKey() = runTest {
val apollo = ApolloMock()
val seed = apollo.createRandomSeed(passphrase = "<PASSWORD>").seed
val keyPair = Ed25519KeyPair(
privateKey = Ed25519PrivateKey(ByteArray(0)),
publicKey = Ed25519PublicKey(ByteArray(0))
)
val publicKey = PrismDIDPublicKey(
apollo = ApolloMock(),
id = PrismDIDPublicKey.Usage.MASTER_KEY.id(0),
usage = PrismDIDPublicKey.Usage.MASTER_KEY,
keyData = keyPair.publicKey
)
val protoData = publicKey.toProto()
val proto = PublicKey(
id = protoData.id,
usage = protoData.usage,
keyData = protoData.keyData
)
val parsedPublicKey = PrismDIDPublicKey(
apollo = apollo,
proto = proto
)
assertEquals(parsedPublicKey.id, "master0")
assertContentEquals(parsedPublicKey.keyData.raw, publicKey.keyData.raw)
assertEquals(parsedPublicKey.usage, publicKey.usage)
}
}
| 2 | Kotlin | 0 | 5 | 0bd74856e649ca625b103f3fe0bdb6b4de4c38c3 | 1,956 | atala-prism-wallet-sdk-kmm | Apache License 2.0 |
app/src/main/java/io/horizontalsystems/bankwallet/modules/coin/tweets/CoinTweetsFragment.kt | timi10x | 473,915,173 | true | {"Kotlin": 2796704, "Shell": 2039, "Ruby": 1350} | package io.horizontalsystems.bankwallet.modules.coin.tweets
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.ViewCompositionStrategy
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.fragment.app.viewModels
import androidx.navigation.navGraphViewModels
import coil.annotation.ExperimentalCoilApi
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState
import io.horizontalsystems.bankwallet.R
import io.horizontalsystems.bankwallet.core.BaseFragment
import io.horizontalsystems.bankwallet.entities.ViewState
import io.horizontalsystems.bankwallet.modules.coin.CoinViewModel
import io.horizontalsystems.bankwallet.ui.compose.ComposeAppTheme
import io.horizontalsystems.bankwallet.ui.compose.HSSwipeRefresh
import io.horizontalsystems.bankwallet.ui.compose.components.ButtonSecondaryDefault
import io.horizontalsystems.bankwallet.ui.compose.components.CellTweet
import io.horizontalsystems.bankwallet.ui.compose.components.ListErrorView
import io.horizontalsystems.bankwallet.ui.helpers.LinkHelper
@ExperimentalCoilApi
class CoinTweetsFragment : BaseFragment() {
private val vmFactory by lazy { CoinTweetsModule.Factory(coinViewModel.fullCoin) }
private val coinViewModel by navGraphViewModels<CoinViewModel>(R.id.coinFragment)
private val viewModel by viewModels<CoinTweetsViewModel> { vmFactory }
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
return ComposeView(requireContext()).apply {
setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
setContent {
ComposeAppTheme {
CoinTweetsScreen(viewModel)
}
}
}
}
}
@ExperimentalCoilApi
@Composable
fun CoinTweetsScreen(viewModel: CoinTweetsViewModel) {
val items by viewModel.itemsLiveData.observeAsState(listOf())
val isRefreshing by viewModel.isRefreshingLiveData.observeAsState(false)
val viewState by viewModel.viewStateLiveData.observeAsState()
val context = LocalContext.current
HSSwipeRefresh(
state = rememberSwipeRefreshState(isRefreshing),
onRefresh = { viewModel.refresh() },
) {
when (val tmp = viewState) {
ViewState.Success -> {
LazyColumn(
modifier = Modifier.padding(horizontal = 16.dp),
) {
items(items) { tweet: TweetViewItem ->
Spacer(modifier = Modifier.height(12.dp))
CellTweet(tweet) {
LinkHelper.openLinkInAppBrowser(context, it.url)
}
}
item {
Box(
modifier = Modifier
.padding(vertical = 32.dp)
.fillMaxWidth(),
contentAlignment = Alignment.Center
) {
ButtonSecondaryDefault(
title = stringResource(id = R.string.CoinPage_Twitter_SeeOnTwitter),
onClick = {
LinkHelper.openLinkInAppBrowser(context, viewModel.twitterPageUrl)
}
)
}
}
}
}
is ViewState.Error -> {
if (tmp.t is TweetsProvider.UserNotFound) {
Box(modifier = Modifier.fillMaxSize()) {
Text(
modifier = Modifier.align(Alignment.Center),
text = stringResource(id = R.string.CoinPage_Twitter_NotAvailable),
color = ComposeAppTheme.colors.grey,
style = ComposeAppTheme.typography.subhead2,
)
}
} else {
ListErrorView(
stringResource(R.string.Market_SyncError)
) {
viewModel.refresh()
}
}
}
}
}
}
| 1 | null | 2 | 1 | a520b87e9553e69c76d9d48a0adb0268a53e65b2 | 4,928 | unstoppable-wallet-android | MIT License |
src/main/kotlin/service/GameService.kt | fzdayn77 | 622,851,369 | false | null | package service
import entity.*
/**
* A service layer class that provides the logic for actions
* that are not directly related to a single player
*/
class GameService(private val rootService: RootService) : AbstractRefreshableService() {
/**
* defines the number of the existing players
*/
var numberOfPlayers: Int = 4
/**
* A function that creates all the players for our game (minimum 2 players and maximum 4 players).
*
* @param playerNames a list of the players´names
* @param allCards defines the card stack that will be created
*/
fun createPlayers(playerNames: MutableList<String>, allCards: CardPile): MutableList<Player> {
// defines a list of players with the same size as the list of names
val listOfPlayers = mutableListOf<Player>()
if (playerNames.size !in 2..4)
println("ERROR: Number of Players must be 2, 3 or 4 !!")
else {
for (name in playerNames) {
listOfPlayers.add(Player(name, 0.0, allCards.drawThree()))
}
}
return listOfPlayers
}
/**
* creates the card pile with 32 shuffled cards to start the game with
*/
private fun createAllCards(): CardPile {
val cards = CardPile()
cards.cardsOnPile = defaultRandomCardList()
cards.shuffleCards()
return cards
}
/**
* Starts a new game (overwriting an active game, if it exists)
*
* @param playerNames a list of the different players´names
*
*/
fun startGame(playerNames: MutableList<String>) {
// defines the card pile
val allCards: CardPile = createAllCards()
// defines the middle deck
val middleDeck2 = allCards.drawThree()
// define the list of players
val playersList = createPlayers(playerNames, allCards)
// initialize the game
rootService.currentGame = Swimming(playersList, middleDeck2, allCards)
rootService.currentGame!!.passCounter = 0
rootService.currentGame!!.middleDeck = middleDeck2
rootService.currentGame!!.drawPile = allCards
rootService.currentGame!!.discardPile = CardPile()
rootService.currentGame!!.players = playersList
rootService.currentGame!!.moves = playersList.size
onAllRefreshable { refreshOnStartGame() }
}
/**
* This function stops the active game and takes us back to the start
* menu (this will start a new game)
*/
fun stopGame() {
if (rootService.currentGame == null)
println("ERROR: There is no existing game to be stopped !!")
else
rootService.currentGame = null
onAllRefreshable { refreshOnStopGame() }
}
/**
* a function that helps to return the value of a card as a Double number
*/
private fun cardScore(c: Card): Double {
return when (c.getValue) {
CardValue.SEVEN -> 7.0
CardValue.EIGHT -> 8.0
CardValue.NINE -> 9.0
CardValue.TEN, CardValue.JACK, CardValue.QUEEN, CardValue.KING -> 10.0
CardValue.ACE -> 11.0
else -> 0.0
}
}
/**
* calculates the score of every single player
*/
fun calculatePlayerScore(playerHandDeck: MutableList<Card>): Double {
// c1, c2 and c3 define the three cards in the hand of the player
val c1: Card = playerHandDeck[0]
val c2: Card = playerHandDeck[1]
val c3: Card = playerHandDeck[2]
// a set of a possible three cards (king or queen or jack)
val theSet = setOf(CardValue.KING, CardValue.QUEEN, CardValue.JACK)
// case1: the same suit (the ACE card is equals to 11 points)
return if (c1.getSuit == c2.getSuit && c1.getSuit == c3.getSuit) {
cardScore(c1) + cardScore(c2) + cardScore(c3)
}
// case2: three cards with th same number/value
else if (c1.getValue == c2.getValue && c1.getValue == c3.getValue) {
30.5
}
// case3: return 10 points
else if (c1.getValue in theSet && c2.getValue in theSet && c3.getValue in theSet) {
10.0
}
// case4: the normal case
else {
cardScore(c1) + cardScore(c2) + cardScore(c3) - 10.0
}
}
/**
* Creates a shuffled 32 cards list of all four suits and cards
* from 7 to Ace
*/
private fun defaultRandomCardList() = MutableList(32) { index ->
Card(
CardValue.values()[(index % 8) + 5],
CardSuit.values()[index / 8]
)
}
} | 0 | Kotlin | 0 | 0 | 838fdcdcc7e001d8584a1743329316345696423f | 4,798 | swimming-card-game | MIT License |
demo-app/src/main/java/cash/z/ecc/android/sdk/demoapp/preference/model/entry/BooleanPreferenceDefault.kt | Electric-Coin-Company | 151,763,639 | false | {"Kotlin": 1024418, "Rust": 104327} | package cash.z.ecc.android.sdk.demoapp.preference.model.entry
import cash.z.ecc.android.sdk.demoapp.preference.api.PreferenceProvider
data class BooleanPreferenceDefault(
override val key: Key,
private val defaultValue: Boolean
) : PreferenceDefault<Boolean> {
@Suppress("SwallowedException")
override suspend fun getValue(preferenceProvider: PreferenceProvider) =
preferenceProvider.getString(key)?.let {
try {
it.toBooleanStrict()
} catch (e: IllegalArgumentException) {
// TODO [#32]: Log coercion failure instead of just silently returning default
// TODO [#32]: https://github.com/zcash/zcash-android-wallet-sdk/issues/32
defaultValue
}
} ?: defaultValue
override suspend fun putValue(
preferenceProvider: PreferenceProvider,
newValue: Boolean
) {
preferenceProvider.putString(key, newValue.toString())
}
}
| 201 | Kotlin | 11 | 2 | 19cca515fb79c39365bbee8438918ea5573f5b73 | 983 | zcash-android-wallet-sdk | MIT License |
modules/feature/app/settings/impl/src/main/kotlin/kekmech/ru/feature_app_settings_impl/presentation/screens/favorites/elm/FavoritesActor.kt | tonykolomeytsev | 203,239,594 | false | {"Kotlin": 972736, "JavaScript": 8360, "Python": 2365, "Shell": 46} | package kekmech.ru.feature_app_settings_impl.presentation.screens.favorites.elm
import kekmech.ru.feature_app_settings_impl.presentation.screens.favorites.elm.FavoritesEvent.Internal
import kekmech.ru.feature_favorite_schedule_api.data.repository.FavoriteScheduleRepository
import kekmech.ru.lib_elm.actorFlow
import kotlinx.coroutines.flow.Flow
import vivid.money.elmslie.coroutines.Actor
import kekmech.ru.feature_app_settings_impl.presentation.screens.favorites.elm.FavoritesCommand as Command
import kekmech.ru.feature_app_settings_impl.presentation.screens.favorites.elm.FavoritesEvent as Event
internal class FavoritesActor(
private val favoriteScheduleRepository: FavoriteScheduleRepository,
) : Actor<Command, Event> {
override fun execute(command: Command): Flow<Event> =
when (command) {
is Command.GetAllFavorites -> actorFlow { favoriteScheduleRepository.getAllFavorites() }
.mapEvents(Internal::GetAllFavoritesSuccess)
is Command.UpdateOrInsertFavorite -> actorFlow {
favoriteScheduleRepository.updateOrInsertFavorite(
command.favoriteSchedule
)
}.mapEvents()
is Command.DeleteFavorite -> actorFlow {
favoriteScheduleRepository.deleteFavorite(
command.favoriteSchedule
)
}.mapEvents()
}
}
| 18 | Kotlin | 4 | 30 | de1929aa80141629b56a8dbc11096c6135a90c10 | 1,411 | mpeiapp | MIT License |
src/test/kotlin/io/github/projectmapk/jackson/module/kogera/ExtensionsTest.kt | ProjectMapK | 488,347,906 | false | {"Kotlin": 913410, "Java": 6932} | package io.github.projectmapk.jackson.module.kogera
import com.fasterxml.jackson.databind.JsonDeserializer
import com.fasterxml.jackson.databind.JsonSerializer
import com.fasterxml.jackson.databind.module.SimpleModule
import io.mockk.confirmVerified
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
class ExtensionsTest {
@Nested
inner class AddDeserializerTest {
val module = mockk<SimpleModule> {
every { addDeserializer(any<Class<*>>(), any()) } returns this
}
@Test
fun primitiveType() {
val mockDeserializer: JsonDeserializer<Double> = mockk()
module.addDeserializer(Double::class, mockDeserializer)
verify(exactly = 1) { module.addDeserializer(Double::class.javaPrimitiveType, mockDeserializer) }
verify(exactly = 1) { module.addDeserializer(Double::class.javaObjectType, mockDeserializer) }
}
@Test
fun objectType() {
val mockDeserializer: JsonDeserializer<Any> = mockk()
module.addDeserializer(Any::class, mockDeserializer)
verify(exactly = 1) { module.addDeserializer(Any::class.javaObjectType, mockDeserializer) }
confirmVerified(module)
}
@Test
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
fun wrapperType() {
val mockDeserializer: JsonDeserializer<Integer> = mockk()
module.addDeserializer(Integer::class, mockDeserializer)
verify(exactly = 1) { module.addDeserializer(Integer::class.javaPrimitiveType, mockDeserializer) }
verify(exactly = 1) { module.addDeserializer(Integer::class.javaObjectType, mockDeserializer) }
}
}
@Nested
inner class AddSerializerTest {
val module = mockk<SimpleModule> {
every { addSerializer(any<Class<*>>(), any()) } returns this
}
@Test
fun primitiveType() {
val mockSerializer: JsonSerializer<Double> = mockk()
module.addSerializer(Double::class, mockSerializer)
verify(exactly = 1) { module.addSerializer(Double::class.javaPrimitiveType, mockSerializer) }
verify(exactly = 1) { module.addSerializer(Double::class.javaObjectType, mockSerializer) }
}
@Test
fun objectType() {
val mockSerializer: JsonSerializer<Any> = mockk()
module.addSerializer(Any::class, mockSerializer)
verify(exactly = 1) { module.addSerializer(Any::class.javaObjectType, mockSerializer) }
confirmVerified(module)
}
@Test
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
fun wrapperType() {
val mockSerializer: JsonSerializer<Integer> = mockk()
module.addSerializer(Integer::class, mockSerializer)
verify(exactly = 1) { module.addSerializer(Integer::class.javaPrimitiveType, mockSerializer) }
verify(exactly = 1) { module.addSerializer(Integer::class.javaObjectType, mockSerializer) }
}
}
}
| 6 | Kotlin | 2 | 129 | 6cd18c04f39f11f13ac9b9bdec4459ea23ea19d6 | 3,133 | jackson-module-kogera | Apache License 2.0 |
simple-github/src/main/kotlin/com/androidhuman/example/simplegithub/ui/repo/RepositoryActivity.kt | banziha104 | 121,844,193 | false | null | package com.androidhuman.example.simplegithub.ui.repo
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.view.View
import com.androidhuman.example.simplegithub.R
import com.androidhuman.example.simplegithub.extensions.plusAssign
import com.androidhuman.example.simplegithub.rx.AutoClearedDisposable
import com.androidhuman.example.simplegithub.ui.GlideApp
import dagger.android.support.DaggerAppCompatActivity
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.activity_repository.*
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Locale
import javax.inject.Inject
class RepositoryActivity : DaggerAppCompatActivity() {
companion object {
const val KEY_USER_LOGIN = "user_login"
const val KEY_REPO_NAME = "repo_name"
}
internal val disposables = AutoClearedDisposable(this)
internal val viewDisposables
= AutoClearedDisposable(lifecycleOwner = this, alwaysClearOnStop = false)
@Inject lateinit var viewModelFactory: RepositoryViewModelFactory
lateinit var viewModel: RepositoryViewModel
internal val dateFormatInResponse = SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ssX", Locale.getDefault())
internal val dateFormatToShow = SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.getDefault())
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_repository)
viewModel = ViewModelProviders.of(
this, viewModelFactory)[RepositoryViewModel::class.java]
lifecycle += disposables
lifecycle += viewDisposables
viewDisposables += viewModel.repository
.filter { !it.isEmpty }
.map { it.value }
.observeOn(AndroidSchedulers.mainThread())
.subscribe { repository ->
GlideApp.with(this@RepositoryActivity)
.load(repository.owner.avatarUrl)
.into(ivActivityRepositoryProfile)
tvActivityRepositoryName.text = repository.fullName
tvActivityRepositoryStars.text = resources
.getQuantityString(R.plurals.star, repository.stars, repository.stars)
if (null == repository.description) {
tvActivityRepositoryDescription.setText(R.string.no_description_provided)
} else {
tvActivityRepositoryDescription.text = repository.description
}
if (null == repository.language) {
tvActivityRepositoryLanguage.setText(R.string.no_language_specified)
} else {
tvActivityRepositoryLanguage.text = repository.language
}
try {
val lastUpdate = dateFormatInResponse.parse(repository.updatedAt)
tvActivityRepositoryLastUpdate.text = dateFormatToShow.format(lastUpdate)
} catch (e: ParseException) {
tvActivityRepositoryLastUpdate.text = getString(R.string.unknown)
}
}
viewDisposables += viewModel.message
.observeOn(AndroidSchedulers.mainThread())
.subscribe { message -> showError(message) }
viewDisposables += viewModel.isContentVisible
.observeOn(AndroidSchedulers.mainThread())
.subscribe { visible -> setContentVisibility(visible) }
viewDisposables += viewModel.isLoading
.observeOn(AndroidSchedulers.mainThread())
.subscribe { isLoading ->
if (isLoading) {
showProgress()
} else {
hideProgress()
}
}
val login = intent.getStringExtra(KEY_USER_LOGIN) ?: throw IllegalArgumentException(
"No login info exists in extras")
val repo = intent.getStringExtra(KEY_REPO_NAME) ?: throw IllegalArgumentException(
"No repo info exists in extras")
disposables += viewModel.requestRepositoryInfo(login, repo)
}
private fun showProgress() {
pbActivityRepository.visibility = View.VISIBLE
}
private fun hideProgress() {
pbActivityRepository.visibility = View.GONE
}
private fun setContentVisibility(show: Boolean) {
llActivityRepositoryContent.visibility = if (show) View.VISIBLE else View.GONE
}
private fun showError(message: String) {
with(tvActivityRepositoryMessage) {
text = message
visibility = View.VISIBLE
}
}
}
| 0 | Kotlin | 0 | 1 | 53405ba475d45925d578eb42fcffef96390429f3 | 4,899 | KotlinWithLib | Apache License 2.0 |
kvision-modules/kvision-state-flow/src/main/kotlin/io/kvision/state/StateBinding.kt | nickhristov | 369,028,306 | true | {"Kotlin": 2862529, "CSS": 16908, "JavaScript": 10588, "HTML": 1858} | /*
* Copyright (c) 2017-present <NAME>
*
* 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 io.kvision.state
import io.kvision.core.Widget
import io.kvision.form.GenericFormComponent
import io.kvision.panel.SimplePanel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlin.js.Date
/**
* An extension function which binds the widget to the given state flow.
*
* @param S the state type
* @param W the widget type
* @param stateFlow the StateFlow instance
* @param removeChildren remove all children of the component
* @param runImmediately whether to run factory function immediately with the current state
* @param factory a function which re-creates the view based on the given state
*/
fun <S, W : Widget> W.bind(
stateFlow: StateFlow<S>,
removeChildren: Boolean = true,
runImmediately: Boolean = true,
factory: (W.(S) -> Unit)
): W {
return this.bind(stateFlow.observableState, removeChildren, runImmediately, factory)
}
/**
* An extension function which binds the container to the given state flow of a list of items.
*
* @param S the state type
* @param W the container type
* @param stateFlow the StateFlow instance
* @param equalizer optional custom equalizer function
* @param factory a function which re-creates the view based on the given state
*/
fun <S, W : SimplePanel> W.bindEach(
stateFlow: StateFlow<List<S>>,
equalizer: ((S, S) -> Boolean)? = null,
factory: (SimplePanel.(S) -> Unit)
): W {
return this.bindEach(stateFlow.observableState, equalizer, factory)
}
/**
* Bidirectional data binding to the MutableStateFlow instance.
* @param mutableStateFlow the MutableStateFlow instance
* @return current component
*/
fun <S, T : GenericFormComponent<S>> T.bindTo(mutableStateFlow: MutableStateFlow<S>): T {
return this.bindTo(mutableStateFlow.mutableState)
}
/**
* Bidirectional data binding to the MutableStateFlow instance.
* @param mutableStateFlow the MutableStateFlow instance
* @return current component
*/
fun <T : GenericFormComponent<String?>> T.bindTo(mutableStateFlow: MutableStateFlow<String>): T {
return this.bindTo(mutableStateFlow.mutableState)
}
/**
* Bidirectional data binding to the MutableStateFlow instance.
* @param mutableStateFlow the MutableStateFlow instance
* @return current component
*/
fun <T : GenericFormComponent<Number?>> T.bindTo(mutableStateFlow: MutableStateFlow<Int?>): T {
return this.bindTo(mutableStateFlow.mutableState)
}
/**
* Bidirectional data binding to the MutableStateFlow instance.
* @param mutableStateFlow the MutableStateFlow instance
* @return current component
*/
fun <T : GenericFormComponent<Number?>> T.bindTo(mutableStateFlow: MutableStateFlow<Int>): T {
return this.bindTo(mutableStateFlow.mutableState)
}
/**
* Bidirectional data binding to the MutableStateFlow instance.
* @param mutableStateFlow the MutableStateFlow instance
* @return current component
*/
fun <T : GenericFormComponent<Number?>> T.bindTo(mutableStateFlow: MutableStateFlow<Double?>): T {
return this.bindTo(mutableStateFlow.mutableState)
}
/**
* Bidirectional data binding to the MutableStateFlow instance.
* @param mutableStateFlow the MutableStateFlow instance
* @return current component
*/
fun <T : GenericFormComponent<Number?>> T.bindTo(mutableStateFlow: MutableStateFlow<Double>): T {
return this.bindTo(mutableStateFlow.mutableState)
}
/**
* Bidirectional data binding to the MutableStateFlow instance.
* @param mutableStateFlow the MutableStateFlow instance
* @return current component
*/
fun <T : GenericFormComponent<Date?>> T.bindTo(mutableStateFlow: MutableStateFlow<Date>): T {
return this.bindTo(mutableStateFlow.mutableState)
}
| 0 | Kotlin | 0 | 0 | ea3b2b1887748599778d5f790b6a1bd353f0e194 | 4,799 | kvision | MIT License |
kotlin/accumulate/src/main/kotlin/Accumulate.kt | Fyzxs | 78,318,942 | false | null | object Accumulate {
fun <T, U> accumulate(input: List<T>, transform: (T) -> U): List<U> {
val list = mutableListOf<U>()
input.forEach { list.add(transform(it)) }
return list
}
} | 0 | Kotlin | 0 | 0 | ab5b95ef4b75ad103ebbd577101dee61891131f6 | 209 | exercism.io | MIT License |
domain/src/main/kotlin/com/sortinghat/backend/domain/behaviors/Visitable.kt | the-sortinghat | 529,660,037 | false | {"Kotlin": 193813, "Dockerfile": 1130} | package com.sortinghat.backend.domain.behaviors
interface Visitable {
fun accept(v: Visitor)
fun children(): Iterable<Visitable>
}
| 0 | Kotlin | 1 | 0 | 95695a1808e477ce67d8257891f4fa9be21f8cce | 141 | backend | MIT License |
app/src/main/java/com/app/turingrobot/core/dagger/component/AppComponent.kt | flex-col | 105,131,404 | false | {"Kotlin": 80664, "Java": 12646} | package com.app.turingrobot.core.dagger.component
import com.app.turingrobot.core.dagger.module.AppModule
import com.app.turingrobot.ui.core.BaseActivity
import com.app.turingrobot.ui.core.BaseFragment
import javax.inject.Singleton
import dagger.Component
/*
* Created by sword on 2017/3/27.
*/
@Singleton
@Component(modules = arrayOf(AppModule::class))
interface AppComponent {
fun inject(activity: BaseActivity)
fun inject(fragment: BaseFragment)
}
| 0 | Kotlin | 0 | 0 | 420c3a6caa0272473abab9a5b4da001c9eea75c3 | 469 | robot | MIT License |
elytra-sdk/src/main/kotlin/io/elytra/sdk/network/protocol/codecs/play/outbound/TitleCodec.kt | WinX64 | 253,052,856 | true | {"Kotlin": 219826, "Python": 2433} | package io.elytra.sdk.network.protocol.codecs.play.outbound
import com.flowpowered.network.Codec
import io.elytra.api.chat.TextComponent
import io.elytra.sdk.network.protocol.message.play.outbound.TitleMessage
import io.elytra.sdk.network.protocol.message.play.outbound.TitleMessage.Type
import io.elytra.sdk.network.utils.minecraft
import io.netty.buffer.ByteBuf
class TitleCodec : Codec<TitleMessage> {
override fun encode(buffer: ByteBuf, message: TitleMessage): ByteBuf {
val type = message.type
buffer.minecraft.writeEnumValue(type)
if (type == Type.TITLE || type == Type.SUBTITLE || type == Type.ACTIONBAR)
buffer.minecraft.writeTextComponent(message.message!!)
if (type == Type.TIMES) {
buffer.writeInt(message.fadeInTime)
buffer.writeInt(message.displayTime)
buffer.writeInt(message.fadeOutTime)
}
return buffer
}
override fun decode(buffer: ByteBuf): TitleMessage {
val type = buffer.minecraft.readEnumValue(Type::class.java)
var message: TextComponent? = null
var fadeInTime = 0
var displayTime = 0
var fadeOutTime = 0
if (type == Type.TITLE || type == Type.SUBTITLE || type == Type.ACTIONBAR)
message = buffer.minecraft.readTextComponent()
if (type == Type.TIMES) {
fadeInTime = buffer.readInt()
displayTime = buffer.readInt()
fadeOutTime = buffer.readInt()
}
return TitleMessage(type, message, fadeInTime, displayTime, fadeOutTime)
}
}
| 0 | Kotlin | 0 | 0 | 58a6516261697f7a1ca7c1a9457007ffdb4b15b1 | 1,590 | Elytra | MIT License |
app/src/main/java/com/android/viewpager2tabsample/Tab3Fragment.kt | chakangost | 247,870,099 | false | null | package com.android.viewpager2tabsample
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
class Tab3Fragment : Fragment() {
override fun onCreateView (
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_tab3, container)
}
companion object {
fun create(): Tab3Fragment {
return Tab3Fragment()
}
}
} | 0 | Kotlin | 1 | 13 | 06d3bf6959e2f4739b72ec119b7f2262258bb6ab | 562 | Viewpager2TabLayoutSample | Apache License 2.0 |
app/src/main/java/com/cameronvwilliams/raise/ui/offline/view/OfflineFragment.kt | RaiseSoftware | 119,627,507 | false | null | package com.cameronvwilliams.raise.ui.offline.view
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.IdRes
import com.cameronvwilliams.raise.R
import com.cameronvwilliams.raise.data.model.DeckType
import com.cameronvwilliams.raise.ui.BaseFragment
import com.cameronvwilliams.raise.ui.MainActivity
import com.cameronvwilliams.raise.ui.offline.presenter.OfflinePresenter
import com.jakewharton.rxbinding2.view.clicks
import com.jakewharton.rxbinding2.widget.checkedChanges
import io.reactivex.Observable
import kotlinx.android.synthetic.main.intro_offline_fragment.*
import javax.inject.Inject
class OfflineFragment: BaseFragment() {
@Inject
lateinit var window: MainActivity
@Inject
lateinit var presenter: OfflinePresenter
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.intro_offline_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
window.setOfflineMode()
presenter.onViewCreated(this)
}
override fun onDestroyView() {
super.onDestroyView()
presenter.onViewDestroyed()
}
override fun onBackPressed(): Boolean {
return presenter.onBackPressed()
}
fun closeClicks() = closeButton.clicks()
fun startClicks() = startButton.clicks()
fun deckTypeChanges(): Observable<DeckType> = deckTypeRadioGroup.checkedChanges()
.map(this::mapRadioToDeckType)
fun enableStartButton() {
startButton.isEnabled = true
}
fun disableStartButton() {
startButton.isEnabled = false
}
fun setSelectedDeckType(offlineDeckType: DeckType) {
val selectedId = mapDeckTypeToRadio(offlineDeckType)
selectedId?.let {
deckTypeRadioGroup.check(it)
}
}
@androidx.annotation.IdRes
private fun mapDeckTypeToRadio(deckType: DeckType): Int? {
return when (deckType) {
DeckType.FIBONACCI -> R.id.fibonacciRadio
DeckType.T_SHIRT -> R.id.tshirtRadio
else -> null
}
}
private fun mapRadioToDeckType(@IdRes radioId: Int): DeckType {
return when (radioId) {
R.id.fibonacciRadio -> DeckType.FIBONACCI
R.id.tshirtRadio -> DeckType.T_SHIRT
else -> DeckType.NONE
}
}
companion object {
fun newInstance(): OfflineFragment {
return OfflineFragment()
}
}
} | 0 | Kotlin | 0 | 4 | 3cd0786dba77645efa5508a662478e5893037919 | 2,666 | Raise-Android | MIT License |
library/src/main/java/com/egeniq/androidtvprogramguide/timeline/ProgramGuideTimelineRow.kt | egeniq | 202,347,008 | false | {"Kotlin": 138465} | /*
* Copyright (c) 2020, Egeniq
*
* 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.egeniq.androidtvprogramguide.timeline
import android.content.Context
import android.os.Build
import android.os.Parcel
import android.os.Parcelable
import android.util.AttributeSet
import androidx.annotation.RequiresApi
import kotlin.math.abs
class ProgramGuideTimelineRow @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) :
ProgramGuideTimelineGridView(context, attrs, defStyle) {
companion object {
private const val FADING_EDGE_STRENGTH_START = 1.0f
}
private var scrollPosition: Int = 0
/** Returns the current scroll position */
val currentScrollOffset: Int
get() = abs(scrollPosition)
fun resetScroll() {
layoutManager?.scrollToPosition(0)
scrollPosition = 0
}
/** Scrolls horizontally to the given position. */
fun scrollTo(scrollOffset: Int, smoothScroll: Boolean) {
val dx = scrollOffset - currentScrollOffset
if (smoothScroll) {
if (layoutDirection == LAYOUT_DIRECTION_LTR) {
smoothScrollBy(dx, 0)
} else {
smoothScrollBy(-dx, 0)
}
} else {
if (layoutDirection == LAYOUT_DIRECTION_LTR) {
scrollBy(dx, 0)
} else {
scrollBy(-dx, 0)
}
}
}
override fun onScrolled(dx: Int, dy: Int) {
scrollPosition += dx
}
override fun getLeftFadingEdgeStrength(): Float {
return FADING_EDGE_STRENGTH_START
}
override fun getRightFadingEdgeStrength(): Float {
return 0f
}
// State saving part
public override fun onSaveInstanceState(): Parcelable {
//begin boilerplate code that allows parent classes to save state
val superState = super.onSaveInstanceState()
val ss = SavedState(superState)
//end
ss.scrollPosition = scrollPosition
return ss
}
public override fun onRestoreInstanceState(state: Parcelable) {
//begin boilerplate code so parent classes can restore state
if (state !is SavedState) {
super.onRestoreInstanceState(state)
return
}
super.onRestoreInstanceState(state.superState)
//end
this.scrollPosition = state.scrollPosition
}
internal class SavedState : BaseSavedState {
var scrollPosition = 0
constructor(superState: Parcelable?) : super(superState)
private constructor(source: Parcel) : super(source) {
this.scrollPosition = source.readInt()
}
@RequiresApi(Build.VERSION_CODES.N)
private constructor(source: Parcel, loader: ClassLoader?) : super(source, loader) {
this.scrollPosition = source.readInt()
}
override fun writeToParcel(out: Parcel, flags: Int) {
super.writeToParcel(out, flags)
out.writeInt(this.scrollPosition)
}
companion object {
@Suppress("unused")
@JvmField
val CREATOR: Parcelable.Creator<SavedState> =
object : Parcelable.ClassLoaderCreator<SavedState> {
override fun createFromParcel(source: Parcel): SavedState {
return SavedState(source)
}
override fun createFromParcel(
source: Parcel,
loader: ClassLoader?
): SavedState {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) SavedState(
source,
loader
) else SavedState(source)
}
override fun newArray(size: Int): Array<SavedState?> {
return arrayOfNulls(size)
}
}
}
}
}
| 2 | Kotlin | 57 | 145 | 8bfc8ce540a9528cd961f133aefa053377157054 | 4,533 | android-tv-program-guide | Apache License 2.0 |
domain/src/main/java/com/jinglebroda/domain/model/searchRecipeModel/advancedSearchGetParams/AdvancedSearchGetParams.kt | jingleBroda | 629,142,633 | false | {"Kotlin": 98477} | package com.jinglebroda.domain.model.searchRecipeModel.advancedSearchGetParams
data class AdvancedSearchGetParams(
val ingredientsString:String,
val caloriesRange:String?,
val diet:List<String>?
) | 0 | Kotlin | 0 | 0 | 856f3d611ab642c292e3b262f3e0e41752acfcc2 | 209 | Look_to_cook | MIT License |
app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/DownloadPageLoader.kt | AniFOSS | 377,170,228 | true | {"Kotlin": 4060627} | package eu.kanade.tachiyomi.ui.reader.loader
import android.app.Application
import android.net.Uri
import com.hippo.unifile.UniFile
import eu.kanade.domain.entries.manga.model.Manga
import eu.kanade.tachiyomi.data.database.models.manga.toDomainChapter
import eu.kanade.tachiyomi.data.download.manga.MangaDownloadManager
import eu.kanade.tachiyomi.data.download.manga.MangaDownloadProvider
import eu.kanade.tachiyomi.source.MangaSource
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter
import eu.kanade.tachiyomi.ui.reader.model.ReaderPage
import rx.Observable
import uy.kohesive.injekt.injectLazy
import java.io.File
/**
* Loader used to load a chapter from the downloaded chapters.
*/
class DownloadPageLoader(
private val chapter: ReaderChapter,
private val manga: Manga,
private val source: MangaSource,
private val downloadManager: MangaDownloadManager,
private val downloadProvider: MangaDownloadProvider,
) : PageLoader() {
// Needed to open input streams
private val context: Application by injectLazy()
/**
* Returns an observable containing the pages found on this downloaded chapter.
*/
override fun getPages(): Observable<List<ReaderPage>> {
val dbChapter = chapter.chapter
val chapterPath = downloadProvider.findChapterDir(dbChapter.name, dbChapter.scanlator, manga.title, source)
return if (chapterPath?.isFile == true) {
getPagesFromArchive(chapterPath)
} else {
getPagesFromDirectory()
}
}
private fun getPagesFromArchive(chapterPath: UniFile): Observable<List<ReaderPage>> {
val loader = ZipPageLoader(File(chapterPath.filePath!!))
return loader.getPages()
}
private fun getPagesFromDirectory(): Observable<List<ReaderPage>> {
return downloadManager.buildPageList(source, manga, chapter.chapter.toDomainChapter()!!)
.map { pages ->
pages.map { page ->
ReaderPage(page.index, page.url, page.imageUrl) {
context.contentResolver.openInputStream(page.uri ?: Uri.EMPTY)!!
}.apply {
status = Page.State.READY
}
}
}
}
override fun getPage(page: ReaderPage): Observable<Page.State> {
return Observable.just(Page.State.READY)
}
}
| 1 | Kotlin | 0 | 0 | 08787976b43da6e02207081e1ecccb7fcd89c307 | 2,432 | aniyomi | Apache License 2.0 |
graphics/src/main/java/com/mindforge/graphics/interaction/Interactive.kt | juliuskunze | 48,072,938 | false | {"Kotlin": 178564, "Java": 16634} | package com.mindforge.graphics.interaction
interface Interactive<out T> {
val content: T
} | 0 | Kotlin | 3 | 12 | c1e767b00ef5ee5c3387c613c795f2dcf161c103 | 95 | subnote | MIT License |
app/src/main/java/com/example/customproject/database/ConcreteItem.kt | Aeth01 | 542,880,018 | false | {"Kotlin": 46369} | package com.example.customproject.database
import android.os.Parcelable
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.PrimaryKey
import kotlinx.parcelize.Parcelize
import java.lang.NumberFormatException
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
@Parcelize
@Entity(
tableName="item_table",
foreignKeys = [ForeignKey(
entity = BrandItem::class,
parentColumns = arrayOf("brandName"),
childColumns = arrayOf("brand_name"),
onDelete = ForeignKey.CASCADE,
onUpdate = ForeignKey.CASCADE
)]
)
data class ConcreteItem(
@PrimaryKey(autoGenerate = true) val itemId : Int = 0,
@ColumnInfo(name="item_name") val name : String,
@ColumnInfo(name="brand_name", index = true) val brand : String = "",
@ColumnInfo(name="price") val price : Float,
@ColumnInfo(name="date") val date : String,
@ColumnInfo(name="seller") val seller : String
) : Parcelable {
companion object {
// check date valid
@Throws(ParseException::class)
fun validDate(date : String) : Boolean {
// if parse successful, return true. Else throw parse exception
val sdf = SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH)
sdf.isLenient = false
sdf.parse(date)
return true
}
// check price is valid
@Throws(NumberFormatException::class)
fun validPrice(price : String) : Boolean {
if (price.toFloat() <= 0F) {
throw NumberFormatException()
}
return true
}
}
} | 0 | Kotlin | 0 | 1 | 46b80a8aa205c2df5a291ae50b0a8a9172b7270e | 1,679 | COS30017-Custom-Project | MIT License |
android/khajit/app/src/main/java/com/project/khajit_app/data/models/CreateArticleResponseModel.kt | bounswe | 170,124,936 | false | {"Kotlin": 416637, "Python": 210731, "SCSS": 184849, "CSS": 97799, "Less": 78481, "JavaScript": 56513, "HTML": 35601, "Dockerfile": 1032, "Shell": 76} | package com.project.khajit_app.data.models
data class CreateArticleResponseModel( val id: Int?,
val title:String?,
val content : String?,
val is_public : Boolean?,
val author : Int,
val created_date : String?,
val detail : String? )
| 31 | Kotlin | 2 | 9 | 40370c1e8ff7f49dead59034e8baab8a99e3adbf | 470 | bounswe2019group1 | MIT License |
common/src/test/com/natpryce/snodge/form/MutateValueTest.kt | npryce | 17,959,152 | false | null | package com.natpryce.snodge.form
import com.natpryce.snodge.always
import kotlin.random.Random
import kotlin.test.Test
import kotlin.test.assertEquals
class MutateValueTest {
@Test
fun mutate_value_of_form_field() {
val original = form("a" to "a1", "b" to "b1", "a" to "a2")
val mutants = mutateValue(always("x")).invoke(Random.Default, original).map { it.value }.toSet()
assertEquals(
setOf(
form("a" to "x", "b" to "b1", "a" to "a2"),
form("a" to "a1", "b" to "x", "a" to "a2"),
form("a" to "a1", "b" to "b1", "a" to "x")
),
mutants)
}
}
| 1 | Kotlin | 8 | 150 | f6da35610c0c33da5a781efe38237cb9a4b6ca23 | 681 | snodge | Apache License 2.0 |
app/src/test/java/com/coinninja/coinkeeper/model/dto/AddressDTOTest.kt | coinninjadev | 175,276,289 | false | null | package com.coinninja.coinkeeper.model.dto
import app.coinninja.cn.libbitcoin.model.DerivationPath
import com.coinninja.coinkeeper.model.db.Address
import com.google.common.truth.Truth.assertThat
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.junit.MockitoJUnitRunner
@RunWith(MockitoJUnitRunner::class)
class AddressDTOTest {
@Test
fun test_display_derivation_path() {
val pubKey = "<KEY>"
val addr = "-- address --"
val address: Address = mock()
whenever(address.derivationPath).thenReturn(DerivationPath(49, 0, 0, 0, 44))
whenever(address.address).thenReturn(addr)
val addressDTO = AddressDTO(address, pubKey)
assertThat(addressDTO.derivationPath).isEqualTo("M/49/0/0/0/44")
assertThat(addressDTO.address).isEqualTo(addr)
assertThat(addressDTO.uncompressedPublicKey).isEqualTo(pubKey)
}
} | 2 | Kotlin | 0 | 5 | d67d7c0b9cad27db94470231073c5d6cdda83cd0 | 1,009 | dropbit-android | MIT License |
sql/testing/src/main/kotlin/net/aquadc/persistence/sql/database.kt | Miha-x64 | 102,399,925 | false | null | package net.aquadc.persistence.sql
import net.aquadc.persistence.extended.tuple.Tuple
import net.aquadc.persistence.extended.tuple.Tuple3
import net.aquadc.persistence.extended.either.plus
import net.aquadc.persistence.extended.partial
import net.aquadc.persistence.sql.ColMeta.Companion.embed
import net.aquadc.persistence.sql.blocking.JdbcSession
import net.aquadc.persistence.sql.dialect.Dialect
import net.aquadc.persistence.struct.Schema
import net.aquadc.persistence.type.i32
import net.aquadc.persistence.type.i64
import net.aquadc.persistence.type.nullable
import net.aquadc.persistence.type.string
import java.sql.DriverManager
object SomeSchema : Schema<SomeSchema>() {
val A = "a" let string
val B = "b" let i32
val C = "c" mut i64
}
val SomeTable = tableOf(SomeSchema, "some_table", "_id", i32)
object SchWithId : Schema<SchWithId>() {
val Id = "_id" let i32
val Value = "value" let string
val MutValue = "mutValue".mut(string, default = "")
}
val TableWithId = tableOf(SchWithId, "with_id", SchWithId.Id)
object WithNested : Schema<WithNested>() {
val OwnField = "q" let string
val Nested = "w" mut SchWithId
val OtherOwnField = "e" let i64
}
val TableWithEmbed = tableOf(WithNested, "with_nested", "_id", i64) {
arrayOf(
embed(SnakeCase, Nested)
)
}
object DeeplyNested : Schema<DeeplyNested>() {
val OwnField = "own" let string
val Nested = "nest" mut WithNested
}
val TableWithDeepEmbed = tableOf(DeeplyNested, "deep", "_id", i64) {
arrayOf(
embed(SnakeCase, Nested),
embed(SnakeCase, Nested / WithNested.Nested)
)
}
val goDeeper = Tuple3(
"first", DeeplyNested,
"second", WithNullableNested,
"third", string + SomeSchema
)
val WeNeedToGoDeeper = tableOf(goDeeper, "deeper", "_id", i64) {
arrayOf(
embed(SnakeCase, First)
, embed(SnakeCase, First / DeeplyNested.Nested)
, embed(SnakeCase, First / DeeplyNested.Nested / WithNested.Nested)
, embed(SnakeCase, Second)
, embed(SnakeCase, Second / WithNullableNested.Nested, "fieldSet")
, embed(SnakeCase, Third, "which")
, embed(SnakeCase, Third % (goDeeper.run { goDeeper.Third.type }.schema as Tuple).Second, "fieldSet")
)
}
object WithNullableNested : Schema<WithNullableNested>() {
val OwnField = "q" let string
val Nested = "w" mut nullable(SchWithId)
val OtherOwnField = "e" let i64
}
val TableWithNullableEmbed = tableOf(WithNullableNested, "with_nullable_nested", "_id", i64) {
arrayOf(
embed(SnakeCase, Nested, "nested_fields")
)
}
object WithPartialNested : Schema<WithPartialNested>() {
val Nested = "nested" mut partial(SchWithId)
val OwnField = "q" let string
}
val TableWithPartialEmbed = tableOf(WithPartialNested, "with_partial_nested", "_id", i64) {
arrayOf(
embed(SnakeCase, Nested, "nested_fields")
)
}
object WithEverything : Schema<WithEverything>() {
val Nest1 = "nest1" let nullable(partial(WithPartialNested))
val Nest2 = "nest2" mut SchWithId
}
val TableWithEverything = tableOf(WithEverything, "with_everything", "_id", i64) {
arrayOf(
embed(SnakeCase, Nest1, "fields"),
embed(SnakeCase, Nest1 / WithPartialNested.Nested, "fields"),
embed(SnakeCase, Nest2)
)
}
val stringOrNullableString = string + nullable(string)
val schemaWithNullableEither = Tuple("1", stringOrNullableString, "2", nullable(stringOrNullableString))
val TableWithNullableEither = tableOf(schemaWithNullableEither, "tableContainingEither","_id", i64) {
arrayOf(
embed(SnakeCase, First, "which"),
embed(SnakeCase, Second, "whetherAndWhich")
)
}
// for Templates test
val User = Tuple("name", string, "email", string)
val UserTable = tableOf(User, "users", "_id", i64)
val Contact = Tuple("value", string, "user_id", i64)
val ContactTable = tableOf(Contact, "contacts", "_id", i64)
val TestTables = arrayOf(
SomeTable, TableWithId, TableWithEmbed, TableWithDeepEmbed, WeNeedToGoDeeper,
TableWithNullableEmbed, TableWithPartialEmbed, TableWithEverything, TableWithNullableEither,
UserTable, ContactTable
)
fun session(dialect: Dialect, url: String): JdbcSession =
JdbcSession(DriverManager.getConnection(url).also { conn ->
val stmt = conn.createStatement()
TestTables.forEach { stmt.execute(dialect.createTable(it, temporary = true)) }
stmt.close()
}, dialect)
| 11 | Kotlin | 10 | 118 | d0a804271d0aaaa6368a2addce3ef7f081f5f560 | 4,467 | Lychee | Apache License 2.0 |
app/src/test/java/com/synergy/android/test_utils/InstantLiveDataExecutor.kt | rishatyakushev | 200,054,827 | false | null | package com.synergy.android.test_utils
import androidx.arch.core.executor.TaskExecutor
object InstantLiveDataExecutor : TaskExecutor() {
override fun executeOnDiskIO(runnable: Runnable) = runnable.run()
override fun postToMainThread(runnable: Runnable) = runnable.run()
override fun isMainThread(): Boolean = true
}
| 0 | Kotlin | 0 | 0 | a6eb3c132dd691a6e881a5fb9da01b087b375542 | 332 | Synergy5K-Android | Apache License 2.0 |
diktat-rules/src/test/kotlin/org/cqfn/diktat/ruleset/utils/VariablesWithAssignmentsSearchTest.kt | akuleshov7 | 331,273,197 | true | {"Kotlin": 1249768, "TeX": 45784, "Java": 2002, "Shell": 601} | package org.cqfn.diktat.ruleset.utils
import org.cqfn.diktat.ruleset.utils.search.findAllVariablesWithAssignments
import org.cqfn.diktat.util.applyToCode
import com.pinterest.ktlint.core.ast.ElementType.FILE
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
@Suppress("UnsafeCallOnNullableType")
class VariablesWithAssignmentsSearchTest {
@Test
fun `testing proper variables search in function`() {
applyToCode("""
fun foo(a: Int) {
fun foo1() {
var o = 1
b = o
c = o
o = 15
o = 17
}
}
""".trimIndent(), 0) { node, _ ->
if (node.elementType == FILE) {
val vars = node.findAllVariablesWithAssignments().mapKeys { it.key.text }
val keys = vars.keys
val var1 = keys.elementAt(0)
Assertions.assertEquals("var o = 1", var1)
Assertions.assertEquals(2, vars[var1]?.size)
}
}
}
@Test
fun `testing proper variables search in class`() {
applyToCode("""
class A {
var o = 1
fun foo(a: Int) {
fun foo1() {
b = o
c = o
d = o
o = 15
o = 17
}
}
}
""".trimIndent(), 0) { node, _ ->
if (node.elementType == FILE) {
val vars = node.findAllVariablesWithAssignments().mapKeys { it.key.text }
val keys = vars.keys
val var1 = keys.elementAt(0)
Assertions.assertEquals("var o = 1", var1)
Assertions.assertEquals(2, vars[var1]?.size)
}
}
}
@Test
@Disabled
fun `testing proper variables search with lambda`() {
applyToCode("""
fun foo(a: Int) {
var a = 1
a++
}
""".trimIndent(), 0) { node, _ ->
if (node.elementType == FILE) {
val vars = node.findAllVariablesWithAssignments().mapKeys { it.key.text }
val keys = vars.keys
val var1 = keys.elementAt(0)
Assertions.assertEquals("var a = 1", var1)
Assertions.assertEquals(1, vars[var1]?.size)
}
}
}
}
| 1 | Kotlin | 0 | 0 | bc2e7122cbd2be8062ff8862c9fb5defd95c84d6 | 2,573 | diKTat | MIT License |
buildSrc/src/main/kotlin/DebugDependencies.kt | DavideSorcelli | 556,376,284 | false | {"Kotlin": 52055} | object DebugDependencies {
const val COMPOSE_UI_TOOLING = "androidx.compose.ui:ui-tooling:${Versions.COMPOSE}"
const val COMPOSE_UI_TEST_MANIFEST = "androidx.compose.ui:ui-test-manifest:${Versions.COMPOSE}"
} | 0 | Kotlin | 0 | 0 | e92b6ea08b1ff46ee3d609e973be4cb886fc070d | 216 | BeersApp | Apache License 2.0 |
sample/src/main/java/com/thoughtbot/expandablerecyclerview/sample/singlecheck/SingleCheckArtistViewHolder.kt | mohamedagamy | 324,799,949 | true | {"Java": 62885, "Shell": 723} | package com.thoughtbot.expandablerecyclerview.sample.singlecheck
import android.view.View
import android.widget.Checkable
import android.widget.CheckedTextView
import com.thoughtbot.expandablecheckrecyclerview.viewholders.CheckableChildViewHolder
import com.thoughtbot.expandablerecyclerview.sample.R
class SingleCheckArtistViewHolder(itemView: View) : CheckableChildViewHolder(itemView) {
private val childCheckedTextView: CheckedTextView
override fun getCheckable(): Checkable {
return childCheckedTextView
}
fun setArtistName(artistName: String?) {
childCheckedTextView.text = artistName
}
init {
childCheckedTextView = itemView.findViewById<View>(R.id.list_item_singlecheck_artist_name) as CheckedTextView
}
} | 0 | Java | 0 | 0 | c3dec08935bbc035e8537de04f1dfe1367b617d4 | 769 | expandable-recycler-view | MIT License |
app/src/main/java/com/monday8am/tweetmeck/data/TimelineQuery.kt | monday8am | 218,958,294 | false | null | package com.monday8am.tweetmeck.data
sealed class TimelineQuery {
data class List(val listId: Long) : TimelineQuery()
data class User(val screenName: String) : TimelineQuery()
data class Hashtag(val hashtag: String) : TimelineQuery()
companion object {
fun fromFormattedString(url: String): TimelineQuery {
val parsed = url.split(":")
return when (parsed[0]) {
"list" -> List(parsed[1].toLong())
"user" -> User(parsed[1])
else -> Hashtag(parsed[1])
}
}
}
fun toFormattedString(): String {
return when (this) {
is List -> "list:${this.listId}"
is User -> "user:${this.screenName}"
is Hashtag -> "hashtag:${this.hashtag}"
}
}
}
| 9 | Kotlin | 0 | 3 | d4d942e0ede2bfa39db082291b9b9889f27b99de | 809 | tweetmeck | MIT License |
app/src/main/java/com/grevi/masakapa/data/remote/response/CategorysResponse.kt | tomorisakura | 316,280,767 | false | null | package com.grevi.masakapa.data.remote.response
import com.google.gson.annotations.SerializedName
import com.grevi.masakapa.model.Categorys
data class CategorysResponse(
@SerializedName("method") var method : String,
@SerializedName("status") var status : Boolean,
@SerializedName("results") var results : MutableList<Categorys>
) | 0 | Kotlin | 7 | 26 | d19e5b6d075689603826e031edc6c968faa92878 | 344 | masak-apa | MIT License |
src/main/kotlin/org/opensearch/indexmanagement/transform/TransformMetadataService.kt | opensearch-project | 354,094,562 | false | {"Kotlin": 3464427, "Shell": 2188, "Python": 1396, "Java": 244} | /*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/
package org.opensearch.indexmanagement.transform
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.apache.logging.log4j.LogManager
import org.opensearch.ExceptionsHelper
import org.opensearch.action.DocWriteRequest
import org.opensearch.action.DocWriteResponse
import org.opensearch.action.get.GetRequest
import org.opensearch.action.get.GetResponse
import org.opensearch.action.index.IndexRequest
import org.opensearch.action.index.IndexResponse
import org.opensearch.client.Client
import org.opensearch.common.xcontent.LoggingDeprecationHandler
import org.opensearch.common.xcontent.XContentFactory
import org.opensearch.common.xcontent.XContentHelper
import org.opensearch.common.xcontent.XContentType
import org.opensearch.core.xcontent.NamedXContentRegistry
import org.opensearch.core.xcontent.ToXContent
import org.opensearch.indexmanagement.IndexManagementPlugin
import org.opensearch.indexmanagement.opensearchapi.parseWithType
import org.opensearch.indexmanagement.opensearchapi.suspendUntil
import org.opensearch.indexmanagement.transform.exceptions.TransformMetadataException
import org.opensearch.indexmanagement.transform.model.ContinuousTransformStats
import org.opensearch.indexmanagement.transform.model.Transform
import org.opensearch.indexmanagement.transform.model.TransformMetadata
import org.opensearch.indexmanagement.transform.model.TransformStats
import org.opensearch.indexmanagement.util.IndexUtils.Companion.hashToFixedSize
import org.opensearch.transport.RemoteTransportException
import java.time.Instant
@SuppressWarnings("ReturnCount")
class TransformMetadataService(private val client: Client, val xContentRegistry: NamedXContentRegistry) {
private val logger = LogManager.getLogger(javaClass)
@Suppress("BlockingMethodInNonBlockingContext")
suspend fun getMetadata(transform: Transform): TransformMetadata {
return if (transform.metadataId != null) {
// update metadata
val getRequest = GetRequest(IndexManagementPlugin.INDEX_MANAGEMENT_INDEX, transform.metadataId).routing(transform.id)
val response: GetResponse = client.suspendUntil { get(getRequest, it) }
val metadataSource = response.sourceAsBytesRef
val transformMetadata =
metadataSource?.let {
withContext(Dispatchers.IO) {
val xcp = XContentHelper.createParser(xContentRegistry, LoggingDeprecationHandler.INSTANCE, metadataSource, XContentType.JSON)
xcp.parseWithType(response.id, response.seqNo, response.primaryTerm, TransformMetadata.Companion::parse)
}
}
// TODO: Should we attempt to create a new document instead if failed to parse, the only reason this can happen is if someone deleted
// the metadata doc?
transformMetadata ?: throw TransformMetadataException("Failed to parse the existing metadata document")
} else {
logger.debug("Creating metadata doc as none exists at the moment for transform job [${transform.id}]")
createMetadata(transform)
}
}
private suspend fun createMetadata(transform: Transform): TransformMetadata {
// Including timestamp in the metadata id to prevent clashes if the job was deleted but metadata is not deleted, in that case we want to
// create a clean metadata doc
val id = hashToFixedSize("TransformMetadata#${transform.id}#${transform.lastUpdateTime}")
val metadata =
TransformMetadata(
id = id,
transformId = transform.id,
lastUpdatedAt = Instant.now(),
status = TransformMetadata.Status.INIT,
stats = TransformStats(0, 0, 0, 0, 0),
continuousStats = if (transform.continuous) ContinuousTransformStats(null, null) else null,
)
return writeMetadata(metadata)
}
@Suppress("BlockingMethodInNonBlockingContext", "ThrowsCount", "ComplexMethod")
suspend fun writeMetadata(metadata: TransformMetadata, updating: Boolean = false): TransformMetadata {
val errorMessage = "Failed to ${if (updating) "update" else "create"} metadata doc ${metadata.id} for transform job ${metadata.transformId}"
try {
val builder = metadata.toXContent(XContentFactory.jsonBuilder(), ToXContent.EMPTY_PARAMS)
val indexRequest =
IndexRequest(IndexManagementPlugin.INDEX_MANAGEMENT_INDEX)
.source(builder)
.id(metadata.id)
.routing(metadata.transformId)
if (updating) {
indexRequest.setIfSeqNo(metadata.seqNo).setIfPrimaryTerm(metadata.primaryTerm)
} else {
indexRequest.opType(DocWriteRequest.OpType.CREATE)
}
val response: IndexResponse = client.suspendUntil { index(indexRequest, it) }
return when (response.result) {
DocWriteResponse.Result.CREATED, DocWriteResponse.Result.UPDATED -> {
metadata.copy(seqNo = response.seqNo, primaryTerm = response.primaryTerm)
}
else -> {
logger.error(errorMessage)
throw TransformMetadataException("Failed to write metadata, received ${response.result?.lowercase} status")
}
}
} catch (e: RemoteTransportException) {
val unwrappedException = ExceptionsHelper.unwrapCause(e) as Exception
logger.error(errorMessage, unwrappedException)
throw TransformMetadataException(errorMessage, unwrappedException)
} catch (e: Exception) {
logger.error(errorMessage, e)
throw TransformMetadataException(errorMessage, e)
}
}
}
| 112 | Kotlin | 105 | 45 | 8530939e43efbe4dcf66421eda0e0bf7a857974c | 5,972 | index-management | Apache License 2.0 |
src/modules/users/service/InMemoryUserService.kt | aditmodhvadia | 334,506,216 | false | null | package com.aditmodhvadia.modules.users.service
import com.aditmodhvadia.models.UserDto
import com.aditmodhvadia.modules.users.data.UserDataSource
class InMemoryUserService(private val userDataSource: UserDataSource) : UserService {
override fun findAll(): Collection<UserDto> = userDataSource.retrieveUsers()
} | 10 | Kotlin | 0 | 0 | 3c046531c630f7c9276d2d79f39a96e513a114bd | 317 | ktor-backend | MIT License |
library/src/jvmCommonMain/kotlin/client/NetworkEventCallback.kt | DrewCarlson | 228,961,452 | false | null | /*
* Created by <NAME>.
* Copyright (c) 2021 Breadwinner AG. All right reserved.
*
* See the LICENSE file at the project root for license information.
* See the CONTRIBUTORS file at the project root for a list of contributors.
*/
package com.blockset.walletkit.client
import com.blockset.walletkit.nativex.WKListener
import com.blockset.walletkit.nativex.WKNetworkEventType
import com.blockset.walletkit.listenerScope
import kotlinx.coroutines.*
internal val NetworkEventCallback = WKListener.NetworkEventCallback { context, coreNetwork, event ->
listenerScope.launch {
try {
when (checkNotNull(event.type())) {
WKNetworkEventType.CREATED -> Unit
WKNetworkEventType.FEES_UPDATED -> Unit
WKNetworkEventType.CURRENCIES_UPDATED -> Unit
WKNetworkEventType.DELETED -> Unit
}
} finally {
coreNetwork.give()
}
}
}
| 4 | Kotlin | 1 | 1 | 6a6b20a69e6307d89ad7ce3494fb794411fb7e76 | 954 | WalletKit-Kotlin | The Unlicense |
widgets/src/androidMain/kotlin/dev/icerock/moko/widgets/core/view/MarginedFrameLayout.kt | icerockdev | 218,209,603 | false | null | /*
* Copyright 2019 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
*/
package dev.icerock.moko.widgets.core.view
import android.content.Context
import android.view.ViewGroup
import android.widget.FrameLayout
// we should manually convert MarginLayoutParams to FrameLayout.LayoutParams because of
// https://android.googlesource.com/platform/frameworks/base/+/2dd20a6%5E%21/
internal open class MarginedFrameLayout(context: Context) : FrameLayout(context) {
override fun generateLayoutParams(lp: ViewGroup.LayoutParams): LayoutParams {
return when (lp) {
is LayoutParams -> lp
is MarginLayoutParams -> LayoutParams(lp)
else -> LayoutParams(lp)
}
}
}
| 40 | Kotlin | 29 | 333 | 63ea65d622f702432a5b5d1f587ba0fb8a81f95e | 747 | moko-widgets | Apache License 2.0 |
Expoandes/app/src/main/java/com/example/expoandes/CosasPropiasView.kt | leo283 | 360,563,279 | false | null | package com.example.expoandes
import android.content.ContentValues
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.widget.LinearLayout
import android.widget.Space
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.view.isEmpty
import com.google.firebase.firestore.FirebaseFirestore
class CosasPropiasView : AppCompatActivity() {
private val db= FirebaseFirestore.getInstance()
override fun onCreate(savedInstanceState: Bundle?) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_cosas_propias_view)
mostrar_objetos()
}
fun mostrar_objetos() {
val prefs = this.getSharedPreferences(getString(R.string.prefs_file), Context.MODE_PRIVATE)
val email = prefs.getString("email", null)
val layout_objetos = findViewById<LinearLayout>(R.id.cosas_propias_full)
val objetos_prestamo = db.collection("Mingle_users").document(email.toString()).collection("mis_prestamos").document("cosas")
val hola = db.collection("Mingle_users").document(email.toString()).collection("mis_prestamos").get()
hola.addOnSuccessListener { resultado->
if (resultado!=null){
layout_objetos.removeAllViews()
for (documento in resultado){
val data=documento.data
val estado=data["estado"].toString()
val nombre= data["nombre"].toString()
val texto_nombre = TextView(this)
val espacio = Space(this)
espacio.minimumHeight=80
texto_nombre.text=nombre
texto_nombre.textSize=16f
texto_nombre.gravity=Gravity.CENTER
var colorr=(0xFF000000).toInt()
if (estado=="disponible"){colorr=(0xFF418337).toInt()}else if(estado=="no disponible"){colorr=(0xFFdf1623).toInt()}
texto_nombre.setTextColor(colorr)
texto_nombre.setTextColor(colorr)
layout_objetos.addView(espacio)
layout_objetos.addView(texto_nombre)
println(nombre)
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 4dd7bcd43b326faa3414e654b46d1857e23f9b63 | 2,454 | expoandes | Creative Commons Zero v1.0 Universal |
build.gradle.kts | gradle-samples | 521,376,445 | false | {"Kotlin": 1133, "Java": 820} | defaultTasks("run")
tasks.register("run") {
dependsOn(gradle.includedBuild("my-app").task(":app:run"))
}
tasks.register("checkAll") {
dependsOn(gradle.includedBuild("my-app").task(":app:check"))
dependsOn(gradle.includedBuild("my-utils").task(":number-utils:check"))
dependsOn(gradle.includedBuild("my-utils").task(":string-utils:check"))
}
| 0 | Kotlin | 0 | 0 | c4923f8b11b040894052b00913ca078c78f6083e | 359 | Defining-and-using-a-composite-build-Kotlin | Apache License 2.0 |
platform/runner-plugin/std/sys/src/main/kotlin/io/hamal/plugin/std/sys/topic/TopicCreateFunction.kt | hamal-io | 622,870,037 | false | {"Kotlin": 2271632, "C": 1398396, "TypeScript": 281644, "Lua": 117891, "C++": 40651, "Makefile": 11728, "Java": 7564, "CMake": 2810, "JavaScript": 2640, "CSS": 1567, "Shell": 977, "HTML": 903} | package io.hamal.plugin.std.sys.func
import io.hamal.lib.common.snowflake.SnowflakeId
import io.hamal.lib.domain.vo.CodeValue
import io.hamal.lib.domain.vo.FuncInputs
import io.hamal.lib.domain.vo.FuncName
import io.hamal.lib.domain.vo.FlowId
import io.hamal.lib.kua.function.Function1In2Out
import io.hamal.lib.kua.function.FunctionContext
import io.hamal.lib.kua.function.FunctionInput1Schema
import io.hamal.lib.kua.function.FunctionOutput2Schema
import io.hamal.lib.kua.type.KuaError
import io.hamal.lib.kua.type.KuaMap
import io.hamal.lib.kua.type.KuaString
import io.hamal.lib.sdk.ApiSdk
import io.hamal.lib.sdk.api.ApiFuncCreateRequest
class FuncCreateFunction(
private val sdk: ApiSdk
) : Function1In2Out<KuaMap, KuaError, KuaMap>(
FunctionInput1Schema(KuaMap::class),
FunctionOutput2Schema(KuaError::class, KuaMap::class)
) {
override fun invoke(ctx: FunctionContext, arg1: KuaMap): Pair<KuaError?, KuaMap?> {
return try {
val res = sdk.func.create(
arg1.findString("flow_id")?.let { FlowId(SnowflakeId(it)) } ?: ctx[FlowId::class],
ApiFuncCreateRequest(
name = FuncName(arg1.getString("name")),
inputs = FuncInputs(),
code = CodeValue(arg1.getString("code"))
)
)
null to KuaMap(
mutableMapOf(
"id" to KuaString(res.id.value.value.toString(16)),
"status" to KuaString(res.status.name),
"func_id" to KuaString(res.funcId.value.value.toString(16)),
"group_id" to KuaString(res.groupId.value.value.toString(16)),
"flow_id" to KuaString(res.flowId.value.value.toString(16))
)
)
} catch (t: Throwable) {
KuaError(t.message!!) to null
}
}
} | 22 | Kotlin | 0 | 0 | e6e452ee9e66621c4e753209a1936ced4185a3ba | 1,892 | hamal | GNU Affero General Public License v3.0 |
app/src/main/java/ir/esmaeili/stopcar/repository/database/DBHelper.kt | BasetEsmaeili | 250,985,369 | false | {"Kotlin": 198280, "Java": 50069} | package ir.esmaeili.stopcar.repository.database
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.Maybe
import io.reactivex.Single
import ir.esmaeili.stopcar.models.Car
import ir.esmaeili.stopcar.models.History
import ir.esmaeili.stopcar.models.HistoryJoinCar
interface DBHelper {
fun insertCar(car: Car): Single<Boolean>
fun getCars(): Flowable<List<Car>>
fun insertHistory(history: History): Single<Boolean>
fun getHistoryList(): Flowable<List<HistoryJoinCar>>
fun deleteCarWithHistory(carID: Long): Single<Boolean>
fun getCarCount(): Flowable<Long>
fun deleteAll(): Completable
} | 0 | Kotlin | 3 | 7 | 8287613ca3afb090f52e9bed02671a0375d1c3d9 | 643 | StopCar-Redesigned | Apache License 2.0 |
src/Chapter07/7.1.2_CompoundAssignmentOperators.kt | ldk123456 | 157,306,847 | false | null | package Chapter07.CompoundAssignmentOperators
data class Point(val x: Int, val y: Int)
operator fun Point.plus(other: Point): Point {
return Point(x + other.x, y + other.y)
}
fun main() {
var point = Point(1, 2)
point += Point(3, 4)
println(point)
//>>>Point(x=4, y=6)
val numbers = ArrayList<Int>()
numbers += 42
println(numbers)
//>>>[42]
val list = arrayListOf(1, 2)
list += 3 //+=修改list
val newList = list + listOf(4, 5) //+返回一个包含所有元素的新列表
println(list) //>>>[1, 2, 3]
println(newList) //>>>[1, 2, 3, 4, 5]
} | 0 | Kotlin | 0 | 0 | 301ea7daa495231ff878317311d7ded3a0fbcbc8 | 613 | KotlinInAction | Apache License 2.0 |
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/VideoTimeSeries.kt | Danilo-Araujo-Silva | 271,904,885 | false | null | package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/**
*````
*
* Name: VideoTimeSeries
*
* Full name: System`VideoTimeSeries
*
* VideoTimeSeries[f, video] applies f to each frame of the Video object video, returning a time series.
* VideoTimeSeries[f, video, n] applies f to non-overlapping partitions of n video frames.
* Usage: VideoTimeSeries[f, video, n, d] applies f to partitions with offset d.
*
* Alignment -> Automatic
* MetaInformation -> None
* MissingDataMethod -> Automatic
* Options: ResamplingMethod -> Automatic
*
* Protected
* Attributes: ReadProtected
*
* local: paclet:ref/VideoTimeSeries
* Documentation: web: http://reference.wolfram.com/language/ref/VideoTimeSeries.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun videoTimeSeries(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("VideoTimeSeries", arguments.toMutableList(), options)
}
| 2 | Kotlin | 0 | 3 | 4fcf68af14f55b8634132d34f61dae8bb2ee2942 | 1,416 | mathemagika | Apache License 2.0 |
core/src/main/java/org/kerala/core/server/converters/AppendEntriesConverters.kt | kination | 245,778,979 | true | {"Kotlin": 149336, "Java": 13392, "Dockerfile": 335} | package org.kerala.core.server.converters
import org.kerala.core.consensus.messages.AppendEntriesRequest
import org.kerala.core.consensus.messages.AppendEntriesResponse
import org.kerala.core.server.cluster.KeralaAppendEntriesRequest
import org.kerala.core.server.cluster.KeralaAppendEntriesResponse
class AppendEntriesConverters {
class ToRpcRequest : Converter<AppendEntriesRequest, KeralaAppendEntriesRequest> {
private val converterRegistry: ConverterRegistry by ConverterRegistry.delegate
override fun convert(source: AppendEntriesRequest): KeralaAppendEntriesRequest {
val converter = converterRegistry.getConverter<EntryConverters.ToRpc>()
return KeralaAppendEntriesRequest.newBuilder()
.addAllEntries(source.entries.map(converter::convert))
.setTerm(source.term)
.setTopicId(source.topicId)
.setLeaderId(source.leaderId)
.setPrevLogTerm(source.prevLogTerm)
.setPrevLogIndex(source.prevLogIndex)
.setLeaderCommit(source.leaderCommit)
.build()
}
}
class FromRpcRequest : Converter<KeralaAppendEntriesRequest, AppendEntriesRequest> {
private val converterRegistry: ConverterRegistry by ConverterRegistry.delegate
override fun convert(source: KeralaAppendEntriesRequest): AppendEntriesRequest {
val converter = converterRegistry.getConverter<EntryConverters.FromRpc>()
return AppendEntriesRequest(
source.term,
source.topicId,
source.prevLogTerm,
source.prevLogIndex,
source.leaderId,
source.leaderCommit,
source.entriesList.map(converter::convert))
}
}
class ToRpcResponse : Converter<AppendEntriesResponse, KeralaAppendEntriesResponse> {
override fun convert(source: AppendEntriesResponse): KeralaAppendEntriesResponse {
return KeralaAppendEntriesResponse.newBuilder()
.setTerm(source.term)
.setSuccess(source.isSuccessful)
.setPrevLogIndex(source.prevLogIndex)
.build()
}
}
class FromRpcResponse : Converter<KeralaAppendEntriesResponse, AppendEntriesResponse> {
override fun convert(source: KeralaAppendEntriesResponse): AppendEntriesResponse {
return AppendEntriesResponse(source.term, source.success, source.prevLogIndex)
}
}
}
| 0 | Kotlin | 0 | 0 | 2a51441710e81dd810ca64beca5374d781231567 | 2,329 | kerala | MIT License |
app/src/main/java/io/outblock/lilico/page/staking/amount/StakingAmountViewModel.kt | Outblock | 435,317,689 | false | {"Kotlin": 1563313, "Java": 104099} | package io.outblock.lilico.page.staking.amount
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import io.outblock.lilico.manager.account.Balance
import io.outblock.lilico.manager.account.BalanceManager
import io.outblock.lilico.manager.account.OnBalanceUpdate
import io.outblock.lilico.manager.coin.CoinRateManager
import io.outblock.lilico.manager.coin.FlowCoin
import io.outblock.lilico.manager.coin.FlowCoinListManager
import io.outblock.lilico.manager.coin.OnCoinRateUpdate
import io.outblock.lilico.manager.staking.StakingManager
import io.outblock.lilico.manager.staking.StakingProvider
import io.outblock.lilico.utils.ioScope
class StakingAmountViewModel : ViewModel(), OnBalanceUpdate, OnCoinRateUpdate {
val balanceLiveData = MutableLiveData<Float>()
val processingLiveData = MutableLiveData<Boolean>()
private var coinRate = 0.0f
init {
BalanceManager.addListener(this)
CoinRateManager.addListener(this)
}
fun coinRate() = coinRate
fun load(provider: StakingProvider, isUnstake: Boolean) {
ioScope {
val coin = FlowCoinListManager.getCoin(FlowCoin.SYMBOL_FLOW) ?: return@ioScope
if (isUnstake) {
val node = StakingManager.stakingNode(provider) ?: return@ioScope
balanceLiveData.postValue(node.tokensStaked)
} else {
BalanceManager.getBalanceByCoin(coin)
}
CoinRateManager.fetchCoinRate(coin)
}
}
override fun onBalanceUpdate(coin: FlowCoin, balance: Balance) {
if (coin.isFlowCoin()) {
balanceLiveData.postValue(balance.balance)
}
}
override fun onCoinRateUpdate(coin: FlowCoin, price: Float) {
coinRate = price
}
} | 63 | Kotlin | 3 | 4 | a238e4f9db0d93a9c87fc9682860f2ea265c798b | 1,790 | Lilico-Android | Apache License 2.0 |
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/execute/usecases/RequestBiometricConfirmationUseCase.kt | Waboodoo | 34,525,124 | false | {"Kotlin": 1818178, "HTML": 179455, "CSS": 2092, "Python": 1548} | package ch.rmy.android.http_shortcuts.activities.execute.usecases
import android.content.Context
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.exceptions.UserException
import ch.rmy.android.http_shortcuts.utils.BiometricUtil
import kotlinx.coroutines.CancellationException
import javax.inject.Inject
class RequestBiometricConfirmationUseCase
@Inject
constructor(
private val context: Context,
private val biometricUtil: BiometricUtil,
) {
suspend operator fun invoke(shortcutName: String) {
val result = try {
biometricUtil.prompt(
title = shortcutName,
subtitle = context.getString(R.string.subtitle_biometric_confirmation_prompt),
negativeButtonText = context.getString(R.string.dialog_cancel),
)
} catch (e: BiometricUtil.BiometricException) {
throw UserException.create {
getString(R.string.error_biometric_confirmation_failed, e.message)
}
}
when (result) {
BiometricUtil.Result.SUCCESS -> Unit
BiometricUtil.Result.NEGATIVE_BUTTON -> throw CancellationException()
}
}
}
| 28 | Kotlin | 102 | 875 | 9a11aca0607c965c02de433443a0e57afd8bc2a4 | 1,201 | HTTP-Shortcuts | MIT License |
kmongo-property/src/test/kotlin/org/litote/kmongo/FiltersTest.kt | Litote | 58,964,537 | false | {"Kotlin": 1722533, "Java": 56965, "Shell": 2012} | /*
* Copyright (C) 2016/2022 Litote
*
* 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.litote.kmongo
import com.mongodb.client.model.Filters
import org.junit.Test
import kotlin.test.assertEquals
/**
*
*/
class FiltersTest {
class T(val s: List<String>, val string: String, val zz:List<Z>)
class Z(val a: String)
@Test
fun `all works with Iterable sub interface`() {
//check this compile
T::s all setOf("test")
}
@Test
fun `eq works with null`() {
//check this compile
T::s eq null
}
@Test
fun `in works with a collection property`() {
//check this compile
T::s `in` setOf("test")
}
@Test
fun `nin works with a collection property`() {
//check this compile
T::s nin setOf("test")
}
@Test
fun `regex works with a string property`() {
val r1 = T::string regex "test"
val r2 = T::string regex "test".toRegex().toPattern()
val r3 = T::string regex "test".toRegex()
val r4 = T::string.regex("test", "")
assertEquals(r1.document, Filters.regex("string", "test").document)
assertEquals(r1.document, r2.document)
assertEquals(r1.document, r3.document)
assertEquals(r1.document, r4.document)
}
@Test
fun `regex works with a collection property`() {
val r1 = T::s regex "test"
val r2 = T::s regex "test".toRegex().toPattern()
val r3 = T::s regex "test".toRegex()
val r4 = T::s.regex("test", "")
assertEquals(r1.document, Filters.regex("s", "test").document)
assertEquals(r1.document, r2.document)
assertEquals(r1.document, r3.document)
assertEquals(r1.document, r4.document)
}
@Test
fun `positional projection`() {
val p = T::zz.pos(0) / Z::a
assertEquals("zz.0.a", p.path())
}
data class Map1(val p1: Map<String, Map2>)
data class Map2(val p2: Map<String, String>)
@Test
fun `multiple key projection`() {
val m1 = Map1::p1.keyProjection("a")
val m2 = Map2::p2.keyProjection("b")
val doc = m1 / m2
assertEquals("p1.a.p2.b", doc.path())
}
} | 42 | Kotlin | 74 | 789 | 0e7143051e07e5415e70ad5bc2bbfa3e57afc923 | 2,721 | kmongo | Apache License 2.0 |
packages/expo-dev-menu/android/src/main/java/expo/modules/devmenu/DevMenuHost.kt | zenorocha | 463,705,690 | true | {"Objective-C": 20549336, "Java": 13710548, "C++": 9520547, "Kotlin": 5385308, "TypeScript": 4710581, "Objective-C++": 4267513, "Swift": 1115912, "JavaScript": 963626, "Starlark": 604565, "Ruby": 492836, "C": 286916, "Makefile": 158759, "Shell": 51241, "Assembly": 46734, "HTML": 36667, "CMake": 25283, "CSS": 1306, "Batchfile": 89} | package expo.modules.devmenu
import android.app.Application
import android.content.Context
import android.util.Log
import com.facebook.hermes.reactexecutor.HermesExecutorFactory
import com.facebook.react.ReactInstanceManager
import com.facebook.react.ReactNativeHost
import com.facebook.react.bridge.JSIModulePackage
import com.facebook.react.bridge.JavaScriptExecutorFactory
import com.facebook.react.devsupport.DevServerHelper
import com.facebook.react.jscexecutor.JSCExecutorFactory
import com.facebook.react.modules.systeminfo.AndroidInfoHelpers
import com.facebook.react.shell.MainReactPackage
import com.facebook.soloader.SoLoader
import expo.modules.devmenu.react.DevMenuReactInternalSettings
import java.io.BufferedReader
import java.io.FileNotFoundException
import java.io.InputStreamReader
/**
* Class that represents react host used by dev menu.
*/
class DevMenuHost(application: Application) : ReactNativeHost(application) {
override fun getPackages() = listOf(
MainReactPackage(null),
DevMenuPackage(),
getVendoredPackage("com.swmansion.reanimated.ReanimatedPackage"),
getVendoredPackage("com.swmansion.gesturehandler.react.RNGestureHandlerPackage"),
getVendoredPackage("com.th3rdwave.safeareacontext.SafeAreaContextPackage"),
)
override fun getJSIModulePackage(): JSIModulePackage {
return getVendoredJNIPackage("com.swmansion.reanimated.ReanimatedJSIModulePackage")
}
override fun getUseDeveloperSupport() = false // change it and run `yarn start` in `expo-dev-menu` to launch dev menu from local packager
override fun getBundleAssetName() = "EXDevMenuApp.android.js"
override fun getJSMainModuleName() = "index"
fun getContext(): Context = super.getApplication()
override fun getJavaScriptExecutorFactory(): JavaScriptExecutorFactory? {
SoLoader.init(application.applicationContext, /* native exopackage */ false)
if (SoLoader.getLibraryPath("libjsc.so") != null) {
return JSCExecutorFactory(application.packageName, AndroidInfoHelpers.getFriendlyDeviceName())
}
return HermesExecutorFactory()
}
override fun createReactInstanceManager(): ReactInstanceManager {
val reactInstanceManager = super.createReactInstanceManager()
if (useDeveloperSupport) {
// To use a different packager url, we need to replace internal RN objects.
try {
val serverIp = BufferedReader(
InputStreamReader(super.getApplication().assets.open("dev-menu-packager-host"))
).use {
it.readLine()
}
val devMenuInternalReactSettings = DevMenuReactInternalSettings(serverIp, super.getApplication())
val devSupportManager = reactInstanceManager.devSupportManager
val devSupportManagerBaseClass = devSupportManager.javaClass.superclass!!
setPrivateField(
obj = devSupportManager,
objClass = devSupportManagerBaseClass,
field = "mDevSettings",
newValue = devMenuInternalReactSettings
)
val devServerHelper: DevServerHelper = getPrivateFiled(devSupportManager, devSupportManagerBaseClass, "mDevServerHelper")
setPrivateField(
obj = devServerHelper,
objClass = devServerHelper.javaClass,
field = "mSettings",
newValue = devMenuInternalReactSettings
)
Log.i(DEV_MENU_TAG, "DevSettings was correctly injected.")
} catch (e: FileNotFoundException) {
Log.e(DEV_MENU_TAG, "Couldn't find `dev-menu-packager-host` file.", e)
} catch (e: Exception) {
Log.e(DEV_MENU_TAG, "Couldn't inject DevSettings object.", e)
}
}
return reactInstanceManager
}
}
| 0 | null | 1 | 1 | 4714e7a91dd300e6baa695ab89bedafc088d67f6 | 3,663 | expo | MIT License |
desktop/src/main/java/lt/neworld/randomdecision2/Application.kt | neworld | 55,846,624 | false | null | package lt.neworld.randomdecision2
/**
* @author neworld
* @since 09/04/16
*/
fun main(args: Array<String>) {
if (args.any { it == "--no-gui" }) {
CLI().run()
} else {
setupLookAndFeel()
Window().run()
}
} | 1 | Kotlin | 0 | 0 | bf87e3ee97a905e374432e4e17911ccfae7c0bf3 | 246 | random-decision | Apache License 2.0 |
bukkit/rpk-travel-bukkit/src/main/kotlin/com/rpkit/travel/bukkit/permissions/TravelPermissions.kt | RP-Kit | 54,840,905 | false | null | package com.rpkit.travel.bukkit.permissions
class TravelPermissions {
val parentWarpPermission = "rpkit.travel.command.warp"
}
| 51 | Kotlin | 11 | 22 | aee4060598dc25cd8e4f3976ed5e70eb1bf874a2 | 133 | RPKit | Apache License 2.0 |
samples/chat/server/src/commonMain/kotlin/Chats.kt | rsocket | 109,894,810 | false | {"Kotlin": 483371, "JavaScript": 203} | /*
* Copyright 2015-2022 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 io.rsocket.kotlin.samples.chat.server
import io.rsocket.kotlin.samples.chat.api.*
class Chats {
private val storage = Storage<Chat>()
val values: List<Chat> get() = storage.values()
fun getOrNull(id: Int): Chat? = storage.getOrNull(id)
fun delete(id: Int) {
storage.remove(id)
}
fun create(name: String): Chat {
if (storage.values().any { it.name == name }) error("Chat with such name already exists")
val chatId = storage.nextId()
val chat = Chat(chatId, name)
storage.save(chatId, chat)
return chat
}
fun exists(id: Int): Boolean = storage.contains(id)
}
operator fun Chats.get(id: Int): Chat = getOrNull(id) ?: error("No user with id '$id' exists")
operator fun Chats.minusAssign(id: Int): Unit = delete(id)
operator fun Chats.contains(id: Int): Boolean = exists(id)
| 27 | Kotlin | 36 | 515 | 88e692837137a99de18cfbe69b9a52ac5626a5f9 | 1,487 | rsocket-kotlin | Apache License 2.0 |
src/main/kotlin/com/github/mmauro94/media_merger/util/json/converters/DurationConverter.kt | MMauro94 | 177,452,540 | false | {"Kotlin": 218767, "Dockerfile": 357} | package com.github.mmauro94.media_merger.util.json.converters
import com.beust.klaxon.Converter
import com.beust.klaxon.JsonValue
import com.beust.klaxon.KlaxonException
import com.github.mmauro94.media_merger.util.parseTimeStringOrNull
import com.github.mmauro94.media_merger.util.toSecondsDuration
import com.github.mmauro94.media_merger.util.toTimeString
import java.time.Duration
object DurationConverter : Converter {
override fun canConvert(cls: Class<*>) = cls == Duration::class.java
override fun fromJson(jv: JsonValue): Duration? {
return if (jv.inside == null) null
else
jv.string?.toBigDecimalOrNull()?.toSecondsDuration()
?: jv.string?.parseTimeStringOrNull()
?: jv.int?.toBigDecimal()?.toSecondsDuration()
?: throw KlaxonException("Invalid duration")
}
override fun toJson(value: Any): String {
return if (value is Duration) "\"" + value.toTimeString() + "\""
else throw KlaxonException("Must be a Duration")
}
} | 0 | Kotlin | 0 | 0 | 40a1d363e2260a41bfb6cb77e4c07f49b8cccc89 | 1,036 | media-merger | MIT License |
ontrack-extension-issues/src/main/java/net/nemerosa/ontrack/extension/issues/IssueServiceExtensionService.kt | nemerosa | 19,351,480 | false | {"Kotlin": 8298680, "JavaScript": 2587834, "Java": 1129286, "HTML": 505573, "Groovy": 377453, "CSS": 137378, "Less": 35164, "Dockerfile": 6298, "Shell": 5086} | package net.nemerosa.ontrack.extension.issues
import net.nemerosa.ontrack.extension.issues.model.ConfiguredIssueService
import net.nemerosa.ontrack.model.structure.Project
/**
* High level access to [IssueServiceExtension] from components of the Ontrack model.
*/
interface IssueServiceExtensionService {
/**
* Given a project, returns any associated [ConfiguredIssueService].
*/
fun getIssueServiceExtension(project: Project): ConfiguredIssueService?
} | 39 | Kotlin | 26 | 94 | c3cd484b681647bf68e43fa76a0bd4fccacf2972 | 475 | ontrack | MIT License |
jetlime/src/main/java/com/pushpal/jetlime/ui/JetLimeItemView.kt | fontaipi | 562,438,641 | false | {"Kotlin": 65695} | package com.pushpal.jetlime.ui
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.paddingFromBaseline
import androidx.compose.foundation.layout.size
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.PathEffect
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.ConstraintSet
import com.pushpal.jetlime.R
import com.pushpal.jetlime.data.config.IconType
import com.pushpal.jetlime.data.config.JetLimeItemConfig
import com.pushpal.jetlime.data.config.JetLimeViewConfig
import com.pushpal.jetlime.data.config.LineType
const val heightFactor = 3
/**
* [JetLimeItemView] is exposed to be used as composable
* @param title is the optional title of the item
* @param description is the optional description of the item
* @param content is any optional composable that can be populated in the item
* @param itemConfig is the config for the item. See [JetLimeItemConfig]
* @param viewConfig is the config for the entire view. See [JetLimeViewConfig]
* @param totalItems is the total number of items
*/
@Composable
fun JetLimeItemView(
title: String? = null,
description: String? = null,
itemConfig: JetLimeItemConfig,
viewConfig: JetLimeViewConfig,
totalItems: Int,
content: @Composable () -> Unit = {}
) {
BoxWithConstraints(
modifier = Modifier
.fillMaxWidth()
.background(color = viewConfig.backgroundColor)
.height(itemConfig.itemHeight)
) {
ConstraintLayout(
constraintSet = decoupledConstraints(
lineStartMargin = viewConfig.lineStartMargin,
lineEndMargin = viewConfig.lineEndMargin
)
) {
Canvas(
modifier = Modifier
.fillMaxHeight()
.layoutId("line")
) {
val startX = 0f
val startY = if (itemConfig.isFirstItem()) {
size.height / heightFactor
} else 0f
val endX = 0f
val endY = if (itemConfig.isLastItem(totalItems)) {
size.height / heightFactor
} else size.height
val pathEffect = when (viewConfig.lineType) {
is LineType.Dashed -> PathEffect.dashPathEffect(
viewConfig.lineType.intervals,
viewConfig.lineType.phase
)
else -> null
}
drawLine(
cap = StrokeCap.Round,
start = Offset(x = startX, y = startY),
end = Offset(x = endX, y = endY),
color = viewConfig.lineColor,
pathEffect = pathEffect,
strokeWidth = viewConfig.lineThickness
)
}
if (viewConfig.showIcons) {
val iconImage = when (itemConfig.iconType) {
IconType.Empty -> ImageVector.vectorResource(id = R.drawable.icon_empty)
IconType.Checked -> ImageVector.vectorResource(id = R.drawable.icon_check)
IconType.Filled -> ImageVector.vectorResource(id = R.drawable.icon_filled)
is IconType.Custom -> (itemConfig.iconType as IconType.Custom).iconImage
}
var finalAlpha = 1f
itemConfig.iconAnimation?.let { safeIconAnimation ->
val infiniteTransition = rememberInfiniteTransition()
val alpha by infiniteTransition.animateFloat(
initialValue = safeIconAnimation.initialValue,
targetValue = safeIconAnimation.targetValue,
animationSpec = infiniteRepeatable(
animation = safeIconAnimation.keySpecs,
repeatMode = RepeatMode.Reverse
)
)
finalAlpha = alpha
}
Image(
imageVector = iconImage,
contentDescription = "Indicator",
contentScale = ContentScale.Crop,
colorFilter = ColorFilter.tint(
color = itemConfig.iconColor
),
modifier = Modifier
.size(viewConfig.iconSize)
.scale(finalAlpha)
.clip(viewConfig.iconShape)
.border(
width = viewConfig.iconBorderThickness,
color = itemConfig.iconBorderColor,
shape = viewConfig.iconShape
)
.background(
color = itemConfig.iconBackgroundColor,
shape = viewConfig.iconShape
)
.layoutId("indicator")
)
}
title?.let { safeTitle ->
Text(
text = safeTitle,
color = itemConfig.titleColor,
style = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Bold,
fontSize = 16.sp
),
modifier = Modifier
.paddingFromBaseline(bottom = 8.dp)
.layoutId("title")
)
}
description?.let { safeDescription ->
Text(
text = safeDescription,
color = itemConfig.descriptionColor,
style = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 14.sp
),
modifier = Modifier
.paddingFromBaseline(bottom = 16.dp)
.layoutId("description")
)
}
Box(modifier = Modifier.layoutId("content")) {
content()
}
}
}
}
private fun decoupledConstraints(
lineStartMargin: Dp,
lineEndMargin: Dp
): ConstraintSet {
return ConstraintSet {
val lineC = createRefFor("line")
val indicatorC = createRefFor("indicator")
val titleC = createRefFor("title")
val descriptionC = createRefFor("description")
val contentC = createRefFor("content")
constrain(lineC) {
top.linkTo(parent.top)
bottom.linkTo(parent.bottom)
start.linkTo(parent.start, margin = lineStartMargin)
}
constrain(indicatorC) {
start.linkTo(lineC.start)
top.linkTo(titleC.top, margin = 0.dp)
end.linkTo(lineC.end)
}
constrain(titleC) {
top.linkTo(
anchor = parent.top,
margin = 16.dp
)
start.linkTo(
anchor = lineC.end,
margin = lineEndMargin
)
}
constrain(descriptionC) {
top.linkTo(titleC.bottom)
start.linkTo(titleC.start)
}
constrain(contentC) {
top.linkTo(descriptionC.bottom)
start.linkTo(
anchor = lineC.end,
margin = lineEndMargin
)
}
}
}
@Preview("Preview JetLimeItemView")
@Composable
fun PreviewJetLimeItemView() {
JetLimeItemView(
title = "Cafe Coffee Day",
description = "2/A South Green Lane",
itemConfig = JetLimeItemConfig(position = 0, itemHeight = 150.dp),
viewConfig = JetLimeViewConfig(lineStartMargin = 48.dp),
totalItems = 3
) {
Text(
text = "Canada 287",
style = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Thin,
fontSize = 12.sp
)
)
}
} | 0 | Kotlin | 0 | 0 | f4c66e42a3920414c134be0804986a47ae08b905 | 8,278 | jetlime | MIT License |
src/main/kotlin/no/nav/klage/util/AuditLogEvent.kt | navikt | 598,507,066 | true | {"Kotlin": 742484, "Dockerfile": 46} | package no.nav.klage.oppgave.domain
data class AuditLogEvent(
val navIdent: String,
val action: Action = Action.ACCESS,
val decision: Decision = Decision.PERMIT,
val personFnr: String?,
val logLevel: Level = Level.INFO
) {
enum class Level {
INFO, WARN
}
enum class Action(val value: String) {
ACCESS("audit:access")
}
enum class Decision {
PERMIT, DENY
}
} | 3 | Kotlin | 3 | 0 | c4903bb46d13fcbba4701bb266677fc8f0bbdbe8 | 429 | kabin-api | MIT License |
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/MinimumTimeIncrement.kt | Danilo-Araujo-Silva | 271,904,885 | false | null | package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/**
*````
*
* Name: MinimumTimeIncrement
*
* Full name: System`MinimumTimeIncrement
*
* Usage: MinimumTimeIncrement[tseries] gives the minimum time increment in the time series tseries.
*
* Options: None
*
* Protected
* Attributes: ReadProtected
*
* local: paclet:ref/MinimumTimeIncrement
* Documentation: web: http://reference.wolfram.com/language/ref/MinimumTimeIncrement.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun minimumTimeIncrement(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("MinimumTimeIncrement", arguments.toMutableList(), options)
}
| 2 | Kotlin | 0 | 3 | 4fcf68af14f55b8634132d34f61dae8bb2ee2942 | 1,068 | mathemagika | Apache License 2.0 |
app/src/main/java/com/example/bluromatic/workers/BlurWorker.kt | google-developer-training | 578,276,048 | false | {"Kotlin": 44590} | /*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.bluromatic.workers
import android.content.Context
import android.graphics.BitmapFactory
import android.net.Uri
import android.util.Log
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import com.example.bluromatic.DELAY_TIME_MILLIS
import com.example.bluromatic.KEY_BLUR_LEVEL
import com.example.bluromatic.KEY_IMAGE_URI
import com.example.bluromatic.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
private const val TAG = "BlurWorker"
class BlurWorker(ctx: Context, params: WorkerParameters) : CoroutineWorker(ctx, params) {
override suspend fun doWork(): Result {
val resourceUri = inputData.getString(KEY_IMAGE_URI)
val blurLevel = inputData.getInt(KEY_BLUR_LEVEL, 1)
makeStatusNotification(
applicationContext.resources.getString(R.string.blurring_image),
applicationContext
)
return withContext(Dispatchers.IO) {
// This is an utility function added to emulate slower work.
delay(DELAY_TIME_MILLIS)
return@withContext try {
require(!resourceUri.isNullOrBlank()) {
val errorMessage =
applicationContext.resources.getString(R.string.invalid_input_uri)
Log.e(TAG, errorMessage)
errorMessage
}
val resolver = applicationContext.contentResolver
val picture = BitmapFactory.decodeStream(
resolver.openInputStream(Uri.parse(resourceUri))
)
val output = blurBitmap(picture, blurLevel)
// Write bitmap to a temp file
val outputUri = writeBitmapToFile(applicationContext, output)
val outputData = workDataOf(KEY_IMAGE_URI to outputUri.toString())
Result.success(outputData)
} catch (throwable: Throwable) {
Log.e(
TAG,
applicationContext.resources.getString(R.string.error_applying_blur),
throwable
)
Result.failure()
}
}
}
}
| 8 | Kotlin | 21 | 18 | 2c1cfa0cbeb60b68929b316386752b9df67023aa | 2,908 | basic-android-kotlin-compose-training-workmanager | Apache License 2.0 |
vgscheckout/src/main/java/com/verygoodsecurity/vgscheckout/collect/view/card/conection/InputCardNumberConnection.kt | verygoodsecurity | 371,054,567 | false | null | package com.verygoodsecurity.vgscheckout.collect.view.card.conection
import com.verygoodsecurity.vgscheckout.collect.core.model.state.FieldContent
import com.verygoodsecurity.vgscheckout.collect.core.model.state.VGSFieldState
import com.verygoodsecurity.vgscheckout.collect.view.card.filter.CardBrandPreview
import com.verygoodsecurity.vgscheckout.collect.view.card.filter.VGSCardFilter
import com.verygoodsecurity.vgscheckout.collect.view.card.validation.VGSValidator
import com.verygoodsecurity.vgscheckout.collect.view.card.validation.payment.ChecksumAlgorithm
import com.verygoodsecurity.vgscheckout.collect.view.card.validation.payment.brand.LuhnCheckSumValidator
/** @suppress */
internal class InputCardNumberConnection(
id: Int,
validator: VGSValidator?,
private val IcardBrand: IDrawCardBrand? = null,
private val divider: String? = null
) : BaseInputConnection(id, validator) {
var canOverrideDefaultValidation = false
private val cardFilters = mutableListOf<VGSCardFilter>()
private var output = VGSFieldState()
override fun setOutput(state: VGSFieldState) {
output = state
}
override fun getOutput() = output
override fun clearFilters() {
cardFilters.clear()
}
override fun addFilter(filter: VGSCardFilter?) {
filter?.let {
cardFilters.add(0, it)
}
}
override fun run() {
val brand = detectBrand()
mapValue(brand)
IcardBrand?.onCardBrandPreview(brand)
validate(brand)
}
private fun validate(brand: CardBrandPreview) {
val isRequiredRuleValid = isRequiredValid()
val isContentRuleValid = isContentValid(brand)
output.isValid = isRequiredRuleValid && isContentRuleValid
}
private fun isRequiredValid(): Boolean {
return output.isRequired && !output.content?.data.isNullOrEmpty() || !output.isRequired
}
private fun isContentValid(card: CardBrandPreview): Boolean {
val content = output.content?.data
return when {
!output.isRequired && content.isNullOrEmpty() -> true
output.enableValidation -> checkIsContentValid(card)
else -> true
}
}
private fun checkIsContentValid(card: CardBrandPreview): Boolean {
val rawStr = output.content?.data?.replace(divider ?: " ", "") ?: ""
return if (canOverrideDefaultValidation || !card.successfullyDetected) {
isValid(rawStr)
} else {
val isLengthAppropriate: Boolean = checkLength(card.numberLength, rawStr.length)
val isLuhnValid: Boolean = validateCheckSum(card.algorithm, rawStr)
isLengthAppropriate && isLuhnValid
}
}
private fun validateCheckSum(
algorithm: ChecksumAlgorithm,
cardNumber: String
): Boolean {
return when (algorithm) {
ChecksumAlgorithm.LUHN -> LuhnCheckSumValidator().isValid(cardNumber)
ChecksumAlgorithm.NONE -> true
else -> false
}
}
private fun mapValue(item: CardBrandPreview) {
with(output.content as? FieldContent.CardNumberContent) {
this?.cardtype = item.cardType
this?.cardBrandName = item.name
this?.iconResId = item.resId
this?.numberRange = item.numberLength
this?.rangeCVV = item.cvcLength
}
}
private fun detectBrand(): CardBrandPreview {
for (i in cardFilters.indices) {
val filter = cardFilters[i]
return filter.detect(output.content?.data)
}
return CardBrandPreview()
}
private fun checkLength(
rangeNumber: Array<Int>,
length: Int?
): Boolean {
return rangeNumber.contains(length)
}
internal interface IDrawCardBrand {
fun onCardBrandPreview(
card: CardBrandPreview
)
}
} | 5 | Kotlin | 1 | 1 | 49fdede7a225435b37837f5396dcfea06217e275 | 3,921 | vgs-checkout-android | MIT License |
device-server/src/main/kotlin/com/badoo/automation/deviceserver/ios/simulator/data/DataContainer.kt | badoo | 133,063,088 | false | null | package com.badoo.automation.deviceserver.ios.simulator.data
import com.badoo.automation.deviceserver.LogMarkers
import com.badoo.automation.deviceserver.command.ShellUtils
import com.badoo.automation.deviceserver.host.IRemote
import net.logstash.logback.marker.MapEntriesAppendingMarker
import org.slf4j.LoggerFactory
import java.io.File
import java.lang.RuntimeException
import java.nio.file.Path
import java.time.Duration
class DataContainer(
private val remote: IRemote,
internal val basePath: File,
private val bundleId: String
) {
private val logger = LoggerFactory.getLogger(DataContainer::class.java.simpleName)
private val logMarker = MapEntriesAppendingMarker(mapOf(
LogMarkers.HOSTNAME to remote.hostName
))
fun listFiles(path: Path): List<String> {
val expandedPath = sshNoEscapingWorkaround(expandPath(path).toString())
val result = remote.execIgnoringErrors(listOf("ls", "-1", "-p", expandedPath))
if (!result.isSuccess) {
throw(DataContainerException("Could not list $path for $bundleId: $result"))
}
return result.stdOut.lines().filter { it.isNotEmpty() }
}
fun readFile(path: Path): ByteArray {
val expandedPath = sshNoEscapingWorkaround(expandPath(path).toString())
try {
return remote.captureFile(File(expandedPath))
} catch (e: RuntimeException) {
throw DataContainerException("Could not read file $path for $bundleId", e)
}
}
fun setPlistValue(path: Path, key: String, value: String) {
val expandedPath = sshNoEscapingWorkaround(expandPath(path).toString())
remote.shell("/usr/libexec/PlistBuddy -c 'Set $key $value' $expandedPath", false)
}
fun addPlistValue(path: Path, key: String, value: String, type: String) {
val expandedPath = sshNoEscapingWorkaround(expandPath(path).toString())
remote.shell("/usr/libexec/PlistBuddy -c 'Add $key $type $value' $expandedPath", false)
}
fun writeFile(file: File, data: ByteArray) {
val dataContainerFile = File(basePath.absolutePath, file.name)
if (remote.isLocalhost()) {
dataContainerFile.writeBytes(data)
logger.debug(logMarker, "Successfully wrote data to file ${dataContainerFile.absolutePath}")
} else {
writeRemoteFile(file, data, dataContainerFile)
}
}
private fun writeRemoteFile(file: File, data: ByteArray, dataContainerFile: File) {
val tmpFile = File.createTempFile("${file.nameWithoutExtension}.", ".${file.extension}")
try {
tmpFile.writeBytes(data)
remote.scpToRemoteHost(tmpFile.absolutePath, dataContainerFile.absolutePath, Duration.ofMinutes(1))
logger.debug(logMarker, "Successfully wrote data to remote file ${dataContainerFile.absolutePath}")
} finally {
tmpFile.delete()
}
}
private fun sshNoEscapingWorkaround(path: String): String {
// FIXME: fix escaping on ssh side and remove workarounds
return when {
remote.isLocalhost() -> path
else -> ShellUtils.escape(path)
}
}
private fun expandPath(path: Path): Path {
val expanded = basePath.toPath().resolve(path).normalize()
if (!expanded.startsWith(basePath.absolutePath)) {
throw DataContainerException("$path points outside the container of $bundleId")
}
return expanded
}
}
| 2 | Kotlin | 11 | 39 | 2569119e7d074356a320f5440470f74e1f41e4f3 | 3,503 | ios-device-server | MIT License |
common/src/main/java/jp/co/soramitsu/common/list/PayloadGenerator.kt | soramitsu | 278,060,397 | false | {"Kotlin": 4749089, "Java": 18796} | package jp.co.soramitsu.common.list
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
typealias DiffCheck<T, V> = (T) -> V
open class PayloadGenerator<T>(private vararg val checks: DiffCheck<T, *>) {
fun diff(first: T, second: T): List<DiffCheck<T, *>> {
return checks.filter { check -> check(first) != check(second) }
}
}
typealias UnknownPayloadHandler = (Any?) -> Unit
@Suppress("UNCHECKED_CAST")
fun <T, VH : RecyclerView.ViewHolder> ListAdapter<T, VH>.resolvePayload(
holder: VH,
position: Int,
payloads: List<Any>,
onUnknownPayload: UnknownPayloadHandler? = null,
onDiffCheck: (DiffCheck<T, *>) -> Unit
) {
if (payloads.isEmpty()) {
onBindViewHolder(holder, position)
} else {
when (val payload = payloads.first()) {
is List<*> -> {
val diffChecks = payload as List<DiffCheck<T, *>>
diffChecks.forEach(onDiffCheck)
}
else -> onUnknownPayload?.invoke(payload)
}
}
}
| 18 | Kotlin | 22 | 75 | c8074122fa171223eea6f6d6e434aa1041d1c71f | 1,065 | fearless-Android | Apache License 2.0 |
sample/src/main/java/com/wada811/viewsavedstatektx/sample/SampleView.kt | wada811 | 262,597,213 | false | {"Kotlin": 7267} | package com.wada811.viewsavedstatektx.sample
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import androidx.appcompat.widget.AppCompatTextView
import androidx.savedstate.SavedStateRegistry.AutoRecreated
import androidx.savedstate.SavedStateRegistryOwner
import com.wada811.viewsavedstatektx.savedState
class SampleView
@JvmOverloads
constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = android.R.attr.textViewStyle
) : AppCompatTextView(context, attrs, defStyleAttr) {
private val state by savedState()
private var count: Int by state.property(0)
override fun onAttachedToWindow() {
super.onAttachedToWindow()
text = "$count"
state.runOnNextRecreation<OnNextRecreation>()
}
private class OnNextRecreation : AutoRecreated {
override fun onRecreated(owner: SavedStateRegistryOwner) {
Log.d("View-SavedState-ktx", "SampleView: OnNextRecreation: $owner")
if (owner is SampleActivity) {
Log.d("View-SavedState-ktx", "SampleView: intent: ${owner.intent?.extras}")
} else if (owner is SampleFragment) {
Log.d("View-SavedState-ktx", "SampleView: arguments: ${owner.arguments}")
}
}
}
fun countUp() {
count++
text = "$count"
}
fun countDown() {
count--
text = "$count"
}
}
| 1 | Kotlin | 0 | 5 | fc3127a8a2d9e88a4bbaa5a96cdb650a0f2ff5e5 | 1,443 | View-SavedState-ktx | Apache License 2.0 |
modules/core/src/main/java/de/deutschebahn/bahnhoflive/repository/timetable/RawTimetable.kt | dbbahnhoflive | 267,806,942 | false | {"Kotlin": 1166808, "Java": 919061, "HTML": 43851} | package de.deutschebahn.bahnhoflive.repository.timetable
class RawTimetable {
} | 0 | Kotlin | 4 | 33 | ae72e13b97a60ca942b63ff36f8b982ea0a7bb4f | 80 | dbbahnhoflive-android | Apache License 2.0 |
Copy2Message/app/src/main/java/com/greimul/copy2message/viewmodel/HistoryViewModel.kt | GreimuL | 253,409,709 | false | null | package com.greimul.copy2message.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.viewModelScope
import com.greimul.copy2message.db.History
import com.greimul.copy2message.db.HistoryDatabase
import com.greimul.copy2message.db.HistoryRepo
import kotlinx.coroutines.launch
class HistoryViewModel(application:Application):AndroidViewModel(application) {
private val repo:HistoryRepo
val historyList:LiveData<List<History>>
init{
repo = HistoryRepo(HistoryDatabase.getDatabase(application).historyDao())
historyList = repo.historyList
}
fun insert(history:History) = viewModelScope.launch {
repo.insert(history)
}
fun deleteAll()=viewModelScope.launch {
repo.deleteAll()
}
} | 0 | Kotlin | 0 | 0 | dead147f44d67afe4033a94c6e2c54ee77ef776b | 838 | Copy2Message | MIT License |
core/ui/src/main/java/com/daryeou/app/core/ui/KakaoMediaItemCompatCard.kt | daryeou | 615,569,210 | false | null | package com.daryeou.app.core.ui
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.SubcomposeAsyncImage
import coil.request.ImageRequest
import coil.size.Size
import com.daryeou.app.core.designsystem.icon.AppIcons
import com.daryeou.app.core.designsystem.theme.AppTheme
import com.daryeou.app.core.model.kakao.KakaoSearchMediaBasicData
import com.daryeou.app.core.model.kakao.KakaoSearchMediaItemData
import com.daryeou.app.core.model.kakao.KakaoSearchMediaType
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
@Composable
fun KakaoMediaItemCompatCard(
modifier: Modifier = Modifier,
itemData: KakaoSearchMediaItemData,
isExpanded: Boolean = false,
onClickImage: (KakaoSearchMediaItemData) -> Unit,
onClickLink: (KakaoSearchMediaItemData) -> Unit,
onClickFavorite: (KakaoSearchMediaItemData) -> Unit,
) {
val localDensity = LocalDensity.current
val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
val createdDateText = formatter.format(itemData.mediaInfo.dateTime)
val imageAspectRatio = 1f
var imageUrl by remember { mutableStateOf(itemData.mediaInfo.thumbnailUrl) }
var isOriginalImageLoading by remember { mutableStateOf(false) }
var imageWidthFractionTarget by rememberSaveable { mutableStateOf(0.3f) }
var captionBackgroundAlphaTarget by rememberSaveable { mutableStateOf(0f) }
var titlePaddingTarget by rememberSaveable { mutableStateOf(0.3f) }
val imageWidthFraction: Float by animateFloatAsState(
targetValue = imageWidthFractionTarget,
animationSpec = tween(
durationMillis = 300,
),
)
val captionBackgroundAlpha: Float by animateFloatAsState(
targetValue = captionBackgroundAlphaTarget,
animationSpec = tween(
durationMillis = 300,
),
)
val titlePaddingFraction: Float by animateFloatAsState(
targetValue = titlePaddingTarget,
animationSpec = tween(
durationMillis = 300,
),
)
LaunchedEffect(isExpanded) {
if (isExpanded) {
imageWidthFractionTarget = 1f
captionBackgroundAlphaTarget = 0.5f
titlePaddingTarget = 0f
imageUrl = itemData.mediaInfo.originalUrl ?: itemData.mediaInfo.thumbnailUrl
isOriginalImageLoading = true
} else {
imageWidthFractionTarget = 0.3f
captionBackgroundAlphaTarget = 0f
titlePaddingTarget = 0.3f
}
}
Card(
modifier = modifier,
shape = RoundedCornerShape(0.dp),
) {
BoxWithConstraints(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
.clickable(
onClick = {
onClickImage(itemData)
},
),
) {
val imageSize = remember(imageWidthFractionTarget) {
with(localDensity) {
Size(
(maxWidth * imageWidthFractionTarget).toPx().toInt(),
(maxWidth * imageAspectRatio * imageWidthFractionTarget).toPx().toInt(),
)
}
}
SubcomposeAsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(imageUrl)
.size(imageSize)
.crossfade(true)
.build(),
contentDescription = "Media Image",
modifier = Modifier
.fillMaxWidth(imageWidthFraction)
.aspectRatio(imageAspectRatio),
contentScale = ContentScale.Crop,
loading = {
if (isOriginalImageLoading) {
originalImageLoading()
}
}
)
Column(
modifier = Modifier
.align(Alignment.TopStart)
.fillMaxWidth()
.wrapContentHeight()
.background(
color = MaterialTheme.colorScheme.surface.copy(
alpha = captionBackgroundAlpha,
),
)
.padding(start = maxWidth * titlePaddingFraction)
.padding(16.dp),
) {
Text(
text = itemData.mediaInfo.title,
modifier = Modifier
.wrapContentHeight(),
style = MaterialTheme.typography.bodyLarge,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = createdDateText,
modifier = Modifier
.wrapContentHeight(),
style = MaterialTheme.typography.labelLarge,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
Row(
modifier = Modifier
.align(Alignment.BottomStart)
.fillMaxWidth()
.wrapContentHeight()
.background(
color = MaterialTheme.colorScheme.surface.copy(
alpha = captionBackgroundAlpha,
),
),
verticalAlignment = Alignment.CenterVertically,
) {
Image(
modifier = Modifier
.size(36.dp)
.padding(6.dp),
imageVector = if (itemData.mediaInfo.mediaType == KakaoSearchMediaType.IMAGE) {
AppIcons.Image
} else {
AppIcons.Video
},
contentDescription = "Media Type",
)
Spacer(modifier = Modifier.weight(1f))
Icon(
imageVector = AppIcons.OpenInNew,
contentDescription = "Open Web",
modifier = Modifier
.size(36.dp)
.clip(
shape = CircleShape
)
.clickable(
onClick = {
onClickLink(itemData)
},
)
.padding(6.dp)
)
Icon(
imageVector = if (itemData.isFavorite) {
AppIcons.FavoriteFilled
} else {
AppIcons.Favorite
},
contentDescription = "Favorite",
modifier = Modifier
.size(36.dp)
.clip(
shape = CircleShape
)
.clickable(
onClick = {
onClickFavorite(itemData)
},
)
.padding(6.dp)
)
}
}
}
}
@Composable
private fun originalImageLoading() {
Column(
modifier = Modifier
.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
CircularProgressIndicator(
modifier = Modifier
.padding(30.dp)
.size(30.dp)
)
Text(
text = stringResource(id = R.string.media_item_original_loading),
style = MaterialTheme.typography.labelMedium
)
}
}
@Preview(
showBackground = true,
widthDp = 360,
heightDp = 640,
)
@Composable
internal fun MediaCompatCardPreview() {
AppTheme() {
var expanded by rememberSaveable() { mutableStateOf(false) }
Box(modifier = Modifier.fillMaxSize()) {
KakaoMediaItemCompatCard(
modifier = Modifier,
isExpanded = expanded,
itemData = KakaoSearchMediaItemData(
isFavorite = false,
KakaoSearchMediaBasicData(
title = "Title",
url = "https://www.naver.com",
thumbnailUrl = "https://www.simplilearn.com/ice9/free_resources_article_thumb/what_is_image_Processing.jpg",
dateTime = Date(),
mediaType = KakaoSearchMediaType.IMAGE,
)
),
onClickLink = {},
onClickImage = {
expanded = !expanded
},
onClickFavorite = {},
)
}
}
} | 0 | Kotlin | 0 | 1 | ec447dd197e25f751be0beb3862d0ee7580facca | 11,040 | kakao-assignment | The Unlicense |
components/proxy/src/test/kotlin/com/hotels/styx/routing/db/StyxObjectStoreTest.kt | ExpediaGroup | 106,841,635 | false | {"Java": 3091743, "Kotlin": 813315, "Scala": 394046, "JavaScript": 26394, "Python": 18089, "Shell": 14134, "HTML": 9844, "CSS": 8097, "Makefile": 5123, "Lua": 4188, "Dockerfile": 1629, "ANTLR": 1331, "Groovy": 132} | /*
Copyright (C) 2013-2023 Expedia Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.hotels.styx.routing.db
import com.hotels.styx.api.configuration.ObjectStore
import io.kotest.assertions.timing.eventually
import io.kotest.core.spec.style.FeatureSpec
import io.kotest.matchers.booleans.shouldBeTrue
import io.kotest.matchers.collections.shouldBeEmpty
import io.kotest.matchers.collections.shouldNotBeEmpty
import io.kotest.matchers.ints.shouldBeGreaterThanOrEqual
import io.kotest.matchers.longs.shouldBeGreaterThanOrEqual
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
import reactor.core.publisher.Flux
import reactor.kotlin.core.publisher.toFlux
import reactor.test.StepVerifier
import java.util.Optional
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.Executors.newFixedThreadPool
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeUnit.SECONDS
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
import kotlin.time.toJavaDuration
class StyxObjectStoreTest : FeatureSpec() {
init {
feature("Retrieval") {
scenario("Retrieves object by key") {
val db = StyxObjectStore<String>()
db.insert("redirect", "Record")
db.get("redirect") shouldBe Optional.of("Record")
}
scenario("Returns empty if object is not found") {
val db = StyxObjectStore<String>()
db.get("notfound") shouldBe Optional.empty()
}
scenario("Retrieves all entries") {
val db = StyxObjectStore<String>()
db.insert("x", "x")
db.insert("y", "y")
db.insert("z", "z")
db.entrySet().map { it.toPair() } shouldBe listOf(
"x" to "x",
"y" to "y",
"z" to "z"
)
}
}
feature("Insert") {
scenario("Notifies watchers for any change") {
val db = StyxObjectStore<String>()
StepVerifier.create(db.watch())
.expectNextCount(1)
.then { db.insert("x", "x") }
.assertNext {
it.get("x") shouldBe Optional.of("x")
it.get("y") shouldBe Optional.empty()
}
.then { db.insert("y", "y") }
.assertNext {
it.get("x") shouldBe Optional.of("x")
it.get("y") shouldBe Optional.of("y")
}
.thenCancel()
.log()
.verify(4.seconds.toJavaDuration())
db.watchers() shouldBe 0
}
scenario("Maintains database integrity in concurrent operations") {
val db = StyxObjectStore<String>()
val executor = newFixedThreadPool(8)
for (i in 1..10000) {
executor.execute { db.insert("redirect-$i", "Record-$i") }
}
executor.shutdown()
executor.awaitTermination(2, SECONDS)
for (i in 1..10000) {
db.get("redirect-$i") shouldBe (Optional.of("Record-$i"))
}
}
scenario("Maintains relative ordering between change and initial watch notifications") {
val executor = Executors.newSingleThreadExecutor()
val db = StyxObjectStore<Int>(executor)
val events = mutableListOf<Int>()
val watchConsumer = db.watch().toFlux().subscribe {
// Keeps the event notification thread busy to build up a backlog of events.
Thread.sleep(10)
}
db.insert("key", 1)
db.insert("key", 2)
val watcher = db.watch()
.toFlux()
.subscribe {
events.add(it.get("key").orElse(0xBAD_BEEF))
}
db.insert("key", 3)
db.insert("key", 4)
watchConsumer.dispose()
watcher.dispose()
executor.shutdown()
executor.awaitTermination(250, TimeUnit.MILLISECONDS)
// Ensure the events were delivered in order
events.fold(0) { acc, value ->
value.shouldNotBe(0xBAD_BEEF)
value.shouldBeGreaterThanOrEqual(acc)
value
}
}
scenario("Replaces already existing object") {
val db = StyxObjectStore<String>()
StepVerifier.create(db.watch())
.expectNextCount(1)
.then { db.insert("x", "x") }
.assertNext {
it.get("x") shouldBe Optional.of("x")
}
.then { db.insert("x", "x2") }
.assertNext {
it.get("x") shouldBe Optional.of("x2")
}
.thenCancel()
.verify(1.seconds.toJavaDuration())
db.get("x") shouldBe Optional.of("x2")
}
scenario("Returns Optional.empty, when no previous value exists") {
val db = StyxObjectStore<String>()
db.insert("key", "a-value") shouldBe Optional.empty()
}
scenario("Returns previous, replaced value") {
val db = StyxObjectStore<String>()
db.insert("key", "old-value") shouldBe Optional.empty()
db.insert("key", "new-value") shouldBe Optional.of("old-value")
}
}
feature("Compute") {
scenario("Compute a new value when key doesn't already exist") {
val db = StyxObjectStore<String>()
StepVerifier.create(db.watch())
.expectNextCount(1)
.then { db.compute("key") { currentEntry -> "first value" } }
.assertNext { it.get("key") shouldBe Optional.of("first value") }
.thenCancel()
.verify()
}
scenario("Retains the existing value") {
val db = StyxObjectStore<String>()
db.insert("key", "old value")
StepVerifier.create(db.watch())
.expectNextCount(1)
.then { db.compute("key") { currentEntry -> "old value" } }
.expectNoEvent(10.milliseconds.toJavaDuration())
.thenCancel()
.verify()
}
scenario("Replace an existing value") {
val db = StyxObjectStore<String>()
val latch = CountDownLatch(1)
db.addDispatchListener("_") {
when (it) {
is ChangeNotification ->
if (it.snapshot.index() == 1L) {
latch.countDown()
}
else -> { }
}
}
db.insert("key", "old value")
latch.await()
StepVerifier.create(db.watch())
.expectNextCount(1)
.then { db.compute("key") { currentEntry -> "new value" } }
.assertNext { it.get("key") shouldBe Optional.of("new value") }
.thenCancel()
.verify()
}
scenario("Deletes value if computation returns null") {
val db = StyxObjectStore<String>()
db.insert("key", "old value")
StepVerifier.create(db.watch())
.expectNextCount(1)
.then { db.compute("key") { currentEntry -> null } }
.assertNext { it.entrySet().filter { it.key === "key" }.size shouldBe 0 }
.thenCancel()
.verify()
}
scenario("Maintains relative ordering between change and initial watch notifications") {
val executor = Executors.newSingleThreadExecutor()
val db = StyxObjectStore<Int>(executor)
val events = mutableListOf<Int>()
val watchConsumer = db.watch().toFlux().subscribe {
// Keeps the event notification thread busy to build up a backlog of events.
Thread.sleep(10)
}
db.compute("key") { 1 }
db.compute("key") { 2 }
val watcher = db.watch()
.toFlux()
.subscribe {
events.add(it.get("key").orElse(0xBAD_BEEF))
}
db.compute("key") { 3 }
db.compute("key") { 4 }
watchConsumer.dispose()
watcher.dispose()
executor.shutdown()
executor.awaitTermination(250, TimeUnit.MILLISECONDS)
// Ensure the events were delivered in order
events.fold(0) { acc, value ->
value.shouldNotBe(0xBAD_BEEF)
value.shouldBeGreaterThanOrEqual(acc)
value
}
}
}
feature("Remove") {
scenario("Removes previously stored objects") {
val db = StyxObjectStore<String>()
db.insert("x", "x")
db.insert("y", "y")
db.get("x") shouldBe Optional.of("x")
db.get("y") shouldBe Optional.of("y")
db.remove("x")
db.remove("y")
db.get("x") shouldBe Optional.empty()
db.get("y") shouldBe Optional.empty()
}
scenario("Non-existent object doesn't trigger watchers") {
val db = StyxObjectStore<String>()
StepVerifier.create(db.watch())
.expectNextCount(1)
.then { db.remove("x") }
.expectNoEvent(500.milliseconds.toJavaDuration())
.thenCancel()
.verify()
db.insert("y", "Y")
StepVerifier.create(db.watch())
.expectNextCount(1)
.then { db.remove("x") }
.expectNoEvent(500.milliseconds.toJavaDuration())
.thenCancel()
.verify()
}
scenario("Notifies watchers") {
val db = StyxObjectStore<String>()
val watchEvents = CopyOnWriteArrayList<ObjectStore<String>>()
db.insert("x", "x")
db.insert("y", "y")
Flux.from(db.watch()).subscribe { watchEvents.add(it) }
eventually(1.seconds) {
watchEvents.size shouldBeGreaterThanOrEqual 1
watchEvents.last().get("x") shouldBe Optional.of("x")
}
db.remove("x")
db.remove("y")
eventually(1.seconds) {
watchEvents.last()["x"] shouldBe Optional.empty()
watchEvents.last()["y"] shouldBe Optional.empty()
}
}
scenario("Maintains database integrity in concurrent operations") {
val db = StyxObjectStore<String>()
// Populate database with data:
for (i in 1..10000) {
db.insert("redirect-$i", "Record-$i")
}
// Then remove everyting, concurrently:
val executor = newFixedThreadPool(8)
for (i in 1..10000) {
executor.execute { db.remove("redirect-$i") }
}
executor.shutdown()
executor.awaitTermination(2, SECONDS)
db.entrySet().shouldBeEmpty()
}
scenario("Maintains relative ordering between change and initial watch notifications") {
val executor = Executors.newSingleThreadExecutor()
val db = StyxObjectStore<Int>(executor)
db.insert("key-01", 1)
db.insert("key-02", 2)
db.insert("key-03", 3)
db.insert("key-04", 4)
val events = mutableListOf<Long>()
val watchConsumer = db.watch().toFlux().subscribe {
// Keeps the event notification thread busy to build up a backlog of events.
Thread.sleep(10)
}
db.remove("key-01")
db.remove("key-02")
val watcher = db.watch()
.toFlux()
.subscribe {
events.add(it.index())
}
db.remove("key-03")
db.remove("key-04")
watchConsumer.dispose()
watcher.dispose()
executor.shutdown()
executor.awaitTermination(250, TimeUnit.MILLISECONDS)
// Ensure the events were delivered in order
events.fold(0L) { previous, index ->
index.shouldBeGreaterThanOrEqual(previous)
index
}
}
scenario("Returns Optional.empty, when previous value doesn't exist") {
val db = StyxObjectStore<String>()
db.remove("key") shouldBe Optional.empty()
}
scenario("Returns previous, replaced value") {
val db = StyxObjectStore<String>()
db.insert("key", "a-value") shouldBe Optional.empty()
db.remove("key") shouldBe Optional.of("a-value")
}
}
feature("Watch") {
scenario("Publishes an immutable final state snapshot") {
val db = StyxObjectStore<String>()
val watchEvents = CopyOnWriteArrayList<ObjectStore<String>>()
val watcher = db.watch().toFlux().subscribe { watchEvents.add(it) }
eventually(1.seconds) {
watchEvents.isNotEmpty().shouldBeTrue()
watchEvents[0].get("x") shouldBe Optional.empty()
watchEvents[0].get("y") shouldBe Optional.empty()
}
db.insert("x", "x")
db.insert("y", "y")
eventually(1.seconds) {
watchEvents.last()["x"].isPresent.shouldBeTrue()
watchEvents.last()["y"].isPresent.shouldBeTrue()
}
watcher.dispose()
db.watchers() shouldBe 0
}
scenario("Supports multiple watchers") {
for (x in 0..100) {
val db = StyxObjectStore<String>()
val watchEvents1 = CopyOnWriteArrayList<ObjectStore<String>>()
val watchEvents2 = CopyOnWriteArrayList<ObjectStore<String>>()
val watcher1 = Flux.from(db.watch()).subscribe { watchEvents1.add(it) }
val watcher2 = Flux.from(db.watch()).subscribe { watchEvents2.add(it) }
// Wait for the initial watch event ...
eventually(1.seconds) {
watchEvents1.size shouldBe 1
watchEvents1[0].get("x") shouldBe Optional.empty()
watchEvents2.size shouldBe 1
watchEvents2[0].get("x") shouldBe Optional.empty()
}
db.insert("x", "x")
db.insert("y", "y")
// ... otherwise we aren't guaranteed what events are going show up.
//
// The ordering between initial watch event in relation to objectStore.inserts are
// non-deterministic.
eventually(1.seconds) {
watchEvents1.last()["x"].isPresent.shouldBeTrue()
watchEvents1.last()["y"].isPresent.shouldBeTrue()
watchEvents1.last()["x"].shouldBe(Optional.of("x"))
watchEvents1.last()["y"].shouldBe(Optional.of("y"))
}
watcher1.dispose()
db.watchers() shouldBe 1
watcher2.dispose()
db.watchers() shouldBe 0
}
}
scenario("Provides current snapshot at subscription") {
val db = StyxObjectStore<String>()
val watchEvents = CopyOnWriteArrayList<ObjectStore<String>>()
db.insert("x", "x")
Flux.from(db.watch()).subscribe {
watchEvents.add(it)
}
eventually(1.seconds) {
watchEvents.isNotEmpty().shouldBeTrue()
watchEvents[0].get("x") shouldBe Optional.of("x")
}
}
scenario("Snapshot provides all entries") {
val db = StyxObjectStore<String>()
val watchEvents = CopyOnWriteArrayList<ObjectStore<String>>()
db.insert("x", "payload-x")
db.insert("y", "payload-y")
Flux.from(db.watch()).subscribe {
watchEvents.add(it)
}
eventually(1.seconds) {
watchEvents.shouldNotBeEmpty()
watchEvents.last()
.entrySet()
.map { it.toPair() }
.let {
it shouldBe listOf(
"x" to "payload-x",
"y" to "payload-y")
}
}
db.remove("y")
eventually(1.seconds) {
watchEvents.shouldNotBeEmpty()
watchEvents.last()
.entrySet()
.map { it.toPair() }
.let {
it shouldBe listOf(
"x" to "payload-x")
}
}
db.insert("z", "payload-z")
eventually(1.seconds) {
watchEvents.shouldNotBeEmpty()
watchEvents.last()
.entrySet()
.map { it.toPair() }
.let {
it shouldBe listOf(
"x" to "payload-x",
"z" to "payload-z")
}
}
}
}
}
}
| 2 | Java | 81 | 249 | abf4df67929980ef0cdae6b06c891fa749000954 | 20,150 | styx | Apache License 2.0 |
node/src/test/kotlin/net/corda/node/services/vault/NodeVaultServiceTest.kt | corda | 70,137,417 | false | {"Kotlin": 10573028, "Java": 270270, "C++": 239894, "Python": 37811, "Shell": 28320, "CSS": 23544, "Groovy": 14473, "CMake": 5393, "Dockerfile": 2575, "Batchfile": 1777, "PowerShell": 660, "C": 454} | package net.corda.node.services.vault
import co.paralleluniverse.fibers.Suspendable
import org.mockito.kotlin.argThat
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
import net.corda.core.contracts.*
import net.corda.core.crypto.NullKeys
import net.corda.core.crypto.SecureHash
import net.corda.core.crypto.generateKeyPair
import net.corda.core.identity.*
import net.corda.core.internal.NotaryChangeTransactionBuilder
import net.corda.core.internal.packageName
import net.corda.core.node.NotaryInfo
import net.corda.core.node.StatesToRecord
import net.corda.core.node.services.*
import net.corda.core.node.services.vault.PageSpecification
import net.corda.core.node.services.vault.QueryCriteria
import net.corda.core.node.services.vault.QueryCriteria.*
import net.corda.core.transactions.SignedTransaction
import net.corda.core.transactions.TransactionBuilder
import net.corda.core.utilities.NonEmptySet
import net.corda.core.utilities.OpaqueBytes
import net.corda.core.utilities.getOrThrow
import net.corda.core.utilities.toNonEmptySet
import net.corda.finance.*
import net.corda.finance.contracts.asset.Cash
import net.corda.finance.contracts.utils.sumCash
import net.corda.finance.schemas.CashSchemaV1
import net.corda.finance.workflows.asset.CashUtils
import net.corda.finance.workflows.getCashBalance
import net.corda.node.services.api.WritableTransactionStorage
import net.corda.nodeapi.internal.persistence.CordaPersistence
import net.corda.testing.common.internal.testNetworkParameters
import net.corda.testing.contracts.DummyContract
import net.corda.testing.contracts.DummyState
import net.corda.testing.core.*
import net.corda.testing.internal.LogHelper
import net.corda.testing.internal.vault.*
import net.corda.testing.node.MockServices
import net.corda.testing.node.makeTestIdentityService
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatExceptionOfType
import org.junit.*
import org.mockito.Mockito.doReturn
import rx.observers.TestSubscriber
import java.math.BigDecimal
import java.security.PublicKey
import java.util.*
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import javax.persistence.PersistenceException
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class NodeVaultServiceTest {
private companion object {
val cordappPackages = listOf("net.corda.finance.contracts.asset", CashSchemaV1::class.packageName, "net.corda.testing.contracts",
"net.corda.testing.internal.vault")
val dummyCashIssuer = TestIdentity(CordaX500Name("Snake Oil Issuer", "London", "GB"), 10)
val DUMMY_CASH_ISSUER = dummyCashIssuer.ref(1)
val bankOfCorda = TestIdentity(BOC_NAME)
val dummyNotary = TestIdentity(DUMMY_NOTARY_NAME, 20)
val megaCorp = TestIdentity(CordaX500Name("MegaCorp", "London", "GB"))
val miniCorp = TestIdentity(CordaX500Name("MiniCorp", "London", "GB"))
val BOC get() = bankOfCorda.party
val BOC_IDENTITY get() = bankOfCorda.identity
val DUMMY_CASH_ISSUER_IDENTITY get() = dummyCashIssuer.identity
val DUMMY_NOTARY get() = dummyNotary.party
val DUMMY_NOTARY_IDENTITY get() = dummyNotary.identity
val MEGA_CORP get() = megaCorp.party
val MEGA_CORP_KEY get() = megaCorp.keyPair
val MEGA_CORP_PUBKEY get() = megaCorp.publicKey
val MEGA_CORP_IDENTITY get() = megaCorp.identity
val MINI_CORP get() = miniCorp.party
val MINI_CORP_IDENTITY get() = miniCorp.identity
}
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
private lateinit var services: MockServices
private lateinit var vaultFiller: VaultFiller
private lateinit var identity: PartyAndCertificate
private lateinit var issuerServices: MockServices
private lateinit var bocServices: MockServices
private val vaultService get() = services.vaultService as NodeVaultService
private lateinit var database: CordaPersistence
@Before
fun setUp() {
LogHelper.setLevel(NodeVaultService::class)
val parameters = testNetworkParameters(notaries = listOf(NotaryInfo(DUMMY_NOTARY, true)))
val databaseAndServices = MockServices.makeTestDatabaseAndMockServices(
cordappPackages,
makeTestIdentityService(MEGA_CORP_IDENTITY, MINI_CORP_IDENTITY, DUMMY_CASH_ISSUER_IDENTITY, DUMMY_NOTARY_IDENTITY),
megaCorp,
parameters)
database = databaseAndServices.first
services = databaseAndServices.second
vaultFiller = VaultFiller(services, dummyNotary)
// This is safe because MockServices only ever have a single identity
identity = services.myInfo.singleIdentityAndCert()
issuerServices = MockServices(cordappPackages, dummyCashIssuer, mock(), parameters)
bocServices = MockServices(cordappPackages, bankOfCorda, mock(), parameters)
services.identityService.verifyAndRegisterIdentity(DUMMY_CASH_ISSUER_IDENTITY)
services.identityService.verifyAndRegisterIdentity(BOC_IDENTITY)
}
@After
fun tearDown() {
database.close()
LogHelper.reset(NodeVaultService::class)
}
@Suspendable
private fun VaultService.unconsumedCashStatesForSpending(amount: Amount<Currency>,
onlyFromIssuerParties: Set<AbstractParty>? = null,
notary: Party? = null,
lockId: UUID = UUID.randomUUID(),
withIssuerRefs: Set<OpaqueBytes>? = null): List<StateAndRef<Cash.State>> {
val notaries = if (notary != null) listOf(notary) else null
var baseCriteria: QueryCriteria = QueryCriteria.VaultQueryCriteria(notary = notaries)
if (onlyFromIssuerParties != null || withIssuerRefs != null) {
baseCriteria = baseCriteria.and(QueryCriteria.FungibleAssetQueryCriteria(
issuer = onlyFromIssuerParties?.toList(),
issuerRef = withIssuerRefs?.toList()))
}
return tryLockFungibleStatesForSpending(lockId, baseCriteria, amount, Cash.State::class.java)
}
class FungibleFoo(override val amount: Amount<Currency>, override val participants: List<AbstractParty>) : FungibleState<Currency>
@Test(timeout=300_000)
fun `fungible state selection test`() {
val issuerParty = services.myInfo.legalIdentities.first()
val fungibleFoo = FungibleFoo(100.DOLLARS, listOf(issuerParty))
services.apply {
val tx = signInitialTransaction(TransactionBuilder(DUMMY_NOTARY).apply {
addCommand(Command(DummyContract.Commands.Create(), issuerParty.owningKey))
addOutputState(fungibleFoo, DummyContract.PROGRAM_ID)
})
recordTransactions(listOf(tx))
}
val baseCriteria: QueryCriteria = QueryCriteria.VaultQueryCriteria(notary = listOf(DUMMY_NOTARY))
database.transaction {
val states = services.vaultService.tryLockFungibleStatesForSpending(
lockId = UUID.randomUUID(),
eligibleStatesQuery = baseCriteria,
amount = 10.DOLLARS,
contractStateType = FungibleFoo::class.java
)
assertEquals(states.single().state.data.amount, 100.DOLLARS)
}
}
@Test(timeout=300_000)
fun `duplicate insert of transaction does not fail`() {
database.transaction {
val cash = Cash()
val howMuch = 100.DOLLARS
val issuance = TransactionBuilder(null as Party?)
cash.generateIssue(issuance, Amount(howMuch.quantity, Issued(DUMMY_CASH_ISSUER, howMuch.token)), services.myInfo.singleIdentity(), dummyNotary.party)
val transaction = issuerServices.signInitialTransaction(issuance, DUMMY_CASH_ISSUER.party.owningKey)
services.recordTransactions(transaction)
services.recordTransactions(transaction)
}
}
@Test(timeout=300_000)
fun `can query with page size max-integer`() {
database.transaction {
vaultFiller.fillWithSomeTestCash(100.DOLLARS, issuerServices, 3, DUMMY_CASH_ISSUER)
}
database.transaction {
val w1 = vaultService.queryBy<Cash.State>(PageSpecification(pageNumber = 1, pageSize = Integer.MAX_VALUE)).states
assertThat(w1).hasSize(3)
}
}
@Test(timeout=300_000)
fun `states not local to instance`() {
database.transaction {
vaultFiller.fillWithSomeTestCash(100.DOLLARS, issuerServices, 3, DUMMY_CASH_ISSUER)
}
database.transaction {
val w1 = vaultService.queryBy<Cash.State>().states
assertThat(w1).hasSize(3)
val originalVault = vaultService
val services2 = object : MockServices(emptyList(), MEGA_CORP.name, mock()) {
override val vaultService: NodeVaultService get() = originalVault
override fun recordTransactions(statesToRecord: StatesToRecord, txs: Iterable<SignedTransaction>) {
for (stx in txs) {
(validatedTransactions as WritableTransactionStorage).addTransaction(stx)
vaultService.notify(statesToRecord, stx.tx)
}
}
}
val w2 = services2.vaultService.queryBy<Cash.State>().states
assertThat(w2).hasSize(3)
}
}
@Test(timeout=300_000)
fun `states for refs`() {
database.transaction {
vaultFiller.fillWithSomeTestCash(100.DOLLARS, issuerServices, 3, DUMMY_CASH_ISSUER)
}
database.transaction {
val w1 = vaultService.queryBy<Cash.State>().states
assertThat(w1).hasSize(3)
val states = vaultService.queryBy<Cash.State>(VaultQueryCriteria(stateRefs = listOf(w1[1].ref, w1[2].ref))).states
assertThat(states).hasSize(2)
}
}
@Test(timeout=300_000)
fun `states soft locking reserve and release`() {
database.transaction {
vaultFiller.fillWithSomeTestCash(100.DOLLARS, issuerServices, 3, DUMMY_CASH_ISSUER)
}
database.transaction {
val unconsumedStates = vaultService.queryBy<Cash.State>().states
assertThat(unconsumedStates).hasSize(3)
val stateRefsToSoftLock = NonEmptySet.of(unconsumedStates[1].ref, unconsumedStates[2].ref)
// soft lock two of the three states
val softLockId = UUID.randomUUID()
vaultService.softLockReserve(softLockId, stateRefsToSoftLock)
// all softlocked states
val criteriaLocked = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.LOCKED_ONLY))
assertThat(vaultService.queryBy<Cash.State>(criteriaLocked).states).hasSize(2)
// my softlocked states
val criteriaByLockId = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.SPECIFIED, listOf(softLockId)))
assertThat(vaultService.queryBy<Cash.State>(criteriaByLockId).states).hasSize(2)
// excluding softlocked states
val unlockedStates1 = vaultService.queryBy<Cash.State>(VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.UNLOCKED_ONLY))).states
assertThat(unlockedStates1).hasSize(1)
// soft lock release one of the states explicitly
vaultService.softLockRelease(softLockId, NonEmptySet.of(unconsumedStates[1].ref))
val unlockedStates2 = vaultService.queryBy<Cash.State>(VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.UNLOCKED_ONLY))).states
assertThat(unlockedStates2).hasSize(2)
// soft lock release the rest by id
vaultService.softLockRelease(softLockId)
val unlockedStates = vaultService.queryBy<Cash.State>(VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.UNLOCKED_ONLY))).states
assertThat(unlockedStates).hasSize(3)
// should be back to original states
assertThat(unlockedStates).isEqualTo(unconsumedStates)
}
}
@Test(timeout=300_000)
fun `soft locking attempt concurrent reserve`() {
val backgroundExecutor = Executors.newFixedThreadPool(2)
val countDown = CountDownLatch(2)
val softLockId1 = UUID.randomUUID()
val softLockId2 = UUID.randomUUID()
val criteriaByLockId1 = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.SPECIFIED, listOf(softLockId1)))
val criteriaByLockId2 = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.SPECIFIED, listOf(softLockId2)))
val vaultStates =
database.transaction {
assertEquals(0.DOLLARS, services.getCashBalance(USD))
vaultFiller.fillWithSomeTestCash(100.DOLLARS, issuerServices, 3, DUMMY_CASH_ISSUER)
}
val stateRefsToSoftLock = (vaultStates.states.map { it.ref }).toNonEmptySet()
println("State Refs:: $stateRefsToSoftLock")
// 1st tx locks states
backgroundExecutor.submit {
try {
database.transaction {
vaultService.softLockReserve(softLockId1, stateRefsToSoftLock)
assertThat(vaultService.queryBy<Cash.State>(criteriaByLockId1).states).hasSize(3)
}
println("SOFT LOCK STATES #1 succeeded")
} catch (e: Exception) {
println("SOFT LOCK STATES #1 failed")
} finally {
countDown.countDown()
}
}
// 2nd tx attempts to lock same states
backgroundExecutor.submit {
try {
Thread.sleep(100) // let 1st thread soft lock them 1st
database.transaction {
vaultService.softLockReserve(softLockId2, stateRefsToSoftLock)
assertThat(vaultService.queryBy<Cash.State>(criteriaByLockId2).states).hasSize(3)
}
println("SOFT LOCK STATES #2 succeeded")
} catch (e: Exception) {
println("SOFT LOCK STATES #2 failed")
} finally {
countDown.countDown()
}
}
countDown.await()
database.transaction {
val lockStatesId1 = vaultService.queryBy<Cash.State>(criteriaByLockId1).states
println("SOFT LOCK #1 final states: $lockStatesId1")
assertThat(lockStatesId1.size).isIn(0, 3)
val lockStatesId2 = vaultService.queryBy<Cash.State>(criteriaByLockId2).states
println("SOFT LOCK #2 final states: $lockStatesId2")
assertThat(lockStatesId2.size).isIn(0, 3)
}
}
@Test(timeout=300_000)
fun `soft locking partial reserve states fails`() {
val softLockId1 = UUID.randomUUID()
val softLockId2 = UUID.randomUUID()
val vaultStates =
database.transaction {
assertEquals(0.DOLLARS, services.getCashBalance(USD))
vaultFiller.fillWithSomeTestCash(100.DOLLARS, issuerServices, 3, DUMMY_CASH_ISSUER)
}
val stateRefsToSoftLock = vaultStates.states.map { it.ref }
println("State Refs:: $stateRefsToSoftLock")
// lock 1st state with LockId1
database.transaction {
vaultService.softLockReserve(softLockId1, NonEmptySet.of(stateRefsToSoftLock.first()))
val criteriaByLockId1 = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.SPECIFIED, listOf(softLockId1)))
assertThat(vaultService.queryBy<Cash.State>(criteriaByLockId1).states).hasSize(1)
}
// attempt to lock all 3 states with LockId2
database.transaction {
assertThatExceptionOfType(StatesNotAvailableException::class.java).isThrownBy(
{ vaultService.softLockReserve(softLockId2, stateRefsToSoftLock.toNonEmptySet()) }
).withMessageContaining("only 2 rows available").withNoCause()
}
}
@Test(timeout=300_000)
fun `attempt to lock states already soft locked by me`() {
val softLockId1 = UUID.randomUUID()
val criteriaByLockId1 = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.SPECIFIED, listOf(softLockId1)))
val vaultStates =
database.transaction {
assertEquals(0.DOLLARS, services.getCashBalance(USD))
vaultFiller.fillWithSomeTestCash(100.DOLLARS, issuerServices, 3, DUMMY_CASH_ISSUER)
}
val stateRefsToSoftLock = (vaultStates.states.map { it.ref }).toNonEmptySet()
println("State Refs:: $stateRefsToSoftLock")
// lock states with LockId1
database.transaction {
vaultService.softLockReserve(softLockId1, stateRefsToSoftLock)
assertThat(vaultService.queryBy<Cash.State>(criteriaByLockId1).states).hasSize(3)
}
// attempt to relock same states with LockId1
database.transaction {
vaultService.softLockReserve(softLockId1, stateRefsToSoftLock)
assertThat(vaultService.queryBy<Cash.State>(criteriaByLockId1).states).hasSize(3)
}
}
@Test(timeout=300_000)
fun `lock additional states to some already soft locked by me`() {
val softLockId1 = UUID.randomUUID()
val criteriaByLockId1 = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.SPECIFIED, listOf(softLockId1)))
val vaultStates =
database.transaction {
assertEquals(0.DOLLARS, services.getCashBalance(USD))
vaultFiller.fillWithSomeTestCash(100.DOLLARS, issuerServices, 3, DUMMY_CASH_ISSUER)
}
val stateRefsToSoftLock = vaultStates.states.map { it.ref }
println("State Refs:: $stateRefsToSoftLock")
// lock states with LockId1
database.transaction {
vaultService.softLockReserve(softLockId1, NonEmptySet.of(stateRefsToSoftLock.first()))
assertThat(vaultService.queryBy<Cash.State>(criteriaByLockId1).states).hasSize(1)
}
// attempt to lock all states with LockId1 (including previously already locked one)
database.transaction {
vaultService.softLockReserve(softLockId1, stateRefsToSoftLock.toNonEmptySet())
assertThat(vaultService.queryBy<Cash.State>(criteriaByLockId1).states).hasSize(3)
}
}
@Test(timeout=300_000)
fun `softLockRelease - correctly releases n locked states`() {
fun queryStates(softLockingType: SoftLockingType) =
vaultService.queryBy<Cash.State>(VaultQueryCriteria(softLockingCondition = SoftLockingCondition(softLockingType))).states
database.transaction {
vaultFiller.fillWithSomeTestCash(100.DOLLARS, issuerServices, 100, DUMMY_CASH_ISSUER)
}
val softLockId = UUID.randomUUID()
val lockCount = NodeVaultService.DEFAULT_SOFT_LOCKING_SQL_IN_CLAUSE_SIZE * 2
database.transaction {
assertEquals(100, queryStates(SoftLockingType.UNLOCKED_ONLY).size)
val unconsumedStates = vaultService.queryBy<Cash.State>().states
val lockSet = mutableListOf<StateRef>()
for (i in 0 until lockCount) {
lockSet.add(unconsumedStates[i].ref)
}
vaultService.softLockReserve(softLockId, NonEmptySet.copyOf(lockSet))
assertEquals(lockCount, queryStates(SoftLockingType.LOCKED_ONLY).size)
val unlockSet0 = mutableSetOf<StateRef>()
for (i in 0 until NodeVaultService.DEFAULT_SOFT_LOCKING_SQL_IN_CLAUSE_SIZE + 1) {
unlockSet0.add(lockSet[i])
}
vaultService.softLockRelease(softLockId, NonEmptySet.copyOf(unlockSet0))
assertEquals(NodeVaultService.DEFAULT_SOFT_LOCKING_SQL_IN_CLAUSE_SIZE - 1, queryStates(SoftLockingType.LOCKED_ONLY).size)
val unlockSet1 = mutableSetOf<StateRef>()
for (i in NodeVaultService.DEFAULT_SOFT_LOCKING_SQL_IN_CLAUSE_SIZE + 1 until NodeVaultService.DEFAULT_SOFT_LOCKING_SQL_IN_CLAUSE_SIZE + 3) {
unlockSet1.add(lockSet[i])
}
vaultService.softLockRelease(softLockId, NonEmptySet.copyOf(unlockSet1))
assertEquals(NodeVaultService.DEFAULT_SOFT_LOCKING_SQL_IN_CLAUSE_SIZE - 1 - 2, queryStates(SoftLockingType.LOCKED_ONLY).size)
vaultService.softLockRelease(softLockId) // release the rest
assertEquals(100, queryStates(SoftLockingType.UNLOCKED_ONLY).size)
}
}
@Test(timeout=300_000)
fun `unconsumedStatesForSpending exact amount`() {
database.transaction {
vaultFiller.fillWithSomeTestCash(100.DOLLARS, issuerServices, 1, DUMMY_CASH_ISSUER)
}
database.transaction {
val unconsumedStates = vaultService.queryBy<Cash.State>().states
assertThat(unconsumedStates).hasSize(1)
val spendableStatesUSD = vaultService.unconsumedCashStatesForSpending(100.DOLLARS)
spendableStatesUSD.forEach(::println)
assertThat(spendableStatesUSD).hasSize(1)
assertThat(spendableStatesUSD[0].state.data.amount.quantity).isEqualTo(100L * 100)
val criteriaLocked = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.LOCKED_ONLY))
assertThat(vaultService.queryBy<Cash.State>(criteriaLocked).states).hasSize(1)
}
}
@Test(timeout=300_000)
fun `unconsumedStatesForSpending from two issuer parties`() {
database.transaction {
vaultFiller.fillWithSomeTestCash(100.DOLLARS, issuerServices, 1, DUMMY_CASH_ISSUER)
vaultFiller.fillWithSomeTestCash(100.DOLLARS, bocServices, 1, BOC.ref(1))
}
database.transaction {
val spendableStatesUSD = vaultService.unconsumedCashStatesForSpending(200.DOLLARS,
onlyFromIssuerParties = setOf(DUMMY_CASH_ISSUER.party, BOC))
spendableStatesUSD.forEach(::println)
assertThat(spendableStatesUSD).hasSize(2)
assertThat(spendableStatesUSD[0].state.data.amount.token.issuer).isIn(DUMMY_CASH_ISSUER, BOC.ref(1))
assertThat(spendableStatesUSD[1].state.data.amount.token.issuer).isIn(DUMMY_CASH_ISSUER, BOC.ref(1))
assertThat(spendableStatesUSD[0].state.data.amount.token.issuer).isNotEqualTo(spendableStatesUSD[1].state.data.amount.token.issuer)
}
}
@Test(timeout=300_000)
fun `unconsumedStatesForSpending from specific issuer party and refs`() {
database.transaction {
vaultFiller.fillWithSomeTestCash(100.DOLLARS, issuerServices, 1, DUMMY_CASH_ISSUER)
vaultFiller.fillWithSomeTestCash(100.DOLLARS, bocServices, 1, BOC.ref(1))
vaultFiller.fillWithSomeTestCash(100.DOLLARS, bocServices, 1, BOC.ref(2))
vaultFiller.fillWithSomeTestCash(100.DOLLARS, bocServices, 1, BOC.ref(3))
}
database.transaction {
val unconsumedStates = vaultService.queryBy<Cash.State>().states
assertThat(unconsumedStates).hasSize(4)
val spendableStatesUSD = vaultService.unconsumedCashStatesForSpending(200.DOLLARS,
onlyFromIssuerParties = setOf(BOC), withIssuerRefs = setOf(OpaqueBytes.of(1), OpaqueBytes.of(2)))
assertThat(spendableStatesUSD).hasSize(2)
assertThat(spendableStatesUSD[0].state.data.amount.token.issuer.party).isEqualTo(BOC)
assertThat(spendableStatesUSD[0].state.data.amount.token.issuer.reference).isIn(BOC.ref(1).reference, BOC.ref(2).reference)
assertThat(spendableStatesUSD[1].state.data.amount.token.issuer.reference).isIn(BOC.ref(1).reference, BOC.ref(2).reference)
assertThat(spendableStatesUSD[0].state.data.amount.token.issuer.reference).isNotEqualTo(spendableStatesUSD[1].state.data.amount.token.issuer.reference)
}
}
@Test(timeout=300_000)
fun `unconsumedStatesForSpending insufficient amount`() {
database.transaction {
vaultFiller.fillWithSomeTestCash(100.DOLLARS, issuerServices, 1, DUMMY_CASH_ISSUER)
}
database.transaction {
val unconsumedStates = vaultService.queryBy<Cash.State>().states
assertThat(unconsumedStates).hasSize(1)
val spendableStatesUSD = vaultService.unconsumedCashStatesForSpending(110.DOLLARS)
spendableStatesUSD.forEach(::println)
assertThat(spendableStatesUSD).hasSize(0)
val criteriaLocked = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.LOCKED_ONLY))
assertThat(vaultService.queryBy<Cash.State>(criteriaLocked).states).hasSize(0)
}
}
@Test(timeout=300_000)
fun `unconsumedStatesForSpending small amount`() {
database.transaction {
vaultFiller.fillWithSomeTestCash(100.DOLLARS, issuerServices, 2, DUMMY_CASH_ISSUER)
}
database.transaction {
val unconsumedStates = vaultService.queryBy<Cash.State>().states
assertThat(unconsumedStates).hasSize(2)
val spendableStatesUSD = vaultService.unconsumedCashStatesForSpending(1.DOLLARS)
spendableStatesUSD.forEach(::println)
assertThat(spendableStatesUSD).hasSize(1)
assertThat(spendableStatesUSD[0].state.data.amount.quantity).isGreaterThanOrEqualTo(100L)
val criteriaLocked = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.LOCKED_ONLY))
assertThat(vaultService.queryBy<Cash.State>(criteriaLocked).states).hasSize(1)
}
}
@Test(timeout=300_000)
fun `states soft locking query granularity`() {
database.transaction {
listOf(USD, GBP, CHF).forEach {
vaultFiller.fillWithSomeTestCash(AMOUNT(100, it), issuerServices, 10, DUMMY_CASH_ISSUER)
}
}
database.transaction {
var unlockedStates = 30
val allStates = vaultService.queryBy<Cash.State>().states
assertThat(allStates).hasSize(unlockedStates)
var lockedCount = 0
for (i in 1..5) {
val lockId = UUID.randomUUID()
val spendableStatesUSD = vaultService.unconsumedCashStatesForSpending(20.DOLLARS, lockId = lockId)
spendableStatesUSD.forEach(::println)
assertThat(spendableStatesUSD.size <= unlockedStates)
unlockedStates -= spendableStatesUSD.size
val criteriaLocked = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.SPECIFIED, listOf(lockId)))
val lockedStates = vaultService.queryBy<Cash.State>(criteriaLocked).states
if (spendableStatesUSD.isNotEmpty()) {
assertEquals(spendableStatesUSD.size, lockedStates.size)
val lockedTotal = lockedStates.map { it.state.data }.sumCash()
val foundAmount = spendableStatesUSD.map { it.state.data }.sumCash()
assertThat(foundAmount.toDecimal() >= BigDecimal("20.00"))
assertThat(lockedTotal == foundAmount)
lockedCount += lockedStates.size
}
}
val criteriaLocked = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.LOCKED_ONLY))
assertThat(vaultService.queryBy<Cash.State>(criteriaLocked).states).hasSize(lockedCount)
}
}
@Test(timeout=300_000)
fun addNoteToTransaction() {
val megaCorpServices = MockServices(cordappPackages, MEGA_CORP.name, mock(), MEGA_CORP_KEY)
database.transaction {
val freshKey = identity.owningKey
// Issue a txn to Send us some Money
val usefulBuilder = TransactionBuilder(null).apply {
Cash().generateIssue(this, 100.DOLLARS `issued by` MEGA_CORP.ref(1), AnonymousParty(freshKey), DUMMY_NOTARY)
}
val usefulTX = megaCorpServices.signInitialTransaction(usefulBuilder)
services.recordTransactions(usefulTX)
vaultService.addNoteToTransaction(usefulTX.id, "USD Sample Note 1")
vaultService.addNoteToTransaction(usefulTX.id, "USD Sample Note 2")
vaultService.addNoteToTransaction(usefulTX.id, "USD Sample Note 3")
assertEquals(3, vaultService.getTransactionNotes(usefulTX.id).count())
// Issue more Money (GBP)
val anotherBuilder = TransactionBuilder(null).apply {
Cash().generateIssue(this, 200.POUNDS `issued by` MEGA_CORP.ref(1), AnonymousParty(freshKey), DUMMY_NOTARY)
}
val anotherTX = megaCorpServices.signInitialTransaction(anotherBuilder)
services.recordTransactions(anotherTX)
vaultService.addNoteToTransaction(anotherTX.id, "GBP Sample Note 1")
assertEquals(1, vaultService.getTransactionNotes(anotherTX.id).count())
}
}
@Test(timeout=300_000)
fun `is ownable state relevant`() {
val myAnonymousIdentity = services.keyManagementService.freshKeyAndCert(identity, false)
val myKeys = services.keyManagementService.filterMyKeys(listOf(identity.owningKey, myAnonymousIdentity.owningKey)).toSet()
// Well-known owner
assertTrue { myKeys.isOwnableStateRelevant(identity.party, participants = emptyList()) }
// Anonymous owner
assertTrue { myKeys.isOwnableStateRelevant(myAnonymousIdentity.party, participants = emptyList()) }
// Unknown owner
assertFalse { myKeys.isOwnableStateRelevant(createUnknownIdentity(), participants = emptyList()) }
// Under target version 3 only the owner is relevant. This is to preserve backwards compatibility
assertFalse { myKeys.isOwnableStateRelevant(createUnknownIdentity(), participants = listOf(identity.party)) }
}
private fun createUnknownIdentity() = AnonymousParty(generateKeyPair().public)
private fun Set<PublicKey>.isOwnableStateRelevant(owner: AbstractParty, participants: List<AbstractParty>): Boolean {
class TestOwnableState : OwnableState {
override val owner: AbstractParty get() = owner
override val participants: List<AbstractParty> get() = participants
override fun withNewOwner(newOwner: AbstractParty): CommandAndState = throw AbstractMethodError()
}
return NodeVaultService.isRelevant(TestOwnableState(), this)
}
// TODO: Unit test linear state relevancy checks
@Test(timeout=300_000)
fun `correct updates are generated for general transactions`() {
val notary = identity.party
val vaultSubscriber = TestSubscriber<Vault.Update<*>>().apply {
vaultService.updates.subscribe(this)
}
val identity = services.myInfo.singleIdentityAndCert()
val anonymousIdentity = services.keyManagementService.freshKeyAndCert(identity, false)
// We use a random key pair to pay to here, as we don't actually use the cash once sent
val thirdPartyIdentity = AnonymousParty(generateKeyPair().public)
val amount = Amount(1000, Issued(BOC.ref(1), GBP))
// Issue then move some cash
val issueBuilder = TransactionBuilder(notary).apply {
Cash().generateIssue(this, amount, anonymousIdentity.party.anonymise(), identity.party)
}
val issueTx = issueBuilder.toWireTransaction(bocServices)
val cashState = StateAndRef(issueTx.outputs.single(), StateRef(issueTx.id, 0))
// ensure transaction contract state is persisted in DBStorage
val signedIssuedTx = services.signInitialTransaction(issueBuilder)
(services.validatedTransactions as WritableTransactionStorage).addTransaction(signedIssuedTx)
database.transaction { vaultService.notify(StatesToRecord.ONLY_RELEVANT, issueTx) }
val expectedIssueUpdate = Vault.Update(emptySet(), setOf(cashState), null)
val moveTx = database.transaction {
val moveBuilder = TransactionBuilder(notary).apply {
CashUtils.generateSpend(services, this, Amount(1000, GBP), identity, thirdPartyIdentity)
}
val moveTx = moveBuilder.toWireTransaction(services)
vaultService.notify(StatesToRecord.ONLY_RELEVANT, moveTx)
moveTx
}
val expectedMoveUpdate = Vault.Update(setOf(cashState), emptySet(), null, consumingTxIds = mapOf(cashState.ref to moveTx.id))
// ensure transaction contract state is persisted in DBStorage
val signedMoveTx = services.signInitialTransaction(issueBuilder)
(services.validatedTransactions as WritableTransactionStorage).addTransaction(signedMoveTx)
val observedUpdates = vaultSubscriber.onNextEvents
assertEquals(observedUpdates, listOf(expectedIssueUpdate, expectedMoveUpdate))
}
@Test(timeout=300_000)
fun `correct updates are generated when changing notaries`() {
val service = vaultService
val notary = identity.party
val vaultSubscriber = TestSubscriber<Vault.Update<*>>().apply {
service.updates.subscribe(this)
}
val identity = services.myInfo.singleIdentityAndCert()
assertEquals(services.identityService.partyFromKey(identity.owningKey), identity.party)
val anonymousIdentity = services.keyManagementService.freshKeyAndCert(identity, false)
val thirdPartyServices = MockServices(emptyList(), MEGA_CORP.name, mock<IdentityService>().also {
doReturn(null).whenever(it).verifyAndRegisterIdentity(argThat { name == MEGA_CORP.name })
})
val thirdPartyIdentity = thirdPartyServices.keyManagementService.freshKeyAndCert(thirdPartyServices.myInfo.singleIdentityAndCert(), false)
val amount = Amount(1000, Issued(BOC.ref(1), GBP))
// Issue some cash
val issueTxBuilder = TransactionBuilder(notary).apply {
Cash().generateIssue(this, amount, anonymousIdentity.party, notary)
}
val issueStx = bocServices.signInitialTransaction(issueTxBuilder)
// We need to record the issue transaction so inputs can be resolved for the notary change transaction
(services.validatedTransactions as WritableTransactionStorage).addTransaction(issueStx)
val initialCashState = StateAndRef(issueStx.tx.outputs.single(), StateRef(issueStx.id, 0))
// Change notary
services.identityService.verifyAndRegisterIdentity(DUMMY_NOTARY_IDENTITY)
val newNotary = DUMMY_NOTARY
val changeNotaryTx = NotaryChangeTransactionBuilder(listOf(initialCashState.ref), issueStx.notary!!, newNotary, services.networkParametersService.currentHash).build()
val cashStateWithNewNotary = StateAndRef(initialCashState.state.copy(notary = newNotary), StateRef(changeNotaryTx.id, 0))
database.transaction {
service.notifyAll(StatesToRecord.ONLY_RELEVANT, listOf(issueStx.tx, changeNotaryTx))
}
// ensure transaction contract state is persisted in DBStorage
(services.validatedTransactions as WritableTransactionStorage).addTransaction(SignedTransaction(changeNotaryTx, listOf(NullKeys.NULL_SIGNATURE)))
// Move cash
val moveTxBuilder = database.transaction {
TransactionBuilder(newNotary).apply {
CashUtils.generateSpend(services, this, Amount(amount.quantity, GBP), identity, thirdPartyIdentity.party.anonymise())
}
}
val moveTx = moveTxBuilder.toWireTransaction(services)
// ensure transaction contract state is persisted in DBStorage
val signedMoveTx = services.signInitialTransaction(moveTxBuilder)
(services.validatedTransactions as WritableTransactionStorage).addTransaction(signedMoveTx)
database.transaction {
service.notify(StatesToRecord.ONLY_RELEVANT, moveTx)
}
val expectedIssueUpdate = Vault.Update(emptySet(), setOf(initialCashState), null)
val expectedNotaryChangeUpdate = Vault.Update(setOf(initialCashState), setOf(cashStateWithNewNotary), null, Vault.UpdateType.NOTARY_CHANGE, consumingTxIds = mapOf(initialCashState.ref to changeNotaryTx.id))
val expectedMoveUpdate = Vault.Update(setOf(cashStateWithNewNotary), emptySet(), null, consumingTxIds = mapOf(cashStateWithNewNotary.ref to moveTx.id))
val observedUpdates = vaultSubscriber.onNextEvents
assertEquals(observedUpdates, listOf(expectedIssueUpdate, expectedNotaryChangeUpdate, expectedMoveUpdate))
}
@Test(timeout=300_000)
fun observerMode() {
fun countCash(): Long {
return database.transaction {
vaultService.queryBy(Cash.State::class.java, QueryCriteria.VaultQueryCriteria(relevancyStatus = Vault.RelevancyStatus.ALL), PageSpecification(1)).totalStatesAvailable
}
}
val currentCashStates = countCash()
// Send some minimalist dummy transaction.
val txb = TransactionBuilder(DUMMY_NOTARY)
txb.addOutputState(Cash.State(MEGA_CORP.ref(0), 100.DOLLARS, MINI_CORP), Cash::class.java.name)
txb.addCommand(Cash.Commands.Move(), MEGA_CORP_PUBKEY)
val wtx = txb.toWireTransaction(services)
database.transaction {
vaultService.notify(StatesToRecord.ONLY_RELEVANT, wtx)
}
// ensure transaction contract state is persisted in DBStorage
val signedTxb = services.signInitialTransaction(txb)
(services.validatedTransactions as WritableTransactionStorage).addTransaction(signedTxb)
// Check that it was ignored as irrelevant.
assertEquals(currentCashStates, countCash())
// Now try again and check it was accepted.
database.transaction {
vaultService.notify(StatesToRecord.ALL_VISIBLE, wtx)
}
assertEquals(currentCashStates + 1, countCash())
}
@Test(timeout=300_000)
fun `insert equal cash states issued by single transaction`() {
val nodeIdentity = MEGA_CORP
val coins = listOf(1.DOLLARS, 1.DOLLARS).map { it.issuedBy(nodeIdentity.ref(1)) }
//create single transaction with 2 'identical' cash outputs
val txb = TransactionBuilder(DUMMY_NOTARY)
coins.map { txb.addOutputState(TransactionState(Cash.State(it, nodeIdentity), Cash.PROGRAM_ID, DUMMY_NOTARY)) }
txb.addCommand(Cash.Commands.Issue(), nodeIdentity.owningKey)
val issueTx = txb.toWireTransaction(services)
// ensure transaction contract state is persisted in DBStorage
val signedIssuedTx = services.signInitialTransaction(txb)
(services.validatedTransactions as WritableTransactionStorage).addTransaction(signedIssuedTx)
database.transaction { vaultService.notify(StatesToRecord.ONLY_RELEVANT, issueTx) }
val recordedStates = database.transaction {
vaultService.queryBy<Cash.State>().states.size
}
assertThat(recordedStates).isEqualTo(coins.size)
}
@Test(timeout=300_000)
fun `insert different cash states issued by single transaction`() {
val nodeIdentity = MEGA_CORP
val coins = listOf(2.DOLLARS, 1.DOLLARS).map { it.issuedBy(nodeIdentity.ref(1)) }
//create single transaction with 2 'identical' cash outputs
val txb = TransactionBuilder(DUMMY_NOTARY)
coins.map { txb.addOutputState(TransactionState(Cash.State(it, nodeIdentity), Cash.PROGRAM_ID, DUMMY_NOTARY)) }
txb.addCommand(Cash.Commands.Issue(), nodeIdentity.owningKey)
val issueTx = txb.toWireTransaction(services)
// ensure transaction contract state is persisted in DBStorage
val signedIssuedTx = services.signInitialTransaction(txb)
(services.validatedTransactions as WritableTransactionStorage).addTransaction(signedIssuedTx)
database.transaction { vaultService.notify(StatesToRecord.ONLY_RELEVANT, issueTx) }
val recordedStates = database.transaction {
vaultService.queryBy<Cash.State>().states.size
}
assertThat(recordedStates).isEqualTo(coins.size)
}
@Test(timeout=300_000)
fun `test state relevance criteria`() {
fun createTx(number: Int, vararg participants: Party): SignedTransaction {
return services.signInitialTransaction(TransactionBuilder(DUMMY_NOTARY).apply {
addOutputState(DummyState(number, participants.toList()), DummyContract.PROGRAM_ID)
addCommand(DummyCommandData, listOf(megaCorp.publicKey))
})
}
fun List<StateAndRef<DummyState>>.getNumbers() = map { it.state.data.magicNumber }.toSet()
services.recordTransactions(StatesToRecord.ONLY_RELEVANT, listOf(createTx(1, megaCorp.party)))
services.recordTransactions(StatesToRecord.ONLY_RELEVANT, listOf(createTx(2, miniCorp.party)))
services.recordTransactions(StatesToRecord.ONLY_RELEVANT, listOf(createTx(3, miniCorp.party, megaCorp.party)))
services.recordTransactions(StatesToRecord.ALL_VISIBLE, listOf(createTx(4, miniCorp.party)))
services.recordTransactions(StatesToRecord.ALL_VISIBLE, listOf(createTx(5, bankOfCorda.party)))
services.recordTransactions(StatesToRecord.ALL_VISIBLE, listOf(createTx(6, megaCorp.party, bankOfCorda.party)))
services.recordTransactions(StatesToRecord.NONE, listOf(createTx(7, bankOfCorda.party)))
// Test one.
// RelevancyStatus is ALL by default. This should return five states.
val resultOne = vaultService.queryBy<DummyState>().states.getNumbers()
assertEquals(setOf(1, 3, 4, 5, 6), resultOne)
// Test two.
// RelevancyStatus set to NOT_RELEVANT.
val criteriaTwo = VaultQueryCriteria(relevancyStatus = Vault.RelevancyStatus.NOT_RELEVANT)
val resultTwo = vaultService.queryBy<DummyState>(criteriaTwo).states.getNumbers()
assertEquals(setOf(4, 5), resultTwo)
// Test three.
// RelevancyStatus set to RELEVANT.
val criteriaThree = VaultQueryCriteria(relevancyStatus = Vault.RelevancyStatus.RELEVANT)
val resultThree = vaultService.queryBy<DummyState>(criteriaThree).states.getNumbers()
assertEquals(setOf(1, 3, 6), resultThree)
// We should never see 2 or 7.
}
@Test(timeout=300_000)
fun `Unique column constraint failing causes linear state to not persist to vault`() {
fun createTx(): SignedTransaction {
return services.signInitialTransaction(TransactionBuilder(DUMMY_NOTARY).apply {
addOutputState(UniqueDummyLinearContract.State(listOf(megaCorp.party), "Dummy linear id"), UNIQUE_DUMMY_LINEAR_CONTRACT_PROGRAM_ID)
addCommand(DummyCommandData, listOf(megaCorp.publicKey))
})
}
services.recordTransactions(StatesToRecord.ONLY_RELEVANT, listOf(createTx()))
assertThatExceptionOfType(PersistenceException::class.java).isThrownBy {
services.recordTransactions(StatesToRecord.ONLY_RELEVANT, listOf(createTx()))
}
assertEquals(1, database.transaction {
vaultService.queryBy<UniqueDummyLinearContract.State>().states.size
})
}
@Test(timeout=300_000)
fun `Unique column constraint failing causes fungible state to not persist to vault`() {
fun createTx(): SignedTransaction {
return services.signInitialTransaction(TransactionBuilder(DUMMY_NOTARY).apply {
addOutputState(UniqueDummyFungibleContract.State(10.DOLLARS `issued by` DUMMY_CASH_ISSUER, megaCorp.party), UNIQUE_DUMMY_FUNGIBLE_CONTRACT_PROGRAM_ID)
addCommand(DummyCommandData, listOf(megaCorp.publicKey))
})
}
services.recordTransactions(StatesToRecord.ONLY_RELEVANT, listOf(createTx()))
assertThatExceptionOfType(PersistenceException::class.java).isThrownBy {
services.recordTransactions(StatesToRecord.ONLY_RELEVANT, listOf(createTx()))
}
assertEquals(1, database.transaction {
vaultService.queryBy<UniqueDummyFungibleContract.State>().states.size
})
assertEquals(10.DOLLARS.quantity, database.transaction {
vaultService.queryBy<UniqueDummyFungibleContract.State>().states.first().state.data.amount.quantity
})
}
@Test(timeout=300_000)
fun `Unique column constraint failing causes all states in transaction to fail`() {
fun createTx(): SignedTransaction {
return services.signInitialTransaction(TransactionBuilder(DUMMY_NOTARY).apply {
addOutputState(UniqueDummyLinearContract.State(listOf(megaCorp.party), "Dummy linear id"), UNIQUE_DUMMY_LINEAR_CONTRACT_PROGRAM_ID)
addOutputState(DummyDealContract.State(listOf(megaCorp.party), "Dummy linear id"), DUMMY_DEAL_PROGRAM_ID)
addCommand(DummyCommandData, listOf(megaCorp.publicKey))
})
}
services.recordTransactions(StatesToRecord.ONLY_RELEVANT, listOf(createTx()))
assertThatExceptionOfType(PersistenceException::class.java).isThrownBy {
services.recordTransactions(StatesToRecord.ONLY_RELEVANT, listOf(createTx()))
}
assertEquals(1, database.transaction {
vaultService.queryBy<UniqueDummyLinearContract.State>().states.size
})
assertEquals(1, database.transaction {
vaultService.queryBy<DummyDealContract.State>().states.size
})
}
@Test(timeout=300_000)
fun `Vault queries return all states by default`() {
fun createTx(number: Int, vararg participants: Party): SignedTransaction {
return services.signInitialTransaction(TransactionBuilder(DUMMY_NOTARY).apply {
addOutputState(DummyState(number, participants.toList()), DummyContract.PROGRAM_ID)
addCommand(DummyCommandData, listOf(megaCorp.publicKey))
})
}
fun List<StateAndRef<DummyState>>.getNumbers() = map { it.state.data.magicNumber }.toSet()
services.recordTransactions(StatesToRecord.ONLY_RELEVANT, listOf(createTx(1, megaCorp.party)))
services.recordTransactions(StatesToRecord.ONLY_RELEVANT, listOf(createTx(2, miniCorp.party)))
services.recordTransactions(StatesToRecord.ONLY_RELEVANT, listOf(createTx(3, miniCorp.party, megaCorp.party)))
services.recordTransactions(StatesToRecord.ALL_VISIBLE, listOf(createTx(4, miniCorp.party)))
services.recordTransactions(StatesToRecord.ALL_VISIBLE, listOf(createTx(5, bankOfCorda.party)))
services.recordTransactions(StatesToRecord.ALL_VISIBLE, listOf(createTx(6, megaCorp.party, bankOfCorda.party)))
services.recordTransactions(StatesToRecord.NONE, listOf(createTx(7, bankOfCorda.party)))
// Test one.
// RelevancyStatus is ALL by default. This should return five states.
val resultOne = vaultService.queryBy<DummyState>().states.getNumbers()
assertEquals(setOf(1, 3, 4, 5, 6), resultOne)
// We should never see 2 or 7.
}
@Test(timeout=300_000)
@Ignore
fun `trackByCriteria filters updates and snapshots`() {
/*
* This test is ignored as the functionality it tests is not yet implemented - see CORDA-2389
*/
fun addCashToVault() {
database.transaction {
vaultFiller.fillWithSomeTestCash(100.DOLLARS, issuerServices, 1, DUMMY_CASH_ISSUER)
}
}
fun addDummyToVault() {
database.transaction {
vaultFiller.fillWithDummyState()
}
}
addCashToVault()
addDummyToVault()
val criteria = VaultQueryCriteria(contractStateTypes = setOf(Cash.State::class.java))
val data = vaultService.trackBy<ContractState>(criteria)
for (state in data.snapshot.states) {
assertEquals(Cash.PROGRAM_ID, state.state.contract)
}
val allCash = data.updates.all {
it.produced.all {
it.state.contract == Cash.PROGRAM_ID
}
}
addCashToVault()
addDummyToVault()
addCashToVault()
allCash.subscribe {
assertTrue(it)
}
}
@Test(timeout=300_000)
fun `test concurrent update of contract state type mappings`() {
// no registered contract state types at start-up.
assertEquals(0, vaultService.contractStateTypeMappings.size)
fun makeCash(amount: Amount<Currency>, issuer: AbstractParty, depositRef: Byte = 1) =
StateAndRef(
TransactionState(Cash.State(amount `issued by` issuer.ref(depositRef), identity.party), Cash.PROGRAM_ID, DUMMY_NOTARY, constraint = AlwaysAcceptAttachmentConstraint),
StateRef(SecureHash.randomSHA256(), Random().nextInt(32))
)
val cashIssued = setOf<StateAndRef<ContractState>>(makeCash(100.DOLLARS, dummyCashIssuer.party))
val cashUpdate = Vault.Update(emptySet(), cashIssued)
val service = Executors.newFixedThreadPool(10)
(1..100).map {
service.submit {
database.transaction {
vaultService.publishUpdates.onNext(cashUpdate)
}
}
}.forEach { it.getOrThrow() }
vaultService.contractStateTypeMappings.forEach {
println("${it.key} = ${it.value}")
}
// Cash.State and its superclasses and interfaces: FungibleAsset, FungibleState, OwnableState, QueryableState
assertEquals(4, vaultService.contractStateTypeMappings.size)
service.shutdown()
}
}
| 59 | Kotlin | 1,089 | 3,966 | c7514e1c603c077b49987fd79bd77060612967ed | 50,401 | corda | Apache License 2.0 |
compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/LateinitLowering.kt | cpovirk | 113,101,073 | true | {"Java": 27299655, "Kotlin": 26644510, "JavaScript": 155518, "HTML": 57096, "Lex": 18174, "Groovy": 14207, "ANTLR": 9797, "IDL": 8587, "Shell": 5436, "CSS": 4679, "Batchfile": 4437} | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.common.lower
import org.jetbrains.kotlin.backend.common.CommonBackendContext
import org.jetbrains.kotlin.backend.common.FileLoweringPass
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.builders.*
import org.jetbrains.kotlin.ir.declarations.IrFile
import org.jetbrains.kotlin.ir.declarations.IrFunction
import org.jetbrains.kotlin.ir.declarations.IrProperty
import org.jetbrains.kotlin.ir.expressions.IrBlock
import org.jetbrains.kotlin.ir.expressions.impl.IrBlockImpl
import org.jetbrains.kotlin.ir.expressions.impl.IrExpressionBodyImpl
import org.jetbrains.kotlin.ir.symbols.IrFieldSymbol
import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid
import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
import org.jetbrains.kotlin.types.KotlinType
class LateinitLowering(val context: CommonBackendContext): FileLoweringPass {
override fun lower(irFile: IrFile) {
irFile.transformChildrenVoid(object: IrElementTransformerVoid() {
override fun visitProperty(declaration: IrProperty): IrStatement {
if (declaration.descriptor.isLateInit && declaration.descriptor.kind.isReal)
transformGetter(declaration.backingField!!.symbol, declaration.getter!!)
return declaration
}
private fun transformGetter(backingFieldSymbol: IrFieldSymbol, getter: IrFunction) {
val type = backingFieldSymbol.descriptor.type
assert (!KotlinBuiltIns.isPrimitiveType(type), { "'lateinit' modifier is not allowed on primitive types" })
val startOffset = getter.startOffset
val endOffset = getter.endOffset
val irBuilder = context.createIrBuilder(getter.symbol, startOffset, endOffset)
irBuilder.run {
val block = irBlock(type)
val resultVar = scope.createTemporaryVariable(
irGetField(getter.dispatchReceiverParameter?.let { irGet(it.symbol) }, backingFieldSymbol)
)
block.statements.add(resultVar)
val throwIfNull = irIfThenElse(context.builtIns.nothingType,
irNotEquals(irGet(resultVar.symbol), irNull()),
irReturn(irGet(resultVar.symbol)),
irCall(throwErrorFunction))
block.statements.add(throwIfNull)
getter.body = IrExpressionBodyImpl(startOffset, endOffset, block)
}
}
})
}
private val throwErrorFunction = context.ir.symbols.ThrowUninitializedPropertyAccessException
private fun IrBuilderWithScope.irBlock(type: KotlinType): IrBlock
= IrBlockImpl(startOffset, endOffset, type)
} | 2 | Java | 2 | 1 | b6ca9118ffe142e729dd17deeecfb35badba1537 | 3,565 | kotlin | Apache License 2.0 |
rx-preferences/src/main/java/com/f2prateek/rx/preferences2/BooleanAdapter.kt | carvaq | 360,856,178 | true | {"Kotlin": 32778, "Shell": 946} | package com.f2prateek.rx.preferences2
import android.content.SharedPreferences
import android.content.SharedPreferences.Editor
internal object BooleanAdapter : RealPreference.Adapter<Boolean> {
override fun get(
key: String,
preferences: SharedPreferences,
defaultValue: Boolean
): Boolean {
return preferences.getBoolean(key, defaultValue)
}
override fun set(
key: String,
value: Boolean,
editor: Editor
) {
editor.putBoolean(key, value)
}
} | 0 | Kotlin | 0 | 0 | fbb072ece86649fc778dd969611103d94cccbb91 | 533 | rx-preferences | Apache License 2.0 |
app/src/main/java/com/example/newsapplication/MainActivity.kt | PauloSzT | 647,544,079 | false | null | package com.example.newsapplication
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.example.movieapp.ui.theme.NewsAppTheme
import com.example.newsapplication.di.applicationModule
import com.example.newsapplication.ui.navigation.BottomNav
import com.example.newsapplication.ui.navigation.NavItem
import com.example.newsapplication.ui.navigation.NavItem.Companion.title
import com.example.newsapplication.ui.navigation.NavigationGraph
import org.koin.android.ext.koin.androidContext
import org.koin.core.context.GlobalContext
import org.koin.core.context.startKoin
class MainActivity : ComponentActivity() {
@OptIn(ExperimentalMaterial3Api::class)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if(GlobalContext.getOrNull() == null){
startKoin {
androidContext(this@MainActivity)
modules(applicationModule)
}
}
setContent {
val navHostController = rememberNavController()
var title by remember { mutableStateOf("") }
var displayTopBar by remember { mutableStateOf(true) }
var displayBottomBar by remember { mutableStateOf(true) }
DisposableEffect(key1 = Unit) {
val destinationListener =
NavController.OnDestinationChangedListener { _, destination, _ ->
displayBottomBar = destination.route != NavItem.Detail.route
displayTopBar = destination.route != NavItem.Search.route
title = destination.route?.title().orEmpty()
}
navHostController.addOnDestinationChangedListener(destinationListener)
onDispose { navHostController.removeOnDestinationChangedListener(destinationListener) }
}
NewsAppTheme {
Scaffold(
topBar = {
Column(
modifier = Modifier.padding(bottom = 8.dp)
) {
TopAppBar(
title = {
Text(
text = title,
style = MaterialTheme.typography.titleLarge
)
},
navigationIcon = {
if (displayTopBar) {
IconButton(onClick = { navHostController.navigateUp() }) {
Icon(Icons.Filled.ArrowBack, null)
}
}
},
modifier = Modifier
.background(color = Color.White)
)
Divider(
modifier = Modifier
.fillMaxWidth()
.height(1.dp)
.padding(horizontal = 16.dp),
color = MaterialTheme.colorScheme.onBackground
)
}
},
modifier = Modifier.fillMaxSize(),
bottomBar = {
if (displayBottomBar) {
BottomNav(navController = navHostController)
}
},
) { innerPadding ->
NavigationGraph(
modifier = Modifier
.fillMaxSize()
.padding(innerPadding),
navHostController = navHostController
)
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | 9e0bd38103e37d7e0356aed6b569754753ad7d0a | 5,289 | News_App | MIT License |
fxgl/src/main/kotlin/com/almasb/fxgl/scene3d/PrismBasedShapes.kt | AlmasB | 32,761,091 | false | {"Kotlin": 1775860, "Java": 1771047, "CSS": 45751, "C++": 2908, "JavaScript": 2585, "kvlang": 134} | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB (<EMAIL>).
* See LICENSE for details.
*/
package com.almasb.fxgl.scene3d
/**
*
* @author <NAME> (<EMAIL>)
*/
class Cylinder
@JvmOverloads constructor(
/**
* Distance between center and base vertices.
*/
bottomRadius: Double = DEFAULT_RADIUS,
/**
* Distance between center and top vertices.
*/
topRadius: Double = DEFAULT_RADIUS,
height: Double = DEFAULT_SIZE
) : Prism(bottomRadius, topRadius, height, DEFAULT_NUM_DIVISIONS)
class Pyramid
@JvmOverloads constructor(
/**
* Distance between center and base vertices.
*/
bottomRadius: Double = DEFAULT_RADIUS,
/**
* Distance between center and top vertices.
*/
topRadius: Double = 0.0,
height: Double = DEFAULT_SIZE,
numDivisions: Int = 3
) : Prism(bottomRadius, topRadius, height, numDivisions)
class Cone
@JvmOverloads constructor(
/**
* Distance between center and base vertices.
*/
bottomRadius: Double = DEFAULT_RADIUS,
/**
* Distance between center and top vertices.
*/
topRadius: Double = 0.0,
height: Double = DEFAULT_SIZE
) : Prism(bottomRadius, topRadius, height, DEFAULT_NUM_DIVISIONS) | 128 | Kotlin | 558 | 4,053 | fe194645eea4db4bac7f2d015b9f2c2d3249a26d | 1,412 | FXGL | MIT License |
webrtc/src/main/java/com/konovalov/vad/webrtc/Vad.kt | gkonovalov | 224,550,411 | false | {"C": 341482, "Kotlin": 104707, "C++": 16212, "Assembly": 15149, "Makefile": 4315} | package com.konovalov.vad.webrtc
import com.konovalov.vad.webrtc.config.FrameSize
import com.konovalov.vad.webrtc.config.Mode
import com.konovalov.vad.webrtc.config.SampleRate
/**
* Created by <NAME> on 6/1/2023.
*
* The WebRTC VAD algorithm, based on GMM, analyzes the audio signal to determine whether it
* contains speech or non-speech segments.
*
* The WebRTC VAD supports the following parameters:
*
* Sample Rates:
*
* 8000Hz,
* 16000Hz,
* 32000Hz,
* 48000Hz
*
* Frame Sizes (per sample rate):
*
* For 8000Hz: 80, 160, 240
* For 16000Hz: 160, 320, 480
* For 32000Hz: 320, 640, 960
* For 48000Hz: 480, 960, 1440
*
* Mode:
*
* NORMAL,
* LOW_BITRATE,
* AGGRESSIVE,
* VERY_AGGRESSIVE
*
* Please note that the VAD class supports these specific combinations of sample
* rates and frame sizes, and the classifiers determine the aggressiveness of the voice
* activity detection algorithm.
*
* @param sampleRate is required for processing audio input.
* @param frameSize is required for processing audio input.
* @param mode is required for the VAD model.
* @param speechDurationMs is minimum duration in milliseconds for speech segments (optional).
* @param silenceDurationMs is minimum duration in milliseconds for silence segments (optional).
*/
class Vad private constructor() {
private lateinit var sampleRate: SampleRate
private lateinit var frameSize: FrameSize
private lateinit var mode: Mode
private var speechDurationMs = 0
private var silenceDurationMs = 0
/**
* Set, retrieve and validate sample rate for Vad Model.
*
* Valid Sample Rates:
*
* 8000Hz,
* 16000Hz,
* 32000Hz,
* 48000Hz
*
* @param sampleRate is required for processing audio input.
*/
fun setSampleRate(sampleRate: SampleRate): Vad = apply {
this.sampleRate = sampleRate
}
/**
* Set, retrieve and validate frame size for Vad Model.
*
* Valid Frame Sizes (per sample rate):
*
* For 8000Hz: 80, 160, 240
* For 16000Hz: 160, 320, 480
* For 32000Hz: 320, 640, 960
* For 48000Hz: 480, 960, 1440
*
* @param frameSize is required for processing audio input.
*/
fun setFrameSize(frameSize: FrameSize): Vad = apply {
this.frameSize = frameSize
}
/**
* Set and retrieve detection mode for Vad model.
*
* Mode:
*
* NORMAL,
* LOW_BITRATE,
* AGGRESSIVE,
* VERY_AGGRESSIVE
*
* @param mode is required for processing audio input.
*/
fun setMode(mode: Mode): Vad = apply {
this.mode = mode
}
/**
* Set the minimum duration in milliseconds for speech segments.
* The value of this parameter will define the necessary and sufficient duration of positive
* results to recognize result as speech. This parameter is optional.
*
* Permitted range (0ms >= speechDurationMs <= 300000ms).
*
* Parameters used for {@link VadSilero.isSpeech}.
*
* @param speechDurationMs minimum duration in milliseconds for speech segments.
*/
fun setSpeechDurationMs(speechDurationMs: Int): Vad = apply {
this.speechDurationMs = speechDurationMs
}
/**
* Set the minimum duration in milliseconds for silence segments.
* The value of this parameter will define the necessary and sufficient duration of
* negative results to recognize it as silence. This parameter is optional.
*
* Permitted range (0ms >= silenceDurationMs <= 300000ms).
*
* Parameters used in {@link VadSilero.isSpeech}.
*
* @param silenceDurationMs minimum duration in milliseconds for silence segments.
*/
fun setSilenceDurationMs(silenceDurationMs: Int): Vad = apply {
this.silenceDurationMs = silenceDurationMs
}
/**
* Builds and returns a VadModel instance based on the specified parameters.
*
* @return constructed VadWebRTC model.
* @throws IllegalArgumentException if there was an error during initialization of VAD.
*/
fun build(): VadWebRTC {
return VadWebRTC(
sampleRate,
frameSize,
mode,
speechDurationMs,
silenceDurationMs
)
}
companion object {
@JvmStatic
fun builder(): Vad {
return Vad()
}
}
} | 1 | C | 37 | 152 | ad98ff50d05ba5680a97eb64738fadad0b7b31dc | 4,530 | android-vad | MIT License |
app/src/main/java/com/jdagnogo/welovemarathon/activities/di/ActivitiesModule.kt | jdagnogo | 424,252,162 | false | null | package com.jdagnogo.welovemarathon.activities.di
import com.jdagnogo.welovemarathon.activities.data.ActivitiesDao
import com.jdagnogo.welovemarathon.activities.data.ActivitiesData
import com.jdagnogo.welovemarathon.activities.data.ActivitiesMapper
import com.jdagnogo.welovemarathon.activities.data.ActivitiesRemoteData
import com.jdagnogo.welovemarathon.activities.data.ActivitiesRepository
import com.jdagnogo.welovemarathon.activities.domain.ActivitiesUseCase
import com.jdagnogo.welovemarathon.activities.domain.GetActivitiesCategoriesUseCase
import com.jdagnogo.welovemarathon.activities.domain.GetActivitiesTagUseCase
import com.jdagnogo.welovemarathon.activities.domain.GetActivitiesUseCase
import com.jdagnogo.welovemarathon.activities.presentation.ActivitiesReducer
import com.jdagnogo.welovemarathon.common.banner.GetBannerUseCase
import com.jdagnogo.welovemarathon.common.data.WLMDatabase
import com.jdagnogo.welovemarathon.common.domain.DataFreshnessUseCase
import com.jdagnogo.welovemarathon.common.like.domain.FavUseCase
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object ActivitiesModule {
@Provides
@Singleton
fun provideGetActivitiesUseCase(
repository: ActivitiesRepository,
): GetActivitiesUseCase {
return GetActivitiesUseCase(repository)
}
@Provides
@Singleton
fun provideGetActivitiesTagUseCase(
repository: ActivitiesRepository,
): GetActivitiesTagUseCase {
return GetActivitiesTagUseCase(repository)
}
@Provides
@Singleton
fun provideActivitiesData(
activitiesDao: ActivitiesDao,
activitiesRemoteData: ActivitiesRemoteData,
activitiesMapper: ActivitiesMapper,
dataFreshnessUseCase: DataFreshnessUseCase,
) = ActivitiesData(activitiesDao, activitiesRemoteData, dataFreshnessUseCase, activitiesMapper)
@Provides
@Singleton
fun provideActivitiesMapper(): ActivitiesMapper {
return ActivitiesMapper()
}
@Singleton
@Provides
fun provideActivitiesDao(db: WLMDatabase): ActivitiesDao = db.getActivitiesDao()
@Provides
@Singleton
fun provideActivitiesUseCase(
getActivitiesUseCase: GetActivitiesUseCase,
getActivitiesCategoriesUseCase: GetActivitiesCategoriesUseCase,
getActivitiesTagUseCase: GetActivitiesTagUseCase,
getBannerUseCase: GetBannerUseCase,
favUseCase: FavUseCase
) = ActivitiesUseCase(
getActivitiesUseCase = getActivitiesUseCase,
getActivitiesCategoriesUseCase = getActivitiesCategoriesUseCase,
getBannerUseCase = getBannerUseCase,
getActivitiesTagUseCase = getActivitiesTagUseCase,
favUseCase = favUseCase
)
@Provides
@Singleton
fun provideActivitiesReducer() = ActivitiesReducer()
@Provides
@Singleton
fun provideGetActivitiesCategoriesUseCase(repository: ActivitiesRepository) =
GetActivitiesCategoriesUseCase(repository)
}
| 0 | Kotlin | 0 | 0 | b1c202a9afa2e61de8b309d38884401d42350936 | 3,111 | WeLoveMArathon | The Unlicense |
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/KernelObject.kt | Danilo-Araujo-Silva | 271,904,885 | false | null | package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/**
*````
*
* Name: KernelObject
*
* Full name: System`KernelObject
*
* Usage: KernelObject[n, name, …] represents a kernel available for parallel computing.
*
* Options: None
*
* Protected
* Attributes: ReadProtected
*
* local: paclet:ref/KernelObject
* Documentation: web: http://reference.wolfram.com/language/ref/KernelObject.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun kernelObject(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("KernelObject", arguments.toMutableList(), options)
}
| 2 | Kotlin | 0 | 3 | 4fcf68af14f55b8634132d34f61dae8bb2ee2942 | 1,010 | mathemagika | Apache License 2.0 |
app/src/main/java/com/philipgurr/composenews/ui/common/NewsList.kt | PhilipGurr | 295,165,762 | false | null | package com.philipgurr.composenews.ui.common
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.material.Text
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
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.layout.ContentScale
import androidx.compose.ui.unit.dp
import coil.compose.rememberImagePainter
import coil.size.OriginalSize
import coil.size.Scale
import com.philipgurr.composenews.domain.NewsPost
import com.philipgurr.composenews.domain.Screen
@Composable
fun NewsList(
padding: PaddingValues,
posts: List<NewsPost>,
navigate: (Screen) -> Unit
) {
val baseModifier = Modifier.padding(padding)
LazyColumn(
modifier = baseModifier
.fillMaxWidth()
.fillMaxHeight()
) {
items(posts) {
NewsListItem(newsPost = it, onClick = { post ->
navigate(Screen.NewsDetail(post))
})
}
}
}
@Composable
fun NewsListItem(newsPost: NewsPost, onClick: (NewsPost) -> Unit) {
Card(
modifier = Modifier.padding(10.dp, 10.dp, 10.dp, 15.dp),
border = BorderStroke(1.dp, Color.LightGray),
elevation = 10.dp,
shape = RoundedCornerShape(30.dp)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = { onClick(newsPost) }),
horizontalAlignment = Alignment.CenterHorizontally
) {
val imageUrl = newsPost.urlToImage
if(imageUrl != null && imageUrl.isNotEmpty()) {
Image(
painter = rememberImagePainter(data = imageUrl, builder = {
size(OriginalSize)
scale(Scale.FIT)
}),
contentDescription = "Article Image",
contentScale = ContentScale.FillWidth,
modifier = Modifier
.clip(
RoundedCornerShape(30.dp, 30.dp, 0.dp, 0.dp)
)
)
}
ArticleText(newsPost)
}
}
}
@Composable
private fun ArticleText(newsPost: NewsPost) {
val paddingTitle = Modifier.padding(15.dp, 10.dp, 15.dp, 5.dp)
val paddingDesc = Modifier.padding(15.dp, 5.dp, 15.dp, 20.dp)
Text(
text = newsPost.title ?: "",
style = MaterialTheme.typography.h6,
modifier = paddingTitle
)
Text(
text = newsPost.description ?: "",
style = MaterialTheme.typography.body2,
modifier = paddingDesc
)
} | 0 | Kotlin | 0 | 0 | 07bdd0e687d346db74f0f985239b25c2a6ef06fb | 3,073 | compose-news-example | Apache License 2.0 |
hometask_1/app/src/main/java/ru/skillbranch/gameofthrones/HouseFragment.kt | cyrilthegreat | 285,820,846 | false | null | package ru.skillbranch.gameofthrones
import androidx.lifecycle.ViewModelProviders
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
class HouseFragment : Fragment() {
companion object {
fun newInstance() = HouseFragment()
}
private lateinit var viewModel: HouseViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.house_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProviders.of(this).get(HouseViewModel::class.java)
// TODO: Use the ViewModel
}
} | 0 | Kotlin | 0 | 0 | 573e9071eca5106d02de1effb439be7013e99eab | 861 | skill-branch | Apache License 2.0 |
roboquant/src/main/kotlin/org/roboquant/metrics/VWAPMetric.kt | neurallayer | 406,929,056 | false | {"JavaScript": 3008153, "Kotlin": 1583428, "CSS": 1977} | /*
* Copyright 2020-2024 Neural Layer
*
* 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 org.roboquant.metrics
import org.roboquant.brokers.Account
import org.roboquant.common.Asset
import org.roboquant.feeds.Event
import org.roboquant.feeds.PriceBar
import java.time.Instant
/**
* Calculate the daily VWAP (Volume Weighted Average Price) for the assets in a feed.
*
* Please note VWAP is a single-day indicator, as soon as the metric detects that a new trading day started, the VWAP
* will be reset. Also, it requires [PriceBar] data to be fully accurate, since it needs the "TYPICAL" price.
*
* VWAP = Cumulative Typical Price x Volume/Cumulative Volume
*
* @property minSize minimum number of events before calculating the first VWAP, default is 2
* @constructor Create a new instance of the VWAPMetric
*/
class VWAPMetric(val minSize: Int = 2) : Metric {
private val calculators = mutableMapOf<Asset, VWAPDaily>()
/**
* @see Metric.calculate
*/
override fun calculate(account: Account, event: Event): Map<String, Double> {
val result = mutableMapOf<String, Double>()
for (priceBar in event.prices.values.filterIsInstance<PriceBar>()) {
val calc = calculators.getOrPut(priceBar.asset) { VWAPDaily(minSize) }
calc.add(priceBar, event.time)
if (calc.isReady()) {
result["vwap.${priceBar.asset.symbol}"] = calc.calc()
}
}
return result
}
override fun reset() {
calculators.clear()
}
}
/**
* Calculates the Daily VWAP. VWAP is a single-day indicator, and is restarted at the start of each new trading day.
* It uses the exchange of the underlying asset to determine what is still within one day.
*
* @property minSteps The minimum number of steps required
* @constructor Create empty Daily VWAP calculator
*/
private class VWAPDaily(private val minSteps: Int) {
private val total = mutableListOf<Double>()
private val volume = mutableListOf<Double>()
private var last: Instant = Instant.MIN
fun add(action: PriceBar, time: Instant) {
val exchange = action.asset.exchange
if (last != Instant.MIN && !exchange.sameDay(time, last)) clear()
last = time
val v = action.volume
total.add(action.getPrice("TYPICAL") * v)
volume.add(v)
}
fun isReady() = total.size >= minSteps
fun calc(): Double {
return total.sum() / volume.sum()
}
private fun clear() {
total.clear()
volume.clear()
last = Instant.MIN
}
}
| 8 | JavaScript | 38 | 286 | 0402d626324d159d2eab9e65977490b1444c5c32 | 3,112 | roboquant | Apache License 2.0 |
app/src/main/java/memoizrlabs/com/composable_styles/utils/ThemeUtils.kt | memoizr | 64,826,130 | false | null | package memoizrlabs.com.composable_styles.utils
import android.content.Context
import android.view.View
import memoizrlabs.com.composable_styles.app.styles.AppTheme
import memoizrlabs.com.composable_styles.app.styles.DefaultTheme
import org.jetbrains.anko.dip
import org.jetbrains.anko.sp
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class ThemeDelegate : ReadWriteProperty<Context, AppTheme> {
var theme: AppTheme = DefaultTheme()
override fun getValue(thisRef: Context, property: KProperty<*>): AppTheme {
return theme
}
override fun setValue(thisRef: Context, property: KProperty<*>, value: AppTheme) {
theme = value
}
}
var Context.appTheme: AppTheme by ThemeDelegate()
var Context.dimens: CustomResources by ResourcesDelegate()
val View.dimens: CustomResources get() = context.dimens
val View.colors: AppTheme get() = context.appTheme
class ResourcesDelegate() : ReadWriteProperty<Context, CustomResources> {
var resources: CustomResources? = null
override fun getValue(thisRef: Context, property: KProperty<*>): CustomResources {
if (resources == null) resources = DefaultResources(thisRef)
return resources!!
}
override fun setValue(thisRef: Context, property: KProperty<*>, value: CustomResources) {
resources = value
}
}
interface CustomResources {
val _1x: Int
val _2x: Int
val smallTextSize: Float
val mediumTextSize: Float
val giantTextSize: Float
val actionBarElevation: Float
}
class DefaultResources(private val context: Context): CustomResources {
override val actionBarElevation: Float get() = context.dip(10).toFloat()
override val giantTextSize: Float get() = context.sp(18).toFloat()
override val mediumTextSize: Float get() = context.sp(10).toFloat()
override val smallTextSize: Float get() = context.sp(5).toFloat()
override val _1x: Int get() = context.dip(8)
override val _2x: Int get() = context.dip(16)
}
| 0 | Kotlin | 0 | 0 | 2805901b43024f1a5822a1fe8a4686edd7bc4e7f | 2,000 | composable-styles-test | Apache License 2.0 |
app/src/main/java/com/example/inventory/ui/LoginActivity.kt | wenvelope | 538,791,409 | false | {"Kotlin": 58359} | package com.example.inventory.ui
import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import com.example.inventory.AppManager
import com.example.inventory.BaseActivity
import com.example.inventory.MainActivity
import com.example.inventory.R
import com.example.inventory.databinding.ActivityLoginBinding
import com.example.inventory.network.InventoryNetWork
import com.example.inventory.spread.showToast
import com.example.inventory.spread.startActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.lang.Exception
class LoginActivity : BaseActivity() {
private lateinit var mBinding:ActivityLoginBinding
private lateinit var sp:SharedPreferences
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AppManager.finishOtherActivity(LoginActivity::class.java.name)
mBinding = DataBindingUtil.setContentView(this,R.layout.activity_login)
sp = getSharedPreferences("TOKEN", Context.MODE_PRIVATE)
mBinding.apply {
button.setOnClickListener {
val username =usernameEdit.text.toString()
val password = <PASSWORD>Edit.text.toString()
if(username.isEmpty()||password.isEmpty()){
"用户名或者密码为空".showToast()
}else{
lifecycleScope.launch {
val response = withContext(Dispatchers.IO){
val result = try {
val responseBody =InventoryNetWork.getUserId(username,password).string()
Result.success(responseBody)
}catch (e:Exception){
Result.failure(e)
}
result.getOrNull()
}
if(response!=null){
when(response){
"登陆成功"->{
[email protected]<HomeActivity> {
sp.edit().apply {
putString("TOKEN",username)
apply()
}
}
}
else->{
response.showToast()
}
}
}else{
"网络错误".showToast()
}
}
}
}
}
}
} | 0 | Kotlin | 0 | 0 | d2fa3c4aa7fa478e57bfff76754919a762c86687 | 2,903 | Inventory | MIT License |
Problems/Algorithms/1856. Maximum Subarray Min-Product/MaxMinProduct.kt | xuedong | 189,745,542 | false | {"Kotlin": 332182, "Java": 294218, "Python": 237866, "C++": 97190, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65} | class Solution {
fun maxSumMinProduct(nums: IntArray): Int {
val n = nums.size
val stack = Stack<Int>()
val nextSmaller = IntArray(n) { n }
val prevSmaller = IntArray(n) { -1 }
for (i in 0..n-1) {
while (!stack.isEmpty() && nums[i] < nums[stack.peek()]) {
nextSmaller[stack.peek()] = i
stack.pop()
}
stack.push(i)
}
while (!stack.isEmpty()) {
stack.pop()
}
for (i in n-1 downTo 0) {
while (!stack.isEmpty() && nums[i] < nums[stack.peek()]) {
prevSmaller[stack.peek()] = i
stack.pop()
}
stack.push(i)
}
var prefix: Long = 0
val prefixes = LongArray(n+1) { 0 }
for (i in 1..n) {
prefix += nums[i-1]
prefixes[i] = prefix
}
var ans: Long = 0
for (i in 0..n-1) {
val right = nextSmaller[i]
val left = prevSmaller[i]
val sum: Long = prefixes[right] - prefixes[left+1]
ans = maxOf(ans, sum * nums[i])
}
return (ans % 1000000007).toInt()
}
}
| 0 | Kotlin | 0 | 1 | 5e919965b43917eeee15e4bff12a0b6bea4fd0e7 | 1,267 | leet-code | MIT License |
app/src/test/java/com/timothypaetz/android/androidtesttricks/Trick1ActivityTest.kt | paetztm | 678,092,902 | false | null | package com.timothypaetz.android.androidtesttricks
import io.mockk.every
import io.mockk.mockk
import org.junit.Assert.*
import org.junit.Test
import org.mockito.Mockito.*
import org.mockito.kotlin.mock
class Trick1ActivityTest {
/**
* Mockito Example
*/
@Test
fun `verify no name user returns false for hasCompletedProfile`() {
// given
val trick1Activity: Trick1Activity = mock(defaultAnswer = CALLS_REAL_METHODS)
val noNameUser = User(name = null)
// when
val actual = trick1Activity.hasCompletedProfile(noNameUser)
// then
assertFalse(actual)
}
@Test
fun `verify named user returns true for hasCompletedProfile`() {
// given
val trick1Activity: Trick1Activity = mock(defaultAnswer = CALLS_REAL_METHODS)
val namedUser = User(name = "<NAME>")
// when
val actual = trick1Activity.hasCompletedProfile(namedUser)
// then
assertTrue(actual)
}
/**
* Mockk example
*/
@Test
fun `verify no name user returns false for hasCompletedProfile using mockk`() {
// given
val trick1Activity = mockk<Trick1Activity>()
val noNameUser = User(name = null)
every { trick1Activity.hasCompletedProfile(noNameUser) } answers { callOriginal() }
// when
val actual = trick1Activity.hasCompletedProfile(noNameUser)
// then
assertFalse(actual)
}
@Test
fun `verify named user returns true for hasCompletedProfile using mockk`() {
// given
val trick1Activity = mockk<Trick1Activity>()
val namedUser = User(name = "<NAME>")
every { trick1Activity.hasCompletedProfile(namedUser) } answers { callOriginal() }
// when
val actual = trick1Activity.hasCompletedProfile(namedUser)
// then
assertTrue(actual)
}
} | 0 | Kotlin | 0 | 0 | d085b50f33a5981d5d1fb08c5f5ee794adcbf8ee | 1,920 | androidtesttricks | Apache License 2.0 |
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/highlighter/markers/SuperDeclarationMarker.kt | trinhanhngoc | 391,653,369 | true | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.highlighter.markers
import com.intellij.codeInsight.daemon.GutterIconNavigationHandler
import com.intellij.psi.NavigatablePsiElement
import com.intellij.psi.PsiElement
import com.intellij.util.Function
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.descriptors.PropertyAccessorDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.codeInsight.KtFunctionPsiElementCellRenderer
import org.jetbrains.kotlin.idea.core.getDirectlyOverriddenDeclarations
import org.jetbrains.kotlin.idea.search.usagesSearch.propertyDescriptor
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.renderer.RenderingFormat
import java.awt.event.MouseEvent
object SuperDeclarationMarkerTooltip : Function<PsiElement, String> {
override fun `fun`(element: PsiElement): String? {
val ktDeclaration = element.getParentOfType<KtDeclaration>(false) ?: return null
val (elementDescriptor, overriddenDescriptors) = resolveDeclarationWithParents(ktDeclaration)
if (overriddenDescriptors.isEmpty()) return ""
val isAbstract = elementDescriptor!!.modality == Modality.ABSTRACT
val renderer = DescriptorRenderer.withOptions {
textFormat = RenderingFormat.HTML
withDefinedIn = false
startFromName = true
withoutSuperTypes = true
}
val containingStrings = overriddenDescriptors.map {
val declaration = it.containingDeclaration
val memberKind = if (it is PropertyAccessorDescriptor || it is PropertyDescriptor)
KotlinBundle.message("highlighter.tool.tip.text.property")
else
KotlinBundle.message("highlighter.tool.tip.text.function")
val isBaseAbstract = it.modality == Modality.ABSTRACT
KotlinBundle.message(
"highlighter.text.in",
"${if (!isAbstract && isBaseAbstract)
KotlinBundle.message("highlighter.text.implements")
else
KotlinBundle.message("highlighter.text.overrides")
} $memberKind",
renderer.render(declaration)
)
}
return containingStrings.sorted().joinToString(separator = "<br/>")
}
}
class SuperDeclarationMarkerNavigationHandler : GutterIconNavigationHandler<PsiElement>, TestableLineMarkerNavigator {
override fun navigate(e: MouseEvent?, element: PsiElement?) {
e?.let { getTargetsPopupDescriptor(element)?.showPopup(e) }
}
override fun getTargetsPopupDescriptor(element: PsiElement?): NavigationPopupDescriptor? {
val declaration = element?.getParentOfType<KtDeclaration>(false) ?: return null
val (elementDescriptor, overriddenDescriptors) = resolveDeclarationWithParents(declaration)
if (overriddenDescriptors.isEmpty()) return null
val superDeclarations = ArrayList<NavigatablePsiElement>()
for (overriddenMember in overriddenDescriptors) {
val declarations = DescriptorToSourceUtilsIde.getAllDeclarations(element.project, overriddenMember)
superDeclarations += declarations.filterIsInstance<NavigatablePsiElement>()
}
val elementName = elementDescriptor!!.name
return NavigationPopupDescriptor(
superDeclarations,
KotlinBundle.message("overridden.marker.overrides.choose.implementation.title", elementName),
KotlinBundle.message("overridden.marker.overrides.choose.implementation.find.usages", elementName),
KtFunctionPsiElementCellRenderer()
)
}
}
data class ResolveWithParentsResult(
val descriptor: CallableMemberDescriptor?,
val overriddenDescriptors: Collection<CallableMemberDescriptor>
)
fun resolveDeclarationWithParents(element: KtDeclaration): ResolveWithParentsResult {
val descriptor = if (element is KtParameter)
element.propertyDescriptor
else
element.resolveToDescriptorIfAny()
if (descriptor !is CallableMemberDescriptor) return ResolveWithParentsResult(null, listOf())
return ResolveWithParentsResult(descriptor, descriptor.getDirectlyOverriddenDeclarations())
}
| 0 | null | 0 | 0 | f37a7bcddf4f66018f9cc8dbc109e0d49c3832a9 | 4,862 | intellij-community | Apache License 2.0 |
integration-tests/src/test/kotlin/com/google/devtools/ksp/test/AndroidIncrementalIT.kt | danysantiago | 457,494,834 | true | {"Kotlin": 1187141, "Java": 14135} | /*
* Copyright 2020 Google LLC
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.ksp.test
import com.google.devtools.ksp.test.fixtures.BuildResultFixture
import org.gradle.testkit.runner.GradleRunner
import org.gradle.testkit.runner.TaskOutcome
import org.junit.Assert
import org.junit.Rule
import org.junit.Test
class AndroidIncrementalIT {
@Rule
@JvmField
val project: TemporaryTestProject = TemporaryTestProject("playground-android-multi", "playground")
@Test
fun testPlaygroundAndroid() {
val gradleRunner = GradleRunner.create().withProjectDir(project.root)
gradleRunner.withArguments(
"clean", ":application:compileDebugKotlin", "--configuration-cache-problems=warn", "--debug", "--stacktrace"
).build().let { result ->
Assert.assertEquals(TaskOutcome.SUCCESS, result.task(":workload:compileDebugKotlin")?.outcome)
Assert.assertEquals(TaskOutcome.SUCCESS, result.task(":application:compileDebugKotlin")?.outcome)
}
project.root.resolve("workload/src/main/java/com/example/A.kt").also {
it.appendText(
"""
class Unused
""".trimIndent()
)
}
gradleRunner.withArguments(
":application:compileDebugKotlin", "--configuration-cache-problems=warn", "--debug", "--stacktrace"
).build().let { result ->
Assert.assertEquals(
setOf("workload/src/main/java/com/example/A.kt"),
BuildResultFixture(result).compiledKotlinSources,
)
}
}
}
| 0 | Kotlin | 0 | 2 | f26de8f0566c9e3fee9210828b5c69ea608da584 | 2,231 | ksp | Apache License 2.0 |
domain/src/main/kotlin/wskim/aos/domain/usecase/DutchInfoUseCase.kt | tmvlke | 707,316,658 | false | {"Kotlin": 149898} | package wskim.aos.domain.usecase
import wskim.aos.domain.repository.DutchInfoRepository
import wskim.aos.domain.proguardSafeZone.vo.DutchEndListItemVO
import wskim.aos.domain.proguardSafeZone.vo.DutchHistoryListItemVO
import wskim.aos.domain.proguardSafeZone.vo.DutchListItemVO
import javax.inject.Inject
class DutchInfoUseCase @Inject constructor(
private val dutchInfoRepository: DutchInfoRepository,
) {
// 더치 페이 글쓰기 전 유효성 체크
fun processedDutchWriteValidation(
title: String,
amount: String,
enterPersonList: List<String>
): Boolean {
return title.isNotEmpty() && amount.isNotEmpty() && enterPersonList.isNotEmpty()
}
// 더치 페이 글쓰기
fun saveDutchInfo(dutchListItemVO: DutchListItemVO) {
dutchInfoRepository.insertDutchInfo(dutchListItemVO)
}
// 더치 페이 목록 조회
fun findDutchInfoList() : ArrayList<DutchListItemVO> {
return dutchInfoRepository.selectDutchInfoList()
}
// 더치 페이 정산 목록 조회
fun findDutchEndInfoList() : ArrayList<DutchEndListItemVO> {
return dutchInfoRepository.selectDutchEndInfoList()
}
// 더치 페이 개별 정산
fun modifyDutchEndSomeInfo(name: String) {
dutchInfoRepository.updateDutchEndSomeInfo(name = name)
}
// 더치 페이 전체 정산
fun modifyDutchEndAllInfo() {
dutchInfoRepository.updateDutchEndAllInfo()
}
// 더치 페이 정산 전 전체 가격
fun findDutchTotalAmount(): Int {
return dutchInfoRepository.selectDutchTotalAmount()
}
// 더치 페이 정산 된 전체 이력
fun findDutchHistoryInfoList(): ArrayList<DutchHistoryListItemVO> {
return dutchInfoRepository.selectDutchHistoryInfoList()
}
} | 0 | Kotlin | 0 | 1 | 5823e99c4545f9856696eec27a4afeed4c8228de | 1,812 | SimpleDutch | Apache License 2.0 |
yabapi-core/src/commonMain/kotlin/moe/sdl/yabapi/data/stream/LiveStreamResponse.kt | SDLMoe | 437,756,989 | false | {"Kotlin": 738209} | package moe.sdl.yabapi.data.stream
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import moe.sdl.yabapi.Yabapi
import moe.sdl.yabapi.data.GeneralCode
import moe.sdl.yabapi.data.GeneralCode.UNKNOWN
import moe.sdl.yabapi.data.live.LiveRoomStatus
@Serializable
public data class LiveStreamResponse(
@SerialName("code") val code: GeneralCode = UNKNOWN,
@SerialName("message") val message: String? = null,
@SerialName("ttl") val ttl: Int? = null,
@SerialName("data") val data: LiveStreamInfo? = null,
) {
// public fun filterStream()
}
@Serializable
public data class LiveStreamInfo(
@SerialName("room_id") val roomId: Long? = null,
@SerialName("short_id") val shortId: Long? = null,
@SerialName("uid") val uid: Long? = null,
@SerialName("is_hidden") val isHidden: Boolean? = null,
@SerialName("is_locked") val isLocked: Boolean? = null,
@SerialName("is_portrait") val isPortrait: Boolean? = null,
@SerialName("live_status") val status: LiveRoomStatus? = null,
@SerialName("hidden_till") val hiddenTill: Long? = null,
@SerialName("lock_till") val lockTill: Long? = null,
@SerialName("encrypted") val encrypted: Boolean? = null,
@SerialName("pwd_verified") val pwdVerified: Boolean? = null,
@SerialName("live_time") val liveTime: Long? = null,
@SerialName("room_shield") val roomShield: Int? = null,
@SerialName("all_special_types") val allSpecialTypes: JsonArray? = null,
@SerialName("playurl_info") val playUrlInfo: LivePlayInfo? = null,
)
@Serializable
public data class LivePlayInfo(
@SerialName("conf_json") val _confJson: String? = null,
@SerialName("playurl") val playUrl: LiveStreamPlayUrl? = null,
) {
public val confJson: LiveStreamConfigInfo? by lazy {
_confJson?.let { Yabapi.defaultJson.value.decodeFromString(it) }
}
}
@Serializable
public data class LiveStreamConfigInfo(
@SerialName("cdn_rate") val cdnRate: Int? = null,
@SerialName("report_interval_sec") val reportIntervalSec: Int? = null,
)
@Serializable
public data class LiveStreamPlayUrl(
@SerialName("cid") val cid: Long? = null,
@SerialName("g_qn_desc") val gQnDesc: List<QnDescNode> = emptyList(),
@SerialName("stream") val stream: List<ProtocolTrack> = emptyList(),
@SerialName("p2p_data") val p2pData: P2pData? = null,
@SerialName("dolby_qn") val dolbyQn: JsonElement? = null,
) {
@Serializable
public data class QnDescNode(
@SerialName("qn") val qn: Int? = null,
@SerialName("desc") val desc: String? = null,
@SerialName("hdr_desc") val hdrDesc: String? = null,
)
@Serializable
public data class ProtocolTrack(
@SerialName("protocol_name") val protocolName: String? = null,
@SerialName("format") val format: List<FormatTrack> = emptyList(),
)
@Serializable
public data class P2pData(
@SerialName("p2p") val isP2p: Boolean? = null,
@SerialName("p2p_type") val p2pType: Int? = null,
@SerialName("m_p2p") val mP2P: Boolean? = null,
@SerialName("m_servers") val mServers: JsonElement? = null,
)
@Serializable
public data class FormatTrack(
@SerialName("format_name") val formatName: String? = null,
@SerialName("codec") val codec: List<CodecTrack> = emptyList(),
)
@Serializable
public data class CodecTrack(
@SerialName("codec_name") val codecName: String? = null,
@SerialName("current_qn") val currentQn: Int? = null,
@SerialName("accept_qn") val acceptQn: List<Int> = emptyList(),
@SerialName("base_url") val baseUrl: String? = null,
@SerialName("url_info") val urlInfo: List<UrlInfo> = emptyList(),
@SerialName("hdr_qn") val hdrQn: JsonElement? = null,
@SerialName("dolby_type") val doblyType: Int? = null,
) {
val playUrl: String? by lazy {
val url = urlInfo.firstOrNull()
url?.run {
host + baseUrl + extra
}
}
}
@Serializable
public data class UrlInfo(
@SerialName("host") val host: String? = null,
@SerialName("extra") val extra: String? = null,
@SerialName("stream_ttl") val ttl: Int? = null,
)
}
| 0 | Kotlin | 1 | 26 | c8be46f9b5e4db1e429c33b0821643fd94789fa1 | 4,399 | Yabapi | Creative Commons Zero v1.0 Universal |
core/testdata/format/inheritedExtensions.kt | google | 146,018,194 | true | null | open class Foo
class Bar : Foo()
fun Foo.first() {
}
fun Bar.second() {
}
| 12 | Kotlin | 7 | 14 | b4acc55431d4984d5253862d964e0939f5bd76d2 | 79 | dokka | Apache License 2.0 |
android/khajit/app/src/main/java/com/project/khajit_app/data/models/isFollowingPortfolioResponse.kt | bounswe | 170,124,936 | false | {"Kotlin": 416637, "Python": 210731, "SCSS": 184849, "CSS": 97799, "Less": 78481, "JavaScript": 56513, "HTML": 35601, "Dockerfile": 1032, "Shell": 76} | package com.project.khajit_app.data.models
data class isFollowingPortfolioResponse( val detail: String?, val result: String?) | 31 | Kotlin | 2 | 9 | 40370c1e8ff7f49dead59034e8baab8a99e3adbf | 126 | bounswe2019group1 | MIT License |
android/DartsScorecard/domain/src/main/java/nl/entreco/domain/setup/players/DeletePlayerRequest.kt | Entreco | 110,022,468 | false | null | package nl.entreco.domain.setup.players
/**
* Created by entreco on 17/03/2018.
*/
class DeletePlayerRequest(val ids: LongArray) | 4 | Kotlin | 0 | 0 | a031a0eeadd0aa21cd587b5008364a16f890b264 | 131 | Darts-Scorecard | Apache License 2.0 |
mds_engine/src/jvmMain/kotlin/mds/engine/interfaces/MdsEngineConfigBuilder.kt | MikeDirven | 655,573,300 | false | {"Kotlin": 48307} | package mds.engine.interfaces
interface MdsEngineConfigBuilder {
/**
* Port to listen on. Defaults to 8080
*/
var port: Int
/**
* The host to listen on
*/
var host: String
/**
* The maximum amount of thread pools to use for incoming requests
*/
var maxPools: Int
/**
* The maximum amount of thread per pool to use for incoming requests
*/
var maxPoolThreads: Int
/**
* The entry point to activate while building te server
*/
var entryPoint: mds.engine.MdsEngine.() -> Unit
} | 0 | Kotlin | 0 | 1 | 62e7def6971b2b7730dd658a094f0bff21b04d75 | 569 | MDS | Apache License 2.0 |
src/main/java/net/atlantis/weeding/listener/WeedingListener.kt | AtlantisMinecraft | 83,115,780 | false | null | package net.atlantis.weeding.listener
import net.atlantis.weeding.Weeding
import net.atlantis.weeding.item.WeedItem
import net.atlantis.weeding.item.WeedingItem
import org.bukkit.ChatColor
import org.bukkit.Material
import org.bukkit.Particle
import org.bukkit.Sound
import org.bukkit.block.Block
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.block.Action
import org.bukkit.event.player.PlayerInteractEvent
class WeedingListener(private val plugin: Weeding) : Listener {
init {
plugin.server.pluginManager.registerEvents(this, plugin)
}
@EventHandler
fun onClick(event: PlayerInteractEvent) {
if (event.action == Action.RIGHT_CLICK_AIR || event.action == Action.RIGHT_CLICK_BLOCK) {
val player = event.player
val itemStack = player.inventory.itemInMainHand
var count = 0
if (WeedingItem.isWeedingTotem(itemStack)) {
val hash: Set<Material>? = null
val targetLocation = player.getTargetBlock(hash, 100).location
val range = 5
for (x in -range..range) {
for (y in -range..range) {
for (z in -range..range) {
val targetX = (targetLocation.x + x).toInt()
val targetY = (targetLocation.y + y).toInt()
val targetZ = (targetLocation.z + z).toInt()
val block = player.world.getBlockAt(targetX, targetY, targetZ)
if (weeding(block)) {
count += 1
}
}
}
}
if (count > 0) {
player.playSound(player.location, Sound.ENTITY_ENDERMEN_TELEPORT, 3.0f, 0.533f)
}
player.sendMessage("[" + ChatColor.AQUA.toString() + ChatColor.BOLD.toString() + "Weeding" + ChatColor.RESET.toString() + "] $count 個除草しました")
}
}
}
private fun weeding(block: Block): Boolean = if (WeedItem.isWeedItem(block)) {
block.type = Material.AIR
block.world.spawnParticle(Particle.LAVA, block.location, 2)
true
} else {
false
}
} | 0 | Kotlin | 0 | 0 | a32eb951218917eadf5b894246ed828e154e8dcd | 2,332 | Weeding | MIT License |
src/main/kotlin/io/lettuce/ServerUtils.kt | lettuce-io | 84,678,779 | true | null | /*
* Copyright 2018-2019 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 io.lettuce
import org.springframework.core.io.ClassPathResource
import org.springframework.util.StreamUtils
import javax.activation.MimetypesFileTypeMap
import java.io.IOException
import java.io.InputStream
import java.nio.charset.StandardCharsets
import java.nio.file.FileSystem
import java.nio.file.FileSystems
import java.nio.file.Path
import java.nio.file.Paths
import java.util.Collections
/**
* @author <NAME>
*/
internal object ServerUtils {
val mimeTypes: MimetypesFileTypeMap
get() {
val fileTypeMap = MimetypesFileTypeMap()
fileTypeMap.addMimeTypes("text/css css text CSS")
fileTypeMap.addMimeTypes("text/javascript js text JS")
fileTypeMap.addMimeTypes("image/png png image PNG")
fileTypeMap.addMimeTypes("image/svg+xml svg image svg")
fileTypeMap.addMimeTypes("application/x-font-woff woff font WOFF")
fileTypeMap.addMimeTypes("application/x-font-woff woff2 font WOFF2")
return fileTypeMap
}
@Throws(IOException::class)
fun resolveContentPath(): Path {
val cp = ClassPathResource("static")
if (cp.isFile) {
return Paths.get(cp.uri)
}
val fs = FileSystems.newFileSystem(cp.uri, emptyMap<String, Any>())
Runtime.getRuntime().addShutdownHook(Thread {
try {
fs.close()
} catch (io: IOException) {
// ignore
}
})
return fs.getPath("static")
}
@Throws(IOException::class)
fun getResourceAsString(resource: String): String {
ServerUtils::class.java.getResourceAsStream(resource).use { `is` -> return StreamUtils.copyToString(`is`, StandardCharsets.UTF_8) }
}
}
| 0 | CSS | 6 | 10 | 466531bc379b8244d627f31ee3daac5ef0340572 | 2,396 | lettuce.io | Apache License 2.0 |
app/src/main/java/com/dombikpanda/doktarasor/ui/view/activity/MainActivity.kt | omeryavuzyigit61 | 507,668,259 | false | {"Kotlin": 106259} | package com.dombikpanda.doktarasor.ui.view.activity
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import com.dombikpanda.doktarasor.di.MyContextWrapper
import com.dombikpanda.doktarasor.R
import com.dombikpanda.doktarasor.di.MyPreference
class MainActivity : AppCompatActivity() {
private lateinit var myPreference: MyPreference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportActionBar?.hide()
Handler(Looper.getMainLooper()).postDelayed({
val intent = Intent(this, LoginActivity::class.java)
startActivity(intent)
finish()
}, 750)
}
override fun attachBaseContext(newBase: Context?) {
myPreference = MyPreference(newBase!!)
val lang: String? = myPreference.getLanguageCount()
super.attachBaseContext(lang?.let { MyContextWrapper.wrap(newBase, it) })
}
} | 0 | Kotlin | 0 | 0 | 8b68b97a359630fb4f333f2d5f6d034e4e172cd6 | 1,107 | DoktaraSor | MIT License |
channels/telegram/src/main/kotlin/com/justai/jaicf/channel/telegram/TelegramEvent.kt | klits111 | 282,262,247 | true | {"Kotlin": 236742, "Java": 11791} | package com.justai.jaicf.channel.telegram
object TelegramEvent {
const val LOCATION = "location"
const val CONTACT = "contact"
} | 0 | null | 0 | 1 | 13be1ef63afc67c913e934d6b20d2a2a862731db | 137 | jaicf-kotlin | Apache License 2.0 |
shared/src/commonMain/kotlin/com.sbga.sdgbapp/DB/OptionStarrotateID.kt | NickJi2019 | 717,286,554 | false | {"Kotlin": 134744, "Ruby": 2257, "Swift": 1595, "JavaScript": 485, "HTML": 323} | package com.sbga.sdgbapp.DB
enum class OptionMatchingID(val value: Int) {
Off(0),
On(1),
Begin(0),
End(2),
Invalid(-1)
}
| 0 | Kotlin | 1 | 4 | 4358ab163f560a9e28255b789e42b8054e4cd8f9 | 142 | SDGBApp | MIT License |
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/KonanLower.kt | sbogolepov | 165,853,039 | true | {"Kotlin": 4364554, "C++": 827577, "Groovy": 144911, "C": 122275, "Objective-C++": 84211, "Swift": 36907, "JavaScript": 18038, "Python": 11091, "Shell": 9240, "Batchfile": 7139, "Objective-C": 3532, "Pascal": 1698, "Java": 782, "Dockerfile": 422, "HTML": 185} | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.backend.konan
import org.jetbrains.kotlin.backend.common.runOnFilePostfix
import org.jetbrains.kotlin.backend.common.lower.*
import org.jetbrains.kotlin.backend.konan.lower.*
import org.jetbrains.kotlin.backend.konan.lower.ExpectDeclarationsRemoving
import org.jetbrains.kotlin.backend.konan.lower.FinallyBlocksLowering
import org.jetbrains.kotlin.backend.konan.lower.InitializersLowering
import org.jetbrains.kotlin.backend.konan.lower.LateinitLowering
import org.jetbrains.kotlin.backend.konan.lower.SharedVariablesLowering
import org.jetbrains.kotlin.backend.konan.lower.loops.ForLoopsLowering
import org.jetbrains.kotlin.ir.declarations.IrFile
import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
import org.jetbrains.kotlin.ir.util.checkDeclarationParents
import org.jetbrains.kotlin.ir.util.patchDeclarationParents
import org.jetbrains.kotlin.ir.util.replaceUnboundSymbols
internal class KonanLower(val context: Context, val parentPhaser: PhaseManager) {
fun lower() {
val irModule = context.irModule!!
// Phases to run against whole module.
lowerModule(irModule, parentPhaser)
// Phases to run against a file.
irModule.files.forEach {
lowerFile(it, PhaseManager(context, parentPhaser))
}
irModule.checkDeclarationParents()
}
private fun lowerModule(irModule: IrModuleFragment, phaser: PhaseManager) {
phaser.phase(KonanPhase.REMOVE_EXPECT_DECLARATIONS) {
irModule.files.forEach(ExpectDeclarationsRemoving(context)::lower)
}
phaser.phase(KonanPhase.TEST_PROCESSOR) {
TestProcessor(context).process(irModule)
}
phaser.phase(KonanPhase.LOWER_BEFORE_INLINE) {
irModule.files.forEach(PreInlineLowering(context)::lower)
}
// Inlining must be run before other phases.
phaser.phase(KonanPhase.LOWER_INLINE) {
FunctionInlining(context).inline(irModule)
}
phaser.phase(KonanPhase.LOWER_AFTER_INLINE) {
irModule.files.forEach(PostInlineLowering(context)::lower)
// TODO: Seems like this should be deleted in PsiToIR.
irModule.files.forEach(ContractsDslRemover(context)::lower)
}
phaser.phase(KonanPhase.LOWER_INTEROP_PART1) {
irModule.files.forEach(InteropLoweringPart1(context)::lower)
}
phaser.phase(KonanPhase.LOWER_LATEINIT) {
irModule.files.forEach(LateinitLowering(context)::lower)
}
val symbolTable = context.ir.symbols.symbolTable
do {
@Suppress("DEPRECATION")
irModule.replaceUnboundSymbols(context)
} while (symbolTable.unboundClasses.isNotEmpty())
irModule.patchDeclarationParents()
// validateIrModule(context, irModule) // Temporarily disabled until moving to new IR finished.
}
private fun lowerFile(irFile: IrFile, phaser: PhaseManager) {
phaser.phase(KonanPhase.LOWER_STRING_CONCAT) {
StringConcatenationLowering(context).lower(irFile)
}
phaser.phase(KonanPhase.LOWER_DATA_CLASSES) {
DataClassOperatorsLowering(context).runOnFilePostfix(irFile)
}
phaser.phase(KonanPhase.LOWER_FOR_LOOPS) {
ForLoopsLowering(context).lower(irFile)
}
phaser.phase(KonanPhase.LOWER_ENUMS) {
EnumClassLowering(context).run(irFile)
}
/**
* TODO: this is workaround for issue of unitialized parents in IrDeclaration,
* the last one detected in [EnumClassLowering]. The issue appears in [DefaultArgumentStubGenerator].
*/
irFile.patchDeclarationParents()
phaser.phase(KonanPhase.LOWER_INITIALIZERS) {
InitializersLowering(context).runOnFilePostfix(irFile)
}
phaser.phase(KonanPhase.LOWER_SHARED_VARIABLES) {
SharedVariablesLowering(context).runOnFilePostfix(irFile)
}
phaser.phase(KonanPhase.LOWER_DELEGATION) {
PropertyDelegationLowering(context).lower(irFile)
}
phaser.phase(KonanPhase.LOWER_CALLABLES) {
CallableReferenceLowering(context).lower(irFile)
}
/**
* TODO: this is workaround for issue of unitialized parents in IrDeclaration,
* the last one detected in [CallableReferenceLowering]. The issue appears in [LocalDeclarationsLowering].
*/
irFile.patchDeclarationParents()
phaser.phase(KonanPhase.LOWER_LOCAL_FUNCTIONS) {
LocalDeclarationsLowering(context).runOnFilePostfix(irFile)
}
phaser.phase(KonanPhase.LOWER_TAILREC) {
TailrecLowering(context).runOnFilePostfix(irFile)
}
phaser.phase(KonanPhase.LOWER_FINALLY) {
FinallyBlocksLowering(context).lower(irFile)
}
phaser.phase(KonanPhase.LOWER_DEFAULT_PARAMETER_EXTENT) {
DefaultArgumentStubGenerator(context).runOnFilePostfix(irFile)
KonanDefaultParameterInjector(context).runOnFilePostfix(irFile)
}
phaser.phase(KonanPhase.LOWER_BUILTIN_OPERATORS) {
BuiltinOperatorLowering(context).lower(irFile)
}
phaser.phase(KonanPhase.LOWER_INNER_CLASSES) {
InnerClassLowering(context).runOnFilePostfix(irFile)
}
phaser.phase(KonanPhase.LOWER_INTEROP_PART2) {
InteropLoweringPart2(context).lower(irFile)
}
phaser.phase(KonanPhase.LOWER_VARARG) {
VarargInjectionLowering(context).runOnFilePostfix(irFile)
}
phaser.phase(KonanPhase.LOWER_COMPILE_TIME_EVAL) {
CompileTimeEvaluateLowering(context).lower(irFile)
}
phaser.phase(KonanPhase.LOWER_COROUTINES) {
SuspendFunctionsLowering(context).lower(irFile)
}
phaser.phase(KonanPhase.LOWER_TYPE_OPERATORS) {
TypeOperatorLowering(context).runOnFilePostfix(irFile)
}
phaser.phase(KonanPhase.BRIDGES_BUILDING) {
BridgesBuilding(context).runOnFilePostfix(irFile)
WorkersBridgesBuilding(context).lower(irFile)
}
phaser.phase(KonanPhase.AUTOBOX) {
// validateIrFile(context, irFile) // Temporarily disabled until moving to new IR finished.
Autoboxing(context).lower(irFile)
}
phaser.phase(KonanPhase.RETURNS_INSERTION) {
ReturnsInsertionLowering(context).lower(irFile)
}
}
}
| 0 | Kotlin | 2 | 1 | 6d141ba87d576e87d87f905627b83f3dac7202b0 | 6,685 | kotlin-native | Apache License 2.0 |
app/src/main/java/com/example/formapp/navigation/AppScreens.kt | fgarridofi | 743,682,977 | false | {"Kotlin": 224638, "JavaScript": 7398} | package com.example.formapp.navigation
sealed class AppScreens(val route :String){
object InicioScreen: AppScreens("inicio_screen")
object FormScreen: AppScreens("formulario_screen")
object MenuPrincipalScreen: AppScreens("menu_screen")
object NavegarScreen: AppScreens("navegar_screen")
object HistorialScreen: AppScreens("historial_screen")
object RecambiosScreen: AppScreens("recambios_screen")
object MenuNeumaticosScreen : AppScreens("menu_neumaticos_screen")
object MenuFiltrosScreen : AppScreens("menu_filtros_screen")
object MenuFrenosScreen : AppScreens("menu_frenos_screen")
object MenuLiquidosScreen : AppScreens("menu_liquidos_screen")
object MenuOtrosComponentesScreen : AppScreens("menu_otroscomponentes_screen")
object MenuAceitesScreen : AppScreens("menu_aceites_screen")
object PruebaScreen : AppScreens("prueba")
}
| 0 | Kotlin | 0 | 1 | 9cfd8de17550e60b8776f8200e93362b024cedc2 | 886 | car-navigation-mobile-app | MIT License |
app/src/main/java/dev/atsushieno/fluidsynthmidideviceservicej/ConfigurationKeys.kt | atsushieno | 147,109,652 | false | null | package dev.atsushieno.fluidsynthmidideviceservicej
class ConfigurationKeys
{
companion object {
@JvmStatic
val SynthAudioChannels = "synth.audio-channels"
@JvmStatic
val SynthAudioGroups = "synth.audio-groups"
@JvmStatic
val SynthChorusActive = "synth.chorus.active"
@JvmStatic
val SynthCpuCores = "synth.cpu-cores"
@JvmStatic
val SynthDeviceId = "synth.device-id"
@JvmStatic
val SynthDump = "synth.dump"
@JvmStatic
val SynthEffectsChannels = "synth.effects-channels"
@JvmStatic
val SynthGain = "synth.gain"
@JvmStatic
val SynthLadspaActive = "synth.ladspa.active"
@JvmStatic
val SynthMidiChannels = "synth.midi-channels"
@JvmStatic
val SynthMidiBankSelect = "synth.midi-bank-select"
@JvmStatic
val SynthMinNoteLength = "synth.min-note-length"
@JvmStatic
val SynthParallelRender = "synth.parallel-render"
@JvmStatic
val SynthPolyphony = "synth.polyphony"
@JvmStatic
val SynthReverbActive = "synth.reverb.active"
@JvmStatic
val SynthSampleRate = "synth.sample-rate"
@JvmStatic
val SynthThreadSafeApi = "synth.threadsafe-api"
@JvmStatic
val SynthVerbose = "synth.verbose"
@JvmStatic
val AudioDriver = "audio.driver"
@JvmStatic
val AudioPeriods = "audio.periods"
@JvmStatic
val AudioPeriodSize = "audio.period-size"
@JvmStatic
val AudioRealtimePrio = "audio.realtime-prio"
@JvmStatic
val AudioSampleFormat = "audio.sample-format"
@JvmStatic
val AudioAlsaDevice = "audio.alsa.device"
@JvmStatic
val AudioCoreAudioDevice = "audio.coreaudio.device"
@JvmStatic
val AudioDartDevice = "audio.dart.device"
@JvmStatic
val AudioDsoundDevice = "audio.dsound.device"
@JvmStatic
val AudioFileEndian = "audio.file.endian"
@JvmStatic
val AudioFileFormat = "audio.file.format"
@JvmStatic
val AudioFileName = "audio.file.name"
@JvmStatic
val AudioFileType = "audio.file.type"
@JvmStatic
val AudioJackAutoconnect = "audio.jack.autoconnect"
@JvmStatic
val AudioJackId = "audio.jack.id"
@JvmStatic
val AudioJackMulti = "audio.jack.multi"
@JvmStatic
val AudioJackServer = "audio.jack.server"
@JvmStatic
val AudioOssDevice = "audio.oss.device"
@JvmStatic
val AudioPortAudioDevice = "audio.portaudio.device"
@JvmStatic
val AudioPulseAudioDevice = "audio.pulseaudio.device"
@JvmStatic
val AudioPulseAudioServer = "audio.pulseaudio.server"
@JvmStatic
val MidiDriver = "midi.driver"
@JvmStatic
val MidiRealTimePriority = "midi.realtime-prio"
@JvmStatic
val MidiAlsaDevice = "midi.alsa.device"
@JvmStatic
val MidiAlsaSeqDevice = "midi.alsa_seq.device"
@JvmStatic
val MidiAlsaSeqId = "midi.alsa_seq.id"
@JvmStatic
val MidiJackId = "midi.jack.id"
@JvmStatic
val MidiJackServer = "midi.jack.server"
@JvmStatic
val MidiOssDevice = "midi.oss.device"
@JvmStatic
val MidiPortName = "midi.portname"
@JvmStatic
val AudioOboeId = "audio.oboe.id"
@JvmStatic
val AudioOboeSharingMode = "audio.oboe.sharing-mode"
@JvmStatic
val AudioOboePerformanceMode = "audio.oboe.performance-mode"
@JvmStatic
val AudioOboeSampleRateConversionQuality = "audio.oboe.sample-rate-conversion-quality"
@JvmStatic
val AudioOboeErrorRecoveryMode = "audio.oboe.error-recovery-mode"
}
}
| 6 | Kotlin | 6 | 24 | 7a6ab797eeee8dd4c20228af2d854491ad989964 | 3,880 | fluidsynth-midi-service-j | MIT License |
src/commonMain/kotlin/com/darkos/oauth/scope/ScopesConfig.kt | Darkos-den | 315,729,047 | false | null | package com.darkos.oauth.scope
import com.darkos.oauth.client.OAuthDsl
@OAuthDsl
class ScopesConfig{
internal var scopes: List<OAuthScope> = emptyList()
fun addScope(scope: OAuthScope){
if(scopes.contains(scope).not()){
scopes = scopes + scope
}
}
internal fun apply(config: ScopesConfig){
config.scopes.forEach(this::addScope)
}
} | 0 | Kotlin | 0 | 0 | f30c14a49d5ce3645995ee38d805c60fc8f26aa2 | 391 | oauth-client | Apache License 2.0 |
library/src/main/java/com/victor/kplayer/library/util/FacebookParser.kt | Victor2018 | 154,598,071 | false | null | package com.victor.kplayer.library.util
import android.text.TextUtils
import com.victor.kplayer.library.data.FacebookReq
/*
* -----------------------------------------------------------------
* Copyright (C) 2018-2028, by longtv, All rights reserved.
* -----------------------------------------------------------------
* File: FacebookParser.java
* Author: Victor
* Date: 2018/10/24 15:59
* Description:
* -----------------------------------------------------------------
*/
class FacebookParser {
companion object {
fun parseFacebook (response: String?): FacebookReq {
var facebookReq = FacebookReq()
if (response?.contains("\n")!!) {
val items = response.split("\n".toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()
for (i in items.indices) {
if (items[i].contains("no_ratelimit")) {
val datas = items[i].split(",".toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()
for (j in datas.indices) {
if (datas[j].contains("hd_src_no_ratelimit") && datas[j].split("\"".toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray().size >= 2) {
facebookReq.hdPlayUrl = datas[j].split("\"".toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()[1]
}
if (datas[j].contains("sd_src_no_ratelimit") && datas[j].split("\"".toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray().size >= 2) {
facebookReq.sdPlayUrl = datas[j].split("\"".toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()[1]
}
}
}
}
}
facebookReq.playUrl = facebookReq.hdPlayUrl
if (TextUtils.isEmpty(facebookReq.playUrl)) {
facebookReq.playUrl = facebookReq.sdPlayUrl
}
return facebookReq
}
}
} | 0 | Kotlin | 1 | 1 | 0e7fa0c74616f666d2109a99ffea250c617ff6d9 | 2,042 | KPlayer | Apache License 2.0 |
compiler/testData/codegen/box/reflection/createAnnotation/callByJava.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // TARGET_BACKEND: JVM
// WITH_REFLECT
// FILE: J.java
public interface J {
@interface NoParams {}
@interface OneDefault {
String s() default "OK";
}
@interface OneNonDefault {
String s();
}
@interface TwoParamsOneDefault {
String s();
int x() default 42;
}
@interface TwoNonDefaults {
String string();
Class<?> clazz();
}
@interface ManyDefaultParams {
int i() default 0;
String s() default "";
double d() default 3.14;
}
}
// FILE: K.kt
import J.*
import kotlin.reflect.KClass
import kotlin.reflect.full.primaryConstructor
import kotlin.test.assertEquals
import kotlin.test.assertFails
inline fun <reified T : Annotation> create(args: Map<String, Any?>): T {
val ctor = T::class.constructors.single()
return ctor.callBy(args.mapKeys { entry -> ctor.parameters.single { it.name == entry.key } })
}
inline fun <reified T : Annotation> create(): T = create(emptyMap())
fun box(): String {
create<NoParams>()
val t1 = create<OneDefault>()
assertEquals("OK", t1.s)
assertFails { create<OneDefault>(mapOf("s" to 42)) }
val t2 = create<OneNonDefault>(mapOf("s" to "OK"))
assertEquals("OK", t2.s)
assertFails { create<OneNonDefault>() }
val t3 = create<TwoParamsOneDefault>(mapOf("s" to "OK"))
assertEquals("OK", t3.s)
assertEquals(42, t3.x)
val t4 = create<TwoParamsOneDefault>(mapOf("s" to "OK", "x" to 239))
assertEquals(239, t4.x)
assertFails { create<TwoParamsOneDefault>(mapOf("s" to "Fail", "x" to "Fail")) }
assertFails("KClass (not Class) instances should be passed as arguments") {
create<TwoNonDefaults>(mapOf("clazz" to String::class.java, "string" to "Fail"))
}
val t5 = create<TwoNonDefaults>(mapOf("clazz" to String::class, "string" to "OK"))
assertEquals("OK", t5.string)
val t6 = create<ManyDefaultParams>()
assertEquals(0, t6.i)
assertEquals("", t6.s)
assertEquals(3.14, t6.d)
return "OK"
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 2,042 | kotlin | Apache License 2.0 |
aoc-2018/src/main/kotlin/nl/jstege/adventofcode/aoc2018/days/Day11.kt | JStege1206 | 92,714,900 | false | null | package nl.jstege.adventofcode.aoc2018.days
import nl.jstege.adventofcode.aoccommon.days.Day
import nl.jstege.adventofcode.aoccommon.utils.extensions.applyIf
import nl.jstege.adventofcode.aoccommon.utils.extensions.head
import nl.jstege.adventofcode.aoccommon.utils.extensions.min
import kotlin.math.min
class Day11 : Day(title = "Chronal Charge") {
companion object Configuration {
private const val GRID_WIDTH = 300
private const val GRID_HEIGHT = 300
private const val FIRST_SQUARE_SIZE = 3
}
override fun first(input: Sequence<String>): Any = input.head.toInt().let { serialNumber ->
solve(serialNumber, FIRST_SQUARE_SIZE, FIRST_SQUARE_SIZE)
.let { (x, y, size) -> "${x - size + 1},${y - size + 1}" }
}
override fun second(input: Sequence<String>): Any = input.head.toInt().let { serialNumber ->
solve(serialNumber, 1, min(GRID_WIDTH, GRID_HEIGHT))
.let { (x, y, size) -> "${x - size + 1},${y - size + 1},$size" }
}
private fun solve(
serialNumber: Int,
minSquareSize: Int,
maxSquareSize: Int
): Triple<Int, Int, Int> {
val grid = IntArray((GRID_HEIGHT + 1) * (GRID_WIDTH + 1))
var max = Triple(0, 0, Int.MIN_VALUE)
var maxValue = Int.MIN_VALUE
for (y in 1..GRID_HEIGHT) {
for (x in 1..GRID_WIDTH) {
grid[x, y] = powerInCell(serialNumber, x, y) + grid[x, y - 1] + grid[x - 1, y] -
grid[x - 1, y - 1]
for (size in minSquareSize..min(maxSquareSize, x, y)) {
grid.getSumOfSquare(x, y, size)
.applyIf({ this > maxValue }) {
maxValue = this
max = Triple(x, y, size)
}
}
}
}
return max
}
private fun powerInCell(serialNumber: Int, x: Int, y: Int): Int = (x + 10).let { rackId ->
(rackId * y + serialNumber) * rackId / 100 % 10 - 5
}
private fun toIndex(x: Int, y: Int) = y * (GRID_WIDTH + 1) + x
private fun IntArray.getSumOfSquare(x: Int, y: Int, size: Int): Int =
this[x, y] - this[x, y - size] - this[x - size, y] + this[x - size, y - size]
private operator fun IntArray.get(x: Int, y: Int): Int =
this[toIndex(x, y)]
private operator fun IntArray.set(x: Int, y: Int, value: Int) {
this[toIndex(x, y)] = value
}
}
| 0 | Kotlin | 0 | 0 | d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025 | 2,483 | AdventOfCode | MIT License |
compiler/tests-spec/testData/diagnostics/linked/overload-resolution/building-the-overload-candidate-set-ocs/call-without-an-explicit-receiver/p-5/pos/4.1.kt | android | 263,405,600 | true | null | // FIR_IDENTICAL
// !LANGUAGE: +NewInference
// !DIAGNOSTICS: -UNUSED_VARIABLE -ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE -UNUSED_VALUE -UNUSED_PARAMETER -UNUSED_EXPRESSION -NOTHING_TO_INLINE
// SKIP_TXT
/*
* KOTLIN DIAGNOSTICS SPEC TEST (POSITIVE)
*
* SPEC VERSION: 0.1-278
* MAIN LINK: overload-resolution, building-the-overload-candidate-set-ocs, call-without-an-explicit-receiver -> paragraph 5 -> sentence 4
* PRIMARY LINKS: overload-resolution, building-the-overload-candidate-set-ocs, call-without-an-explicit-receiver -> paragraph 4 -> sentence 1
* overload-resolution, building-the-overload-candidate-set-ocs, call-without-an-explicit-receiver -> paragraph 8 -> sentence 1
* overload-resolution, building-the-overload-candidate-set-ocs, call-without-an-explicit-receiver -> paragraph 6 -> sentence 1
* overload-resolution, building-the-overload-candidate-set-ocs, call-with-specified-type-parameters -> paragraph 1 -> sentence 2
* NUMBER: 1
* DESCRIPTION: Top-level non-extension functions: Callables explicitly imported into the current file
*/
// FILE: TestCase.kt
// TESTCASE NUMBER: 1
package testsCase1
import libPackageCase1.*
import libPackageCase1Explicit.emptyArray
fun case1() {
<!DEBUG_INFO_CALL("fqName: libPackageCase1Explicit.emptyArray; typeCall: function")!>emptyArray<Int>()<!>
}
// FILE: Lib.kt
package libPackageCase1
public fun <T> emptyArray(): Array<T> = TODO()
// FILE: Lib.kt
package libPackageCase1Explicit
public fun <T> emptyArray(): Array<T> = TODO()
// FILE: LibtestsPack.kt
package testsCase1
public fun <T> emptyArray(): Array<T> = TODO()
// FILE: TestCase.kt
// TESTCASE NUMBER: 2
package testsCase2
import libPackageCase2.*
import libPackageCase2Explicit.emptyArray
fun case2() {
<!DEBUG_INFO_CALL("fqName: libPackageCase2Explicit.emptyArray; typeCall: function")!>emptyArray<Int>()<!>
}
class A {
operator fun <T>invoke(): T = TODO()
}
// FILE: Lib.kt
package libPackageCase2
public fun <T> emptyArray(): Array<T> = TODO()
// FILE: Lib.kt
package libPackageCase2Explicit
import testsCase2.*
val emptyArray: A
get() = A()
public fun <T> emptyArray(): Array<T> = TODO()
// FILE: LibtestsPack.kt
package testsCase2
public fun <T> emptyArray(): Array<T> = TODO()
// FILE: TestCase.kt
// TESTCASE NUMBER: 3
package testsCase3
import libPackageCase3.*
import libPackageCase3Explicit.emptyArray
fun case3() {
<!DEBUG_INFO_CALL("fqName: testsCase3.A.invoke; typeCall: variable&invoke")!>emptyArray<Int>()<!>
}
class A {
operator fun <T>invoke(): T = TODO()
}
// FILE: Lib.kt
package libPackageCase3
public fun <T> emptyArray(): Array<T> = TODO()
// FILE: Lib.kt
package libPackageCase3Explicit
import testsCase3.*
val emptyArray: A
get() = A()
private fun <T> emptyArray(): Array<T> = TODO()
// FILE: LibtestsPack.kt
package testsCase3
public fun <T> emptyArray(): Array<T> = TODO()
| 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 2,881 | kotlin | Apache License 2.0 |
rxhttp-compiler/src/main/java/com/rxhttp/compiler/kapt/RxHttpExtensions.kt | zhuifeng2215 | 583,514,899 | false | {"Kotlin": 486335, "Java": 253132} | package com.rxhttp.compiler.kapt
import com.rxhttp.compiler.common.getParamsName
import com.rxhttp.compiler.common.getTypeOfString
import com.rxhttp.compiler.common.getTypeVariableString
import com.rxhttp.compiler.isDependenceRxJava
import com.rxhttp.compiler.rxHttpPackage
import com.rxhttp.compiler.rxhttpKClassName
import com.squareup.kotlinpoet.AnnotationSpec
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.FileSpec
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.LambdaTypeName
import com.squareup.kotlinpoet.MemberName
import com.squareup.kotlinpoet.ParameterSpec
import com.squareup.kotlinpoet.ParameterizedTypeName
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.TypeVariableName
import com.squareup.kotlinpoet.asClassName
import com.squareup.kotlinpoet.asTypeName
import com.squareup.kotlinpoet.asTypeVariableName
import org.jetbrains.annotations.Nullable
import javax.annotation.processing.Filer
import javax.lang.model.element.TypeElement
import javax.lang.model.type.TypeKind
/**
* User: ljx
* Date: 2020/3/9
* Time: 17:04
*/
class RxHttpExtensions {
private val baseRxHttpName = ClassName(rxHttpPackage, "BaseRxHttp")
private val callFactoryName = ClassName("rxhttp.wrapper", "CallFactory")
private val toFunList = ArrayList<FunSpec>()
private val asFunList = ArrayList<FunSpec>()
//根据@Parser注解,生成asXxx()、toXxx()、toFlowXxx()系列方法
fun generateRxHttpExtendFun(typeElement: TypeElement, key: String) {
//遍历获取泛型类型
val typeVariableNames = typeElement.typeParameters.map {
it.asTypeVariableName()
}
//遍历构造方法
for (constructor in typeElement.getPublicConstructors()) {
val tempParameters = constructor.parameters
var fromIndex = typeVariableNames.size
if ("java.lang.reflect.Type[]" ==
tempParameters.firstOrNull()?.asType()?.toString()
) {
fromIndex = 1
}
//构造方法参数数量小于泛型数量,直接过滤掉
if (tempParameters.size < fromIndex) continue
//移除前n个Type类型参数,n为泛型数量
val parameters = tempParameters.subList(fromIndex, tempParameters.size)
//根据构造方法参数,获取asXxx方法需要的参数
val varArgsFun = constructor.isVarArgs //该构造方法是否携带可变参数,即是否为可变参数方法
val parameterList = parameters.mapIndexed { index, variableElement ->
val variableType = variableElement.asType()
val variableName = variableElement.simpleName.toString()
val annotation = variableElement.getAnnotation(Nullable::class.java)
var type = variableType.asTypeName()
val isVarArg = varArgsFun
&& index == constructor.parameters.lastIndex
&& variableType.kind == TypeKind.ARRAY
if (isVarArg) { //最后一个参数是可变参数
if (type is ParameterizedTypeName) {
type = type.typeArguments[0].toKClassTypeName()
}
} else {
type = type.toKClassTypeName()
}
if (annotation != null) type = type.copy(true)
val parameterSpecBuilder = ParameterSpec.builder(variableName, type)
if (isVarArg) {
parameterSpecBuilder.addModifiers(KModifier.VARARG)
}
parameterSpecBuilder.build()
}
val modifiers = ArrayList<KModifier>()
if (typeVariableNames.isNotEmpty()) {
modifiers.add(KModifier.INLINE)
}
val types = getTypeVariableString(typeVariableNames) // <T>, <K, V> 等
val typeOfs = getTypeOfString(typeVariableNames) // javaTypeOf<T>()等
val params = getParamsName(parameterList) //构造方法参数名列表
val finalParams = when {
typeOfs.isEmpty() -> params
params.isEmpty() -> typeOfs
else -> "$typeOfs, $params"
}
val parser = "%T$types($finalParams)"
if (typeVariableNames.isNotEmpty()) { //对声明了泛型的解析器,生成kotlin编写的asXxx方法
FunSpec.builder("as$key")
.addModifiers(modifiers)
.receiver(baseRxHttpName)
.addParameters(parameterList)
.addStatement("return asParser($parser)", typeElement.asClassName()) //方法里面的表达式
.addTypeVariables(typeVariableNames.getTypeVariableNames())
.build()
.apply { asFunList.add(this) }
}
FunSpec.builder("to$key")
.addModifiers(modifiers)
.receiver(callFactoryName)
.addParameters(parameterList)
.addStatement("return toParser($parser)", typeElement.asClassName()) //方法里面的表达式
.addTypeVariables(typeVariableNames.getTypeVariableNames())
.build()
.apply { toFunList.add(this) }
}
}
fun generateClassFile(filer: Filer) {
val t = TypeVariableName("T")
val k = TypeVariableName("K")
val v = TypeVariableName("V")
val launchName = ClassName("kotlinx.coroutines", "launch")
val progressName = ClassName("rxhttp.wrapper.entity", "Progress")
val simpleParserName = ClassName("rxhttp.wrapper.parse", "SimpleParser")
val coroutineScopeName = ClassName("kotlinx.coroutines", "CoroutineScope")
val p = TypeVariableName("P")
val r = TypeVariableName("R")
val wildcard = TypeVariableName("*")
val bodyParamName =
ClassName("rxhttp.wrapper.param", "AbstractBodyParam").parameterizedBy(p)
val rxHttpBodyParamName =
ClassName(rxHttpPackage, "RxHttpAbstractBodyParam").parameterizedBy(p, r)
val pBound = TypeVariableName("P", bodyParamName)
val rBound = TypeVariableName("R", rxHttpBodyParamName)
val progressSuspendLambdaName = LambdaTypeName.get(
parameters = arrayOf(progressName),
returnType = Unit::class.asClassName()
).copy(suspending = true)
val fileBuilder = FileSpec.builder(rxHttpPackage, "RxHttp")
.addImport("rxhttp.wrapper.utils", "javaTypeOf")
.addImport("rxhttp", "toParser")
val rxHttpName = rxhttpKClassName.parameterizedBy(wildcard, wildcard)
FunSpec.builder("executeList")
.addModifiers(KModifier.INLINE)
.receiver(rxHttpName)
.addTypeVariable(t.copy(reified = true))
.addStatement("return executeClass<List<T>>()")
.build()
.apply { fileBuilder.addFunction(this) }
FunSpec.builder("executeClass")
.addModifiers(KModifier.INLINE)
.receiver(rxHttpName)
.addTypeVariable(t.copy(reified = true))
.addStatement("return execute(%T<T>(javaTypeOf<T>()))", simpleParserName)
.build()
.apply { fileBuilder.addFunction(this) }
if (isDependenceRxJava()) {
FunSpec.builder("asList")
.addModifiers(KModifier.INLINE)
.receiver(baseRxHttpName)
.addTypeVariable(t.copy(reified = true))
.addStatement("return asClass<List<T>>()")
.build()
.apply { fileBuilder.addFunction(this) }
FunSpec.builder("asMap")
.addModifiers(KModifier.INLINE)
.receiver(baseRxHttpName)
.addTypeVariable(k.copy(reified = true))
.addTypeVariable(v.copy(reified = true))
.addStatement("return asClass<Map<K,V>>()")
.build()
.apply { fileBuilder.addFunction(this) }
FunSpec.builder("asClass")
.addModifiers(KModifier.INLINE)
.receiver(baseRxHttpName)
.addTypeVariable(t.copy(reified = true))
.addStatement("return asParser(%T<T>(javaTypeOf<T>()))", simpleParserName)
.build()
.apply { fileBuilder.addFunction(this) }
asFunList.forEach {
fileBuilder.addFunction(it)
}
}
val deprecatedAnnotation = AnnotationSpec.builder(Deprecated::class)
.addMember(
"""
"scheduled to be removed in RxHttp 3.0 release.",
level = DeprecationLevel.ERROR
""".trimIndent()
)
.build()
FunSpec.builder("upload")
.addKdoc(
"""
调用此方法监听上传进度
@param coroutine CoroutineScope对象,用于开启协程回调进度,进度回调所在线程取决于协程所在线程
@param progress 进度回调
此方法已废弃,请使用Flow监听上传进度,性能更优,且更简单,如:
```
RxHttp.postForm("/server/...")
.addFile("file", File("xxx/1.png"))
.toFlow<T> { //这里也可选择你解析器对应的toFlowXxx方法
val currentProgress = it.progress //当前进度 0-100
val currentSize = it.currentSize //当前已上传的字节大小
val totalSize = it.totalSize //要上传的总字节大小
}.catch {
//异常回调
}.collect {
//成功回调
}
```
""".trimIndent()
)
.addAnnotation(deprecatedAnnotation)
.receiver(rxHttpBodyParamName)
.addTypeVariable(pBound)
.addTypeVariable(rBound)
.addParameter("coroutine", coroutineScopeName)
.addParameter("progressCallback", progressSuspendLambdaName)
.addCode(
"""
param.setProgressCallback { progress, currentSize, totalSize ->
coroutine.%T { progressCallback(Progress(progress, currentSize, totalSize)) }
}
@Suppress("UNCHECKED_CAST")
return this as R
""".trimIndent(), launchName
)
.returns(r)
.build()
.apply { fileBuilder.addFunction(this) }
val toFlow = MemberName("rxhttp", "toFlow")
val toFlowProgress = MemberName("rxhttp", "toFlowProgress")
val onEachProgress = MemberName("rxhttp", "onEachProgress")
val bodyParamFactory = ClassName("rxhttp.wrapper", "BodyParamFactory")
toFunList.forEach {
fileBuilder.addFunction(it)
val parseName = it.name.substring(2)
val typeVariables = it.typeVariables
val arguments = StringBuilder()
it.parameters.forEach { p ->
if (KModifier.VARARG in p.modifiers) {
arguments.append("*")
}
arguments.append(p.name).append(",")
}
if (arguments.isNotEmpty()) arguments.deleteCharAt(arguments.length - 1)
FunSpec.builder("toFlow$parseName")
.addModifiers(it.modifiers)
.receiver(callFactoryName)
.addParameters(it.parameters)
.addTypeVariables(typeVariables)
.addStatement(
"""return %M(to$parseName${getTypeVariableString(typeVariables)}($arguments))""",
toFlow
)
.build()
.apply { fileBuilder.addFunction(this) }
val capacityParam = ParameterSpec.builder("capacity", Int::class)
.defaultValue("1")
.build()
val isInLine = KModifier.INLINE in it.modifiers
val builder = ParameterSpec.builder("progress", progressSuspendLambdaName)
if (isInLine) builder.addModifiers(KModifier.NOINLINE)
FunSpec.builder("toFlow$parseName")
.addModifiers(it.modifiers)
.receiver(bodyParamFactory)
.addTypeVariables(typeVariables)
.addParameters(it.parameters)
.addParameter(capacityParam)
.addParameter(builder.build())
.addCode(
"""
return
%M(to$parseName${getTypeVariableString(typeVariables)}($arguments), capacity)
.%M(progress)
""".trimIndent(), toFlowProgress, onEachProgress
)
.build()
.apply { fileBuilder.addFunction(this) }
FunSpec.builder("toFlow${parseName}Progress")
.addModifiers(it.modifiers)
.receiver(bodyParamFactory)
.addTypeVariables(typeVariables)
.addParameters(it.parameters)
.addParameter(capacityParam)
.addCode(
"""return %M(to$parseName${getTypeVariableString(typeVariables)}($arguments), capacity)""",
toFlowProgress
)
.build()
.apply { fileBuilder.addFunction(this) }
}
fileBuilder.build().writeTo(filer)
}
}
//获取泛型对象列表
private fun List<TypeVariableName>.getTypeVariableNames(): List<TypeVariableName> {
val anyTypeName = Any::class.asTypeName()
return map {
val bounds = it.bounds //泛型边界
if (bounds.isEmpty() || (bounds.size == 1 && bounds[0].toString() == "java.lang.Object")) {
TypeVariableName(it.name, anyTypeName).copy(reified = true)
} else {
(it.toKClassTypeName() as TypeVariableName).copy(reified = true)
}
}
} | 0 | Kotlin | 0 | 0 | 982ea675ccc2aa05e62e1ac3b16d0fc0c92244d8 | 14,512 | rxhttp | Apache License 2.0 |
app/src/main/java/com/example/temperatureconverterviewmodeldemo/MainActivity.kt | Ben-ayesu | 603,935,889 | false | null | package com.example.temperatureconverterviewmodeldemo
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.Crossfade
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.temperatureconverterviewmodeldemo.ui.theme.TemperatureConverterViewModelDemoTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
TemperatureConverterViewModelDemoTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
ScreenSetup()
}
}
}
}
}
@Composable
fun ScreenSetup(
viewModel: DemoViewModel = viewModel()
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxSize()
) {
var textState by remember {
mutableStateOf("")
}
val onTextChange = { text : String ->
textState = text
}
Text(
text = "Temperature Converter",
modifier = Modifier.padding(20.dp),
style = MaterialTheme.typography.bodyMedium,
)
MainScreen(
isFahrennheit = viewModel.isFahrenheit,
result = viewModel.result,
convertTemp = {
viewModel.convertTemp(it)
},
switchChange = {
viewModel.switchChange()
}
)
}
}
@Composable
fun MainScreen(
isFahrennheit: Boolean,
result: String,
convertTemp: (String) -> Unit,
switchChange: () -> Unit
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxSize()
) {
var textState by remember {
mutableStateOf("")
}
val onTextChange = { text: String ->
textState = text
}
Text(
text = "Temperature Converter",
modifier = Modifier.padding(20.dp),
style = MaterialTheme.typography.bodyMedium,
)
InputRow(
isFahrennheit = isFahrennheit,
textState = result,
switchChange = { convertTemp },
onTextChange = {
switchChange()
}
)
Text(
text = result,
modifier = Modifier
.padding(20.dp),
style = MaterialTheme.typography.headlineMedium
)
Button(
onClick = { convertTemp(textState) }
) {
Text(text = "Convert Temperature")
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun InputRow(
isFahrennheit: Boolean,
textState: String,
switchChange: () -> Unit,
onTextChange: (String) -> Unit
) {
Row(
verticalAlignment = Alignment.CenterVertically
) {
Switch(
checked = isFahrennheit,
onCheckedChange = { switchChange }
)
OutlinedTextField(
value = textState,
onValueChange = {
onTextChange(it)
},
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Number
),
singleLine = true,
label = {
Text(text = "Enter temperature")
},
modifier = Modifier
.padding(8.dp),
textStyle = TextStyle(fontWeight = FontWeight.Bold, fontSize = 30.sp),
trailingIcon = {
Icon(
painter = painterResource(R.drawable.baseline_ac_unit_24),
contentDescription = stringResource(R.string.frost),
modifier = Modifier
.size(40.dp)
)
}
)
Crossfade(
targetState = isFahrennheit,
animationSpec = tween(2000)
) { visible ->
when(visible) {
true -> Text(
"\u2109",
style = MaterialTheme.typography.headlineMedium
)
false -> Text(
"\u2103",
style = MaterialTheme.typography.headlineMedium
)
}
}
}
}
@Preview(
showBackground = true,
showSystemUi = true
)
@Composable
fun DefaultPreview(
model: DemoViewModel = viewModel()
) {
TemperatureConverterViewModelDemoTheme {
MainScreen(
isFahrennheit = model.isFahrenheit,
result = model.result,
convertTemp = {
model.convertTemp(it)
},
switchChange = {
model.switchChange()
}
)
}
} | 0 | Kotlin | 0 | 0 | 7384d22f62def993c0419e95643a86a3d4c844e3 | 6,399 | Temperature_Converter_ViewModelDemo | MIT License |
app/src/main/java/com/shzlabs/mamopay/data/local/prefs/UserPreferences.kt | shahzar | 245,971,747 | false | {"Kotlin": 70039} | package com.shzlabs.mamopay.data.local.prefs
import android.content.SharedPreferences
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class UserPreferences @Inject constructor(private val prefs: SharedPreferences) {
companion object {
const val KEY_AUTH_STATE = "PREF_KEY_AUTH_STATE"
const val KEY_PIN_HASH = "PREF_KEY_PIN_HASH"
const val KEY_BIOMETRIC_AUTH_SET = "PREF_KEY_BIOMETRIC_AUTH_SET"
const val KEY_FIRST_NAME = "PREF_KEY_FIRST_NAME"
const val KEY_LAST_NAME = "PREF_KEY_LAST_NAME"
}
fun setAuthState(authState: String) =
prefs.edit().putString(KEY_AUTH_STATE, authState).apply()
fun getAuthState(): String? =
prefs.getString(KEY_AUTH_STATE, null)
fun removeAuthState() =
prefs.edit().remove(KEY_AUTH_STATE).apply()
fun setFirstName(firstName: String) =
prefs.edit().putString(KEY_FIRST_NAME, firstName).apply()
fun getFirstName(): String? =
prefs.getString(KEY_FIRST_NAME, null)
fun removeFirstName() =
prefs.edit().remove(KEY_FIRST_NAME).apply()
fun setLastName(lastName: String) =
prefs.edit().putString(KEY_LAST_NAME, lastName).apply()
fun getLastName(): String? =
prefs.getString(KEY_LAST_NAME, null)
fun removeLastName() =
prefs.edit().remove(KEY_LAST_NAME).apply()
fun setPinHash(pin: String) =
prefs.edit().putString(KEY_PIN_HASH, pin).apply()
fun getPinHash(): String? =
prefs.getString(KEY_PIN_HASH, null)
fun removePinHash() =
prefs.edit().remove(KEY_PIN_HASH).apply()
fun setBiometricAuth(success: Boolean) =
prefs.edit().putBoolean(KEY_BIOMETRIC_AUTH_SET, success).apply()
fun getBiometricAuth(): Boolean =
prefs.getBoolean(KEY_BIOMETRIC_AUTH_SET, false)
fun removeBiometricAuth() =
prefs.edit().remove(KEY_BIOMETRIC_AUTH_SET).apply()
} | 0 | Kotlin | 0 | 3 | 403d5112b7c890ceec06f92f54f365debc575f81 | 1,925 | Fintech-Startup | Apache License 2.0 |