path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
CadastroPet/app/src/main/java/com/example/cadastropet/repository/AppDatabase.kt
RebecaVieiraM
839,322,635
false
{"Kotlin": 6157}
package com.example.cadastropet.repository import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase import com.example.cadastropet.model.PetModel import com.example.cadastropet.repository.dao.PetDao @Database(entities = [PetModel::class], version = 1) abstract class AppDatabase : RoomDatabase() { abstract fun petDao(): PetDao//Referência de PetDAO, pois iremos selecionar essa classe por meio da instancia do banco companion object{ private lateinit var INSTANCE: AppDatabase fun getDataBase(context: Context): AppDatabase{ if(!::INSTANCE.isInitialized) { synchronized(AppDatabase::class) { INSTANCE = Room.databaseBuilder(context, AppDatabase::class.java, "petdb").addMigrations( MIGRATION_1_2, MIGRATION_2_3).allowMainThreadQueries().build() } } return INSTANCE } private val MIGRATION_1_2: Migration = object : Migration(1, 2){ override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("") } } private val MIGRATION_2_3: Migration = object : Migration(2, 3){ override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("") } } } }
0
Kotlin
0
0
f8fff834cf4a30513dd0a5fe94d8c992ec282fc6
1,511
CadastroPet
MIT License
app/src/main/java/com/androidproject/githubuserapp/activity/DetailsActivity.kt
Biswajeet-23
597,825,743
false
null
package com.androidproject.githubuserapp.activity import android.annotation.SuppressLint import android.content.Intent import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.ImageView import androidx.core.content.ContextCompat import androidx.lifecycle.lifecycleScope import com.androidproject.githubuserapp.MainActivity import com.androidproject.githubuserapp.databinding.ActivityDetailsBinding import com.androidproject.githubuserapp.roomDB.AppDatabase import com.androidproject.githubuserapp.roomDB.FavRepoDao import com.androidproject.githubuserapp.roomDB.FavRepoModel import com.bumptech.glide.Glide import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch class DetailsActivity : AppCompatActivity() { private lateinit var binding : ActivityDetailsBinding @SuppressLint("SetTextI18n") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityDetailsBinding.inflate(layoutInflater) //creating the reference for image view val avatarImage: ImageView = binding.avatarImg //Extracting values from intent val repoName = intent.getStringExtra("title") val url = intent.getStringExtra("url") val description = intent.getStringExtra("description") val repoId: Int? = intent.getStringExtra("id")?.toInt() val avatar = intent.getStringExtra("avatar") val starCount: Int? = intent.getStringExtra("stargazers")?.toInt() val watchCount: Int? = intent.getStringExtra("watchers")?.toInt() val forkCount: Int? = intent.getStringExtra("forks")?.toInt() val subscriberCount: Int? = intent.getStringExtra("subscribers")?.toInt() val ownerName = intent.getStringExtra("owner") // val issueCount: Int? = intent.getStringExtra("open_issues")?.toInt() // val networkCount: Int? = intent.getStringExtra("network")?.toInt() //initialising Texts in the UI binding.tvTitle.text = "$repoName" binding.tvDescription.text = "$description" binding.tvURL.text = url // binding.tvId.text = "Id: $repoId" binding.tvFork.text = "$forkCount" binding.tvWatch.text = "$watchCount" binding.tvStar.text = "$starCount" binding.tvSubs.text = "$subscriberCount" binding.owner.text = "$ownerName" //adding the avatar image using glide Glide.with(this) .load(avatar) .circleCrop() .into(avatarImage) binding.tvURL.setOnClickListener { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) ContextCompat.startActivity(this, intent, null) } //For creating instance of database and setting the add button favouriteAction(repoId, repoName, url, description, starCount, watchCount, forkCount, subscriberCount, avatar, ownerName) setContentView(binding.root) } @SuppressLint("SetTextI18n") private fun favouriteAction( repoId: Int?, repoName: String?, url: String?, description: String?, starCount: Int?, watchCount: Int?, forkCount: Int?, subscriberCount: Int?, avatar: String?, ownerName: String? ) { val favDao = AppDatabase.getInstance(this).productDao() if(favDao.isExist(repoId)!=null){ binding.addRepo.text = "Go To Repo" }else{ binding.addRepo.text = "Add To Repo" } binding.addRepo.setOnClickListener { if (favDao.isExist(repoId) != null) { openRepoList() } else { addToRepoList(favDao, repoId, repoName, description, url, starCount, watchCount, forkCount, subscriberCount, avatar, ownerName) } } } private fun addToRepoList( favDao: FavRepoDao, id: Int?, name: String?, description: String?, html_url: String?, stargazers_count: Int?, watchers_count: Int?, forks_count: Int?, subscribers_count: Int?, avatar_url: String?, owner: String? ) { val data = FavRepoModel(id, name, html_url, description, stargazers_count, watchers_count, forks_count, subscribers_count, avatar_url, owner) lifecycleScope.launch(Dispatchers.IO){ favDao.insertProduct(data) binding.addRepo.text = "Go To Repo" } } private fun openRepoList() { val preference = this.getSharedPreferences("Info", MODE_PRIVATE) val editor = preference.edit() editor.putBoolean("isFav", true) editor.apply() startActivity(Intent(this, MainActivity::class.java)) finish() } }
0
Kotlin
0
1
371e2c174c2befead5959eb62fcfc30c620dff53
5,068
Github-Search-Api
MIT License
app/src/main/java/kr/owens/upa/helper/TickerHelper.kt
owen151128
369,703,277
false
null
package kr.owens.upa.helper import kr.owens.upa.model.Ticker object TickerHelper { private const val KOREA_WON = "KRW" fun filterFiat(tickers: List<Ticker>, fiat: String = KOREA_WON) = tickers.filter { it.market.startsWith(fiat) } fun sort(tickers: List<Ticker>) = tickers.sortedBy { it.koreanName } }
0
Kotlin
0
0
641a5f45e265dfefce5389e55245c8c91e01d341
325
upbit_price_alarm
Apache License 2.0
feature/player/src/main/kotlin/dev/dexsr/klio/player/android/presentation/root/main/PlaybackControlScreen.kt
flammky
462,795,948
false
null
package dev.dexsr.klio.player.android.presentation.root.main import androidx.compose.animation.core.* import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.offset import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.layout.SubcomposeLayout import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.AndroidUiDispatcher import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.util.fastForEach import androidx.compose.ui.util.fastMap import dev.dexsr.klio.base.compose.SimpleStack import dev.dexsr.klio.player.android.presentation.root.upnext.UpNextBottomSheet import kotlinx.coroutines.* import kotlinx.coroutines.flow.distinctUntilChanged @Composable fun TransitioningPlaybackControlScreen( modifier: Modifier, state: PlaybackControlScreenState ) { BoxWithConstraints(modifier) { val transitionState = rememberAnimatedTransitionState( state = state, height = constraints.maxHeight, ) val stagedOffsetPx = transitionState.stagedOffsetPx SimpleStack( modifier = Modifier .offset { IntOffset(x = 0, y = stagedOffsetPx) } .onGloballyPositioned { transitionState.renderedOffsetPx = stagedOffsetPx } ) { if (transitionState.shouldShowScreen()) { PlaybackControlScreen( state = state, transitionState = transitionState ) } } } } @Composable fun PlaybackControlScreen( state: PlaybackControlScreenState, transitionState: PlaybackControlScreenTransitionState ) { SubcomposeLayout { constraints -> val main = subcompose("MAIN") { PlaybackControlMainScreen( state = rememberPlaybackControlMainScreenState( container = state, transitionState = transitionState ) ) }.fastMap { it.measure(constraints) } val upNext = subcompose("UPNEXT") { UpNextBottomSheet( container = state ) }.fastMap { it.measure(constraints) } layout( width = constraints.maxWidth, height = constraints.maxHeight ) { main.fastForEach { it.place(0,0, 0f) } upNext.fastForEach { it.place(0, 0, 0f) } } } } @Composable private fun rememberAnimatedTransitionState( state: PlaybackControlScreenState, height: Int, showAnimationSpec: FiniteAnimationSpec<Int> = tween(350), hideAnimationSpec: FiniteAnimationSpec<Int> = tween(200), savedSnapAnimationSpec: FiniteAnimationSpec<Int> = snap(0) ): PlaybackControlScreenTransitionState { // TODO: savable val rememberState = remember(state) { PlaybackControlScreenTransitionState( screenState = state, ) } val animatable = remember(state) { Animatable( initialValue = height, typeConverter = Int.VectorConverter ) } val heightState = rememberUpdatedState(newValue = height) DisposableEffect( key1 = state, key2 = animatable, effect = { val coroutineScope = CoroutineScope(SupervisorJob()) coroutineScope.launch(Dispatchers.Main) { var task: Job? = null snapshotFlow { state.freeze } .distinctUntilChanged() .collect { freeze -> task?.cancel() if (freeze) return@collect task = launch { var animator: Job? = null snapshotFlow { state.showSelf } .collect { animateToShow -> animator?.cancel() animator = launch { var animateToTarget: Job? = null snapshotFlow { if (animateToShow) 0 else heightState.value } .distinctUntilChanged() .collect { target -> animateToTarget?.cancel() animateToTarget = launch(AndroidUiDispatcher.Main) { animatable.animateTo( target, animationSpec = if (animateToShow) { if (rememberState.consumeShowSnap) { rememberState.consumeShowSnap = false savedSnapAnimationSpec } else { showAnimationSpec } } else { hideAnimationSpec } ) rememberState.consumeShowSnap = animateToShow } } } } } } } onDispose { coroutineScope.cancel() } } ) return rememberState.apply { targetHeightPx = heightState.value stagedOffsetPx = animatable.value } }
0
null
6
56
a452c453815851257462623be704559d306fb383
5,995
Music-Player
Apache License 2.0
mewwalletbl/src/main/java/com/myetherwallet/mewwalletbl/key/util/AES.kt
MyEtherWallet
225,456,139
false
null
package com.myetherwallet.mewwalletbl.key.util import android.security.keystore.KeyProperties import javax.crypto.Cipher import javax.crypto.spec.SecretKeySpec /** * Created by BArtWell on 15.07.2019. */ private const val ALGORITHM = KeyProperties.KEY_ALGORITHM_AES private const val TRANSFORMATION = "${KeyProperties.KEY_ALGORITHM_AES}/${KeyProperties.BLOCK_MODE_ECB}/${KeyProperties.ENCRYPTION_PADDING_PKCS7}" internal object AES { fun encrypt(input: ByteArray, key: ByteArray) = crypt(input, key, Cipher.ENCRYPT_MODE) fun decrypt(input: ByteArray, key: ByteArray) = crypt(input, key, Cipher.DECRYPT_MODE) private fun crypt(input: ByteArray, key: ByteArray, mode: Int): ByteArray { val secretKeySpec = SecretKeySpec(key, ALGORITHM) val cipher = Cipher.getInstance(TRANSFORMATION) cipher.init(mode, secretKeySpec) return cipher.doFinal(input) } }
2
Kotlin
14
8
0c876055cad9373c425230b8444978bee11e2a52
905
mew-wallet-android-biz-logic
MIT License
library/src/main/java/com/trendyol/showcase/ui/showcase/ShowcaseView.kt
MertNYuksel
336,248,559
true
{"Kotlin": 43824}
package com.trendyol.showcase.ui.showcase import android.content.Context import android.graphics.Canvas import android.util.AttributeSet import android.view.LayoutInflater import androidx.annotation.LayoutRes import androidx.constraintlayout.widget.ConstraintLayout import androidx.databinding.DataBindingUtil import com.trendyol.showcase.R import com.trendyol.showcase.databinding.LayoutShowcaseBinding import com.trendyol.showcase.showcase.ShowcaseModel import com.trendyol.showcase.ui.tooltip.TooltipViewState import com.trendyol.showcase.util.OnTouchClickListener import com.trendyol.showcase.util.TooltipFieldUtil import com.trendyol.showcase.util.getShowcaseActivity import com.trendyol.showcase.util.shape.CircleShape import com.trendyol.showcase.util.shape.RectangleShape import com.trendyol.showcase.util.statusBarHeight class ShowcaseView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : ConstraintLayout(context, attrs, defStyleAttr) { private val binding: LayoutShowcaseBinding = DataBindingUtil.inflate( LayoutInflater.from(context), R.layout.layout_showcase, this, true ) var showcaseModel: ShowcaseModel? = null set(value) { field = value bind(value) } override fun dispatchDraw(canvas: Canvas) { if (showcaseModel == null) return super.dispatchDraw(canvas) showcaseModel?.also { model -> val shape = when (model.highlightType) { HighlightType.CIRCLE -> { CircleShape( statusBarDiff = getStatusBarHeight(model.isStatusBarVisible), screenWidth = width, screenHeight = height, x = model.horizontalCenter(), y = model.verticalCenter(), radius = model.radius + model.highlightPadding ) } HighlightType.RECTANGLE -> { RectangleShape( statusBarDiff = getStatusBarHeight(model.isStatusBarVisible), screenWidth = width, screenHeight = height, left = model.rectF.left - (model.highlightPadding / 2), top = model.rectF.top - (model.highlightPadding / 2), right = model.rectF.right + (model.highlightPadding / 2), bottom = model.rectF.bottom + (model.highlightPadding / 2) ) } } shape.draw(model.windowBackgroundColor, model.windowBackgroundAlpha, canvas) } super.dispatchDraw(canvas) } private fun getStatusBarHeight(isStatusBarVisible: Boolean): Int = if (isStatusBarVisible) { statusBarHeight() } else { 0 } private fun listenClickEvents() { OnTouchClickListener().apply { clickListener = { _, x, y -> if (showcaseModel?.cancellableFromOutsideTouch == true) { getShowcaseActivity()?.onBackPress(isHighlightClick(x, y)) } else if (isHighlightClick(x, y)) { getShowcaseActivity()?.onBackPress(true) } } }.also { setOnTouchListener(it) } } private fun isHighlightClick(x: Float, y: Float) = showcaseModel?.let { val newRectF = it.rectF when (it.highlightType) { HighlightType.CIRCLE -> { newRectF.left -= (it.radius + it.highlightPadding) newRectF.right += (it.radius + it.highlightPadding) newRectF.top -= (it.radius + it.highlightPadding - statusBarHeight()) newRectF.bottom += (it.radius + it.highlightPadding - statusBarHeight()) } HighlightType.RECTANGLE -> { newRectF.left -= (it.highlightPadding / 2) newRectF.right += (it.highlightPadding / 2) newRectF.top -= (it.highlightPadding / 2) newRectF.bottom += (it.highlightPadding / 2) } } newRectF.contains(x, y) } ?: false private fun bind(showcaseModel: ShowcaseModel?) { if (showcaseModel == null) return listenClickEvents() val arrowPosition = TooltipFieldUtil.decideArrowPosition( showcaseModel = showcaseModel, screenHeight = resources.displayMetrics.heightPixels ) val arrowMargin = TooltipFieldUtil.calculateArrowMargin( horizontalCenter = showcaseModel.horizontalCenter(), density = resources.displayMetrics.density ) val marginFromBottom = when (showcaseModel.highlightType) { HighlightType.CIRCLE -> TooltipFieldUtil.calculateMarginForCircle( top = showcaseModel.topOfCircle(), bottom = showcaseModel.bottomOfCircle(), arrowPosition = arrowPosition, statusBarHeight = statusBarHeight(), isStatusBarVisible = showcaseModel.isStatusBarVisible, screenHeight = resources.displayMetrics.heightPixels ) HighlightType.RECTANGLE -> TooltipFieldUtil.calculateMarginForRectangle( top = showcaseModel.rectF.top, bottom = showcaseModel.rectF.bottom, arrowPosition = arrowPosition, statusBarHeight = statusBarHeight(), isStatusBarVisible = showcaseModel.isStatusBarVisible, screenHeight = resources.displayMetrics.heightPixels ) } binding.showcaseViewState = ShowcaseViewState(margin = marginFromBottom) binding.tooltipViewState = TooltipViewState( titleText = showcaseModel.titleText, descriptionText = showcaseModel.descriptionText, titleTextColor = showcaseModel.titleTextColor, descriptionTextColor = showcaseModel.descriptionTextColor, backgroundColor = showcaseModel.popupBackgroundColor, closeButtonColor = showcaseModel.closeButtonColor, showCloseButton = showcaseModel.showCloseButton, arrowResource = showcaseModel.arrowResource, arrowPosition = arrowPosition, arrowPercentage = showcaseModel.arrowPercentage, arrowMargin = arrowMargin, titleTextSize = showcaseModel.titleTextSize, descriptionTextSize = showcaseModel.descriptionTextSize, textPosition = showcaseModel.textPosition, imageUrl = showcaseModel.imageUrl, showCustomContent = showcaseModel.customContent != null, isStatusBarVisible = showcaseModel.isStatusBarVisible ) binding.executePendingBindings() if (showcaseModel.customContent != null) { setCustomContent(showcaseModel.customContent) } } private fun setCustomContent(@LayoutRes customContent: Int) { binding.tooltipView.setCustomContent(customContent) } }
0
null
0
0
00643ecc0ce308972a90af92a6bb55c451638b3d
7,143
showcase
Apache License 2.0
modules/core/arrow-instances-core/src/main/kotlin/arrow/instances/id.kt
simonbasle
157,551,397
true
{"Kotlin": 1552802, "CSS": 142107, "JavaScript": 66545, "HTML": 11364, "Java": 4465, "Shell": 3043}
package arrow.instances import arrow.Kind import arrow.core.* import arrow.instance import arrow.typeclasses.* import arrow.instances.traverse as idTraverse @instance(Id::class) interface IdEqInstance<A> : Eq<Id<A>> { fun EQ(): Eq<A> override fun Id<A>.eqv(b: Id<A>): Boolean = EQ().run { value.eqv(b.value) } } @instance(Id::class) interface IdShowInstance<A> : Show<Id<A>> { override fun Id<A>.show(): String = toString() } @instance(Id::class) interface IdFunctorInstance : Functor<ForId> { override fun <A, B> Kind<ForId, A>.map(f: (A) -> B): Id<B> = fix().map(f) } @instance(Id::class) interface IdApplicativeInstance : Applicative<ForId> { override fun <A, B> Kind<ForId, A>.ap(ff: Kind<ForId, (A) -> B>): Id<B> = fix().ap(ff) override fun <A, B> Kind<ForId, A>.map(f: (A) -> B): Id<B> = fix().map(f) override fun <A> just(a: A): Id<A> = Id.just(a) } @instance(Id::class) interface IdMonadInstance : Monad<ForId> { override fun <A, B> Kind<ForId, A>.ap(ff: Kind<ForId, (A) -> B>): Id<B> = fix().ap(ff) override fun <A, B> Kind<ForId, A>.flatMap(f: (A) -> Kind<ForId, B>): Id<B> = fix().flatMap(f) override fun <A, B> tailRecM(a: A, f: kotlin.Function1<A, IdOf<Either<A, B>>>): Id<B> = Id.tailRecM(a, f) override fun <A, B> Kind<ForId, A>.map(f: (A) -> B): Id<B> = fix().map(f) override fun <A> just(a: A): Id<A> = Id.just(a) } @instance(Id::class) interface IdComonadInstance : Comonad<ForId> { override fun <A, B> Kind<ForId, A>.coflatMap(f: (Kind<ForId, A>) -> B): Id<B> = fix().coflatMap(f) override fun <A> Kind<ForId, A>.extract(): A = fix().extract() override fun <A, B> Kind<ForId, A>.map(f: (A) -> B): Id<B> = fix().map(f) } @instance(Id::class) interface IdBimonadInstance : Bimonad<ForId> { override fun <A, B> Kind<ForId, A>.ap(ff: Kind<ForId, (A) -> B>): Id<B> = fix().ap(ff) override fun <A, B> Kind<ForId, A>.flatMap(f: (A) -> Kind<ForId, B>): Id<B> = fix().flatMap(f) override fun <A, B> tailRecM(a: A, f: kotlin.Function1<A, IdOf<Either<A, B>>>): Id<B> = Id.tailRecM(a, f) override fun <A, B> Kind<ForId, A>.map(f: (A) -> B): Id<B> = fix().map(f) override fun <A> just(a: A): Id<A> = Id.just(a) override fun <A, B> Kind<ForId, A>.coflatMap(f: (Kind<ForId, A>) -> B): Id<B> = fix().coflatMap(f) override fun <A> Kind<ForId, A>.extract(): A = fix().extract() } @instance(Id::class) interface IdFoldableInstance : Foldable<ForId> { override fun <A, B> Kind<ForId, A>.foldLeft(b: B, f: (B, A) -> B): B = fix().foldLeft(b, f) override fun <A, B> Kind<ForId, A>.foldRight(lb: Eval<B>, f: (A, Eval<B>) -> Eval<B>): Eval<B> = fix().foldRight(lb, f) } fun <A, G, B> IdOf<A>.traverse(GA: Applicative<G>, f: (A) -> Kind<G, B>): Kind<G, Id<B>> = GA.run { f(value()).map { Id(it) } } fun <A, G> IdOf<Kind<G, A>>.sequence(GA: Applicative<G>): Kind<G, Id<A>> = idTraverse(GA, ::identity) @instance(Id::class) interface IdTraverseInstance : Traverse<ForId> { override fun <A, B> Kind<ForId, A>.map(f: (A) -> B): Id<B> = fix().map(f) override fun <G, A, B> Kind<ForId, A>.traverse(AP: Applicative<G>, f: (A) -> Kind<G, B>): Kind<G, Id<B>> = idTraverse(AP, f) override fun <A, B> Kind<ForId, A>.foldLeft(b: B, f: (B, A) -> B): B = fix().foldLeft(b, f) override fun <A, B> arrow.Kind<arrow.core.ForId, A>.foldRight(lb: arrow.core.Eval<B>, f: (A, arrow.core.Eval<B>) -> arrow.core.Eval<B>): Eval<B> = fix().foldRight(lb, f) }
1
Kotlin
1
0
30e4454a825383dae15677b29d838944030589e5
3,528
kategory
Apache License 2.0
lib/src/integrationTest/kotlin/com/lemonappdev/konsist/core/declaration/kofunction/forkomodifier/KoFunctionDeclarationForKoModifierProviderTest.kt
LemonAppDev
621,181,534
false
null
package com.lemonappdev.konsist.core.declaration.kofunction.forkomodifier import com.lemonappdev.konsist.TestSnippetProvider.getSnippetKoScope import com.lemonappdev.konsist.api.KoModifier import com.lemonappdev.konsist.api.KoModifier.DATA import com.lemonappdev.konsist.api.KoModifier.OPEN import com.lemonappdev.konsist.api.KoModifier.PROTECTED import com.lemonappdev.konsist.api.KoModifier.PUBLIC import com.lemonappdev.konsist.api.KoModifier.SUSPEND import org.amshove.kluent.assertSoftly import org.amshove.kluent.shouldBeEqualTo import org.junit.jupiter.api.Test import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments.arguments import org.junit.jupiter.params.provider.MethodSource class KoFunctionDeclarationForKoModifierProviderTest { @Test fun `function-has-no-modifiers`() { // given val sut = getSnippetFile("function-has-no-modifiers") .functions() .first() // then assertSoftly(sut) { modifiers shouldBeEqualTo emptyList() numModifiers shouldBeEqualTo 0 hasModifiers() shouldBeEqualTo false hasModifier(OPEN) shouldBeEqualTo false hasModifier(OPEN, DATA) shouldBeEqualTo false hasAllModifiers(OPEN) shouldBeEqualTo false hasAllModifiers(OPEN, DATA) shouldBeEqualTo false hasModifiers(OPEN) shouldBeEqualTo false hasModifiers(OPEN, DATA) shouldBeEqualTo false } } @Test fun `function-has-protected-and-suspend-modifiers`() { // given val sut = getSnippetFile("function-has-protected-and-suspend-modifiers") .functions(includeNested = true) .first() // then assertSoftly(sut) { numModifiers shouldBeEqualTo 2 hasModifiers() shouldBeEqualTo true hasModifier(PROTECTED) shouldBeEqualTo true hasModifier(PUBLIC) shouldBeEqualTo false hasModifier(PROTECTED, SUSPEND) shouldBeEqualTo true hasAllModifiers(PROTECTED) shouldBeEqualTo true hasAllModifiers(PUBLIC) shouldBeEqualTo false hasAllModifiers(PROTECTED, OPEN) shouldBeEqualTo false hasAllModifiers(PROTECTED, SUSPEND) shouldBeEqualTo true hasModifiers(PROTECTED) shouldBeEqualTo true hasModifiers(SUSPEND) shouldBeEqualTo true hasModifiers(OPEN) shouldBeEqualTo false hasModifiers(PROTECTED, SUSPEND) shouldBeEqualTo true hasModifiers(SUSPEND, PROTECTED) shouldBeEqualTo true hasModifiers(PROTECTED, OPEN) shouldBeEqualTo false hasModifiers(OPEN, SUSPEND, PROTECTED) shouldBeEqualTo false } } @ParameterizedTest @MethodSource("provideValues") fun `function-modifiers`( fileName: String, modifiers: List<KoModifier>, ) { // given val sut = getSnippetFile(fileName) .functions(includeNested = true) .first() // then sut.modifiers shouldBeEqualTo modifiers } private fun getSnippetFile(fileName: String) = getSnippetKoScope("core/declaration/kofunction/forkomodifier/snippet/forkomodifierprovider/", fileName) companion object { @Suppress("unused") @JvmStatic fun provideValues() = listOf( arguments("function-has-modifiers", listOf(PROTECTED, OPEN, SUSPEND, KoModifier.INLINE, KoModifier.OPERATOR)), arguments("function-has-modifiers-and-annotation-with-parameter", listOf(PROTECTED, OPEN)), arguments("function-has-modifiers-and-annotation-without-parameter", listOf(PROTECTED, OPEN)), arguments("function-has-modifiers-annotation-and-comment", listOf(PROTECTED, OPEN)), arguments("function-has-modifiers-and-annotations", listOf(PROTECTED, OPEN)), arguments("function-has-modifiers-and-annotation-with-angle-brackets", listOf(PROTECTED, OPEN)), arguments("function-has-modifiers-and-kdoc", listOf(PROTECTED, OPEN)), arguments("function-has-modifiers-kdoc-and-annotation-before-them", listOf(PROTECTED, OPEN)), arguments("function-has-modifiers-multiline-comment-and-annotation-before-them", listOf(PROTECTED, OPEN)), arguments("function-has-modifiers-and-comment-before-them", listOf(PROTECTED, OPEN)), arguments("function-has-modifiers-and-comment-after-them", listOf(PROTECTED, OPEN)), ) } }
7
null
22
840
81324e09fe46c9f1095b133713ae0062e742c2e3
4,659
konsist
Apache License 2.0
modulo5/src/aula23/exercicio07/Main.kt
ProgramaCatalisa
491,134,850
false
{"Kotlin": 80614}
package aula23.exercicio07 import aula23.exercicio07.menu.Menu fun main() { Menu.menu() }
0
Kotlin
0
0
e0b994cd6b173da0f791fd3cb2eca96316cb6a6d
95
ResolucaoExerciciosKotlin
Apache License 2.0
VivaCoronia/app/src/main/java/de/tudarmstadt/iptk/foxtrot/vivacoronia/trading/models/ProductSearchQuery.kt
ckuessner
313,282,198
false
null
package de.tudarmstadt.iptk.foxtrot.vivacoronia.trading.models import android.net.Uri import android.os.Parcel import android.os.Parcelable import com.google.android.gms.maps.model.LatLng class ProductSearchQuery ( var productName: String, var category: String, var amountMin: String, var location: LatLng?, var radiusInKm: Int ) : Parcelable { constructor(parcel: Parcel) : this( parcel.readString()!!, parcel.readString()!!, parcel.readString()!!, parcel.readParcelable(LatLng::class.java.classLoader), parcel.readInt() ) enum class SortOptions (val attribute: String) { NAME("name"), DISTANCE("distance"), PRICE("price") } constructor() : this( "", "", "", null, 0) var userId: String = "" var priceMin: String = "" var priceMax: String = "" var sortBy: SortOptions = SortOptions.NAME override fun toString(): String { val builder = Uri.Builder() if (userId.isNotEmpty()) builder.appendQueryParameter("userId", userId) if (productName.isNotEmpty()) builder.appendQueryParameter("product", productName) if (category.isNotEmpty()) builder.appendQueryParameter("productCategory", category) if (priceMin.isNotEmpty()) builder.appendQueryParameter("priceMin", priceMin.replace(",", ".")) if (priceMax.isNotEmpty()) builder.appendQueryParameter("priceMax", priceMax.replace(",", ".")) if (amountMin.isNotEmpty()) builder.appendQueryParameter("amountMin", amountMin) if (location != null) { builder.appendQueryParameter("longitude", location!!.longitude.toString()) builder.appendQueryParameter("latitude", location!!.latitude.toString()) } if (radiusInKm != 0) builder.appendQueryParameter("radiusInKm", radiusInKm.toString()) builder.appendQueryParameter("sortBy", sortBy.attribute) return builder.toString().replaceFirst("?", "") } override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeString(productName) dest.writeString(category) dest.writeString(amountMin) dest.writeParcelable(location, flags) dest.writeInt(radiusInKm) dest.writeString(priceMin) dest.writeString(priceMax) dest.writeString(sortBy.attribute) dest.writeString(userId) } companion object CREATOR : Parcelable.Creator<ProductSearchQuery> { override fun createFromParcel(parcel: Parcel): ProductSearchQuery { return ProductSearchQuery(parcel) } override fun newArray(size: Int): Array<ProductSearchQuery?> { return arrayOfNulls(size) } } }
0
Kotlin
0
0
779a0382c2a3f06ed57f23b25777985bf80db5b8
2,985
vivacoronia-frontend
Apache License 2.0
app/src/main/java/dev/spikeysanju/expensetracker/view/details/TransactionDetailsFragment.kt
Spikeysanju
330,410,387
false
null
package dev.spikeysanju.expensetracker.view.details import android.Manifest import android.annotation.SuppressLint import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.activity.result.contract.ActivityResultContracts import androidx.core.app.ShareCompat import androidx.core.content.ContextCompat import androidx.core.view.drawToBitmap import androidx.fragment.app.activityViewModels import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import cleanTextContent import dagger.hilt.android.AndroidEntryPoint import dev.spikeysanju.expensetracker.R import dev.spikeysanju.expensetracker.databinding.FragmentTransactionDetailsBinding import dev.spikeysanju.expensetracker.model.Transaction import dev.spikeysanju.expensetracker.utils.saveBitmap import dev.spikeysanju.expensetracker.utils.viewState.DetailState import dev.spikeysanju.expensetracker.view.base.BaseFragment import dev.spikeysanju.expensetracker.view.main.viewmodel.TransactionViewModel import hide import indianRupee import kotlinx.coroutines.flow.collect import show import snack @AndroidEntryPoint class TransactionDetailsFragment : BaseFragment<FragmentTransactionDetailsBinding, TransactionViewModel>() { private val args: TransactionDetailsFragmentArgs by navArgs() override val viewModel: TransactionViewModel by activityViewModels() // handle permission dialog private val requestLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted -> if (isGranted) shareImage() else showErrorDialog() } private fun showErrorDialog() = findNavController().navigate( TransactionDetailsFragmentDirections.actionTransactionDetailsFragmentToErrorDialog( "Compartilhamento de imagem falhou!", "Você precisa ativar a permissão de armazenamento para compartilhar a transação como imagem" ) ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val transaction = args.transaction getTransaction(transaction.id) observeTransaction() } private fun getTransaction(id: Int) { viewModel.getByID(id) } private fun observeTransaction() = lifecycleScope.launchWhenCreated { viewModel.detailState.collect { detailState -> when (detailState) { DetailState.Loading -> { } is DetailState.Success -> { onDetailsLoaded(detailState.transaction) } is DetailState.Error -> { binding.root.snack( string = R.string.text_error ) } DetailState.Empty -> { findNavController().navigateUp() } } } } private fun onDetailsLoaded(transaction: Transaction) = with(binding.transactionDetails) { title.text = transaction.title amount.text = indianRupee(transaction.amount).cleanTextContent type.text = transaction.transactionType tag.text = transaction.tag date.text = transaction.date note.text = transaction.note createdAt.text = transaction.createdAtDateFormat binding.editTransaction.setOnClickListener { val bundle = Bundle().apply { putSerializable("transaction", transaction) } findNavController().navigate( R.id.action_transactionDetailsFragment_to_editTransactionFragment, bundle ) } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_share, menu) super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_delete -> { viewModel.deleteByID(args.transaction.id) .run { findNavController().navigateUp() } } R.id.action_share_text -> shareText() R.id.action_share_image -> shareImage() } return super.onOptionsItemSelected(item) } private fun shareImage() { if (!isStoragePermissionGranted()) { requestLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE) return } // unHide the app logo and name showAppNameAndLogo() val imageURI = binding.transactionDetails.detailView.drawToBitmap().let { bitmap -> hideAppNameAndLogo() saveBitmap(requireActivity(), bitmap) } ?: run { binding.root.snack( string = R.string.text_error_occurred ) return } val intent = ShareCompat.IntentBuilder(requireActivity()) .setType("image/jpeg") .setStream(imageURI) .intent startActivity(Intent.createChooser(intent, null)) } private fun showAppNameAndLogo() = with(binding.transactionDetails) { appIconForShare.show() appNameForShare.show() } private fun hideAppNameAndLogo() = with(binding.transactionDetails) { appIconForShare.hide() appNameForShare.hide() } private fun isStoragePermissionGranted(): Boolean = ContextCompat.checkSelfPermission( requireContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED @SuppressLint("StringFormatMatches") private fun shareText() = with(binding) { val shareMsg = getString( R.string.share_message, transactionDetails.title.text.toString(), transactionDetails.amount.text.toString(), transactionDetails.type.text.toString(), transactionDetails.tag.text.toString(), transactionDetails.date.text.toString(), transactionDetails.note.text.toString(), transactionDetails.createdAt.text.toString() ) val intent = ShareCompat.IntentBuilder(requireActivity()) .setType("text/plain") .setText(shareMsg) .intent startActivity(Intent.createChooser(intent, null)) } override fun getViewBinding( inflater: LayoutInflater, container: ViewGroup? ) = FragmentTransactionDetailsBinding.inflate(inflater, container, false) }
23
null
151
883
dd807562eeb0c3fe6c14bc0882b2c442a6bd7388
7,015
Expenso
Apache License 2.0
idea/tests/testData/indentationOnNewline/controlFlowConstructions/DoWhile.kt
JetBrains
278,369,660
false
null
fun some() { do println() while (true) <caret> }
0
Kotlin
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
57
intellij-kotlin
Apache License 2.0
app/src/main/java/com/lkw1120/pokedex/usecase/model/PokeItem.kt
lkw1120
727,588,825
false
{"Kotlin": 84577}
package com.lkw1120.pokedex.usecase.model data class PokeItem( val id: Long, val name: String, val url: String, )
0
Kotlin
0
1
6df9cbe60762b1799746304a68f3f29e6422b9df
127
compose-pokedex
Apache License 2.0
src/main/kotlin/zanagram/List.kt
HenriqueRocha
259,845,874
false
null
package zanagram /** * A generic ordered collection of elements that supports adding and removing elements. */ interface List<E> { /** * Adds the specified element to the end of this list. * @param e element to be appended to this list */ fun add(e: E) /** * Returns the size of this list. */ fun size(): Int fun contains(e: E): Boolean /** * Returns the element at the specified index in the list. */ operator fun get(index: Int): E /** * Replaces the element at the specified position in this list with the specified element. */ operator fun set(index: Int, element: E) }
1
Kotlin
0
0
fbc4f2fc5489306dbc0eddfcd2a527745e297b78
663
zanagram
MIT License
snippets/kotlin/src/main/kotlin/com/algolia/snippets/Monitoring.kt
algolia
419,291,903
false
{"PHP": 5345450, "Go": 5338681, "Ruby": 4383162, "C#": 4219770, "Java": 3631981, "Python": 2757318, "Swift": 2573290, "Scala": 1614948, "Kotlin": 1593815, "Dart": 1572885, "TypeScript": 1481708, "Mustache": 609735, "MDX": 125223, "JavaScript": 82988, "CSS": 39035, "Shell": 7972, "HTML": 605}
package com.algolia.snippets import com.algolia.client.api.MonitoringClient import com.algolia.client.model.monitoring.* import kotlinx.serialization.json.* import kotlin.system.exitProcess class SnippetMonitoringClient { suspend fun snippetForCustomDelete() { // >SEPARATOR customDelete // Initialize the client val client = MonitoringClient(appId = "YOUR_APP_ID", apiKey = "YOUR_API_KEY") // Call the API var response = client.customDelete( path = "/test/minimal", ) // Use the response println(response) // SEPARATOR< exitProcess(0) } suspend fun snippetForCustomGet() { // >SEPARATOR customGet // Initialize the client val client = MonitoringClient(appId = "YOUR_APP_ID", apiKey = "YOUR_API_KEY") // Call the API var response = client.customGet( path = "/test/minimal", ) // Use the response println(response) // SEPARATOR< exitProcess(0) } suspend fun snippetForCustomPost() { // >SEPARATOR customPost // Initialize the client val client = MonitoringClient(appId = "YOUR_APP_ID", apiKey = "YOUR_API_KEY") // Call the API var response = client.customPost( path = "/test/minimal", ) // Use the response println(response) // SEPARATOR< exitProcess(0) } suspend fun snippetForCustomPut() { // >SEPARATOR customPut // Initialize the client val client = MonitoringClient(appId = "YOUR_APP_ID", apiKey = "YOUR_API_KEY") // Call the API var response = client.customPut( path = "/test/minimal", ) // Use the response println(response) // SEPARATOR< exitProcess(0) } suspend fun snippetForGetClusterIncidents() { // >SEPARATOR getClusterIncidents // Initialize the client val client = MonitoringClient(appId = "YOUR_APP_ID", apiKey = "YOUR_API_KEY") // Call the API var response = client.getClusterIncidents( clusters = "c1-de", ) // Use the response println(response) // SEPARATOR< exitProcess(0) } suspend fun snippetForGetClusterStatus() { // >SEPARATOR getClusterStatus // Initialize the client val client = MonitoringClient(appId = "YOUR_APP_ID", apiKey = "YOUR_API_KEY") // Call the API var response = client.getClusterStatus( clusters = "c1-de", ) // Use the response println(response) // SEPARATOR< exitProcess(0) } suspend fun snippetForGetIncidents() { // >SEPARATOR getIncidents // Initialize the client val client = MonitoringClient(appId = "YOUR_APP_ID", apiKey = "YOUR_API_KEY") // Call the API var response = client.getIncidents() // Use the response println(response) // SEPARATOR< exitProcess(0) } suspend fun snippetForGetIndexingTime() { // >SEPARATOR getIndexingTime // Initialize the client val client = MonitoringClient(appId = "YOUR_APP_ID", apiKey = "YOUR_API_KEY") // Call the API var response = client.getIndexingTime( clusters = "c1-de", ) // Use the response println(response) // SEPARATOR< exitProcess(0) } suspend fun snippetForGetInventory() { // >SEPARATOR getInventory // Initialize the client val client = MonitoringClient(appId = "YOUR_APP_ID", apiKey = "YOUR_API_KEY") // Call the API var response = client.getInventory() // Use the response println(response) // SEPARATOR< exitProcess(0) } suspend fun snippetForGetLatency() { // >SEPARATOR getLatency // Initialize the client val client = MonitoringClient(appId = "YOUR_APP_ID", apiKey = "YOUR_API_KEY") // Call the API var response = client.getLatency( clusters = "c1-de", ) // Use the response println(response) // SEPARATOR< exitProcess(0) } suspend fun snippetForGetMetrics() { // >SEPARATOR getMetrics // Initialize the client val client = MonitoringClient(appId = "YOUR_APP_ID", apiKey = "YOUR_API_KEY") // Call the API var response = client.getMetrics( metric = Metric.entries.first { it.value == "avg_build_time" }, period = Period.entries.first { it.value == "minute" }, ) // Use the response println(response) // SEPARATOR< exitProcess(0) } suspend fun snippetForGetReachability() { // >SEPARATOR getReachability // Initialize the client val client = MonitoringClient(appId = "YOUR_APP_ID", apiKey = "YOUR_API_KEY") // Call the API var response = client.getReachability( clusters = "c1-de", ) // Use the response println(response) // SEPARATOR< exitProcess(0) } suspend fun snippetForGetStatus() { // >SEPARATOR getStatus // Initialize the client val client = MonitoringClient(appId = "YOUR_APP_ID", apiKey = "YOUR_API_KEY") // Call the API var response = client.getStatus() // Use the response println(response) // SEPARATOR< exitProcess(0) } }
22
PHP
9
30
cefee57147db685610eec93d1fec57895e6ee43d
5,018
api-clients-automation
MIT License
testapp/src/main/java/com/github/marcherdiego/mvp/testapp/ui/mvp/presenter/AttributeForFragmentMainPresenter.kt
marcherdiego
124,760,586
false
null
package com.github.marcherdiego.mvp.testapp.ui.mvp.presenter import com.github.marcherdiego.mvp.events.bus.Bus import com.github.marcherdiego.mvp.events.presenter.BaseActivityPresenter import com.github.marcherdiego.mvp.testapp.ui.fragments.Fragment1 import com.github.marcherdiego.mvp.testapp.ui.fragments.Fragment2 import com.github.marcherdiego.mvp.testapp.ui.mvp.model.AttributeFragmentMainModel import com.github.marcherdiego.mvp.testapp.ui.mvp.view.AttributeFragmentMainView import com.github.marcherdiego.mvp.testapp.ui.mvp.view.AttributeFragmentMainView.NextFragmentClickedEvent import org.greenrobot.eventbus.Subscribe class AttributeForFragmentMainPresenter( view: AttributeFragmentMainView, model: AttributeFragmentMainModel, bus: Bus ) : BaseActivityPresenter<AttributeFragmentMainView, AttributeFragmentMainModel>(view, model, bus) { init { //Just so we can show the fragment 1 when the view is created onNextFragmentClicked(null) } @Subscribe fun onNextFragmentClicked(event: NextFragmentClickedEvent?) { val fragment = when (val nextFragment = model.nextState) { AttributeFragmentMainModel.STATE_1 -> Fragment1() AttributeFragmentMainModel.STATE_2 -> Fragment2() else -> throw IllegalArgumentException("Invalid fragment code: $nextFragment") } view.setCurrentFragment(fragment) } }
1
Kotlin
7
18
9f6d2827117babfc494a0ee4381620ccbf44f633
1,415
android_mvp
Apache License 2.0
PeakTest/app/src/main/java/com/che/peaktask/ui/fragments/HomeFragment.kt
evgen-chernets
409,651,210
false
{"Kotlin": 13583}
package com.che.peaktask.ui.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import com.che.peaktask.R import com.che.peaktask.databinding.FragmentHomeBinding import com.che.peaktask.ui.MainViewModel import com.che.peaktask.ui.custom.PeakShapesCanvas class HomeFragment : Fragment() { private val mainViewModel: MainViewModel by activityViewModels() private var _binding: FragmentHomeBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentHomeBinding.inflate(inflater, container, false) val root: View = binding.root binding.shapesCanvas.post { initController() } val shapesCanvas: PeakShapesCanvas = binding.shapesCanvas mainViewModel.shapesData.observe(viewLifecycleOwner, { shapesCanvas.drawShapes(it, listener, longListener) }) binding.viewModel = mainViewModel binding.lifecycleOwner = this return root } private fun initController() { val imageWidth = context?.getDrawable(R.drawable.ic_square)?.minimumWidth ?: 20 val imageHeight = context?.getDrawable(R.drawable.ic_square)?.minimumHeight ?: 20 val x = binding.shapesCanvas.width - imageWidth val y = binding.shapesCanvas.height - imageHeight mainViewModel.initController(x, y) } private val listener = View.OnClickListener { mainViewModel.onShapeClicked(it.z.toInt()) } private val longListener = View.OnLongClickListener { mainViewModel.onShapeLongClicked(it.z.toInt()) true } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
0
b17d440ba1182fd967b9e9c32765f0362eaff0c2
2,044
PopReachTest
Apache License 2.0
features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/pin/DefaultPinCodeManager.kt
element-hq
546,522,002
false
null
/* * Copyright (c) 2023 New Vector Ltd * * 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.element.android.features.lockscreen.impl.pin import com.squareup.anvil.annotations.ContributesBinding import io.element.android.features.lockscreen.impl.storage.LockScreenStore import io.element.android.libraries.cryptography.api.EncryptionDecryptionService import io.element.android.libraries.cryptography.api.EncryptionResult import io.element.android.libraries.cryptography.api.SecretKeyRepository import io.element.android.libraries.di.AppScope import io.element.android.libraries.di.SingleIn import kotlinx.coroutines.flow.Flow import java.util.concurrent.CopyOnWriteArrayList import javax.inject.Inject private const val SECRET_KEY_ALIAS = "elementx.SECRET_KEY_ALIAS_PIN_CODE" @ContributesBinding(AppScope::class) @SingleIn(AppScope::class) class DefaultPinCodeManager @Inject constructor( private val secretKeyRepository: SecretKeyRepository, private val encryptionDecryptionService: EncryptionDecryptionService, private val lockScreenStore: LockScreenStore, ) : PinCodeManager { private val callbacks = CopyOnWriteArrayList<PinCodeManager.Callback>() override fun addCallback(callback: PinCodeManager.Callback) { callbacks.add(callback) } override fun removeCallback(callback: PinCodeManager.Callback) { callbacks.remove(callback) } override fun hasPinCode(): Flow<Boolean> { return lockScreenStore.hasPinCode() } override suspend fun getPinCodeSize(): Int { val encryptedPinCode = lockScreenStore.getEncryptedCode() ?: return 0 val secretKey = secretKeyRepository.getOrCreateKey(SECRET_KEY_ALIAS, false) val decryptedPinCode = encryptionDecryptionService.decrypt(secretKey, EncryptionResult.fromBase64(encryptedPinCode)) return decryptedPinCode.size } override suspend fun createPinCode(pinCode: String) { val secretKey = secretKeyRepository.getOrCreateKey(SECRET_KEY_ALIAS, false) val encryptedPinCode = encryptionDecryptionService.encrypt(secretKey, pinCode.toByteArray()).toBase64() lockScreenStore.saveEncryptedPinCode(encryptedPinCode) callbacks.forEach { it.onPinCodeCreated() } } override suspend fun verifyPinCode(pinCode: String): Boolean { val encryptedPinCode = lockScreenStore.getEncryptedCode() ?: return false return try { val secretKey = secretKeyRepository.getOrCreateKey(SECRET_KEY_ALIAS, false) val decryptedPinCode = encryptionDecryptionService.decrypt(secretKey, EncryptionResult.fromBase64(encryptedPinCode)) val pinCodeToCheck = pinCode.toByteArray() decryptedPinCode.contentEquals(pinCodeToCheck).also { isPinCodeCorrect -> if (isPinCodeCorrect) { lockScreenStore.resetCounter() callbacks.forEach { callback -> callback.onPinCodeVerified() } } else { lockScreenStore.onWrongPin() } } } catch (failure: Throwable) { false } } override suspend fun deletePinCode() { lockScreenStore.deleteEncryptedPinCode() lockScreenStore.resetCounter() callbacks.forEach { it.onPinCodeRemoved() } } override suspend fun getRemainingPinCodeAttemptsNumber(): Int { return lockScreenStore.getRemainingPinCodeAttemptsNumber() } }
263
null
65
955
31d0621fa15fe153bfd36104e560c9703eabe917
4,022
element-x-android
Apache License 2.0
core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/specialBuiltinMembers.kt
msdgwzhy6
421,687,586
false
null
/* * Copyright 2010-2015 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. */ @file:JvmName("SpecialBuiltinMembers") package org.jetbrains.kotlin.load.java import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.load.java.descriptors.JavaCallableMemberDescriptor import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe import org.jetbrains.kotlin.resolve.descriptorUtil.module import org.jetbrains.kotlin.utils.DFS import org.jetbrains.kotlin.utils.addToStdlib.check import org.jetbrains.kotlin.load.java.BuiltinSpecialProperties.getBuiltinSpecialPropertyGetterName import org.jetbrains.kotlin.load.java.BuiltinMethodsWithSpecialGenericSignature.sameAsBuiltinMethodWithErasedValueParameters import org.jetbrains.kotlin.load.java.BuiltinMethodsWithSpecialGenericSignature.getSpecialSignatureInfo import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe object BuiltinSpecialProperties { private val PROPERTY_FQ_NAME_TO_JVM_GETTER_NAME_MAP = mapOf( FqName("kotlin.Enum.name") to Name.identifier("name"), FqName("kotlin.Enum.ordinal") to Name.identifier("ordinal"), FqName("kotlin.Collection.size") to Name.identifier("size"), FqName("kotlin.Map.size") to Name.identifier("size"), FqName("kotlin.CharSequence.length") to Name.identifier("length"), FqName("kotlin.Map.keys") to Name.identifier("keySet"), FqName("kotlin.Map.values") to Name.identifier("values"), FqName("kotlin.Map.entries") to Name.identifier("entrySet") ) private val GETTER_JVM_NAME_TO_PROPERTIES_SHORT_NAME_MAP: Map<Name, List<Name>> = PROPERTY_FQ_NAME_TO_JVM_GETTER_NAME_MAP.getInversedShortNamesMap() private val FQ_NAMES = PROPERTY_FQ_NAME_TO_JVM_GETTER_NAME_MAP.keySet() internal val SHORT_NAMES = FQ_NAMES.map { it.shortName() }.toSet() fun hasBuiltinSpecialPropertyFqName(callableMemberDescriptor: CallableMemberDescriptor): Boolean { if (callableMemberDescriptor.name !in SHORT_NAMES) return false return callableMemberDescriptor.hasBuiltinSpecialPropertyFqNameImpl() } fun CallableMemberDescriptor.hasBuiltinSpecialPropertyFqNameImpl(): Boolean { if (fqNameOrNull() in FQ_NAMES) return true if (!isFromBuiltins()) return false return overriddenDescriptors.any { hasBuiltinSpecialPropertyFqName(it) } } fun getPropertyNameCandidatesBySpecialGetterName(name1: Name): List<Name> = GETTER_JVM_NAME_TO_PROPERTIES_SHORT_NAME_MAP[name1] ?: emptyList() fun CallableMemberDescriptor.getBuiltinSpecialPropertyGetterName(): String? { assert(isFromBuiltins()) { "This method is defined only for builtin members, but $this found" } val descriptor = propertyIfAccessor.firstOverridden { hasBuiltinSpecialPropertyFqName(it) } ?: return null return PROPERTY_FQ_NAME_TO_JVM_GETTER_NAME_MAP[descriptor.fqNameSafe]?.asString() } } object BuiltinMethodsWithSpecialGenericSignature { private val ERASED_COLLECTION_PARAMETER_FQ_NAMES = setOf( FqName("kotlin.Collection.containsAll"), FqName("kotlin.MutableCollection.removeAll"), FqName("kotlin.MutableCollection.retainAll") ) private val GENERIC_PARAMETERS_FQ_NAMES = setOf( FqName("kotlin.Collection.contains"), FqName("kotlin.MutableCollection.remove"), FqName("kotlin.Map.containsKey"), FqName("kotlin.Map.containsValue"), FqName("kotlin.Map.get"), FqName("kotlin.MutableMap.remove"), FqName("kotlin.List.indexOf"), FqName("kotlin.List.lastIndexOf") ) private val ERASED_VALUE_PARAMETERS_FQ_NAMES = GENERIC_PARAMETERS_FQ_NAMES + ERASED_COLLECTION_PARAMETER_FQ_NAMES private val ERASED_VALUE_PARAMETERS_SHORT_NAMES = ERASED_VALUE_PARAMETERS_FQ_NAMES.map { it.shortName() }.toSet() private val CallableMemberDescriptor.hasErasedValueParametersInJava: Boolean get() = fqNameOrNull() in ERASED_VALUE_PARAMETERS_FQ_NAMES @JvmStatic fun getOverriddenBuiltinFunctionWithErasedValueParametersInJava( functionDescriptor: FunctionDescriptor ): FunctionDescriptor? { if (!functionDescriptor.name.sameAsBuiltinMethodWithErasedValueParameters) return null return functionDescriptor.firstOverridden { it.hasErasedValueParametersInJava } as FunctionDescriptor? } val Name.sameAsBuiltinMethodWithErasedValueParameters: Boolean get () = this in ERASED_VALUE_PARAMETERS_SHORT_NAMES enum class SpecialSignatureInfo(val signature: String?) { ONE_COLLECTION_PARAMETER("(Ljava/util/Collection<+Ljava/lang/Object;>;)Z"), GENERIC_PARAMETER(null) } fun CallableMemberDescriptor.isBuiltinWithSpecialDescriptorInJvm(): Boolean { if (!isFromBuiltins()) return false return getSpecialSignatureInfo() == SpecialSignatureInfo.GENERIC_PARAMETER || doesOverrideBuiltinWithDifferentJvmName() } @JvmStatic fun CallableMemberDescriptor.getSpecialSignatureInfo(): SpecialSignatureInfo? { val builtinFqName = firstOverridden { it is FunctionDescriptor && it.hasErasedValueParametersInJava }?.fqNameOrNull() ?: return null return when (builtinFqName) { in ERASED_COLLECTION_PARAMETER_FQ_NAMES -> SpecialSignatureInfo.ONE_COLLECTION_PARAMETER in GENERIC_PARAMETERS_FQ_NAMES -> SpecialSignatureInfo.GENERIC_PARAMETER else -> error("Unexpected kind of special builtin: $builtinFqName") } } } object BuiltinMethodsWithDifferentJvmName { val REMOVE_AT_FQ_NAME = FqName("kotlin.MutableList.removeAt") val FQ_NAMES_TO_JVM_MAP: Map<FqName, Name> = mapOf( FqName("kotlin.Number.toByte") to Name.identifier("byteValue"), FqName("kotlin.Number.toShort") to Name.identifier("shortValue"), FqName("kotlin.Number.toInt") to Name.identifier("intValue"), FqName("kotlin.Number.toLong") to Name.identifier("longValue"), FqName("kotlin.Number.toFloat") to Name.identifier("floatValue"), FqName("kotlin.Number.toDouble") to Name.identifier("doubleValue"), REMOVE_AT_FQ_NAME to Name.identifier("remove"), FqName("kotlin.CharSequence.get") to Name.identifier("charAt") ) val ORIGINAL_SHORT_NAMES: List<Name> = FQ_NAMES_TO_JVM_MAP.keySet().map { it.shortName() } val JVM_SHORT_NAME_TO_BUILTIN_SHORT_NAMES_MAP: Map<Name, List<Name>> = FQ_NAMES_TO_JVM_MAP.getInversedShortNamesMap() val Name.sameAsRenamedInJvmBuiltin: Boolean get() = this in ORIGINAL_SHORT_NAMES fun getJvmName(callableMemberDescriptor: CallableMemberDescriptor): Name? { return FQ_NAMES_TO_JVM_MAP[callableMemberDescriptor.fqNameOrNull() ?: return null] } fun isBuiltinFunctionWithDifferentNameInJvm(callableMemberDescriptor: CallableMemberDescriptor): Boolean { if (!callableMemberDescriptor.isFromBuiltins()) return false val fqName = callableMemberDescriptor.fqNameOrNull() ?: return false return callableMemberDescriptor.firstOverridden { FQ_NAMES_TO_JVM_MAP.containsKey(fqName) } != null } fun getBuiltinFunctionNamesByJvmName(name: Name): List<Name> = JVM_SHORT_NAME_TO_BUILTIN_SHORT_NAMES_MAP[name] ?: emptyList() val CallableMemberDescriptor.isRemoveAtByIndex: Boolean get() = name.asString() == "removeAt" && fqNameOrNull() == REMOVE_AT_FQ_NAME } @Suppress("UNCHECKED_CAST") fun <T : CallableMemberDescriptor> T.getOverriddenBuiltinWithDifferentJvmName(): T? { if (name !in BuiltinMethodsWithDifferentJvmName.ORIGINAL_SHORT_NAMES && propertyIfAccessor.name !in BuiltinSpecialProperties.SHORT_NAMES) return null return when (this) { is PropertyDescriptor, is PropertyAccessorDescriptor -> firstOverridden { BuiltinSpecialProperties.hasBuiltinSpecialPropertyFqName(it.propertyIfAccessor) } as T? else -> firstOverridden { BuiltinMethodsWithDifferentJvmName.isBuiltinFunctionWithDifferentNameInJvm(it) } as T? } } fun CallableMemberDescriptor.doesOverrideBuiltinWithDifferentJvmName(): Boolean = getOverriddenBuiltinWithDifferentJvmName() != null @Suppress("UNCHECKED_CAST") fun <T : CallableMemberDescriptor> T.getOverriddenBuiltinWithDifferentJvmDescriptor(): T? { getOverriddenBuiltinWithDifferentJvmName()?.let { return it } if (!name.sameAsBuiltinMethodWithErasedValueParameters) return null return firstOverridden { it.isFromBuiltins() && it.getSpecialSignatureInfo() == BuiltinMethodsWithSpecialGenericSignature.SpecialSignatureInfo.GENERIC_PARAMETER }?.original as T? } fun getJvmMethodNameIfSpecial(callableMemberDescriptor: CallableMemberDescriptor): String? { val builtinOverridden = getBuiltinOverriddenThatAffectsJvmName(callableMemberDescriptor)?.propertyIfAccessor ?: return null return when (builtinOverridden) { is PropertyDescriptor -> builtinOverridden.getBuiltinSpecialPropertyGetterName() else -> BuiltinMethodsWithDifferentJvmName.getJvmName(builtinOverridden)?.asString() } } private fun getBuiltinOverriddenThatAffectsJvmName( callableMemberDescriptor: CallableMemberDescriptor ): CallableMemberDescriptor? { val overriddenBuiltin = callableMemberDescriptor.getOverriddenBuiltinWithDifferentJvmName() ?: return null if (callableMemberDescriptor.isFromJavaOrBuiltins()) return overriddenBuiltin return null } // Util methods private val CallableMemberDescriptor.isFromJava: Boolean get() = propertyIfAccessor is JavaCallableMemberDescriptor && propertyIfAccessor.containingDeclaration is JavaClassDescriptor private fun CallableMemberDescriptor.isFromBuiltins(): Boolean { if (!(propertyIfAccessor.fqNameOrNull()?.firstSegmentIs(KotlinBuiltIns.BUILT_INS_PACKAGE_NAME) ?: false)) return false return builtIns.builtInsModule == module } private val CallableMemberDescriptor.propertyIfAccessor: CallableMemberDescriptor get() = if (this is PropertyAccessorDescriptor) correspondingProperty else this private fun CallableDescriptor.fqNameOrNull(): FqName? = fqNameUnsafe.check { it.isSafe }?.toSafe() private fun CallableMemberDescriptor.firstOverridden( predicate: (CallableMemberDescriptor) -> Boolean ): CallableMemberDescriptor? { var result: CallableMemberDescriptor? = null return DFS.dfs(listOf(this), object : DFS.Neighbors<CallableMemberDescriptor> { override fun getNeighbors(current: CallableMemberDescriptor?): Iterable<CallableMemberDescriptor> { return current?.overriddenDescriptors ?: emptyList() } }, object : DFS.AbstractNodeHandler<CallableMemberDescriptor, CallableMemberDescriptor?>() { override fun beforeChildren(current: CallableMemberDescriptor) = result == null override fun afterChildren(current: CallableMemberDescriptor) { if (result == null && predicate(current)) { result = current } } override fun result(): CallableMemberDescriptor? = result } ) } public fun CallableMemberDescriptor.isFromJavaOrBuiltins() = isFromJava || isFromBuiltins() private fun Map<FqName, Name>.getInversedShortNamesMap(): Map<Name, List<Name>> = entrySet().groupBy { it.value }.mapValues { entry -> entry.value.map { it.key.shortName() } }
0
null
0
1
ff00bde607d605c4eba2d98fbc9e99af932accb6
12,472
kotlin
Apache License 2.0
src/lsp/intellij-plugin/src/main/kotlin/Annotator.kt
flock-community
506,356,849
false
null
package community.flock.wirespec.lsp.intellij_plugin import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.ExternalAnnotator import com.intellij.lang.annotation.HighlightSeverity import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiFile import community.flock.wirespec.compiler.core.WirespecSpec import community.flock.wirespec.compiler.core.exceptions.WirespecException import community.flock.wirespec.compiler.core.parse.Parser import community.flock.wirespec.compiler.core.tokenize.tokenize import community.flock.wirespec.compiler.utils.Logger import kotlinx.coroutines.runBlocking class Annotator : ExternalAnnotator<List<WirespecException>, List<WirespecException>>() { private val logger = object : Logger() {} override fun collectInformation(file: PsiFile) = runBlocking { WirespecSpec.tokenize(file.text) .let { Parser(logger).parse(it) } .fold({ it }, { emptyList() }) } override fun doAnnotate(collectedInfo: List<WirespecException>?) = collectedInfo override fun apply(file: PsiFile, annotationResult: List<WirespecException>?, holder: AnnotationHolder) { annotationResult?.forEach { holder .newAnnotation(HighlightSeverity.ERROR, it.message ?: "") .range( TextRange( it.coordinates.idxAndLength.idx - it.coordinates.idxAndLength.length, it.coordinates.idxAndLength.idx ) ) .create() } super.apply(file, annotationResult, holder) } }
18
null
1
9
3dce08aec1b787d90ae284b5bd0cf7a50628afa8
1,650
wirespec
Apache License 2.0
sample/src/main/java/indi/yume/tools/sample/ComposeActivity.kt
Yumenokanata
132,113,505
false
null
package indi.yume.tools.sample import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.TextView import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import indi.yume.tools.dsladapter.* import indi.yume.tools.dsladapter.renderers.* import indi.yume.tools.dsladapter.renderers.databinding.CLEAR_ALL import indi.yume.tools.dsladapter.renderers.databinding.databindingOf import indi.yume.tools.dsladapter.updater.* import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.functions.Consumer import io.reactivex.schedulers.Schedulers class ComposeActivity : AppCompatActivity() { internal var index = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_compose) setTitle("Multiple compose Demo") val recyclerView = findViewById<RecyclerView>(R.id.compose_recycler_view) val stringRenderer = LayoutRenderer<String>(layout = R.layout.simple_item, count = 3, binder = { view, title, index -> view.findViewById<TextView>(R.id.simple_text_view).text = title + index }, recycleFun = { view -> view.findViewById<TextView>(R.id.simple_text_view).text = "" }) val itemRenderer = databindingOf<ItemModel>(R.layout.item_layout) .onRecycle(CLEAR_ALL) .itemId(BR.model) .itemId(BR.content, { m -> m.content + "xxxx" }) .stableIdForItem { it.id } .forItem() val renderer = TitleItemRenderer( itemType = type<List<ItemModel>>(), titleGetter = { "TitleItemRenderer: title" }, subsGetter = { it }, title = stringRenderer, subs = itemRenderer) val adapter = RendererAdapter.multipleBuild() // .add(layout<Unit>(R.layout.list_header)) // .add(listOf(ItemModel().some()).some(), // optionRenderer( // noneItemRenderer = LayoutRenderer.dataBindingItem<Unit, ItemLayoutBinding>( // count = 5, // layout = R.layout.item_layout, // bindBinding = { ItemLayoutBinding.bind(it) }, // binder = { bind, item, _ -> // bind.content = "Last5 this is empty item" // }, // recycleFun = { it.model = null; it.content = null; it.click = null }), // itemRenderer = LayoutRenderer.dataBindingItem<Option<ItemModel>, ItemLayoutBinding>( // count = 5, // layout = R.layout.item_layout, // bindBinding = { ItemLayoutBinding.bind(it) }, // binder = { bind, item, _ -> // bind.content = "Last5 this is some item" // }, // recycleFun = { it.model = null; it.content = null; it.click = null }) // .forList() // )) // .add(provideData(index).let { HListK.singleId(it).putF(it) }, // ComposeRenderer.startBuild // .add(LayoutRenderer<ItemModel>(layout = R.layout.simple_item, // stableIdForItem = { item, index -> item.id }, // binder = { view, itemModel, index -> view.findViewById<TextView>(R.id.simple_text_view).text = "Last4 ${itemModel.title}" }, // recycleFun = { view -> view.findViewById<TextView>(R.id.simple_text_view).text = "" }) // .forList({ i, index -> index })) // .add(databindingOf<ItemModel>(R.layout.item_layout) // .onRecycle(CLEAR_ALL) // .itemId(BR.model) // .itemId(BR.content, { m -> "Last4 " + m.content + "xxxx" }) // .stableIdForItem { it.id } // .forItem() // .replaceUpdate { CustomUpdate(it) } // .forList()) // .build().ignoreType // { oldData, newData, payload -> // getLast1().reduce { data -> // subs(2) { // up.update(ItemModel()) // } // } // }) .add(provideData(index), LayoutRenderer<ItemModel>( count = 1, layout = R.layout.simple_item, stableIdForItem = { item, index -> item.id }, binder = { view, itemModel, index -> view.findViewById<TextView>(R.id.simple_text_view).text = "Last3 ${itemModel.title}" }, recycleFun = { view -> view.findViewById<TextView>(R.id.simple_text_view).text = "" }) .forList(keyGetter = { i, index -> index }, itemIsSingle = true)) // .add(provideData(index), renderer) // .add(DateFormat.getInstance().format(Date()), // databindingOf<String>(R.layout.list_footer) // .itemId(BR.text) // .forItem()) .build() recyclerView.adapter = adapter recyclerView.layoutManager = LinearLayoutManager(this) var time = 0L findViewById<View>(R.id.load_next_button).setOnClickListener { v -> index++ val newData = provideData(index) Single.fromCallable { time = System.currentTimeMillis() val r = adapter.update(::ComposeUpdater) { // getLast2().up { // update(newData) // } + getLast0().up(::updatable) { // move(2, 4) + // subs(3) { // update(ItemModel(189, "Subs Title $index", "subs Content")) // } updateAuto(newData.shuffled(), diffUtilCheck { i, _ -> i.id }) } // } + getLast4().up { // update(hlistKOf(emptyList<ItemModel>().toIdT(), emptyList<ItemModel>().toIdT())) // } + getLast5().up { // sealedItem({ get0().fix() }) { // update(listOf(ItemModel().some(), none<ItemModel>())) // } // } } println("computation over: ${System.currentTimeMillis() - time}") r } .subscribeOn(Schedulers.computation()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(Consumer { adapter.updateData(it) }) } } }
2
null
6
71
5d0cc1a2e4d7affaf98ad4e00584724230267885
7,806
DslAdapter
Apache License 2.0
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/api/VimscriptFunctionService.kt
JetBrains
1,459,486
false
{"Kotlin": 5959132, "Java": 211095, "ANTLR": 84686, "HTML": 2184}
/* * Copyright 2003-2023 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.api import com.maddyhome.idea.vim.vimscript.model.VimLContext import com.maddyhome.idea.vim.vimscript.model.expressions.Scope import com.maddyhome.idea.vim.vimscript.model.functions.FunctionHandler import com.maddyhome.idea.vim.vimscript.model.functions.LazyVimscriptFunction import com.maddyhome.idea.vim.vimscript.model.statements.FunctionDeclaration interface VimscriptFunctionService { fun deleteFunction(name: String, scope: Scope? = null, vimContext: VimLContext) fun storeFunction(declaration: FunctionDeclaration) fun getFunctionHandler(scope: Scope?, name: String, vimContext: VimLContext): FunctionHandler fun getFunctionHandlerOrNull(scope: Scope?, name: String, vimContext: VimLContext): FunctionHandler? fun getUserDefinedFunction(scope: Scope?, name: String, vimContext: VimLContext): FunctionDeclaration? fun getBuiltInFunction(name: String): FunctionHandler? fun registerHandlers() fun addHandler(handler: LazyVimscriptFunction) }
6
Kotlin
749
9,241
66b01b0b0d48ffec7b0148465b85e43dfbc908d3
1,204
ideavim
MIT License
src/backend/archive/api-archive/src/main/kotlin/com/tencent/bkrepo/archive/request/DeleteCompressRequest.kt
TencentBlueKing
548,243,758
false
{"Kotlin": 13657594, "Vue": 1261332, "JavaScript": 683823, "Shell": 124343, "Lua": 100415, "SCSS": 34137, "Python": 25877, "CSS": 17382, "HTML": 13052, "Dockerfile": 4483, "Smarty": 3661, "Java": 423}
package com.tencent.bkrepo.archive.request import com.tencent.bkrepo.repository.constant.SYSTEM_USER data class DeleteCompressRequest( val sha256: String, val storageCredentialsKey: String?, val operator: String = SYSTEM_USER, )
363
Kotlin
38
70
54b0c7ab20ddbd988387bac6c9143b594681e73c
243
bk-repo
MIT License
protocol/osrs-223/src/main/kotlin/net/rsprox/protocol/game/incoming/decoder/codec/locs/OpLocTDecoder.kt
blurite
822,339,098
false
null
package net.rsprox.protocol.game.incoming.decoder.codec.locs import net.rsprot.buffer.JagByteBuf import net.rsprot.protocol.ClientProt import net.rsprot.protocol.util.gCombinedIdAlt1 import net.rsprox.protocol.ProxyMessageDecoder import net.rsprox.protocol.game.incoming.decoder.prot.GameClientProt import net.rsprox.protocol.game.incoming.model.locs.OpLocT import net.rsprox.protocol.session.Session public class OpLocTDecoder : ProxyMessageDecoder<OpLocT> { override val prot: ClientProt = GameClientProt.OPLOCT override fun decode( buffer: JagByteBuf, session: Session, ): OpLocT { val selectedSub = buffer.g2Alt1() val selectedObj = buffer.g2Alt3() val z = buffer.g2() val controlKey = buffer.g1Alt2() == 1 val x = buffer.g2Alt2() val selectedCombinedId = buffer.gCombinedIdAlt1() val id = buffer.g2Alt1() return OpLocT( id, x, z, controlKey, selectedCombinedId, selectedSub, selectedObj, ) } }
9
null
4
9
41535908e6ccb633c8f2564e8961efa771abd6de
1,090
rsprox
MIT License
src/test/kotlin/adventofcode/Day3Test.kt
jwcarman
325,348,954
false
null
/* * Copyright (c) 2020 <NAME> * * 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 adventofcode import adventofcode.fabric.Claim import adventofcode.io.Resources.readLines import mu.KotlinLogging import org.junit.jupiter.api.Test private val log = KotlinLogging.logger {} class Day3Test { @Test fun `Part One`() { val count = readLines("/Day3.txt") .map(this::parseClaim) .flatMap(Claim::points) .groupingBy { it } .eachCount() .filterValues { it > 1 } .count() log.info { "Part One: $count" } } @Test fun `Part Two`() { val claims = readLines("/Day3.txt") .map { line -> parseClaim(line) } val pointCounts = claims .flatMap(Claim::points) .groupingBy { it } .eachCount() val id = claims .first { it.points().all { point -> pointCounts[point] == 1 } } .id log.info { "Part Two: $id" } } fun parseClaim(input: String): Claim { val regex = """#(\d+) @ (\d+),(\d+): (\d+)x(\d+)""".toRegex() return regex.matchEntire(input) ?.destructured ?.let { (id, x, y, width, height) -> Claim( id.toInt(), x.toInt(), y.toInt(), width.toInt(), height.toInt() ) } ?: throw IllegalArgumentException("Bad input '$input!'") } }
0
Kotlin
0
1
049cd7f36a8773324625f7d84dc6ac52cfac2299
2,054
adventofcode2018
Apache License 2.0
app/shared/google-sign-in/impl/src/androidMain/kotlin/build/wallet/google/signin/GoogleSignOutActionImpl.kt
proto-at-block
761,306,853
false
{"C": 10424094, "Kotlin": 7156393, "Rust": 2046237, "Swift": 700307, "Python": 331492, "HCL": 271992, "Shell": 111209, "TypeScript": 102700, "C++": 64770, "Meson": 64234, "JavaScript": 36227, "Just": 28071, "Ruby": 9428, "Dockerfile": 5731, "Makefile": 3839, "Open Policy Agent": 1552, "Procfile": 80}
package build.wallet.google.signin import build.wallet.catching import build.wallet.logging.LogLevel.Error import build.wallet.logging.log import com.github.michaelbull.result.Result import com.github.michaelbull.result.map import com.github.michaelbull.result.mapError import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.tasks.await import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout import kotlin.time.Duration.Companion.seconds class GoogleSignOutActionImpl( private val googleSignInClientProvider: GoogleSignInClientProvider, ) : GoogleSignOutAction { override suspend fun signOut(): Result<Unit, GoogleSignOutError> { log { "Signing out from Google accounts" } return Result .catching { withTimeout(10.seconds) { withContext(Dispatchers.IO) { with(googleSignInClientProvider.clientForGoogleDrive) { // Revoking access disconnects customer's Google account from our app. revokeAccess().continueWith { signOut() } }.await() } } } .map { log { "Successfully logged out from Google account and revoked access." } // Noop: Sign out action was successful. } .mapError { error -> log(Error, throwable = error) { "Failed to sign out from Google account." } GoogleSignOutError("Google Sign Out failed. $error") } } }
3
C
16
98
1f9f2298919dac77e6791aa3f1dbfd67efe7f83c
1,422
bitkey
MIT License
app/src/main/java/com/example/android/asteroidsradar/backgroundwork/RefreshDataWorker.kt
GerganaT
394,024,628
false
null
/* Copyright 2021, <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.android.asteroidsradar.backgroundwork import android.content.Context import androidx.work.CoroutineWorker import androidx.work.WorkerParameters import com.example.android.asteroidsradar.database.getAsteroidsDatabase import com.example.android.asteroidsradar.repository.AsteroidRepository import retrofit2.HttpException class RefreshDataWorker(context: Context, workerParams: WorkerParameters) : CoroutineWorker(context, workerParams) { override suspend fun doWork(): Result { val database = getAsteroidsDatabase(applicationContext) val repository = AsteroidRepository(database) return try { repository.updateAsteroidsDatabase() repository.deleteOlderAsteroidsFromDatabase() Result.success() } catch (httpException: HttpException) { Result.retry() } } }
0
Kotlin
0
0
2bb6ef0e3cdbd6e63b3c09e3e06c0ca6eda593fa
1,431
AsteroidRadar
Apache License 2.0
app/src/main/java/com/vladimirpetrovski/currencyconverter/domain/usecase/RecalculateRatesUseCase.kt
vladimirpetrovski
199,713,601
false
null
package com.vladimirpetrovski.currencyconverter.domain.usecase import com.vladimirpetrovski.currencyconverter.domain.CalculateRatesHelper import com.vladimirpetrovski.currencyconverter.domain.model.CalculatedRate import com.vladimirpetrovski.currencyconverter.domain.repository.RatesRepository import io.reactivex.Single import java.math.BigDecimal import javax.inject.Inject /** * Recalculate given amount with rates from the cache. * * @return new recalculated list. */ class RecalculateRatesUseCase @Inject constructor( private val ratesRepository: RatesRepository, private val calculateRatesHelper: CalculateRatesHelper ) { operator fun invoke(amount: BigDecimal): Single<List<CalculatedRate>> { val list = calculateRatesHelper.calculate( ratesRepository.cachedCalculatedRates, amount, ratesRepository.cachedLatestRates ) ratesRepository.cachedCalculatedRates = list return Single.just(list) } }
0
Kotlin
0
3
5979a2e1ccc0267d967302fc3a082b75c714b9a6
991
CurrencyConverter
The Unlicense
src/main/kotlin/no/nav/tms/min/side/proxy/proxyRoutes.kt
navikt
455,493,229
false
null
package no.nav.tms.min.side.proxy import io.ktor.client.statement.readBytes import io.ktor.server.application.ApplicationCall import io.ktor.server.application.call import io.ktor.server.request.receiveText import io.ktor.server.response.respond import io.ktor.server.routing.Route import io.ktor.server.routing.get import io.ktor.server.routing.post import io.ktor.util.pipeline.PipelineContext import no.nav.tms.token.support.idporten.sidecar.user.IdportenUserFactory fun Route.proxyRoutes(contentFetcher: ContentFetcher) { get("/aap/{proxyPath...}") { val response = contentFetcher.getAapContent(accessToken, proxyPath) call.respond(response.status, response.readBytes()) } get("/arbeid/{proxyPath...}") { val response = contentFetcher.getArbeidContent(accessToken, proxyPath) call.respond(response.status, response.readBytes()) } get("/dittnav/{proxyPath...}") { val response = contentFetcher.getDittNavContent(accessToken, proxyPath) call.respond(response.status, response.readBytes()) } post("/dittnav/{proxyPath...}") { val content = jsonConfig().parseToJsonElement(call.receiveText()) val response = contentFetcher.postDittNavContent(accessToken, content, proxyPath) call.respond(response.status) } get("/sykefravaer/{proxyPath...}") { val response = contentFetcher.getSykefravaerContent(accessToken, proxyPath) call.respond(response.status, response.readBytes()) } get("/utkast/{proxyPath...}") { val response = contentFetcher.getUtkastContent(accessToken, proxyPath) call.respond(response.status, response.readBytes()) } get("/personalia/{proxyPath...}") { val response = contentFetcher.getPersonaliaContent(accessToken, proxyPath) call.respond(response.status, response.readBytes()) } get("/meldekort/{proxyPath...}") { val response = contentFetcher.getMeldekortContent(accessToken, proxyPath) call.respond(response.status, response.readBytes()) } } private val PipelineContext<Unit, ApplicationCall>.accessToken get() = IdportenUserFactory.createIdportenUser(call).tokenString private val PipelineContext<Unit, ApplicationCall>.proxyPath: String? get() = call.parameters.getAll("proxyPath")?.joinToString("/")
1
Kotlin
0
0
32c28423b9e1b0fd6cc3868c6c65cdca5d06f40b
2,342
tms-min-side-proxy
MIT License
src/main/kotlin/su/sonoma/fishingmod/Fishingmod.kt
saddydead1
743,375,355
false
{"Kotlin": 22737}
package su.sonoma.fishingmod import com.mojang.logging.LogUtils import net.minecraft.client.Minecraft import net.minecraft.core.registries.Registries import net.minecraft.network.chat.Component import net.minecraft.world.item.CreativeModeTab import net.minecraft.world.item.CreativeModeTab.ItemDisplayParameters import net.minecraft.world.item.CreativeModeTabs import net.minecraft.world.item.Item import net.minecraft.world.level.block.Blocks import net.minecraftforge.api.distmarker.Dist import net.minecraftforge.common.MinecraftForge import net.minecraftforge.event.server.ServerStartingEvent import net.minecraftforge.eventbus.api.SubscribeEvent import net.minecraftforge.fml.ModLoadingContext import net.minecraftforge.fml.common.Mod import net.minecraftforge.fml.common.Mod.EventBusSubscriber import net.minecraftforge.fml.config.ModConfig import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent import net.minecraftforge.registries.DeferredRegister import net.minecraftforge.registries.ForgeRegistries import net.minecraftforge.registries.RegistryObject import org.slf4j.Logger import su.sonoma.fishingmod.block.ModBlocks import su.sonoma.fishingmod.item.Bait import su.sonoma.fishingmod.item.Fish import su.sonoma.fishingmod.item.ModItems import thedarkcolour.kotlinforforge.forge.MOD_BUS as modEventBus // The value here should match an entry in the META-INF/mods.toml file @Mod(Fishingmod.MODID) object Fishingmod { const val MODID: String = "fishingmod" val LOGGER: Logger = LogUtils.getLogger() val CREATIVE_MODE_TABS: DeferredRegister<CreativeModeTab> = DeferredRegister.create(Registries.CREATIVE_MODE_TAB, MODID) init { modEventBus.addListener { event: FMLCommonSetupEvent -> this.commonSetup(event) } ModItems.ITEMS.register(modEventBus) Fish.FISH.register(modEventBus) Bait.BAIT.register(modEventBus) ModBlocks.BLOCKS.register(modEventBus) CREATIVE_MODE_TABS.register(modEventBus) // Register ourselves for server and other game events we are interested in MinecraftForge.EVENT_BUS.register(this) // // Register the item to a creative tab // modEventBus.addListener { event: BuildCreativeModeTabContentsEvent -> this.addCreative(event) } // Register our mod's ForgeConfigSpec so that Forge can create and load the config file for us ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, Config.SPEC) } private fun commonSetup(event: FMLCommonSetupEvent) { // Some common setup code LOGGER.info("HELLO FROM COMMON SETUP") LOGGER.info("DIRT BLOCK >> {}", ForgeRegistries.BLOCKS.getKey(Blocks.DIRT)) if (Config.logDirtBlock) LOGGER.info("DIRT BLOCK >> {}", ForgeRegistries.BLOCKS.getKey(Blocks.DIRT)) LOGGER.info(Config.magicNumberIntroduction + Config.magicNumber) Config.items.forEach { item: Item -> LOGGER.info("ITEM >> {}", item.toString()) } } // You can use SubscribeEvent and let the Event Bus discover methods to call @SubscribeEvent fun onServerStarting(event: ServerStartingEvent?) { // Do something when the server starts LOGGER.info("HELLO from server starting") } // You can use EventBusSubscriber to automatically register all static methods in the class annotated with @SubscribeEvent @EventBusSubscriber(modid = MODID, bus = EventBusSubscriber.Bus.MOD, value = [Dist.CLIENT]) object ClientModEvents { @SubscribeEvent fun onClientSetup(event: FMLClientSetupEvent?) { // Some client setup code LOGGER.info("HELLO FROM CLIENT SETUP") LOGGER.info("MINECRAFT NAME >> {}", Minecraft.getInstance().user.name) } } val EXAMPLE_TAB: RegistryObject<CreativeModeTab> = CREATIVE_MODE_TABS.register("example_tab") { CreativeModeTab.builder() .withTabsBefore(CreativeModeTabs.COMBAT) .icon { Bait.WORM.get().defaultInstance } .title(Component.translatable(MODID + ".fish_tab")) .displayItems { parameters: ItemDisplayParameters?, output: CreativeModeTab.Output -> output.accept( Fish.COOKEDFISH.get()) output.accept( Fish.HUNTERFISH.get()) output.accept( Fish.PERCHFISH.get()) output.accept( Fish.CARP.get()) output.accept( Fish.MIDNIGHT_CARP.get()) output.accept( Fish.ANCHOYS.get()) output.accept( Fish.CATFISH.get()) output.accept( ModItems.HOOK.get()) output.accept(ModItems.GOLDENHOOK.get()) output.accept( ModItems.BASICROD.get()) output.accept( ModItems.PRISMROD.get()) output.accept( ModItems.FISHINGLINE.get()) output.accept( ModItems.RODSTICK.get()) output.accept(ModItems.PRISMARINESTICK.get()) output.accept( ModItems.FISHTOOL.get()) output.accept( ModItems.COMPOSITE.get()) output.accept(ModItems.PRISMARINEINGOT.get()) output.accept( ModItems.RAWCOMPOSITE.get()) output.accept( Bait.WORM.get() ) output.accept( Bait.COOKEDWORM.get() ) output.accept( Bait.BUG.get()) output.accept( ModItems.WORMBLOCK.get()) }.build() } }
0
Kotlin
0
1
e8c37e44e6885535aec4cdf1cad1efcc87c1b684
5,472
Fishing-Mod
MIT License
helios-test/src/main/kotlin/helios/arrow/laws/PrismLaws.kt
47degrees
118,187,374
false
null
package arrow.test.laws import arrow.core.* import arrow.instances.const.applicative.applicative import arrow.instances.id.applicative.applicative import arrow.typeclasses.* import arrow.optics.Prism import arrow.optics.modify import io.kotlintest.properties.Gen import io.kotlintest.properties.forAll object PrismLaws { fun <A, B> laws(prism: Prism<A, B>, aGen: Gen<A>, bGen: Gen<B>, funcGen: Gen<(B) -> B>, EQA: Eq<A>, EQOptionB: Eq<Option<B>>): List<Law> = listOf( Law("Prism law: partial round trip one way") { prism.partialRoundTripOneWay(aGen, EQA) }, Law("Prism law: round trip other way") { prism.roundTripOtherWay(bGen, EQOptionB) }, Law("Prism law: modify identity") { prism.modifyIdentity(aGen, EQA) }, Law("Prism law: compose modify") { prism.composeModify(aGen, funcGen, EQA) }, Law("Prism law: consistent set modify") { prism.consistentSetModify(aGen, bGen, EQA) }, Law("Prism law: consistent modify with modifyF Id") { prism.consistentModifyModifyFId(aGen, funcGen, EQA) }, Law("Prism law: consistent get option modify id") { prism.consistentGetOptionModifyId(aGen, EQOptionB) } ) fun <A, B> Prism<A, B>.partialRoundTripOneWay(aGen: Gen<A>, EQA: Eq<A>): Unit = forAll(aGen) { a -> getOrModify(a).fold(::identity, this::reverseGet) .equalUnderTheLaw(a, EQA) } fun <A, B> Prism<A, B>.roundTripOtherWay(bGen: Gen<B>, EQOptionB: Eq<Option<B>>): Unit = forAll(bGen) { b -> getOption(reverseGet(b)) .equalUnderTheLaw(Some(b), EQOptionB) } fun <A, B> Prism<A, B>.modifyIdentity(aGen: Gen<A>, EQA: Eq<A>): Unit = forAll(aGen) { a -> modify(a, ::identity).equalUnderTheLaw(a, EQA) } fun <A, B> Prism<A, B>.composeModify(aGen: Gen<A>, funcGen: Gen<(B) -> B>, EQA: Eq<A>): Unit = forAll(aGen, funcGen, funcGen) { a, f, g -> modify(modify(a, f), g).equalUnderTheLaw(modify(a, g compose f), EQA) } fun <A, B> Prism<A, B>.consistentSetModify(aGen: Gen<A>, bGen: Gen<B>, EQA: Eq<A>): Unit = forAll(aGen, bGen) { a, b -> set(a, b).equalUnderTheLaw(modify(a) { b }, EQA) } fun <A, B> Prism<A, B>.consistentModifyModifyFId(aGen: Gen<A>, funcGen: Gen<(B) -> B>, EQA: Eq<A>): Unit = forAll(aGen, funcGen) { a, f -> modifyF(Id.applicative(), a) { Id.just(f(it)) }.value().equalUnderTheLaw(modify(a, f), EQA) } fun <A, B> Prism<A, B>.consistentGetOptionModifyId(aGen: Gen<A>, EQOptionB: Eq<Option<B>>): Unit = forAll(aGen) { a -> modifyF(Const.applicative(object : Monoid<Option<B>> { override fun Option<B>.combine(b: Option<B>): Option<B> = orElse { b } override fun empty(): Option<B> = None }), a) { Const(Some(it)) }.value().equalUnderTheLaw(getOption(a), EQOptionB) } }
26
null
25
166
e6cff1ee7f6832fbdf121779c1062987ef25f160
2,762
helios
Apache License 2.0
src/test/kotlin/no/nav/helse/flex/soknadsopprettelse/PrettyOrgnavnTest.kt
navikt
475,306,289
false
null
package no.nav.helse.flex.soknadsopprettelse import org.amshove.kluent.`should be equal to` import org.junit.jupiter.api.Test internal class PrettyOrgnavnTest { @Test fun `Gjør SKRIKENDE orgnavn pene`() { "NAV OSLO".prettyOrgnavn() `should be equal to` "NAV Oslo" "MATBUTIKKEN AS".prettyOrgnavn() `should be equal to` "Matbutikken AS" "COOP NORGE SA,AVD LAGER STAVANGER".prettyOrgnavn() `should be equal to` "Coop Norge SA, avd lager Stavanger" } }
6
null
0
4
644877fd8c3d888002fae1d62f95c90704526492
489
sykepengesoknad-backend
MIT License
app/src/main/java/host/stjin/anonaddy/widget/AliasWidget1RemoteViewsService.kt
anonaddy
854,490,200
false
{"Kotlin": 1335623}
package host.stjin.anonaddy.widget import android.content.Intent import android.widget.RemoteViewsService class AliasWidget1RemoteViewsService : RemoteViewsService() { override fun onGetViewFactory(intent: Intent): RemoteViewsFactory { return AliasWidget1RemoteViewsFactory(this) } }
0
Kotlin
0
3
ac5d5ee3d7ca14cf88711c1c92ec991fb1ce5ef3
301
addy-android
MIT License
src/main/kotlin/io/github/runedata/cache/content/config/ObjectDefinition.kt
Rune-Status
151,259,951
false
null
/* Copyright 2018 <NAME> 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.github.runedata.cache.content.config import io.github.runedata.cache.content.IndexType import io.github.runedata.cache.filesystem.Archive import io.github.runedata.cache.filesystem.CacheStore import io.github.runedata.cache.filesystem.util.getParams import io.github.runedata.cache.filesystem.util.getString import io.github.runedata.cache.filesystem.util.getUnsignedByte import io.github.runedata.cache.filesystem.util.getUnsignedShort import java.nio.ByteBuffer class ObjectDefinition(id: Int) : ConfigEntry(id) { var textureFind: IntArray? = null var decorDisplacement = 16 var isHollow = false var name = "null" var objectModels: IntArray? = null var objectTypes: IntArray? = null var colorFind: IntArray? = null var mapIconId = -1 var textureReplace: IntArray? = null var width = 1 var length = 1 var anInt2083 = 0 var anIntArray2084: IntArray? = null var offsetX = 0 var nonFlatShading = false var anInt2088 = -1 var animationID = -1 var varpID = -1 var ambient = 0 var contrast = 0 var options = arrayOfNulls<String>(5) var clipType = 2 var mapSceneID = -1 var colorReplace: IntArray? = null var isClipped = true var modelSizeX = 128 var modelSizeHeight = 128 var modelSizeY = 128 var offsetHeight = 0 var offsetY = 0 var obstructsGround = false var contouredGround = -1 var supportItems = -1 var configChangeDest: IntArray? = null var isMirrored = false var configId = -1 var ambientSoundId = -1 var modelClipped = false var anInt2112 = 0 var anInt2113 = 0 var impenetrable = true var accessBlock = 0 var params: MutableMap<Int, Any>? = null override fun decode(buffer: ByteBuffer): ObjectDefinition { while (true) { val opcode = buffer.getUnsignedByte() when (opcode) { 0 -> { post() return this } 1 -> { val length = buffer.getUnsignedByte() if (length > 0) { objectTypes = IntArray(length) objectModels = IntArray(length) for (index in 0 until length) { objectModels!![index] = buffer.getUnsignedShort() objectTypes!![index] = buffer.getUnsignedByte() } } } 2 -> name = buffer.getString() 5 -> { val length = buffer.getUnsignedByte() if (length > 0) { objectTypes = null objectModels = IntArray(length) { buffer.getUnsignedShort() } } } 14 -> width = buffer.getUnsignedByte() 15 -> length = buffer.getUnsignedByte() 17 -> { clipType = 0 impenetrable = false } 18 -> impenetrable = false 19 -> anInt2088 = buffer.getUnsignedByte() 21 -> contouredGround = 0 22 -> nonFlatShading = false 23 -> modelClipped = true 24 -> animationID = buffer.getUnsignedShort() 27 -> clipType = 1 28 -> decorDisplacement = buffer.getUnsignedByte() 29 -> ambient = buffer.get().toInt() 39 -> contrast = buffer.get().toInt() in 30..34 -> options[opcode - 30] = buffer.getString().takeIf { it != "Hidden" } 40 -> { val colors = buffer.getUnsignedByte() colorFind = IntArray(colors) colorReplace = IntArray(colors) for (i in 0 until colors) { colorFind!![i] = buffer.getUnsignedShort() colorReplace!![i] = buffer.getUnsignedShort() } } 41 -> { val textures = buffer.getUnsignedByte() textureFind = IntArray(textures) textureReplace = IntArray(textures) for (i in 0 until textures) { textureFind!![i] = buffer.getUnsignedShort() textureReplace!![i] = buffer.getUnsignedShort() } } 62 -> isMirrored = true 64 -> isClipped = false 65 -> modelSizeX = buffer.getUnsignedShort() 66 -> modelSizeHeight = buffer.getUnsignedShort() 67 -> modelSizeY = buffer.getUnsignedShort() 68 -> mapSceneID = buffer.getUnsignedShort() 69 -> accessBlock = buffer.get().toInt() 70 -> offsetX = buffer.getUnsignedShort() 71 -> offsetHeight = buffer.getUnsignedShort() 72 -> offsetY = buffer.getUnsignedShort() 73 -> obstructsGround = true 74 -> isHollow = true 75 -> supportItems = buffer.getUnsignedByte() 77 -> { varpID = buffer.getUnsignedShort() configId = buffer.getUnsignedShort() val length = buffer.getUnsignedByte() configChangeDest = IntArray(length + 2) { if (it == length + 1) -1 else buffer.getUnsignedShort() } } 78 -> { ambientSoundId = buffer.getUnsignedShort() anInt2083 = buffer.getUnsignedByte() } 79 -> { anInt2112 = buffer.getUnsignedShort() anInt2113 = buffer.getUnsignedShort() anInt2083 = buffer.getUnsignedByte() val length = buffer.getUnsignedByte() anIntArray2084 = IntArray(length) { buffer.getUnsignedShort() } } 81 -> contouredGround = buffer.getUnsignedByte() 82 -> mapIconId = buffer.getUnsignedShort() 92 -> { varpID = buffer.getUnsignedShort() configId = buffer.getUnsignedShort() val v = buffer.getUnsignedShort() val length = buffer.getUnsignedByte() configChangeDest = IntArray(length + 2) { if (it == length + 1) v else buffer.getUnsignedShort() } } 249 -> params = buffer.getParams() else -> error(opcode) } } } private fun post() { if (anInt2088 == -1) { anInt2088 = 0 if (this.objectModels != null && (this.objectTypes == null || objectTypes!![0] == 10)) { anInt2088 = 1 } for (var1 in 0..4) { if (options[var1] != null) { anInt2088 = 1 } } } if (supportItems == -1) { supportItems = if (clipType != 0) 1 else 0 } } companion object { private const val ARCHIVE_INDEX = 6 fun load(store: CacheStore): Map<Int, ObjectDefinition> { val refTable = store.getReferenceTable(IndexType.CONFIGS.id) val entry = refTable.getEntry(ARCHIVE_INDEX) val archive = Archive.decode(store.readData( IndexType.CONFIGS.id, ARCHIVE_INDEX ).data, refTable.getEntry(ARCHIVE_INDEX)!!.amountOfChildren ) var defCount = 0 val objDefs = mutableMapOf<Int, ObjectDefinition>() for(id in 0 until entry!!.capacity) { val child = entry.getEntry(id) ?: continue objDefs[id] = ObjectDefinition(id).decode(archive.getEntry(child.index)) defCount++ } return objDefs } } }
0
null
0
0
891d71d516099cce51a0472e2c627e6e73e161d8
8,771
Bartvhelvert-Cache-Content
Apache License 2.0
app/src/main/java/com/example/slabber/ChatApp.kt
Wahabahmad694
477,558,751
false
null
package com.example.slabber import android.app.Application import io.socket.client.IO import io.socket.client.Socket import java.net.URISyntaxException class ChatApp : Application() { val socket: Socket init { try { socket = IO.socket("ws://192.168.2.216:3000/") } catch (e: URISyntaxException) { throw RuntimeException(e) } } }
0
Kotlin
0
0
d7f87252662fc50db0089810b231702eb5e97e35
391
Slabber
Apache License 2.0
int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiDropdownStyling.kt
JetBrains
440,164,967
false
null
package org.jetbrains.jewel.intui.standalone.styling import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.shape.CornerSize import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.dp import org.jetbrains.jewel.foundation.theme.JewelTheme import org.jetbrains.jewel.intui.core.theme.IntUiDarkTheme import org.jetbrains.jewel.intui.core.theme.IntUiLightTheme import org.jetbrains.jewel.intui.standalone.standalonePainterProvider import org.jetbrains.jewel.intui.standalone.theme.defaultTextStyle import org.jetbrains.jewel.ui.component.styling.DropdownColors import org.jetbrains.jewel.ui.component.styling.DropdownIcons import org.jetbrains.jewel.ui.component.styling.DropdownMetrics import org.jetbrains.jewel.ui.component.styling.DropdownStyle import org.jetbrains.jewel.ui.component.styling.MenuStyle import org.jetbrains.jewel.ui.painter.PainterProvider val DropdownStyle.Companion.Default: IntUiDefaultDropdownStyleFactory get() = IntUiDefaultDropdownStyleFactory object IntUiDefaultDropdownStyleFactory { @Composable fun light( colors: DropdownColors = DropdownColors.Default.light(), metrics: DropdownMetrics = DropdownMetrics.default(), icons: DropdownIcons = DropdownIcons.defaults(), textStyle: TextStyle = JewelTheme.defaultTextStyle, menuStyle: MenuStyle = MenuStyle.light(), ) = DropdownStyle(colors, metrics, icons, textStyle, menuStyle) @Composable fun dark( colors: DropdownColors = DropdownColors.Default.dark(), metrics: DropdownMetrics = DropdownMetrics.default(), icons: DropdownIcons = DropdownIcons.defaults(), textStyle: TextStyle = JewelTheme.defaultTextStyle, menuStyle: MenuStyle = MenuStyle.dark(), ) = DropdownStyle(colors, metrics, icons, textStyle, menuStyle) } val DropdownStyle.Companion.Undecorated: IntUiUndecoratedDropdownStyleFactory get() = IntUiUndecoratedDropdownStyleFactory object IntUiUndecoratedDropdownStyleFactory { @Composable fun light( colors: DropdownColors = DropdownColors.Undecorated.light(), metrics: DropdownMetrics = DropdownMetrics.undecorated(), icons: DropdownIcons = DropdownIcons.defaults(), textStyle: TextStyle = JewelTheme.defaultTextStyle, menuStyle: MenuStyle = MenuStyle.light(), ) = DropdownStyle(colors, metrics, icons, textStyle, menuStyle) @Composable fun dark( colors: DropdownColors = DropdownColors.Undecorated.dark(), metrics: DropdownMetrics = DropdownMetrics.undecorated(), icons: DropdownIcons = DropdownIcons.defaults(), textStyle: TextStyle = JewelTheme.defaultTextStyle, menuStyle: MenuStyle = MenuStyle.dark(), ) = DropdownStyle(colors, metrics, icons, textStyle, menuStyle) } val DropdownColors.Companion.Default: IntUiDefaultDropdownColorsFactory get() = IntUiDefaultDropdownColorsFactory object IntUiDefaultDropdownColorsFactory { @Composable fun light( background: Color = IntUiLightTheme.colors.grey(14), backgroundDisabled: Color = IntUiLightTheme.colors.grey(13), backgroundFocused: Color = background, backgroundPressed: Color = background, backgroundHovered: Color = background, content: Color = IntUiLightTheme.colors.grey(1), contentDisabled: Color = IntUiLightTheme.colors.grey(8), contentFocused: Color = content, contentPressed: Color = content, contentHovered: Color = content, border: Color = IntUiLightTheme.colors.grey(9), borderDisabled: Color = IntUiLightTheme.colors.grey(11), borderFocused: Color = IntUiLightTheme.colors.blue(4), borderPressed: Color = border, borderHovered: Color = border, iconTint: Color = IntUiLightTheme.colors.grey(7), iconTintDisabled: Color = IntUiLightTheme.colors.grey(9), iconTintFocused: Color = iconTint, iconTintPressed: Color = iconTint, iconTintHovered: Color = iconTint, ) = DropdownColors( background, backgroundDisabled, backgroundFocused, backgroundPressed, backgroundHovered, content, contentDisabled, contentFocused, contentPressed, contentHovered, border, borderDisabled, borderFocused, borderPressed, borderHovered, iconTint, iconTintDisabled, iconTintFocused, iconTintPressed, iconTintHovered, ) @Composable fun dark( background: Color = IntUiDarkTheme.colors.grey(2), backgroundDisabled: Color = background, backgroundFocused: Color = background, backgroundPressed: Color = background, backgroundHovered: Color = background, content: Color = IntUiDarkTheme.colors.grey(12), contentDisabled: Color = IntUiDarkTheme.colors.grey(7), contentFocused: Color = content, contentPressed: Color = content, contentHovered: Color = content, border: Color = IntUiDarkTheme.colors.grey(5), borderDisabled: Color = IntUiDarkTheme.colors.grey(5), borderFocused: Color = IntUiDarkTheme.colors.blue(6), borderPressed: Color = border, borderHovered: Color = border, iconTint: Color = IntUiDarkTheme.colors.grey(10), iconTintDisabled: Color = IntUiDarkTheme.colors.grey(6), iconTintFocused: Color = iconTint, iconTintPressed: Color = iconTint, iconTintHovered: Color = iconTint, ) = DropdownColors( background, backgroundDisabled, backgroundFocused, backgroundPressed, backgroundHovered, content, contentDisabled, contentFocused, contentPressed, contentHovered, border, borderDisabled, borderFocused, borderPressed, borderHovered, iconTint, iconTintDisabled, iconTintFocused, iconTintPressed, iconTintHovered, ) } val DropdownColors.Companion.Undecorated: IntUiUndecoratedDropdownColorsFactory get() = IntUiUndecoratedDropdownColorsFactory object IntUiUndecoratedDropdownColorsFactory { @Composable fun light( background: Color = Color.Transparent, backgroundDisabled: Color = background, backgroundFocused: Color = background, backgroundPressed: Color = IntUiLightTheme.colors.grey(14).copy(alpha = 0.1f), backgroundHovered: Color = backgroundPressed, content: Color = IntUiLightTheme.colors.grey(1), contentDisabled: Color = IntUiLightTheme.colors.grey(8), contentFocused: Color = content, contentPressed: Color = content, contentHovered: Color = content, iconTint: Color = IntUiLightTheme.colors.grey(7), iconTintDisabled: Color = IntUiLightTheme.colors.grey(9), iconTintFocused: Color = iconTint, iconTintPressed: Color = iconTint, iconTintHovered: Color = iconTint, ) = DropdownColors( background, backgroundDisabled, backgroundFocused, backgroundPressed, backgroundHovered, content, contentDisabled, contentFocused, contentPressed, contentHovered, border = Color.Transparent, borderDisabled = Color.Transparent, borderFocused = Color.Transparent, borderPressed = Color.Transparent, borderHovered = Color.Transparent, iconTint, iconTintDisabled, iconTintFocused, iconTintPressed, iconTintHovered, ) @Composable fun dark( background: Color = Color.Transparent, backgroundDisabled: Color = background, backgroundFocused: Color = background, backgroundPressed: Color = Color(0x0D000000), // Not a palette color backgroundHovered: Color = backgroundPressed, content: Color = IntUiDarkTheme.colors.grey(12), contentDisabled: Color = IntUiDarkTheme.colors.grey(7), contentFocused: Color = content, contentPressed: Color = content, contentHovered: Color = content, iconTint: Color = IntUiDarkTheme.colors.grey(10), iconTintDisabled: Color = IntUiDarkTheme.colors.grey(6), iconTintFocused: Color = iconTint, iconTintPressed: Color = iconTint, iconTintHovered: Color = iconTint, ) = DropdownColors( background, backgroundDisabled, backgroundFocused, backgroundPressed, backgroundHovered, content, contentDisabled, contentFocused, contentPressed, contentHovered, border = Color.Transparent, borderDisabled = Color.Transparent, borderFocused = Color.Transparent, borderPressed = Color.Transparent, borderHovered = Color.Transparent, iconTint, iconTintDisabled, iconTintFocused, iconTintPressed, iconTintHovered, ) } fun DropdownMetrics.Companion.default( arrowMinSize: DpSize = DpSize((23 + 3).dp, 24.dp), minSize: DpSize = DpSize((49 + 23 + 6).dp, 24.dp), cornerSize: CornerSize = CornerSize(4.dp), contentPadding: PaddingValues = PaddingValues(horizontal = 6.dp, vertical = 3.dp), borderWidth: Dp = 1.dp, ) = DropdownMetrics( arrowMinSize, minSize, cornerSize, contentPadding, borderWidth, ) fun DropdownMetrics.Companion.undecorated( arrowMinSize: DpSize = DpSize((23 + 3).dp, 24.dp), minSize: DpSize = DpSize((49 + 23 + 6).dp, 24.dp), cornerSize: CornerSize = CornerSize(4.dp), contentPadding: PaddingValues = PaddingValues(horizontal = 6.dp, vertical = 3.dp), borderWidth: Dp = 0.dp, ) = DropdownMetrics( arrowMinSize, minSize, cornerSize, contentPadding, borderWidth, ) fun DropdownIcons.Companion.defaults( chevronDown: PainterProvider = standalonePainterProvider("expui/general/chevronDown.svg"), ) = DropdownIcons(chevronDown)
62
null
28
623
0ac4e0244cdf62255243e15d323df46eb255e0b7
10,262
jewel
Apache License 2.0
kodando-react-dom/src/main/kotlin/kodando/react/dom/events/SyntheticEvent.kt
kodando
81,663,289
false
null
package kodando.react.dom.events import org.w3c.dom.Node import org.w3c.dom.events.Event import org.w3c.dom.events.EventTarget import kotlin.js.Date /** * Created by danfma on 02/06/2016. */ external interface SyntheticEvent<TNode : Node> { var currentTarget: TNode var bubbles: Boolean? var cancelable: Boolean? var defaultPrevented: Boolean? var eventPhase: Number? var isTrusted: Boolean? var nativeEvent: Event? var target: EventTarget? var timeStamp: Date? var type: String? fun preventDefault(): Unit fun stopPropagation(): Unit }
12
Kotlin
5
76
f1428066ca01b395c1611717fde5463ba0042b19
566
kodando
MIT License
plugins/kotlin/j2k/new/tests/testData/newJ2k/docComments/primaryConstructorDoc.kt
ingokegel
72,937,917
false
null
/** * This constructor is especially useful */ internal class CtorComment { var myA: String = "str" } internal class CtorComment2 /** * This constructor is especially useful */
284
null
5162
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
186
intellij-community
Apache License 2.0
compose/ui/ui/integration-tests/ui-demos/src/main/java/androidx/compose/ui/demos/MultipleCollect.kt
RikkaW
389,105,112
false
null
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("PLUGIN_WARNING") package androidx.compose.ui.demos import androidx.compose.foundation.layout.Box import androidx.compose.foundation.background import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.ui.layout.Layout import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.layoutId import androidx.compose.ui.unit.Constraints @Composable fun HeaderFooterLayout( header: @Composable () -> Unit, footer: @Composable () -> Unit, content: @Composable () -> Unit ) { Layout({ Box(Modifier.layoutId("header")) { header() } Box(Modifier.layoutId("footer")) { footer() } content() }) { measurables, constraints -> val headerPlaceable = measurables.first { it.layoutId == "header" }.measure( Constraints.fixed(constraints.maxWidth, 100) ) val footerPadding = 50 val footerPlaceable = measurables.first { it.layoutId == "footer" }.measure( Constraints.fixed(constraints.maxWidth - footerPadding * 2, 100) ) val contentMeasurables = measurables.filter { it.layoutId == null } val itemHeight = (constraints.maxHeight - headerPlaceable.height - footerPlaceable.height) / contentMeasurables.size val contentPlaceables = contentMeasurables.map { measurable -> measurable.measure(Constraints.fixed(constraints.maxWidth, itemHeight)) } layout(constraints.maxWidth, constraints.maxHeight) { headerPlaceable.placeRelative(0, 0) footerPlaceable.placeRelative( footerPadding, constraints.maxHeight - footerPlaceable.height ) var top = headerPlaceable.height contentPlaceables.forEach { placeable -> placeable.placeRelative(0, top) top += itemHeight } } } } @Composable fun MultipleCollectTest() { val header = @Composable { Box(Modifier.fillMaxSize().background(Color(android.graphics.Color.GRAY))) } val footer = @Composable { Box(Modifier.fillMaxSize().background(Color(android.graphics.Color.BLUE))) } HeaderFooterLayout(header = header, footer = footer) { Box(Modifier.fillMaxSize().background(Color(android.graphics.Color.GREEN))) Box(Modifier.fillMaxSize().background(Color(android.graphics.Color.YELLOW))) } }
29
null
937
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
3,147
androidx
Apache License 2.0
app/src/main/java/com/teobaranga/monica/contacts/data/MultipleContactsResponse.kt
teobaranga
686,113,276
false
{"Kotlin": 269714}
package com.teobaranga.monica.contacts.data import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import com.teobaranga.monica.data.common.MetaResponse @JsonClass(generateAdapter = true) data class MultipleContactsResponse( @Json(name = "data") val data: List<ContactResponse>, @Json(name = "meta") val meta: MetaResponse, )
1
Kotlin
1
8
b14afe98fc1d5eb67782ad106aeee607ab267c80
356
monica
Apache License 2.0
src/commonMain/kotlin/data/items/MercilessGladiatorsSilkAmice.kt
marisa-ashkandi
332,658,265
false
null
package `data`.items import `data`.Constants import `data`.buffs.Buffs import `data`.itemsets.ItemSets import `data`.model.Color import `data`.model.Item import `data`.model.ItemSet import `data`.model.Socket import `data`.model.SocketBonus import `data`.socketbonus.SocketBonuses import character.Buff import character.Stats import kotlin.Array import kotlin.Boolean import kotlin.Double import kotlin.Int import kotlin.String import kotlin.collections.List import kotlin.js.JsExport @JsExport public class MercilessGladiatorsSilkAmice : Item() { public override var isAutoGenerated: Boolean = true public override var id: Int = 32047 public override var name: String = "Merciless Gladiator's Silk Amice" public override var itemLevel: Int = 136 public override var quality: Int = 4 public override var icon: String = "inv_shoulder_19.jpg" public override var inventorySlot: Int = 3 public override var itemSet: ItemSet? = ItemSets.byId(579) public override var itemClass: Constants.ItemClass? = Constants.ItemClass.ARMOR public override var itemSubclass: Constants.ItemSubclass? = Constants.ItemSubclass.CLOTH public override var allowableClasses: Array<Constants.AllowableClass>? = arrayOf( Constants.AllowableClass.MAGE ) public override var minDmg: Double = 0.0 public override var maxDmg: Double = 0.0 public override var speed: Double = 0.0 public override var stats: Stats = Stats( stamina = 46, intellect = 15, armor = 171, spellCritRating = 14.0, resilienceRating = 23.0 ) public override var sockets: Array<Socket> = arrayOf( Socket(Color.BLUE), Socket(Color.YELLOW) ) public override var socketBonus: SocketBonus? = SocketBonuses.byId(2859) public override var phase: Int = 2 public override val buffs: List<Buff> by lazy { listOfNotNull( Buffs.byIdOrName(18053, "Increase Spell Dam 36", this) )} }
21
Kotlin
11
25
9cb6a0e51a650b5d04c63883cb9bf3f64057ce73
1,960
tbcsim
MIT License
android/src/main/java/com/samelody/samples/android/features/main/MainFragment.kt
belinwu
140,991,591
false
{"Gradle Kotlin DSL": 8, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 6, "Batchfile": 1, "Markdown": 1, "Proguard": 4, "Java": 2, "XML": 30, "INI": 2, "Kotlin": 53}
package com.samelody.samples.android.features.main import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import com.samelody.samples.android.R class MainFragment : Fragment() { companion object { @JvmStatic fun newInstance() = MainFragment() } private val viewModel: MainViewModel by viewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return inflater.inflate(R.layout.main_fragment, container, false) } }
0
Kotlin
0
2
dce2b98cb031df6bbf04cfc576541a2d96134b5d
710
samples
Apache License 2.0
src/main/java/io/github/hotlava03/baclava4j/commands/CommandExecutor.kt
tierrif
222,762,402
false
{"Kotlin": 15895}
package io.github.hotlava03.baclava4j.commands abstract class CommandExecutor { abstract fun onCommand(e: CommandEvent?) }
0
Kotlin
0
0
8b1c0886ac87c9a2d21aa276008275cfd99b3d45
127
Baclava4j
Apache License 2.0
app/src/main/java/com/taro/aimentor/onboarding/OnboardingActivity.kt
Gear61
623,306,992
false
null
package com.taro.aimentor.onboarding import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.taro.aimentor.R import com.taro.aimentor.databinding.OnboardingPageBinding import com.taro.aimentor.home.MainActivity import com.taro.aimentor.persistence.PreferencesManager import com.taro.aimentor.util.UIUtil class OnboardingActivity: AppCompatActivity() { companion object { const val NUM_QUESTIONS = 3f } private lateinit var binding: OnboardingPageBinding private lateinit var preferencesManager: PreferencesManager private lateinit var fragmentController: OnboardingFragmentController private var questionNumber = 1 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = OnboardingPageBinding.inflate(layoutInflater) setContentView(binding.root) preferencesManager = PreferencesManager.getInstance(this) fragmentController = OnboardingFragmentController( fragmentManager = supportFragmentManager, containerId = R.id.container ) fragmentController.onStateChange(newState = OnboardingAskState.OCCUPATION) setProgress() bindSubmitButton() } private fun setProgress() { val progress = (questionNumber.toFloat() / NUM_QUESTIONS) * 100f binding.progressBar.setProgressCompat(progress.toInt(), true) } private fun bindSubmitButton() { binding.submitButton.setOnClickListener { if (!isInputValid()) { return@setOnClickListener } when (questionNumber) { 1 -> { if (preferencesManager.occupation == getString(R.string.student)) { fragmentController.onStateChange(newState = OnboardingAskState.FIELD_OF_STUDY) } else { fragmentController.onStateChange(newState = OnboardingAskState.YEARS_OF_EXPERIENCE) } } 2 -> { fragmentController.onStateChange(newState = OnboardingAskState.INTERVIEW_STATUS) } 3 -> { startActivity(Intent(this, MainActivity::class.java)) finish() } } questionNumber += 1 setProgress() } } private fun isInputValid(): Boolean { when (fragmentController.currentState) { OnboardingAskState.OCCUPATION -> { if (preferencesManager.occupation.isBlank()) { UIUtil.showLongToast( stringId = R.string.no_occupation_error_message, context = this ) return false } return true } OnboardingAskState.YEARS_OF_EXPERIENCE -> { if (preferencesManager.yearsOfExperience < 0) { UIUtil.showLongToast( stringId = R.string.no_yoe_error_message, context = this ) return false } return true } OnboardingAskState.FIELD_OF_STUDY -> { if (preferencesManager.fieldOfStudy.isBlank()) { UIUtil.showLongToast( stringId = R.string.no_field_of_study_error_message, context = this ) return false } return true } else -> return true } } }
0
Kotlin
1
16
9931bb96adf2bf2c76862fdbcd6e29fad9eda5e2
3,738
ai-mentor-android
Apache License 2.0
smithy-swift-codegen/src/main/kotlin/software/amazon/smithy/swift/codegen/integration/serde/UnionEncodeGeneratorStrategy.kt
smithy-lang
242,852,561
false
{"Kotlin": 1325611, "Swift": 499776, "Smithy": 113078}
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package software.amazon.smithy.swift.codegen.integration.serde import software.amazon.smithy.aws.traits.protocols.RestXmlTrait import software.amazon.smithy.model.shapes.MemberShape import software.amazon.smithy.model.traits.TimestampFormatTrait import software.amazon.smithy.swift.codegen.SwiftWriter import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.serde.json.UnionEncodeGenerator import software.amazon.smithy.swift.codegen.integration.serde.xml.UnionEncodeXMLGenerator class UnionEncodeGeneratorStrategy( private val ctx: ProtocolGenerator.GenerationContext, private val members: List<MemberShape>, private val writer: SwiftWriter, private val defaultTimestampFormat: TimestampFormatTrait.Format ) { fun render() { when (ctx.protocol) { RestXmlTrait.ID -> { UnionEncodeXMLGenerator(ctx, members, writer, defaultTimestampFormat).render() } else -> { UnionEncodeGenerator(ctx, members, writer, defaultTimestampFormat).render() } } } }
11
Kotlin
26
27
88529feec7b618eede831a82729f732f691e05fc
1,258
smithy-swift
Apache License 2.0
domain/src/main/kotlin/com/example/core/pt/port/out/PtJpaPort.kt
PARKPARKWOO
737,782,254
false
{"Kotlin": 354106, "Dockerfile": 124}
package com.example.core.pt.port.out import com.example.core.pt.command.SavePtCommand import com.example.core.pt.model.AiPt import java.util.UUID interface PtJpaPort { fun save(command: SavePtCommand): AiPt fun findByThisWeek(memberId: UUID): AiPt? }
13
Kotlin
0
0
f422abce0bde8d9bc654e47678756c3e0a987a27
262
barbellrobot-backend
Apache License 2.0
app/src/test/kotlin/com/cesarvaliente/kunidirectional/edititem/EditItemControllerViewTest.kt
CesarValiente
88,026,476
false
null
/** * Copyright (C) 2017 <NAME> & <NAME> * * https://github.com/CesarValiente * https://github.com/coshaw * * 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.cesarvaliente.kunidirectional.edititem import com.cesarvaliente.kunidirectional.COLOR import com.cesarvaliente.kunidirectional.FAVORITE import com.cesarvaliente.kunidirectional.LOCAL_ID import com.cesarvaliente.kunidirectional.POSITION import com.cesarvaliente.kunidirectional.TEXT import com.cesarvaliente.kunidirectional.TestStore import com.cesarvaliente.kunidirectional.createItem import com.cesarvaliente.kunidirectional.store.Color import com.cesarvaliente.kunidirectional.store.EditItemScreen import com.cesarvaliente.kunidirectional.store.Item import com.cesarvaliente.kunidirectional.store.ItemsListScreen import com.cesarvaliente.kunidirectional.store.Navigation import com.cesarvaliente.kunidirectional.store.State import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.argumentCaptor import com.nhaarman.mockito_kotlin.reset import com.nhaarman.mockito_kotlin.spy import com.nhaarman.mockito_kotlin.times import com.nhaarman.mockito_kotlin.verify import org.hamcrest.CoreMatchers.not import org.junit.After import org.junit.Assert.assertThat import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.MockitoAnnotations import java.lang.ref.WeakReference import org.hamcrest.CoreMatchers.`is` as iz class EditItemControllerViewTest { private @Mock lateinit var editItemViewCallback: EditItemViewCallback private lateinit var editItemControllerView: EditItemControllerView private lateinit var editItemControllerViewSpy: EditItemControllerView private lateinit var store: TestStore @Before fun setup() { MockitoAnnotations.initMocks(this) store = TestStore editItemControllerView = EditItemControllerView( editItemViewCallback = WeakReference(editItemViewCallback), store = store) editItemControllerView.isActivityRunning = true editItemControllerViewSpy = spy(editItemControllerView) store.stateHandlers.add(editItemControllerViewSpy) } @After fun clean() { store.clear() } @Test fun should_create_an_item_and_handle_State() { editItemControllerViewSpy.createItem(localId = LOCAL_ID, text = TEXT, favorite = FAVORITE, color = COLOR, position = POSITION) argumentCaptor<State>().apply { verify(editItemControllerViewSpy).handleState(capture()) with(lastValue.itemsListScreen.items) { assertThat(this, iz(not(emptyList()))) assertThat(this.size, iz(1)) with(component1()) { assertThat(this.localId, iz(LOCAL_ID)) assertThat(this.text, iz(TEXT)) assertThat(this.favorite, iz(FAVORITE)) assertThat(this.color, iz(COLOR)) assertThat(this.position, iz(POSITION)) } } assertThat(lastValue.editItemScreen.currentItem.isEmpty(), iz(true)) assertThat(lastValue.navigation, iz(Navigation.ITEMS_LIST)) } } @Test fun should_update_an_item_and_handle_State() { val item1 = createItem(1) val state = State(itemsListScreen = ItemsListScreen(listOf(item1)), editItemScreen = EditItemScreen(item1), navigation = Navigation.EDIT_ITEM) store.dispatch(state) val NEW_TEXT = "new text" editItemControllerViewSpy.updateItem(localId = item1.localId, text = NEW_TEXT, color = Color.GREEN) argumentCaptor<State>().apply { verify(editItemControllerViewSpy, times(2)).handleState(capture()) assertThat(lastValue.itemsListScreen.items, iz(not(emptyList()))) assertThat(lastValue.itemsListScreen.items.size, iz(1)) fun verifyItem(item: Item) = with(item) { assertThat(localId, iz(item1.localId)) assertThat(text, iz(NEW_TEXT)) assertThat(favorite, iz(item1.favorite)) assertThat(color, iz(Color.GREEN)) assertThat(position, iz(item1.position)) } verifyItem(lastValue.itemsListScreen.items.component1()) verifyItem(lastValue.editItemScreen.currentItem) assertThat(lastValue.navigation, iz(Navigation.EDIT_ITEM)) } } @Test fun should_update_Item_color_and_handle_State() { val item1 = createItem(1) val state = State(itemsListScreen = ItemsListScreen(listOf(item1)), editItemScreen = EditItemScreen(item1), navigation = Navigation.EDIT_ITEM) store.dispatch(state) editItemControllerViewSpy.updateColor(localId = item1.localId, color = Color.BLUE) argumentCaptor<State>().apply { verify(editItemControllerViewSpy, times(2)).handleState(capture()) assertThat(lastValue.itemsListScreen.items, iz(not(emptyList()))) assertThat(lastValue.itemsListScreen.items.size, iz(1)) fun verifyItem(item: Item) = with(item) { assertThat(localId, iz(item1.localId)) assertThat(text, iz(item1.text)) assertThat(favorite, iz(item1.favorite)) assertThat(color, iz(Color.BLUE)) assertThat(position, iz(item1.position)) } verifyItem(lastValue.itemsListScreen.items.component1()) verifyItem(lastValue.editItemScreen.currentItem) assertThat(lastValue.navigation, iz(Navigation.EDIT_ITEM)) } } @Test fun should_back_to_Items_list_and_handle_State() { val state = State(navigation = Navigation.EDIT_ITEM) store.dispatch(state) editItemControllerViewSpy.backToItems() argumentCaptor<State>().apply { verify(editItemControllerViewSpy, times(2)).handleState(capture()) assertThat(lastValue.itemsListScreen.items, iz(emptyList())) assertThat(lastValue.editItemScreen.currentItem.isEmpty(), iz(true)) assertThat(lastValue.navigation, iz(Navigation.ITEMS_LIST)) } } @Test fun should_handle_State_and_call_updateItem_function() { val state = State(navigation = Navigation.EDIT_ITEM) editItemControllerView.handleState(state) verify(editItemViewCallback).updateItem(any()) } @Test fun should_handle_State_and_call_backToItemsList_function() { val state = State(navigation = Navigation.ITEMS_LIST) reset(editItemViewCallback) editItemControllerView.handleState(state) verify(editItemViewCallback).backToItemsList() } }
2
null
30
313
81706091f1700165a63eba310a12cedc136ded1f
7,522
KUnidirectional
Apache License 2.0
source/sdk/src/test/java/com/stytch/sdk/b2b/network/StytchB2BApiTest.kt
stytchauth
314,556,359
false
{"Kotlin": 1650258, "HTML": 508}
package com.stytch.sdk.b2b.network import android.app.Application import android.content.Context import com.stytch.sdk.b2b.StytchB2BClient import com.stytch.sdk.b2b.network.models.AllowedAuthMethods import com.stytch.sdk.b2b.network.models.AuthMethods import com.stytch.sdk.b2b.network.models.B2BRequests import com.stytch.sdk.b2b.network.models.EmailInvites import com.stytch.sdk.b2b.network.models.EmailJitProvisioning import com.stytch.sdk.b2b.network.models.MfaMethod import com.stytch.sdk.b2b.network.models.SsoJitProvisioning import com.stytch.sdk.common.DeviceInfo import com.stytch.sdk.common.EncryptionManager import com.stytch.sdk.common.StytchResult import com.stytch.sdk.common.errors.StytchAPIError import com.stytch.sdk.common.errors.StytchSDKNotConfiguredError import com.stytch.sdk.common.network.InfoHeaderModel import com.stytch.sdk.common.network.StytchDataResponse import com.stytch.sdk.common.network.models.CommonRequests import com.stytch.sdk.common.network.models.Locale import io.mockk.clearAllMocks import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every import io.mockk.just import io.mockk.mockk import io.mockk.mockkObject import io.mockk.mockkStatic import io.mockk.runs import io.mockk.unmockkAll import kotlinx.coroutines.runBlocking import org.junit.After import org.junit.Before import org.junit.Test import retrofit2.HttpException import java.security.KeyStore internal class StytchB2BApiTest { var mContextMock = mockk<Context>(relaxed = true) private val mockDeviceInfo = DeviceInfo( applicationPackageName = "com.stytch.test", applicationVersion = "1.0.0", osName = "Android", osVersion = "14", deviceName = "<NAME>", screenSize = "", ) @Before fun before() { val mockApplication: Application = mockk { every { registerActivityLifecycleCallbacks(any()) } just runs every { packageName } returns "Stytch" } mContextMock = mockk(relaxed = true) { every { applicationContext } returns mockApplication } mockkStatic(KeyStore::class) mockkObject(EncryptionManager) mockkObject(StytchB2BApi) every { EncryptionManager.createNewKeys(any(), any()) } returns Unit every { KeyStore.getInstance(any()) } returns mockk(relaxed = true) } @After fun after() { unmockkAll() clearAllMocks() } @Test fun `StytchB2BApi isInitialized returns correctly based on configuration state`() { StytchB2BApi.configure("publicToken", DeviceInfo()) assert(StytchB2BApi.isInitialized) } @Test(expected = StytchSDKNotConfiguredError::class) fun `StytchB2BApi apiService throws exception when not configured`() { every { StytchB2BApi.isInitialized } returns false StytchB2BApi.apiService } @Test fun `StytchB2BApi apiService is available when configured`() { StytchB2BClient.configure(mContextMock, "") StytchB2BApi.apiService } // TODO every method calls safeApi @Test fun `StytchB2BApi MagicLinks Email loginOrCreate calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.loginOrSignupByEmail(any()) } returns mockk(relaxed = true) StytchB2BApi.MagicLinks.Email.loginOrSignupByEmail("", "", "", "", "", "", "", null) coVerify { StytchB2BApi.apiService.loginOrSignupByEmail(any()) } } @Test fun `StytchB2BApi MagicLinks Email authenticate calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.authenticate(any()) } returns mockk(relaxed = true) StytchB2BApi.MagicLinks.Email.authenticate("", 30, "") coVerify { StytchB2BApi.apiService.authenticate(any()) } } @Test fun `StytchB2BApi MagicLinks Email invite calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.sendInviteMagicLink(any()) } returns mockk(relaxed = true) StytchB2BApi.MagicLinks.Email.invite("<EMAIL>") coVerify { StytchB2BApi.apiService.sendInviteMagicLink(any()) } } @Test fun `StytchB2BApi MagicLinks Discovery send calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.sendDiscoveryMagicLink(any()) } returns mockk(relaxed = true) StytchB2BApi.MagicLinks.Discovery.send("", "", "", "", Locale.EN) coVerify { StytchB2BApi.apiService.sendDiscoveryMagicLink(any()) } } @Test fun `StytchB2BApi MagicLinks Discovery authenticate calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.authenticateDiscoveryMagicLink(any()) } returns mockk(relaxed = true) StytchB2BApi.MagicLinks.Discovery.authenticate("", "") coVerify { StytchB2BApi.apiService.authenticateDiscoveryMagicLink(any()) } } @Test fun `StytchB2BApi Sessions authenticate calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.authenticateSessions(any()) } returns mockk(relaxed = true) StytchB2BApi.Sessions.authenticate(30) coVerify { StytchB2BApi.apiService.authenticateSessions(any()) } } @Test fun `StytchB2BApi Sessions revoke calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.revokeSessions() } returns mockk(relaxed = true) StytchB2BApi.Sessions.revoke() coVerify { StytchB2BApi.apiService.revokeSessions() } } @Test fun `StytchB2BApi Sessions exchange calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.exchangeSession(any()) } returns mockk(relaxed = true) StytchB2BApi.Sessions.exchange(organizationId = "test-123", sessionDurationMinutes = 30) coVerify { StytchB2BApi.apiService.exchangeSession(any()) } } @Test fun `StytchB2BApi Organizations getOrganization calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.getOrganization() } returns mockk(relaxed = true) StytchB2BApi.Organization.getOrganization() coVerify { StytchB2BApi.apiService.getOrganization() } } @Test fun `StytchB2BApi Organizations update calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.updateOrganization(any()) } returns mockk(relaxed = true) StytchB2BApi.Organization.updateOrganization() coVerify { StytchB2BApi.apiService.updateOrganization(any()) } } @Test fun `StytchB2BApi Organizations delete calls appropriate apiService method()`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.deleteOrganization() } returns mockk(relaxed = true) StytchB2BApi.Organization.deleteOrganization() coVerify { StytchB2BApi.apiService.deleteOrganization() } } @Test fun `StytchB2BApi Organizations member delete calls appropriate apiService method()`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.deleteOrganizationMember(any()) } returns mockk(relaxed = true) StytchB2BApi.Organization.deleteOrganizationMember("my-member-id") coVerify { StytchB2BApi.apiService.deleteOrganizationMember(any()) } } @Test fun `StytchB2BApi Organizations member reactivate calls appropriate apiService method()`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.reactivateOrganizationMember(any()) } returns mockk(relaxed = true) StytchB2BApi.Organization.reactivateOrganizationMember("my-member-id") coVerify { StytchB2BApi.apiService.reactivateOrganizationMember(any()) } } @Test fun `StytchB2BApi Organization deleteOrganizationMemberMFAPhoneNumber calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.deleteOrganizationMemberMFAPhoneNumber( any(), ) } returns mockk(relaxed = true) StytchB2BApi.Organization.deleteOrganizationMemberMFAPhoneNumber("my-member-id") coVerify { StytchB2BApi.apiService.deleteOrganizationMemberMFAPhoneNumber("my-member-id") } } @Test fun `StytchB2BApi Organization deleteOrganizationMemberMFATOTP calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.deleteOrganizationMemberMFATOTP(any()) } returns mockk(relaxed = true) StytchB2BApi.Organization.deleteOrganizationMemberMFATOTP("my-member-id") coVerify { StytchB2BApi.apiService.deleteOrganizationMemberMFATOTP("my-member-id") } } @Test fun `StytchB2BApi Organization deleteOrganizationMemberPassword calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.deleteOrganizationMemberPassword( any(), ) } returns mockk(relaxed = true) StytchB2BApi.Organization.deleteOrganizationMemberPassword("password-id") coVerify { StytchB2BApi.apiService.deleteOrganizationMemberPassword("password-id") } } @Test fun `StytchB2BApi Organization createOrganizationMember calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.createMember(any()) } returns mockk(relaxed = true) StytchB2BApi.Organization.createOrganizationMember( emailAddress = "[email protected]", name = "Stytch Robot", isBreakGlass = true, mfaEnrolled = true, mfaPhoneNumber = "+15551235555", untrustedMetadata = mapOf("key 1" to "value 1"), createMemberAsPending = true, roles = listOf("my-role", "my-other-role"), ) coVerify { StytchB2BApi.apiService.createMember(any()) } } @Test fun `StytchB2BApi Organization updateOrganizationMember calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.updateOrganizationMember( "my-member-id", any(), ) } returns mockk(relaxed = true) StytchB2BApi.Organization.updateOrganizationMember( memberId = "my-member-id", emailAddress = "[email protected]", name = "Stytch Robot", isBreakGlass = true, mfaEnrolled = true, mfaPhoneNumber = "+15551235555", untrustedMetadata = mapOf("key 1" to "value 1"), roles = listOf("my-role", "my-other-role"), preserveExistingSessions = true, defaultMfaMethod = MfaMethod.SMS, ) coVerify { StytchB2BApi.apiService.updateOrganizationMember("my-member-id", any()) } } @Test fun `StytchB2BApi Organization searchMembers calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.searchMembers(any()) } returns mockk(relaxed = true) StytchB2BApi.Organization.search() coVerify { StytchB2BApi.apiService.searchMembers(any()) } } @Test fun `StytchB2BApi Member get calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.getMember() } returns mockk(relaxed = true) StytchB2BApi.Member.getMember() coVerify { StytchB2BApi.apiService.getMember() } } @Test fun `StytchB2BApi Member update calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.updateMember(any()) } returns mockk(relaxed = true) StytchB2BApi.Member.updateMember("", emptyMap(), false, "", MfaMethod.SMS) coVerify { StytchB2BApi.apiService.updateMember(any()) } } @Test fun `StytchB2BApi Member deleteMFAPhoneNumber calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.deleteMFAPhoneNumber() } returns mockk(relaxed = true) StytchB2BApi.Member.deleteMFAPhoneNumber() coVerify { StytchB2BApi.apiService.deleteMFAPhoneNumber() } } @Test fun `StytchB2BApi Member deleteMFATOTP calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.deleteMFATOTP() } returns mockk(relaxed = true) StytchB2BApi.Member.deleteMFATOTP() coVerify { StytchB2BApi.apiService.deleteMFATOTP() } } @Test fun `StytchB2BApi Member deletePassword calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.deletePassword("passwordId") } returns mockk(relaxed = true) StytchB2BApi.Member.deletePassword("passwordId") coVerify { StytchB2BApi.apiService.deletePassword("passwordId") } } @Test fun `StytchB2BApi Passwords authenticate calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.authenticatePassword(any()) } returns mockk(relaxed = true) StytchB2BApi.Passwords.authenticate("", "", "") coVerify { StytchB2BApi.apiService.authenticatePassword(any()) } } @Test fun `StytchB2BApi Passwords resetByEmailStart calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.resetPasswordByEmailStart(any()) } returns mockk(relaxed = true) StytchB2BApi.Passwords.resetByEmailStart( organizationId = "", emailAddress = "", codeChallenge = "", loginRedirectUrl = null, resetPasswordRedirectUrl = null, resetPasswordExpirationMinutes = null, resetPasswordTemplateId = null, ) coVerify { StytchB2BApi.apiService.resetPasswordByEmailStart(any()) } } @Test fun `StytchB2BApi Passwords resetByEmail calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.resetPasswordByEmail(any()) } returns mockk(relaxed = true) StytchB2BApi.Passwords.resetByEmail(passwordResetToken = "", password = "", codeVerifier = "") coVerify { StytchB2BApi.apiService.resetPasswordByEmail(any()) } } @Test fun `StytchB2BApi Passwords resetByExisting calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.resetPasswordByExisting(any()) } returns mockk(relaxed = true) StytchB2BApi.Passwords.resetByExisting( organizationId = "", emailAddress = "", existingPassword = "", newPassword = "", ) coVerify { StytchB2BApi.apiService.resetPasswordByExisting(any()) } } @Test fun `StytchB2BApi Passwords resetBySession calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.resetPasswordBySession(any()) } returns mockk(relaxed = true) StytchB2BApi.Passwords.resetBySession(organizationId = "", password = "") coVerify { StytchB2BApi.apiService.resetPasswordBySession(any()) } } @Test fun `StytchB2BApi Passwords strengthCheck calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.passwordStrengthCheck(any()) } returns mockk(relaxed = true) StytchB2BApi.Passwords.strengthCheck(email = "", password = "") coVerify { StytchB2BApi.apiService.passwordStrengthCheck(any()) } } @Test fun `StytchB2BApi Discovery discoverOrganizations calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.discoverOrganizations(any()) } returns mockk(relaxed = true) StytchB2BApi.Discovery.discoverOrganizations(null) coVerify { StytchB2BApi.apiService.discoverOrganizations(any()) } } @Test fun `StytchB2BApi Discovery exchangeSession calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.intermediateSessionExchange(any()) } returns mockk(relaxed = true) StytchB2BApi.Discovery.exchangeSession( intermediateSessionToken = "", organizationId = "", sessionDurationMinutes = 30, ) coVerify { StytchB2BApi.apiService.intermediateSessionExchange(any()) } } @Test fun `StytchB2BApi Discovery createOrganization calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.createOrganization(any()) } returns mockk(relaxed = true) StytchB2BApi.Discovery.createOrganization( intermediateSessionToken = "", organizationLogoUrl = "", organizationSlug = "", organizationName = "", sessionDurationMinutes = 30, ssoJitProvisioning = SsoJitProvisioning.ALL_ALLOWED, emailJitProvisioning = EmailJitProvisioning.RESTRICTED, emailInvites = EmailInvites.ALL_ALLOWED, emailAllowedDomains = listOf("allowed-domain.com"), authMethods = AuthMethods.RESTRICTED, allowedAuthMethods = listOf(AllowedAuthMethods.PASSWORD, AllowedAuthMethods.MAGIC_LINK), ) val expectedParams = B2BRequests.Discovery.CreateRequest( intermediateSessionToken = "", organizationLogoUrl = "", organizationSlug = "", organizationName = "", sessionDurationMinutes = 30, ssoJitProvisioning = SsoJitProvisioning.ALL_ALLOWED, emailJitProvisioning = EmailJitProvisioning.RESTRICTED, emailInvites = EmailInvites.ALL_ALLOWED, emailAllowedDomains = listOf("allowed-domain.com"), authMethods = AuthMethods.RESTRICTED, allowedAuthMethods = listOf(AllowedAuthMethods.PASSWORD, AllowedAuthMethods.MAGIC_LINK), ) coVerify { StytchB2BApi.apiService.createOrganization(expectedParams) } } @Test fun `StytchB2BApi SSO authenticate calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.ssoAuthenticate(any()) } returns mockk(relaxed = true) StytchB2BApi.SSO.authenticate( ssoToken = "", sessionDurationMinutes = 30, codeVerifier = "", ) coVerify { StytchB2BApi.apiService.ssoAuthenticate(any()) } } @Test fun `StytchB2BApi SSO getConnections calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.ssoGetConnections() } returns mockk(relaxed = true) StytchB2BApi.SSO.getConnections() coVerify { StytchB2BApi.apiService.ssoGetConnections() } } @Test fun `StytchB2BApi SSO deleteConnection calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.ssoDeleteConnection(any()) } returns mockk(relaxed = true) val connectionId = "my-connection-id" StytchB2BApi.SSO.deleteConnection(connectionId = connectionId) coVerify { StytchB2BApi.apiService.ssoDeleteConnection(connectionId) } } @Test fun `StytchB2BApi SSO SAML createConnection calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.ssoSamlCreate(any()) } returns mockk(relaxed = true) val displayName = "my cool saml connection" StytchB2BApi.SSO.samlCreateConnection(displayName = displayName) coVerify { StytchB2BApi.apiService.ssoSamlCreate( B2BRequests.SSO.SAMLCreateRequest(displayName = displayName), ) } } @Test fun `StytchB2BApi SSO SAML updateConnection calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.ssoSamlUpdate(any(), any()) } returns mockk(relaxed = true) val connectionId = "my-connection-id" StytchB2BApi.SSO.samlUpdateConnection(connectionId = connectionId) coVerify { StytchB2BApi.apiService.ssoSamlUpdate(connectionId = connectionId, any()) } } @Test fun `StytchB2BApi SSO SAML updateConnectionByUrl calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.ssoSamlUpdateByUrl(any(), any()) } returns mockk(relaxed = true) val connectionId = "my-connection-id" val metadataUrl = "metadata.url" StytchB2BApi.SSO.samlUpdateByUrl(connectionId = connectionId, metadataUrl = metadataUrl) coVerify { StytchB2BApi.apiService.ssoSamlUpdateByUrl(connectionId = connectionId, any()) } } @Test fun `StytchB2BApi SSO SAML samlDeleteVerificationCertificate calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.ssoSamlDeleteVerificationCertificate( any(), any(), ) } returns mockk(relaxed = true) val connectionId = "my-connection-id" val certificateId = "mt-certificate-id" StytchB2BApi.SSO.samlDeleteVerificationCertificate( connectionId = connectionId, certificateId = certificateId, ) coVerify { StytchB2BApi.apiService.ssoSamlDeleteVerificationCertificate( connectionId = connectionId, certificateId = certificateId, ) } } @Test fun `StytchB2BApi SSO OIDC createConnection calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.ssoOidcCreate(any()) } returns mockk(relaxed = true) val displayName = "my cool oidc connection" StytchB2BApi.SSO.oidcCreateConnection(displayName = displayName) coVerify { StytchB2BApi.apiService.ssoOidcCreate( B2BRequests.SSO.OIDCCreateRequest(displayName = displayName), ) } } @Test fun `StytchB2BApi SSO OIDC updateConnection calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.ssoOidcUpdate(any(), any()) } returns mockk(relaxed = true) val connectionId = "my-cool-oidc-connection" StytchB2BApi.SSO.oidcUpdateConnection(connectionId = connectionId) coVerify { StytchB2BApi.apiService.ssoOidcUpdate( connectionId = connectionId, request = B2BRequests.SSO.OIDCUpdateRequest(connectionId = connectionId), ) } } @Test fun `StytchB2BApi Bootstrap getBootstrapData calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true every { StytchB2BApi.publicToken } returns "mock-public-token" coEvery { StytchB2BApi.apiService.getBootstrapData("mock-public-token") } returns mockk(relaxed = true) StytchB2BApi.getBootstrapData() coVerify { StytchB2BApi.apiService.getBootstrapData("mock-public-token") } } @Test fun `StytchB2BApi Events logEvent calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true every { StytchB2BApi.publicToken } returns "mock-public-token" coEvery { StytchB2BApi.apiService.logEvent(any()) } returns mockk(relaxed = true) val details = mapOf("test-key" to "test value") val header = InfoHeaderModel.fromDeviceInfo(mockDeviceInfo) StytchB2BApi.Events.logEvent( eventId = "event-id", appSessionId = "app-session-id", persistentId = "persistent-id", clientSentAt = "ISO date string", timezone = "Timezone/Identifier", eventName = "event-name", infoHeaderModel = header, details = details, ) coVerify(exactly = 1) { StytchB2BApi.apiService.logEvent( listOf( CommonRequests.Events.Event( telemetry = CommonRequests.Events.EventTelemetry( eventId = "event-id", appSessionId = "app-session-id", persistentId = "persistent-id", clientSentAt = "ISO date string", timezone = "Timezone/Identifier", app = CommonRequests.Events.VersionIdentifier( identifier = header.app.identifier, version = header.app.version, ), os = CommonRequests.Events.VersionIdentifier( identifier = header.os.identifier, version = header.os.version, ), sdk = CommonRequests.Events.VersionIdentifier( identifier = header.sdk.identifier, version = header.sdk.version, ), device = CommonRequests.Events.DeviceIdentifier( model = header.device.identifier, screenSize = header.device.version, ), ), event = CommonRequests.Events.EventEvent( publicToken = "mock-public-token", eventName = "event-name", details = details, ), ), ), ) } } @Test fun `StytchB2BApi OTP sendSMSOTP calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.sendSMSOTP(any()) } returns mockk(relaxed = true) StytchB2BApi.OTP.sendSMSOTP("", "") coVerify { StytchB2BApi.apiService.sendSMSOTP(any()) } } @Test fun `StytchB2BApi OTP authenticateSMSOTP calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.authenticateSMSOTP(any()) } returns mockk(relaxed = true) StytchB2BApi.OTP.authenticateSMSOTP("", "", "", null, 30) coVerify { StytchB2BApi.apiService.authenticateSMSOTP(any()) } } @Test fun `StytchB2BApi TOTP create calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.createTOTP(any()) } returns mockk(relaxed = true) StytchB2BApi.TOTP.create("", "") coVerify { StytchB2BApi.apiService.createTOTP(any()) } } @Test fun `StytchB2BApi TOTP authenticate calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.authenticateTOTP(any()) } returns mockk(relaxed = true) StytchB2BApi.TOTP.authenticate("", "", "", null, null, 30) coVerify { StytchB2BApi.apiService.authenticateTOTP(any()) } } @Test fun `StytchB2BApi RecoveryCodes get calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.getRecoveryCodes() } returns mockk(relaxed = true) StytchB2BApi.RecoveryCodes.get() coVerify { StytchB2BApi.apiService.getRecoveryCodes() } } @Test fun `StytchB2BApi RecoveryCodes rotate calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.rotateRecoveryCodes() } returns mockk(relaxed = true) StytchB2BApi.RecoveryCodes.rotate() coVerify { StytchB2BApi.apiService.rotateRecoveryCodes() } } @Test fun `StytchB2BApi RecoveryCodes recover calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.recoverRecoveryCodes(any()) } returns mockk(relaxed = true) StytchB2BApi.RecoveryCodes.recover("", "", 30, "") coVerify { StytchB2BApi.apiService.recoverRecoveryCodes(any()) } } @Test fun `StytchB2BApi OAuth authenticate calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.oauthAuthenticate(any()) } returns mockk(relaxed = true) StytchB2BApi.OAuth.authenticate("", Locale.EN, 30, "", "") coVerify { StytchB2BApi.apiService.oauthAuthenticate(any()) } } @Test fun `StytchB2BApi OAuth discoveryAuthenticate calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.oauthDiscoveryAuthenticate(any()) } returns mockk(relaxed = true) StytchB2BApi.OAuth.discoveryAuthenticate("", "") coVerify { StytchB2BApi.apiService.oauthDiscoveryAuthenticate(any()) } } @Test fun `StytchB2BApi SearchManager searchOrganizations calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.searchOrganizations(any()) } returns mockk(relaxed = true) StytchB2BApi.SearchManager.searchOrganizations("organization-slug") coVerify { StytchB2BApi.apiService.searchOrganizations(any()) } } @Test fun `StytchB2BApi SearchManager searchOrganizationMembers calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.searchOrganizationMembers(any()) } returns mockk(relaxed = true) StytchB2BApi.SearchManager.searchMembers("[email protected]", "organization-id") coVerify { StytchB2BApi.apiService.searchOrganizationMembers(any()) } } @Test fun `StytchB2BApi SCIM createConnection calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.scimCreateConnection(any()) } returns mockk(relaxed = true) StytchB2BApi.SCIM.createConnection("", "") coVerify { StytchB2BApi.apiService.scimCreateConnection(any()) } } @Test fun `StytchB2BApi SCIM updateConnection calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.scimUpdateConnection(any(), any()) } returns mockk(relaxed = true) StytchB2BApi.SCIM.updateConnection("connection-id", "", "", emptyList()) coVerify { StytchB2BApi.apiService.scimUpdateConnection(eq("connection-id"), any()) } } @Test fun `StytchB2BApi SCIM deleteConection calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.scimDeleteConnection(any()) } returns mockk(relaxed = true) StytchB2BApi.SCIM.deleteConection("connection-id") coVerify { StytchB2BApi.apiService.scimDeleteConnection(eq("connection-id")) } } @Test fun `StytchB2BApi SCIM getConnection calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.scimGetConnection() } returns mockk(relaxed = true) StytchB2BApi.SCIM.getConnection() coVerify { StytchB2BApi.apiService.scimGetConnection() } } @Test fun `StytchB2BApi SCIM getConnectionGroups calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.scimGetConnectionGroups(any()) } returns mockk(relaxed = true) StytchB2BApi.SCIM.getConnectionGroups("", 1000) coVerify { StytchB2BApi.apiService.scimGetConnectionGroups(any()) } } @Test fun `StytchB2BApi SCIM rotateStart calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.scimRotateStart(any()) } returns mockk(relaxed = true) StytchB2BApi.SCIM.rotateStart("connection-id") coVerify { StytchB2BApi.apiService.scimRotateStart(any()) } } @Test fun `StytchB2BApi SCIM rotateCancel calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.scimRotateCancel(any()) } returns mockk(relaxed = true) StytchB2BApi.SCIM.rotateCancel("connection-id") coVerify { StytchB2BApi.apiService.scimRotateCancel(any()) } } @Test fun `StytchB2BApi SCIM rotateComplete calls appropriate apiService method`() = runBlocking { every { StytchB2BApi.isInitialized } returns true coEvery { StytchB2BApi.apiService.scimRotateComplete(any()) } returns mockk(relaxed = true) StytchB2BApi.SCIM.rotateComplete("connection-id") coVerify { StytchB2BApi.apiService.scimRotateComplete(any()) } } @Test(expected = StytchSDKNotConfiguredError::class) fun `safeApiCall throws exception when StytchB2BClient is not initialized`(): Unit = runBlocking { every { StytchB2BApi.isInitialized } returns false val mockApiCall: suspend () -> StytchDataResponse<Boolean> = mockk() StytchB2BApi.safeB2BApiCall { mockApiCall() } } @Test fun `safeApiCall returns success when call succeeds`() = runBlocking { every { StytchB2BApi.isInitialized } returns true fun mockApiCall(): StytchDataResponse<Boolean> = StytchDataResponse(true) val result = StytchB2BApi.safeB2BApiCall { mockApiCall() } assert(result is StytchResult.Success) } @Test fun `safeApiCall returns correct error for HttpException`() = runBlocking { every { StytchB2BApi.isInitialized } returns true fun mockApiCall(): StytchDataResponse<Boolean> = throw HttpException( mockk(relaxed = true) { every { errorBody() } returns null }, ) val result = StytchB2BApi.safeB2BApiCall { mockApiCall() } assert(result is StytchResult.Error) } @Test fun `safeApiCall returns correct error for StytchErrors`() = runBlocking { every { StytchB2BApi.isInitialized } returns true fun mockApiCall(): StytchDataResponse<Boolean> = throw StytchAPIError(errorType = "", message = "") val result = StytchB2BApi.safeB2BApiCall { mockApiCall() } assert(result is StytchResult.Error) } @Test fun `safeApiCall returns correct error for other exceptions`() = runBlocking { every { StytchB2BApi.isInitialized } returns true fun mockApiCall(): StytchDataResponse<Boolean> { error("Test") } val result = StytchB2BApi.safeB2BApiCall { mockApiCall() } assert(result is StytchResult.Error) } }
4
Kotlin
2
23
bebbad4dcb86b2746f7a765fa3dcb867e79d4b6f
40,675
stytch-android
MIT License
plugin-dotnet-agent/src/test/kotlin/jetbrains/buildServer/dotnet/test/dotnet/DotnetEnvironmentVariablesTest.kt
JetBrains
49,584,664
false
null
/* * Copyright 2000-2023 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 jetbrains.buildServer.dotnet.test.dotnet import io.mockk.MockKAnnotations import io.mockk.clearAllMocks import io.mockk.every import io.mockk.impl.annotations.MockK import jetbrains.buildServer.agent.* import jetbrains.buildServer.agent.runner.PathType import jetbrains.buildServer.agent.runner.PathsService import jetbrains.buildServer.agent.Version import jetbrains.buildServer.agent.runner.ParameterType import jetbrains.buildServer.agent.runner.ParametersService import jetbrains.buildServer.dotnet.* import jetbrains.buildServer.dotnet.DotnetEnvironmentVariables.Companion.UseSharedCompilationEnvVarName import jetbrains.buildServer.dotnet.logging.LoggerResolver import jetbrains.buildServer.util.OSType import org.testng.Assert import org.testng.annotations.BeforeMethod import org.testng.annotations.DataProvider import org.testng.annotations.Test import java.io.File class EnvironmentVariablesTest { @MockK private lateinit var _environment: Environment @MockK private lateinit var _parametersService: ParametersService @MockK private lateinit var _pathsService: PathsService @MockK private lateinit var _nugetEnvironmentVariables: EnvironmentVariables @MockK private lateinit var _virtualContext: VirtualContext @MockK private lateinit var _loggerResolver: LoggerResolver private val _tmpPath = File("Tmp") @BeforeMethod fun setUp() { MockKAnnotations.init(this) clearAllMocks() every { _nugetEnvironmentVariables.getVariables(any()) } returns emptySequence() every { _virtualContext.resolvePath(any()) } answers { "v_" + arg<String>(0) } every { _parametersService.tryGetParameter(ParameterType.Environment, UseSharedCompilationEnvVarName) } returns null every { _parametersService.tryGetParameter(ParameterType.Configuration, DotnetConstants.PARAM_MESSAGES_GUARD) } returns null every { _loggerResolver.resolve(ToolType.MSBuild) } returns File("msbuild_logger"); every { _loggerResolver.resolve(ToolType.VSTest) } returns File("vstest_logger"); every { _pathsService.getPath(PathType.AgentTemp) } returns _tmpPath } @Test fun shouldProvideDefaultVars() { // Given val environmentVariables = createInstance() val systemPath = File("system") val nugetPath = File(File(systemPath, "dotnet"), ".nuget").absolutePath // When every { _environment.os } returns OSType.WINDOWS every { _environment.tryGetVariable("USERPROFILE") } returns "path" every { _pathsService.getPath(PathType.System) } returns systemPath every { _nugetEnvironmentVariables.getVariables(any()) } returns sequenceOf(CommandLineEnvironmentVariable("NUGET_VAR", nugetPath)) every { _virtualContext.isVirtual } returns false every { _virtualContext.targetOSType } returns OSType.WINDOWS val actualVariables = environmentVariables.getVariables(Version(1, 2, 3)).toList() // Then Assert.assertEquals(actualVariables, (DotnetEnvironmentVariables.defaultVariables + commonVars + sequenceOf(CommandLineEnvironmentVariable(UseSharedCompilationEnvVarName, "false"), CommandLineEnvironmentVariable("NUGET_VAR", nugetPath))).toList()) } @Test fun shouldNotPublishedMessageGuardPathWhenItIsNotAllowed() { // Given val environmentVariables = createInstance() val systemPath = File("system") val nugetPath = File(File(systemPath, "dotnet"), ".nuget").absolutePath // When every { _environment.os } returns OSType.WINDOWS every { _environment.tryGetVariable("USERPROFILE") } returns "path" every { _pathsService.getPath(PathType.System) } returns systemPath every { _nugetEnvironmentVariables.getVariables(any()) } returns sequenceOf(CommandLineEnvironmentVariable("NUGET_VAR", nugetPath)) every { _virtualContext.isVirtual } returns false every { _virtualContext.targetOSType } returns OSType.WINDOWS every { _parametersService.tryGetParameter(ParameterType.Configuration, DotnetConstants.PARAM_MESSAGES_GUARD) } returns "false" val actualVariables = environmentVariables.getVariables(Version(1, 2, 3)).toList() // Then Assert.assertEquals( actualVariables, ( DotnetEnvironmentVariables.defaultVariables + sequenceOf( CommandLineEnvironmentVariable(DotnetEnvironmentVariables.MSBuildLoggerEnvVar, File("msbuild_logger").canonicalPath), CommandLineEnvironmentVariable(DotnetEnvironmentVariables.VSTestLoggerEnvVar, File("vstest_logger").canonicalPath)) + sequenceOf( CommandLineEnvironmentVariable(UseSharedCompilationEnvVarName, "false"), CommandLineEnvironmentVariable("NUGET_VAR", nugetPath)) ).toList() ) } @Test fun shouldNotUseSharedCompilationByDefault() { // Given val environmentVariables = createInstance() val systemPath = File("system") // When every { _environment.os } returns OSType.WINDOWS every { _environment.tryGetVariable("USERPROFILE") } returns "path" every { _pathsService.getPath(PathType.System) } returns systemPath every { _virtualContext.isVirtual } returns false every { _virtualContext.targetOSType } returns OSType.WINDOWS val actualVariables = environmentVariables.getVariables(Version(1, 2, 3)).toList() // Then Assert.assertEquals(actualVariables, (DotnetEnvironmentVariables.defaultVariables + commonVars + sequenceOf(CommandLineEnvironmentVariable(UseSharedCompilationEnvVarName, "false"))).toList()) } @Test fun shouldUseSharedCompilationWhenThisParameterWasOverridedInEnvVars() { // Given val environmentVariables = createInstance() val systemPath = File("system") // When every { _environment.os } returns OSType.WINDOWS every { _environment.tryGetVariable("USERPROFILE") } returns "path" every { _pathsService.getPath(PathType.System) } returns systemPath every { _virtualContext.isVirtual } returns false every { _virtualContext.targetOSType } returns OSType.WINDOWS every { _parametersService.tryGetParameter(ParameterType.Environment, UseSharedCompilationEnvVarName) } returns "true" val actualVariables = environmentVariables.getVariables(Version(1, 2, 3)).toList() // Then Assert.assertEquals(actualVariables, (DotnetEnvironmentVariables.defaultVariables + commonVars + sequenceOf(CommandLineEnvironmentVariable(UseSharedCompilationEnvVarName, "true"))).toList()) } @DataProvider(name = "osTypesData") fun osTypesData(): Array<Array<OSType>> { return arrayOf( arrayOf(OSType.UNIX), arrayOf(OSType.MAC)) } @Test(dataProvider = "osTypesData") fun shouldProvideDefaultVarsWhenVirtualContextFromWindows(os: OSType) { // Given val environmentVariables = createInstance() val systemPath = File("system") // When every { _environment.os } returns OSType.WINDOWS every { _environment.tryGetVariable("USERPROFILE") } returns "path" every { _pathsService.getPath(PathType.System) } returns systemPath every { _virtualContext.isVirtual } returns true every { _virtualContext.targetOSType } returns os val actualVariables = environmentVariables.getVariables(Version(1, 2, 3)).toList() // Then Assert.assertEquals(actualVariables, (DotnetEnvironmentVariables.defaultVariables + commonVars + sequenceOf(CommandLineEnvironmentVariable(UseSharedCompilationEnvVarName, "false"))).toList()) } @Test fun shouldProvideDefaultVarsWhenVirtualContextForWindowsContainer() { // Given val environmentVariables = createInstance() val systemPath = File("system") // When every { _environment.os } returns OSType.WINDOWS every { _environment.tryGetVariable("USERPROFILE") } returns "path" every { _pathsService.getPath(PathType.System) } returns systemPath every { _virtualContext.isVirtual } returns true every { _virtualContext.targetOSType } returns OSType.WINDOWS val actualVariables = environmentVariables.getVariables(Version(1, 2, 3)).toList() // Then Assert.assertEquals(actualVariables, (DotnetEnvironmentVariables.defaultVariables + commonVars + sequenceOf(CommandLineEnvironmentVariable(UseSharedCompilationEnvVarName, "false"))).toList()) } @Test fun shouldOverrideDefaultNugetPackagesPathWhenSpecifiedAsEnvVar() { // Given val environmentVariables = createInstance() val systemPath = File("system") // When every { _nugetEnvironmentVariables.getVariables(any()) } returns sequenceOf(CommandLineEnvironmentVariable("NUGET_VAR", "custom_nuget_packages_path")) every { _environment.os } returns OSType.WINDOWS every { _environment.tryGetVariable("USERPROFILE") } returns "path" every { _pathsService.getPath(PathType.System) } returns systemPath every { _virtualContext.isVirtual } returns false every { _virtualContext.targetOSType } returns OSType.WINDOWS val actualVariables = environmentVariables.getVariables(Version(1, 2, 3)).toList() // Then Assert.assertEquals(actualVariables, (DotnetEnvironmentVariables.defaultVariables + commonVars + sequenceOf(CommandLineEnvironmentVariable(UseSharedCompilationEnvVarName, "false"), CommandLineEnvironmentVariable("NUGET_VAR", "custom_nuget_packages_path"))).toList()) } private fun createInstance() = DotnetEnvironmentVariables( _environment, _parametersService, _pathsService, _nugetEnvironmentVariables, _loggerResolver, ) private val commonVars = sequenceOf( CommandLineEnvironmentVariable(DotnetEnvironmentVariables.MSBuildLoggerEnvVar, File("msbuild_logger").canonicalPath), CommandLineEnvironmentVariable(DotnetEnvironmentVariables.VSTestLoggerEnvVar, File("vstest_logger").canonicalPath), CommandLineEnvironmentVariable(DotnetEnvironmentVariables.ServiceMessagesPathEnvVar, _tmpPath.canonicalPath) ) }
3
Kotlin
25
91
a19e1b8856a120d6f7f0d85cf7c2161adfae241f
11,060
teamcity-dotnet-plugin
Apache License 2.0
plugin-dotnet-agent/src/test/kotlin/jetbrains/buildServer/dotnet/test/dotnet/DotnetEnvironmentVariablesTest.kt
JetBrains
49,584,664
false
null
/* * Copyright 2000-2023 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 jetbrains.buildServer.dotnet.test.dotnet import io.mockk.MockKAnnotations import io.mockk.clearAllMocks import io.mockk.every import io.mockk.impl.annotations.MockK import jetbrains.buildServer.agent.* import jetbrains.buildServer.agent.runner.PathType import jetbrains.buildServer.agent.runner.PathsService import jetbrains.buildServer.agent.Version import jetbrains.buildServer.agent.runner.ParameterType import jetbrains.buildServer.agent.runner.ParametersService import jetbrains.buildServer.dotnet.* import jetbrains.buildServer.dotnet.DotnetEnvironmentVariables.Companion.UseSharedCompilationEnvVarName import jetbrains.buildServer.dotnet.logging.LoggerResolver import jetbrains.buildServer.util.OSType import org.testng.Assert import org.testng.annotations.BeforeMethod import org.testng.annotations.DataProvider import org.testng.annotations.Test import java.io.File class EnvironmentVariablesTest { @MockK private lateinit var _environment: Environment @MockK private lateinit var _parametersService: ParametersService @MockK private lateinit var _pathsService: PathsService @MockK private lateinit var _nugetEnvironmentVariables: EnvironmentVariables @MockK private lateinit var _virtualContext: VirtualContext @MockK private lateinit var _loggerResolver: LoggerResolver private val _tmpPath = File("Tmp") @BeforeMethod fun setUp() { MockKAnnotations.init(this) clearAllMocks() every { _nugetEnvironmentVariables.getVariables(any()) } returns emptySequence() every { _virtualContext.resolvePath(any()) } answers { "v_" + arg<String>(0) } every { _parametersService.tryGetParameter(ParameterType.Environment, UseSharedCompilationEnvVarName) } returns null every { _parametersService.tryGetParameter(ParameterType.Configuration, DotnetConstants.PARAM_MESSAGES_GUARD) } returns null every { _loggerResolver.resolve(ToolType.MSBuild) } returns File("msbuild_logger"); every { _loggerResolver.resolve(ToolType.VSTest) } returns File("vstest_logger"); every { _pathsService.getPath(PathType.AgentTemp) } returns _tmpPath } @Test fun shouldProvideDefaultVars() { // Given val environmentVariables = createInstance() val systemPath = File("system") val nugetPath = File(File(systemPath, "dotnet"), ".nuget").absolutePath // When every { _environment.os } returns OSType.WINDOWS every { _environment.tryGetVariable("USERPROFILE") } returns "path" every { _pathsService.getPath(PathType.System) } returns systemPath every { _nugetEnvironmentVariables.getVariables(any()) } returns sequenceOf(CommandLineEnvironmentVariable("NUGET_VAR", nugetPath)) every { _virtualContext.isVirtual } returns false every { _virtualContext.targetOSType } returns OSType.WINDOWS val actualVariables = environmentVariables.getVariables(Version(1, 2, 3)).toList() // Then Assert.assertEquals(actualVariables, (DotnetEnvironmentVariables.defaultVariables + commonVars + sequenceOf(CommandLineEnvironmentVariable(UseSharedCompilationEnvVarName, "false"), CommandLineEnvironmentVariable("NUGET_VAR", nugetPath))).toList()) } @Test fun shouldNotPublishedMessageGuardPathWhenItIsNotAllowed() { // Given val environmentVariables = createInstance() val systemPath = File("system") val nugetPath = File(File(systemPath, "dotnet"), ".nuget").absolutePath // When every { _environment.os } returns OSType.WINDOWS every { _environment.tryGetVariable("USERPROFILE") } returns "path" every { _pathsService.getPath(PathType.System) } returns systemPath every { _nugetEnvironmentVariables.getVariables(any()) } returns sequenceOf(CommandLineEnvironmentVariable("NUGET_VAR", nugetPath)) every { _virtualContext.isVirtual } returns false every { _virtualContext.targetOSType } returns OSType.WINDOWS every { _parametersService.tryGetParameter(ParameterType.Configuration, DotnetConstants.PARAM_MESSAGES_GUARD) } returns "false" val actualVariables = environmentVariables.getVariables(Version(1, 2, 3)).toList() // Then Assert.assertEquals( actualVariables, ( DotnetEnvironmentVariables.defaultVariables + sequenceOf( CommandLineEnvironmentVariable(DotnetEnvironmentVariables.MSBuildLoggerEnvVar, File("msbuild_logger").canonicalPath), CommandLineEnvironmentVariable(DotnetEnvironmentVariables.VSTestLoggerEnvVar, File("vstest_logger").canonicalPath)) + sequenceOf( CommandLineEnvironmentVariable(UseSharedCompilationEnvVarName, "false"), CommandLineEnvironmentVariable("NUGET_VAR", nugetPath)) ).toList() ) } @Test fun shouldNotUseSharedCompilationByDefault() { // Given val environmentVariables = createInstance() val systemPath = File("system") // When every { _environment.os } returns OSType.WINDOWS every { _environment.tryGetVariable("USERPROFILE") } returns "path" every { _pathsService.getPath(PathType.System) } returns systemPath every { _virtualContext.isVirtual } returns false every { _virtualContext.targetOSType } returns OSType.WINDOWS val actualVariables = environmentVariables.getVariables(Version(1, 2, 3)).toList() // Then Assert.assertEquals(actualVariables, (DotnetEnvironmentVariables.defaultVariables + commonVars + sequenceOf(CommandLineEnvironmentVariable(UseSharedCompilationEnvVarName, "false"))).toList()) } @Test fun shouldUseSharedCompilationWhenThisParameterWasOverridedInEnvVars() { // Given val environmentVariables = createInstance() val systemPath = File("system") // When every { _environment.os } returns OSType.WINDOWS every { _environment.tryGetVariable("USERPROFILE") } returns "path" every { _pathsService.getPath(PathType.System) } returns systemPath every { _virtualContext.isVirtual } returns false every { _virtualContext.targetOSType } returns OSType.WINDOWS every { _parametersService.tryGetParameter(ParameterType.Environment, UseSharedCompilationEnvVarName) } returns "true" val actualVariables = environmentVariables.getVariables(Version(1, 2, 3)).toList() // Then Assert.assertEquals(actualVariables, (DotnetEnvironmentVariables.defaultVariables + commonVars + sequenceOf(CommandLineEnvironmentVariable(UseSharedCompilationEnvVarName, "true"))).toList()) } @DataProvider(name = "osTypesData") fun osTypesData(): Array<Array<OSType>> { return arrayOf( arrayOf(OSType.UNIX), arrayOf(OSType.MAC)) } @Test(dataProvider = "osTypesData") fun shouldProvideDefaultVarsWhenVirtualContextFromWindows(os: OSType) { // Given val environmentVariables = createInstance() val systemPath = File("system") // When every { _environment.os } returns OSType.WINDOWS every { _environment.tryGetVariable("USERPROFILE") } returns "path" every { _pathsService.getPath(PathType.System) } returns systemPath every { _virtualContext.isVirtual } returns true every { _virtualContext.targetOSType } returns os val actualVariables = environmentVariables.getVariables(Version(1, 2, 3)).toList() // Then Assert.assertEquals(actualVariables, (DotnetEnvironmentVariables.defaultVariables + commonVars + sequenceOf(CommandLineEnvironmentVariable(UseSharedCompilationEnvVarName, "false"))).toList()) } @Test fun shouldProvideDefaultVarsWhenVirtualContextForWindowsContainer() { // Given val environmentVariables = createInstance() val systemPath = File("system") // When every { _environment.os } returns OSType.WINDOWS every { _environment.tryGetVariable("USERPROFILE") } returns "path" every { _pathsService.getPath(PathType.System) } returns systemPath every { _virtualContext.isVirtual } returns true every { _virtualContext.targetOSType } returns OSType.WINDOWS val actualVariables = environmentVariables.getVariables(Version(1, 2, 3)).toList() // Then Assert.assertEquals(actualVariables, (DotnetEnvironmentVariables.defaultVariables + commonVars + sequenceOf(CommandLineEnvironmentVariable(UseSharedCompilationEnvVarName, "false"))).toList()) } @Test fun shouldOverrideDefaultNugetPackagesPathWhenSpecifiedAsEnvVar() { // Given val environmentVariables = createInstance() val systemPath = File("system") // When every { _nugetEnvironmentVariables.getVariables(any()) } returns sequenceOf(CommandLineEnvironmentVariable("NUGET_VAR", "custom_nuget_packages_path")) every { _environment.os } returns OSType.WINDOWS every { _environment.tryGetVariable("USERPROFILE") } returns "path" every { _pathsService.getPath(PathType.System) } returns systemPath every { _virtualContext.isVirtual } returns false every { _virtualContext.targetOSType } returns OSType.WINDOWS val actualVariables = environmentVariables.getVariables(Version(1, 2, 3)).toList() // Then Assert.assertEquals(actualVariables, (DotnetEnvironmentVariables.defaultVariables + commonVars + sequenceOf(CommandLineEnvironmentVariable(UseSharedCompilationEnvVarName, "false"), CommandLineEnvironmentVariable("NUGET_VAR", "custom_nuget_packages_path"))).toList()) } private fun createInstance() = DotnetEnvironmentVariables( _environment, _parametersService, _pathsService, _nugetEnvironmentVariables, _loggerResolver, ) private val commonVars = sequenceOf( CommandLineEnvironmentVariable(DotnetEnvironmentVariables.MSBuildLoggerEnvVar, File("msbuild_logger").canonicalPath), CommandLineEnvironmentVariable(DotnetEnvironmentVariables.VSTestLoggerEnvVar, File("vstest_logger").canonicalPath), CommandLineEnvironmentVariable(DotnetEnvironmentVariables.ServiceMessagesPathEnvVar, _tmpPath.canonicalPath) ) }
3
Kotlin
25
91
a19e1b8856a120d6f7f0d85cf7c2161adfae241f
11,060
teamcity-dotnet-plugin
Apache License 2.0
presentation/src/main/java/com/doool/pokedex/presentation/ui/home/SearchViewModel.kt
D000L
407,756,410
false
null
package com.doool.pokedex.presentation.ui.home import androidx.lifecycle.viewModelScope import com.doool.pokedex.core.base.BaseViewModel import com.doool.pokedex.domain.LoadState import com.doool.pokedex.domain.model.Item import com.doool.pokedex.domain.model.PokemonDetail import com.doool.pokedex.domain.model.PokemonMove import com.doool.pokedex.domain.model.PokemonSpecies import com.doool.pokedex.domain.usecase.search.Search import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.distinctUntilChangedBy import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import javax.inject.Inject data class SearchUIModel( var pokemon: List<Pair<PokemonDetail, PokemonSpecies>> = emptyList(), var items: List<Item> = emptyList(), var moves: List<PokemonMove> = emptyList() ) @HiltViewModel class SearchViewModel @Inject constructor( private val searchUsacese: Search ) : BaseViewModel() { companion object { private const val SEARCH_ITEM_LIMIT = 6 } val query = MutableStateFlow("") val searchResultState = query.distinctUntilChangedBy { it }.flatMapLatest { searchUsacese(Pair(it, SEARCH_ITEM_LIMIT)) }.map { when (it) { is LoadState.Error -> LoadState.Error() is LoadState.Loading -> LoadState.Loading() is LoadState.Success -> LoadState.Success( SearchUIModel( it.data.pokemon, it.data.item, it.data.move ) ) } } fun search(query: String) { viewModelScope.launch { [email protected](query) } } fun clearQuery() { query.tryEmit("") } }
4
Kotlin
1
7
d79a0f6b15f384f719bd812d2cbf8144ba6f45b4
1,851
pokedex-compose
Apache License 2.0
codegen-core/src/main/kotlin/io/vrap/rmf/codegen/io/MemoryDataSink.kt
commercetools
136,635,215
false
null
package io.vrap.rmf.codegen.io; import com.google.common.collect.Maps class MemoryDataSink: DataSink { val files: MutableMap<String, String> = mutableMapOf() override fun write(templateFile: TemplateFile) { files.put(templateFile.relativePath, templateFile.content) } override fun postClean() { // files.clear() } }
20
null
6
14
1d29b69ae49e17c28a26be72fd28979ca74922ec
357
rmf-codegen
Apache License 2.0
mokkery-runtime/src/commonMain/kotlin/dev/mokkery/internal/CallContext.kt
lupuuss
652,785,006
false
{"Kotlin": 556906}
package dev.mokkery.internal import dev.mokkery.internal.tracing.CallArg import kotlin.reflect.KClass internal class CallContext( val scope: MokkeryInterceptorScope, val name: String, returnType: KClass<*>, args: List<CallArg>, val supers: Map<KClass<*>, (List<Any?>) -> Any?> = emptyMap(), val spyDelegate: Any? = null // regular function or suspend function (List<Any?>) -> Any? ) { // filters out unimplemented KClasses on K/N val returnType: KClass<*> = returnType.takeIfImplementedOrAny() val args: List<CallArg> = args.copyWithReplacedKClasses() override fun toString() = callToString(scope.id, name, args) }
9
Kotlin
8
185
71c8e946d1a3e9ab015e160304e2f85e5333c395
659
Mokkery
Apache License 2.0
app/src/main/kotlin/taiwan/no1/app/ssfm/features/search/SearchIndexFragment.kt
pokk
90,497,127
false
null
package taiwan.no1.app.ssfm.features.search import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import com.devrapid.kotlinknifer.recyclerview.WrapContentLinearLayoutManager import com.devrapid.kotlinknifer.recyclerview.itemdecorator.HorizontalItemDecorator import com.devrapid.kotlinknifer.scaledDrawable import org.jetbrains.anko.bundleOf import taiwan.no1.app.ssfm.R import taiwan.no1.app.ssfm.databinding.FragmentSearchIndexBinding import taiwan.no1.app.ssfm.features.base.AdvancedFragment import taiwan.no1.app.ssfm.misc.extension.gContext import taiwan.no1.app.ssfm.misc.extension.recyclerview.ArtistAdapter import taiwan.no1.app.ssfm.misc.extension.recyclerview.DataInfo import taiwan.no1.app.ssfm.misc.extension.recyclerview.RVCustomScrollCallback import taiwan.no1.app.ssfm.misc.extension.recyclerview.TrackAdapter import taiwan.no1.app.ssfm.misc.extension.recyclerview.firstFetch import taiwan.no1.app.ssfm.misc.extension.recyclerview.keepAllLastItemPosition import taiwan.no1.app.ssfm.misc.extension.recyclerview.refreshAndChangeList import taiwan.no1.app.ssfm.misc.extension.recyclerview.restoreAllLastItemPosition import taiwan.no1.app.ssfm.misc.widgets.recyclerviews.adapters.BaseDataBindingAdapter import taiwan.no1.app.ssfm.models.entities.lastfm.BaseEntity import javax.inject.Inject /** * * @author jieyi * @since 8/20/17 */ class SearchIndexFragment : AdvancedFragment<SearchIndexFragmentViewModel, FragmentSearchIndexBinding>() { //region Static initialization companion object Factory { /** * Use this factory method to create a new instance of this fragment using the * provided parameters. * * @return A new instance of [android.app.Fragment] SearchIndexFragment. */ fun newInstance() = SearchIndexFragment().apply { arguments = bundleOf() } } //endregion @Inject override lateinit var viewModel: SearchIndexFragmentViewModel private val artistInfo by lazy { DataInfo() } private val trackInfo by lazy { DataInfo() } private var artistRes = mutableListOf<BaseEntity>() private var trackRes = mutableListOf<BaseEntity>() //region Fragment lifecycle override fun onResume() { super.onResume() binding?.apply { listOf(Pair(artistInfo, artistLayoutManager), Pair(trackInfo, trackLayoutManager)).restoreAllLastItemPosition() } } override fun onPause() { super.onPause() binding?.apply { listOf(Triple(artistInfo, rvTopArtists, artistLayoutManager), Triple(trackInfo, rvTopTracks, trackLayoutManager)).keepAllLastItemPosition() } } override fun onDestroyView() { listOf((binding?.artistAdapter as BaseDataBindingAdapter<*, *>), (binding?.trackAdapter as BaseDataBindingAdapter<*, *>)).forEach { it.detachAll() } super.onDestroyView() } //endregion //region Base fragment implement override fun rendered(savedInstanceState: Bundle?) { binding?.apply { artistLayoutManager = WrapContentLinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false) trackLayoutManager = WrapContentLinearLayoutManager(activity) artistAdapter = ArtistAdapter(this@SearchIndexFragment, R.layout.item_artist_type_1, artistRes) { holder, item, _ -> if (null == holder.binding.avm) holder.binding.avm = RecyclerViewSearchArtistChartViewModel(item) else holder.binding.avm?.setArtistItem(item) val sd = gContext().scaledDrawable(R.drawable.ic_feature, 0.5f, 0.5f) holder.binding.tvPlayCount.setCompoundDrawables(sd, null, null, null) } trackAdapter = TrackAdapter(this@SearchIndexFragment, R.layout.item_music_type_1, trackRes) { holder, item, _ -> if (null == holder.binding.avm) holder.binding.avm = RecyclerViewSearchTrackChartViewModel(item) else holder.binding.avm?.setTrackItem(item) } artistLoadmore = RVCustomScrollCallback(binding?.artistAdapter as ArtistAdapter, artistInfo, artistRes, viewModel::fetchArtistList) trackLoadmore = RVCustomScrollCallback(binding?.trackAdapter as TrackAdapter, trackInfo, trackRes, viewModel::fetchTrackList) artistDecoration = HorizontalItemDecorator(20) } // First time showing this fragment. artistInfo.firstFetch { viewModel.fetchArtistList(it.page, it.limit) { resList, total -> artistRes.refreshAndChangeList(resList, total, binding?.artistAdapter as ArtistAdapter, it) } } trackInfo.firstFetch { viewModel.fetchTrackList(it.page, it.limit) { resList, total -> trackRes.refreshAndChangeList(resList, total, binding?.trackAdapter as TrackAdapter, it) } } } override fun provideInflateView(): Int = R.layout.fragment_search_index //endregion }
0
Kotlin
0
1
1928c2f1a42634ede147517854d06b6fd5d11e7b
5,632
SSFM
Apache License 2.0
compiler/testData/codegen/boxInline/tryCatchFinally/tryCatchFinally.2.kt
staltz
38,581,975
true
{"Java": 15450397, "Kotlin": 8578737, "JavaScript": 176060, "HTML": 22810, "Lex": 17327, "Protocol Buffer": 13024, "ANTLR": 9689, "CSS": 9431, "Shell": 3931, "IDL": 3257, "Groovy": 3010, "Batchfile": 2831}
class My(val value: Int) inline fun <T, R> T.performWithFinally(job: (T)-> R, finally: (T) -> R) : R { try { return job(this) } finally { return finally(this) } } inline fun <T, R> T.performWithFailFinally(job: (T)-> R, failJob : (e: RuntimeException, T) -> R, finally: (T) -> R) : R { try { return job(this) } catch (e: RuntimeException) { return failJob(e, this) } finally { return finally(this) } } inline fun String.toInt2() : Int = java.lang.Integer.parseInt(this)
0
Java
0
1
ff00bde607d605c4eba2d98fbc9e99af932accb6
540
kotlin
Apache License 2.0
app/src/main/java/com/github/vipulasri/timelineview/sample/BaseActivity.kt
vipulasri
48,049,436
false
null
package com.github.vipulasri.timelineview.sample import android.annotation.SuppressLint import android.graphics.drawable.Drawable import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import com.github.vipulasri.timelineview.sample.example.whenNotNull @SuppressLint("Registered") open class BaseActivity : AppCompatActivity() { var toolbar: Toolbar? = null //If back button is displayed in action bar, return false protected var isDisplayHomeAsUpEnabled: Boolean get() = false set(value) { whenNotNull(supportActionBar) { it.setDisplayHomeAsUpEnabled(value) } } override fun setContentView(layoutResID: Int) { super.setContentView(layoutResID) injectViews() //Displaying the back button in the action bar if (isDisplayHomeAsUpEnabled) { whenNotNull(supportActionBar) { it.setDisplayHomeAsUpEnabled(true) } } } protected fun injectViews() { toolbar = findViewById(R.id.toolbar) setupToolbar() } fun setContentViewWithoutInject(layoutResId: Int) { super.setContentView(layoutResId) } protected fun setupToolbar() { whenNotNull(toolbar) { setSupportActionBar(it) } } fun setActivityTitle(title: Int) { whenNotNull(supportActionBar) { it.setTitle(title) } } fun setActivityTitle(title: String) { whenNotNull(supportActionBar) { it.setTitle(title) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { //Menu when (item.itemId) { //When home is clicked android.R.id.home -> { onActionBarHomeIconClicked() return true } } return super.onOptionsItemSelected(item) } fun setHomeAsUpIndicator(drawable: Drawable) { whenNotNull(supportActionBar) { it.setHomeAsUpIndicator(drawable) } } //Method for when home button is clicked private fun onActionBarHomeIconClicked() { if (isDisplayHomeAsUpEnabled) { onBackPressed() } else { finish() } } }
7
null
648
3,734
963ac7a9e49aba33c06e3bf52b5a4b938fecec54
2,340
Timeline-View
Apache License 2.0
app/src/main/java/com/mikepenz/materialdrawer/app/CompactHeaderDrawerActivity.kt
mikepenz
30,120,110
false
null
package com.mikepenz.materialdrawer.app import android.content.Context import android.content.res.Configuration import android.graphics.Color import android.os.Build import android.os.Bundle import android.util.TypedValue import android.view.Menu import android.view.MenuItem import androidx.annotation.AttrRes import androidx.annotation.ColorInt import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.view.ActionMode import androidx.core.content.ContextCompat import androidx.core.content.res.ResourcesCompat import com.mikepenz.iconics.IconicsDrawable import com.mikepenz.iconics.typeface.library.fontawesome.FontAwesome import com.mikepenz.iconics.typeface.library.fontawesome.FontAwesomeBrand import com.mikepenz.iconics.typeface.library.googlematerial.GoogleMaterial import com.mikepenz.iconics.utils.actionBar import com.mikepenz.iconics.utils.paddingDp import com.mikepenz.materialdrawer.app.databinding.ActivitySampleBinding import com.mikepenz.materialdrawer.holder.BadgeStyle import com.mikepenz.materialdrawer.holder.ColorHolder import com.mikepenz.materialdrawer.iconics.iconicsIcon import com.mikepenz.materialdrawer.iconics.withIcon import com.mikepenz.materialdrawer.model.* import com.mikepenz.materialdrawer.model.interfaces.* import com.mikepenz.materialdrawer.widget.AccountHeaderView class CompactHeaderDrawerActivity : AppCompatActivity() { private lateinit var binding: ActivitySampleBinding //save our header or result private lateinit var headerView: AccountHeaderView private lateinit var actionBarDrawerToggle: ActionBarDrawerToggle override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySampleBinding.inflate(layoutInflater).also { setContentView(it.root) } // Handle Toolbar setSupportActionBar(binding.toolbar) supportActionBar?.setTitle(R.string.drawer_item_compact_header) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setHomeButtonEnabled(true) actionBarDrawerToggle = ActionBarDrawerToggle(this, binding.root, binding.toolbar, com.mikepenz.materialdrawer.R.string.material_drawer_open, com.mikepenz.materialdrawer.R.string.material_drawer_close) // Create a few sample profile val profile = ProfileDrawerItem().apply { nameText = "<NAME>"; descriptionText = "<EMAIL>"; iconRes = R.drawable.profile; badgeText = "123" badgeStyle = BadgeStyle().apply { textColor = ColorHolder.fromColor(Color.WHITE) color = ColorHolder.fromColorRes(R.color.colorAccent) } } val profile2 = ProfileDrawerItem().apply { nameText = "<NAME>"; descriptionText = "<EMAIL>"; iconRes = R.drawable.profile2 } val profile3 = ProfileDrawerItem().apply { nameText = "<NAME>"; descriptionText = "<EMAIL>"; iconRes = R.drawable.profile3 } val profile4 = ProfileDrawerItem().apply { nameText = "<NAME>"; descriptionText = "<EMAIL>"; iconRes = R.drawable.profile4 } val profile5 = ProfileDrawerItem().apply { nameText = "Batman"; descriptionText = "<EMAIL>"; iconRes = R.drawable.profile5 } // Create the AccountHeader headerView = AccountHeaderView(this).apply { attachToSliderView(binding.slider) addProfiles( profile, profile2, profile3, profile4, profile5, //don't ask but google uses 14dp for the add account icon in gmail but 20dp for the normal icons (like manage account) ProfileSettingDrawerItem().withName("Add Account").withDescription("Add new GitHub Account").withIcon(IconicsDrawable(context, GoogleMaterial.Icon.gmd_add).apply { actionBar(); paddingDp = 5 }).withIconTinted(true).withIdentifier(PROFILE_SETTING.toLong()), ProfileSettingDrawerItem().withName("Manage Account").withIcon(GoogleMaterial.Icon.gmd_settings).withIdentifier(100001) ) withSavedInstance(savedInstanceState) } binding.slider.apply { itemAdapter.add( PrimaryDrawerItem().apply { nameRes = R.string.drawer_item_home; iconicsIcon = FontAwesome.Icon.faw_home; identifier = 1 }, PrimaryDrawerItem().apply { nameRes = R.string.drawer_item_free_play; iconicsIcon = FontAwesome.Icon.faw_gamepad }, PrimaryDrawerItem().apply { nameRes = R.string.drawer_item_custom; iconicsIcon = FontAwesome.Icon.faw_eye; identifier = 5 }, SectionDrawerItem().apply { nameRes = R.string.drawer_item_section_header }, SecondaryDrawerItem().apply { nameRes = R.string.drawer_item_settings; iconicsIcon = FontAwesome.Icon.faw_cog }, SecondaryDrawerItem().apply { nameRes = R.string.drawer_item_help; iconicsIcon = FontAwesome.Icon.faw_question; isEnabled = false }, SecondaryDrawerItem().apply { nameRes = R.string.drawer_item_open_source; iconicsIcon = FontAwesomeBrand.Icon.fab_github }, SecondaryDrawerItem().apply { nameRes = R.string.drawer_item_contact; iconicsIcon = FontAwesome.Icon.faw_bullhorn } ) onDrawerItemClickListener = { _, drawerItem, _ -> if (drawerItem.identifier == 1L) { startSupportActionMode(ActionBarCallBack()) } if (drawerItem is Nameable) { binding.toolbar.title = drawerItem.name?.getText(this@CompactHeaderDrawerActivity) } false } setSavedInstance(savedInstanceState) } // set the selection to the item with the identifier 5 if (savedInstanceState == null) { binding.slider.setSelection(5, false) } } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) actionBarDrawerToggle.onConfigurationChanged(newConfig) } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) actionBarDrawerToggle.syncState() } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (actionBarDrawerToggle.onOptionsItemSelected(item)) { return true } return super.onOptionsItemSelected(item) } override fun onSaveInstanceState(_outState: Bundle) { var outState = _outState //add the values which need to be saved from the drawer to the bundle outState = binding.slider.saveInstanceState(outState) //add the values which need to be saved from the accountHeader to the bundle outState = headerView.saveInstanceState(outState) super.onSaveInstanceState(outState) } override fun onBackPressed() { //handle the back press :D close the drawer first and if the drawer is closed close the activity if (binding.root.isDrawerOpen(binding.slider)) { binding.root.closeDrawer(binding.slider) } else { super.onBackPressed() } } internal inner class ActionBarCallBack : ActionMode.Callback { override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { return false } override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.statusBarColor = getThemeColor(android.R.attr.colorPrimaryDark, ContextCompat.getColor(this@CompactHeaderDrawerActivity, R.color.colorPrimaryDark)) } mode.menuInflater.inflate(R.menu.cab, menu) return true } override fun onDestroyActionMode(mode: ActionMode) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.statusBarColor = Color.TRANSPARENT } } override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { return false } private fun Context.getThemeColor(@AttrRes attr: Int, @ColorInt def: Int = 0): Int { val tv = TypedValue() return if (theme.resolveAttribute(attr, tv, true)) { if (tv.resourceId != 0) ResourcesCompat.getColor(resources, tv.resourceId, theme) else tv.data } else def } } companion object { private const val PROFILE_SETTING = 1 } }
5
null
2080
11,670
b03f1d495ae65fd88bdd3ee7e496665ae9721c0f
8,674
MaterialDrawer
Apache License 2.0
app/src/main/java/com/aljon/purrito/di/CatModule.kt
ajcordenete
257,904,844
false
null
package com.aljon.purrito.di import androidx.lifecycle.ViewModel import com.aljon.purrito.ui.feed.cat.CatFeedViewModel import dagger.Binds import dagger.Module import dagger.multibindings.IntoMap @Module abstract class CatModule { @Binds @IntoMap @ViewModelKey(CatFeedViewModel::class) abstract fun bindViewModel(viewModel: CatFeedViewModel) : ViewModel }
0
Kotlin
0
1
e44054efcc552473a66402a77f02039c266ab3cc
374
Purrito
Apache License 2.0
src/commonMain/kotlin/com/oyosite/ticon/dillan/scenes/TileSceneBase.kt
eehunter
418,286,944
false
null
package com.oyosite.ticon.dillan.scenes import com.soywiz.korge.scene.Scene import com.soywiz.korge.view.Container class TileSceneBase : Scene() { override suspend fun Container.sceneInit() { } }
0
Kotlin
0
0
e194845938548461983641f9e38bf90ec097795f
207
Dillan
MIT License
src/commonMain/kotlin/com/oyosite/ticon/dillan/scenes/TileSceneBase.kt
eehunter
418,286,944
false
null
package com.oyosite.ticon.dillan.scenes import com.soywiz.korge.scene.Scene import com.soywiz.korge.view.Container class TileSceneBase : Scene() { override suspend fun Container.sceneInit() { } }
0
Kotlin
0
0
e194845938548461983641f9e38bf90ec097795f
207
Dillan
MIT License
app/src/main/java/space/taran/arknavigator/utils/ImageUtils.kt
ARK-Builders
394,855,699
false
null
package space.taran.arknavigator.utils import android.graphics.drawable.Drawable import android.util.Log import android.widget.ImageView import com.bumptech.glide.Glide import com.bumptech.glide.Priority import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.load.resource.bitmap.DownsampleStrategy import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.RequestOptions import com.bumptech.glide.request.target.CustomTarget import com.bumptech.glide.request.target.Target import com.bumptech.glide.request.transition.Transition import com.bumptech.glide.signature.ObjectKey import com.davemorrissey.labs.subscaleview.ImageSource import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView import com.ortiz.touchview.TouchImageView import space.taran.arknavigator.R import space.taran.arknavigator.mvp.model.repo.index.ResourceId import space.taran.arknavigator.ui.App import java.nio.file.Path object ImageUtils { private const val MAX_GLIDE_SIZE = 1500 private const val PREVIEW_SIGNATURE = "preview" private const val THUMBNAIL_SIGNATURE = "thumbnail" const val APPEARANCE_DURATION = 300L fun iconForExtension(ext: String): Int { val drawableID = App.instance.resources .getIdentifier( "ic_file_$ext", "drawable", App.instance.packageName ) return if (drawableID > 0) drawableID else R.drawable.ic_file } fun loadGlideZoomImage(resource: ResourceId, image: Path, view: TouchImageView) = Glide.with(view.context) .load(image.toFile()) .apply( RequestOptions() .priority(Priority.IMMEDIATE) .signature(ObjectKey("$resource$PREVIEW_SIGNATURE")) .downsample(DownsampleStrategy.CENTER_INSIDE) .override(MAX_GLIDE_SIZE) ) .into(object : CustomTarget<Drawable>() { override fun onResourceReady( resource: Drawable, transition: Transition<in Drawable>? ) { view.setImageDrawable(resource) view.animate().apply { duration = APPEARANCE_DURATION alpha(1f) } } override fun onLoadCleared(placeholder: Drawable?) {} }) fun loadSubsamplingImage(image: Path, view: SubsamplingScaleImageView) { view.orientation = SubsamplingScaleImageView.ORIENTATION_USE_EXIF view.setImage(ImageSource.uri(image.toString())) } fun loadThumbnailWithPlaceholder( resource: ResourceId, image: Path?, placeHolder: Int, view: ImageView ) { Log.d(IMAGES, "loading image $image") Glide.with(view.context) .load(image?.toFile()) .placeholder(placeHolder) .signature(ObjectKey("$resource$THUMBNAIL_SIGNATURE")) .transition(DrawableTransitionOptions.withCrossFade()) .into(view) } fun <T> glideExceptionListener() = object : RequestListener<T> { override fun onLoadFailed( e: GlideException?, model: Any?, target: Target<T>?, isFirstResource: Boolean ): Boolean { Log.d( GLIDE, "load failed with message: ${ e?.message } for target of type: ${ target?.javaClass?.canonicalName }" ) return true } override fun onResourceReady( resource: T, model: Any?, target: Target<T>?, dataSource: DataSource?, isFirstResource: Boolean ) = false } }
93
Kotlin
3
8
886c7da36af73cc9235452d3b03412cc4c01e607
4,018
ARK-Navigator
MIT License
compose-ide-plugin/compiler-hosted-src/androidx/compose/compiler/plugins/kotlin/analysis/ComposeWritableSlices.kt
JetBrains
60,701,247
false
{"Kotlin": 49550960, "Java": 35837871, "HTML": 1217714, "Starlark": 909188, "C++": 357481, "Python": 106384, "C": 71782, "Lex": 66732, "NSIS": 58538, "AIDL": 35382, "Shell": 26938, "CMake": 26798, "JavaScript": 18437, "Smali": 7580, "Batchfile": 6951, "RenderScript": 4411, "Makefile": 2495, "IDL": 269, "QMake": 18}
package androidx.compose.compiler.plugins.kotlin.analysis import androidx.compose.compiler.plugins.kotlin.lower.KeyInfo import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.ir.declarations.IrAttributeContainer import org.jetbrains.kotlin.ir.expressions.IrExpression import org.jetbrains.kotlin.ir.expressions.IrFunctionAccessExpression import org.jetbrains.kotlin.psi.KtLambdaExpression import org.jetbrains.kotlin.util.slicedMap.BasicWritableSlice import org.jetbrains.kotlin.util.slicedMap.RewritePolicy import org.jetbrains.kotlin.util.slicedMap.WritableSlice object ComposeWritableSlices { val INFERRED_COMPOSABLE_DESCRIPTOR: WritableSlice<FunctionDescriptor, Boolean> = BasicWritableSlice(RewritePolicy.DO_NOTHING) val LAMBDA_CAPABLE_OF_COMPOSER_CAPTURE: WritableSlice<FunctionDescriptor, Boolean> = BasicWritableSlice(RewritePolicy.DO_NOTHING) val INFERRED_COMPOSABLE_LITERAL: WritableSlice<KtLambdaExpression, Boolean> = BasicWritableSlice(RewritePolicy.DO_NOTHING) val IS_COMPOSABLE_CALL: WritableSlice<IrAttributeContainer, Boolean> = BasicWritableSlice(RewritePolicy.DO_NOTHING) val IS_SYNTHETIC_COMPOSABLE_CALL: WritableSlice<IrFunctionAccessExpression, Boolean> = BasicWritableSlice(RewritePolicy.DO_NOTHING) val IS_STATIC_FUNCTION_EXPRESSION: WritableSlice<IrExpression, Boolean> = BasicWritableSlice(RewritePolicy.DO_NOTHING) val IS_COMPOSABLE_SINGLETON: WritableSlice<IrAttributeContainer, Boolean> = BasicWritableSlice(RewritePolicy.DO_NOTHING) val IS_COMPOSABLE_SINGLETON_CLASS: WritableSlice<IrAttributeContainer, Boolean> = BasicWritableSlice(RewritePolicy.DO_NOTHING) val DURABLE_FUNCTION_KEY: WritableSlice<IrAttributeContainer, KeyInfo> = BasicWritableSlice(RewritePolicy.DO_NOTHING) }
3
Kotlin
740
921
dbd9aeae0dc5b8c56ce2c7d51208ba26ea0f169b
1,852
android
Apache License 2.0
app/src/main/java/com/dluvian/voyage/ui/components/row/mainEvent/MainEventRow.kt
dluvian
766,355,809
false
{"Kotlin": 991595}
package com.dluvian.voyage.ui.components.row.mainEvent import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.tween import androidx.compose.animation.slideOutVertically import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.IntrinsicSize import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.VerticalDivider import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import com.dluvian.voyage.core.ComposableContent import com.dluvian.voyage.core.MAX_CONTENT_LINES import com.dluvian.voyage.core.MAX_SUBJECT_LINES import com.dluvian.voyage.core.OnUpdate import com.dluvian.voyage.core.OpenThread import com.dluvian.voyage.core.OpenThreadRaw import com.dluvian.voyage.core.ThreadViewShowReplies import com.dluvian.voyage.core.ThreadViewToggleCollapse import com.dluvian.voyage.core.model.Comment import com.dluvian.voyage.core.model.CrossPost import com.dluvian.voyage.core.model.LegacyReply import com.dluvian.voyage.core.model.RootPost import com.dluvian.voyage.core.model.ThreadableMainEvent import com.dluvian.voyage.data.nostr.createNevent import com.dluvian.voyage.ui.components.button.OptionsButton import com.dluvian.voyage.ui.components.button.footer.CountedCommentButton import com.dluvian.voyage.ui.components.button.footer.ReplyIconButton import com.dluvian.voyage.ui.components.text.AnnotatedText import com.dluvian.voyage.ui.theme.spacing import com.dluvian.voyage.ui.views.nonMain.MoreRepliesTextButton @Composable fun MainEventRow( ctx: MainEventCtx, showAuthorName: Boolean, onUpdate: OnUpdate ) { when (ctx) { is FeedCtx -> MainEventMainRow( ctx = ctx, showAuthorName = showAuthorName, onUpdate = onUpdate ) is ThreadRootCtx -> { when (ctx.threadableMainEvent) { is RootPost -> MainEventMainRow( ctx = ctx, showAuthorName = showAuthorName, onUpdate = onUpdate ) is LegacyReply, is Comment -> RowWithDivider(level = 1) { MainEventMainRow( ctx = ctx, showAuthorName = showAuthorName, onUpdate = onUpdate ) } } } is ThreadReplyCtx -> { RowWithDivider(level = ctx.level) { MainEventMainRow( ctx = ctx, showAuthorName = showAuthorName, onUpdate = onUpdate ) } } } } @Composable private fun MainEventMainRow( ctx: MainEventCtx, showAuthorName: Boolean, onUpdate: OnUpdate ) { val onClickRow = { when (ctx) { is ThreadReplyCtx -> onUpdate(ThreadViewToggleCollapse(id = ctx.reply.id)) is FeedCtx -> { when (val event = ctx.mainEvent) { is ThreadableMainEvent -> onUpdate(OpenThread(mainEvent = event)) is CrossPost -> onUpdate(OpenThreadRaw(nevent = createNevent(hex = event.crossPostedId))) } } is ThreadRootCtx -> {} } } Column( modifier = Modifier .fillMaxWidth() .clickable(onClick = onClickRow) .padding(spacing.bigScreenEdge) ) { MainEventHeader( ctx = ctx, showAuthorName = showAuthorName, onUpdate = onUpdate, ) Spacer(modifier = Modifier.height(spacing.large)) ctx.mainEvent.getRelevantSubject()?.let { subject -> if (subject.isNotEmpty()) { AnnotatedText( text = subject, maxLines = MAX_SUBJECT_LINES, style = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.SemiBold) ) Spacer(modifier = Modifier.height(spacing.large)) } } AnimatedVisibility( visible = !ctx.isCollapsedReply(), exit = slideOutVertically(animationSpec = tween(durationMillis = 0)) ) { AnnotatedText( text = ctx.mainEvent.content, maxLines = when (ctx) { is ThreadReplyCtx, is ThreadRootCtx -> Int.MAX_VALUE is FeedCtx -> MAX_CONTENT_LINES } ) Spacer(modifier = Modifier.height(spacing.large)) } if (!ctx.isCollapsedReply()) MainEventActions( mainEvent = ctx.mainEvent, onUpdate = onUpdate, additionalStartAction = { OptionsButton(mainEvent = ctx.mainEvent, onUpdate = onUpdate) when (ctx) { is ThreadReplyCtx -> { if (ctx.reply.replyCount > 0 && !ctx.hasLoadedReplies) { MoreRepliesTextButton( replyCount = ctx.reply.replyCount, onShowReplies = { onUpdate(ThreadViewShowReplies(id = ctx.reply.id)) } ) } } is FeedCtx, is ThreadRootCtx -> {} } }, additionalEndAction = { when (ctx) { is ThreadReplyCtx -> ReplyIconButton(ctx = ctx, onUpdate = onUpdate) is ThreadRootCtx -> CountedCommentButton(ctx = ctx, onUpdate = onUpdate) is FeedCtx -> { when (ctx.mainEvent) { is RootPost, is CrossPost -> CountedCommentButton(ctx = ctx, onUpdate = onUpdate) is LegacyReply, is Comment -> ReplyIconButton( ctx = ctx, onUpdate = onUpdate ) } } } }) } } @Composable private fun RowWithDivider(level: Int, content: ComposableContent) { Row(modifier = Modifier.height(IntrinsicSize.Min)) { repeat(times = level) { VerticalDivider( modifier = Modifier .fillMaxHeight() .padding(start = spacing.large, end = spacing.medium) ) } content() } }
36
Kotlin
4
39
9fe406eada1a905c8f1a2510196babd647444eff
7,006
voyage
MIT License
app/src/main/java/io/bibuti/opennews/core/BaseViewModel.kt
bibutikoley
325,942,445
false
null
package io.bibuti.opennews.core import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import androidx.lifecycle.ViewModel /** * This class supports the ViewState concepts. * Extend VM from this class, if you want to use the view state functionality. */ open class BaseViewModel<VIEW_STATE>(initialState: VIEW_STATE) : ViewModel() { val viewState = NonNullMutableLiveData(initialState) fun updateViewState(update: (VIEW_STATE) -> VIEW_STATE) { viewState.value = update(viewState.value) } /** * Custom class that does not allow [null] data-types. */ open class NonNullMutableLiveData<T>(initialValue: T) : MutableLiveData<T>() { init { value = initialValue } //Not allowing Null Values override fun getValue(): T { return super.getValue()!! } fun observe(owner: LifecycleOwner, block: (T) -> Unit) { observe(owner, Observer { it?.let(block) }) } } }
0
Kotlin
0
1
c59e27f8bc771d8339728657f7ee96d0e5d26520
1,085
OpenNews
MIT License
kotlin-code-generation/src/test/kotlin/spec/KotlinValueClassTest.kt
toolisticon
804,098,315
false
null
@file:OptIn(ExperimentalKotlinPoetApi::class) package io.toolisticon.kotlin.generation.spec import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.ExperimentalKotlinPoetApi import io.toolisticon.kotlin.generation.KotlinCodeGeneration.buildValueClass import io.toolisticon.kotlin.generation.TestFixtures import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class KotlinValueClassTest { @Test fun `build foo with string value`() { val className = ClassName("test", "Foo") val valueClass = buildValueClass(className = className) { addConstructorProperty("bar", String::class) { makePrivate() addAnnotation(TestFixtures.myAnnotationSpec) } } assertThat(valueClass.toFileSpec().code.trim()).isEqualTo( """package test import io.toolisticon.kotlin.generation.TestFixtures import kotlin.String import kotlin.jvm.JvmInline @JvmInline public value class Foo( @TestFixtures.MyAnnotation private val bar: String, )""" ) } @Test fun `create foo value class`() { val className = ClassName("io.acme", "Foo") val spec = buildValueClass(className) { addConstructorProperty("bar", String::class) { addAnnotation(TestFixtures.myAnnotationSpec) } } assertThat(spec.code.trim()).isEqualTo( """ @kotlin.jvm.JvmInline public value class Foo( @io.toolisticon.kotlin.generation.TestFixtures.MyAnnotation public val bar: kotlin.String, ) """.trimIndent() ) } }
6
null
0
2
e16f4f5ab3fc01ca585e833caa67e85f9152caa6
1,560
kotlin-code-generation
Apache License 2.0
PlacesWishList/app/src/main/java/com/github/matthews8/placeswishlist/placefragment/PlaceListAdapter.kt
MatthewS8
375,648,877
false
{"Kotlin": 35136}
package com.github.matthews8.placeswishlist.placefragment import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.github.matthews8.placeswishlist.database.Place import com.github.matthews8.placeswishlist.databinding.ListItemPlaceBinding class PlaceListAdapter: ListAdapter<Place, PlaceListAdapter.ViewHolder>(PlaceListDiffCallback()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder.inflateFrom(parent) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val placeItem = getItem(position) holder.bind(placeItem) } class ViewHolder private constructor(val binding: ListItemPlaceBinding): RecyclerView.ViewHolder(binding.root){ fun bind(item: Place) { binding.place = item binding.executePendingBindings() } companion object { fun inflateFrom(parent: ViewGroup): ViewHolder { val layoutInflater = LayoutInflater.from(parent.context) val binding = ListItemPlaceBinding.inflate(layoutInflater,parent, false) return ViewHolder(binding) } } } } class PlaceListDiffCallback: DiffUtil.ItemCallback<Place>(){ override fun areItemsTheSame(oldItem: Place, newItem: Place): Boolean { return oldItem.placeId == newItem.placeId } override fun areContentsTheSame(oldItem: Place, newItem: Place): Boolean { return oldItem == newItem } }
0
Kotlin
0
0
010d1981156c7182f9c99b2db28447df9962677f
1,670
ProgettoSAM
MIT License
03-coroutines-ktor/src/main/kotlin/me/ilya40umov/kc/coroutines/friends/User.kt
ilya40umov
160,675,851
false
{"Kotlin": 55455}
package me.ilya40umov.kc.coroutines.friends data class User( val userId: Long, val name: String, val friendIds: List<Long> = emptyList() )
0
Kotlin
2
4
28c3db824b31d43a7c4db9ae58e8991df5acd81a
151
kotlin-concurrency
Apache License 2.0
src/main/kotlin/kotlinmudv2/action/actions/manipulate/CreateSacrificeErrorAction.kt
danielmunro
515,227,142
false
{"Kotlin": 214222, "Dockerfile": 179, "Makefile": 134}
package kotlinmudv2.action.actions.manipulate import kotlinmudv2.action.Action import kotlinmudv2.action.Command import kotlinmudv2.action.Syntax import kotlinmudv2.mob.Disposition fun createSacrificeErrorAction(): Action { return Action( Command.Sacrifice, listOf(Syntax.Command, Syntax.FreeForm), listOf(Disposition.Standing), ) { request -> request.respondError("you don't see that anywhere.") } }
0
Kotlin
0
0
28b5a049c54ad072ccade19c9ad2bb36b9cf8909
447
kotlinmud-v2
MIT License
app/src/main/java/com/absut/todo/ui/task/TaskFragment.kt
Aksx73
533,222,652
false
{"Kotlin": 29719}
package com.absut.todo.ui.task import android.content.DialogInterface import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import androidx.appcompat.widget.SearchView import androidx.core.view.MenuHost import androidx.core.view.MenuProvider import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.setFragmentResultListener import androidx.fragment.app.viewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.absut.todo.R import com.absut.todo.data.SortOrder import com.absut.todo.data.Task import com.absut.todo.databinding.FragmentTaskBinding import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch /** * A simple [Fragment] subclass as the default destination in the navigation. */ @AndroidEntryPoint class TaskFragment : Fragment(R.layout.fragment_task), TaskAdapter.OnItemClickListener, MenuProvider { private val viewModel by viewModels<TaskViewModel>() private lateinit var searchView: SearchView override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val binding = FragmentTaskBinding.bind(view) val menuHost: MenuHost = requireActivity() menuHost.addMenuProvider(this, viewLifecycleOwner, Lifecycle.State.RESUMED) val taskAdapter = TaskAdapter(this) binding.apply { recyclerView.apply { adapter = taskAdapter layoutManager = LinearLayoutManager(requireContext()) setHasFixedSize(true) } ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) { override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { return false } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { val task = taskAdapter.currentList[viewHolder.adapterPosition] viewModel.onTaskSwiped(task) } }).attachToRecyclerView(recyclerView) fab.setOnClickListener { val action = TaskFragmentDirections.actionHomeFragmentToAddEditFragment(null) findNavController().navigate(action) } } setFragmentResultListener("add_edit_request") { _, bundle -> val result = bundle.getInt("add_edit_result") viewModel.onAddEditResult(result) Log.d("TAG", "onViewCreated: $result") } viewModel.tasks.observe(viewLifecycleOwner) { taskAdapter.submitList(it) binding.emptyView.isVisible = it.isEmpty() } observeEvents() } private fun observeEvents() { lifecycleScope.launchWhenStarted { viewModel.tasksEvent.collectLatest { event -> when (event) { is TaskViewModel.TasksEvent.ShowTaskSavedConfirmationMessage -> { Log.d("TAG", "observeEvents: ${event.msg}") Snackbar.make(requireView(), event.msg, Snackbar.LENGTH_SHORT).show() Log.d("TAG", "observeEvents: ${event.msg}") } is TaskViewModel.TasksEvent.ShowUndoDeleteTaskMessage -> { Snackbar.make(requireView(), "Task deleted", Snackbar.LENGTH_LONG) .setAction("Undo") { viewModel.onUndoDeleteClick(event.task) }.show() } } } } } override fun onItemClick(task: Task) { val action = TaskFragmentDirections.actionHomeFragmentToAddEditFragment(task, "Edit Task") findNavController().navigate(action) } override fun onCheckBoxClick(task: Task, isChecked: Boolean) { viewModel.onTaskCheckedChanged(task, isChecked) } override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { menuInflater.inflate(R.menu.menu_main, menu) val searchItem = menu.findItem(R.id.action_search) searchView = searchItem.actionView as SearchView val pendingQuery = viewModel.searchQuery.value if (pendingQuery != null && pendingQuery.isNotEmpty()) { searchItem.expandActionView() searchView.setQuery(pendingQuery, false) } searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { return false } override fun onQueryTextChange(newText: String?): Boolean { viewModel.searchQuery.value = newText return true } }) viewLifecycleOwner.lifecycleScope.launch { menu.findItem(R.id.action_hide_completed).isChecked = viewModel.preferenceFlow.first().hideCompleted } } override fun onMenuItemSelected(menuItem: MenuItem): Boolean { return when (menuItem.itemId) { R.id.action_sort_by_name -> { viewModel.onSortOrderSelected(SortOrder.BY_NAME) true } R.id.action_sort_by_date_created -> { viewModel.onSortOrderSelected(SortOrder.BY_DATE) true } R.id.action_hide_completed -> { menuItem.isChecked = !menuItem.isChecked viewModel.onHideCompletedClick(menuItem.isChecked) true } R.id.action_delete_all_completed -> { deleteAllCompletedTask() true } else -> false } } private fun deleteAllCompletedTask() { MaterialAlertDialogBuilder(requireActivity()) .setTitle("Delete all completed task?") .setMessage("This action cannot be undone") .setPositiveButton("Delete") { _, _ -> viewModel.deleteAllCompletedTask() } .setNegativeButton("Cancel", null) .show() } override fun onDestroyView() { super.onDestroyView() searchView.setOnQueryTextListener(null) } }
0
Kotlin
0
1
223c7cb044319d841d2548bf6435c495004bce40
7,042
TodoApp
MIT License
database/src/test/kotlin/no/nav/su/se/bakover/database/klage/KlageinstanshendelsePostgresRepoTest.kt
navikt
227,366,088
false
null
package no.nav.su.se.bakover.database.klage import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldContain import no.nav.su.se.bakover.database.TestDataHelper import no.nav.su.se.bakover.database.withMigratedDb import no.nav.su.se.bakover.domain.journal.JournalpostId import no.nav.su.se.bakover.domain.klage.KlageinstansUtfall import no.nav.su.se.bakover.domain.klage.ProsessertKlageinstanshendelse import no.nav.su.se.bakover.domain.klage.UprosessertKlageinstanshendelse import no.nav.su.se.bakover.test.fixedTidspunkt import org.junit.jupiter.api.Test import org.postgresql.util.PSQLException import java.util.UUID internal class KlageinstanshendelsePostgresRepoTest { @Test fun `kan opprette uprosessert klageinstanshendelse`() { withMigratedDb { dataSource -> val testDataHelper = TestDataHelper(dataSource) val klageinstanshendelsePostgresRepo = testDataHelper.klageinstanshendelsePostgresRepo val uprosessertKlageinstanshendelse = UprosessertKlageinstanshendelse( id = UUID.randomUUID(), opprettet = fixedTidspunkt, metadata = UprosessertKlageinstanshendelse.Metadata( topic = "klage.vedtak-fattet.v1", hendelseId = UUID.randomUUID().toString(), offset = 1, partisjon = 2, key = UUID.randomUUID().toString(), value = "{}", ), ).also { klageinstanshendelsePostgresRepo.lagre(it) } klageinstanshendelsePostgresRepo.hentUbehandlaKlageinstanshendelser() shouldBe listOf(uprosessertKlageinstanshendelse) } } @Test fun `Dedup på metadata's hendelseId`() { withMigratedDb { dataSource -> val testDataHelper = TestDataHelper(dataSource) val klageinstanshendelsePostgresRepo = testDataHelper.klageinstanshendelsePostgresRepo val uprosessertKlageinstanshendelse = UprosessertKlageinstanshendelse( id = UUID.randomUUID(), opprettet = fixedTidspunkt, metadata = UprosessertKlageinstanshendelse.Metadata( topic = "klage.behandling-events.v1", hendelseId = UUID.randomUUID().toString(), offset = 1, partisjon = 2, key = UUID.randomUUID().toString(), value = "{}", ), ).also { klageinstanshendelsePostgresRepo.lagre(it) klageinstanshendelsePostgresRepo.lagre(it.copy(id = UUID.randomUUID())) } klageinstanshendelsePostgresRepo.hentUbehandlaKlageinstanshendelser() shouldBe listOf(uprosessertKlageinstanshendelse) } } @Test fun `Konflikt på duplikat id`() { withMigratedDb { dataSource -> val testDataHelper = TestDataHelper(dataSource) val klageinstanshendelsePostgresRepo = testDataHelper.klageinstanshendelsePostgresRepo UprosessertKlageinstanshendelse( id = UUID.randomUUID(), opprettet = fixedTidspunkt, metadata = UprosessertKlageinstanshendelse.Metadata( topic = "klage.behandling-events.v1", hendelseId = UUID.randomUUID().toString(), offset = 1, partisjon = 2, key = UUID.randomUUID().toString(), value = "{}", ), ).also { klageinstanshendelsePostgresRepo.lagre(it) shouldThrow<PSQLException> { klageinstanshendelsePostgresRepo.lagre(it) }.message shouldContain "duplicate key value violates unique constraint \"klagevedtak_pkey\"" } } } @Test fun `Endrer og lagrer type til PROSESSERT`() { withMigratedDb { dataSource -> val testDataHelper = TestDataHelper(dataSource) val klageinstanshendelsePostgresRepo = testDataHelper.klageinstanshendelsePostgresRepo val id = UUID.randomUUID() val klage = testDataHelper.persisterKlageOversendt() UprosessertKlageinstanshendelse( id = id, opprettet = fixedTidspunkt, metadata = UprosessertKlageinstanshendelse.Metadata( topic = "klage.behandling-events.v1", hendelseId = UUID.randomUUID().toString(), offset = 1, partisjon = 2, key = UUID.randomUUID().toString(), value = "{\"kildeReferanse\": ${klage.id}}", ), ).also { klageinstanshendelsePostgresRepo.lagre(it) klageinstanshendelsePostgresRepo.lagre( ProsessertKlageinstanshendelse( id = it.id, opprettet = fixedTidspunkt, klageId = klage.id, utfall = KlageinstansUtfall.STADFESTELSE, journalpostIDer = listOf(JournalpostId(UUID.randomUUID().toString())), oppgaveId = null, ), ) klageinstanshendelsePostgresRepo.hentUbehandlaKlageinstanshendelser() shouldBe emptyList() } } } }
5
null
1
1
d7157394e11b5b3c714a420a96211abb0a53ea45
5,548
su-se-bakover
MIT License
csstype-kotlin/src/jsMain/kotlin/web/cssom/BackfaceVisibility.kt
karakum-team
393,199,102
false
{"Kotlin": 6272741}
// Automatically generated - do not modify! package web.cssom import seskar.js.JsValue sealed external interface BackfaceVisibility { companion object { @JsValue("hidden") val hidden: BackfaceVisibility @JsValue("visible") val visible: BackfaceVisibility } }
0
Kotlin
8
36
95b065622a9445caf058ad2581f4c91f9e2b0d91
303
types-kotlin
Apache License 2.0
idea/testData/quickfix/autoImports/importTrait.before.Main.kt
JakeWharton
99,388,807
false
null
// "Import" "true" // ERROR: Unresolved reference: TestTrait fun test() { val a = <caret>TestTrait }
0
null
30
83
4383335168338df9bbbe2a63cb213a68d0858104
106
kotlin
Apache License 2.0
core/src/main/kotlin/dev/komu/kraken/utils/collections/CircularBuffer.kt
komu
83,556,775
false
{"Kotlin": 225797}
package dev.komu.kraken.utils.collections import java.util.* class CircularBuffer<E : Any>(capacity: Int): AbstractCollection<E>() { private val buffer = Array<Any?>(capacity) { null } private var start = 0 private var _size = 0 private var modCount = 0 init { require(capacity > 0) } override fun add(element: E): Boolean { modCount++ if (_size < capacity) { buffer[_size] = element _size++ } else { buffer[start] = element start = (start + 1) % buffer.size } return true } @Suppress("UNCHECKED_CAST") operator fun get(index: Int): E = buffer[index(index)]!! as E private fun set(index: Int, value: E) { modCount++ buffer[index(index)] = value } private fun index(index: Int): Int { if (index < 0 || index >= _size) throw IndexOutOfBoundsException("size=$_size, index=$index") return (start + index) % buffer.size } fun last(): E { if (isEmpty()) throw IllegalStateException("buffer is empty") return get(_size - 1) } fun last(count: Int): List<E> { if (count < 0) throw IllegalArgumentException("negative count") val n = count.coerceAtMost(_size) val result = ArrayList<E>(n) for (i in 0 until n) result.add(get(_size - n + i)) return result } fun replaceLast(value: E) { if (isEmpty()) throw IllegalStateException("buffer is empty") modCount++ set(_size - 1, value) } override fun clear() { _size = 0 start = 0 modCount++ for (i in buffer.indices) buffer[i] = null } override fun isEmpty() = _size == 0 override val size: Int get() = _size val capacity: Int get() = buffer.size override fun iterator(): MutableIterator<E> = BufferIterator() override fun equals(other: Any?): Boolean { if (other == this) return true if (other is CircularBuffer<*>) { return if (_size == other._size && buffer.size == other.buffer.size) { indices.none { this[it] != other[it] } } else false } return false } override fun hashCode(): Int { var hash = 0 for (i in this.indices) hash = hash * 79 + this[i].hashCode() return hash } private inner class BufferIterator: MutableIterator<E> { private var index: Int = 0 private val expectedModCount = modCount override fun hasNext() = index < _size override fun next(): E { if (modCount != expectedModCount) throw ConcurrentModificationException() return get(index++) } override fun remove() = throw UnsupportedOperationException("remove not supported") } }
0
Kotlin
0
0
680362d8e27c475b4ef1e2d13b67cb87f67249f6
3,016
kraken
Apache License 2.0
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/motion/updown/MotionShiftUpAction.kt
JetBrains
1,459,486
false
null
/* * Copyright 2003-2023 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.action.motion.updown import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimCaret import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.command.Command import com.maddyhome.idea.vim.handler.Motion import com.maddyhome.idea.vim.handler.ShiftedArrowKeyHandler /** * @author <NAME> */ public class MotionShiftUpAction : ShiftedArrowKeyHandler(false) { override val type: Command.Type = Command.Type.OTHER_READONLY override fun motionWithKeyModel(editor: VimEditor, caret: VimCaret, context: ExecutionContext, cmd: Command) { val vertical = injector.motion.getVerticalMotionOffset(editor, caret, -cmd.count) when (vertical) { is Motion.AdjustedOffset -> { caret.moveToOffset(vertical.offset) caret.vimLastColumn = vertical.intendedColumn } is Motion.AbsoluteOffset -> caret.moveToOffset(vertical.offset) is Motion.NoMotion -> {} is Motion.Error -> injector.messages.indicateError() } } override fun motionWithoutKeyModel(editor: VimEditor, context: ExecutionContext, cmd: Command) { injector.scroll.scrollFullPage(editor, editor.primaryCaret(), -cmd.count) } }
9
null
749
9,241
66b01b0b0d48ffec7b0148465b85e43dfbc908d3
1,473
ideavim
MIT License
necsdkwrapper/src/main/java/jp/co/zeppelin/nec/hearable/necsdkwrapper/model/NecHearableVoiceMemoResp.kt
ZEPPELINpublic
238,634,924
false
null
package jp.co.zeppelin.nec.hearable.necsdkwrapper.model /** * NEC Hearable voice memo response observables * * (c) 2020 Zeppelin Inc., Shibuya, Tokyo JAPAN */ /** * Result of attempting to record voice memo to local .wav file */ sealed class NecHearableVoiceMemoRecordRespBase class NecHearableVoiceMemoRecordSuccess : NecHearableVoiceMemoRecordRespBase() class NecHearableVoiceMemoRecordFail : NecHearableVoiceMemoRecordRespBase() /** * Result of attempting upload of local voice memo recorded .wav file to server */ sealed class NecHearableVoiceMemoUploadRespBase class NecHearableVoiceMemoUploadSuccess : NecHearableVoiceMemoUploadRespBase() class NecHearableVoiceMemoUploadFail : NecHearableVoiceMemoUploadRespBase()
0
Kotlin
0
0
a7f6ff9365602a2b024eb2fa4eafa191422c0f89
736
earpiece_recognition
MIT License
js/js.translator/testData/box/rtti/sideEffectProperty.kt
JakeWharton
99,388,807
false
null
// EXPECTED_REACHABLE_NODES: 1117 package foo var counter = 0 class A { fun getCounter(): Any? = when (counter++) { 0 -> "0" 1 -> null else -> counter } } fun box(): String { assertEquals(false, A().getCounter() is Int?, "(1)") assertEquals(true, A().getCounter() is Int?, "(2)") assertEquals(true, A().getCounter() is Int?, "(3)") assertEquals(3, counter) return "OK" }
184
null
5691
83
4383335168338df9bbbe2a63cb213a68d0858104
450
kotlin
Apache License 2.0
debugger/src/main/kotlin/org/rust/debugger/runconfig/RsLocalDebugProcess.kt
SaarYogev
211,165,404
true
{"Kotlin": 3257698, "Rust": 77474, "Lex": 18933, "HTML": 11268, "Shell": 760, "Java": 586, "RenderScript": 318}
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.debugger.runconfig import com.intellij.execution.filters.TextConsoleBuilder import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.xdebugger.XDebugSession import com.jetbrains.cidr.execution.RunParameters import com.jetbrains.cidr.execution.debugger.CidrLocalDebugProcess import com.jetbrains.cidr.execution.debugger.backend.DebuggerCommandException import com.jetbrains.cidr.execution.debugger.backend.gdb.GDBDriver import com.jetbrains.cidr.execution.debugger.backend.lldb.LLDBDriver class RsLocalDebugProcess( parameters: RunParameters, debugSession: XDebugSession, consoleBuilder: TextConsoleBuilder ) : CidrLocalDebugProcess(parameters, debugSession, consoleBuilder) { fun loadPrettyPrinters(sysroot: String) { val threadId = currentThreadId val frameIndex = currentFrameIndex postCommand { driver -> when (driver) { is LLDBDriver -> driver.loadPrettyPrinters(threadId, frameIndex, sysroot) is GDBDriver -> driver.loadPrettyPrinters(threadId, frameIndex, sysroot) } } } private fun LLDBDriver.loadPrettyPrinters(threadId: Long, frameIndex: Int, sysroot: String) { val path = "$sysroot/lib/rustlib/etc/lldb_rust_formatters.py".systemDependentAndEscaped() try { executeConsoleCommand(threadId, frameIndex, """command script import "$path"""") executeConsoleCommand(threadId, frameIndex, """type summary add --no-value --python-function lldb_rust_formatters.print_val -x ".*" --category Rust""") executeConsoleCommand(threadId, frameIndex, """type category enable Rust""") } catch (e: DebuggerCommandException) { printlnToConsole(e.message) LOG.warn(e) } } private fun GDBDriver.loadPrettyPrinters(threadId: Long, frameIndex: Int, sysroot: String) { val path = "$sysroot/lib/rustlib/etc".systemDependentAndEscaped() // Avoid multiline Python scripts due to https://youtrack.jetbrains.com/issue/CPP-9090 val command = """python """ + """sys.path.insert(0, "$path"); """ + """import gdb_rust_pretty_printing; """ + """gdb_rust_pretty_printing.register_printers(gdb); """ try { executeConsoleCommand(threadId, frameIndex, command) } catch (e: DebuggerCommandException) { printlnToConsole(e.message) LOG.warn(e) } } private fun String.systemDependentAndEscaped(): String = StringUtil.escapeStringCharacters(FileUtil.toSystemDependentName(this)) companion object { private val LOG: Logger = Logger.getInstance(RsLocalDebugProcess::class.java) } }
0
null
0
1
26be75d84b07150b9f4687216cc4923221de659f
2,945
intellij-rust
MIT License
plugins/devkit/devkit-kotlin-tests/testData/inspections/componentNotRegistered/RegisteredApplicationComponent.kt
hieuprogrammer
284,920,751
true
null
import com.intellij.openapi.components.BaseComponent class RegisteredApplicationComponent : BaseComponent { class InnerStaticClassApplicationContext : BaseComponent }
1
null
1
2
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
170
intellij-community
Apache License 2.0
plugins/devkit/devkit-kotlin-tests/testData/inspections/componentNotRegistered/RegisteredApplicationComponent.kt
hieuprogrammer
284,920,751
true
null
import com.intellij.openapi.components.BaseComponent class RegisteredApplicationComponent : BaseComponent { class InnerStaticClassApplicationContext : BaseComponent }
1
null
1
2
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
170
intellij-community
Apache License 2.0
compiler/testData/codegen/box/coroutines/featureIntersection/safeCallOnTwoReceivers.kt
JakeWharton
99,388,807
false
null
// IGNORE_BACKEND: NATIVE // WITH_RUNTIME // WITH_COROUTINES import kotlin.coroutines.experimental.* import kotlin.coroutines.experimental.intrinsics.* import kotlin.test.assertEquals class A(val w: String) { suspend fun String.ext(): String = suspendCoroutineOrReturn { x -> x.resume(this + w) COROUTINE_SUSPENDED } } suspend fun A.coroutinebug(v: String?): String { val r = v?.ext() if (r == null) return "null" return r } suspend fun A.coroutinebug2(v: String?): String { val r = v?.ext() ?: "null" return r } fun builder(c: suspend () -> Unit) { c.startCoroutine(EmptyContinuation) } fun box(): String { var result = "fail 2" builder { val a = A("K") val x1 = a.coroutinebug(null) if (x1 != "null") throw RuntimeException("fail 1: $x1") val x2 = a.coroutinebug(null) if (x2 != "null") throw RuntimeException("fail 2: $x2") val x3 = a.coroutinebug2(null) if (x3 != "null") throw RuntimeException("fail 3: $x3") result = a.coroutinebug2("O") } return result }
181
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
1,108
kotlin
Apache License 2.0
app/src/main/java/com/app/whakaara/ui/loading/Loading.kt
ahudson20
531,856,934
false
{"Kotlin": 536307}
package com.app.whakaara.ui.loading import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.width import androidx.compose.material3.CircularProgressIndicator import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import com.app.whakaara.ui.theme.FontScalePreviews import com.app.whakaara.ui.theme.Spacings.spaceXxLarge import com.app.whakaara.ui.theme.ThemePreviews import com.app.whakaara.ui.theme.WhakaaraTheme @Composable fun Loading(modifier: Modifier = Modifier) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, modifier = modifier .fillMaxSize() ) { CircularProgressIndicator( modifier = Modifier .width(spaceXxLarge) .height(spaceXxLarge) ) } } @Composable @ThemePreviews @FontScalePreviews fun LoadingPreview() { WhakaaraTheme { Loading() } }
2
Kotlin
3
30
f63a8f59815bec094a6d0c19d0368a87a2b87923
1,186
whakaara
MIT License
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/sagemaker/CfnModelCardMetricDataItemsPropertyDsl.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 70198112}
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package io.cloudshiftdev.awscdkdsl.services.sagemaker import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker import io.cloudshiftdev.awscdkdsl.common.MapBuilder import kotlin.Any import kotlin.String import kotlin.Unit import kotlin.collections.Collection import kotlin.collections.MutableList import software.amazon.awscdk.services.sagemaker.CfnModelCard /** * Metric data. * * The `type` determines the data types that you specify for `value` , `XAxisName` and `YAxisName` . * For information about specifying values for metrics, see * [model card JSON schema](https://docs.aws.amazon.com/sagemaker/latest/dg/model-cards.html#model-cards-json-schema) * . * * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.sagemaker.*; * Object value; * MetricDataItemsProperty metricDataItemsProperty = MetricDataItemsProperty.builder() * .name("name") * .type("type") * .value(value) * // the properties below are optional * .notes("notes") * .xAxisName(List.of("xAxisName")) * .yAxisName(List.of("yAxisName")) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sagemaker-modelcard-metricdataitems.html) */ @CdkDslMarker public class CfnModelCardMetricDataItemsPropertyDsl { private val cdkBuilder: CfnModelCard.MetricDataItemsProperty.Builder = CfnModelCard.MetricDataItemsProperty.builder() private val _xAxisName: MutableList<String> = mutableListOf() private val _yAxisName: MutableList<String> = mutableListOf() /** @param name the value to be set. */ public fun name(name: String) { cdkBuilder.name(name) } /** @param notes the value to be set. */ public fun notes(notes: String) { cdkBuilder.notes(notes) } /** @param type the value to be set. */ public fun type(type: String) { cdkBuilder.type(type) } /** @param value the value to be set. */ public fun `value`(`value`: MapBuilder.() -> Unit = {}) { val builder = MapBuilder() builder.apply(`value`) cdkBuilder.`value`(builder.map) } /** @param value the value to be set. */ public fun `value`(`value`: Any) { cdkBuilder.`value`(`value`) } /** @param xAxisName the value to be set. */ public fun xAxisName(vararg xAxisName: String) { _xAxisName.addAll(listOf(*xAxisName)) } /** @param xAxisName the value to be set. */ public fun xAxisName(xAxisName: Collection<String>) { _xAxisName.addAll(xAxisName) } /** @param yAxisName the value to be set. */ public fun yAxisName(vararg yAxisName: String) { _yAxisName.addAll(listOf(*yAxisName)) } /** @param yAxisName the value to be set. */ public fun yAxisName(yAxisName: Collection<String>) { _yAxisName.addAll(yAxisName) } public fun build(): CfnModelCard.MetricDataItemsProperty { if (_xAxisName.isNotEmpty()) cdkBuilder.xAxisName(_xAxisName) if (_yAxisName.isNotEmpty()) cdkBuilder.yAxisName(_yAxisName) return cdkBuilder.build() } }
0
Kotlin
0
3
256ad92aebe2bcf9a4160089a02c76809dbbedba
3,427
awscdk-dsl-kotlin
Apache License 2.0
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/sagemaker/CfnModelCardMetricDataItemsPropertyDsl.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 70198112}
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package io.cloudshiftdev.awscdkdsl.services.sagemaker import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker import io.cloudshiftdev.awscdkdsl.common.MapBuilder import kotlin.Any import kotlin.String import kotlin.Unit import kotlin.collections.Collection import kotlin.collections.MutableList import software.amazon.awscdk.services.sagemaker.CfnModelCard /** * Metric data. * * The `type` determines the data types that you specify for `value` , `XAxisName` and `YAxisName` . * For information about specifying values for metrics, see * [model card JSON schema](https://docs.aws.amazon.com/sagemaker/latest/dg/model-cards.html#model-cards-json-schema) * . * * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.sagemaker.*; * Object value; * MetricDataItemsProperty metricDataItemsProperty = MetricDataItemsProperty.builder() * .name("name") * .type("type") * .value(value) * // the properties below are optional * .notes("notes") * .xAxisName(List.of("xAxisName")) * .yAxisName(List.of("yAxisName")) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sagemaker-modelcard-metricdataitems.html) */ @CdkDslMarker public class CfnModelCardMetricDataItemsPropertyDsl { private val cdkBuilder: CfnModelCard.MetricDataItemsProperty.Builder = CfnModelCard.MetricDataItemsProperty.builder() private val _xAxisName: MutableList<String> = mutableListOf() private val _yAxisName: MutableList<String> = mutableListOf() /** @param name the value to be set. */ public fun name(name: String) { cdkBuilder.name(name) } /** @param notes the value to be set. */ public fun notes(notes: String) { cdkBuilder.notes(notes) } /** @param type the value to be set. */ public fun type(type: String) { cdkBuilder.type(type) } /** @param value the value to be set. */ public fun `value`(`value`: MapBuilder.() -> Unit = {}) { val builder = MapBuilder() builder.apply(`value`) cdkBuilder.`value`(builder.map) } /** @param value the value to be set. */ public fun `value`(`value`: Any) { cdkBuilder.`value`(`value`) } /** @param xAxisName the value to be set. */ public fun xAxisName(vararg xAxisName: String) { _xAxisName.addAll(listOf(*xAxisName)) } /** @param xAxisName the value to be set. */ public fun xAxisName(xAxisName: Collection<String>) { _xAxisName.addAll(xAxisName) } /** @param yAxisName the value to be set. */ public fun yAxisName(vararg yAxisName: String) { _yAxisName.addAll(listOf(*yAxisName)) } /** @param yAxisName the value to be set. */ public fun yAxisName(yAxisName: Collection<String>) { _yAxisName.addAll(yAxisName) } public fun build(): CfnModelCard.MetricDataItemsProperty { if (_xAxisName.isNotEmpty()) cdkBuilder.xAxisName(_xAxisName) if (_yAxisName.isNotEmpty()) cdkBuilder.yAxisName(_yAxisName) return cdkBuilder.build() } }
0
Kotlin
0
3
256ad92aebe2bcf9a4160089a02c76809dbbedba
3,427
awscdk-dsl-kotlin
Apache License 2.0
cca-app/src/main/java/ru/sodajl/chordconsonanceanalyzer/MainActivity.kt
SoDa-Salie
407,555,972
false
null
package ru.sodajl.chordconsonanceanalyzer import android.app.Activity import android.os.Bundle import android.util.Log import android.view.View import android.view.Window import android.view.WindowManager import ru.sodajl.chordconsonanceanalyzer.androidaudiodevice.JSynAndroidAudioDevice import ru.sodajl.chordconsonanceanalyzer.databinding.ActivityMainBinding import ru.sodajl.chordconsonanceanalyzer.osc.core.OscData import ru.sodajl.chordconsonanceanalyzer.osc.core.OscFunctions import ru.sodajl.chordconsonanceanalyzer.osc.factory.OscCreator import ru.sodajl.chordconsonanceanalyzer.osc.factory.OscPlaybackModes import ru.sodajl.chordconsonanceanalyzer.osc.factory.OscWaveForms class MainActivity : Activity() { private lateinit var binding: ActivityMainBinding val LOG_TAG = "myLogs" private lateinit var oscCreatorInfinite: OscCreator private lateinit var oscCreatorFinite: OscCreator private lateinit var device: JSynAndroidAudioDevice private lateinit var playbackMode: OscPlaybackModes override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) requestWindowFeature(Window.FEATURE_NO_TITLE) requestWindowFeature(Window.FEATURE_ACTION_BAR) window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN) //ViewBinding как способ вытащить сконфигурированные вьюхи binding = ActivityMainBinding.inflate(layoutInflater) val view = binding.root setContentView(view) device = JSynAndroidAudioDevice() playbackMode = OscPlaybackModes.INFINITE oscCreatorInfinite = OscCreator( 15, OscWaveForms.SINE, OscPlaybackModes.INFINITE, 220.0, 4.0, device ) oscCreatorFinite = OscCreator( 15, OscWaveForms.SINE, OscPlaybackModes.FINITE, 220.0, 4.0, device ) binding.btnPlay.setOnClickListener { val oscData: OscData val oscFunctions: OscFunctions if (playbackMode == OscPlaybackModes.INFINITE) { oscData = oscCreatorInfinite.getOscData() oscFunctions = oscCreatorInfinite.getOscFunctions() oscFunctions.performStart() } else { oscData = oscCreatorFinite.getOscData() oscFunctions = oscCreatorFinite.getOscFunctions() oscFunctions.performStartFor(oscData.getDuration().toLong()) } /*binding.btnPlay.isEnabled = oscFunctions.getLifecycleState() == OscLifecycleStates.STOPPED.name*/ binding.btnPlaybackMode.isEnabled = false } binding.btnStop.setOnClickListener { val oscData: OscData val oscFunctions: OscFunctions if (playbackMode == OscPlaybackModes.INFINITE) { oscData = oscCreatorInfinite.getOscData() oscFunctions = oscCreatorInfinite.getOscFunctions() oscFunctions.performStop() } else { oscData = oscCreatorFinite.getOscData() oscFunctions = oscCreatorFinite.getOscFunctions() oscFunctions.performStop() } /*binding.btnStop.isEnabled = oscFunctions.getLifecycleState() == OscLifecycleStates.STARTED.name*/ binding.btnPlaybackMode.isEnabled = true } binding.btnDecreaseFrequency.setOnClickListener { val oscData: OscData if (playbackMode == OscPlaybackModes.INFINITE) oscData = oscCreatorInfinite.getOscData() else oscData = oscCreatorFinite.getOscData() val currentFrequency = oscData.getFrequency() oscData.setFrequency(currentFrequency - 5.0) } binding.btnIncreaseFrequency.setOnClickListener { val oscData: OscData if (playbackMode == OscPlaybackModes.INFINITE) oscData = oscCreatorInfinite.getOscData() else oscData = oscCreatorFinite.getOscData() val currentFrequency = oscData.getFrequency() oscData.setFrequency(currentFrequency + 5.0) } binding.btnPlaybackMode.setOnClickListener { if(playbackMode == OscPlaybackModes.INFINITE) playbackMode = OscPlaybackModes.FINITE else playbackMode = OscPlaybackModes.INFINITE } } override fun onResume() { super.onResume() window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY } override fun onStop() { super.onStop() Log.d(LOG_TAG, "onStop") val oscFunctions: OscFunctions if (playbackMode == OscPlaybackModes.INFINITE) { oscFunctions = oscCreatorInfinite.getOscFunctions() oscFunctions.performStop() } else { oscFunctions = oscCreatorFinite.getOscFunctions() oscFunctions.performStop() } } }
0
Kotlin
0
0
4bd087690b73db5cfcc28446f2a7e526695feb02
4,287
ChordConsonanceAnalyzer
Apache License 2.0
src/main/kotlin/com/yanicksenn/miniretrieval/parser/AnyDocumentParser.kt
yanicksenn
512,225,699
false
{"Kotlin": 62130}
package com.yanicksenn.miniretrieval.parser import com.yanicksenn.miniretrieval.parser.adapter.PDFDocumentParser import com.yanicksenn.miniretrieval.parser.adapter.PPTDocumentParser import com.yanicksenn.miniretrieval.parser.adapter.TXTDocumentParser import com.yanicksenn.miniretrieval.to.Document import java.io.File object AnyDocumentParser : IDocumentParser { override fun parse(file: File): Sequence<Document> { return when (file.extension.lowercase()) { "pdf" -> PDFDocumentParser.parse(file) "pptx", "ppt" -> PPTDocumentParser.parse(file) "txt" -> TXTDocumentParser.parse(file) else -> emptySequence() } } }
2
Kotlin
0
0
f168ac3a51a30478b21b73e40488266ff8ae9320
688
mini-retrieval
MIT License
amadeus-android/src/main/java/com/amadeus/android/Analytics.kt
amadeus4dev-examples
251,277,473
false
{"Kotlin": 407450}
package com.amadeus.android import com.amadeus.android.analytics.ItineraryPriceMetrics import com.squareup.moshi.Moshi import kotlinx.coroutines.CoroutineDispatcher import okhttp3.OkHttpClient import retrofit2.Retrofit class Analytics internal constructor( retrofit: Retrofit, dispatcher: CoroutineDispatcher ) { /** * A namespaced client for the * `/v1/analytics/itinerary-price-metrics` endpoints. */ val itineraryPriceMetrics = ItineraryPriceMetrics(retrofit, dispatcher) }
14
Kotlin
8
19
0dc89b54f1fceae6038d50a3566b1f7a2a874b90
512
amadeus-android
MIT License
node-api/src/main/kotlin/net/corda/nodeapi/internal/IdentityGenerator.kt
shotishu
116,027,287
true
{"Kotlin": 4488931, "Java": 224503, "Groovy": 11712, "Shell": 1884, "Batchfile": 106}
package net.corda.nodeapi.internal import net.corda.core.crypto.CompositeKey import net.corda.core.crypto.Crypto import net.corda.core.crypto.generateKeyPair import net.corda.core.identity.CordaX500Name import net.corda.core.identity.Party import net.corda.core.internal.cert import net.corda.core.internal.createDirectories import net.corda.core.internal.div import net.corda.core.internal.toX509CertHolder import net.corda.core.utilities.trace import net.corda.nodeapi.internal.config.NodeSSLConfiguration import net.corda.nodeapi.internal.crypto.* import org.slf4j.LoggerFactory import java.nio.file.Path import java.security.cert.X509Certificate /** * Contains utility methods for generating identities for a node. * * WARNING: This is not application for production use and must never called by the node. */ // TODO Rename to DevIdentityGenerator object IdentityGenerator { private val log = LoggerFactory.getLogger(javaClass) // TODO These don't need to be prefixes but can be the full aliases // TODO Move these constants out of here as the node needs access to them const val NODE_IDENTITY_ALIAS_PREFIX = "identity" const val DISTRIBUTED_NOTARY_ALIAS_PREFIX = "distributed-notary" /** * Install a node key store for the given node directory using the given legal name and an optional root cert. If no * root cert is specified then the default one in certificates/cordadevcakeys.jks is used. */ fun installKeyStoreWithNodeIdentity(nodeDir: Path, legalName: CordaX500Name, customRootCert: X509Certificate? = null): Party { val nodeSslConfig = object : NodeSSLConfiguration { override val baseDirectory = nodeDir override val keyStorePassword: String = "<PASSWORD>" override val trustStorePassword get() = throw NotImplementedError("Not expected to be called") } // TODO The passwords for the dev key stores are spread everywhere and should be constants in a single location val caKeyStore = loadKeyStore(javaClass.classLoader.getResourceAsStream("certificates/cordadevcakeys.jks"), "cordacadevpass") val intermediateCa = caKeyStore.getCertificateAndKeyPair(X509Utilities.CORDA_INTERMEDIATE_CA, "cordacadevkeypass") // TODO If using a custom root cert, then the intermidate cert needs to be generated from it as well, and not taken from the default val rootCert = customRootCert ?: caKeyStore.getCertificate(X509Utilities.CORDA_ROOT_CA) nodeSslConfig.certificatesDirectory.createDirectories() nodeSslConfig.createDevKeyStores(rootCert.toX509CertHolder(), intermediateCa, legalName) val keyStoreWrapper = KeyStoreWrapper(nodeSslConfig.nodeKeystore, nodeSslConfig.keyStorePassword) val identity = keyStoreWrapper.storeLegalIdentity(legalName, "$NODE_IDENTITY_ALIAS_PREFIX-private-key", Crypto.generateKeyPair()) return identity.party } fun generateDistributedNotaryIdentity(dirs: List<Path>, notaryName: CordaX500Name, threshold: Int = 1, customRootCert: X509Certificate? = null): Party { require(dirs.isNotEmpty()) log.trace { "Generating identity \"$notaryName\" for nodes: ${dirs.joinToString()}" } val keyPairs = (1..dirs.size).map { generateKeyPair() } val compositeKey = CompositeKey.Builder().addKeys(keyPairs.map { it.public }).build(threshold) val caKeyStore = loadKeyStore(javaClass.classLoader.getResourceAsStream("certificates/cordadevcakeys.jks"), "cordacadevpass") val intermediateCa = caKeyStore.getCertificateAndKeyPair(X509Utilities.CORDA_INTERMEDIATE_CA, "cordacadevkeypass") // TODO If using a custom root cert, then the intermidate cert needs to be generated from it as well, and not taken from the default val rootCert = customRootCert ?: caKeyStore.getCertificate(X509Utilities.CORDA_ROOT_CA) keyPairs.zip(dirs) { keyPair, nodeDir -> val (serviceKeyCert, compositeKeyCert) = listOf(keyPair.public, compositeKey).map { publicKey -> X509Utilities.createCertificate(CertificateType.SERVICE_IDENTITY, intermediateCa.certificate, intermediateCa.keyPair, notaryName, publicKey) } val distServKeyStoreFile = (nodeDir / "certificates").createDirectories() / "distributedService.jks" val keystore = loadOrCreateKeyStore(distServKeyStoreFile, "cordacadevpass") keystore.setCertificateEntry("$DISTRIBUTED_NOTARY_ALIAS_PREFIX-composite-key", compositeKeyCert.cert) keystore.setKeyEntry( "$DISTRIBUTED_NOTARY_ALIAS_PREFIX-private-key", keyPair.private, "cordacadevkeypass".toCharArray(), arrayOf(serviceKeyCert.cert, intermediateCa.certificate.cert, rootCert)) keystore.save(distServKeyStoreFile, "cordacadevpass") } return Party(notaryName, compositeKey) } }
0
Kotlin
0
0
fe3c2b39839387f3a655024f26d96bc600b74d50
4,943
corda
Apache License 2.0
app/src/main/java/com/simplepeople/watcha/ui/main/favorite/FavoriteScreen.kt
hbjosemaria
786,895,118
false
{"Kotlin": 425852, "HTML": 9109}
package com.simplepeople.watcha.ui.main.favorite import androidx.compose.animation.Crossfade import androidx.compose.animation.core.tween import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.navigationBars import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.grid.LazyGridState import androidx.compose.foundation.lazy.grid.rememberLazyGridState import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Scaffold import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.paging.LoadState import androidx.paging.compose.collectAsLazyPagingItems import com.simplepeople.watcha.R import com.simplepeople.watcha.ui.common.composables.ImageWithMessage import com.simplepeople.watcha.ui.common.composables.LoadingIndicator import com.simplepeople.watcha.ui.common.composables.SharedNavigationBar import com.simplepeople.watcha.ui.common.composables.movielist.MovieList import com.simplepeople.watcha.ui.common.composables.topbar.MainTopAppBar import com.simplepeople.watcha.ui.navigation.UserProfileResult @OptIn(ExperimentalMaterial3Api::class) @Composable fun FavoriteScreen( favoriteViewModel: FavoriteViewModel = hiltViewModel(), lazyGridState: LazyGridState = rememberLazyGridState(), navigateToMovieDetails: (Long) -> Unit, navigateToNavigationBarItem: (String) -> Unit, userProfileResult: UserProfileResult, updateNavigationItemIndex: (Int) -> Unit, selectedNavigationItemIndex: Int, ) { val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior() val favoriteScreenUiState by favoriteViewModel.favoriteScreenState.collectAsState() LaunchedEffect(favoriteScreenUiState.scrollToTop) { if (favoriteScreenUiState.scrollToTop) { lazyGridState.scrollToItem(0) favoriteViewModel.scrollingToTop(false) } } Scaffold( contentWindowInsets = WindowInsets.navigationBars, bottomBar = { SharedNavigationBar( navigateToNavigationBarItem = navigateToNavigationBarItem, selectedNavigationItemIndex = selectedNavigationItemIndex, updateNavigationBarSelectedIndex = updateNavigationItemIndex, scrollToTopAction = { favoriteViewModel.scrollingToTop(true) }, avatarUrl = if (userProfileResult is UserProfileResult.Success) { userProfileResult.userProfile.getUserImageUrl() } else "" ) } ) { innerPadding -> Crossfade( targetState = favoriteScreenUiState.movieListState, label = "List animation", animationSpec = tween(350) ) { state -> Box( modifier = Modifier .padding(innerPadding) .nestedScroll(scrollBehavior.nestedScrollConnection) .fillMaxSize() ) { when (state) { is FavoriteScreenMovieListState.Error -> { ImageWithMessage( modifier = Modifier .align(Alignment.Center), image = R.drawable.movie_list_loading_error, message = R.string.movie_list_error ) } is FavoriteScreenMovieListState.Loading -> { LoadingIndicator( modifier = Modifier .align(Alignment.Center) ) } is FavoriteScreenMovieListState.Success -> { val movieList = state.movieList.collectAsLazyPagingItems() when { movieList.itemCount > 0 -> { MovieList( movieList = movieList, navigateToMovieDetails = navigateToMovieDetails, lazyGridState = lazyGridState, paddingValues = PaddingValues( top = 98.dp, start = 10.dp, end = 10.dp, bottom = 10.dp ) ) } movieList.itemCount == 0 && movieList.loadState.source.append == LoadState.NotLoading( endOfPaginationReached = true ) -> { ImageWithMessage( modifier = Modifier .align(Alignment.Center), image = R.drawable.favorite_empty, message = R.string.favorite_list_empty ) } } } } } MainTopAppBar( scrollBehavior = scrollBehavior ) } } }
0
Kotlin
0
3
9a0f988d4cee4a9c68122321b076ad75d348276a
5,952
Watcha
Apache License 2.0
P12781.kt
daily-boj
253,815,781
false
null
data class Vector2(val x: Double, val y: Double) : Comparable<Vector2> { fun cross(other: Vector2): Double = this.x * other.y - this.y * other.x operator fun times(r: Double): Vector2 = Vector2(this.x * r, this.y * r) operator fun plus(other: Vector2): Vector2 = Vector2(this.x + other.x, this.y + other.y) operator fun minus(other: Vector2): Vector2 = Vector2(this.x - other.x, this.y - other.y) override fun compareTo(other: Vector2): Int { val xCompared = this.x.compareTo(other.x) return if (xCompared != 0) { xCompared } else { this.y.compareTo(other.y) } } } fun ccw(p: Vector2, a: Vector2, b: Vector2): Double = (a - p).cross(b - p) fun lineIntersection(a: Vector2, b: Vector2, c: Vector2, d: Vector2): Boolean { val ab = ccw(a, b, c) * ccw(a, b, d) val cd = ccw(c, d, a) * ccw(c, d, b) return ab < 0 && cd < 0 } fun main(args: Array<out String>) { val (a, b, c, d) = readLine()!! .split(" ") .filter { it.isNotEmpty() } .map { it.toDouble() } .chunked(2) .map { (x, y) -> Vector2(x, y) } if (lineIntersection(a, b, c, d)) { println(1) } else { println(0) } }
0
Rust
0
12
74294a4628e96a64def885fdcdd9c1444224802c
1,271
RanolP
The Unlicense
room/room-gradle-plugin/src/main/java/androidx/room/gradle/RoomSchemaCopyTask.kt
androidx
256,589,781
false
{"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
/* * Copyright 2024 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.gradle import java.io.File import java.security.MessageDigest import kotlin.io.path.copyTo import kotlin.io.path.createDirectories import org.gradle.api.DefaultTask import org.gradle.api.GradleException import org.gradle.api.file.Directory import org.gradle.api.file.DirectoryProperty import org.gradle.api.provider.ListProperty import org.gradle.api.tasks.IgnoreEmptyDirectories import org.gradle.api.tasks.InputFiles import org.gradle.api.tasks.Internal import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.SkipWhenEmpty import org.gradle.api.tasks.TaskAction import org.gradle.work.DisableCachingByDefault /** * This copy task consolidates schemas files from annotation processing tasks where room-compiler * runs and exports schemas, moving them to a user configured location so they can be checked-in as * part of their codebase and to be used for migration tests. * * This task does not correctly declare outputs by design. But in practice, the [schemaDirectory] is * the output of this task. This is done to avoid circular task dependencies between the annotation * processing task (javac, ksp or kapt) as the [schemaDirectory] is also an input of those tasks. * The circle is broken by this task not correctly defining its output and instead relying on * [org.gradle.api.Task.finalizedBy]. However, this task is in most cases skipped due to its usage * of `@SkipWhenEmpty` and `@IgnoreEmptyDirectories` and because room-compiler will only export * schemas if the database definition changed. This is a compromise done to fix and improve various * caching and inconsistency issues when exporting Room schema files from an annotation processor * task. * * Consolidation of schemas files is done for various Android variants (e.g. debug, release, etc) or * Kotlin targets (e.g. linuxX64, jvm, etc) since a user can declare a schema location for multiple * annotation processing tasks due to the database definition being the same. This tasks validates * that is the case with a simple checksum. See [RoomExtension.schemaDirectory] for more * information. */ @DisableCachingByDefault(because = "Simple disk bound task.") abstract class RoomSchemaCopyTask : DefaultTask() { @get:InputFiles @get:SkipWhenEmpty @get:IgnoreEmptyDirectories @get:PathSensitive(PathSensitivity.RELATIVE) abstract val apTaskSchemaOutputDirectories: ListProperty<Directory> @get:Internal abstract val schemaDirectory: DirectoryProperty @TaskAction fun copySchemas() { // Map of relative path to its source file hash. val copiedHashes = mutableMapOf<String, MutableMap<String, String>>() apTaskSchemaOutputDirectories .get() .map { it.asFile } .filter { it.exists() } .forEach { outputDir -> outputDir .walkTopDown() .filter { it.isFile } .forEach { schemaFile -> val schemaPath = schemaFile.toPath() val basePath = outputDir.toPath().relativize(schemaPath) val target = schemaDirectory.get().asFile.toPath().resolve(basePath).apply { parent?.createDirectories() } schemaPath.copyTo(target = target, overwrite = true) copiedHashes .getOrPut(basePath.toString()) { mutableMapOf() } .put(schemaFile.sha256(), schemaPath.toString()) } } // Validate that if multiple schema files for the same database and version are copied // to the same schema directory that they are the same in content (via checksum), as // otherwise it would indicate per-variant schemas and thus requiring per-variant // schema directories. copiedHashes .filterValues { it.size > 1 } .forEach { (_, hashes) -> val errorMsg = buildString { appendLine( "Inconsistency detected exporting Room schema files (checksum - source):" ) hashes.entries.forEach { appendLine(" ${it.key} - ${it.value}") } appendLine( "The listed files differ in content but were copied into the same " + "schema directory '${schemaDirectory.get()}'. A possible indicator that " + "per-variant / per-target schema locations must be provided." ) } throw GradleException(errorMsg) } } private fun File.sha256(): String { return MessageDigest.getInstance("SHA-256").digest(this.readBytes()).joinToString("") { "%02x".format(it) } } }
29
Kotlin
1011
5,321
98b929d303f34d569e9fd8a529f022d398d1024b
5,619
androidx
Apache License 2.0
src/main/kotlin/days/Day9.kt
hughjdavey
159,955,618
false
null
package days import util.infiniteList import java.util.LinkedList class Day9 : Day(9) { private val players = inputString.substring(0..inputString.indexOf(" players")).trim().toInt() private val lastMarbleScore = inputString.substring(inputString.indexOf("worth ") + 6..inputString.indexOf(" points")).trim().toInt() override fun partOne(): Any { return winningScore(players, lastMarbleScore) } override fun partTwo(): Any { return winningScore(players, lastMarbleScore * 100) } companion object { fun winningScore(players: Int, lastMarble: Int): Long { val playersLoop = infiniteList((1L .. players).map { Player(it) }).withIndex() val marbleCircle2 = MarbleCircle() val gameHistory2 = playersLoop.takeWhile { (index, player) -> player.lastMarble = index + 1L player.score += marbleCircle2.placeMarble(player.lastMarble).toInt() index != lastMarble } return gameHistory2.maxBy { it.value.score }?.value?.score ?: 0 } } data class Player(val number: Long, var score: Long = 0, var lastMarble: Long = 0) class MarbleCircle { private val marbles = LinkedList(listOf(0L)) fun placeMarble(marble: Long): Long { if (marble % 23 == 0L) { for (i in 0 until 6) { marbles.addLast(marbles.removeFirst()) } return marbles.removeFirst() + marble } else { for (i in 0 until 2) { marbles.addFirst(marbles.removeLast()) } marbles.addLast(marble) } return 0 } } }
0
Kotlin
0
0
4f163752c67333aa6c42cdc27abe07be094961a7
1,764
aoc-2018
Creative Commons Zero v1.0 Universal
src/main/kotlin/troy/apiModels/PhishingDomainModel.kt
daksh7011
440,123,158
false
{"Kotlin": 99491, "Groovy": 26750, "Dockerfile": 251}
package troy.apiModels import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class PhishingDomainModel( @SerialName("domains") val domains: List<String> )
1
Kotlin
1
0
4ad33716223657dcfa716b7ae90add6d13987cc8
212
troy
MIT License
src/dorkbox/peParser/headers/flags/DllCharacteristicsType.kt
dorkbox
28,162,386
false
null
/* * Copyright 2023 dorkbox, llc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dorkbox.peParser.headers.flags enum class DllCharacteristicsType(private val hexValue: String, val description: String) { IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE("40", "DLL can be relocated at load time."), IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY("80", "Code Integrity checks are enforced."), IMAGE_DLL_CHARACTERISTICS_NX_COMPAT("100", "Image is NX compatible."), IMAGE_DLL_CHARACTERISTICS_ISOLATION("200", "Isolation aware, but do not isolate the image."), IMAGE_DLLCHARACTERISTICS_NO_SEH("400", "Does not use structured exception (SE) handling. No SE handler may be called in this image."), IMAGE_DLLCHARACTERISTICS_NO_BIND("800", "Do not bind the image."), IMAGE_DLLCHARACTERISTICS_WDM_DRIVER("2000", "A WDM driver."), IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE("8000", "Terminal Server aware."); companion object { operator fun get(key: UShort): Array<DllCharacteristicsType> { val chars: MutableList<DllCharacteristicsType> = ArrayList(0) val keyAsInt: Int = key.toInt() for (c in values()) { val mask = c.hexValue.toLong(16) if (keyAsInt.toLong() and mask != 0L) { chars.add(c) } } return chars.toTypedArray<DllCharacteristicsType>() } } }
2
null
4
24
dae9521b4d5420e32b4a9e0015983868d856067e
1,941
PeParser
Creative Commons Zero v1.0 Universal
app/src/main/java/com/cerminnovations/moviesboard/data/remote/model/search/SearchDto.kt
mbobiosio
324,425,383
false
null
package com.cerminnovations.moviesboard.model.search import com.cerminnovations.moviesboard.model.response.Response import com.squareup.moshi.Json /* * Created by <NAME> on Jan 04, 2021. * Twitter: @cazewonder * Nigeria */ data class Search( @Json(name = "page") val page: Int?, @Json(name = "results") val results: List<SearchResult>, @Json(name = "total_pages") val totalPages: Int?, @Json(name = "total_results") val totalResults: Int? ) : Response
0
null
3
7
07270aa17f45edabfb6792fd529c212e1c585ce4
486
MoviesBoard
MIT License
app/src/main/java/com/steven/movieapp/widget/refreshLoad/WrapRecyclerView.kt
StevenYan88
174,098,969
false
null
package com.steven.movieapp.widget.refreshLoad import android.content.Context import android.util.AttributeSet import android.view.View import androidx.recyclerview.widget.RecyclerView /** * Description: * Data:2019/2/20 * Actor:Steven */ open class WrapRecyclerView : RecyclerView { private lateinit var mWrapRecyclerAdapter: WrapRecyclerAdapter private lateinit var mAdapter: RecyclerView.Adapter<RecyclerView.ViewHolder> constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) override fun setAdapter(adapter: RecyclerView.Adapter<RecyclerView.ViewHolder>?) { this.mAdapter = adapter!! mWrapRecyclerAdapter = if (adapter is WrapRecyclerAdapter) { adapter } else { WrapRecyclerAdapter(adapter) } super.setAdapter(mWrapRecyclerAdapter) //解决GridLayout添加头部和底部要占据一行 mWrapRecyclerAdapter.adjustSpanSize(this) } fun addHeaderView(view: View) { mWrapRecyclerAdapter.addHeaderView(view) } fun addFooterView(view: View) { mWrapRecyclerAdapter.addFooterView(view) } fun removeHeaderView(view: View) { mWrapRecyclerAdapter.removeHeaderView(view) } fun removeFooterView(view: View) { mWrapRecyclerAdapter.removeFooterView(view) } }
1
null
23
76
7903af00677417a20cf1e06e8b647c762ed90585
1,478
MovieApp
Apache License 2.0
Ocean_Android/app/src/main/java/com/example/ocean_android_intro/MainActivity.kt
pcamposaugusto
437,975,205
false
null
package com.example.ocean_android_intro import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button import android.widget.EditText import android.widget.TextView import android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Acessar o elemento que está no layout XML // Classe R = recursos val tvResultado = findViewById<TextView>(R.id.tvResultado) val btnEnviar = findViewById<Button>(R.id.btnEnviar) val etNome = findViewById<EditText>(R.id.etNome) val btnAbrirTela = findViewById<Button>(R.id.btnAbrirTela) // Alteramos o texto do tvResultado para uma string que quisermos // tvResultado.text = "<NAME>" // Declaramos um ouvinte para eventos de clique no btnEnviar // Assim que um clique no btnEnviar ocorrer, o código dentro das chaves {} será executado btnEnviar.setOnClickListener { // pegamos o que foi digitado no EditText val nome = etNome.text // Caso o nome esteja em branco, entra no if if(nome.isBlank()) { // Exibe uma mensagem de erro no EditText etNome.error = getString(R.string.type_valid_name) } else { // Alteramos o texto do tvResultado para uma string que está armazenado na variável nome tvResultado.text = nome Toast.makeText(this, getString(R.string.updated_successfully), Toast.LENGTH_LONG).show() } } // Detectar clique no botão btnAbrirTela btnAbrirTela.setOnClickListener { //Criamos uma intenção de abrir a tela ResultadoActivity val abrirTelaIntent = Intent(this, ResultadoActivity::class.java) //Adicionamos uma informação à Intent que abre a nova tela val nome = "NOME_DIGITADO" val value = etNome.text abrirTelaIntent.putExtra(nome, value) // Registramos a intenção do Android startActivity(abrirTelaIntent) } } }
0
Kotlin
0
1
4066c98d9dc5e213679123cc887fb4bfc7d7e89b
2,285
Ocean_Android
MIT License
app/src/main/java/com/dluvian/nozzle/ui/app/navigation/PostCardNavLambdas.kt
dluvian
645,936,540
false
{"Kotlin": 679778}
package com.dluvian.nozzle.ui.app.navigation import com.dluvian.nozzle.model.Relay data class PostCardNavLambdas( val onNavigateToThread: (String) -> Unit, val onNavigateToProfile: (String) -> Unit, val onNavigateToReply: () -> Unit, val onNavigateToQuote: (String) -> Unit, val onNavigateToId: (String) -> Unit, val onNavigateToPost: () -> Unit, val onNavigateToRelayProfile: (Relay) -> Unit, )
13
Kotlin
3
35
30ffd7b88fdb612afd80e422a0bfe92a74733338
426
Nozzle
MIT License
app/src/main/java/org/sirekanyan/outline/ui/AboutDialog.kt
sirekanian
680,634,623
false
{"Kotlin": 107119}
package org.sirekanyan.outline.ui import android.content.Intent import android.content.Intent.ACTION_SENDTO import android.net.Uri import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.text.ClickableText import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Email import androidx.compose.material.icons.filled.Info import androidx.compose.material3.AlertDialog import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalClipboardManager import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.dp import org.sirekanyan.outline.BuildConfig import org.sirekanyan.outline.R import org.sirekanyan.outline.ext.logDebug import org.sirekanyan.outline.ext.showToast import org.sirekanyan.outline.isDebugBuild import org.sirekanyan.outline.isPlayFlavor import org.sirekanyan.outline.ui.icons.IconOpenInNew import org.sirekanyan.outline.ui.icons.IconPlayStore @Composable fun AboutDialogContent(onDismiss: () -> Unit) { val appName = stringResource(R.string.outln_app_name) val appVersion = BuildConfig.VERSION_NAME AlertDialog( icon = { Icon(Icons.Default.Info, null) }, title = { Text("$appName $appVersion") }, text = { val context = LocalContext.current val annotatedString = buildAnnotatedString { append("An application for managing Outline VPN servers. ") append("You can find more information on ") withStyle(SpanStyle(MaterialTheme.colorScheme.primary)) { pushStringAnnotation("link", "https://getoutline.org") append("getoutline.org") pop() } } val textColor = MaterialTheme.colorScheme.onSurfaceVariant val textStyle = MaterialTheme.typography.bodyMedium.copy(textColor) ClickableText(annotatedString, style = textStyle) { offset -> val links = annotatedString.getStringAnnotations("link", offset, offset) links.firstOrNull()?.item?.let { link -> context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(link))) onDismiss() } } }, onDismissRequest = onDismiss, confirmButton = { val context = LocalContext.current val clipboard = LocalClipboardManager.current AboutItem(Icons.Default.Email, "Send feedback") { val email = "[email protected]" val subject = Uri.encode("Feedback: $appName $appVersion") val intent = Intent(ACTION_SENDTO, Uri.parse("mailto:$email?subject=$subject")) try { context.startActivity(intent) } catch (exception: Exception) { logDebug("Cannot find email app", exception) clipboard.setText(AnnotatedString(email)) context.showToast("Email is copied") } } if (isPlayFlavor() || isDebugBuild()) { val playUri = "https://play.google.com/store/apps/details?id=${context.packageName}" AboutItem(IconPlayStore, "Rate on Play Store") { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(playUri))) onDismiss() } } }, ) } @Composable private fun AboutItem(icon: ImageVector, text: String, onClick: () -> Unit) { TextButton( onClick = onClick, modifier = Modifier.fillMaxWidth().heightIn(min = 56.dp), border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary), ) { Icon(icon, null, Modifier.padding(horizontal = 4.dp)) Text( text = text, modifier = Modifier.weight(1f).padding(horizontal = 8.dp), maxLines = 1, overflow = TextOverflow.Ellipsis, ) Icon(IconOpenInNew, null, Modifier.padding(horizontal = 8.dp)) } }
5
Kotlin
0
35
5140a02d2559f9490fbed323341fb6cb72610866
4,787
outline
Apache License 2.0
compose-mds/src/main/java/ch/sbb/compose_mds/sbbicons/medium/LocationPinBMedium.kt
SchweizerischeBundesbahnen
853,290,161
false
{"Kotlin": 6728512}
package ch.sbb.compose_mds.sbbicons.medium import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import ch.sbb.compose_mds.sbbicons.MediumGroup public val MediumGroup.LocationPinBMedium: ImageVector get() { if (_locationPinBMedium != null) { return _locationPinBMedium!! } _locationPinBMedium = Builder(name = "LocationPinBMedium", defaultWidth = 36.0.dp, defaultHeight = 36.0.dp, viewportWidth = 36.0f, viewportHeight = 36.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(18.0f, 6.262f) arcToRelative(8.75f, 8.75f, 0.0f, false, false, -8.75f, 8.75f) verticalLineToRelative(0.02f) curveToRelative(0.06f, 1.51f, 0.509f, 2.78f, 1.22f, 3.965f) lineToRelative(0.007f, 0.01f) lineToRelative(7.125f, 11.249f) lineToRelative(0.422f, 0.667f) lineToRelative(0.422f, -0.667f) lineToRelative(7.125f, -11.249f) lineToRelative(0.007f, -0.01f) lineToRelative(0.005f, -0.01f) curveToRelative(0.694f, -1.216f, 1.154f, -2.512f, 1.167f, -3.97f) verticalLineToRelative(-0.005f) arcTo(8.75f, 8.75f, 0.0f, false, false, 18.0f, 6.262f) moveToRelative(-6.675f, 12.215f) curveToRelative(-0.635f, -1.058f, -1.022f, -2.163f, -1.075f, -3.475f) arcToRelative(7.75f, 7.75f, 0.0f, false, true, 15.5f, 0.008f) curveToRelative(-0.011f, 1.237f, -0.398f, 2.362f, -1.03f, 3.472f) lineToRelative(-6.696f, 10.572f) close() moveTo(16.248f, 19.805f) verticalLineToRelative(-3.7f) horizontalLineToRelative(2.29f) quadToRelative(1.282f, 0.0f, 1.683f, 0.173f) quadToRelative(1.03f, 0.43f, 1.03f, 1.709f) quadToRelative(-0.001f, 1.136f, -0.764f, 1.566f) quadToRelative(-0.448f, 0.252f, -1.741f, 0.252f) close() moveTo(16.248f, 14.985f) verticalLineToRelative(-3.268f) horizontalLineToRelative(2.374f) quadToRelative(1.004f, 0.0f, 1.346f, 0.136f) quadToRelative(0.41f, 0.164f, 0.634f, 0.554f) quadToRelative(0.229f, 0.388f, 0.229f, 0.933f) quadToRelative(-0.001f, 0.546f, -0.263f, 0.955f) quadToRelative(-0.262f, 0.41f, -0.702f, 0.554f) quadToRelative(-0.44f, 0.136f, -1.366f, 0.136f) close() moveTo(18.804f, 10.511f) horizontalLineToRelative(-3.805f) verticalLineToRelative(10.501f) horizontalLineToRelative(4.394f) quadToRelative(1.068f, 0.0f, 1.721f, -0.38f) quadToRelative(1.391f, -0.821f, 1.392f, -2.695f) quadToRelative(0.0f, -1.429f, -0.996f, -2.176f) quadToRelative(-0.293f, -0.223f, -0.822f, -0.381f) arcToRelative(2.2f, 2.2f, 0.0f, false, false, 1.026f, -0.876f) quadToRelative(0.372f, -0.596f, 0.372f, -1.365f) quadToRelative(0.0f, -0.725f, -0.34f, -1.34f) arcToRelative(2.34f, 2.34f, 0.0f, false, false, -0.923f, -0.937f) quadToRelative(-0.634f, -0.351f, -2.019f, -0.351f) } } .build() return _locationPinBMedium!! } private var _locationPinBMedium: ImageVector? = null
0
Kotlin
0
1
090a66a40e1e5a44d4da6209659287a68cae835d
4,180
mds-android-compose
MIT License
KotlinFromScratch/src/Functions.kt
Catherine22
177,104,765
false
{"Java": 464949, "Kotlin": 50932, "CMake": 1704, "C++": 476}
class Functions { fun test() { println("Basic functions") println(double(10)) println(triple(10)) println(isPrimeNumber(17)) println("") println("Default arguments") val s = "Function parameters can have default values, which are" read(s.toByteArray()) println("") println("Override functions") val b = B() b.foo() println("") println("lambda") foo(0, 2) { println("Fill in all arguments") } foo(0) { println("Fill in some arguments") } foo(baz = 2) { println("Fill in specific arguments") } foo(qux = { println("Fill in the last argument") }) foo { println("Fill in the last argument") } println("") println("variable number of arguments (vararg)") foo(strings = *arrayOf("a", "b", "c")) println("") println("Unit-returning functions") println("fun bar(): Unit {} is equivalent to fun bar() {}") println("") println("infix functions") println("aaa".add(3)) println("aaa" add 3) this bar "bbb" bar("bbb") println("") println("Local functions") f() } private fun double(x: Int): Int = 2 * x private fun triple(x: Int) = 3 * x private fun isPrimeNumber(x: Int): Boolean { var factors = 0 for (i in 2..x / 2) { if (x % i == 0) { factors++ } } return factors == 0 } private fun read(bytes: ByteArray, off: Int = 0, len: Int = bytes.size) { val s = String(bytes, off, len) println(s) } open class A { open fun foo() {} } class B : A() { override fun foo() {} } private fun foo(bar: Int = 0, baz: Int = 1, qux: () -> Unit) { qux() } // In Java -> public void println(String.. args) { } private fun foo(vararg strings: String) { println(strings[0]) } private infix fun String.add(x: Int) = "$this$x" private infix fun bar(s: String) = println(s) private fun f() { fun f() { println("call f() in f()") } print("call f() -> ") f() } }
1
Java
1
15
dae2c63815a5e054af01a757a0ac8c598d2857c9
2,262
Associate-Android-Developer-Practice
MIT License