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/cn/neday/android/app/config/KoinConfig.kt
nEdAy
491,729,187
false
{"Kotlin": 59724, "Java": 3486}
package cn.neday.android.app.config import android.app.Application import cn.neday.android.app.di.repositoryModule import cn.neday.android.app.di.viewModelModule import cn.neday.android.business.di.httpClientModule import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.core.context.startKoin object KoinConfig { fun init(application: Application) { startKoin { androidLogger() androidContext(application) modules( listOf( httpClientModule, repositoryModule, viewModelModule ) ) } } }
0
Kotlin
0
2
99ccc39b6c9439f1cfc9ed223a25d3a26e651942
707
android-application-with-kotlin-template
MIT License
Music Wiki/MusicWiki/app/src/main/java/com/adityamshidlyali/musicwiki/view/activity/MainActivity.kt
AdityaShidlyali
591,732,762
false
null
package com.adityamshidlyali.musicwiki.view.activity import android.content.Intent import android.os.Bundle import android.transition.AutoTransition import android.transition.TransitionManager import android.view.View import android.widget.Toast import androidx.activity.viewModels import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.core.view.isVisible import androidx.lifecycle.lifecycleScope import com.adityamshidlyali.musicwiki.R import com.adityamshidlyali.musicwiki.databinding.ActivityMainBinding import com.adityamshidlyali.musicwiki.network.EndPoints import com.adityamshidlyali.musicwiki.viewmodel.GenreTagsViewModel import com.google.android.material.chip.Chip import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch @AndroidEntryPoint class MainActivity : AppCompatActivity() { private val TAG = javaClass.simpleName private lateinit var binding: ActivityMainBinding private val viewModel: GenreTagsViewModel by viewModels() private val genresChips = ArrayList<Chip>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) /** * AlertDialog to show the loading state of the tag lists from the network */ val alertDialogBuilder = AlertDialog.Builder(this) alertDialogBuilder.setView(layoutInflater.inflate(R.layout.loading_dialog, null)) alertDialogBuilder.setCancelable(false) val loadingDialog = alertDialogBuilder.create() /** * minimize the hidden chips to show only the top10 genres */ binding.chipGroupGenresExpanded.visibility = View.GONE binding.bExpandGenres.icon = ContextCompat.getDrawable(this@MainActivity, R.drawable.ic_expand_more) binding.bExpandGenres.text = baseContext.getString(R.string.more_genres) /** * handle the click of more/less button to expand cardview and show other genres */ binding.bExpandGenres.setOnClickListener { if (!binding.chipGroupGenresExpanded.isVisible) { TransitionManager.beginDelayedTransition(binding.cardViewGenres, AutoTransition()) binding.chipGroupGenresExpanded.visibility = View.VISIBLE binding.bExpandGenres.icon = ContextCompat.getDrawable(this@MainActivity, R.drawable.ic_expand_less) binding.bExpandGenres.text = baseContext.getString(R.string.less_genres) } else { TransitionManager.beginDelayedTransition(binding.cardViewGenres, AutoTransition()) binding.chipGroupGenresExpanded.visibility = View.GONE binding.bExpandGenres.icon = ContextCompat.getDrawable(this@MainActivity, R.drawable.ic_expand_more) binding.bExpandGenres.text = baseContext.getString(R.string.more_genres) } } /** * Launch the coroutine to get the list tags(Genres) */ lifecycleScope.launch { viewModel.getGenreTags(EndPoints.API_KEY, EndPoints.FORMAT, EndPoints.TOP_TAGS) viewModel.genreListFetchStateFlow.collect { when (it) { is GenreTagsViewModel.GetGenreTagsEvent.Loading -> { if (!loadingDialog.isShowing) { loadingDialog.show() } } /** * Populate the chips using the objects hashcode as unique ID * to handle the clicks of chips from chipgroup uniquely */ is GenreTagsViewModel.GetGenreTagsEvent.Success -> { if (loadingDialog.isShowing) { loadingDialog.dismiss() } for (i in it.genreTags!!) { val genreChip = Chip(this@MainActivity) genreChip.text = i.name.replaceFirstChar { it -> it.titlecase() } genreChip.id = i.hashCode() genresChips.add(genreChip) } runOnUiThread { for (i in 0..9) { binding.chipGroupGenresTop10.addView(genresChips[i]) } for (i in 10 until genresChips.size) { binding.chipGroupGenresExpanded.addView(genresChips[i]) } } } is GenreTagsViewModel.GetGenreTagsEvent.Failure -> { Toast.makeText( this@MainActivity, "Something went wrong please try again", Toast.LENGTH_LONG ).show() } else -> { } } } } /** * handle the clicks of chips from chipgroup * and launch the GenreDetailsActivity to show the details of the Genres selected by user using chips * * only for top10 genres displayed */ binding.chipGroupGenresTop10.setOnCheckedStateChangeListener { group, _ -> val selectedChipId = group.checkedChipId val selectedChip = group.findViewById<Chip>(selectedChipId) selectedChip.isChecked = false selectedChip.setOnClickListener { val intent = Intent(this@MainActivity, GenreTagDetailsActivity::class.java) intent.putExtra( "genre_tag", selectedChip.text.toString() ) startActivity(intent) } } /** * handle the clicks of chips from chipgroup * and launch the GenreDetailsActivity to show the details of the Genres selected by user using chips * * only for other genres displayed expect top 10 genres */ binding.chipGroupGenresExpanded.setOnCheckedStateChangeListener { group, _ -> val selectedChipId = group.checkedChipId val selectedChip = group.findViewById<Chip>(selectedChipId) selectedChip.isChecked = false selectedChip.setOnClickListener { val intent = Intent(this@MainActivity, GenreTagDetailsActivity::class.java) intent.putExtra( "genre_tag", selectedChip.text.toString() ) startActivity(intent) } } } }
0
Kotlin
0
0
8170c323fec9c628249b3b85999666a15bc415fa
6,998
MusicWiki_Assessment
MIT License
src/test/kotlin/kotlinmud/action/impl/cast/CureSeriousTest.kt
danielmunro
241,230,796
false
null
package kotlinmud.action.impl.cast import assertk.assertThat import assertk.assertions.isEqualTo import assertk.assertions.isGreaterThan import kotlinmud.io.type.IOStatus import kotlinmud.mob.skill.type.SkillType import kotlinmud.test.helper.createTestService import kotlinmud.test.helper.getIdentifyingWord import org.junit.Test class CureSeriousTest { @Test fun testCanCureSeriousOnSelfImplicit() { // setup val test = createTestService() // given val mob = test.createMob { it.skills[SkillType.CURE_SERIOUS] = 100 } mob.hp = 1 // when val response = test.runAction("cast 'cure serious'") // then assertThat(response.message.toActionCreator).isEqualTo("you feel better!") assertThat(response.message.toTarget).isEqualTo("you feel better!") assertThat(response.message.toObservers).isEqualTo("$mob feels better!") // and assertThat(mob.hp).isGreaterThan(1) } @Test fun testCanCureSeriousOnOthers() { // setup val test = createTestService() // given val caster = test.createPlayerMob { it.skills[SkillType.CURE_SERIOUS] = 100 } val target = test.createMob() // when val response = test.runActionForIOStatus( caster, "cast 'cure serious' ${getIdentifyingWord(target)}", IOStatus.OK ) // then assertThat(response.message.toActionCreator).isEqualTo("$target feels better!") assertThat(response.message.toTarget).isEqualTo("you feel better!") assertThat(response.message.toObservers).isEqualTo("$target feels better!") } }
0
Kotlin
1
9
b7ee0d21ae813990896b1b8c6703da9bd1f1fc5b
1,729
kotlinmud
MIT License
app/src/main/java/com/begner/hdmivolumeosd/OSDStyles.kt
begner
296,143,576
false
null
package com.begner.hdmivolumeosd abstract class OSDStyles { lateinit var availableStyles : List<OSDStyle> fun getByIndex(index: Int) : OSDStyle { return availableStyles[index] } fun getIndexByKey(searchKey: String):Int { return availableStyles.indexOfFirst { it.key == searchKey } } fun getPositionByKey(searchKey: String):OSDStyle { var prop = availableStyles.find { it.key == searchKey } if (prop == null) { prop = OSDStyle("default", "Default") } return prop } fun getLabelArray(): Array<String> { val keyMap: List<String> = availableStyles.map { it.label } return keyMap.toTypedArray() } }
0
Kotlin
0
0
6bbf75ce23d9539ba105326cc938a812d9e6dc06
713
HDMIVolumeOSD
MIT License
data/src/main/java/com/mcdenny/data/impl/RemoteRepositoryImpl.kt
OlukaDenis
655,817,208
false
null
package com.mcdenny.data.impl import com.mcdenny.data.remote.mappers.WeatherRemoteMapper import com.mcdenny.data.remote.services.ApiService import com.mcdenny.domain.models.weather.WeatherDomainModel import com.mcdenny.domain.repository.RemoteRepository import javax.inject.Inject class RemoteRepositoryImpl @Inject constructor( private val service: ApiService, private val weatherRemoteMapper: WeatherRemoteMapper ): RemoteRepository { override suspend fun fetchLocationWeather(query: HashMap<String, Any>): WeatherDomainModel { return try { val response = service.fetchLocationWeather(query) weatherRemoteMapper.toDomain(response) } catch (throwable: Throwable) { throw throwable } } override suspend fun fetchDailyWeatherForecast(query: HashMap<String, Any>): List<WeatherDomainModel> { return try { val response = service.fetchDailyWeather(query).list response.map { weatherRemoteMapper.toDomain(it) } } catch (throwable: Throwable) { throw throwable } } }
0
Kotlin
0
0
cd5bdcd77a7f38be132a2fa785eaa70f0c57fdf2
1,108
weatheapp-MADS04
The Unlicense
app/src/main/java/com/vvwxx/bangkit/restaurantapp/di/Injection.kt
AdnSmile
639,550,491
false
null
package com.vvwxx.bangkit.restaurantapp.di import android.content.Context import com.vvwxx.bangkit.restaurantapp.data.RestaurantRepository import com.vvwxx.bangkit.restaurantapp.data.local.RestaurantDatabase import com.vvwxx.bangkit.restaurantapp.data.remote.retrofit.ApiConfig object Injection { fun provideRepository(context: Context): RestaurantRepository { val apiService = ApiConfig.getApiService() val database = RestaurantDatabase.getDatabase(context) val dao = database.restaurantDao() return RestaurantRepository.getInstance(apiService, dao) } }
0
Kotlin
0
0
5260d3e502957874e346071d107d443cd6e69202
596
restaurant-app
MIT License
app/src/main/java/com/ozkan/weatherapp/presentation/main_screen/daily_weather_screen/PerDayWeatherDisplay.kt
ozkantuncel
525,074,814
false
{"Kotlin": 61118}
package com.ozkan.weatherapp.presentation.main_screen.daily_weather_screen import androidx.compose.animation.animateContentSize import androidx.compose.animation.core.LinearOutSlowInEasing import androidx.compose.animation.core.tween import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Image 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.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Card import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import com.ozkan.weatherapp.domain.weather.WeatherPerData import com.ozkan.weatherapp.presentation.main_screen.WeatherState import com.ozkan.weatherapp.presentation.ui.theme.DeepBlue import java.time.format.DateTimeFormatter @ExperimentalMaterialApi @Composable fun PerDayWeatherDisplay( weatherPerDayData: WeatherPerData, weatherState: WeatherState, index: Int? = 0, modifier: Modifier ) { val formattedTimeDayAndMonth = remember(weatherPerDayData) { weatherPerDayData.time.format( DateTimeFormatter.ofPattern("MMM dd") ) } val formattedTimeDayName = remember(weatherPerDayData) { weatherPerDayData.time.format( DateTimeFormatter.ofPattern("EEEE") ) } var expand by remember { mutableStateOf(false) } var stroke by remember { mutableStateOf(1) } Card( modifier = Modifier .animateContentSize( animationSpec = tween( durationMillis = 400, easing = LinearOutSlowInEasing ) ) .padding(8.dp), backgroundColor = DeepBlue, shape = RoundedCornerShape(8.dp), border = BorderStroke(stroke.dp, Color.White), onClick = { expand = !expand stroke = if (expand) 2 else 1 println(index) } ) { Column(modifier = Modifier.fillMaxWidth()) { Row( modifier = modifier, horizontalArrangement = Arrangement.SpaceBetween ) { Column() { Text( text = formattedTimeDayName, color = Color.LightGray ) Spacer(modifier = Modifier.padding(5.dp)) Text( text = formattedTimeDayAndMonth, color = Color.LightGray ) } Image( painter = painterResource(id = weatherPerDayData.weatherType.iconRes), contentDescription = null, modifier = Modifier.width(40.dp) ) Column() { Text( text = "En Yüksek: ${weatherPerDayData.temperaturemaxday}C", color = Color.LightGray ) Text( text = "En Düşük: ${weatherPerDayData.temperatureminday}C", color = Color.LightGray ) } } if (expand) { PerDayHourlyWeather(state = weatherState, index = index) } } } }
0
Kotlin
0
3
356eaf7c25ae02017405c7a1bdb2efc8c33dc211
4,006
WeatherApp-Jetpack-Compose
The Unlicense
app/src/main/java/com/example/nhlstats/features/teams/domain/PositionType.kt
NoNews
232,546,746
false
null
package com.example.nhlstats.features.teams.domain enum class PositionType { FORWARD, GOALIE, DEFENSEMAN }
0
Kotlin
0
0
18f690067cef42cf29577aa691f47b0c77c9d67c
111
NHL
Apache License 2.0
vtp-pensjon-application/src/main/kotlin/no/nav/pensjon/vtp/auth/Utils.kt
navikt
254,055,233
false
{"Kotlin": 911727, "TypeScript": 78108, "JavaScript": 67530, "HTML": 1723, "Dockerfile": 494, "CSS": 366, "SCSS": 338}
package no.nav.pensjon.vtp.auth import com.nimbusds.oauth2.sdk.ParseException import com.nimbusds.oauth2.sdk.auth.PrivateKeyJWT import java.nio.charset.StandardCharsets import java.util.* import java.util.Base64.getDecoder fun getUser(authorization: String?): String? = if (authorization?.lowercase(Locale.getDefault())?.startsWith("basic") == true) { String(getDecoder().decode(authorization.substring("Basic".length).trim()), StandardCharsets.UTF_8).split(":") .firstOrNull() } else { null } fun getClientId(clientAssertion: String?, clientAssertionType: String?): String? = try { PrivateKeyJWT.parse("client_assertion_type=$clientAssertionType&client_assertion=$clientAssertion").clientID.value } catch (_: ParseException) { null }
6
Kotlin
0
1
32caad695463f5554e0acbdeb36c2e24be5eb105
785
vtp-pensjon
MIT License
core/common/src/main/kotlin/core/common/ListExt.kt
Kt-Kraft
868,318,173
false
{"Kotlin": 106999, "Shell": 3484}
package core.common public fun <T> List<T>.rotate(distance: Int): List<T> { val listSize = this.size if (listSize == 0) return this val normalizedDistance = (distance % listSize + listSize) % listSize return this.drop(normalizedDistance) + this.take(normalizedDistance) }
0
Kotlin
0
0
153bbc744f244b02001ae244924a6ef061bb2467
281
easy-android
MIT License
src/test/java/pl/edu/zut/mad/schedule/login/MessageProviderLoginTest.kt
MADWI
85,480,616
false
{"Kotlin": 123928}
package pl.edu.zut.mad.schedule.login import okhttp3.ResponseBody import org.assertj.core.api.Assertions.assertThat import org.junit.Test import pl.edu.zut.mad.schedule.R import retrofit2.HttpException import retrofit2.Response import java.lang.Exception @Suppress("IllegalIdentifier") class MessageProviderLoginTest { private val messageProvider = MessageProviderLogin() @Test fun `provider return res id album number not found when error is 404`() { val httpError = getHttpErrorWithCode(404) val messageId = messageProvider.getResIdByError(httpError) assertThat(R.string.error_album_number_not_found).isEqualTo(messageId) } @Test fun `provider return res id database update when error is 503`() { val httpError = getHttpErrorWithCode(503) val messageId = messageProvider.getResIdByError(httpError) assertThat(R.string.error_service_database_update).isEqualTo(messageId) } @Test fun `provider return res id internal when error is 500`() { val httpError = getHttpErrorWithCode(500) val messageId = messageProvider.getResIdByError(httpError) assertThat(R.string.error_service_internal).isEqualTo(messageId) } @Test fun `provider return res id unrecognized in other cases`() { val messageId = messageProvider.getResIdByError(Exception()) assertThat(R.string.error_service_unrecognized).isEqualTo(messageId) } private fun getHttpErrorWithCode(code: Int): HttpException { val responseBody = ResponseBody.create(null, "") val response: Response<String> = Response.error(code, responseBody) return HttpException(response) } }
2
Kotlin
0
0
ad79a44025399c11372630ba3041190f27fe904d
1,707
schedule
Apache License 2.0
src/main/java/net/dankrushen/tdhbot/commands/BaseCommand.kt
ButterscotchV
184,464,770
false
{"Kotlin": 54121}
package net.dankrushen.tdhbot.commands import com.jagrosh.jdautilities.command.Command import com.jagrosh.jdautilities.command.CommandEvent import net.dankrushen.tdhbot.BotUtils import net.dankrushen.tdhbot.TDHBot abstract class BaseCommand(val tdhBot: TDHBot) : Command() { companion object { var errorNumber = 0 } private val commands = mutableMapOf<Int, (CommandEvent, Array<String>) -> Unit>() override fun execute(cmdEvent: CommandEvent) { try { cmdEvent.message.addReaction(BotUtils.processingEmoji).complete() val args = CommandUtils.stringToArgs(cmdEvent.args) val command = getCommand(args.size) if (command != null) { command(cmdEvent, args) } else { cmdEvent.replyError("Incorrect number of arguments.") } } catch (e: Exception) { val errorNumber = ++errorNumber println("Error #$errorNumber") e.printStackTrace() cmdEvent.reactError() cmdEvent.replyError("Check logs for error #$errorNumber\n```\n${e.message}\n```") } finally { CommandUtils.removeReaction(cmdEvent, BotUtils.processingEmoji) } } fun getCommand(numArgs: Int = 0): ((CommandEvent, Array<String>) -> Unit)? { // Closest as in closest below numArgs var closestEntry: Map.Entry<Int, (CommandEvent, Array<String>) -> Unit>? = null for (entry in commands) { // If the number of arguments matches exactly, return this immediately if (entry.key == numArgs) return entry.value // For entries with the same or less arguments, find the maximum argument command if (entry.key <= numArgs && (closestEntry == null || entry.key > closestEntry.key)) { closestEntry = entry } } return closestEntry?.value } fun setCommand(numArgs: Int = 0, body: (CommandEvent, Array<String>) -> Unit) { if (numArgs < 0) throw IllegalArgumentException("numArgs must not be less than 0") commands[numArgs] = body } fun removeCommand(numArgs: Int) { commands.remove(numArgs) } fun removeAllCommands() { commands.clear() } }
0
Kotlin
0
0
4dd9b5c60c468259e273dbf8b76a437c551950b5
2,327
tdhbot
MIT License
imagego_picasso/src/main/java/com/fungo/imagego/picasso/transform/CircleTransformation.kt
xintao222
232,958,313
false
null
package com.fungo.imagego.picasso.transform import android.graphics.* import com.squareup.picasso.Transformation /** * @author Pinger * @since 18-10-31 下午4:18 * * Picasso 绘制圆形图片,并且可以绘制圆形边框,指定边框颜色 * * @param borderColor 边框颜色 * @param borderWidth 边框宽度 * */ class CircleTransformation(private val borderWidth: Int = 0, borderColor: Int = 0) : Transformation { /** * 绘制边框的画笔 */ private var mBorderPaint = Paint() /** * 设置画笔的属性 */ init { mBorderPaint.isDither = true mBorderPaint.isAntiAlias = true mBorderPaint.color = borderColor mBorderPaint.style = Paint.Style.STROKE mBorderPaint.strokeWidth = borderWidth.toFloat() } override fun transform(source: Bitmap?): Bitmap? { if (source == null) return source val width = source.width val height = source.height val size: Int = Math.min(width, height) val x: Int = (width - size) / 2 val y: Int = (height - size) / 2 val squaredBitmap: Bitmap = Bitmap.createBitmap(source, x, y, size, size) if (squaredBitmap != source) { source.recycle() } val bitmap: Bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888) //绘制圆形 val canvas = Canvas(bitmap) val paint = Paint() // 设置shader val shader = BitmapShader(squaredBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP) paint.shader = shader paint.isAntiAlias = true // 将边框和圆形画到canvas上 val r: Float = size / 2f val r1: Float = (size - 2 * borderWidth) / 2f canvas.drawCircle(r, r, r1, paint) canvas.drawCircle(r, r, r1, mBorderPaint) squaredBitmap.recycle() return bitmap } override fun key(): String { return "picasso circle" } }
0
Kotlin
1
0
eca4f2c59c0e4a8bbc159d750168c3d694d4f351
1,862
ImageGo
Apache License 2.0
lib/src/main/kotlin/com/github/mrbean355/dota2/json/transform/TeamDraftTransformer.kt
MrBean355
303,105,754
false
null
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.mrbean355.dota2.json.transform import com.github.mrbean355.dota2.draft.DraftHero import com.github.mrbean355.dota2.draft.TeamDraft import com.github.mrbean355.dota2.draft.TeamDraftImpl import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonTransformingSerializer import kotlinx.serialization.json.addJsonObject import kotlinx.serialization.json.buildJsonArray import kotlinx.serialization.json.jsonObject /** * Merges multiple pick and ban fields: * ``` * { * "pick0_id": 19, * "pick0_class": "tiny", * "pick1_id": 0, * "pick1_class": "", * "ban0_id": 135, * "ban0_class": "dawnbreaker", * "ban1_id": 101, * "ban1_class": "skywrath_mage" * } * ``` * Into arrays: * ``` * { * "picks": [ * { "id": 19, "name": "tiny" }, * { "id": 0, "name": "" } * ], * "bans": [ * { "id": 135, "name": "dawnbreaker" }, * { "id": 101, "name": "skywrath_mage" } * ] * } * ``` */ internal object TeamDraftTransformer : JsonTransformingSerializer<TeamDraftImpl>(TeamDraftImpl.serializer()) { private const val PickPrefix = "pick" private const val BanPrefix = "ban" override fun transformDeserialize(element: JsonElement): JsonElement { val root = element.jsonObject val picks = root.extractArray(PickPrefix) val bans = root.extractArray(BanPrefix) val transformed = root .filterNot { it.key.startsWith(PickPrefix) || it.key.startsWith(BanPrefix) } .plus(TeamDraft::picks.name to picks) .plus(TeamDraft::bans.name to bans) return JsonObject(transformed) } private fun JsonObject.extractArray(kind: String): JsonArray { val regex = """$kind(\d+)_id""".toRegex() val clazz = "$kind%s_class" return buildJsonArray { forEach { (key, value) -> regex.matchEntire(key)?.let { match -> addJsonObject { put(DraftHero::id.name, value) put(DraftHero::name.name, getValue(clazz.format(match.groupValues[1]))) } } } } } }
0
Kotlin
0
6
59193d7f2a5b8566569fd83698f38f9410a54034
2,865
dota2-gsi
Apache License 2.0
app/src/main/java/com/klamerek/fantasyrealms/screen/CustomActivity.kt
benjamin-klamerek
291,635,739
false
null
package com.klamerek.fantasyrealms.screen import android.content.Context import androidx.appcompat.app.AppCompatActivity import com.klamerek.fantasyrealms.util.LocaleManager abstract class CustomActivity : AppCompatActivity() { override fun attachBaseContext(base: Context?) { super.attachBaseContext(LocaleManager.updateContextWithPreferredLanguage(base!!)) } }
2
Kotlin
6
7
8c92031cfd21f357b36f9c408f26f9dbdcd8e654
384
fantasy-realm-scoring
MIT License
data/src/main/java/com/jyproject/data/features/seoulbike/SeoulBikeRepositoryImpl.kt
JunYeong0314
778,833,940
false
{"Kotlin": 208970}
package com.jyproject.data.features.seoulbike import com.jyproject.data.mappers.SeoulBikeMapper import com.jyproject.data.remote.service.seoulbike.GetSeoulBikeInfoService import com.jyproject.domain.features.seoulbike.SeoulBikeRepository import com.jyproject.domain.models.SeoulBike import javax.inject.Inject class SeoulBikeRepositoryImpl @Inject constructor( private val seoulBikeInfoService: GetSeoulBikeInfoService, private val seoulBikeMapper: SeoulBikeMapper ): SeoulBikeRepository { override suspend fun getCycleInfo(regionName: String): Result<List<SeoulBike>?> { return runCatching { val result = seoulBikeInfoService.getSeoulBikeInfo(regionName).body() result?.let { seoulBikeMapper.mapperToSeoulBike(it) } } } }
0
Kotlin
0
0
edb71cf4db51cee1593aa31c66c25d616492d24c
809
PlacePick
MIT License
main/src/main/java/com/work/theIsle/app/BaseAppActivity.kt
Tiannuo
498,562,269
false
{"Kotlin": 218272, "Java": 43175}
package com.work.theIsle.app import com.work.baselib.activity.BaseActivity import com.work.theIsle.hilt.httpProcessor.IHttpProcessor /** * @Author TIKOU * @Date 2022/7/16-19:47 * @Email <EMAIL> & <EMAIL> * @Description */ abstract class BaseAppActivity : BaseActivity() { public fun getBaseHttp(): IHttpProcessor { return (application as BaseApp).baseHttp } }
0
Kotlin
2
4
bf02c12830d80c6bcf7441c50c3f685d322fdf53
382
AndroidWork
Apache License 2.0
src/main/kotlin/com/foxentry/foxentrysdk/models/LocationGetRequest.kt
Foxentry
830,077,226
false
{"Kotlin": 442689}
/** * Foxentry API reference * * The version of the OpenAPI document: 2.0 Contact: <EMAIL> * * NOTE: This file is auto generated. Do not edit the file manually. */ package com.foxentry.foxentrysdk.models import com.fasterxml.jackson.annotation.JsonValue import com.fasterxml.jackson.databind.annotation.JsonDeserialize import com.foxentry.foxentrysdk.core.* @JsonDeserialize(`as` = LocationGetRequestImpl::class) interface LocationGetRequest { val customId: String? val query: LocationGetRequestQuery val options: LocationGetRequestOptions? val client: ClientRequest? } data class LocationGetRequestImpl( override val customId: String?, override val query: LocationGetRequestQuery, override val options: LocationGetRequestOptions?, override val client: ClientRequest?, ) : LocationGetRequest @JsonDeserialize(`as` = LocationGetRequestQueryImpl::class) interface LocationGetRequestQuery { val country: String val id: String } data class LocationGetRequestQueryImpl( override val country: String, override val id: String, ) : LocationGetRequestQuery /** Query options. */ @JsonDeserialize(`as` = LocationGetRequestOptionsImpl::class) interface LocationGetRequestOptions { val idType: LocationGetRequestOptionsIdType val dataScope: LocationGetRequestOptionsDataScope val dataSource: List<String?>? val zipFormat: Boolean? val cityFormat: LocationGetRequestOptionsCityFormat? } data class LocationGetRequestOptionsImpl( override val idType: LocationGetRequestOptionsIdType, override val dataScope: LocationGetRequestOptionsDataScope, override val dataSource: List<String?>?, override val zipFormat: Boolean?, override val cityFormat: LocationGetRequestOptionsCityFormat?, ) : LocationGetRequestOptions /** * Internal is assigned by Foxentry. External ID may vary for every supported country. CZ = RUIAN, * PL = Government data, SK = no external ID. */ enum class LocationGetRequestOptionsIdType(@JsonValue val value: String) { INTERNAL("internal"), EXTERNAL("external"), } /** Data scope of returned data. */ enum class LocationGetRequestOptionsDataScope(@JsonValue val value: String) { BASIC("basic"), FULL("full"), } /** * This option determines the format in which the city is returned. <b>Minimal</b> = Praha, * <b>basic</b> = Praha 8, <b>extended</b> = Praha 8 - Karlín. */ enum class LocationGetRequestOptionsCityFormat(@JsonValue val value: String) { MINIMAL("minimal"), BASIC("basic"), EXTENDED("extended"), }
0
Kotlin
0
0
8b215f6df68bd39c86ca0d44689e55704cc39457
2,512
kotlin-sdk
MIT License
app/src/main/java/com/smassive/stararchwars/infrastructure/StarArchWarsApplication.kt
SmasSive
117,000,445
false
null
package com.smassive.stararchwars.infrastructure import android.app.Application import android.content.Context import android.os.StrictMode import com.github.salomonbrys.kodein.Kodein import com.github.salomonbrys.kodein.KodeinAware import com.github.salomonbrys.kodein.android.autoAndroidModule import com.github.salomonbrys.kodein.conf.ConfigurableKodein import com.smassive.stararchwars.BuildConfig import com.smassive.stararchwars.infrastructure.di.appModule class StarArchWarsApplication : Application(), KodeinAware { override val kodein = ConfigurableKodein(mutable = true) override fun onCreate() { super.onCreate() if (BuildConfig.DEBUG) { StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() // or .detectAll() for all detectable problems .penaltyLog() .build()) StrictMode.setVmPolicy(StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .detectLeakedClosableObjects() .penaltyLog() .penaltyDeath() .build()) } initializeInjector() } private fun initializeInjector() { kodein.clear() kodein.addImport(autoAndroidModule(asApp())) kodein.addImport(appModule(asApp())) } fun addModule(activityModule: Kodein.Module) { kodein.addImport(activityModule, allowOverride = true) } } fun Context.asApp() = this.applicationContext as StarArchWarsApplication
0
Kotlin
0
2
9a54d282005088eeabb8ca76203947c2b793a556
1,497
star-arch-wars
Apache License 2.0
library/src/main/java/com/luckyhan/studio/mokaeditor/UpdateSpan.kt
junhanRyu
365,757,498
false
{"Kotlin": 54117}
package com.luckyhan.studio.mokaeditor import android.text.TextPaint import android.text.style.MetricAffectingSpan class UpdateSpan : MetricAffectingSpan() { override fun updateDrawState(tp: TextPaint?) { } override fun updateMeasureState(textPaint: TextPaint) { } }
1
Kotlin
0
4
64baa5e0561e06a47ca2806abeb3f6f145609929
287
MokaEditor
Apache License 2.0
src/main/kotlin/ru/zahara/cookielib/other/WorldUtils.kt
GoogeTan
398,628,946
false
null
@file:JvmName("WorldUtils") package ru.zahara.cookielib.other import net.minecraft.block.Block import net.minecraft.block.BlockState import net.minecraft.client.Minecraft import net.minecraft.client.entity.player.ClientPlayerEntity import net.minecraft.client.world.ClientWorld import net.minecraft.entity.Entity import net.minecraft.entity.player.PlayerEntity import net.minecraft.item.ItemStack import net.minecraft.server.MinecraftServer import net.minecraft.state.Property import net.minecraft.tileentity.TileEntity import net.minecraft.util.math.AxisAlignedBB import net.minecraft.util.math.BlockPos import net.minecraft.world.IWorld import net.minecraft.world.World import net.minecraftforge.fml.server.ServerLifecycleHooks import java.lang.IndexOutOfBoundsException /** * Мир на клиентической стороне. На сервере равен null */ @get:JvmName("getClientWorld") val clientWorld : ClientWorld? get() = try { Minecraft.getInstance().world } catch (e : Exception) { null } /** * Игрок на клиентической стороне. На сервере равен null */ @get:JvmName("getClientPlayer") val clientPlayer : ClientPlayerEntity? get() = try { Minecraft.getInstance().player } catch (e : Exception) { null } /** * Вовращает объект клиента. На сервере равен null */ @get:JvmName("getClient") val client : Minecraft? get() = try { Minecraft.getInstance() } catch (e : Exception) { null } /** * Вовзращает объект сервера. */ @get:JvmName("getServer") val server : MinecraftServer? get() = client?.integratedServer ?: ServerLifecycleHooks.getCurrentServer() /** * Возвращает `true` если [World] находится на серверной стороне. */ @get:JvmName("isServerWorld") val World.isNotRemote get() = !this.isRemote /** * Возвращает `true` если [PlayerEntity] находится на серверной стороне. */ @get:JvmName("isServerPlayer") val PlayerEntity.isNotRemote get() = !world.isRemote /** * Возвращает `true` если [PlayerEntity] находится на клиентической стороне. */ @get:JvmName("isClientPlayer") val PlayerEntity.isRemote get() = world.isRemote /** * Пытается получить [TileEntity] данного класса/интерфейса Type на данной позиции. * @param pos позиция искомого тайла * @param Type класс искомого тайла */ inline fun<reified Type> IWorld.getTileAt(pos : BlockPos) = getTileEntity(pos) as? Type /** * Ломает блок в мире от лица entity. * * @param shouldDrop должен ли выпасть дроп. * @param entity Кто ломает блок. * @param stack Чем ломается блок. */ @Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS", "NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS") fun World.destroyBlock(pos: BlockPos, shouldDrop: Boolean, entity: Entity?, stack: ItemStack) : Boolean { val state = this[pos] return if (state.isAir(this, pos)) { false } else { val fluidState = this.getFluidState(pos) if (shouldDrop) { val tile = if (state.hasTileEntity()) this.getTileEntity(pos) else null Block.spawnDrops(state, this, pos, tile, entity, stack) } this.setBlockState(pos, fluidState.blockState) } } /** * Удобный способ получения блока на позиции. Эквивалентен [IWorld.getBlockState] */ operator fun IWorld.get(pos: BlockPos) : BlockState = this.getBlockState(pos) /** * Удобный способ установки блока на позицию. Эквивалентен [IWorld.setBlockState] */ operator fun IWorld.set(pos: BlockPos, state : BlockState, flag : Int) : Boolean = this.setBlockState(pos, state, flag) /** * Удобный способ установки блока на позицию. Эквивалентен [IWorld.setBlockState] */ operator fun IWorld.set(pos: BlockPos, state : BlockState) : Boolean = this.setBlockState(pos, state, 3) /** * Удобный способ получения проперти у блока на позиции. Эквивалентен: [IWorld.getBlockState] + [BlockState.get] */ operator fun <T : Comparable<T>> World.get(pos: BlockPos, property: Property<T>) : T = this[pos][property] /** * Удобный способ установки проперти у блока на позиции. Эквивалентен установке блока с изменением 1 проперти: [IWorld.getBlockState] + [BlockState.with] + [IWorld.setBlockState] */ operator fun <T : Comparable<T>, V : T> World.set(pos: BlockPos, property: Property<T>, value: V) { val state = this[pos] this[pos] = state.with(property, value) } inline operator fun BlockPos.component3(): Int = z inline operator fun BlockPos.component2(): Int = y inline operator fun BlockPos.component1(): Int = x inline operator fun AxisAlignedBB.component1() = BlockPos(minX, minY, minZ) inline operator fun AxisAlignedBB.component2() = BlockPos(maxX, minY, minZ) inline operator fun AxisAlignedBB.component3() = BlockPos(minX, maxY, minZ) inline operator fun AxisAlignedBB.component4() = BlockPos(minX, minY, maxZ) inline operator fun AxisAlignedBB.component5() = BlockPos(maxX, maxY, minZ) inline operator fun AxisAlignedBB.component6() = BlockPos(minX, maxY, maxZ) inline operator fun AxisAlignedBB.component7() = BlockPos(maxX, minY, maxZ) inline operator fun AxisAlignedBB.component8() = BlockPos(maxX, maxY, maxZ) class AxisAlignedBBIterator(val box : AxisAlignedBB) : Iterator<BlockPos> { constructor(pos1 : BlockPos, pos2 : BlockPos) : this(AxisAlignedBB(pos1, pos2)) var blockPos : BlockPos.Mutable = box.component1().toMutable() override fun next(): BlockPos { return if (blockPos.x == box.maxX.toInt()) { if (blockPos.y == box.maxY.toInt()) { if (blockPos.z == box.minZ.toInt()) throw IndexOutOfBoundsException() else blockPos.toImmutable().also { blockPos.move((box.minX - box.maxX).toInt(), (box.minY - box.maxY).toInt(), 1) } } else blockPos.toImmutable().also { blockPos.move((box.minX - box.maxX).toInt(), 1, 0) } } else blockPos.toImmutable().also { blockPos.move(1, 0, 0) } } override fun hasNext(): Boolean { return blockPos.x < box.maxX || blockPos.y < box.maxY || blockPos.z < box.maxZ } } operator fun BlockPos.rangeTo(other : BlockPos) = AxisAlignedBB(this, other) operator fun AxisAlignedBB.iterator() = AxisAlignedBBIterator(this) operator fun BlockPos.plus(box : AxisAlignedBB) = AxisAlignedBB(x + box.minX, y + box.minY, z + box.minZ, x + box.maxX, y + box.maxX, z + box.maxZ) operator fun AxisAlignedBB.plus(pos : BlockPos) = AxisAlignedBB(pos.x + minX, pos.y + minY, pos.z + minZ, pos.x + maxX, pos.y + maxX, pos.z + maxZ)
0
Kotlin
0
0
4b85acb31ec3985403f9677986cb484ac1e07001
6,522
CookieLib
MIT License
domain/src/main/java/com/ps/domain/utils/Result.kt
satyamgarg
709,651,406
false
{"Kotlin": 69827, "Java": 47915}
package com.ps.domain.utils sealed interface Result<T> { data class Success<T>(val data: T) : Result<T> data class Error<T>(val errorMessage: String) : Result<T> data class Exception<T>(val throwable: Throwable) : Result<T> }
0
Kotlin
0
0
c3f26dbb729ae89a51dc3f498ef1bb65692cddb0
247
ps-movie-app
MIT License
SceytChatUiKit/src/main/java/com/sceyt/sceytchatuikit/presentation/uicomponents/mediaview/videoview/scalableVideoView/ScaleManager.kt
sceyt
549,073,085
false
null
package com.sceyt.sceytchatuikit.presentation.uicomponents.mediaview.videoview.scalableVideoView import android.graphics.Matrix class ScaleManager(private val mViewSize: Size, private val mVideoSize: Size) { fun getScaleMatrix(scalableType: ScalableType?): Matrix? { return when (scalableType) { ScalableType.NONE -> noScale ScalableType.FIT_XY -> fitXY() ScalableType.FIT_CENTER -> fitCenter() ScalableType.FIT_START -> fitStart() ScalableType.FIT_END -> fitEnd() ScalableType.LEFT_TOP -> getOriginalScale(PivotPoint.LEFT_TOP) ScalableType.LEFT_CENTER -> getOriginalScale(PivotPoint.LEFT_CENTER) ScalableType.LEFT_BOTTOM -> getOriginalScale(PivotPoint.LEFT_BOTTOM) ScalableType.CENTER_TOP -> getOriginalScale(PivotPoint.CENTER_TOP) ScalableType.CENTER -> getOriginalScale(PivotPoint.CENTER) ScalableType.CENTER_BOTTOM -> getOriginalScale(PivotPoint.CENTER_BOTTOM) ScalableType.RIGHT_TOP -> getOriginalScale(PivotPoint.RIGHT_TOP) ScalableType.RIGHT_CENTER -> getOriginalScale(PivotPoint.RIGHT_CENTER) ScalableType.RIGHT_BOTTOM -> getOriginalScale(PivotPoint.RIGHT_BOTTOM) ScalableType.LEFT_TOP_CROP -> getCropScale(PivotPoint.LEFT_TOP) ScalableType.LEFT_CENTER_CROP -> getCropScale(PivotPoint.LEFT_CENTER) ScalableType.LEFT_BOTTOM_CROP -> getCropScale(PivotPoint.LEFT_BOTTOM) ScalableType.CENTER_TOP_CROP -> getCropScale(PivotPoint.CENTER_TOP) ScalableType.CENTER_CROP -> getCropScale(PivotPoint.CENTER) ScalableType.CENTER_BOTTOM_CROP -> getCropScale(PivotPoint.CENTER_BOTTOM) ScalableType.RIGHT_TOP_CROP -> getCropScale(PivotPoint.RIGHT_TOP) ScalableType.RIGHT_CENTER_CROP -> getCropScale(PivotPoint.RIGHT_CENTER) ScalableType.RIGHT_BOTTOM_CROP -> getCropScale(PivotPoint.RIGHT_BOTTOM) ScalableType.START_INSIDE -> startInside() ScalableType.CENTER_INSIDE -> centerInside() ScalableType.END_INSIDE -> endInside() else -> null } } private fun getMatrix(sx: Float, sy: Float, px: Float, py: Float): Matrix { val matrix = Matrix() matrix.setScale(sx, sy, px, py) return matrix } private fun getMatrix(sx: Float, sy: Float, pivotPoint: PivotPoint): Matrix { return when (pivotPoint) { PivotPoint.LEFT_TOP -> getMatrix(sx, sy, 0f, 0f) PivotPoint.LEFT_CENTER -> getMatrix(sx, sy, 0f, mViewSize.height / 2f) PivotPoint.LEFT_BOTTOM -> getMatrix(sx, sy, 0f, mViewSize.height.toFloat()) PivotPoint.CENTER_TOP -> getMatrix(sx, sy, mViewSize.width / 2f, 0f) PivotPoint.CENTER -> getMatrix(sx, sy, mViewSize.width / 2f, mViewSize.height / 2f) PivotPoint.CENTER_BOTTOM -> getMatrix( sx, sy, mViewSize.width / 2f, mViewSize.height.toFloat() ) PivotPoint.RIGHT_TOP -> getMatrix(sx, sy, mViewSize.width.toFloat(), 0f) PivotPoint.RIGHT_CENTER -> getMatrix( sx, sy, mViewSize.width.toFloat(), mViewSize.height / 2f ) PivotPoint.RIGHT_BOTTOM -> getMatrix( sx, sy, mViewSize.width.toFloat(), mViewSize.height.toFloat() ) } } private val noScale: Matrix get() { val sx = mVideoSize.width / mViewSize.width.toFloat() val sy = mVideoSize.height / mViewSize.height.toFloat() return getMatrix(sx, sy, PivotPoint.LEFT_TOP) } private fun getFitScale(pivotPoint: PivotPoint): Matrix { var sx = mViewSize.width.toFloat() / mVideoSize.width var sy = mViewSize.height.toFloat() / mVideoSize.height val minScale = sx.coerceAtMost(sy) sx = minScale / sx sy = minScale / sy return getMatrix(sx, sy, pivotPoint) } private fun fitXY(): Matrix { return getMatrix(1f, 1f, PivotPoint.LEFT_TOP) } private fun fitStart(): Matrix { return getFitScale(PivotPoint.LEFT_TOP) } private fun fitCenter(): Matrix { return getFitScale(PivotPoint.CENTER) } private fun fitEnd(): Matrix { return getFitScale(PivotPoint.RIGHT_BOTTOM) } private fun getOriginalScale(pivotPoint: PivotPoint): Matrix { val sx = mVideoSize.width / mViewSize.width.toFloat() val sy = mVideoSize.height / mViewSize.height.toFloat() return getMatrix(sx, sy, pivotPoint) } private fun getCropScale(pivotPoint: PivotPoint): Matrix { var sx = mViewSize.width.toFloat() / mVideoSize.width var sy = mViewSize.height.toFloat() / mVideoSize.height val maxScale = sx.coerceAtLeast(sy) sx = maxScale / sx sy = maxScale / sy return getMatrix(sx, sy, pivotPoint) } private fun startInside(): Matrix { return if (mVideoSize.height <= mViewSize.width && mVideoSize.height <= mViewSize.height ) { // video is smaller than view size getOriginalScale(PivotPoint.LEFT_TOP) } else { // either of width or height of the video is larger than view size fitStart() } } private fun centerInside(): Matrix { return if (mVideoSize.height <= mViewSize.width && mVideoSize.height <= mViewSize.height ) { // video is smaller than view size getOriginalScale(PivotPoint.CENTER) } else { // either of width or height of the video is larger than view size fitCenter() } } private fun endInside(): Matrix { return if (mVideoSize.height <= mViewSize.width && mVideoSize.height <= mViewSize.height ) { // video is smaller than view size getOriginalScale(PivotPoint.RIGHT_BOTTOM) } else { // either of width or height of the video is larger than view size fitEnd() } } }
0
Kotlin
0
0
0b135841180b7c4fdd66b1b0f7655d8d79fe8a03
6,289
sceyt-chat-android-uikit
MIT License
app/src/main/java/com/sebastijanzindl/galore/presentation/screens/forgotPassword/ForgotPasswordScreenViewModel.kt
m1thrandir225
743,270,603
false
{"Kotlin": 400176}
package com.sebastijanzindl.galore.presentation.screens.forgotPassword import android.util.Log import androidx.compose.material3.SnackbarDuration import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.sebastijanzindl.galore.presentation.component.SnackbarMessage import dagger.hilt.android.lifecycle.HiltViewModel import io.github.jan.supabase.gotrue.Auth import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class ForgotPasswordScreenViewModel @Inject constructor( private val auth: Auth, ) : ViewModel() { private val _isLoading = MutableStateFlow<Boolean>(false) val isLoading = _isLoading.asStateFlow() private val _toastMessage = MutableStateFlow<SnackbarMessage?>(null) val toastMessage = _toastMessage.asStateFlow() private val _magicLinkSent= MutableStateFlow<Boolean?>(null) val magicLinkSent = _magicLinkSent.asStateFlow() private fun sendToastMessage(message: String) { val snackbarMessage = SnackbarMessage.from( withDismissAction = false, userMessage = com.sebastijanzindl.galore.presentation.component.UserMessage.from(message), actionLabelMessage = null, onSnackbarResult = {}, duration = SnackbarDuration.Short ) _toastMessage.update { snackbarMessage } } fun dismissToast() { _toastMessage.update { null } } fun sendPasswordResetRequest(email: String) { viewModelScope.launch { try { _isLoading.value = true auth.resetPasswordForEmail(email) sendToastMessage("Please check your email") _magicLinkSent.value = true } catch (e: Exception) { e.message?.let { Log.e("Password Reset Request", it) } _magicLinkSent.value = false sendToastMessage("An error occurred") } finally { _isLoading.value = false } } } }
0
Kotlin
0
0
f578b800dbc6be3ab7421662176d8f4b7d652c03
2,169
galore-android
MIT License
plantcare/src/test/kotlin/com/projects/plantcare/PlantcareApplicationTests.kt
GhadgePrachi
610,027,176
false
null
package com.projects.plantcare import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class PlantcareApplicationTests { @Test fun contextLoads() { } }
0
Kotlin
0
0
8d6fe7f346aba977e03b875f968d79a1d282ba80
213
Backend-GRPC-MicroServices
Apache License 2.0
src/main/kotlin/br/com/zup/edu/pix/novachave/TipoDeChave.kt
caiorodrigueszup
385,247,255
true
{"Kotlin": 70251}
package br.com.zup.edu.pix.novachave import org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator import org.hibernate.validator.internal.constraintvalidators.hv.br.CPFValidator enum class TipoDeChave { CPF { override fun valida(chave: String?): Boolean { if (chave.isNullOrBlank()) { return false } if (!chave.matches("^[0-9]{11}\$".toRegex())) { return false } return CPFValidator().run { initialize(null) isValid(chave, null) } } }, CELULAR { override fun valida(chave: String?): Boolean { if (chave.isNullOrBlank()) { return false } return chave.matches("^\\+[1-9][0-9]\\d{1,14}$".toRegex()) } }, EMAIL { override fun valida(chave: String?): Boolean { if (chave.isNullOrBlank()) { return false } return EmailValidator().run { initialize(null) isValid(chave, null) } } }, ALEATORIA { override fun valida(chave: String?) = chave.isNullOrBlank() }; abstract fun valida(chave: String?): Boolean }
0
Kotlin
0
0
b5adb6b86b19cd7347b91f7cdc231e3961e48f64
1,297
orange-talents-05-template-pix-keymanager-grpc
Apache License 2.0
libs/imageLoader/src/main/java/top/sunhy/image/progress/OnProgressListener.kt
RDSunhy
421,280,382
false
null
package top.sunhy.image.progress //interface OnProgressListener { // fun onProgress(isComplete: Boolean, percentage: Int, bytesRead: Long, totalBytes: Long) //} //给函数起别名 便于调用和书写 typealias OnProgressListener = ((isComplete: Boolean, percentage: Int, bytesRead: Long, totalBytes: Long) -> Unit)?
0
Kotlin
0
0
ff8d615fceeb21169caba21df32e120e2ac783f6
299
android-component
Apache License 2.0
feature/settings/src/test/kotlin/com/lolo/io/onelist/feature/settings/fragment/SettingsFragmentViewModelTest.kt
lolo-io
198,519,184
false
{"Kotlin": 363415, "Roff": 549}
package com.lolo.io.onelist.feature.settings.fragment import android.net.Uri import com.lolo.io.onelist.core.testing.fake.FakeOneListRepository import com.lolo.io.onelist.core.testing.fake.FakeSharedPreferenceHelper import com.lolo.io.onelist.core.testing.fake.FakeUseCases import com.lolo.io.onelist.core.testing.rules.MainDispatcherRule import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import kotlin.test.assertContains import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue @RunWith(RobolectricTestRunner::class) class SettingsFragmentViewModelTest { @get:Rule val dispatcherRule = MainDispatcherRule() private lateinit var viewModel: SettingsFragmentViewModel private lateinit var fakeRepository: FakeOneListRepository private lateinit var fakePreferences: FakeSharedPreferenceHelper private lateinit var fakeUseCases: FakeUseCases @Before fun setUp() { viewModel = SettingsFragmentViewModel( FakeUseCases(FakeOneListRepository().also { fakeRepository = it }).also { fakeUseCases = it }, FakeSharedPreferenceHelper().also { fakePreferences = it } ) } @Test fun getPreferUseFiles() { fakePreferences.preferUseFiles = true val actualTrue = viewModel.preferUseFiles assertTrue(actualTrue) fakePreferences.preferUseFiles = false val actualFalse = viewModel.preferUseFiles assertFalse(actualFalse) } @Test fun getVersion() { fakePreferences.version = "1.2.3" val actual = viewModel.version assertEquals("1.2.3", actual) } @Test fun setBackupPath() { fakePreferences.preferUseFiles = true viewModel.setBackupPath(Uri.parse("fake/path"), "fake/path") assertGetterFunctionCalled( fakeUseCases.calledFunctions, FakeUseCases::setBackupUri.name ) assertTrue(fakePreferences.preferUseFiles) viewModel.setBackupPath(null, null) assertGetterFunctionCalled( fakeUseCases.calledFunctions, FakeUseCases::setBackupUri.name ) assertFalse(fakePreferences.preferUseFiles) } @Test fun importList() = runTest { viewModel.importList(Uri.EMPTY) assertGetterFunctionCalled( fakeUseCases.calledFunctions, FakeUseCases::importList.name ) } @Test fun backupAllListsOnDevice() = runTest { viewModel.backupAllListsOnDevice() assertGetterFunctionCalled( fakeUseCases.calledFunctions, FakeUseCases::syncAllLists.name ) } @Test fun onPreferUseFiles() { viewModel.onPreferUseFiles() assertGetterFunctionCalled( fakeUseCases.calledFunctions, FakeUseCases::loadAllLists.name ) } @Test fun getSyncFolderNotAccessible() { fakePreferences.setCanAccessBackupUri(true) val actualTrue = viewModel.syncFolderNotAccessible assertFalse(actualTrue) fakePreferences.setCanAccessBackupUri(false) val actualFalse = viewModel.syncFolderNotAccessible assertTrue(actualFalse) } private fun assertGetterFunctionCalled(calledFunctions: List<String>, functionName: String) { assertContains( fakeUseCases.calledFunctions.map { it.lowercase() }, "get${functionName.lowercase()}" ) } }
14
Kotlin
26
92
ca7df6ec46344bde7c5e357d0784ecdfdecbb78e
3,685
OneList
MIT License
platform/src/main/kotlin/researchstack/backend/adapter/outgoing/mongo/task/UpdateTaskSpecMongoAdapter.kt
S-ResearchStack
520,365,362
false
{"Kotlin": 1297198, "Dockerfile": 202, "Shell": 59}
package researchstack.backend.adapter.outgoing.mongo.task import kotlinx.coroutines.reactor.awaitSingle import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty import org.springframework.dao.DuplicateKeyException import org.springframework.stereotype.Component import researchstack.backend.adapter.outgoing.mongo.mapper.toEntity import researchstack.backend.adapter.outgoing.mongo.repository.TaskSpecRepository import researchstack.backend.application.exception.AlreadyExistsException import researchstack.backend.application.port.outgoing.task.UpdateTaskSpecOutPort import researchstack.backend.domain.task.TaskSpec @ConditionalOnProperty(name = ["database-type"], havingValue = "MONGO") @Component class UpdateTaskSpecMongoAdapter( private val taskSpecRepository: TaskSpecRepository ) : UpdateTaskSpecOutPort { override suspend fun updateTaskSpec(taskSpec: TaskSpec) { taskSpecRepository .findByIdAndStudyId(taskSpec.id, taskSpec.studyId) .flatMap { taskSpecRepository.save(taskSpec.toEntity()) } .onErrorMap(DuplicateKeyException::class.java) { AlreadyExistsException("duplicate key: ${it.message}") } .awaitSingle() } }
1
Kotlin
9
29
214dc84476e2de6948c3fc5225cebca0707bfb91
1,272
backend-system
Apache License 2.0
features/characters/src/main/java/com/developersancho/characters/detail/CharacterDetailContract.kt
developersancho
454,045,719
false
{"Kotlin": 643302}
package com.developersancho.characters.detail import com.developersancho.model.dto.character.CharacterDto data class CharacterDetailViewState( val character: CharacterDto? = null ) sealed class CharacterDetailEvent { data class LoadDetail(val id: Int) : CharacterDetailEvent() }
1
Kotlin
33
236
53d96f038e70712387f26a0099949c26a2aa2311
289
JetRorty.Android
Apache License 2.0
src/aoc23/Day05.kt
mihassan
575,356,150
false
{"Kotlin": 112702}
@file:Suppress("PackageDirectoryMismatch") package aoc23.day05 import kotlin.math.max import kotlin.math.min import lib.Collections.headTail import lib.Solution import lib.Strings.extractLongs import lib.Strings.longs enum class Category { SEED, SOIL, FERTILIZER, WATER, LIGHT, TEMPERATURE, HUMIDITY, LOCATION; companion object { fun parse(categoryStr: String) = Category.valueOf(categoryStr.uppercase()) } } data class Item(val category: Category, val number: Long) data class RangeMap(val srcRange: LongRange, val destRange: LongRange) { constructor(destRangeStart: Long, srcRangeStart: Long, rangeLength: Long) : this( srcRangeStart..<srcRangeStart + rangeLength, destRangeStart..<destRangeStart + rangeLength ) fun apply(srcNumber: Long): Long = when (srcNumber) { in srcRange -> srcNumber + destRange.first - srcRange.first else -> srcNumber } companion object { fun parse(rangeMapStr: String): RangeMap { val (destRangeStart, srcRangeStart, rangeLength) = rangeMapStr.longs() return RangeMap(destRangeStart, srcRangeStart, rangeLength) } } } data class CategoryMap( val srcCategory: Category, val destCategory: Category, val rangeMaps: List<RangeMap>, ) { fun apply(srcItem: Item): Item = when (srcItem.category) { srcCategory -> Item(destCategory, applyRangeMaps(srcItem.number)) else -> srcItem } private fun applyRangeMaps(srcNumber: Long): Long = rangeMaps .firstOrNull { srcNumber in it.srcRange } ?.apply(srcNumber) ?: srcNumber companion object { fun parse(categoryMapStr: String): CategoryMap { val (headerStr, rangesStr) = categoryMapStr.lines().headTail() val (srcCategoryStr, destCategoryStr) = HEADER_REGEX.matchEntire(headerStr!!)!!.destructured val srcCategory = Category.parse(srcCategoryStr) val destCategory = Category.parse(destCategoryStr) val rangeMaps = rangesStr.map(RangeMap.Companion::parse) return CategoryMap(srcCategory, destCategory, rangeMaps) } private val HEADER_REGEX = """(\w+)-to-(\w+) map:""".toRegex() } } data class Almanac(val seeds: List<Long>, val categoryMaps: List<CategoryMap>) { fun convert(item: Item, destCategory: Category): Item { var convertedItem = item while (convertedItem.category != destCategory) { convertedItem = categoryMaps .first { it.srcCategory == convertedItem.category } .apply(convertedItem) } return convertedItem } companion object { fun parse(almanacStr: String): Almanac { val (seedsStr, categoriesStr) = almanacStr.split("\n\n").headTail() val seeds = seedsStr!!.extractLongs() val categoryMaps = categoriesStr.map(CategoryMap.Companion::parse) return Almanac(seeds, categoryMaps) } } } typealias Input = Almanac typealias Output = Long private val solution = object : Solution<Input, Output>(2023, "Day05") { override fun parse(input: String): Input = Almanac.parse(input) override fun format(output: Output): String = "$output" override fun part1(input: Input): Output = input.seeds.map { seed -> input.convert(Item(Category.SEED, seed), Category.LOCATION) }.minOf { it.number } override fun part2(input: Input): Output { var result = Long.MAX_VALUE // Check all seeds in the given range which potentially skipping over some seeds. fun check(range: LongProgression): Long? { var minSeed: Long? = null var minLocation = result for (seed in range) { val location = input.convert(Item(Category.SEED, seed), Category.LOCATION) if (location.number < minLocation) { minSeed = seed minLocation = location.number } } result = min(result, minLocation) return minSeed } input.seeds.chunked(2) .forEach { (start, length) -> if (length < 1000000) { // For small ranges, check all seeds. check(start..<start + length) } else { // For large ranges, check in two stages. // Stage 1: Jump by 1,000 to get closer to the minimum seed. check(start..<start + length step 1000)?.let { minSeed -> // Stage 2: Check last 1,000 seeds (inclusive of minSeed) which we skipped earlier. // Care should be taken to not go past start. check(max(minSeed - 999, start)..minSeed) } } } return result } } fun main() = solution.run()
0
Kotlin
0
0
8b73716ecede41f5d908f303d34cbe63871aa608
4,535
aoc-kotlin
Apache License 2.0
app/src/main/java/org/mightyfrog/android/s4fd/settings/SettingsComponent.kt
dena-appleseed
85,302,865
true
{"Kotlin": 121067, "Java": 54160}
package org.mightyfrog.android.s4fd.settings import dagger.Component import org.mightyfrog.android.s4fd.AppComponent import org.mightyfrog.android.s4fd.util.ActivityScope /** * @author <NAME> */ @ActivityScope @Component(dependencies = arrayOf(AppComponent::class), modules = arrayOf(SettingsModule::class)) interface SettingsComponent { fun inject(fragment: SettingsFragment) }
0
Kotlin
0
0
99527af4124c33e3599160e5311da6dc9e32ad60
387
S4FD
Apache License 2.0
app/src/main/java/com/example/taxiservice/ViewModelWithSharedPReferenceFactory.kt
NovikFeed
744,641,153
false
{"Kotlin": 120000}
package com.example.taxiservice import android.app.Application import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider class ViewModelWithSharedPReferenceFactory(private val application: Application, private val sharedPreference : SharedPreferenceManager, private val repository: TaxiRepository) : ViewModelProvider.AndroidViewModelFactory(application) { override fun <T : ViewModel> create(modelClass: Class<T>): T { if(modelClass.isAssignableFrom(InZoneViewModel::class.java)){ return InZoneViewModel(application, sharedPreference, repository) as T } throw IllegalArgumentException("Unknown ViewMode Class ") } }
0
Kotlin
0
0
2a1f818de8a4b5740eafa27dbd220dad5fcc4b8d
775
taxi-service
MIT License
android/app/src/main/java/cloud/multipos/pos/models/Employee.kt
multipos-app
773,180,579
false
{"Kotlin": 548453, "Java": 306036}
/** * Copyright (C) 2023 multiPOS, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cloud.multipos.pos.models import cloud.multipos.pos.* import cloud.multipos.pos.db.* import cloud.multipos.pos.util.* import cloud.multipos.pos.receipts.* class Employee (val employee: Jar?): Jar (), Model { val deny = mutableListOf <String> () init { if (employee != null) { copy (employee) var employeeProfileResult = DbResult ("select pd.profile_class from profiles p, profile_permissions pd " + "where p.id = pd.profile_id and p.id = " + employee.getInt ("profile_id"), Pos.app.db) while (employeeProfileResult.fetchRow ()) { var employeeProfile = employeeProfileResult.row (); deny.add (employeeProfile.getString ("profile_class")); } } } fun deny (): MutableList <String> { return deny } override fun display (): String { val sb = StringBuffer () if (has ("fname") && (getString ("fname").length > 0)) { sb.append (getString ("fname") + " ") } if (has ("lname") && (getString ("lname").length > 0)) { sb.append (getString ("lname") + " ") } return sb.toString () } override fun update () { } override fun receipt (): PrintCommands { val pc = PrintCommands () pc .add (PrintCommand.getInstance ().directive (PrintCommand.CENTER_TEXT).text (Pos.app.getString ("clerk_desc"))) .add (PrintCommand.getInstance ().directive (PrintCommand.CENTER_TEXT).text (display ())) return pc } }
0
Kotlin
1
7
119bb0c86a5f9589e0219249b02f0f56d43120f7
2,128
pos
Apache License 2.0
app/src/main/java/net/omisoft/aborovskoy/umoriliviper/ui/main/di/MainModule.kt
OmiSoftNet
181,910,936
false
{"Kotlin": 21904}
package net.omisoft.aborovskoy.umoriliviper.ui.main.di import dagger.Module import dagger.Provides import net.omisoft.aborovskoy.umoriliviper.app.di.ActivityScope import net.omisoft.aborovskoy.umoriliviper.ui.main.* import net.omisoft.aborovskoy.umoriliviper.ui.main.api.MainApi import net.omisoft.aborovskoy.umoriliviper.ui.main.data.MainRepo import retrofit2.Retrofit @Module class MainModule { @Provides @ActivityScope fun api(retrofit: Retrofit) = retrofit.create(MainApi::class.java) @Provides @ActivityScope fun repository(api: MainApi) = MainRepo(api) @Provides @ActivityScope fun router(activity: MainActivity): MainContract.Router = MainRouter(activity) @Provides @ActivityScope fun presenter(router: MainContract.Router, interactor: MainInteractor) = MainPresenter(router, interactor) @Provides @ActivityScope fun interactor(repository: MainRepo) = MainInteractor(repository) }
0
Kotlin
20
38
a3ba3d8802343a79ddfaa8761af6a7b9a9f5b01c
955
android-viper-template
MIT License
utils/math/src/test/kotlin/io/bluetape4k/math/interpolation/LinearInterpolatorTest.kt
debop
625,161,599
false
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
package io.bluetape4k.math.interpolation class LinearInterpolatorTest: AbstractInterpolationTest() { override val interpolator: Interpolator = LinearInterpolator() }
0
Kotlin
0
1
ce3da5b6bddadd29271303840d334b71db7766d2
173
bluetape4k
MIT License
app/src/main/java/com/jiahaoliuliu/androidmvvmsample/di/component/PresentationComponent.kt
jiahaoliuliu
738,095,866
false
{"Kotlin": 23914}
package com.jiahaoliuliu.androidmvvmsample.di.component import com.jiahaoliuliu.androidmvvmsample.di.ActivityScope import com.jiahaoliuliu.androidmvvmsample.di.module.PresentationModule import com.jiahaoliuliu.androidmvvmsample.presentation.main.view.TopHeadlineActivity import dagger.Component @ActivityScope @Component(dependencies = [ApplicationComponent::class], modules = [PresentationModule::class]) interface PresentationComponent { fun inject(activity: TopHeadlineActivity) }
0
Kotlin
0
1
b317e01a2993c334827c82708fdedcf7fb9838af
490
AndroidMVVMSample
Apache License 2.0
src/main/kotlin/org/emgen/extensions/CharExtensions.kt
emilancius
234,365,097
false
null
package org.emgen.extensions import org.emgen.Operator object CharExtensions { fun Char.operator(): Boolean = this in Operator.values().map { it.value } fun Char.toOperator(): Operator = if (this.operator()) { Operator.values().find { it.value == this }!! } else { throw Exception("") } }
1
Kotlin
2
0
f73f335268f6cc41f6ccb18c69036081514c3aa5
349
sono-core
MIT License
app/src/main/java/com/liuyuchuan/easymusic/utils/ToastExt.kt
SirLYC
133,898,818
false
{"Kotlin": 135440}
package com.liuyuchuan.easymusic.utils import android.app.Activity import android.support.annotation.StringRes import android.support.v4.app.Fragment import android.widget.Toast /** * Created by Liu Yuchuan on 2018/5/2. */ fun Activity.toast(msg: String) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show() } fun Fragment.toast(msg: String) { Toast.makeText(context!!, msg, Toast.LENGTH_SHORT).show() } fun Activity.toast(@StringRes msgRes: Int) { Toast.makeText(this, msgRes, Toast.LENGTH_SHORT).show() } fun Fragment.toast(@StringRes msgRes: Int) { Toast.makeText(context!!, msgRes, Toast.LENGTH_SHORT).show() } fun Activity.toastLong(msg: String) { Toast.makeText(this, msg, Toast.LENGTH_LONG).show() } fun Fragment.toastLong(msg: String) { Toast.makeText(context!!, msg, Toast.LENGTH_LONG).show() } fun Activity.toastLong(@StringRes msgRes: Int) { Toast.makeText(this, msgRes, Toast.LENGTH_LONG).show() } fun Fragment.toastLong(@StringRes msgRes: Int) { Toast.makeText(context!!, msgRes, Toast.LENGTH_LONG).show() }
0
Kotlin
0
2
bfa45de49d2ab6d26b29afa0d1fbd87b6ca1cc1f
1,066
EasyMusic
Apache License 2.0
definitions-ecs/src/testFixtures/kotlin/fledware/ecs/definitions/test/EntityTest.kt
fledware
408,627,203
false
null
package fledware.ecs.definitions.test import fledware.definitions.DefinitionException import fledware.definitions.util.DefinitionReflectionException import fledware.definitions.util.ReflectCallerState import fledware.definitions.util.safeGet import fledware.ecs.definitions.entityDefinitions import fledware.ecs.definitions.instantiator.ComponentArgument import fledware.ecs.definitions.instantiator.EntityInstantiator import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertNull abstract class EntityTest { abstract fun createDriver(): ManagerDriver @Test fun canCreatePersonEntityWithArgs() = testCreatedPersonEntity { entityInstantiator("/person").createWithArgs(listOf( ComponentArgument("placement", "x", 1), ComponentArgument("placement", "y", 2), ComponentArgument("placement", "size", 3) )) } @Test fun canCreatePersonEntityWithMap() = testCreatedPersonEntity { entityInstantiator("/person").createWithNames(mapOf( "placement" to mapOf( "x" to 1, "y" to 2, "size" to 3 ) )) } private inline fun testCreatedPersonEntity(block: ManagerDriver.() -> Any) { val driver = createDriver() val placementClass = driver.componentClass("placement") val entity = driver.block() assertEquals("/person", driver.entityDefinitionType(entity)) assertEquals(1, driver.entityComponent(entity, placementClass).safeGet("x")) assertEquals(2, driver.entityComponent(entity, placementClass).safeGet("y")) assertEquals(3, driver.entityComponent(entity, placementClass).safeGet("size")) } @Test fun throwsOnMissingIncorrectNamesType() { val driver = createDriver() val entityInstantiator = driver.entityInstantiator("/person") val exception = assertFailsWith<DefinitionException> { entityInstantiator.createWithNames(mapOf("placement" to mapOf("size" to "big!", "x" to 4, "y" to 4))) } as DefinitionReflectionException assertMissingPlacementException(exception) } @Test fun throwsOnMissingIncorrectArgumentType() { val driver = createDriver() val entityInstantiator = driver.entityInstantiator("/person") val exception = assertFailsWith<DefinitionException> { entityInstantiator.createWithArgs(listOf( ComponentArgument("placement", "x", 4), ComponentArgument("placement", "y", 4), ComponentArgument("placement", "size", "big!") )) } as DefinitionReflectionException assertMissingPlacementException(exception) } private fun assertMissingPlacementException(exception: DefinitionReflectionException) { assertEquals("placement", exception.definition?.defName) assertEquals(ReflectCallerState.Valid, exception.arguments["x"]?.state) assertEquals(ReflectCallerState.Valid, exception.arguments["y"]?.state) assertEquals(ReflectCallerState.InvalidType, exception.arguments["size"]?.state) assertEquals("must be class kotlin.Int: is class java.lang.String (big!)", exception.arguments["size"]?.message) } @Test fun entityCanExtendAnotherEntity() { val driver = createDriver() val person = driver.entityInstantiator("/person") assertNull(person.definition.extends) assertEquals(mapOf( "placement" to mapOf(), "movement" to mapOf("deltaX" to 0, "deltaY" to 0), "health" to mapOf("health" to 5) ), person.defaultComponentValues) val coolguy = driver.entityInstantiator("/coolguy") assertEquals("/person", coolguy.definition.extends) assertEquals(mapOf( "placement" to mapOf(), "movement" to mapOf("deltaX" to 0, "deltaY" to 0), "health" to mapOf("health" to 10) ), coolguy.defaultComponentValues) val coolguy2 = driver.entityInstantiator("/coolguy2") assertEquals("/coolguy", coolguy2.definition.extends) assertEquals(mapOf( "placement" to mapOf(), "movement" to mapOf("deltaX" to 1, "deltaY" to 1), "health" to mapOf("health" to 10) ), coolguy2.defaultComponentValues) } }
3
Kotlin
0
0
1d3d0fcc0ad64ae0960be14bc38aa1600b6aea49
4,110
FledDefs
Apache License 2.0
app/src/main/java/com/expensify/budgettracker/BudgetDatabse.kt
Iksudha
546,746,988
false
{"Kotlin": 107004}
package com.expensify.budgettracker import androidx.room.Database import androidx.room.RoomDatabase @Database(entities = arrayOf(BudgetModel::class), version = 1) abstract class BudgetDatabse: RoomDatabase() { abstract fun budgetdao(): BudgetDao }
0
Kotlin
0
0
f97ada4d19c9490c27ab58468f35cb4be91ef1ce
255
Budget_Tracker
MIT License
feature/rss/src/main/java/zaitsev/a/d/mirea/rss/service/AstroBeneNewsService.kt
Anton-Zaitsev
816,037,410
false
{"Gradle Kotlin DSL": 12, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 11, "Batchfile": 1, "Git Attributes": 1, "Markdown": 1, "Kotlin": 256, "TOML": 1, "CMake": 2, "C++": 8, "Proguard": 11, "XML": 36, "INI": 4, "Java": 3}
package zaitsev.a.d.mirea.rss.service import okhttp3.ResponseBody import retrofit2.Call import retrofit2.http.GET interface AstroBeneNewsService { @GET("/Astrobene") fun getNewsDefault(): Call<ResponseBody> }
0
Java
0
0
08623c8850b0b301c7af9c7961d6436988f6d1a3
218
AI-News
MIT License
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RegisTeleOp.kt
jalvarez5625
408,566,065
false
{"Java": 40226, "Kotlin": 4944}
package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.DcMotorController; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; @TeleOp(name="RegisTeleOp", group="Linear Opmode") public class RegisTeleOp extends RegisLinearOp { double servoPosition = servo.servoHome; final double servoSpeed = .01; public void runOpMode() { super.runOpMode(); while (opModeIsActive()) { double max; double rot = 0.5; double X = gamepad1.left_stick_x; double Y = -gamepad1.left_stick_y; double R = gamepad1.right_stick_x; double turn = 751.8*2; double Intakepower = gamepad2.right_trigger; double Outtakepower = gamepad2.left_trigger; boolean stopIntake = gamepad1.y; max = Math.abs(X*X) + Math.abs(Y*Y) + rot * Math.abs(R*R); max = (max < 1)? 1: max; rightFrontMotor.setPower((-X + Y - R) / max); rightBackMotor.setPower((X + Y - R) / max); leftFrontMotor.setPower((X + Y + R) / max); leftBackMotor.setPower((-X + Y + R) / max); if ( Intakepower > 0) { intakeMotor.setPower(.1); }else if (Outtakepower > 0) { intakeMotor.setPower(-.1); }else if (gamepad1.right_trigger == 0 && gamepad1.left_trigger == 0) { intakeMotor.setPower(0); } if (gamepad2.left_bumper){ armMotor.setPower(-.15); } else if (!gamepad2.right_bumper && !gamepad1.left_bumper) { armMotor.setPower(0); } else if (gamepad2.right_bumper) { armMotor.setPower(.15); } if (gamepad2.x){ servoPosition += servoSpeed; }else if (gamepad2.a){ servoPosition += servoSpeed; } servoPosition = Range.clip(servoPosition, servoMax, servoMin); servo.setPosition(servoPosition); telemetry.addData("Status", "Running"); telemetry.update(); } } }
1
null
1
1
9a7a77d89e12eaddb40ed82ac18795843b83c0fa
2,235
2021-2022_Regis_FTC_code
MIT License
core/database/src/commonMain/kotlin/com/cdcoding/database/mapper/AssembleAssetInfoMapper.kt
Christophe-DC
822,562,468
false
{"Kotlin": 728291, "Ruby": 4739, "Swift": 617}
package com.cdcoding.database.mapper import com.cdcoding.common.utils.toAssetId import com.cdcoding.database.db.model.asExternal import com.cdcoding.local.db.AssembleAssetInfo import com.cdcoding.model.Account import com.cdcoding.model.Asset import com.cdcoding.model.AssetInfo import com.cdcoding.model.AssetMetaData import com.cdcoding.model.Balances class AssembleAssetInfoMapper() { fun asExternal(entity: List<AssembleAssetInfo>): List<AssetInfo> { return entity.groupBy { it.id }.mapNotNull { records -> val first = records.value.firstOrNull() ?: return@mapNotNull null val assetId = first.id.toAssetId() ?: return@mapNotNull null val balances = Balances( /*records.value.mapNotNull { if (it.amount != null && it.balanceType != null) { AssetBalance(assetId, Balance(it.balanceType, it.amount)) } else { null } }*/ ) val currency = null // Currency.entries.firstOrNull { it.string == first.priceCurrency } AssetInfo( owner = Account( id = first.id_, chain = first.chain.asExternal(), address = first.address, derivationPath = first.derivationPath, extendedPublicKey = first.extendedPublicKey, ), asset = Asset( id = assetId, name = first.name, symbol = first.symbol, decimals = first.decimals.toInt(), type = first.type.asExternal(), ), balances = balances, price = /*if (first.priceValue != null && currency != null) { AssetPriceInfo( currency = currency, price = AssetPrice( assetId = assetId.toIdentifier(), price = first.priceValue, priceChangePercentage24h = first.priceDayChanges ?: 0.0, ) ) } else */ null, metadata = AssetMetaData( isEnabled = first.is_visible == 1L, isBuyEnabled = first.is_buy_enabled == 1L, isSwapEnabled = first.is_swap_enabled == 1L, isStakeEnabled = first.is_stake_enabled == 1L, ), links = /*if (first.links != null) gson.fromJson( first.links, AssetLinks::class.java ) else*/ null, market = /*if (first.market != null) gson.fromJson( first.market, AssetMarket::class.java ) else */ null, rank = first.rank.toInt(), walletName = first.walletName, walletType = first.walletType.asExternal(), stakeApr = null //first.stakingApr, ) } } }
0
Kotlin
0
0
8519d210188c7403340442e8249ffb2879e7d7a0
3,157
secureWallet
Apache License 2.0
app/src/main/java/gsrv/klassenplaner/ui/addedit/base/BaseAddEditViewModel.kt
jonas-haeusler
207,426,160
false
null
package gsrv.klassenplaner.ui.addedit.base import androidx.annotation.StringRes import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import gsrv.klassenplaner.R import gsrv.klassenplaner.data.Result import gsrv.klassenplaner.data.entities.BaseItem import gsrv.klassenplaner.data.entities.Group import gsrv.klassenplaner.data.repository.BaseRepository import gsrv.klassenplaner.data.repository.GroupRepository import gsrv.klassenplaner.util.SingleLiveEvent import kotlinx.coroutines.launch import timber.log.Timber import java.util.* /** * ViewModel for [BaseAddEditFragment] */ abstract class BaseAddEditViewModel<T : BaseItem>( private val baseRepository: BaseRepository<T>, groupRepository: GroupRepository ) : ViewModel() { private val now = Calendar.getInstance() private val calendar = Calendar.getInstance().apply { set(Calendar.HOUR_OF_DAY, 0) set(Calendar.MINUTE, 0) set(Calendar.SECOND, 0) set(Calendar.MILLISECOND, 0) } data class ViewState( val groupsLoading: Boolean = false, val groups: List<Group> = emptyList(), val date: Date? = null, val group: Group? = null, val isSaving: Boolean = false ) sealed class Command { class ShowMessage(@StringRes val messageId: Int) : Command() class InvalidInput(val inputError: InputError) : Command() class SetText(val subject: String, val text: String) : Command() object Abort : Command() object SaveSuccessful : Command() object SaveFailed : Command() object DeletionFailed : Command() object DeletionSuccessful : Command() } sealed class InputError { object InvalidSubject : InputError() object InvalidDate : InputError() object InvalidGroup : InputError() } private val _viewState = MediatorLiveData<ViewState>() val viewState: LiveData<ViewState> get() = _viewState protected var currentViewState: ViewState get() = _viewState.value!! set(value) { _viewState.value = value } val command: SingleLiveEvent<Command> = SingleLiveEvent() /** * The item that was resolved by passing it's id to [setup], null when that never happened. */ private var prePopulatedItem: T? = null /** * Whether this is a new item or an item that is edited */ private val newItem: Boolean get() = prePopulatedItem == null private var shouldSetup = false init { currentViewState = ViewState() _viewState.addSource(groupRepository.getGroups()) { result -> val resultData = result.data?.filter { it.isLoggedIn } if (result is Result.Error || resultData.isNullOrEmpty()) { command.value = Command.ShowMessage(R.string.error_loading_groups) command.value = Command.Abort } else { currentViewState = currentViewState.copy( groups = resultData, groupsLoading = result is Result.Loading ) // Setup the pre-populated item if necessary and hasn't been done before if (shouldSetup) { shouldSetup = false prePopulatedItem?.let { setupItem(it) } } } } } /** * Load an existing item into the ViewModel. No-op when [itemId] is null. */ fun setup(itemId: String?) { itemId?.let { viewModelScope.launch { runCatching { val item = baseRepository.get(it.toInt()) prePopulatedItem = item shouldSetup = true }.onFailure { Timber.e(it) command.value = Command.Abort } } } } fun save(subject: String, text: String) = with(currentViewState) { var valid = true if (subject.isBlank()) { valid = false command.value = Command.InvalidInput(InputError.InvalidSubject) } if (date == null || date < now.time) { valid = false command.value = Command.InvalidInput(InputError.InvalidDate) } if (group == null || !group.isLoggedIn) { valid = false command.value = Command.InvalidInput(InputError.InvalidGroup) } if (valid) { val item = constructItem(subject, date!!, group!!, text, prePopulatedItem) if (newItem) { save(item) } else { item.id = prePopulatedItem!!.id update(item) } } } fun delete() { if (newItem) { return } viewModelScope.launch { runCatching { baseRepository.delete(prePopulatedItem!!) command.value = Command.DeletionSuccessful }.onFailure { Timber.e(it) command.value = Command.DeletionFailed } } } fun setDate(year: Int, month: Int, dayOfMonth: Int) { calendar.set(Calendar.YEAR, year) calendar.set(Calendar.MONTH, month) calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth) currentViewState = currentViewState.copy(date = Date(calendar.timeInMillis)) } fun setDate(timeInMillis: Long) { calendar.timeInMillis = timeInMillis currentViewState = currentViewState.copy(date = Date(calendar.timeInMillis)) } fun setGroup(group: Group?) { currentViewState = currentViewState.copy(group = group) } private fun save(item: T) { viewModelScope.launch { runCatching { currentViewState = currentViewState.copy(isSaving = true) baseRepository.create(item) command.value = Command.SaveSuccessful }.onFailure { Timber.e(it) command.value = Command.SaveFailed } } } private fun update(item: T) { viewModelScope.launch { runCatching { currentViewState = currentViewState.copy(isSaving = true) baseRepository.update(item) command.value = Command.SaveSuccessful }.onFailure { Timber.e(it) command.value = Command.SaveFailed } } } protected abstract fun setupItem(item: T) protected abstract fun constructItem( subject: String, date: Date, group: Group, text: String, prePopulatedItem: T? ): T }
0
Kotlin
0
0
562394d80f0c6e037c010949229d4719de0683cc
6,831
klassenplaner
Apache License 2.0
app/src/main/java/com/vrajdesai78/GroceryStore/ui/explore/ExploreFragment.kt
vrajdesai78
491,003,106
false
null
package com.vrajdesai78.GroceryStore.ui.explore import android.content.Intent import android.os.Bundle import android.view.View import android.widget.SearchView import android.widget.Toast import androidx.fragment.app.Fragment import androidx.recyclerview.widget.GridLayoutManager import com.vrajdesai78.GroceryStore.R import com.vrajdesai78.GroceryStore.adapter.ExploreAdapter import com.vrajdesai78.GroceryStore.listener.OnClickItemAndAdd import com.vrajdesai78.GroceryStore.model.product.ProductEntity import com.vrajdesai78.GroceryStore.ui.detailproduct.DetailProductActivity import com.vrajdesai78.GroceryStore.utill.Constant import kotlinx.android.synthetic.main.fragment_explore.* import org.koin.android.viewmodel.ext.android.viewModel class ExploreFragment : Fragment(R.layout.fragment_explore) { private val viewModel: ExploreViewModel by viewModel() private val exploreAdapter: ExploreAdapter by lazy { ExploreAdapter() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) et_search.requestFocus() searchProduct() observeSearch() setListSearch() } private fun searchProduct() { et_search.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(qword: String?): Boolean { et_search.clearFocus() viewModel.requestProductQuery(qword) return true } override fun onQueryTextChange(qword: String?): Boolean { viewModel.requestProductQuery(qword) return false } }) } private fun observeSearch() { viewModel.searchProduct.observe(viewLifecycleOwner, { exploreAdapter.setDataAdapter(it) }) } private fun setListSearch() { rv_explore.setHasFixedSize(true) rv_explore.adapter = exploreAdapter rv_explore.layoutManager = GridLayoutManager(activity, 2) exploreAdapter.onClickListener = object : OnClickItemAndAdd { override fun onClick(productEntity: ProductEntity) { navigationToDetail(productEntity) } override fun onClickAdd(productEntity: ProductEntity) { addProductToCart(productEntity) } } } private fun navigationToDetail(productEntity: ProductEntity) { val intent = Intent(activity, DetailProductActivity::class.java) intent.putExtra(Constant.DATA, productEntity) startActivity(intent) } private fun addProductToCart(productEntity: ProductEntity) { if (productEntity.qty == 0) { viewModel.addToCahar(productEntity) Toast.makeText(activity, "Product added to cart", Toast.LENGTH_SHORT).show() } else { viewModel.removeProductCart(productEntity) } } }
0
Kotlin
0
2
594a81dcb226c0cf4aab8ef170c396609fa167f7
2,962
Grocery-Store-Alan
Apache License 2.0
app/src/main/java/com/kilomobi/cosmo/data/BluetoothRepository.kt
fkistner-dev
751,512,153
false
{"Kotlin": 51531}
package com.kilomobi.cosmo.data import android.bluetooth.BluetoothDevice import com.kilomobi.cosmo.domain.BluetoothScanner import javax.inject.Inject interface BluetoothRepository { suspend fun startBluetoothScan(): List<BluetoothDevice> suspend fun stopBluetoothScan() } class BluetoothRepositoryImpl @Inject constructor( private val bluetoothScanner: BluetoothScanner ) : BluetoothRepository { override suspend fun startBluetoothScan(): List<BluetoothDevice> { return bluetoothScanner.startScan() } override suspend fun stopBluetoothScan() { bluetoothScanner.stopScan() } }
0
Kotlin
0
0
3bb21657b0e6ab02a797d4f6b8a436111a59cd16
625
cosmo-android
MIT License
app/src/main/java/com/asgatech/networklib/constants/AppConstants.kt
asgatech20
416,731,557
false
{"Kotlin": 19957}
package com.asgatech.networklib.constants /** * @Author: <NAME> * @Date: 10/13/2021 * @Date: <EMAIL> */ object AppConstants { var BASE_URL="https://jsonplaceholder.typicode.com/" }
0
Kotlin
0
0
bd54a9e4fbdbea7f7056a6882491958f2f3e6291
189
NetworkLib
Apache License 2.0
kotlin-mui/src/main/generated/mui/material/Tooltip.ext.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! package mui.material @Suppress("NAME_CONTAINS_ILLEGAL_CHARS") // language=JavaScript @JsName("""(/*union*/{bottomEnd: 'bottom-end', bottomStart: 'bottom-start', bottom: 'bottom', leftEnd: 'left-end', leftStart: 'left-start', left: 'left', rightEnd: 'right-end', rightStart: 'right-start', right: 'right', topEnd: 'top-end', topStart: 'top-start', top: 'top'}/*union*/)""") external enum class TooltipPlacement { bottomEnd, bottomStart, bottom, leftEnd, leftStart, left, rightEnd, rightStart, right, topEnd, topStart, top, ; }
10
Kotlin
145
983
7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35
625
kotlin-wrappers
Apache License 2.0
feature-wallet-impl/src/main/java/jp/co/soramitsu/wallet/impl/domain/beacon/SignableOperation.kt
soramitsu
278,060,397
false
{"Kotlin": 5738459, "Java": 18796}
package jp.co.soramitsu.wallet.impl.domain.beacon import java.math.BigInteger interface WithAmount { val amount: BigInteger } sealed class SignableOperation( val module: String, val call: String, val args: Map<String, Any?>, val rawData: String ) { class Transfer( module: String, call: String, args: Map<String, Any?>, rawData: String, val destination: String, override val amount: BigInteger ) : SignableOperation(module, call, args, rawData), WithAmount class Other( module: String, call: String, args: Map<String, Any?>, rawData: String ) : SignableOperation(module, call, args, rawData) }
15
Kotlin
30
89
1de6dfa7c77d4960eca2d215df2bdcf71a2ef5f2
716
fearless-Android
Apache License 2.0
pickcore/src/main/kotlin/com/lovoo/android/pickcore/PickPicProvider.kt
lovoo
224,686,577
false
null
/** * Copyright 2018 LOVOO GmbH * * 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.lovoo.android.pickcore import com.lovoo.android.pickcore.contract.CameraEngine import com.lovoo.android.pickcore.contract.ImageEngine import com.lovoo.android.pickcore.contract.SelectionHolder import com.lovoo.android.pickcore.engine.DefaultImageEngine import com.lovoo.android.pickcore.engine.DisabledCameraEngine /** * Object that allows at runtime to change core feature from PickPic. * If you use [com.lovoo.android.pickapp.view.PickPicActivity] you don`t need to provide anything on your own. * * Please watch out for memory leaks if you provide instances that hold a reference * to any UI element such as Activity, Fragment, View... * * Example: * * class MyActivity: Activity, ImageEngine, CameraEngine { * * override fun onResume() { * super.onResume() * PickPicProvider.imageEngine = this * PickPicProvider.cameraEngine = this * ... * } * * override fun onPause() { * super.onPause() * PickPicProvider.imageEngine = DefaultImageEngine() // remove Activity reference * PickPicProvider.cameraEngine = DisabledCameraEngine() // remove Activity reference * ... * } * * ... * } * * As you can see in the example the reference will be cleared in onDestroy. * But I want to encourage you to use a stand-alone Engine class without any UI reference. * And even if you do so please consider the issue with singleton instance and Lifecycle. * For example an Activity set an engine in onCreate and clears it in onDestroy, when two * such Activities are created then the engine from Activity A will be overwritten by Activity B. * Or worse Activity B will clear the engine in onDestroy and Activity A is just resumed. * * Best would be to use [com.lovoo.android.pickapp.view.PickPicActivity] as singleInstance * or set engine within your Application.onCreate() call. */ object PickPicProvider { /** * [ImageEngine] that is used from PickPic to load images as thumbnails and preview. * Should be set at soon as possible */ var imageEngine: ImageEngine = DefaultImageEngine() /** * [CameraEngine] that defines if the camera will be available for a certain [Gallery]. * Please consider to keep the user flow consistent. Its a bad experience when the user * navigate to a custom folder, used the camera button there and the taken picture is added * to the DCIM or another folder. It would be better to show the camera button only in * Galleries were you can save the picture, so that it appears afterwards. */ var cameraEngine: CameraEngine = DisabledCameraEngine() /** * [SelectionHolder] implementation that keeps track of the selected [Picture]s and provides * the option to listen for changes. */ var selectionHolder: SelectionHolder? = null }
0
Kotlin
1
13
9b0d31c362e21ec44bce02d6c1d021da5076de80
3,422
android-pickpic
Apache License 2.0
app/src/commonMain/kotlin/ir/ehsannarmani/compose_charts/ui/App.kt
ehsannarmani
805,278,796
false
{"Kotlin": 179380, "Swift": 587}
package ir.ehsannarmani.compose_charts.ui import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.dp @Composable fun App(){ val density = LocalDensity.current var composableWidth by remember { mutableStateOf(0.dp) } Box(modifier = Modifier .fillMaxSize() .background(Color(0xff101010)).onGloballyPositioned { coordinates -> composableWidth = with(density){ coordinates.size.width.toDp() } }){ if (composableWidth >= 600.dp) { TabletSample() }else{ PhoneSample() } } }
2
Kotlin
5
88
37e856ab418b2e0944cee70b6237efbdb746901b
1,087
ComposeCharts
Apache License 2.0
src/commonMain/kotlin/ksn/ui/SkiaDragStatus.kt
seisuke
509,360,379
false
{"Kotlin": 165567, "HTML": 268}
package ksn.ui import androidx.compose.ui.geometry.Offset data class SkiaDragStatus( val start: Offset, val end: Offset, ) { companion object { val Zero = SkiaDragStatus( Offset.Zero, Offset.Zero ) } }
0
Kotlin
0
4
fe6480c744dabcdcf532d6733a089b500f229c80
261
ksn-draw
Apache License 2.0
platform/src/main/kotlin/researchstack/backend/application/port/incoming/version/VersionResponse.kt
S-ResearchStack
520,365,362
false
{"Kotlin": 1297198, "Dockerfile": 202, "Shell": 59}
package researchstack.backend.application.port.incoming.version data class VersionResponse( val minimum: String, val latest: String )
1
Kotlin
9
29
214dc84476e2de6948c3fc5225cebca0707bfb91
143
backend-system
Apache License 2.0
app/src/main/java/com/example/galleryapp_compose/ui/camera/CameraViewModel.kt
PauloSzT
642,027,877
false
null
package com.example.galleryapp_compose.ui.camera import android.Manifest import android.content.Context import android.content.pm.PackageManager import android.location.LocationManager import android.net.Uri import android.util.Log import android.widget.Toast import androidx.camera.core.ImageCapture import androidx.camera.core.ImageCaptureException import androidx.core.app.ActivityCompat import com.example.galleryapp_compose.ui.camera.CameraConstants.ERROR_MESSAGE import com.example.galleryapp_compose.ui.camera.CameraConstants.IMAGE_FORMAT import com.example.galleryapp_compose.ui.camera.CameraConstants.SUCCESS_MESSAGE import java.io.File import java.text.SimpleDateFormat import java.util.Locale import java.util.concurrent.Executor class CameraViewModel (private val context: Context) { private val locationManager: LocationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager val cameraUiState = CameraUiState( ::takePhoto ) private fun takePhoto( filenameFormat: String, imageCapture: ImageCapture, outputDirectory: File, executor: Executor, onImageCaptured: (Uri) -> Unit, onError: (ImageCaptureException) -> Unit ) { val photoFile = File( outputDirectory, SimpleDateFormat(filenameFormat, Locale.US).format(System.currentTimeMillis()) + IMAGE_FORMAT ) val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile) .setMetadata(ImageCapture.Metadata().apply { (ActivityCompat.checkSelfPermission( context, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( context, Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) val lastLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER) this.location = lastLocation }).build() imageCapture.takePicture(outputOptions, executor, object: ImageCapture.OnImageSavedCallback { override fun onError(exception: ImageCaptureException) { Log.d("Error", ERROR_MESSAGE, exception) onError(exception) } override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) { val savedUri = Uri.fromFile(photoFile) val msg = "$SUCCESS_MESSAGE $savedUri" Toast.makeText(context, msg, Toast.LENGTH_SHORT).show() Log.d("This", msg) onImageCaptured(savedUri) } }) } }
0
Kotlin
0
0
ff0020fd13ce6382ebeae42afefb475c4fde4e23
2,808
GalleryApp_compose_navigation
MIT License
app/src/main/java/com/example/galleryapp_compose/ui/camera/CameraViewModel.kt
PauloSzT
642,027,877
false
null
package com.example.galleryapp_compose.ui.camera import android.Manifest import android.content.Context import android.content.pm.PackageManager import android.location.LocationManager import android.net.Uri import android.util.Log import android.widget.Toast import androidx.camera.core.ImageCapture import androidx.camera.core.ImageCaptureException import androidx.core.app.ActivityCompat import com.example.galleryapp_compose.ui.camera.CameraConstants.ERROR_MESSAGE import com.example.galleryapp_compose.ui.camera.CameraConstants.IMAGE_FORMAT import com.example.galleryapp_compose.ui.camera.CameraConstants.SUCCESS_MESSAGE import java.io.File import java.text.SimpleDateFormat import java.util.Locale import java.util.concurrent.Executor class CameraViewModel (private val context: Context) { private val locationManager: LocationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager val cameraUiState = CameraUiState( ::takePhoto ) private fun takePhoto( filenameFormat: String, imageCapture: ImageCapture, outputDirectory: File, executor: Executor, onImageCaptured: (Uri) -> Unit, onError: (ImageCaptureException) -> Unit ) { val photoFile = File( outputDirectory, SimpleDateFormat(filenameFormat, Locale.US).format(System.currentTimeMillis()) + IMAGE_FORMAT ) val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile) .setMetadata(ImageCapture.Metadata().apply { (ActivityCompat.checkSelfPermission( context, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( context, Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) val lastLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER) this.location = lastLocation }).build() imageCapture.takePicture(outputOptions, executor, object: ImageCapture.OnImageSavedCallback { override fun onError(exception: ImageCaptureException) { Log.d("Error", ERROR_MESSAGE, exception) onError(exception) } override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) { val savedUri = Uri.fromFile(photoFile) val msg = "$SUCCESS_MESSAGE $savedUri" Toast.makeText(context, msg, Toast.LENGTH_SHORT).show() Log.d("This", msg) onImageCaptured(savedUri) } }) } }
0
Kotlin
0
0
ff0020fd13ce6382ebeae42afefb475c4fde4e23
2,808
GalleryApp_compose_navigation
MIT License
character_detail/src/main/java/com/ezike/tobenna/starwarssearch/character_detail/presentation/CharacterDetailViewIntentProcessor.kt
Ezike
294,171,829
false
null
package com.ezike.tobenna.starwarssearch.character_detail.presentation import com.ezike.tobenna.starwarssearch.character_detail.mapper.CharacterDetailModelMapper import com.ezike.tobenna.starwarssearch.character_detail.presentation.CharacterDetailViewResult.CharacterDetail import com.ezike.tobenna.starwarssearch.character_detail.ui.LoadCharacterDetailIntent import com.ezike.tobenna.starwarssearch.character_detail.ui.views.error.RetryFetchCharacterDetailsIntent import com.ezike.tobenna.starwarssearch.character_detail.ui.views.film.RetryFetchFilmIntent import com.ezike.tobenna.starwarssearch.character_detail.ui.views.planet.RetryFetchPlanetIntent import com.ezike.tobenna.starwarssearch.character_detail.ui.views.specie.RetryFetchSpecieIntent import com.ezike.tobenna.starwarssearch.lib_character_search.domain.model.Character import com.ezike.tobenna.starwarssearch.lib_character_search.domain.model.Film import com.ezike.tobenna.starwarssearch.lib_character_search.domain.model.Planet import com.ezike.tobenna.starwarssearch.lib_character_search.domain.model.Specie import com.ezike.tobenna.starwarssearch.lib_character_search.domain.usecase.detail.FetchFilms import com.ezike.tobenna.starwarssearch.lib_character_search.domain.usecase.detail.FetchPlanet import com.ezike.tobenna.starwarssearch.lib_character_search.domain.usecase.detail.FetchSpecies import com.ezike.tobenna.starwarssearch.lib_character_search.domain.usecase.detail.GetCharacterDetail import com.ezike.tobenna.starwarssearch.presentation.base.InvalidViewIntentException import com.ezike.tobenna.starwarssearch.presentation.base.ViewIntent import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.merge import kotlinx.coroutines.flow.onStart import javax.inject.Inject class CharacterDetailViewIntentProcessor @Inject constructor( private val fetchPlanet: FetchPlanet, private val fetchSpecies: FetchSpecies, private val fetchFilms: FetchFilms, private val getCharacterDetail: GetCharacterDetail, private val characterMapper: CharacterDetailModelMapper ) : CharacterDetailIntentProcessor { override fun intentToResult(viewIntent: ViewIntent): Flow<CharacterDetailViewResult> { return when (viewIntent) { is LoadCharacterDetailIntent -> { val character = characterMapper.mapToDomain( viewIntent.character ) getCharacterInfo( model = character, initialResult = CharacterDetail( character = character ) ) } is RetryFetchPlanetIntent -> retryFetchPlanet(viewIntent.url) is RetryFetchSpecieIntent -> retryFetchSpecie(viewIntent.url) is RetryFetchFilmIntent -> retryFetchFilm(viewIntent.url) is RetryFetchCharacterDetailsIntent -> { val character = characterMapper.mapToDomain( viewIntent.character ) getCharacterInfo( model = character, initialResult = CharacterDetailViewResult.Retrying ) } else -> throw InvalidViewIntentException(viewIntent) } } private fun getCharacterInfo( model: Character, initialResult: CharacterDetailViewResult ): Flow<CharacterDetailViewResult> { return getCharacterDetail(model.url) .flatMapLatest { character -> merge( getFilms(character.filmUrls), getPlanet(character.planetUrl), getSpecies(character.speciesUrls) ) } .onStart { emit(initialResult) } .catch { error -> emit( CharacterDetailViewResult.FetchCharacterDetailError( model.name, error ) ) } } private fun getFilms(urls: List<String>): Flow<FilmDetailViewResult> { return fetchFilms(urls) .map<List<Film>, FilmDetailViewResult> { films -> FilmDetailViewResult.Success(films) }.onStart { emit(FilmDetailViewResult.Loading) }.catch { error -> error.printStackTrace() emit(FilmDetailViewResult.Error(error)) } } private fun getSpecies(urls: List<String>): Flow<SpecieDetailViewResult> { return fetchSpecies(urls) .map<List<Specie>, SpecieDetailViewResult> { species -> SpecieDetailViewResult.Success(species) }.onStart { emit(SpecieDetailViewResult.Loading) }.catch { error -> error.printStackTrace() emit(SpecieDetailViewResult.Error(error)) } } private fun getPlanet(url: String): Flow<PlanetDetailViewResult> { return fetchPlanet(url) .map<Planet, PlanetDetailViewResult> { planet -> PlanetDetailViewResult.Success(planet) }.onStart { emit(PlanetDetailViewResult.Loading) }.catch { error -> error.printStackTrace() emit(PlanetDetailViewResult.Error(error)) } } private fun retryFetchPlanet(url: String): Flow<PlanetDetailViewResult> { return getCharacterDetail(url) .flatMapLatest { character -> getPlanet(character.planetUrl) } .catch { error -> emit(PlanetDetailViewResult.Error(error)) } } private fun retryFetchSpecie(url: String): Flow<SpecieDetailViewResult> { return getCharacterDetail(url) .flatMapLatest { character -> getSpecies(character.speciesUrls) } .catch { error -> emit(SpecieDetailViewResult.Error(error)) } } private fun retryFetchFilm(url: String): Flow<FilmDetailViewResult> { return getCharacterDetail(url) .flatMapLatest { character -> getFilms(character.filmUrls) } .catch { error -> emit(FilmDetailViewResult.Error(error)) } } }
0
Kotlin
28
172
792caabf5a29b8bb4698c36c3257916a1cf6611d
6,272
StarWarsSearch-MVI
Apache License 2.0
sdk-lib/src/main/java/cash/z/ecc/android/sdk/internal/model/TransactionDataRequest.kt
Electric-Coin-Company
151,763,639
false
{"Kotlin": 1174854, "Rust": 121956}
package cash.z.ecc.android.sdk.internal.model import cash.z.ecc.android.sdk.exception.SdkException import cash.z.ecc.android.sdk.internal.ext.toHexReversed import cash.z.ecc.android.sdk.model.BlockHeight /** * Serves as cross layer (Kotlin, Rust) communication class. */ sealed interface TransactionDataRequest { sealed class EnhancementRequired(open val txid: ByteArray) : TransactionDataRequest { abstract fun txIdString(): String } data class GetStatus(override val txid: ByteArray) : EnhancementRequired(txid) { override fun txIdString() = txid.toHexReversed() } data class Enhancement(override val txid: ByteArray) : EnhancementRequired(txid) { override fun txIdString() = txid.toHexReversed() } data class SpendsFromAddress( val address: String, val startHeight: BlockHeight, val endHeight: BlockHeight?, ) : TransactionDataRequest { init { if (endHeight != null) { require(endHeight >= startHeight) { "End height $endHeight must not be less than start height $startHeight." } } } } companion object { fun new(jni: JniTransactionDataRequest): TransactionDataRequest { return when (jni) { is JniTransactionDataRequest.GetStatus -> GetStatus(jni.txid) is JniTransactionDataRequest.Enhancement -> Enhancement(jni.txid) is JniTransactionDataRequest.SpendsFromAddress -> SpendsFromAddress( jni.address, BlockHeight.new(jni.startHeight), if (jni.endHeight == -1L) { null } else { BlockHeight.new(jni.endHeight) } ) else -> throw SdkException("Unknown JniTransactionDataRequest variant", cause = null) } } } }
182
Kotlin
9
5
8893f83fd7dcaaca9d5e2633f5c8bebed84dba77
2,022
zcash-android-wallet-sdk
MIT License
src/main/kotlin/com/mvp/order/domain/service/admin/user/UserAdminServiceImpl.kt
lfneves
729,675,910
false
{"Kotlin": 155323, "Gherkin": 5931, "Dockerfile": 153}
package com.mvp.order.domain.service.admin.user import com.mvp.order.domain.model.auth.RemoveUserDTO import com.mvp.order.domain.model.exception.Exceptions import com.mvp.order.domain.model.user.admin.UserAdminResponseDTO import com.mvp.order.infrastruture.entity.user.UserEntity import com.mvp.order.infrastruture.repository.order.OrderProductRepository import com.mvp.order.infrastruture.repository.order.OrderRepository import com.mvp.order.infrastruture.repository.user.AddressRepository import com.mvp.order.infrastruture.repository.user.UserRepository import com.mvp.order.utils.constants.ErrorMsgConstants import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service class UserAdminServiceImpl( private val userRepository: UserRepository, private val addressRepository: AddressRepository, private val orderRepository: OrderRepository, private val orderProductRepository: OrderProductRepository, ): UserAdminService { override fun getUsers(): List<UserAdminResponseDTO> { val users: MutableList<UserEntity> = userRepository.findAll() return users.map { user -> val address = user.idAddress?.let { addressRepository.findById(it).get() } user.toAdminDTO(address) } } @Transactional override fun deleteByUsername(removeUserDTO: RemoveUserDTO) { val userEntity = userRepository.findByUsernameWithAddress(removeUserDTO.username) if(userEntity.isPresent) { val user = userEntity.get() if(removeUserDTO.name != user.name) { throw Exceptions.NotFoundException(ErrorMsgConstants.ERROR_USER_NOT_FOUND) } val address = user.idAddress?.let { addressRepository.findById(it).get() } if(address != null && removeUserDTO.addressEntity.street != address.street) { throw Exceptions.NotFoundException(ErrorMsgConstants.ERROR_USER_NOT_FOUND) } val order = orderRepository.findByUsername(removeUserDTO.username) order.id?.let { orderProductRepository.deleteByIdOrder(it) } order.id?.let { orderRepository.deleteById(it) } userRepository.deleteById(user.id!!.toLong()) user.idAddress?.let { addressRepository.deleteById(it) } } else { throw Exceptions.NotFoundException(ErrorMsgConstants.ERROR_USER_NOT_FOUND) } } // Used in the development process should not be used in production override fun deleteAllUsers() { return userRepository .deleteAll() } }
0
Kotlin
0
0
9de7cd13d01c6e93e8f5df28b0805048c7dd324c
2,625
tech-challenge-order
MIT License
oldAndroidProjects/More Projects/NewPractice/KMP/Multi-Theme/composeApp/src/commonMain/kotlin/theme/color_palettes/OrangeColorBase.kt
shivathapaa
800,628,391
false
{"Kotlin": 3491940, "Shell": 2341, "Swift": 621}
package theme.color_palettes import androidx.compose.ui.graphics.Color import theme.MaterialThemeColorsPalette object OrangeColorBase : MaterialThemeColorsPalette { override val primaryLight:Color = Color(0xFF914C00) override val onPrimaryLight:Color = Color(0xFFFFFFFF) override val primaryContainerLight:Color = Color(0xFFFD8C15) override val onPrimaryContainerLight:Color = Color(0xFF331700) override val secondaryLight:Color = Color(0xFF855328) override val onSecondaryLight:Color = Color(0xFFFFFFFF) override val secondaryContainerLight:Color = Color(0xFFFFC498) override val onSecondaryContainerLight:Color = Color(0xFF5D3209) override val tertiaryLight:Color = Color(0xFF5B6400) override val onTertiaryLight:Color = Color(0xFFFFFFFF) override val tertiaryContainerLight:Color = Color(0xFFA4B217) override val onTertiaryContainerLight:Color = Color(0xFF1D2100) override val errorLight:Color = Color(0xFFBA1A1A) override val onErrorLight:Color = Color(0xFFFFFFFF) override val errorContainerLight:Color = Color(0xFFFFDAD6) override val onErrorContainerLight:Color = Color(0xFF410002) override val backgroundLight:Color = Color(0xFFFFF8F5) override val onBackgroundLight:Color = Color(0xFF241912) override val surfaceLight:Color = Color(0xFFFFF8F5) override val onSurfaceLight:Color = Color(0xFF241912) override val surfaceVariantLight:Color = Color(0xFFFADDCA) override val onSurfaceVariantLight:Color = Color(0xFF564335) override val outlineLight:Color = Color(0xFF897363) override val outlineVariantLight:Color = Color(0xFFDDC1AF) override val scrimLight:Color = Color(0xFF000000) override val inverseSurfaceLight:Color = Color(0xFF3A2E26) override val inverseOnSurfaceLight:Color = Color(0xFFFFEDE3) override val inversePrimaryLight:Color = Color(0xFFFFB77F) override val surfaceDimLight:Color = Color(0xFFEAD6CA) override val surfaceBrightLight:Color = Color(0xFFFFF8F5) override val surfaceContainerLowestLight:Color = Color(0xFFFFFFFF) override val surfaceContainerLowLight:Color = Color(0xFFFFF1E9) override val surfaceContainerLight:Color = Color(0xFFFFEADD) override val surfaceContainerHighLight:Color = Color(0xFFF9E4D8) override val surfaceContainerHighestLight:Color = Color(0xFFF3DFD2) override val primaryDark:Color = Color(0xFFFFB77F) override val onPrimaryDark:Color = Color(0xFF4E2600) override val primaryContainerDark:Color = Color(0xFFE47B00) override val onPrimaryContainerDark:Color = Color(0xFF030100) override val secondaryDark:Color = Color(0xFFFBB885) override val onSecondaryDark:Color = Color(0xFF4E2600) override val secondaryContainerDark:Color = Color(0xFF61350D) override val onSecondaryContainerDark:Color = Color(0xFFFFCBA4) override val tertiaryDark:Color = Color(0xFFC1D039) override val onTertiaryDark:Color = Color(0xFF2E3300) override val tertiaryContainerDark:Color = Color(0xFF909D00) override val onTertiaryContainerDark:Color = Color(0xFF000000) override val errorDark:Color = Color(0xFFFFB4AB) override val onErrorDark:Color = Color(0xFF690005) override val errorContainerDark:Color = Color(0xFF93000A) override val onErrorContainerDark:Color = Color(0xFFFFDAD6) override val backgroundDark:Color = Color(0xFF1B110A) override val onBackgroundDark:Color = Color(0xFFF3DFD2) override val surfaceDark:Color = Color(0xFF1B110A) override val onSurfaceDark:Color = Color(0xFFF3DFD2) override val surfaceVariantDark:Color = Color(0xFF564335) override val onSurfaceVariantDark:Color = Color(0xFFDDC1AF) override val outlineDark:Color = Color(0xFFA48C7B) override val outlineVariantDark:Color = Color(0xFF564335) override val scrimDark:Color = Color(0xFF000000) override val inverseSurfaceDark:Color = Color(0xFFF3DFD2) override val inverseOnSurfaceDark:Color = Color(0xFF3A2E26) override val inversePrimaryDark:Color = Color(0xFF914C00) override val surfaceDimDark:Color = Color(0xFF1B110A) override val surfaceBrightDark:Color = Color(0xFF43372E) override val surfaceContainerLowestDark:Color = Color(0xFF150C06) override val surfaceContainerLowDark:Color = Color(0xFF241912) override val surfaceContainerDark:Color = Color(0xFF281D16) override val surfaceContainerHighDark:Color = Color(0xFF332820) override val surfaceContainerHighestDark:Color = Color(0xFF3E322A) }
0
Kotlin
0
0
c32fbea3c5dd8ee9c1286d30528f7daeabb2b190
4,494
Android-Practice-Projects
The Unlicense
app/src/main/java/dev/jahidhasanco/fliq/di/AppModule.kt
JahidHasanCO
405,033,258
false
{"Kotlin": 72063}
package dev.jahidhasanco.fliq.di import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import dev.jahidhasanco.fliq.data.network.ApiService import dev.jahidhasanco.fliq.data.network.BASE_URL import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object AppModule { @Provides @Singleton fun providesLoggingInterceptor(): HttpLoggingInterceptor { return HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY) } @Provides @Singleton fun providesOkHttpClient(httpLoggingInterceptor: HttpLoggingInterceptor): OkHttpClient { val okHttpClient = OkHttpClient.Builder() .addInterceptor(httpLoggingInterceptor) .connectTimeout(15, TimeUnit.SECONDS) return okHttpClient.build() } @Provides @Singleton fun providesApiService(okHttpClient: OkHttpClient): ApiService { val retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient) .build() return retrofit.create(ApiService::class.java) } }
2
Kotlin
4
19
e08959114ace3d85c8454cfc56e086a23b35857f
1,402
Fliq.-The-Movie-DB
MIT License
app/src/main/java/com/revolgenx/anilib/user/viewmodel/UserStatsViewModel.kt
AniLibApp
244,410,204
false
{"Kotlin": 1593083, "Shell": 52}
package com.revolgenx.anilib.user.viewmodel import com.revolgenx.anilib.user.data.field.UserStatsField import com.revolgenx.anilib.user.service.UserStatsService import com.revolgenx.anilib.infrastructure.source.stats.UserStatsSource import com.revolgenx.anilib.common.viewmodel.SourceViewModel open class UserStatsViewModel(private val userStatsService: UserStatsService) : SourceViewModel<UserStatsSource, UserStatsField>() { override var field: UserStatsField = UserStatsField() override fun createSource(): UserStatsSource { source = UserStatsSource(userStatsService, field, compositeDisposable) return source!! } }
36
Kotlin
3
76
b3caec5c00779c878e4cf22fb7d2034aefbeee54
656
AniLib
Apache License 2.0
app/src/main/java/com/zzr/jetpacktest/kotlin_test/CollectionDemo.kt
zrzhong
288,220,143
false
null
package com.zzr.jetpacktest.kotlin_test /** * @Author zzr * @Desc * @Date 2020/9/30 */ fun main() { // listTest() sequenceTest() val list = 5 for (i in 0 until list){ } } fun listTest() { val list = listOf(1, 2, 3, 4, 5, 6) val result = list .map { println("In Map $it") it * 2 }.filter { println("In Filter $it") it % 3 == 0 } println(result.first()) } fun sequenceTest() { val sequence = sequenceOf(1, 2, 3, 4, 5, 6) val result = sequence .map { println("In Map $it") it * 2 }.filter { println("In Filter $it") it % 3 == 0 } println(result.first()) }
1
null
1
1
7765544fd6df3d615dadbe03f7df1daaac7aa1ab
747
JetpackTest
Apache License 2.0
presentation/src/main/java/com/pp/jetweatherfy/presentation/utils/Constants.kt
pauloaapereira
348,738,402
false
null
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pp.jetweatherfy.presentation.utils import androidx.compose.ui.unit.dp const val DailyTimestampFormat = "E, d MMM" const val HourlyTimestampFormat = "K:mm a" const val AnimationDuration = 1000 const val BackgroundAnimationDuration = 400 const val SelectedAlpha = 0.25f const val UnselectedAlpha = 0.1f val AnimationStartOffset = 400.dp val AnimationEndOffset = 0.dp
0
Kotlin
18
155
fcf55a107586de46a081d8e692c0f3722f4bc3d8
970
AndroidDevChallenge_Week4_JetWeatherfy
Apache License 2.0
app/src/main/java/com/vn/ntesco/model/CheckListModel.kt
hoaphanit
296,677,787
false
{"Java": 4293900, "Kotlin": 611527, "Assembly": 1013, "Rich Text Format": 402}
package com.vn.ntesco.model import com.google.gson.annotations.SerializedName data class CheckListModel( @SerializedName("attributes") var attributesList: List<String> = listOf(), @SerializedName("children") var childrenList: MutableList<MutableList<String>> = mutableListOf(), @SerializedName("created_at") var createdAt: String? = "", @SerializedName("id") var id: Int? = 0, @SerializedName("name") var name: String? = "", @SerializedName("status") var status: Int? = 0, @SerializedName("updated_at") var updatedAt: String? = "" ) { var inputAttributesList: MutableList<MutableList<String>>? = mutableListOf() var isExpanded = false }
1
null
1
1
bf0a47a50eeb3d7113586417e07e7729fc1bb521
759
ntesco.android.github
Apache License 2.0
features/dialogs/src/main/java/com/ribsky/dialogs/connection/CheckConnectionDialog.kt
nexy791
607,748,138
false
null
package com.ribsky.dialogs.connection import android.annotation.SuppressLint import androidx.core.os.bundleOf import androidx.fragment.app.setFragmentResult import com.ribsky.common.base.BaseSheet import com.ribsky.dialogs.databinding.DialogCheckConnectionBinding import com.ribsky.navigation.features.DialogsNavigation.Companion.RESULT_KEY_CONNECTION class CheckConnectionDialog : BaseSheet<DialogCheckConnectionBinding>(DialogCheckConnectionBinding::inflate) { @SuppressLint("SetTextI18n") override fun initViews() = with(binding) { btnNext.setOnClickListener { setFragmentResult(RESULT_KEY_CONNECTION, bundleOf()) dismiss() } } override fun clear() { } override fun initObserves() { } }
0
Kotlin
0
7
d2e9f7c04635e1793bfe8f421b4bc5ef162556c0
768
dymka
Apache License 2.0
app/src/main/java/com/recrsn/cardtrack/repositories/CardRepository.kt
recrsn
293,649,383
false
null
package com.recrsn.cardtrack.repositories import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.Query import com.recrsn.cardtrack.models.Card import com.recrsn.cardtrack.models.CardType @Dao interface CardRepository { @Query("SELECT * FROM card ORDER BY identifier ASC") fun findAll(): LiveData<List<Card>> @Query("SELECT * FROM card WHERE id = :id LIMIT 1") fun findById(id: Int): Card? @Insert fun insert(card: Card) @Query("SELECT * FROM card WHERE identifier = :identifier AND bank = :bank AND country = :country AND type = :type") fun findByIdentity(identifier: String, type: CardType, bank: String, country: String): Card? }
1
Kotlin
0
0
e10be20103283f1b38918abd22f03db4265ffa25
723
card-track
Apache License 2.0
api-client/src/test/java/com/kshitijpatil/tazabazar/api/TestProductApi.kt
Kshitij09
395,308,440
false
null
package com.kshitijpatil.tazabazar.api import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.runBlocking import okhttp3.OkHttpClient import org.junit.Test import java.net.HttpURLConnection class TestProductApi { private val client = OkHttpClient.Builder().build() private val api = ApiModule.provideProductApi(client) @Test fun test_getAllProducts() = runBlocking { val products = api.getAllProducts() assertThat(products).isNotEmpty() } @Test fun test_getProductsByCategory() = runBlocking { val products = api.getAllProducts("fruits") assertThat(products).isNotEmpty() } @Test fun test_getProductBySku() = runBlocking { // valid sku var productResponse = api.getProduct("vgt-004") assertThat(productResponse.body()).isNotNull() // invalid sku productResponse = api.getProduct("vgt-10001") assertThat(productResponse.isSuccessful).isFalse() assertThat(productResponse.code()).isEqualTo(HttpURLConnection.HTTP_NOT_FOUND) } @Test fun test_getProductCategories() = runBlocking { val categories = api.getProductCategories() assertThat(categories).isNotEmpty() } @Test fun test_getProductInventories() = runBlocking { val inventories = api.getProductInventories("fru-002") assertThat(inventories).isNotEmpty() } }
8
Kotlin
2
1
d709b26d69cf46c3d6123a217190f098b79a6562
1,424
TazaBazar
Apache License 2.0
app/src/main/java/com/carterchen247/alarmscheduler/demo/log/LogItem.kt
CarterChen247
245,651,581
false
null
package com.carterchen247.alarmscheduler.demo.log data class LogItem( val msg: String, val time: String )
1
Kotlin
0
6
669bfcbffddcf3596aad6d8e2b1c00197ac9f87b
114
AlarmScheduler
The Unlicense
core/src/main/kotlin/me/kcra/takenaka/core/mapping/resolve/MappingResolver.kt
zlataovce
596,960,001
false
null
/* * This file is part of takenaka, licensed under the Apache License, Version 2.0 (the "License"). * * Copyright (c) 2023 <NAME> * * 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 me.kcra.takenaka.core.mapping.resolve import me.kcra.takenaka.core.Version import me.kcra.takenaka.core.VersionedWorkspace import java.nio.file.Path /** * A mapping file resolver. * * @author <NAME> */ interface MappingResolver : OutputContainer<Path?> { /** * The mapping workspace. */ val workspace: VersionedWorkspace /** * The mapping file output of this resolver. */ val mappingOutput: Output<out Path?> } /** * A shorthand for getting the workspace version. */ inline val MappingResolver.version: Version get() = workspace.version /** * A base for a mapping resolver. * * Subclasses should override the [outputs] property with their own values. */ abstract class AbstractMappingResolver : AbstractOutputContainer<Path?>(), MappingResolver
5
Kotlin
0
8
bf716f44463c88d9079e2a3296ca07593d8da692
1,436
takenaka
Apache License 2.0
app/src/main/java/com/tomclaw/nimpas/screen/book/list/BookListInteractor.kt
solkin
148,905,097
false
null
package com.tomclaw.nimpas.screen.book.list import com.tomclaw.nimpas.storage.Book import com.tomclaw.nimpas.storage.Shelf import com.tomclaw.nimpas.util.SchedulersFactory import io.reactivex.Completable import io.reactivex.Observable interface BookListInteractor { fun listBooks(): Observable<Map<String, Book>> fun switchBook(id: String): Completable } class BookListInteractorImpl( private val shelf: Shelf, private val schedulers: SchedulersFactory ) : BookListInteractor { override fun listBooks(): Observable<Map<String, Book>> { return shelf.listBooks() .toObservable() .subscribeOn(schedulers.io()) } override fun switchBook(id: String): Completable { return shelf.switchBook(id) .subscribeOn(schedulers.io()) } }
1
null
1
2
778898001880685b2beb93e386f652e4e984d2c3
834
nimpas-android
MIT License
src/main/kotlin/se/brainleech/adventofcode/aoc2015/Aoc2015Day03.kt
fwangel
435,571,075
false
null
package se.brainleech.adventofcode.aoc2015 import se.brainleech.adventofcode.compute import se.brainleech.adventofcode.readText import se.brainleech.adventofcode.verify class Aoc2015Day03 { data class Position(val x: Int, val y: Int) { fun move(direction: Char): Position { return when (direction) { '<' -> Position(x - 1, y) '>' -> Position(x + 1, y) '^' -> Position(x, y - 1) 'v' -> Position(x, y + 1) else -> this } } } fun part1(input: String): Int { var position = Position(0, 0) val visited = mutableMapOf(position to 1) input.onEach { direction -> position = position.move(direction) visited.merge(position, 1) { a, b -> a + b } } return visited.values.count() } fun part2(input: String): Int { var santaPosition = Position(0, 0) var robotPosition = Position(0, 0) val visited = mutableMapOf(santaPosition to 2) input.onEachIndexed { index, direction -> if (index.mod(2) == 0) { santaPosition = santaPosition.move(direction) visited.merge(santaPosition, 1) { a, b -> a + b } } else { robotPosition = robotPosition.move(direction) visited.merge(robotPosition, 1) { a, b -> a + b } } } return visited.values.count() } } fun main() { val solver = Aoc2015Day03() val prefix = "aoc2015/aoc2015day03" val testData = readText("$prefix.test.txt") val realData = readText("$prefix.real.txt") verify(4, solver.part1(testData)) compute({ solver.part1(realData) }, "$prefix.part1 = ") verify(3, solver.part2(testData)) compute({ solver.part2(realData) }, "$prefix.part2 = ") }
0
Kotlin
0
0
0bba96129354c124aa15e9041f7b5ad68adc662b
1,867
adventofcode
MIT License
src/main/java/me/han/muffin/client/event/events/client/PostMoveEvent.kt
SmallFishDD
425,272,585
false
{"Kotlin": 1725682, "Java": 943392, "GLSL": 15937}
package me.han.muffin.client.event.events.client class PostMoveEvent
1
Kotlin
2
2
13235eada9edd9ccca039dea4d3a59cc7a930830
69
muffin-0.10.4-src-leaked
MIT License
app/src/androidTest/java/com/mub/almostaferandroidtask/features/home/viewmodel/HomeViewModelTest.kt
ahmedMubarak2024
645,084,909
false
null
package com.mub.almostaferandroidtask.features.home.viewmodel import androidx.paging.AsyncPagingDataDiffer import com.mub.almostaferandroidtask.helper.BaseRoomTest import com.mub.almostaferandroidtask.helper.TestDiffCallback import com.mub.almostaferandroidtask.helper.TestListCallback import com.mub.almostaferandroidtask.model.Constants import com.mub.almostaferandroidtask.model.comman.Movie import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.launch import kotlinx.coroutines.test.runTest import org.junit.Assert import org.junit.Test import org.koin.core.component.inject import kotlin.time.Duration.Companion.seconds class HomeViewModelTest : BaseRoomTest() { private val homeViewModel: HomeViewModel by inject() private val differ = AsyncPagingDataDiffer( diffCallback = TestDiffCallback<Movie>(), updateCallback = TestListCallback(), workerDispatcher = Dispatchers.Main ) suspend fun delayTime(): String { Thread.sleep(1000) return "" } @Test fun testObservePubMovies_whenPubMoviesInDataBase() { addPubMovies() val differ = AsyncPagingDataDiffer( diffCallback = TestDiffCallback<Movie>(), updateCallback = TestListCallback(), workerDispatcher = Dispatchers.Main ) runTest(timeout = 60.seconds) { val job = launch { differ.submitData(homeViewModel.observePubMovies().firstOrNull()!!) } awaitAll(async { delayTime() }) Assert.assertTrue( "should return list not empty", differ.snapshot().items.isNotEmpty() ) job.cancel() } } @Test fun testObservePubMovies_onlyReturnPubMoviesInDataBase() { addPubMovies() addRevenueMovies() addAverageVoteMovies() runTest(timeout = 60.seconds) { homeViewModel.observePubMovies().firstOrNull()?.let { val job = launch { differ.submitData(it) } delayTime() Assert.assertFalse( "shouldOnlyReturnPubMovies", differ.snapshot().items.any { it.sortedBy != Constants.SORTED_BY_POPULARITY }) job.cancel() } } } @Test fun testObservePubMovies_returnEmptyListWhenNoPubMovies() { addRevenueMovies() addAverageVoteMovies() runTest(timeout = 60.seconds) { homeViewModel.observePubMovies().firstOrNull()?.let { val job = launch { differ.submitData(it) } delayTime() Assert.assertTrue("shouldReturnEmptyList", differ.snapshot().items.isEmpty()) job.cancel() } } } @Test fun testAddRevenueMovies_whenRevenueMoviesInDataBase() { addRevenueMovies() val differ = AsyncPagingDataDiffer( diffCallback = TestDiffCallback<Movie>(), updateCallback = TestListCallback(), workerDispatcher = Dispatchers.Main ) runTest(timeout = 60.seconds) { val job = launch { differ.submitData(homeViewModel.observeRevenueMovies().firstOrNull()!!) } awaitAll(async { delayTime() }) Assert.assertTrue( "should return list not empty", differ.snapshot().items.isNotEmpty() ) job.cancel() } } @Test fun testAddRevenueMovies_onlyReturnRevenueMoviesInDataBase() { addPubMovies() addRevenueMovies() addAverageVoteMovies() runTest(timeout = 60.seconds) { homeViewModel.observeRevenueMovies().firstOrNull()?.let { val job = launch { differ.submitData(it) } delayTime() Assert.assertFalse( "shouldOnlyReturnPubMovies", differ.snapshot().items.any { it.sortedBy != Constants.SORTED_BY_POPULARITY }) job.cancel() } } } @Test fun testAddRevenueMovies_returnEmptyListWhenNoRevenueMovies() { addPubMovies() addAverageVoteMovies() runTest(timeout = 60.seconds) { homeViewModel.observeRevenueMovies().firstOrNull()?.let { val job = launch { differ.submitData(it) } delayTime() Assert.assertTrue("shouldReturnEmptyList", differ.snapshot().items.isEmpty()) job.cancel() } } } @Test fun testAddAverageVoteMovies_whenAverageVoteMoviesInDataBase() { addAverageVoteMovies() val differ = AsyncPagingDataDiffer( diffCallback = TestDiffCallback<Movie>(), updateCallback = TestListCallback(), workerDispatcher = Dispatchers.Main ) runTest(timeout = 60.seconds) { val job = launch { differ.submitData(homeViewModel.observeAverageVoteMovies().firstOrNull()!!) } awaitAll(async { delayTime() }) Assert.assertTrue( "should return list not empty", differ.snapshot().items.isNotEmpty() ) job.cancel() } } @Test fun testAddAverageVoteMovies_onlyReturnAverageVoteMoviesInDataBase() { addPubMovies() addRevenueMovies() addAverageVoteMovies() runTest(timeout = 60.seconds) { homeViewModel.observeAverageVoteMovies().firstOrNull()?.let { val job = launch { differ.submitData(it) } delayTime() Assert.assertFalse( "shouldOnlyReturnPubMovies", differ.snapshot().items.any { it.sortedBy != Constants.SORTED_BY_POPULARITY }) job.cancel() } } } @Test fun testAddAverageVoteMovies_returnEmptyListWhenNoAverageVoteMovies() { addPubMovies() addRevenueMovies() runTest(timeout = 60.seconds) { homeViewModel.observeAverageVoteMovies().firstOrNull()?.let { val job = launch { differ.submitData(it) } delayTime() Assert.assertTrue("shouldReturnEmptyList", differ.snapshot().items.isEmpty()) job.cancel() } } } }
0
Kotlin
0
0
9fe719552d26e3e2c6d1a1da3a95de82307f2f4e
6,731
AlMostaferAndroidTask
Apache License 2.0
kotlin-spring-boot/src/main/kotlin/x/domainpersistencemodeling/DemoApplication.kt
binkley
227,846,529
false
null
package x.domainpersistencemodeling import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication // TODO: Why doesn't Spring plugin for Kotlin make this `open`? class DemoApplication fun main(args: Array<String>) { runApplication<DemoApplication>(*args) }
1
null
1
1
22dc7763ef1cffb63ffb0f18f7bbe5f6fb975b4e
340
domain-persistence-modeling
The Unlicense
app/src/main/java/com/lahsuak/apps/tasks/ui/widget/TaskWidgetCompose.kt
KaushalVasava
506,109,776
false
null
package com.lahsuak.apps.tasks.ui.widget import android.app.PendingIntent import android.app.TaskStackBuilder import android.content.Context import android.content.Intent import android.content.Intent.FLAG_ACTIVITY_NEW_TASK import android.os.Build import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.core.net.toUri import androidx.glance.GlanceId import androidx.glance.GlanceModifier import androidx.glance.Image import androidx.glance.ImageProvider import androidx.glance.action.ActionParameters import androidx.glance.action.clickable import androidx.glance.appwidget.GlanceAppWidget import androidx.glance.appwidget.GlanceAppWidgetReceiver import androidx.glance.appwidget.action.ActionCallback import androidx.glance.appwidget.action.actionRunCallback import androidx.glance.appwidget.cornerRadius import androidx.glance.appwidget.provideContent import androidx.glance.appwidget.state.updateAppWidgetState import androidx.glance.background import androidx.glance.layout.Row import androidx.glance.layout.padding import androidx.glance.text.Text import com.lahsuak.apps.tasks.R import com.lahsuak.apps.tasks.ui.MainActivity import com.lahsuak.apps.tasks.ui.theme.lightBlue import com.lahsuak.apps.tasks.util.NavigationConstants object TaskWidgetCompose : GlanceAppWidget() { override suspend fun provideGlance(context: Context, id: GlanceId) { provideContent { Image( provider = ImageProvider(R.drawable.ic_edit), contentDescription = stringResource(id = R.string.add_task), modifier = GlanceModifier .background(lightBlue) .padding(16.dp) .cornerRadius(8.dp) .clickable( actionRunCallback(TaskActionCallback::class.java) ) ) } } } class TaskWidgetReceiver : GlanceAppWidgetReceiver() { override val glanceAppWidget: GlanceAppWidget get() = TaskWidgetCompose } class TaskActionCallback : ActionCallback { override suspend fun onAction( context: Context, glanceId: GlanceId, parameters: ActionParameters, ) { updateAppWidgetState(context, glanceId) { val deepLinkIntent = Intent( Intent.ACTION_VIEW, NavigationConstants.Key.ADD_UPDATE_TASK_DEEP_LINK.toUri(), context, MainActivity::class.java ).apply { flags = FLAG_ACTIVITY_NEW_TASK } val flag = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.S) { PendingIntent.FLAG_IMMUTABLE } else PendingIntent.FLAG_UPDATE_CURRENT val deepLinkPendingIntent: PendingIntent = TaskStackBuilder.create(context).run { addNextIntentWithParentStack(deepLinkIntent) getPendingIntent(0, flag) } deepLinkPendingIntent.send() } TaskWidgetCompose.update(context, glanceId) } }
1
null
5
30
49e024e90b1f58612e174336983c0e304afd647f
3,073
Tasks
Apache License 2.0
idea/testData/refactoring/copy/copyWithImportInsertion/before/foo/Foo.kt
JakeWharton
99,388,807
false
null
package foo import bar.bar class <caret>Foo { init { 42.bar() } } class Baz { }
0
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
99
kotlin
Apache License 2.0
app/src/test/java/com/example/basearch/UserDaoTest.kt
carlosalexandre3107
240,369,695
true
{"Kotlin": 52263}
package com.example.basearch import junit.framework.Assert.assertEquals import kotlinx.coroutines.runBlocking import org.junit.Test class UserDaoTest { @Test fun insertAndGetUser() = runBlocking { // // Given a User that has been inserted into the DB // userDao.insertUser(user) // // // When getting the Users via the DAO // val usersFromDb = userDao.getUsers() // // // Then the retrieved Users matches the original user object // assertEquals(listOf(user), userFromDb) } }
0
null
0
0
f6b54c2269d8ead03765776d6ad9d0bdc16a991b
531
android-base-architecture
MIT License
vector/src/main/java/im/vector/app/features/analytics/plan/CreatedRoom.kt
tchapgouv
340,329,238
false
null
/* * Copyright (c) 2021 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.app.features.analytics.plan import im.vector.app.features.analytics.itf.VectorAnalyticsEvent // GENERATED FILE, DO NOT EDIT. FOR MORE INFORMATION VISIT // https://github.com/matrix-org/matrix-analytics-events/ /** * Triggered when the user creates a room. */ data class CreatedRoom( /** * Whether the room is a DM. */ val isDM: Boolean, ) : VectorAnalyticsEvent { override fun getName() = "CreatedRoom" override fun getProperties(): Map<String, Any>? { return mutableMapOf<String, Any>().apply { put("isDM", isDM) }.takeIf { it.isNotEmpty() } } }
4
null
6
9
5aa86fe9d36ad8087f289152d5e718fdfad65a2c
1,233
tchap-android
Apache License 2.0
domain/src/main/java/com/mctech/stocktradetracking/domain/stock_share/interaction/strategies/ComputeBalanceStrategy.kt
Martins-Iroka
268,206,701
true
{"Kotlin": 273800}
package com.mctech.stocktradetracking.domain.stock_share.interaction.strategies import com.mctech.stocktradetracking.domain.stock_share.entity.StockShare import com.mctech.stocktradetracking.domain.stock_share.entity.StockShareFinalBalance interface ComputeBalanceStrategy { fun execute(stockShareList: List<StockShare>): StockShareFinalBalance }
0
null
0
0
2a21fd6eaff708de721eeafb189d1bee916cd721
352
StockTradeTracking
Apache License 2.0
app/src/main/java/com/bluerayfsm/features/dailyPlan/model/AllPlanListResponseModel.kt
DebashisINT
772,059,684
false
{"Kotlin": 14146263, "Java": 1002625}
package com.bluerayfsm.features.dailyPlan.model import com.bluerayfsm.base.BaseResponse import java.io.Serializable /** * Created by Saikat on 03-01-2020. */ class AllPlanListResponseModel : BaseResponse(), Serializable { var plan_data: ArrayList<AllPlanListDataModel>? = null }
0
Kotlin
0
0
875bc5a3927897d1daa465a4f122c35df513a7ec
286
BluerayFSM
Apache License 2.0
app/src/main/java/com/learning/photoshow/core/viewmodels/SplashViewModel.kt
ramzyhassan44
358,888,621
false
null
package com.learning.photoshow.core.viewmodels import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.learning.photoshow.core.routers.MAIN_SCREEN_ROUTER import com.learning.photoshow.core.routers.Router import kotlinx.coroutines.delay import kotlinx.coroutines.launch class SplashViewModel(private val router: Router) : ViewModel() { fun initialize() { viewModelScope.launch { delay(3000) router.routeTo(MAIN_SCREEN_ROUTER, null, true) } } }
0
Kotlin
0
0
93004bd8e795235985180a8f0e92d5886065a4b7
525
photos-show
Apache License 2.0
app/src/main/java/com/mashaktifoodfsm/features/weather/api/WeatherRepo.kt
DebashisINT
515,081,791
false
{"Kotlin": 13505104, "Java": 994492}
package com.mashaktifoodfsm.features.weather.api import com.mashaktifoodfsm.base.BaseResponse import com.mashaktifoodfsm.features.task.api.TaskApi import com.mashaktifoodfsm.features.task.model.AddTaskInputModel import com.mashaktifoodfsm.features.weather.model.ForeCastAPIResponse import com.mashaktifoodfsm.features.weather.model.WeatherAPIResponse import io.reactivex.Observable class WeatherRepo(val apiService: WeatherApi) { fun getCurrentWeather(zipCode: String): Observable<WeatherAPIResponse> { return apiService.getTodayWeather(zipCode) } fun getWeatherForecast(zipCode: String): Observable<ForeCastAPIResponse> { return apiService.getForecast(zipCode) } }
0
Kotlin
0
0
4feb7a634cfdbaba5d8df8384d8b2d94f55886c9
700
MashaktiFood
Apache License 2.0
oauth2-webclient-sample/src/main/kotlin/net/medeiser/samples/oauth/secure/oauth2webclientsample/config/WebClientConfig.kt
medeiser
270,338,040
false
null
package net.medeiser.samples.oauth.secure.oauth2webclientsample.config import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientManager import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientProviderBuilder import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository import org.springframework.security.oauth2.client.web.DefaultReactiveOAuth2AuthorizedClientManager import org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository import org.springframework.web.reactive.function.client.WebClient @Configuration class WebClientConfig { @Bean fun webClient(authorizedClientManager: ReactiveOAuth2AuthorizedClientManager): WebClient { val oauth2Client = ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager) oauth2Client.setDefaultClientRegistrationId("custom") return WebClient.builder() .filter(oauth2Client) .build() } @Bean fun authorizedClientManager( clientRegistrationRepository: ReactiveClientRegistrationRepository, authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager { val authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder() .clientCredentials() .build() val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager( clientRegistrationRepository, authorizedClientRepository) authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) return authorizedClientManager } }
1
Kotlin
1
2
7642a41e95c68a8e3ab864a8e6714eeca9d685ec
1,971
kotlin-oauth2-services
MIT License
monad-stack/src/main/java/com/github/jorgecastillo/kotlinandroid/presentation/navigation/Navigation.kt
yesitskev
129,077,640
true
{"Kotlin": 69704}
package com.github.jorgecastillo.kotlinandroid.presentation.navigation import arrow.core.IdHK import arrow.data.Reader import arrow.data.map import com.github.jorgecastillo.kotlinandroid.di.context.SuperHeroesContext.GetHeroesContext import com.github.jorgecastillo.kotlinandroid.view.SuperHeroDetailActivity class HeroDetailsPage { fun go(heroId: String) = Reader.ask<IdHK, GetHeroesContext>().map({ (ctx) -> SuperHeroDetailActivity.launch(ctx, heroId) }) }
0
Kotlin
0
0
4f76358f91c5d869ab7c40cdecfcdbccc46d28cb
469
ArrowAndroidSamples
Apache License 2.0
app/src/main/java/com/deanezra/network/model/PlantsResponse.kt
deanezra
345,489,844
false
null
package com.deanezra.network.model import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName // The Trefle plants api returns a list of plants in Json array called 'data', // a links object (with urls) and a meta object (with a total counts of all plants). // So we use this 'base' class to allow Retrofit serialize the data into a list of Plant objects: class PlantsResponse { @SerializedName("data") @Expose var plantlist: MutableList<Plant>? = null // For simplicity, We don't care about links and meta in this app /* @SerializedName("links") @Expose var links: Int? = null @SerializedName("meta") @Expose var meta: String? = null */ }
0
Kotlin
0
0
15849d0ae698e508d58fa1fff13589a7b9efe7a1
725
TreflePlantsAndroid
Apache License 2.0
app/src/main/java/com/example/skyapartmentscleaning/data/hystory_checklist/HistoryChecklistPoint.kt
Volkoks
308,943,911
false
null
package com.example.skyapartmentscleaning.data.hystory_checklist data class HistoryChecklistPoint( val namePoint: String, val descriptionPoint: String )
0
Kotlin
0
0
847fa306a2fd88a0e42b4f99dc50a453eece93d0
161
sky_cleaning
Apache License 2.0
src/commonMain/kotlin/khala/internal/zmq/client/ClientLoopQuery.kt
ardenit
292,069,266
false
{"Kotlin": 108807}
package khala.internal.zmq.client internal sealed class ClientLoopQuery<L, S> { internal class InvokeQuery<L, S>(val block: ClientLoopScope<L, S>.(L) -> Unit) : ClientLoopQuery<L, S>() internal class StopQuery<L, S> : ClientLoopQuery<L, S>() }
3
Kotlin
0
0
8955092d9c6c36b1a7407017ef2a327e51e6d7b4
257
khala-internal
Apache License 2.0
app/src/main/java/com/ahndwon/gethub/api/dao/UserData.kt
ahndwon
141,035,948
false
{"Kotlin": 86408, "Java": 1113}
package com.ahndwon.gethub.api.dao import com.google.gson.annotations.SerializedName data class UserData(val login: String, val name: String, @field:SerializedName("repos_url") val reposUrl: String, @field:SerializedName("avatar_url") val avatarUrl: String, val email: String, val followers: Int, val following: Int, val url: String)
2
Kotlin
0
0
48839270d05ed8276b5c9890639766801a99c491
516
GetHub
Apache License 2.0
app/src/main/java/com/bengcare/bengcare/utils/paging/BookingPagingSource.kt
BengCare
796,771,725
false
{"Kotlin": 421897}
package com.bengcare.bengcare.utils.paging import androidx.paging.PagingSource import androidx.paging.PagingState import com.bengcare.bengcare.data.local.LocalDataSource import com.bengcare.bengcare.data.remote.RemoteDataSource import com.bengcare.bengcare.data.remote.response.Booking import com.bengcare.bengcare.utils.Resource import kotlinx.coroutines.flow.MutableSharedFlow class BookingPagingSource( private val status: String, private val flow: MutableSharedFlow<Resource<Unit>>, private val localDataSource: LocalDataSource, private val remoteDataSource: RemoteDataSource ) : PagingSource<Int, Booking>() { private companion object { const val INITIAL_PAGE_INDEX = 1 } override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Booking> { return try { val position = params.key ?: INITIAL_PAGE_INDEX if(position== INITIAL_PAGE_INDEX) { flow.emit(Resource.LOADING()) } val responseData = remoteDataSource.getAllBooking( authorization = "Bearer ${localDataSource.checkToken().toString()}", page = position, perPage = params.loadSize, status = status ) LoadResult.Page( data = responseData.body()!!.data, prevKey = if (position == INITIAL_PAGE_INDEX) null else position - 1, nextKey = if (responseData.body()!!.data.isEmpty()) null else position + 1 ).also { if(responseData.body()!!.data.isEmpty() && position == INITIAL_PAGE_INDEX) { flow.emit(Resource.EMPTY()) } else { flow.emit(Resource.SUCCESS(Unit)) } } } catch (exception: Exception) { flow.emit(Resource.ERROR(exception.toString())) return LoadResult.Error(exception) } } override fun getRefreshKey(state: PagingState<Int, Booking>): Int? { return state.anchorPosition?.let { anchorPosition -> val anchorPage = state.closestPageToPosition(anchorPosition) anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1) } } }
0
Kotlin
0
0
177d60c1f224e0b29f5f5e8c38019ca55234c300
2,285
BengCare-Android
MIT License
src/main/java/yoshikihigo/cpanalyzer/binding/nitron/StatementWithAst.kt
Durun
220,210,684
true
{"Git Config": 1, "Gradle": 2, "Shell": 1, "Text": 3, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "INI": 2, "Java": 239, "Kotlin": 3, "YAML": 1}
package yoshikihigo.cpanalyzer.binding.nitron import com.github.durun.nitron.core.ast.node.AstNode import yoshikihigo.cpanalyzer.data.Statement import yoshikihigo.cpanalyzer.lexer.token.Token class StatementWithAst( fromLine: Int, toLine: Int, nestLevel: Int, isTarget: Boolean, tokens: List<Token>, rText: String, nText: String, hash: ByteArray, val ast: AstNode? ) : Statement(fromLine, toLine, nestLevel, isTarget, tokens, rText, nText, hash) { }
0
Java
0
0
0cc43e9660230dcb0e25aba27a0ecc8446337778
523
MPAnalyzer
MIT License
src/main/java/catmoe/fallencrystal/moefilter/api/command/impl/test/event/MessageEvent.kt
CatMoe
638,486,044
false
null
package catmoe.fallencrystal.moefilter.api.command.impl.test.event import catmoe.fallencrystal.moefilter.api.event.EventListener import catmoe.fallencrystal.moefilter.api.event.FilterEvent import catmoe.fallencrystal.moefilter.api.event.events.TestMessageEvent import catmoe.fallencrystal.moefilter.util.message.MessageUtil import net.md_5.bungee.api.connection.ProxiedPlayer class MessageEvent : EventListener { @FilterEvent fun handleMessageEvent(event: TestMessageEvent) { val sender = event.sender val message = event.message val type = event.type if (sender !is ProxiedPlayer) { MessageUtil.logInfo(message); return } // Console MessageUtil.sendMessage(sender, type, message) } }
2
Kotlin
0
2
4afea088e12dc89d93dbc54f9c3a30b9c0d6f3f7
739
MoeFilter
Apache License 2.0
ext-spring-boot-starter-springmvc-automapping/src/main/kotlin/nxcloud/ext/springmvc/automapping/spring/boot/autoconfigure/support/NXSpringMvcAutoMappingAutoConfiguration.kt
Sunshow
588,022,200
false
null
package nxcloud.ext.springmvc.automapping.spring.boot.autoconfigure.support import com.fasterxml.jackson.databind.ObjectMapper import nxcloud.ext.springmvc.automapping.spi.impl.JacksonAutoMappingRequestParameterResolver import nxcloud.ext.springmvc.automapping.spi.impl.PathVariableAutoMappingRequestParameterResolver import nxcloud.ext.springmvc.automapping.spi.impl.QueryParameterAutoMappingRequestParameterResolver import nxcloud.ext.springmvc.automapping.spring.AutoMappingHandlerMethodArgumentResolver import nxcloud.ext.springmvc.automapping.spring.AutoMappingRequestHandlerRegistrar import nxcloud.ext.springmvc.automapping.spring.AutoMappingRequestParameterTypeBinding import nxcloud.ext.springmvc.automapping.spring.AutoMappingRequestResponseBodyMethodProcessor import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.autoconfigure.AutoConfiguration import org.springframework.boot.autoconfigure.condition.ConditionalOnClass import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.core.annotation.Order import org.springframework.http.converter.HttpMessageConverter import org.springframework.web.method.support.HandlerMethodArgumentResolver import org.springframework.web.method.support.HandlerMethodReturnValueHandler import org.springframework.web.servlet.config.annotation.WebMvcConfigurer import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice @AutoConfiguration @ConditionalOnClass(RequestMappingHandlerMapping::class) class NXSpringMvcAutoMappingAutoConfiguration { @Bean @ConditionalOnMissingBean(AutoMappingRequestHandlerRegistrar::class) protected fun autoMappingRequestHandlerRegistrar(): AutoMappingRequestHandlerRegistrar { return AutoMappingRequestHandlerRegistrar() } @Bean @ConditionalOnMissingBean(AutoMappingHandlerMethodArgumentResolver::class) protected fun autoMappingRequestBodyArgumentResolver(): AutoMappingHandlerMethodArgumentResolver { return AutoMappingHandlerMethodArgumentResolver() } @Bean @ConditionalOnMissingBean(AutoMappingRequestResponseBodyMethodProcessor::class) protected fun autoMappingRequestResponseBodyMethodProcessor( converters: List<HttpMessageConverter<*>>, responseBodyAdvices: List<ResponseBodyAdvice<out Any>>?, ): AutoMappingRequestResponseBodyMethodProcessor { return AutoMappingRequestResponseBodyMethodProcessor(converters, responseBodyAdvices) } @Bean @ConditionalOnMissingBean(AutoMappingRequestParameterTypeBinding::class) protected fun autoMappingRequestParameterTypeBinding(): AutoMappingRequestParameterTypeBinding { return AutoMappingRequestParameterTypeBinding() } @Order(1020) @Bean @ConditionalOnClass(ObjectMapper::class) @ConditionalOnMissingBean(JacksonAutoMappingRequestParameterResolver::class) protected fun jacksonAutoMappingRequestParameterResolver(objectMapper: ObjectMapper): JacksonAutoMappingRequestParameterResolver { return JacksonAutoMappingRequestParameterResolver(objectMapper) } @Order(1010) @Bean @ConditionalOnMissingBean(QueryParameterAutoMappingRequestParameterResolver::class) protected fun queryParameterAutoMappingRequestParameterResolver(): QueryParameterAutoMappingRequestParameterResolver { return QueryParameterAutoMappingRequestParameterResolver() } // 需要先处理路径上的参数解析 @Order(1000) @Bean @ConditionalOnMissingBean(PathVariableAutoMappingRequestParameterResolver::class) protected fun pathVariableAutoMappingRequestParameterResolver(): PathVariableAutoMappingRequestParameterResolver { return PathVariableAutoMappingRequestParameterResolver() } @Configuration @ConditionalOnClass(WebMvcConfigurer::class) internal class AutoMappingReturnValueWebMvcConfigurer : WebMvcConfigurer { @Autowired private lateinit var autoMappingHandlerMethodArgumentResolver: AutoMappingHandlerMethodArgumentResolver @Autowired private lateinit var autoMappingRequestResponseBodyMethodProcessor: AutoMappingRequestResponseBodyMethodProcessor override fun addReturnValueHandlers(handlers: MutableList<HandlerMethodReturnValueHandler>) { // 如果有需要直接返回 void 的情况,需要通过直接设置 RequestMappingHandlerAdapter 的 returnValueHandlers, // 把 AutoMappingRequestResponseBodyMethodProcessor 放在 ViewNameMethodReturnValueHandler 前面, 否则会被 ViewNameMethodReturnValueHandler 拦截 // 绝大部分情况接口都会做统一封装, 所以不会有直接返回 void 的情况, 所以这里暂时不做处理 handlers.add( autoMappingRequestResponseBodyMethodProcessor ) } override fun addArgumentResolvers(resolvers: MutableList<HandlerMethodArgumentResolver>) { resolvers.add( autoMappingHandlerMethodArgumentResolver ) } } }
0
Kotlin
0
0
8e64ac8fc0bb947082590c90011de2df036a30e7
5,134
nxcloud-springmvc-automapping
Apache License 2.0
app/src/main/java/dev/ztivnick/boredwatch/RetrofitObject.kt
ztivnick
505,156,674
false
null
package dev.ztivnick.boredwatch import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object RetrofitObject { private const val baseUrl = "http://www.boredapi.com/" private fun getRetrofitInstance(): Retrofit { return Retrofit.Builder().baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .build() } val retrofitInstance: BoredInterface = getRetrofitInstance().create(BoredInterface::class.java) }
0
Kotlin
0
0
6444433e4e73d0a157c2725d8803832b87b73688
490
Bored-Watch
MIT License
src/main/kotlin/AST/ASTArrayAccessNode.kt
Ten-James
696,690,413
false
{"Kotlin": 106391, "C": 587}
package AST import compiler.DefinedType class ASTArrayAccessNode: ASTVariableNode { var array:ASTVariableNode var index:ASTNode constructor(array:ASTVariableNode, index:ASTNode): super("", DefinedType("")) { this.array = array this.index = index } override fun getType(): DefinedType { return array.getType().toDereference() } override fun copy(): ASTArrayAccessNode { return ASTArrayAccessNode(array.copy(), index.copy()) } override fun retype(map: Map<String, DefinedType>) { array.retype(map) index.retype(map) } override fun toString(): String { return "ARRAY ACCESS, \narray=${array.toString().replace("\n","\n\t")}, \nindex=${index.toString().replace("\n","\n\t")}\n" } override fun toC(sideEffect:Boolean): String { return "${array.toC(false)}[${index.toC(false)}]" } }
0
Kotlin
1
1
0840541d9a47887e055d124833a34943fc0d56f0
903
czechtina
MIT License
resource/src/main/kotlin/me/jiangcai/common/resource/impl/OSSResource.kt
mingshz
166,675,112
false
{"Gradle": 20, "INI": 11, "Shell": 2, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 10, "XML": 8, "Kotlin": 311, "JavaScript": 1, "HTML": 4, "Java Properties": 10, "Java": 71, "JSON": 2}
package me.jiangcai.common.resource.impl import com.aliyun.oss.OSS import me.jiangcai.common.resource.Resource import org.springframework.core.io.AbstractResource import org.springframework.core.io.WritableResource import java.io.* import java.net.URL /** * @author CJ */ class OSSResource( private val client: OSS, private val bucketName: String, private val path: String, private val urlPrefix: String ) : AbstractResource(), Resource, WritableResource { override fun httpUrl(): URL { return URL(urlPrefix + path) } override fun getResourcePath(): String = path override fun getDescription(): String = "oss resource of $path" override fun exists(): Boolean { return try { client.getObjectMetadata(bucketName, path) != null } catch (e: Exception) { false } } override fun contentLength(): Long { return client.getObjectMetadata(bucketName, path).contentLength } override fun lastModified(): Long { return client.getObjectMetadata(bucketName, path).lastModified.time } override fun getFilename(): String { return path } override fun getURL(): URL { return httpUrl() } override fun getInputStream(): InputStream { return client.getObject(bucketName, path) .use { ByteArrayInputStream(it.objectContent.readBytes()) } } override fun isWritable(): Boolean = true override fun getOutputStream(): OutputStream { return object : ByteArrayOutputStream() { @Throws(IOException::class) override fun close() { client.putObject(bucketName, path, ByteArrayInputStream(buf)) } } } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is OSSResource) return false // if (!super.equals(other)) return false if (bucketName != other.bucketName) return false if (path != other.path) return false return true } override fun hashCode(): Int { var result = 0 result = 31 * result + bucketName.hashCode() result = 31 * result + path.hashCode() return result } }
1
null
1
1
8c9566723e6fe39c4fadc1262212a9e4aa3fd660
2,282
library
MIT License
app/src/main/java/com/example/appsophos/features/dashboard/presentation/MenuScreenFragment.kt
AngyeTR
576,984,367
false
{"Kotlin": 73318}
package com.example.appsophos.features.dashboard.presentation import android.content.res.Configuration import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatDelegate import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import com.example.appsophos.R import com.example.appsophos.SharedApp.Companion.prefs import com.google.android.material.appbar.MaterialToolbar import java.util.Locale class MenuScreenFragment: Fragment() { private lateinit var userName : String @RequiresApi(Build.VERSION_CODES.N) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) userName = prefs?.namePref.toString() var lang = prefs?.langPref if (lang.equals("es")) { setLang("es") } else { setLang("en") } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_menu_screen, container, false) } @RequiresApi(Build.VERSION_CODES.N) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val btnSendDocs = view.findViewById<Button>(R.id.ob_send) val btnViewDocs = view.findViewById<Button>(R.id.ob_view) val btnOffices = view.findViewById<Button>(R.id.ob_office) setAppBar() btnSendDocs.setOnClickListener { findNavController().navigate(R.id.action_menuScreenFragment_to_sendDocsFragment) } btnViewDocs.setOnClickListener{ findNavController().navigate(R.id.action_menuScreenFragment_to_viewDocsFragment) } btnOffices.setOnClickListener{ findNavController().navigate(R.id.action_menuScreenFragment_to_officesScreenFragment) } } @RequiresApi(Build.VERSION_CODES.N) fun setAppBar(){ val appBar = view?.findViewById<MaterialToolbar>(R.id.topAppBar) appBar?.title = userName appBar?.setOnMenuItemClickListener{ menuItem -> when (menuItem.itemId) { R.id.send_option -> { findNavController().navigate(R.id.action_menuScreenFragment_to_sendDocsFragment) true } R.id.view_option -> { findNavController().navigate(R.id.action_menuScreenFragment_to_viewDocsFragment) true } R.id.offices_option -> { findNavController().navigate(R.id.action_menuScreenFragment_to_officesScreenFragment) true } R.id.mode_option -> { var darkMode = prefs?.modePref if(darkMode == true){ AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) prefs?.modePref = false } else { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) prefs?.modePref = true } findNavController().navigate(R.id.action_menuScreenFragment_self) true } R.id.lang_option -> { var lang = prefs?.langPref if (lang.equals("es")) { setLang("en") } else { setLang("es") } findNavController().navigate(R.id.action_menuScreenFragment_self) true } R.id.close_option -> { findNavController().navigate(R.id.action_menuScreenFragment_to_loginScreenFragment) true } else -> false } } } @RequiresApi(Build.VERSION_CODES.N) private fun setLang(lang: String) { val locale = Locale(lang) Locale.setDefault(locale) val config = Configuration() config.locale = locale resources.updateConfiguration(config, requireContext().resources.displayMetrics) prefs?.langPref = lang } }
0
Kotlin
0
0
b32a5edc5e325ac025febc253ba74ed80b9095f2
4,508
AppSophos
Apache License 2.0
jvm/word-finder/src/main/kotlin/net/maelbrancke/filip/service/Solver.kt
filipmaelbrancke
597,192,385
false
{"Rust": 268793, "Kotlin": 47518, "Shell": 17239, "Dockerfile": 478, "PLpgSQL": 238}
package net.maelbrancke.filip.service import arrow.core.Either import arrow.core.raise.Raise import arrow.core.raise.either import arrow.core.raise.ensure import net.maelbrancke.filip.CannotGenerateSolution import net.maelbrancke.filip.NoSolutionsAvailable import net.maelbrancke.filip.WordCombination import net.maelbrancke.filip.WordFinderError import net.maelbrancke.filip.logger const val DEFAULT_TARGET_LENGTH = 6 const val DEFAULT_NUMBER_OF_COMBINATIONS = 2 data class CreateSolution( val words: Set<String>, val targetLength: Int, val numberOfCombinations: Int = DEFAULT_NUMBER_OF_COMBINATIONS ) { companion object { operator fun invoke(inputWords: List<String>): CreateSolution { return CreateSolution(inputWords.toSet(), DEFAULT_TARGET_LENGTH) } } } interface SolverService { suspend fun findSolutions(input: CreateSolution): Either<WordFinderError, List<WordCombination>> } fun solverService(): SolverService = object : SolverService { private val logger = logger() private tailrec suspend fun Raise<CannotGenerateSolution>.recursiveSolutionGeneration( words: List<String>, index: Int, carryOn: List<WordCombination> ): List<WordCombination> { ensure(words.isNotEmpty()) { CannotGenerateSolution("Unable to generate a solution from too small an inpput collection $words") } if (index > words.lastIndex) { return carryOn } val otherElements = words.subList(0, index) + words.subList(index + 1, words.size) val element = words[index] return recursiveSolutionGeneration( words, index + 1, carryOn + otherElements.map { WordCombination(element + it, listOf(element, it)) }) } override suspend fun findSolutions(input: CreateSolution): Either<WordFinderError, List<WordCombination>> = either { val targetWords = input.words.extractWordsOfLength(input.targetLength) val inputWords = input.words.filter { it.length < input.targetLength } //.toList() logger.info("The target words are: $targetWords") ensure(inputWords.isNotEmpty()) { CannotGenerateSolution("Unable to generate a solution, invalid inputs") } val solutions = recursiveSolutionGeneration(inputWords, 0, emptyList()) .filter { it.output.length == input.targetLength } .filter { targetWords.contains(it.output) } ensure(solutions.isNotEmpty()) { NoSolutionsAvailable("Unable to find solutions for ${input.words}") } solutions } } fun genericSolverService(): SolverService = object : SolverService { private val logger = logger() private suspend fun generateCombinationsUntil( words: List<String>, combinationSize: Int, remainingLength: Int, start: Int, currentCombo: MutableList<String>, result: MutableList<WordCombination> ) { if (combinationSize == 0 && remainingLength == 0) { val combined = currentCombo.joinToString(separator = "") if (words.contains(combined)) { result.add(WordCombination(combined, currentCombo.toList())) } } for (i in start until words.size) { val word = words[i] if (word.length <= remainingLength) { currentCombo.add(word) generateCombinationsUntil( words, combinationSize - 1, remainingLength - word.length, i, currentCombo, result ) currentCombo.removeAt(currentCombo.size - 1) } } } override suspend fun findSolutions(input: CreateSolution): Either<WordFinderError, List<WordCombination>> = either { val result: MutableList<WordCombination> = mutableListOf() generateCombinationsUntil(input.words.toList(), input.numberOfCombinations, input.targetLength, 0, mutableListOf(), result) ensure(result.isNotEmpty()) { NoSolutionsAvailable("Unable to find solutions for ${input.words}") } result.toList() } } fun Set<String>.extractWordsOfLength(targetWordLength: Int) = this.filter { it.length == targetWordLength }
0
Rust
0
0
cc93acb760ec3d2b5ec150d8ef545869704d36a4
4,340
playground
MIT License
core/src/org/river/exertion/ecs/component/action/ActionLookComponent.kt
exertionriver
345,650,250
false
null
package org.river.exertion.ecs.component.action import com.badlogic.ashley.core.Component import ktx.ashley.mapperFor import org.river.exertion.ecs.component.action.core.IActionComponent class ActionLookComponent : IActionComponent, Component { override val componentName = "Look" companion object { val mapper = mapperFor<ActionLookComponent>() } }
0
Kotlin
0
2
e554d700d5fbc16953a61d782cbe63162072483a
373
koboldCave
MIT License
src/main/kotlin/com/github/xbaimiao/shoppro/core/shop/Shop.kt
xbaimiao
514,507,465
false
{"Kotlin": 82802, "Java": 207}
package com.github.xbaimiao.shoppro.core.shop import com.github.xbaimiao.shoppro.core.item.Item import com.github.xbaimiao.shoppro.core.item.ShopItem import org.bukkit.entity.Player import org.bukkit.inventory.ItemStack abstract class Shop { enum class ShopType(val string: String) { BUY("buy"), SELL("sell"); companion object { fun formString(string: String): ShopType { return ShopType.values().first { it.string == string } } } } abstract fun getTitle(player: Player): String abstract fun getType(): ShopType abstract fun getName(): String abstract fun sellAll(player: Player) abstract fun open(player: Player) abstract fun getItems(): Collection<Item> abstract fun sellItem(player: Player, shopItem: ShopItem, itemStack: ItemStack): Boolean }
0
Kotlin
2
0
2be5e653c2296c0cd41b8cf82eeee3c8a24a924e
859
ShopPro
MIT License