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
lookandfeel/src/commonMain/kotlin/moe/tlaster/precompose/navigation/NavHostDefaults.kt
alexzhirkevich
636,411,288
false
{"Kotlin": 480229, "Ruby": 1724, "Swift": 571, "Shell": 228}
@file:OptIn(ExperimentalMaterialApi::class) package moe.tlaster.precompose.navigation import androidx.compose.animation.slideInHorizontally import androidx.compose.animation.slideOutHorizontally import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.FractionalThreshold import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.unit.dp import com.github.alexzhirkevich.lookandfeel.theme.LookAndFeel import com.github.alexzhirkevich.lookandfeel.theme.currentLookAndFeel import moe.tlaster.precompose.navigation.transition.NavTransition object NavHostDefaults { fun materialNavTransition(): NavTransition = NavTransition() fun cupertinoNavTransition(): NavTransition = NavTransition( createTransition = slideInHorizontally { it }, destroyTransition = slideOutHorizontally { it }, pauseTransition = slideOutHorizontally { -it / 4 }, resumeTransition = slideInHorizontally { -it / 4 }, ) fun materialSwipeProperties() : SwipeProperties? = null fun cupertinoSwipeProperties(): SwipeProperties = SwipeProperties( slideInHorizontally = { -it / 4 }, spaceToSwipe = 20.dp, swipeThreshold = FractionalThreshold(.5f), ) } @Composable fun NavHostDefaults.defaultNavTransition() : NavTransition{ val lnf = currentLookAndFeel return remember(lnf) { when (lnf) { LookAndFeel.Cupertino -> cupertinoNavTransition() else -> materialNavTransition() } } } @Composable fun NavHostDefaults.defaultSwipeProperties() : SwipeProperties? { val lnf = currentLookAndFeel return remember(lnf) { when (lnf) { LookAndFeel.Cupertino -> cupertinoSwipeProperties() else -> materialSwipeProperties() } } }
5
Kotlin
14
359
89f41414e712fc3d75bba4ef3609b04d617f2b19
1,852
compose-look-and-feel
Apache License 2.0
MultipleAppModulesExample/feature1app/src/main/java/me/abunka/multipleappmodules/feature1app/ActivityA.kt
yankeppey
150,957,921
false
null
package me.abunka.multipleappmodules.feature1app import android.content.Context import android.content.Intent import android.os.Bundle import dagger.android.support.DaggerAppCompatActivity class ActivityA: DaggerAppCompatActivity() { companion object { fun getIntent(context: Context) = Intent(context, ActivityA::class.java) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_a) } }
0
Kotlin
36
106
63dd53e0d49761b1767e359cea6123807fe7a024
499
MultipleAppModules
MIT License
sudovirtualcards/src/test/java/com/sudoplatform/sudovirtualcards/SudoVirtualCardsReviewUnfundedFundingSourceTest.kt
sudoplatform
287,155,437
false
{"Kotlin": 1003676}
/* * Copyright © 2023 <NAME>, Inc. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 */ package com.sudoplatform.sudovirtualcards import android.content.Context import com.amazonaws.mobileconnectors.appsync.AWSAppSyncClient import com.apollographql.apollo.api.Response import com.apollographql.apollo.exception.ApolloHttpException import com.sudoplatform.sudokeymanager.KeyManagerInterface import com.sudoplatform.sudologging.Logger import com.sudoplatform.sudouser.SudoUserClient import com.sudoplatform.sudovirtualcards.graphql.CallbackHolder import com.sudoplatform.sudovirtualcards.graphql.ReviewUnfundedFundingSourceMutation import com.sudoplatform.sudovirtualcards.graphql.fragment.SealedAttribute import com.sudoplatform.sudovirtualcards.graphql.type.BankAccountType import com.sudoplatform.sudovirtualcards.graphql.type.CardType import com.sudoplatform.sudovirtualcards.graphql.type.CreditCardNetwork import com.sudoplatform.sudovirtualcards.graphql.type.IdInput import com.sudoplatform.sudovirtualcards.types.BankAccountFundingSource import com.sudoplatform.sudovirtualcards.types.CreditCardFundingSource import com.sudoplatform.sudovirtualcards.types.FundingSourceFlags import com.sudoplatform.sudovirtualcards.types.FundingSourceState import io.kotlintest.shouldBe import io.kotlintest.shouldNotBe import io.kotlintest.shouldThrow import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import okhttp3.MediaType.Companion.toMediaType import okhttp3.Protocol import okhttp3.ResponseBody.Companion.toResponseBody import org.junit.After import org.junit.Assert.fail import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import org.mockito.ArgumentMatchers.anyString import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.doThrow import org.mockito.kotlin.mock import org.mockito.kotlin.stub import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoMoreInteractions import java.net.HttpURLConnection import com.sudoplatform.sudovirtualcards.graphql.fragment.BankAccountFundingSource as BankAccountFundingSourceGraphQL import com.sudoplatform.sudovirtualcards.graphql.fragment.CreditCardFundingSource as CreditCardFundingSourceGraphQL import com.sudoplatform.sudovirtualcards.graphql.type.FundingSourceFlags as GraphQLFlags import com.sudoplatform.sudovirtualcards.graphql.type.FundingSourceState as FundingSourceStateGraphQL /** * Test the correct operation of [SudoVirtualCardsClient.reviewUnfundedFundingSource] * using mocks and spies. */ @RunWith(Parameterized::class) class SudoVirtualCardsReviewUnfundedFundingSourceTest(private val provider: String) : BaseTests() { companion object { @JvmStatic @Parameterized.Parameters(name = "{0}") fun data(): Collection<String> { return listOf( "stripe", "checkoutCard", "checkoutBankAccount", ) } } private val idInput = IdInput.builder() .id("id") .build() private val creditCardResult by before { ReviewUnfundedFundingSourceMutation.ReviewUnfundedFundingSource( "CreditCardFundingSource", ReviewUnfundedFundingSourceMutation.AsCreditCardFundingSource( "CreditCardFundingSource", ReviewUnfundedFundingSourceMutation.AsCreditCardFundingSource.Fragments( CreditCardFundingSourceGraphQL( "CreditCardFundingSource", "id", "owner", 1, 1.0, 10.0, FundingSourceStateGraphQL.INACTIVE, emptyList(), "USD", CreditCardFundingSourceGraphQL.TransactionVelocity( "TransactionVelocity", 10000, listOf("10000/P1D"), ), "last4", CreditCardNetwork.VISA, CardType.CREDIT, ), ), ), null, ) } private val bankAccountResult by before { ReviewUnfundedFundingSourceMutation.ReviewUnfundedFundingSource( "BankAccountFundingSource", null, ReviewUnfundedFundingSourceMutation.AsBankAccountFundingSource( "BankAccountFundingSource", ReviewUnfundedFundingSourceMutation.AsBankAccountFundingSource.Fragments( BankAccountFundingSourceGraphQL( "BankAccountFundingSource", "id", "owner", 1, 1.0, 10.0, FundingSourceStateGraphQL.INACTIVE, listOf(GraphQLFlags.UNFUNDED), "USD", BankAccountFundingSourceGraphQL.TransactionVelocity( "TransactionVelocity", 10000, listOf("10000/P1D"), ), BankAccountType.CHECKING, BankAccountFundingSourceGraphQL.Authorization( "Authorization", "language", "content", "contentType", "signature", "keyId", "algorithm", "data", ), "last4", BankAccountFundingSourceGraphQL.InstitutionName( "InstitutionName", BankAccountFundingSourceGraphQL.InstitutionName.Fragments( SealedAttribute( "typename", "keyId", "algorithm", "string", mockSeal("base64EncodedSealedData"), ), ), ), null, null, ), ), ), ) } private val creditCardResponse by before { Response.builder<ReviewUnfundedFundingSourceMutation.Data>(ReviewUnfundedFundingSourceMutation(idInput)) .data(ReviewUnfundedFundingSourceMutation.Data(creditCardResult)) .build() } private val bankAccountResponse by before { Response.builder<ReviewUnfundedFundingSourceMutation.Data>(ReviewUnfundedFundingSourceMutation(idInput)) .data(ReviewUnfundedFundingSourceMutation.Data(bankAccountResult)) .build() } private val mutationResponse by before { mapOf( "stripe" to creditCardResponse, "checkoutCard" to creditCardResponse, "checkoutBankAccount" to bankAccountResponse, ) } private val holder = CallbackHolder<ReviewUnfundedFundingSourceMutation.Data>() private val mockContext by before { mock<Context>() } private val mockUserClient by before { mock<SudoUserClient>() } private val mockAppSyncClient by before { mock<AWSAppSyncClient>().stub { on { mutate(any<ReviewUnfundedFundingSourceMutation>()) } doReturn holder.mutationOperation } } private val mockKeyManager by before { mock<KeyManagerInterface>().stub { on { decryptWithPrivateKey(anyString(), any(), any()) } doReturn ByteArray(42) on { decryptWithSymmetricKey(any<ByteArray>(), any<ByteArray>()) } doReturn "42".toByteArray() } } private val client by before { SudoVirtualCardsClient.builder() .setContext(mockContext) .setSudoUserClient(mockUserClient) .setAppSyncClient(mockAppSyncClient) .setKeyManager(mockKeyManager) .setLogger(mock<Logger>()) .build() } @Before fun init() { holder.callback = null } @After fun fini() { verifyNoMoreInteractions(mockContext, mockUserClient, mockKeyManager, mockAppSyncClient) } @Test fun `ReviewUnfundedFundingSource() should return results when no error present`() = runBlocking<Unit> { holder.callback shouldBe null val deferredResult = async(Dispatchers.IO) { client.reviewUnfundedFundingSource("id") } deferredResult.start() delay(100L) holder.callback shouldNotBe null holder.callback?.onResponse(mutationResponse[provider] ?: throw missingProvider(provider)) val result = deferredResult.await() result shouldNotBe null when (result) { is CreditCardFundingSource -> { with(result) { id shouldBe "id" owner shouldBe "owner" version shouldBe 1 createdAt shouldNotBe null updatedAt shouldNotBe null state shouldBe FundingSourceState.INACTIVE currency shouldBe "USD" last4 shouldBe "last4" network shouldBe CreditCardFundingSource.CreditCardNetwork.VISA } } is BankAccountFundingSource -> { with(result) { id shouldBe "id" owner shouldBe "owner" version shouldBe 1 createdAt shouldNotBe null updatedAt shouldNotBe null state shouldBe FundingSourceState.INACTIVE flags shouldBe listOf(FundingSourceFlags.UNFUNDED) currency shouldBe "USD" transactionVelocity?.maximum shouldBe 10000 transactionVelocity?.velocity shouldBe listOf("10000/P1D") bankAccountType shouldBe BankAccountFundingSource.BankAccountType.CHECKING last4 shouldBe "last4" institutionName shouldNotBe null institutionLogo shouldBe null } } else -> { fail("Unexpected FundingSource type") } } if (provider == "checkoutBankAccount") { verify(mockKeyManager).decryptWithPrivateKey(anyString(), any(), any()) verify(mockKeyManager).decryptWithSymmetricKey(any<ByteArray>(), any<ByteArray>()) } verify(mockAppSyncClient).mutate(any<ReviewUnfundedFundingSourceMutation>()) } @Test fun `ReviewUnfundedFundingSource() should throw when mutation response is null`() = runBlocking<Unit> { holder.callback shouldBe null val nullResponse by before { Response.builder<ReviewUnfundedFundingSourceMutation.Data>(ReviewUnfundedFundingSourceMutation(idInput)) .data(null) .build() } val deferredResult = async(Dispatchers.IO) { shouldThrow<SudoVirtualCardsClient.FundingSourceException.ReviewFailedException> { client.reviewUnfundedFundingSource("id") } } deferredResult.start() delay(100L) holder.callback shouldNotBe null holder.callback?.onResponse(nullResponse) deferredResult.await() verify(mockAppSyncClient).mutate(any<ReviewUnfundedFundingSourceMutation>()) } @Test fun `ReviewUnfundedFundingSource() should throw when response has a funding source not found error`() = runBlocking<Unit> { holder.callback shouldBe null val errorReviewResponse by before { val error = com.apollographql.apollo.api.Error( "mock", emptyList(), mapOf("errorType" to "FundingSourceNotFoundError"), ) Response.builder<ReviewUnfundedFundingSourceMutation.Data>(ReviewUnfundedFundingSourceMutation(idInput)) .errors(listOf(error)) .data(null) .build() } val deferredResult = async(Dispatchers.IO) { shouldThrow<SudoVirtualCardsClient.FundingSourceException.FundingSourceNotFoundException> { client.reviewUnfundedFundingSource("id") } } deferredResult.start() delay(100L) holder.callback shouldNotBe null holder.callback?.onResponse(errorReviewResponse) deferredResult.await() verify(mockAppSyncClient).mutate(any<ReviewUnfundedFundingSourceMutation>()) } @Test fun `ReviewUnfundedFundingSource() should throw when response has an account locked error`() = runBlocking<Unit> { holder.callback shouldBe null val errorReviewResponse by before { val error = com.apollographql.apollo.api.Error( "mock", emptyList(), mapOf("errorType" to "AccountLockedError"), ) Response.builder<ReviewUnfundedFundingSourceMutation.Data>(ReviewUnfundedFundingSourceMutation(idInput)) .errors(listOf(error)) .data(null) .build() } val deferredResult = async(Dispatchers.IO) { shouldThrow<SudoVirtualCardsClient.FundingSourceException.AccountLockedException> { client.reviewUnfundedFundingSource("id") } } deferredResult.start() delay(100L) holder.callback shouldNotBe null holder.callback?.onResponse(errorReviewResponse) deferredResult.await() verify(mockAppSyncClient).mutate(any<ReviewUnfundedFundingSourceMutation>()) } @Test fun `ReviewUnfundedFundingSource() should throw when http error occurs`() = runBlocking<Unit> { holder.callback shouldBe null val deferredResult = async(Dispatchers.IO) { shouldThrow<SudoVirtualCardsClient.FundingSourceException.ReviewFailedException> { client.reviewUnfundedFundingSource("id") } } deferredResult.start() delay(100L) val request = okhttp3.Request.Builder() .get() .url("http://www.smh.com.au") .build() val responseBody = "{}".toResponseBody("application/json; charset=utf-8".toMediaType()) val forbidden = okhttp3.Response.Builder() .protocol(Protocol.HTTP_1_1) .code(HttpURLConnection.HTTP_FORBIDDEN) .request(request) .message("Forbidden") .body(responseBody) .build() holder.callback shouldNotBe null holder.callback?.onHttpError(ApolloHttpException(forbidden)) deferredResult.await() verify(mockAppSyncClient).mutate(any<ReviewUnfundedFundingSourceMutation>()) } @Test fun `ReviewUnfundedFundingSource() should throw when unknown error occurs`() = runBlocking<Unit> { holder.callback shouldBe null mockAppSyncClient.stub { on { mutate(any<ReviewUnfundedFundingSourceMutation>()) } doThrow RuntimeException("Mock Runtime Exception") } val deferredResult = async(Dispatchers.IO) { shouldThrow<SudoVirtualCardsClient.FundingSourceException.UnknownException> { client.reviewUnfundedFundingSource("id") } } deferredResult.start() delay(100L) deferredResult.await() verify(mockAppSyncClient).mutate(any<ReviewUnfundedFundingSourceMutation>()) } }
0
Kotlin
0
0
81f92ab8ff2c2256fb8d7d07abf28cebd4f4400c
16,106
sudo-virtual-cards-android
Apache License 2.0
litenet/src/main/java/com/aqrlei/litenet/ITransformerFactory.kt
AqrLei
288,324,186
false
null
package com.aqrlei.litenet /** * created by AqrLei on 2020/3/20 */ interface ITransformerFactory { fun <T> createTransformer(): ITransformer<T> }
0
Kotlin
0
0
9e95bf813060ec0e691fab7b274bf65bdeb005ed
152
LiteNet
Apache License 2.0
vscode/src/jsMain/kotlin/vscode/CommentThread.kt
lppedd
761,812,661
false
{"Kotlin": 1887051}
package vscode import js.array.ReadonlyArray /** * A collection of [Comment]s representing a conversation at a particular range in a document. */ external interface CommentThread { /** * The uri of the document the thread has been created on. */ val uri: Uri /** * The range the comment thread is located within the document. The thread icon will be shown * at the last line of the range. */ var range: Range /** * The ordered comments of the thread. */ var comments: ReadonlyArray<Comment> /** * Whether the thread should be collapsed or expanded when opening the document. * Defaults to Collapsed. */ var collapsibleState: CommentThreadCollapsibleState /** * Whether the thread supports reply. * Defaults to true. */ var canReply: Boolean /** * Context value of the comment thread. This can be used to contribute thread specific actions. * For example, a comment thread is given a context value as `editable`. When contributing actions to `comments/commentThread/title` * using `menus` extension point, you can specify context value for key `commentThread` in `when` expression like `commentThread == editable`. * ```json * "contributes": { * "menus": { * "comments/commentThread/title": [ * { * "command": "extension.deleteCommentThread", * "when": "commentThread == editable" * } * ] * } * } * ``` * This will show action `extension.deleteCommentThread` only for comment threads with `contextValue` is `editable`. */ var contextValue: String? /** * The optional human-readable label describing the [CommentThread] */ var label: String? /** * The optional state of a comment thread, which may affect how the comment is displayed. */ var state: CommentThreadState? /** * Dispose this comment thread. * * Once disposed, this comment thread will be removed from visible editors and Comment Panel when appropriate. */ fun dispose() }
0
Kotlin
0
3
0f493d3051afa3de2016e5425a708c7a9ed6699a
2,035
kotlin-externals
MIT License
app/src/main/java/com/example/meditation/ui/PlayContentVideoFragment.kt
hoavu2505
492,882,528
false
{"Kotlin": 191388}
package com.example.meditation.ui import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.example.meditation.R import com.example.meditation.databinding.FragmentPlayContentVideoBinding import com.example.meditation.model.Content import com.google.android.material.transition.MaterialFadeThrough import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.listeners.AbstractYouTubePlayerListener class PlayContentVideoFragment : Fragment() { private lateinit var binding : FragmentPlayContentVideoBinding private val args : PlayContentVideoFragmentArgs by navArgs() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) sharedElementEnterTransition = MaterialFadeThrough().apply { duration = 300L } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val content = args.content val videoID = content.audio!![0] Log.d("videoID", videoID) binding = FragmentPlayContentVideoBinding.inflate(layoutInflater, container, false) val view = binding.root val youTubePlayerView = binding.youtubePlayer lifecycle.addObserver(youTubePlayerView) ui(content) binding.youtubePlayer.addYouTubePlayerListener(object :AbstractYouTubePlayerListener() { override fun onReady(youTubePlayer: com.pierfrancescosoffritti.androidyoutubeplayer.core.player.YouTubePlayer) { super.onReady(youTubePlayer) youTubePlayer.loadVideo(videoID, 0F) // val defaultPlayerUiController = DefaultPlayerUiController(binding.youtubePlayer, youTubePlayer) // binding.youtubePlayer.setCustomPlayerUi(defaultPlayerUiController.rootView) } }) binding.imgClose.setOnClickListener { findNavController().popBackStack() } return view } private fun ui(content: Content) { binding.tvContentName.text = content.name when(content.mode){ "Video" -> binding.imgType.setImageResource(R.drawable.ic_video) } binding.tvType.text = content.type binding.tvDuration.text = content.duration.toString() + " PHÚT" binding.tvDescription.text = content.description } override fun onDestroy() { super.onDestroy() binding.youtubePlayer.release() } }
0
Kotlin
0
0
dff95e7494508692340232224d3285137c61b2c9
2,686
Meditation-App
Apache License 2.0
core/src/main/java/com/github/offile/permissionshelper/runtime/RuntimeResult.kt
offile
338,356,908
false
null
package com.github.offile.permissionshelper.runtime import com.github.offile.permissionshelper.core.Result class RuntimeResult( isGranted: Boolean, val grantedList: List<String> = emptyList(), val deniedList: List<String> = emptyList(), ) : Result(isGranted)
0
Kotlin
0
0
0d65bcb170f15a92f8227e0d348e63c089324dd0
272
PermissionsHelper
Apache License 2.0
app/src/main/java/cab/snapp/blackBox/MyApplication.kt
snapp-incubator
670,599,580
false
null
package cab.snapp.blackBox import android.app.Application import cab.snapp.blackBox.crashHandler.CrashHandler import cab.snapp.blackBox.dagger.ApplicationComponent import cab.snapp.blackBox.dagger.DaggerApplicationComponent import cab.snapp.blackBox.poaro.SnappLogger import cab.snapp.blackBox.poaro.f import javax.inject.Inject class MyApplication : Application() { @Inject lateinit var crashHandler: CrashHandler @Inject lateinit var logger: SnappLogger companion object { lateinit var component: ApplicationComponent } override fun onCreate() { super.onCreate() component = DaggerApplicationComponent.factory().create(this.filesDir){ throwable -> logger.f("Crash", throwable.stackTraceToString()) } component.inject(this) crashHandler.startWatching() } }
0
Kotlin
2
6
4d13f5d586799ca8490b72905d11bd9c3c43ebcd
858
BlackBox
Apache License 2.0
Network/src/main/java/com/flexcode/wedatecompose/network/data/models/auth/UserSubscriptions.kt
Felix-Kariuki
588,745,399
false
null
/* * Copyright 2023 <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.flexcode.wedatecompose.network.data.models.auth data class UserSubscriptions( val seeDistanceBetweenYouAndCrush: Int = -1, val seeDistanceBetweenYouAndCrushTime: Long = 0L, val seeAdmirersOnMap: Int = -1, val seeAdmirersTime: Long = 0L, val hideYourLocationFromOthers: Int = -1, val hideYourLocationFromOthersTime: Long = 0L, val lifeTimeSubscriptions: Int = -1, // 15000 val lifeTimeSubscriptionsTime: Long = 0L /** * -1 is for false 1000 for success */ ) /** * save last login time at home and if last login time is not greater than * <expire time hours(9)> don't update else update and if its greater or == * update and change the swipeTimes to 0 */ /** * save the swipes expired time exactly at the last swipe made then: * perfom checks on home screen to see if cureent timestamp minus the `swipesExpiredTime` * is <expire time hours(9)> or more if so reset swiped times to 0 and at expiration update * `swipesExpiredTime` */
13
Kotlin
1
9
20a9b38cb4ae45572a248f819eca775e2d2f2678
1,594
Mingle
Apache License 2.0
modules/feature-categories/src/main/java/com/kpstv/mvvmnewsapp/categories/data/model/Categories.kt
KaustubhPatange
432,745,679
false
null
package com.kpstv.mvvmnewsapp.categories.data.model import com.kpstv.bindings.AutoGenerateConverter import com.kpstv.bindings.ConverterType @AutoGenerateConverter(using = ConverterType.MOSHI) internal data class Categories( val categories: List<String> )
0
Kotlin
0
0
5589654c5061df770106d0d80ec67cc478d94046
260
mvvm-multi-module-sample
Apache License 2.0
app/src/main/java/top/yogiczy/mytv/ui/screens/settings/SettingsScreen.kt
yaoxieyoulei
784,724,425
false
{"Kotlin": 278935, "HTML": 14090}
package top.yogiczy.mytv.ui.screens.settings import android.content.pm.PackageInfo import androidx.compose.foundation.background import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.tv.material3.ExperimentalTvMaterial3Api import androidx.tv.material3.MaterialTheme import top.yogiczy.mytv.ui.rememberChildPadding import top.yogiczy.mytv.ui.screens.settings.components.SettingsAppInfo import top.yogiczy.mytv.ui.screens.settings.components.SettingsMain import top.yogiczy.mytv.ui.screens.settings.components.UpdateState import top.yogiczy.mytv.ui.screens.settings.components.rememberPackageInfo import top.yogiczy.mytv.ui.screens.settings.components.rememberUpdateState import top.yogiczy.mytv.ui.theme.MyTVTheme @OptIn(ExperimentalTvMaterial3Api::class) @Composable fun SettingsScreen( modifier: Modifier = Modifier, settingsState: SettingsState = rememberSettingsState(), updateState: UpdateState = rememberUpdateState(), packageInfo: PackageInfo = rememberPackageInfo(), onClose: () -> Unit = {}, ) { val childPadding = rememberChildPadding() val focusRequester = remember { FocusRequester() } LaunchedEffect(Unit) { focusRequester.requestFocus() } Box( modifier = modifier .fillMaxSize() .background(MaterialTheme.colorScheme.background.copy(alpha = 0.5f)) .focusRequester(focusRequester) .pointerInput(Unit) { detectTapGestures(onTap = { onClose() }) }, ) { Column(modifier = Modifier.align(Alignment.BottomStart)) { SettingsAppInfo( modifier = Modifier.padding(start = childPadding.start), packageInfo = packageInfo, ) Spacer(modifier = Modifier.height(20.dp)) SettingsMain(settingsState = settingsState, updateState = updateState) } } } @Preview(device = "id:Android TV (720p)") @Composable private fun SettingsScreenPreview() { MyTVTheme { SettingsScreen( settingsState = SettingsState(), updateState = UpdateState( context = LocalContext.current, packageInfo = PackageInfo(), coroutineScope = rememberCoroutineScope(), ), packageInfo = PackageInfo().apply { versionName = "1.0.0" } ) } }
4
Kotlin
4
22
63150a9e6b2f08a1c8ec6eb54921bdcf3158050f
3,182
mytv-android
MIT License
platform/backend/api/src/main/kotlin/io/hamal/api/web/func/CreateFuncController.kt
hamal-io
622,870,037
false
{"Kotlin": 1744717, "C": 1398401, "TypeScript": 54320, "C++": 40651, "Lua": 36419, "Makefile": 11728, "Java": 7564, "CMake": 2881, "JavaScript": 1532, "HTML": 694, "Shell": 456, "CSS": 118}
package io.hamal.api.web.func import io.hamal.api.web.req.Assembler import io.hamal.core.adapter.CreateFuncPort import io.hamal.lib.domain.vo.GroupId import io.hamal.lib.sdk.api.ApiCreateFuncReq import io.hamal.lib.sdk.api.ApiSubmittedReq import org.springframework.http.HttpStatus.ACCEPTED import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RestController @RestController internal class CreateFuncController(private val createFunc: CreateFuncPort) { @PostMapping("/v1/groups/{groupId}/funcs") fun createFunc( @PathVariable("groupId") groupId: GroupId, @RequestBody req: ApiCreateFuncReq ): ResponseEntity<ApiSubmittedReq> = createFunc(groupId, req) { ResponseEntity(Assembler.assemble(it), ACCEPTED) } }
6
Kotlin
0
0
6c7f5cc645ba67fb85df20d9a5d2e18372a012f4
983
hamal
Creative Commons Zero v1.0 Universal
library/src/main/java/dev/yasan/helper/android/library/PersianViewHelper.kt
yasandev
333,085,867
false
null
package dev.yasan.helper.android.library import android.app.Activity import android.view.View /** * A helper class with a set of functions that help with view related difficulties in Persian Android applications. * @author <NAME> */ object PersianViewHelper { /** * Sets the activity's layout direction to right-to-left * @author <NAME> */ fun forceRTL(activity: Activity) { activity.window.decorView.layoutDirection = View.LAYOUT_DIRECTION_RTL } /** * Sets the activity's layout direction to left-to-right * @author <NAME> */ fun forceLTR(activity: Activity) { activity.window.decorView.layoutDirection = View.LAYOUT_DIRECTION_LTR } /** * Sets the view's layout direction to right-to-left * @author <NAME> */ fun forceRTL(view: View) { view.layoutDirection = View.LAYOUT_DIRECTION_RTL } /** * Sets the view's layout direction to left-to-right * @author <NAME> */ fun forceLTR(view: View) { view.layoutDirection = View.LAYOUT_DIRECTION_LTR } } /** * Sets the activity's layout direction to right-to-left * @author <NAME> */ fun Activity.forceRTL() = PersianViewHelper.forceRTL(this) /** * Sets the activity's layout direction to left-to-right * @author <NAME> */ fun Activity.forceLTR() = PersianViewHelper.forceLTR(this) /** * Sets the view's layout direction to right-to-left * @author <NAME> */ fun View.forceRTL() = PersianViewHelper.forceRTL(this) /** * Sets the view's layout direction to left-to-right * @author <NAME> */ fun View.forceLTR() = PersianViewHelper.forceLTR(this)
0
Kotlin
0
6
e52fd5b8e1d32869de3543206b61bb2ebc05c5fd
1,601
yasan-helper-android-persian
MIT License
parserkt-util/src/commonMain/kotlin/org/parserkt/util/NumOps.kt
ParserKt
242,278,819
false
null
package org.parserkt.util interface BasicNumOps<NUM> { val zero: NUM fun from(n: Number): NUM fun to(n1: NUM): Number fun unaryMinus(a: NUM): NUM fun plus(b: NUM, a: NUM): NUM fun minus(b: NUM, a: NUM): NUM fun times(b: NUM, a: NUM): NUM fun div(b: NUM, a: NUM): NUM fun rem(b: NUM, a: NUM): NUM } interface NumOps<NUM: Comparable<NUM>>: BasicNumOps<NUM> { open class Instance<NUM: Comparable<NUM>>( override val zero: NUM, private val from: (Number) -> NUM, private val unaryMinus: Pipe<NUM>, private val plus: InfixJoin<NUM>, private val minus: InfixJoin<NUM>, private val times: InfixJoin<NUM>, private val div: InfixJoin<NUM>, private val rem: InfixJoin<NUM>, private val to: (NUM) -> Number = { it as Number } ): NumOps<NUM> { override fun from(n: Number) = from.invoke(n) override fun to(n1: NUM) = to.invoke(n1) override fun unaryMinus(a: NUM) = unaryMinus.invoke(a) override fun plus(b: NUM, a: NUM) = plus.invoke(a, b) override fun minus(b: NUM, a: NUM) = minus.invoke(a, b) override fun times(b: NUM, a: NUM) = times.invoke(a, b) override fun div(b: NUM, a: NUM) = div.invoke(a, b) override fun rem(b: NUM, a: NUM) = rem.invoke(a, b) } } private inline fun low(crossinline join: Byte.(Byte) -> Int): InfixJoin<Byte> = { b, a -> join(a, b).toByte() } private inline fun lowS(crossinline join: Short.(Short) -> Int): InfixJoin<Short> = { b, a -> join(a, b).toShort() } object ByteOps: NumOps.Instance<Byte>(0, Number::toByte, { (-it).toByte() }, low(Byte::plus), low(Byte::minus), low(Byte::times), low(Byte::div), low(Byte::rem)) object ShortOps: NumOps.Instance<Short>(0, Number::toShort, { (-it).toShort() }, lowS(Short::plus), lowS(Short::minus), lowS(Short::times), lowS(Short::div), lowS(Short::rem)) object IntOps: NumOps.Instance<Int>(0, Number::toInt, Int::unaryMinus, Int::plus, Int::minus, Int::times, Int::div, Int::rem) object LongOps: NumOps.Instance<Long>(0L, Number::toLong, Long::unaryMinus, Long::plus, Long::minus, Long::times, Long::div, Long::rem) object FloatOps: NumOps.Instance<Float>(0.0F, Number::toFloat, Float::unaryMinus, Float::plus, Float::minus, Float::times, Float::div, Float::rem) object DoubleOps: NumOps.Instance<Double>(0.0, Number::toDouble, Double::unaryMinus, Double::plus, Double::minus, Double::times, Double::div, Double::rem)
1
Kotlin
0
11
37599098dc9aafef7b509536e6d17ceca370d6cf
2,360
ParserKt
MIT License
parserkt-util/src/commonMain/kotlin/org/parserkt/util/NumOps.kt
ParserKt
242,278,819
false
null
package org.parserkt.util interface BasicNumOps<NUM> { val zero: NUM fun from(n: Number): NUM fun to(n1: NUM): Number fun unaryMinus(a: NUM): NUM fun plus(b: NUM, a: NUM): NUM fun minus(b: NUM, a: NUM): NUM fun times(b: NUM, a: NUM): NUM fun div(b: NUM, a: NUM): NUM fun rem(b: NUM, a: NUM): NUM } interface NumOps<NUM: Comparable<NUM>>: BasicNumOps<NUM> { open class Instance<NUM: Comparable<NUM>>( override val zero: NUM, private val from: (Number) -> NUM, private val unaryMinus: Pipe<NUM>, private val plus: InfixJoin<NUM>, private val minus: InfixJoin<NUM>, private val times: InfixJoin<NUM>, private val div: InfixJoin<NUM>, private val rem: InfixJoin<NUM>, private val to: (NUM) -> Number = { it as Number } ): NumOps<NUM> { override fun from(n: Number) = from.invoke(n) override fun to(n1: NUM) = to.invoke(n1) override fun unaryMinus(a: NUM) = unaryMinus.invoke(a) override fun plus(b: NUM, a: NUM) = plus.invoke(a, b) override fun minus(b: NUM, a: NUM) = minus.invoke(a, b) override fun times(b: NUM, a: NUM) = times.invoke(a, b) override fun div(b: NUM, a: NUM) = div.invoke(a, b) override fun rem(b: NUM, a: NUM) = rem.invoke(a, b) } } private inline fun low(crossinline join: Byte.(Byte) -> Int): InfixJoin<Byte> = { b, a -> join(a, b).toByte() } private inline fun lowS(crossinline join: Short.(Short) -> Int): InfixJoin<Short> = { b, a -> join(a, b).toShort() } object ByteOps: NumOps.Instance<Byte>(0, Number::toByte, { (-it).toByte() }, low(Byte::plus), low(Byte::minus), low(Byte::times), low(Byte::div), low(Byte::rem)) object ShortOps: NumOps.Instance<Short>(0, Number::toShort, { (-it).toShort() }, lowS(Short::plus), lowS(Short::minus), lowS(Short::times), lowS(Short::div), lowS(Short::rem)) object IntOps: NumOps.Instance<Int>(0, Number::toInt, Int::unaryMinus, Int::plus, Int::minus, Int::times, Int::div, Int::rem) object LongOps: NumOps.Instance<Long>(0L, Number::toLong, Long::unaryMinus, Long::plus, Long::minus, Long::times, Long::div, Long::rem) object FloatOps: NumOps.Instance<Float>(0.0F, Number::toFloat, Float::unaryMinus, Float::plus, Float::minus, Float::times, Float::div, Float::rem) object DoubleOps: NumOps.Instance<Double>(0.0, Number::toDouble, Double::unaryMinus, Double::plus, Double::minus, Double::times, Double::div, Double::rem)
1
Kotlin
0
11
37599098dc9aafef7b509536e6d17ceca370d6cf
2,360
ParserKt
MIT License
shared/src/commonMain/kotlin/composable/dialog/MiddleButtonDialog.kt
ntietje1
672,375,249
false
{"Kotlin": 328571, "Swift": 726}
package composable.dialog import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.LinearOutSlowInEasing import androidx.compose.animation.core.TweenSpec import androidx.compose.animation.slideInHorizontally import androidx.compose.animation.slideOutHorizontally import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.hapticfeedback.HapticFeedbackType import androidx.compose.ui.platform.LocalHapticFeedback import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.min import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties import composable.lifecounter.LifeCounterComponent import data.SettingsManager import data.SettingsManager.startingLife import getAnimationCorrectionFactor import lifelinked.shared.generated.resources.Res import lifelinked.shared.generated.resources.back_icon_alt import lifelinked.shared.generated.resources.coin_icon import lifelinked.shared.generated.resources.heart_solid_icon import lifelinked.shared.generated.resources.mana_icon import lifelinked.shared.generated.resources.moon_icon import lifelinked.shared.generated.resources.planeswalker_icon import lifelinked.shared.generated.resources.player_count_icon import lifelinked.shared.generated.resources.player_select_icon import lifelinked.shared.generated.resources.reset_icon import lifelinked.shared.generated.resources.search_icon import lifelinked.shared.generated.resources.settings_icon_small import lifelinked.shared.generated.resources.six_icon import lifelinked.shared.generated.resources.star_icon_small import lifelinked.shared.generated.resources.sun_and_moon_icon import lifelinked.shared.generated.resources.sun_icon import lifelinked.shared.generated.resources.x_icon import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.vectorResource import theme.scaledSp /** * The possible states of the middle button dialog */ private enum class MiddleButtonDialogState { Default, CoinFlip, PlayerNumber, FourPlayerLayout, StartingLife, DiceRoll, Counter, Settings, Scryfall, AboutMe, PlaneChase, PlanarDeck } /** * A dialog that allows the user to quickly interact with settings or move to other screens * @param modifier the modifier for this composable * @param onDismiss the action to perform when the dialog is dismissed * @param component the LifeCounterComponent * @param toggleTheme the action to perform when the theme is toggled */ @OptIn(ExperimentalResourceApi::class) @Composable fun MiddleButtonDialog( modifier: Modifier = Modifier, onDismiss: () -> Unit, component: LifeCounterComponent, toggleTheme: () -> Unit ) { var state by remember { mutableStateOf(MiddleButtonDialogState.Default) } val backStack = remember { mutableStateListOf(onDismiss) } val haptic = LocalHapticFeedback.current val duration = (450 / getAnimationCorrectionFactor()).toInt() var showResetDialog by remember { mutableStateOf(false) } val enterAnimation = slideInHorizontally( TweenSpec( duration, easing = LinearOutSlowInEasing ) ) { (-it * 1.25).toInt() } val exitAnimation = slideOutHorizontally( TweenSpec( duration, easing = LinearOutSlowInEasing ) ) { (it * 1.25).toInt() } @Composable fun FormattedAnimatedVisibility( visible: Boolean, content: @Composable () -> Unit ) { AnimatedVisibility( visible = visible, enter = enterAnimation, exit = exitAnimation ) { BoxWithConstraints( modifier = modifier .fillMaxSize() .background(MaterialTheme.colorScheme.background.copy(alpha = 0.1f)) .border( 1.dp, MaterialTheme.colorScheme.onPrimary.copy(alpha = 0.25f) ), ) { content() } } } val dialogContent: @Composable () -> Unit = { // BackHandler { // backStack.removeLast().invoke() // } BoxWithConstraints( modifier = modifier.fillMaxSize(), ) { val buttonModifier = Modifier.size( min( maxWidth / 3, maxHeight / 4 ) ) FormattedAnimatedVisibility( visible = state == MiddleButtonDialogState.CoinFlip ) { CoinFlipDialogContent( modifier = modifier, history = component.coinFlipHistory ) } FormattedAnimatedVisibility( visible = state == MiddleButtonDialogState.PlayerNumber ) { PlayerNumberDialogContent( modifier = Modifier.fillMaxSize(), onDismiss = onDismiss, setPlayerNum = { component.setNumPlayers(it) component.resetPlayerStates() }, resetPlayers = { component.resetPlayerStates() }, show4PlayerDialog = { state = MiddleButtonDialogState.FourPlayerLayout } ) } FormattedAnimatedVisibility( visible = state == MiddleButtonDialogState.FourPlayerLayout ) { FourPlayerLayoutContent( modifier = Modifier.fillMaxSize(), onDismiss = onDismiss, setPlayerNum = { component.setNumPlayers(it) component.resetPlayerStates() }, setAlt4PlayerLayout = { SettingsManager.alt4PlayerLayout = it } ) } FormattedAnimatedVisibility( visible = state == MiddleButtonDialogState.StartingLife ) { StartingLifeDialogContent( modifier = Modifier.fillMaxSize(), onDismiss = onDismiss, setStartingLife = { startingLife = it component.resetPlayerStates() } ) } FormattedAnimatedVisibility( visible = state == MiddleButtonDialogState.DiceRoll ) { DiceRollDialogContent(Modifier.fillMaxSize()) } FormattedAnimatedVisibility( visible = state == MiddleButtonDialogState.Counter ) { CounterDialogContent( modifier = Modifier.fillMaxSize(), counters = component.counters ) } FormattedAnimatedVisibility( visible = state == MiddleButtonDialogState.Scryfall ) { ScryfallDialogContent( Modifier.fillMaxSize(), player = null, backStack = backStack, selectButtonEnabled = false, rulingsButtonEnabled = true ) } FormattedAnimatedVisibility( visible = state == MiddleButtonDialogState.Settings ) { SettingsDialogContent(Modifier.fillMaxSize(), goToAboutMe = { state = MiddleButtonDialogState.AboutMe }, addGoToSettingsToBackStack = { backStack.add { state = MiddleButtonDialogState.Settings } }) } FormattedAnimatedVisibility( visible = state == MiddleButtonDialogState.AboutMe ) { AboutMeDialogContent( Modifier.fillMaxSize() ) } FormattedAnimatedVisibility( visible = state == MiddleButtonDialogState.PlaneChase ) { PlaneChaseDialogContent( modifier = Modifier.fillMaxSize(), component = component, goToChoosePlanes = { state = MiddleButtonDialogState.PlanarDeck backStack.add { state = MiddleButtonDialogState.PlaneChase } } ) } FormattedAnimatedVisibility( visible = state == MiddleButtonDialogState.PlanarDeck ) { val choosePlanesActions = remember { ChoosePlanesActions(planarDeck = component.planarDeck, backStack = backStack, planarBackStack = component.planarBackStack) } ChoosePlanesDialogContent( modifier = Modifier.fillMaxSize(), actions = choosePlanesActions ) } FormattedAnimatedVisibility( visible = state == MiddleButtonDialogState.Default ) { GridDialogContent( Modifier.fillMaxSize(), title = "Settings", items = listOf( { SettingsButton( modifier = buttonModifier, imageVector = vectorResource(Res.drawable.player_select_icon), text = "Player Select", shadowEnabled = false, onPress = { component.goToPlayerSelectScreen() onDismiss() }) }, { SettingsButton( modifier = buttonModifier, imageVector = vectorResource(Res.drawable.reset_icon), text = "Reset Game", shadowEnabled = false, onPress = { showResetDialog = true }) }, { SettingsButton( modifier = buttonModifier, imageVector = vectorResource(Res.drawable.heart_solid_icon), text = "Starting Life", shadowEnabled = false, onPress = { state = MiddleButtonDialogState.StartingLife backStack.add { state = MiddleButtonDialogState.Default } }) }, { SettingsButton( buttonModifier, imageVector = vectorResource(Res.drawable.star_icon_small), text = "Toggle Theme", shadowEnabled = false, onPress = { toggleTheme() }, ) }, { SettingsButton( buttonModifier, imageVector = vectorResource(Res.drawable.player_count_icon), text = "Player Number", shadowEnabled = false, onPress = { state = MiddleButtonDialogState.PlayerNumber backStack.add { state = MiddleButtonDialogState.Default } }) }, { SettingsButton( buttonModifier, imageVector = vectorResource(Res.drawable.mana_icon), text = "Mana & Storm", shadowEnabled = false, onPress = { state = MiddleButtonDialogState.Counter backStack.add { state = MiddleButtonDialogState.Default } }) }, { SettingsButton( buttonModifier, imageVector = vectorResource(Res.drawable.six_icon), text = "Dice roll", shadowEnabled = false, onPress = { state = MiddleButtonDialogState.DiceRoll backStack.add { state = MiddleButtonDialogState.Default } }) }, { SettingsButton( buttonModifier, imageVector = vectorResource(Res.drawable.coin_icon), text = "Coin Flip", shadowEnabled = false, onPress = { state = MiddleButtonDialogState.CoinFlip backStack.add { state = MiddleButtonDialogState.Default } }) }, { SettingsButton(buttonModifier, imageVector = when (component.dayNight) { LifeCounterComponent.DayNightState.DAY -> vectorResource(Res.drawable.sun_icon) LifeCounterComponent.DayNightState.NIGHT -> vectorResource(Res.drawable.moon_icon) LifeCounterComponent.DayNightState.NONE -> vectorResource(Res.drawable.sun_and_moon_icon) }, text = when (component.dayNight) { LifeCounterComponent.DayNightState.DAY -> "Day/Night" LifeCounterComponent.DayNightState.NIGHT -> "Day/Night" LifeCounterComponent.DayNightState.NONE -> "Day/Night" }, shadowEnabled = false, onPress = { component.toggleDayNight() }, onLongPress = { component.dayNight = LifeCounterComponent.DayNightState.NONE haptic.performHapticFeedback(HapticFeedbackType.LongPress) }) }, { SettingsButton(buttonModifier, imageVector = vectorResource(Res.drawable.search_icon), text = "Card Search", shadowEnabled = false, onPress = { state = MiddleButtonDialogState.Scryfall backStack.add { state = MiddleButtonDialogState.Default } }) }, { SettingsButton(buttonModifier, imageVector = vectorResource(Res.drawable.planeswalker_icon), text = "Planechase", shadowEnabled = false, onPress = { state = MiddleButtonDialogState.PlaneChase backStack.add { state = MiddleButtonDialogState.Default } }) }, { SettingsButton(buttonModifier, imageVector = vectorResource(Res.drawable.settings_icon_small), text = "Settings", shadowEnabled = false, onPress = { state = MiddleButtonDialogState.Settings backStack.add { state = MiddleButtonDialogState.Default } }) }) ) } } } if (showResetDialog) { WarningDialog( onDismiss = { showResetDialog = false }, title = "Reset Game", message = "Select an option to start a new game", optionOneMessage = "Same players", optionTwoMessage = "Different players", onOptionOne = { component.resetPlayerStates() showResetDialog = false onDismiss() }, onOptionTwo = { component.resetCustomizations() component.resetPlayerStates() showResetDialog = false onDismiss() }, ) } SettingsDialog( onDismiss = { onDismiss() }, content = dialogContent, onBack = { backStack.removeLast().invoke() }) } /** * A generic dialog for displaying a grid of buttons * @param modifier the modifier for this composable * @param title the title of the dialog * @param items the composable items to display in the grid */ @Composable fun GridDialogContent( modifier: Modifier = Modifier, title: String, items: List<@Composable () -> Unit> = emptyList() ) { Box(modifier = modifier) { Column( Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Spacer(modifier = Modifier.weight(0.05f)) Text( modifier = Modifier .wrapContentHeight() .wrapContentWidth(), text = title, fontSize = 25.scaledSp, color = MaterialTheme.colorScheme.onPrimary ) Spacer(modifier = Modifier.weight(0.025f)) LazyVerticalGrid(modifier = Modifier .padding(horizontal = 10.dp) .wrapContentSize(), columns = GridCells.Fixed(3), content = { items(items.size) { index -> items[index]() } }) Spacer(modifier = Modifier.weight(0.075f)) } } } /** * A base dialog for displaying settings within * @param modifier the modifier for this composable * @param onDismiss the action to perform when the dialog is dismissed * @param onBack the action to perform when the back button is pressed * @param exitButtonEnabled whether the exit button is enabled * @param backButtonEnabled whether the back button is enabled * @param content the content of the dialog */ @Composable fun SettingsDialog( modifier: Modifier = Modifier, onDismiss: () -> Unit = {}, onBack: () -> Unit = {}, exitButtonEnabled: Boolean = true, backButtonEnabled: Boolean = true, content: @Composable () -> Unit = {} ) { Dialog( onDismissRequest = onDismiss, properties = DialogProperties( dismissOnBackPress = true, usePlatformDefaultWidth = false, ) ) { BoxWithConstraints( modifier = modifier .fillMaxSize() .background(MaterialTheme.colorScheme.background.copy(alpha = 0.5f)), contentAlignment = Alignment.Center ) { val buttonSize = maxHeight / 15f Column(Modifier.fillMaxSize()) { if (exitButtonEnabled) { Row( Modifier .fillMaxWidth() .wrapContentHeight(), horizontalArrangement = Arrangement.End ) { ExitButton( Modifier.size(buttonSize), onDismiss = onDismiss, visible = exitButtonEnabled ) } } Box( Modifier.weight(0.1f).padding(5.dp) ) { content() } if (backButtonEnabled) { Row( Modifier .fillMaxWidth() .wrapContentHeight(), horizontalArrangement = Arrangement.SpaceBetween ) { BackButton( Modifier.size(buttonSize), onBack = onBack, visible = backButtonEnabled ) } } } } } } /** * Back button for use in dialogs * @param modifier the modifier for this composable * @param visible whether the button is visible * @param onBack the action to perform when the button is pressed */ @OptIn(ExperimentalResourceApi::class) @Composable fun BackButton(modifier: Modifier = Modifier, visible: Boolean, onBack: () -> Unit) { SettingsButton( modifier = modifier, backgroundColor = Color.Transparent, text = "", visible = visible, shadowEnabled = false, imageVector = vectorResource(Res.drawable.back_icon_alt), onTap = onBack ) } /** * Exit button for use in dialogs * @param modifier the modifier for this composable * @param visible whether the button is visible * @param onDismiss the action to perform when the button is pressed */ @OptIn(ExperimentalResourceApi::class) @Composable fun ExitButton(modifier: Modifier = Modifier, visible: Boolean, onDismiss: () -> Unit) { SettingsButton( modifier = modifier, backgroundColor = Color.Transparent, text = "", visible = visible, shadowEnabled = false, imageVector = vectorResource(Res.drawable.x_icon), onTap = onDismiss ) }
0
Kotlin
0
1
b43699790df2e74bf29be6d6c32511d8778d6676
24,159
MTG_Life_Total_App
Apache License 2.0
src/main/kotlin/org/openweather/cached/service/model/interfaces/Wind.kt
ZsoltBerki
357,253,147
false
null
package org.openweather.cached.service.model.interfaces interface Wind { /** * Wind speed. Wind speed. Units – default: metre/sec, metric: metre/sec, imperial: miles/hour. */ val windSpeed: Float /** * Wind gust. Units – default: metre/sec, metric: metre/sec, imperial: miles/hour. */ val windGust: Float? /** * Wind direction, degrees (meteorological) */ val windDegree: Float }
0
Kotlin
0
0
2a0c19117816d4aeba9ef94b3bbc57f5b4ed4288
437
OpenWeatherKotlin
Apache License 2.0
Barlom-Domain-JVM/src/main/kotlin/o/barlom/domain/metamodel/api/types/EBoolean.kt
martin-nordberg
82,682,055
false
null
// // (C) Copyright 2015-2017 <NAME> // Apache 2.0 License // package o.barlom.domain.metamodel.api.types /** * Enumeration of possible values for whether something is true or false. Useful for converting to functions that work * on enums (e.g. Yes/No radio buttons). */ enum class EBoolean { /** A value is true. */ FALSE, /** A value is false. */ TRUE; /** * Tests whether this enum value is FALSE. * @return true if this is FALSE. */ fun isFalse(): Boolean { return this == FALSE } /** * Tests whether this enum value is TRUE. * @return true if this is TRUE. */ fun isTrue(): Boolean { return this == TRUE } /** * Converts this enum value to a boolean equivalent. * @return true, false, or null */ fun toBoolean(): Boolean { return when (this) { FALSE -> false TRUE -> true } } companion object { /** * Determines the abstractness corresponding to a boolean value for is-abstract. * @param isAbstract whether the item is abstract. * @return the corresponding enum value. */ fun fromBoolean(value: Boolean): EBoolean { return if (value) TRUE else FALSE } } }
0
Kotlin
0
0
337b46f01f6eec6dfb3b86824c26f1c103e9d9a2
1,309
ZZ-Barlom
Apache License 2.0
app/src/main/java/com/andreadev/roomsample/di/components/PresenterComponent.kt
battagliandrea
112,673,607
false
null
package com.andreadev.roomsample.di.components import com.andreadev.roomsample.di.PresenterScope import com.andreadev.roomsample.di.modules.PresenterModule import com.andreadev.roomsample.ui.itemslist.ItemListFragment import com.andreadev.roomsample.ui.splash.SplashFragment import dagger.Component /** * Created by andrea on 26/08/2017. */ @PresenterScope @Component(dependencies = arrayOf(AppComponent::class), modules = arrayOf(PresenterModule::class)) interface PresenterComponent { fun inject(splashFragment: SplashFragment) fun inject(itemListFragment: ItemListFragment) }
0
Kotlin
0
0
6e2ab03813ff80ab3f6b2cb7fbaaafb86289b582
594
RoomSample
Apache License 2.0
src/commonMain/kotlin/com/cozmicgames/Application.kt
CozmicGames
477,147,957
false
{"Kotlin": 690755}
package com.cozmicgames interface Application { /** * Called when the application is first created. */ fun onCreate() {} /** * Called each frame. * * @param delta The time in seconds since the last frame. */ fun onFrame(delta: Float) {} /** * Called when the application is being destroyed. */ fun onDispose() {} /** * Called when the application is resized. * * @param width The new width of the application. * @param height The new height of the application. */ fun onResize(width: Int, height: Int) {} /** * Called when the application is paused. */ fun onPause() {} /** * Called when the application is resumed from a paused state. */ fun onResume() {} }
0
Kotlin
0
0
08290e122f639e87c823f8220c80738c1c7fb631
798
Kore
MIT License
gaia/src/commonMain/kotlin/fyi/pauli/ichor/gaia/networking/packet/incoming/handshaking/Handshake.kt
ichor-dev
676,285,724
false
{"Kotlin": 75790}
package fyi.pauli.ichor.gaia.networking.packet.incoming.handshaking import fyi.pauli.ichor.gaia.networking.packet.State import fyi.pauli.ichor.gaia.networking.packet.incoming.IncomingPacket import fyi.pauli.prolialize.serialization.types.NumberType import fyi.pauli.prolialize.serialization.types.primitives.MinecraftNumberType import kotlinx.serialization.Serializable @Serializable public data class Handshake( val protocolVersion: Int, val serverAddress: String, @NumberType(MinecraftNumberType.UNSIGNED) val serverPort: Short, val nextState: State ) : IncomingPacket
5
Kotlin
0
0
b0aa02416f95ef5586376c0f940f05fd28f2d760
576
ichor
Apache License 2.0
message-server/src/main/kotlin/com/qingzhu/messageserver/service/ConversationStatusService.kt
linjinhai
394,838,665
true
{"Kotlin": 693654, "ANTLR": 281490, "Java": 48298, "Dockerfile": 375}
package com.qingzhu.messageserver.service import com.hazelcast.config.IndexType import com.hazelcast.core.HazelcastInstance import com.hazelcast.query.Predicate import com.hazelcast.query.Predicates import com.hazelcast.query.impl.predicates.EqualPredicate import com.qingzhu.messageserver.domain.entity.ConversationStatus import org.springframework.beans.factory.annotation.Qualifier import org.springframework.stereotype.Service import reactor.core.publisher.Mono import java.util.concurrent.TimeUnit @Service class ConversationStatusService( @Qualifier("hazelcastInstance") private val hazelcastInstance: HazelcastInstance, private val staffStatusService: StaffStatusService, private val messagePersistentService: MessagePersistentService, ) { private fun getStatusMap(organizationId: Int) = hazelcastInstance.getMap<Long, ConversationStatus>("$organizationId:conversation") /** * 设置客服状态 */ fun saveStatus(conversationStatus: ConversationStatus) { val statusMap = getStatusMap(conversationStatus.organizationId) if (statusMap.isEmpty) { statusMap.addIndex(IndexType.HASH, "staffId") statusMap.addIndex(IndexType.HASH, "userId") } statusMap.put(conversationStatus.id, conversationStatus, 1, TimeUnit.HOURS) } /** * 结束会话 */ fun endConversation(conversationStatus: ConversationStatus): Mono<ConversationStatus> { val statusMap = getStatusMap(conversationStatus.organizationId) return Mono.justOrEmpty(statusMap[conversationStatus.id]) .doOnNext { it.endConversation() statusMap.put(it.id, it, 15, TimeUnit.MINUTES) staffStatusService.removeCustomer( it.organizationId, it.staffId, it.userId ) } .flatMap { messagePersistentService.convPersistent(it) .map { _ -> it } } } /** * 生成会话 */ fun generate(conversationStatusDto: ConversationStatus): Mono<ConversationStatus> { return Mono.just(conversationStatusDto) .doOnNext { saveStatus(it) } } fun findLatestByUserId(organizationId: Int, userId: Long): Mono<ConversationStatus> { val statusMap = getStatusMap(organizationId) @Suppress("UNCHECKED_CAST") val equalPredicate = EqualPredicate("userId", userId) as Predicate<Long, ConversationStatus> val pagePredicate = Predicates.pagingPredicate(equalPredicate, // desc for conversation id { o1, o2 -> (o2?.key?.minus(o1?.key ?: 0) ?: 0).toInt() }, 1 ) return Mono.justOrEmpty( statusMap .values(pagePredicate) .stream().findFirst() ) } }
0
null
0
0
b4718991300746ccc627c735c79f478b3cfa0956
2,846
contact-center
Apache License 2.0
app/src/main/java/jarvay/workpaper/compose/rule/RuleForm.kt
Jarvay
837,149,810
false
{"Kotlin": 96878}
package jarvay.workpaper.compose.rule import android.annotation.SuppressLint import android.util.Log import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.filled.Save import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.Checkbox import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.rememberTimePickerState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import androidx.navigation.NavController import jarvay.workpaper.R import jarvay.workpaper.compose.components.TimePickerDialog import jarvay.workpaper.data.album.Album import jarvay.workpaper.data.rule.Rule import jarvay.workpaper.data.rule.RuleWithAlbum import jarvay.workpaper.others.FormMode import jarvay.workpaper.others.dayOptions import jarvay.workpaper.others.formatTime import jarvay.workpaper.ui.theme.FORM_ITEM_SPACE import jarvay.workpaper.ui.theme.SCREEN_HORIZONTAL_PADDING @SuppressLint("MutableCollectionMutableState") @OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) @Composable fun RuleForm( navController: NavController, albums: List<Album>, values: RuleWithAlbum? = null, onSave: (Rule) -> Unit, ) { var startTimePickerState = rememberTimePickerState( is24Hour = true, initialHour = values?.rule?.startHour ?: 0, initialMinute = values?.rule?.startMinute ?: 0 ) var startPickerShow by remember { mutableStateOf(false) } var albumMenuExpanded by remember { mutableStateOf(false) } var album by remember { mutableStateOf(value = values?.album) } var checkedState by remember { mutableStateOf(values?.rule?.days?.toSet() ?: dayOptions.map { it.value }.toSet()) } if (startPickerShow) { TimePickerDialog( timePickerState = startTimePickerState, onDismiss = { startPickerShow = false }) { timePickerState -> startTimePickerState = timePickerState startPickerShow = false } } Scaffold(topBar = { CenterAlignedTopAppBar( title = { Text("") }, navigationIcon = { IconButton(onClick = { navController.navigateUp() }) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "") } }, actions = { IconButton(onClick = { onSave( Rule( startHour = startTimePickerState.hour, startMinute = startTimePickerState.minute, albumId = album!!.albumId, days = checkedState.toList() ) ) }, enabled = album != null) { Icon(Icons.Default.Save, "") } } ) }) { padding -> val defaultModifier = Modifier.fillMaxWidth() Column( verticalArrangement = Arrangement.spacedBy(FORM_ITEM_SPACE), modifier = Modifier .padding(padding) .padding(horizontal = SCREEN_HORIZONTAL_PADDING) ) { LazyVerticalGrid(columns = GridCells.Adaptive(minSize = 96.dp)) { items(items = dayOptions) { option -> Row(verticalAlignment = Alignment.CenterVertically) { Checkbox( checked = checkedState.contains(option.value), onCheckedChange = { checked -> val checkedSet = checkedState.toMutableSet() if (checked) { checkedSet.add(option.value) } else { checkedSet.remove(option.value) } checkedState = checkedSet.toMutableSet() }) Text(stringResource(id = option.labelId)) } } } OutlinedTextField( label = { Text(text = stringResource(id = R.string.rule_start_time)) }, value = formatTime(startTimePickerState.hour, startTimePickerState.minute), onValueChange = {}, readOnly = true, enabled = false, modifier = defaultModifier.clickable { startPickerShow = true }) Box(modifier = Modifier) { OutlinedTextField( label = { Text(text = stringResource(id = R.string.rule_album)) }, value = album?.name ?: "", onValueChange = {}, modifier = defaultModifier.clickable { albumMenuExpanded = true }, enabled = false, ) DropdownMenu( expanded = albumMenuExpanded, onDismissRequest = { albumMenuExpanded = false }) { albums.forEach { DropdownMenuItem(text = { Text(text = it.name) }, onClick = { album = it albumMenuExpanded = false }) } } } } } }
0
Kotlin
0
0
37c15736fa2b01bf8583e658c05e335d56909dec
7,058
workpaper-android
MIT License
wow-query/src/test/kotlin/me/ahoo/wow/query/SnapshotStatesKtTest.kt
Ahoo-Wang
628,167,080
false
{"Kotlin": 2407170, "TypeScript": 50124, "Java": 37656, "HTML": 15900, "Lua": 3978, "JavaScript": 2514, "Dockerfile": 820, "SCSS": 609, "Less": 413}
package me.ahoo.wow.query import io.mockk.every import io.mockk.mockk import me.ahoo.wow.api.query.DynamicDocument import me.ahoo.wow.api.query.MaterializedSnapshot import me.ahoo.wow.api.query.PagedList import me.ahoo.wow.api.query.SimpleDynamicDocument import org.hamcrest.MatcherAssert.* import org.hamcrest.Matchers.* import org.junit.jupiter.api.Test import reactor.core.publisher.Flux import reactor.core.publisher.Mono import reactor.kotlin.core.publisher.toMono import reactor.kotlin.test.test class SnapshotStatesKtTest { @Test fun toState() { val snapshot = mockk<MaterializedSnapshot<String>> { every { state } returns "state" } snapshot.toMono().toState().test().expectNext("state").verifyComplete() } @Test fun dyToState() { val snapshot = SimpleDynamicDocument(mapOf("state" to SimpleDynamicDocument(mapOf("id" to "id")))) snapshot.toMono().toStateDocument().test().consumeNextWith { assertThat(it.getValue<String>("id"), equalTo("id")) }.verifyComplete() } @Test fun fluxToState() { val snapshot = mockk<MaterializedSnapshot<String>> { every { state } returns "state" } Flux.just(snapshot).toState().test().expectNext("state").verifyComplete() } @Test fun dyFluxToState() { val snapshot = SimpleDynamicDocument(mapOf("state" to SimpleDynamicDocument(mapOf("id" to "id")))) Flux.just(snapshot).toStateDocument().test().consumeNextWith { assertThat(it.getValue<String>("id"), equalTo("id")) }.verifyComplete() } @Test fun toStatePagedList() { val snapshot = mockk<MaterializedSnapshot<String>> { every { state } returns "state" } val pagedList = PagedList(1, listOf(snapshot)) Mono.just(pagedList).toStatePagedList().test() .expectNextCount(1) .verifyComplete() } @Test fun dyToStatePagedList() { val snapshot = SimpleDynamicDocument( mapOf("state" to SimpleDynamicDocument(mapOf("id" to "id"))) ) as DynamicDocument val pagedList = PagedList(1, listOf(snapshot)) Mono.just(pagedList).toStateDocumentPagedList().test() .expectNextCount(1) .verifyComplete() } }
3
Kotlin
22
167
f9bf2e88ac483523692f8325f6c6a59bcb2259c2
2,334
Wow
Apache License 2.0
src/main/kotlin/com/kazzutilsv2/features/events/mythological/MythoTracker.kt
FizzHatMc
804,593,419
false
{"Kotlin": 418098, "Java": 35134, "Shell": 1219}
package com.kazzutilsv2.features.events.mythological import net.minecraftforge.client.event.ClientChatReceivedEvent import net.minecraftforge.fml.common.eventhandler.SubscribeEvent class MythoTracker { companion object{ var inq: Int = 0 var champ: Int = 0 var mino: Int = 0 var gaia: Int = 0 var lynx: Int = 0 var hunter: Int = 0 var totalMobs: Int = 0 var coins: Double = 0.0 var burrows: Int = 0 var feathers: Int = 0 var sinceInq: Int = 0 var champChance: Double = 0.0 var minoChance: Double = 0.0 var gaiaChance: Double = 0.0 var lynxChance: Double = 0.0 var hunterChance: Double = 0.0 var inqChance : Double = 0.0 fun getVarByName(name: String) : Any{ when (name) { "inq" -> return inq "champ" -> return champ "mino" -> return mino "gaia" -> return gaia "lynx" -> return lynx "hunter" -> return hunter "totalMobs" -> return totalMobs "coins" ->return coins "burrows" -> return burrows "feathers" -> return feathers "sinceInq" -> return sinceInq "champChance" -> return champChance "minoChance" -> return minoChance "gaiaChance" -> return gaiaChance "lynxChance" -> return lynxChance "hunterChance" -> return hunterChance "inqChance" -> return inqChance else -> return "N/A" } } } @SubscribeEvent fun onChat(event : ClientChatReceivedEvent){ if (event.type.toInt() == 2) return val message = event.message.unformattedTextForChat when(message){ "You dug out a Minos Inquisitor!" -> inq++ "You dug out a Champion!" -> champ++ "You dug out a Minotaur!" -> mino++ "You dug out a Gaia!" -> gaia++ "You dug out a Lynx!" -> lynx++ "You dug out a Hunter!" -> hunter++ } if(message.contains("You dug out a Minos Inquisitor!")) sinceInq = 0 if(message.contains("You dug out") && message.contains("coins!")){ val coin = message.substring(message.indexOf("out") + 4, message.indexOf("coins!") - 1).replace(",", "") val coins2 = coin.toInt() var coins3 = coins2.toDouble() / 1000000 coins3 *= 100 val komma = coins3.toInt() coins3 = komma.toDouble() / 100 coins += coins3 } if(message.contains("You dug out a Griffin Feather!")) feathers++ if(message.contains("You dug out a Griffin Burrow!")) burrows++ totalMobs = inq + champ + mino + gaia + lynx + hunter if(totalMobs>0){ inqChance = (Math.round(((inq / totalMobs) * 100).toDouble()) / 100).toDouble() champChance = (Math.round(((champ / totalMobs) * 100).toDouble()) / 100).toDouble() minoChance = (Math.round(((mino / totalMobs) * 100).toDouble()) / 100).toDouble() gaiaChance = (Math.round(((gaia / totalMobs) * 100).toDouble()) / 100).toDouble() lynxChance = (Math.round(((lynx / totalMobs) * 100).toDouble()) / 100).toDouble() hunterChance = (Math.round(((hunter / totalMobs) * 100).toDouble()) / 100).toDouble() } } }
0
Kotlin
0
0
dd3928ebb6923bf74d8215062fcc75e52e7d7637
3,520
KazzUtilsV2
The Unlicense
androidApp/src/main/java/com/nicolasmilliard/githubcontributormultiplatform/ui/InjectViewModelFactory.kt
Couchsurfing
615,128,638
false
null
package com.nicolasmilliard.githubcontributormultiplatform.ui import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.nicolasmilliard.githubcontributormultiplatform.ui.home.HomeViewModel import me.tatarka.inject.annotations.Inject @Suppress("UNCHECKED_CAST") @Inject class InjectViewModelFactory(private val homeViewModel: () -> HomeViewModel): ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(HomeViewModel::class.java)) { return homeViewModel() as T } throw UnsupportedOperationException() } }
0
Kotlin
0
0
51add02eeaa80e4ceccdaf7cef137f0f9ad8bbd6
631
github-multiplatform-playground
Apache License 2.0
core/src/main/java/id/rifqipadisiliwangi/core/utils/ResultWrapper.kt
Rifqips
767,860,717
false
{"Kotlin": 316033}
package id.rifqipadisiliwangi.core.utils import id.rifqipadisiliwangi.core.utils.exceptions.ApiException import id.rifqipadisiliwangi.core.utils.exceptions.NoInternetException import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.onStart import retrofit2.HttpException import java.io.IOException sealed class ResultWrapper<T>( val payload: T? = null, val message: String? = null, val exception: Exception? = null ) { class Success<T>(data: T) : ResultWrapper<T>(data) class Error<T>(exception: Exception?, data: T? = null) : ResultWrapper<T>(data, exception = exception) class Empty<T>(data: T? = null) : ResultWrapper<T>(data) class Loading<T>(data: T? = null) : ResultWrapper<T>(data) } fun <T> ResultWrapper<T>.proceedWhen( doOnSuccess: ((resource: ResultWrapper<T>) -> Unit)? = null, doOnError: ((resource: ResultWrapper<T>) -> Unit)? = null, doOnLoading: ((resource: ResultWrapper<T>) -> Unit)? = null, doOnEmpty: ((resource: ResultWrapper<T>) -> Unit)? = null ) { when (this) { is ResultWrapper.Success -> doOnSuccess?.invoke(this) is ResultWrapper.Error -> doOnError?.invoke(this) is ResultWrapper.Loading -> doOnLoading?.invoke(this) is ResultWrapper.Empty -> doOnEmpty?.invoke(this) } } suspend fun <T> proceed(block: suspend () -> T): ResultWrapper<T> { return try { val result = block.invoke() if (result is Collection<*> && result.isEmpty()) { ResultWrapper.Empty(result) } else { ResultWrapper.Success(result) } } catch (e: Exception) { ResultWrapper.Error<T>(exception = Exception(e)) } } fun <T> proceedFlow(block: suspend () -> T): Flow<ResultWrapper<T>> { return flow<ResultWrapper<T>> { val result = block.invoke() emit( if (result is Collection<*> && result.isEmpty()) { ResultWrapper.Empty(result) } else { ResultWrapper.Success(result) } ) }.catch { e -> val exception = when (e) { is IOException -> NoInternetException() is HttpException -> ApiException(e.message().orEmpty(), e.code(), e.response()) else -> Exception(e) } emit(ResultWrapper.Error<T>(exception = exception)) }.onStart { emit(ResultWrapper.Loading()) } }
0
Kotlin
0
0
d3dcbf01c5155a6b761a2919c214bda5de0374a9
2,511
TokoPaerbe
MIT License
mui-icons-kotlin/src/jsMain/kotlin/mui/icons/material/SafetyCheck.kt
karakum-team
387,062,541
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/SafetyCheck") @file:JsNonModule package mui.icons.material @JsName("default") external val SafetyCheck: SvgIconComponent
0
Kotlin
3
31
b23d946ab3392e7a1ec017176ae48b952334fc75
204
mui-kotlin
Apache License 2.0
app/src/main/java/com/toxicbakery/androidthings/mirror/module/newsfeed/ui/view/NewsFeedViewLayout.kt
knobtviker
141,413,822
true
{"Kotlin": 93331}
package com.toxicbakery.androidthings.mirror.module.newsfeed.ui.view import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import com.github.salomonbrys.kodein.Kodein import com.github.salomonbrys.kodein.instance import com.toxicbakery.androidthings.mirror.R import com.toxicbakery.androidthings.mirror.module.newsfeed.kodein.newsFeedKodein import com.toxicbakery.androidthings.mirror.module.newsfeed.ui.adapter.NewsFeedAdapter import com.toxicbakery.androidthings.mirror.module.newsfeed.ui.presenter.NewsFeedPresenter import com.toxicbakery.androidthings.mirror.module.newsfeed.ui.viewholder.NewsFeedViewHolder import com.toxicbakery.androidthings.mirror.ui.view.BaseMvpKodeinFrameLayout class NewsFeedViewLayout @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : BaseMvpKodeinFrameLayout<NewsFeedViewHolder, NewsFeedPresenter>(context, attrs, defStyleAttr) { private val adapter = NewsFeedAdapter() override fun provideOverridingKodein(): Kodein = Kodein { extend(newsFeedKodein) } override val presenter: NewsFeedPresenter by injector.instance() override val viewHolder: NewsFeedViewHolder = LayoutInflater.from(context) .inflate(R.layout.module_news_feed_layout, this, true) .let{ NewsFeedViewHolder(it, adapter) } }
0
Kotlin
0
0
4263ee2c7fb0cdf8f237e14351d87dcadf7a84c0
1,397
AndroidThings-Mirror
Apache License 2.0
app/src/main/java/dog/snow/androidrecruittest/data/network/model/NetworkUser.kt
trOnk12
252,550,688
false
{"Kotlin": 57018}
package dog.snow.androidrecruittest.data.network.model import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize data class NetworkUser( val id: Int, val name: String, val username: String, val email: String, val address: Address, val phone: String, val website: String, val company: Company ) : Parcelable { @Parcelize data class Address( val street: String, val suite: String, val city: String, val zipcode: String, val geo: Geo ) : Parcelable { @Parcelize data class Geo(val lat: String, val lng: String) : Parcelable } @Parcelize data class Company( val name: String, val catchPhrase: String, val bs: String ) : Parcelable }
0
Kotlin
0
0
1fea6aab8ff3838975ae8ac5416a1eda6dbb2383
793
image-viewer
Apache License 2.0
app/src/main/java/dog/snow/androidrecruittest/data/network/model/NetworkUser.kt
trOnk12
252,550,688
false
{"Kotlin": 57018}
package dog.snow.androidrecruittest.data.network.model import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize data class NetworkUser( val id: Int, val name: String, val username: String, val email: String, val address: Address, val phone: String, val website: String, val company: Company ) : Parcelable { @Parcelize data class Address( val street: String, val suite: String, val city: String, val zipcode: String, val geo: Geo ) : Parcelable { @Parcelize data class Geo(val lat: String, val lng: String) : Parcelable } @Parcelize data class Company( val name: String, val catchPhrase: String, val bs: String ) : Parcelable }
0
Kotlin
0
0
1fea6aab8ff3838975ae8ac5416a1eda6dbb2383
793
image-viewer
Apache License 2.0
app/src/main/java/com/newapp/test_firebase_app/ui/start/createAccount/CreateAccountViewModel.kt
Soknop0211
621,139,868
false
null
package com.newapp.test_firebase_app.ui.start.createAccount import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.newapp.test_firebase_app.data.Event import com.newapp.test_firebase_app.data.Result import com.newapp.test_firebase_app.data.db.entity.User import com.newapp.test_firebase_app.data.db.repository.AuthRepository import com.newapp.test_firebase_app.data.db.repository.DatabaseRepository import com.newapp.test_firebase_app.data.model.CreateUser import com.newapp.test_firebase_app.ui.DefaultViewModel import com.newapp.test_firebase_app.util.isEmailValid import com.newapp.test_firebase_app.util.isTextValid import com.google.firebase.auth.FirebaseUser class CreateAccountViewModel : DefaultViewModel() { private val dbRepository = DatabaseRepository() private val authRepository = AuthRepository() private val mIsCreatedEvent = MutableLiveData<Event<FirebaseUser>>() val isCreatedEvent: LiveData<Event<FirebaseUser>> = mIsCreatedEvent val displayNameText = MutableLiveData<String>() // Two way val emailText = MutableLiveData<String>() // Two way val passwordText = MutableLiveData<String>() // Two way val isCreatingAccount = MutableLiveData<Boolean>() private fun createAccount() { isCreatingAccount.value = true val createUser = CreateUser(displayNameText.value!!, emailText.value!!, passwordText.value!!) authRepository.createUser(createUser) { result: Result<FirebaseUser> -> onResult(null, result) if (result is Result.Success) { mIsCreatedEvent.value = Event(result.data!!) dbRepository.updateNewUser(User().apply { info.id = result.data.uid info.displayName = createUser.displayName }) } if (result is Result.Success || result is Result.Error) isCreatingAccount.value = false } } fun createAccountPressed() { if (!isTextValid(2, displayNameText.value)) { mSnackBarText.value = Event("Display name is too short") return } if (!isEmailValid(emailText.value.toString())) { mSnackBarText.value = Event("Invalid email format") return } if (!isTextValid(6, passwordText.value)) { mSnackBarText.value = Event("Password is too short") return } createAccount() } }
0
Kotlin
0
0
d538754c811b156002f89219c26a79685d9e4c8b
2,474
Chat-Project-Test
MIT License
app/src/androidTest/java/com/fevziomurtekin/deezer/ui/MainActivityTest.kt
gustavobite
331,638,803
true
{"Kotlin": 191832}
package com.fevziomurtekin.deezer.ui import androidx.lifecycle.Lifecycle import androidx.test.core.app.ActivityScenario import androidx.test.espresso.Espresso.* import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.ext.junit.runners.AndroidJUnit4 import com.fevziomurtekin.deezer.R import com.fevziomurtekin.deezer.core.data.ApiResult import com.fevziomurtekin.deezer.ui.main.MainActivity import dagger.hilt.android.testing.HiltAndroidRule import dagger.hilt.android.testing.HiltAndroidTest import org.hamcrest.Matchers.not import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @HiltAndroidTest @RunWith(AndroidJUnit4::class) class MainActivityTest { @get:Rule var hiltRule = HiltAndroidRule(this) @Test fun test_isGoneSplash() { ActivityScenario.launch(MainActivity::class.java).use { it.moveToState(Lifecycle.State.CREATED) it.onActivity { activity-> activity.viewModel.genreListLiveData.observe(activity){r-> if(r is ApiResult.Succes){ onView(withId(R.id.cl_splash)).check(matches(not(isDisplayed()))) } } } } } }
0
null
0
0
1ec7f41041162a651c6e9f98ad1cfe2a06cb3cef
1,360
DeezerClone
Apache License 2.0
kotlin/src/main/java/com/example/kt/KtMainActivity2.kt
fenggit
506,854,183
false
{"Kotlin": 76622, "Java": 13382, "Shell": 1110}
package com.example.kt import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.MainScope import kotlinx.coroutines.cancel import kotlinx.coroutines.launch /** * author : felix * date : 2023/9/5 * description : */ class KtMainActivity2 : AppCompatActivity(), CoroutineScope by MainScope() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) launch { // TODO } } override fun onDestroy() { super.onDestroy() cancel() } }
0
Kotlin
0
0
6da6233f19f091aac88adfbc3795fb1b4d859b3d
616
AndroidDailyLab
Apache License 2.0
src/mingwNativeTest/kotlin/ca/gosyer/appdirs/MingwNativeTest.kt
Syer10
578,459,054
false
{"Kotlin": 44823, "Shell": 1639}
package ca.gosyer.appdirs class MingwNativeTest : WindowsTest()
0
Kotlin
2
26
63290dea066fb5d3d7d46740a0335b918b6355f5
64
Kotlin-Multiplatform-AppDirs
Apache License 2.0
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/constructs/ConstructOrder.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 149148378}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.constructs public enum class ConstructOrder( private val cdkObject: software.constructs.ConstructOrder, ) { PREORDER(software.constructs.ConstructOrder.PREORDER), POSTORDER(software.constructs.ConstructOrder.POSTORDER), ; public companion object { internal fun wrap(cdkObject: software.constructs.ConstructOrder): ConstructOrder = when (cdkObject) { software.constructs.ConstructOrder.PREORDER -> ConstructOrder.PREORDER software.constructs.ConstructOrder.POSTORDER -> ConstructOrder.POSTORDER } internal fun unwrap(wrapped: ConstructOrder): software.constructs.ConstructOrder = wrapped.cdkObject } }
0
Kotlin
0
4
305b2af4703c09194822c8ad2c508fdfeb021cc5
858
kotlin-cdk-wrapper
Apache License 2.0
common/src/commonMain/kotlin/com/darkrockstudios/apps/hammer/common/projecteditor/sceneeditor/SceneEditor.kt
Wavesonics
499,367,913
false
null
package com.darkrockstudios.apps.hammer.common.projecteditor.sceneeditor import com.arkivanov.decompose.value.MutableValue import com.arkivanov.decompose.value.Value import com.darkrockstudios.apps.hammer.common.data.PlatformRichText import com.darkrockstudios.apps.hammer.common.data.SceneBuffer import com.darkrockstudios.apps.hammer.common.data.SceneItem import com.darkrockstudios.apps.hammer.common.dependencyinjection.HammerComponent interface SceneEditor : HammerComponent { val state: Value<State> var lastDiscarded: MutableValue<Long> fun addEditorMenu() fun removeEditorMenu() fun loadSceneContent() fun storeSceneContent(): Boolean fun onContentChanged(content: PlatformRichText) fun beginSceneNameEdit() fun endSceneNameEdit() fun changeSceneName(newName: String) fun beginSaveDraft() fun endSaveDraft() fun saveDraft(draftName: String): Boolean data class State( val sceneItem: SceneItem, val sceneBuffer: SceneBuffer? = null, val isEditingName: Boolean = false, val isSavingDraft: Boolean = false ) }
0
Kotlin
0
0
62d2425e954e7b8701a1d8e5d582b07a4ee4832b
1,110
hammer-editor
MIT License
core/analytics/src/main/java/com/azuredragon/core/analytics/AppAnalytics.kt
bastionkid
536,519,741
false
null
package com.azuredragon.core.analytics import com.azuredragon.core.analytics.provider.AnalyticsAgent interface AppAnalytics { val analyticsAgents: MutableList<AnalyticsAgent> fun addAnalyticsProvider(analyticsAgent: AnalyticsAgent): Boolean fun removeAnalyticsProvider(analyticsAgent: AnalyticsAgent): Boolean fun setUserProperties(userId: String, properties: Map<String, Any?>) fun trackEvent(eventName: String, properties: Map<String, Any?>) fun onLogout() }
1
Kotlin
0
0
ca22bbdfc1c6e9263d33693f03e1e67d7cef2630
492
android-app-template
Apache License 2.0
app/src/main/java/com/zk/wanandroidtodo/ui/todo/AddTodoModel.kt
StephenZKCurry
147,613,070
false
null
package com.zk.wanandroidtodo.ui.todo import com.zk.wanandroidtodo.bean.DataResponse import com.zk.wanandroidtodo.manager.RetrofitManager import com.zk.wanandroidtodo.utils.RxSchedulers import io.reactivex.Observable /** * @description: 添加待办清单Model * @author: zhukai * @date: 2018/9/5 11:16 */ class AddTodoModel : AddTodoContract.IAddTodoModel { /** * 添加待办清单 */ override fun addTodo(title: String, content: String, date: String, type: Int): Observable<DataResponse<Any>> { return RetrofitManager.service.addTodo(title, content, date, type) .compose(RxSchedulers.applySchedulers()) } }
0
Kotlin
0
0
52e4cbbe9ed3f8e9340946911e3303b2272501ec
654
WanAndroidTodo_Kotlin
Apache License 2.0
data/src/main/java/com/depromeet/threedays/data/api/exception/ResultCall.kt
depromeet12th
548,194,728
false
{"Kotlin": 463798}
package com.depromeet.threedays.data.api.exception import com.depromeet.threedays.data.entity.base.ErrorResponse import com.depromeet.threedays.domain.exception.ThreeDaysException import okhttp3.Request import okio.Timeout import retrofit2.* import timber.log.Timber import java.io.IOException class ResultCall<T>(private val call: Call<T>, private val retrofit: Retrofit) : Call<Result<T>> { override fun enqueue(callback: Callback<Result<T>>) { call.enqueue(object : Callback<T> { override fun onResponse(call: Call<T>, response: Response<T>) { if (response.isSuccessful) { if(response.body() == null) { callback.onResponse( this@ResultCall, Response.success(Result.failure(ThreeDaysException(ThreeDaysException.NO_BODY_RESPONSE, HttpException(response)))) ) } else { callback.onResponse( this@ResultCall, Response.success(response.code(), Result.success(response.body()!!)) ) } } else { if(response.errorBody() == null) { callback.onResponse( this@ResultCall, Response.success(Result.failure(ThreeDaysException(ThreeDaysException.NO_ERROR_BODY_RESPONSE, HttpException(response)))) ) } else { val errorBody = retrofit.responseBodyConverter<ErrorResponse>( ErrorResponse::class.java, ErrorResponse::class.java.annotations ).convert(response.errorBody()!!) val message: String = errorBody?.message ?: ThreeDaysException.NO_ERROR_MESSAGE_RESPONSE callback.onResponse(this@ResultCall, Response.success(Result.failure(ThreeDaysException(message, HttpException(response)))) ) Timber.tag("ResultCall - onResponse").e("${ThreeDaysException(message, HttpException(response))}") } } } override fun onFailure(call: Call<T>, t: Throwable) { val message = when (t) { is IOException -> ThreeDaysException.INTERNET_CONNECTION_WAS_LOST is HttpException -> ThreeDaysException.UNKNOWN_EXCEPTION else -> t.localizedMessage } callback.onResponse( this@ResultCall, Response.success(Result.failure(ThreeDaysException(message, t))) ) Timber.tag("ResultCall - onFailure").e("${ThreeDaysException(message, t)}") } }) } override fun isExecuted(): Boolean { return call.isExecuted } override fun execute(): Response<Result<T>> { return Response.success(Result.success(call.execute().body()!!)) } override fun cancel() { call.cancel() } override fun isCanceled(): Boolean { return call.isCanceled } override fun clone(): Call<Result<T>> { return ResultCall(call.clone(), retrofit) } override fun request(): Request { return call.request() } override fun timeout(): Timeout { return call.timeout() } }
0
Kotlin
1
14
889015221d286c2679a42f5a0a0003c1a3ef350a
3,578
three-days-android
MIT License
mandrake-backend/src/main/kotlin/com/fernandocejas/mandrake/backend/core/flags/FeatureFlags.kt
android10
357,895,491
false
null
/** * Copyright (C) 2021 <NAME> 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 com.fernandocejas.mandrake.backend.core.flags import com.fernandocejas.mandrake.backend.core.config.* /** * Feature flags states (activated/deactivated) can be used as conditionals. * * ### Example: * * ```Flag.Conversations whenActivated { fn } otherwise { fn }``` */ class FeatureFlags(configuration: Configuration) { private val activatedFeatures: Set<Feature> = configuration.activatedFeatures private fun isFeatureEnabled(feature: Feature) = activatedFeatures.contains(feature) fun whenActivated(feature: Feature, fnFeatureEnabled: () -> Unit): Condition { val enabled = isFeatureEnabled(feature) if (enabled) fnFeatureEnabled.invoke(); return Condition(enabled) } inner class Condition(private val expression: Boolean) { infix fun otherwise(otherwise: () -> Unit) { if (!expression) otherwise.invoke() } } }
0
Kotlin
0
0
cee0f15878254c37adde90120343b47be92c90b7
1,517
mandrake
MIT License
app/src/main/java/com/mighty16/testapp/presentation/BasePresenter.kt
Mighty16
166,873,611
false
{"Kotlin": 37588}
package com.mighty16.testapp.presentation abstract class BasePresenter<V> { protected var view: V? = null protected val onViewAttachedActions = mutableListOf<(V) -> Unit>() fun attachView(view: V) { this.view = view if (onViewAttachedActions.isNotEmpty()) { onViewAttachedActions.forEach { it.invoke(view) } onViewAttachedActions.clear() } } fun detachView() { view = null } fun doWhenViewAttached(action: (V) -> Unit) { view?.let{ action(it) return } onViewAttachedActions.add(action) } abstract fun onViewReady() fun dispose() { } }
0
Kotlin
0
0
e3b6d45b12a05980a505ba49429e27161be4a6a1
695
Groupie-Test-App
MIT License
app/src/main/java/com/breezeshankar/features/login/model/productlistmodel/ProductListResponseModel.kt
DebashisINT
851,529,165
false
{"Kotlin": 15698684, "Java": 1025747}
package com.breezeshankar.features.login.model.productlistmodel import com.breezeshankar.app.domain.ProductListEntity import com.breezeshankar.base.BaseResponse /** * Created by Saikat on 20-11-2018. */ class ProductListResponseModel : BaseResponse() { //var product_list: ArrayList<ProductListDataModel>? = null var product_list: ArrayList<ProductListEntity>? = null }
0
Kotlin
0
0
d382b7af0064e3965a2a89789c42731687d911f5
381
SHANKARMG
Apache License 2.0
app/src/main/java/com/prasad/daggerbasic/MainApplication.kt
prasad091
272,716,745
false
null
package com.prasad.daggerbasic class MainApplication { }
0
Kotlin
0
0
d197da0946865f72c1f3a0ee0a5ee44928d322d7
57
Dagger2-Sample-with-Litho
Apache License 2.0
raionsnackbar/src/main/java/com/raion/raionsnackbar/RaionSneeze.kt
Raion-Community
456,448,205
false
{"Kotlin": 34720, "Java": 10649}
package com.raion.raionsnackbar import android.annotation.SuppressLint import android.graphics.Color import android.view.LayoutInflater import android.view.View import androidx.core.content.res.ResourcesCompat import com.bumptech.glide.Glide import com.google.android.material.snackbar.Snackbar import com.raion.raionsnackbar.databinding.SnackbarLayoutBinding /** * RaionSneeze * Copyright (c) 2021 all rights reserved. * Created by <NAME> as Head of Programmer Division Raion Community. * Contact me if you find any bugs or just want to collaborate in this project */ @SuppressLint("ShowToast") class RaionSneeze { companion object { /** * * Call this function to make a normal snackbar and customized it by yourself * * @param view to set view parent that snackbar would be placed * @param text to handle message that will shown from the snackbar * @param duration to control duration of your toast (LENGTH_LONG, LENGTH_SHORT, or LENGTH_INDEFINITE) */ @SuppressLint("UseCompatLoadingForDrawables") fun makeNormalSneeze( view: View, text: String = "", duration: Int = Snackbar.LENGTH_SHORT ): Snackbar { val snackBar = Snackbar.make(view, text, duration) snackBar.view.setBackgroundColor(Color.TRANSPARENT) val sneezeLayout = snackBar.view as Snackbar.SnackbarLayout val binding = buildSneeze(view) binding.apply { ivIcon.visibility = View.GONE tvMessage.text = text container.background = view.context.getDrawable(R.color.gray) sneezeLayout.addView(binding.root, -1, -1) } return snackBar } /** * * Call this function to show a normal snackbar * * @param view to set view parent that snackbar would be placed * @param text to handle message that will shown from the snackbar * @param duration to control duration of your toast (LENGTH_LONG, LENGTH_SHORT, or LENGTH_INDEFINITE) */ fun showNormalSneeze( view: View, text: String = "", duration: Int = Snackbar.LENGTH_SHORT ) = makeNormalSneeze(view, text, duration).show() /** * * Call this function to make an info snackbar and customized it by yourself * * @param view to set view parent that snackbar would be placed * @param text to handle message that will shown from the snackbar * @param duration to control duration of your toast (LENGTH_LONG, LENGTH_SHORT, or LENGTH_INDEFINITE) */ @SuppressLint("UseCompatLoadingForDrawables") fun makeInfoSneeze( view: View, text: String = "", duration: Int = Snackbar.LENGTH_SHORT ): Snackbar { val snackBar = Snackbar.make(view, text, duration) snackBar.view.setBackgroundColor(Color.TRANSPARENT) val sneezeLayout = snackBar.view as Snackbar.SnackbarLayout val binding = buildSneeze(view) binding.apply { Glide.with(view).load(R.drawable.ic_info).into(ivIcon) tvMessage.text = text container.background = view.context.getDrawable(R.color.blue) sneezeLayout.addView(binding.root, -1, -1) } return snackBar } /** * * Call this function to show a info snackbar * * @param view to set view parent that snackbar would be placed * @param text to handle message that will shown from the snackbar * @param duration to control duration of your toast (LENGTH_LONG, LENGTH_SHORT, or LENGTH_INDEFINITE) */ fun showInfoSneeze( view: View, text: String = "", duration: Int = Snackbar.LENGTH_SHORT ) = makeInfoSneeze(view, text, duration).show() /** * * Call this function to make an success snackbar and customized it by yourself * * @param view to set view parent that snackbar would be placed * @param text to handle message that will shown from the snackbar * @param duration to control duration of your toast (LENGTH_LONG, LENGTH_SHORT, or LENGTH_INDEFINITE) */ @SuppressLint("UseCompatLoadingForDrawables") fun makeSuccessSneeze( view: View, text: String = "", duration: Int = Snackbar.LENGTH_SHORT ): Snackbar { val snackBar = Snackbar.make(view, text, duration) snackBar.view.setBackgroundColor(Color.TRANSPARENT) val sneezeLayout = snackBar.view as Snackbar.SnackbarLayout val binding = buildSneeze(view) binding.apply { Glide.with(view).load(R.drawable.ic_success).into(ivIcon) tvMessage.text = text container.background = view.context.getDrawable(R.color.green) sneezeLayout.addView(binding.root) } return snackBar } /** * * Call this function to show a success snackbar * * @param view to set view parent that snackbar would be placed * @param text to handle message that will shown from the snackbar * @param duration to control duration of your toast (LENGTH_LONG, LENGTH_SHORT, or LENGTH_INDEFINITE) */ fun showSuccessSneeze( view: View, text: String = "", duration: Int = Snackbar.LENGTH_SHORT ) = makeSuccessSneeze(view, text, duration).show() /** * * Call this function to make an error snackbar and customized it by yourself * * @param view to set view parent that snackbar would be placed * @param text to handle message that will shown from the snackbar * @param duration to control duration of your toast (LENGTH_LONG, LENGTH_SHORT, or LENGTH_INDEFINITE) */ @SuppressLint("UseCompatLoadingForDrawables") fun makeErrorSneeze( view: View, text: String = "", duration: Int = Snackbar.LENGTH_SHORT ): Snackbar { val snackBar = Snackbar.make(view, text, duration) snackBar.view.setBackgroundColor(Color.TRANSPARENT) val sneezeLayout = snackBar.view as Snackbar.SnackbarLayout val binding = buildSneeze(view) binding.apply { Glide.with(view).load(R.drawable.ic_info).into(ivIcon) tvMessage.text = text container.background = view.context.getDrawable(R.color.red) sneezeLayout.addView(binding.root) } return snackBar } /** * * Call this function to show a error snackbar * * @param view to set view parent that snackbar would be placed * @param text to handle message that will shown from the snackbar * @param duration to control duration of your toast (LENGTH_LONG, LENGTH_SHORT, or LENGTH_INDEFINITE) */ fun showErrorSneeze( view: View, text: String = "", duration: Int = Snackbar.LENGTH_SHORT ) = makeErrorSneeze(view, text, duration).show() /** * * Call this function to make an warning snackbar and customized it by yourself * * @param view to set view parent that snackbar would be placed * @param text to handle message that will shown from the snackbar * @param duration to control duration of your toast (LENGTH_LONG, LENGTH_SHORT, or LENGTH_INDEFINITE) */ @SuppressLint("UseCompatLoadingForDrawables") fun makeWarningSneeze( view: View, text: String = "", duration: Int = Snackbar.LENGTH_SHORT ): Snackbar { val snackBar = Snackbar.make(view, text, duration) snackBar.view.setBackgroundColor(Color.TRANSPARENT) val sneezeLayout = snackBar.view as Snackbar.SnackbarLayout val binding = buildSneeze(view) binding.apply { Glide.with(view).load(R.drawable.ic_warning).into(ivIcon) tvMessage.text = text container.background = view.context.getDrawable(R.color.yellow) sneezeLayout.addView(binding.root) } return snackBar } /** * * Call this function to show a warning snackbar * * @param view to set view parent that snackbar would be placed * @param text to handle message that will shown from the snackbar * @param duration to control duration of your toast (LENGTH_LONG, LENGTH_SHORT, or LENGTH_INDEFINITE) */ fun showWarningSneeze( view: View, text: String = "", duration: Int = Snackbar.LENGTH_SHORT ) = makeErrorSneeze(view, text, duration).show() private fun buildSneeze(view: View) = SnackbarLayoutBinding.inflate(LayoutInflater.from(view.context)) } }
2
Kotlin
1
7
61514fd121115f71e58ceb61bbc66f3c5ed4f895
9,279
Raion-UI-Kit
MIT License
app/src/main/java/com/github/meudayhegde/esputils/ui/buttons/RemoteButton.kt
meudayhegde
179,924,023
false
{"Kotlin": 373055, "HTML": 689}
package com.github.meudayhegde.esputils.ui.buttons import android.content.Context import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.graphics.drawable.GradientDrawable import android.graphics.drawable.StateListDrawable import android.os.Build import android.util.AttributeSet import android.view.Gravity import android.view.View import android.view.ViewGroup import android.widget.* import androidx.core.content.ContextCompat import androidx.core.graphics.drawable.DrawableCompat import com.github.meudayhegde.esputils.ESPUtilsApp import com.github.meudayhegde.esputils.MainActivity import com.github.meudayhegde.esputils.holders.ButtonProperties import com.github.meudayhegde.esputils.listeners.OnRemoteButtonModificationListener import kotlin.math.min class RemoteButton : LinearLayout { private var properties: ButtonProperties? = null private val gd = GradientDrawable() private val gdPressed = GradientDrawable() private val stateDrawable = StateListDrawable() constructor(context: Context) : super(context) { visibility = View.GONE } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { visibility = View.GONE } constructor(context: Context, attrs: AttributeSet?, int: Int) : super(context, attrs, int) { visibility = View.GONE } private var icon: ImageView = ImageView(context) private var textView: TextView = TextView(context) var text: CharSequence? set(value) { textView.text = value textView.visibility = if (value.isNullOrEmpty()) View.GONE else View.VISIBLE } get() { return textView.text } init { orientation = HORIZONTAL gravity = Gravity.CENTER addView(icon) addView(textView) } fun initialize(properties: ButtonProperties?) { this.properties = properties if (properties == null) { visibility = View.GONE return } visibility = View.VISIBLE textView.setTextColor(Color.WHITE) setButtonProperties(properties) properties.setOnModificationListener(object : OnRemoteButtonModificationListener { override fun onTextColorChanged() { textView.setTextColor(properties.textColor) onIconModified() } override fun onTypeModified() { if (parent is RelativeLayout) setType( properties.iconType, RelativeLayout.CENTER_IN_PARENT ) else setType(properties.iconType) onIconModified() } override fun onIconModified() { setIcon(ESPUtilsApp.iconDrawableList[properties.icon]) } override fun onTextModified() { text = properties.text } override fun onColorModified() { setBackgroundColor(properties.color) } override fun onIrModified() {} override fun onPositionModified() {} }) } private fun setButtonProperties(btnProperties: ButtonProperties) { properties = btnProperties if (parent is RelativeLayout) setType( btnProperties.iconType, RelativeLayout.CENTER_IN_PARENT ) else setType(btnProperties.iconType) text = btnProperties.text textView.setTextSize( if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) Button.AUTO_SIZE_TEXT_TYPE_UNIFORM else 1, 12F ) gd.cornerRadius = 100F gd.orientation = GradientDrawable.Orientation.BOTTOM_TOP gdPressed.cornerRadius = 100F gdPressed.orientation = GradientDrawable.Orientation.BOTTOM_TOP setBackgroundColor(btnProperties.color) stateDrawable.addState(intArrayOf(android.R.attr.state_pressed), gdPressed) stateDrawable.addState(intArrayOf(), gd) background = stateDrawable textView.setTextColor(btnProperties.textColor) setIcon(ESPUtilsApp.iconDrawableList[btnProperties.icon]) } override fun setBackgroundColor(color: Int) { setButtonDrawableColor(gd, gdPressed, properties!!.color) } fun getProperties(): ButtonProperties { return properties!! } fun setIcon(resId: Int) { if (resId != ESPUtilsApp.iconDrawableList[0]) { var drawable = ContextCompat.getDrawable(context, resId) drawable = drawable?.mutate() DrawableCompat.setTint(drawable!!, properties!!.textColor) icon.setImageDrawable(drawable) orientation = if (properties!!.iconType == TYPE_RECT_HOR) HORIZONTAL else VERTICAL } else { icon.setImageDrawable(ColorDrawable(Color.TRANSPARENT)) } } fun setType(type: Int, vararg params: Int) { orientation = if (type == TYPE_RECT_HOR) HORIZONTAL else VERTICAL layoutParams = Class.forName(parent.javaClass.name).classes[0].getConstructor( Int::class.java, Int::class.java ).newInstance( when (type) { TYPE_RECT_HOR, TYPE_ROUND_MEDIUM -> BTN_WIDTH else -> MIN_HEIGHT }, when (type) { TYPE_RECT_HOR, TYPE_ROUND_MINI -> MIN_HEIGHT else -> BTN_WIDTH } ) as ViewGroup.LayoutParams? layoutParams.javaClass.getMethod( "setMargins", Int::class.java, Int::class.java, Int::class.java, Int::class.java ).invoke(layoutParams, 12, 12, 12, 12) params.forEach { layoutParams.javaClass.getMethod("addRule", Int::class.java).invoke(layoutParams, it) } } companion object { const val TYPE_ROUND_MINI = 0 const val TYPE_RECT_HOR = 1 const val TYPE_RECT_VER = 2 const val TYPE_ROUND_MEDIUM = 3 var BTN_WIDTH = 160 var MIN_HEIGHT = 80 fun onConfigChanged() { val x = min(MainActivity.layoutParams.width, MainActivity.layoutParams.height) val c = MainActivity.NUM_COLUMNS BTN_WIDTH = ((x / c) * (1 - (1 / (1.3 * c)))).toInt() MIN_HEIGHT = BTN_WIDTH / 2 } /** * Set Normal and Pressed gradient color from a single color int */ fun setButtonDrawableColor( drawableNormal: GradientDrawable, drawablePressed: GradientDrawable, colorInt: Int ) { val red = Color.red(colorInt) val green = Color.green(colorInt) val blue = Color.blue(colorInt) val newColorInt = Color.argb( 0xFF, when { red > 0x80 -> red - 0x30 else -> red + 0x30 }, when { green > 0x80 -> green - 0x30 else -> green + 0x30 }, when { blue > 0x80 -> blue - 0x30 else -> blue + 0x30 } ) drawableNormal.colors = intArrayOf(colorInt, newColorInt) drawableNormal.setStroke(8, newColorInt) val pressedColorInt = Color.argb( 0xFF, when { red > 0x80 -> red - 0x20 else -> red + 0x20 }, when { green > 0x80 -> green - 0x20 else -> green + 0x20 }, when { blue > 0x80 -> blue - 0x20 else -> blue + 0x20 } ) val pressedColorGradientInt = Color.argb( 0xFF, when { red > 0x80 -> red - 0x50 else -> red + 0x50 }, when { green > 0x80 -> green - 0x50 else -> green + 0x50 }, when { blue > 0x80 -> blue - 0x50 else -> blue + 0x50 } ) drawablePressed.colors = intArrayOf(pressedColorInt, pressedColorGradientInt) drawablePressed.setStroke(8, pressedColorGradientInt) } } }
0
Kotlin
0
0
64657bb214e6adc93d279dc08f6f6456932c6e69
8,234
ESPUtils_android
Apache License 2.0
app/src/main/java/com/flexcode/devspace/github/presentation/fragments/FollowersFragment.kt
Felix-Kariuki
533,876,693
false
null
package com.flexcode.devspace.github.presentation.fragments import android.content.SharedPreferences import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isGone import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import com.flexcode.devspace.core.utils.Constants import com.flexcode.devspace.core.utils.Resource import com.flexcode.devspace.databinding.FragmentFollowersBinding import com.flexcode.devspace.github.presentation.adapters.FollowersAdapter import com.flexcode.devspace.github.presentation.viewmodels.GetFollowersViewModel import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject import kotlinx.coroutines.flow.collectLatest @AndroidEntryPoint class FollowersFragment : Fragment() { private var _binding: FragmentFollowersBinding? = null private val binding get() = _binding!! private lateinit var followersAdapter: FollowersAdapter private val getFollowersViewModel: GetFollowersViewModel by viewModels() @Inject lateinit var sharedPref: SharedPreferences override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentFollowersBinding.inflate(inflater, container, false) followersAdapter = FollowersAdapter( FollowersAdapter.OnClickListener { /** * TODO: Navigate to details */ } ) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val username = sharedPref.getString(Constants.KEY_GITHUB_USERNAME, "empty") getFollowers(username!!) buttonsClickListener() } private fun buttonsClickListener() { binding.apply { followersBack.setOnClickListener { requireActivity().onBackPressed() } } } private fun getFollowers(username: String) { viewLifecycleOwner.lifecycleScope.launchWhenCreated { getFollowersViewModel.getFollowers(username).collectLatest { result -> when (result) { is Resource.Success -> { binding.animationView.isGone = true binding.reposRecyclerView.isVisible = true followersAdapter.submitList(result.data) binding.reposRecyclerView.adapter = followersAdapter } is Resource.Loading -> { binding.reposRecyclerView.isGone = true binding.animationView.isVisible = true } is Resource.Error -> { /** * Show Error */ binding.animationView.isGone = true } } } } } override fun onDestroy() { super.onDestroy() _binding = null } }
0
Kotlin
1
6
64fa5ef872adeb4c746accdbabe7cfd6c468cfc8
3,229
DevSpace
MIT License
app/src/main/java/com/gms/app/repo/StoredDataRepo.kt
YasserAdel564
406,843,475
false
{"Kotlin": 193933}
package com.gms.app.repo import androidx.lifecycle.LiveData import com.gms.app.data.storage.local.db.AppDao import com.gms.app.data.storage.remote.model.auth.CountryModel import com.gms.app.data.storage.remote.model.auth.GenderModel import com.gms.app.data.storage.remote.model.auth.NationalityModel import javax.inject.Inject class StoredDataRepo @Inject constructor( private val db: AppDao ) { //Fetch fun getStoredGenders(): LiveData<List<GenderModel>> { return db.getStoredLiveGenders() } fun getStoredCountries(): LiveData<List<CountryModel>> { return db.getStoredLiveCountries() } fun getStoredNationalities(): LiveData<List<NationalityModel>> { return db.getStoredLiveNationalities() } //Delete fun clearDB() { db.clearGenders() db.clearCountries() db.clearNationalities() } }
0
Kotlin
0
0
96d69372c3d70597395641c6529d48e0830f4770
880
GMS
MIT License
app/src/main/java/de/mr_pine/xkcdfeed/Login.kt
Mr-Pine
411,434,831
false
null
package de.mr_pine.xkcdfeed import android.util.Log import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import com.google.firebase.auth.AuthCredential import com.google.firebase.auth.FirebaseUser import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase private const val TAG = "Login" data class LoadingState private constructor(val status: Status, val msg: String? = null) { companion object { val IDLE = LoadingState(Status.IDLE) val LOADING = LoadingState(Status.RUNNING) val LOGGED_IN = LoadingState(Status.LOGGED_IN) fun error(msg: String?) = LoadingState(Status.FAILED, msg) } enum class Status { RUNNING, FAILED, IDLE, LOGGED_IN } } class LoginViewModel : ViewModel() { private val auth = Firebase.auth var user: FirebaseUser? by mutableStateOf(auth.currentUser) var loadingState by mutableStateOf(LoadingState.IDLE) val mutableSignedIn = mutableStateOf(false) var signedIn by mutableSignedIn init { if (user != null) { loadingState = LoadingState.LOGGED_IN signedIn = true } } fun signInWithCredential(credential: AuthCredential, onFinished: () -> Unit = {}) { loadingState = LoadingState.LOADING val authResult = auth.signInWithCredential(credential) authResult.addOnSuccessListener { loadingState = LoadingState.LOGGED_IN mutableSignedIn.value = true Log.d(TAG, "signInWithCredential: Finished!") onFinished() }.addOnFailureListener { loadingState = LoadingState.error(it.localizedMessage) } } fun signOut(onFinished: () -> Unit) { auth.signOut() loadingState = LoadingState.IDLE mutableSignedIn.value = false onFinished() } }
1
Kotlin
1
1
6324bd1d6c688f0fb2162c27429b29c1563d8f99
1,980
XKCDFeed
Apache License 2.0
ok-phonesell-pa-transport-mp/src/commonMain/kotlin/ru/otus/otuskotlin/phonesell/pa/transport/models/common/ResponseStatusDto.kt
otuskotlin
327,228,590
false
null
package ru.otus.otuskotlin.phonesell.pa.transport.models.common import kotlinx.serialization.Serializable @Serializable enum class ResponseStatusDto { SUCCESS, BAD_REQUEST, INTERNAL_SERVER_ERROR, NOT_FOUND, }
0
Kotlin
0
0
c4e5b9a30aaba73c5d6c28bb8c6ebab578c8950b
227
otuskotlin-202012-phonesell-pa
MIT License
app/src/main/java/com/mudassir/moviesapp/di/module/DataModule.kt
mookyjan
313,948,503
false
null
package com.mudassir.moviesapp.di.module import com.mudassir.data.gateway.MovieDetailGateWayImpl import com.mudassir.data.gateway.MovieListGateWayImpl import com.mudassir.data.remote.GetMovieListRemoteDataSource import com.mudassir.data.remote.api.MovieService import com.mudassir.data.repository.MovieListRepository import com.mudassir.domain.gateway.MovieDetailGateWay import com.mudassir.domain.gateway.MovieListGateWay import dagger.Module import dagger.Provides @Module class DataModule { @Provides fun provideMovieListRemoteDataSource(movieService: MovieService) = GetMovieListRemoteDataSource(movieService) @Provides fun provideMovieRepository(movieRemoteDataSource: GetMovieListRemoteDataSource) = MovieListRepository(movieRemoteDataSource) @Provides fun provideMovieGateWay(movieListRepository: MovieListRepository): MovieListGateWay = MovieListGateWayImpl(movieListRepository) @Provides fun provideMovieDetailGateWay(movieListRepository: MovieListRepository): MovieDetailGateWay = MovieDetailGateWayImpl(movieListRepository) }
0
Kotlin
0
4
ebdc9848305a3cb2272e2ac8c396e0db223172ae
1,121
MoviesApp
Apache License 2.0
src/test/kotlin/eZmaxApi/models/CustomEzsignsignatureEzsignsignaturesAutomaticResponseTest.kt
eZmaxinc
271,950,932
false
{"Kotlin": 6909939}
/** * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. * */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package eZmaxApi.models import io.kotlintest.shouldBe import io.kotlintest.specs.ShouldSpec import eZmaxApi.models.CustomEzsignsignatureEzsignsignaturesAutomaticResponse import eZmaxApi.models.FieldEEzsignsignatureType class CustomEzsignsignatureEzsignsignaturesAutomaticResponseTest : ShouldSpec() { init { // uncomment below to create an instance of CustomEzsignsignatureEzsignsignaturesAutomaticResponse //val modelInstance = CustomEzsignsignatureEzsignsignaturesAutomaticResponse() // to test the property `pkiEzsignsignatureID` - The unique ID of the Ezsignsignature should("test pkiEzsignsignatureID") { // uncomment below to test the property //modelInstance.pkiEzsignsignatureID shouldBe ("TODO") } // to test the property `eEzsignsignatureType` should("test eEzsignsignatureType") { // uncomment below to test the property //modelInstance.eEzsignsignatureType shouldBe ("TODO") } // to test the property `iEzsignpagePagenumber` - The page number in the Ezsigndocument should("test iEzsignpagePagenumber") { // uncomment below to test the property //modelInstance.iEzsignpagePagenumber shouldBe ("TODO") } } }
0
Kotlin
0
0
961c97a9f13f3df7986ea7ba55052874183047ab
1,565
eZmax-SDK-kotlin
MIT License
compiler/fir/java/src/org/jetbrains/kotlin/fir/java/MutableJavaTypeParameterStack.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
/* * Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.fir.java import org.jetbrains.kotlin.fir.symbols.impl.FirTypeParameterSymbol import org.jetbrains.kotlin.load.java.structure.JavaTypeParameter class MutableJavaTypeParameterStack : JavaTypeParameterStack() { private val typeParameterMap = mutableMapOf<JavaTypeParameter, FirTypeParameterSymbol>() fun addParameter(javaTypeParameter: JavaTypeParameter, symbol: FirTypeParameterSymbol) { typeParameterMap[javaTypeParameter] = symbol } fun addStack(javaTypeParameterStack: MutableJavaTypeParameterStack) { typeParameterMap += javaTypeParameterStack.typeParameterMap } override operator fun get(javaTypeParameter: JavaTypeParameter): FirTypeParameterSymbol? { return typeParameterMap[javaTypeParameter] } override operator fun iterator(): Iterator<Map.Entry<JavaTypeParameter, FirTypeParameterSymbol>> { return typeParameterMap.iterator() } fun copy(): MutableJavaTypeParameterStack = MutableJavaTypeParameterStack().also { it.typeParameterMap += typeParameterMap } } abstract class JavaTypeParameterStack : Iterable<Map.Entry<JavaTypeParameter, FirTypeParameterSymbol>> { abstract operator fun get(javaTypeParameter: JavaTypeParameter): FirTypeParameterSymbol? companion object { val EMPTY: JavaTypeParameterStack = object : JavaTypeParameterStack() { override fun get(javaTypeParameter: JavaTypeParameter): FirTypeParameterSymbol? = null override fun iterator(): Iterator<Map.Entry<JavaTypeParameter, FirTypeParameterSymbol>> { return emptyMap<JavaTypeParameter, FirTypeParameterSymbol>().iterator() } } } }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
1,918
kotlin
Apache License 2.0
app/src/main/java/me/thanel/linecalendar/widget/configure/SpinnerAdapter.kt
Tunous
131,023,329
false
null
package me.thanel.linecalendar.widget.configure import android.content.Context import android.support.annotation.ArrayRes import android.support.annotation.StringRes import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.TextView import me.thanel.linecalendar.R class SpinnerAdapter( context: Context, @ArrayRes arrayResId: Int, @StringRes private val titleResId: Int ) : ArrayAdapter<CharSequence>( context, R.layout.spinner_item_with_title, android.R.id.text1, context.resources.getTextArray(arrayResId) ) { init { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) } override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View = super.getView(position, convertView, parent).apply { findViewById<TextView>(R.id.titleTextView).setText(titleResId) } }
0
Kotlin
0
0
8170b32daaa845961d42aabb125c2adef547d075
930
LineCalendar
Apache License 2.0
app/src/main/java/com/deveshmittal/chess/ui/chess/square/decoration/DefaultSquareBackground.kt
deveshmittal
724,714,952
false
{"Kotlin": 161684}
package com.deveshmittal.chess.ui.chess.square.decoration import com.deveshmittal.chess.ui.base.square_dark import com.deveshmittal.chess.ui.base.square_light object DefaultSquareBackground : SquareBackground( lightSquareColor = square_light, darkSquareColor = square_dark, )
0
Kotlin
0
0
7d9242e5626294748285e5ae34431b64d24c74dd
286
chess
Apache License 2.0
app/src/main/java/com/example/pokedex/data/remote/response/DreamWorld.kt
nicolaussatria
729,398,936
false
{"Kotlin": 36825}
package com.example.pokedex.data.remote.response data class DreamWorld( val front_default: String, val front_female: Any )
0
Kotlin
0
0
8f6ee7ca9d9c29d4976b374cc344fa8314d1b286
131
pokedex
Apache License 2.0
kotlin-electron/src/jsMain/generated/electron/utility/OpenDialogReturnValue.kt
JetBrains
93,250,841
false
{"Kotlin": 12159121, "JavaScript": 330528}
// Generated by Karakum - do not modify it manually! package electron.utility typealias OpenDialogReturnValue = electron.core.OpenDialogReturnValue
40
Kotlin
165
1,319
a8a1947d73e3ed26426f1e27b641bff427dfd6a0
152
kotlin-wrappers
Apache License 2.0
src/main/kotlin/wang/crick/keeper/client/GitlabClient.kt
chly1103
242,962,035
false
{"Kotlin": 29334, "Java": 15593, "TSQL": 3863, "Dockerfile": 444}
package wang.crick.keeper.client import com.alibaba.fastjson.JSON import com.alibaba.fastjson.JSONArray import com.alibaba.fastjson.JSONObject import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.toRequestBody import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Value import org.springframework.stereotype.Component import java.util.* const val MEDIA_TYPE_JSON = "application/json; charset=utf-8" const val TOKEN = "Private-Token" const val PAGE_SIZE = 100 @Component class GitlabClient { private val log: Logger = LoggerFactory.getLogger(this.javaClass) @Value("\${gitlab.token}") private lateinit var gitlabToken: String @Value("\${gitlab.api}") private lateinit var gitlabApi: String @Autowired private lateinit var okHttpClient: OkHttpClient fun getUser(userId: String): JSONObject { return JSONObject.parseObject(get("$gitlabApi/users/$userId")) } fun listProjectIssue(projectId: Int, params: String): List<JSONObject> { val list: ArrayList<JSONObject> = ArrayList() var page = 1 do { val item = JSONArray.parseArray(this.get("$gitlabApi/projects/$projectId/issues?per_page=100&page=$page$params"), JSONObject::class.java) list.addAll(item) page++ log.info("list project issue! page -> $page size -> ${list.size} item_size -> ${item.size}") } while (item.size == PAGE_SIZE) return list } fun listOpenProjectIssue(projectId: Int): List<JSONObject> { return listProjectIssue(projectId, "&state=opened") } fun listParticipants(projectId: Int, issueIid: Int): List<JSONObject> { return JSONArray.parseArray(get("$gitlabApi/projects/$projectId/issues/$issueIid/participants"), JSONObject::class.java) } fun getGroupByName(name: String): JSONObject { val response = get("$gitlabApi/groups?search=$name") return JSONArray.parseArray(response, JSONObject::class.java) .find { it.getString("name") == name }!! } fun getGroupDetailById(id: Int): JSONObject { val response = get("$gitlabApi/groups/$id") return JSON.parseObject(response) } fun listGroupProject(groupId: Int): List<JSONObject> { return JSONArray.parseArray(get("$gitlabApi/groups/$groupId/projects?per_page=100"), JSONObject::class.java) } fun listGroupIssue(groupId: Int): List<JSONObject> { val list: ArrayList<JSONObject> = ArrayList() var page = 1 do { val item = JSONArray.parseArray(get("$gitlabApi/groups/$groupId/issues?per_page=100&page=$page"), JSONObject::class.java) list.addAll(item) page++ log.info("listGroupIssue -> " + list.size + "item -> " + item.size) } while (item.size == 100) return list } fun editIssueLabels(projectId: Int, issueIid: Int, labels: String, close: Boolean) { var url = "$gitlabApi/projects/$projectId/issues/$issueIid?labels=$labels" if (close) { url = "$url&state_event=close" } this.put(url, "") } fun editAssignee(projectId: Int, issueIid: Int, authorId: Int) { this.put("$gitlabApi/projects/$projectId/issues/$issueIid?assignee_ids=$authorId", "") } private fun get(url: String): String { val request = Request.Builder() .url(url) .header(TOKEN, gitlabToken) .get() .build() return okHttpClient.newCall(request).execute().body!!.string() } private fun put(url: String, body: String): String { val request = Request.Builder() .url(url) .header(TOKEN, gitlabToken) .put(body.toRequestBody(MEDIA_TYPE_JSON.toMediaTypeOrNull())) .build() return okHttpClient.newCall(request).execute().body!!.string() } }
0
null
0
0
1127751be333f8f6b8698b1db4fc15845005bafe
4,122
keeper
MIT License
app/src/main/java/com/app/slidingup/ui/events/viewmodel/EventsViewModel.kt
yash786agg
220,455,628
false
null
package com.app.slidingup.ui.events.viewmodel import com.app.slidingup.api.NetworkState import com.app.slidingup.base.BaseViewModel import com.app.slidingup.extensions.NonNullMediatorLiveData import com.app.slidingup.model.events.EventsApiResponse import com.app.slidingup.repository.events.EventsUseCase import kotlinx.coroutines.launch class EventsViewModel(private val eventsUseCase : EventsUseCase) : BaseViewModel() { // FOR DATA -- fun getEvents() : NonNullMediatorLiveData<NetworkState<EventsApiResponse>> { val events = NonNullMediatorLiveData<NetworkState<EventsApiResponse>>() ioScope.launch { eventsUseCase.executeQuery(events) } return events } }
0
Kotlin
0
8
5f7c313f87b838983cbb002734fbb29282fd43da
699
SlidingBottomSheet
Apache License 2.0
src/main/java/net/ccbluex/liquidbounce/features/module/modules/combat/BowAimbot.kt
Rmejia39
733,988,804
false
{"Kotlin": 2304965, "Java": 1271227, "GLSL": 13515, "JavaScript": 8926}
/* * FDPClient Hacked Client * A free open source mixin-based injection hacked client for Minecraft using Minecraft Forge by LiquidBounce. * https://github.com/SkidderMC/FDPClient/ */ package net.ccbluex.liquidbounce.features.module.modules.combat import net.ccbluex.liquidbounce.event.EventTarget import net.ccbluex.liquidbounce.event.Render3DEvent import net.ccbluex.liquidbounce.event.UpdateEvent import net.ccbluex.liquidbounce.features.module.Module import net.ccbluex.liquidbounce.features.module.ModuleCategory import net.ccbluex.liquidbounce.features.module.ModuleInfo import net.ccbluex.liquidbounce.utils.EntityUtils import net.ccbluex.liquidbounce.utils.RotationUtils import net.ccbluex.liquidbounce.utils.render.RenderUtils import net.ccbluex.liquidbounce.features.value.BoolValue import net.ccbluex.liquidbounce.features.value.FloatValue import net.ccbluex.liquidbounce.features.value.ListValue import net.minecraft.entity.Entity import net.minecraft.entity.EntityLivingBase import net.minecraft.item.ItemBow import java.awt.Color @ModuleInfo(name = "BowAimbot", category = ModuleCategory.COMBAT) object BowAimbot : Module() { private val silentValue = BoolValue("Silent", true) private val predictValue = BoolValue("Predict", true) private val throughWallsValue = BoolValue("ThroughWalls", false) private val predictSizeValue = FloatValue("PredictSize", 2F, 0.1F, 5F).displayable { predictValue.get() } private val priorityValue = ListValue("Priority", arrayOf("Health", "Distance", "Direction"), "Direction") private val markValue = BoolValue("Mark", true) private var target: Entity? = null override fun onDisable() { target = null } @EventTarget fun onUpdate(event: UpdateEvent) { target = null if (mc.thePlayer.itemInUse?.item is ItemBow) { val entity = getTarget(throughWallsValue.get(), priorityValue.get()) ?: return target = entity RotationUtils.faceBow(target, silentValue.get(), predictValue.get(), predictSizeValue.get()) } } @EventTarget fun onRender3D(event: Render3DEvent) { if (target != null && !priorityValue.equals("Multi") && markValue.get()) { RenderUtils.drawPlatform(target, Color(37, 126, 255, 70)) } } private fun getTarget(throughWalls: Boolean, priorityMode: String): Entity? { val targets = mc.theWorld.loadedEntityList.filter { it is EntityLivingBase && EntityUtils.isSelected(it, true) && (throughWalls || mc.thePlayer.canEntityBeSeen(it)) } return when (priorityMode.uppercase()) { "DISTANCE" -> targets.minByOrNull { mc.thePlayer.getDistanceToEntity(it) } "DIRECTION" -> targets.minByOrNull { RotationUtils.getRotationDifference(it) } "HEALTH" -> targets.minByOrNull { (it as EntityLivingBase).health } else -> null } } fun hasTarget() = target != null && mc.thePlayer.canEntityBeSeen(target) }
3
Kotlin
0
0
b48c4e83c888568111a6665037db7fd3f7813ed3
3,035
FDPClient
MIT License
src/main/kotlin/ttt/drift/Drift.kt
turnthetide
175,595,257
false
null
package ttt.drift import io.quarkus.runtime.StartupEvent import io.vertx.core.Vertx import mu.KotlinLogging import javax.enterprise.event.Observes import javax.inject.Inject class Drift { val logger = KotlinLogging.logger { } @Inject lateinit var vertx: Vertx fun onStart(@Observes event: StartupEvent) { vertx.deployVerticle(MatchesVerticle()) vertx.deployVerticle(WebVerticle()) } }
0
Kotlin
0
3
b612b86dedb42c400ec2e60c9643bc24e08bb561
427
drift
MIT License
encrpytion/src/main/java/social/androiddev/firefly/encryption/DeviceKeyBundle.kt
digitalbuddha
599,627,508
false
{"Kotlin": 545804, "Nix": 3254, "Java": 978}
package social.androiddev.firefly.encryption import org.whispersystems.libsignal.IdentityKeyPair import org.whispersystems.libsignal.SignalProtocolAddress import org.whispersystems.libsignal.state.PreKeyRecord import org.whispersystems.libsignal.state.SignedPreKeyRecord data class DeviceKeyBundle( val registrationId: Int, val address: SignalProtocolAddress, val identityKeyPair: IdentityKeyPair, val preKeys: List<PreKeyRecord>, val signedPreKey: SignedPreKeyRecord )
4
Kotlin
5
31
dbfb0d20aa074260384b3c9c8cc083cb32ca50c2
491
Firefly
Apache License 2.0
shared/data/recipes_search/src/commonMain/kotlin/com/iwanickimarcel/recipes_search/RecipesSearchHistoryDatabaseDriverFactory.kt
MarcelIwanicki
712,987,885
false
{"Kotlin": 376361, "Swift": 342}
package com.iwanickimarcel.recipes_search import app.cash.sqldelight.db.SqlDriver expect class RecipesSearchHistoryDatabaseDriverFactory { fun create(): SqlDriver }
0
Kotlin
0
1
0d9676a542ba3d9b8b2bdf366aefadf298e6da81
170
freat
The Unlicense
app/src/main/java/dev/mayank/cowinvaccinebook/component/HiltBroadcastReceiver.kt
hackelite01
370,006,949
false
null
package dev.mayank.cowinvaccinebook.component import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import androidx.annotation.CallSuper abstract class HiltBroadcastReceiver : BroadcastReceiver() { @CallSuper override fun onReceive(context: Context?, intent: Intent?) { // Do Nothing } }
0
Kotlin
0
3
36cdad2997c2f62a7ddf1ffa20ec2b35c65b0e73
347
cowin-vaccine-booking
MIT License
support-navigation/src/main/java/android/support/navigation/Navigator.kt
quangpv
448,463,537
false
null
package android.support.navigation import android.os.Bundle import androidx.annotation.CallSuper import androidx.annotation.IdRes import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.lifecycle import androidx.fragment.app.savedStateRegistry import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.LifecycleOwner import androidx.savedstate.SavedStateRegistry import java.util.* import kotlin.reflect.KClass abstract class Navigator( protected val fragmentManager: FragmentManager, @IdRes val container: Int, ) { companion object { private const val KEY_SAVED_STATE = "com:support:core:navigation:navigator" } abstract val lastDestination: Destination? private val mTransactionManager = TransactionManager() private var mExecutable: Boolean = true private var mDestinationChangeListeners = arrayListOf<OnDestinationChangeListener>() private val mTagManager = FragmentTagManager() protected val tagManager get() = mTagManager protected val Destination.requireFragment: Fragment get() = fragment ?: error("Not found requireFragment $tag") protected val Destination.fragment: Fragment? get() = fragmentManager.findFragmentByTag(tag) // Fix for case "Can not perform this action after onSaveInstanceState" private val mObserver = object : LifecycleEventObserver { private var mSavedStateRegistry: SavedStateRegistry? = null override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) { when (event) { Lifecycle.Event.ON_CREATE -> { mSavedStateRegistry = fragmentManager.savedStateRegistry registerSavedState(mSavedStateRegistry!!) } Lifecycle.Event.ON_DESTROY -> { source.lifecycle.removeObserver(this) mSavedStateRegistry?.unregisterSavedStateProvider(KEY_SAVED_STATE) mDestinationChangeListeners.clear() mSavedStateRegistry = null } Lifecycle.Event.ON_START -> { if (!mExecutable) { mExecutable = true mTransactionManager.executeIfNeeded() } } else -> { } } } } private val mSavedStateListener = SavedStateRegistry.SavedStateProvider { Bundle().also(::onSaveInstance) } init { fragmentManager.lifecycle.addObserver(mObserver) } private fun registerSavedState(registry: SavedStateRegistry) { with(registry) { unregisterSavedStateProvider(KEY_SAVED_STATE) registerSavedStateProvider( KEY_SAVED_STATE, mSavedStateListener ) if (isRestored) { val savedInstance = consumeRestoredStateForKey(KEY_SAVED_STATE) if (savedInstance != null) onRestoreInstance(savedInstance) } } } protected open fun notifyDestinationChange(kClass: KClass<out Fragment>) { mDestinationChangeListeners.forEach { it.onDestinationChanged(kClass) } } fun addDestinationChangeListener(function: OnDestinationChangeListener) { if (mDestinationChangeListeners.contains(function)) return mDestinationChangeListeners.add(function) } fun removeDestinationChangeListener(function: OnDestinationChangeListener) { mDestinationChangeListeners.remove(function) } abstract fun navigate( kClass: KClass<out Fragment>, args: Bundle? = null, navOptions: NavOptions? = null, ) abstract fun navigateUp(result: Bundle? = null, ignoreBackable: Boolean = false): Boolean open fun popBackStack(popupTo: KClass<out Fragment>, inclusive: Boolean): Boolean { throw UnsupportedOperationException("Not support, please use FragmentNavigator version 2") } @CallSuper protected open fun onSaveInstance(state: Bundle) { mExecutable = false mTagManager.saveState(state) } protected open fun onRestoreInstance(saved: Bundle) { mTagManager.restoreState(saved) } protected fun transaction(function: SupportFragmentTransaction. () -> Unit) { mTransactionManager.push(Transaction(function)) } private inner class TransactionManager { private val mTransactions = ArrayDeque<Transaction>() private val isEmpty get() = mTransactions.isEmpty() private val next get() = mTransactions.takeIf { it.isNotEmpty() }?.peekFirst() fun push(transaction: Transaction) = synchronized(this) { transaction.onFinishListener = { mTransactions.pop() next?.execute() } val shouldExecute = isEmpty && mExecutable mTransactions.add(transaction) if (shouldExecute) transaction.execute() } fun executeIfNeeded() { if (mTransactions.isEmpty()) return mTransactions.first.execute() } } private inner class Transaction(private val function: SupportFragmentTransaction.() -> Unit) { var onFinishListener: (() -> Unit)? = null fun execute() { fragmentManager.beginTransaction().also { val tran = SupportFragmentTransactionImpl(it) tran.function() it.runOnCommit { onFinishListener?.invoke() } it.commit() } } } }
0
Kotlin
0
0
12927aee44fa546ea5d105737292f71c262e94e9
5,682
android-support
MIT License
app/src/main/java/com/example/premierepage/model/Image.kt
abderrahmen-Baccouch
468,118,218
false
{"Kotlin": 288746}
package com.example.premierepage.model data class Image( val _id: String, val name: String )
1
Kotlin
1
0
c2ceee994ee947004bca4717fa899ed68aa370cf
101
LifeBalance
MIT License
app/src/main/java/com/ahmed/bankapp/ui/user/UsersActivity.kt
AhmedZaki918
672,480,872
false
{"Kotlin": 88107}
package com.ahmed.bankapp.ui.user import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.ahmed.bankapp.R import com.ahmed.bankapp.data.BankUser import com.ahmed.bankapp.databinding.ActivityUsersBinding import com.ahmed.bankapp.ui.adapter.UsersAdapter import com.ahmed.bankapp.util.drawScreenHeader import com.ahmed.bankapp.util.installSplash class UsersActivity : AppCompatActivity() { private lateinit var binding: ActivityUsersBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) installSplash() binding = ActivityUsersBinding.inflate(layoutInflater) setContentView(binding.root) binding.apply { header.drawScreenHeader( "${getString(R.string.users)} (${BankUser.displayUsers().size})", this@UsersActivity ) rvUsers.adapter = UsersAdapter(BankUser.displayUsers()) } } }
0
Kotlin
0
0
531a0d4e84c81228f53d2d89f0863b22f374df42
976
Bank-App
Open LDAP Public License v2.2.1
app/src/main/java/com/tinf18ai2/vorlesungsplan/services/LecturePlanFetchService.kt
TINF18AI2
221,454,743
false
null
package com.tinf18ai2.vorlesungsplan.services import com.tinf18ai2.vorlesungsplan.models.Vorlesungswoche import io.reactivex.Single interface LecturePlanFetchService { /** * Fetches the selected week (by offset) from the remote server and returns a * <code>Single</code> object, which will be notified when the update is available. */ fun fetch(weekOffset: Int): Single<Vorlesungswoche> }
13
Kotlin
0
5
e65e5dc5cdce87c00a8d62bddfc7e1098a7ff3ae
415
Vorlesungsplan
MIT License
core/src/main/kotlin/me/konyaco/pixivlib/exception/PixivException.kt
Konyaco
231,805,095
false
{"Kotlin": 19563}
package me.konyaco.pixivlib.exception class PixivException : Exception { constructor() : super() constructor(message: String) : super(message) constructor(message: String, cause: Throwable) : super(message, cause) }
0
Kotlin
0
0
a1e8a6a7f83ec4f81fe1c12d0e0356c62dd6d0ff
228
PixivUtil
Apache License 2.0
src/main/kotlin/org/lm/psi/LmFile.kt
mchernyavsky
112,193,727
false
null
package org.lm.psi import com.intellij.extapi.psi.PsiFileBase import com.intellij.openapi.fileTypes.FileType import com.intellij.psi.FileViewProvider import com.intellij.psi.PsiElement import org.lm.LmFileType import org.lm.LmLanguage import org.lm.psi.ext.LmNamedElement import org.lm.psi.stubs.LmFileStub import org.lm.resolve.* class LmFile(viewProvider: FileViewProvider) : PsiFileBase(viewProvider, LmLanguage), LmNamedElement { val nameWithoutSuffix: String = name.removeSuffix('.' + LmFileType.defaultExtension) override fun setName(name: String): PsiElement { val nameWithExtension = if (name.endsWith('.' + LmFileType.defaultExtension)) { name } else { "$name.${LmFileType.defaultExtension}" } return super.setName(nameWithExtension) } override fun getStub(): LmFileStub? = super.getStub() as? LmFileStub override fun getReference(): LmReference? = null override fun getFileType(): FileType = LmFileType override fun toString(): String = "LM File" override fun getNameIdentifier(): PsiElement? = null }
0
Kotlin
0
0
a09526cec7d16ef34cd526f7069c6de0b669a56d
1,108
intellij-lm
MIT License
examples/rabbitmq-springboot/src/main/kotlin/io/kevs/rabbitmq/springboot/example/subscribers/DoSomethingOnTestEventSubscriber.kt
MikiLoz92
502,142,453
false
null
package io.kevs.rabbitmq.springboot.example.subscribers import io.kevs.rabbitmq.springboot.example.event.TestEvent import io.kevs.station.rabbitmq.annotation.ConsumerCount import io.kevs.station.rabbitmq.annotation.SubscribeTo import io.kevs.station.rabbitmq.annotation.spring.WithChannelProvider import io.kevs.station.rabbitmq.annotation.spring.WithCoroutineScopeProvider import io.kevs.station.rabbitmq.subscriber.EventSubscriber import org.springframework.stereotype.Component @Component @WithChannelProvider("channelProvider") @WithCoroutineScopeProvider("coroutineScopeProvider") @SubscribeTo(TestEvent::class) @ConsumerCount(16) class DoSomethingOnTestEventSubscriber : EventSubscriber<TestEvent> { override suspend fun invoke(event: TestEvent) { //println("Event ${event.someData} executing on thread ${Thread.currentThread().name}") } }
0
Kotlin
0
0
861b0e117c6af98311983d6623882534ff32cebd
864
kevs
MIT License
src/main/kotlin/net/inherency/finances/external/google/TabName.kt
scottygaydos
278,980,273
false
null
package net.inherency.finances.external.google enum class TabName { ACCOUNTS, BILLS, BUDGET_CATEGORIES, BUDGET_CATEGORY_RULES, BUDGET_TEMPLATE, BUDGETS, CATEGORIZED_TRANSACTIONS, MINT_TRANSACTIONS, RECONCILED_TRANSACTIONS }
0
Kotlin
0
0
39072865fc3dd032a9584abefc3d8b68765cf6ad
260
finance_budget_and_reconciler
Apache License 2.0
platform/remote-driver/test-sdk/src/com/intellij/driver/sdk/ui/components/BookmarksGridUi.kt
SamB
215,873,627
false
{"Text": 9365, "INI": 518, "YAML": 419, "Ant Build System": 11, "Batchfile": 34, "Dockerfile": 9, "Shell": 633, "Markdown": 740, "Ignore List": 143, "Git Revision List": 1, "Git Attributes": 11, "EditorConfig": 256, "XML": 7809, "SVG": 4411, "Kotlin": 58041, "Java": 83545, "HTML": 3781, "Java Properties": 215, "Gradle": 449, "Maven POM": 95, "JavaScript": 228, "CSS": 79, "JSON": 1472, "JFlex": 33, "Makefile": 5, "Diff": 137, "XSLT": 113, "Gradle Kotlin DSL": 676, "Groovy": 3156, "desktop": 1, "JAR Manifest": 17, "PHP": 47, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 13, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 26, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 72, "GraphQL": 125, "Nginx": 1, "HAProxy": 1, "OpenStep Property List": 48, "Python": 17005, "C": 110, "C++": 42, "Protocol Buffer": 3, "fish": 2, "PowerShell": 3, "Go": 36, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "HCL": 4, "Elixir": 2, "Ruby": 4, "XML Property List": 84, "E-mail": 18, "Roff": 283, "Roff Manpage": 40, "Swift": 3, "TOML": 192, "Checksums": 49, "Java Server Pages": 11, "Vue": 1, "Dotenv": 1, "reStructuredText": 67, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 17, "Handlebars": 1, "Rust": 16, "Go Checksums": 1, "Go Module": 1, "NSIS": 8, "PlantUML": 6, "SCSS": 2, "Thrift": 3, "Cython": 13, "Regular Expression": 3, "JSON5": 4, "OASv3-json": 3, "OASv3-yaml": 1}
package com.intellij.driver.sdk.ui.components import com.intellij.driver.sdk.ui.Finder import org.intellij.lang.annotations.Language fun Finder.bookmarksMnemonicGrid(@Language("xpath") xpath: String? = null) = x(xpath ?: "//div[@class='MyContentPanel'][//div[@class='BookmarkLayoutGrid']]", BookmarksGridLayoutUiComponent::class.java) class BookmarksGridLayoutUiComponent(data: ComponentData) : UiComponent(data) { val textField get() = x("//div[@class='JBTextField']") private fun findButton(text: String) = x("//div[@class='JButton' and @text='$text']", JButtonUIComponent::class.java) fun clickButton(text: String) = findButton(text).click() fun doubleClickButton(text: String) = findButton(text).doubleClick() private class JButtonUIComponent(data: ComponentData) : UiComponent(data) }
1
null
1
1
37c7118b1a4fb7f21c1a2636355c91f2a7d9ba05
813
intellij-community
Apache License 2.0
app/src/main/java/eu/kanade/presentation/browse/components/SourceSettingsButton.kt
komikku-app
743,200,516
false
{"Kotlin": 5951497}
package eu.kanade.presentation.browse.components import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Settings import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import cafe.adriel.voyager.navigator.LocalNavigator import cafe.adriel.voyager.navigator.currentOrThrow import eu.kanade.domain.source.model.installedExtension import eu.kanade.tachiyomi.ui.browse.extension.details.ExtensionDetailsScreen import exh.source.EH_SOURCE_ID import exh.source.EXH_SOURCE_ID import tachiyomi.domain.source.model.Source import tachiyomi.i18n.MR import tachiyomi.presentation.core.i18n.stringResource import tachiyomi.source.local.LocalSource @Composable fun SourceSettingsButton( id: Long, @Suppress("UNUSED_PARAMETER") modifier: Modifier = Modifier, ) { // Create a fake source val source = Source(id, "", "", supportsLatest = false, isStub = false) SourceSettingsButton(source = source) } @Composable fun SourceSettingsButton( source: Source, @Suppress("UNUSED_PARAMETER") modifier: Modifier = Modifier, ) { // Avoid E-Hentai & ExHentai which is built-in & not actually installed extensions if (source.id == LocalSource.ID || source.id == EH_SOURCE_ID || source.id == EXH_SOURCE_ID) return val navigator = LocalNavigator.currentOrThrow IconButton(onClick = { if (source.installedExtension !== null) { navigator.push(ExtensionDetailsScreen(source.installedExtension!!.pkgName)) } }) { Icon( imageVector = Icons.Outlined.Settings, contentDescription = stringResource(MR.strings.label_settings), ) } }
93
Kotlin
14
504
bc460dd3b1edf67d095df0b15c6d1dc39444d5e6
1,764
komikku
Apache License 2.0
app/src/main/java/eu/kanade/presentation/browse/components/SourceSettingsButton.kt
komikku-app
743,200,516
false
{"Kotlin": 5951497}
package eu.kanade.presentation.browse.components import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Settings import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import cafe.adriel.voyager.navigator.LocalNavigator import cafe.adriel.voyager.navigator.currentOrThrow import eu.kanade.domain.source.model.installedExtension import eu.kanade.tachiyomi.ui.browse.extension.details.ExtensionDetailsScreen import exh.source.EH_SOURCE_ID import exh.source.EXH_SOURCE_ID import tachiyomi.domain.source.model.Source import tachiyomi.i18n.MR import tachiyomi.presentation.core.i18n.stringResource import tachiyomi.source.local.LocalSource @Composable fun SourceSettingsButton( id: Long, @Suppress("UNUSED_PARAMETER") modifier: Modifier = Modifier, ) { // Create a fake source val source = Source(id, "", "", supportsLatest = false, isStub = false) SourceSettingsButton(source = source) } @Composable fun SourceSettingsButton( source: Source, @Suppress("UNUSED_PARAMETER") modifier: Modifier = Modifier, ) { // Avoid E-Hentai & ExHentai which is built-in & not actually installed extensions if (source.id == LocalSource.ID || source.id == EH_SOURCE_ID || source.id == EXH_SOURCE_ID) return val navigator = LocalNavigator.currentOrThrow IconButton(onClick = { if (source.installedExtension !== null) { navigator.push(ExtensionDetailsScreen(source.installedExtension!!.pkgName)) } }) { Icon( imageVector = Icons.Outlined.Settings, contentDescription = stringResource(MR.strings.label_settings), ) } }
93
Kotlin
14
504
bc460dd3b1edf67d095df0b15c6d1dc39444d5e6
1,764
komikku
Apache License 2.0
buildlogic/src/main/kotlin/com/tidal/sdk/SdkModules.kt
tidal-music
806,866,286
false
{"Kotlin": 1775374, "Shell": 9881, "Python": 7380, "Mustache": 911}
package com.tidal.sdk import org.gradle.api.Project val Project.sdkModules get() = rootProject.subprojects.filter { it.parent === rootProject }
27
Kotlin
0
23
1f654552133ef7794fe9bb7677bc7fc94c713aa3
150
tidal-sdk-android
Apache License 2.0
shared/src/main/java/viach/apps/shared/repository/DefaultClipboardRepository.kt
viacheslav-chugunov
691,548,132
false
{"Kotlin": 170000}
package viach.apps.shared.repository import android.content.ClipData import android.content.ClipboardManager import android.content.Context internal class DefaultClipboardRepository( private val context: Context ) : ClipboardRepository { override fun copy(text: String) { val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val clip = ClipData.newPlainText("SecurePal", text) clipboard.setPrimaryClip(clip) } }
0
Kotlin
0
0
9d18715cb96941e9665e3dad8bcba510da58905c
484
SecurePal-Android
MIT License
kotlin-js-helpers/src/jsMain/kotlin/me/underlow/help/RBuilderHelpers.kt
underlow
217,339,192
false
null
@file:Suppress("unused") package me.underlow.help import kotlinext.js.jsObject import react.Component import react.Props import react.RBuilder /** * Helper function to support simplified syntax: * * fun RBuilder.googleLogout(block: GoogleLogoutProps.() -> Unit) = buildWithProperties(block) * * and then instead * * GoogleLogin{ * attrs{ * clientId = "your client id" * } * } * * write * * googleLogout{ * clientId = "your client id" * } * */ inline fun < T : Props, reified C : Component<T, *>> RBuilder.buildWithProperties( crossinline builder: T.() -> Unit) = child(C::class) { this.attrs { builder.invoke(this) } }
0
Kotlin
0
0
d370a281f2d36dc549d273d1aa9091004ecbc63a
704
kjs-wrappers
MIT License
services/say-goodbye/src/main/kotlin/com/ebay/wenliu2/dubbo/services/SayGoodByeApp.kt
wenliu2
214,076,207
false
null
package com.ebay.wenliu2.dubbo.services import org.apache.dubbo.config.spring.context.annotation.EnableDubbo import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication import java.util.concurrent.CountDownLatch @EnableDubbo @SpringBootApplication open class SayGoodByeApp { companion object { @JvmStatic fun main(args: Array<String>) { SpringApplication.run(SayGoodByeApp::class.java, *args) val countDown = CountDownLatch(1) countDown.await() } } }
0
Kotlin
0
0
3b68a28f9dc2bb06aa2a17c2a70303de97008309
578
dubbo-gradle-multi-proj
Apache License 2.0
sample/src/main/java/com/paulrybitskyi/hiltbinder/sample/deps/ViewDeps.kt
cheeky-pundit
340,510,784
true
{"Kotlin": 115693, "Java": 21855, "Shell": 537}
/* * Copyright 2021 <NAME>, <EMAIL> * * 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.paulrybitskyi.hiltbinder.sample.deps import com.paulrybitskyi.hiltbinder.BindType import dagger.hilt.android.WithFragmentBindings import dagger.hilt.android.scopes.ViewScoped import javax.inject.Inject internal interface ViewDep1 internal interface ViewDep2 internal interface ViewDep3 internal interface ViewDep4 @BindType(installIn = BindType.Component.VIEW) internal class ViewDep1Impl @Inject constructor(): ViewDep1 @ViewScoped @BindType internal class ViewDep2Impl @Inject constructor(): ViewDep2 @BindType(installIn = BindType.Component.VIEW_WITH_FRAGMENT) internal class ViewDep3Impl @Inject constructor(): ViewDep3 @ViewScoped @WithFragmentBindings @BindType internal class ViewDep4Impl @Inject constructor(): ViewDep4
0
null
0
0
bf23d37115a2f69877af334cfbce60ef0372f443
1,347
hilt-binder
Apache License 2.0
statistics/src/main/java/com/duckduckgo/app/statistics/api/OfflinePixelSender.kt
hojat72elect
822,396,044
false
{"Kotlin": 11627106, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784}
package com.duckduckgo.app.statistics.api import com.duckduckgo.di.DaggerSet import io.reactivex.Completable import io.reactivex.Completable.* /** * Most pixels are "send and forget" however we sometimes need to guarantee that a pixel will be * sent. In those cases we schedule them to happen as part of our app data sync. */ class OfflinePixelSender constructor( private val offlinePixels: DaggerSet<OfflinePixel>, ) { fun sendOfflinePixels(): Completable { return mergeDelayError( listOf(*offlinePixels.map { it.send() }.toTypedArray()), ) } }
0
Kotlin
0
0
54351d039b85138a85cbfc7fc3bd5bc53637559f
594
DuckDuckGo
Apache License 2.0
jtransc-utils/src/com/jtransc/lang/cloneable.kt
jtransc
51,313,992
false
null
package com.jtransc.lang /* fun <T : Cloneable> T.tclone(): T { return this.clone() as T } */
59
Java
66
619
6f9a2166f128c2ce5fb66f9af46fdbdbcbbe4ba4
96
jtransc
Apache License 2.0
apollo-runtime-kotlin/src/commonMain/kotlin/com/apollographql/apollo/internal/RealApolloCall.kt
scorebet
270,762,877
true
{"Java": 1939749, "Kotlin": 1441013, "ANTLR": 3786, "Shell": 291}
package com.apollographql.apollo.internal import com.apollographql.apollo.ApolloMutationCall import com.apollographql.apollo.ApolloQueryCall import com.apollographql.apollo.interceptor.ApolloRequest import com.apollographql.apollo.api.ApolloExperimental import com.apollographql.apollo.api.ExecutionContext import com.apollographql.apollo.api.Operation import com.apollographql.apollo.api.Response import com.apollographql.apollo.api.ScalarTypeAdapters import com.apollographql.apollo.interceptor.RealInterceptorChain import com.apollographql.apollo.interceptor.ApolloRequestInterceptor import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flow @ApolloExperimental @ExperimentalCoroutinesApi class RealApolloCall<T> constructor( private val operation: Operation<*, T, *>, private val scalarTypeAdapters: ScalarTypeAdapters, private val interceptors: List<ApolloRequestInterceptor>, private val executionContext: ExecutionContext ) : ApolloQueryCall<T>, ApolloMutationCall<T> { override fun execute(): Flow<Response<T>> { val request = ApolloRequest( operation = operation, scalarTypeAdapters = scalarTypeAdapters, executionContext = executionContext ) return flow { emit(RealInterceptorChain(interceptors)) }.flatMapLatest { interceptorChain -> interceptorChain.proceed(request) } } }
5
null
1
1
1ec73e535c7f5293b9bc269cbe1008d0dd03440b
1,475
apollo-android
MIT License
carsharing-app/app/src/main/java/com/syndicate/carsharing/database/models/Rate.kt
Prodix
702,147,988
false
{"Kotlin": 472081, "C#": 67271, "TypeScript": 30924, "HTML": 10194, "CSS": 6310, "Java": 1110}
package com.syndicate.carsharing.database.models import com.fasterxml.jackson.annotation.JsonProperty data class Rate ( @JsonProperty("Id") val id: Int = 0, @JsonProperty("TransportId") val transportId: Int = 0, @JsonProperty("RateName") val rateName: String = "", @JsonProperty("OnRoadPrice") val onRoadPrice: Double = 0.0, @JsonProperty("ParkingPrice") val parkingPrice: Double = 0.0 )
7
Kotlin
0
1
3d8ec90f3e6c58dea15d5fc0f5fe888536842ab3
409
carsharing-information-system
MIT License
bilibili-api/src/main/kotlin/com/github/wumo/bilibili/api/Cache.kt
wumo
271,946,803
false
null
package com.github.wumo.bilibili.api import com.github.wumo.bilibili.model.Folder import com.github.wumo.bilibili.model.MediaResource import java.util.concurrent.ConcurrentHashMap typealias fetchMediasFuncType = suspend (folder: Folder, page: Int, tid: Int, order: Int) -> List<MediaResource> object Cache { val cacheFavMedias = ConcurrentHashMap<CachedMediasKey, List<MediaResource>>() val cachedMedias = ConcurrentHashMap<String, MediaResource>() }
0
Kotlin
0
0
7e60ee17bc464ca98d6150117d8311ac7c824021
457
bilibili-desktop
MIT License
crystal-map-connector/src/main/kotlin/ch/ergon/dope/extension/type/stringfunction/InitCap.kt
ergon
745,483,606
false
{"Kotlin": 1886765}
package ch.ergon.dope.extension.type.stringfunction import ch.ergon.dope.resolvable.expression.unaliased.type.function.stringfunction.initCap import ch.ergon.dope.resolvable.expression.unaliased.type.function.stringfunction.title import ch.ergon.dope.toDopeType import com.schwarz.crystalapi.schema.CMJsonField fun initCap(inStr: CMJsonField<String>) = initCap(inStr.toDopeType()) fun title(inStr: CMJsonField<String>) = title(inStr.toDopeType())
2
Kotlin
0
6
40b18241d25c360080768902fc108ea70bb2f211
450
dope-query-builder
MIT License
core/src/main/java/com/seewo/brick/params/CornerRadius.kt
robin8yeung
591,142,442
false
{"Kotlin": 517624, "Java": 4201}
package com.seewo.brick.params class CornerRadius private constructor( val leftTop: Float, val rightTop: Float, val rightBottom: Float, val leftBottom: Float, ) { val toArray: FloatArray get() = floatArrayOf( leftTop, leftTop, rightTop, rightTop, rightBottom, rightBottom, leftBottom, leftBottom, ) companion object { @JvmStatic fun only( leftTop: Int = 0, rightTop: Int = 0, rightBottom: Int = 0, leftBottom: Int = 0, ): CornerRadius = CornerRadius( leftTop.toFloat(), rightTop.toFloat(), rightBottom.toFloat(), leftBottom.toFloat()) @JvmStatic fun zero() = only() @JvmStatic fun all(radius: Int) = only(radius, radius, radius, radius) } }
0
Kotlin
4
75
7f8873e8a5cde58bcde3771880fc6b489bfcd4a5
828
BrickUI
Apache License 2.0
src/main/kotlin/software/amazon/smithy/intellij/SmithySpellcheckingStrategy.kt
iancaffey
455,381,865
false
{"Kotlin": 286598, "Lex": 5063, "Smithy": 2929}
package software.amazon.smithy.intellij import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiComment import com.intellij.psi.PsiDocCommentBase import com.intellij.psi.PsiElement import com.intellij.psi.PsiNameIdentifierOwner import com.intellij.spellchecker.inspections.CommentSplitter import com.intellij.spellchecker.inspections.PlainTextSplitter import com.intellij.spellchecker.inspections.Splitter import com.intellij.spellchecker.tokenizer.PsiIdentifierOwnerTokenizer import com.intellij.spellchecker.tokenizer.SpellcheckingStrategy import com.intellij.spellchecker.tokenizer.TokenConsumer import com.intellij.spellchecker.tokenizer.Tokenizer import software.amazon.smithy.intellij.psi.SmithyString import software.amazon.smithy.intellij.psi.SmithyTextBlock /** * A [SpellcheckingStrategy] for [Smithy](https://awslabs.github.io/smithy) IDL model files. * * @author <NAME> * @since 1.0 */ class SmithySpellcheckingStrategy : SpellcheckingStrategy() { override fun getTokenizer(element: PsiElement): Tokenizer<out PsiElement> = when (element) { is PsiComment -> CommentTokenizer is PsiNameIdentifierOwner -> PsiIdentifierOwnerTokenizer() is SmithyString -> StringTokenizer is SmithyTextBlock -> TextBlockTokenizer else -> EMPTY_TOKENIZER } } abstract class SimpleTokenizer<T : PsiElement> : Tokenizer<T>() { abstract val splitter: Splitter abstract fun textRange(t: T): TextRange override fun tokenize(t: T, consumer: TokenConsumer) { consumer.consumeToken(t, t.text, false, 0, textRange(t), splitter) } } object CommentTokenizer : SimpleTokenizer<PsiComment>() { override val splitter = CommentSplitter.getInstance() override fun textRange(comment: PsiComment) = TextRange.create(if (comment is PsiDocCommentBase) 3 else 2, comment.textLength) } object StringTokenizer : SimpleTokenizer<SmithyString>() { override val splitter = PlainTextSplitter.getInstance() override fun textRange(string: SmithyString) = TextRange.create(1, string.textLength - 1) } object TextBlockTokenizer : SimpleTokenizer<SmithyTextBlock>() { override val splitter = PlainTextSplitter.getInstance() override fun textRange(text: SmithyTextBlock) = TextRange.create(3, text.textLength - 3) }
2
Kotlin
2
24
286adf8f042e9ebeeb28bbd99aa3ac320ed95f23
2,303
smithy-intellij-plugin
MIT License
data/src/main/kotlin/team/applemango/runnerbe/data/runningitem/model/runningitem/information/RunningItemInformationData.kt
ricky-buzzni
485,390,072
false
{"Kotlin": 615137}
/* * RunnerBe © 2022 Team AppleMango. all rights reserved. * RunnerBe license is under the MIT. * * [Result.kt] created by <NAME> on 22. 2. 24. 오후 10:24 * * Please see: https://github.com/applemango-runnerbe/RunnerBe-Android/blob/main/LICENSE. */ package team.applemango.runnerbe.data.runningitem.model.runningitem.information import com.fasterxml.jackson.annotation.JsonProperty import team.applemango.runnerbe.data.runningitem.model.runner.RunnerData import team.applemango.runnerbe.data.runningitem.model.runningitem.RunningItemData data class RunningItemInformationData( @field:JsonProperty("postingInfo") val postingInfo: List<RunningItemData?>? = null, @field:JsonProperty("runnerInfo") val runnerInfo: List<RunnerData?>? = null, @field:JsonProperty("waitingRunnerInfo") val waitingRunnerInfo: List<RunnerData?>? = null, )
0
null
0
0
f48fb298c07732a9c32afcff0bddb16f9fe2e37a
865
RunnerBe-Android
MIT License
data/src/main/kotlin/team/applemango/runnerbe/data/runningitem/model/runningitem/information/RunningItemInformationData.kt
ricky-buzzni
485,390,072
false
{"Kotlin": 615137}
/* * RunnerBe © 2022 Team AppleMango. all rights reserved. * RunnerBe license is under the MIT. * * [Result.kt] created by <NAME> on 22. 2. 24. 오후 10:24 * * Please see: https://github.com/applemango-runnerbe/RunnerBe-Android/blob/main/LICENSE. */ package team.applemango.runnerbe.data.runningitem.model.runningitem.information import com.fasterxml.jackson.annotation.JsonProperty import team.applemango.runnerbe.data.runningitem.model.runner.RunnerData import team.applemango.runnerbe.data.runningitem.model.runningitem.RunningItemData data class RunningItemInformationData( @field:JsonProperty("postingInfo") val postingInfo: List<RunningItemData?>? = null, @field:JsonProperty("runnerInfo") val runnerInfo: List<RunnerData?>? = null, @field:JsonProperty("waitingRunnerInfo") val waitingRunnerInfo: List<RunnerData?>? = null, )
0
null
0
0
f48fb298c07732a9c32afcff0bddb16f9fe2e37a
865
RunnerBe-Android
MIT License
app/src/main/java/com/example/energytimer/FirstFragment.kt
angelh32
387,980,891
false
null
package com.example.energytimer 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 androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.RecyclerView import com.example.energytimer.adapters.TimerItemAdapter import com.example.energytimer.database.CustomTimer import com.example.energytimer.databinding.FragmentFirstBinding import com.example.energytimer.fragment.EditTimerFragment import com.example.energytimer.fragment.SharedData import com.example.energytimer.fragment.ShowTimerFragment import com.example.energytimer.tools.CustomAlarm import com.example.energytimer.tools.CustomNotification import com.example.energytimer.tools.Help class FirstFragment : Fragment() { private var _binding: FragmentFirstBinding? = null private val binding get() = _binding!! private var currentList: List<CustomTimer> = listOf() private lateinit var recyclerView: RecyclerView private lateinit var timerAdapter: TimerItemAdapter private val model: SharedData by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentFirstBinding.inflate(inflater, container, false) timerAdapter = TimerItemAdapter { timer -> adapterOnClick(timer) } timerAdapter.submitList(currentList) recyclerView = binding.recyclerViewTimers recyclerView.adapter = timerAdapter model.buildDatabase(requireContext()) recyclerView.addItemDecoration( DividerItemDecoration( this.context, DividerItemDecoration.VERTICAL ) ) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { model.timerList.observe(viewLifecycleOwner, { list -> timerAdapter.submitList(list) }) model.refreshTimers() model.refreshTypes() binding.createTimer.setOnClickListener { val newFragment = EditTimerFragment() model.selectTimer(Help.createEmptyTimer()) newFragment.show(parentFragmentManager, "NEW_TIMER") } val alarm = CustomAlarm(requireContext()) alarm.setAlarm() super.onViewCreated(view, savedInstanceState) } override fun onDestroyView() { super.onDestroyView() _binding = null } private fun adapterOnClick(customTimer: CustomTimer) { model.selectTimer(customTimer) model.selectById(customTimer.typeId) ShowTimerFragment().show(parentFragmentManager, "TIMER") } }
0
Kotlin
0
0
0d6039067f9d021322d4c441627afaca393f7086
2,524
game-energy-notifier
MIT License
ui/src/main/java/com/m3u/ui/Player.kt
realOxy
592,741,804
false
{"Kotlin": 542903}
package com.m3u.ui import android.view.ViewGroup import androidx.annotation.OptIn import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.tween import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.Immutable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.viewinterop.AndroidView import androidx.media3.common.Player import androidx.media3.common.util.UnstableApi import androidx.media3.ui.AspectRatioFrameLayout import androidx.media3.ui.PlayerView import com.m3u.core.annotation.ClipMode import com.m3u.material.ktx.ifUnspecified import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlin.time.Duration.Companion.milliseconds @Immutable data class PlayerState( val player: Player?, val url: String, @ClipMode val clipMode: Int, val keepScreenOn: Boolean, val onInstallMedia: (String) -> Unit, val onUninstallMedia: () -> Unit ) @Composable fun rememberPlayerState( player: Player?, url: String, onInstallMedia: (String) -> Unit, @ClipMode clipMode: Int = ClipMode.ADAPTIVE, keepScreenOn: Boolean = true, onUninstallMedia: () -> Unit, ): PlayerState { val currentOnInstallMedia by rememberUpdatedState(onInstallMedia) val currentOnUninstallMedia by rememberUpdatedState(onUninstallMedia) return remember( player, url, clipMode, keepScreenOn, currentOnInstallMedia, currentOnUninstallMedia ) { PlayerState( player, url, clipMode, keepScreenOn, currentOnInstallMedia, currentOnUninstallMedia ) } } @OptIn(UnstableApi::class) @Composable fun Player( state: PlayerState, modifier: Modifier = Modifier, startColor: Color = Color.Unspecified, ) { val player = state.player val url = state.url val keepScreenOn = state.keepScreenOn val clipMode = state.clipMode var actualColor by remember(startColor) { mutableStateOf(startColor) } val currentShutterColor by animateColorAsState( targetValue = actualColor.ifUnspecified { Color.Black }, label = "player-shutter-color", animationSpec = tween(durationMillis = 800, delayMillis = 400) ) LaunchedEffect(startColor) { actualColor = Color.Black } AndroidView( factory = { context -> PlayerView(context).apply { useController = false layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) setShutterBackgroundColor(currentShutterColor.toArgb()) } }, modifier = modifier ) { view -> view.apply { setShutterBackgroundColor(currentShutterColor.toArgb()) setPlayer(player) setKeepScreenOn(keepScreenOn) resizeMode = when (clipMode) { ClipMode.ADAPTIVE -> AspectRatioFrameLayout.RESIZE_MODE_FIT ClipMode.CLIP -> AspectRatioFrameLayout.RESIZE_MODE_ZOOM ClipMode.STRETCHED -> AspectRatioFrameLayout.RESIZE_MODE_FILL else -> AspectRatioFrameLayout.RESIZE_MODE_FIT } } } val scope = rememberCoroutineScope() DisposableEffect(player, url) { scope.launch { delay(150.milliseconds) state.onInstallMedia(url) } onDispose { state.onUninstallMedia() } } }
2
Kotlin
6
53
770c425822d63e43652e8ca2ce85f917f61ee8e4
4,063
M3UAndroid
Apache License 2.0
src/com/github/felipehjcosta/adapters/infrastructure/RemoteCharactersRepository.kt
felipehjcosta
163,593,322
false
null
package com.github.felipehjcosta.adapters.infrastructure import com.github.felipehjcosta.domain.CharactersRepository import com.github.felipehjcosta.domain.MarvelCharacter import com.tripl3dogdare.havenjson.Json import io.ktor.client.HttpClient import io.ktor.client.engine.apache.Apache import io.ktor.client.request.get import io.ktor.client.request.url import java.time.Instant class RemoteCharactersRepository( private val baseUrl: String, private val publicApiKey: String, private val privateApiKey: String ) : CharactersRepository { override suspend fun fetchCharacters(): List<MarvelCharacter> { val timestamp = Instant.now().toEpochMilli() val hash = generateHash(timestamp, publicApiKey, privateApiKey) val client = HttpClient(Apache) val url = "$baseUrl/v1/public/characters" + "?offset=0" + "&limit=10" + "&apikey=$publicApiKey" + "&ts=$timestamp" + "&hash=$hash" val response = client.get<String> { url(url) } client.close() return Json.parse(response).run { this["data"]["results"].asList?.map { MarvelCharacter(it["id"].asInt!!.toLong(), it["name"].asString!!, it["description"].asString!!) } } ?: emptyList() } private fun generateHash(timestamp: Long, publicApiKey: String, privateApiKey: String): String { return "$timestamp$privateApiKey$publicApiKey".toMD5() } }
0
Kotlin
0
0
3b4aaf4dd8639090e60d00d5261a41ec37c2f762
1,509
marvelql
MIT License
app/src/main/java/ru/vladroid/notes/utils/SwipeToDeleteCallback.kt
Shmuser
245,204,453
false
null
package ru.vladroid.notes.utils import android.graphics.Canvas import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import kotlin.math.abs abstract class SwipeToDeleteCallback : ItemTouchHelper.Callback() { override fun onChildDraw( c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean ) { val itemView = viewHolder.itemView if (abs(dX) >= 2 * Double.MIN_VALUE || isCurrentlyActive) itemView.alpha = (itemView.width + dX) / itemView.width else itemView.alpha = 1.0f super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive) } override fun getMovementFlags( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder ): Int { return makeMovementFlags( ItemTouchHelper.ACTION_STATE_IDLE, ItemTouchHelper.LEFT ) .or( makeMovementFlags( ItemTouchHelper.ACTION_STATE_SWIPE, ItemTouchHelper.LEFT ) ) } override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { return false } }
0
Kotlin
0
0
7ba5f87851caf78deb0e4618d6c7548160f9327f
1,455
Notes
MIT License
base/base-chat/src/main/java/qsos/base/chat/view/holder/LocationViewHolder.kt
puyunfeng
210,260,355
false
{"Kotlin": 506821, "HTML": 4334}
package qsos.base.chat.view.holder import android.annotation.SuppressLint import android.view.View import kotlinx.android.synthetic.main.chat_item_location.view.* import qsos.lib.base.data.chat.MsgEntity /** * @author : 华清松 * @description : 聊天列表项-位置 */ @SuppressLint("SetTextI18n") class LocationViewHolder(itemView: View) : AbsChatViewHolder(itemView) { override fun setChildView(data: MsgEntity, position: Int) { child2View?.chat_item_location_name_tv?.text = data.data.location?.name child2View?.setOnClickListener { v -> onClick(v) } } }
0
null
0
0
e6001d57db67e368777fda200dbd4f15290e4667
594
abcl
Apache License 2.0
app/src/main/java/com/dlogan/android/tvmaze/ui/ShowAdapter.kt
davelogan
191,637,515
false
null
/* * Copyright (C) 2017 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 com.dlogan.android.tvmaze.ui import android.view.ViewGroup import androidx.paging.PagedListAdapter import androidx.recyclerview.widget.DiffUtil import com.dlogan.android.tvmaze.data.epg.ScheduledShow /** * A simple PagedListAdapter that binds schedule items into CardViews. * <p> * PagedListAdapter is a RecyclerView.Adapter base class which can present the content of PagedLists * in a RecyclerView. It requests new pages as the user scrolls, and handles new PagedLists by * computing all_shows differences on a background thread, and dispatching minimal, efficient updates to * the RecyclerView to ensure minimal UI thread work. * <p> * If you want to use your own Adapter base class, try using a PagedListAdapterHelper inside your * adapter instead. * * @see android.arch.paging.PagedListAdapter * @see android.arch.paging.AsyncPagedListDiffer */ class ShowAdapter: PagedListAdapter<ScheduledShow, ShowViewHolder>(diffCallback) { override fun onBindViewHolder(holder: ShowViewHolder, position: Int) { holder.bindTo(getItem(position)) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ShowViewHolder { return ShowViewHolder.create(parent) } companion object { private val diffCallback = object : DiffUtil.ItemCallback<ScheduledShow>() { override fun areItemsTheSame(oldItem: ScheduledShow, newItem: ScheduledShow): Boolean = oldItem.id == newItem.id /** * Note that in kotlin, == checking on data classes compares all contents, but in Java, * typically you'll implement Object#equals, and use it to compare object contents. */ override fun areContentsTheSame(oldItem: ScheduledShow, newItem: ScheduledShow): Boolean = oldItem == newItem } } }
0
Kotlin
0
0
fd74bd0e3838f8b9e3e50c7da4b3d8637b70042e
2,485
TVMaze
Apache License 2.0
backend-side/src/main/kotlin/com/kemana/backend/model/Direction.kt
utsmannn
218,322,735
false
null
package com.kemana.backend.model import com.fasterxml.jackson.annotation.JsonProperty data class DirectionOrigin( @JsonProperty("code") val code: String?, @JsonProperty("routes") val routes: List<Route?>?, @JsonProperty("uuid") val uuid: String?, @JsonProperty("waypoints") val waypoints: List<Waypoint?>? ) data class Route( @JsonProperty("distance") val distance: Double?, @JsonProperty("duration") val duration: Double?, @JsonProperty("geometry") val geometry: String?, @JsonProperty("legs") val legs: List<Leg?>?, @JsonProperty("weight") val weight: Double?, @JsonProperty("weight_name") val weightName: String? ) data class Leg( @JsonProperty("distance") val distance: Double?, @JsonProperty("duration") val duration: Double?, @JsonProperty("steps") val steps: List<Any?>?, @JsonProperty("summary") val summary: String?, @JsonProperty("weight") val weight: Double? ) data class Waypoint( @JsonProperty("distance") val distance: Double?, @JsonProperty("location") val location: List<Double?>?, @JsonProperty("name") val name: String? ) data class ResponsesDirection( val distance: Double?, val geometry: String? )
0
Kotlin
75
209
4d12af9242d95bfe28242a5e27ecf2bb65b68179
1,396
Kemana
Apache License 2.0
movie-tv-detail/detail-data/src/main/java/com/prmto/data/remote/mapper/credit/CreditDtoMapper.kt
tolgaprm
541,709,201
false
{"Kotlin": 540597}
package com.prmto.data.remote.mapper.credit import com.prmto.data.remote.dto.credit.CreditDto import com.prmto.domain.models.credit.Credit fun CreditDto.toCredit(): Credit { return Credit( cast = cast?.toCast().orEmpty(), crew = crew?.toCrew().orEmpty() ) }
0
Kotlin
4
85
d9365e5339cb5daa231a8fe77c7376ab828d289b
283
Mova-MovieApp
Apache License 2.0
src/main/kotlin/domain/graphs/Graphs.kt
alexaldev
424,953,645
false
{"Kotlin": 12995}
package domain.graphs import domain.TrianglesCounter import domain.TrianglesCounterAlgorithm import java.util.concurrent.ConcurrentHashMap import java.util.stream.Stream abstract class Graph { abstract fun generateMetrics(): List<GraphMetrics> abstract fun addEdge(sourceV: Int, destinationV: Int) abstract fun removeEdge(v: Int, u: Int): Boolean abstract fun neighbours(v: Int): Set<Int> abstract fun isEdge(v1: Int, v2: Int): Boolean abstract fun vertices(): Stream<Int> abstract fun degree(v: Int): Int abstract fun backedDataStructureDescription(): String enum class Type { ADJ_MAP, ADJ_MATRIX } } sealed class GraphMetrics(val name: String, val value: Double) { data class NumOfVertices(val count: Int) : GraphMetrics("|V|", count.toDouble()) data class NumOfEdges(val count: Int) : GraphMetrics("|E|", count.toDouble()) data class NumOfTotalTriangles(val count: Int) : GraphMetrics("Total count of triangles", count.toDouble()) } // ---------- Implementations ----------------- class GraphWithAdjMatrix(private val numOfVertices: Int) : Graph() { private val matrix = MutableList(numOfVertices) { MutableList(numOfVertices) {0} } private val verticesCount: Int by lazy { numOfVertices } private val edgesCount: Int by lazy { matrix.sumOf { row -> row.count { it == 1 } } } override fun generateMetrics(): List<GraphMetrics> { return listOf( GraphMetrics.NumOfVertices(verticesCount), GraphMetrics.NumOfEdges(edgesCount) ) } override fun addEdge(sourceV: Int, destinationV: Int) { matrix[sourceV][destinationV] = 1 } override fun backedDataStructureDescription(): String { TODO("Not yet implemented") } override fun removeEdge(v: Int, u: Int): Boolean { val edgeExists = (matrix[v][u] == 1) return if (edgeExists) { matrix[v][u] = 0 true } else { false } } override fun neighbours(v: Int): Set<Int> { TODO("Not yet implemented.") } override fun isEdge(v1: Int, v2: Int): Boolean { TODO("Not yet implemented") } override fun vertices(): Stream<Int> { TODO("Not yet implemented") } override fun degree(v: Int): Int { TODO("Not yet implemented") } } class GraphWithMap(trianglesCounter: TrianglesCounter = TrianglesCounter(TrianglesCounterAlgorithm.Naive)) : Graph() { private val adjacencyMap: HashMap<Int, HashSet<Int>> = HashMap() private val verticesCount: Int by lazy { adjacencyMap.size } private val edgesCount: Int by lazy { adjacencyMap .values .fold(0) { acc, hashSet -> acc + hashSet.size } / 2 } override fun addEdge(sourceV: Int, destinationV: Int) { adjacencyMap .computeIfAbsent(sourceV) { HashSet() } .add(destinationV) adjacencyMap .computeIfAbsent(destinationV) { HashSet() } .add(sourceV) } override fun toString(): String = StringBuffer().apply { for (key in adjacencyMap.keys) { append("$key -> ") append(adjacencyMap[key]?.joinToString(", ", "[", "]\n")) } }.toString() override fun generateMetrics(): List<GraphMetrics> { return listOf( GraphMetrics.NumOfVertices(verticesCount), GraphMetrics.NumOfEdges(edgesCount) ) } override fun backedDataStructureDescription() = """ |This graph is represented by an adjacency hashmap. |It keeps in-memory a hashmap with this structure: |[V] -> [neighbour1, neighnour2,...] |... |... """.trimMargin() override fun removeEdge(v: Int, u: Int) = adjacencyMap[v]?.remove(u) ?: false override fun neighbours(v: Int): Set<Int> = adjacencyMap[v] ?: emptySet() override fun isEdge(v1: Int, v2: Int): Boolean { TODO("Not yet implemented") } override fun vertices(): Stream<Int> { return adjacencyMap.keys.stream() } override fun degree(v: Int): Int { TODO("Not yet implemented") } }
0
Kotlin
0
0
f0dfaca21728493bd2a99cd9048e6f3f9e596f63
4,201
GraphTriangleDetection
Apache License 2.0
modules/fx/arrow-fx/src/test/kotlin/arrow/fx/FiberTest.kt
yairkukielka
226,488,406
true
{"Kotlin": 2653729, "CSS": 152663, "JavaScript": 67900, "HTML": 23177, "Scala": 8150, "Java": 4465, "Shell": 3043, "Ruby": 1598}
package arrow.fx import arrow.core.extensions.monoid import arrow.fx.extensions.applicative import arrow.fx.extensions.io.applicative.unit import arrow.fx.extensions.io.concurrent.concurrent import arrow.fx.extensions.monoid import arrow.fx.typeclasses.Fiber import arrow.fx.typeclasses.FiberOf import arrow.fx.typeclasses.FiberPartialOf import arrow.fx.typeclasses.fix import arrow.test.UnitSpec import arrow.test.laws.ApplicativeLaws import arrow.test.laws.MonoidLaws import arrow.typeclasses.Eq import io.kotlintest.properties.Gen class FiberTest : UnitSpec() { init { fun FIBER_EQ(): Eq<FiberOf<ForIO, Int>> = object : Eq<FiberOf<ForIO, Int>> { override fun FiberOf<ForIO, Int>.eqv(b: FiberOf<ForIO, Int>): Boolean = EQ<Int>().run { fix().join().eqv(b.fix().join()) } } testLaws( ApplicativeLaws.laws<FiberPartialOf<ForIO>>(Fiber.applicative(IO.concurrent()), FIBER_EQ()), MonoidLaws.laws(Fiber.monoid(IO.concurrent(), Int.monoid()), Gen.int().map { i -> Fiber(IO.just(i), IO.unit) }, FIBER_EQ()) ) } }
0
null
0
0
5d4e714dddcba3ff02a65f3d2425f6c5412ebd0d
1,077
arrow
Apache License 2.0