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
src/main/kotlin/com/bpsrobotics/engine/utils/Sugar.kt
TheFlyingHedgehogs
446,919,594
false
null
package com.bpsrobotics.engine.utils import com.kauailabs.navx.frc.AHRS import kotlin.math.PI // Don't show warnings if these functions are unused or could be private @Suppress("unused", "MemberVisibilityCanBePrivate") /** * Sugar is an object where we are adding convenience functions */ object Sugar { /** * Converts the value from radians to degrees * * @return the value in radians as a double */ fun Double.radiansToDegrees(): Double { return times(180 / PI) } /** * Converts the value from degrees to radians * * @return the value in degrees as a double */ fun Double.degreesToRadians(): Double { return times(PI / 180) } /** * Converts the value from radians to degrees * * @return the value in radians as a double */ fun Int.radiansToDegrees(): Double { return toDouble().radiansToDegrees() } /** * Converts the value from degrees to radians * * @return the value in degrees as a double */ fun Int.degreesToRadians():Double{ return toDouble().degreesToRadians() } /** * Clamps this double to be within the range [min]..[max], inclusive. */ fun Double.clamp(min: Double = 0.0, max: Double = 1.0) = this.coerceIn(min, max) } typealias NAVX = AHRS
0
Kotlin
0
1
6e35698cf194d7cdbec05ecee8873f0c16fabeb5
1,342
2022-rapid-react
Apache License 2.0
data/src/main/java/com/example/data/mappers/mapperutil.kt
dayakaral
851,617,558
false
{"Kotlin": 28876}
package com.example.data.mappers import com.example.data.db.entities.DefinitionEntity import com.example.data.db.entities.LicenseEntity import com.example.data.db.entities.MeaningEntity import com.example.data.db.entities.PhoneticEntity import com.example.data.db.entities.WordEntity import com.example.domain.entities.Definition import com.example.domain.entities.License import com.example.domain.entities.Meaning import com.example.domain.entities.Phonetic import com.example.domain.entities.Word import retrofit2.Retrofit fun WordEntity.toDomainModel(): Word { return Word( word = word, phonetics = phonetics.map { it.toDomainModel() }, meanings = meanings.map { it.toDomainModel() }, license = license?.toDomainModel(), sourceUrls = sourceUrls ) } fun PhoneticEntity.toDomainModel(): Phonetic { return Phonetic( text = text, audio = audio, sourceUrl = sourceUrl, license = license?.toDomainModel() ) } fun MeaningEntity.toDomainModel(): Meaning { return Meaning( partOfSpeech = partOfSpeech, definitions = definitions.map { it.toDomainModel() }, synonyms = synonyms, antonyms = antonyms ) } fun DefinitionEntity.toDomainModel(): Definition { return Definition( definition = definition, synonyms = synonyms, antonyms = antonyms, example = example ) } fun LicenseEntity.toDomainModel(): License { return License( name = name, url = url ) } fun Word.toEntityModel(): WordEntity { return WordEntity( word = word, phonetics = phonetics.map { it.toEntityModel() }, meanings = meanings.map { it.toEntityModel() }, license = license?.toEntityModel(), sourceUrls = sourceUrls ) } fun Phonetic.toEntityModel(): PhoneticEntity { return PhoneticEntity( text = text, audio = audio, sourceUrl = sourceUrl, license = license?.toEntityModel() ) } fun Meaning.toEntityModel(): MeaningEntity { return MeaningEntity( partOfSpeech = partOfSpeech, definitions = definitions.map { it.toEntityModel() }, synonyms = synonyms, antonyms = antonyms ) } fun Definition.toEntityModel(): DefinitionEntity { return DefinitionEntity( definition = definition, synonyms = synonyms, antonyms = antonyms, example = example ) } fun License.toEntityModel(): LicenseEntity { return LicenseEntity( name = name, url = url ) }
0
Kotlin
0
0
f03d1ad299c74f7b9e32659204864a2598abb6cf
2,585
Dayakar_Dictionary
MIT License
src/test/resources/test-compile-data/jvm/kotlin-web-site/basic-syntax/5ec261721162729866abc1e8f7293ef4.14.kt
AlexanderPrendota
219,478,945
false
null
//sampleStart fun maxOf(a: Int, b: Int): Int { if (a > b) { return a } else { return b } } //sampleEnd fun main() { println("max of 0 and 42 is ${maxOf(0, 42)}") }
14
Kotlin
47
89
95326951087813b6dea8b5ef4234fc06f252bd80
196
kotlin-compiler-server
Apache License 2.0
Android_Service_2024/app/src/main/java/com/example/androidservicelearnings/job/jobsecheduler/MyJobService.kt
rahulgothwal5
767,463,333
false
{"Kotlin": 70836}
package com.example.androidservicelearnings.job.jobsecheduler import android.app.job.JobParameters import android.app.job.JobService import android.util.Log import com.example.androidservicelearnings.MainActivity import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class MyJobService:JobService() { lateinit var job: Job override fun onStartJob(params: JobParameters?): Boolean { Log.d(MainActivity.TAG, Thread.currentThread().id.toString()) job = GlobalScope.launch { withContext(Dispatchers.IO) { for (i in 1..10) { delay(1000) Log.d(MainActivity.TAG, "Service is running $i") } } stopSelf() } return true; } override fun onStopJob(params: JobParameters?): Boolean { job.cancel() Log.d(MainActivity.TAG, "Service stopped") return false; } }
0
Kotlin
0
0
ee9344488239b66bf4aed2d07afefe329bb76f23
1,086
Android-Services-2024
MIT License
app/src/main/java/com/devop/aashish/android/vo/Request.kt
aashish-aadarsh
228,884,203
false
null
/* * Copyright(c) 2019 Aashish Aadarsh * * 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. * * @author : Aashish Aadarsh * Follow Me: "https://github.com/aashish-aadarsh" */ package com.devop.aashish.android.vo import com.devop.aashish.android.utility.contract.ResponseHandler data class Request<T>( var requestEndPoint: String, var requestBaseURL: String, var requestMethod: HttpMethod, var requestBody: Any? = null, var requestParam: Map<String, Any>? = null, var requestHeader: Map<String, Any>? = null, var requestPathParam: Map<String, Any>? = null, var requestMetaData: String? = null, var responseHandler: ResponseHandler<T>? = null, var responseClass: Class<T>? = null )
0
Kotlin
0
0
e3e8a06368a8eca59c7c99d2da277c5ce50107c2
1,270
android-sync-lib
Apache License 2.0
imagekit/src/main/java/com/gobinda/currency/converter/imagekit/CountryImageProvider.kt
gobinda1547
745,860,953
false
{"Kotlin": 54684}
package com.gobinda.currency.converter.imagekit import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory object CountryImageProvider { fun getBitmap(context: Context, countryCode: String): Bitmap { try { val validFileName = countryCode.lowercase().substring(0, 2) + ".png" val inputStream = context.assets.open(validFileName) val bitmap = BitmapFactory.decodeStream(inputStream) inputStream.close() return bitmap } catch (e: Exception) { e.printStackTrace() } val validFileName = "not_found.png" val inputStream = context.assets.open(validFileName) val bitmap = BitmapFactory.decodeStream(inputStream) inputStream.close() return bitmap } }
0
Kotlin
0
0
144ed0a1b0c9464a31e778d41e1ca21905779045
829
Currency-Converter-Android-App
MIT License
konversation-plugin/src/main/kotlin/org/rewedigital/dialog/utils/KonversationExtensions.kt
CTeyson
220,455,569
true
{"Kotlin": 99215}
package org.rewedigital.dialog.utils import org.rewedigital.dialog.handler.DialogflowHandler import org.rewedigital.dialog.handler.DialogflowResponseBuilder import org.rewedigital.dialog.model.google.GoogleSimpleResponse import org.rewedigital.dialog.model.google.RichResponse import org.rewedigital.konversation.Environment import org.rewedigital.konversation.Konversation import org.rewedigital.konversation.Output fun DialogflowResponseBuilder.withGoogleSimpleResponse(konversation: Konversation) : DialogflowResponseBuilder = apply { withGoogleSimpleResponse(konversation.createOutput()) } fun RichResponse.withSimpleResponse(konversation: Konversation) : RichResponse = apply { withSimpleResponse(konversation.createOutput()) } fun DialogflowResponseBuilder.withGoogleSimpleResponse(output: Output) : DialogflowResponseBuilder = apply { withGoogleSimpleResponse(GoogleSimpleResponse(ssml = output.ssml, displayText = output.displayText)) } fun RichResponse.withSimpleResponse(output: Output) : RichResponse = apply { withSimpleResponse(ssml = output.ssml, displayText = output.displayText) } fun DialogflowHandler.loadKonversation(name: String) = Konversation(name, Environment("google", languageCode.orEmpty())) fun DialogflowResponseBuilder.withGoogleSuggestions(output: Output) : DialogflowResponseBuilder = apply { withGoogleSuggestions(*output.suggestions.toTypedArray()) } fun DialogflowResponseBuilder.withGoogleSuggestions(konversation: Konversation) : DialogflowResponseBuilder = apply { withGoogleSuggestions(konversation.createOutput()) } fun DialogflowResponseBuilder.withGoogleReprompts(konversation: Konversation) : DialogflowResponseBuilder = apply { withGoogleReprompts(konversation.createOutput()) } fun DialogflowResponseBuilder.withGoogleReprompts(output: Output) : DialogflowResponseBuilder = apply { withGoogleReprompts(*output.reprompts.entries.sortedBy { it.key }.map { it.value }.toTypedArray()) }
0
null
0
0
4077ceab3ae2b2baa98a728784f31daa75f381d0
1,972
dialog
MIT License
src/test/kotlin/no/fdk/concept_catalog/contract/SearchConcepts.kt
Informasjonsforvaltning
366,717,204
false
null
package no.fdk.concept_catalog.contract import com.fasterxml.jackson.module.kotlin.readValue import no.fdk.concept_catalog.configuration.JacksonConfigurer import no.fdk.concept_catalog.model.Begrep import no.fdk.concept_catalog.model.JsonSearchOperation import no.fdk.concept_catalog.utils.ApiTestContext import no.fdk.concept_catalog.utils.BEGREP_1 import no.fdk.concept_catalog.utils.BEGREP_2 import no.fdk.concept_catalog.utils.authorizedRequest import no.fdk.concept_catalog.utils.jwk.Access import no.fdk.concept_catalog.utils.jwk.JwtToken import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import org.springframework.boot.test.context.SpringBootTest import org.springframework.http.HttpMethod import org.springframework.http.HttpStatus import org.springframework.test.context.ContextConfiguration import kotlin.test.assertEquals private val mapper = JacksonConfigurer().objectMapper() @TestInstance(TestInstance.Lifecycle.PER_CLASS) @SpringBootTest( properties = ["spring.profiles.active=contract-test"], webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT ) @ContextConfiguration(initializers = [ApiTestContext.Initializer::class]) @Tag("contract") class SearchConcepts : ApiTestContext() { @Test fun `Unauthorized when access token is not included`() { val rsp = authorizedRequest("/begreper/search?orgNummer=123456789", port, mapper.writeValueAsString(JsonSearchOperation("test")), null, HttpMethod.POST) assertEquals(HttpStatus.UNAUTHORIZED.value(), rsp["status"]) } @Test fun `Forbidden for wrong orgnr`() { val rsp = authorizedRequest( "/begreper/search?orgNummer=999888777", port, mapper.writeValueAsString(JsonSearchOperation("test")), JwtToken(Access.ORG_READ).toString(), HttpMethod.POST ) assertEquals(HttpStatus.FORBIDDEN.value(), rsp["status"]) } @Test fun `Ok for read access`() { val rsp = authorizedRequest( "/begreper/search?orgNummer=123456789", port, mapper.writeValueAsString(JsonSearchOperation("test")), JwtToken(Access.ORG_READ).toString(), HttpMethod.POST ) assertEquals(HttpStatus.OK.value(), rsp["status"]) val result: List<Begrep> = mapper.readValue(rsp["body"] as String) assertEquals(listOf(), result) } @Test fun `Empty query returns bad request`() { val rsp = authorizedRequest( "/begreper/search?orgNummer=123456789", port, mapper.writeValueAsString(JsonSearchOperation("")), JwtToken(Access.ORG_WRITE).toString(), HttpMethod.POST ) assertEquals(HttpStatus.BAD_REQUEST.value(), rsp["status"]) } @Test fun `Query returns correct results`() { val rsp = authorizedRequest( "/begreper/search?orgNummer=123456789", port, mapper.writeValueAsString(JsonSearchOperation("Begrep")), JwtToken(Access.ORG_WRITE).toString(), HttpMethod.POST ) assertEquals(HttpStatus.OK.value(), rsp["status"]) val result: List<Begrep> = mapper.readValue(rsp["body"] as String) assertEquals(listOf(BEGREP_1, BEGREP_2), result) } @Test fun `Query returns no results`() { val rsp = authorizedRequest( "/begreper/search?orgNummer=123456789", port, mapper.writeValueAsString(JsonSearchOperation("zxcvbnm")), JwtToken(Access.ORG_WRITE).toString(), HttpMethod.POST ) assertEquals(HttpStatus.OK.value(), rsp["status"]) val result: List<Begrep> = mapper.readValue(rsp["body"] as String) assertEquals(listOf(), result) } }
4
Kotlin
0
0
d9cf806429288841490c41aced349ac521fbcdfa
3,755
concept-catalog
Apache License 2.0
src/main/kotlin/docker/DockerService.kt
blackducksoftware
190,764,009
false
null
package docker import com.synopsys.integration.exception.IntegrationException import com.synopsys.integration.log.Slf4jIntLogger import convertToString import org.apache.commons.lang3.StringUtils import org.slf4j.LoggerFactory import java.io.File import java.io.InputStream import java.util.concurrent.TimeUnit // TODO: Make DockerService more generic class DockerService { private val logger = Slf4jIntLogger(LoggerFactory.getLogger(javaClass)) fun installAndStartArtifactory(version: String, artifactoryPort: String): String { val artifactoryInstallProcess = installArtifactory(version) artifactoryInstallProcess.waitFor(5, TimeUnit.MINUTES) if (artifactoryInstallProcess.exitValue() != 0) { throw IntegrationException("Failed to install artifactory. Docker returned an exit code of ${artifactoryInstallProcess.exitValue()}") } val startArtifactoryProcess = initializeArtifactory(version, artifactoryPort, false) startArtifactoryProcess.waitFor(3, TimeUnit.MINUTES) if (startArtifactoryProcess.exitValue() != 0) { throw IntegrationException("Failed to start artifactory. Docker returned an exit code of ${startArtifactoryProcess.exitValue()}") } return startArtifactoryProcess.inputStream.convertToString().trim() } fun installArtifactory(version: String): Process { return runCommand("docker", "pull", "docker.bintray.io/jfrog/artifactory-pro:$version") } fun initializeArtifactory(version: String, artifactoryPort: String, inheritIO: Boolean = true): Process { return runCommand("docker", "run", "--name", "artifactory-automation-$version", "-d", "-p", "$artifactoryPort:$artifactoryPort", "docker.bintray.io/jfrog/artifactory-pro:$version", inheritIO = inheritIO) } fun startArtifactory(containerHash: String): Process { return runCommand("docker", "start", containerHash) } fun stopArtifactory(containerHash: String): Process { return runCommand("docker", "stop", containerHash) } fun getArtifactoryLogs(containerHash: String): InputStream { val process = runCommand("docker", "logs", containerHash) process.waitFor() return process.inputStream } fun uploadFile(containerHash: String, file: File, location: String): Process { return runCommand("docker", "cp", file.canonicalPath, "$containerHash:$location") } fun downloadFile(containerHash: String, outputFile: File, location: String): Process { return runCommand("docker", "cp", "$containerHash:$location", outputFile.canonicalPath) } fun chownFile(containerHash: String, owner: String, group: String, filePath: String): Process { return runCommand("docker", "exec", "--user=root", containerHash, "chown", "-R", "$owner:$group", filePath) } fun chmodFile(containerHash: String, permissions: String, filePath: String): Process { return runCommand("docker", "exec", "--user=root", containerHash, "chmod", "-R", permissions, filePath) } private fun runCommand(vararg command: String, inheritIO: Boolean = true): Process { logger.info("Running command: " + StringUtils.join(command, " ")) val processBuilder = ProcessBuilder(*command) if (inheritIO) { processBuilder.inheritIO() } return processBuilder.start() } }
0
Kotlin
0
0
1cd99710b9887b36869e3835a44922470a09d4f9
3,411
blackduck-artifactory-automation
Apache License 2.0
app/src/main/java/de/niklasbednarczyk/nbweather/MainViewModel.kt
NiklasBednarczyk
529,683,941
false
null
package de.niklasbednarczyk.nbweather import dagger.hilt.android.lifecycle.HiltViewModel import de.niklasbednarczyk.nbweather.core.common.string.NBString import de.niklasbednarczyk.nbweather.core.data.localremote.models.resource.NBResource import de.niklasbednarczyk.nbweather.core.data.localremote.models.resource.NBResource.Companion.transformToList import de.niklasbednarczyk.nbweather.core.ui.R import de.niklasbednarczyk.nbweather.core.ui.fragment.viewmodel.NBViewModel import de.niklasbednarczyk.nbweather.core.ui.icons.NBIcons import de.niklasbednarczyk.nbweather.core.ui.navigation.destination.NBTopLevelDestinations import de.niklasbednarczyk.nbweather.data.geocoding.models.LocationModelData import de.niklasbednarczyk.nbweather.data.geocoding.repositories.GeocodingRepository import de.niklasbednarczyk.nbweather.data.settings.repositories.SettingsAppearanceRepository import de.niklasbednarczyk.nbweather.data.settings.repositories.SettingsDataRepository import de.niklasbednarczyk.nbweather.navigation.NBNavigationDrawerItem import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flatMapLatest import javax.inject.Inject @HiltViewModel class MainViewModel @Inject constructor( private val geocodingRepository: GeocodingRepository, private val settingsAppearanceRepository: SettingsAppearanceRepository, settingsDataRepository: SettingsDataRepository ) : NBViewModel<MainUiState>(MainUiState()) { companion object { private val headline = NBNavigationDrawerItem.Headline( label = NBString.Resource(de.niklasbednarczyk.nbweather.R.string.app_name) ) private val settingsItem = NBNavigationDrawerItem.Item.Other( label = NBString.Resource(R.string.screen_settings_overview_title), icon = NBIcons.Settings, topLevelDestination = NBTopLevelDestinations.Settings ) private val aboutItem = NBNavigationDrawerItem.Item.Other( label = NBString.Resource(R.string.screen_about_overview_title), icon = NBIcons.About, topLevelDestination = NBTopLevelDestinations.About ) } private val drawerItemsFlow: Flow<List<NBNavigationDrawerItem>> = settingsDataRepository.getData().flatMapLatest { data -> val language = data.language NBResource.combineResourceFlows( geocodingRepository.getVisitedLocations(language), geocodingRepository.getCurrentLocation(language) ) { visitedLocations, currentLocation -> val items = mutableListOf<NBNavigationDrawerItem>() items.add(headline) val locationItems = visitedLocations?.map { visitedLocation -> val sameLatitude = visitedLocation.latitude == currentLocation?.latitude val sameLongitude = visitedLocation.longitude == currentLocation?.longitude val selected = sameLatitude && sameLongitude NBNavigationDrawerItem.Item.Location( label = visitedLocation.localizedNameAndCountry, icon = NBIcons.Location, selected = selected, location = visitedLocation ) } ?: emptyList() items.addAll(locationItems) items.add(NBNavigationDrawerItem.Divider) items.add(settingsItem) items.add(aboutItem) items }.transformToList() } init { collectFlow( { drawerItemsFlow }, { oldUiState, output -> oldUiState.copy(drawerItems = output) } ) collectFlow( { geocodingRepository.getIsInitialCurrentLocationSet() }, { oldUiState, output -> oldUiState.copy(isInitialCurrentLocationSetResource = output) } ) collectFlow( { settingsAppearanceRepository.getData() }, { oldUiState, output -> oldUiState.copy(settingsAppearance = output) } ) } fun setCurrentLocation(latitude: Double, longitude: Double) { launchSuspend { geocodingRepository.insertOrUpdateCurrentLocation( latitude = latitude, longitude = longitude ) } } }
22
Kotlin
0
0
b2d94e99336b908a48e784febda56a4750039cb2
4,384
NBWeather
MIT License
src/vi/teamlanhlung/src/eu/kanade/tachiyomi/extension/vi/teamlanhlung/TeamLanhLung.kt
komikku-app
720,497,299
false
{"Kotlin": 6775539, "JavaScript": 2160}
package eu.kanade.tachiyomi.extension.vi.teamlanhlung import eu.kanade.tachiyomi.multisrc.a3manga.A3Manga class TeamLanhLung : A3Manga("Team Lạnh Lùng", "https://teamlanhlungday.vip", "vi")
22
Kotlin
8
97
7fc1d11ee314376fe0daa87755a7590a03bc11c0
192
komikku-extensions
Apache License 2.0
seeker/src/test/java/dev/vivvvek/seeker/SeekerUtilsTest.kt
2307vivek
595,118,282
false
null
/* * Copyright 2023 Vivek Singh * * 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 dev.vivvvek.seeker import androidx.compose.ui.graphics.Color import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test class SeekerUtilsTest { private lateinit var state: SeekerState private lateinit var segments: List<Segment> @Before fun setup() { state = SeekerState() segments = listOf( Segment(name = "Intro", start = 0f), Segment(name = "Talk 1", start = 0.5f), Segment(name = "Talk 2", start = 0.8f), ) } @Test fun check_correctPixelValuesForSegments() { val segmentPxs = segmentToPxValues(segments, 0f..1f, 100f) val expected = listOf( SegmentPxs(name = "Intro", startPx = 0f, endPx = 50f, color = Color.Unspecified), SegmentPxs(name = "Talk 1", startPx = 50f, endPx = 80f, color = Color.Unspecified), SegmentPxs(name = "Talk 2", startPx = 80f, endPx = 100f, color = Color.Unspecified) ) assertEquals(expected, segmentPxs) } }
1
Kotlin
4
98
17f639093eca623930c75cd69ca44376e5116e62
1,632
Seeker
Apache License 2.0
projects/tier-to-delius/src/main/kotlin/uk/gov/justice/digital/hmpps/controller/model/PersonDetails.kt
ministryofjustice
500,855,647
false
{"Kotlin": 4354937, "HTML": 70066, "D2": 44286, "Ruby": 25921, "Shell": 19356, "SCSS": 6370, "HCL": 2712, "Dockerfile": 2447, "JavaScript": 1372, "Python": 268}
package uk.gov.justice.digital.hmpps.controller.model data class PersonDetails( val crn: String, val name: Name ) data class Name( val forenames: String, val surname: String )
4
Kotlin
0
2
bafb32470fd72f96026e8e8c53a636778c6abacf
194
hmpps-probation-integration-services
MIT License
app/src/main/kotlin/com/contentful/tea/kotlin/content/rest/Converter.kt
contentful
132,734,874
false
null
package com.contentful.tea.kotlin.content.rest import com.contentful.java.cda.CDAAsset import com.contentful.java.cda.CDAEntry import com.contentful.java.cda.image.ImageOption import com.contentful.java.cda.image.ImageOption.formatOf import com.contentful.java.cda.image.ImageOption.https import com.contentful.tea.kotlin.content.Category import com.contentful.tea.kotlin.content.Course import com.contentful.tea.kotlin.content.Layout import com.contentful.tea.kotlin.content.LayoutModule import com.contentful.tea.kotlin.content.Lesson import com.contentful.tea.kotlin.content.LessonModule fun Course.Companion.fromRestEntry(entry: CDAEntry, locale: String): Course = Course( entry.getField<String?>(locale, "title").orEmpty(), entry.getField<String?>(locale, "slug").orEmpty(), try { entry.getField<CDAAsset?>(locale, "image") ?.urlForImageWith(ImageOption.https(), ImageOption.formatOf(ImageOption.Format.webp)) .orEmpty() } catch (_: Throwable) { "" }, entry.getField<String?>(locale, "shortDescription").orEmpty(), entry.getField<String?>(locale, "description").orEmpty(), entry.getField<Double?>(locale, "duration").or(0.0).toInt(), entry.getField<String?>(locale, "skillLevel").orEmpty(), entry.getField<List<CDAEntry>?>(locale, "lessons") .orEmpty() .map { Lesson.fromRestEntry(it, locale) }, entry.getField<List<CDAEntry>>(locale, "categories") .orEmpty() .map { Category.fromRestEntry(it, locale) } ) private fun Double?.or(default: Double): Double = this ?: default fun Category.Companion.fromRestEntry(entry: CDAEntry, locale: String) = Category( entry.id(), entry.getField<String?>(locale, "title").orEmpty(), entry.getField<String?>(locale, "slug").orEmpty() ) fun Layout.Companion.fromRestEntry(entry: CDAEntry, locale: String) = Layout( entry.getField<String?>(locale, "title").orEmpty(), entry.getField<String?>(locale, "slug").orEmpty(), entry.getField<List<CDAEntry>?>(locale, "contentModules").orEmpty().map { findLayoutModule(it, locale) } ) fun findLayoutModule(entry: CDAEntry, locale: String): LayoutModule = when (entry.contentType().id()) { "layoutHighlightedCourse" -> LayoutModule.HightlightedCourse.fromRestEntry(entry, locale) "layoutCopy" -> LayoutModule.Copy.fromRestEntry(entry, locale) "layoutHeroImage" -> LayoutModule.HeroImage.fromRestEntry(entry, locale) else -> LayoutModule.Copy( "<layout module type not found>", "## layout module type not found", "", "", "", "" ) } fun LayoutModule.HightlightedCourse.Companion.fromRestEntry(entry: CDAEntry, locale: String) = LayoutModule.HightlightedCourse( entry.getField<String?>(locale, "title").orEmpty(), if (entry.getField<CDAEntry?>(locale, "course") == null) { Course( "", "", "", "", "", 0, "", emptyList(), emptyList() ) } else { Course.fromRestEntry(entry.getField<CDAEntry>(locale, "course"), locale) } ) fun LayoutModule.HeroImage.Companion.fromRestEntry(entry: CDAEntry, locale: String) = LayoutModule.HeroImage( entry.getField<String?>(locale, "title").orEmpty(), entry.getField<String?>(locale, "headline").orEmpty(), try { entry.getField<CDAAsset?>(locale, "backgroundImage") ?.urlForImageWith(https(), formatOf(ImageOption.Format.webp)).orEmpty() } catch (_: Throwable) { "" } ) fun LayoutModule.Copy.Companion.fromRestEntry(entry: CDAEntry, locale: String) = LayoutModule.Copy( entry.getField<String?>(locale, "title").orEmpty(), entry.getField<String?>(locale, "headline").orEmpty(), entry.getField<String?>(locale, "copy").orEmpty(), entry.getField<String?>(locale, "ctaTitle").orEmpty(), entry.getField<String?>(locale, "ctaLink").orEmpty(), entry.getField<String?>(locale, "visualStyle").orEmpty() ) fun Lesson.Companion.fromRestEntry(entry: CDAEntry, locale: String) = Lesson( entry.getField<String?>(locale, "title").orEmpty(), entry.getField<String?>(locale, "slug").orEmpty(), entry.getField<List<CDAEntry>?>(locale, "modules") .orEmpty() .map { findLessonModule(it, locale) } ) fun findLessonModule(entry: CDAEntry, locale: String): LessonModule = when (entry.contentType().id()) { "lessonCodeSnippets" -> LessonModule.CodeSnippet.fromRestEntry(entry, locale) "lessonImage" -> LessonModule.Image.fromRestEntry(entry, locale) "lessonCopy" -> LessonModule.Copy.fromRestEntry(entry, locale) else -> LessonModule.Copy( "<lesson module type not found>", "## lesson module type not found" ) } fun LessonModule.CodeSnippet.Companion.fromRestEntry(entry: CDAEntry, locale: String) = LessonModule.CodeSnippet( entry.getField<String?>(locale, "title").orEmpty(), entry.getField<String?>(locale, "curl").orEmpty(), entry.getField<String?>(locale, "dotNet").orEmpty(), entry.getField<String?>(locale, "javascript").orEmpty(), entry.getField<String?>(locale, "java").orEmpty(), entry.getField<String?>(locale, "javaAndroid").orEmpty(), entry.getField<String?>(locale, "php").orEmpty(), entry.getField<String?>(locale, "python").orEmpty(), entry.getField<String?>(locale, "ruby").orEmpty(), entry.getField<String?>(locale, "swift").orEmpty() ) fun LessonModule.Image.Companion.fromRestEntry(entry: CDAEntry, locale: String) = LessonModule.Image( entry.getField<String?>(locale, "title").orEmpty(), entry.getField<String?>(locale, "caption").orEmpty(), try { entry.getField<CDAAsset?>(locale, "image") ?.urlForImageWith( ImageOption.https(), ImageOption.formatOf(ImageOption.Format.webp) ).orEmpty() } catch (_: Throwable) { "" } ) fun LessonModule.Copy.Companion.fromRestEntry(entry: CDAEntry, locale: String) = LessonModule.Copy( entry.getField<String?>(locale, "title").orEmpty(), entry.getField<String?>(locale, "copy").orEmpty() )
1
Kotlin
24
14
e92edf20018b9a149100abb36286a226906e5c2d
6,404
the-example-app.kotlin
Apache License 2.0
app/src/main/java/com/aulbachscheuerpflug/mobileVrCamera/uiComponents/TakePhotoButton.kt
MobileVRCamera
669,464,993
false
{"Kotlin": 205215, "Java": 1153}
package com.aulbachscheuerpflug.mobileVrCamera.uiComponents import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.LinearOutSlowInEasing import androidx.compose.animation.core.TweenSpec import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredSize import androidx.compose.foundation.layout.size import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.rotate import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.aulbachscheuerpflug.mobileVrCamera.Duration import com.aulbachscheuerpflug.mobileVrCamera.GuidedModeSteps import com.aulbachscheuerpflug.mobileVrCamera.INFO_CONTENT_DESC import com.aulbachscheuerpflug.mobileVrCamera.MAXIMUM_QUALITY_COMPRESSION import com.aulbachscheuerpflug.mobileVrCamera.MINIMUM_QUALITY_COMPRESSION import com.aulbachscheuerpflug.mobileVrCamera.MainViewModel import com.aulbachscheuerpflug.mobileVrCamera.R import com.aulbachscheuerpflug.mobileVrCamera.TAKE_PHOTO_GUIDE_INFO_DESC import com.aulbachscheuerpflug.mobileVrCamera.TAKE_PHOTO_INFO_DESC import com.aulbachscheuerpflug.mobileVrCamera.bluetooth.BluetoothUiState import com.aulbachscheuerpflug.mobileVrCamera.uiAssets.Black import com.aulbachscheuerpflug.mobileVrCamera.uiAssets.Grey import com.aulbachscheuerpflug.mobileVrCamera.uiAssets.RoundShape import com.aulbachscheuerpflug.mobileVrCamera.uiAssets.White import com.aulbachscheuerpflug.mobileVrCamera.utils.playCustomSound import com.aulbachscheuerpflug.mobileVrCamera.utils.playSystemSound import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlin.math.roundToInt @Composable fun TakePhotoButton( mainViewModel: MainViewModel, bluetoothState: BluetoothUiState, onTakePhotoClicked: () -> Unit, rotation: Int, ) { val context = LocalContext.current val configuration = LocalConfiguration.current val coroutineScope = rememberCoroutineScope() val animatedRotationDegrees by animateFloatAsState( targetValue = rotation.toFloat(), animationSpec = TweenSpec(durationMillis = 500, easing = LinearOutSlowInEasing) ) Surface( color = Color.Transparent, shape = RectangleShape, modifier = Modifier .size((configuration.screenWidthDp / 3).dp) ) { Surface( color = if (mainViewModel.isTakingStereoImage) Grey else White, shape = RoundShape, modifier = Modifier .size(128.dp) .padding(all = 5.dp) .border(1.dp, Black, RoundShape) ) { IconButton( onClick = { playSystemSound(context) if (!mainViewModel.showInfoPopUps) { if (mainViewModel.countdown == null) { val delaySeconds = when (mainViewModel.selectedDuration) { Duration.Zero -> 0 Duration.One -> 1 Duration.Three -> 3 Duration.Five -> 5 Duration.Ten -> 10 Duration.Fifteen -> 15 } if (delaySeconds > 0) { val shouldStop = false mainViewModel.countdownJob = coroutineScope.launch { for (i in delaySeconds downTo 1) { if (shouldStop) break mainViewModel.countdown = i delay(1000) } if (!shouldStop) { mainViewModel.countdown = null onTakePhotoClicked() playCustomSound(context, R.raw.phototaken) mainViewModel.isTakingStereoImage = true } } } else { onTakePhotoClicked() mainViewModel.isTakingStereoImage = true playCustomSound(context, R.raw.phototaken) } } else { mainViewModel.countdownJob?.cancel() mainViewModel.countdownJob = null mainViewModel.countdown = null } } else { mainViewModel.titleText = "Take Photo:" mainViewModel.descriptionText = if (mainViewModel.guidedModeSteps == null) TAKE_PHOTO_INFO_DESC else TAKE_PHOTO_GUIDE_INFO_DESC mainViewModel.showDescPopUp = true } }, modifier = Modifier .padding(8.dp) .onGloballyPositioned { layoutCoordinates -> val position = layoutCoordinates.localToRoot(Offset(0f, 0f)) val size = layoutCoordinates.size val centerX = position.x + size.width / 2 val centerY = position.y + size.height / 2 mainViewModel.takePhotoButtonPosition = IntOffset(centerX.roundToInt(), centerY.roundToInt()) } .rotate(animatedRotationDegrees), enabled = (mainViewModel.guidedModeSteps == null || mainViewModel.guidedModeSteps == GuidedModeSteps.PHOTO || (bluetoothState.transferProgress in MINIMUM_QUALITY_COMPRESSION until MAXIMUM_QUALITY_COMPRESSION-1)) && !mainViewModel.isTakingStereoImage ) { Box(contentAlignment = Alignment.Center, modifier = Modifier.size(65.dp)) { if (mainViewModel.countdown == null) { Icon( painter = painterResource(id = R.drawable.baseline_camera_alt_48), contentDescription = "TakePhoto-Button", tint = Black, modifier = Modifier.requiredSize(65.dp) ) } else { Text( text = mainViewModel.countdown.toString(), fontSize = 36.sp, textAlign = TextAlign.Center, modifier = Modifier.align(Alignment.Center) ) } } } } AnimatedVisibility( visible = mainViewModel.showInfoPopUps, enter = fadeIn(), exit = fadeOut(), ) { Icon( painter = painterResource(id = R.drawable.baseline_info_24), modifier = Modifier .requiredSize(30.dp) .offset(45.dp, 40.dp) .border(1.dp, Black, RoundShape) .background(Black, shape = RoundShape) .rotate(animatedRotationDegrees), contentDescription = INFO_CONTENT_DESC, tint = if (mainViewModel.descriptionText == TAKE_PHOTO_INFO_DESC && mainViewModel.showDescPopUp) Grey else White, ) } } } @Preview @Composable fun TakePhotoButtonPreview() { val mainViewModelDummy = MainViewModel() val bluetoothUiStateDummy = BluetoothUiState( scannedDevices = listOf(), pairedDevices = listOf(), isConnected = false, isConnecting = false, errorMessage = null, transferProgress = 50, isScanning = false, ) TakePhotoButton( mainViewModel = mainViewModelDummy, bluetoothState = bluetoothUiStateDummy, onTakePhotoClicked = {}, rotation = 0, ) }
0
Kotlin
0
1
bd57f48091f4d69d151ae808ba04939e483fe738
9,275
MobileVRCamera
MIT License
app/src/main/java/com/lomamo/lomamo3/adapters/MovieAdapter.kt
L0pesi
589,295,448
false
null
package com.lomamo.lomamo3.adapters import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.lomamo.lomamo3.R import com.lomamo.lomamo3.database.models.MovieData import com.lomamo.lomamo3.models.Movie import kotlinx.android.synthetic.main.movie_item.view.* class MovieAdapter( private val movies : List<MovieData>, private val listener: OnMovieClickListener ) : RecyclerView.Adapter<MovieAdapter.MovieViewHolder>() { class MovieViewHolder(view: View) : RecyclerView.ViewHolder(view){ private val IMAGE_BASE = "https://image.tmdb.org/t/p/w500/" fun bindMovie(movie : MovieData, listener: OnMovieClickListener){ itemView.movie_title.text = movie.title itemView.movie_release_date.text = movie.release Glide.with(itemView).load(IMAGE_BASE + movie.poster).into(itemView.movie_poster) itemView.setOnClickListener { listener.onMovieClick(movie) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MovieViewHolder { return MovieViewHolder( LayoutInflater.from(parent.context).inflate(R.layout.movie_item, parent, false) ) } override fun getItemCount(): Int = movies.size override fun onBindViewHolder(holder: MovieViewHolder, position: Int) { holder.bindMovie(movies[position],listener) } interface OnMovieClickListener { fun onMovieClick(movie: MovieData) } }
0
Kotlin
0
0
536f75b62c486b6110f4b48794d5aaba466dad09
1,597
lomamo3
The Unlicense
src/main/kotlin/tokyo/pmmp/test/Core.kt
fuyutsuki
121,720,904
false
null
package tokyo.pmmp.test import cn.nukkit.plugin.PluginBase import cn.nukkit.utils.TextFormat class Core : PluginBase() { override fun onEnable() { logger.info(TextFormat.GREEN.toString() + "ことりん(・8・)") } override fun onDisable() { logger.info(TextFormat.RED.toString() + "さよならちゅん(・8・)") } }
0
Kotlin
1
0
c0bf58d18ef7fcd36d3b3728ffb871598ccae88a
326
TestPlugin-Kotlin
MIT License
src/commonMain/kotlin/ru/spbstu/wheels/collections/IAbstractMutableSet.kt
vorpal-research
185,828,983
false
{"Kotlin": 245655}
package ru.spbstu.wheels.collections interface IAbstractMutableSet<T>: IAbstractSet<T>, MutableSet<T>, IAbstractMutableCollection<T> { override fun addAll(elements: Collection<T>): Boolean = super.addAll(elements) override fun clear() = super.clear() override fun removeAll(elements: Collection<T>): Boolean = super.removeAll(elements) override fun retainAll(elements: Collection<T>): Boolean = super.retainAll(elements) override fun equals(other: Any?): Boolean override fun hashCode(): Int override fun toString(): String abstract class Impl<T> : IAbstractMutableSet<T> { override fun equals(other: Any?): Boolean = setEquals(other) override fun hashCode(): Int = setHashCode() override fun toString(): String = setToString() } }
0
Kotlin
2
1
389f9c290d496aae3d4f5eaa2a0d4f4863f281c2
795
kotlin-wheels
MIT License
src/jsMain/kotlin/baaahs/app/ui/settings/MainSettingsPanel.kt
baaahs
174,897,412
false
{"Kotlin": 4817815, "C": 1529197, "C++": 661363, "GLSL": 412779, "JavaScript": 61944, "HTML": 56277, "CMake": 30499, "CSS": 4340, "Shell": 2381, "Python": 1450}
package baaahs.app.ui.settings import baaahs.app.settings.UiSettings import baaahs.app.ui.appContext import baaahs.app.ui.dialog.DialogPanel import baaahs.ui.View import baaahs.ui.renderWrapper import baaahs.ui.typographyH6 import baaahs.ui.xComponent import mui.material.* import react.* class MainSettingsPanel( private var changeUiSettings: ((UiSettings) -> UiSettings) -> Unit ) : DialogPanel { override val title: String get() = "Main" override fun getView(): View = renderWrapper { mainSettingsPanel { attrs.changeUiSettings = changeUiSettings } } } private val MainSettingsPanelView = xComponent<MainSettingsPanelProps>("MainSettingsPanel") { props -> val appContext = useContext(appContext) val uiSettings = appContext.uiSettings val handleDarkModeChange by switchEventHandler(uiSettings) { _, checked -> props.changeUiSettings { it.copy(darkMode = checked) } } val handleRenderButtonPreviewsChange by switchEventHandler(uiSettings) { _, checked -> props.changeUiSettings { it.copy(renderButtonPreviews = checked) } } val handleUseSharedContextsChange by switchEventHandler(uiSettings) { _, checked -> props.changeUiSettings { it.copy(useSharedContexts = checked) } } val handleDeveloperModeChange by switchEventHandler(uiSettings) { _, checked -> props.changeUiSettings { it.copy(developerMode = checked) } } List { ListItem { FormControlLabel { attrs.control = buildElement { Switch { attrs.checked = uiSettings.darkMode attrs.onChange = handleDarkModeChange } } attrs.label = buildElement { typographyH6 { +"Dark Mode" } } } } } Divider {} List { ListItem { FormControlLabel { attrs.control = buildElement { Switch { attrs.checked = uiSettings.renderButtonPreviews attrs.onChange = handleRenderButtonPreviewsChange } } attrs.label = buildElement { typographyH6 { +"Render Button Previews" } } } } } Divider {} List { ListItem { FormControlLabel { attrs.control = buildElement { Switch { attrs.checked = uiSettings.developerMode attrs.onChange = handleDeveloperModeChange } } attrs.label = buildElement { typographyH6 { +"Developer Mode" } } } } } if (uiSettings.developerMode) { Divider {} List { ListItem { FormControlLabel { attrs.control = buildElement { Switch { attrs.checked = uiSettings.useSharedContexts attrs.onChange = handleUseSharedContextsChange } } attrs.label = buildElement { typographyH6 { +"Use Shared Contexts" } } } } } } } external interface MainSettingsPanelProps : Props { var changeUiSettings: ((UiSettings) -> UiSettings) -> Unit } fun RBuilder.mainSettingsPanel(handler: RHandler<MainSettingsPanelProps>) = child(MainSettingsPanelView, handler = handler)
111
Kotlin
13
40
77ad22b042fc0ac440410619dd27b468c3b3a600
3,550
sparklemotion
MIT License
proj-js/src/jsMain/kotlin/io/github/alexoooo/sample/proj/Main.kt
alexoooo
251,178,920
false
{"Kotlin": 26068, "JavaScript": 473, "HTML": 209}
package io.github.alexoooo.sample.proj import kotlinx.browser.window import react.FC import react.Props import react.create import react.dom.client.createRoot import web.html.HTMLElement fun main() { val rootHtmlElementId = "react-app" fun emptyRootElement(): HTMLElement { val rootElement = web.dom.document.getElementById(rootHtmlElementId) ?: throw IllegalStateException("'$rootHtmlElementId' element not found") while (rootElement.hasChildNodes()) { rootElement.removeChild(rootElement.firstChild!!) } return rootElement } window.onload = { val rootElement = emptyRootElement() createRoot(rootElement).render(App.create()) } } private val App = FC<Props> { +"Hello, world!" }
1
Kotlin
0
0
315a248515d9d646367fdcdd9457d4040b0d775a
784
sample-multiplatform-boot-react
Creative Commons Zero v1.0 Universal
src/main/kotlin/elements/api/ability/executor/AbilityExecutor.kt
ElementsPlugin
163,351,686
false
null
package elements.api.ability.executor import org.spongepowered.api.scheduler.Task import java.util.concurrent.TimeUnit interface AbilityExecutor { val currentTask: Task? fun executeDelay(delay: Long, unit: TimeUnit, task: (Long) -> Unit) fun executeYield(unit: TimeUnit, task: (Long) -> Unit) }
0
Kotlin
0
0
d86f268dd9e7f1799ec4ab33e6cf12d030e82de7
311
elements-api
MIT License
common/src/main/java/jp/co/soramitsu/common/interfaces/FileProvider.kt
guangxingmao
315,566,082
true
{"Kotlin": 795393}
package jp.co.soramitsu.common.interfaces import io.reactivex.Single import java.io.File interface FileProvider { fun createFileInTempStorage(fileName: String): Single<File> }
0
null
0
0
e4139ee7cbb9b48b4b622d6a3ddcf4a9e25dabca
182
fearless-Android
Apache License 2.0
multifilepicker/src/main/java/br/com/alissontfb/multifilepicker/model/ObFileView.kt
AlissonBolsoni
172,914,743
false
null
package br.com.alissontfb.multifilepicker.model import java.io.File import java.util.* class ObFileView( var root: File, var itemsInPath: ArrayList<ObFileItemView> ) class ObFileItemView( val item: File ){ var checked = false }
0
Kotlin
0
0
300ab6bfd44562779e6d190f6914c1637460bda4
271
MultiPickerLib
MIT License
maps-compose-web/src/jsMain/kotlin/com/chihsuanwu/maps/compose/web/MapApplier.kt
chihsuanwu
606,414,454
false
{"Kotlin": 170197, "HTML": 180}
package com.chihsuanwu.maps.compose.web import androidx.compose.runtime.AbstractApplier import com.chihsuanwu.maps.compose.web.jsobject.MapView internal interface MapNode { fun onAttached() {} fun onRemoved() {} fun onCleared() {} } private object MapNodeRoot : MapNode internal class MapApplier( val map: MapView, ): AbstractApplier<MapNode>(MapNodeRoot) { private val decorations = mutableListOf<MapNode>() override fun insertBottomUp(index: Int, instance: MapNode) { decorations.add(index, instance) instance.onAttached() } override fun insertTopDown(index: Int, instance: MapNode) { } override fun remove(index: Int, count: Int) { repeat(count) { decorations[index + it].onRemoved() } decorations.remove(index, count) } override fun move(from: Int, to: Int, count: Int) { decorations.move(from, to, count) } override fun onClear() { decorations.forEach { it.onCleared() } decorations.clear() } }
3
Kotlin
1
13
be5a689d2fc9ae62baf40169fae6727fd18f2ae9
1,042
google-maps-compose-web
Apache License 2.0
app/src/main/java/com/ricardojrsousa/movook/presentation/viewHolders/MovieSuggestionViewHolder.kt
RicardoRSousa
246,833,387
false
null
package com.ricardojrsousa.movook.presentation.viewHolders import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import com.ricardojrsousa.movook.R import com.ricardojrsousa.movook.core.data.Movie import com.ricardojrsousa.movook.wrappers.loadBigMoviePoster import com.ricardojrsousa.movook.wrappers.loadMoviePoster import kotlinx.android.synthetic.main.list_item_movie_suggestion.view.* /** * Created by <NAME> on 26/01/2021. */ class MovieSuggestionViewHolder : BindableViewHolder<Movie> { override lateinit var itemView: View override fun init(layoutInflater: LayoutInflater, container: ViewGroup?): BindableViewHolder<Movie> { itemView = layoutInflater.inflate(R.layout.list_item_movie_suggestion, container, false) return this } override fun bind(movie: Movie?, clickListener: ((view: ImageView?, t: Movie?) -> Unit)?) { with(itemView.movie_suggestion_cover) { loadBigMoviePoster(movie?.posterPath, cornerRadius = 10f) transitionName = movie?.id } with(itemView) { movie_suggestion_title.text = movie?.title movie_suggestion_desc.text = movie?.overview movie_suggestion_vote_view.setVote(movie?.voteAverage) movie_suggestion_year.text = movie?.getReleaseYear() } itemView.setOnClickListener { clickListener?.invoke(itemView.movie_suggestion_cover, movie) } } }
0
Kotlin
0
0
5dc6dea7b0785f95409f9b32600e702c0abefa22
1,491
Movook
The Unlicense
nanoc-kt-core/src/main/java/net/opatry/nanoc/kt/dsl/PreProcessRule.kt
opatry
327,147,143
false
null
package net.opatry.nanoc.kt.dsl import net.opatry.nanoc.kt.core.ContextProvider import net.opatry.nanoc.kt.core.Repository class PreProcessRule(private val repository: Repository, val run: PreProcessRule.() -> Unit): Rule(), ContextProvider by repository
0
Kotlin
0
0
cdf946e5ec4cff6a9653f224979e1e6442a6e9d9
256
nanoc-kt
Apache License 2.0
components/keyscreen/impl/src/main/java/com/flipperdevices/keyscreen/impl/viewmodel/KeyScreenViewModelFactory.kt
flipperdevices
288,258,832
false
null
package com.flipperdevices.keyscreen.impl.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.flipperdevices.bridge.dao.api.model.FlipperKeyPath class KeyScreenViewModelFactory( private val keyPath: FlipperKeyPath? ) : ViewModelProvider.NewInstanceFactory() { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { return KeyScreenViewModel(keyPath) as T } }
2
Kotlin
29
266
ea066973aaca66c6c5338912397d59a7c8b658d1
470
Flipper-Android-App
MIT License
oauth2/src/test/kotlin/org/scriptonbasestar/auth/oauth2/CallContextInImpl.kt
ScriptonBasestar-io
453,046,222
false
{"Kotlin": 106009}
package org.scriptonbasestar.auth.oauth2 import org.scriptonbasestar.auth.http.Headers import org.scriptonbasestar.auth.http.HttpMethod import org.scriptonbasestar.auth.http.HttpProto import org.scriptonbasestar.auth.http.Params import org.scriptonbasestar.auth.oauth2.context.CallContextIn import org.scriptonbasestar.auth.oauth2.context.CallContextOut class CallContextInImpl( override val protocol: HttpProto, override val path: String, override val method: HttpMethod, override val headers: Headers, override val queryParameters: Params, override val formParameters: Params, ) : CallContextIn { override fun <R> out(cb: () -> Unit): CallContextOut<R> { TODO("Not yet implemented") } }
0
Kotlin
0
0
99463f1f3733c6029fbcdb9bf9dc1df95eb6ee76
731
sb-authorization-server
Apache License 2.0
app/src/main/java/ru/axcheb/spotifyapi/ui/search/SearchableViewHolder.kt
axcheb
402,218,865
false
null
package ru.axcheb.spotifyapi.ui.search import androidx.recyclerview.widget.RecyclerView import androidx.viewbinding.ViewBinding import ru.axcheb.spotifyapi.data.model.SearchableEntity abstract class SearchableViewHolder<T : SearchableEntity>(binding: ViewBinding) : RecyclerView.ViewHolder(binding.root) { abstract fun bind(item: T?) }
0
Kotlin
0
0
a40c53cfe39d9e9b2ee58c09236e9b0d57e4462d
345
SpotifyBrowser
MIT License
shared/src/main/java/com/armandodarienzo/k9board/shared/model/TextComposition.kt
armyj94
783,586,202
false
{"Kotlin": 164768}
package com.armandodarienzo.k9board.shared.model class TextComposition( startIndex: Int, endIndex: Int, text: String ) { var startIndex = startIndex private set var endIndex = endIndex private set var text = text private set val length: Int = endIndex - startIndex fun setText(newText: String) { text = newText endIndex = startIndex + text.length } fun setRegion(startIndex: Int, newText: String) { this.startIndex = startIndex setText(newText) } fun reset(startIndex: Int) { this.startIndex = startIndex this.endIndex = startIndex this.text = "" } fun reset() { reset(0) } }
0
Kotlin
0
0
73c51d708b0b82aa421b9ae622d21ed2a4234014
732
K9board
The Unlicense
core/src/jvmMain/kotlin/info/laht/threekt/objects/Line.kt
jonike
199,983,331
true
{"Kotlin": 581556, "GLSL": 105344}
package info.laht.threekt.objects import info.laht.threekt.core.* import info.laht.threekt.materials.LineBasicMaterial import info.laht.threekt.math.Vector3 open class Line @JvmOverloads constructor( geometry: BufferGeometry? = null, material: LineBasicMaterial? =null ): Object3DImpl(), GeometryObject, MaterialObject { override var geometry = geometry ?: BufferGeometry() override var material = material ?: LineBasicMaterial() open fun computeLineDistances(): Line { val start = Vector3() val end = Vector3() // we assume non-indexed geometry if (geometry.index == null) { val positionAttribute = geometry.attributes.position!! val lineDistances = mutableListOf(0f) for (i in 1 until positionAttribute.count) { start.fromBufferAttribute(positionAttribute, i - 1) end.fromBufferAttribute(positionAttribute, i) lineDistances[i] = lineDistances[i - 1] lineDistances[i] += start.distanceTo(end) } geometry.addAttribute("lineDistance", FloatBufferAttribute(lineDistances.toFloatArray(), 1)) } else { println( "Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry." ) } return this } override fun raycast(raycaster: Raycaster, intersects: List<Intersection>) { TODO() } } class LineLoop( geometry: BufferGeometry, material: LineBasicMaterial ) : Line(geometry, material)
0
Kotlin
0
0
6704a3cea0e5d754304f945929bb4a257a5be6bd
1,567
three.kt
MIT License
local/src/test/kotlin/io/github/gmvalentino8/github/sample/local/error/LocalExceptionHandlerTest.kt
wasabi-muffin
462,369,263
false
{"Kotlin": 2712155, "Mustache": 4796, "Ruby": 1144, "Shell": 812}
package io.github.gmvalentino8.github.sample.local.error import io.kotest.matchers.shouldBe import io.github.gmvalentino8.github.sample.data.core.DataException import io.github.gmvalentino8.github.sample.local.core.LocalExceptionHandler import org.junit.Test class LocalExceptionHandlerTest { private val localExceptionHandler = LocalExceptionHandler() private val textException = Exception("test") @Test fun `test local exception handler`() { val exception = localExceptionHandler.handle(textException) exception shouldBe DataException.LocalException.DatabaseException(message = textException.message, cause = textException) } }
0
Kotlin
0
1
2194a2504bde08427ad461d92586497c7187fb40
669
github-sample-project
Apache License 2.0
app/src/main/java/com/harshad/projectclean/APIRequests/grievance_data_class/GrievancesListResponse.kt
TwoPointerr
455,129,436
false
{"Kotlin": 57873}
package com.harshad.projectclean.APIRequests.grievance_data_class data class GrievancesListResponse(val gri_data: List<SingleGrievanceResponse>)
1
Kotlin
1
2
c815c0cfda332dabf5f63dab5d96a4ad1c41c9e4
146
Project-Clean-Android-Application
MIT License
app/src/main/java/com/uzias/starwarsshop/core/networking/errors/RestErrorsHandler.kt
uziassantosferreira
108,789,405
false
null
package com.uzias.starwarsshop.core.networking.errors import com.uzias.starwarsshop.core.errors.ContentNotFoundError import com.uzias.starwarsshop.core.errors.UnexpectedResponseError import io.reactivex.Flowable import io.reactivex.FlowableTransformer import io.reactivex.functions.Function import org.reactivestreams.Publisher import retrofit2.HttpException class RestErrorsHandler<T> : FlowableTransformer<T, T> { override fun apply(upstream: Flowable<T>): Publisher<T> { return upstream.onErrorResumeNext(Function<Throwable, Publisher<out T>> { this.handleIfRestError(it) }) } private fun handleIfRestError(throwable: Throwable): Publisher<T> { if (notFound(throwable)) { return Flowable.error(ContentNotFoundError()) } if (otherRestError(throwable)) { return Flowable.error(UnexpectedResponseError("Undesired response for this call")) } return Flowable.error<T>(throwable) } private fun otherRestError(throwable: Throwable): Boolean { return !notFound(throwable) && throwable is HttpException } private fun notFound(throwable: Throwable): Boolean { if (throwable is HttpException) { return throwable.code() == 404 } return false } }
0
Kotlin
1
38
dec2d949a69e870bf37a76c4f22d86c93c12c143
1,296
Star-Wars-Shop
Apache License 2.0
vitrivr-engine-module-m3d/src/main/kotlin/org/vitrivr/engine/model3d/lwjglrender/render/Render.kt
vitrivr
679,355,326
false
{"Kotlin": 1141621, "GLSL": 568}
package org.vitrivr.engine.model3d.lwjglrender.render import org.lwjgl.opengl.GL import org.lwjgl.opengl.GL30 import org.vitrivr.engine.model3d.lwjglrender.window.Window import org.vitrivr.engine.model3d.lwjglrender.glmodel.GLScene /** * This class holds the render logic for the LWJGL engine * Holds the [SceneRender] which loads shaders */ class Render { /** * Instance of the scene render * @see SceneRender */ private val sceneRender: SceneRender /** * Instance of the render options * @see RenderOptions */ private var options: RenderOptions? = null /** * Create a render instance Set up the Render options for OpenGL */ init { GL.createCapabilities() GL30.glEnable(GL30.GL_DEPTH_TEST) GL30.glEnable(GL30.GL_CULL_FACE) GL30.glCullFace(GL30.GL_BACK) this.sceneRender = SceneRender() } /** * Set the render options [RenderOptions] * * @param options see [RenderOptions] */ fun setOptions(options: RenderOptions?) { this.options = options } /** * Releases all resources */ fun cleanup() { sceneRender.cleanup() this.options = null } /** * Renders a given Scene in a Given Window * * @param window GL (offscreen) window instance [Window] * @param scene GL Scene (containing all models) [GLScene] */ fun render(window: Window, scene: GLScene?) { GL30.glClear(GL30.GL_COLOR_BUFFER_BIT or GL30.GL_DEPTH_BUFFER_BIT) GL30.glViewport(0, 0, window.width, window.height) if (scene != null) { this.options?.let { sceneRender.render(scene, it) } } } }
9
Kotlin
3
5
da6775b4ebee9ab4e8b76848bafdcdd31db189f9
1,721
vitrivr-engine
MIT License
app/src/main/java/com/nakul/blogWall/adapters/TrendingBlogAdapter.kt
nakul-19
368,067,955
false
null
package com.nakul.blogWall.adapters import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.nakul.blogWall.activities.BlogActivity import com.nakul.blogWall.databinding.ItemTrendingBlogsBinding import com.nakul.blogWall.models.blog.Blog class TrendingBlogAdapter(private val list: ArrayList<Blog>) : RecyclerView.Adapter<TrendingBlogAdapter.ViewHolder>() { class ViewHolder(_binding: ItemTrendingBlogsBinding) : RecyclerView.ViewHolder(_binding.root) { var binding: ItemTrendingBlogsBinding = _binding } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder = ViewHolder( ItemTrendingBlogsBinding.inflate(LayoutInflater.from(parent.context), parent, false) ) override fun onBindViewHolder(holder: ViewHolder, position: Int) { if (list.isNotEmpty()) { val b = holder.binding Glide.with(holder.itemView.context) .load(list[position].image) .into(b.image) b.heading.text = list[position].title b.root.setOnClickListener { BlogActivity.start(it.context, list[position]) } } } override fun getItemCount(): Int { return if (list.isEmpty()) 1 else list.size } }
0
Kotlin
0
6
75088bce7a5f4b516c7c702cc83c7226c151e829
1,410
Blog-Wall
MIT License
payze-android-sdk/src/main/java/com/payze/sdk/model/CardBrandType.kt
PayzeTech
876,806,123
false
{"Kotlin": 62807, "Java": 26374}
package com.payze.sdk.model enum class CardBrandType(val type: String) { VISA("Visa"), MASTER_CARD("MasterCard"), HUMO("Humo"), UZ_CARD("Uzcard"), AMEX("AmexCredit"); }
0
Kotlin
0
0
9360a967d0de1d50a34f9af0799f696f2943aead
189
Payze-Android-SDK
MIT License
src/main/kotlin/com/github/atsumerudev/api/metron/network/MetronService.kt
AtsumeruDev
584,515,155
false
null
package com.github.atsumerudev.api.metron.network import com.github.atsumerudev.api.metron.model.Issue import com.github.atsumerudev.api.metron.model.ResponseResult import com.github.atsumerudev.api.metron.model.Serie import com.github.atsumerudev.api.metron.model.info.* import com.github.atsumerudev.api.metron.model.short.ShortIssue import com.github.atsumerudev.api.metron.model.short.ShortSerie import io.reactivex.Single import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query interface MetronService { // Arc @GET("/api/arc/") fun getArcs( @Query("page") page: Int, @Query("name") name: String?, @Query("modified_gt") modifiedGt: String? ): Single<ResponseResult<Arc>> @GET("/api/arc/{id}/") fun getArc(@Path("id") arkId: Int): Single<Arc> @GET("/api/arc/{id}/issue_list/") fun getArcIssueList(@Path("id") arkId: Int): Single<ResponseResult<ShortIssue>> // Character @GET("/api/character/") fun getCharacters( @Query("page") page: Int, @Query("name") name: String?, @Query("modified_gt") modifiedGt: String? ): Single<ResponseResult<Character>> @GET("/api/character/{id}/") fun getCharacter(@Path("id") characterId: Int): Single<Character> @GET("/api/character/{id}/issue_list/") fun getCharacterIssueList(@Path("id") characterId: Int): Single<ResponseResult<ShortIssue>> // Creator @GET("/api/creator/") fun getCreators( @Query("page") page: Int, @Query("name") name: String?, @Query("modified_gt") modifiedGt: String? ): Single<ResponseResult<Creator>> @GET("/api/creator/{id}/") fun getCreator(@Path("id") creatorId: Int): Single<Creator> // Issue @GET("/api/issue/") fun getIssues( @Query("page") page: Int, @Query("number") number: Int?, @Query("cover_month") coverMonth: Int?, @Query("cover_year") coverYear: Int?, @Query("publisher_id") publisherId: Int?, @Query("publisher_name") publisherName: String?, @Query("series_id") seriesId: Int?, @Query("series_name") seriesName: String?, @Query("series_volume") seriesVolume: Int?, @Query("series_year_began") seriesYearBegan: Int?, @Query("sku") sku: String?, @Query("store_date") storeDate: String?, @Query("store_date_range_after") storeDateRangeAfter: String?, @Query("store_date_range_before") storeDateRangeBefore: String?, @Query("upc") upc: String?, @Query("modified_gt") modifiedGt: String? ): Single<ResponseResult<ShortIssue>> @GET("/api/issue/{id}/") fun getIssue(@Path("id") issueId: Int): Single<Issue> // Publisher @GET("/api/publisher/") fun getPublishers( @Query("page") page: Int, @Query("name") name: String?, @Query("modified_gt") modifiedGt: String? ): Single<ResponseResult<Publisher>> @GET("/api/publisher/{id}/") fun getPublisher(@Path("id") publisherId: Int): Single<Publisher> @GET("/api/publisher/{id}/series_list/") fun getPublisherSeriesList(@Path("id") publisherId: Int): Single<ResponseResult<ShortSerie>> // Role @GET("/api/role/") fun getRoles( @Query("page") page: Int, @Query("name") name: String?, @Query("modified_gt") modifiedGt: String? ): Single<ResponseResult<Role>> // Serie @GET("/api/series/") fun getSeries( @Query("page") page: Int, @Query("name") name: String?, @Query("publisher_id") publisherId: Int?, @Query("publisher_name") publisherName: String?, @Query("series_type") seriesType: String?, @Query("series_type_id") seriesTypeId: Int?, @Query("volume") volume: Int?, @Query("year_began") yearBegan: Int?, @Query("year_end") yearEnd: Int?, @Query("modified_gt") modifiedGt: String? ): Single<ResponseResult<ShortSerie>> @GET("/api/series/{id}/") fun getSerie(@Path("id") serieId: Int): Single<Serie> @GET("/api/series/{id}/issue_list/") fun getSerieIssueList(@Path("id") serieId: Int): Single<ResponseResult<ShortIssue>> // Team @GET("/api/team/") fun getTeams( @Query("page") page: Int, @Query("name") name: String?, @Query("modified_gt") modifiedGt: String? ): Single<ResponseResult<Team>> @GET("/api/team/{id}/") fun getTeam(@Path("id") teamId: Int): Single<Team> @GET("/api/team/{id}/issue_list/") fun getTeamIssueList(@Path("id") teamId: Int): Single<ResponseResult<ShortIssue>> }
0
Kotlin
0
0
5df48fef47f17e3498765b26a2b4378264227036
4,619
MetronAPI
MIT License
presentation/src/main/java/com/example/huitdduru/view/sign/RegisterActivity.kt
HUITDDURU
468,589,462
false
null
package com.example.huitdduru.view.sign import android.os.Bundle import androidx.fragment.app.Fragment import androidx.fragment.app.commit import com.example.huitdduru.R import com.example.huitdduru.databinding.ActivityRegisterBinding import com.example.huitdduru.base.BaseActivity import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class RegisterActivity : BaseActivity<ActivityRegisterBinding>(R.layout.activity_register) { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding.activity = this val fragmentManager = supportFragmentManager fragmentManager.commit { add(R.id.container, InfoFragment()) } } fun replace(fragment: Fragment) { val fragmentManager = supportFragmentManager fragmentManager.commit { replace(R.id.container, fragment) } } }
1
Kotlin
1
0
4d390a361b75289f76e4ce427a07e28a8c19d909
912
RUMA_Android
MIT License
fontawesome/src/de/msrd0/fontawesome/icons/FA_L.kt
msrd0
363,665,023
false
null
/* @generated * * This file is part of the FontAwesome Kotlin library. * https://github.com/msrd0/fontawesome-kt * * This library is not affiliated with FontAwesome. * * 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 de.msrd0.fontawesome.icons import de.msrd0.fontawesome.Icon import de.msrd0.fontawesome.Style import de.msrd0.fontawesome.Style.SOLID /** L */ object FA_L: Icon { override val name get() = "L" override val unicode get() = "4c" override val styles get() = setOf(SOLID) override fun svg(style: Style) = when(style) { SOLID -> """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><path d="M320 448c0 17.67-14.31 32-32 32H64c-17.69 0-32-14.33-32-32v-384C32 46.34 46.31 32.01 64 32.01S96 46.34 96 64.01v352h192C305.7 416 320 430.3 320 448z"/></svg>""" else -> null } }
0
Kotlin
0
0
b2fdb74278104be68c95e8f083fc75ab74395112
1,340
fontawesome-kt
Apache License 2.0
app/src/main/java/cafe/adriel/cryp/view/custom/QrCodeOverlayView.kt
adrielcafe
105,951,831
false
null
package cafe.adriel.cryp.view.custom import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.graphics.PointF import android.util.AttributeSet import android.view.View import cafe.adriel.cryp.R import cafe.adriel.cryp.colorFrom class QrCodeOverlayView(context: Context, attributeSet: AttributeSet? = null) : View(context, attributeSet) { private var points: Array<out PointF>? = null private var paint = Paint() init { paint.apply { color = colorFrom(R.color.colorAccent) style = Paint.Style.FILL } } override fun draw(canvas: Canvas) { super.draw(canvas) points?.forEach { canvas.drawCircle(it.x, it.y, 20f, paint) } } fun setPoints(points: Array<out PointF>) { this.points = points invalidate() } }
0
Kotlin
9
27
5e9c5f805c66990f4b7da3169a0044bb251ccd22
888
CrypAndroidApp
MIT License
data/src/main/java/com/phil/airinkorea/data/database/model/GPSLocationEntity.kt
want8607
574,473,916
false
null
package com.phil.airinkorea.data.database.model import androidx.room.ColumnInfo import androidx.room.Entity import com.phil.airinkorea.data.model.Location /** * 사용자의 GPS로 부터 얻어온 시군구 정보, 측정소 정보를 가지는 entity */ @Entity( tableName = "gps_location", primaryKeys = ["en_do", "en_sigungu", "en_eupmyeondong"] ) data class GPSLocationEntity( @ColumnInfo(name = "row_id") val rowId: Int = 1, @ColumnInfo(name = "en_do") val enDo: String, @ColumnInfo(name = "en_sigungu") val enSigungu: String, @ColumnInfo(name = "en_eupmyeondong") val enEupmyeondong: String, @ColumnInfo(name = "station") val station: String ) fun GPSLocationEntity.mapToExternalModel(): Location = Location( `do` = enDo, sigungu = enSigungu, eupmyeondong = enEupmyeondong, station = station )
0
Kotlin
0
0
e61bc7ef1039578347e1d47f32f629c085ffce3d
825
AirInKorea
Apache License 2.0
app/src/test/java/com/anddev404/calculatorbmi/SharedViewModelTest.kt
anddev404
528,137,106
false
{"Kotlin": 62710, "HTML": 6655}
package com.anddev404.calculatorbmi import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.LiveData import androidx.lifecycle.Observer import com.anddev404.calculatorbmi.data.model.WeightUnit import junit.framework.TestCase import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test class SharedViewModelTest { lateinit var viewModel: SharedViewModel lateinit var bmiLiveData: LiveData<Float> lateinit var idealWeightLiveData: LiveData<String> lateinit var correctWeightLiveData: LiveData<String> lateinit var underOverWeightLiveData: LiveData<Pair<Float, String>> lateinit var bmiObserver: Observer<Float> lateinit var idealWeightObserver: Observer<String> lateinit var correctWeightObserver: Observer<String> lateinit var underOverWeightObserver: Observer<Pair<Float, String>> @get:Rule val rule = InstantTaskExecutorRule() @Before fun setup() { viewModel = SharedViewModel() bmiLiveData = viewModel.bmi idealWeightLiveData = viewModel.idealWeight correctWeightLiveData = viewModel.correctWeight underOverWeightLiveData = viewModel.underOverWeight } @Test fun bmi() { bmiObserver = Observer { TestCase.assertEquals(24.22f, it, 0.01f) } idealWeightObserver = Observer { TestCase.assertEquals("62.9 kg", it) } correctWeightObserver = Observer { TestCase.assertEquals("53.5 kg -...\n...- 72.3 kg", it) } underOverWeightObserver = Observer { TestCase.assertEquals(0.0f, it.first) TestCase.assertEquals("...", it.second) } bmiLiveData.observeForever(bmiObserver) idealWeightLiveData.observeForever(idealWeightObserver) correctWeightLiveData.observeForever(correctWeightObserver) underOverWeightLiveData.observeForever(underOverWeightObserver) viewModel.changeWeightUnit(WeightUnit.KG) viewModel.changeHeight(170f) viewModel.changeWeight(70f) } @After fun teardown() { bmiLiveData.removeObserver(bmiObserver) idealWeightLiveData.removeObserver(idealWeightObserver) correctWeightLiveData.removeObserver(correctWeightObserver) underOverWeightLiveData.removeObserver(underOverWeightObserver) } }
0
Kotlin
1
0
d07545a6b62328f7d6dbff272d96adb975379b3b
2,403
Calculator-Bmi
Apache License 2.0
libraries/rib-base/src/main/java/com/badoo/ribs/routing/source/backstack/BackStackFeature.kt
ShikaSD
178,303,031
true
{"Kotlin": 1643578}
package com.badoo.ribs.routing.source.backstack import android.os.Bundle import android.os.Parcelable import com.badoo.mvicore.android.AndroidTimeCapsule import com.badoo.mvicore.element.Actor import com.badoo.mvicore.element.Bootstrapper import com.badoo.mvicore.element.Reducer import com.badoo.mvicore.element.TimeCapsule import com.badoo.mvicore.extension.mapNotNull import com.badoo.mvicore.feature.ActorReducerFeature import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.routing.Routing import com.badoo.ribs.routing.history.RoutingHistory import com.badoo.ribs.routing.history.RoutingHistoryElement import com.badoo.ribs.routing.history.RoutingHistoryElement.Activation.ACTIVE import com.badoo.ribs.routing.history.RoutingHistoryElement.Activation.INACTIVE import com.badoo.ribs.routing.source.RoutingSource import com.badoo.ribs.routing.source.backstack.BackStackFeature.Operation import com.badoo.ribs.routing.source.backstack.operation.BackStackOperation import com.badoo.ribs.routing.source.backstack.operation.NewRoot import com.badoo.ribs.routing.source.backstack.operation.Remove import com.badoo.ribs.routing.source.backstack.operation.canPop import com.badoo.ribs.routing.source.backstack.operation.canPopOverlay import com.badoo.ribs.routing.source.backstack.operation.pop import io.reactivex.Observable import io.reactivex.Observable.empty import io.reactivex.Observable.just import io.reactivex.ObservableSource import io.reactivex.Observer import io.reactivex.functions.Consumer private val timeCapsuleKey = BackStackFeature::class.java.name private fun <C : Parcelable> TimeCapsule<BackStackFeatureState<C>>.initialState(): BackStackFeatureState<C> = (get(timeCapsuleKey) ?: BackStackFeatureState()) /** * State store implementing [RoutingSource] that keeps a simple linear history of [Routing]s. * * It will maintain a [RoutingHistory] such the last, and only the last [RoutingHistoryElement] is * set to active [RoutingHistoryElement.Activation.ACTIVE]. * * Elements are persisted to Bundle (see [AndroidTimeCapsule]) and restored automatically. * * @see BackStackFeature.Operation for supported operations * @see BackStackFeature.BootstrapperImpl for operations emitted during initialisation * @see BackStackFeature.ActorImpl for logic deciding whether an operation should be carried out * @see BackStackFeature.ReducerImpl for the implementation of applying state changes */ class BackStackFeature<C : Parcelable> internal constructor( private val initialConfiguration: C, private val timeCapsule: AndroidTimeCapsule ) : Consumer<Operation<C>>, RoutingSource<C> { private val feature = ActorReducerFeature<Operation<C>, Effect<C>, BackStackFeatureState<C>, Nothing>( initialState = timeCapsule.initialState(), bootstrapper = BootstrapperImpl( timeCapsule.initialState(), initialConfiguration ), actor = ActorImpl(), reducer = ReducerImpl( contentIdFactory = this::contentIdForPosition, overlayIdFactory = this::overlayIdForPosition ) ) val state: BackStackFeatureState<C> get() = feature.state val activeConfiguration: ObservableSource<C> get() = Observable.wrap(feature) .mapNotNull { it.backStack .last() ?.routing ?.configuration } .startWith(initialConfiguration) override fun baseLineState(fromRestored: Boolean): RoutingHistory<C> = timeCapsule.initialState() constructor( initialConfiguration: C, // TODO consider 2nd constructor with RoutingHistoryElement<C> buildParams: BuildParams<*> ) : this( initialConfiguration, AndroidTimeCapsule(buildParams.savedInstanceState) ) init { timeCapsule.register(timeCapsuleKey) { feature.state } } /** * The back stack operation this [BackStackFeature] supports. */ data class Operation<C : Parcelable>(val backStackOperation: BackStackOperation<C>) /** * The set of back stack operations affecting the state. */ sealed class Effect<C : Parcelable> { // Consider adding oldState to NewsPublisher abstract val oldState: BackStackFeatureState<C> data class Applied<C : Parcelable>( override val oldState: BackStackFeatureState<C>, val backStackOperation: BackStackOperation<C> ) : Effect<C>() } /** * Automatically sets [initialConfiguration] as [NewRoot] when initialising the [BackStackFeature] */ class BootstrapperImpl<C : Parcelable>( private val state: BackStackFeatureState<C>, private val initialConfiguration: C ) : Bootstrapper<Operation<C>> { override fun invoke(): Observable<Operation<C>> = when { state.backStack.isEmpty() -> just(Operation( NewRoot( initialConfiguration ) )) else -> empty() } } /** * Checks if the required operations are to be executed based on the current [State]. * Emits corresponding [Effect]s if the answer is yes. */ class ActorImpl<C : Parcelable> : Actor<BackStackFeatureState<C>, Operation<C>, Effect<C>> { @SuppressWarnings("LongMethod") override fun invoke(state: BackStackFeatureState<C>, op: Operation<C>): Observable<out Effect<C>> = if (op.backStackOperation.isApplicable(state.backStack)) { just( Effect.Applied( state, op.backStackOperation ) ) } else { empty() } } /** * Creates a new [State] based on the old one + the applied [Effect] */ @SuppressWarnings("LongMethod") class ReducerImpl<C : Parcelable>( val contentIdFactory: (Int, C) -> Routing.Identifier, val overlayIdFactory: (Int, C, Int, C) -> Routing.Identifier ) : Reducer<BackStackFeatureState<C>, Effect<C>> { override fun invoke(state: BackStackFeatureState<C>, effect: Effect<C>): BackStackFeatureState<C> = state.apply(effect) private fun BackStackFeatureState<C>.apply(effect: Effect<C>): BackStackFeatureState<C> = when (effect) { is Effect.Applied -> { val updated = effect .backStackOperation.invoke(backStack) .applyBackStackMaintenance() copy( backStack = updated ) } } // TODO add unit test checking id uniqueness private fun BackStack<C>.applyBackStackMaintenance(): BackStack<C> = mapIndexed { index, element -> element.copy( activation = if (index == lastIndex) ACTIVE else INACTIVE, routing = routingWithCorrectId(element, index), overlays = overlaysWithCorrectId(element, index) ) } private fun routingWithCorrectId(element: RoutingHistoryElement<C>, index: Int): Routing<C> = element.routing.copy( identifier = contentIdFactory( index, element.routing.configuration ) ) private fun overlaysWithCorrectId(element: RoutingHistoryElement<C>, index: Int): List<Routing<C>> = element.overlays.mapIndexed { overlayIndex, overlay -> overlay.copy( identifier = overlayIdFactory( index, element.routing.configuration, overlayIndex, overlay.configuration ) ) } } fun popBackStack(): Boolean = // TODO rename if (feature.state.backStack.canPop) { pop() true } else { false } fun popOverlay(): Boolean = if (feature.state.backStack.canPopOverlay) { pop() true } else { false } override fun handleBackPressFirst(): Boolean = popOverlay() override fun handleBackPressFallback(): Boolean = popBackStack() override fun remove(identifier: Routing.Identifier) { feature.accept(Operation( Remove( identifier ) )) } override fun accept(operation: Operation<C>) { feature.accept(operation) } override fun subscribe(observer: Observer<in RoutingHistory<C>>) = feature.subscribe(observer) override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) timeCapsule.saveState(outState) } internal fun contentIdForPosition(position: Int, content: C): Routing.Identifier = Routing.Identifier("Back stack ${System.identityHashCode(this)} #$position = $content") internal fun overlayIdForPosition(position: Int, content: C, overlayIndex: Int, overlay: C): Routing.Identifier = Routing.Identifier("Back stack ${System.identityHashCode(this)} overlay #$position.$overlayIndex = $content.$overlay") }
0
Kotlin
0
0
0ffeabef7928bb94d186baa5b8d94616f77c6a01
9,379
RIBs
Apache License 2.0
konfig-yaml/src/jvmTest/kotlin/net/mamoe/konfig/yaml/TestNewStream.kt
Hai-tun
261,638,920
true
{"Kotlin": 155051}
package net.mamoe.konfig.yaml import kotlinx.serialization.Serializable import org.junit.Test internal class TestNewStream { @Test fun testNewStream() { @Serializable data class Data( val s: String ) println( Yaml.default.parse( Data.serializer(), """ s: test """ ) ) } }
0
null
0
0
10d0f98be2f24ed5989364f7d59941caffdcc441
396
konfig
Apache License 2.0
src/main/kotlin/payload/response/Items.kt
LastExceed
249,260,520
false
null
package payload.response import kotlinx.serialization.Serializable import payload.response.common.ItemShort @Serializable data class Items private constructor( val items: List<ItemShort> )
24
Kotlin
0
3
c6526533f943fb5819d275fdfae0b97ae5a1d7d0
191
WarframeMarKT
MIT License
src/main/kotlin/com/michigang1/backendcourse/models/Category.kt
michigang1
717,830,098
false
{"Kotlin": 23565, "Dockerfile": 440}
package com.michigang1.backendcourse.models data class Category( var id: Int = 0, val name: String? = "No name provided", )
0
Kotlin
0
1
6940a025d0e624b57798dde73d1660f9a95a3997
134
back-end-course
MIT License
subprojects/android-test/test-screenshot/src/main/java/com/avito/android/test/screenshot_test/internal/BitmapHelpers.kt
avito-tech
230,265,582
false
{"Kotlin": 3385243, "Java": 52258, "Shell": 28052, "Dockerfile": 12770, "Makefile": 8156, "HTML": 2803}
package com.avito.android.test.screenshot_test.internal import android.annotation.SuppressLint import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.util.Log import java.io.File import java.io.FileInputStream import java.io.FileOutputStream @SuppressLint("SdCardPath") internal fun getBitmapFromDevice(file: File): Bitmap { return FileInputStream(file).use { BitmapFactory.decodeStream(it) } } internal fun Context.getBitmapFromAsset(filePath: String): Bitmap { return assets.open(filePath).use { BitmapFactory.decodeStream(it) } } internal fun saveBitmap(bitmap: Bitmap, file: File) { FileOutputStream(file).use { bitmap.compress( Bitmap.CompressFormat.PNG, 100, it ) Log.i("ViewSaver", "successfully save screenshot to ${file.absolutePath}") } }
7
Kotlin
45
382
52f5fe52961d2e32413f1228746249055b07f663
913
avito-android
MIT License
subprojects/android-test/test-screenshot/src/main/java/com/avito/android/test/screenshot_test/internal/BitmapHelpers.kt
avito-tech
230,265,582
false
{"Kotlin": 3385243, "Java": 52258, "Shell": 28052, "Dockerfile": 12770, "Makefile": 8156, "HTML": 2803}
package com.avito.android.test.screenshot_test.internal import android.annotation.SuppressLint import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.util.Log import java.io.File import java.io.FileInputStream import java.io.FileOutputStream @SuppressLint("SdCardPath") internal fun getBitmapFromDevice(file: File): Bitmap { return FileInputStream(file).use { BitmapFactory.decodeStream(it) } } internal fun Context.getBitmapFromAsset(filePath: String): Bitmap { return assets.open(filePath).use { BitmapFactory.decodeStream(it) } } internal fun saveBitmap(bitmap: Bitmap, file: File) { FileOutputStream(file).use { bitmap.compress( Bitmap.CompressFormat.PNG, 100, it ) Log.i("ViewSaver", "successfully save screenshot to ${file.absolutePath}") } }
7
Kotlin
45
382
52f5fe52961d2e32413f1228746249055b07f663
913
avito-android
MIT License
sykepenger-mediators/src/main/kotlin/no/nav/helse/spleis/PersonMediator.kt
navikt
193,907,367
false
null
package no.nav.helse.spleis import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.databind.node.ObjectNode import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule import com.fasterxml.jackson.module.kotlin.convertValue import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import java.util.UUID import no.nav.helse.Personidentifikator import no.nav.helse.hendelser.Påminnelse import no.nav.helse.hendelser.PersonHendelse import no.nav.helse.person.PersonObserver import no.nav.helse.person.TilstandType import no.nav.helse.rapids_rivers.JsonMessage import no.nav.helse.rapids_rivers.MessageContext import no.nav.helse.rapids_rivers.RapidsConnection import no.nav.helse.spleis.db.HendelseRepository import no.nav.helse.spleis.meldinger.model.HendelseMessage import org.slf4j.LoggerFactory internal class PersonMediator( private val message: HendelseMessage, private val hendelse: PersonHendelse, private val hendelseRepository: HendelseRepository ) : PersonObserver { private val meldinger = mutableListOf<Pakke>() private val replays = mutableListOf<String>() private companion object { private val sikkerLogg = LoggerFactory.getLogger("tjenestekall") private val logg = LoggerFactory.getLogger(PersonMediator::class.java) private val objectMapper = jacksonObjectMapper() .registerModule(JavaTimeModule()) .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) } fun finalize(rapidsConnection: RapidsConnection, context: MessageContext) { sendUtgåendeMeldinger(context) sendReplays(rapidsConnection) } private fun sendUtgåendeMeldinger(context: MessageContext) { if (meldinger.isEmpty()) return message.logOutgoingMessages(sikkerLogg, meldinger.size) meldinger.forEach { pakke -> pakke.publish(context) } } private fun sendReplays(rapidsConnection: RapidsConnection) { if (replays.isEmpty()) return message.logReplays(sikkerLogg, replays.size) replays.forEach { melding -> rapidsConnection.queueReplayMessage(hendelse.fødselsnummer(), melding) } } private fun queueMessage(fødselsnummer: String, eventName: String, message: String) { meldinger.add(Pakke(fødselsnummer, eventName, message)) } override fun inntektsmeldingReplay(personidentifikator: Personidentifikator, vedtaksperiodeId: UUID) { hendelseRepository.finnInntektsmeldinger(personidentifikator).forEach { inntektsmelding -> createReplayMessage(inntektsmelding, mapOf( "@event_name" to "inntektsmelding_replay", "vedtaksperiodeId" to vedtaksperiodeId )) } } private fun createReplayMessage(message: JsonNode, extraFields: Map<String, Any>) { message as ObjectNode message.put("@replay", true) extraFields.forEach { (key, value), -> message.replace(key, objectMapper.convertValue<JsonNode>(value)) } replays.add(message.toString()) } override fun vedtaksperiodePåminnet(vedtaksperiodeId: UUID, organisasjonsnummer: String, påminnelse: Påminnelse) { queueMessage(JsonMessage.newMessage("vedtaksperiode_påminnet", påminnelse.toOutgoingMessage())) } override fun vedtaksperiodeIkkePåminnet(vedtaksperiodeId: UUID, organisasjonsnummer: String, nåværendeTilstand: TilstandType) { queueMessage(JsonMessage.newMessage("vedtaksperiode_ikke_påminnet", mapOf( "organisasjonsnummer" to organisasjonsnummer, "vedtaksperiodeId" to vedtaksperiodeId, "tilstand" to nåværendeTilstand ))) } override fun annullering(event: PersonObserver.UtbetalingAnnullertEvent) { queueMessage(JsonMessage.newMessage("utbetaling_annullert", mutableMapOf( "organisasjonsnummer" to event.organisasjonsnummer, "utbetalingId" to event.utbetalingId, "korrelasjonsId" to event.korrelasjonsId, "fom" to event.fom, "tom" to event.tom, "annullertAvSaksbehandler" to event.annullertAvSaksbehandler, "tidspunkt" to event.annullertAvSaksbehandler, "saksbehandlerEpost" to event.saksbehandlerEpost, "epost" to event.saksbehandlerEpost, "saksbehandlerIdent" to event.saksbehandlerIdent, "ident" to event.saksbehandlerIdent, "utbetalingslinjer" to event.utbetalingslinjer.map { mapOf( "fom" to it.fom, "tom" to it.tom, "grad" to it.grad, "beløp" to it.beløp )} ).apply { event.arbeidsgiverFagsystemId?.also { this["fagsystemId"] = it this["arbeidsgiverFagsystemId"] = it } event.personFagsystemId?.also { this["personFagsystemId"] = it } })) } override fun utbetalingEndret(event: PersonObserver.UtbetalingEndretEvent) { queueMessage(JsonMessage.newMessage("utbetaling_endret", mapOf( "organisasjonsnummer" to event.organisasjonsnummer, "utbetalingId" to event.utbetalingId, "type" to event.type, "forrigeStatus" to event.forrigeStatus, "gjeldendeStatus" to event.gjeldendeStatus, "arbeidsgiverOppdrag" to event.arbeidsgiverOppdrag, "personOppdrag" to event.personOppdrag, "korrelasjonsId" to event.korrelasjonsId ))) } override fun nyVedtaksperiodeUtbetaling( personidentifikator: Personidentifikator, aktørId: String, organisasjonsnummer: String, utbetalingId: UUID, vedtaksperiodeId: UUID ) { val eventName = "vedtaksperiode_ny_utbetaling" queueMessage(personidentifikator.toString(), eventName, JsonMessage.newMessage(eventName, mapOf( "fødselsnummer" to personidentifikator.toString(), "aktørId" to aktørId, "organisasjonsnummer" to organisasjonsnummer, "vedtaksperiodeId" to vedtaksperiodeId, "utbetalingId" to utbetalingId )).toJson()) } override fun overstyringIgangsatt(event: PersonObserver.OverstyringIgangsatt) { queueMessage(JsonMessage.newMessage("overstyring_igangsatt", mapOf( "revurderingId" to UUID.randomUUID(), "kilde" to message.id, "skjæringstidspunkt" to event.skjæringstidspunkt, "periodeForEndringFom" to event.periodeForEndring.start, "periodeForEndringTom" to event.periodeForEndring.endInclusive, "årsak" to event.årsak, "typeEndring" to event.typeEndring, "berørtePerioder" to event.berørtePerioder.map { mapOf( "vedtaksperiodeId" to it.vedtaksperiodeId, "skjæringstidspunkt" to it.skjæringstidspunkt, "periodeFom" to it.periode.start, "periodeTom" to it.periode.endInclusive, "orgnummer" to it.orgnummer, "typeEndring" to it.typeEndring, ) } ))) } override fun utbetalingUtbetalt(event: PersonObserver.UtbetalingUtbetaltEvent) { queueMessage(utbetalingAvsluttet("utbetaling_utbetalt", event)) } override fun utbetalingUtenUtbetaling(event: PersonObserver.UtbetalingUtbetaltEvent) { queueMessage(utbetalingAvsluttet("utbetaling_uten_utbetaling", event)) } private fun utbetalingAvsluttet(eventName: String, event: PersonObserver.UtbetalingUtbetaltEvent) = JsonMessage.newMessage(eventName, mapOf( "organisasjonsnummer" to event.organisasjonsnummer, "utbetalingId" to event.utbetalingId, "korrelasjonsId" to event.korrelasjonsId, "type" to event.type, "fom" to event.fom, "tom" to event.tom, "maksdato" to event.maksdato, "forbrukteSykedager" to event.forbrukteSykedager, "gjenståendeSykedager" to event.gjenståendeSykedager, "stønadsdager" to event.stønadsdager, "ident" to event.ident, "epost" to event.epost, "tidspunkt" to event.tidspunkt, "automatiskBehandling" to event.automatiskBehandling, "arbeidsgiverOppdrag" to event.arbeidsgiverOppdrag, "personOppdrag" to event.personOppdrag, "utbetalingsdager" to event.utbetalingsdager, "vedtaksperiodeIder" to event.vedtaksperiodeIder )) override fun feriepengerUtbetalt(event: PersonObserver.FeriepengerUtbetaltEvent) = queueMessage(JsonMessage.newMessage("feriepenger_utbetalt", mapOf( "organisasjonsnummer" to event.organisasjonsnummer, "arbeidsgiverOppdrag" to event.arbeidsgiverOppdrag, "personOppdrag" to event.personOppdrag, ))) override fun vedtaksperiodeEndret(event: PersonObserver.VedtaksperiodeEndretEvent) { queueMessage(JsonMessage.newMessage("vedtaksperiode_endret", mapOf( "organisasjonsnummer" to event.organisasjonsnummer, "vedtaksperiodeId" to event.vedtaksperiodeId, "gjeldendeTilstand" to event.gjeldendeTilstand, "forrigeTilstand" to event.forrigeTilstand, "hendelser" to event.hendelser, "makstid" to event.makstid, "fom" to event.fom, "tom" to event.tom ))) } override fun opprettOppgaveForSpeilsaksbehandlere(event: PersonObserver.OpprettOppgaveForSpeilsaksbehandlereEvent) { queueMessage(JsonMessage.newMessage("opprett_oppgave_for_speilsaksbehandlere", mapOf( "hendelser" to event.hendelser, ))) } override fun opprettOppgave(event: PersonObserver.OpprettOppgaveEvent) { queueMessage(JsonMessage.newMessage("opprett_oppgave", mapOf( "hendelser" to event.hendelser, ))) } override fun utsettOppgave(event: PersonObserver.UtsettOppgaveEvent) { queueMessage(JsonMessage.newMessage("utsett_oppgave", mapOf( "hendelse" to event.hendelse ))) } override fun vedtaksperiodeForkastet(event: PersonObserver.VedtaksperiodeForkastetEvent) { queueMessage(JsonMessage.newMessage("vedtaksperiode_forkastet", mapOf( "organisasjonsnummer" to event.organisasjonsnummer, "vedtaksperiodeId" to event.vedtaksperiodeId, "tilstand" to event.gjeldendeTilstand, "hendelser" to event.hendelser, "fom" to event.fom, "tom" to event.tom ))) } override fun vedtakFattet(event: PersonObserver.VedtakFattetEvent) { queueMessage(JsonMessage.newMessage("vedtak_fattet", mutableMapOf( "organisasjonsnummer" to event.organisasjonsnummer, "vedtaksperiodeId" to event.vedtaksperiodeId, "fom" to event.periode.start, "tom" to event.periode.endInclusive, "hendelser" to event.hendelseIder, "skjæringstidspunkt" to event.skjæringstidspunkt, "sykepengegrunnlag" to event.sykepengegrunnlag, "grunnlagForSykepengegrunnlag" to event.beregningsgrunnlag, "grunnlagForSykepengegrunnlagPerArbeidsgiver" to event.omregnetÅrsinntektPerArbeidsgiver, "begrensning" to event.sykepengegrunnlagsbegrensning, "inntekt" to event.inntekt, "vedtakFattetTidspunkt" to event.vedtakFattetTidspunkt ).apply { event.utbetalingId?.let { this["utbetalingId"] = it } })) } override fun avstemt(result: Map<String, Any>) { queueMessage(JsonMessage.newMessage("person_avstemt", result)) } override fun vedtaksperiodeIkkeFunnet(event: PersonObserver.VedtaksperiodeIkkeFunnetEvent) { queueMessage(JsonMessage.newMessage("vedtaksperiode_ikke_funnet", mapOf( "organisasjonsnummer" to event.organisasjonsnummer, "vedtaksperiodeId" to event.vedtaksperiodeId ))) } override fun manglerInntektsmelding(event: PersonObserver.ManglendeInntektsmeldingEvent) { queueMessage(JsonMessage.newMessage("trenger_inntektsmelding", mapOf( "organisasjonsnummer" to event.organisasjonsnummer, "vedtaksperiodeId" to event.vedtaksperiodeId, "fom" to event.fom, "tom" to event.tom, "søknadIder" to event.søknadIder ))) } override fun trengerIkkeInntektsmelding(event: PersonObserver.TrengerIkkeInntektsmeldingEvent) { queueMessage(JsonMessage.newMessage("trenger_ikke_inntektsmelding", mapOf( "organisasjonsnummer" to event.organisasjonsnummer, "vedtaksperiodeId" to event.vedtaksperiodeId, "fom" to event.fom, "tom" to event.tom, "søknadIder" to event.søknadIder ))) } override fun trengerArbeidsgiveropplysninger(event: PersonObserver.TrengerArbeidsgiveropplysningerEvent) { queueMessage(JsonMessage.newMessage("trenger_opplysninger_fra_arbeidsgiver", event.toJsonMap())) } private fun leggPåStandardfelter(outgoingMessage: JsonMessage) = outgoingMessage.apply { this["aktørId"] = hendelse.aktørId() this["fødselsnummer"] = hendelse.fødselsnummer() } private fun queueMessage(outgoingMessage: JsonMessage) { loggHvisTomHendelseliste(outgoingMessage) queueMessage(hendelse.fødselsnummer(), outgoingMessage.also { it.interestedIn("@event_name") }["@event_name"].asText(), leggPåStandardfelter(outgoingMessage).toJson()) } private fun loggHvisTomHendelseliste(outgoingMessage: JsonMessage) { objectMapper.readTree(outgoingMessage.toJson()).let { if (it.path("hendelser").isArray && it["hendelser"].isEmpty) { logg.warn("Det blir sendt ut et event med tom hendelseliste - ooouups") } } } private data class Pakke ( private val fødselsnummer: String, private val eventName: String, private val blob: String, ) { fun publish(context: MessageContext) { context.publish(fødselsnummer, blob.also { sikkerLogg.info("sender $eventName: $it") }) } } }
1
Kotlin
5
5
a1d4ace847a123e6bf09754ea0640116caf6ceb7
14,439
helse-spleis
MIT License
app/src/main/java/com/romnan/kamusbatak/domain/model/Language.kt
deddyrumapea
458,088,031
false
{"Kotlin": 204437, "CMake": 1603}
package com.romnan.kamusbatak.domain.model import com.romnan.kamusbatak.R import com.romnan.kamusbatak.domain.util.UIText enum class Language( val displayName: UIText, val codeName: String, ) { BTK( displayName = UIText.StringResource(R.string.batak), codeName = "btk", ), IND( displayName = UIText.StringResource(R.string.indonesia), codeName = "ind", ), }
0
Kotlin
0
1
31f0711b770ec97ce4b3f7fc4a07dc02331db1ed
417
KamusBatak
Apache License 2.0
2022/06/06.kt
LiquidFun
435,683,748
false
{"Kotlin": 40554, "Rust": 37108, "Python": 36317, "Julia": 29455, "OCaml": 2592, "C++": 1965, "Shell": 1714, "APL": 191}
fun String.solve(n: Int) = n + this.windowed(n).indexOfFirst { it.toSet().size == it.length } fun main() { val s = readln() println(s.solve(4)) println(s.solve(14)) }
0
Kotlin
7
45
de350478dcc03bf8dee41fca356247e512769475
180
adventofcode
Apache License 2.0
android/app/src/main/java/com/algorand/android/assetsearch/domain/pagination/AssetSearchPagination.kt
perawallet
364,359,642
false
{"Swift": 8753304, "Kotlin": 7709389, "Objective-C": 88978, "Shell": 7715, "Ruby": 4727, "C": 596}
/* * Copyright 2022 Pera Wallet, LDA * 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.algorand.android.assetsearch.domain.pagination import androidx.paging.PagingData import com.algorand.android.assetsearch.domain.model.AssetSearchDTO import com.algorand.android.assetsearch.domain.model.AssetSearchQuery import com.algorand.android.assetsearch.domain.repository.AssetSearchRepository import javax.inject.Inject import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach class AssetSearchPagination @Inject constructor() { private val querySharedFlow = MutableSharedFlow<AssetSearchQuery>() private lateinit var assetSearchPager: AssetSearchPager fun initPagination( assetSearchPagerBuilder: AssetSearchPagerBuilder, scope: CoroutineScope, repository: AssetSearchRepository, defaultQuery: AssetSearchQuery, queryDebounce: Long = DEFAULT_QUERY_DEBOUNCE ): Flow<PagingData<AssetSearchDTO>> { assetSearchPager = assetSearchPagerBuilder.build(repository, defaultQuery) querySharedFlow .debounce(queryDebounce) .onEach { assetSearchPager.updateQuery(it) } .flowOn(Dispatchers.Default) .launchIn(scope) return assetSearchPager.toFlow(scope) } suspend fun searchAsset(query: AssetSearchQuery) { querySharedFlow.emit(query) } fun invalidateDataSource() { assetSearchPager.invalidateDataSource() } companion object { private const val DEFAULT_QUERY_DEBOUNCE = 400L } }
22
Swift
62
181
92fc77f73fa4105de82d5e87b03c1e67600a57c0
2,318
pera-wallet
Apache License 2.0
app/src/main/kotlin/com/adesso/movee/internal/util/typeconverter/GenreConverter.kt
adessoTurkey
246,803,496
false
{"Kotlin": 262786, "Shell": 866}
package com.adesso.movee.internal.util.typeconverter import androidx.room.TypeConverter class GenreConverter { @TypeConverter fun fromString(genreIds: String): List<Long> { return if (genreIds.isNotEmpty()) { genreIds.split(",").map { it.toLong() } } else { emptyList() } } @TypeConverter fun listToString(list: List<Long>): String { return list.joinToString(separator = ",") } }
31
Kotlin
13
35
b34346a815204c966311f0c879b66e05a10eab13
464
android-sample-app
Apache License 2.0
repository/src/main/java/jp/co/yahoo/android/repository/item/ItemEntityRepository.kt
yuukiw00w
186,211,214
false
{"Kotlin": 10759, "Ruby": 1176, "Shell": 368}
package jp.co.yahoo.android.repository.item data class ItemEntityRepository(val itemEntity: ItemEntity)
0
Kotlin
0
0
b325597621616fdcb0a37e2f3d73b613f02e3f90
104
QiitaReaderForAndroid
Apache License 2.0
composeApp/src/commonMain/kotlin/ui/Assets.kt
ShreyashKore
672,328,509
false
null
package ui import models.ChichenItza import models.ChristRedeemer import models.Colosseum import models.GreatWall import models.MachuPicchu import models.Petra import models.PyramidsGiza import models.TajMahal import models.Wonder object ImagePaths { const val root = "files/images" val collectibles = "$root/collectibles" } // For wonder specific assets, add an extension property to Wonder for easy lookup val Wonder.assetPath: String get() = when (this) { PyramidsGiza -> "${ImagePaths.root}/pyramids" GreatWall -> "${ImagePaths.root}/great_wall_of_china" Petra -> "${ImagePaths.root}/petra" Colosseum -> "${ImagePaths.root}/colosseum" ChichenItza -> "${ImagePaths.root}/chichen_itza" MachuPicchu -> "${ImagePaths.root}/machu_picchu" TajMahal -> "${ImagePaths.root}/taj_mahal" ChristRedeemer -> "${ImagePaths.root}/christ_the_redeemer" } fun Wonder.getAssetPath(name: String): String { return "$assetPath/$name" } val Wonder.wonderButtonPath: String get() = getAssetPath("wonder-button.png") val Wonder.mainImageName: String get() = when (this) { ChichenItza -> "chichen.png" ChristRedeemer -> "redeemer.png" Colosseum -> "colosseum.png" GreatWall -> "great-wall.png" MachuPicchu -> "machu-picchu.png" Petra -> "petra.png" PyramidsGiza -> "pyramids.png" TajMahal -> "taj-mahal.png" } val Wonder.homeBtnImage: String get() = getAssetPath("wonder-button.png") val Wonder.photo1: String get() = getAssetPath("photo-1.jpg") val Wonder.photo2: String get() = getAssetPath("photo-2.jpg") val Wonder.photo3: String get() = getAssetPath("photo-3.jpg") val Wonder.photo4: String get() = getAssetPath("photo-4.jpg") val Wonder.flattenedImage: String get() = getAssetPath("flattened.jpg")
4
null
2
94
a0d32d8abc3e6b0470f38e74d1e632e1ab3f0999
1,874
wonderous_compose
MIT License
app/shared/cloud-backup/public/src/commonMain/kotlin/build/wallet/cloud/backup/csek/SealedCsek.kt
proto-at-block
761,306,853
false
{"C": 10424094, "Kotlin": 7156393, "Rust": 2046237, "Swift": 700307, "Python": 331492, "HCL": 271992, "Shell": 111209, "TypeScript": 102700, "C++": 64770, "Meson": 64234, "JavaScript": 36227, "Just": 28071, "Ruby": 9428, "Dockerfile": 5731, "Makefile": 3839, "Open Policy Agent": 1552, "Procfile": 80}
package build.wallet.cloud.backup.csek import build.wallet.serialization.ByteStringAsHexSerializer import kotlinx.serialization.Serializable import okio.ByteString /** * Represents encrypted CSEK (Cloud Storage Encryption Key). Acts as an alias to access raw * [Csek] from [CsekDao]. * * Generally speaking, this key is created through the process of signing [Csek] by the * hardware. Unlike [Csek], this key is safe to pass around and keep in memory for as long * as needed. * * Note: using a typealias instead of a wrapped data class to preserve backwards compatibility with * older backups where sealed CSEK was encoded as an inlined field instead of wrapped object. */ typealias SealedCsek = @Serializable(with = ByteStringAsHexSerializer::class) ByteString
0
C
10
98
1f9f2298919dac77e6791aa3f1dbfd67efe7f83c
778
bitkey
MIT License
year2019/day14/chemistry/src/test/kotlin/com/curtislb/adventofcode/year2019/day14/chemistry/ReactionTest.kt
curtislb
226,797,689
false
{"Kotlin": 1905641}
package com.curtislb.adventofcode.year2019.day14.chemistry import kotlin.test.assertEquals import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows /** * Tests [Reaction]. */ class ReactionTest { @Test fun testConstructWithNoReactants() { assertThrows<IllegalArgumentException> { Reaction( emptyList(), MaterialAmount("magic", 1L) ) } } @Test fun testToString() { assertEquals( "1 lorem => 2 ipsum", Reaction(listOf(MaterialAmount("lorem", 1L)), MaterialAmount("ipsum", 2L)).toString() ) assertEquals( "2 foo, 3 bar => 1 foobar", Reaction( listOf(MaterialAmount("foo", 2L), MaterialAmount("bar", 3L)), MaterialAmount("foobar", 1L) ).toString() ) assertEquals( "5 A, 11 B, 9 C => 23 XYZ", Reaction( listOf(MaterialAmount("A", 5L), MaterialAmount("B", 11L), MaterialAmount("C", 9L)), MaterialAmount("XYZ", 23L) ).toString() ) } @Test fun testFromString() { assertEquals( Reaction(listOf(MaterialAmount("lorem", 1L)), MaterialAmount("ipsum", 2L)), Reaction.from("1 lorem => 2 ipsum"), ) assertEquals( Reaction( listOf(MaterialAmount("foo", 2L), MaterialAmount("bar", 3L)), MaterialAmount("foobar", 1L) ), Reaction.from("2 foo, 3 bar => 1 foobar"), ) assertEquals( Reaction( listOf(MaterialAmount("A", 5L), MaterialAmount("B", 11L), MaterialAmount("C", 9L)), MaterialAmount("XYZ", 23L) ), Reaction.from("5 A, 11 B, 9 C => 23 XYZ"), ) } }
0
Kotlin
1
1
addf5ae8d002d30abf1ab816e23502a296debc4e
1,883
AdventOfCode
MIT License
mod/src/main/kotlin/kotx/customgui/view/creators/RectViewCreator.kt
TeamKun
344,696,205
false
null
package kotx.customgui.view.creators import com.mojang.blaze3d.matrix.MatrixStack import kotx.customgui.gui.guis.EditorGUI import kotx.customgui.util.component import kotx.customgui.view.ViewCreator import kotx.customgui.view.ViewType import kotx.customgui.view.holders.RectViewHolder import kotx.customgui.view.views.RectView import net.minecraft.client.gui.widget.AbstractSlider import net.minecraft.client.gui.widget.button.Button import org.lwjgl.glfw.GLFW import java.awt.Color class RectViewCreator : ViewCreator<RectView, RectViewHolder>() { override val type: ViewType = ViewType.RECT override val points: Int = 2 override var initView: RectViewHolder? = null private lateinit var button: Button private var red = 1.0 private var green = 1.0 private var blue = 1.0 private var alpha = 1.0 private lateinit var redSlider: AbstractSlider private lateinit var greenSlider: AbstractSlider private lateinit var blueSlider: AbstractSlider private lateinit var alphaSlider: AbstractSlider override fun initialize() { if (initView != null) { red = initView!!.content.color.red.toDouble() / 255 green = initView!!.content.color.green.toDouble() / 255 blue = initView!!.content.color.blue.toDouble() / 255 alpha = initView!!.content.color.alpha.toDouble() / 255 } else { red = 1.0 green = 1.0 blue = 1.0 alpha = 1.0 } redSlider = handler.widget(object : AbstractSlider(width / 2 - 100, 50, 200, 20, "赤 ${(red * 255).toInt()}".component(), red) { override fun func_230979_b_() { red = sliderValue } override fun func_230972_a_() { message = "赤 ${(sliderValue * 255).toInt()}".component() } }) as AbstractSlider greenSlider = handler.widget(object : AbstractSlider(width / 2 - 100, 80, 200, 20, "緑 ${(green * 255).toInt()}".component(), green) { override fun func_230979_b_() { green = sliderValue } override fun func_230972_a_() { message = "緑 ${(sliderValue * 255).toInt()}".component() } }) as AbstractSlider blueSlider = handler.widget(object : AbstractSlider(width / 2 - 100, 110, 200, 20, "青 ${(blue * 255).toInt()}".component(), blue) { override fun func_230979_b_() { blue = sliderValue } override fun func_230972_a_() { message = "青 ${(sliderValue * 255).toInt()}".component() } }) as AbstractSlider alphaSlider = handler.widget(object : AbstractSlider(width / 2 - 100, 140, 200, 20, "不透明度 ${(alpha * 255).toInt()}".component(), alpha) { override fun func_230979_b_() { this@RectViewCreator.alpha = sliderValue } override fun func_230972_a_() { message = "不透明度 ${(sliderValue * 255).toInt()}".component() } }) as AbstractSlider button = buttonCenter("作成", width / 2, 190) { handle() } } override fun onKeyPress(key: Int, modifiers: Int): Boolean { if (key == GLFW.GLFW_KEY_ENTER) handle() return super.onKeyPress(key, modifiers) } private fun handle() { if (initView != null) EditorGUI.holders.removeIf { it.index == initView!!.index } build( RectView( Color( (red * 255).toInt(), (green * 255).toInt(), (blue * 255).toInt(), (alpha * 255).toInt() ) ) ) } override fun draw(stack: MatrixStack, mouseX: Int, mouseY: Int) { rect(stack, 0, 0, width, height, Color(0, 0, 0, 100)) textCenter(stack, "色を指定", width / 2, 30, Color.WHITE) rectCenter( stack, width / 2, 190, 200, 30, Color( (red * 255).toInt(), (green * 255).toInt(), (blue * 255).toInt(), (alpha * 255).toInt() ) ) } }
0
Kotlin
0
0
57f4d373f2f9bb80c91ce5671e78edb4e32deb49
4,162
CustomGUI
MIT License
app/src/main/java/com/androidstudy/mpesa/MpesaExpressApp.kt
orama254
300,177,523
true
{"Kotlin": 35147, "Java": 2248}
package com.androidstudy.mpesa import com.androidstudy.mpesa.di.DaggerAppComponent import dagger.android.AndroidInjector import dagger.android.DaggerApplication class MpesaExpressApp : DaggerApplication() { override fun applicationInjector(): AndroidInjector<out DaggerApplication> { return DaggerAppComponent.create() } }
0
null
0
0
fc0b3c29d439cd2f6717531a040b66645eac5ba6
341
android-mpesa-api
MIT License
sample/src/main/kotlin/pl/hypeapp/materialtimelinesample/model/Timepoint.kt
hypeapps
106,310,523
false
null
package pl.hypeapp.materialtimelinesample.model import pl.hypeapp.materialtimelinesample.adapter.ViewType data class Timepoint(val timepoint: String, val description: String) : ViewType { override fun getViewType(): Int = ViewType.LINE }
3
Kotlin
81
457
3f8c5d703d32deaa830166c125895b0ce50ccebc
267
MaterialTimelineView
MIT License
client/src/main/java/com/fesskiev/compose/presentation/NoteDetailsViewModel.kt
fesskiev
328,395,075
false
null
package com.fesskiev.compose.presentation import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.fesskiev.compose.data.remote.parseHttpError import com.fesskiev.compose.domain.GetNoteByIdUseCase import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.launch class NoteDetailsViewModel(private val getNoteByIdUseCase: GetNoteByIdUseCase) : ViewModel() { val stateFlow = MutableStateFlow(NoteDetailsUiState()) fun getNoteByUid(noteUid: Int) { viewModelScope.launch { getNoteByIdUseCase.getNoteByUid(noteUid) .onStart { stateFlow.value = stateFlow.value.copy(loading = true, errorResourceId = null) } .catch { stateFlow.value = stateFlow.value.copy(loading = false, errorResourceId = parseHttpError(it)) }.collect { stateFlow.value = stateFlow.value.copy(loading = false, note = it, errorResourceId = null) } } } }
0
Kotlin
0
0
30ebd00d91fda759f5b4b558e0b0f12fcb61b67b
1,161
NotesClientServerApp
MIT License
src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BlueprintWebClientService.kt
excelsior-esy
190,620,763
false
{"Gradle Kotlin DSL": 2, "INI": 5, "Shell": 3, "Text": 3, "Ignore List": 1, "Batchfile": 1, "AsciiDoc": 1, "YAML": 4, "JSON": 77, "Python": 28, "Java Properties": 4, "XML": 30, "Unity3D Asset": 7, "Kotlin": 184, "Velocity Template Language": 10, "Jinja": 1, "Java": 16, "Dockerfile": 1, "Groovy": 4}
/* * Copyright © 2017-2019 AT&T, Bell Canada, Nordix Foundation * Modifications Copyright © 2018-2019 IBM. * Modifications Copyright © 2019 Huawei. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onap.ccsdk.cds.blueprintsprocessor.rest.service import com.fasterxml.jackson.databind.JsonNode import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.apache.commons.io.IOUtils import org.apache.http.client.ClientProtocolException import org.apache.http.client.methods.HttpDelete import org.apache.http.client.methods.HttpGet import org.apache.http.client.methods.HttpPatch import org.apache.http.client.methods.HttpPost import org.apache.http.client.methods.HttpPut import org.apache.http.client.methods.HttpUriRequest import org.apache.http.entity.StringEntity import org.apache.http.impl.client.CloseableHttpClient import org.apache.http.impl.client.HttpClients import org.apache.http.message.BasicHeader import org.onap.ccsdk.cds.blueprintsprocessor.rest.utils.WebClientUtils import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.springframework.http.HttpMethod import java.io.IOException import java.io.InputStream import java.nio.charset.Charset interface BlueprintWebClientService { fun defaultHeaders(): Map<String, String> fun host(uri: String): String fun httpClient(): CloseableHttpClient { return HttpClients.custom() .addInterceptorFirst(WebClientUtils.logRequest()) .addInterceptorLast(WebClientUtils.logResponse()) .build() } fun exchangeResource(methodType: String, path: String, request: String): WebClientResponse<String> { return this.exchangeResource(methodType, path, request, defaultHeaders()) } fun exchangeResource(methodType: String, path: String, request: String, headers: Map<String, String>): WebClientResponse<String> { /** * TODO: Basic headers in the implementations of this client do not get added * in blocking version, whereas in NB version defaultHeaders get added. * the difference is in convertToBasicHeaders vs basicHeaders */ val convertedHeaders: Array<BasicHeader> = convertToBasicHeaders(headers) return when (HttpMethod.resolve(methodType)) { HttpMethod.DELETE -> delete(path, convertedHeaders, String::class.java) HttpMethod.GET -> get(path, convertedHeaders, String::class.java) HttpMethod.POST -> post(path, request, convertedHeaders, String::class.java) HttpMethod.PUT -> put(path, request, convertedHeaders, String::class.java) HttpMethod.PATCH -> patch(path, request, convertedHeaders, String::class.java) else -> throw BluePrintProcessorException("Unsupported met" + "hodType($methodType)") } } fun convertToBasicHeaders(headers: Map<String, String>): Array<BasicHeader> { return headers.map { BasicHeader(it.key, it.value) }.toTypedArray() } fun <T> delete(path: String, headers: Array<BasicHeader>, responseType: Class<T>): WebClientResponse<T> { val httpDelete = HttpDelete(host(path)) httpDelete.setHeaders(headers) return performCallAndExtractTypedWebClientResponse(httpDelete, responseType) } fun <T> get(path: String, headers: Array<BasicHeader>, responseType: Class<T>): WebClientResponse<T> { val httpGet = HttpGet(host(path)) httpGet.setHeaders(headers) return performCallAndExtractTypedWebClientResponse(httpGet, responseType) } fun <T> post(path: String, request: Any, headers: Array<BasicHeader>, responseType: Class<T>): WebClientResponse<T> { val httpPost = HttpPost(host(path)) val entity = StringEntity(strRequest(request)) httpPost.entity = entity httpPost.setHeaders(headers) return performCallAndExtractTypedWebClientResponse(httpPost, responseType) } fun <T> put(path: String, request: Any, headers: Array<BasicHeader>, responseType: Class<T>): WebClientResponse<T> { val httpPut = HttpPut(host(path)) val entity = StringEntity(strRequest(request)) httpPut.entity = entity httpPut.setHeaders(headers) return performCallAndExtractTypedWebClientResponse(httpPut, responseType) } fun <T> patch(path: String, request: Any, headers: Array<BasicHeader>, responseType: Class<T>): WebClientResponse<T> { val httpPatch = HttpPatch(host(path)) val entity = StringEntity(strRequest(request)) httpPatch.entity = entity httpPatch.setHeaders(headers) return performCallAndExtractTypedWebClientResponse(httpPatch, responseType) } /** * Perform the HTTP call and return HTTP status code and body. * @param httpUriRequest {@link HttpUriRequest} object * @return {@link WebClientResponse} object * http client may throw IOException and ClientProtocolException on error */ @Throws(IOException::class, ClientProtocolException::class) private fun <T> performCallAndExtractTypedWebClientResponse( httpUriRequest: HttpUriRequest, responseType: Class<T>): WebClientResponse<T> { val httpResponse = httpClient().execute(httpUriRequest) val statusCode = httpResponse.statusLine.statusCode httpResponse.entity.content.use { val body = getResponse(it, responseType) return WebClientResponse(statusCode, body) } } suspend fun getNB(path: String): WebClientResponse<String> { return getNB(path, null, String::class.java) } suspend fun getNB(path: String, additionalHeaders: Array<BasicHeader>?): WebClientResponse<String> { return getNB(path, additionalHeaders, String::class.java) } suspend fun <T> getNB(path: String, additionalHeaders: Array<BasicHeader>?, responseType: Class<T>): WebClientResponse<T> = withContext(Dispatchers.IO) { get(path, additionalHeaders!!, responseType) } suspend fun postNB(path: String, request: Any): WebClientResponse<String> { return postNB(path, request, null, String::class.java) } suspend fun postNB(path: String, request: Any, additionalHeaders: Array<BasicHeader>?): WebClientResponse<String> { return postNB(path, request, additionalHeaders, String::class.java) } suspend fun <T> postNB(path: String, request: Any, additionalHeaders: Array<BasicHeader>?, responseType: Class<T>): WebClientResponse<T> = withContext(Dispatchers.IO) { post(path, request, additionalHeaders!!, responseType) } suspend fun putNB(path: String, request: Any): WebClientResponse<String> { return putNB(path, request, null, String::class.java) } suspend fun putNB(path: String, request: Any, additionalHeaders: Array<BasicHeader>?): WebClientResponse<String> { return putNB(path, request, additionalHeaders, String::class.java) } suspend fun <T> putNB(path: String, request: Any, additionalHeaders: Array<BasicHeader>?, responseType: Class<T>): WebClientResponse<T> = withContext(Dispatchers.IO) { put(path, request, additionalHeaders!!, responseType) } suspend fun <T> deleteNB(path: String): WebClientResponse<String> { return deleteNB(path, null, String::class.java) } suspend fun <T> deleteNB(path: String, additionalHeaders: Array<BasicHeader>?): WebClientResponse<String> { return deleteNB(path, additionalHeaders, String::class.java) } suspend fun <T> deleteNB(path: String, additionalHeaders: Array<BasicHeader>?, responseType: Class<T>): WebClientResponse<T> = withContext(Dispatchers.IO) { delete(path, additionalHeaders!!, responseType) } suspend fun <T> patchNB(path: String, request: Any, additionalHeaders: Array<BasicHeader>?, responseType: Class<T>): WebClientResponse<T> = withContext(Dispatchers.IO) { patch(path, request, additionalHeaders!!, responseType) } suspend fun exchangeNB(methodType: String, path: String, request: Any): WebClientResponse<String> { return exchangeNB(methodType, path, request, hashMapOf(), String::class.java) } suspend fun exchangeNB(methodType: String, path: String, request: Any, additionalHeaders: Map<String, String>?): WebClientResponse<String> { return exchangeNB(methodType, path, request, additionalHeaders, String::class.java) } suspend fun <T> exchangeNB(methodType: String, path: String, request: Any, additionalHeaders: Map<String, String>?, responseType: Class<T>): WebClientResponse<T> { //TODO: possible inconsistency //NOTE: this basic headers function is different from non-blocking val convertedHeaders: Array<BasicHeader> = basicHeaders(additionalHeaders!!) return when (HttpMethod.resolve(methodType)) { HttpMethod.GET -> getNB(path, convertedHeaders, responseType) HttpMethod.POST -> postNB(path, request, convertedHeaders, responseType) HttpMethod.DELETE -> deleteNB(path, convertedHeaders, responseType) HttpMethod.PUT -> putNB(path, request, convertedHeaders, responseType) HttpMethod.PATCH -> patchNB(path, request, convertedHeaders, responseType) else -> throw BluePrintProcessorException("Unsupported method" + "Type($methodType)") } } private fun strRequest(request: Any): String { return when (request) { is String -> request.toString() is JsonNode -> request.toString() else -> JacksonUtils.getJson(request) } } private fun <T> getResponse(it: InputStream, responseType: Class<T>): T { return if (responseType == String::class.java) { IOUtils.toString(it, Charset.defaultCharset()) as T } else { JacksonUtils.readValue(it, responseType)!! } } private fun basicHeaders(headers: Map<String, String>?): Array<BasicHeader> { val basicHeaders = mutableListOf<BasicHeader>() defaultHeaders().forEach { (name, value) -> basicHeaders.add(BasicHeader(name, value)) } headers?.forEach { name, value -> basicHeaders.add(BasicHeader(name, value)) } return basicHeaders.toTypedArray() } // Non Blocking Rest Implementation suspend fun httpClientNB(): CloseableHttpClient { return HttpClients.custom() .addInterceptorFirst(WebClientUtils.logRequest()) .addInterceptorLast(WebClientUtils.logResponse()) .build() } //TODO maybe there could be cases where we care about return headers? data class WebClientResponse<T>(val status: Int, val body: T) }
1
null
1
1
8e5d445d627fb36106468fed1d8d21988f59f976
11,709
blueprintsprocessor
Apache License 2.0
core/src/com/jupiter/europa/entity/ability/spell/Spells.kt
ntemplon
27,618,453
false
{"Gradle": 4, "Text": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Kotlin": 138, "Java": 19, "XML": 3, "JSON": 2}
/* * The MIT License * * Copyright 2015 <NAME>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.jupiter.europa.entity.ability.spell import com.jupiter.europa.entity.ability.Ability import com.jupiter.europa.entity.stats.characterclass.CharacterClass import org.reflections.Reflections /** * Created by nathan on 5/25/15. */ public object Spells { // Constants private val spellReflections = Reflections("com.jupiter.europa") private val spellTypes: Set<Class<out Ability>> = spellReflections.getTypesAnnotatedWith(javaClass<Spell>(), true) .filter { type -> javaClass<Ability>().isAssignableFrom(type) } .map { type -> type as? java.lang.Class<out Ability> } .filterNotNull() .toSet() private val SPELL_LIST: Map<Class<out CharacterClass>, Map<Int, Set<Class<out Ability>>>> = spellTypes .groupBy({ type -> type.getAnnotation(javaClass<Spell>()).characterClass }) .mapValues { entry -> entry.getValue().groupBy { spellType -> spellType.getAnnotation(javaClass<Spell>()).level } .mapValues { entry -> entry.getValue().toSet() } } private val EMPTY: Set<Class<out Ability>> = setOf() // Static Methods public fun getSpells(characterClass: Class<out CharacterClass>, level: Int): Set<Class<out Ability>> { if (SPELL_LIST.containsKey(characterClass)) { val spells = SPELL_LIST.get(characterClass) if (spells != null && spells.containsKey(level)) { return spells.get(level) ?: EMPTY } } return EMPTY } }
0
Kotlin
0
2
53129de6e9d293f5603f8e8a30824d4de2deb93e
2,721
legends-of-omterra
MIT License
app/src/main/java/brandonhogan/com/liftscout/ui/main/MainViewModel.kt
BrandonMHogan
148,831,992
false
null
package brandonhogan.com.liftscout.ui.main import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class MainViewModel : ViewModel() { object _data: MutableLiveData<String>() fun data(): MutableLiveData<String> { return _data } init { } // private val _data = MutableLiveData<String>() // // val data: MutableLiveData<String> // // init { // _data.value = "Hello Whatever!" // } }
0
Kotlin
0
0
ffce19f8211bb358bb3c17f427834bfb0f90c8a0
494
LiftScout-Android-older
Apache License 2.0
app/src/test/kotlin/jp/co/yumemi/android/code_check/viewModels/MockSearchViewModel.kt
takarabe-hamuyatti
447,246,733
false
{"Kotlin": 26566}
package jp.co.yumemi.android.code_check.viewModels import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import jp.co.yumemi.android.code_check.viewModels.SearchViewModel.Companion.SORT_NOT_UPDATED import jp.co.yumemi.android.code_check.viewModels.SearchViewModel.Companion.SORT_POPULAR import jp.co.yumemi.android.code_check.viewModels.SearchViewModel.Companion.SORT_UPDATED import kotlinx.coroutines.launch import java.util.* class MockSearchViewModel : ViewModel() { private var _sortKind = MutableLiveData(SORT_UPDATED) val sortKind: LiveData<String> get() = _sortKind fun onClickUpdatedRepository() { _sortKind.value = SORT_UPDATED } fun onClickNotUpdatedRepository() { _sortKind.value = SORT_NOT_UPDATED } fun onClickPopularRepository() { _sortKind.value = SORT_POPULAR } }
9
Kotlin
0
0
e3b7694d4f679e41e8ed4f4060ed72a38f00816d
949
android-codcheck-takarabe
Apache License 2.0
app/src/main/java/dev/sebastiano/bundel/navigation/LicensesScreen.kt
code-with-the-italians
362,199,267
false
null
package dev.sebastiano.bundel.navigation import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import dev.sebastiano.bundel.R import dev.sebastiano.bundel.preferences.DependenciesModel import dev.sebastiano.bundel.preferences.PreferencesTopAppBar import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.json.Json import kotlinx.serialization.json.decodeFromStream @OptIn(ExperimentalMaterial3Api::class, ExperimentalSerializationApi::class) @Composable internal fun LicensesScreen(onBackPress: () -> Unit) { var licenses by remember { mutableStateOf(listOf<DependenciesModel.Dependency>()) } val assetManager = LocalContext.current.resources.assets LaunchedEffect(key1 = Unit) { // TODO THIS IS STUPID. Move to a VM and save your soul launch(Dispatchers.IO) { assetManager.open("licences.json").use { val json: Json = Json.Default licenses = json.decodeFromStream(it) as List<DependenciesModel.Dependency> } } } // TODO deshittify this Scaffold( modifier = Modifier.fillMaxWidth(), topBar = { PreferencesTopAppBar(title = stringResource(id = R.string.preferences_licenses_title), onBackPress = onBackPress) } ) { paddingValues -> if (licenses == null) { Box(modifier = Modifier.padding(paddingValues), contentAlignment = Alignment.Center) { Text(text = "Nothing?!?!") } } else { LazyColumn(Modifier.padding(paddingValues)) { items(licenses) { Text(it.name ?: it.coordinates) } } } } }
4
Kotlin
22
243
01e0945be1787bc6ac7b9765f63599ab33d85e2d
2,521
bundel
Apache License 2.0
app/src/main/kotlin/io/github/bsfranca2/athena/dto/TesteDto.kt
bsfranca2
275,465,877
false
null
package io.github.bsfranca2.athena.dto import javax.validation.Valid import javax.validation.constraints.Email import javax.validation.constraints.NotBlank import javax.validation.constraints.NotNull data class TesteDto(@field:Valid val pessoas: List<PessoaDto>) data class PessoaDto(@field:Email val email: String, @field:Email @field:NotBlank val secondaryEmail: String)
11
Kotlin
0
0
8a048990c1a6ebf23a567490476fc7e41fdadc71
376
Athena
MIT License
src/main/kotlin/be/zvz/semy/utils/ClovaManager.kt
JellyBrick
650,763,916
false
null
package be.zvz.semy.utils import be.zvz.clova.Clova object ClovaManager { private val clova = Clova() val ocr = clova.ocr.getValue(Clova.OCR.PAPAGO) val speech = clova.tts.getValue(Clova.TTS.CLOVA) val translate = clova.translation.getValue(Clova.Translation.N2MT) }
2
Kotlin
0
0
e200bb7aaefee96d7fc959bb4a7e8822529c82e0
284
semy
Apache License 2.0
src/commonMain/kotlin/maryk/rocksdb/TransactionOptions.kt
webnah
195,759,908
true
{"Kotlin": 707302}
package maryk.rocksdb expect class TransactionOptions() : RocksObject { fun isSetSnapshot(): Boolean fun setSetSnapshot(setSnapshot: Boolean): TransactionOptions /** * True means that before acquiring locks, this transaction will * check if doing so will cause a deadlock. If so, it will return with * [Status.Code.Busy]. The user should retry their transaction. * * @return true if a deadlock is detected. */ fun isDeadlockDetect(): Boolean /** * Setting to true means that before acquiring locks, this transaction will * check if doing so will cause a deadlock. If so, it will return with * [Status.Code.Busy]. The user should retry their transaction. * * @param deadlockDetect true if we should detect deadlocks. * * @return this TransactionOptions instance */ fun setDeadlockDetect(deadlockDetect: Boolean): TransactionOptions /** * The wait timeout in milliseconds when a transaction attempts to lock a key. * * If 0, no waiting is done if a lock cannot instantly be acquired. * If negative, [TransactionDBOptions.getTransactionLockTimeout] * will be used * * @return the lock timeout in milliseconds */ fun getLockTimeout(): Long /** * If positive, specifies the wait timeout in milliseconds when * a transaction attempts to lock a key. * * If 0, no waiting is done if a lock cannot instantly be acquired. * If negative, [TransactionDBOptions.getTransactionLockTimeout] * will be used * * Default: -1 * * @param lockTimeout the lock timeout in milliseconds * * @return this TransactionOptions instance */ fun setLockTimeout(lockTimeout: Long): TransactionOptions /** * Expiration duration in milliseconds. * * If non-negative, transactions that last longer than this many milliseconds * will fail to commit. If not set, a forgotten transaction that is never * committed, rolled back, or deleted will never relinquish any locks it * holds. This could prevent keys from being written by other writers. * * @return expiration the expiration duration in milliseconds */ fun getExpiration(): Long /** * Expiration duration in milliseconds. * * If non-negative, transactions that last longer than this many milliseconds * will fail to commit. If not set, a forgotten transaction that is never * committed, rolled back, or deleted will never relinquish any locks it * holds. This could prevent keys from being written by other writers. * * Default: -1 * * @param expiration the expiration duration in milliseconds * * @return this TransactionOptions instance */ fun setExpiration(expiration: Long): TransactionOptions /** * Gets the number of traversals to make during deadlock detection. * * @return the number of traversals to make during * deadlock detection */ fun getDeadlockDetectDepth(): Long /** * Sets the number of traversals to make during deadlock detection. * * Default: 50 * * @param deadlockDetectDepth the number of traversals to make during * deadlock detection * * @return this TransactionOptions instance */ fun setDeadlockDetectDepth( deadlockDetectDepth: Long ): TransactionOptions /** * Get the maximum number of bytes that may be used for the write batch. * * @return the maximum number of bytes, 0 means no limit. */ fun getMaxWriteBatchSize(): Long /** * Set the maximum number of bytes that may be used for the write batch. * * @param maxWriteBatchSize the maximum number of bytes, 0 means no limit. * * @return this TransactionOptions instance */ fun setMaxWriteBatchSize(maxWriteBatchSize: Long): TransactionOptions }
0
Kotlin
0
0
92ec1677df1646d817abfd434929d27d430ec319
3,962
rocksdb
Apache License 2.0
app/src/main/java/ru/mobile/lukslol/di/module/RepositoryModule.kt
silverxcoins
260,674,124
false
{"Kotlin": 73778}
package ru.mobile.lukslol.di.module import dagger.Module import dagger.Provides import ru.mobile.lukslol.domain.repository.FeedRepository import ru.mobile.lukslol.domain.repository.SummonerRepository import ru.mobile.lukslol.domain.repository.impl.FeedRepositoryImpl import ru.mobile.lukslol.domain.repository.impl.SummonerRepositoryImpl import ru.mobile.lukslol.service.db.Database import ru.mobile.lukslol.service.network.NetworkManager import ru.mobile.lukslol.service.prefs.Prefs import javax.inject.Singleton @Module class RepositoryModule { @Singleton @Provides fun provideSummonerRepository(networkManager: NetworkManager, db: Database, prefs: Prefs): SummonerRepository { return SummonerRepositoryImpl(networkManager, db, prefs) } @Singleton @Provides fun provideFeedRepository(networkManager: NetworkManager, db: Database, prefs: Prefs): FeedRepository { return FeedRepositoryImpl(networkManager, db, prefs) } }
0
Kotlin
0
1
bdedaf16c62777f413e56d0d3a0b1336d1966d98
972
LukS-LoL-Tracker
Apache License 2.0
transport/src/commonMain/kotlin/com/genesys/cloud/messenger/transport/shyrka/receive/PresignedUrlResponse.kt
MyPureCloud
425,920,457
false
{"Kotlin": 475567, "Swift": 107568, "Shell": 5872, "Ruby": 4062}
package com.genesys.cloud.messenger.transport.shyrka.receive import kotlinx.serialization.Serializable @Serializable internal data class PresignedUrlResponse( val attachmentId: String, val headers: Map<String, String>, val url: String, val fileName: String? = null, val fileSize: Int? = null, val fileType: String? = null )
1
Kotlin
6
9
2679aa5fe48c362bc95a6ef2629f6cc41a12a0f4
350
genesys-messenger-transport-mobile-sdk
MIT License
src/test/kotlin/dsl11.getter/LinkSpec.kt
C06A
127,220,753
false
null
package dsl11.getter import io.kotlintest.matchers.* import io.kotlintest.specs.StringSpec import java.net.URI import java.util.* class LinkSpec: StringSpec() { init { val linkList = listOf<Link>( "relation" link "address", "relation" link { HREF["address"] TYPE["image/*"] HREFLANG[Locale.CHINESE.toLanguageTag()] NAME["test name"] TITLE["test title"] PROFILE["test profile"] DEPRECATION["deprecation+info"] TEMPLATED["true"] }, "relation" link { PROFILE["test profile"] HREF["address"] TEMPLATED["true"] DEPRECATION["deprecation+info"] TITLE["test title"] NAME["test name"] HREFLANG["zh"] TYPE["image/*"] } ) val linkMin = linkList[0] val linkMax = linkList[1] val linkByNames = linkList[2] "link with minimal set" { val link = linkMin link.rel shouldBe "relation" link.href.toString() shouldBe "address" link.type shouldBe "application/hal+json" link.hreflang shouldBe null link.name shouldBe null link.title shouldBe null link.profile shouldBe null link.deprecation shouldBe null link.templated shouldBe null } "link with whole set by order" { val link = linkMax link.rel shouldBe "relation" link.href.toString() shouldBe "address" link.type shouldBe "image/*" link.hreflang shouldBe Locale.CHINESE link.name shouldBe "test name" link.title shouldBe "test title" link.profile shouldBe "test profile" link.deprecation.toString() shouldBe "deprecation+info" link.templated shouldBe true } "link with whole set by names" { val link = linkByNames link.rel shouldBe "relation" link.href.toString() shouldBe "address" link.type shouldBe "image/*" link.hreflang shouldBe Locale.CHINESE link.name shouldBe "<NAME>" link.title shouldBe "test title" link.profile shouldBe "test profile" link.deprecation.toString() shouldBe "deprecation+info" link.templated shouldBe true } "minimal Link.toString()" { val link = linkMin link.toString() shouldBe listOf<String>( "\"relation\":{", "\"href\":\"address\",", "\"type\":\"application/hal+json\"", "}").joinToString("") } "Link.toString()" { val link = linkByNames link.toString() shouldBe listOf<String>( "\"relation\":{", "\"href\":\"address\",", "\"type\":\"image/*\",", "\"hreflang\":\"zh\",", "\"templated\":\"true\",", "\"name\":\"<NAME>\",", "\"title\":\"test title\",", "\"profile\":\"test profile\",", "\"deprecation\":\"deprecation+info\"", "}").joinToString("") } "Invalid parameters" { val e = shouldThrow<IllegalArgumentException> { "" link URI("") } val msg = e.message when (msg) { null -> AssertionError("Message in exception cannot be null") is String -> msg should include("'rel'") } } "Empty link" { val e = shouldThrow<IllegalArgumentException> { "empty" link { } } val msg = e.message println(msg) when (msg) { null -> AssertionError("Message in exception cannot be null") is String -> msg should include("empty") } } } }
0
Kotlin
0
0
afeb540b7060f7ddf01427158205b3a96b3a8fc0
4,275
ExampleDSL
Apache License 2.0
android/app/src/main/kotlin/be/chiahpa/khiin/keyboard/components/IconKey.kt
OMAMA-Taioan
634,144,761
false
{"Rust": 354725, "Kotlin": 48490, "Swift": 45584, "Svelte": 12104, "Shell": 5204, "C": 4007, "PowerShell": 3819, "JavaScript": 1756, "TypeScript": 1623, "CSS": 721, "HTML": 371}
package be.chiahpa.khiin.keyboard.components import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Image import androidx.compose.foundation.border import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.size import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp @Composable fun RowScope.IconKey( icon: Int, weight: Float = 1f, keyColor: Color = Color.Transparent, tint: Color = MaterialTheme.colorScheme.onSurface, cornerSize: Dp = 12.dp, onClick: () -> Unit = {} ) { BaseKey( weight = weight, keyColor = keyColor, cornerSize = cornerSize, ) { Image( painterResource(id = icon), null, modifier = Modifier.size(32.dp), colorFilter = ColorFilter.tint(tint) ) } }
4
Rust
3
8
9a7ad181c68470817a887ba92282e481f3c41c38
1,272
khiin-rs
MIT License
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/BrandCucumber.kt
walter-juan
868,046,028
false
{"Kotlin": 34345428}
package com.woowla.compose.icon.collections.tabler.tabler.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Round import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup public val OutlineGroup.BrandCucumber: ImageVector get() { if (_brandCucumber != null) { return _brandCucumber!! } _brandCucumber = Builder(name = "BrandCucumber", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(20.0f, 10.99f) curveToRelative(-0.01f, 5.52f, -4.48f, 10.0f, -10.0f, 10.01f) verticalLineToRelative(-2.26f) lineToRelative(-0.01f, -0.01f) curveToRelative(-4.28f, -1.11f, -6.86f, -5.47f, -5.76f, -9.75f) arcToRelative(8.0f, 8.0f, 0.0f, false, true, 9.74f, -5.76f) curveToRelative(3.53f, 0.91f, 6.03f, 4.13f, 6.03f, 7.78f) verticalLineToRelative(-0.01f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(10.5f, 8.0f) lineToRelative(-0.5f, -1.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(13.5f, 14.0f) lineToRelative(0.5f, 1.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(9.0f, 12.5f) lineToRelative(-1.0f, 0.5f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(11.0f, 14.0f) lineToRelative(-0.5f, 1.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(13.0f, 8.0f) lineToRelative(0.5f, -1.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(16.0f, 12.5f) lineToRelative(-1.0f, -0.5f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(9.0f, 10.0f) lineToRelative(-1.0f, -0.5f) } } .build() return _brandCucumber!! } private var _brandCucumber: ImageVector? = null
0
Kotlin
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
4,541
compose-icon-collections
MIT License
kotlin_adapter/adapter_exension/stickyHeader/StickyAdapterInterface.kt
Jay-YaoJie
164,579,725
false
null
package kotlin_adapter.adapter_exension.stickyHeader import android.view.ViewGroup /** * Created by liufei on 2017/12/4. */ interface StickyAdapterInterface<VH> { fun getHeaderId(position: Int): Long fun onCreateHeaderViewHolder(parent: ViewGroup, position: Int): VH? fun onBindHeaderViewHolder(holder: VH, position: Int) }
0
Kotlin
0
2
0eba3da933e8db7a0738f36e9b26144afe249b0f
344
kotlin---RecyclerViewAdapter
Apache License 2.0
testing/src/main/kotlin/testing/ClassMapper.kt
Mr-Mappie
808,724,827
false
{"Kotlin": 71204, "CSS": 52879, "SCSS": 27835, "HTML": 19024, "JavaScript": 10402}
package testing import tech.mappie.api.ObjectMappie class Class( private val field: String, argument: Int, ) class ClassDto( field: String, val argument: Int ) { override fun equals(other: Any?): Boolean { if (other != null && other is ClassDto) { return argument == other.argument } return false } override fun hashCode() = argument.hashCode() } object ClassMapper : ObjectMappie<Class, ClassDto>() { override fun map(from: Class) = mapping { ClassDto::argument fromConstant 1 } }
8
Kotlin
0
0
0d2f9f2a3024100f8c65cd97c0254f0d2541116e
574
mappie
Apache License 2.0
src/Day12.kt
li-xin-yi
573,617,763
false
null
fun main() { val directions = listOf((0 to 1), (1 to 0), (0 to -1), (-1 to 0)) fun solvePart1(input: List<String>): Int { val n = input.size val m = input[0].length var (startX, startY) = (0 to 0) for (i in 0 until n) { for (j in 0 until m) { if (input[i][j] == 'S') { startX = i startY = j break } } } val queue = ArrayDeque<List<Int>>() val seen = List(n) { MutableList(m) { false } } seen[startX][startY] = true queue.add(listOf(startX, startY, 0, 'a'.code)) while (queue.isNotEmpty()) { val (x, y, step, key) = queue.removeFirst() for ((dx, dy) in directions) { val (nx, ny) = (x + dx to y + dy) if (nx < 0 || nx >= n || ny < 0 || ny >= m || seen[nx][ny]) continue if (input[nx][ny] == 'E') { if (key + 1 >= 'z'.code) return step + 1 continue } if (input[nx][ny].code > key + 1) continue seen[nx][ny] = true queue.add(listOf(nx, ny, step + 1, input[nx][ny].code)) } } return 0 } fun solvePart2(input: List<String>): Int { val n = input.size val m = input[0].length var (startX, startY) = (0 to 0) for (i in 0 until n) { for (j in 0 until m) { if (input[i][j] == 'E') { startX = i startY = j break } } } val queue = ArrayDeque<List<Int>>() val seen = List(n) { MutableList(m) { false } } seen[startX][startY] = true queue.add(listOf(startX, startY, 0, 'z'.code)) while (queue.isNotEmpty()) { val (x, y, step, key) = queue.removeFirst() for ((dx, dy) in directions) { val (nx, ny) = (x + dx to y + dy) if (nx < 0 || nx >= n || ny < 0 || ny >= m || seen[nx][ny]) continue if (input[nx][ny] == 'S' || input[nx][ny] == 'a') { if (key <= 'a'.code + 1) return step + 1 continue } if (input[nx][ny].code < key - 1) continue seen[nx][ny] = true queue.add(listOf(nx, ny, step + 1, input[nx][ny].code)) } } return 0 } val testInput = readInput("input/Day12_test") check(solvePart1(testInput) == 31) check(solvePart2(testInput) == 29) val input = readInput("input/Day12_input") println(solvePart1(input)) println(solvePart2(input)) }
0
Kotlin
0
1
fb18bb7e462b8b415875a82c5c69962d254c8255
2,827
AoC-2022-kotlin
Apache License 2.0
src/Day12.kt
li-xin-yi
573,617,763
false
null
fun main() { val directions = listOf((0 to 1), (1 to 0), (0 to -1), (-1 to 0)) fun solvePart1(input: List<String>): Int { val n = input.size val m = input[0].length var (startX, startY) = (0 to 0) for (i in 0 until n) { for (j in 0 until m) { if (input[i][j] == 'S') { startX = i startY = j break } } } val queue = ArrayDeque<List<Int>>() val seen = List(n) { MutableList(m) { false } } seen[startX][startY] = true queue.add(listOf(startX, startY, 0, 'a'.code)) while (queue.isNotEmpty()) { val (x, y, step, key) = queue.removeFirst() for ((dx, dy) in directions) { val (nx, ny) = (x + dx to y + dy) if (nx < 0 || nx >= n || ny < 0 || ny >= m || seen[nx][ny]) continue if (input[nx][ny] == 'E') { if (key + 1 >= 'z'.code) return step + 1 continue } if (input[nx][ny].code > key + 1) continue seen[nx][ny] = true queue.add(listOf(nx, ny, step + 1, input[nx][ny].code)) } } return 0 } fun solvePart2(input: List<String>): Int { val n = input.size val m = input[0].length var (startX, startY) = (0 to 0) for (i in 0 until n) { for (j in 0 until m) { if (input[i][j] == 'E') { startX = i startY = j break } } } val queue = ArrayDeque<List<Int>>() val seen = List(n) { MutableList(m) { false } } seen[startX][startY] = true queue.add(listOf(startX, startY, 0, 'z'.code)) while (queue.isNotEmpty()) { val (x, y, step, key) = queue.removeFirst() for ((dx, dy) in directions) { val (nx, ny) = (x + dx to y + dy) if (nx < 0 || nx >= n || ny < 0 || ny >= m || seen[nx][ny]) continue if (input[nx][ny] == 'S' || input[nx][ny] == 'a') { if (key <= 'a'.code + 1) return step + 1 continue } if (input[nx][ny].code < key - 1) continue seen[nx][ny] = true queue.add(listOf(nx, ny, step + 1, input[nx][ny].code)) } } return 0 } val testInput = readInput("input/Day12_test") check(solvePart1(testInput) == 31) check(solvePart2(testInput) == 29) val input = readInput("input/Day12_input") println(solvePart1(input)) println(solvePart2(input)) }
0
Kotlin
0
1
fb18bb7e462b8b415875a82c5c69962d254c8255
2,827
AoC-2022-kotlin
Apache License 2.0
src/main/kotlin/io/github/perracodex/ktor/config/IConfigCatalog.kt
perracodex
864,818,115
false
{"Kotlin": 20783}
/* * Copyright (c) 2024-Present Perracodex. Use of this source code is governed by an MIT license. */ package io.github.perracodex.ktor.config /** * Interface for the configuration catalog holding each of the [IConfigCatalogSection] settings. * * @see IConfigCatalogSection */ public interface IConfigCatalog /** * Interface for each concrete configuration section within the [IConfigCatalog] implementation. * * @see IConfigCatalog */ public interface IConfigCatalogSection
0
Kotlin
0
0
8e33f64f0222ffc98d6f043e91a77e74c0873870
488
ktor-config
MIT License
src/test/kotlin/ktPyString/PythonCompliantSliceTests.kt
ChanTsune
200,603,776
false
{"Kotlin": 190063}
package ktPyString import kotlin.test.* class PythonCompliantSliceTests { @Test fun test_cmp() { val s1 = Slice(1, 2, 3) val s2 = Slice(1, 2, 3) val s3 = Slice(1, 2, 4) assertEquals(s1, s2) assertNotEquals(s1, s3) } @Test fun test_members() { var s = Slice(1) assertEquals(s.start, null) assertEquals(s.stop, 1) assertEquals(s.step, null) s = Slice(1, 2) assertEquals(s.start, 1) assertEquals(s.stop, 2) assertEquals(s.step, null) s = Slice(1, 2, 3) assertEquals(s.start, 1) assertEquals(s.stop, 2) assertEquals(s.step, 3) } @Test fun test_indices() { assertEquals(Slice(null).indices(10), Triple(0, 10, 1)) assertEquals(Slice(null, null, 2).indices(10), Triple(0, 10, 2)) assertEquals(Slice(1, null, 2).indices(10), Triple(1, 10, 2)) assertEquals(Slice(null, null, -1).indices(10), Triple(9, -1, -1)) assertEquals(Slice(null, null, -2).indices(10), Triple(9, -1, -2)) assertEquals(Slice(3, null, -2).indices(10), Triple(3, -1, -2)) assertEquals(Slice(null, -9).indices(10), Triple(0, 1, 1)) assertEquals(Slice(null, -10).indices(10), Triple(0, 0, 1)) assertEquals(Slice(null, -11).indices(10), Triple(0, 0, 1)) assertEquals(Slice(null, -10, -1).indices(10), Triple(9, 0, -1)) assertEquals(Slice(null, -11, -1).indices(10), Triple(9, -1, -1)) assertEquals(Slice(null, -12, -1).indices(10), Triple(9, -1, -1)) assertEquals(Slice(null, 9).indices(10), Triple(0, 9, 1)) assertEquals(Slice(null, 10).indices(10), Triple(0, 10, 1)) assertEquals(Slice(null, 11).indices(10), Triple(0, 10, 1)) assertEquals(Slice(null, 8, -1).indices(10), Triple(9, 8, -1)) assertEquals(Slice(null, 9, -1).indices(10), Triple(9, 9, -1)) assertEquals(Slice(null, 10, -1).indices(10), Triple(9, 9, -1)) assertEquals(Slice(-100, 100).indices(10), Slice(null).indices(10)) assertEquals(Slice(100, -100, -1).indices(10), Slice(null, null, -1).indices(10)) assertEquals(Slice(-100, 100, 2).indices(10), Triple(0, 10, 2)) } }
3
Kotlin
0
0
e3620ff0f88c80c7a358cb9c679798242035f276
2,239
ktPyString
MIT License
common/src/main/java/com/laposa/common/features/common/composables/selectDialog/SelectDialog.kt
laposa
796,639,770
false
{"Kotlin": 274304}
package com.laposa.common.features.common.composables.selectDialog import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.tv.material3.Border import androidx.tv.material3.Card import androidx.tv.material3.CardDefaults import androidx.tv.material3.Icon import androidx.tv.material3.ListItem import androidx.tv.material3.MaterialTheme import androidx.tv.material3.MaterialTheme.colorScheme import androidx.tv.material3.Text import ie.laposa.common.R @OptIn(ExperimentalMaterial3Api::class) @Composable fun <T> SelectDialog( value: T, title: String, getOptionTitle: (T) -> String, options: List<T>, focusRequester: FocusRequester? = null, onOptionSelected: (T) -> Unit, ) { val connectionTypeDialogFocusRequester = FocusRequester() val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) var isDialogVisible by remember { mutableStateOf(false) } LaunchedEffect(isDialogVisible) { if (isDialogVisible) { connectionTypeDialogFocusRequester.requestFocus() } } Card( modifier = (focusRequester?.let { Modifier .height(70.dp) .focusRequester(it) } ?: Modifier.height(70.dp)).testTag("select_dialog_$title"), colors = CardDefaults.colors( containerColor = Color.Transparent, ), onClick = { isDialogVisible = true }, border = CardDefaults.border( border = Border( border = BorderStroke( 1.dp, colorScheme.border ) ), focusedBorder = Border( border = BorderStroke( 2.dp, Color.White, ) ) ), scale = CardDefaults.scale(focusedScale = 1.025f), ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxHeight() .padding(16.dp) ) { Column { Text( text = title, color = colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodyLarge ) Spacer(modifier = Modifier.height(4.dp)) Text( text = getOptionTitle(value), style = MaterialTheme.typography.bodyMedium, textAlign = TextAlign.Start, color = colorScheme.onSurfaceVariant ) } Spacer(modifier = Modifier.weight(1f)) Icon( painter = painterResource(id = if (isDialogVisible) R.drawable.ic_arrow_drop_up else R.drawable.ic_arrow_drop_down), contentDescription = null, modifier = Modifier.size(32.dp) ) } } if (!isDialogVisible) return ModalBottomSheet( onDismissRequest = { isDialogVisible = false }, containerColor = colorScheme.surfaceVariant, sheetState = sheetState ) { Column(modifier = Modifier.padding(32.dp)) { Text( text = title, style = MaterialTheme.typography.headlineSmall, textAlign = TextAlign.Center ) Spacer(modifier = Modifier.height(16.dp)) options.forEachIndexed { index, it -> ListItem(selected = false, headlineContent = { Text(getOptionTitle(it)) }, modifier = if (index == 0) Modifier.focusRequester( connectionTypeDialogFocusRequester ) else Modifier, onClick = { onOptionSelected(it) isDialogVisible = false }) } } } }
4
Kotlin
0
2
b0f5964f7e62f8070577465a5199a386f4cdfb19
5,073
media-player
MIT License
app/src/main/java/com/example/mysurfapp/MyScreen.kt
adatechschool
793,549,577
false
{"Kotlin": 12471}
package com.example.mysurfapp import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.PlatformTextStyle import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.em import androidx.compose.ui.unit.sp import androidx.navigation.NavController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController @Composable fun MyScreen(navController: NavController) { MaterialTheme { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { // Background Image Image( painter = painterResource(id = R.drawable.surfhome), contentDescription = null, modifier = Modifier.fillMaxSize(), contentScale = androidx.compose.ui.layout.ContentScale.Crop ) // Transparent Box Box( modifier = Modifier.size(381.dp, 466.dp) .clip(RoundedCornerShape(16.dp)) .background(Color(0x40FFFFFF)) // Custom color .padding(16.dp), contentAlignment = Alignment.Center ) { // Align elements in center like a column Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { // Title TextView Text( text = "THE PERFECT SPOTS", textAlign = TextAlign.Center, lineHeight = 1.em, fontSize = 44.sp, color = Color.White, // Custom text color modifier = Modifier.padding(top = 16.dp), ) // Start Button Button( onClick = { navController.navigate("surf_spots") // Todo: Handle button click (e.g., navigation or action) }, modifier = Modifier.padding(top = 16.dp) ) { Text(text = "Start") } } } } } } @Preview @Composable fun PreviewMyScreen() { val navController = rememberNavController() NavHost(navController, startDestination = "home") { composable("home") { MyScreen(navController) } } }
0
Kotlin
0
0
2f1bb5951e30d97fc76aff484b131324535b8290
3,270
projet-collectif-mobile-front-surfspots
MIT License
shared/mvi/src/commonMain/kotlin/com/badoo/kmpmvi/shared/mvi/Store.kt
badoo
256,260,923
false
null
package com.badoo.kmpmvi.shared.mvi import com.badoo.reaktive.base.Consumer import com.badoo.reaktive.disposable.Disposable import com.badoo.reaktive.observable.Observable interface Store<in Intent : Any, out State : Any> : Consumer<Intent>, Observable<State>, Disposable { val state: State }
0
Kotlin
10
69
d9b6a23d5a3aae001c455776f797d36d13dad7ac
300
KmpMvi
Apache License 2.0
plugin/project-plugin/src/main/kotlin/jpa/unit/Repository.kt
top-bettercode
387,652,015
false
null
package jpa.unit import ProjectGenerator import top.bettercode.generator.dom.java.JavaType import top.bettercode.generator.dom.java.element.Interface /** * @author <NAME> */ val repository: ProjectGenerator.(Interface) -> Unit = { unit -> unit.apply { javadoc { +"/**" +" * $remarks 数据层" +" */" } implement( JavaType("top.bettercode.simpleframework.data.jpa.BaseRepository").typeArgument( entityType, primaryKeyType ) ) } }
0
Kotlin
0
1
352c0a288c47139b1bf4d286dc57b2b25c4e7938
560
summer
Apache License 2.0
app/src/main/java/com/wreckingballsoftware/design/ui/compose/DeSignFab.kt
leewaggoner
698,812,124
false
{"Kotlin": 132764}
package com.wreckingballsoftware.design.ui.compose import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Add import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import com.wreckingballsoftware.design.R import com.wreckingballsoftware.design.ui.theme.customColorsPalette @Composable fun DeSignFab( modifier: Modifier = Modifier, onClick: () -> Unit, ) { Box( modifier = Modifier .fillMaxSize() ) { FloatingActionButton( modifier = modifier.then( Modifier .align(alignment = Alignment.BottomEnd), ), onClick = onClick, containerColor = MaterialTheme.customColorsPalette.tertiary ) { Icon( imageVector = Icons.Outlined.Add, contentDescription = stringResource(id = R.string.create_campaign), ) } } } @Preview(name = "DeSignFab Preview") @Composable fun DeSignFabPreview() { DeSignFab { } }
0
Kotlin
0
0
a939ead8c4bc7c8bb55e5e9e0eada400bc67ffd0
1,439
design
Apache License 2.0
redwood-gradle-plugin/src/main/kotlin/app/cash/redwood/gradle/RedwoodComposeExtension.kt
cashapp
305,409,146
false
{"Kotlin": 1915304, "Swift": 13738, "Java": 1583, "Objective-C": 1499, "Shell": 253, "HTML": 235, "C": 43}
/* * Copyright (C) 2023 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.cash.redwood.gradle import org.gradle.api.Action import org.gradle.api.provider.Property public interface RedwoodComposeExtension { /** * The version of the JetBrains Compose compiler to use, or a Maven coordinate triple of * the custom Compose compiler to use. * * Example: using a custom version of the JetBrains Compose compiler * ```kotlin * redwood { * kotlinCompilerPlugin.set("1.4.8") * } * ``` * * Example: using a custom Maven coordinate for the Compose compiler * ```kotlin * redwood { * kotlinCompilerPlugin.set("com.example:custom-compose-compiler:1.0.0") * } * ``` */ public val kotlinCompilerPlugin: Property<String> /** * Configuration options that require extra care when used. * * @see DangerZone */ public fun dangerZone(body: Action<DangerZone>) /** * Configuration options that require extra care when used. Please read the documentation of * each member carefully to understand how it affects your build. */ public interface DangerZone { /** * Enable the output of metrics from the Compose compiler. * * Text files will be written to `generated/redwood/compose-metrics/` in the project's build * directory. See * [the compiler documentation](https://github.com/androidx/androidx/blob/androidx-main/compose/compiler/design/compiler-metrics.md#reports-breakdown) * for more information about the contents. * * **NOTE:** This should only be enabled during investigation as it breaks the use of * Gradle's build cache for this project's Kotlin compilation tasks. * * @see enableReports */ public fun enableMetrics() /** * Enable the output of reports from the Compose compiler. * * Text files will be written to `generated/redwood/compose-reports/` in the project's build * directory. See * [the compiler documentation](https://github.com/androidx/androidx/blob/androidx-main/compose/compiler/design/compiler-metrics.md#reports-breakdown) * for more information about the contents. * * **NOTE:** This should only be enabled during investigation as it breaks the use of * Gradle's build cache for this project's Kotlin compilation tasks. * * @see enableMetrics */ public fun enableReports() } }
117
Kotlin
64
1,495
8e0d63f26fed367ba98c1e0123e4bc0a38cb854e
2,955
redwood
Apache License 2.0
telegramit-core/src/main/kotlin/org/botlaxy/telegramit/core/client/model/TelegramChatPermissions.kt
vitaxa
258,866,097
false
null
package org.botlaxy.telegramit.core.client.model import com.fasterxml.jackson.annotation.JsonProperty data class TelegramChatPermissions( @get:JsonProperty("can_send_messages") var canSendMesssage: Boolean, @get:JsonProperty("can_send_media_messages") var canSendMediaMessages: Boolean, @get:JsonProperty("can_send_polls") var canSendPolls: Boolean, @get:JsonProperty("can_send_other_messages") var canSendOtherMessages: Boolean, @get:JsonProperty("can_add_web_page_previews") var canAddWebPagePreviews: Boolean, @get:JsonProperty("can_change_info") var canChangeInfo: Boolean, @get:JsonProperty("can_invite_users") var canInviteUsers: Boolean, @get:JsonProperty("can_pin_messages") var canPinMessages: Boolean )
0
Kotlin
2
9
2e7fdb9e1e3edf2638d7dbb0895b4f8a10fbaa43
779
telegramit
Apache License 2.0
app/src/main/java/wrproject/com/sample_mvvm/util/NetworkUtil.kt
Wcisang
120,296,422
false
null
package wrproject.com.sample_mvvm.util import android.content.Context import android.net.ConnectivityManager /** * Created by WCisang on 04/02/2018. */ class NetworkUtil(private var applicationContext: Context) { private var status: Boolean? = false val isConnectedToInternet: Boolean? get() { val conManager = applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val ni = conManager.activeNetworkInfo return ni != null && ni.isConnected } }
0
Kotlin
0
1
2010784c862fecad7c22c1fc63becb8bfc24b741
542
Sample_MVVM_Kotlin_Retrofit
MIT License
core/src/main/java/dev/varshakulkarni/core/repository/HangmanDataSource.kt
Varsha-Kulkarni
614,714,293
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 dev.varshakulkarni.core.repository import dev.varshakulkarni.core.model.Movie import kotlinx.coroutines.flow.Flow interface HangmanDataSource { suspend fun getMovie(): Flow<Movie?> suspend fun updateMovie(movie: Movie) }
0
Kotlin
0
9
3ef034bcf0a605fc513df4abf8d6fef54906bdd7
830
MovieHangman
Apache License 2.0
plot-api/src/commonMain/kotlin/org/jetbrains/letsPlot/intern/layer/stat/BoxplotOutlierStatParameters.kt
JetBrains
172,682,391
false
{"Kotlin": 1563280, "HTML": 24175, "Shell": 73}
/* * Copyright (c) 2023. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package org.jetbrains.letsPlot.intern.layer.stat import org.jetbrains.letsPlot.core.spec.Option import org.jetbrains.letsPlot.intern.Options import org.jetbrains.letsPlot.intern.OptionsCapsule interface BoxplotOutlierStatParameters : OptionsCapsule { @Suppress("SpellCheckingInspection") val coef: Number? // Whisker IQR ratio override fun seal() = Options.of( Option.Stat.Boxplot.COEF to coef ) }
14
Kotlin
36
433
f6edab1a67783d14e2378675f065ef7111bdc1a0
570
lets-plot-kotlin
MIT License
app/src/main/java/fr/smarquis/appstore/Utils.kt
menukaonline
160,306,230
true
{"Kotlin": 129107, "JavaScript": 73915, "HTML": 19525, "Java": 3310, "CSS": 2280}
package fr.smarquis.appstore import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build.VERSION.SDK_INT import android.os.Build.VERSION_CODES.* import android.provider.Settings import android.text.Html import android.text.Spanned import android.text.format.DateUtils import android.text.format.DateUtils.FORMAT_ABBREV_RELATIVE import android.text.format.DateUtils.SECOND_IN_MILLIS import androidx.core.content.pm.PackageInfoCompat import androidx.core.view.doOnNextLayout import androidx.recyclerview.widget.RecyclerView class Utils { companion object { fun isAtLeast(versionCode: Int): Boolean { return SDK_INT >= versionCode } fun isApplicationInstalled(context: Context, packageName: String): Boolean { return try { context.packageManager.getPackageInfo(packageName, 0) true } catch (e: PackageManager.NameNotFoundException) { false } } fun applicationVersionName(context: Context, packageName: String): String? { return try { context.packageManager.getPackageInfo(packageName, 0).versionName } catch (e: PackageManager.NameNotFoundException) { null } } fun applicationVersionCode(context: Context, packageName: String): Long { return try { PackageInfoCompat.getLongVersionCode(context.packageManager.getPackageInfo(packageName, 0)) } catch (e: PackageManager.NameNotFoundException) { 0 } } fun applicationLastUpdateTime(context: Context, packageName: String): Long? { return try { context.packageManager.getPackageInfo(packageName, 0).lastUpdateTime } catch (e: PackageManager.NameNotFoundException) { null } } fun getLaunchIntent(context: Context, packageName: String): Intent? { return context.packageManager.getLaunchIntentForPackage(packageName) } fun getDetailsIntent(packageName: String): Intent { return Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", packageName, null)) } fun getDeleteIntent(packageName: String): Intent { return Intent(Intent.ACTION_DELETE, Uri.fromParts("package", packageName, null)) } fun getMarketIntent(packageName: String): Intent { return Intent(Intent.ACTION_VIEW, Uri.Builder().scheme("market").authority("details").appendQueryParameter("id", packageName).build()) } fun notificationSettingsIntent(context: Context, channelId: String? = null, openChannel: Boolean = true): Intent { return when { SDK_INT >= O -> { val action = if (channelId != null && openChannel) Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS else Settings.ACTION_APP_NOTIFICATION_SETTINGS Intent(action).apply { putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName) putExtra(Settings.EXTRA_CHANNEL_ID, channelId) } } SDK_INT > N_MR1 -> { Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).apply { putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName) } } SDK_INT >= LOLLIPOP -> { Intent("android.settings.APP_NOTIFICATION_SETTINGS").apply { putExtra("app_package", context.packageName) putExtra("app_uid", context.applicationInfo.uid) } } else -> { Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply { addCategory(Intent.CATEGORY_DEFAULT) data = Uri.parse("package:" + context.packageName) } } } } fun highlight(viewHolder: RecyclerView.ViewHolder) { viewHolder.setIsRecyclable(false) viewHolder.itemView.apply { isPressed = true // Animate RippleDrawable if (Utils.isAtLeast(LOLLIPOP)) { postDelayed({ drawableHotspotChanged(width / 2F, height / 2F) isPressed = false viewHolder.setIsRecyclable(true) }, resources.getInteger(android.R.integer.config_mediumAnimTime) * 2.toLong()) } else { doOnNextLayout { isPressed = false viewHolder.setIsRecyclable(true) } requestLayout() } } } fun parseHtml(description: String?): Spanned? { return if (description == null || description.isBlank()) { null } else { description.replace("\n", "<br>").let { if (Utils.isAtLeast(N)) { Html.fromHtml(it, Html.FROM_HTML_MODE_LEGACY) } else { @Suppress("DEPRECATION") Html.fromHtml(it) } } } } fun relativeTimeSpan(time: Long?, now: Long = System.currentTimeMillis(), minResolution: Long = SECOND_IN_MILLIS, flags: Int = FORMAT_ABBREV_RELATIVE): CharSequence? { return DateUtils.getRelativeTimeSpanString(time ?: now, now, minResolution, flags) } } }
0
Kotlin
2
2
fa899a36047dae847f1fa57a05acba9425c3895d
5,821
InternalAppStore
Apache License 2.0
app/src/main/kotlin/games/onestar/speedclicking/receivers/SplashScreenReceiver.kt
1stargames
99,736,150
false
null
package games.onestar.speedclicking.receivers import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import games.onestar.speedclicking.ui.activities.MainActivity class SplashScreenReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val i = Intent(context, MainActivity::class.java) i.flags = Intent.FLAG_ACTIVITY_NEW_TASK context.startActivity(i) } }
1
Kotlin
0
0
4bced9da3b192cc436ebbabb00a09e2ae8360b59
475
speed_clicking
MIT License
src/main/kotlin/jp/assasans/protanki/server/serialization/StoreCurrencyAdapter.kt
Assasans
452,391,158
false
{"Kotlin": 418747}
package jp.assasans.protanki.server.serialization import com.squareup.moshi.FromJson import com.squareup.moshi.ToJson import jp.assasans.protanki.server.store.StoreCurrency class StoreCurrencyAdapter { @ToJson fun toJson(type: StoreCurrency): String = type.key @FromJson fun fromJson(value: String) = StoreCurrency.get(value) }
5
Kotlin
18
32
5cfb1e2682c029e47a69cb2910e80d14015c5896
339
protanki-server
MIT License
library/src/main/kotlin/com/drakeet/multitype/MutableTypes.kt
mChenys
373,845,036
true
{"Kotlin": 57365}
/* * Copyright (c) 2016-present. <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.drakeet.multitype /** * A TypePool implemented by an ArrayList. * 布局类型集的封装 * * @author <NAME> */ open class MutableTypes constructor( open val initialCapacity: Int = 0, open val types: MutableList<Type<*>> = ArrayList(initialCapacity) // 存储所有的布局类型 ) : Types { /** * 返回布局类型的总数 */ override val size: Int get() = types.size /** * 注册布局类型[Type] */ override fun <T> register(type: Type<T>) { types.add(type) } /** * 反注册布局类型 * @param clazz 数据bean的class * @return 操作是否成功 */ override fun unregister(clazz: Class<*>): Boolean { // 删除所有与参数clazz相关的布局类型 return types.removeAll { // 这里it是Type对象,it.class是Type的属性Class<out T>对象,因此比较的是数据bean的class,如果相同则删除此Type it.clazz == clazz } } /** * 根据索引获取布局类型Type */ @Suppress("UNCHECKED_CAST") override fun <T> getType(index: Int): Type<T> = types[index] as Type<T> /** * 返回布局类型在第一次出现在布局集合[types]的位置 * @param clazz:数据bean的Class对象,Class对象是唯一的,相同类型的数据bean,它们的Class对象是同一个 */ override fun firstIndexOf(clazz: Class<*>): Int { // 从布局集合types中搜索第一次出现对应Type的索引,可以这么说Type出现的索引完全取决于数据bean的Class对象,这也是此框架的特色,按数据bean来类型来实现多布局 val index = types.indexOfFirst { it.clazz == clazz // 这里对比的是Type内的数据bean的class属性!!注意:这里比较的是Class对象,由于Class对象是唯一的,因此同类型的数据bean的Class对比是true } if (index != -1) { return index } return types.indexOfFirst { it.clazz.isAssignableFrom(clazz) } } }
0
Kotlin
0
0
f65f1e866ae9e40b88e930bc113dafb552415291
2,164
MultiType
Apache License 2.0
app/src/main/java/com/lovoo/android/tvmaze/ui/base/BasePresenter.kt
boygaggoo
122,779,787
false
null
package com.lovoo.android.ui.base import com.lovoo.android.tvmaze.data.AppManager open class BasePresenter<V : MvpView> constructor(private val dm: AppManager) : MvpPresenter<V> { private var mMvpView: V? = null fun getDataManager(): AppManager? = dm override fun onDetach() { mMvpView = null } override fun onAttach(mvpView: V) { mMvpView = mvpView } fun getMvpView(): V? = mMvpView override fun handleError(error: Any) { mMvpView?.onError(error as String) } }
0
Kotlin
0
1
dcdeba092e9237268610bdaf9f215229f5520be1
531
TVMAZEAPI
Apache License 2.0
api/src/main/kotlin/com/posts/api/web/sse/FeedSse.kt
jmavs21
293,675,225
false
{"Kotlin": 64924, "TypeScript": 44377, "JavaScript": 17141, "HTML": 1677, "Dockerfile": 367}
package com.posts.api.web.sse import org.springframework.web.servlet.mvc.method.annotation.SseEmitter interface FeedSse { fun addEmitter(userId: Long, emitter: SseEmitter) fun removeEmitter(userId: Long) fun sendToEmitters(userName: String, toUserId: Long) }
0
Kotlin
0
0
1545bf9ff44e566f4ba7da3e5a0b3b7555b4da96
269
posts
MIT License
src/main/kotlin/ui/CustomFooter.kt
Xuezhiyang211
375,374,997
true
{"Kotlin": 325387, "CSS": 1747, "HTML": 789, "JavaScript": 566}
package ui import kotlinx.css.LinearDimension import kotlinx.css.TextAlign import kotlinx.css.color import kotlinx.css.marginBottom import kotlinx.css.marginTop import kotlinx.css.textAlign import kotlinx.css.width import react.RBuilder import react.RComponent import react.RProps import react.RState import styled.css import styled.styledFooter import ui.external.materialui.Color import ui.external.materialui.TypographyVariant import ui.external.materialui.link import ui.external.materialui.typography import ui.strings.Strings class CustomFooter : RComponent<CustomFooterProps, RState>() { override fun RBuilder.render() { styledFooter { css { width = LinearDimension("100%") textAlign = TextAlign.center color = kotlinx.css.Color.grey marginBottom = LinearDimension("15px") marginTop = LinearDimension("5px") } typography { attrs { variant = TypographyVariant.body2 color = Color.inherit } +"UtaFormatix © 2015 - 2021 | " link { attrs { href = "https://github.com/sdercolin/utaformatix3" target = "_blank" color = Color.inherit } +"View Source Code on GitHub" } +" | " link { attrs { onClick = { props.onOpenEmbeddedPage(Strings.ReleaseNotesUrl) } color = Color.inherit } +"Release Notes" } } } } } external class CustomFooterProps : RProps { var onOpenEmbeddedPage: (urlKey: Strings) -> Unit }
0
null
0
0
c8716d8f86feeaef8883ea827b2043b360a4e170
1,920
utaformatix3
Apache License 2.0
app/src/main/java/com/roksanateimouri/sample/map/android/features/map/MapsFragment.kt
RoxanaTeymouri
388,099,985
false
{"Kotlin": 25674}
package com.roksanateimouri.sample.map.android.features.map import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.Observer import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.BitmapDescriptorFactory import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.MarkerOptions import com.roksanateimouri.sample.map.android.R import com.roksanateimouri.sample.map.android.base.BaseFragment import com.roksanateimouri.sample.map.android.pojo.VehicleTypeEnum import com.roksanateimouri.sample.map.android.pojo.model.Poi import com.roksanateimouri.sample.map.android.utils.getBitmapFromVectorDrawable import org.koin.android.viewmodel.ext.android.viewModel /** * MapsFragment to show the available cars on map to the user * */ class MapsFragment : BaseFragment(), OnMapReadyCallback { private val viewModel: MapsViewModel by viewModel() private var savedInstanceState: Bundle? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_maps, container, false) } override fun tryAgainDialogAction() { viewModel.getVehicles() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) this.savedInstanceState = savedInstanceState observeErrorMessage(viewModel.getExceptionData()) val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment? mapFragment?.getMapAsync(this) } private fun showMarkers(googleMap: GoogleMap?, vehicles: List<Poi>) { vehicles.forEach { vehicle -> val icon = when (vehicle.fleetType) { VehicleTypeEnum.TAXI.type -> getBitmapFromVectorDrawable(context,R.drawable.ic_taxi) VehicleTypeEnum.POOLING.type -> getBitmapFromVectorDrawable(context,R.drawable.ic_pooling) else -> null } val location = LatLng(vehicle.coordinate.latitude, vehicle.coordinate.longitude) googleMap?.addMarker( MarkerOptions() .position(location) .icon(BitmapDescriptorFactory.fromBitmap(icon)) ) } zoomToTheLastVehicle(googleMap, vehicles.last()) } private fun zoomToTheLastVehicle(googleMap: GoogleMap?, vehicle: Poi) { googleMap?.animateCamera( CameraUpdateFactory.newLatLngZoom( LatLng( vehicle.coordinate.latitude, vehicle.coordinate.longitude ), 14F ) ) } override fun onMapReady(googleMap: GoogleMap?) { if (savedInstanceState == null) viewModel.getVehicles() viewModel.getVehicleLiveData().observe(viewLifecycleOwner, Observer { showMarkers(googleMap, it.poiList) }) } }
0
Kotlin
0
0
eeaf57bf9de261a4941b8c09b1275bc41f027a8e
3,293
MapSample
Apache License 2.0
src/test/kotlin/io/github/vfmunhoz/protectedtypes/extensions/StringExtensionsTest.kt
vfmunhoz
379,449,312
false
null
package io.github.vfmunhoz.protectedtypes.extensions import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith internal class StringExtensionsTest { private val text = "Hello ProtectedTypes!" @Test fun `should throw an exception if start position is greater than end position`() { assertFailsWith<IndexOutOfBoundsException> { text.replaceFrom(8, 1, "@") } } @Test fun `replaces part of a string without skipping any char`() { assertEquals("Hello @@@@@@@@@@@@@@@", text.replaceFrom(6, text.length -1, "@")) assertEquals("@@@@@ ProtectedTypes!", text.replaceFrom(0, 4, "@")) assertEquals("Hello @@@@@@@@@Types!", text.replaceFrom(6, 14, "@")) } @Test fun `replaces part of a string skipping multiple chars`() { assertEquals("Hello @@@@@@@@@@@@@@!", text.replaceFrom(6, text.length -1, "@", setOf('!'))) assertEquals("@@ll@ ProtectedTypes!", text.replaceFrom(0, 4, "@", setOf('l'))) assertEquals("Hello P@@t@@t@@Types!", text.replaceFrom(6, 14, "@", setOf('P', 't'))) } }
1
Kotlin
0
7
fe9e70fea1d9981dbfec1111dfb381610942b668
1,104
kotlin-protected-types
MIT License