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
app/src/main/java/com/stellarcontainersfsm/features/alarm/model/VisitReportResponseModel.kt
DebashisINT
756,252,499
false
{"Kotlin": 14218175, "Java": 1004755}
package com.stellarcontainersfsm.features.alarm.model import com.stellarcontainersfsm.base.BaseResponse /** * Created by Saikat on 21-02-2019. */ class VisitReportResponseModel : BaseResponse() { var visit_report_list: ArrayList<VisitReportDataModel>? = null }
0
Kotlin
0
0
afb97c29d93fc5bd8668cd16d2525947ad51b8a5
268
StellarContainersFSM
Apache License 2.0
epic-calendar-compose/src/commonMain/kotlin/epicarchitect/calendar/compose/basis/BasisEpicCalendar.kt
epicarchitect
628,392,697
false
null
package epicarchitect.calendar.compose.basis import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.text.style.TextAlign import epicarchitect.calendar.compose.basis.config.LocalBasisEpicCalendarConfig import epicarchitect.calendar.compose.basis.state.BasisEpicCalendarState import epicarchitect.calendar.compose.basis.state.LocalBasisEpicCalendarState import epicarchitect.calendar.compose.basis.state.rememberBasisEpicCalendarState import kotlinx.datetime.DayOfWeek import kotlinx.datetime.LocalDate typealias BasisDayOfMonthContent = @Composable BoxScope.(LocalDate) -> Unit typealias BasisDayOfWeekContent = @Composable BoxScope.(DayOfWeek) -> Unit val DefaultDayOfMonthContent: BasisDayOfMonthContent = { date -> val state = LocalBasisEpicCalendarState.current!! val config = LocalBasisEpicCalendarConfig.current Text( modifier = Modifier.alpha( alpha = remember(date, state.currentMonth) { if (date in state.currentMonth) 1.0f else 0.5f } ), text = date.dayOfMonth.toString(), textAlign = TextAlign.Center, color = config.contentColor ) } val DefaultDayOfWeekContent: BasisDayOfWeekContent = { dayOfWeek -> val config = LocalBasisEpicCalendarConfig.current Text( text = dayOfWeek.localized(), textAlign = TextAlign.Center, color = config.contentColor ) } @Composable fun BasisEpicCalendar( modifier: Modifier = Modifier, state: BasisEpicCalendarState = LocalBasisEpicCalendarState.current ?: rememberBasisEpicCalendarState(), onDayOfMonthClick: ((LocalDate) -> Unit)? = null, onDayOfWeekClick: ((DayOfWeek) -> Unit)? = null, dayOfWeekContent: BasisDayOfWeekContent = DefaultDayOfWeekContent, dayOfMonthContent: BasisDayOfMonthContent = DefaultDayOfMonthContent ) = with(state.config) { CompositionLocalProvider( LocalBasisEpicCalendarConfig provides state.config, LocalBasisEpicCalendarState provides state ) { Column( modifier = modifier.then( Modifier.padding(contentPadding) ), verticalArrangement = Arrangement.spacedBy(rowsSpacerHeight), ) { if (displayDaysOfWeek) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { daysOfWeek.forEach { dayOfWeek -> Box( modifier = Modifier.weight(1f), contentAlignment = Alignment.Center ) { Box( modifier = Modifier .clip(dayOfWeekShape) .height(dayOfWeekViewHeight) .width(columnWidth) .let { if (onDayOfWeekClick == null) it else it.clickable { onDayOfWeekClick(dayOfWeek) } }, contentAlignment = Alignment.Center ) { dayOfWeekContent(dayOfWeek) } } } } } state.dateGridInfo.dateMatrix.forEach { rowDates -> Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { rowDates.forEach { date -> Box( modifier = Modifier.weight(1f), contentAlignment = Alignment.Center ) { if (displayDaysOfAdjacentMonths || date.epicMonth == state.currentMonth) { Box( modifier = Modifier .clip(dayOfMonthShape) .height(dayOfMonthViewHeight) .width(columnWidth) .let { if (onDayOfMonthClick == null) it else it.clickable { onDayOfMonthClick(date) } }, contentAlignment = Alignment.Center ) { dayOfMonthContent(date) } } } } } } } } }
6
null
4
99
78d1a4dbfbd36c7ad224753936440526ba8a0bf0
5,834
epic-calendar
MIT License
fluentlenium-kotest/src/test/kotlin/io/fluentlenium/adapter/kotest/expectspec/DataDrivenSpec.kt
FluentLenium
2,088,736
false
null
package io.fluentlenium.adapter.kotest.expectspec import io.fluentlenium.adapter.kotest.FluentExpectSpec import io.fluentlenium.adapter.kotest.TestConstants import io.kotest.datatest.withData class DataDrivenSpec : FluentExpectSpec({ context("context") { withData(listOf("A", "B")) { goTo(TestConstants.DEFAULT_URL) } } withData(listOf("C")) { goTo(TestConstants.DEFAULT_URL) } })
32
null
212
867
6674ac80b0ab990c1ee5b8417109fc3134f27eeb
436
FluentLenium
Apache License 2.0
app/src/main/java/com/sebastianopighi/bestlyrics/domain/repositories/LyricsDataStore.kt
sebastianopighi
166,530,880
false
null
package com.sebastianopighi.bestlyrics.domain.repositories import com.sebastianopighi.bestlyrics.domain.models.LyricsEntity import io.reactivex.Single interface LyricsDataStore { fun getLyrics(trackId: Int): Single<LyricsEntity?> }
0
Kotlin
0
0
d6b096e5a64943b33e858610edd878d6f7b2d8e1
238
best-lyrics
MIT License
app/src/main/java/org/haidy/servify/presentation/screens/verified/VerifiedInteractionListener.kt
HaidyAbuGom3a
805,534,454
false
{"Kotlin": 702248}
package org.haidy.servify.presentation.screens.verified interface VerifiedInteractionListener { fun onClickExplore() }
0
Kotlin
0
2
8c2ba73cea5d29cc2ef7048d832f8ecea13f34ee
123
Servify
Apache License 2.0
src/main/kotlin/com/velocitypowered/api/kt/util/GameProfile.kt
PureOrigins
401,843,325
true
{"Kotlin": 9756}
package com.velocitypowered.api.kt.util import com.velocitypowered.api.util.GameProfile import java.util.UUID operator fun GameProfile.plus(properties: Iterable<GameProfile.Property>): GameProfile = addProperties(properties) operator fun GameProfile.plus(property: GameProfile.Property): GameProfile = addProperty(property) operator fun GameProfile.component1(): UUID = id operator fun GameProfile.component2(): String = name operator fun GameProfile.component3(): Collection<GameProfile.Property> = properties operator fun GameProfile.Property.component1(): String = name operator fun GameProfile.Property.component2(): String = value operator fun GameProfile.Property.component3(): String? = signature
0
Kotlin
0
0
6fb3dfe90b747156af6950a6e4989ae3187ee04a
713
velocity-language-kotlin
MIT License
app/src/main/kotlin/dev/leachryan/patterns/core/model/Dice.kt
leachryan
742,930,763
false
{"Kotlin": 2715}
package dev.leachryan.patterns.core.model class Dice(private val sides: Int) { fun roll(): Int = (1..sides).random() }
0
Kotlin
0
0
63676a934b37bb2e3131e0dd7329e9390d5233e5
125
kotlin-strategy-pattern
MIT License
app/src/prod/java/com/xmartlabs/gong/App.kt
xmartlabs
258,843,640
false
null
package com.xmartlabs.gong import com.xmartlabs.gong.device.di.DiAppModules import org.koin.android.ext.koin.androidContext import org.koin.core.context.startKoin class App : AppBase() { companion object { lateinit var instance: App private set } override fun setupKoinModules() { startKoin { androidContext(this@App) modules(DiAppModules.provideModules()) } } override fun onCreate() { instance = this super.onCreate() } }
8
null
5
89
5ac14c809c4ebd12e378b3ed66df34adc839e3dc
528
gong
MIT License
src/main/kotlin/kr/heartpattern/spikot/command/internal/CommandNode.kt
Spikot
129,165,327
false
null
/* * Copyright 2020 Spikot project authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kr.heartpattern.spikot.command.internal import kr.heartpattern.spikot.command.AbstractCommand import kr.heartpattern.spikot.command.CommandContext import kr.heartpattern.spikot.command.internal.handler.AbstractCommandHandler import kotlin.reflect.KClass internal class CommandNode( val handler: AbstractCommandHandler ) { companion object { inline operator fun <reified T : AbstractCommand> invoke(): CommandNode { return CommandNode(T::class) } operator fun <T : AbstractCommand> invoke(type: KClass<T>): CommandNode { return CommandNode(AbstractCommandHandler.create(type)) } } fun execute(context: CommandContext) { return resolve(context, AbstractCommandHandler::execute) } fun complete(context: CommandContext): List<String> { return resolve(context, AbstractCommandHandler::complete) } fun completeChild(context: CommandContext): List<String>{ return resolve(context, AbstractCommandHandler::completeChild) } fun help(context: CommandContext): String { return resolve(context){help()} } fun usage(context: CommandContext): String { return resolve(context){usage()} } private fun <T> resolve(context: CommandContext, executor: AbstractCommandHandler.(CommandContext) -> T): T { return resolve(context, 0, executor) } private fun <T> resolve(context: CommandContext, pos: Int, executor: AbstractCommandHandler.(CommandContext) -> T): T { if (pos == context.args.size) return handler.executor(context.copy(args=context.args.subList(pos, context.args.size))) for (child in handler.childs) for (name in child.handler.names) if (context.args[pos].equals(name, ignoreCase = true)) return child.resolve(context, pos + 1, executor) return handler.executor(context.copy(args=context.args.subList(pos, context.args.size))) } }
0
Kotlin
3
11
a44e2c9ad3203f3ea1bbf65ae9ef53f6f6283d77
2,610
SpikotLegacy
Apache License 2.0
application/app/src/main/java/com/aaronfodor/android/songquiz/model/AccountService.kt
aaronfodor
349,864,292
false
null
package com.aaronfodor.android.songquiz.model import android.content.Context import android.content.Intent import androidx.lifecycle.MutableLiveData import com.aaronfodor.android.songquiz.R import com.aaronfodor.android.songquiz.model.repository.dataclasses.Account import com.spotify.sdk.android.auth.AuthorizationClient import com.spotify.sdk.android.auth.AuthorizationRequest import com.spotify.sdk.android.auth.AuthorizationResponse import dagger.hilt.android.qualifiers.ApplicationContext import javax.inject.Inject import javax.inject.Singleton enum class AccountState{ LOGGED_IN, INVALID_TOKEN, LOGGED_OUT } /** * Injected everywhere as a singleton */ @Singleton class AccountService @Inject constructor( @ApplicationContext val context: Context ) { private var account= Account("") private val clientId = context.getString(R.string.spotifyClientId) private val spotifyRedirectURI = context.getString(R.string.com_spotify_sdk_redirect_uri) /** * Used for fallback token requests on behalf of the app. Works when client secret is available. * Only one valid token is existing at the same time with this option. Only use it for testing. */ val spotifyTokenRequestParam = context.getString(R.string.spotifyClientId) + ":" + context.getString(R.string.spotifyClientSec) /** * Require a new token before it expires in that many seconds */ val tokenRequireBeforeExpiresSec = 30 val accountState: MutableLiveData<AccountState> by lazy { MutableLiveData<AccountState>() } fun getAuthRequest() : AuthorizationRequest{ if(accountState.value == AccountState.LOGGED_OUT){ // force the logged out dialog AuthorizationClient.clearCookies(context) } val builder = AuthorizationRequest.Builder( clientId, AuthorizationResponse.Type.TOKEN, spotifyRedirectURI) return builder.setScopes(arrayOf("user-read-email")).setShowDialog(false).build() } fun getResponse(resultCode: Int, data: Intent) : AuthorizationResponse{ return AuthorizationClient.getResponse(resultCode, data) } fun setAccount(accountToSet: Account){ if(accountToSet.id.isNotBlank()){ account = accountToSet if(isValidToken(accountToSet.token, accountToSet.tokenExpireTime)){ accountState.postValue(AccountState.LOGGED_IN) } else{ accountState.postValue(AccountState.INVALID_TOKEN) } } else{ accountState.postValue(AccountState.LOGGED_OUT) account = Account("") } } fun updateToken(token: String, tokenExpireTime: Long){ val accountToSet = Account( id = account.id, name = account.name, email = account.email, uri = account.uri, country = account.country, token = token, tokenExpireTime = tokenExpireTime ) account = accountToSet if(isValidToken(token, tokenExpireTime)){ accountState.postValue(AccountState.LOGGED_IN) } else{ accountState.postValue(AccountState.INVALID_TOKEN) } } private fun isValidToken(token: String, tokenExpireTime: Long) : Boolean{ val currentTime = System.currentTimeMillis() return token.isNotBlank() && currentTime < tokenExpireTime } fun getValidToken() : String{ val currentTime = System.currentTimeMillis() if(account.token.isBlank() || currentTime > account.tokenExpireTime){ accountState.postValue(AccountState.INVALID_TOKEN) } return account.token } fun logout(){ AuthorizationClient.clearCookies(context) account = Account("") accountState.postValue(AccountState.LOGGED_OUT) } fun getUserNameAndEmail() : Pair<String, String>{ return Pair(account.name, account.email) } }
0
Kotlin
2
0
799b76951474a8f6f86dbd753ad160e537fd0926
4,001
SongQuiz
MIT License
8vim/src/main/kotlin/inc/flide/vim8/ime/theme/ImeTheme.kt
8VIM
72,917,629
false
null
package inc.flide.vim8.ime.theme import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.ReadOnlyComposable import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.platform.LocalContext import inc.flide.vim8.lib.compose.AppTheme import inc.flide.vim8.lib.compose.observeAsNonNullState import inc.flide.vim8.themeManager private val LocalTheme = staticCompositionLocalOf<ThemeManager.ThemeInfo> { error("not init") } object ImeTheme { val current: ThemeManager.ThemeInfo @Composable @ReadOnlyComposable get() = LocalTheme.current } @Composable fun ImeTheme(content: @Composable () -> Unit) { val context = LocalContext.current val themeManager by context.themeManager() val currentTheme by themeManager.currentTheme.observeAsNonNullState() val current = remember(currentTheme) { currentTheme } AppTheme(colorScheme = current.scheme) { CompositionLocalProvider(LocalTheme provides current) { content() } } }
73
null
61
461
089482f6bb5f715bc9168b8289957cee865573ae
1,178
8VIM
Apache License 2.0
features/forex/src/main/java/uk/co/jamiecruwys/feature/forex/presentation/ForexViewModel.kt
JamieCruwys
341,255,213
false
null
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.jamiecruwys.feature.forex.presentation import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import uk.co.jamiecruwys.base.data.User import uk.co.jamiecruwys.base.data.UserRepository import uk.co.jamiecruwys.feature.forex.data.domain.ForexDomainModel import uk.co.jamiecruwys.feature.forex.data.repository.ForexRepository import javax.inject.Inject @HiltViewModel class ForexViewModel @Inject constructor( private val forexRepository: ForexRepository, private val userRepository: UserRepository ) : ViewModel() { private val _loading = MutableLiveData<Boolean>() val loading: LiveData<Boolean> get() = _loading private val _items = MutableLiveData<List<ForexDomainModel>>() val items: LiveData<List<ForexDomainModel>> get() = _items private val _user = MutableLiveData<User>() val user: LiveData<User> get() = _user fun load() { _loading.postValue(true) viewModelScope.launch { val items = forexRepository.getData() val user = userRepository.getUser() _items.postValue(items) _loading.postValue(false) _user.postValue(user) } } }
1
Kotlin
2
4
443b1aef2f0c105369144e8c86e65741e589e608
1,945
android-modularisation
Apache License 2.0
bbootimg/src/test/kotlin/avb/desc/UnknownDescriptorTest.kt
cfig
56,238,465
false
null
// Copyright 2021 <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 avb.desc import org.apache.commons.codec.binary.Hex import org.junit.Test import org.slf4j.LoggerFactory import java.io.ByteArrayInputStream class UnknownDescriptorTest { private val log = LoggerFactory.getLogger(UnknownDescriptorTest::class.java) @Test fun readDescriptors() { //output by "xxd -p <file>" val descStr = "000000000000000200000000000000b800000000017b9000736861323536" + "000000000000000000000000000000000000000000000000000000000004" + "000000200000002000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000626f6f7428f6d60b554d9532bd45874ab0cd" + "cb2219c4f437c9350f484fa189a881878ab6156408cd763ff119635ec9db" + "2a9656e220fa1dc27e26e59bd3d85025b412ffc3" val descBA = Hex.decodeHex(descStr + descStr) val descList = UnknownDescriptor.parseDescriptors(ByteArrayInputStream(descBA), descBA.size.toLong()) descList.forEach{ log.info(it.toString()) } } }
20
null
222
972
cae7591d55647084d9ec0f73631caac7d43481d3
1,719
Android_boot_image_editor
Apache License 2.0
core-mvp-binding/sample/src/main/java/ru/surfstudio/android/mvp/binding/rx/sample/twoway/TwoWayRoute.kt
surfstudio
139,034,657
false
null
package ru.surfstudio.android.mvp.binding.rx.sample.twoway import android.content.Context import android.content.Intent import ru.surfstudio.android.core.ui.navigation.activity.route.ActivityRoute /** * Маршрут [TwoWayActivityView]. */ class TwoWayRoute : ActivityRoute() { override fun prepareIntent(context: Context) = Intent(context, TwoWayActivityView::class.java).apply { } }
5
null
30
249
6d73ebcaac4b4bd7186e84964cac2396a55ce2cc
394
SurfAndroidStandard
Apache License 2.0
app/src/main/java/com/sam/video/timeline/widget/MaxHeightRecyclerView.kt
meitu
312,538,026
false
null
package com.sam.video.timeline.widget import android.content.Context import android.util.AttributeSet /** * 限制最大高度的rv * @author SamWang(<EMAIL>) * @date 2019-08-07 */ class MaxHeightRecyclerView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : androidx.recyclerview.widget.RecyclerView(context, attrs, defStyleAttr) { var maxHeight = 0 override fun onMeasure(widthSpec: Int, heightSpec: Int) { val newHeightSpec = if (maxHeight > 0) { MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST) } else { heightSpec } super.onMeasure(widthSpec, newHeightSpec) } }
1
Kotlin
21
87
757b4cb51656f7c87836e0b323209f0fa6916bd4
694
VideoTimeLine
Apache License 2.0
app/src/main/java/com/example/eamobiles/di/RemoteModule.kt
AnguloDev10
414,837,957
false
null
package com.example.eamobiles.di import com.example.eamobiles.data.remote.AnimeService import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object RemoteModule { private const val API_BASE_URL ="https://anime-facts-rest-api.herokuapp.com/" @Provides @Singleton fun provideRetrofit(): Retrofit { return Retrofit.Builder() .baseUrl(API_BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() } @Provides @Singleton fun provideAnimeService(retrofit: Retrofit): AnimeService { println(API_BASE_URL) return retrofit.create(AnimeService::class.java) } }
0
Kotlin
0
0
b01ee45e8061a16002ba29c5eb89bba6ffdcbb45
887
ComposeMVVM
Apache License 2.0
core/src/test/kotlin/io/holunda/connector/compose/ComposeFunctionTest.kt
holunda-io
630,812,028
false
{"Python": 403136, "Kotlin": 57145, "Dockerfile": 1729, "Shell": 372}
package io.holunda.connector.compose import com.fasterxml.jackson.databind.node.* import io.holunda.connector.* import io.mockk.* import org.junit.jupiter.api.* class ComposeFunctionTest : AbstractFunctionTest<ComposeFunction>() { override val function = ComposeFunction() @Test fun `should execute compose function`() { val mockRequest = mockk<ComposeRequest>(relaxed = true) every { mockRequest.inputJson } returns TextNode("") val mockResult = TextNode("result") val result = executeFunctionTest(mockRequest, mockResult, ComposeRequest::class.java) verify { ComposeTask.fromRequest(mockRequest) } Assertions.assertInstanceOf(ComposeResult::class.java, result) Assertions.assertEquals(mockResult, (result as ComposeResult).result) } }
20
Python
0
24
655d64157bb01c247e7105118ab88d08d2ea0a11
815
camunda-8-connector-gpt
Apache License 2.0
marker/jvm-marker/src/test/testData/scope/CallerFunctions.kt
sourceplusplus
173,253,271
false
{"Kotlin": 1227211, "Java": 190403, "JavaScript": 3929, "Groovy": 3042, "Python": 2564}
private class CallerFunctions { private fun callerFunction() { directCalledFunction() } private fun directCalledFunction() { indirectCalledFunction() } private fun indirectCalledFunction() { println(true) } }
14
Kotlin
13
87
199006a410529d961dc184f0740a5d845bd87899
258
interface-jetbrains
Apache License 2.0
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/SearchHeart.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Bold.SearchHeart: ImageVector get() { if (_searchHeart != null) { return _searchHeart!! } _searchHeart = Builder(name = "SearchHeart", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 512.0f, viewportHeight = 512.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(512.0f, 466.928f) lineTo(403.624f, 358.552f) curveToRelative(74.164f, -98.987f, 54.041f, -239.353f, -44.945f, -313.517f) reflectiveCurveTo(119.325f, -9.007f, 45.161f, 89.98f) reflectiveCurveTo(-8.88f, 329.333f, 90.107f, 403.497f) curveToRelative(79.531f, 59.587f, 188.816f, 59.638f, 268.403f, 0.126f) lineTo(466.886f, 512.0f) lineTo(512.0f, 466.928f) close() moveTo(65.745f, 225.121f) curveToRelative(0.0f, -88.022f, 71.356f, -159.377f, 159.377f, -159.377f) reflectiveCurveTo(384.499f, 137.1f, 384.499f, 225.121f) reflectiveCurveToRelative(-71.356f, 159.377f, -159.377f, 159.377f) curveTo(137.139f, 384.405f, 65.838f, 313.104f, 65.745f, 225.121f) close() moveTo(320.195f, 203.34f) curveToRelative(0.0f, 55.081f, -95.626f, 122.72f, -95.626f, 122.72f) reflectiveCurveToRelative(-95.626f, -67.64f, -95.626f, -122.72f) curveToRelative(-1.251f, -27.702f, 20.118f, -51.208f, 47.813f, -52.594f) curveToRelative(27.701f, 1.376f, 49.076f, 24.888f, 47.813f, 52.594f) curveToRelative(-1.251f, -27.702f, 20.118f, -51.208f, 47.813f, -52.594f) curveTo(300.083f, 152.121f, 321.458f, 175.634f, 320.195f, 203.34f) close() } } .build() return _searchHeart!! } private var _searchHeart: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,709
icons
MIT License
ktor-utils/jsAndWasmShared/src/io/ktor/util/logging/LoggerJs.kt
ktorio
40,136,600
false
{"Kotlin": 6007831, "C": 453568, "Python": 948, "JavaScript": 775, "HTML": 336, "Mustache": 77, "Handlebars": 9}
// ktlint-disable filename /* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.util.logging public enum class LogLevel { TRACE, DEBUG, INFO, WARN, ERROR, NONE } public actual interface Logger { public val level: LogLevel public actual fun error(message: String) public actual fun error(message: String, cause: Throwable) public actual fun warn(message: String) public actual fun warn(message: String, cause: Throwable) public actual fun info(message: String) public actual fun info(message: String, cause: Throwable) public actual fun debug(message: String) public actual fun debug(message: String, cause: Throwable) public actual fun trace(message: String) public actual fun trace(message: String, cause: Throwable) } public actual val Logger.isTraceEnabled: Boolean get() = true
156
Kotlin
1051
12,926
f90f2edf11caca28a61dbe9973faae64c17a2842
949
ktor
Apache License 2.0
checkup/src/main/java/com/straiberry/android/checkup/checkup/domain/usecase/RemoteUpdateDentalIssueUseCase.kt
STRAIBERRY-AI-INC
490,596,796
false
{"Kotlin": 637726, "HTML": 1282}
package com.straiberry.android.checkup.checkup.domain.usecase import com.straiberry.android.checkup.checkup.domain.repository.CheckupRepo class RemoteUpdateDentalIssueUseCase(private val checkupRepo: CheckupRepo) { suspend fun execute( toothId: Int, toothNumber: String, duration: Int, cause: Int, pain: Int ) = checkupRepo.updateDentalIssue(toothId, toothNumber, duration, cause, pain) }
1
Kotlin
0
3
d2f93dac8ca1ce8e64a3c0983d0b029d89e369e1
439
straiberry-checkup
The Unlicense
common/ui/src/main/kotlin/app.surgo.common.ui/ItemsHeader.kt
tsukiymk
382,220,719
false
{"Kotlin": 889558, "Shell": 553, "CMake": 252, "C++": 166}
package app.surgo.common.ui import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.basicMarquee import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import app.surgo.common.compose.theme.BodySpacing import app.surgo.common.resources.R @OptIn(ExperimentalFoundationApi::class) @Composable fun ItemsHeader( title: String, modifier: Modifier = Modifier, onClick: () -> Unit = {} ) { Surface(modifier) { Row( modifier = Modifier.padding(horizontal = BodySpacing, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically ) { Text( text = title, modifier = Modifier.basicMarquee(), style = MaterialTheme.typography.titleMedium ) Spacer(Modifier.weight(1f)) TextButton(onClick) { Text(stringResource(R.string.text_more)) } } } }
0
Kotlin
0
0
99038e0621ecc17e47965c3b352391c6a780f26c
1,428
surgo
Apache License 2.0
relive-simulator-core/src/commonMain/kotlin/xyz/qwewqa/relive/simulator/core/presets/dress/generated/dress1090001.kt
qwewqa
390,928,568
false
null
package xyz.qwewqa.relive.simulator.core.presets.dress.generated import xyz.qwewqa.relive.simulator.core.stage.actor.ActType import xyz.qwewqa.relive.simulator.core.stage.actor.Attribute import xyz.qwewqa.relive.simulator.core.stage.actor.StatData import xyz.qwewqa.relive.simulator.core.stage.dress.ActParameters import xyz.qwewqa.relive.simulator.core.stage.dress.ActBlueprint import xyz.qwewqa.relive.simulator.core.stage.dress.PartialDressBlueprint import xyz.qwewqa.relive.simulator.core.stage.dress.StatBoost import xyz.qwewqa.relive.simulator.core.stage.dress.StatBoostType import xyz.qwewqa.relive.simulator.stage.character.Character import xyz.qwewqa.relive.simulator.stage.character.DamageType import xyz.qwewqa.relive.simulator.stage.character.Position /* import xyz.qwewqa.relive.simulator.core.presets.condition.* import xyz.qwewqa.relive.simulator.core.presets.dress.generated.dress1090001 import xyz.qwewqa.relive.simulator.core.stage.Act import xyz.qwewqa.relive.simulator.core.stage.actor.ActType import xyz.qwewqa.relive.simulator.core.stage.actor.CountableBuff import xyz.qwewqa.relive.simulator.core.stage.dress.DressCategory import xyz.qwewqa.relive.simulator.core.stage.autoskill.new import xyz.qwewqa.relive.simulator.core.stage.dress.blueprint import xyz.qwewqa.relive.simulator.core.stage.buff.* import xyz.qwewqa.relive.simulator.core.stage.passive.* import xyz.qwewqa.relive.simulator.core.stage.stageeffect.* val dress = dress1090001( name = "聖翔音楽学園", acts = listOf( ActType.Act1.blueprint("斬撃") { Act { /* %attr%属性攻撃(威力%value%) target: 前から1番目の敵役 hit_rate1: 100 values1: [88, 92, 96, 101, 105] times1: 1 */ } }, ActType.Act2.blueprint("渾身の斬撃") { Act { /* %attr%属性攻撃(威力%value%) target: 前から1番目の敵役 hit_rate1: 100 values1: [129, 136, 142, 149, 155] times1: 1 */ } }, ActType.Act3.blueprint("活力の喝采") { Act { /* %attr%属性攻撃(威力%value%) target: 前から1番目の敵役 hit_rate1: 100 values1: [132, 138, 145, 151, 158] times1: 1 通常防御力アップ(%value%) target: 自身 hit_rate2: 100 values2: [15, 16, 18, 19, 21] times2: [3, 3, 3, 3, 3] */ } }, ActType.ClimaxAct.blueprint("水仙花") { Act { /* 特殊バリア(%value%) target: 味方全体 hit_rate1: 100 values1: [330, 640, 1170, 1920, 2940] times1: [3, 3, 3, 3, 3] */ } } ), autoSkills = listOf( listOf( /* auto skill 1: 被ダメージダウン(%value%) target: 自身 values: [2, 3, 3, 3, 4] */ ), listOf( /* auto skill 2: マテリアル特攻(%value%) target: 自身 values: [50, 75, 75, 75, 100] */ ), listOf( /* auto skill 3: 与ダメージアップ(%value%) target: 自身 values: [5, 6, 6, 7, 8] */ ), ), unitSkill = null /* None */, multipleCA = false, categories = setOf(), ) */ val dress1090001 = PartialDressBlueprint( id = 1090001, name = "聖翔音楽学園", baseRarity = 2, cost = 6, character = Character.Kaoruko, attribute = Attribute.Moon, damageType = DamageType.Normal, position = Position.Back, positionValue = 32050, stats = StatData( hp = 732, actPower = 126, normalDefense = 48, specialDefense = 49, agility = 108, dexterity = 5, critical = 50, accuracy = 0, evasion = 0, ), growthStats = StatData( hp = 24130, actPower = 2090, normalDefense = 790, specialDefense = 810, agility = 1790, ), actParameters = mapOf( ActType.Act1 to ActBlueprint( name = "斬撃", type = ActType.Act1, apCost = 1, icon = 1, parameters = listOf( actParameters0, actParameters1, actParameters1, actParameters1, actParameters1, ), ), ActType.Act2 to ActBlueprint( name = "渾身の斬撃", type = ActType.Act2, apCost = 2, icon = 1, parameters = listOf( actParameters10, actParameters1, actParameters1, actParameters1, actParameters1, ), ), ActType.Act3 to ActBlueprint( name = "活力の喝采", type = ActType.Act3, apCost = 3, icon = 10, parameters = listOf( actParameters7, actParameters153, actParameters1, actParameters1, actParameters1, ), ), ActType.ClimaxAct to ActBlueprint( name = "水仙花", type = ActType.ClimaxAct, apCost = 2, icon = 31, parameters = listOf( actParameters253, actParameters1, actParameters1, actParameters1, actParameters1, ), ), ), autoSkillRanks = listOf(1, 4, 9, null), autoSkillPanels = listOf(0, 0, 5, 0), rankPanels = growthBoard3, friendshipPanels = friendshipPattern0, remakeParameters = listOf( ), )
0
Kotlin
11
7
70e1cfaee4c2b5ab4deff33b0e4fd5001c016b74
5,490
relight
MIT License
src/main/kotlin/core/usecase/AssignCreditInteractor.kt
TimeEscaper
380,326,985
false
null
package core.usecase import core.domain.* import core.port.CreditAssignmentRepositoryException import core.port.ICreditAssignmentRepository private val POSITIVE_CREDIT = CreditValue(20) private val NEGATIVE_CREDIT = CreditValue(-20) private val MESSAGE_SELF_ASSIGN_WARNING = BotMessage( "You can not assign or debit any credits to yourself! Have a -20 credit penalty for that!") class AssignCreditInteractor(private val assignmentsRepo: ICreditAssignmentRepository) { @Throws(AssignCreditException::class) fun assignPositive(chatId: ChatId, assignee: User, assignerId: UserId): BotMessage? { return assignCredit(chatId, assignee, assignerId, POSITIVE_CREDIT) } @Throws(AssignCreditException::class) fun assignNegative(chatId: ChatId, assignee: User, assignerId: UserId): BotMessage? { return assignCredit(chatId, assignee, assignerId, NEGATIVE_CREDIT) } @Throws(AssignCreditException::class) private fun assignCredit(chatId: ChatId, assignee: User, assignerId: UserId, value: CreditValue): BotMessage? { var valueToAssign = value var resultMessage: BotMessage? = null if (assignerId == assignee.userId) { valueToAssign = NEGATIVE_CREDIT resultMessage = MESSAGE_SELF_ASSIGN_WARNING } try { assignmentsRepo.addAssignment(CreditAssignment(chatId, assignee, valueToAssign)) } catch (e: CreditAssignmentRepositoryException) { throw AssignCreditException("Failed to assign credit in chat $chatId to user ${assignee.userId} by $assignerId", e) } return resultMessage } }
0
Kotlin
1
3
09f974857cf8323c563d06fe48b086a1e5610f0b
1,638
social_creditor_bot
MIT License
kotlin-common-gradle-plugins/src/main/kotlin/com/huanshankeji/ProjectNames.kt
huanshankeji
488,230,525
false
{"Kotlin": 46318}
package com.huanshankeji import org.gradle.api.Project val Project.fullNameForFileSystem get() = path.removePrefix(":").replace(":", "--") val Project.fullNameWithRootProjectNameForFileSystem get() = rootProject.name + "--" + fullNameForFileSystem val Project.defaultFullNameForPublishing get() = (rootProject.name + path).replace(":", "-") val Project.defaultPrefixForPublishing get() = (rootProject.name + path.lastIndexOf(':').let { if (it == -1) "" else path.substring(0, it) }) .replace(":", "-")
7
Kotlin
0
6
aabbd88f8f35402f7efc9093e4253daf2efe3ca1
543
gradle-common
Apache License 2.0
shared/src/commonMain/kotlin/UIComponentButton.kt
lspradeep
674,487,748
false
null
import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier expect class UIComponentButton(onClick: () -> Unit){ @Composable fun UIComponentButton(modifier: Modifier, text: String) }
0
Kotlin
0
4
5e48e62c4533430c890ada9b2c6b5e72085dbf44
210
compose-multiplatform-media
Apache License 2.0
shared/src/commonMain/kotlin/UIComponentButton.kt
lspradeep
674,487,748
false
null
import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier expect class UIComponentButton(onClick: () -> Unit){ @Composable fun UIComponentButton(modifier: Modifier, text: String) }
0
Kotlin
0
4
5e48e62c4533430c890ada9b2c6b5e72085dbf44
210
compose-multiplatform-media
Apache License 2.0
aoc2022/day13.kt
davidfpc
726,214,677
false
{"Kotlin": 127212}
package aoc2022 import utils.InputRetrieval import kotlin.math.min fun main() { Day13.execute() } object Day13 { fun execute() { val input = readInput() println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } private fun part1(input: List<String>): Int { return input.windowed(2, 3).mapIndexed { index, it -> val (left, right) = it val result = parse(left).isSmaller(parse(right)) if (result == Result.LOWER) { index + 1 } else 0 }.sum() } private val DELIMITERS = mutableListOf(parse("[[2]]", isDivider = true), parse("[[6]]", isDivider = true)) private fun part2(input: List<String>): Int { val parsedInput = input.filter { it.isNotEmpty() }.map { parse(it) } val inputWithDividers = DELIMITERS.apply { addAll(parsedInput) } return inputWithDividers.sortedWith { a: DigitOrList, b: DigitOrList -> a.isSmaller(b).value } .mapIndexed { index, value -> if (value.isDivider) { index + 1 } else { 0 } } .filter { it != 0 } .reduce(Int::times) } private fun parse(input: String, isDivider: Boolean = false): DigitOrList { val allParents = ArrayDeque<MutableList<DigitOrList>>() var currentList: MutableList<DigitOrList>? = null var i = 0 while (i < input.length) { when (input[i]) { in '0'..'9' -> { // Get all numbers var finalIndex = i + 1 while (input[finalIndex] != ',' && input[finalIndex] != ']') { finalIndex++ } val values = DigitOrList(input.substring(i, finalIndex).toInt()) currentList?.add(values) i = finalIndex } '[' -> { currentList?.also { allParents.add(it) } currentList = mutableListOf() i++ } ']' -> { allParents.removeLastOrNull()?.also { parent -> currentList?.also { parent.add(DigitOrList(it)) } currentList = parent } i++ } else -> i++ } } return DigitOrList(currentList!!, isDivider) } data class DigitOrList(var digit: Int?, var list: List<DigitOrList>?, val isDivider: Boolean) { constructor(value: Int, isDivider: Boolean = false) : this(value, null, isDivider) constructor(value: List<DigitOrList>, isDivider: Boolean = false) : this(null, value, isDivider) private fun isDigit() = digit != null fun isSmaller(other: DigitOrList): Result { if (this.isDigit() && other.isDigit()) { return if (this.digit!! < other.digit!!) { Result.LOWER } else if (this.digit!! > other.digit!!) { Result.GREATER } else { Result.EQUAL } } if (!this.isDigit() && !other.isDigit()) { val size = min(this.list!!.size, other.list!!.size) return (0 until size).map { this.list!![it].isSmaller(other.list!![it]) }.firstOrNull { it != Result.EQUAL } ?: if (this.list!!.size < other.list!!.size) { Result.LOWER } else if (this.list!!.size > other.list!!.size) { Result.GREATER } else { Result.EQUAL } } if (this.isDigit()) { return DigitOrList(listOf(this)).isSmaller(other) } return this.isSmaller(DigitOrList(listOf(other))) } } enum class Result(val value: Int) { EQUAL(0), LOWER(-1), GREATER(1) } fun readInput(): List<String> = InputRetrieval.getFile(2022, 13).readLines() }
0
Kotlin
0
0
8dacf809ab3f6d06ed73117fde96c81b6d81464b
4,225
Advent-Of-Code
MIT License
pulsar.core/src/main/kotlin/com/marshalldbrain/pulsar/colony/production/DistrictManager.kt
marshallbrain
221,334,008
false
null
package com.marshalldbrain.pulsar.colony.production import com.marshalldbrain.ion.collections.getOrDefault import com.marshalldbrain.pulsar.colony.construction.ConstructionTask import com.marshalldbrain.pulsar.colony.construction.ConstructionType import com.marshalldbrain.pulsar.resources.ResourceUpdater class DistrictManager( private val allDistrictTypes: Set<DistrictType>, private val resource: ResourceUpdater, private val job: JobUpdater ) : DistrictInfo { override val max = 5 private val map = possibleTypes .filter { it.starting } .take(max) .associateWith { 0 } .toMutableMap() override val remaining: Int get() = max - districts.size override val possibleTypes: Set<DistrictType> get() = allDistrictTypes.filter { it.possible }.toSet() override val remainingTypes: Set<DistrictType> get() = allDistrictTypes - districts.keys override val districts: Map<DistrictType, Int> get() = map override fun createConstructionTask( target: List<DistrictType>, type: ConstructionType, amount: Int ): ConstructionTask { return when (type) { ConstructionType.BUILD -> { ConstructionTask( "Building ${target[0].id}", target[0].cost, target[0].time, amount ) { OnComplete().build(target) } } ConstructionType.DESTROY -> { ConstructionTask( "Destroying ${target[0].id}", emptyMap(), 0, amount ) { OnComplete().destroy(target) } } ConstructionType.REPLACE -> { ConstructionTask( "Replacing ${target[1].id} with ${target[0].id}", target[0].cost, target[0].time, amount ) { OnComplete().replace(target) } } ConstructionType.TOOL -> { ConstructionTask( "Tooling ${if(target.size > 1) target[1].id else "untooled"} to ${target[0].id}", target[0].cost, target[0].time, amount ) { OnComplete().tool(target) } } ConstructionType.DETOOL -> { ConstructionTask( "Detooling ${target[0].id}", emptyMap(), 0, amount ) { OnComplete().detool(target) } } else -> throw Exception("Unsupported Construction Type: $type") } } private fun modifyDistrict(target: DistrictType, amount: Int) { map[target] = map.getValue(target) + amount resource.update(target.production, amount) resource.update(target.upkeep, -amount) job.update(target.jobs, amount) } private inner class OnComplete { fun build(target: List<DistrictType>) { modifyDistrict(target[0], 1) } fun destroy(target: List<DistrictType>) { if (map[target[0]]!! > 0) { modifyDistrict(target[0], -1) } } fun replace(target: List<DistrictType>) { if (map[target[1]]!! > 0) { modifyDistrict(target[1], -1) modifyDistrict(target[0], 1) } } fun tool(target: List<DistrictType>) { if (target.size > 1 && map.containsKey(target[1])) { modifyDistrict(target[1], map.getValue(target[1])) map.remove(target[1]) } map[target[0]] = 0 } fun detool(target: List<DistrictType>) { if (map.containsKey(target[0])) { modifyDistrict(target[0], map.getValue(target[0])) map.remove(target[0]) } } } } interface DistrictInfo { val max: Int val remaining: Int val districts: Map<DistrictType, Int> val possibleTypes: Set<DistrictType> val remainingTypes: Set<DistrictType> fun createConstructionTask( target: List<DistrictType>, type: ConstructionType, amount: Int ): ConstructionTask }
0
Kotlin
0
0
ca61d17315f18480f074ee58d801e140605c5b12
3,435
pulsar-experiment-4
MIT License
app/src/test/java/com/prush/justanotherplayer/SplashActivityPresenterTest.kt
iamporus
203,219,989
false
null
package com.prush.justanotherplayer import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.verify import com.prush.justanotherplayer.ui.splash.SplashActivityPresenter import com.prush.justanotherplayer.ui.splash.SplashActivityView import org.junit.Rule import org.junit.Test import org.mockito.junit.MockitoJUnit import org.mockito.junit.MockitoRule class SplashActivityPresenterTest { @get:Rule var mockitoRule: MockitoRule = MockitoJUnit.rule() @Test fun shouldGotoMainActivity() { //given val splashActivityView = mock<SplashActivityView> {} val splashActivityPresenter = SplashActivityPresenter(splashActivityView) //when splashActivityPresenter.gotoMainActivity() //then verify(splashActivityView).gotoMainActivity() } }
0
Kotlin
2
8
1d83a0cd55fa1d92c5bc1a6b0a95c34056809a14
830
Yamp
Apache License 2.0
features/home/ui/src/main/java/io/github/japskiddin/sudoku/feature/home/ui/components/ItemSelector.kt
Japskiddin
766,410,608
false
{"Kotlin": 260171}
package io.github.japskiddin.sudoku.feature.home.ui.components import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Row import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import io.github.japskiddin.sudoku.core.ui.theme.SudokuTheme import io.github.japskiddin.sudoku.feature.home.ui.R import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf @Composable internal fun ItemSelector( modifier: Modifier = Modifier, items: ImmutableList<String>, defaultItemPos: Int, ) { var currentItemPos by remember { mutableIntStateOf(defaultItemPos) } val currentItem = items[currentItemPos] Row( modifier = modifier, verticalAlignment = Alignment.CenterVertically ) { Image( painter = painterResource(id = R.drawable.ic_arrow_left), contentDescription = stringResource(id = R.string.swipe_left), modifier = Modifier.clickable { if (currentItemPos <= 0) { currentItemPos = items.count() - 1 } else { currentItemPos-- } } ) Text( text = currentItem, textAlign = TextAlign.Center, fontWeight = FontWeight.Medium, modifier = Modifier.weight(1f) ) Image( painter = painterResource(id = R.drawable.ic_arrow_right), contentDescription = stringResource(id = R.string.swipe_right), modifier = Modifier.clickable { if (currentItemPos >= items.count() - 1) { currentItemPos = 0 } else { currentItemPos++ } } ) } } @Preview( name = "Item Selector", showBackground = true ) @Composable private fun ItemSelectorPreview() { SudokuTheme { ItemSelector( items = persistentListOf("Item 1", "Item 2", "Item 3", "Item 4"), defaultItemPos = 1 ) } }
0
Kotlin
0
0
85cb1a33ef7cbc8db21c0a1b7210ce86a2446dee
2,629
SudokuGame
Apache License 2.0
alcholrehab/app/src/main/java/com/example/alcholrehab/utils/NetworkUtils.kt
bhargavbvs
476,408,431
false
null
package com.example.alcholrehab.utils import android.content.Context import android.net.ConnectivityManager import android.net.NetworkCapabilities import android.os.Build import com.example.alcholrehab.AlcoholRehab object NetworkUtils { fun isConnected(): Boolean { val connectivityManager = AlcoholRehab.application.getSystemService( Context.CONNECTIVITY_SERVICE ) as ConnectivityManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val activeNetwork = connectivityManager.activeNetwork ?: return false val capabilities = connectivityManager.getNetworkCapabilities(activeNetwork) ?: return false return when { capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true else -> false } } else { connectivityManager.activeNetworkInfo?.run { return when (type) { ConnectivityManager.TYPE_WIFI -> true ConnectivityManager.TYPE_MOBILE -> true ConnectivityManager.TYPE_ETHERNET -> true else -> false } } } return false } }
0
Kotlin
1
0
bf2b5941a00c1bf68d65863fb36e68cacfff23af
1,429
Courage-to-Change
MIT License
app/src/main/kotlin/com/adesso/movee/data/NetworkConnectionDispatcherImpl.kt
adessoTurkey
246,803,496
false
{"Kotlin": 262786, "Shell": 866}
package com.adesso.movee.data import android.content.Context import android.net.ConnectivityManager import android.net.Network import android.net.NetworkRequest import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.ProcessLifecycleOwner import com.adesso.movee.domain.NetworkConnection import com.adesso.movee.domain.NetworkConnectionDispatcher import com.adesso.movee.internal.extension.isNetworkAvailable import dagger.hilt.android.qualifiers.ApplicationContext import javax.inject.Inject import javax.inject.Singleton import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.receiveAsFlow @Singleton class NetworkConnectionDispatcherImpl @Inject constructor( @ApplicationContext private val context: Context, ) : NetworkConnectionDispatcher, DefaultLifecycleObserver { private val _state = Channel<NetworkConnection>(Channel.CONFLATED) override val state = _state.receiveAsFlow() private val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager private val networkCallback = object : ConnectivityManager.NetworkCallback() { override fun onAvailable(network: Network) { _state.trySend(NetworkConnection.AVAILABLE) } override fun onLost(network: Network) { _state.trySend(NetworkConnection.UNAVAILABLE) } } init { ProcessLifecycleOwner.get().lifecycle.addObserver(this) _state.trySend(getConnectionState()) } override fun getConnectionState(): NetworkConnection { return if (context.isNetworkAvailable()) { NetworkConnection.AVAILABLE } else { NetworkConnection.UNAVAILABLE } } private fun registerNetworkCallback() { connectivityManager?.registerNetworkCallback( NetworkRequest.Builder().build(), networkCallback ) } override fun onStart(owner: LifecycleOwner) { registerNetworkCallback() } override fun onStop(owner: LifecycleOwner) { connectivityManager?.unregisterNetworkCallback(networkCallback) } }
31
Kotlin
13
35
b34346a815204c966311f0c879b66e05a10eab13
2,193
android-sample-app
Apache License 2.0
src/test/kotlin/tech/espero/gruber/fullstackchallenge/controller/UserControllerTest.kt
danielgruber
458,578,234
false
{"Kotlin": 72512}
package tech.espero.gruber.fullstackchallenge.controller import org.json.JSONObject import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post import org.springframework.test.web.servlet.MockMvc import org.springframework.http.MediaType import org.springframework.test.web.servlet.result.MockMvcResultMatchers.* import tech.espero.gruber.fullstackchallenge.exceptions.PasswordTooWeakException import tech.espero.gruber.fullstackchallenge.model.User import tech.espero.gruber.fullstackchallenge.repository.UserRepository @AutoConfigureMockMvc @SpringBootTest class UserControllerTest { companion object { const val TEST_USERNAME = "testuser1" const val TEST_PASSWORD = "abc123AB" const val TEST_PASSWORD_TOO_WEAK = "1234" val ROLE_SELLER = User.UserRole.SELLER.toString() val ROLE_BUYER = User.UserRole.BUYER.toString() val ROLE_INVALID = "INVALID" } @Autowired private lateinit var mockMvc: MockMvc @Autowired private lateinit var userRepository: UserRepository /** * Tests if POST /users to register a user with BUYER role, valid username and password returns valid JSON result. */ @Test fun testRegisterBuyer() { try { val json = JSONObject() json.put("username", TEST_USERNAME) json.put("userRole", ROLE_BUYER) json.put("password", TEST_PASSWORD) mockMvc.perform( post("/user").contentType(MediaType.APPLICATION_JSON).content(json.toString()) ).andExpect( status().isCreated ).andExpect( content().contentType(MediaType.APPLICATION_JSON) ).andExpect( jsonPath("$.role").value(ROLE_BUYER) ) } finally { userRepository.getByUsernameIgnoreCase(TEST_USERNAME)?.let { userRepository.delete(it) } } } /** * Tests if POST /users to register a user with SELLER role, valid username and password returns valid JSON result. */ @Test fun testRegisterSeller() { try { val json = JSONObject() json.put("username", TEST_USERNAME) json.put("userRole", ROLE_SELLER) json.put("password", TEST_PASSWORD) mockMvc.perform( post("/user").contentType(MediaType.APPLICATION_JSON).content(json.toString()) ).andExpect( status().isCreated ).andExpect( content().contentType(MediaType.APPLICATION_JSON) ).andExpect( jsonPath("$.role").value(ROLE_SELLER) ) } finally { userRepository.getByUsernameIgnoreCase(TEST_USERNAME)?.let { userRepository.delete(it) } } } /** * Tests if POST /users to register a user with invalid role, valid username and password returns bad request. */ @Test fun testRegisterInvalidRole() { try { val json = JSONObject() json.put("username", TEST_USERNAME) json.put("userRole", ROLE_INVALID) json.put("password", TEST_PASSWORD) mockMvc.perform( post("/user"). contentType(MediaType.APPLICATION_JSON). content(json.toString()) ).andExpect( status().isBadRequest ).andExpect( content().contentType(MediaType.APPLICATION_JSON) ) } finally { userRepository.getByUsernameIgnoreCase(TEST_USERNAME)?.let { userRepository.delete(it) } } } /** * Tests if POST /users to register a user with duplicate username, valid role and password returns a conflict status. */ @Test fun testRegisterDuplicateUsername() { try { val json = JSONObject() json.put("username", TEST_USERNAME) json.put("userRole", ROLE_BUYER) json.put("password", TEST_PASSWORD) // perform 1st request mockMvc.perform( post("/user"). contentType(MediaType.APPLICATION_JSON). content(json.toString()) ).andExpect( status().isCreated ) mockMvc.perform( post("/user"). contentType(MediaType.APPLICATION_JSON). content(json.toString()) ).andExpect( status().isConflict ).andExpect( content().contentType(MediaType.APPLICATION_JSON) ) } finally { userRepository.getByUsernameIgnoreCase(TEST_USERNAME)?.let { userRepository.delete(it) } } } /** * Tests if POST /users to register a user with weak password, valid role and username returns a bad request status. */ @Test fun testRegisterWeakPassword() { try { val json = JSONObject() json.put("username", TEST_USERNAME) json.put("userRole", ROLE_BUYER) json.put("password", TEST_PASSWORD_TOO_WEAK) // perform 1st request mockMvc.perform( post("/user"). contentType(MediaType.APPLICATION_JSON). content(json.toString()) ).andExpect( status().isBadRequest ).andExpect( content().contentType(MediaType.APPLICATION_JSON) ).andExpect( jsonPath("$.exception").value(PasswordTooWeakException::class.simpleName) ) } finally { userRepository.getByUsernameIgnoreCase(TEST_USERNAME)?.let { userRepository.delete(it) } } } /** * Tests if POST /users to register a user with empty username, valid role and password returns a bad request status. */ @Test fun testRegisterEmptyUser() { try { val json = JSONObject() json.put("username", "") json.put("userRole", ROLE_BUYER) json.put("password", TEST_PASSWORD) // perform 1st request mockMvc.perform( post("/user"). contentType(MediaType.APPLICATION_JSON). content(json.toString()) ).andExpect( status().isBadRequest ).andExpect( content().contentType(MediaType.APPLICATION_JSON) ) } finally { userRepository.getByUsernameIgnoreCase("")?.let { userRepository.delete(it) } } } }
0
Kotlin
0
0
87323a708956e9577d659ebd100005388043d717
7,017
Full-stack-challenge
Apache License 2.0
jdroid-android-core/src/test/java/com/jdroid/android/AbstractUnitTest.kt
fwonly123
198,339,170
false
{"Java Properties": 2, "Markdown": 6, "Gradle": 22, "Shell": 1, "YAML": 2, "EditorConfig": 1, "Ignore List": 16, "XML": 233, "Kotlin": 394, "Java": 254, "JSON": 5, "JavaScript": 1, "INI": 2, "HTML": 1}
package com.jdroid.android abstract class AbstractUnitTest : AbstractTest() { override fun isHttpMockEnabled(): Boolean { return true } }
1
null
1
1
578194586fc7d7e71d3742756651d658cb498bd0
156
jdroid-android
Apache License 2.0
composeApp/src/commonMain/kotlin/model/User.kt
mjaremczuk
732,345,154
false
{"Kotlin": 28092, "HTML": 304}
package model import androidx.compose.runtime.Stable @Stable data class User( val login: String, val password: String, )
0
Kotlin
0
0
efa8fce42e4963b7e26c49b93789496edb40e039
131
ProjectsHelper
Apache License 2.0
composeApp/src/commonMain/kotlin/org/sn/notebykmp/data/data_sourse/LocalData.kt
SaeedNoshadi89
798,733,711
false
{"Kotlin": 142944, "Swift": 522, "HTML": 280}
package org.sn.notebykmp.data.data_sourse import org.sn.notebykmp.domain.model.Category object LocalData { val category = listOf( Category(id = 1, name = "All"), Category(id = 2, name = "Work"), Category(id = 3, name = "Life style") ) }
0
Kotlin
2
31
27416f64e3fcf1c6c572a4194dc794d7bc12f758
270
NoteByKMP
MIT License
app/src/main/java/com/mehdisekoba/imdb/data/model/detail/ResponseDetail.kt
MehdiSekoba
783,286,213
false
{"Kotlin": 145486}
package com.mehdisekoba.imdb.data.model.detail import com.google.gson.annotations.SerializedName @Suppress("ktlint:standard:max-line-length") data class ResponseDetail( @SerializedName("adult") val adult: Boolean?, // false @SerializedName("backdrop_path") val backdropPath: String?, // /87IVlclAfWL6mdicU1DDuxdwXwe.jpg @SerializedName("belongs_to_collection") val belongsToCollection: BelongsToCollection?, @SerializedName("budget") val budget: Int?, // 190000000 @SerializedName("genres") val genres: List<Genre>?, @SerializedName("homepage") val homepage: String?, // https://www.dunemovie.com @SerializedName("id") val id: Int?, // 693134 @SerializedName("imdb_id") val imdbId: String?, // tt15239678 @SerializedName("original_language") val originalLanguage: String?, // en @SerializedName("original_title") val originalTitle: String?, // Dune: Part Two @SerializedName("overview") val overview: String?, // Follow the mythic journey of <NAME> as he unites with Chani and the Fremen while on a path of revenge against the conspirators who destroyed his family. Facing a choice between the love of his life and the fate of the known universe, Paul endeavors to prevent a terrible future only he can foresee. @SerializedName("popularity") val popularity: Double?, // 736.807 @SerializedName("poster_path") val posterPath: String?, // /8b8R8l88Qje9dn9OE8PY05Nxl1X.jpg @SerializedName("production_companies") val productionCompanies: List<ProductionCompany?>?, @SerializedName("production_countries") val productionCountries: List<ProductionCountry?>?, @SerializedName("release_date") val releaseDate: String?, // 2024-02-27 @SerializedName("revenue") val revenue: Int?, // 509672149 @SerializedName("runtime") val runtime: Int?, // 167 @SerializedName("spoken_languages") val spokenLanguages: List<SpokenLanguage?>?, @SerializedName("status") val status: String?, // Released @SerializedName("tagline") val tagline: String?, // Long live the fighters. @SerializedName("title") val title: String?, // Dune: Part Two @SerializedName("video") val video: Boolean?, // false @SerializedName("vote_average") val voteAverage: Double?, // 8.396 @SerializedName("vote_count") val voteCount: Int?, // 1993 ) { data class BelongsToCollection( @SerializedName("backdrop_path") val backdropPath: String?, // /ygVSGv86R0BTOKJIb8RQ1sFxs4q.jpg @SerializedName("id") val id: Int?, // 726871 @SerializedName("name") val name: String?, // Dune Collection @SerializedName("poster_path") val posterPath: String?, // /wcVafar6Efk3YgFvh8oZQ4yHL6H.jpg ) data class Genre( @SerializedName("id") val id: Int?, // 878 @SerializedName("name") val name: String?, // Science Fiction ) data class ProductionCompany( @SerializedName("id") val id: Int?, // 923 @SerializedName("logo_path") val logoPath: String?, // /8M99Dkt23MjQMTTWukq4m5XsEuo.png @SerializedName("name") val name: String?, // Legendary Pictures @SerializedName("origin_country") val originCountry: String?, // US ) data class ProductionCountry( @SerializedName("iso_3166_1") val iso31661: String?, // US @SerializedName("name") val name: String?, // United States of America ) data class SpokenLanguage( @SerializedName("english_name") val englishName: String?, // English @SerializedName("iso_639_1") val iso6391: String?, // en @SerializedName("name") val name: String?, // English ) }
0
Kotlin
1
11
e4a2c6589681fca604a92b159811bf0a3106094f
3,812
imdb
Apache License 2.0
integration-scenarios/src/test/kotlin/wild/monitor/WildMonitorServiceIntegrationTest.kt
ddubson
169,662,670
false
null
package wild.monitor import io.restassured.RestAssured.given import org.hamcrest.CoreMatchers.notNullValue import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test class WildMonitorServiceIntegrationTest { @Test @DisplayName("WildMonitor Critical Path 1") fun criticalPath1() { given() .body("""{ "projectName": "Amazing Loon" }""") .contentType("application/json") .`when`() .post("/projects") .then() .statusCode(200) .contentType("application/json") .body("id", notNullValue()) } }
0
Kotlin
0
0
28bc6535ab639c3ea712383d55f60dbdcb094cf0
657
wild-monitor
MIT License
compiler/fir/resolve/testData/resolve/expresssions/receiverConsistency.kt
cr8tpro
189,964,139
false
null
fun foo() {} class C { fun bar() {} fun err() {} class Nested { fun test() { err() } } } fun test() { val c = C() foo() c.bar() val err = C() err.foo() }
0
null
1
2
dca23f871cc22acee9258c3d58b40d71e3693858
221
kotlin
Apache License 2.0
lightguide/src/main/java/com/forgetsy/lightguide/shape/RoundedRectangle.kt
ForgetSky
346,703,857
false
null
package com.forgetsy.lightguide.shape import android.animation.TimeInterpolator import android.graphics.Canvas import android.graphics.Paint import android.graphics.Rect import android.graphics.RectF import com.forgetsy.lightguide.shape.Shape.Companion.DEFAULT_DURATION import com.forgetsy.lightguide.shape.Shape.Companion.DEFAULT_INTERPOLATOR /** * [Shape] of RoundedRectangle with customizable height, width, and radius. */ class RoundedRectangle @JvmOverloads constructor( override val margin: Float = 10f, private val radius: Float = 20f, override val duration: Long = DEFAULT_DURATION, override val interpolator: TimeInterpolator = DEFAULT_INTERPOLATOR ) : Shape { private var rectF : RectF? = null var centerX: Float = 0f var centerY: Float = 0f private var height: Float = 0f private var width: Float = 0f override fun setAnchorRect(anchor: Rect) { width = anchor.width().toFloat() + margin height = anchor.height().toFloat() + margin centerX = anchor.centerX().toFloat() centerY = anchor.centerY().toFloat() rectF = RectF(centerX- width * 0.5f, centerY - height * 0.5f, centerX + width * 0.5f, centerY + height * 0.5f) } override fun draw(canvas: Canvas, value: Float, paint: Paint) { val halfWidth = width / 2 * value val halfHeight = height / 2 * value val left = centerX - halfWidth val top = centerY - halfHeight val right = centerX + halfWidth val bottom = centerY + halfHeight val rect = RectF(left, top, right, bottom) canvas.drawRoundRect(rect, radius, radius, paint) } override fun getRectF(): RectF { return rectF?: RectF() } }
0
Kotlin
0
1
e2a8150e5a95567412cd03ce3f685356a18b1eb8
1,649
LightGuide
Apache License 2.0
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/batch/EcsFargateContainerDefinitionDsl.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 70198112}
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package io.cloudshiftdev.awscdkdsl.services.batch import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker import kotlin.Boolean import kotlin.Number import kotlin.String import kotlin.collections.Collection import kotlin.collections.Map import kotlin.collections.MutableList import software.amazon.awscdk.Size import software.amazon.awscdk.services.batch.EcsFargateContainerDefinition import software.amazon.awscdk.services.batch.EcsVolume import software.amazon.awscdk.services.batch.LinuxParameters import software.amazon.awscdk.services.batch.Secret import software.amazon.awscdk.services.ecs.ContainerImage import software.amazon.awscdk.services.ecs.CpuArchitecture import software.amazon.awscdk.services.ecs.FargatePlatformVersion import software.amazon.awscdk.services.ecs.LogDriver import software.amazon.awscdk.services.ecs.OperatingSystemFamily import software.amazon.awscdk.services.iam.IRole import software.constructs.Construct /** * A container orchestrated by ECS that uses Fargate resources. * * Example: * ``` * EcsJobDefinition jobDefn = EcsJobDefinition.Builder.create(this, "JobDefn") * .container(EcsFargateContainerDefinition.Builder.create(this, "myFargateContainer") * .image(ContainerImage.fromRegistry("public.ecr.aws/amazonlinux/amazonlinux:latest")) * .memory(Size.mebibytes(2048)) * .cpu(256) * .ephemeralStorageSize(Size.gibibytes(100)) * .fargateCpuArchitecture(CpuArchitecture.ARM64) * .fargateOperatingSystemFamily(OperatingSystemFamily.LINUX) * .build()) * .build(); * ``` */ @CdkDslMarker public class EcsFargateContainerDefinitionDsl( scope: Construct, id: String, ) { private val cdkBuilder: EcsFargateContainerDefinition.Builder = EcsFargateContainerDefinition.Builder.create(scope, id) private val _command: MutableList<String> = mutableListOf() private val _volumes: MutableList<EcsVolume> = mutableListOf() /** * Indicates whether the job has a public IP address. * * For a job that's running on Fargate resources in a private subnet to send outbound traffic to * the internet (for example, to pull container images), the private subnet requires a NAT * gateway be attached to route requests to the internet. * * Default: false * * [Documentation](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-networking.html) * * @param assignPublicIp Indicates whether the job has a public IP address. */ public fun assignPublicIp(assignPublicIp: Boolean) { cdkBuilder.assignPublicIp(assignPublicIp) } /** * The command that's passed to the container. * * Default: - no command * * [Documentation](https://docs.docker.com/engine/reference/builder/#cmd) * * @param command The command that's passed to the container. */ public fun command(vararg command: String) { _command.addAll(listOf(*command)) } /** * The command that's passed to the container. * * Default: - no command * * [Documentation](https://docs.docker.com/engine/reference/builder/#cmd) * * @param command The command that's passed to the container. */ public fun command(command: Collection<String>) { _command.addAll(command) } /** * The number of vCPUs reserved for the container. * * Each vCPU is equivalent to 1,024 CPU shares. For containers running on EC2 resources, you * must specify at least one vCPU. * * @param cpu The number of vCPUs reserved for the container. */ public fun cpu(cpu: Number) { cdkBuilder.cpu(cpu) } /** * The environment variables to pass to a container. * * Cannot start with `AWS_BATCH`. We don't recommend using plaintext environment variables for * sensitive information, such as credential data. * * Default: - no environment variables * * @param environment The environment variables to pass to a container. */ public fun environment(environment: Map<String, String>) { cdkBuilder.environment(environment) } /** * The size for ephemeral storage. * * Default: - 20 GiB * * @param ephemeralStorageSize The size for ephemeral storage. */ public fun ephemeralStorageSize(ephemeralStorageSize: Size) { cdkBuilder.ephemeralStorageSize(ephemeralStorageSize) } /** * The role used by Amazon ECS container and AWS Fargate agents to make AWS API calls on your * behalf. * * Default: - a Role will be created * * [Documentation](https://docs.aws.amazon.com/batch/latest/userguide/execution-IAM-role.html) * * @param executionRole The role used by Amazon ECS container and AWS Fargate agents to make AWS * API calls on your behalf. */ public fun executionRole(executionRole: IRole) { cdkBuilder.executionRole(executionRole) } /** * The vCPU architecture of Fargate Runtime. * * Default: - X86_64 * * @param fargateCpuArchitecture The vCPU architecture of Fargate Runtime. */ public fun fargateCpuArchitecture(fargateCpuArchitecture: CpuArchitecture) { cdkBuilder.fargateCpuArchitecture(fargateCpuArchitecture) } /** * The operating system for the compute environment. * * Default: - LINUX * * @param fargateOperatingSystemFamily The operating system for the compute environment. */ public fun fargateOperatingSystemFamily(fargateOperatingSystemFamily: OperatingSystemFamily) { cdkBuilder.fargateOperatingSystemFamily(fargateOperatingSystemFamily) } /** * Which version of Fargate to use when running this container. * * Default: LATEST * * @param fargatePlatformVersion Which version of Fargate to use when running this container. */ public fun fargatePlatformVersion(fargatePlatformVersion: FargatePlatformVersion) { cdkBuilder.fargatePlatformVersion(fargatePlatformVersion) } /** * The image that this container will run. * * @param image The image that this container will run. */ public fun image(image: ContainerImage) { cdkBuilder.image(image) } /** * The role that the container can assume. * * Default: - no job role * * [Documentation](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html) * * @param jobRole The role that the container can assume. */ public fun jobRole(jobRole: IRole) { cdkBuilder.jobRole(jobRole) } /** * Linux-specific modifications that are applied to the container, such as details for device * mappings. * * Default: none * * @param linuxParameters Linux-specific modifications that are applied to the container, such * as details for device mappings. */ public fun linuxParameters(linuxParameters: LinuxParameters) { cdkBuilder.linuxParameters(linuxParameters) } /** * The loging configuration for this Job. * * Default: - the log configuration of the Docker daemon * * @param logging The loging configuration for this Job. */ public fun logging(logging: LogDriver) { cdkBuilder.logging(logging) } /** * The memory hard limit present to the container. * * If your container attempts to exceed the memory specified, the container is terminated. You * must specify at least 4 MiB of memory for a job. * * @param memory The memory hard limit present to the container. */ public fun memory(memory: Size) { cdkBuilder.memory(memory) } /** * Gives the container readonly access to its root filesystem. * * Default: false * * @param readonlyRootFilesystem Gives the container readonly access to its root filesystem. */ public fun readonlyRootFilesystem(readonlyRootFilesystem: Boolean) { cdkBuilder.readonlyRootFilesystem(readonlyRootFilesystem) } /** * A map from environment variable names to the secrets for the container. * * Allows your job definitions to reference the secret by the environment variable name defined * in this property. * * Default: - no secrets * * [Documentation](https://docs.aws.amazon.com/batch/latest/userguide/specifying-sensitive-data.html) * * @param secrets A map from environment variable names to the secrets for the container. */ public fun secrets(secrets: Map<String, Secret>) { cdkBuilder.secrets(secrets) } /** * The user name to use inside the container. * * Default: - no user * * @param user The user name to use inside the container. */ public fun user(user: String) { cdkBuilder.user(user) } /** * The volumes to mount to this container. * * Automatically added to the job definition. * * Default: - no volumes * * @param volumes The volumes to mount to this container. */ public fun volumes(vararg volumes: EcsVolume) { _volumes.addAll(listOf(*volumes)) } /** * The volumes to mount to this container. * * Automatically added to the job definition. * * Default: - no volumes * * @param volumes The volumes to mount to this container. */ public fun volumes(volumes: Collection<EcsVolume>) { _volumes.addAll(volumes) } public fun build(): EcsFargateContainerDefinition { if (_command.isNotEmpty()) cdkBuilder.command(_command) if (_volumes.isNotEmpty()) cdkBuilder.volumes(_volumes) return cdkBuilder.build() } }
0
Kotlin
0
3
256ad92aebe2bcf9a4160089a02c76809dbbedba
10,016
awscdk-dsl-kotlin
Apache License 2.0
lifecycle/autodispose-lifecycle-ktx/src/test/kotlin/com/uber/autodispose/lifecycle/ktx/KotlinLifecycleScopeProviderTest.kt
msocheat
159,807,643
true
{"Java": 306114, "Kotlin": 33135, "Shell": 938}
/* * Copyright (C) 2018. Uber Technologies * * 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.uber.autodispose.lifecycle import com.google.common.truth.Truth.assertThat import com.uber.autodispose.lifecycle.KotlinLifecycleScopeProviderTest.LifecycleEvent.START import com.uber.autodispose.lifecycle.KotlinLifecycleScopeProviderTest.LifecycleEvent.STOP import com.uber.autodispose.test.RecordingObserver import io.reactivex.Observable import io.reactivex.subjects.BehaviorSubject import io.reactivex.subjects.PublishSubject import org.junit.Test class KotlinLifecycleScopeProviderTest { internal enum class LifecycleEvent { START, STOP } /** * A thing with a lifecycle that uses the default implementation of [requestScope]. */ internal class ThingWithALifecycle : KotlinLifecycleScopeProvider<LifecycleEvent> { var lifecycle: BehaviorSubject<LifecycleEvent> = BehaviorSubject.createDefault( START) override fun lifecycle(): Observable<LifecycleEvent> { return lifecycle.hide() } override fun correspondingEvents(): CorrespondingEventsFunction<LifecycleEvent> { return CorrespondingEventsFunction { event -> when (event) { START -> STOP STOP -> throw LifecycleEndedException( "Ended!") } } } override fun peekLifecycle(): LifecycleEvent? { return lifecycle.value } } @Test fun smokeTest() { val o = RecordingObserver<Int>(System.out::println) val source = PublishSubject.create<Int>() val provider = ThingWithALifecycle() val lifecycle = provider.lifecycle source.autoDisposable(provider) .subscribe(o) o.takeSubscribe() assertThat(source.hasObservers()).isTrue() assertThat(lifecycle.hasObservers()).isTrue() source.onNext(1) assertThat(o.takeNext()).isEqualTo(1) lifecycle.onNext(START) source.onNext(2) assertThat(source.hasObservers()).isTrue() assertThat(lifecycle.hasObservers()).isTrue() assertThat(o.takeNext()).isEqualTo(2) lifecycle.onNext(STOP) source.onNext(3) o.assertNoMoreEvents() assertThat(source.hasObservers()).isFalse() assertThat(lifecycle.hasObservers()).isFalse() } }
0
Java
0
0
921965d965684e3749fcc841b28fcae2c59035ed
2,754
AutoDispose
Apache License 2.0
Kotlin/src/RotateArrayTest.kt
santosh241
293,432,227
false
null
import org.junit.Assert import org.junit.Test import java.util.Arrays class RotateArrayTest { @Test fun testRotate() { val ra = RotateArray() val array0 = intArrayOf(1) ra.rotate(array0, 1) Assert.assertTrue(Arrays.equals(array0, intArrayOf(1))) val array1 = intArrayOf(1, 2) ra.rotate(array1, 1) Assert.assertTrue(Arrays.equals(array1, intArrayOf(2, 1))) val array2 = intArrayOf(1, 2, 3, 4, 5, 6, 7) ra.rotate(array2, 3) Assert.assertTrue(Arrays.equals(array2, intArrayOf(5, 6, 7, 1, 2, 3, 4))) } }
1
null
1
2
39f85cdedaaf5b85f7ce842ecef975301fc974cf
598
Windary
MIT License
Section3/Video3.4/CommunicatingWithFragments/app/src/main/java/fragment/packt/com/communicatingwithfragments/BlankFragment2.kt
sby5388
256,136,381
true
{"Java": 36215068, "Kotlin": 132222, "Assembly": 138}
package fragment.packt.com.communicatingwithfragments import android.content.Context import android.os.Bundle import android.support.v4.app.Fragment import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Activities that contain this fragment must implement the * [BlankFragment2.OnFragmentInteractionListener] interface * to handle interaction events. * Use the [BlankFragment2.newInstance] factory method to * create an instance of this fragment. * */ class BlankFragment2 : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var listener: OnFragmentInteractionListener2? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view : View = inflater.inflate(R.layout.fragment_blank_fragment2, container, false) val myTextView : TextView = view.findViewById(R.id.txt_frg2) // Inflate the layout for this fragment myTextView.text = param1 return view } // TODO: Rename method, update argument and hook method into UI event fun onButtonPressed(textFromFrg2: String) { listener?.onFragmentInteraction2(textFromFrg2) } override fun onAttach(context: Context) { super.onAttach(context) if (context is OnFragmentInteractionListener2) { listener = context } else { throw RuntimeException(context.toString() + " must implement OnFragmentInteractionListener") } } override fun onResume() { super.onResume() listener?.onFragmentInteraction2("Hello Fragment 1") Log.d("Trace","f2 Resumed") } override fun onStop() { super.onStop() Log.d("Trace","f2 stopped") } override fun onPause() { super.onPause() Log.d("Trace","f2 Paused") } override fun onDetach() { super.onDetach() listener = null } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * * * See the Android Training lesson [Communicating with Other Fragments] * (http://developer.android.com/training/basics/fragments/communicating.html) * for more information. */ interface OnFragmentInteractionListener2 { // TODO: Update argument type and name fun onFragmentInteraction2(textFromFrg2: String) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment BlankFragment2. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String?) = BlankFragment2().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) } } } }
0
Java
0
0
9eeea6097983b13e411afa21dcec6460c7d7ee70
3,768
Hands-on-Android-Application-Components-Services-and-Fragments
MIT License
src/me/anno/io/base/BaseReader.kt
won21kr
351,713,352
true
{"Kotlin": 1983578, "Java": 301507, "C": 75596, "GLSL": 9436}
package me.anno.io.base import me.anno.audio.effects.SoundPipeline import me.anno.audio.effects.falloff.ExponentialFalloff import me.anno.audio.effects.falloff.LinearFalloff import me.anno.audio.effects.falloff.SquareFalloff import me.anno.audio.effects.impl.AmplitudeEffect import me.anno.audio.effects.impl.EchoEffect import me.anno.audio.effects.impl.EqualizerEffect import me.anno.audio.effects.impl.PitchEffect import me.anno.io.ISaveable import me.anno.io.InvalidFormatException import me.anno.io.utils.StringMap import me.anno.objects.* import me.anno.objects.animation.AnimatedProperty import me.anno.objects.animation.Keyframe import me.anno.objects.animation.drivers.FunctionDriver import me.anno.objects.animation.drivers.HarmonicDriver import me.anno.objects.animation.drivers.PerlinNoiseDriver import me.anno.objects.attractors.EffectColoring import me.anno.objects.attractors.EffectMorphing import me.anno.objects.distributions.* import me.anno.objects.effects.MaskLayer import me.anno.objects.forces.impl.* import me.anno.objects.geometric.Circle import me.anno.objects.geometric.Polygon import me.anno.objects.meshes.Mesh import me.anno.objects.particles.ParticleSystem import me.anno.objects.particles.TextParticles import me.anno.objects.documents.pdf.PDFDocument import me.anno.objects.text.Text import me.anno.objects.text.Timer import me.anno.studio.history.History import me.anno.studio.history.HistoryState import me.anno.ui.editor.sceneView.SceneTabData import me.anno.utils.structures.arrays.BoolArray import org.apache.logging.log4j.LogManager abstract class BaseReader { val content = HashMap<Int, ISaveable>() val sortedContent get() = content.entries.sortedBy { it.key }.map { it.value }.toList() private val missingReferences = HashMap<Int, ArrayList<Pair<Any, String>>>() fun register(value: ISaveable, ptr: Int) { if (ptr != 0) { content[ptr] = value missingReferences[ptr]?.forEach { (obj, name) -> when (obj) { is ISaveable -> { obj.readObject(name, value) } is MissingListElement -> { obj.target[obj.targetIndex] = value } else -> throw RuntimeException("Unknown missing reference type") } } } else if (ptr == 0) LOGGER.warn("Got object with uuid $ptr: $value, it will be ignored") } fun addMissingReference(owner: Any, name: String, childPtr: Int) { val list = missingReferences[childPtr] val entry = owner to name if (list != null) { list += entry } else { missingReferences[childPtr] = arrayListOf(entry) } } fun assert(b: Boolean) { if (!b) throw InvalidFormatException("Assertion failed") } fun assert(b: Boolean, msg: String) { if (!b) throw InvalidFormatException(msg) } fun assert(isValue: String, shallValue: String) { if (!isValue.equals(shallValue, true)) { throw InvalidFormatException("Expected $shallValue but got $isValue") } } fun assert(isValue: Char, shallValue: Char) { if (isValue != shallValue.toLowerCase() && isValue != shallValue.toUpperCase()) { throw InvalidFormatException("Expected $shallValue but got $isValue") } } fun assert(isValue: Char, shallValue: Char, context: String) { if (isValue != shallValue.toLowerCase() && isValue != shallValue.toUpperCase()) { throw InvalidFormatException("Expected $shallValue but got $isValue for $context") } } abstract fun readObject(): ISaveable abstract fun readAllInList() companion object { private val LOGGER = LogManager.getLogger(BaseReader::class) fun error(msg: String): Nothing = throw InvalidFormatException("[BaseReader] $msg") fun error(msg: String, appended: Any?): Nothing = throw InvalidFormatException("[BaseReader] $msg $appended") fun getNewClassInstance(clazz: String): ISaveable { return when (clazz) { "SMap" -> StringMap() "Transform" -> Transform() "Text" -> Text() "Circle" -> Circle() "Polygon" -> Polygon() "Video", "Audio", "Image" -> Video() "GFXArray" -> GFXArray() "MaskLayer" -> MaskLayer() "ParticleSystem" -> ParticleSystem() "Camera" -> Camera() "Mesh" -> Mesh() "Timer" -> Timer() "AnimatedProperty" -> AnimatedProperty.any() "Keyframe" -> Keyframe<Any>() "HarmonicDriver" -> HarmonicDriver() "PerlinNoiseDriver" -> PerlinNoiseDriver() "CustomDriver", "FunctionDriver" -> FunctionDriver() "SceneTabData" -> SceneTabData() "ColorAttractor", "EffectColoring" -> EffectColoring() "UVAttractor", "EffectMorphing" -> EffectMorphing() "SoundPipeline" -> SoundPipeline() "EchoEffect" -> EchoEffect() "AmplitudeEffect" -> AmplitudeEffect() "EqualizerEffect" -> EqualizerEffect() "PitchEffect" -> PitchEffect() "SquareFalloffEffect" -> SquareFalloff() "LinearFalloffEffect" -> LinearFalloff() "ExponentialFalloffEffect" -> ExponentialFalloff() "AnimatedDistribution" -> AnimatedDistribution() "GaussianDistribution" -> GaussianDistribution() "ConstantDistribution" -> ConstantDistribution() "UniformDistribution", // replaced "CuboidDistribution" -> CuboidDistribution() "CuboidHullDistribution" -> CuboidHullDistribution() "SphereHullDistribution" -> SphereHullDistribution() "SphereDistribution", "SphereVolumeDistribution" -> SphereVolumeDistribution() "GlobalForce" -> GlobalForce() "GravityField" -> GravityField() "LorentzForce" -> LorentzForce() "NoisyLorentzForce" -> NoisyLorentzForce() "MultiGravityForce" -> BetweenParticleGravity() "TornadoField" -> TornadoField() "VelocityFrictionForce" -> VelocityFrictionForce() "History" -> History() "HistoryState" -> HistoryState() "BoolArray" -> BoolArray() "TextParticles" -> TextParticles() "SoftLink" -> SoftLink() "PDFDocument" -> PDFDocument() else -> { // just for old stuff; AnimatedProperties must not be loaded directly; always just copied into if (clazz.startsWith("AnimatedProperty<")) AnimatedProperty.any() else ISaveable.objectTypeRegistry[clazz]?.invoke() ?: throw UnknownClassException(clazz) } } } } }
0
null
0
0
b85295f59ddfa9fc613a384d439fd1b30b06a5a4
7,153
RemsStudio
Apache License 2.0
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsactivitiesmanagementapi/service/AppointmentOccurrenceAllocationServiceTest.kt
ministryofjustice
533,838,017
false
null
package uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.service import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoInteractions import org.mockito.kotlin.whenever import reactor.core.publisher.Mono import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.client.prisonapi.api.PrisonApiApplicationClient import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.client.prisonapi.model.InmateDetail import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.entity.Appointment import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.entity.AppointmentInstance import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.entity.AppointmentOccurrence import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.entity.AppointmentOccurrenceAllocation import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.repository.AppointmentInstanceRepository import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.repository.AppointmentOccurrenceAllocationRepository import java.util.Optional class AppointmentOccurrenceAllocationServiceTest { private val prisonApiClient = mock<PrisonApiApplicationClient>() private val appointmentInstanceRepository = mock<AppointmentInstanceRepository>() private val appointmentOccurrenceAllocationRepository = mock<AppointmentOccurrenceAllocationRepository>() private val appointmentOccurrenceAllocationService = AppointmentOccurrenceAllocationService( prisonApiClient, appointmentInstanceRepository, appointmentOccurrenceAllocationRepository, ) @Test fun `cancels all future appointments`() { val appointmentOccurrenceAllocationId = 42L val prisonCode = "PVI" val prisonerNumber = "ABC123" val inmateDetail = mock<InmateDetail>() val appointmentInstance = mock<AppointmentInstance>() val parentAppointment = mock<Appointment>() val parentAllocation = mock<AppointmentOccurrenceAllocation>() val parentOccurrence = mock<AppointmentOccurrence>() whenever(appointmentInstance.appointmentOccurrenceAllocationId).thenReturn(appointmentOccurrenceAllocationId) whenever( prisonApiClient.getPrisonerDetails( prisonerNumber = prisonerNumber, fullInfo = true, extraInfo = true, ), ).thenReturn(Mono.just(inmateDetail)) whenever(appointmentInstanceRepository.findByPrisonCodeAndPrisonerNumberFromNow(prisonCode, prisonerNumber)) .thenReturn(listOf(appointmentInstance)) whenever(appointmentOccurrenceAllocationRepository.findById(appointmentOccurrenceAllocationId)).thenReturn(Optional.of(parentAllocation)) whenever(parentAllocation.appointmentOccurrence).thenReturn(parentOccurrence) whenever(parentAllocation.appointmentOccurrenceAllocationId).thenReturn(appointmentOccurrenceAllocationId) whenever(parentOccurrence.appointment).thenReturn(parentAppointment) whenever(parentAllocation.isIndividualAppointment()).thenReturn(false) appointmentOccurrenceAllocationService.cancelFutureOffenderAppointments(prisonCode, prisonerNumber) verify(parentAllocation).removeFromAppointmentOccurrence() } @Test fun `cancels all future appointments and deletes orphaned individual appointment `() { val appointmentOccurrenceAllocationId = 42L val prisonCode = "PVI" val prisonerNumber = "ABC123" val inmateDetail = mock<InmateDetail>() val appointmentInstance = mock<AppointmentInstance>() val parentAppointment = mock<Appointment>() val parentAllocation = mock<AppointmentOccurrenceAllocation>() val parentOccurrence = mock<AppointmentOccurrence>() whenever(appointmentInstance.appointmentOccurrenceAllocationId).thenReturn(appointmentOccurrenceAllocationId) whenever( prisonApiClient.getPrisonerDetails( prisonerNumber = prisonerNumber, fullInfo = true, extraInfo = true, ), ).thenReturn(Mono.just(inmateDetail)) whenever(appointmentInstanceRepository.findByPrisonCodeAndPrisonerNumberFromNow(prisonCode, prisonerNumber)) .thenReturn(listOf(appointmentInstance)) whenever(appointmentOccurrenceAllocationRepository.findById(appointmentOccurrenceAllocationId)).thenReturn(Optional.of(parentAllocation)) whenever(parentAllocation.appointmentOccurrence).thenReturn(parentOccurrence) whenever(parentAllocation.appointmentOccurrenceAllocationId).thenReturn(appointmentOccurrenceAllocationId) whenever(parentOccurrence.appointment).thenReturn(parentAppointment) whenever(parentAllocation.isIndividualAppointment()).thenReturn(true) appointmentOccurrenceAllocationService.cancelFutureOffenderAppointments(prisonCode, prisonerNumber) verify(parentAllocation).removeOccurrence(parentOccurrence) } @Test fun `does not cancel anything if there are no future appointments`() { val prisonCode = "PVI" val prisonerNumber = "ABC123" val inmateDetail = mock<InmateDetail>() whenever( prisonApiClient.getPrisonerDetails( prisonerNumber = prisonerNumber, fullInfo = true, extraInfo = true, ), ).thenReturn(Mono.just(inmateDetail)) whenever(appointmentInstanceRepository.findByPrisonCodeAndPrisonerNumberFromNow(prisonCode, prisonerNumber)) .thenReturn(listOf()) appointmentOccurrenceAllocationService.cancelFutureOffenderAppointments(prisonCode, prisonerNumber) verifyNoInteractions(appointmentOccurrenceAllocationRepository) } }
4
Kotlin
0
1
8e1f42b2b35528679e7aefb5da9818e82e8b22d2
5,535
hmpps-activities-management-api
MIT License
app/src/main/java/pt/hventura/mycoktails/cocktails/coctailsMap/CocktailMapViewModel.kt
hventura
473,391,656
false
{"Kotlin": 83087}
package pt.hventura.mycoktails.cocktails.coctailsMap import android.app.Application import androidx.lifecycle.MutableLiveData import org.joda.time.DateTime import pt.hventura.mycoktails.base.BaseViewModel import pt.hventura.mycoktails.data.CocktailsRepositoryImpl /** * I choose to create this viewModel so that in the future i can implement a new feature: * i am thinking in creating GeoFencing. * On user entering geofence i trigger a notification saying user is near a good place for a cocktail. * */ class CocktailMapViewModel(private val app: Application, private val repository: CocktailsRepositoryImpl) : BaseViewModel(app) { var hourOfDay = MutableLiveData(DateTime().hourOfDay) }
0
Kotlin
0
0
bf31fdaa3d85b22495056db3723a91225a8d05a0
700
MyCocktails
MIT License
app/src/main/java/com/example/cookingrecipe/apidata/AnalyzedInstruction.kt
real-Darkshadow
571,245,039
false
null
package com.example.cookingrecipe.apidata data class AnalyzedInstruction( val name: String, val steps: List<Step> )
0
Kotlin
0
0
35115fa9998bbd10bdd8d14c4916478bdeaf5a72
124
CookingRecipe
MIT License
sdk/src/main/kotlin/com/tpay/sdk/internal/paymentMethod/CreditCardAdapter.kt
tpay-com
702,885,281
false
{"Kotlin": 521890}
package com.tpay.sdk.internal.paymentMethod import android.view.ViewGroup import android.widget.LinearLayout import androidx.recyclerview.widget.RecyclerView import com.tpay.sdk.R import com.tpay.sdk.api.models.TokenizedCard import com.tpay.sdk.api.paycard.CreditCardBrand import com.tpay.sdk.designSystem.buttons.ButtonPayCard import com.tpay.sdk.extensions.px import com.tpay.sdk.extensions.updateMargins internal class CreditCardAdapter : RecyclerView.Adapter<CreditCardAdapter.CreditCardViewHolder>() { var creditCardItemListener: CreditCardItemListener? = null private var currentlySelected: CreditCardViewHolder? = null var items: List<TokenizedCard> = emptyList() set(value) { notifyDataSetChanged() field = value } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CreditCardViewHolder { return CreditCardViewHolder(ButtonPayCard(parent.context)) } override fun onBindViewHolder(holder: CreditCardViewHolder, position: Int) { holder.run { bind(items[position]) onClick { currentlySelected?.isSelected = false creditCardItemListener?.onClick(items[position]) isSelected = true currentlySelected = holder } } } override fun getItemCount(): Int = items.size class CreditCardViewHolder(private val payCardButton: ButtonPayCard): RecyclerView.ViewHolder(payCardButton) { fun bind(tokenizedCard: TokenizedCard){ payCardButton.run { payCardBrand = when(tokenizedCard.brand){ CreditCardBrand.MASTERCARD -> ButtonPayCard.PayCardBrand.MASTERCARD CreditCardBrand.VISA -> ButtonPayCard.PayCardBrand.VISA else -> ButtonPayCard.PayCardBrand.NONE } dottedCardNumber = "${context.getString(R.string.pay_card_tail_dots)} ${tokenizedCard.cardTail}" layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) updateMargins(top = HOLDER_MARGIN_TOP) } } var isSelected: Boolean get() = payCardButton.isSelected set(value) { payCardButton.isSelected = value } fun onClick(func: () -> Unit){ payCardButton.setOnClickListener { func() } } companion object { private val HOLDER_MARGIN_TOP = 6.px } } fun interface CreditCardItemListener { fun onClick(tokenizedCard: TokenizedCard) } }
0
Kotlin
1
0
b75aa85efa7cabbd628e95111b770d9b2cc2b639
2,733
tpay-android
MIT License
app/src/main/java/com/revolgenx/anilib/ui/fragment/review/ReviewComposerFragment.kt
rev0lgenX
244,410,204
false
null
package com.revolgenx.anilib.ui.fragment.review import android.content.Context import android.content.res.ColorStateList import android.os.Bundle import android.view.* import android.view.inputmethod.InputMethodManager import androidx.core.os.bundleOf import com.pranavpandey.android.dynamic.support.theme.DynamicTheme import com.revolgenx.anilib.R import com.revolgenx.anilib.data.field.review.ReviewField import com.revolgenx.anilib.common.ui.fragment.BaseToolbarFragment import com.revolgenx.anilib.data.model.review.ReviewModel import com.revolgenx.anilib.common.preference.userId import com.revolgenx.anilib.databinding.MarkwonHelperLayoutBinding import com.revolgenx.anilib.databinding.ReviewComposerFragmentLayoutBinding import com.revolgenx.anilib.infrastructure.repository.util.Status import com.revolgenx.anilib.ui.view.makeToast import com.revolgenx.anilib.util.getClipBoardText import com.revolgenx.anilib.ui.view.util.attachHelperToView import com.revolgenx.anilib.ui.viewmodel.review.ReviewComposerViewModel import io.noties.markwon.editor.MarkwonEditorTextWatcher import org.koin.androidx.viewmodel.ext.android.viewModel class ReviewComposerFragment : BaseToolbarFragment<ReviewComposerFragmentLayoutBinding>() { companion object { private const val REVIEW_MEDIA_ID_KEY = "REVIEW_MEDIA_ID_KEY" fun newInstance(mediaId: Int) = ReviewComposerFragment().also { it.arguments = bundleOf(REVIEW_MEDIA_ID_KEY to mediaId) } } override var titleRes: Int? = R.string.review_composer private val viewModel by viewModel<ReviewComposerViewModel>() private val reviewMediaId get() = arguments?.getInt(REVIEW_MEDIA_ID_KEY) override var setHomeAsUp: Boolean = true override val menuRes: Int = R.menu.review_composer_menu private var privateReviewMenu: MenuItem? = null private var deleteReviewMenu: MenuItem? = null private var saveReviewMenu: MenuItem? = null override fun bindView( inflater: LayoutInflater, parent: ViewGroup? ): ReviewComposerFragmentLayoutBinding { return ReviewComposerFragmentLayoutBinding.inflate(inflater, parent, false) } override fun onToolbarInflated() { val menu = getBaseToolbar().menu privateReviewMenu = menu.findItem(R.id.privateReview) deleteReviewMenu = menu.findItem(R.id.deleteReview) saveReviewMenu = menu.findItem(R.id.saveReview) deleteReviewMenu!!.isVisible = false updatePrivateToolbar() } override fun onToolbarMenuSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.privateReview -> { item.setIcon(if (item.isChecked) R.drawable.ic_eye else R.drawable.ic_private) item.isChecked = !item.isChecked viewModel.field.model?.private = item.isChecked true } R.id.deleteReview -> { deleteReview() true } R.id.saveReview -> { saveReview() true } else -> return super.onOptionsItemSelected(item) } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel.field.mediaId = reviewMediaId ?: return viewModel.field.userId = requireContext().userId() viewModel.reviewLiveData.observe(viewLifecycleOwner) { res -> when (res.status) { Status.SUCCESS -> { showLoading(false) if (viewModel.field.model == null) { if (res.data != null) { deleteReviewMenu!!.isVisible = true viewModel.field.model = res.data updateView() } else { viewModel.field.model = ReviewModel() } binding.writeReviewEt.setSelection(binding.writeReviewEt.length()) binding.writeReviewEt.requestFocus() (requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.showSoftInput( binding.writeReviewEt, 0 ) } } Status.ERROR -> { showError() } Status.LOADING -> { showLoading(true) } } } updateTheme() initEditText() if (savedInstanceState == null) { viewModel.getReview() } } private fun initEditText() { attachHelperToView( MarkwonHelperLayoutBinding.bind(binding.markwonHelper.markdownHelperLayout), binding.writeReviewEt ) binding.summaryPasteIv.setOnClickListener { binding.reviewSummaryEt.append(requireContext().getClipBoardText()) } } private fun updateTheme() { binding.reviewSummaryTextInputLayout.counterTextColor = ColorStateList.valueOf(DynamicTheme.getInstance().get().accentColor) binding.writeReviewTextInputLayout.counterTextColor = ColorStateList.valueOf(DynamicTheme.getInstance().get().accentColor) } private fun updateView() { viewModel.field.model?.apply { updatePrivateToolbar() summary?.let { binding.reviewSummaryEt.setText(it) } binding.writeReviewEt.setText(body) score?.let { binding.reviewScorePlusMinusTv.setCounter(it.toDouble()) } } } private fun updatePrivateToolbar() { viewModel.field.model?.apply { privateReviewMenu?.setIcon(if (private == true) R.drawable.ic_private else R.drawable.ic_eye) privateReviewMenu?.isChecked = private ?: false } } private fun showLoading(b: Boolean) { binding.resourceStatusLayout.resourceStatusContainer.visibility = if (b) View.VISIBLE else View.GONE binding.resourceStatusLayout.resourceProgressLayout.progressLayout.visibility = if (b) View.VISIBLE else View.GONE binding.resourceStatusLayout.resourceErrorLayout.errorLayout.visibility = View.GONE } private fun showError() { binding.resourceStatusLayout.resourceStatusContainer.visibility = View.VISIBLE binding.resourceStatusLayout.resourceErrorLayout.errorLayout.visibility = View.VISIBLE binding.resourceStatusLayout.resourceProgressLayout.progressLayout.visibility = View.GONE } private fun saveReview() { viewModel.field.type = ReviewField.ReviewFieldType.MUTATE if (!updateModel()) return viewModel.saveReview { when (it.status) { Status.SUCCESS -> { showLoading(false) finishActivity() } Status.LOADING -> { showLoading(true) } Status.ERROR -> { showLoading(false) makeToast(R.string.operation_failed, icon = R.drawable.ic_error) } } } } private fun deleteReview() { viewModel.field.type = ReviewField.ReviewFieldType.DELETE viewModel.deleteReview { when (it.status) { Status.SUCCESS -> { showLoading(false) finishActivity() } Status.LOADING -> { showLoading(true) } Status.ERROR -> { showLoading(false) makeToast(R.string.operation_failed, icon = R.drawable.ic_error) } } } } private fun updateModel(): Boolean { val reviewLength = binding.writeReviewEt.length() if (reviewLength < 2201) { binding.writeReviewTextInputLayout.error = getString(R.string.check_character_length) return false } val summaryLength = binding.reviewSummaryEt.length() if (summaryLength < 21 || summaryLength > 120) { binding.reviewSummaryTextInputLayout.error = getString(R.string.check_character_length) return false } viewModel.field.model?.apply { summary = binding.reviewSummaryEt.text.toString() body = binding.writeReviewEt.text.toString() score = binding.reviewScorePlusMinusTv.counterHolder.toInt() } return true } }
3
Kotlin
1
24
355d2b5510682d869f18e0113453237af8a1f1cc
8,780
AniLib
Apache License 2.0
core/src/main/java/com/gerosprime/gylog/models/workouts/history/WorkoutExerciseHistoryLoader.kt
gerosprime
213,372,637
false
{"Gradle": 12, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 11, "Batchfile": 1, "Markdown": 1, "INI": 9, "Proguard": 10, "Kotlin": 326, "XML": 133, "Java": 11}
package com.gerosprime.gylog.models.workouts.history import io.reactivex.Single interface WorkoutExerciseHistoryLoader { fun load(workoutId : Long, exerciseId : Long) : Single<WorkoutExerciseHistoryResult> }
0
Kotlin
0
1
a775377e6a8bdb81e405eb1b04ca5fd14f5dd9c6
213
gylog-android-app
Apache License 2.0
common/src/main/kotlin/net/spaceeye/vmod/toolgun/modes/state/ConnectionMode.kt
SuperSpaceEye
751,999,893
false
null
package net.spaceeye.vmod.toolgun.modes.state import net.minecraft.world.entity.player.Player import net.minecraft.world.level.Level import net.spaceeye.vmod.constraintsManaging.addFor import net.spaceeye.vmod.constraintsManaging.extensions.RenderableExtension import net.spaceeye.vmod.constraintsManaging.makeManagedConstraint import net.spaceeye.vmod.constraintsManaging.types.ConnectionMConstraint import net.spaceeye.vmod.limits.DoubleLimit import net.spaceeye.vmod.limits.ServerLimits import net.spaceeye.vmod.rendering.types.A2BRenderer import net.spaceeye.vmod.toolgun.modes.gui.ConnectionGUI import net.spaceeye.vmod.toolgun.modes.hud.ConnectionHUD import net.spaceeye.vmod.networking.SerializableItem.get import net.spaceeye.vmod.toolgun.modes.* import net.spaceeye.vmod.toolgun.modes.extensions.* import net.spaceeye.vmod.toolgun.modes.util.PositionModes import net.spaceeye.vmod.toolgun.modes.util.serverRaycast2PointsFnActivation import net.spaceeye.vmod.utils.* import org.valkyrienskies.core.api.ships.ServerShip import org.valkyrienskies.core.api.ships.properties.ShipId import java.awt.Color class ConnectionMode: ExtendableToolgunMode(), ConnectionGUI, ConnectionHUD { var compliance: Double by get(0, 1e-20, {ServerLimits.instance.compliance.get(it)}) var maxForce: Double by get(1, 1e10, {ServerLimits.instance.maxForce.get(it)}) var width: Double by get(2, .2, {DoubleLimit(0.01).get(it)}) //TODO var color: Color by get(3, Color(62, 62, 62, 255)) var fixedDistance: Double by get(4, -1.0, {ServerLimits.instance.fixedDistance.get(it)}) var connectionMode: ConnectionMConstraint.ConnectionModes by get(5, ConnectionMConstraint.ConnectionModes.FIXED_ORIENTATION) var primaryFirstRaycast: Boolean by get(6, false) var posMode = PositionModes.NORMAL var precisePlacementAssistSideNum = 3 var previousResult: RaycastFunctions.RaycastResult? = null fun activatePrimaryFunction(level: Level, player: Player, raycastResult: RaycastFunctions.RaycastResult) = serverRaycast2PointsFnActivation(posMode, precisePlacementAssistSideNum, level, raycastResult, { if (previousResult == null || primaryFirstRaycast) { previousResult = it; Pair(false, null) } else { Pair(true, previousResult) } }, ::resetState) { level, shipId1, shipId2, ship1, ship2, spoint1, spoint2, rpoint1, rpoint2, prresult, rresult -> level.makeManagedConstraint(ConnectionMConstraint( spoint1, spoint2, rpoint1, rpoint2, ship1, ship2, shipId1, shipId2, compliance, maxForce, fixedDistance, connectionMode, listOf(prresult.blockPosition, rresult.blockPosition), ).addExtension(RenderableExtension(A2BRenderer( ship1?.id ?: -1L, ship2?.id ?: -1L, spoint1, spoint2, color, width )))){it.addFor(player)} resetState() } override fun eResetState() { previousResult = null primaryFirstRaycast = false } companion object { val paNetworkingObj = PlacementAssistNetworking("connection_networking") init { ToolgunModes.registerWrapper(ConnectionMode::class) { it.addExtension<ConnectionMode> { BasicConnectionExtension<ConnectionMode>("connection_mode" ,allowResetting = true ,primaryFunction = { inst, level, player, rr -> inst.activatePrimaryFunction(level, player, rr) } ,primaryClientCallback = { inst -> inst.primaryFirstRaycast = !inst.primaryFirstRaycast; inst.refreshHUD() } ,blockPrimary = {inst -> inst.getExtensionOfType<PlacementAssistExtension>().paStage != ThreeClicksActivationSteps.FIRST_RAYCAST} ,blockSecondary = {inst -> inst.primaryFirstRaycast} ) }.addExtension<ConnectionMode> { BlockMenuOpeningExtension<ConnectionMode> { inst -> inst.primaryFirstRaycast } }.addExtension<ConnectionMode> { PlacementAssistExtension(true, {mode -> it.posMode = mode}, {num -> it.precisePlacementAssistSideNum = num}, paNetworkingObj, { spoint1: Vector3d, spoint2: Vector3d, rpoint1: Vector3d, rpoint2: Vector3d, ship1: ServerShip, ship2: ServerShip?, shipId1: ShipId, shipId2: ShipId, rresults: Pair<RaycastFunctions.RaycastResult, RaycastFunctions.RaycastResult>, paDistanceFromBlock: Double -> ConnectionMConstraint( spoint1, spoint2, rpoint1, rpoint2, ship1, ship2, shipId1, shipId2, it.compliance, it.maxForce, it.fixedDistance, it.connectionMode, listOf(rresults.first.blockPosition, rresults.second.blockPosition), rresults.second.worldNormalDirection!! ) } ) } } } } }
2
null
9
6
1b54435e7b48ffae90a937d7ce22dc053fc95947
5,063
VMod
MIT License
app/src/main/java/com/baserecycleradapter/example/advance/vh/HeaderVH.kt
kamranahmadhadi
324,846,118
false
null
package com.baserecycleradapter.example.advance.vh import android.view.View import android.widget.TextView import com.base.recycleradapter.BaseViewHolder import com.baserecycleradapter.example.R import com.baserecycleradapter.example.advance.model.Header class HeaderVH(view: View) : BaseViewHolder<Header>(view) { private val headerTextView: TextView = view.findViewById(R.id.headerTextView) override fun bindData(data: Header, position: Int) { headerTextView.text = data.title } }
0
Kotlin
0
0
5f13ef649914fa9a59c273104d1b8a89b0403d32
505
BaseRecyclerAdapter
Apache License 2.0
app/src/main/java/com/alirezaafkar/phuzei/injection/module/NetworkModule.kt
seiyria
295,443,909
true
{"Kotlin": 66614}
package com.seiyria.reuuzei.injection.module import com.seiyria.reuuzei.API_SCOPE import com.seiyria.reuuzei.AUTHORIZATION import com.seiyria.reuuzei.BASE_API_URL import com.seiyria.reuuzei.BASE_URL import com.seiyria.reuuzei.BuildConfig import com.seiyria.reuuzei.CODE import com.seiyria.reuuzei.KEY_CLIENT_ID import com.seiyria.reuuzei.KEY_REDIRECT_URI import com.seiyria.reuuzei.KEY_RESPONSE_TYPE import com.seiyria.reuuzei.KEY_SCOPE import com.seiyria.reuuzei.REDIRECT_URI import com.seiyria.reuuzei.SCHEME import com.seiyria.reuuzei.data.api.AlbumsApi import com.seiyria.reuuzei.data.api.PhotosApi import com.seiyria.reuuzei.data.api.TokenApi import com.seiyria.reuuzei.data.pref.AppPreferences import com.seiyria.reuuzei.data.pref.token import com.seiyria.reuuzei.injection.qualifier.AuthorizationInterceptor import com.seiyria.reuuzei.injection.qualifier.LoggingInterceptor import com.seiyria.reuuzei.util.TokenAuthenticator import com.google.gson.Gson import com.google.gson.GsonBuilder import dagger.Module import dagger.Provides import okhttp3.HttpUrl import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit import javax.inject.Singleton /** * Created by <NAME> on 16/3/2018AD. */ @Module(includes = [DataModule::class]) class NetworkModule { @Provides @Singleton fun provideRetrofit( okHttpClient: OkHttpClient, gsonFactory: GsonConverterFactory, authenticator: TokenAuthenticator, rxJavaFactory: RxJava2CallAdapterFactory ): Retrofit { val client = okHttpClient.newBuilder() .authenticator(authenticator).build() return Retrofit.Builder() .baseUrl(BASE_API_URL) .client(client) .addConverterFactory(gsonFactory) .addCallAdapterFactory(rxJavaFactory) .build() } @Provides @Singleton fun provideOkHttpClient( @LoggingInterceptor loggingInterceptor: Interceptor, @AuthorizationInterceptor authorizationInterceptor: Interceptor ): OkHttpClient { return OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .addInterceptor(authorizationInterceptor) .readTimeout(15, TimeUnit.SECONDS) .writeTimeout(15, TimeUnit.SECONDS) .connectTimeout(15, TimeUnit.SECONDS) .build() } @Provides @Singleton fun provideRxJavaFactory(): RxJava2CallAdapterFactory { return RxJava2CallAdapterFactory.create() } @Provides @Singleton fun provideGson(): Gson { return GsonBuilder() .setDateFormat("yyyy-MM-dd HH:mm:ss") .create() } @Provides @Singleton fun provideGsonFactory(gson: Gson): GsonConverterFactory { return GsonConverterFactory.create(gson) } @Provides @Singleton @LoggingInterceptor fun provideLoggingInterceptor(): Interceptor { return HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY) } @Provides @Singleton @AuthorizationInterceptor fun provideAuthorizationInterceptor(prefs: AppPreferences): Interceptor { return Interceptor { val original = it.request() val request = original.newBuilder() .header(AUTHORIZATION, prefs.token()) .build() return@Interceptor it.proceed(request) } } @Provides fun provideAuthUrl(): HttpUrl { return HttpUrl.Builder() .scheme(SCHEME) .host(BASE_URL) .addPathSegments("o/oauth2/v2/auth") .addQueryParameter(KEY_SCOPE, API_SCOPE) .addQueryParameter(KEY_RESPONSE_TYPE, CODE) .addQueryParameter(KEY_REDIRECT_URI, REDIRECT_URI) .addQueryParameter(KEY_CLIENT_ID, BuildConfig.CLIENT_ID) .build() } @Provides fun provideTokenAuthenticator( gson: Gson, client: OkHttpClient, prefs: AppPreferences ): TokenAuthenticator { return TokenAuthenticator(gson, client, prefs) } @Provides @Singleton fun provideTokenApi(retrofit: Retrofit): TokenApi { return retrofit.create(TokenApi::class.java) } @Provides @Singleton fun provideAlbumsApi(retrofit: Retrofit): AlbumsApi { return retrofit.create(AlbumsApi::class.java) } @Provides @Singleton fun providePhotosApi(retrofit: Retrofit): PhotosApi { return retrofit.create(PhotosApi::class.java) } }
0
Kotlin
0
0
6dc14696007dde5b9f93b7d6a0e87f3961e0dacc
4,741
reuuzei
Apache License 2.0
server/src/main/kotlin/com/asadmshah/rplace/server/Server.kt
asadmshah
93,749,947
false
null
package com.asadmshah.rplace.server import com.asadmshah.rplace.pubsub.PubSubClientModule import io.undertow.Undertow fun main(args: Array<String>) { val component = DaggerDIComponent .builder() .pubSubClientModule(PubSubClientModule()) .build() Undertow.builder() .addHttpListener(80, "0.0.0.0") .setHandler(component.rootHandler()) .build() .start() }
0
Kotlin
0
0
17f33f12c98a4ef36f365d3ea9a9da0f7c2220f2
449
rplace-server
The Unlicense
components/src/main/java/com/mercadolibre/android/andesui/snackbar/duration/AndesSnackbarDurationInterface.kt
jorGonzalez291292
296,400,886
false
null
package com.mercadolibre.android.andesui.snackbar.duration /** * Defines all types related properties that an [AndesSnackbar] needs to be drawn properly. * Those properties change depending on the style of the tag. */ internal interface AndesSnackbarDurationInterface { /** * Returns a duration for the snackbar. */ fun duration(): Int } internal class AndesSnackbarShortDuration : AndesSnackbarDurationInterface { override fun duration() = 3000 } internal class AndesSnackbarNormalDuration : AndesSnackbarDurationInterface { override fun duration() = 6000 } internal class AndesSnackbarLongDuration : AndesSnackbarDurationInterface { override fun duration() = 10000 }
0
null
0
1
5b1d7b395cb60073c044365fef9d0c205c8b68cb
707
fury_andesui-android
MIT License
virtue-storage-kv/src/jsMain/kotlin/com/eygraber/virtue/storage/kv/VirtueKeyValueStorage.js.kt
eygraber
807,438,503
false
{"Kotlin": 140635, "Shell": 1747}
package com.eygraber.virtue.storage.kv import com.eygraber.virtue.paths.VirtuePaths import io.github.xxfast.kstore.KStore import io.github.xxfast.kstore.storage.storeOf internal actual fun createStore( paths: VirtuePaths, name: String, ): KStore<List<KeyValue>> = storeOf(name)
1
Kotlin
0
4
9e07f30a9b7f2e74638c22b22fa48a4156ae540e
284
virtue
MIT License
src/main/kotlin/io/github/gaming32/mckt/nbt/NbtTagType.kt
mckt-Minecraft
532,076,162
false
null
package io.github.gaming32.mckt.nbt @RequiresOptIn(level = RequiresOptIn.Level.ERROR) private annotation class DontUse @DontUse object NbtTagType { const val NULL = 0 const val BYTE = 1 const val SHORT = 2 const val INT = 3 const val LONG = 4 const val FLOAT = 5 const val DOUBLE = 6 const val BYTE_ARRAY = 7 const val STRING = 8 const val LIST = 9 const val COMPOUND = 10 const val INT_ARRAY = 11 const val LONG_ARRAY = 12 const val ANY_NUMBER = 99 }
0
Kotlin
0
2
98e88af4f54a12faeea2543c4bbdc950dd744092
510
mckt
MIT License
kotlin/kotlin-and-android-development-featuring-jetpack/chapter-9/code-to-copy/standings/StandingsListItem.kt
hermantai
24,401,146
false
null
package dev.mfazio.abl.standings import dev.mfazio.abl.teams.Division sealed class StandingsListItem { abstract val id: String data class TeamItem(val uiTeamStanding: UITeamStanding) : StandingsListItem() { override val id = uiTeamStanding.teamId } data class Header(val division: Division) : StandingsListItem() { override val id = division.name } }
2
null
1
1
87f62edef85ff947c8b8f014dfd231cbf7cab021
390
samples
Apache License 2.0
app/src/main/java/com/dicoding/asclepius/view/news/NewsActivity.kt
Pavelmez
802,382,087
false
{"Kotlin": 29615}
package com.dicoding.asclepius.view.news import android.os.Bundle import android.widget.ImageView import android.widget.TextView import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.bumptech.glide.Glide import com.dicoding.asclepius.R class NewsActivity : AppCompatActivity() { private lateinit var imageView: ImageView private lateinit var titleText: TextView private lateinit var descripText: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_news) imageView = findViewById(R.id.imageView) titleText = findViewById(R.id.titleText) descripText = findViewById(R.id.descripText) // Get data from intent val title = intent.getStringExtra("title") val description = intent.getStringExtra("description") val imageUrl = intent.getStringExtra("imageUrl") // Set data to views titleText.text = title descripText.text = description Glide.with(this).load(imageUrl).into(imageView) } }
0
Kotlin
0
0
7cf6a739ae0e8e494d93408c8819a41a4ced463a
1,216
Basic-Cancer-Checker
MIT License
app/common/src/commonJvmMain/kotlin/com/denchic45/studiversity/domain/usecase/UploadAttachmentToCourseWorkUseCase.kt
denchic45
435,895,363
false
null
package com.denchic45.studiversity.domain.usecase import com.denchic45.studiversity.data.repository.AttachmentRepository import com.denchic45.studiversity.data.repository.CourseElementRepository import com.denchic45.studiversity.domain.Resource import com.denchic45.stuiversity.api.course.element.model.AttachmentHeader import com.denchic45.stuiversity.api.course.element.model.AttachmentRequest import me.tatarka.inject.annotations.Inject import java.util.UUID @Inject class UploadAttachmentToCourseWorkUseCase( private val courseElementRepository: CourseElementRepository, private val attachmentRepository: AttachmentRepository ) { suspend operator fun invoke( courseId: UUID, workId: UUID, request: AttachmentRequest ): Resource<AttachmentHeader> { return courseElementRepository.addAttachmentToWork(courseId, workId, request) } }
0
Kotlin
0
5
02d19321d16604a052f6dd29aa54be29343991e6
887
Studiversity
Apache License 2.0
app/src/main/java/com/example/photohuntcompose/ui/screens/itemhunt/ItemValidationFailureScreen.kt
burhankamran5
834,095,911
false
{"Kotlin": 49177}
package com.example.photohuntcompose.ui.screens.itemhunt import androidx.compose.foundation.layout.Arrangement 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.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.navigation.NavHostController import androidx.navigation.compose.rememberNavController import com.example.photohuntcompose.navigation.HandleBackPressToHome import com.example.photohuntcompose.navigation.Screen import com.example.photohuntcompose.ui.screens.itemhunt.components.HuntProgress import com.example.photohuntcompose.viewmodel.HuntViewModel import com.example.photohuntcompose.viewmodel.PredictionViewModel @Composable fun ItemValidationFailureScreen(navController: NavHostController, huntViewModel: HuntViewModel, predictionViewModel: PredictionViewModel ) { HandleBackPressToHome(navController, huntViewModel) val retryCount = remember { mutableStateOf(predictionViewModel.shouldRetry()) } Column( modifier = Modifier .fillMaxSize() .padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { Spacer(modifier = Modifier.height(15.dp)) HuntProgress(huntViewModel) Column( modifier = Modifier.weight(1f), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text(text = "🫠", style = MaterialTheme.typography.displayLarge) Spacer(modifier = Modifier.height(16.dp)) Text( text = if (retryCount.value) { "Nope, doesn't look like it." } else { "Nope, doesn't look like it. You've reached your retry limit. Moving to the next item." }, style = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.W500), textAlign = TextAlign.Center) } Row( horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically, ) { OutlinedButton(onClick = { huntViewModel.pickNextItem() predictionViewModel.resetRetryCount() navController.navigate(Screen.Pending.route) }) { Text(text = "Skip") } Spacer(modifier = Modifier.width(8.dp)) Button(onClick = { if (retryCount.value) { predictionViewModel.incrementRetryCount() predictionViewModel.resetPrediction() navController.navigate(Screen.Pending.route) } else { predictionViewModel.resetRetryCount() huntViewModel.pickNextItem() navController.navigate(Screen.Pending.route) } } ) { Text(text = if (retryCount.value) "Try again" else "Next") } } Spacer(modifier = Modifier.height(35.dp)) } } @Preview(showBackground = true) @Composable fun ItemValidationFailureScreenPreview() { val navController = rememberNavController() val huntViewModel = HuntViewModel() val predictionViewModel = PredictionViewModel() ItemValidationFailureScreen(navController, huntViewModel, predictionViewModel) }
0
Kotlin
0
0
f7324dfecd2a4fb6cea0d5390696a04dd4fb8111
4,211
Photo-Hunt-Compose
MIT License
bytebank/src/main/kotlin/br/com/alura/bytebank/arrays/main.kt
FernandoLink
670,308,529
false
null
package br.com.alura.bytebank.arrays import java.math.BigDecimal import java.math.RoundingMode fun main() { val idades: IntArray = intArrayOf(25, 19, 33, 20, 53, 16) idades.forEach { idade -> println(idade) } println(idades.contentToString()) println(idades.max()) println(idades.min()) println(idades.average()) println(idades.all { it >= 18 }) println(idades.any { it <= 18 }) println(idades.filter { it >= 18 }) println(idades.find { it >= 50 }) println(idades.sum()) println(Int.MAX_VALUE) println(Int.MIN_VALUE) println(Int.SIZE_BITS) println(Int.SIZE_BYTES) val salarios: DoubleArray = doubleArrayOf(10000.0, 11000.0, 12000.0, 16000.0) for (indice in salarios.indices) { salarios[indice] += salarios[indice] * 0.1 } println(salarios.contentToString()) salarios.forEachIndexed() { i, salario -> salarios[i] += salario * 0.1 } println(salarios.contentToString()) val contatos = arrayOf("Roberto", "Ana", "Paula") var serie: IntRange = 1.rangeTo(10) for (s in serie) { print("$s ") } println() var numerosPares = 2..100 step 2 for (par in numerosPares) { print("$par ") } println() numerosPares = 2.until(100) step 2 for (par in numerosPares) { print("$par ") } println() val reverso = 100 downTo 0 step 5 reverso.forEach { print("$it ") } println() val intervalo = 1500.0..5000.0 val salario = 4000.0 if (salario in intervalo) { println(true) } else { println(false) } val alfabeto = 'a'..'z' val letra = 'k' if (letra in alfabeto) { println(true) } else { println(false) } val sal = bigDecimalArrayOf("16000.0", "20000.0", "30000.0", "40000.0", "50000.0") println(sal.contentToString()) val aumento = "1.1".toBigDecimal() val salariosComAumento: Array<BigDecimal> = sal.map { salario -> (salario * aumento).setScale(2, RoundingMode.UP) }.toTypedArray() println(salariosComAumento.contentToString()) val gastoInicial = sal.somatoria() println(gastoInicial) val meses = 6.toBigDecimal() println(sal.fold(gastoInicial) { acumulador, salario -> acumulador + (salario * meses).setScale(2, RoundingMode.UP)}) println(sal.sorted().take(3)) println(sal.sorted().takeLast(3).toTypedArray().media()) }
0
Kotlin
0
0
872d9192a741afaa438894698ec0b5e31088434b
2,416
kotlin
MIT License
src/main/kotlin/competition/CompetitionApp.kt
uttran
711,222,508
false
{"Kotlin": 163187, "HTML": 1761}
package competition import MyHandler import MyKey import competition.group.groupSelection import competition.signout.signOut import competition.signout.signOutConfirm import hotKeys import kotlinx.browser.window import kotlinx.coroutines.MainScope import kotlinx.coroutines.await import kotlinx.coroutines.launch import kotlinx.css.BoxSizing import kotlinx.css.Display import kotlinx.css.FlexDirection import kotlinx.css.Position import kotlinx.css.boxSizing import kotlinx.css.display import kotlinx.css.flexDirection import kotlinx.css.height import kotlinx.css.pct import kotlinx.css.position import kotlinx.css.px import kotlinx.css.right import kotlinx.css.top import kotlinx.css.vh import kotlinx.html.js.onClickFunction import react.RBuilder import react.RComponent import react.RProps import react.RState import react.ReactElement import react.setState import styled.css import styled.styledButton import styled.styledDiv suspend fun fetchSource(): List<Thirukkural> { val sourceUrl = "https://raw.githubusercontent.com/dreamuth/dreamuth.github.io/master/resources/thirukkural.json" val sourceData = window.fetch(sourceUrl).await().text().await() val groupsUrl = "https://raw.githubusercontent.com/dreamuth/dreamuth.github.io/master/kids/resources/kids-group-2022-23.json" val groupsData = window.fetch(groupsUrl).await().text().await() val thirukkurals = parseSource(sourceData, groupsData) println("version: 2022-11-04.1") println("Source: $sourceUrl loaded") return thirukkurals } external interface CompetitionAppProps : RProps { var onChange: () -> Unit } external interface CompetitionAppState : RState { var loaded: Boolean var showSignOutConfirm: Boolean var allKurals: List<Thirukkural> var questionState: QuestionState var activeGroup: Group? var searchResultKural: Thirukkural? var selectedKuralMeaning: MutableSet<KuralMeaning> } class CompetitionApp : RComponent<CompetitionAppProps, CompetitionAppState>() { override fun CompetitionAppState.init() { val mainScope = MainScope() mainScope.launch { val source = fetchSource() setState { allKurals = source questionState = createQuestionState(Group.IA, allKurals) selectedKuralMeaning = mutableSetOf(KuralMeaning.SalamanPapa) showSignOutConfirm = false loaded = true println("No of athikarams: ${questionState.athikaramState.targets.size}") println("No of kurals: ${questionState.round2Kurals.size}") window.setInterval(timerHandler(), 1000) } } } private fun createQuestionState(group: Group, thirukkurals: List<Thirukkural>): QuestionState { val targetKurals = thirukkurals.filter { it.group.contains(group) } return QuestionState( selectedGroup = group, selectedRound = Round.I, selectedTopic = Topic.Athikaram, round2Kurals = targetKurals, athikaramState = AthikaramState(targetKurals), kuralState = ThirukkuralState(targetKurals), porulState = ThirukkuralState(targetKurals), firstWordState = FirstWordState(targetKurals), lastWordState = LastWordState(targetKurals), timerState = TimerState(), scoreState = ScoreState() ) } private fun timerHandler(): () -> Unit = { if (state.questionState.timerState.isLive && !state.questionState.timerState.isPaused && state.questionState.timerState.time > 0 ) { setState { questionState.timerState.time-- } } } override fun RBuilder.render() { hotKeys { attrs.keyMap = MyKey(arrayOf("s", "n", "p")) attrs.handlers = MyHandler { setState { when (it.asDynamic()["key"]) { "n" -> onNextClickHandler(questionState) "p" -> onPreviousClickHandler(questionState) } } } styledDiv { css { height = 100.vh display = Display.flex flexDirection = FlexDirection.column boxSizing = BoxSizing.borderBox } styledDiv { css { height = 100.pct position = Position.relative } styledDiv { css { classes = mutableListOf("container-lg pl-0 pr-0") css { height = 100.pct position = Position.relative } } if (state.loaded) { if (state.showSignOutConfirm) { signOutConfirm { onNoClickHandler = { setState { showSignOutConfirm = false } } onYesClickHandler = { setState { showSignOutConfirm = false activeGroup = null } } } } if (state.activeGroup == null) { styledButton { css { classes = mutableListOf("btn btn-outline-primary btn-sm d-none d-sm-block") position = Position.fixed top = 9.px right = 9.px } attrs { onClickFunction = { props.onChange() } } +"திருக்குறள் பயிற்சி" } groupSelection { onGroupClick = { group -> setState { questionState = createQuestionState(group, allKurals) activeGroup = group } } } } else if (!state.showSignOutConfirm) { signOut { onSignOutHandler = { setState { showSignOutConfirm = true } } } person { questionState = state.questionState searchResultKural = state.searchResultKural selectedKuralMeaning = state.selectedKuralMeaning onRoundClick = { round -> setState { if (questionState.selectedRound != round) { questionState.selectedRound = round if (round == Round.I) { questionState.timerState.isLive = false } } } } onTopicClick = { topic -> setState { if (questionState.selectedTopic != topic) { questionState.selectedTopic = topic questionState.timerState.isLive = false } } } onTimerClick = { setState { val timerState = questionState.timerState when { timerState.isLive && timerState.time <= 0 -> resetTimer(questionState, true) timerState.isLive && timerState.isPaused -> timerState.isPaused = false timerState.isLive && !timerState.isPaused -> timerState.isPaused = true else -> timerState.isLive = true } } } onPreviousClick = { setState { onPreviousClickHandler(questionState) } } onWrongClick = { setState { questionState.scoreState.group23Score.round2[questionState.selectedTopic]?.remove( questionState.getCurrentQuestion() ) } } onRightClick = { setState { questionState.scoreState.group23Score.round2[questionState.selectedTopic]?.add( questionState.getCurrentQuestion() ) } } onNextClick = { setState { onNextClickHandler(questionState) } } onIndexClick = { index -> setState { onIndexClickHandler(questionState, index) } } onSearchByKuralNoClick = { kuralNo -> setState { searchResultKural = allKurals.firstOrNull { it.kuralNo == kuralNo } } } onAddKuralClick = { setState { searchResultKural?.let { if (questionState.selectedGroup.type == ScoreType.PottiSuttru) { if (!questionState.scoreState.group23Score.round1.containsKey(it.kuralNo)) { questionState.scoreState.group23Score.round1[it.kuralNo] = Group23Round1Score(it) } } else { if (!questionState.scoreState.group1Score.round1.containsKey(it.kuralNo)) { questionState.scoreState.group1Score.round1[it.kuralNo] = Group1Round1Score(it) } } } searchResultKural = null } } onDeleteKuralClick = { kuralNo -> setState { if (questionState.selectedGroup.type == ScoreType.PottiSuttru) { questionState.scoreState.group23Score.round1.remove(kuralNo) } else { questionState.scoreState.group1Score.round1.remove(kuralNo) } } setState { if (questionState.selectedGroup.type != ScoreType.PottiSuttru) { if (questionState.scoreState.group1Score.round1.isEmpty()) { questionState.scoreState.group1Score.bonus = 0 } } } } onG1Click = { kuralNo, kuralScore -> setState { questionState.scoreState.group1Score.round1[kuralNo] = kuralScore } } onG23Click = { kuralNo, kuralScore -> setState { questionState.scoreState.group23Score.round1[kuralNo] = kuralScore } } onG1BonusClick = { value -> setState { if (questionState.scoreState.group1Score.bonus == value) { questionState.scoreState.group1Score.bonus = 0 } else { questionState.scoreState.group1Score.bonus = value } } } onMuVaradhaClick = { setState { selectedKuralMeaning = if (selectedKuralMeaning.contains(KuralMeaning.MuVaradha)) { val tempList = selectedKuralMeaning.toMutableSet() tempList.remove(KuralMeaning.MuVaradha) tempList } else { val tempList = selectedKuralMeaning.toMutableSet() tempList.add(KuralMeaning.MuVaradha) tempList } } } onSalamanPapaClick = { setState { selectedKuralMeaning = if (selectedKuralMeaning.contains(KuralMeaning.SalamanPapa)) { val tempList = selectedKuralMeaning.toMutableSet() tempList.remove(KuralMeaning.SalamanPapa) tempList } else { val tempList = selectedKuralMeaning.toMutableSet() tempList.add(KuralMeaning.SalamanPapa) tempList } } } onMuKarunanidhiClick = { setState { selectedKuralMeaning = if (selectedKuralMeaning.contains(KuralMeaning.MuKarunanidhi)) { val tempList = selectedKuralMeaning.toMutableSet() tempList.remove(KuralMeaning.MuKarunanidhi) tempList } else { val tempList = selectedKuralMeaning.toMutableSet() tempList.add(KuralMeaning.MuKarunanidhi) tempList } } } } } } } } } } } private fun resetTimer(questionState: QuestionState, isLive: Boolean) { if (isLive) { onNextClickHandler(questionState) } questionState.timerState = TimerState(isLive = isLive) questionState.athikaramState = AthikaramState(questionState.round2Kurals) questionState.kuralState = ThirukkuralState(questionState.round2Kurals) questionState.porulState = ThirukkuralState(questionState.round2Kurals) questionState.firstWordState = FirstWordState(questionState.round2Kurals) questionState.lastWordState = LastWordState(questionState.round2Kurals) questionState.scoreState = ScoreState() } private fun onNextClickHandler(questionState: QuestionState) { when (questionState.selectedTopic) { Topic.Athikaram -> questionState.athikaramState.goNext() Topic.Kural -> questionState.kuralState.goNext() Topic.Porul -> questionState.porulState.goNext() Topic.FirstWord -> questionState.firstWordState.goNext() Topic.LastWord -> questionState.lastWordState.goNext() } } private fun onPreviousClickHandler(questionState: QuestionState) { when (questionState.selectedTopic) { Topic.Athikaram -> questionState.athikaramState.goPrevious() Topic.Kural -> questionState.kuralState.goPrevious() Topic.Porul -> questionState.porulState.goPrevious() Topic.FirstWord -> questionState.firstWordState.goPrevious() Topic.LastWord -> questionState.lastWordState.goPrevious() } } private fun onIndexClickHandler(questionState: QuestionState, index: Int) { when (questionState.selectedTopic) { Topic.Athikaram -> questionState.athikaramState.go(index) Topic.Kural -> questionState.kuralState.go(index) Topic.Porul -> questionState.porulState.go(index) Topic.FirstWord -> questionState.firstWordState.go(index) Topic.LastWord -> questionState.lastWordState.go(index) } } } fun RBuilder.competitionApp(handler: CompetitionAppProps.() -> Unit): ReactElement { return child(CompetitionApp::class) { this.attrs(handler) } }
0
Kotlin
0
0
e77b20d6b486bc673143ad0c2773f816d83364fc
15,729
uttran.github.io
Apache License 2.0
cinescout/people/data/remote/src/commonMain/kotlin/cinescout/people/data/remote/mock/TmdbPeopleMockEngine.kt
fardavide
280,630,732
false
null
package cinescout.people.data.remote.mock import cinescout.network.testutil.respondJson import cinescout.people.data.remote.res.TmdbScreenplayCreditsJson import cinescout.screenplay.domain.sample.TmdbScreenplayIdSample import io.ktor.client.engine.mock.MockEngine import io.ktor.http.Url import io.ktor.http.fullPath fun TmdbPeopleMockEngine() = MockEngine { requestData -> respondJson(getContent(requestData.url)) } private fun getContent(url: Url): String { val fullPath = url.fullPath return when { "/${TmdbScreenplayIdSample.Avatar3.value}/credits" in fullPath -> TmdbScreenplayCreditsJson.Avatar3 "/${TmdbScreenplayIdSample.BreakingBad.value}/credits" in fullPath -> TmdbScreenplayCreditsJson.BreakingBad "/${TmdbScreenplayIdSample.Dexter.value}/credits" in fullPath -> TmdbScreenplayCreditsJson.Dexter "/${TmdbScreenplayIdSample.Grimm.value}/credits" in fullPath -> TmdbScreenplayCreditsJson.Grimm "/${TmdbScreenplayIdSample.Inception.value}/credits" in fullPath -> TmdbScreenplayCreditsJson.Inception "/${TmdbScreenplayIdSample.TheWalkingDeadDeadCity.value}/credits" in fullPath -> TmdbScreenplayCreditsJson.TheWalkingDeadDeadCity "/${TmdbScreenplayIdSample.TheWolfOfWallStreet.value}/credits" in fullPath -> TmdbScreenplayCreditsJson.TheWolfOfWallStreet "/${TmdbScreenplayIdSample.War.value}/credits" in fullPath -> TmdbScreenplayCreditsJson.War else -> throw UnsupportedOperationException(fullPath) } }
14
Kotlin
2
6
f04a22b832397f22065a85af038dd15d90225cde
1,528
CineScout
Apache License 2.0
EmergencyApp/app/src/main/java/com/dicoding/emergencyapp/ui/authentication/signup/SignUpActivity.kt
briancatraguna
364,262,679
false
null
package com.dicoding.emergencyapp.ui.authentication.signup import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Toast import com.dicoding.emergencyapp.R import com.dicoding.emergencyapp.databinding.ActivitySignUpBinding import com.dicoding.emergencyapp.ui.authentication.login.LoginActivity import com.google.android.gms.tasks.OnCompleteListener import com.google.firebase.auth.AuthResult import com.google.firebase.auth.FirebaseAuth class SignUpActivity : AppCompatActivity(),View.OnClickListener { private lateinit var binding: ActivitySignUpBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySignUpBinding.inflate(layoutInflater) setContentView(binding.root) binding.buttonBack.setOnClickListener(this) binding.tvLogin.setOnClickListener(this) binding.buttonSignup.setOnClickListener(this) } override fun onClick(v: View?) { when (v?.id){ R.id.button_back -> { finish() } R.id.tv_login -> { finish() } R.id.button_signup -> { val email = binding.edittextEmail.text.toString().trim() val password = binding.edittextPassword.text.toString().trim() val confirmPassword = binding.edittextConfirmPassword.text.toString().trim() if (email.equals("")){ binding.edittextEmail.error = "Enter email" } else if (password.equals("")){ binding.edittextPassword.error = "Enter password" } else if (confirmPassword.equals("")){ binding.edittextConfirmPassword.error = "Confirm password" } else if (!confirmPassword.equals(password)){ binding.edittextConfirmPassword.error = "Password mismatched" } else { val mAuth: FirebaseAuth = FirebaseAuth.getInstance() mAuth.createUserWithEmailAndPassword(email,password) .addOnCompleteListener(this, OnCompleteListener<AuthResult>(){ if (it.isSuccessful){ Toast.makeText(this,"Account succesfully registered",Toast.LENGTH_SHORT).show() finish() } else { Toast.makeText(this,"Account failed to be registered: ${it.exception}",Toast.LENGTH_SHORT).show() } }) } } } } }
1
Kotlin
2
9
5e2d2f6325650bdf5b406876270dd9dbbfda9491
2,744
SixPackTeamApp
MIT License
buildSrc/src/main/java/Versions.kt
odaridavid
275,939,371
false
null
object Versions { object Kotlin { const val stlibVersion = "1.4.10" const val coroutinesVersion = "1.3.9" } object Jetpack{ const val coreKtxVersion = "1.3.1" const val appCompatVersion = "1.2.0" const val lifecycleKtxVersion = "2.2.0" const val activityKtxVersion = "1.1.0" const val composeVersion = "1.0.0-alpha03" const val hiltVersion = "2.28-alpha" const val hiltLifecycleVersion = "1.0.0-alpha02" } object Material{ const val materialVersion = "1.2.1" } object ThirdParty{ const val okhttpVersion = "4.9.0" const val leakCanaryVersion = "2.4" const val coilVersion = "1.0.0-rc3" const val apolloVersion = "2.4.0" } }
4
Kotlin
0
5
38b632cc6d9c76e9047670e257537012541421f2
772
RickNMortyCompose
Apache License 2.0
src/main/kotlin/voidcaffelatte/varioustnts/tnt/ImpactTNT.kt
voidCaffeLatte
628,475,083
false
null
package voidcaffelatte.varioustnts.tnt import org.bukkit.entity.TNTPrimed import org.bukkit.event.entity.EntityDamageByEntityEvent import org.bukkit.event.entity.EntityExplodeEvent class ImpactTNT( tnt: TNTPrimed, private val power: Double) : TNT { override val id = tnt.uniqueId.toString() override fun onExploded(event: EntityExplodeEvent) { event.blockList().clear() } override fun onDamagedEntity(event: EntityDamageByEntityEvent) { val entity = event.entity val tnt = event.damager val velocity = entity.location.subtract(tnt.location).toVector().normalize().multiply(power) entity.velocity = entity.velocity.add(velocity) event.isCancelled = true } }
0
Kotlin
0
0
f323bfa243a6f45f23cc48de9909abe3006b778f
746
various-tnts
MIT License
src/commonMain/kotlin/fr/amoya/ktaglib/tag/flac/FlacTagParser.kt
moya-a
363,263,644
false
null
package fr.amoya.ktaglib.tag.flac import fr.amoya.ktaglib.tag.Tag import fr.amoya.ktaglib.tag.TagParser /* * fr.amoya.ktaglib.common.parsers.flac * As a part of the Project k-taglib * @Author <NAME> : <<EMAIL>> * Created on 06/05/2021 */ class FlacTagParser : TagParser { override fun parse(rawData: ByteArray): Tag { TODO("Not yet implemented") } }
0
Kotlin
0
1
d3dd69285fa3d1d1efc35e22d5766f5a24a7f248
366
k-taglib
MIT License
kotlin-mui-icons/src/main/generated/mui/icons/material/AirlineSeatReclineExtra.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/AirlineSeatReclineExtra") @file:JsNonModule package mui.icons.material @JsName("default") external val AirlineSeatReclineExtra: SvgIconComponent
12
Kotlin
145
983
a99345a0160a80a7a90bf1adfbfdc83a31a18dd6
228
kotlin-wrappers
Apache License 2.0
app/src/main/java/com/xin/wanandroid/ui/register/RegisterActivity.kt
coolxinxin
294,916,632
false
null
/* * Copyright 2020 Leo * 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.xin.wanandroid.ui.register import androidx.lifecycle.Observer import com.xin.wanandroid.R import com.xin.wanandroid.base.BaseVMActivity import com.xin.wanandroid.ext.setOnNoRepeatClickListener import kotlinx.android.synthetic.main.activity_register.* import kotlinx.android.synthetic.main.common_toolbar.* /** * * █████▒█ ██ ▄████▄ ██ ▄█▀ ██████╗ ██╗ ██╗ ██████╗ * ▓██ ▒ ██ ▓██▒▒██▀ ▀█ ██▄█▒ ██╔══██╗██║ ██║██╔════╝ * ▒████ ░▓██ ▒██░▒▓█ ▄ ▓███▄░ ██████╔╝██║ ██║██║ ███╗ * ░▓█▒ ░▓▓█ ░██░▒▓▓▄ ▄██▒▓██ █▄ ██╔══██╗██║ ██║██║ ██║ * ░▒█░ ▒▒█████▓ ▒ ▓███▀ ░▒██▒ █▄ ██████╔╝╚██████╔╝╚██████╔╝ * ▒ ░ ░▒▓▒ ▒ ▒ ░ ░▒ ▒ ░▒ ▒▒ ▓▒ ╚═════╝ ╚═════╝ ╚═════╝ * ░ ░░▒░ ░ ░ ░ ▒ ░ ░▒ ▒░ * ░ ░ ░░░ ░ ░ ░ ░ ░░ ░ * ░ ░ ░ ░ ░ *@author : Leo *@date : 2020/9/11 16:40 *@since : <EMAIL> *@desc : */ class RegisterActivity : BaseVMActivity<RegisterViewModel>() { override fun getViewModelClass(): Class<RegisterViewModel> = RegisterViewModel::class.java override fun initLayoutView(): Int = R.layout.activity_register override fun initEvent() { setSupportActionBar(toolbar) supportActionBar?.setDisplayShowTitleEnabled(false) btRegister.setOnNoRepeatClickListener { val registerAccount = etRegisterAccount.text.toString() val registerPassword = etRegisterPassword.text.toString() val registerRePassword = etRegisterRepassword.text.toString() when { registerAccount.isEmpty() -> showErrorDialog("账号不能为空") registerPassword.isEmpty() || registerRePassword.isEmpty() -> showErrorDialog("密码不能为空") registerPassword != registerRePassword -> { etRegisterPassword.text?.clear() etRegisterRepassword.text?.clear() showErrorDialog("两次密码不一致,请确定密码") } else -> mViewModel.register(registerAccount, registerPassword, registerRePassword) } } } override fun initData() { mViewModel.apply { registerState.observe(this@RegisterActivity, Observer { if (it) finish() }) } } }
0
Kotlin
0
3
fbb65064bee0b3208a0b69f4feaa49c01818f854
2,874
WanAndroid-JetpackMvvm
Apache License 2.0
src/main/kotlin/polimorphism/Animal.kt
softbluecursoscode
603,710,984
false
{"Kotlin": 30194}
package polimorphism fun main() { val a: Dog = Dog() a.run() a.eat() val b: Animal = Dog() if (b is Dog) { b.run() b.eat() } } abstract class Animal { fun eat() { println("Eating...") } } class Dog : Animal() { fun run() { println("Running...") } } class Cat : Animal() { fun sleep() { println("Sleeping...") } }
0
Kotlin
2
5
d1685053cad799d678364687ea0977d9c727b14d
410
kotlin
MIT License
nebulosa-indi-protocol/src/main/kotlin/nebulosa/indi/protocol/NewBLOBVector.kt
tiagohm
568,578,345
false
{"Kotlin": 2659703, "TypeScript": 482206, "HTML": 231271, "JavaScript": 120088, "SCSS": 11161, "Python": 2817, "Makefile": 445}
package nebulosa.indi.protocol import java.io.PrintStream @Suppress("CanSealedSubClassBeObject") class NewBLOBVector : NewVector<OneBLOB>(), BLOBVector<OneBLOB> { override fun writeTo(stream: PrintStream) = stream.writeXML( "newBLOBVector", elements, "device", device, "name", name, "timestamp", timestamp, ) }
2
Kotlin
2
4
a579e15d2a2aa239965bc0f1c75c04eef74dc243
354
nebulosa
MIT License
js/js.translator/testData/incremental/invalidation/companionInlineFunction/main/m.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}
fun box(stepId: Int, isWasm: Boolean): String { when (stepId) { 0, 1, 2, 3, 4 -> if (foo() != stepId) return "Fail" 5 -> if (foo() != 4) return "Fail" else -> return "Unkown" } return "OK" }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
227
kotlin
Apache License 2.0
app/src/main/java/com/jx3box/ui/search/SearchActivity.kt
JX3BOX
296,293,464
false
{"Gradle": 9, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 7, "Batchfile": 1, "Markdown": 1, "INI": 5, "Proguard": 6, "XML": 143, "Java": 73, "Kotlin": 149, "JSON": 3}
/* * Copyright (C) 2020. jx3box.com * * 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.jx3box.ui.search import com.jx3box.R import com.jx3box.databinding.ActivitySearchBinding import com.jx3box.module_imagebrowser.utils.immersionbar.ImmersionBar import com.jx3box.mvvm.base.BaseVMActivity import org.koin.androidx.viewmodel.ext.android.viewModel /** * @author Carey * @date 2020/10/30 */ class SearchActivity : BaseVMActivity() { private val searchViewModel by viewModel<SearchViewModel>() private val binding by binding<ActivitySearchBinding>(R.layout.activity_search) override fun initData() { } override fun initView() { binding.run { viewModel = searchViewModel } } override fun initImmersionBar() { ImmersionBar.with(this) .statusBarDarkFont(true) .fitsSystemWindows(true) .statusBarColor(R.color.white) .init() } override fun startObserve() { } }
0
Kotlin
0
0
6931ec7f5edc83595f6baeec3063fd9c18759c5f
1,543
jx3box-android
Apache License 2.0
app/src/main/java/com/manhal/movies/repository/DiscoverRepository.kt
Manhal1994
682,047,030
false
null
package com.manhal.movies.repository import android.annotation.SuppressLint import android.util.Log import androidx.annotation.WorkerThread import com.manhal.movies.models.entities.MovieGenre import com.manhal.movies.network.service.TheDiscoverService import com.manhal.movies.persistence.MovieDao import com.manhal.movies.persistence.MovieGenreDao import com.skydoves.sandwich.onError import com.skydoves.sandwich.onException import com.skydoves.sandwich.suspendOnSuccess import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.onCompletion import timber.log.Timber class DiscoverRepository constructor( private val discoverService: TheDiscoverService, private val movieDao: MovieDao, private val movieGenreDao: MovieGenreDao, ) : Repository { init { Timber.d("Injection DiscoverRepository") } @WorkerThread fun loadMovies(page: Int, success: () -> Unit, error: () -> Unit) = flow { var movies = movieDao.getMovieList(page) val movieGenres = arrayListOf<MovieGenre>() if (movies.isEmpty()) { val response = discoverService.fetchDiscoverMovie(page) response.suspendOnSuccess { movies = data.results movies.forEach { movieGenres.clear(); it.page = page for (genreId in it.genre_ids) { movieGenres.add(MovieGenre(genreId.toLong(),it.id)) } movieGenreDao.insertGenreMovieList(movieGenres.toList()) } movieDao.insertMovieList(movies) emit(movies) }.onError { error() }.onException { error() } } else { emit(movies) } }.onCompletion { success() }.flowOn(Dispatchers.IO) @SuppressLint("SuspiciousIndentation") @WorkerThread fun searchMovies(title:String, success: () -> Unit, error: () -> Unit) = flow { val movies = movieDao.searchByTitle(title) emit(movies) }.onCompletion { success() }.flowOn(Dispatchers.IO) @SuppressLint("SuspiciousIndentation") @WorkerThread fun searchMoviesWithGenre(title:String,genresIds:List<Int>, success: () -> Unit, error: () -> Unit) = flow { val ids = arrayListOf<String>() for (it in genresIds) { ids.add(it.toString()) } val movies = movieDao.searchByTitleAndGenre(title,ids) emit(movies) }.onCompletion { success() }.flowOn(Dispatchers.IO) }
0
Kotlin
0
0
a044f3dd507f9d1ec2ffb90c600cb3b2d66706e0
2,399
movies
Apache License 2.0
Android Application/app/src/main/java/com/example/test000/TextVoice2SL.kt
OmarHany23
677,533,253
false
{"Kotlin": 51297, "PureBasic": 13931, "Python": 10215}
package com.example.test000 import android.Manifest import android.annotation.SuppressLint import android.app.DownloadManager import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Bundle import android.os.Environment import android.speech.RecognitionListener import android.speech.RecognizerIntent import android.speech.SpeechRecognizer import android.util.Log import android.widget.* import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.chaquo.python.PyException import com.chaquo.python.PyObject import com.chaquo.python.Python import com.chaquo.python.android.AndroidPlatform import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.firebase.firestore.DocumentReference import com.google.firebase.firestore.FirebaseFirestore import okhttp3.* import java.io.File import java.text.SimpleDateFormat import java.util.* import android.content.Context import android.content.SharedPreferences class TextVoice2SL : AppCompatActivity() { private lateinit var documentRef: DocumentReference private var storedVideos = mutableListOf<File>() private lateinit var correctedStatement: String private lateinit var wordsList: List<String> internal var currentTranslationLanguage: String = "" private val prefsName = "MyPrefs" private val isFirstLaunch = "isFirstLaunch" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_textvoice2sl) val sharedPref: SharedPreferences = getSharedPreferences(prefsName, Context.MODE_PRIVATE) val isFirstLaunch: Boolean = sharedPref.getBoolean(isFirstLaunch, true) if (isFirstLaunch) { // If it's the first launch, start the desired activity or fragment startActivity(Intent(this, OnBoardingMain::class.java)) // Update the shared preference value to indicate that the page has been visited val editor: SharedPreferences.Editor = sharedPref.edit() editor.putBoolean(this.isFirstLaunch, false) editor.apply() } else { // It's not the first launch, proceed with your regular flow val intent = intent // Check if the intent contains an extra with key "currentTranslationLanguage" if (intent.hasExtra("currentTranslationLanguage")) { currentTranslationLanguage = intent.getStringExtra("currentTranslationLanguage")!! } val languagesOptions = findViewById<ImageView>(R.id.languagesMenu) languagesOptions.setOnClickListener { val popupMenu = PopupMenu(this, it) popupMenu.setOnMenuItemClickListener { item -> when (item.itemId) { R.id.englishLanguage -> { currentTranslationLanguage = "En" true } R.id.arabicLanguage -> { currentTranslationLanguage = "Ar" true } else -> { false } } } popupMenu.inflate(R.menu.menu_main) popupMenu.show() } val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView) bottomNavigationView.selectedItemId = R.id.signifyBtn bottomNavigationView.setOnItemSelectedListener { item -> when (item.itemId) { R.id.signifyBtn -> true R.id.tranSignBtn -> { val int = Intent(applicationContext, Image2Text::class.java) int.putExtra("currentTranslationLanguage", currentTranslationLanguage) startActivity(int) overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left) finish() true } R.id.tranSignBetaBtn -> { val int = Intent(applicationContext, Video2Text::class.java) int.putExtra("currentTranslationLanguage", currentTranslationLanguage) startActivity(int) overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left) finish() true } else -> false } } val editText = findViewById<EditText>(R.id.editTextTextMultiLine) val transButton = findViewById<Button>(R.id.trans_button) transButton.setOnClickListener { transText(editText) } val speech2TxtBtn = findViewById<ImageButton>(R.id.micButton) speech2TxtBtn.setOnClickListener { startSpeechToText(editText) Toast.makeText(this, "Start Listening", Toast.LENGTH_SHORT).show() } val replayBtn = findViewById<ImageButton>(R.id.replayButton) replayBtn.setOnClickListener { playVideos() } } } private fun startSpeechToText(editText: EditText) { // Request permission to use the microphone if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED ) { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.RECORD_AUDIO), 1) return } // Create a SpeechRecognizer instance val speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this) // Create an intent for speech recognition val speechRecognizerIntent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH) // Set the language code based on the translationLanguage variable speechRecognizerIntent.putExtra( RecognizerIntent.EXTRA_LANGUAGE, if (currentTranslationLanguage != "") { if (currentTranslationLanguage == "Ar") "ar-SA" else "en-US" } else "en-US" ) speechRecognizerIntent.putExtra( RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM ) // Set up a listener for the recognition results speechRecognizer.setRecognitionListener(object : RecognitionListener { override fun onReadyForSpeech(params: Bundle?) {} override fun onBeginningOfSpeech() {} override fun onRmsChanged(rmsdB: Float) {} override fun onBufferReceived(buffer: ByteArray?) {} override fun onEndOfSpeech() {} override fun onError(error: Int) {} override fun onResults(results: Bundle?) { val matches = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION) if (matches != null) { editText.setText(matches[0]) } } override fun onPartialResults(partialResults: Bundle?) {} override fun onEvent(eventType: Int, params: Bundle?) {} }) // Start listening for speech speechRecognizer.startListening(speechRecognizerIntent) } private fun transText(editText: EditText) { val userInput = editText.text.toString().lowercase() if (currentTranslationLanguage != "") { if (currentTranslationLanguage == "En") { if (!Python.isStarted()) { Python.start(AndroidPlatform(this)) } val py = Python.getInstance() val module: PyObject = py.getModule("client") try { correctedStatement = module.callAttr("autocorrect_En", userInput) .toJava(String::class.java) editText.setText(correctedStatement) } catch (e: PyException) { Toast.makeText(this, e.message, Toast.LENGTH_LONG).show() } wordsList = correctedStatement.split("\\s+".toRegex()) } else if (currentTranslationLanguage == "Ar") { wordsList = userInput.split("\\s+".toRegex()) } } else { if (!Python.isStarted()) { Python.start(AndroidPlatform(this)) } val py = Python.getInstance() val module: PyObject = py.getModule("client") try { correctedStatement = module.callAttr("autocorrect_En", userInput) .toJava(String::class.java) editText.setText(correctedStatement) } catch (e: PyException) { Toast.makeText(this, e.message, Toast.LENGTH_LONG).show() } wordsList = correctedStatement.split("\\s+".toRegex()) } val firestore = FirebaseFirestore.getInstance() // Replace with your actual Firestore reference if (currentTranslationLanguage != "") { if (currentTranslationLanguage == "En") { documentRef = firestore.collection("English_Videos").document("Videos") } else if (currentTranslationLanguage == "Ar") { documentRef = firestore.collection("Arabic_Videos").document("Videos") } } else { documentRef = firestore.collection("English_Videos").document("Videos") } documentRef.get().addOnSuccessListener { documentSnapshot -> if (documentSnapshot.exists()) { storedVideos.clear() for (word in wordsList) { // Retrieve the value of the field from the document snapshot val videoUrl = documentSnapshot.data?.get(word)?.toString() if (videoUrl != null) { val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date()) val videoFileName = "${word}_${timeStamp}.mp4" val success = downloadVideoFromDrive(videoUrl, videoFileName) } else { Toast.makeText(this, "Can't translate this message", Toast.LENGTH_SHORT) .show() } } playVideos(); } else { Toast.makeText(this, "Can't translate this message", Toast.LENGTH_SHORT).show() //Log.d("Firestore Value", "Document not found") } }.addOnFailureListener { exception -> // Handle any errors that occur during the retrieval Log.e("Firestore Value", "Error: ${exception.message}") } } @SuppressLint("Range") private fun downloadVideoFromDrive(driveUrl: String, fileName: String): Boolean { val downloadManager = getSystemService(DOWNLOAD_SERVICE) as DownloadManager val request = DownloadManager.Request(Uri.parse(driveUrl)) request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE) request.setAllowedOverRoaming(false) request.setTitle(fileName) request.setDescription("Downloading video") request.setMimeType("video/*") request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName) downloadManager.enqueue(request) var query = DownloadManager.Query() query.setFilterByStatus(DownloadManager.STATUS_FAILED or DownloadManager.STATUS_PAUSED or DownloadManager.STATUS_SUCCESSFUL or DownloadManager.STATUS_RUNNING or DownloadManager.STATUS_PENDING) var downloading = true var success = false while (downloading) { val c = downloadManager.query(query) if (c.moveToFirst()) { Log.i("FLAG", "Downloading") val status: Int = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS)) if (status == DownloadManager.STATUS_SUCCESSFUL) { Log.i("FLAG", "done") downloading = false val videoFile = File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName ) if (videoFile.exists()) { storedVideos.add(videoFile) success = true } break } if (status == DownloadManager.STATUS_FAILED) { Log.i("FLAG", "Fail") downloading = false success = false break } } c.close() } return success } private fun playVideos() { val videoView = findViewById<VideoView>(R.id.graphic_videoView) if (storedVideos.isNotEmpty()) { var index = 0 val mediaController = MediaController(this) mediaController.setAnchorView(videoView) videoView.setMediaController(mediaController) val videoUri = Uri.parse(storedVideos[index].absolutePath) videoView.setVideoURI(videoUri) videoView.requestFocus() videoView.setOnCompletionListener { index++ if (index < storedVideos.size) { val nextVideoUri = Uri.parse(storedVideos[index].absolutePath) videoView.setVideoURI(nextVideoUri) videoView.start() } } // only start the video here once all listeners have been set up videoView.start() } else { // Toast.makeText(this, "No video files found", Toast.LENGTH_SHORT).show() } } }
0
Kotlin
0
1
522456c022ceb1d661780e8b7bad59c1702748c6
14,306
Sign-Language-Interpreter
MIT License
plugins/scripting/scripting-compiler/testData/compiler/collectDependencies/leaf.req1.kts
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}
// nothing
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
13
kotlin
Apache License 2.0
ui/widgets/modal-bottom-sheet/src/main/kotlin/com/edricchan/studybuddy/ui/widgets/modalbottomsheet/select/dsl/SelectBottomSheetGroupBuilder.kt
EdricChan03
100,260,817
false
{"Kotlin": 840248, "Ruby": 202}
package com.edricchan.studybuddy.ui.widgets.modalbottomsheet.select.dsl import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.fragment.app.FragmentManager import androidx.lifecycle.LifecycleOwner import com.edricchan.studybuddy.ui.widgets.modalbottomsheet.select.SelectBottomSheetFragment import com.edricchan.studybuddy.ui.widgets.modalbottomsheet.select.model.OptionBottomSheetGroup import com.edricchan.studybuddy.ui.widgets.modalbottomsheet.select.model.OptionBottomSheetItem import com.edricchan.studybuddy.ui.widgets.modalbottomsheet.select.selectBottomSheet import com.edricchan.studybuddy.ui.widgets.modalbottomsheet.select.setSelectSheetFragmentResultListeners @DslMarker annotation class SelectableBottomSheetDsl /** * Builder class to create instances of [OptionBottomSheetItem]. * @property id The unique ID, which should be [android.os.Parcelable]. * @property title The title to be displayed for this item. */ @SelectableBottomSheetDsl class SelectBottomSheetItemBuilder<Id>( val id: Id, val title: String ) { /** The icon's resource, or `null` to not show any icon. */ @DrawableRes var iconRes: Int? = null /** Whether clicking on this item has any effect. */ var enabled: Boolean = true /** Creates the [OptionBottomSheetItem] with the specified options from this builder. */ fun build(): OptionBottomSheetItem<Id> = OptionBottomSheetItem( id = id, title = title, icon = iconRes, enabled = enabled ) } /** * Creates a [OptionBottomSheetItem] with the specified arguments. * @param id Unique ID for this item. This value should be [android.os.Parcelable]. * @param title Title to be displayed for this item. * @param init Options for the [OptionBottomSheetItem]. * @see SelectBottomSheetItemBuilder */ @SelectableBottomSheetDsl fun <Id> item( id: Id, title: String, init: SelectBottomSheetItemBuilder<Id>.() -> Unit ): OptionBottomSheetItem<Id> = SelectBottomSheetItemBuilder(id, title).apply(init).build() @SelectableBottomSheetDsl sealed class SelectBottomSheetGroupBuilder<Id, T : OptionBottomSheetGroup<Id>> { /** The items to be used for this [OptionBottomSheetGroup]. */ val items = mutableListOf<OptionBottomSheetItem<Id>>() /** Whether the items in this group are selectable. */ var enabled: Boolean = true /** * Specifies which item should be selected. * * If this builder takes only a [single-selection][SingleSelectBottomSheetGroupBuilder], * there should **only** be one value that returns `true`. If multiple values return * `true` when passed to this lambda, the first item that returns `true` will be used * as the selected item. */ var isSelected: ((item: OptionBottomSheetItem<Id>, index: Int) -> Boolean)? = null /** * Adds an item to this group with the specified arguments. * * @param selected Whether this item should be initially marked as selected. * If `null` is specified, [isSelected] will be used to determine its selection * state, or `false` otherwise. * @param item The item to add. * @return The added item. */ abstract fun addItem( selected: Boolean? = false, item: OptionBottomSheetItem<Id> ): OptionBottomSheetItem<Id> /** * Adds an item to this group with the specified arguments. * * @param id Unique ID for this item. The value should be [android.os.Parcelable]. * @param title Title to be displayed for this item in the user interface. * @param selected Whether this item should be initially marked as selected. * If `null` is specified, [isSelected] will be used to determine its selection * state, or `false` otherwise. * @param itemInit Additional options for the specified item. * @return The added item. */ open fun addItem( id: Id, title: String, selected: Boolean? = false, itemInit: SelectBottomSheetItemBuilder<Id>.() -> Unit = {} ): OptionBottomSheetItem<Id> { return addItem(selected, item(id, title, itemInit)) } /** * Adds the list of items with their selection status. * * This is the equivalent of the following code: * * ``` * items.forEach { * addItem(it.second, it.first) * } * ``` * * @param items The items to be added, with their selection status. * @return The added items. * @see addItem */ open fun addItems( vararg items: Pair<OptionBottomSheetItem<Id>, Boolean> ): List<OptionBottomSheetItem<Id>> = items.map { addItem(it.second, it.first) } /** Removes the [item] from this group. */ abstract fun removeItem(item: OptionBottomSheetItem<Id>) /** Removes the set of [items] from this group. */ open fun removeItems(vararg items: OptionBottomSheetItem<Id>) { items.forEach(::removeItem) } /** Creates the group [T] with the specified options from this builder. */ abstract fun build(): T } /** * Group builder to create a [OptionBottomSheetGroup.SingleSelect]. * * To create a [OptionBottomSheetGroup.MultiSelect], use [MultiSelectBottomSheetGroupBuilder] * instead. * * Consumers should use the relevant [singleSelectGroup] and [singleSelectBottomSheet] * methods where appropriate. */ class SingleSelectBottomSheetGroupBuilder<Id> : SelectBottomSheetGroupBuilder<Id, OptionBottomSheetGroup.SingleSelect<Id>>() { /** * The item's index in this group which should be initially selected, * or `null` for no initial selection. */ var selectedIndex: Int? = null override fun addItem( selected: Boolean?, item: OptionBottomSheetItem<Id> ): OptionBottomSheetItem<Id> { items += item val index = items.indexOf(item) if (selected == true || isSelected?.invoke(item, index) == true) selectedIndex = index return item } override fun removeItem( item: OptionBottomSheetItem<Id> ) { if (selectedIndex != null && selectedIndex == items.indexOf(item)) { selectedIndex = null } items -= item } /** Creates a [OptionBottomSheetGroup.SingleSelect] with the options from this builder. */ override fun build(): OptionBottomSheetGroup.SingleSelect<Id> = OptionBottomSheetGroup.SingleSelect( items = items.toList(), enabled = enabled, selectedIndex = selectedIndex ) } /** Adds the existing [group]'s items to the receiver [SingleSelectBottomSheetGroupBuilder]. */ fun <Id> SingleSelectBottomSheetGroupBuilder<Id>.addItems( group: OptionBottomSheetGroup.SingleSelect<Id> ) { group.forEach { addItem(group.isChecked(it), it) } } /** * Group builder to create a [OptionBottomSheetGroup.MultiSelect]. * * To create a [OptionBottomSheetGroup.SingleSelect], use [SingleSelectBottomSheetGroupBuilder] * instead. * * Consumers should use the relevant [multiSelectGroup] and [multiSelectBottomSheet] * methods where appropriate. */ class MultiSelectBottomSheetGroupBuilder<Id> : SelectBottomSheetGroupBuilder<Id, OptionBottomSheetGroup.MultiSelect<Id>>() { val selectedIndices = mutableSetOf<Int>() override fun addItem( selected: Boolean?, item: OptionBottomSheetItem<Id> ): OptionBottomSheetItem<Id> { items += item val index = items.indexOf(item) if (selected == true || isSelected?.invoke(item, index) == true) selectedIndices += index return item } override fun removeItem( item: OptionBottomSheetItem<Id> ) { val index = items.indexOf(item) selectedIndices -= index items -= item } override fun build(): OptionBottomSheetGroup.MultiSelect<Id> = OptionBottomSheetGroup.MultiSelect<Id>( items = items.toList(), enabled = enabled, selectedIndices = selectedIndices.toSet() ) } /** Adds the existing [group]'s items to the receiver [MultiSelectBottomSheetGroupBuilder]. */ fun <Id> MultiSelectBottomSheetGroupBuilder<Id>.addItems( group: OptionBottomSheetGroup.MultiSelect<Id> ) { group.forEach { addItem(group.isChecked(it), it) } } /** Creates a [OptionBottomSheetGroup.SingleSelect] using the specified [init] options. */ inline fun <Id> singleSelectGroup( init: SingleSelectBottomSheetGroupBuilder<Id>.() -> Unit ): OptionBottomSheetGroup.SingleSelect<Id> = SingleSelectBottomSheetGroupBuilder<Id>().apply(init).build() /** Creates a [OptionBottomSheetGroup.MultiSelect] using the specified [init] options. */ inline fun <Id> multiSelectGroup( init: MultiSelectBottomSheetGroupBuilder<Id>.() -> Unit ): OptionBottomSheetGroup.MultiSelect<Id> = MultiSelectBottomSheetGroupBuilder<Id>().apply(init).build() /** * Creates a [SelectBottomSheetFragment] set to **single**-selection mode with * the specified options. * * If multi-selection is desired, use [multiSelectBottomSheet] instead. * @param headerTitle Header title to be displayed at the top of the bottom sheet. * @param hideDragHandle Whether the drag handle should be hidden. * @param groupInit Options to configure the [OptionBottomSheetGroup.SingleSelect] * to be used. * @see singleSelectGroup * @see selectBottomSheet * @see showSingleSelectBottomSheet */ inline fun <Id : Any> singleSelectBottomSheet( headerTitle: String, hideDragHandle: Boolean = false, groupInit: SingleSelectBottomSheetGroupBuilder<Id>.() -> Unit ): SelectBottomSheetFragment<Id> = selectBottomSheet( headerTitle = headerTitle, hideDragHandle = hideDragHandle, items = singleSelectGroup(groupInit) ) /** * Shows a [SelectBottomSheetFragment] set to **single**-selection mode with * the specified options, bound to the receiver [FragmentManager]. * * Use [showMultiSelectBottomSheet] instead if multi-selection is desired. * @param headerTitle Header title to be displayed at the top of the bottom sheet. * @param hideDragHandle Whether the drag handle should be hidden. * @param lifecycleOwner [LifecycleOwner] used to configure the * [fragment result listeners][setSelectSheetFragmentResultListeners]. * @param onConfirm Lambda that is invoked when the "Confirm" action is pressed in * the bottom sheet, with the selected item passed as the argument. * @param onCanceled Lambda that is invoked when the "Cancel" option is pressed in * the bottom sheet. * @param groupInit Options to configure the [OptionBottomSheetGroup.SingleSelect] * to be used. * @see singleSelectGroup * @see selectBottomSheet * @see singleSelectBottomSheet * @see setSelectSheetFragmentResultListeners */ inline fun <Id : Any> FragmentManager.showSingleSelectBottomSheet( headerTitle: String, hideDragHandle: Boolean = false, lifecycleOwner: LifecycleOwner, crossinline onConfirm: (selectedItem: OptionBottomSheetItem<Id>) -> Unit = {}, crossinline onCanceled: () -> Unit = {}, groupInit: SingleSelectBottomSheetGroupBuilder<Id>.() -> Unit, ): SelectBottomSheetFragment<Id> = singleSelectBottomSheet( headerTitle = headerTitle, hideDragHandle = hideDragHandle, groupInit = groupInit ).apply { show(this@showSingleSelectBottomSheet, tag) setSelectSheetFragmentResultListeners( lifecycleOwner = lifecycleOwner, onConfirm = { onConfirm(it.single()) }, onCanceled = onCanceled ) } /** * Shows a [SelectBottomSheetFragment] set to **single**-selection mode with * the specified options, bound to the receiver [Fragment]'s * [Fragment.getParentFragmentManager]. * * Use [showMultiSelectBottomSheet] instead if multi-selection is desired. * @param headerTitle Header title to be displayed at the top of the bottom sheet. * @param hideDragHandle Whether the drag handle should be hidden. * @param lifecycleOwner [LifecycleOwner] used to configure the * [fragment result listeners][setSelectSheetFragmentResultListeners]. * @param onConfirm Lambda that is invoked when the "Confirm" action is pressed in * the bottom sheet, with the selected item passed as the argument. * @param onCanceled Lambda that is invoked when the "Cancel" option is pressed in * the bottom sheet. * @param groupInit Options to configure the [OptionBottomSheetGroup.SingleSelect] * to be used. * @see singleSelectGroup * @see selectBottomSheet * @see singleSelectBottomSheet * @see setSelectSheetFragmentResultListeners */ inline fun <Id : Any> Fragment.showSingleSelectBottomSheet( headerTitle: String, hideDragHandle: Boolean = false, lifecycleOwner: LifecycleOwner = viewLifecycleOwner, crossinline onConfirm: (selectedItem: OptionBottomSheetItem<Id>) -> Unit = {}, crossinline onCanceled: () -> Unit = {}, groupInit: SingleSelectBottomSheetGroupBuilder<Id>.() -> Unit ): SelectBottomSheetFragment<Id> = parentFragmentManager.showSingleSelectBottomSheet( headerTitle = headerTitle, hideDragHandle = hideDragHandle, lifecycleOwner = lifecycleOwner, onConfirm = onConfirm, onCanceled = onCanceled, groupInit = groupInit, ) /** * Shows a [SelectBottomSheetFragment] set to **single**-selection mode with * the specified options, bound to the receiver [FragmentActivity]'s * [FragmentActivity.getSupportFragmentManager]. * * Use [showMultiSelectBottomSheet] instead if multi-selection is desired. * @param headerTitle Header title to be displayed at the top of the bottom sheet. * @param hideDragHandle Whether the drag handle should be hidden. * @param lifecycleOwner [LifecycleOwner] used to configure the * [fragment result listeners][setSelectSheetFragmentResultListeners]. * @param onConfirm Lambda that is invoked when the "Confirm" action is pressed in * the bottom sheet, with the selected item passed as the argument. * @param onCanceled Lambda that is invoked when the "Cancel" option is pressed in * the bottom sheet. * @param groupInit Options to configure the [OptionBottomSheetGroup.SingleSelect] * to be used. * @see singleSelectGroup * @see selectBottomSheet * @see singleSelectBottomSheet * @see setSelectSheetFragmentResultListeners */ inline fun <Id : Any> FragmentActivity.showSingleSelectBottomSheet( headerTitle: String, hideDragHandle: Boolean = false, lifecycleOwner: LifecycleOwner = this, crossinline onConfirm: (selectedItems: OptionBottomSheetItem<Id>) -> Unit = {}, crossinline onCanceled: () -> Unit = {}, groupInit: SingleSelectBottomSheetGroupBuilder<Id>.() -> Unit ): SelectBottomSheetFragment<Id> = supportFragmentManager.showSingleSelectBottomSheet( headerTitle = headerTitle, hideDragHandle = hideDragHandle, lifecycleOwner = lifecycleOwner, onConfirm = onConfirm, onCanceled = onCanceled, groupInit = groupInit, ) /** * Shows a [SelectBottomSheetFragment] set to **single**-selection mode with * the specified options, bound to the receiver [Fragment]'s [Fragment.getParentFragmentManager]. * * Use [showMultiSelectBottomSheet] instead if multi-selection is desired. * * This overload allows for a string resource to be used for the [header title][headerTitleRes]. * @param headerTitleRes String resource for the header title to be displayed at the * top of the bottom sheet. * @param hideDragHandle Whether the drag handle should be hidden. * @param lifecycleOwner [LifecycleOwner] used to configure the * [fragment result listeners][setSelectSheetFragmentResultListeners]. * @param onConfirm Lambda that is invoked when the "Confirm" action is pressed in * the bottom sheet, with the selected item passed as the argument. * @param onCanceled Lambda that is invoked when the "Cancel" option is pressed in * the bottom sheet. * @param groupInit Options to configure the [OptionBottomSheetGroup.SingleSelect] * to be used. * @see singleSelectGroup * @see selectBottomSheet * @see singleSelectBottomSheet * @see setSelectSheetFragmentResultListeners */ inline fun <Id : Any> Fragment.showSingleSelectBottomSheet( @StringRes headerTitleRes: Int, hideDragHandle: Boolean = false, lifecycleOwner: LifecycleOwner = viewLifecycleOwner, crossinline onConfirm: (selectedItems: OptionBottomSheetItem<Id>) -> Unit = {}, crossinline onCanceled: () -> Unit = {}, groupInit: SingleSelectBottomSheetGroupBuilder<Id>.() -> Unit ): SelectBottomSheetFragment<Id> = parentFragmentManager.showSingleSelectBottomSheet( headerTitle = getString(headerTitleRes), hideDragHandle = hideDragHandle, groupInit = groupInit, lifecycleOwner = lifecycleOwner, onConfirm = onConfirm, onCanceled = onCanceled ) /** * Shows a [SelectBottomSheetFragment] set to **single**-selection mode with * the specified options, bound to the receiver [FragmentActivity]'s * [FragmentActivity.getSupportFragmentManager]. * * Use [showMultiSelectBottomSheet] instead if multi-selection is desired. * * This overload allows for a string resource to be used for the [header title][headerTitleRes]. * @param headerTitleRes String resource for the header title to be displayed at the * top of the bottom sheet. * @param hideDragHandle Whether the drag handle should be hidden. * @param lifecycleOwner [LifecycleOwner] used to configure the * [fragment result listeners][setSelectSheetFragmentResultListeners]. * @param onConfirm Lambda that is invoked when the "Confirm" action is pressed in * the bottom sheet, with the selected item passed as the argument. * @param onCanceled Lambda that is invoked when the "Cancel" option is pressed in * the bottom sheet. * @param groupInit Options to configure the [OptionBottomSheetGroup.SingleSelect] * to be used. * @see singleSelectGroup * @see selectBottomSheet * @see singleSelectBottomSheet * @see setSelectSheetFragmentResultListeners */ inline fun <Id : Any> FragmentActivity.showSingleSelectBottomSheet( @StringRes headerTitleRes: Int, hideDragHandle: Boolean = false, lifecycleOwner: LifecycleOwner = this, crossinline onConfirm: (selectedItems: OptionBottomSheetItem<Id>) -> Unit = {}, crossinline onCanceled: () -> Unit = {}, groupInit: SingleSelectBottomSheetGroupBuilder<Id>.() -> Unit ): SelectBottomSheetFragment<Id> = supportFragmentManager.showSingleSelectBottomSheet( headerTitle = getString(headerTitleRes), hideDragHandle = hideDragHandle, groupInit = groupInit, lifecycleOwner = lifecycleOwner, onConfirm = onConfirm, onCanceled = onCanceled ) /** * Creates a [SelectBottomSheetFragment] set to **multi**-selection mode with the * specified options. * * If single-selection is desired, use [singleSelectBottomSheet] instead. * @param headerTitle Header title to be displayed at thetop of the bottom sheet. * @param hideDragHandle Whether the drag handle should be hidden. * @param groupInit Options to configure the [OptionBottomSheetGroup.MultiSelect] * to be used. */ inline fun <Id : Any> multiSelectBottomSheet( headerTitle: String, hideDragHandle: Boolean = false, groupInit: MultiSelectBottomSheetGroupBuilder<Id>.() -> Unit ): SelectBottomSheetFragment<Id> = selectBottomSheet( headerTitle = headerTitle, hideDragHandle = hideDragHandle, items = multiSelectGroup(groupInit) ) /** * Shows a [SelectBottomSheetFragment] set to **multi**-selection mode with * the specified options, bound to the receiver [FragmentManager]. * * Use [showSingleSelectBottomSheet] instead if single-selection is desired. * @param headerTitle Header title to be displayed at the top of the bottom sheet. * @param hideDragHandle Whether the drag handle should be hidden. * @param lifecycleOwner [LifecycleOwner] used to configure the * [fragment result listeners][setSelectSheetFragmentResultListeners]. * @param onConfirm Lambda that is invoked when the "Confirm" action is pressed in * the bottom sheet, with the selected item passed as the argument. * @param onCanceled Lambda that is invoked when the "Cancel" option is pressed in * the bottom sheet. * @param groupInit Options to configure the [OptionBottomSheetGroup.SingleSelect] * to be used. * @see multiSelectGroup * @see selectBottomSheet * @see multiSelectBottomSheet * @see setSelectSheetFragmentResultListeners */ inline fun <Id : Any> FragmentManager.showMultiSelectBottomSheet( headerTitle: String, hideDragHandle: Boolean = false, lifecycleOwner: LifecycleOwner, crossinline onConfirm: (selectedItems: Set<OptionBottomSheetItem<Id>>) -> Unit = {}, crossinline onCanceled: () -> Unit = {}, groupInit: MultiSelectBottomSheetGroupBuilder<Id>.() -> Unit ) = multiSelectBottomSheet( headerTitle = headerTitle, hideDragHandle = hideDragHandle, groupInit = groupInit ).apply { show(this@showMultiSelectBottomSheet, tag) setSelectSheetFragmentResultListeners( lifecycleOwner = lifecycleOwner, onConfirm = onConfirm, onCanceled = onCanceled ) } /** * Shows a [SelectBottomSheetFragment] set to **multi**-selection mode with * the specified options, bound to the receiver [Fragment]'s [Fragment.getParentFragmentManager]. * * Use [showSingleSelectBottomSheet] instead if single-selection is desired. * @param headerTitle Header title to be displayed at the top of the bottom sheet. * @param hideDragHandle Whether the drag handle should be hidden. * @param lifecycleOwner [LifecycleOwner] used to configure the * [fragment result listeners][setSelectSheetFragmentResultListeners]. * @param onConfirm Lambda that is invoked when the "Confirm" action is pressed in * the bottom sheet, with the selected item passed as the argument. * @param onCanceled Lambda that is invoked when the "Cancel" option is pressed in * the bottom sheet. * @param groupInit Options to configure the [OptionBottomSheetGroup.SingleSelect] * to be used. * @see multiSelectGroup * @see selectBottomSheet * @see multiSelectBottomSheet * @see setSelectSheetFragmentResultListeners */ inline fun <Id : Any> Fragment.showMultiSelectBottomSheet( headerTitle: String, hideDragHandle: Boolean = false, lifecycleOwner: LifecycleOwner = viewLifecycleOwner, crossinline onConfirm: (selectedItems: Set<OptionBottomSheetItem<Id>>) -> Unit = {}, crossinline onCanceled: () -> Unit = {}, groupInit: MultiSelectBottomSheetGroupBuilder<Id>.() -> Unit ) = parentFragmentManager.showMultiSelectBottomSheet( headerTitle = headerTitle, hideDragHandle = hideDragHandle, lifecycleOwner = lifecycleOwner, onConfirm = onConfirm, onCanceled = onCanceled, groupInit = groupInit ) /** * Shows a [SelectBottomSheetFragment] set to **multi**-selection mode with * the specified options, bound to the receiver [FragmentActivity]'s * [FragmentActivity.getSupportFragmentManager]. * * Use [showSingleSelectBottomSheet] instead if single-selection is desired. * @param headerTitle Header title to be displayed at the top of the bottom sheet. * @param hideDragHandle Whether the drag handle should be hidden. * @param lifecycleOwner [LifecycleOwner] used to configure the * [fragment result listeners][setSelectSheetFragmentResultListeners]. * @param onConfirm Lambda that is invoked when the "Confirm" action is pressed in * the bottom sheet, with the selected item passed as the argument. * @param onCanceled Lambda that is invoked when the "Cancel" option is pressed in * the bottom sheet. * @param groupInit Options to configure the [OptionBottomSheetGroup.SingleSelect] * to be used. * @see multiSelectGroup * @see selectBottomSheet * @see multiSelectBottomSheet * @see setSelectSheetFragmentResultListeners */ inline fun <Id : Any> FragmentActivity.showMultiSelectBottomSheet( headerTitle: String, hideDragHandle: Boolean = false, lifecycleOwner: LifecycleOwner = this, crossinline onConfirm: (selectedItems: Set<OptionBottomSheetItem<Id>>) -> Unit = {}, crossinline onCanceled: () -> Unit = {}, groupInit: MultiSelectBottomSheetGroupBuilder<Id>.() -> Unit ) = supportFragmentManager.showMultiSelectBottomSheet( headerTitle = headerTitle, hideDragHandle = hideDragHandle, lifecycleOwner = lifecycleOwner, onConfirm = onConfirm, onCanceled = onCanceled, groupInit = groupInit ) /** * Shows a [SelectBottomSheetFragment] set to **multi**-selection mode with * the specified options, bound to the receiver [Fragment]'s * [Fragment.getParentFragmentManager]. * * Use [showSingleSelectBottomSheet] instead if single-selection is desired. * * This overload allows for a string resource to be used for the [header title][headerTitleRes]. * @param headerTitleRes String resource for the header title to be displayed at * the top of the bottom sheet. * @param hideDragHandle Whether the drag handle should be hidden. * @param lifecycleOwner [LifecycleOwner] used to configure the * [fragment result listeners][setSelectSheetFragmentResultListeners]. * @param onConfirm Lambda that is invoked when the "Confirm" action is pressed in * the bottom sheet, with the selected item passed as the argument. * @param onCanceled Lambda that is invoked when the "Cancel" option is pressed in * the bottom sheet. * @param groupInit Options to configure the [OptionBottomSheetGroup.SingleSelect] * to be used. * @see multiSelectGroup * @see selectBottomSheet * @see multiSelectBottomSheet * @see setSelectSheetFragmentResultListeners */ inline fun <Id : Any> Fragment.showMultiSelectBottomSheet( @StringRes headerTitleRes: Int, hideDragHandle: Boolean = false, lifecycleOwner: LifecycleOwner = viewLifecycleOwner, crossinline onConfirm: (selectedItems: Set<OptionBottomSheetItem<Id>>) -> Unit = {}, crossinline onCanceled: () -> Unit = {}, groupInit: MultiSelectBottomSheetGroupBuilder<Id>.() -> Unit ) = parentFragmentManager.showMultiSelectBottomSheet( headerTitle = getString(headerTitleRes), hideDragHandle = hideDragHandle, lifecycleOwner = lifecycleOwner, onConfirm = onConfirm, onCanceled = onCanceled, groupInit = groupInit ) /** * Shows a [SelectBottomSheetFragment] set to **multi**-selection mode with * the specified options, bound to the receiver [FragmentActivity]'s * [FragmentActivity.getSupportFragmentManager]. * * Use [showSingleSelectBottomSheet] instead if single-selection is desired. * * This overload allows for a string resource to be used for the [header title][headerTitleRes]. * @param headerTitleRes String resource for the header title to be displayed at * the top of the bottom sheet. * @param hideDragHandle Whether the drag handle should be hidden. * @param lifecycleOwner [LifecycleOwner] used to configure the * [fragment result listeners][setSelectSheetFragmentResultListeners]. * @param onConfirm Lambda that is invoked when the "Confirm" action is pressed in * the bottom sheet, with the selected item passed as the argument. * @param onCanceled Lambda that is invoked when the "Cancel" option is pressed in * the bottom sheet. * @param groupInit Options to configure the [OptionBottomSheetGroup.SingleSelect] * to be used. * @see multiSelectGroup * @see selectBottomSheet * @see multiSelectBottomSheet * @see setSelectSheetFragmentResultListeners */ inline fun <Id : Any> FragmentActivity.showMultiSelectBottomSheet( @StringRes headerTitleRes: Int, hideDragHandle: Boolean = false, lifecycleOwner: LifecycleOwner = this, crossinline onConfirm: (selectedItems: Set<OptionBottomSheetItem<Id>>) -> Unit = {}, crossinline onCanceled: () -> Unit = {}, groupInit: MultiSelectBottomSheetGroupBuilder<Id>.() -> Unit ) = supportFragmentManager.showMultiSelectBottomSheet( headerTitle = getString(headerTitleRes), hideDragHandle = hideDragHandle, lifecycleOwner = lifecycleOwner, onConfirm = onConfirm, onCanceled = onCanceled, groupInit = groupInit )
49
Kotlin
10
16
47f86afce4293cb8d91aa47f40ea40d6fb82fb0b
28,095
studybuddy-android
MIT License
src/main/kotlin/no/nav/helse/grensekomp/integration/brreg/UnderenheterNavnResponse.kt
navikt
346,295,781
false
null
package no.nav.helse.grensekomp.integration.brreg data class UnderenheterNavnResponse( val navn: String )
7
Kotlin
0
0
f2479a2e3a011ab373b2a420fe4d1dc81d621329
110
grensekomp
MIT License
src/main/kotlin/com/intershop/gradle/scm/utils/ScmException.kt
IntershopCommunicationsAG
55,636,958
false
null
/* * Copyright 2020 Intershop Communications AG. * * 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.intershop.gradle.scm.utils /** * SCM exception. */ class ScmException /** * Constructs a {@code ScmException} instance with an error message. * * @param message the error message */(message: String) : RuntimeException(message) { /** * Returns the string representation of this exception. * * @return the string representation of this exception */ override fun toString() : String { val cause = super.cause val msg = super.message if(! msg.isNullOrBlank()) { if(cause != null) { return "$msg ( $cause ) " } return msg } if(cause != null) { return cause.toString() } return "" } }
9
Kotlin
5
9
47514e555036dd71d02935945971b4b8a9161ebe
1,366
scmversion-gradle-plugin
Apache License 2.0
koans/src/commonMain/kotlin/com/rsicarelli/koansbr/conventions/invoke/InvokeKotlin.kt
rsicarelli
678,681,968
false
{"Kotlin": 120164, "Java": 9992, "C#": 8749, "PHP": 7690, "Go": 6648, "TypeScript": 6602, "Python": 6090, "Dart": 6059, "Swift": 5735, "JavaScript": 5732}
/* * SPDX-License-Identifier: MIT * Copyright (c) 2014-2019 JetBrains s.r.o. * Copyright (c) 2023-2023 <NAME> */ package com.rsicarelli.koansbr.conventions.invoke class Invokable { var numberOfInvocations: Int = 0 private set operator fun invoke(): Invokable { numberOfInvocations++ return this } } fun invokeTwice(invokable: Invokable) = invokable()()
0
Kotlin
0
6
ef7a2a3b371975bab10dc98484f109e11bcab95b
397
kotlin-koans-edu-br
MIT License
lib/src/main/kotlin/se/elite/dsc/kafka/JsonMapper.kt
elite-se
270,043,143
false
{"CSS": 215798, "Kotlin": 45557, "Go": 8512, "HTML": 6527, "JavaScript": 3268, "Shell": 2347, "Dockerfile": 2006, "HCL": 1444}
import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.databind.util.StdDateFormat import com.fasterxml.jackson.module.kotlin.registerKotlinModule val jsonMapper = ObjectMapper().apply { registerKotlinModule() disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) setDateFormat(StdDateFormat()) }
0
CSS
0
0
8d6393f1a3998b716752b4d6e2efbbfec5df46d4
395
distributed-systems-cloud-2020
MIT License
server/src/main/kotlin/org/archguard/codedb/automate/builtin/LocTask.kt
archguard
565,163,416
false
{"Kotlin": 212032, "TypeScript": 19660, "MDX": 5365, "CSS": 2612, "HTML": 1703, "JavaScript": 1360}
package org.archguard.codedb.automate.builtin import org.archguard.codedb.automate.task.DefaultTask import org.archguard.codedb.automate.task.core.CacheableTask import org.archguard.codedb.automate.task.core.Input import org.archguard.codedb.automate.task.core.Output import org.archguard.codedb.automate.task.core.TaskAction @CacheableTask abstract class LocTask : DefaultTask() { @get:Input val source = "src/main/kotlin" @get:Output val output = "" @TaskAction fun run() { println("Running LocTask") } }
1
Kotlin
2
31
4c1f6a57568affeaab7771e83eb0665e934110a5
547
codedb
MIT License
ClassFileVIewer/src/main/kotlin/ConstantPoolDisplay.kt
kevinrjones
374,307,422
false
null
package com.knowledgespike.classfileviewer fun getCardContent(classFileParser: ClassFileParser, parseData: ClassfileDisplayDetails): ConstantPoolDisplay { parseData.title val constantPoolDsiplay: ConstantPoolDisplay = when (parseData) { is ClassfileDisplayDetails.ConstantValuePoolDisplayDetails -> getConstantPoolValueContent( classFileParser, parseData ) is ClassfileDisplayDetails.UtfConstantPoolDisplayDetails -> getUtfConstantPoolContent( classFileParser, parseData ) is ClassfileDisplayDetails.BasicConstantPoolDisplayDetails -> getBasicConstantPoolContent( classFileParser, parseData ) is ClassfileDisplayDetails.DescriptorConstantPoolDisplayDetails -> getDescriptorConstantPoolContent( classFileParser, parseData ) is ClassfileDisplayDetails.NamedConstantPoolDisplayDetails -> getNamedConstantPoolContent( classFileParser, parseData ) is ClassfileDisplayDetails.RefConstantPoolDisplayDetails -> getRefConstantPoolContent( classFileParser, parseData ) else -> ConstantPoolDisplay("Not in constant pool", listOf()) } return constantPoolDsiplay } fun getConstantPoolValueContent( classFileParser: ClassFileParser, constantPoolDetails: ClassfileDisplayDetails.ConstantValuePoolDisplayDetails ): ConstantPoolDisplay { val name = getStringFromConstantPool(classFileParser, constantPoolDetails.constantPoolIndex) return ConstantPoolDisplay( constantPoolDetails.title, listOf( "#${constantPoolDetails.constantPoolIndex}", name, constantPoolDetails.content ) ) } fun getRefConstantPoolContent( classFileParser: ClassFileParser, constantPoolDetails: ClassfileDisplayDetails.RefConstantPoolDisplayDetails ): ConstantPoolDisplay { val name = getStringFromConstantPool(classFileParser, constantPoolDetails.constantPoolIndex) val className = getStringFromConstantPool(classFileParser, constantPoolDetails.classIndex) val nameAndType = getStringFromConstantPool(classFileParser, constantPoolDetails.nameAndTypeIndex) return ConstantPoolDisplay( "${constantPoolDetails.title} (#${constantPoolDetails.constantPoolIndex})", listOf( "#${constantPoolDetails.classIndex}.#${constantPoolDetails.nameAndTypeIndex}", name, "$className:$nameAndType" ) ) } fun getNamedConstantPoolContent( classFileParser: ClassFileParser, constantPoolDetails: ClassfileDisplayDetails.NamedConstantPoolDisplayDetails ): ConstantPoolDisplay { val descriptor = getStringFromConstantPool(classFileParser, constantPoolDetails.constantPoolIndexLink) return ConstantPoolDisplay( "${constantPoolDetails.title} (#${constantPoolDetails.constantPoolIndex})", listOf( "#${constantPoolDetails.constantPoolIndexLink}", descriptor ) ) } fun getDescriptorConstantPoolContent( classFileParser: ClassFileParser, constantPoolDetails: ClassfileDisplayDetails.DescriptorConstantPoolDisplayDetails ): ConstantPoolDisplay { val name = getStringFromConstantPool(classFileParser, constantPoolDetails.constantPoolIndexLink) val type = getStringFromConstantPool(classFileParser, constantPoolDetails.descriptorPoolIndexLink) return ConstantPoolDisplay( "${constantPoolDetails.title} (#${constantPoolDetails.constantPoolIndex})", listOf( "#${constantPoolDetails.constantPoolIndexLink};#${constantPoolDetails.descriptorPoolIndexLink}", "${name};${type}" ) ) } fun getBasicConstantPoolContent( classFileParser: ClassFileParser, constantPoolDetails: ClassfileDisplayDetails.BasicConstantPoolDisplayDetails ): ConstantPoolDisplay { val text = getStringFromConstantPool(classFileParser, constantPoolDetails.constantPoolIndex) return ConstantPoolDisplay(constantPoolDetails.title, listOf(text)) } fun getUtfConstantPoolContent( classFileParser: ClassFileParser, constantPoolDetails: ClassfileDisplayDetails.UtfConstantPoolDisplayDetails ): ConstantPoolDisplay { val text = getStringFromConstantPool(classFileParser, constantPoolDetails.constantPoolIndex) return ConstantPoolDisplay( "${constantPoolDetails.title} (#${constantPoolDetails.constantPoolIndex})", listOf(text) ) } data class ConstantPoolDisplay(val title: String, val content: List<String>)
0
Kotlin
0
0
97f689a2b7c4e8b74a06ff89c461d24680ce8fd8
4,631
ComposeExamples
MIT License
view/src/main/java/com/workfort/pstuian/view/imageslider/SliderAnimations.kt
arhanashik
411,942,559
false
{"Kotlin": 1051684}
package com.workfort.pstuian.view.imageslider /** * **************************************************************************** * * Created by : arhan on 27 Nov, 2021 at 8:02. * * Email : <EMAIL> * * * * This class is for: * * 1. * * 2. * * 3. * **************************************************************************** */ enum class SliderAnimations { ANTICLOCKSPINTRANSFORMATION, CLOCK_SPINTRANSFORMATION, CUBEINDEPTHTRANSFORMATION, CUBEINROTATIONTRANSFORMATION, CUBEINSCALINGTRANSFORMATION, CUBEOUTDEPTHTRANSFORMATION, CUBEOUTROTATIONTRANSFORMATION, CUBEOUTSCALINGTRANSFORMATION, DEPTHTRANSFORMATION, FADETRANSFORMATION, FANTRANSFORMATION, FIDGETSPINTRANSFORMATION, GATETRANSFORMATION, HINGETRANSFORMATION, HORIZONTALFLIPTRANSFORMATION, POPTRANSFORMATION, SIMPLETRANSFORMATION, SPINNERTRANSFORMATION, TOSSTRANSFORMATION, VERTICALFLIPTRANSFORMATION, VERTICALSHUTTRANSFORMATION, ZOOMOUTTRANSFORMATION }
0
Kotlin
0
2
981e8c097318e3bdcfb10c0cd1968bbb2e0ef899
1,016
PSTUian-android
Apache License 2.0
androidApp/src/main/java/press/sync/SyncPreferencesView.kt
susyimes
323,609,665
true
{"Kotlin": 499797, "Swift": 36689, "Java": 19120, "Ruby": 5783}
package press.sync import android.content.Context import android.net.Uri import android.widget.ViewFlipper import androidx.browser.customtabs.CustomTabsIntent import com.jakewharton.rxbinding3.view.detaches import com.squareup.contour.ContourLayout import com.squareup.inject.assisted.Assisted import com.squareup.inject.assisted.AssistedInject import io.reactivex.android.schedulers.AndroidSchedulers.mainThread import me.saket.press.R import me.saket.press.shared.localization.strings import me.saket.press.shared.sync.SyncPreferencesEvent.DisableSyncClicked import me.saket.press.shared.sync.SyncPreferencesEvent.SetupHostClicked import me.saket.press.shared.sync.SyncPreferencesPresenter import me.saket.press.shared.sync.SyncPreferencesUiEffect import me.saket.press.shared.sync.SyncPreferencesUiEffect.OpenUrl import me.saket.press.shared.sync.SyncPreferencesUiModel import me.saket.press.shared.sync.SyncPreferencesUiModel.SyncDisabled import me.saket.press.shared.sync.SyncPreferencesUiModel.SyncEnabled import me.saket.press.shared.ui.subscribe import me.saket.press.shared.ui.uiUpdates import press.extensions.setDisplayedChild import press.theme.themeAware import press.widgets.PressToolbar class SyncPreferencesView @AssistedInject constructor( @Assisted context: Context, @Assisted private val onDismiss: () -> Unit, private val presenter: SyncPreferencesPresenter ) : ContourLayout(context) { private val toolbar = PressToolbar(context).apply { title = context.strings().sync.title setNavigationOnClickListener { onDismiss() } applyLayout( x = matchParentX(), y = topTo { parent.top() } ) } private val syncDisabledView = SyncDisabledView(context) private val syncEnabledView = SyncEnabledView(context) private val contentFlipperView = ViewFlipper(context).apply { animateFirstView = false setInAnimation(context, R.anim.slide_and_fade_in_from_bottom) setOutAnimation(context, R.anim.slide_and_fade_out_to_top) addView(syncDisabledView) addView(syncEnabledView) applyLayout( x = matchParentX(), y = topTo { toolbar.bottom() }.bottomTo { parent.bottom() } ) } init { themeAware { setBackgroundColor(it.window.backgroundColor) } } override fun onAttachedToWindow() { super.onAttachedToWindow() syncEnabledView.onDisableClick = { presenter.dispatch(DisableSyncClicked) } presenter.uiUpdates() .takeUntil(detaches()) .observeOn(mainThread()) .subscribe(models = ::render, effects = ::render) } private fun render(model: SyncPreferencesUiModel) { return when (model) { is SyncDisabled -> { contentFlipperView.setDisplayedChild(syncDisabledView) syncDisabledView.render(model, onClick = { host -> presenter.dispatch(SetupHostClicked(host)) }) } is SyncEnabled -> { contentFlipperView.setDisplayedChild(syncEnabledView) syncEnabledView.render(model) } } } private fun render(effect: SyncPreferencesUiEffect) { return when (effect) { is OpenUrl -> CustomTabsIntent.Builder() .setShowTitle(true) .addDefaultShareMenuItem() .build() .launchUrl(context, Uri.parse(effect.url)) } } @AssistedInject.Factory interface Factory { fun create(context: Context, onDismiss: () -> Unit): SyncPreferencesView } }
1
null
1
0
27526c7b6ce0073cfbdfc66f1e530bc96193992b
3,411
press
Apache License 2.0
app/src/main/java/com/mariotti/developer/futureclock/extensions/ResourcesExtensions.kt
gmariotti
45,698,513
false
null
package com.mariotti.developer.futureclock.extensions import android.content.res.Resources import android.os.Build fun Resources.getColorBasedOnApi23(colorID: Int): Int { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return this.getColor(colorID, null) } else { return this.getColor(colorID) } }
16
Kotlin
0
0
b4d8cb49a6df9ae511b23d7b94eb40ccbed3cc10
333
future-clock
Apache License 2.0
app/src/main/java/org/xbmc/kore/ui/sections/remote/MyRemoteActivity.kt
ChanNagihong
212,856,306
true
{"Java": 2147372, "Perl": 24856, "Kotlin": 12564, "Shell": 575}
package org.xbmc.kore.ui.sections.remote import android.content.Intent import android.databinding.DataBindingUtil import android.os.Bundle import android.support.design.widget.TabLayout.OnTabSelectedListener import android.support.design.widget.TabLayout.Tab import android.support.v4.text.TextDirectionHeuristicsCompat import android.support.v7.preference.PreferenceManager import android.util.Log import org.xbmc.kore.R import org.xbmc.kore.Settings import org.xbmc.kore.databinding.ActivityMyRemoteBinding import org.xbmc.kore.host.HostConnectionObserver import org.xbmc.kore.host.HostManager import org.xbmc.kore.jsonrpc.method.Files.Media import org.xbmc.kore.jsonrpc.method.Input import org.xbmc.kore.jsonrpc.notification.Player.NotificationsData import org.xbmc.kore.jsonrpc.type.ListType import org.xbmc.kore.jsonrpc.type.ListType.ItemsAll import org.xbmc.kore.jsonrpc.type.PlayerType.GetActivePlayersReturnType import org.xbmc.kore.jsonrpc.type.PlayerType.PropertyValue import org.xbmc.kore.service.ConnectionObserversManagerService import org.xbmc.kore.ui.BaseActivity import org.xbmc.kore.ui.generic.SendTextDialogFragment import org.xbmc.kore.ui.sections.file.MediaFileListFragment import org.xbmc.kore.ui.sections.hosts.AddHostActivity import org.xbmc.kore.utils.LogUtils import org.xbmc.kore.utils.TabsAdapter import org.xbmc.kore.utils.Utils class MyRemoteActivity : BaseActivity(), HostConnectionObserver.PlayerEventsObserver, NowPlayingFragment.NowPlayingListener, SendTextDialogFragment.SendTextDialogListener { private val TAG = LogUtils.makeLogTag(RemoteActivity::class.java) private lateinit var binding: ActivityMyRemoteBinding private lateinit var hostManager: HostManager private lateinit var tabsAdapter: TabsAdapter private var hostConnectionObserver: HostConnectionObserver? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_my_remote) hostManager = HostManager.getInstance(this) if (hostManager.hostInfo == null) { val intent = Intent(this, AddHostActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(intent) finish() return } val moviesBundle = Bundle() moviesBundle.putString(MediaFileListFragment.MEDIA_TYPE, Media.VIDEO) moviesBundle.putParcelable( MediaFileListFragment.SORT_METHOD, ListType.Sort(ListType.Sort.SORT_METHOD_PATH, true, true) ) moviesBundle.putString( MediaFileListFragment.CUSTOM_PATH, "multipath://%2fhome%2fnagihong%2fhdd%2fmovies%2f/%2fhome%2fnagihong%2fMovies%2f/" ) val tvBundle = Bundle() tvBundle.putString(MediaFileListFragment.MEDIA_TYPE, Media.VIDEO) tvBundle.putParcelable( MediaFileListFragment.SORT_METHOD, ListType.Sort(ListType.Sort.SORT_METHOD_PATH, true, true) ) tvBundle.putString( MediaFileListFragment.CUSTOM_PATH, "multipath://%2fhome%2fnagihong%2fTv%2f/%2fhome%2fnagihong%2fhdd%2ftv%2f/" ) val variousBundle = Bundle() variousBundle.putString(MediaFileListFragment.MEDIA_TYPE, Media.VIDEO) variousBundle.putParcelable( MediaFileListFragment.SORT_METHOD, ListType.Sort(ListType.Sort.SORT_METHOD_PATH, true, true) ) variousBundle.putString( MediaFileListFragment.CUSTOM_PATH, "multipath://%2fhome%2fnagihong%2fVarious%2f/%2fhome%2fnagihong%2fhdd%2fvarious%2f/" ) tabsAdapter = TabsAdapter(this, supportFragmentManager) .addTab(NowPlayingFragment::class.java, null, "正在播", 1) .addTab(MediaFileListFragment::class.java, moviesBundle, "电影", 2) .addTab(MediaFileListFragment::class.java, tvBundle, "电视", 3) .addTab(MediaFileListFragment::class.java, variousBundle, "综艺", 4) binding.viewPager.offscreenPageLimit = 4 binding.viewPager.adapter = tabsAdapter binding.tabLayout.setupWithViewPager(binding.viewPager) binding.tabLayout.addOnTabSelectedListener(object : OnTabSelectedListener { private val INTERVAL = 1000L private var lastClickTime = 0L private var clickTimes = 0 override fun onTabReselected(p0: Tab) { if (p0.position != 0) return val time = System.currentTimeMillis() if (time - lastClickTime < INTERVAL) { clickTimes++ if (clickTimes == 5) { clickTimes = 0 startActivity(Intent(this@MyRemoteActivity, MySettingsActivity::class.java)) } } else { clickTimes = 1 } lastClickTime = time } override fun onTabUnselected(p0: Tab?) { } override fun onTabSelected(p0: Tab) { } }) tabsAdapter.notifyDataSetChanged() } override fun onResume() { super.onResume() hostConnectionObserver = hostManager.hostConnectionObserver hostConnectionObserver?.registerPlayerObserver(this) hostConnectionObserver?.refreshWhatsPlaying() hostConnectionObserver?.refreshPlaylists() } override fun onPause() { super.onPause() hostConnectionObserver?.unregisterPlayerObserver(this) hostConnectionObserver = null } // <editor-fold desc="SendTextDialogFragment.SendTextDialogListener"> ---------------------------------------------------------- override fun onSendTextFinished( text: String, done: Boolean ) { val sendText = if (TextDirectionHeuristicsCompat.FIRSTSTRONG_LTR.isRtl(text, 0, text.length)) { StringBuilder(text).reverse() .toString() } else text val action = Input.SendText(sendText, done) action.execute(hostManager.connection, null, null) } override fun onSendTextCancel() { } // </editor-fold desc="SendTextDialogFragment.SendTextDialogListener"> --------------------------------------------------------- // <editor-fold desc="NowPlayingFragment.NowPlayingListener"> ---------------------------------------------------------- override fun SwitchToRemotePanel() { binding.viewPager.currentItem = 0 } // </editor-fold desc="NowPlayingFragment.NowPlayingListener"> --------------------------------------------------------- // <editor-fold desc="HostConnectionObserver.PlayerEventsObserver"> ---------------------------------------------------------- override fun playerOnPropertyChanged(notificationsData: NotificationsData?) { } override fun playerOnPlay( getActivePlayerResult: GetActivePlayersReturnType?, getPropertiesResult: PropertyValue?, getItemResult: ItemsAll? ) { SwitchToRemotePanel() val showNotification = PreferenceManager .getDefaultSharedPreferences(this) .getBoolean( Settings.KEY_PREF_SHOW_NOTIFICATION, Settings.DEFAULT_PREF_SHOW_NOTIFICATION ) if (showNotification) { // Start service that manages connection observers LogUtils.LOGD(TAG, "Starting observer service") if (Utils.isOreoOrLater()) { startForegroundService(Intent(this, ConnectionObserversManagerService::class.java)) } else { startService(Intent(this, ConnectionObserversManagerService::class.java)) } } } override fun playerOnPause( getActivePlayerResult: GetActivePlayersReturnType?, getPropertiesResult: PropertyValue?, getItemResult: ItemsAll? ) { playerOnPlay(getActivePlayerResult, getPropertiesResult, getItemResult) } override fun playerOnStop() { } override fun playerOnConnectionError( errorCode: Int, description: String? ) { playerOnStop() } override fun playerNoResultsYet() { } override fun systemOnQuit() { playerOnStop() } override fun inputOnInputRequested( title: String?, type: String?, value: String? ) { val dialog = SendTextDialogFragment.newInstance(title) dialog.show(supportFragmentManager, null) } override fun observerOnStopObserving() { } // </editor-fold desc="HostConnectionObserver.PlayerEventsObserver"> --------------------------------------------------------- }
0
Java
0
0
33ae15205723080290e50cdc2595c8da1fd76cf0
8,168
Kore
Apache License 2.0
app/src/main/java/com/mapswithme/maps/search/FloatingSearchToolbarController.kt
dnemov
245,413,600
false
{"Gradle": 3, "Java Properties": 3, "Shell": 1, "Text": 16, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "INI": 1, "Proguard": 1, "XML": 624, "Kotlin": 708, "Java": 9, "HTML": 3, "JSON": 95}
package com.mapswithme.maps.search import android.app.Activity import android.text.TextUtils import com.mapswithme.maps.api.ParsedMwmRequest.Companion.currentRequest import com.mapswithme.maps.api.ParsedMwmRequest.Companion.hasRequest import com.mapswithme.maps.widget.SearchToolbarController import com.mapswithme.util.UiUtils class FloatingSearchToolbarController( activity: Activity, private val mListener: SearchToolbarListener? ) : SearchToolbarController(activity.window.decorView, activity) { private var mVisibilityListener: VisibilityListener? = null interface VisibilityListener { fun onSearchVisibilityChanged(visible: Boolean) } override fun onUpClick() { mListener?.onSearchUpClick(query) cancelSearchApiAndHide(true) } override fun onQueryClick(query: String) { super.onQueryClick(query.orEmpty()) mListener?.onSearchQueryClick(query) hide() } override fun onClearClick() { super.onClearClick() mListener?.onSearchClearClick() cancelSearchApiAndHide(false) } fun refreshToolbar() { showProgress(false) if (hasRequest()) { UiUtils.show(toolbar) if (mVisibilityListener != null) mVisibilityListener!!.onSearchVisibilityChanged(true) query = currentRequest!!.title.orEmpty() } else if (!TextUtils.isEmpty(SearchEngine.INSTANCE.query)) { UiUtils.show(toolbar) if (mVisibilityListener != null) mVisibilityListener!!.onSearchVisibilityChanged(true) query = SearchEngine.INSTANCE.query.orEmpty() } else { hide() clear() } } private fun cancelSearchApiAndHide(clearText: Boolean) { SearchEngine.INSTANCE.cancel() if (clearText) clear() hide() } fun hide(): Boolean { if (!UiUtils.isVisible(toolbar)) return false UiUtils.hide(toolbar) if (mVisibilityListener != null) mVisibilityListener!!.onSearchVisibilityChanged(false) return true } fun setVisibilityListener(visibilityListener: VisibilityListener?) { mVisibilityListener = visibilityListener } interface SearchToolbarListener { fun onSearchUpClick(query: String?) fun onSearchQueryClick(query: String?) fun onSearchClearClick() } }
0
Kotlin
0
1
8b75114193e141aee14fcbc207a208c4a39de1db
2,392
omim.kt
Apache License 2.0
sofarc-serv/src/main/kotlin/org/maxur/sofarc/params/ConfigParams.kt
myunusov
94,055,176
false
null
@file:Suppress("unused") package org.maxur.sofarc.params import com.fasterxml.jackson.databind.SerializationFeature import org.jvnet.hk2.annotations.Service import org.maxur.sofarc.core.annotation.Value import org.maxur.sofarc.core.service.jackson.ObjectMapperProvider import org.maxur.sofarc.core.service.grizzly.config.WebAppConfig import org.slf4j.Logger import org.slf4j.LoggerFactory import javax.inject.Inject /** * All Configuration Parameters * * @author myunusov * @version 1.0 * @since <pre>12.06.2017</pre> */ @Service class ConfigParams @Inject constructor( @Value(key = "webapp") val webapp: WebAppConfig, @Value(key = "name") val name: String ) { companion object { val log: Logger = LoggerFactory.getLogger(ConfigParams::class.java) } fun log() { log.info("\n--- Configuration Parameters ---\n") log.info("$this") log.info("\n---------------------------------\n") } override fun toString(): String { val mapper = ObjectMapperProvider().provide() mapper.enable(SerializationFeature.INDENT_OUTPUT) return mapper.writeValueAsString(this) } }
1
null
1
1
d465dc917e5af6bfc32f40e4d406a2767f5261ab
1,168
sofarc
Apache License 2.0
app/src/main/java/org/abuhuraira/app/scenes/listVideos/ListVideosPresenter.kt
YusufSaad
428,501,733
false
{"Java": 3686476, "Kotlin": 315094, "HTML": 4986, "Assembly": 6}
package org.abuhuraira.app.scenes.listVideos import com.example.coreandroid.sources.errors.DataError import org.abuhuraira.app.R import org.abuhuraira.app.common.cleanBase.AppModels import org.abuhuraira.app.common.dataAdapters.VideoDataModel import org.abuhuraira.app.common.extensions.getString import org.abuhuraira.app.scenes.listVideos.common.ListVideosDisplayable import org.abuhuraira.app.scenes.listVideos.common.ListVideosModels import org.abuhuraira.app.scenes.listVideos.common.ListVideosPresentable import java.lang.ref.WeakReference import java.text.SimpleDateFormat import java.util.* /** * Created by ahmedsaad on 2017-10-27. * Copyright © 2017. All rights reserved. */ class ListVideosPresenter(private val fragment: WeakReference<ListVideosDisplayable?>) : ListVideosPresentable { private val dateFormatter = SimpleDateFormat("MMMM d yyyy", Locale.US) override fun presentVideos(response: ListVideosModels.Response) { val viewModel = ListVideosModels.ViewModel( videos = response.videos.fold(arrayListOf()) { acc, videoType -> val video = VideoDataModel.ViewModel( title = videoType.snippet.title, thumbnailImage = videoType.snippet.thumbnails.high.url, id = videoType.id.videoId ?: videoType.id.playlistId ?: "", content = videoType.snippet.description, publishedAt = dateFormatter.format(videoType.snippet.publishedAt) ) if (!video.id.isEmpty()) { acc.add(video) } acc } ) fragment.get()?.displayFetchedVideos(viewModel) } override fun presentVideos(error: DataError) { // Handle and parse error val viewModel = AppModels.Error( title = getString(R.string.generic_error_title), message = getString(R.string.generic_error_message) ) fragment.get()?.displaySupport(viewModel) } }
1
Java
1
2
02f84a27796eed4683dc7bab88b07446a6fe2315
2,113
Ahc-app
MIT License
app/src/main/java/ir/neo/stepbarviewdemo/MainActivity.kt
imaNNeoFighT
128,241,824
false
{"Kotlin": 32461, "Java": 1138}
package ir.neo.stepbarviewdemo import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.* import ir.neo.stepbarview.DpHandler import ir.neo.stepbarview.StepBarView import ir.neo.stepbarview.StepBarView.StepsTitleSetter import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() ,SeekBar.OnSeekBarChangeListener{ lateinit var sbAttrsValue: SeekBar lateinit var spActions : Spinner lateinit var tvValue : TextView var actionsList : MutableList<String> = mutableListOf() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) my_stepBarView4.allowSelectStep = object : StepBarView.AllowSelectStep{ override fun allowSelectStep(step: Int) = step != 2 } sbAttrsValue = findViewById(R.id.sb_attrsValue) spActions = findViewById(R.id.sp_actions) tvValue = findViewById(R.id.tv_value) initSpinner() initStepNames() } private fun initStepNames() { my_stepBarView2.stepsTitleSetter = object : StepsTitleSetter { override fun getStepTitle(step: Int): String { return when (step) { 1 -> "Fist" 2 -> "2nd" 3 -> "Third" 4 -> "4th" 5 -> "Fifth" 6 -> "6th" 7 -> "Seventh" 8 -> "8th" 9 -> "Ninth" 10 -> "10th" else -> "Non" } } } } private fun initSpinner() { actionsList.add("sbv_max_count") actionsList.add("sbv_steps_line_height") actionsList.add("sbv_steps_size") actionsList.add("sbv_steps_text_size") actionsList.add("sbv_steps_line_margin_left") actionsList.add("sbv_steps_line_margin_right") actionsList.add("sbv_allow_touch_step_to") val spinnerArrayAdapter = ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, actionsList) spinnerArrayAdapter.setDropDownViewResource(android.R.layout .simple_spinner_dropdown_item) spActions.adapter = spinnerArrayAdapter spActions.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{ override fun onNothingSelected(parent: AdapterView<*>?) {} override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { refreshSelected(position) } } spActions.setSelection(0) refreshValueText(my_stepBarView4.maxCount) } private fun refreshSelected(position : Int) { sbAttrsValue.setOnSeekBarChangeListener(null) when(actionsList[position]){ "sbv_max_count" -> { sbAttrsValue.max = 20 sbAttrsValue.progress = my_stepBarView4.maxCount-2 refreshValueText(sbAttrsValue.progress) } "sbv_steps_line_height" -> { sbAttrsValue.max = 20 sbAttrsValue.progress = DpHandler.pxToDp(this@MainActivity, my_stepBarView4.stepsLineHeight.toInt()) refreshValueText(sbAttrsValue.progress) } "sbv_steps_size" -> { sbAttrsValue.max = 80 sbAttrsValue.progress = DpHandler.pxToDp(this@MainActivity, my_stepBarView4.stepsSize.toInt()) refreshValueText(sbAttrsValue.progress) } "sbv_steps_text_size" -> { sbAttrsValue.max = 25 sbAttrsValue.progress = DpHandler.pxToSp(this@MainActivity, my_stepBarView4.stepsSize.toInt()).toInt() refreshValueText(sbAttrsValue.progress) } "sbv_steps_line_margin_left" -> { sbAttrsValue.max = 40 sbAttrsValue.progress = DpHandler.pxToDp(this@MainActivity, my_stepBarView4.stepsLineMarginLeft.toInt()) refreshValueText(sbAttrsValue.progress) } "sbv_steps_line_margin_right" -> { sbAttrsValue.max = 100 sbAttrsValue.progress = DpHandler.pxToDp(this@MainActivity, my_stepBarView4.stepsLineMarginRight.toInt()) refreshValueText(sbAttrsValue.progress) } "sbv_allow_touch_step_to" -> { sbAttrsValue.max = my_stepBarView4.maxCount sbAttrsValue.progress = my_stepBarView4.allowTouchStepTo refreshValueText(sbAttrsValue.progress) } } sbAttrsValue.setOnSeekBarChangeListener(this) } private fun refreshValueText(progress: Int) { when(actionsList[spActions.selectedItemPosition]){ "sbv_max_count" -> { tvValue.text = "${progress+2}" } "sbv_steps_line_height" -> { tvValue.text = "$progress dp" } "sbv_steps_size" -> { tvValue.text = "$progress sp" } "sbv_steps_text_size" -> { tvValue.text = "$progress sp" } "sbv_steps_line_margin_left" -> { tvValue.text = "$progress dp" } "sbv_steps_line_margin_right" -> { tvValue.text = "$progress dp" } "sbv_allow_touch_step_to" -> { tvValue.text = "$progress" } } } private fun refreshProgress(progress: Int) { when(actionsList[spActions.selectedItemPosition]){ "sbv_max_count" -> { my_stepBarView4.maxCount= progress+2 } "sbv_steps_line_height" -> { my_stepBarView4.stepsLineHeight = DpHandler.dpToPx(this@MainActivity,progress).toFloat() } "sbv_steps_size" -> { my_stepBarView4.stepsSize = DpHandler.dpToPx(this@MainActivity,progress).toFloat() } "sbv_steps_text_size" -> { my_stepBarView4.stepsTextSize = DpHandler.spToPx(this,progress.toFloat()) } "sbv_steps_line_margin_left" -> { my_stepBarView4.stepsLineMarginLeft = DpHandler.dpToPx(this@MainActivity,progress).toFloat() } "sbv_steps_line_margin_right" -> { my_stepBarView4.stepsLineMarginRight = DpHandler.dpToPx(this@MainActivity,progress).toFloat() } "sbv_allow_touch_step_to" -> { my_stepBarView4.allowTouchStepTo = progress } } } override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) { refreshValueText(progress) refreshProgress(progress) } override fun onStartTrackingTouch(seekBar: SeekBar?){} override fun onStopTrackingTouch(seekBar: SeekBar?){} }
2
Kotlin
23
110
c5f7d9bd44f7f910ca50b7925e38a7200cd759aa
7,046
StepBarView
Apache License 2.0
AndroidSDKFcm/src/main/java/com/leanplum/FirebaseUtil.kt
Leanplum
89,527,711
false
null
/* * Copyright 2021, Leanplum, Inc. All rights reserved. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.leanplum import android.text.TextUtils import com.google.firebase.iid.FirebaseInstanceId import com.google.firebase.messaging.FirebaseMessaging import com.leanplum.internal.Log internal fun updateRegistrationId(provider: LeanplumCloudMessagingProvider) { try { Present.updateRegistrationId(provider) } catch (e: NoSuchMethodError) { Log.d("Using legacy firebase methods.") Legacy.updateRegistrationId(provider) } } internal fun unregister() { try { Present.unregister() } catch (e: NoSuchMethodError) { Log.d("Using legacy firebase methods.") Legacy.unregister() } } /** * Present Firebase interface was added in version 20.3.0. */ private object Present { fun updateRegistrationId(provider: LeanplumCloudMessagingProvider) { FirebaseMessaging.getInstance().token.addOnCompleteListener { if (it.isSuccessful) { val token = it.result.toString() if (!TextUtils.isEmpty(token)) { provider.registrationId = token } } else { Log.e("getToken failed:\n" + Log.getStackTraceString(it.exception)) } } } fun unregister() { try { FirebaseMessaging.getInstance().deleteToken() Log.i("Application was unregistered from FirebaseMessaging.") } catch (e: Exception) { Log.e("Failed to unregister from FirebaseMessaging.") } } } /** * Legacy Firebase interface was removed in version 22.0.0. */ private object Legacy { fun updateRegistrationId(provider: LeanplumCloudMessagingProvider) { FirebaseInstanceId.getInstance().instanceId.addOnCompleteListener { if (it.isSuccessful) { val tokenId = it.result?.token if (!TextUtils.isEmpty(tokenId)) { provider.registrationId = tokenId } } else { Log.e("getInstanceId failed:\n" + Log.getStackTraceString(it.exception)) } } } fun unregister() { try { FirebaseInstanceId.getInstance().deleteInstanceId() Log.i("Application was unregistered from FCM.") } catch (e: Exception) { Log.e("Failed to unregister from FCM.") } } }
14
null
42
41
d392efa2685ce940748e2fb9a343cc4f7ca08292
2,991
Leanplum-Android-SDK
Apache License 2.0
src/util/main/sp/it/util/units/RangeYear.kt
sghpjuikit
18,862,317
false
null
package sp.it.util.units import java.time.Year import sp.it.util.math.max import sp.it.util.math.min import sp.it.util.parsing.ConverterToString /** * Range of year units. * Stores minimum value, maximum value and specificness - whether any value the range was created for was unspecified. * Has proper text representation. * * Mutable. Accumulating year values expands this range. */ class RangeYear { private var min = Integer.MAX_VALUE private var max = Integer.MIN_VALUE private var hasUnspecified = false /** Accumulate specific year value or unspecific value (null) into this range */ fun accumulate(year: Year?) = accumulate(year?.value) /** Accumulate specific year value as int or unspecific value (null) into this range */ fun accumulate(year: Int?) { if (year==null) { hasUnspecified = true } else { min = min min year max = max max year } } operator fun plusAssign(year: Int?) = accumulate(year) operator fun plusAssign(year: Year?) = accumulate(year) /** @return true iff no value has been accumulated, so both [hasSpecific] and [hasUnspecified] return false */ fun isEmpty(): Boolean = !hasSpecific() && !hasUnSpecific() /** @return true iff all specific years in this range are lesser than the specified year */ fun isAfter(y: Year) = hasSpecific() && min>y.value /** @return true iff all specific years in this range are greater than the specified year */ fun isBefore(y: Year) = hasSpecific() && max<y.value /** @return true iff this range has some specific year >= and some specific year <= than the specified year */ operator fun contains(y: Year) = hasSpecific() && min<=y.value && max>=y.value /** @return true iff any specific year has been accumulated to this range */ fun hasSpecific() = max!=Integer.MIN_VALUE /** @return true iff any unspecific year has been accumulated to this range */ fun hasUnSpecific() = hasUnspecified override fun toString() = toS(this) companion object: ConverterToString<RangeYear> { override fun toS(o: RangeYear) = when { o.isEmpty() -> "<none>" o.hasSpecific() -> { when (o.min==o.max) { true -> (if (o.hasUnspecified) "? " else "") + o.max false -> "" + o.min + (if (o.hasUnspecified) " ? " else " - ") + o.max } } else -> "" } } }
11
null
2
22
0a2f29ad192bb224a5737bac012f772c8025e348
2,431
player
RSA Message-Digest License
stplayer/src/main/java/com/st/stplayer/extension/ViewExtension.kt
CharonChui
308,626,657
false
{"Gradle": 9, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 9, "Batchfile": 1, "Markdown": 2, "INI": 6, "Proguard": 7, "Kotlin": 121, "XML": 67, "Java": 43, "GLSL": 2}
package com.st.stplayer.extension import android.graphics.Bitmap import android.graphics.Canvas import android.view.View import android.widget.Toast class ViewExtension { fun View.toast(resId: Int, duration: Int = Toast.LENGTH_SHORT) { Toast.makeText(context, resId, duration).show() } fun View.toast(text: String, duration: Int = Toast.LENGTH_SHORT) { Toast.makeText(context, text, duration).show() } fun View.isVisibile(): Boolean { return visibility == View.VISIBLE } /** * Extension method to get a view as bitmap. */ fun View.getBitmap(): Bitmap { val bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) val canvas = Canvas(bmp) draw(canvas) canvas.save() return bmp } }
1
null
1
1
fb15ae9caeeb9d3b47e0823dd0e0da2266d6ebe0
805
StPlayer
Apache License 2.0
tmp/arrays/youTrackTests/4933.kt
DaniilStepanov
228,623,440
false
null
// Original bug: KT-35175 /** * Random number generator, algorithm "xorwow" from p. 5 of Marsaglia, "Xorshift RNGs". * * Cycles after 2^160 * (2^32-1) repetitions. * * See http://www.jstatsoft.org/v08/i14/paper for details. */
1
null
1
1
602285ec60b01eee473dcb0b08ce497b1c254983
234
bbfgradle
Apache License 2.0
app/src/main/java/com/howettl/mvvm/data/repository/UserRemoteRepository.kt
rakaadinugroho
164,458,532
true
{"Kotlin": 26723}
package com.howettl.mvvm.data.repository import com.howettl.mvvm.data.model.User import com.howettl.mvvm.data.network.UserApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class UserRemoteRepository(private val userApi: UserApi) { suspend fun getUsers(): List<User> { return withContext(Dispatchers.IO) { userApi.getUsers().await() } } suspend fun getUserById(userId: Int): User { return withContext(Dispatchers.IO) { userApi.getUserById(userId).await() } } }
0
Kotlin
0
0
6471930d52b8d786a42acdd0f77adb7bf94022e3
566
android-MVVM-project-template
MIT License
src/test/kotlinIntegration/com/artemkaxboy/redmineexporter/service/IssueCategoryServiceTest.kt
artemkaxboy
408,380,930
false
{"Kotlin": 81482}
package com.artemkaxboy.redmineexporter.service import com.artemkaxboy.redmineexporter.entity.IssueCategory import com.artemkaxboy.redmineexporter.repository.IssueCategoryRepository import org.assertj.core.api.Assertions import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Test import org.junit.runner.RunWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.junit4.SpringRunner @SpringBootTest @RunWith(SpringRunner::class) internal class IssueCategoryServiceTest { @Autowired lateinit var issueCategoryRepository: IssueCategoryRepository @Autowired lateinit var issueCategoryService: IssueCategoryService private val unknownProject1Id = -1L private val project1Id = 1L private val project2Id = 2L val testCategories = listOf( IssueCategory.make(projectId = project1Id, name = "Backend"), IssueCategory.make(projectId = project2Id, name = "Frontend"), IssueCategory.make(projectId = project2Id, name = "DB"), ) @AfterEach fun clearIssues() { issueCategoryRepository.deleteAllInBatch() issueCategoryService.reset() } @Test fun `returns no categories before fetch`() { issueCategoryRepository.saveAll(testCategories) val got = issueCategoryService.getAllCategories(project1Id) Assertions.assertThat(got).isEmpty() } @Test fun `returns all categories for known project after fetch`() { val expected = issueCategoryRepository.saveAll(testCategories) issueCategoryService.fetchCategories() val got = issueCategoryService.getAllCategories(project1Id) Assertions.assertThat(got).hasSameElementsAs(expected.filter { it.projectId == project1Id }) } @Test fun `returns no categories for unknown project after fetch`() { val expected = issueCategoryRepository.saveAll(testCategories) issueCategoryService.fetchCategories() val got = issueCategoryService.getAllCategories(unknownProject1Id) Assertions.assertThat(got).hasSameElementsAs(expected.filter { it.projectId == unknownProject1Id }) } @Test fun `clears all categories by reset`() { issueCategoryRepository.saveAll(testCategories) issueCategoryService.fetchCategories() issueCategoryService.reset() val got = issueCategoryService.getAllCategories(project1Id) Assertions.assertThat(got).isEmpty() } }
4
Kotlin
0
1
a9de7218d0b61bec7c03c9583db29303b7c917ce
2,558
red-exporter
MIT License