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/io/lenses/jdbc4/resultset/UnsupportedTypesResultSet.kt
lensesio
130,357,433
false
null
package io.lenses.jdbc4.resultset import java.io.InputStream import java.io.Reader import java.net.URL import java.sql.Blob import java.sql.Clob import java.sql.NClob import java.sql.Ref import java.sql.ResultSet import java.sql.RowId import java.sql.SQLFeatureNotSupportedException import java.sql.SQLXML interface UnsupportedTypesResultSet : ResultSet { override fun getNClob(index: Int): NClob = throw SQLFeatureNotSupportedException() override fun getNClob(label: String?): NClob = throw SQLFeatureNotSupportedException() override fun getBinaryStream(index: Int): InputStream? = throw SQLFeatureNotSupportedException() override fun getBinaryStream(label: String): InputStream? = throw SQLFeatureNotSupportedException() override fun getBlob(index: Int): Blob? = throw SQLFeatureNotSupportedException() override fun getBlob(label: String): Blob? = throw SQLFeatureNotSupportedException() override fun getUnicodeStream(index: Int): InputStream = throw SQLFeatureNotSupportedException() override fun getUnicodeStream(label: String?): InputStream = throw SQLFeatureNotSupportedException() override fun getNCharacterStream(index: Int): Reader = throw SQLFeatureNotSupportedException() override fun getNCharacterStream(label: String?): Reader = throw SQLFeatureNotSupportedException() override fun getAsciiStream(index: Int): InputStream = throw SQLFeatureNotSupportedException() override fun getAsciiStream(label: String?): InputStream = throw SQLFeatureNotSupportedException() override fun getSQLXML(index: Int): SQLXML = throw SQLFeatureNotSupportedException() override fun getSQLXML(label: String?): SQLXML = throw SQLFeatureNotSupportedException() override fun getURL(index: Int): URL = throw SQLFeatureNotSupportedException() override fun getURL(label: String?): URL = throw SQLFeatureNotSupportedException() override fun getObject(index: Int, map: MutableMap<String, Class<*>>?): Any = throw SQLFeatureNotSupportedException() override fun getObject(label: String?,map: MutableMap<String, Class<*>>?): Any = throw SQLFeatureNotSupportedException() override fun <T : Any?> getObject(index: Int, type: Class<T>?): T = throw SQLFeatureNotSupportedException() override fun <T : Any?> getObject(label: String?, type: Class<T>?): T = throw SQLFeatureNotSupportedException() override fun getClob(index: Int): Clob = throw SQLFeatureNotSupportedException() override fun getClob(label: String?): Clob = throw SQLFeatureNotSupportedException() override fun getArray(index: Int): java.sql.Array = throw SQLFeatureNotSupportedException() override fun getArray(label: String?): java.sql.Array = throw SQLFeatureNotSupportedException() override fun getRef(index: Int): Ref = throw SQLFeatureNotSupportedException() override fun getRef(label: String?): Ref = throw SQLFeatureNotSupportedException() override fun getRowId(index: Int): RowId = throw SQLFeatureNotSupportedException() override fun getRowId(label: String?): RowId = throw SQLFeatureNotSupportedException() }
1
Kotlin
7
20
4ea41f66879c6e506b42432f6899cf6376f26957
3,017
lenses-jdbc
Apache License 2.0
app/src/main/java/com/anibalbastias/android/marvelapp/module/ApplicationModule.kt
anibalbastiass
173,621,278
false
null
package com.anibalbastias.android.marvelapp.module import com.anibalbastias.android.marvelapp.MarvelApplication import com.anibalbastias.android.marvelapp.base.module.BaseApplicationModule import dagger.Module @Module class ApplicationModule(application: MarvelApplication) : BaseApplicationModule(application)
0
Kotlin
1
5
6dc4765788e5a83aa4337034a5cca97d703e5a75
312
AAD-Prepare-Exam
MIT License
ktor-server/ktor-server-plugins/ktor-server-auth/jvm/src/io/ktor/server/auth/OAuth1a.kt
ktorio
40,136,600
false
null
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.auth import io.ktor.client.* import io.ktor.client.call.* import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import io.ktor.http.auth.* import io.ktor.http.content.* import io.ktor.server.application.* import io.ktor.server.response.* import io.ktor.util.* import io.ktor.utils.io.errors.* import java.time.* import java.util.* import javax.crypto.* import javax.crypto.spec.* internal fun ApplicationCall.oauth1aHandleCallback(): OAuthCallback.TokenPair? { val token = parameters[HttpAuthHeader.Parameters.OAuthToken] val verifier = parameters[HttpAuthHeader.Parameters.OAuthVerifier] return when { token != null && verifier != null -> OAuthCallback.TokenPair(token, verifier) else -> null } } internal suspend fun simpleOAuth1aStep1( client: HttpClient, settings: OAuthServerSettings.OAuth1aServerSettings, callbackUrl: String, nonce: String = generateNonce(), extraParameters: List<Pair<String, String>> = emptyList() ): OAuthCallback.TokenPair = simpleOAuth1aStep1( client, settings.consumerSecret + "&", settings.requestTokenUrl, callbackUrl, settings.consumerKey, nonce, extraParameters ) private suspend fun simpleOAuth1aStep1( client: HttpClient, secretKey: String, baseUrl: String, callback: String, consumerKey: String, nonce: String = generateNonce(), extraParameters: List<Pair<String, String>> = emptyList() ): OAuthCallback.TokenPair { val authHeader = createObtainRequestTokenHeaderInternal( callback = callback, consumerKey = consumerKey, nonce = nonce ).signInternal(HttpMethod.Post, baseUrl, secretKey, extraParameters) val url = baseUrl.appendUrlParameters(extraParameters.formUrlEncode()) val response = client.post(url) { header(HttpHeaders.Authorization, authHeader.render(HeaderValueEncoding.URI_ENCODE)) header(HttpHeaders.Accept, ContentType.Any.toString()) } val body = response.bodyAsText() try { if (response.status != HttpStatusCode.OK) { throw IOException("Bad response: $response") } val parameters = body.parseUrlEncodedParameters() require(parameters[HttpAuthHeader.Parameters.OAuthCallbackConfirmed] == "true") { "Response parameter oauth_callback_confirmed should be true" } return OAuthCallback.TokenPair( parameters[HttpAuthHeader.Parameters.OAuthToken]!!, parameters[HttpAuthHeader.Parameters.OAuthTokenSecret]!! ) } catch (cause: Throwable) { throw IOException("Failed to acquire request token due to $body", cause) } } internal suspend fun ApplicationCall.redirectAuthenticateOAuth1a( settings: OAuthServerSettings.OAuth1aServerSettings, requestToken: OAuthCallback.TokenPair ) { redirectAuthenticateOAuth1a(settings.authorizeUrl, requestToken.token) } internal suspend fun ApplicationCall.redirectAuthenticateOAuth1a(authenticateUrl: String, requestToken: String) { val url = authenticateUrl.appendUrlParameters( "${HttpAuthHeader.Parameters.OAuthToken}=${requestToken.encodeURLParameter()}" ) respondRedirect(url) } internal suspend fun requestOAuth1aAccessToken( client: HttpClient, settings: OAuthServerSettings.OAuth1aServerSettings, callbackResponse: OAuthCallback.TokenPair, nonce: String = generateNonce(), extraParameters: Map<String, String> = emptyMap() ): OAuthAccessTokenResponse.OAuth1a = requestOAuth1aAccessToken( client, settings.consumerSecret + "&", // TODO?? settings.accessTokenUrl, settings.consumerKey, token = callbackResponse.token, verifier = callbackResponse.tokenSecret, nonce = nonce, extraParameters = extraParameters, accessTokenInterceptor = settings.accessTokenInterceptor ) private suspend fun requestOAuth1aAccessToken( client: HttpClient, secretKey: String, baseUrl: String, consumerKey: String, token: String, verifier: String, nonce: String = generateNonce(), extraParameters: Map<String, String> = emptyMap(), accessTokenInterceptor: (HttpRequestBuilder.() -> Unit)? ): OAuthAccessTokenResponse.OAuth1a { val params = listOf(HttpAuthHeader.Parameters.OAuthVerifier to verifier) + extraParameters.toList() val authHeader = createUpgradeRequestTokenHeaderInternal(consumerKey, token, nonce) .signInternal(HttpMethod.Post, baseUrl, secretKey, params) // some of really existing OAuth servers don't support other accept header values so keep it val body = client.post(baseUrl) { header(HttpHeaders.Authorization, authHeader.render(HeaderValueEncoding.URI_ENCODE)) header(HttpHeaders.Accept, "*/*") // some of really existing OAuth servers don't support other accept header values so keep it setBody( WriterContent( { params.formUrlEncodeTo(this) }, ContentType.Application.FormUrlEncoded ) ) accessTokenInterceptor?.invoke(this) }.body<String>() try { val parameters = body.parseUrlEncodedParameters() return OAuthAccessTokenResponse.OAuth1a( parameters[HttpAuthHeader.Parameters.OAuthToken] ?: throw OAuth1aException.MissingTokenException(), parameters[HttpAuthHeader.Parameters.OAuthTokenSecret] ?: throw OAuth1aException.MissingTokenException(), parameters ) } catch (cause: OAuth1aException) { throw cause } catch (cause: Throwable) { throw IOException("Failed to acquire request token due to $body", cause) } } /** * Creates an HTTP auth header for OAuth1a obtain token request. */ private fun createObtainRequestTokenHeaderInternal( callback: String, consumerKey: String, nonce: String, timestamp: LocalDateTime = LocalDateTime.now() ): HttpAuthHeader.Parameterized = HttpAuthHeader.Parameterized( authScheme = AuthScheme.OAuth, parameters = mapOf( HttpAuthHeader.Parameters.OAuthCallback to callback, HttpAuthHeader.Parameters.OAuthConsumerKey to consumerKey, HttpAuthHeader.Parameters.OAuthNonce to nonce, HttpAuthHeader.Parameters.OAuthSignatureMethod to "HMAC-SHA1", HttpAuthHeader.Parameters.OAuthTimestamp to timestamp.toEpochSecond(ZoneOffset.UTC).toString(), HttpAuthHeader.Parameters.OAuthVersion to "1.0" ) ) /** * Creates an HTTP auth header for OAuth1a upgrade token request. */ private fun createUpgradeRequestTokenHeaderInternal( consumerKey: String, token: String, nonce: String, timestamp: LocalDateTime = LocalDateTime.now() ): HttpAuthHeader.Parameterized = HttpAuthHeader.Parameterized( authScheme = AuthScheme.OAuth, parameters = mapOf( HttpAuthHeader.Parameters.OAuthConsumerKey to consumerKey, HttpAuthHeader.Parameters.OAuthToken to token, HttpAuthHeader.Parameters.OAuthNonce to nonce, HttpAuthHeader.Parameters.OAuthSignatureMethod to "HMAC-SHA1", HttpAuthHeader.Parameters.OAuthTimestamp to timestamp.toEpochSecond(ZoneOffset.UTC).toString(), HttpAuthHeader.Parameters.OAuthVersion to "1.0" ) ) /** * Signs an HTTP auth header. */ private fun HttpAuthHeader.Parameterized.signInternal( method: HttpMethod, baseUrl: String, key: String, parameters: List<Pair<String, String>> ): HttpAuthHeader.Parameterized = withParameter( HttpAuthHeader.Parameters.OAuthSignature, signatureBaseStringInternal(this, method, baseUrl, parameters.toHeaderParamsList()).hmacSha1(key) ) /** * Builds an OAuth1a signature base string as per RFC. */ internal fun signatureBaseStringInternal( header: HttpAuthHeader.Parameterized, method: HttpMethod, baseUrl: String, parameters: List<HeaderValueParam> ): String = listOf( method.value.toUpperCasePreservingASCIIRules(), baseUrl, parametersString(header.parameters + parameters) ).joinToString("&") { it.encodeURLParameter() } private fun String.hmacSha1(key: String): String { val keySpec = SecretKeySpec(key.toByteArray(), "HmacSHA1") val mac = Mac.getInstance("HmacSHA1") mac.init(keySpec) return Base64.getEncoder().encodeToString(mac.doFinal(this.toByteArray())) } private fun parametersString(parameters: List<HeaderValueParam>): String = parameters.map { it.name.encodeURLParameter() to it.value.encodeURLParameter() } .sortedWith(compareBy<Pair<String, String>> { it.first }.then(compareBy { it.second })) .joinToString("&") { "${it.first}=${it.second}" } /** * An OAuth1a server error. */ public sealed class OAuth1aException(message: String) : Exception(message) { /** * Thrown when an OAuth1a server didn't provide access token. */ public class MissingTokenException : OAuth1aException("The OAuth1a server didn't provide access token") /** * Represents any other OAuth1a error. */ @Deprecated("This is no longer thrown.", level = DeprecationLevel.ERROR) public class UnknownException(message: String) : OAuth1aException(message) }
175
null
962
12,926
f90f2edf11caca28a61dbe9973faae64c17a2842
9,325
ktor
Apache License 2.0
spinner/src/main/java/com/nestoleh/bottomsheetspinner/adapter/BottomSheetSpinnerItemClickListener.kt
nestoleh
297,949,263
false
null
package com.nestoleh.bottomsheetspinner.adapter /** * Functional callback interface for spinner item click listener * * @author oleg.nestyuk */ fun interface BottomSheetSpinnerItemClickListener { fun onItemClicked(position: Int) }
0
Kotlin
4
25
3d5bebff5b9702a8bcc5a2e939db8024a46e0e83
239
BottomSheet-Spinner
Apache License 2.0
android/src/main/kotlin/org/acyb/sayit/app/atom/Text.kt
a-cyborg
766,941,087
false
{"Kotlin": 83355}
/* * Copyright (c) 2024 <NAME> / All rights reserved. * * Use of this source code is governed by Apache v2.0 */ package org.acyb.sayit.app.atom import androidx.compose.material.Text import androidx.compose.runtime.Composable import org.acyb.sayit.app.token.Color import org.acyb.sayit.app.token.Font @Composable fun TextDisplayStandardLarge(text: String) { Text( text = text, color = Color.text.standard, style = Font.display.l, ) } @Composable fun TextHeadlineStandard(text: String) { Text( text = text, color = Color.text.standard, style = Font.headline.s ) } @Composable fun TextTitleStandardLarge(text: String) { Text( text = text, color = Color.text.standard, style = Font.title.l, ) } @Composable fun TextLabelAttentionLarge(text: String) { Text( text = text, color = Color.text.attention, style = Font.label.l, ) } @Composable fun TextBodyStandardLarge(text: String) { Text( text = text, color = Color.text.standard, style = Font.body.l ) } @Composable fun TextBodyStandardMedium(text: String) { Text( text = text, color = Color.text.standard, style = Font.body.m ) }
0
Kotlin
0
0
72ab768135f318ae9b80265c1bc39146ddb747d2
1,278
SayItAlarmMP
Apache License 2.0
api/src/main/java/com/getcode/model/chat/ChatType.kt
code-payments
723,049,264
false
{"Kotlin": 2149401, "C": 198685, "C++": 83029, "Java": 52287, "Shell": 8093, "Ruby": 4626, "CMake": 2594}
package com.getcode.model.chat import com.codeinc.gen.chat.v2.ChatService enum class ChatType { Unknown, Notification, TwoWay; companion object { operator fun invoke(proto: ChatService.ChatType): ChatType { return runCatching { entries[proto.ordinal] }.getOrNull() ?: Unknown } } }
4
Kotlin
13
14
f7078b30d225ca32796fda8792b8a99646967183
332
code-android-app
MIT License
src/main/kotlin/com/github/jomof/kane/impl/functions/SubtractFunction.kt
jomof
320,425,199
false
null
package com.github.jomof.kane.impl.functions import com.github.jomof.kane.* import com.github.jomof.kane.impl.* import com.github.jomof.kane.minus import com.github.jomof.kane.negate import com.github.jomof.kane.plus val MINUS by BinaryOp(op = "-", precedence = 4, infix = true) private class SubtractFunction : AlgebraicBinaryFunction { override val meta = MINUS override fun doubleOp(p1: Double, p2: Double) = p1 - p2 override fun reduceArithmetic(p1: ScalarExpr, p2: ScalarExpr): ScalarExpr? { if (p1 is ScalarVariable && p2 is ScalarVariable) return null val leftIsConst = p1.canGetConstant() val rightIsConst = p2.canGetConstant() return when { leftIsConst && p1.getConstant() == 0.0 -> -p2 leftIsConst && p1.getConstant() == -0.0 -> -p2 rightIsConst && p2.getConstant() == 0.0 -> p1 rightIsConst && p2.getConstant() == -0.0 -> p1 leftIsConst && rightIsConst -> constant(p1.getConstant() - p2.getConstant()) rightIsConst && p1 is AlgebraicBinaryScalarScalarScalar && p1.op == plus && p1.right is ConstantScalar -> { p1.left + (p1.right - p2.getConstant()) } p2 is AlgebraicUnaryScalarScalar && p2.op == negate -> p1 + p2.value else -> null } } override fun differentiate( p1: ScalarExpr, p1d: ScalarExpr, p2: ScalarExpr, p2d: ScalarExpr, variable: ScalarExpr ) = p1d - p2d } val minus: AlgebraicBinaryFunction = SubtractFunction()
0
Kotlin
0
0
f841b79c6f826713a3e1110498cfe38dc4968e64
1,585
kane
Apache License 2.0
buildSrc/src/main/kotlin/Versions.kt
shaw500
351,304,785
true
{"Kotlin": 122639}
object Versions { const val dokka = "0.10.1" const val kotlin = "1.4.30" const val kotlinBenchmark = "0.2.0-dev-20" const val kotlinCoroutines = "1.4.2" const val ktor = "1.5.1" const val logback = "1.2.3" const val versionsPlugin = "0.36.0" }
0
Kotlin
0
0
2236b41cc612d96989ceb4aa6fd26f7f8a15a6fb
272
kotlin-result
ISC License
example/android/app/src/main/kotlin/com/cheebeez/radio_player_example/MainActivity.kt
cheebeez
324,598,493
false
null
package com.cheebeez.radio_player_example import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
2
Kotlin
5
8
45ec9c015f069fe33f742aa80cde2d3c75ab1fa4
138
radio_player
MIT License
src/main/kotlin/me/steven/indrev/packets/common/UpdateMiningDrillBlockBlacklistPacket.kt
GabrielOlvH
265,247,813
false
null
package me.steven.indrev.packets.common import me.steven.indrev.tools.modular.DrillModule import me.steven.indrev.utils.identifier import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking import net.minecraft.item.ItemStack import net.minecraft.nbt.NbtHelper import net.minecraft.nbt.NbtList import net.minecraft.network.PacketByteBuf import net.minecraft.server.MinecraftServer import net.minecraft.server.network.ServerPlayerEntity import net.minecraft.util.math.BlockPos object UpdateMiningDrillBlockBlacklistPacket { val UPDATE_BLACKLIST_PACKET = identifier("update_drill_blacklist") fun register() { ServerPlayNetworking.registerGlobalReceiver(UPDATE_BLACKLIST_PACKET) { server, player, _, buf, _ -> val mode = Mode.values()[buf.readInt()] mode.process(buf, server, player) } } enum class Mode(val process: (PacketByteBuf, MinecraftServer, ServerPlayerEntity) -> Unit) { SINGLE({ buf, server, player -> val pos = buf.readBlockPos() server.execute { val stack = player.mainHandStack val nbt = stack.orCreateNbt.getList("BlacklistedPositions", 10) val posNbt = NbtHelper.fromBlockPos(pos) if (nbt.contains(posNbt)) nbt.remove(posNbt) else nbt.add(posNbt) stack.nbt!!.put("BlacklistedPositions", nbt) } }), FLIP_Y({ _, server, player -> server.execute { val stack = player.mainHandStack val flipped = DrillModule.getBlacklistedPositions(stack).map { BlockPos(it.x, -it.y, it.z) } update(stack, flipped) } }), FLIP_X({ _, server, player -> server.execute { val stack = player.mainHandStack val flipped = DrillModule.getBlacklistedPositions(stack).map { BlockPos(-it.x, it.y, it.z) } update(stack, flipped) } }), ROT_X_90_CLOCKWISE({ _, server, player -> server.execute { val stack = player.mainHandStack val flipped = DrillModule.getBlacklistedPositions(stack).map { BlockPos(it.y, -it.x, it.z) } update(stack, flipped) } }), ROT_X_90_COUNTERCLOCKWISE({ _, server, player -> server.execute { val stack = player.mainHandStack val flipped = DrillModule.getBlacklistedPositions(stack).map { BlockPos(-it.y, it.x, it.z) } update(stack, flipped) } }), CLEAR({ _, server, player -> server.execute { val stack = player.mainHandStack update(stack, emptyList()) } }), } private fun update(stack: ItemStack, blacklist: List<BlockPos>) { if (blacklist.isEmpty()) { stack.removeSubNbt("BlacklistedPositions") return } val tagList = NbtList() blacklist.map { pos -> NbtHelper.fromBlockPos(pos) }.forEach { tagList.add(it) } stack.nbt!!.put("BlacklistedPositions", tagList) } }
51
null
56
192
012a1b83f39ab50a10d03ef3c1a8e2651e517053
3,188
Industrial-Revolution
Apache License 2.0
sample/web-app/src/jsMain/kotlin/dev/chrisbanes/material3/windowsizeclass/sample/Main.kt
chrisbanes
656,061,208
false
null
package dev.chrisbanes.material3.windowsizeclass.sample import org.jetbrains.skiko.wasm.onWasmReady fun main() { onWasmReady { BrowserViewportWindow("Sample") { MainView() } } }
2
Kotlin
2
123
6977118a3918c1faae153b8b3fd40066497b42d4
216
material3-windowsizeclass-multiplatform
Apache License 2.0
src/main/kotlin/org/stream/bot/services/impl/commands/AddBookCommandHandler.kt
alexoley
256,211,611
false
null
package org.stream.bot.services.impl.commands import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import org.stream.bot.Bot import org.stream.bot.entities.Chat import org.stream.bot.entities.FileInfo import org.stream.bot.exceptions.DublicateBookException import org.stream.bot.services.* import org.stream.bot.utils.BotConstants import org.stream.bot.utils.KeyboardFactory import org.stream.bot.utils.States import org.stream.bot.utils.Subscribers import org.telegram.abilitybots.api.util.AbilityUtils import org.telegram.abilitybots.api.util.AbilityUtils.getLocalizedMessage import org.telegram.abilitybots.api.util.AbilityUtils.getUser import org.telegram.telegrambots.meta.api.methods.send.SendMessage import org.telegram.telegrambots.meta.api.objects.Update import org.telegram.telegrambots.meta.api.objects.replykeyboard.ForceReplyKeyboard import org.telegram.telegrambots.meta.exceptions.TelegramApiException import java.io.IOException @Service class AddBookCommandHandler : ICommandHandler { private val logger = LoggerFactory.getLogger(javaClass) @Autowired lateinit var documentFormatExtractorList: List<IDocumentFormatExtractor> @Autowired lateinit var documentPersistManager: IDocumentPersistManager @Autowired lateinit var bot: Bot @Autowired lateinit var chatService: IChatService @Autowired lateinit var bookPartSenderService: BookPartSenderService override fun answer(update: Update) { try { val sendMessage = SendMessage() .setChatId(AbilityUtils.getChatId(update)) .enableMarkdown(MARKDOWN_ENABLED) //Check if book limit not reached //val user = userService.getUserByIdAndSubscriber(AbilityUtils.getChatId(update).toString(), Subscribers.TELEGRAM).awaitFirst() chatService.getUserByIdAndSubscriber(AbilityUtils.getChatId(update).toString(), Subscribers.TELEGRAM).subscribe( { chat -> if (chat.fileList.size >= chat.quantityBookLimit) { //sendMessage.setText("You already reached your book limit.\uD83D\uDE14".botText()) //sendText="Your limit on the number of books is ${e.limit}.\nYou cannot exceed it." sendMessage.setText(getLocalizedMessage("addbook.command.book.limit.exceeded", getUser(update).languageCode, chat.quantityBookLimit).botText()) } else { sendMessage.setText(getLocalizedMessage("addbook.command.send.me.book", getUser(update).languageCode).botText()) .setReplyMarkup(KeyboardFactory.cancelButton(getLocalizedMessage("cancel", getUser(update).languageCode))) .setReplyMarkup(ForceReplyKeyboard()) //db.getMap<Any, Any>(BotConstants.CHAT_STATES)[ctx.chatId().toString()] = States.WAIT_FOR_BOOK bot.rewriteValueInMapEntry(BotConstants.CHAT_STATES, AbilityUtils.getChatId(update).toString(), States.WAIT_FOR_BOOK.toString()) } }, { t -> sendMessage.setText(getLocalizedMessage("error.message.something.wrong.on.server", getUser(update).languageCode).botText()) logger.error(t.message) } , { bot.execute(sendMessage) } ) } catch (e: TelegramApiException) { e.printStackTrace() } } override fun firstReply(update: Update) { chatService.getUserByIdAndSubscriber(AbilityUtils.getChatId(update).toString(), Subscribers.TELEGRAM).subscribe( { chat -> if (chat != null) { val lastFileInfo : FileInfo? = process(update, chat) if(lastFileInfo!=null) { bookPartSenderService.sendMessageAndUpdateFileInfo(lastFileInfo, AbilityUtils.getChatId(update).toString()) } chatService.saveUser(chat).subscribe() } }, { t -> logger.error(t.message) } ) } override fun secondReply(update: Update) { TODO("Not yet implemented") } override fun thirdReply(update: Update) { TODO("Not yet implemented") } private fun process(update: Update, monoChat: Chat): FileInfo? { var fileInfo : FileInfo? = null val sendMessage: SendMessage = SendMessage().setChatId(AbilityUtils.getChatId(update)) var sendText: String? = "" try { //Check if book is too large if (update.message?.document?.fileSize!! > BotConstants.MAX_TELEGRAM_FILE_SIZE) { sendText = getLocalizedMessage("addbook.command.too.large.book", getUser(update).languageCode) return fileInfo } //If document format not supports if (documentFormatExtractorList.stream() .noneMatch { it.getDocumentMimeType().equals(update.message.document.mimeType) }) { sendText = getLocalizedMessage("addbook.command.not.support.document.format", getUser(update).languageCode) return fileInfo } bot.rewriteValueInMapEntry(BotConstants.CHAT_STATES, AbilityUtils.getChatId(update).toString(), States.NOT_WAITING.toString()) //Send loading message if file more than 1 megabyte if (update.message.document.fileSize > 1024 * 1024) { val loadingMessage = getLocalizedMessage("addbook.command.loading.file", getUser(update).languageCode) bot.execute(sendMessage .setText(loadingMessage.botText()) .setReplyMarkup(KeyboardFactory.removeKeyboard()) .enableMarkdown(MARKDOWN_ENABLED)) } val filenameGenerated = System.currentTimeMillis().toString() + "_" + update.message.document.fileName fileInfo = documentPersistManager.persistToStorage(update, filenameGenerated, monoChat.fileList) monoChat.fileList.add(fileInfo) //chatService.saveUser(monoChat).subscribe() sendText = getLocalizedMessage("addbook.command.successful.book.addition", getUser(update).languageCode, update.message.document.fileName) } catch (e: DublicateBookException) { sendText = getLocalizedMessage("addbook.command.dublicate.book", getUser(update).languageCode) } catch (e: TelegramApiException) { e.printStackTrace() } catch (e: IOException) { sendText = getLocalizedMessage("error.message.something.wrong.on.server", getUser(update).languageCode) logger.error("Error in file copying(saving)") e.printStackTrace() } catch (e: NullPointerException) { sendText = getLocalizedMessage("error.message.something.wrong.on.server", getUser(update).languageCode) logger.error("update.message.document.filesize in null") e.printStackTrace() } finally { bot.execute(sendMessage .setText(sendText.botText()) .setReplyMarkup(KeyboardFactory.removeKeyboard()) .enableMarkdown(MARKDOWN_ENABLED)) return fileInfo } } }
0
Kotlin
0
0
03101b0d178ee02403b8b087c9cef2312f56750e
7,990
ReadWithMeBot
MIT License
renders/webgl/src/jsMain/kotlin/com/aitorgf/threekt/renderers/webgl/WebGLInfo.kt
tokkenno
276,641,018
false
null
package com.aitorgf.threekt.renderers.webgl import org.khronos.webgl.WebGLRenderingContext @ExperimentalJsExport @JsExport class WebGLInfo { data class Memory( var geometries: Int = 0, var textures: Int = 0 ) data class Render( var frame: Int = 0, var calls: Int = 0, var triangles: Int = 0, var points: Int = 0, var lines: Int = 0 ) val memory = Memory() val render = Render() fun update(count: Int, mode: Int, instanceCount: Int) { render.calls++; when (mode) { WebGLRenderingContext.TRIANGLES -> render.triangles += instanceCount * (count / 3) WebGLRenderingContext.LINES -> render.lines += instanceCount * (count / 2) WebGLRenderingContext.LINE_STRIP -> render.lines += instanceCount * (count - 1) WebGLRenderingContext.LINE_LOOP -> render.lines += instanceCount * count WebGLRenderingContext.POINTS -> render.points += instanceCount * count else -> WebGLException("Unknown draw mode: $mode") } } fun reset() { this.render.frame++ this.render.calls = 0 this.render.triangles = 0 this.render.points = 0 this.render.lines = 0 } }
0
Kotlin
0
0
ae7731892ca6784f382c858bf623d68f73819fe9
1,271
threekt
MIT License
twitter-tracking-data-evaluation/src/main/kotlin/de/alxgrk/data/Event.kt
alxgrk
292,949,219
false
null
package de.alxgrk.data import com.fasterxml.jackson.annotation.JsonInclude import java.time.ZonedDateTime @JsonInclude(JsonInclude.Include.NON_NULL) data class Event( val eventType: EventType, val userId: String, val action: String, val timestamp: String, val target: String? = null, val selector: String? = null, val scrollPosition: Int? = null, val estimatedTweetsScrolled: Int? = null ) { enum class EventType { BROWSER, ANDROID } fun zonedTimestamp() = if (timestamp.endsWith("Z", ignoreCase = false)) ZonedDateTime.parse(timestamp) else ZonedDateTime.parse(timestamp + "Z") }
0
Kotlin
0
1
2be0c0f2622dad12b4aa0bb502bbcb304242e3ea
684
twitter-tracking
Apache License 2.0
components/archive/search/src/main/java/com/flipperdevices/archive/search/composable/ComposableSearchContent.kt
flipperdevices
288,258,832
false
null
package com.flipperdevices.archive.search.composable import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.flipperdevices.archive.search.R import com.flipperdevices.archive.search.model.SearchState import com.flipperdevices.archive.search.viewmodel.SearchViewModel import com.flipperdevices.archive.shared.composable.ComposableKeyCard import com.flipperdevices.bridge.dao.api.model.FlipperKey import com.flipperdevices.bridge.dao.api.model.parsed.FlipperKeyParsed import com.flipperdevices.bridge.synchronization.api.SynchronizationState import com.flipperdevices.bridge.synchronization.api.SynchronizationUiApi import com.flipperdevices.core.ui.R as DesignSystem import com.flipperdevices.core.ui.composable.LocalRouter @Composable fun ComposableSearchContent( modifier: Modifier, synchronizationUiApi: SynchronizationUiApi, searchViewModel: SearchViewModel ) { val state by searchViewModel.getState().collectAsState() val synchronizationState by searchViewModel.getSynchronizationState().collectAsState() val localState = state when (localState) { SearchState.Loading -> CategoryLoadingProgress(modifier) is SearchState.Loaded -> if (localState.keys.isEmpty()) { CategoryEmpty(modifier) } else CategoryList( modifier, searchViewModel, synchronizationUiApi, synchronizationState, localState.keys ) } } @Composable private fun CategoryList( modifier: Modifier, searchViewModel: SearchViewModel, synchronizationUiApi: SynchronizationUiApi, synchronizationState: SynchronizationState, keys: List<Pair<FlipperKeyParsed, FlipperKey>> ) { val router = LocalRouter.current LazyColumn( modifier.padding(top = 14.dp) ) { items(keys) { (flipperKeyParsed, flipperKey) -> ComposableKeyCard( Modifier.padding(bottom = 14.dp), synchronizationContent = { synchronizationUiApi.RenderSynchronizationState( flipperKey.synchronized, synchronizationState, withText = false ) }, flipperKeyParsed ) { searchViewModel.openKeyScreen(router, flipperKey.path) } } } } @Composable private fun CategoryLoadingProgress(modifier: Modifier) { Box(modifier, contentAlignment = Alignment.Center) { CircularProgressIndicator() } } @Composable private fun CategoryEmpty(modifier: Modifier) { Column( modifier, verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Image( painter = painterResource(R.drawable.ic_not_found), contentDescription = null ) Text( modifier = Modifier.padding(top = 12.dp), text = stringResource(R.string.search_not_found_title), fontWeight = FontWeight.W500, fontSize = 16.sp, color = colorResource(DesignSystem.color.black_100) ) Text( modifier = Modifier.padding(top = 12.dp, start = 98.dp, end = 98.dp), text = stringResource(R.string.search_not_found_description), color = colorResource(DesignSystem.color.black_40), fontSize = 16.sp, fontWeight = FontWeight.W400, textAlign = TextAlign.Center ) } }
2
Kotlin
31
293
522f873d6dcf09a8f1907c1636fb0c3a996f5b44
4,423
Flipper-Android-App
MIT License
testit/src/test/kotlin/com/github/haschi/haushaltsbuch/EinTest.kt
haschi
52,821,330
false
null
package com.github.haschi.haushaltsbuch import org.assertj.core.api.Assertions.assertThat import org.assertj.core.data.Offset import org.junit.Test class EinTest { @Test fun ein_test() { assertThat(1).isCloseTo(2, Offset.offset(1)) } }
11
Kotlin
2
4
e3222c613c369b4a58026ce42c346b575b3082e5
262
dominium
MIT License
src/main/kotlin/org/springframework/samples/petclinic/rest/controller/VetRestController.kt
junoyoon
664,329,578
false
null
/* * Copyright 2016-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.samples.petclinic.rest.controller import jakarta.transaction.Transactional import org.springframework.http.HttpHeaders import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.samples.petclinic.mapper.SpecialtyMapper import org.springframework.samples.petclinic.mapper.VetMapper import org.springframework.samples.petclinic.model.Vet import org.springframework.samples.petclinic.rest.api.VetsApi import org.springframework.samples.petclinic.rest.dto.VetDto import org.springframework.samples.petclinic.rest.dto.VetFieldsDto import org.springframework.samples.petclinic.service.ClinicService import org.springframework.security.access.prepost.PreAuthorize import org.springframework.web.bind.annotation.CrossOrigin import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import org.springframework.web.util.UriComponentsBuilder /** * @author <NAME> */ @RestController @CrossOrigin(exposedHeaders = ["errors, content-type"]) @RequestMapping("api") class VetRestController( private val clinicService: ClinicService, ) : VetsApi { @PreAuthorize("hasRole(@roles.VET_ADMIN)") override fun listVets(): ResponseEntity<List<VetDto>> { val vets = VetMapper.toVetDtos(clinicService.findAllVets()) return if (vets.isEmpty()) { ResponseEntity(HttpStatus.NOT_FOUND) } else ResponseEntity(vets, HttpStatus.OK) } @PreAuthorize("hasRole(@roles.VET_ADMIN)") override fun getVet(vetId: Int): ResponseEntity<VetDto> { val vet: Vet = clinicService.findVetById(vetId) ?: return ResponseEntity(HttpStatus.NOT_FOUND) return ResponseEntity(VetMapper.toVetDto(vet), HttpStatus.OK) } @PreAuthorize("hasRole(@roles.VET_ADMIN)") override fun addVet(vetDto: VetDto): ResponseEntity<VetDto> { val vet = VetMapper.toVet(vetDto) clinicService.saveVet(vet) val headers = HttpHeaders().apply { location = UriComponentsBuilder.newInstance() .path("/api/vets/{id}").buildAndExpand(vet.id).toUri() } return ResponseEntity(VetMapper.toVetDto(vet), headers, HttpStatus.CREATED) } @PreAuthorize("hasRole(@roles.VET_ADMIN)") override fun updateVet(vetId: Int, vetDto: VetFieldsDto): ResponseEntity<VetDto> { val currentVet: Vet = clinicService.findVetById(vetId)?.apply { firstName = vetDto.firstName lastName = vetDto.lastName } ?: return ResponseEntity(HttpStatus.NOT_FOUND) currentVet.clearSpecialties() for (spec in SpecialtyMapper.toSpecialtys(vetDto.specialties)) { currentVet.addSpecialty(spec) } clinicService.saveVet(currentVet) return ResponseEntity(VetMapper.toVetDto(currentVet), HttpStatus.NO_CONTENT) } @PreAuthorize("hasRole(@roles.VET_ADMIN)") @Transactional override fun deleteVet(vetId: Int): ResponseEntity<VetDto> { val vet: Vet = clinicService.findVetById(vetId) ?: return ResponseEntity(HttpStatus.NOT_FOUND) clinicService.deleteVet(vet) return ResponseEntity(HttpStatus.NO_CONTENT) } }
0
Kotlin
1
0
f0bbaedce3f7c917bff38ed639913b685f84c52c
3,877
spring-petclinic-rest-kotlin
Apache License 2.0
AOS/Apps/Sunflower/app/src/main/java/com/zy/sunflower/adapters/PlantListAdapter.kt
syusikoku
280,278,345
false
{"C++": 4006762, "C": 685802, "Dart": 182866, "Java": 169779, "Kotlin": 163220, "GLSL": 12816, "HTML": 8121, "Objective-C": 7450, "CMake": 7331, "Swift": 808, "CSS": 709}
package com.zy.sunflower.adapters import android.content.Context import android.view.View import androidx.navigation.findNavController import cn.charles.kasa.framework.adapter.BaseBindingViewHolder import cn.charles.kasa.framework.adapter.BaseSampleListAdapter import cn.charles.kasa.framework.utils.Utils import com.zy.sunflower.R import com.zy.sunflower.databinding.LayoutItemPlantsBinding import com.zy.sunflower.repository.local.room.entry.Plant import com.zy.sunflower.ui.fragments.HomePageFragmentDirections /** * 植物列表适配器 */ class PlantListAdapter(ctx: Context, list: List<Plant>) : BaseSampleListAdapter<Plant, LayoutItemPlantsBinding>(ctx, list) { override fun getLayoutId(p0: Int): Int = R.layout.layout_item_plants override fun bindData( p0: BaseBindingViewHolder<LayoutItemPlantsBinding>?, p1: Plant?, p2: Int ) { p0?.mBinding?.item = p1 p0?.mBinding?.setItemClickListener { // 进入到详情 Utils.showToastSafe("进入到详情") navigationToPlant(p1!!, it) } } /** * 进入到详情 */ private fun navigationToPlant(plant: Plant, view: View?) { Utils.showToastSafe("navigationToPlant") val direction = HomePageFragmentDirections.actionHomePageFragmentToPlantDetailFragment(plant.plantId) view?.findNavController()?.navigate(direction) } }
0
C++
1
0
07d7bd68ce00773e5a5accde3329c977237d5d02
1,394
SampleApps
Apache License 2.0
typescript/ts-translator/src/org/jetbrains/dukat/ts/translator/createJsByteArrayWithBodyTranslator.kt
Kotlin
159,510,660
false
{"Kotlin": 2656818, "WebIDL": 323681, "TypeScript": 135641, "JavaScript": 19475, "ANTLR": 11333}
package org.jetbrains.dukat.ts.translator import org.jetbrains.dukat.astCommon.NameEntity import org.jetbrains.dukat.moduleNameResolver.ModuleNameResolver import org.jetbrains.dukat.translator.InputTranslator fun createJsByteArrayWithBodyTranslator( moduleNameResolver: ModuleNameResolver, packageName: NameEntity? ): InputTranslator<ByteArray> = JsRuntimeByteArrayTranslator(TypescriptLowerer(moduleNameResolver, packageName, true))
244
Kotlin
42
535
d50b9be913ce8a2332b8e97fd518f1ec1ad7f69e
443
dukat
Apache License 2.0
app/src/main/java/id/yanuar/moovis/data/Resource.kt
januaripin
150,684,072
false
null
package id.yanuar.moovis.data /** * Created by <NAME> * <EMAIL> */ enum class Status { SUCCESS, ERROR, LOADING } data class Resource<out T>(val status: Status, val data: T? = null, val throwable: Throwable? = null) { companion object { fun <T> success(data: T?): Resource<T> { return Resource(Status.SUCCESS, data) } fun <T> error(throwable: Throwable?, data: T? = null): Resource<T> { return Resource(Status.ERROR, data, throwable) } fun <T> loading(data: T? = null): Resource<T> { return Resource(Status.LOADING, data, null) } } }
0
Kotlin
0
0
c9bc2fdfdd5111c982e4fdd89d9d161839d122cc
646
moovis
MIT License
app/src/main/java/com/studyup/classes/NewTeam/events/EventsFragmentList.kt
UTN-FRBA-Mobile
544,243,563
false
{"Kotlin": 120176}
package com.studyup.classes.NewTeam.events import android.annotation.SuppressLint import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.studyup.classes.TeamDetail.events.EventRecycler import com.studyup.databinding.FragmentMembersListBinding import com.studyup.utils.State class EventsFragmentList: Fragment() { private var _binding: FragmentMembersListBinding? = null private val binding get() = _binding!! public var viewAdapter: EventRecyclerViewAdapter? = null private var columnCount = 1 private lateinit var recyclerView: RecyclerView override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentMembersListBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val myDataset = State.newTeam.events.map { EventRecycler(it, false) } as MutableList<EventRecycler> val viewManager = LinearLayoutManager(this.context) this.viewAdapter = EventRecyclerViewAdapter(myDataset, this) val viewAdapter = this.viewAdapter recyclerView = binding.myRecyclerView.apply { layoutManager = viewManager adapter = viewAdapter } } @SuppressLint("NotifyDataSetChanged") fun notify_update() { this.viewAdapter?.myDataset = State.newTeam.events.map { EventRecycler(it, false) } as MutableList<EventRecycler> this.viewAdapter?.notifyDataSetChanged() } }
0
Kotlin
0
1
d8453a7edf5653ff8b2fa7679b05662be3099c56
1,867
StudyUp
MIT License
kmp/compose/foundation/icons/src/commonMain/kotlin/com/egoriku/grodnoroads/foundation/icons/colored/TrafficPoliceBold.kt
BehindWheel
485,026,420
false
{"Kotlin": 1186756, "Ruby": 5708, "Swift": 1889, "Shell": 830}
package com.egoriku.grodnoroads.foundation.icons.colored import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.egoriku.grodnoroads.foundation.icons.GrodnoRoads val GrodnoRoads.Colored.TrafficPolice: ImageVector get() { if (_TrafficPolice != null) { return _TrafficPolice!! } _TrafficPolice = ImageVector.Builder( name = "Colored.TrafficPolice", defaultWidth = 24.dp, defaultHeight = 24.dp, viewportWidth = 32f, viewportHeight = 32f ).apply { path( fill = SolidColor(Color(0xFFFFFFFF)), stroke = SolidColor(Color(0xFF2053B9)), strokeLineWidth = 1f ) { moveTo(8.4f, 2.5f) lineTo(16.424f, 2.5f) lineTo(23.6f, 2.5f) curveTo(24.728f, 2.5f, 25.545f, 2.5f, 26.187f, 2.553f) curveTo(26.823f, 2.605f, 27.243f, 2.705f, 27.589f, 2.881f) curveTo(28.247f, 3.217f, 28.783f, 3.752f, 29.118f, 4.411f) curveTo(29.295f, 4.757f, 29.395f, 5.177f, 29.447f, 5.814f) curveTo(29.5f, 6.455f, 29.5f, 7.272f, 29.5f, 8.4f) lineTo(29.5f, 23.6f) curveTo(29.5f, 24.728f, 29.5f, 25.545f, 29.447f, 26.187f) curveTo(29.395f, 26.823f, 29.295f, 27.243f, 29.118f, 27.589f) curveTo(28.783f, 28.247f, 28.247f, 28.783f, 27.589f, 29.118f) curveTo(27.243f, 29.295f, 26.823f, 29.395f, 26.187f, 29.447f) curveTo(25.545f, 29.5f, 24.728f, 29.5f, 23.6f, 29.5f) lineTo(19.394f, 29.5f) lineTo(8.4f, 29.5f) curveTo(7.272f, 29.5f, 6.455f, 29.5f, 5.814f, 29.447f) curveTo(5.177f, 29.395f, 4.757f, 29.295f, 4.411f, 29.118f) curveTo(3.752f, 28.783f, 3.217f, 28.247f, 2.881f, 27.589f) curveTo(2.705f, 27.243f, 2.605f, 26.823f, 2.553f, 26.187f) curveTo(2.5f, 25.545f, 2.5f, 24.728f, 2.5f, 23.6f) lineTo(2.5f, 8.4f) curveTo(2.5f, 7.272f, 2.5f, 6.455f, 2.553f, 5.814f) curveTo(2.605f, 5.177f, 2.705f, 4.757f, 2.881f, 4.411f) curveTo(3.217f, 3.752f, 3.752f, 3.217f, 4.411f, 2.881f) curveTo(4.757f, 2.705f, 5.177f, 2.605f, 5.814f, 2.553f) curveTo(6.455f, 2.5f, 7.272f, 2.5f, 8.4f, 2.5f) close() } path(fill = SolidColor(Color(0xFF232F34))) { moveTo(16.472f, 6.045f) curveTo(16.472f, 6.099f, 16.663f, 6.504f, 16.897f, 6.946f) curveTo(17.13f, 7.388f, 17.322f, 7.972f, 17.322f, 8.244f) lineTo(17.322f, 8.738f) lineTo(20.212f, 8.738f) lineTo(23.103f, 8.738f) lineTo(23.103f, 8.256f) curveTo(23.103f, 7.721f, 23.389f, 7.834f, 18.937f, 6.622f) curveTo(17.908f, 6.342f, 16.933f, 6.076f, 16.769f, 6.03f) curveTo(16.605f, 5.985f, 16.472f, 5.991f, 16.472f, 6.045f) close() moveTo(7.664f, 8.282f) curveTo(7.545f, 8.395f, 7.46f, 8.94f, 7.46f, 9.585f) lineTo(7.46f, 10.692f) lineTo(8.055f, 10.692f) lineTo(8.65f, 10.692f) lineTo(8.65f, 9.585f) curveTo(8.65f, 8.52f, 8.478f, 8.086f, 8.055f, 8.086f) curveTo(7.952f, 8.086f, 7.776f, 8.174f, 7.664f, 8.282f) close() moveTo(8.446f, 9.513f) curveTo(8.495f, 10.506f, 8.487f, 10.529f, 8.063f, 10.529f) curveTo(7.658f, 10.529f, 7.63f, 10.478f, 7.63f, 9.728f) curveTo(7.63f, 8.732f, 7.764f, 8.382f, 8.119f, 8.446f) curveTo(8.332f, 8.485f, 8.407f, 8.729f, 8.446f, 9.513f) close() moveTo(16.579f, 10.471f) curveTo(18.505f, 9.91f, 22.508f, 9.151f, 22.508f, 9.151f) curveTo(22.669f, 9.093f, 21.939f, 9.086f, 17.338f, 9.063f) curveTo(17.18f, 9.284f, 16.227f, 10.573f, 16.579f, 10.471f) close() moveTo(17.87f, 10.514f) curveTo(17.844f, 10.522f, 17.944f, 10.752f, 18.091f, 11.025f) curveTo(19.017f, 12.741f, 21.855f, 12.424f, 22.419f, 10.542f) curveTo(22.57f, 10.036f, 22.498f, 9.536f, 22.277f, 9.567f) lineTo(17.87f, 10.514f) close() moveTo(7.46f, 13.135f) lineTo(8.65f, 13.135f) lineTo(8.65f, 11.181f) lineTo(7.46f, 11.181f) lineTo(7.46f, 13.135f) close() moveTo(16.792f, 13.278f) curveTo(15.707f, 14.095f, 12.814f, 18.835f, 12.485f, 18.834f) curveTo(12.28f, 18.833f, 9.185f, 17.675f, 8.863f, 17.479f) curveTo(8.745f, 17.407f, 8.65f, 17.027f, 8.65f, 16.626f) curveTo(8.65f, 15.908f, 8.646f, 15.903f, 8.055f, 15.903f) lineTo(7.46f, 15.903f) curveTo(7.46f, 16.665f, 7.615f, 17.681f, 7.281f, 18.382f) curveTo(6.878f, 19.228f, 7.188f, 19.458f, 10.536f, 20.804f) curveTo(11.563f, 21.217f, 12.524f, 21.563f, 13.147f, 21.765f) curveTo(13.601f, 21.913f, 14.118f, 21.874f, 14.439f, 21.521f) curveTo(15.009f, 20.894f, 15.748f, 19.812f, 15.967f, 19.812f) curveTo(16.279f, 19.812f, 15.964f, 22.148f, 16.196f, 22.371f) curveTo(16.246f, 22.418f, 21.912f, 13.462f, 22.054f, 13.112f) curveTo(22.085f, 13.035f, 21.005f, 12.972f, 19.654f, 12.972f) curveTo(17.509f, 12.972f, 17.146f, 13.011f, 16.792f, 13.278f) close() moveTo(17.662f, 22.795f) curveTo(17.662f, 22.969f, 22.52f, 22.906f, 23.103f, 22.906f) lineTo(23.103f, 24.046f) lineTo(16.132f, 24.046f) lineTo(16.132f, 25.023f) curveTo(16.132f, 25.563f, 16.569f, 26f, 17.109f, 26f) lineTo(24.143f, 26f) curveTo(24.695f, 26f, 25.143f, 25.556f, 25.143f, 25.004f) curveTo(25.143f, 21.946f, 25.143f, 15.329f, 25.143f, 13.536f) curveTo(25.143f, 13.264f, 25.002f, 13.044f, 24.73f, 13.022f) curveTo(24.472f, 13.001f, 24.163f, 13f, 24f, 13f) curveTo(24.146f, 13.002f, 17.662f, 22.621f, 17.662f, 22.795f) close() moveTo(7.46f, 15.578f) lineTo(8.65f, 15.578f) lineTo(8.65f, 13.46f) lineTo(7.46f, 13.46f) lineTo(7.46f, 15.578f) close() moveTo(8.48f, 14.5f) curveTo(8.48f, 15.07f, 8.414f, 15.23f, 8.15f, 15.297f) curveTo(7.697f, 15.41f, 7.63f, 15.306f, 7.63f, 14.492f) curveTo(7.63f, 13.848f, 7.667f, 13.786f, 8.055f, 13.786f) curveTo(8.444f, 13.786f, 8.48f, 13.847f, 8.48f, 14.5f) close() } }.build() return _TrafficPolice!! } private var _TrafficPolice: ImageVector? = null
19
Kotlin
1
18
f33ed73eb6d83670f7bb096c4a1995117d80aa2f
7,475
BehindWheelKMP
Apache License 2.0
android/features/recipe/input/src/main/kotlin/io/chefbook/features/recipe/input/ui/screens/ingredients/components/AddIngredientItemBlock.kt
mephistolie
379,951,682
false
{"Kotlin": 1334117, "Ruby": 16819, "Swift": 352}
package io.chefbook.features.recipe.input.ui.screens.ingredients.components import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.height import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.vectorResource import androidx.compose.ui.unit.dp import io.chefbook.core.android.compose.providers.theme.LocalTheme import io.chefbook.design.components.buttons.DynamicButton import io.chefbook.design.theme.dimens.ComponentSmallHeight import io.chefbook.features.recipe.input.ui.mvi.RecipeInputIngredientsScreenIntent import io.chefbook.core.android.R as coreR import io.chefbook.design.R as designR @Composable internal fun AddIngredientItemBlock( onIntent: (RecipeInputIngredientsScreenIntent) -> Unit, modifier: Modifier = Modifier ) { val colors = LocalTheme.colors Row( modifier = modifier, horizontalArrangement = Arrangement.spacedBy(8.dp) ) { DynamicButton(leftIcon = ImageVector.vectorResource(designR.drawable.ic_add), text = stringResource(coreR.string.common_general_section), cornerRadius = 12.dp, unselectedForeground = colors.foregroundPrimary, modifier = Modifier.height(ComponentSmallHeight), onClick = { onIntent(RecipeInputIngredientsScreenIntent.AddIngredientSection) }) DynamicButton(leftIcon = ImageVector.vectorResource(designR.drawable.ic_add), text = stringResource(coreR.string.common_general_ingredient), cornerRadius = 12.dp, unselectedForeground = colors.foregroundPrimary, modifier = Modifier.height(ComponentSmallHeight), onClick = { onIntent(RecipeInputIngredientsScreenIntent.AddIngredient) }) } }
0
Kotlin
0
12
ddaf82ee3142f30aee8920d226a8f07873cdcffe
1,859
chefbook-mobile
Apache License 2.0
src/main/kotlin/no/nav/helse/inntektsmeldingsvarsel/dependencyinjection/KoinProfiles.kt
navikt
255,909,562
false
null
package no.nav.helse.inntektsmeldingsvarsel.dependencyinjection import com.fasterxml.jackson.core.util.DefaultIndenter import com.fasterxml.jackson.core.util.DefaultPrettyPrinter import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.MapperFeature import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.datatype.jdk8.Jdk8Module import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule import com.fasterxml.jackson.module.kotlin.KotlinModule import io.ktor.client.HttpClient import io.ktor.client.engine.apache.Apache import io.ktor.client.features.json.JacksonSerializer import io.ktor.client.features.json.JsonFeature import io.ktor.config.ApplicationConfig import io.ktor.util.KtorExperimentalAPI import no.nav.helse.arbeidsgiver.integrasjoner.pdl.* import no.nav.helse.arbeidsgiver.kubernetes.KubernetesProbeManager import no.nav.helse.inntektsmeldingsvarsel.* import no.nav.helse.inntektsmeldingsvarsel.varsling.* import org.koin.core.Koin import org.koin.core.definition.Kind import org.koin.core.module.Module import org.koin.dsl.module @KtorExperimentalAPI fun selectModuleBasedOnProfile(config: ApplicationConfig): List<Module> { val envModule = when (config.property("koin.profile").getString()) { "TEST" -> buildAndTestConfig() "LOCAL" -> localDevConfig(config) "PREPROD" -> preprodConfig(config) "PROD" -> prodConfig(config) else -> localDevConfig(config) } return listOf(common, envModule) } val common = module { val om = ObjectMapper() om.registerModule(KotlinModule()) om.registerModule(Jdk8Module()) om.registerModule(JavaTimeModule()) om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) om.configure(SerializationFeature.INDENT_OUTPUT, true) om.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true) om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) om.setDefaultPrettyPrinter( DefaultPrettyPrinter().apply { indentArraysWith(DefaultPrettyPrinter.FixedSpaceIndenter.instance) indentObjectsWith(DefaultIndenter(" ", "\n")) } ) single { om } val httpClient = HttpClient(Apache) { install(JsonFeature) { serializer = JacksonSerializer { registerModule(KotlinModule()) registerModule(Jdk8Module()) registerModule(JavaTimeModule()) disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) configure(SerializationFeature.INDENT_OUTPUT, true) configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true) } } } single { httpClient } single { KubernetesProbeManager() } } fun buildAndTestConfig() = module {} // utils @KtorExperimentalAPI fun ApplicationConfig.getString(path: String): String { return this.property(path).getString() } @KtorExperimentalAPI fun ApplicationConfig.getjdbcUrlFromProperties(): String { return String.format( "jdbc:postgresql://%s:%s/%s", this.property("database.host").getString(), this.property("database.port").getString(), this.property("database.name").getString() ) } inline fun <reified T : Any> Koin.getAllOfType(): Collection<T> = let { koin -> koin.rootScope.beanRegistry .getAllDefinitions() .filter { it.kind == Kind.Single } .map { koin.get<Any>(clazz = it.primaryType, qualifier = null, parameters = null) } .filterIsInstance<T>() }
1
Kotlin
0
0
1a808b155f5f1bc996d454e5f42652a696b9d58a
3,751
im-varsel
MIT License
app-tracking-protection/vpn-impl/src/main/java/com/duckduckgo/mobile/android/vpn/ui/notification/NotificationActionReportIssue.kt
hojat72elect
822,396,044
false
{"Kotlin": 11626231, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784}
package com.duckduckgo.mobile.android.vpn.ui.notification import android.app.PendingIntent import android.content.Context import android.content.Intent import androidx.core.app.NotificationCompat import com.duckduckgo.mobile.android.vpn.R import com.duckduckgo.mobile.android.vpn.apps.ui.ManageRecentAppsProtectionActivity import com.duckduckgo.mobile.android.vpn.breakage.ReportBreakageAppListActivity class NotificationActionReportIssue { companion object { fun reportIssueNotificationAction(context: Context): NotificationCompat.Action { val launchIntent = ReportBreakageAppListActivity.intent(context).also { it.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP } return NotificationCompat.Action( R.drawable.ic_baseline_feedback_24, context.getString(R.string.atp_ReportIssue), PendingIntent.getActivity(context, 0, launchIntent, PendingIntent.FLAG_IMMUTABLE), ) } fun mangeRecentAppsNotificationAction(context: Context): NotificationCompat.Action { val launchIntent = ManageRecentAppsProtectionActivity.intent(context).also { it.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP } return NotificationCompat.Action( R.drawable.ic_baseline_feedback_24, context.getString(R.string.atp_ReportIssue), PendingIntent.getActivity(context, 0, launchIntent, PendingIntent.FLAG_IMMUTABLE), ) } } }
0
Kotlin
0
0
b89591136b60933d6a03fac43a38ee183116b7f8
1,611
DuckDuckGo
Apache License 2.0
src/main/kotlin/xyz/aesthetical/lookupbot/utils/parsers/enums/EnumParser.kt
Sxmurai
330,442,850
false
null
/* * Taken from https://github.com/Stardust-Discord/Octave/blob/development/src/main/kotlin/gg/octave/bot/entities/framework/parsers/EnumParser.kt */ package xyz.aesthetical.lookupbot.utils.parsers.enums import me.devoxin.flight.api.Context import me.devoxin.flight.internal.parsers.Parser import java.util.* open class EnumParser<T : Enum<*>>(private val enumClass: Class<T>) : Parser<T> { override fun parse(ctx: Context, param: String): Optional<T> { return Optional.ofNullable( enumClass.enumConstants.firstOrNull { it.name.equals(param, ignoreCase = true) } ) } }
0
Kotlin
0
1
83bc76e3f790505d8c4b089181b1ad774bd561a5
603
lookup-bot
Do What The F*ck You Want To Public License
debugktest/src/main/java/com/mozhimen/debugktest/DebugKApplication.kt
mozhimen
353,952,154
false
null
package com.mozhimen.debugktest import com.mozhimen.basick.elemk.application.bases.BaseApplication /** * @ClassName DebugKApplication * @Description TODO * @Author Mozhimen & <NAME> * @Date 2022/12/16 14:51 * @Version 1.0 */ class DebugKApplication : BaseApplication() { override fun onCreate() { super.onCreate() } }
0
Kotlin
0
2
0b6d7642b1bd7c697d9107c4135c1f2592d4b9d5
342
SwiftKit
Apache License 2.0
network/api/src/main/java/com/yigitozgumus/api/services/MarketSearchService.kt
yigitozgumus
475,998,040
false
{"Kotlin": 49621}
/* * Created by yigitozgumus on 4/2/22, 11:44 AM * Copyright (c) 2022 . All rights reserved. * Last modified 4/2/22, 11:44 AM */ package com.yigitozgumus.api.services import com.yigitozgumus.api.models.Coin import retrofit2.http.GET import retrofit2.http.Query interface MarketSearchService { @GET("coins/markets") suspend fun searchMarket( @Query("vs_currency") vsCurrency: String, @Query("order") order: String = "market_cap_desc", @Query("per_page") perPage: Int = 30, @Query("page") page: Int = 1 ): List<Coin> }
0
Kotlin
0
0
ca3ff32aaab6fd96fcee9f7c69098f99d10300ed
568
DemoCurrencyApplication
MIT License
app/src/main/java/com/kotlincoders/nftexplorer/home/domain/usecase/GetNftDetailsUseCase.kt
Kotlin-Coders
731,346,931
false
{"Kotlin": 72714}
package com.kotlincoders.nftexplorer.home.domain.usecase import com.kotlincoders.nftexplorer.home.domain.model.NftDetails import com.kotlincoders.nftexplorer.home.domain.repository.HomeRepository class GetNftDetailsUseCase( private val repository: HomeRepository ) { suspend operator fun invoke(nftAddress:String):Result<NftDetails>{ return repository.getNftDetails(nftAddress) } }
0
Kotlin
0
0
dc4a729af2d91997670e890e2d34eb1d0a423f8d
403
NFT-Explorer
MIT License
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/ResourceFunction.kt
Danilo-Araujo-Silva
271,904,885
false
null
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction /** *```` * * Name: ResourceFunction * * Full name: System`ResourceFunction * * ResourceFunction[resource] represents the function associated with the specified resource. * Usage: ResourceFunction[resource, prop] gives the specified property of the resource. * * ResourceSystemPath :> $ResourceSystemPath * ResourceVersion -> Automatic * ResourceSystemBase :> Automatic * Version -> Automatic * Options: WolframLanguageVersion -> Automatic * * Protected * Attributes: ReadProtected * * local: paclet:ref/ResourceFunction * Documentation: web: http://reference.wolfram.com/language/ref/ResourceFunction.html * * Definitions: None * * Own values: None * * Down values: None * * Up values: None * * Sub values: None * * Default value: SyntaxInformation[ResourceFunction] = {"ArgumentsPattern" -> {_, _., OptionsPattern[]}, "OptionNames" -> {"ResourceSystemPath", "ResourceVersion", "ResourceSystemBase", "\"Version\"", "\"WolframLanguageVersion\""}} * * Numeric values: None */ fun resourceFunction(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction { return MathematicaFunction("ResourceFunction", arguments.toMutableList(), options) }
2
Kotlin
0
3
4fcf68af14f55b8634132d34f61dae8bb2ee2942
1,593
mathemagika
Apache License 2.0
app/src/main/java/com/example/shonenarena/presentation/match/MatchViewModel.kt
mobyleOfficial
486,758,043
false
{"Kotlin": 42685}
package com.example.shonenarena.presentation.match import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.example.domain.model.Character import com.example.domain.model.Move import com.example.domain.usecase.GetMatch import com.example.shonenarena.presentation.characterinformation.model.CharacterInformationArgs import com.example.shonenarena.presentation.common.base.BaseViewModel import com.example.shonenarena.presentation.moves.mapper.toViewModel import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.* import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import javax.inject.Inject @HiltViewModel class MatchViewModel @Inject constructor(private val getMatchUseCase: GetMatch) : BaseViewModel() { init { getMatch() } private var limitRoundTime = 100 private val _roundTimerLiveData = MutableLiveData<Int>() val roundTimerLiveData: LiveData<Int> = _roundTimerLiveData private val _enemyCharactersLiveData = MutableLiveData<List<Character>>() val enemyCharactersLiveData: LiveData<List<Character>> = _enemyCharactersLiveData private val _userCharactersLiveData = MutableLiveData<List<Character>>() val userCharactersLiveData: LiveData<List<Character>> = _userCharactersLiveData fun navigateToCharacterInformationBottomSheet(moveList: List<Move>) { navigate( MatchFragmentDirections.actionMatchFragmentToCharacterInformationBottomSheet( CharacterInformationArgs( moveList.map { it.toViewModel() }, _enemyCharactersLiveData.value?.map { it.toViewModel() } ?: emptyList() ) ) ) } private fun getMatch() { CoroutineScope(Dispatchers.Main).launch { runCatching { runBlocking { val match = getMatchUseCase.call("") _enemyCharactersLiveData.postValue(match.enemyCharacters) _userCharactersLiveData.postValue(match.userCharacters) } } } updateProgress() } private fun updateProgress() { CoroutineScope(Dispatchers.Main).launch { withContext(Dispatchers.Default) { playerCountdown() .onEach { _roundTimerLiveData.postValue(it) } .launchIn(this) } } } private suspend fun playerCountdown() = flow { while (limitRoundTime >= 0) { delay(1000) emit(limitRoundTime) limitRoundTime-- } } }
0
Kotlin
0
0
2610a3a08bf5eaa6772f3b2c3a708b5652aa18a9
2,813
shonnen_arena
MIT License
project-system-gradle/src/com/android/tools/idea/projectsystem/gradle/AndroidIconProviderProjectGradleToken.kt
JetBrains
60,701,247
false
{"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19}
/* * Copyright (C) 2024 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.projectsystem.gradle import com.android.tools.idea.projectsystem.AndroidIconProviderProjectToken import com.android.tools.idea.projectsystem.AndroidModuleSystem import com.android.tools.idea.projectsystem.GradleToken import com.android.tools.idea.projectsystem.getModuleSystem import com.android.tools.idea.projectsystem.isAndroidTestModule import com.android.tools.idea.projectsystem.isHolderModule import com.android.tools.idea.projectsystem.isMainModule import com.intellij.icons.AllIcons import com.intellij.ide.projectView.impl.ProjectRootsUtil import com.intellij.openapi.module.Module import com.intellij.openapi.roots.ProjectRootManager import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import icons.StudioIcons import javax.swing.Icon class AndroidIconProviderProjectGradleToken : AndroidIconProviderProjectToken<GradleProjectSystem>, GradleToken { override fun getIcon(projectSystem: GradleProjectSystem, element: PsiElement): Icon? { if (element is PsiDirectory) { val psiDirectory = element val virtualDirectory = psiDirectory.virtualFile val project = psiDirectory.project if (ProjectRootsUtil.isModuleContentRoot(virtualDirectory, project)) { val projectFileIndex = ProjectRootManager.getInstance(project).fileIndex val module = projectFileIndex.getModuleForFile(virtualDirectory) // Only provide icons for modules that are setup by the Android plugin - other modules may be provided for // by later providers, we don't assume getModuleIcon returns the correct icon in these cases. if (module != null && !module.isDisposed && module.isLinkedAndroidModule()) { return getModuleIcon(module) } } } return null } override fun getModuleIcon(projectSystem: GradleProjectSystem, module: Module): Icon? = getModuleIcon(module) companion object { @JvmStatic fun getModuleIcon(module: Module): Icon = when { module.isHolderModule() || module.isMainModule() -> getAndroidModuleIcon(module.getModuleSystem()) module.isAndroidTestModule() -> StudioIcons.Shell.Filetree.ANDROID_MODULE else -> AllIcons.Nodes.Module } private fun getAndroidModuleIcon(androidModuleSystem: AndroidModuleSystem): Icon { return getAndroidModuleIcon(androidModuleSystem.type) } fun getAndroidModuleIcon(androidProjectType: AndroidModuleSystem.Type): Icon { return when (androidProjectType) { AndroidModuleSystem.Type.TYPE_NON_ANDROID -> AllIcons.Nodes.Module AndroidModuleSystem.Type.TYPE_APP -> StudioIcons.Shell.Filetree.ANDROID_MODULE AndroidModuleSystem.Type.TYPE_FEATURE, AndroidModuleSystem.Type.TYPE_DYNAMIC_FEATURE -> StudioIcons.Shell.Filetree.FEATURE_MODULE AndroidModuleSystem.Type.TYPE_INSTANTAPP -> StudioIcons.Shell.Filetree.INSTANT_APPS AndroidModuleSystem.Type.TYPE_LIBRARY -> StudioIcons.Shell.Filetree.LIBRARY_MODULE AndroidModuleSystem.Type.TYPE_TEST -> StudioIcons.Shell.Filetree.ANDROID_TEST_ROOT else -> StudioIcons.Shell.Filetree.ANDROID_MODULE } } } }
5
Kotlin
227
948
10110983c7e784122d94c7467e9d243aba943bf4
3,763
android
Apache License 2.0
ITunes/app/src/main/java/com/trios2024aa/itunes/ResultScreen.kt
GabrielMaxUA
856,715,949
false
{"Kotlin": 56680}
package com.trios2024aa.itunes import android.media.MediaPlayer import android.util.Log import androidx.activity.compose.BackHandler import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Info import androidx.compose.material.icons.filled.PlayArrow import androidx.compose.material.icons.filled.Refresh import androidx.compose.material.icons.filled.Search import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.SearchBar import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect 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.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.viewModel import coil.compose.rememberAsyncImagePainter import coil.request.ImageRequest import coil.transform.RoundedCornersTransformation @OptIn(ExperimentalMaterial3Api::class) @Composable fun CategoryItem( repository: ITunesRepository = ITunesRepository(itunesService, RssFeedService.instance), viewModel: ITunesViewModel = viewModel(factory = ITunesViewModelFactory(repository)) ) { val items by viewModel.items val searched by viewModel.searched val isLoading by viewModel.isLoading val errorMessage by viewModel.errorMessage var visibleEpisodeIndex by remember { mutableStateOf<Int?>(null) } var query by remember { mutableStateOf("") } var active by remember { mutableStateOf(false) } // Set SearchBar to inactive by default var mediaPlayer: MediaPlayer? by remember { mutableStateOf(null) } var currentlyPlayingUrl by remember { mutableStateOf<String?>(null) } var visibleItemIndex by remember { mutableStateOf<Int?>(null) } // Ensure MediaPlayer is properly disposed when the Composable is destroyed DisposableEffect(Unit) { onDispose { mediaPlayer?.release() mediaPlayer = null } } BackHandler(enabled = visibleItemIndex != null) { // Reset visibleItemIndex to make all items visible again visibleItemIndex = null } Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally ) { SearchBar( query = query, onQueryChange = { query = it }, // Update the query as the user types onSearch = { // Trigger search when user submits query if (query.isNotBlank()) { viewModel.searchTunes(query.trim()) // Perform the search using the ViewModel } active = false // Close the SearchBar after the search is performed }, active = active, onActiveChange = { isActive -> active = isActive // Manage the active state of the search bar }, placeholder = { Text(text = "What are you looking for?", style = TextStyle(color = Color.Gray)) }, trailingIcon = { // Optional: Search button (can also be triggered by pressing Enter) IconButton(onClick = { if (query.isNotBlank()) { viewModel.searchTunes(query.trim()) // Perform the search } active = false }) { Icon(imageVector = Icons.Default.Search, contentDescription = "Search") } }, modifier = Modifier.fillMaxWidth() ) {} if (isLoading) { // Show a loading indicator Text(text = "Loading...", modifier = Modifier.padding(16.dp)) } else if (errorMessage != null) { // Show error message Text(text = errorMessage ?: "", color = Color.Red, modifier = Modifier.padding(16.dp)) } else { LazyColumn(modifier = Modifier.fillMaxSize()) { when { !searched -> { // Initial state before any search item { Spacer(modifier = Modifier.height(16.dp)) } } items.isNotEmpty() -> { items(items.size) { index -> val item = items[index] // If visibleItemIndex is not null, only show the row for that index if (visibleItemIndex == null || visibleItemIndex == index) { Column ( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally ) { Row( modifier = Modifier .padding(8.dp) .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { val imageUrl = item.artworkUrl60 ?: "https://via.placeholder.com/60" val painter = rememberAsyncImagePainter( model = ImageRequest.Builder(LocalContext.current) .data(imageUrl) .transformations(RoundedCornersTransformation(14f)) .build() ) Image( painter = painter, contentDescription = null, modifier = Modifier .width(70.dp) .height(70.dp) .padding(end = 8.dp) ) val isCurrentTrackPlaying = currentlyPlayingUrl == item.previewUrl Icon( imageVector = if (isCurrentTrackPlaying) Icons.Default.Refresh else Icons.Default.PlayArrow, contentDescription = if (isCurrentTrackPlaying) "Pause Preview" else "Play Preview", modifier = Modifier .width(30.dp) .height(30.dp) .padding(end = 8.dp) .clickable { if (isCurrentTrackPlaying) { mediaPlayer?.stop() mediaPlayer?.reset() currentlyPlayingUrl = null } else { val previewUrl = item.previewUrl if (!previewUrl.isNullOrEmpty()) { try { mediaPlayer?.stop() mediaPlayer?.reset() mediaPlayer = MediaPlayer().apply { setDataSource(previewUrl) prepare() start() } currentlyPlayingUrl = previewUrl } catch (e: Exception) { Log.e( "CategoryItem", "Error playing audio: ${e.message}" ) } } } } ) Column(modifier = Modifier.padding(start = 8.dp), horizontalAlignment = Alignment.Start) { Text( text = item.artistName ?: "Unknown Artist", style = TextStyle(fontWeight = FontWeight.Bold), modifier = Modifier .padding(top = 4.dp) .width(150.dp) // Fixed width for the artist name .fillMaxWidth(0.5f), maxLines = 1, overflow = TextOverflow.Ellipsis ) Text( text = item.trackName ?: "Unknown Track", style = TextStyle(fontWeight = FontWeight.Light), modifier = Modifier .padding(top = 4.dp) .fillMaxWidth(0.5f), // Fixed width for the track name maxLines = 1, overflow = TextOverflow.Ellipsis ) } Row( horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically ) { Text( text = item.kind ?: "Unknown", style = TextStyle(fontWeight = FontWeight.Light), modifier = Modifier .padding(top = 8.dp) .fillMaxWidth(0.5f), maxLines = 2, overflow = TextOverflow.Ellipsis ) Icon( imageVector = Icons.Default.Info, contentDescription = "Show Info", modifier = Modifier .width(30.dp) .height(30.dp) .padding(end = 8.dp) .clickable { // Set the visible item index to the tapped one visibleItemIndex = index // Trigger RSS feed fetching for the selected item viewModel.fetchRssFeed(item.feedUrl) } ) } } // Show additional information if this item is the selected one if (visibleItemIndex == index) { // Fetch RSS feed when the item is selected val rssFeed by viewModel.rssFeed rssFeed?.let { feed -> // Display RSS feed details Column( modifier = Modifier .fillMaxWidth() .padding(8.dp) ) { Text( text = "Podcast Title: ${feed.feedTitle}", style = TextStyle(fontWeight = FontWeight.Bold), modifier = Modifier.padding(bottom = 4.dp) ) // Display episodes in a LazyColumn LazyColumn { items(feed.episodes ?: emptyList()) { episode -> Column(modifier = Modifier.padding(vertical = 4.dp)) { Text( text = "Episode: ${episode.title ?: "Unknown"}", style = TextStyle(fontWeight = FontWeight.Bold), modifier = Modifier.padding(bottom = 4.dp) ) Text( text = "Published: ${episode.guid ?: "Unknown"}", style = TextStyle(fontWeight = FontWeight.Light) ) Spacer(modifier = Modifier.height(8.dp)) } } } } } ?: run { // Show loading indicator while the RSS feed is being fetched CircularProgressIndicator(modifier = Modifier.padding(16.dp)) } } } } } } else -> { item { Text( text = "No results found", modifier = Modifier.padding(16.dp) ) } } } } } } }
0
Kotlin
0
0
206d0e366d1e6433c0ff7adc88ac3974f8c9bee8
17,345
AndroidApp5
MIT License
app/src/main/java/com/example/dropy/network/use_case/cart/OrderCheckOutUseCase.kt
dropyProd
705,360,878
false
{"Kotlin": 3916897, "Java": 20617}
package com.example.dropy.network.use_case.cart import com.example.dropy.network.models.PaymentReq import com.example.dropy.network.models.commondataclasses.ActionResultDataClass import com.example.dropy.network.repositories.cart.CartRepository import com.example.dropy.ui.app.AppViewModel import com.example.dropy.ui.screens.shops.frontside.checkout.CheckoutDataClass import com.example.dropy.ui.utils.Resource import kotlinx.coroutines.flow.Flow class OrderCheckOutUseCase( private val cartRepository: CartRepository ) { suspend fun orderCheckOut( paymentReq: PaymentReq ): Flow<Resource<ActionResultDataClass?>> { return cartRepository.orderCheckOut( paymentReq = paymentReq ) } }
0
Kotlin
0
0
6d994c9c61207bac28c49717b6c250656fe4ae6b
737
DropyLateNights
Apache License 2.0
frames/src/main/java/com/checkout/frames/style/theme/colors/TextColors.kt
benju69
584,397,774
true
{"Kotlin": 848030, "Java": 12926}
package com.checkout.frames.style.theme.colors import androidx.annotation.ColorLong public data class TextColors( @ColorLong val titleColor: Long = 0xFF000000, @ColorLong val subTitleColor: Long = 0xFF000000, @ColorLong val infoColor: Long = 0xFF000000, @ColorLong val errorColor: Long = 0XFFFF0000, )
0
null
0
0
b7ee1157babd81a886f3b634c37496cf99e059bf
336
frames-android
MIT License
app/src/main/java/io/sinzak/android/ui/main/profile/certification/VerifyViewModel.kt
SINZAK
567,559,091
false
{"Kotlin": 482864}
package io.sinzak.android.ui.main.profile.certification import dagger.hilt.android.lifecycle.HiltViewModel import io.sinzak.android.R import io.sinzak.android.enums.Page import io.sinzak.android.model.certify.CertifyModel import io.sinzak.android.model.profile.ProfileModel import io.sinzak.android.ui.base.BaseViewModel import kotlinx.coroutines.flow.MutableStateFlow import javax.inject.Inject @HiltViewModel class VerifyViewModel @Inject constructor( val pModel : ProfileModel, val certifyModel: CertifyModel ) : BaseViewModel() { val profile get() = pModel.profile val linkInput = MutableStateFlow("") val buttonEnabled = MutableStateFlow(false) /************************************************ * 입력을 받습니다 ***************************************/ /** * 포트폴리오 링크를 입력 받습니다 */ fun linkInputText(cs : CharSequence) { cs.toString().let { if (linkInput.value != it) linkInput.value = it buttonEnabled.value = it.isNotEmpty() } } /************************************************ * 클릭 시 실행 ***************************************/ /** * 학교 인증하기 버튼을 누릅니다 */ fun gotoCertificationPage(hasCert : Boolean){ if(!hasCert) navigation.changePage(Page.PROFILE_CERTIFICATION) else return } /** * 신청하기 버튼을 누릅니다 */ fun onSubmit(cert_author:Boolean, verifyProcess : Boolean) { if (cert_author){ uiModel.showToast(valueModel.getString(R.string.str_already_certify)) return } if (verifyProcess){ uiModel.showToast(valueModel.getString(R.string.str_please_wait)) return } certifyModel.requestCertifyPortfolio(linkInput.value.trim()) useFlag(certifyModel.flagPortfolioSuccess){ navigation.changePage(Page.PROFILE) navigation.clearHistory() } } /** * 뒤로가기 버튼을 누릅니다 */ fun onBackPressed() { navigation.revealHistory() } }
0
Kotlin
0
3
3467e8ee8afeb6b91b51f3a454f7010bc717c436
2,053
sinzak-android
MIT License
components/chartview/src/main/java/io/horizontalsystems/chartview/ChartMinimal.kt
horizontalsystems
142,825,178
false
null
package io.horizontalsystems.chartview import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import androidx.constraintlayout.widget.ConstraintLayout import io.horizontalsystems.chartview.Indicator.Candle import io.horizontalsystems.chartview.databinding.ViewChartMinimalBinding import io.horizontalsystems.chartview.models.ChartConfig class ChartMinimal @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : ConstraintLayout(context, attrs, defStyleAttr) { private val binding = ViewChartMinimalBinding.inflate(LayoutInflater.from(context), this) private val config = ChartConfig(context, attrs) private val mainCurve = ChartCurve2(config) private val mainGradient = ChartGradient() fun setData(data: ChartData) { config.setTrendColor(data) val candleValues = data.valuesByTimestamp(Candle) val minCandleValue = candleValues.values.minOrNull() ?: 0f val maxCandleValue = candleValues.values.maxOrNull() ?: 0f val mainCurveAnimator = CurveAnimator( candleValues, data.startTimestamp, data.endTimestamp, minCandleValue, maxCandleValue, null, binding.chartMain.shape.right, binding.chartMain.shape.bottom, 0f, config.curveMinimalVerticalOffset, ) mainCurveAnimator.nextFrame(1f) mainCurve.setShape(binding.chartMain.shape) mainCurve.setCurveAnimator(mainCurveAnimator) mainCurve.setColor(config.curveColor) mainGradient.setCurveAnimator(mainCurveAnimator) mainGradient.setShape(binding.chartMain.shape) mainGradient.setShader(config.curveGradient) binding.chartMain.clear() binding.chartMain.add(mainCurve, mainGradient) binding.chartMain.invalidate() } }
168
null
364
895
218cd81423c570cdd92b1d5161a600d07c35c232
1,942
unstoppable-wallet-android
MIT License
nft/api/src/main/kotlin/com/rarible/protocol/nft/api/controller/CollectionController.kt
NFTDroppr
418,665,809
true
{"Kotlin": 2329156, "Scala": 37343, "Shell": 6001, "HTML": 547}
package com.rarible.protocol.nft.api.controller import com.rarible.core.common.convert import com.rarible.protocol.dto.NftCollectionDto import com.rarible.protocol.dto.NftCollectionsDto import com.rarible.protocol.dto.NftTokenIdDto import com.rarible.protocol.nft.api.service.colllection.CollectionService import com.rarible.protocol.nft.core.model.TokenFilter import org.springframework.core.convert.ConversionService import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.RestController import scalether.domain.Address import java.lang.Integer.min @RestController class CollectionController( private val collectionService: CollectionService, private val conversionService: ConversionService ) : NftCollectionControllerApi { override suspend fun getNftCollectionById( collection: String ): ResponseEntity<NftCollectionDto> { val result = collectionService .get(Address.apply(collection)) .let { conversionService.convert<NftCollectionDto>(it) } return ResponseEntity.ok(result) } override suspend fun searchNftAllCollections( continuation: String?, size: Int? ): ResponseEntity<NftCollectionsDto> { val filter = TokenFilter.All(continuation, size.limit()) val result = searchCollections(filter) return ResponseEntity.ok(result) } override suspend fun searchNftCollectionsByOwner( owner: String, continuation: String?, size: Int? ): ResponseEntity<NftCollectionsDto> { val filter = TokenFilter.ByOwner( Address.apply(owner), continuation, size.limit() ) val result = searchCollections(filter) return ResponseEntity.ok(result) } override suspend fun generateNftTokenId( collection: String, minter: String ): ResponseEntity<NftTokenIdDto> { val collectionAddress = Address.apply(collection) val minterAddress = Address.apply(minter) val nextTokenId = collectionService.generateId(collectionAddress, minterAddress) val result = conversionService.convert<NftTokenIdDto>(nextTokenId) return ResponseEntity.ok(result) } private suspend fun searchCollections(filter: TokenFilter): NftCollectionsDto { val collections = collectionService.search(filter) val continuation = if (collections.isEmpty() || collections.size < filter.size) null else collections.last().id.toString() return NftCollectionsDto( total = collections.size.toLong(), collections = collections.map { conversionService.convert<NftCollectionDto>(it) }, continuation = continuation ) } companion object { fun Int?.limit(): Int = min(this ?: DEFAULT_MAX_SIZE, DEFAULT_MAX_SIZE) private const val DEFAULT_MAX_SIZE = 1_000 } }
0
Kotlin
0
1
b1efdaceab8be95429befe80ce1092fab3004d18
2,934
ethereum-indexer
MIT License
app/src/main/java/org/imaginativeworld/simplemvvm/utils/SharedPref.kt
ImaginativeShohag
225,951,395
false
{"Kotlin": 483782, "Java": 1056}
/* * Copyright 2023 Md. Mahmudul Hasan Shohag * * 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. * * ------------------------------------------------------------------------ * * Project: Simple MVVM * Developed by: @ImaginativeShohag * * Md. Mahmudul Hasan Shohag * [email protected] * * Source: https://github.com/ImaginativeShohag/Simple-MVVM */ package org.imaginativeworld.simplemvvm.utils import android.content.Context import android.content.SharedPreferences import com.squareup.moshi.Moshi import dagger.hilt.android.qualifiers.ApplicationContext import javax.inject.Inject import javax.inject.Singleton import org.imaginativeworld.simplemvvm.BuildConfig import org.imaginativeworld.simplemvvm.models.user.User import timber.log.Timber @Singleton class SharedPref @Inject constructor( @ApplicationContext context: Context ) { companion object { private const val PREF_TOKEN = "token" private const val PREF_USER = "user" } private val context: Context = context.applicationContext @Volatile private var sharedPref: SharedPreferences? = null @Volatile private var user: User? = null private fun getSharedPerf(): SharedPreferences { return sharedPref ?: synchronized(this) { context.getSharedPreferences( "${BuildConfig.APPLICATION_ID}.main", Context.MODE_PRIVATE ) } } fun reset() { getSharedPerf().edit().clear().apply() user = null } // ---------------------------------------------------------------- fun setToken(token: String) { getSharedPerf() .edit() .apply { putString(PREF_TOKEN, token) apply() } } fun getToken(): String? { return getSharedPerf().getString(PREF_TOKEN, null) } // ---------------------------------------------------------------- fun setUser(user: User) { getSharedPerf() .edit() .apply { val moshi = Moshi.Builder().build() val jsonAdapter = moshi.adapter(User::class.java) putString(PREF_USER, jsonAdapter.toJson(user)) apply() } } fun getUser(): User? { return user ?: synchronized(this) { getSharedPerf() .let { val moshi = Moshi.Builder().build() val jsonAdapter = moshi.adapter(User::class.java) val userJson = it.getString(PREF_USER, null) user = if (userJson == null) { null } else { jsonAdapter.fromJson(userJson) } Timber.d("user: $user") user } } } // ---------------------------------------------------------------- fun isUserLoggedIn(): Boolean { return getUser() != null } }
0
Kotlin
12
65
5ddbfcf932de943faf6a47654adbd6a018a1f991
3,544
Simple-MVVM
Apache License 2.0
domain/src/main/java/com/anytypeio/anytype/domain/objects/CreateBookmarkObject.kt
anyproto
647,371,233
false
{"Kotlin": 11623123, "Java": 69306, "Shell": 11350, "Makefile": 1334}
package com.anytypeio.anytype.domain.objects import com.anytypeio.anytype.core_models.Id import com.anytypeio.anytype.core_models.Struct import com.anytypeio.anytype.core_models.Url import com.anytypeio.anytype.domain.base.BaseUseCase import com.anytypeio.anytype.domain.block.repo.BlockRepository import javax.inject.Inject /** * Use-case for creating bookmark object from url. */ class CreateBookmarkObject @Inject constructor( private val repo: BlockRepository ) : BaseUseCase<Id, CreateBookmarkObject.Params>() { override suspend fun run(params: Params) = safe { repo.createBookmarkObject( space = params.space, url = params.url, details = params.details ) } data class Params( val space: Id, val url: Url, val details: Struct = emptyMap() ) }
45
Kotlin
43
528
c708958dcb96201ab7bb064c838ffa8272d5f326
849
anytype-kotlin
RSA Message-Digest License
src/main/kotlin/BitcoindRPCConnection.kt
snktn
389,790,064
false
null
import java.io.BufferedReader import java.io.IOException import java.io.InputStreamReader import java.net.* import kotlin.jvm.Throws class BitcoindRPCConnection (private val url: URL) { @Throws(ConnectException::class, IOException::class) fun getRawTxAddresses(id: String, tx: String) : ArrayList<String> { val list = ArrayList<String>() val jsonInputString = rpcString(id, "getrawtransaction", "\"$tx\", true" ) "\"addresses\":\\[\"(\\w+)".toRegex().findAll(getResponse(jsonInputString)).forEach { list.add(it.groupValues[1]) } return list } @Throws(ConnectException::class, IOException::class) fun getRawMemPool(id: String) : ArrayList<String> { val list = ArrayList<String>() val jsonInputString = rpcString(id, "getrawmempool" ) "\\w{64}".toRegex().findAll(getResponse(jsonInputString)).forEach { list.add(it.value) } return list } @Throws(ConnectException::class, IOException::class) fun getBlockCount(id: String) : Int? { val jsonInputString = rpcString(id, "getblockcount") return ("\\d+".toRegex().find(getResponse(jsonInputString))?.value?.toInt()) } fun auth (userName: String, passWord: String) { Authenticator.setDefault(object : Authenticator() { override fun getPasswordAuthentication(): PasswordAuthentication { return PasswordAuthentication(userName, passWord.toCharArray()) } }) } private fun rpcString (id: String, method: String, params: String = "") : String { return "{\"jsonrpc\":\"1.0\",\"id\":\"$id\",\"method\":\"$method\",\"params\":[$params]}" } @Throws(ConnectException::class) fun connect (jsonInputString: String) : HttpURLConnection { val connection: HttpURLConnection = url.openConnection() as HttpURLConnection connection.requestMethod = "POST" connection.setRequestProperty("Content-Type", "application/json; utf-8") connection.setRequestProperty("Accept", "application/json") connection.doOutput = true connection.outputStream.use { outputStream -> val input = jsonInputString.toByteArray(charset("utf-8")) outputStream.write(input, 0, input.size) } return connection } @Throws(IOException::class) private fun getResponse (jsonInputString: String ) : String { val response = StringBuilder() val connection = connect(jsonInputString) BufferedReader(InputStreamReader(connection.inputStream, "utf-8")).use { bufferedReader -> var responseLine: String? while (bufferedReader.readLine().also { responseLine = it } != null) { response.append(responseLine!!.trim { it <= ' ' }) } } return response.toString() } }
0
Kotlin
0
0
e9e116073b7ee33eab9a4594bce716950726022b
2,888
bitcoind_rpc_client
MIT License
io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/GetChar2.kt
tuProlog
230,784,338
false
{"Kotlin": 3797695, "Java": 18690, "ANTLR": 10366, "CSS": 1535, "JavaScript": 894, "Prolog": 818}
package it.unibo.tuprolog.solve.libs.io.primitives import it.unibo.tuprolog.core.Term import it.unibo.tuprolog.solve.ExecutionContext import it.unibo.tuprolog.solve.libs.io.primitives.IOPrimitiveUtils.ensuringArgumentIsInputChannel import it.unibo.tuprolog.solve.libs.io.primitives.IOPrimitiveUtils.ensuringArgumentIsVarOrChar import it.unibo.tuprolog.solve.libs.io.primitives.IOPrimitiveUtils.readCharAndReply import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object GetChar2 : BinaryRelation.NonBacktrackable<ExecutionContext>("get_char") { override fun Solve.Request<ExecutionContext>.computeOne(first: Term, second: Term): Solve.Response { val channel = ensuringArgumentIsInputChannel(0) ensuringArgumentIsVarOrChar(1) return readCharAndReply(channel, second) } }
73
Kotlin
13
76
8594ebf46b90db619a5c125a73ee0d5d9ad6440f
855
2p-kt
Apache License 2.0
geary-core/src/main/kotlin/com/mineinabyss/geary/ecs/events/EntityRemoved.kt
MineInAbyss
306,093,350
false
null
package com.mineinabyss.geary.ecs.events public class EntityRemoved
20
Kotlin
9
16
6cae001ed4eb7803a921f772752d26f4e7a1d85d
69
Geary
MIT License
rxpm/src/test/kotlin/me/dmdev/rxpm/navigation/NavigationMessageDispatcherTest.kt
vchernyshov
140,483,720
true
{"Kotlin": 106029}
package me.dmdev.rxpm.navigation import com.nhaarman.mockitokotlin2.* import org.junit.Before import org.junit.Test import kotlin.test.assertFailsWith class NavigationMessageDispatcherTest { private val testMessage = object : NavigationMessage {} private lateinit var workingHandler: NavigationMessageHandler private lateinit var ignoringHandler: NavigationMessageHandler private lateinit var unreachableHandler: NavigationMessageHandler @Before fun setUp() { workingHandler = mockMessageHandler(true) ignoringHandler = mockMessageHandler(false) unreachableHandler = mockMessageHandler(true) } private fun mockMessageHandler(handleMessages: Boolean): NavigationMessageHandler { return mock { on { handleNavigationMessage(any()) } doReturn handleMessages } } @Test fun handleMessage() { val dispatcher = createDispatcher(listOf(Unit, ignoringHandler, workingHandler, unreachableHandler)) dispatcher.dispatch(testMessage) verify(ignoringHandler).handleNavigationMessage(testMessage) verify(workingHandler).handleNavigationMessage(testMessage) verifyZeroInteractions(unreachableHandler) } private fun createDispatcher(handlers: List<Any>): NavigationMessageDispatcher { return object : NavigationMessageDispatcher(Unit) { var k = 0 override fun getParent(node: Any?): Any? { val result: Any? = try { handlers[k] } catch (e: ArrayIndexOutOfBoundsException) { null } k++ return result } } } @Test fun failsIfMessageNotHandled() { val dispatcher = createDispatcher(listOf(Unit, ignoringHandler)) assertFailsWith<NotHandledNavigationMessageException> { dispatcher.dispatch(testMessage) } } }
0
Kotlin
0
0
2c4d88932f5ac98d0e063b2ebc7e41a8e4f754fc
1,956
RxPM
MIT License
app/src/main/java/com/inspiredandroid/linuxcommandbibliotheca/fragments/AboutFragment.kt
mattcilus
206,930,830
true
{"Kotlin": 127663}
package com.inspiredandroid.linuxcommandbibliotheca.fragments import android.content.ActivityNotFoundException import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.inspiredandroid.linuxcommandbibliotheca.R import com.inspiredandroid.linuxcommandbibliotheca.misc.Constants import kotlinx.android.synthetic.main.fragment_about.* /* Copyright 2019 Simon Schubert * * 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. */ class AboutFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_about, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) btnBimo.setOnClickListener { startAppMarketActivity(Constants.PACKAGE_BIMO) } btnOrcgenocide.setOnClickListener { startAppMarketActivity(Constants.PACKAGE_ORCGENOCIDE) } btnAncientGenocide.setOnClickListener { startAppMarketActivity(Constants.PACKAGE_ANCIENTGENOCIDE) } btnQuiz.setOnClickListener { startAppMarketActivity(Constants.PACKAGE_QUIZ) } btnRemote.setOnClickListener { startAppMarketActivity(Constants.PACKAGE_LINUXREMOTE) } btnRate.setOnClickListener { startAppMarketActivity(Constants.PACKAGE_COMMANDLIBRARY) } btnIcons8.setOnClickListener { openIcons8Website() } } private fun openIcons8Website() { try { val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://www.icons8.com")) startActivity(intent) } catch (ignored: ActivityNotFoundException) { } } /** * Show app in the Play Store. If Play Store is not installed, show it in the browser instead. * * @param appPackageName package mName */ private fun startAppMarketActivity(appPackageName: String) { try { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$appPackageName"))) } catch (e: android.content.ActivityNotFoundException) { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=$appPackageName"))) } } }
0
null
0
0
d4d25ecdf8acfc05c4995fbc7fab6c2cc6764020
2,897
LinuxCommandBibliotheca
Apache License 2.0
src/main/kotlin/com/github/windchopper/tools/everquest/log/parser/misc/TimestampedMap.kt
windchopper
71,001,170
false
null
package com.github.windchopper.tools.everquest.log.parser.misc import java.time.Instant class TimestampedMap<K, V>(private val delegate: MutableMap<K, V>): MutableMap<K, V> by delegate { private var lastModificationTimeInternal: Instant = Instant.MIN val lastModificationTime: Instant get() = lastModificationTimeInternal override fun put(key: K, value: V): V? { return delegate.put(key, value).also { lastModificationTimeInternal = Instant.now() } } }
0
Kotlin
0
0
6a0eb59b7b732df9916932adf90752b00e60a186
510
everquest-log-parser
Apache License 2.0
idea/testData/diagnosticMessage/typeVarianceConflictInTypeAliasExpansion.kt
JakeWharton
99,388,807
false
null
// !DIAGNOSTICS_NUMBER: 1 // !DIAGNOSTICS: TYPE_VARIANCE_CONFLICT_IN_EXPANDED_TYPE // !MESSAGE_TYPE: TEXT interface InvOut<T1, out T2> typealias AInvOut<T1, T2> = InvOut<T1, T2> typealias AInvOutTT<T> = AInvOut<T, T> class Test<out S> : AInvOutTT<S>
0
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
252
kotlin
Apache License 2.0
src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/queries/StreamModelLines.kt
world-federation-of-advertisers
349,561,061
false
{"Kotlin": 10143809, "Starlark": 951001, "C++": 627937, "CUE": 193010, "HCL": 162357, "TypeScript": 101485, "Python": 77600, "Shell": 20877, "CSS": 9620, "Go": 8063, "JavaScript": 5305, "HTML": 2489}
/* * Copyright 2023 The Cross-Media Measurement Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wfanet.measurement.kingdom.deploy.gcloud.spanner.queries import com.google.cloud.spanner.Statement import org.wfanet.measurement.gcloud.common.toGcloudTimestamp import org.wfanet.measurement.gcloud.spanner.appendClause import org.wfanet.measurement.gcloud.spanner.bind import org.wfanet.measurement.internal.kingdom.StreamModelLinesRequest import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.ModelLineReader class StreamModelLines(private val requestFilter: StreamModelLinesRequest.Filter, limit: Int = 0) : SimpleSpannerQuery<ModelLineReader.Result>() { override val reader = ModelLineReader().fillStatementBuilder { appendWhereClause(requestFilter) appendClause( """ ORDER BY ModelLines.CreateTime ASC, ModelProviders.ExternalModelProviderId ASC, ModelSuites.ExternalModelSuiteId ASC, ModelLines.ExternalModelLineId ASC """ .trimIndent() ) if (limit > 0) { appendClause("LIMIT @${LIMIT}") bind(LIMIT to limit.toLong()) } } private fun Statement.Builder.appendWhereClause(filter: StreamModelLinesRequest.Filter) { val conjuncts = mutableListOf<String>() if (filter.externalModelProviderId != 0L) { conjuncts.add("ExternalModelProviderId = @${EXTERNAL_MODEL_PROVIDER_ID}") bind(EXTERNAL_MODEL_PROVIDER_ID to filter.externalModelProviderId) } if (filter.externalModelSuiteId != 0L) { conjuncts.add("ExternalModelSuiteId = @${EXTERNAL_MODEL_SUITE_ID}") bind(EXTERNAL_MODEL_SUITE_ID to filter.externalModelSuiteId) } if (filter.hasAfter()) { conjuncts.add( """ ((ModelLines.CreateTime > @${CREATED_AFTER}) OR (ModelLines.CreateTime = @${CREATED_AFTER} AND ModelProviders.ExternalModelProviderId > @${EXTERNAL_MODEL_PROVIDER_ID}) OR (ModelLines.CreateTime = @${CREATED_AFTER} AND ModelProviders.ExternalModelProviderId = @${EXTERNAL_MODEL_PROVIDER_ID} AND ModelSuites.ExternalModelSuiteId > @${EXTERNAL_MODEL_SUITE_ID}) OR (ModelLines.CreateTime = @${CREATED_AFTER} AND ModelProviders.ExternalModelProviderId = @${EXTERNAL_MODEL_PROVIDER_ID} AND ModelSuites.ExternalModelSuiteId = @${EXTERNAL_MODEL_SUITE_ID} AND ModelLines.ExternalModelLineId > @${EXTERNAL_MODEL_LINE_ID})) """ .trimIndent() ) bind(CREATED_AFTER to filter.after.createTime.toGcloudTimestamp()) bind(EXTERNAL_MODEL_LINE_ID to filter.after.externalModelLineId) } if (filter.typeValueList.isNotEmpty()) { conjuncts.add("ModelLines.Type IN UNNEST(@${TYPES})") bind(TYPES).toInt64Array(filter.typeValueList.map { it.toLong() }) } if (conjuncts.isEmpty()) { return } appendClause("WHERE ") append(conjuncts.joinToString(" AND ")) } companion object { const val LIMIT = "limit" const val EXTERNAL_MODEL_PROVIDER_ID = "externalModelProviderId" const val EXTERNAL_MODEL_SUITE_ID = "externalModelSuiteId" const val EXTERNAL_MODEL_LINE_ID = "externalModelLineId" const val CREATED_AFTER = "createdAfter" const val TYPES = "types" } }
145
Kotlin
11
36
ba2d2d8d3d4527d844e6d168273b1c2fabfd5d4e
3,839
cross-media-measurement
Apache License 2.0
features/goals/src/main/java/app/chamich/feature/goals/ui/bottomsheet/colors/ColorsBottomSheet.kt
Coinfo
278,306,465
false
{"Kotlin": 136112, "Ruby": 866}
/* * Copyright (c) 2020 Chamich Apps. All rights reserved. */ package app.chamich.feature.goals.ui.bottomsheet.colors import android.content.res.ColorStateList import android.os.Bundle import android.view.View import androidx.annotation.ColorRes import androidx.core.content.ContextCompat import androidx.core.os.bundleOf import androidx.core.view.ViewCompat import androidx.fragment.app.setFragmentResult import androidx.lifecycle.ViewModel import androidx.navigation.fragment.findNavController import app.chamich.feature.goals.R import app.chamich.feature.goals.databinding.GoalsBottomSheetDialogColorsBinding import app.chamich.feature.goals.model.Color import app.chamich.feature.goals.ui.bottomsheet.GoalsBottomSheet internal class ColorsBottomSheet : GoalsBottomSheet<ViewModel, GoalsBottomSheetDialogColorsBinding>() { private lateinit var selectedColor: Color //////////////////////////////////////////////////////////////////////////////////////////////// //region Fragment Override Functions override fun getLayoutId() = R.layout.goals_bottom_sheet_dialog_colors override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupBindings() setupChips(getColorId()) } override fun getViewModelClass() = ViewModel::class.java //endregion //////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// //region Binding Functions fun onUseColorClicked() { setFragmentResult(KEY_RESULT_LISTENER, bundleOf(KEY_RESULT_COLOR to selectedColor)) findNavController().navigateUp() } fun onCancelClicked() { findNavController().navigateUp() } //endregion //////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// //region Private Functions private fun setupBindings() { binding.fragment = this } private fun setupChips(colorId: Int) = Color.asList().forEach { color -> binding.chipGroupColors.addView( inflateAsChip(R.layout.goals_chip_color, binding.chipGroupColors).apply { id = ViewCompat.generateViewId() chipBackgroundColor = getColor(color.colorRes) setOnClickListener { selectedColor = color } setOnCheckedChangeListener { chip, checked -> chip.setText(getCheckedText(checked)) } isChecked = color.id == colorId }) } private fun getColor(@ColorRes color: Int) = ColorStateList.valueOf(ContextCompat.getColor(requireContext(), color)) private fun getColorId() = arguments?.getInt(KEY_COLOR_ID) ?: Color.default().id private fun getCheckedText(checked: Boolean) = if (checked) R.string.goals_colors_text_check_mark else R.string.goals_colors_text_empty //endregion //////////////////////////////////////////////////////////////////////////////////////////////// companion object { const val KEY_COLOR_ID = "KEY_COLOR_ID" const val KEY_RESULT_COLOR = "KEY_RESULT_COLOR" const val KEY_RESULT_LISTENER = "KEY_RESULT_LISTENER" } }
0
Kotlin
3
16
581bf4e4ff7e9cb5067bdf25e4e340b56ebaab92
3,495
Perfectus
Apache License 2.0
app/src/main/java/com/topjohnwu/magisk/ui/theme/Theme.kt
Joyoe
448,423,587
false
{"C++": 749668, "Kotlin": 467515, "Java": 133329, "Shell": 84180, "Python": 14492, "C": 11376, "Makefile": 4612}
package com.topjohnwu.magisk.ui.theme import com.topjohnwu.magisk.R import com.topjohnwu.magisk.core.Config enum class Theme( val themeName: String, val themeRes: Int ) { Piplup( themeName = "Piplup", themeRes = R.style.ThemeFoundationMD2_Piplup ), PiplupAmoled( themeName = "AMOLED", themeRes = R.style.ThemeFoundationMD2_Amoled ), Rayquaza( themeName = "Rayquaza", themeRes = R.style.ThemeFoundationMD2_Rayquaza ), Zapdos( themeName = "Zapdos", themeRes = R.style.ThemeFoundationMD2_Zapdos ), Charmeleon( themeName = "Charmeleon", themeRes = R.style.ThemeFoundationMD2_Charmeleon ), Mew( themeName = "Mew", themeRes = R.style.ThemeFoundationMD2_Mew ), Salamence( themeName = "Salamence", themeRes = R.style.ThemeFoundationMD2_Salamence ), Fraxure( themeName = "Fraxure (Legacy)", themeRes = R.style.ThemeFoundationMD2_Fraxure ); val isSelected get() = Config.themeOrdinal == ordinal fun select() { Config.themeOrdinal = ordinal } companion object { val selected get() = values().getOrNull(Config.themeOrdinal) ?: Piplup } }
0
C++
3
2
f348245daf708ebd5d9cb8e4c3be49ca7c010ce4
1,269
Magisk_jojo_build23013
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppscourtregisterapi/jpa/CourtTypeRepository.kt
ministryofjustice
814,540,723
false
{"Kotlin": 165408, "PLpgSQL": 3634, "Dockerfile": 1366}
package uk.gov.justice.digital.hmpps.hmppscourtregisterapi.jpa import jakarta.persistence.Entity import jakarta.persistence.Id import org.springframework.data.repository.CrudRepository import org.springframework.stereotype.Repository @Repository interface CourtTypeRepository : CrudRepository<CourtType, String> @Entity data class CourtType( @Id val id: String, var description: String, ) { companion object { fun from(oUCodeL1Name: String): CourtType { return CourtType(oUCodeL1Name.uppercase().replace(" ", ""), oUCodeL1Name) } } }
1
Kotlin
0
0
2ba3eff9c9ae12960564c485894fa14761953b42
562
hmpps-court-register-api
MIT License
App/app/src/main/java/com/example/app/Apps.kt
mobibyte
768,909,954
false
{"Kotlin": 11707}
package com.example.app import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @Composable fun AppsScreen() { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { Text(text = "Apps Screen") } }
0
Kotlin
1
1
0c5fe00dc03a2ab72dcf9a794c6ee2db795ec217
458
social-coding-android
MIT License
androidSample/src/main/kotlin/com/alorma/compose/settings/sample/MainActivity.kt
alorma
360,568,361
false
{"Kotlin": 47398}
package com.alorma.compose.settings.sample import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import com.alorma.compose.settings.sample.theme.ComposeSettingsTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ComposeSettingsTheme { SettingsScreen() } } } }
6
Kotlin
25
290
538efa0d0ebebe9f979fc40720da9b5b1e15b502
454
Compose-Settings
MIT License
domain/src/main/kotlin/foo/bar/clean/domain/services/csv/CsvParserImp.kt
erdo
396,050,391
false
{"Kotlin": 385322, "Shell": 2594}
package foo.bar.clean.domain.services.csv import java.util.StringTokenizer class CsvParser( csvData: String, delimiter: String = CSV_DEFAULT_DELIMITER, ) : Iterable<CsvParser.Line> { private val lines: MutableList<Line> = ArrayList() init { require(delimiter.isNotBlank()) { throw RuntimeException("delimiter needs to be at least 1 non-whitespace character") } parseLines(csvData, delimiter) } operator fun get(index: Int): Line = lines[index] override fun iterator(): MutableIterator<Line> { return lines.iterator() } private fun parseLines(csvData: String, delimiter: String) { val stringTokenizer = StringTokenizer(csvData, CSV_LINE_TERMINATOR, false) while (stringTokenizer.hasMoreTokens()) { lines.add(Line(stringTokenizer.nextToken(), delimiter)) } } class Line( line: String, delimiter: String, ) : Iterable<String> { private val columns: MutableList<String> = ArrayList() init { val stringTokenizer = StringTokenizer(line, delimiter, false) while (stringTokenizer.hasMoreTokens()) { columns.add(stringTokenizer.nextToken()); } } operator fun get(index: Int): String = columns[index] override fun iterator(): MutableIterator<String> { return columns.iterator() } } }
0
Kotlin
0
0
763a6fd6528fa51eaf78a2631ad56fba0d2542d3
1,446
commercial-template
Apache License 2.0
base/base-common-android/src/main/java/dev/dexsr/klio/base/theme/md3/compose/Theme.kt
flammky
462,795,948
false
null
package dev.dexsr.klio.base.theme.md3.compose import androidx.compose.material3.ColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.ReadOnlyComposable import androidx.compose.runtime.State import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.graphics.Color import dev.dexsr.klio.base.theme.md3.MD3Theme val MD3Theme.colorScheme: ColorScheme @Composable @ReadOnlyComposable get() = LocalColorScheme.current val MD3Theme.lightColorScheme: ColorScheme @Composable @ReadOnlyComposable get() = LocalLightColorScheme.current val MD3Theme.darkColorScheme: ColorScheme @Composable @ReadOnlyComposable get() = LocalDarkColorScheme.current @Composable fun MD3Theme.backgroundColorAsState(): State<Color> { return rememberUpdatedState(newValue = colorScheme.background) } @Composable fun MD3Theme.backgroundContentColorAsState(): State<Color> { return rememberUpdatedState(newValue = colorScheme.onBackground) } @Composable fun MD3Theme.primaryColorAsState(): State<Color> { return rememberUpdatedState(newValue = colorScheme.primary) } @Composable fun MD3Theme.surfaceColorAsState(): State<Color> { return rememberUpdatedState(newValue = colorScheme.surface) } @Composable fun MD3Theme.surfaceContentColorAsState(): State<Color> { return rememberUpdatedState(newValue = colorScheme.onSurface) } @Composable fun MD3Theme.surfaceVariantColorAsState(): State<Color> { return rememberUpdatedState(newValue = colorScheme.surfaceVariant) } @Composable fun MD3Theme.surfaceVariantContentColorAsState(): State<Color> { return rememberUpdatedState(newValue = colorScheme.onSurfaceVariant) } @Composable fun MD3Theme.secondaryContainerColorAsState(): State<Color> { return rememberUpdatedState(newValue = colorScheme.secondaryContainer) } @Composable fun MD3Theme.secondaryContainerContentColorAsState(): State<Color> { return rememberUpdatedState(newValue = colorScheme.onSecondaryContainer) } @Composable fun MD3Theme.surfaceColorAsState( transform: (Color) -> Color ): State<Color> { return rememberUpdatedState(newValue = transform(colorScheme.surface)) } @Composable fun MD3Theme.outlineVariantColorAsState(): State<Color> { return rememberUpdatedState(newValue = colorScheme.outlineVariant) } @Composable fun MD3Theme.surfaceTintColorAsState(): State<Color> { return rememberUpdatedState(newValue = colorScheme.surfaceTint) } @Composable inline fun <T> MD3Theme.foldLightOrDarkTheme( light: () -> T, dark: () -> T ): T = foldLightOrDarkTheme(!LocalIsThemeDark.current, light, dark) inline fun <T> MD3Theme.foldLightOrDarkTheme( isLight: Boolean, light: () -> T, dark: () -> T ): T = if (isLight) light() else dark() @Composable inline fun MD3Theme.blackOrWhite(): Color = if (LocalIsThemeDark.current) { Color.Black } else { Color.White } @Composable inline fun MD3Theme.blackOrWhiteContent(): Color = if (LocalIsThemeDark.current) { Color.White } else { Color.Black }
0
null
6
56
2b8b4affab4306e351cfc8721c15a5bc7ecba908
3,061
Music-Player
Apache License 2.0
awareness/src/main/java/com/hms/lib/commonmobileservices/awareness/model/AwarenessType.kt
Explore-In-HMS
402,745,331
false
{"Kotlin": 593917}
// Copyright 2020. Explore in HMS. All rights reserved. // // 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.hms.lib.commonmobileservices.awareness.model enum class AwarenessType { WEATHER, BEHAVIOUR, TIME, HEADSET, LOCATION }
3
Kotlin
6
50
68640eadd9950bbdd9aac52dad8d22189a301859
757
common-mobile-services
Apache License 2.0
SKIE/kotlin-compiler/core/src/commonMain/kotlin/co/touchlab/skie/phases/sir/type/PropagateSirVisibilityToClassesPhase.kt
touchlab
685,579,240
false
null
package co.touchlab.skie.phases.sir.type import co.touchlab.skie.kir.element.KirClass import co.touchlab.skie.phases.SirPhase import co.touchlab.skie.sir.element.SirClass import co.touchlab.skie.sir.element.SirModule import co.touchlab.skie.sir.element.SirVisibility import co.touchlab.skie.sir.element.kirClassOrNull import co.touchlab.skie.sir.element.superClassType import co.touchlab.skie.sir.element.superProtocolTypes import co.touchlab.skie.sir.type.SirType object PropagateSirVisibilityToClassesPhase : SirPhase { context(SirPhase.Context) override suspend fun execute() { val updaterProvider = TypeVisibilityUpdaterProvider(sirProvider.allLocalClasses) updaterProvider.allTypeVisibilityUpdaters.forEach { it.propagateVisibility() } } private class TypeVisibilityUpdaterProvider( sirClasses: List<SirClass>, ) { private val cache = sirClasses.associateWith { ClassVisibilityUpdater(it) } init { cache.values.forEach { it.initialize(this) } } val allTypeVisibilityUpdaters: Collection<ClassVisibilityUpdater> = cache.values operator fun get(sirClass: SirClass): ClassVisibilityUpdater = cache.getValue(sirClass) } private class ClassVisibilityUpdater(private val sirClass: SirClass) { private val directDependents = mutableListOf<ClassVisibilityUpdater>() fun initialize(typeVisibilityUpdaterProvider: TypeVisibilityUpdaterProvider) { getDependencies() .filter { it.module is SirModule.Skie || it.module is SirModule.Kotlin } .forEach { typeVisibilityUpdaterProvider[it].registerDirectDependentDeclaration(this) } } private fun registerDirectDependentDeclaration(typeVisibilityUpdater: ClassVisibilityUpdater) { directDependents.add(typeVisibilityUpdater) } fun propagateVisibility() { directDependents.forEach { it.coerceVisibilityAtMost(sirClass.visibility) } } private fun coerceVisibilityAtMost(limit: SirVisibility) { val newVisibility = sirClass.visibility.coerceAtMost(limit) if (sirClass.visibility == newVisibility) { return } sirClass.visibility = newVisibility propagateVisibility() } private fun getDependencies(): Set<SirClass> = setOfNotNull( sirClass.namespace?.classDeclaration, (sirClass.kirClassOrNull?.parent as? KirClass)?.originalSirClass, ) + sirClass.typeParameters.flatMap { typeParameter -> typeParameter.bounds.flatMap { it.type.referencedClasses } }.toSet() + getSuperTypesDependencies() private fun getSuperTypesDependencies(): List<SirClass> = if (sirClass.kind != SirClass.Kind.Protocol) { val classSuperType = listOfNotNull(sirClass.superClassType) val protocolSuperTypes = sirClass.superProtocolTypes val consideredTypes = protocolSuperTypes.flatMap { it.typeArguments } + classSuperType consideredTypes.flatMap { it.referencedClasses } } else { sirClass.superTypes.flatMap { it.referencedClasses } } private val SirType.referencedClasses: List<SirClass> get() = this.normalizedEvaluatedType().referencedTypeDeclarations .map { it as? SirClass ?: error("Normalized type should only reference SirClasses: $it") } } }
9
null
8
735
b96044d4dec91e4b85c5b310226c6f56e3bfa2b5
3,682
SKIE
Apache License 2.0
ingestion/postgres/src/main/kotlin/io/exflo/ingestion/postgres/tasks/BodyImportTask.kt
41north
237,284,768
false
null
/* * Copyright (c) 2020 41North. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.exflo.ingestion.postgres.tasks import com.fasterxml.jackson.databind.ObjectMapper import io.exflo.ingestion.core.ImportTask import io.exflo.ingestion.postgres.extensions.toOmmerRecord import io.exflo.ingestion.postgres.extensions.toTransactionRecord import io.exflo.ingestion.tracker.BlockReader import io.exflo.postgres.jooq.Tables import io.exflo.postgres.jooq.tables.records.BlockHeaderRecord import io.reactivex.rxjava3.core.Emitter import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.schedulers.Schedulers import org.apache.logging.log4j.LogManager import org.hyperledger.besu.ethereum.core.Hash import org.jooq.Cursor import org.jooq.Record3 import org.jooq.SQLDialect import org.jooq.impl.DSL import java.sql.Timestamp import java.time.Duration import java.util.concurrent.TimeUnit import javax.sql.DataSource import kotlin.system.measureTimeMillis class BodyImportTask( private val objectMapper: ObjectMapper, private val blockReader: BlockReader, dataSource: DataSource ) : ImportTask { private val log = LogManager.getLogger() private val dbContext = DSL.using(dataSource, SQLDialect.POSTGRES) private val pollInterval = Duration.ofSeconds(1) @Volatile private var running = true override fun stop() { running = false } override fun run() { while (running) { try { // reset var blockCount = 0 Flowable .generate(initialState, generator, disposeState) .parallel() .runOn(Schedulers.io(), 64) .map { header -> val hash = Hash.fromHexString(header.hash) val body = blockReader.body(hash)!! val ommerRecords = body.ommers.mapIndexed { idx, ommer -> ommer.toOmmerRecord(header, idx) } val transactionRecords = body.transactions.mapIndexed { idx, transaction -> transaction.toTransactionRecord(header, idx) } Pair(header, ommerRecords + transactionRecords) } .sequential() .buffer(5, TimeUnit.SECONDS, 64) .doOnNext { items -> var updateCount = 0 val elapsedMs = measureTimeMillis { val blockHashes = items.map { it.first.hash } val records = items.map { it.second }.flatten() dbContext.transaction { txConfig -> val txCtx = DSL.using(txConfig) txCtx.batchInsert(records).execute() val recordsUpdated = txCtx.update(Tables.IMPORT_QUEUE) .set(Tables.IMPORT_QUEUE.STAGE, 1) .where(Tables.IMPORT_QUEUE.HASH.`in`(blockHashes)) .execute() updateCount = records.size + recordsUpdated } } blockCount += items.size log.debug("Written $blockCount blocks, $updateCount updates in $elapsedMs ms") } .doOnComplete { log.debug("Bodies import pass complete") } .takeUntil { !running } .blockingSubscribe() if (blockCount == 0) { log.debug("Waiting ${pollInterval.toSeconds()} sec(s) before starting another import pass") Thread.sleep(pollInterval.toMillis()) } } catch (t: Throwable) { // TODO handle any transient errors in the Flowable pipeline so that an exception isn't thrown log.error("Critical failure", t) throw t // re-throw } } log.info("Stopped") } private val initialState = { dbContext .select(Tables.BLOCK_HEADER.HASH, Tables.BLOCK_HEADER.NUMBER, Tables.BLOCK_HEADER.TIMESTAMP) .from(Tables.IMPORT_QUEUE) .leftJoin(Tables.BLOCK_HEADER).on(Tables.IMPORT_QUEUE.HASH.eq(Tables.BLOCK_HEADER.HASH)) .where(Tables.IMPORT_QUEUE.STAGE.eq(0)) .orderBy(Tables.IMPORT_QUEUE.TIMESTAMP.asc()) .limit(1024 * 10) .fetchLazy() } private val generator = { cursor: Cursor<Record3<String, Long, Timestamp>>, emitter: Emitter<BlockHeaderRecord> -> try { // conveniently closes the cursor if there is no more records available when (cursor.hasNext()) { true -> emitter.onNext(cursor.fetchNextInto(Tables.BLOCK_HEADER)) false -> emitter.onComplete() } } catch (t: Throwable) { emitter.onError(t) } cursor } private val disposeState = { cursor: Cursor<Record3<String, Long, Timestamp>> -> cursor.close() } }
16
Kotlin
7
17
218d6f83db11268d8e5cb038e96f1d3fcd0a6cc0
5,069
besu-exflo
Apache License 2.0
app/src/main/java/com/madsam/otora/service/BofDataRequestService.kt
MadestSamurai
766,900,440
false
{"Kotlin": 326653}
package com.madsam.otora.service import android.content.Context import android.util.Log import com.madsam.otora.database.DatabaseProvider import com.madsam.otora.entity.bof.BofEntryEntity import com.madsam.otora.entity.bof.BofPointEntity import com.madsam.otora.model.bof.BofEntry import com.madsam.otora.model.bof.BofEntryShow import com.madsam.otora.utils.CommonUtils import com.madsam.otora.utils.ShareUtil import com.madsam.otora.web.Api import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import retrofit2.Retrofit import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory import retrofit2.converter.moshi.MoshiConverterFactory import java.io.IOException import java.time.LocalDate /** * 项目名: OtogeTracker * 文件名: com.madsam.otora.service.BofDataRequestService * 创建者: MadSamurai * 创建时间: 2024/10/13 * 描述: TODO */ class BofDataRequestService(private val context: Context) { companion object { const val TAG = "BofDataRequestService" const val LAST_DATE_KEY = "lastDate" } private val moshi = Moshi.Builder() .addLast(KotlinJsonAdapterFactory()) .build() private val retrofit = Retrofit.Builder() .baseUrl("http://blog.madsam.work/") .addConverterFactory(MoshiConverterFactory.create(moshi)) // Moshi .addCallAdapterFactory(RxJava3CallAdapterFactory.create()) // RxJava .build() private val api = retrofit.create(Api::class.java) private val db = DatabaseProvider.getDatabase(context) private val serviceScope = CoroutineScope(Dispatchers.IO) private fun requestBofttEntryData( date: String ) { try { val bofCall = api.getBofttData(date) val response = bofCall.execute() if (response.isSuccessful) { val bofEntryList = response.body() if (bofEntryList != null) { // Insert data into database bofEntryList.forEach { entry -> val entity = BofEntryEntity( no = entry.no, team = entry.team, artist = entry.artist, genre = entry.genre, title = entry.title, regist = entry.regist, update = entry.update ) db.bofEntryDao().insertOrUpdate(entity) storePoints(entry, date) } } else Log.e(TAG, "Response body is null") } else { Log.e(TAG, "Response is not successful") } } catch (e: IOException) { Log.e(TAG, "IOException: ${e.message}") } } private fun fillMissingDataPoints(entry: BofEntry, date: String) { val startTime = CommonUtils.ymdToMillis(date, "00:00:00") val endTime = CommonUtils.ymdToMillis(date, "23:55:00") val interval = 5 * 60 * 1000 // 5 minutes in milliseconds val filledImpr = mutableListOf<BofEntry.PointInt>() val filledTotal = mutableListOf<BofEntry.PointInt>() val filledMedian = mutableListOf<BofEntry.PointDouble>() val filledAvg = mutableListOf<BofEntry.PointDouble>() var currentTime = startTime val now = System.currentTimeMillis() while (currentTime <= endTime) { // Stop filling if the current time exceeds the current system time and the date is today if (date == LocalDate.now().toString() && currentTime > now) { break } val timeString = CommonUtils.millisToYmd(currentTime).substring(11, 16) // Extract HH:mm val impr = entry.impr.find { it.time.startsWith(timeString) } ?: entry.impr.lastOrNull { it.time < timeString } val total = entry.total.find { it.time.startsWith(timeString) } ?: entry.total.lastOrNull { it.time < timeString } val median = entry.median.find { it.time.startsWith(timeString) } ?: entry.median.lastOrNull { it.time < timeString } val avg = entry.avg.find { it.time.startsWith(timeString) } ?: entry.avg.lastOrNull { it.time < timeString } impr?.let { filledImpr.add(it.copy(time = timeString)) } total?.let { filledTotal.add(it.copy(time = timeString)) } median?.let { filledMedian.add(it.copy(time = timeString)) } avg?.let { filledAvg.add(it.copy(time = timeString)) } currentTime += interval } entry.impr = filledImpr entry.total = filledTotal entry.median = filledMedian entry.avg = filledAvg } private fun storePoints(entry: BofEntry, date: String) { fillMissingDataPoints(entry, date) var isLastEntryOfDay = false val pointsToInsert = mutableListOf<BofPointEntity>() entry.impr.forEach { point -> val timeInMillis = CommonUtils.ymdToMillis(date, point.time) val startInMillis = CommonUtils.ymdToMillis("2024-10-13", "00:00:00") val pointEntity = BofPointEntity( timeAndEntry = ((timeInMillis - startInMillis)/10).toInt() + entry.no, impr = point.value, total = entry.total.find { it.time == point.time }?.value ?: 0, median = entry.median.find { it.time == point.time }?.value ?: 0.0, avg = entry.avg.find { it.time == point.time }?.value ?: 0.0, ) pointsToInsert.add(pointEntity) if (point.time.startsWith("23:55")) { isLastEntryOfDay = true } } db.bofPointDao().insertAll(pointsToInsert) if (isLastEntryOfDay) { saveLastDate(date) } } private fun saveLastDate(date: String) { ShareUtil.putString(LAST_DATE_KEY, date, context) } private fun getLastDate(): String? { return ShareUtil.getString(LAST_DATE_KEY, context) } fun getBofttData(dateTime: LocalDate) { serviceScope.launch { requestBofttEntryData(dateTime.toString()) val yesterday = dateTime.minusDays(1) val lastDate = getLastDate() if (lastDate == null || LocalDate.parse(lastDate).isBefore(yesterday)) { requestBofttEntryData(yesterday.toString()) } var currentDate = lastDate?.let { LocalDate.parse(it) } ?: LocalDate.parse("2024-10-13") while (!currentDate.isAfter(yesterday)) { requestBofttEntryData(currentDate.toString()) currentDate = currentDate.plusDays(1) } } } suspend fun getBofttEntryLatest(): List<BofEntryShow> { return withContext(Dispatchers.IO) { try { val maxId = db.bofPointDao().getMaxId() val time = maxId / 10000 * 10000 getBofttEntryByTime(time) } catch (e: Exception) { Log.e(TAG, "Error fetching latest entry: ${e.message}") emptyList() } } } suspend fun getBofttEntryByTime(time: Int): List<BofEntryShow> { return withContext(Dispatchers.IO) { try { val points = db.bofPointDao().getPointsByRange(time.toInt(), (time + 999).toInt()) if (points.isNotEmpty()) { val entryIds = points.map { it.timeAndEntry % 10000 } val entries = db.bofEntryDao().getEntriesByIds(entryIds) // Calculate the previous day's id based on the provided time val startInMillis = CommonUtils.ymdToMillis("2024-10-13", "00:00:00") val providedTimeMillis = startInMillis + time * 10 val previousDayMillis = providedTimeMillis - 24 * 60 * 60 * 1000 val previousDayId = ((previousDayMillis - startInMillis) / 10).toInt() val previousDayPoints = db.bofPointDao().getPointsByRange(previousDayId, previousDayId + 999) entries.map { entry -> val point = points.find { it.timeAndEntry % 10000 == entry.no } val previousDayPoint = previousDayPoints.find { it.timeAndEntry % 10000 == entry.no } BofEntryShow( no = entry.no, team = entry.team, artist = entry.artist, genre = entry.genre, title = entry.title, regist = entry.regist, update = entry.update, impr = point?.impr ?: 0, total = point?.total ?: 0, median = point?.median ?: 0.0, avg = point?.avg ?: 0.0, oldImpr = previousDayPoint?.impr ?: 0, oldTotal = previousDayPoint?.total ?: 0, oldMedian = previousDayPoint?.median ?: 0.0, oldAvg = previousDayPoint?.avg ?: 0.0, time = CommonUtils.millisToYmd(providedTimeMillis).substring(11, 16) ) } } else { emptyList() } } catch (e: Exception) { Log.e(TAG, "Error fetching entry by time: ${e.message}") emptyList() } } } }
0
Kotlin
0
1
228f92d8381b75b05ff3c8ba40cdb4d242d2f0d9
9,809
OtogeTracker
MIT License
src/main/kotlin/io/github/thebroccolibob/shallowdark/datagen/ShallowDarkDataGenerator.kt
thebroccolibob
757,060,700
false
{"Kotlin": 38300, "Java": 3882}
package io.github.thebroccolibob.shallowdark.datagen import io.github.thebroccolibob.shallowdark.Biomes import net.fabricmc.fabric.api.datagen.v1.DataGeneratorEntrypoint import net.fabricmc.fabric.api.datagen.v1.FabricDataGenerator import net.minecraft.registry.RegistryBuilder import net.minecraft.registry.RegistryKeys object ShallowDarkDataGenerator : DataGeneratorEntrypoint { override fun onInitializeDataGenerator(fabricDataGenerator: FabricDataGenerator) { fabricDataGenerator.createPack().apply { addProvider(TagGenerators::Entities) addProvider(TagGenerators::Blocks) addProvider(::ModelGenerator) addProvider(::LootTableGenerator) addProvider(::EnglishLangGenerator) addProvider(::ModWorldGenerator) } } override fun buildRegistry(registryBuilder: RegistryBuilder?) { registryBuilder?.addRegistry(RegistryKeys.BIOME, Biomes()::boostrap) } }
5
Kotlin
0
0
e501f4ef1f98cbe2873a3e7cf4371ba840e31358
882
ShallowDark
MIT License
src/day07/Day07.kt
ayukatawago
572,742,437
false
{"Kotlin": 58880}
package day07 import readInput fun main() { val testInput = readInput("day07/Day07_test") println(part1(testInput)) println(part2(testInput)) } private fun createDirMap(input: List<String>): Map<String, Int> { val dirMap = hashMapOf("/" to 0) var currentDirName = "/" input.forEach { if (it.startsWith("$ cd /")) return@forEach if (it.startsWith("$ ls")) return@forEach if (it.startsWith("$ cd ..")) { currentDirName = currentDirName.replace("""/[a-z.]*$""".toRegex(), "") return@forEach } if (it.startsWith("$ cd ")) { currentDirName += '/' + it.replace("$ cd ", "") return@forEach } if (it.startsWith("dir ")) { val dirName = it.replace("dir ", "") dirMap["${currentDirName}/$dirName"] = 0 } else { val size = it.replaceFirst(""" .*""".toRegex(), "").toInt() var dirName = currentDirName while (dirName != "/") { dirMap[dirName] = dirMap.getOrDefault(dirName, 0) + size dirName = dirName.replace("""/[a-z.]*$""".toRegex(), "") } dirMap["/"] = dirMap.getOrDefault("/", 0) + size } } return dirMap } private fun part1(input: List<String>): Int { val dirMap = createDirMap(input) println(dirMap) return dirMap.values.filter { it < 100000 }.sum() } private fun part2(input: List<String>): Int { val dirMap = createDirMap(input) val totalSize = dirMap["/"] ?: return 0 val remaining = totalSize - 40000000 if (remaining <= 0) { return 0 } return dirMap.values.sorted().first { it > remaining } }
0
Kotlin
0
0
923f08f3de3cdd7baae3cb19b5e9cf3e46745b51
1,713
advent-of-code-2022
Apache License 2.0
app/src/main/java/com/workfort/pstuian/app/ui/splash/viewstate/DeviceState.kt
arhanashik
411,942,559
false
{"Kotlin": 1116286}
package com.workfort.pstuian.app.ui.splash.viewstate import com.workfort.pstuian.app.data.local.device.DeviceEntity /** * **************************************************************************** * * Created by : arhan on 28 Oct, 2021 at 18:51. * * Email : <EMAIL> * * * * This class is for: * * 1. * * 2. * * 3. * * * * Last edited by : arhan on 2021/10/28. * * * * Last Reviewed by : <Reviewer Name> on <mm/dd/yy> * **************************************************************************** */ sealed class DeviceState { object Idle : DeviceState() object Loading : DeviceState() data class Success(val device: DeviceEntity) : DeviceState() data class Error(val message: String?) : DeviceState() } sealed class DevicesState { object Idle : DevicesState() object Loading : DevicesState() data class Success(val data: List<DeviceEntity>) : DevicesState() data class Error(val message: String) : DevicesState() }
0
Kotlin
0
2
9c51ec4d4d477ae739b922c49127ac69844f4d6e
980
PSTUian-android
Apache License 2.0
app/src/main/java/com/tecknobit/neutron/viewmodels/ConnectActivityViewModel.kt
N7ghtm4r3
799,333,621
false
{"Kotlin": 253721, "Java": 1653}
package com.tecknobit.neutron.viewmodels import android.content.Context import android.content.Intent import androidx.compose.material3.SnackbarHostState import androidx.compose.runtime.MutableState import androidx.compose.ui.text.intl.Locale.Companion.current import androidx.lifecycle.ViewModel import com.tecknobit.apimanager.formatters.JsonHelper import com.tecknobit.equinox.FetcherManager.FetcherManagerWrapper import com.tecknobit.neutron.activities.navigation.Splashscreen.Companion.localUser import com.tecknobit.neutron.activities.session.MainActivity import com.tecknobit.neutroncore.helpers.Endpoints.BASE_ENDPOINT import com.tecknobit.neutroncore.helpers.InputValidator.DEFAULT_LANGUAGE import com.tecknobit.neutroncore.helpers.InputValidator.LANGUAGES_SUPPORTED import com.tecknobit.neutroncore.helpers.InputValidator.isEmailValid import com.tecknobit.neutroncore.helpers.InputValidator.isHostValid import com.tecknobit.neutroncore.helpers.InputValidator.isNameValid import com.tecknobit.neutroncore.helpers.InputValidator.isPasswordValid import com.tecknobit.neutroncore.helpers.InputValidator.isServerSecretValid import com.tecknobit.neutroncore.helpers.InputValidator.isSurnameValid import com.tecknobit.neutroncore.records.User.IDENTIFIER_KEY import com.tecknobit.neutroncore.records.User.LANGUAGE_KEY import com.tecknobit.neutroncore.records.User.NAME_KEY import com.tecknobit.neutroncore.records.User.SURNAME_KEY import com.tecknobit.neutroncore.records.User.TOKEN_KEY /** * The **ConnectActivityViewModel** class is the support class used by the [ConnectActivityViewModel] * to execute the authentication requests to the backend * * @param snackbarHostState: the host to launch the snackbar messages * @param context: the current context where this model has been created * * @author N7ghtm4r3 - Tecknobit * @see NeutronViewModel * @see ViewModel * @see FetcherManagerWrapper */ class ConnectActivityViewModel( snackbarHostState: SnackbarHostState, val context: Context ) : NeutronViewModel( snackbarHostState = snackbarHostState ) { /** * **isSignUp** -> whether the auth request to execute is sign up or sign in */ lateinit var isSignUp: MutableState<Boolean> /** * **host** -> the value of the host to reach */ lateinit var host: MutableState<String> /** * **hostError** -> whether the [host] field is not valid */ lateinit var hostError: MutableState<Boolean> /** * **serverSecret** -> the value of the server secret */ lateinit var serverSecret: MutableState<String> /** * **serverSecretError** -> whether the [serverSecret] field is not valid */ lateinit var serverSecretError: MutableState<Boolean> /** * **name** -> the name of the user */ lateinit var name: MutableState<String> /** * **nameError** -> whether the [name] field is not valid */ lateinit var nameError: MutableState<Boolean> /** * **surname** -> the surname of the user */ lateinit var surname: MutableState<String> /** * **surnameError** -> whether the [surname] field is not valid */ lateinit var surnameError: MutableState<Boolean> /** * **email** -> the email of the user */ lateinit var email: MutableState<String> /** * **emailError** -> whether the [email] field is not valid */ lateinit var emailError: MutableState<Boolean> /** * **password** -> the password of the user */ lateinit var password: MutableState<String> /** * **passwordError** -> whether the [password] field is not valid */ lateinit var passwordError: MutableState<Boolean> /** * Wrapper function to execute the specific authentication request * * No-any params required */ fun auth() { if (isSignUp.value) signUp() else signIn() } /** * Function to execute the sign up authentication request, if successful the [localUser] will * be initialized with the data received by the request * * No-any params required */ private fun signUp() { if (signUpFormIsValid()) { val currentLanguageTag = current.toLanguageTag().substringBefore("-") var language = LANGUAGES_SUPPORTED[currentLanguageTag] language = if (language == null) DEFAULT_LANGUAGE else currentLanguageTag requester.changeHost(host.value + BASE_ENDPOINT) requester.sendRequest( request = { requester.signUp( serverSecret = serverSecret.value, name = name.value, surname = surname.value, email = email.value, password = <PASSWORD>, language = language ) }, onSuccess = { response -> launchApp( name = name.value, surname = surname.value, language = language, response = response ) }, onFailure = { showSnack(it) } ) } } /** * Function to validate the inputs for the [signUp] request * * No-any params required * * @return whether the inputs are valid as [Boolean] */ private fun signUpFormIsValid(): Boolean { var isValid: Boolean = isHostValid(host.value) if (!isValid) { hostError.value = true return false } isValid = isServerSecretValid(serverSecret.value) if (!isValid) { serverSecretError.value = true return false } isValid = isNameValid(name.value) if (!isValid) { nameError.value = true return false } isValid = isSurnameValid(surname.value) if (!isValid) { surnameError.value = true return false } isValid = isEmailValid(email.value) if (!isValid) { emailError.value = true return false } isValid = isPasswordValid(password.value) if (!isValid) { passwordError.value = true return false } return true } /** * Function to execute the sign in authentication request, if successful the [localUser] will * be initialized with the data received by the request * * No-any params required */ private fun signIn() { if (signInFormIsValid()) { requester.changeHost(host.value + BASE_ENDPOINT) requester.sendRequest( request = { requester.signIn( email = email.value, password = <PASSWORD> ) }, onSuccess = { response -> launchApp( name = response.getString(NAME_KEY), surname = response.getString(SURNAME_KEY), language = response.getString(LANGUAGE_KEY), response = response ) }, onFailure = { showSnack(it) } ) } } /** * Function to validate the inputs for the [signIn] request * * No-any params required * * @return whether the inputs are valid as [Boolean] */ private fun signInFormIsValid(): Boolean { var isValid: Boolean = isHostValid(host.value) if (!isValid) { hostError.value = true return false } isValid = isEmailValid(email.value) if (!isValid) { emailError.value = true return false } isValid = isPasswordValid(password.value) if (!isValid) { passwordError.value = true return false } return true } /** * Function to launch the application after the authentication request * * @param response: the response of the authentication request * @param name: the name of the user * @param surname: the surname of the user * @param language: the language of the user */ private fun launchApp( response: JsonHelper, name: String, surname: String, language: String ) { requester.setUserCredentials( userId = response.getString(IDENTIFIER_KEY), userToken = response.getString(TOKEN_KEY) ) localUser.insertNewUser( host.value.ifEmpty { null }, name, surname, email.value, password.value, language, response ) context.startActivity(Intent(context, MainActivity::class.java)) } }
0
Kotlin
0
0
bfcb167d74add107eee87217bc3e013077dcc5ee
9,081
Neutron-Android
MIT License
adaptive-core/src/commonMain/kotlin/fun/adaptive/adat/store/AdatStore.kt
spxbhuhb
788,711,010
false
{"Kotlin": 2318583, "Java": 24560, "HTML": 7875, "JavaScript": 3880, "Shell": 687}
package `fun`.adaptive.adat.store import `fun`.adaptive.adat.AdatClass abstract class AdatStore<A : AdatClass> { open fun update(instance: A, path: Array<String>, value: Any?) { throw UnsupportedOperationException() } open fun update(original : A, new : A) { throw UnsupportedOperationException() } open fun update(new : A) { throw UnsupportedOperationException() } }
34
Kotlin
0
3
e7d8bb8682a6399675bc75d2976b862268d20fb5
421
adaptive
Apache License 2.0
app/src/main/java/com/example/loginsesame/AccountList.kt
hydrogen-1
357,795,613
true
null
package com.example.loginsesame import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import com.example.loginsesame.RecyclerViewAdapter.RecyclerAdapter import kotlinx.android.synthetic.main.activity_password_overview.* lateinit var accountAdapter : RecyclerAdapter class AccountList : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_password_overview) accountAdapter = RecyclerAdapter(mutableListOf()) rvAccounts.adapter = accountAdapter rvAccounts.layoutManager = LinearLayoutManager(this) // Inserts Test Values val new_account = account("<EMAIL>", "<NAME>") accountAdapter.addAccount(new_account) } }
0
null
0
0
c179ebe3be482a11851e08cbee46911f9788f991
860
Team_17
MIT License
src/main/kotlin/dev/cubxity/mc/protocol/packets/game/server/ServerWindowItemsPacket.kt
MCProtocol
197,942,784
false
null
/* * Copyright (c) 2018 - 2019 Cubxity, superblaubeere27 and KodingKing1 * * 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 dev.cubxity.mc.protocol.packets.game.server import dev.cubxity.mc.protocol.ProtocolVersion import dev.cubxity.mc.protocol.data.obj.Slot import dev.cubxity.mc.protocol.net.io.NetInput import dev.cubxity.mc.protocol.net.io.NetOutput import dev.cubxity.mc.protocol.packets.Packet class ServerWindowItemsPacket( var windowId: Int, var slotData: Array<Slot> ) : Packet() { override fun read(buf: NetInput, target: ProtocolVersion) { windowId = buf.readUnsignedByte() slotData = arrayOf() for (i in 0 until buf.readShort()) { slotData += buf.readSlot() } } override fun write(out: NetOutput, target: ProtocolVersion) { out.writeByte(windowId) out.writeShort(slotData.size.toShort()) for (data in slotData) { out.writeSlot(data) } } }
1
null
1
4
1d2f08e856631c9668fb8bd9bc9ce32ade72815f
1,971
MCProtocol
MIT License
samples/src/main/java/com/Skyflow/CustomValidationsActivity.kt
skyflowapi
396,648,989
false
{"Kotlin": 674976, "Shell": 585}
package com.Skyflow import Skyflow.* import Skyflow.collect.elements.validations.ElementValueMatchRule import android.graphics.Color import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.Gravity import android.widget.LinearLayout import com.Skyflow.collect.elements.validations.LengthMatchRule import com.Skyflow.collect.elements.validations.RegexMatchRule import com.Skyflow.collect.elements.validations.ValidationSet import kotlinx.android.synthetic.main.activity_custom_validations.* class CustomValidationsActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_custom_validations) val skyflowConfiguration = Skyflow.Configuration( "VAULT_ID", "VAULT_URL", CollectActivity.DemoTokenProvider(), Options(LogLevel.ERROR, Env.PROD) ) val skyflowClient = Skyflow.init(skyflowConfiguration) val collectContainer = skyflowClient.container(ContainerType.COLLECT) val padding = Skyflow.Padding(8, 8, 8, 8) val bstyle = Skyflow.Style( Color.parseColor("#403E6B"), 10f, padding, null, R.font.roboto_light, Gravity.START, Color.parseColor("#403E6B") ) val cstyle = Skyflow.Style( Color.GREEN, 10f, padding, 6, R.font.roboto_light, Gravity.END, Color.GREEN ) val fstyle = Skyflow.Style( Color.parseColor("#403E6B"), 10f, padding, 6, R.font.roboto_light, Gravity.START, Color.GREEN ) val estyle = Skyflow.Style( Color.YELLOW, 10f, padding, 4, R.font.roboto_light, Gravity.CENTER, Color.YELLOW ) val istyle = Skyflow.Style(Color.RED, 15f, padding, 6, R.font.roboto_light, Gravity.START, Color.RED) val styles = Skyflow.Styles(bstyle, null, estyle, fstyle, istyle) var labelStyles = Styles(bstyle, null, estyle, fstyle, istyle) var baseErrorStyles = Style(null, null, padding, null, R.font.roboto_light, Gravity.START, Color.RED) val errorStyles = Styles(baseErrorStyles) val nameValidationSet = ValidationSet() nameValidationSet.add(RegexMatchRule("[A-Za-z]+","name should have alphabets")) nameValidationSet.add((LengthMatchRule(5,20,"length should be between 5 and 20"))) val nameInput = Skyflow.CollectElementInput( "cards", "name", SkyflowElementType.INPUT_FIELD, styles, labelStyles, errorStyles, label = "full name", placeholder = "enter full name",validations = nameValidationSet ) val nameWithCustomValidation = collectContainer.create(this, nameInput) //pin and confirm pin val pinInput = Skyflow.CollectElementInput( "cards", "pin", Skyflow.SkyflowElementType.PIN, styles, labelStyles, errorStyles, "pin" , "enter pin", ) val pin = collectContainer.create(this, pinInput) val pinValidationSet = ValidationSet() pinValidationSet.add(ElementValueMatchRule(pin,"value not matched")) val confirmPinInput = Skyflow.CollectElementInput( "cards", "confim_pin", SkyflowElementType.PIN, styles, labelStyles, errorStyles, "confirm pin", "enter confirm pin",validations = pinValidationSet ) val confirmPin = collectContainer.create(this, confirmPinInput) //end val parent = findViewById<LinearLayout>(R.id.parent) val lp = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) lp.setMargins(20, -20, 20, 0) nameWithCustomValidation.layoutParams = lp pin.layoutParams = lp confirmPin.layoutParams = lp parent.addView(nameWithCustomValidation) parent.addView(pin) parent.addView(confirmPin) } }
12
Kotlin
2
7
0ffcbf43c2767d6324f29952e8ce94d354aa57d8
4,404
skyflow-android
MIT License
app/ads/src/main/java/net/c7j/wna/huawei/consent/ProtocolDialog.kt
careful7j
604,723,393
false
{"Kotlin": 271725}
package net.c7j.wna.huawei.consent import android.app.AlertDialog import android.app.Dialog import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.graphics.Color import android.graphics.Typeface import android.os.Build import android.os.Bundle import android.text.Spannable import android.text.SpannableStringBuilder import android.text.method.LinkMovementMethod import android.text.method.ScrollingMovementMethod import android.text.style.ClickableSpan import android.text.style.ForegroundColorSpan import android.text.style.StyleSpan import android.view.LayoutInflater import android.view.View import android.view.Window import android.widget.Button import android.widget.LinearLayout import android.widget.TextView import net.c7j.wna.huawei.ads.R // This dialog shows privacy policy example class ProtocolDialog(private val mContext: Context) : Dialog(mContext, net.c7j.wna.huawei.box.R.style.ads_consent_dialog) { private var titleTv: TextView? = null private var protocolTv: TextView? = null private var confirmButton: Button? = null private var cancelButton: Button? = null private var inflater: LayoutInflater? = null private var mCallback: ProtocolDialogCallback? = null interface ProtocolDialogCallback { fun onAgree() fun onCancel() } fun setCallback(callback: ProtocolDialogCallback?) { mCallback = callback } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) window?.requestFeature(Window.FEATURE_NO_TITLE) inflater = LayoutInflater.from(mContext) val fl = findViewById<LinearLayout>(R.id.base_dialog_layout) val rootView = inflater?.inflate(R.layout.dialog_privacy_huawei, fl,false) as LinearLayout setContentView(rootView) titleTv = findViewById(R.id.uniform_dialog_title) titleTv?.text = mContext.getString(net.c7j.wna.huawei.box.R.string.protocol_title) protocolTv = findViewById(R.id.protocol_center_content) initClickableSpan() initButtonBar(rootView) } private fun initButtonBar(rootView: LinearLayout) { confirmButton = rootView.findViewById(R.id.base_okBtn) confirmButton?.setOnClickListener { mContext.getSharedPreferences(AdsConstant.SP_NAME, Context.MODE_PRIVATE) .edit() .putInt(AdsConstant.SP_PROTOCOL_KEY, AdsConstant.SP_PROTOCOL_AGREE) .apply() dismiss() mCallback?.onAgree() } cancelButton = rootView.findViewById(R.id.base_cancelBtn) cancelButton?.setOnClickListener { dismiss() mCallback?.onCancel() } } private fun initClickableSpan() { protocolTv?.movementMethod = ScrollingMovementMethod.getInstance() val privacyInfoText = mContext.getString(net.c7j.wna.huawei.box.R.string.protocol_content_text) val spanPrivacyInfoText = SpannableStringBuilder(privacyInfoText) val personalizedAdsTouchHere: ClickableSpan = object : ClickableSpan() { override fun onClick(widget: View) { startActivity(ACTION_OAID_SETTING) } } val privacyStart = mContext.resources.getInteger(net.c7j.wna.huawei.box.R.integer.privacy_start) val privacyEnd = mContext.resources.getInteger(net.c7j.wna.huawei.box.R.integer.privacy_end) val privacySpan = StyleSpan(Typeface.BOLD) spanPrivacyInfoText.setSpan(privacySpan, privacyStart, privacyEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) val colorPersonalize = ForegroundColorSpan(Color.BLUE) val personalizedStart = mContext.resources.getInteger(net.c7j.wna.huawei.box.R.integer.personalized_start) val personalizedEnd = mContext.resources.getInteger(net.c7j.wna.huawei.box.R.integer.personalized_end) spanPrivacyInfoText.setSpan(personalizedAdsTouchHere, personalizedStart, personalizedEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) spanPrivacyInfoText.setSpan(colorPersonalize, personalizedStart, personalizedEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) protocolTv?.text = spanPrivacyInfoText protocolTv?.movementMethod = LinkMovementMethod.getInstance() } fun startActivity(action: String) { val enterNative = Intent(action) val pkgMng = mContext.packageManager if (pkgMng != null) { val list = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { context.packageManager.queryIntentActivities( enterNative, PackageManager.ResolveInfoFlags.of(PackageManager.MATCH_DEFAULT_ONLY.toLong())) } else { context.packageManager.queryIntentActivities(enterNative, 0) } if (list.isNotEmpty()) { enterNative.setPackage("com.huawei.hwid") mContext.startActivity(enterNative) } else { addAlertView() } } } /** No function is available, ask user to install Huawei Mobile Services (APK) of the latest version */ private fun addAlertView() { val builder = AlertDialog.Builder(mContext) builder.setTitle(mContext.getString(net.c7j.wna.huawei.box.R.string.alert_title)) builder.setMessage(mContext.getString(net.c7j.wna.huawei.box.R.string.alert_content)) builder.setPositiveButton(mContext.getString(net.c7j.wna.huawei.box.R.string.alert_confirm), null) builder.show() } companion object { // private const val ACTION_SIMPLE_PRIVACY = "com.huawei.hms.ppskit.ACTION.SIMPLE_PRIVACY" private const val ACTION_OAID_SETTING = "com.huawei.hms.action.OAID_SETTING" } }
0
Kotlin
1
5
e563f3eb0e7c21088c7139177f9f4ca786f43232
5,754
HMSExamples
Apache License 2.0
app/src/main/java/com/itl/kg/androidlabkt/roomLab/viewModel/RoomLabViewModelFactory.kt
KenGuerrilla
364,918,808
false
null
package com.itl.kg.androidlabkt.roomLab.viewModel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.itl.kg.androidlabkt.roomLab.data.RoomLabRepository /** * * Created by kenguerrilla on 2020/6/15. * */ class RoomLabViewModelFactory( private val repository: RoomLabRepository ) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel?> create(modelClass: Class<T>): T { return RoomLabDataViewModel(repository) as T } }
0
Kotlin
0
0
4cd76444bb1a0f9f123444c2042ba1d953dc9831
520
AndroidLabKT
Apache License 2.0
api/src/in/jalgaoncohelp/api/resource/model/ResourceResponse.kt
Jalgaon-CoHelp
363,230,448
false
null
/* * MIT License * * Copyright (c) 2021 <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 `in`.jalgaoncohelp.api.resource.model import `in`.jalgaoncohelp.api.model.PagedResponse import `in`.jalgaoncohelp.core.resource.model.Resource import kotlinx.serialization.Serializable @Serializable data class ResourceResponse( val id: Long, val type: String, val contactName: String, val mobileNumber: String, val resourceName: String, val address: String? = null, val taluka: String, val note: String? = null, val createdAt: Long ) { companion object { fun from(resource: Resource) = ResourceResponse( id = resource.id, type = resource.type.code, contactName = resource.contactName, mobileNumber = resource.mobileNumber, resourceName = resource.resourceName.code, address = resource.address, taluka = resource.taluka, note = resource.note, createdAt = resource.createdAtMillis ) } } @Serializable class PagedResourceResponse( override val total: Long, override val pages: Long, val resources: List<ResourceResponse> ) : PagedResponse
5
Kotlin
0
27
0872290820cd82264cbbc176514e163886ab290f
2,256
api-service
MIT License
samples/star/src/jvmMain/kotlin/com/slack/circuit/star/repo/InjectedPetRepository.jvm.kt
slackhq
523,011,227
false
{"Kotlin": 481907, "JavaScript": 4556, "Shell": 3808, "Ruby": 1378}
// Copyright (C) 2024 Slack Technologies, LLC // SPDX-License-Identifier: Apache-2.0 package com.slack.circuit.star.repo import com.slack.circuit.star.data.PetfinderApi import com.slack.circuit.star.db.SqlDriverFactory import com.slack.circuit.star.di.AppScope import com.squareup.anvil.annotations.ContributesBinding import com.squareup.anvil.annotations.optional.SingleIn import javax.inject.Inject @SingleIn(AppScope::class) @ContributesBinding(AppScope::class) class InjectedPetRepository @Inject constructor(sqliteDriverFactory: SqlDriverFactory, private val petFinderApi: PetfinderApi) : PetRepository by PetRepositoryImpl(sqliteDriverFactory, petFinderApi)
24
Kotlin
65
1,341
9631dfbcccbf840681708d31711c4e47df03827b
668
circuit
Apache License 2.0
audio-sdk/src/main/kotlin/com/leovp/audio/aac/AacStreamPlayer.kt
yhz61010
329,485,030
false
null
package com.leovp.audio.aac import android.content.Context import android.media.* import android.os.SystemClock import com.leovp.audio.base.bean.AudioDecoderInfo import com.leovp.lib_bytes.toHexStringLE import com.leovp.log_sdk.LogContext import kotlinx.coroutines.* import java.nio.ByteBuffer import java.util.concurrent.ArrayBlockingQueue import java.util.concurrent.atomic.AtomicLong import kotlin.math.abs /** * Author: <NAME> * Date: 20-8-20 下午5:18 */ class AacStreamPlayer(private val ctx: Context, private val audioDecoderInfo: AudioDecoderInfo) { companion object { private const val TAG = "AacStreamPlayer" private const val PROFILE_AAC_LC = MediaCodecInfo.CodecProfileLevel.AACObjectLC private const val AUDIO_DATA_QUEUE_CAPACITY = 10 private const val RESYNC_AUDIO_AFTER_DROP_FRAME_TIMES = 3 private const val AUDIO_INIT_LATENCY_IN_MS = 1200 private const val REASSIGN_LATENCY_TIME_THRESHOLD_IN_MS: Long = 5000 private const val AUDIO_ALLOW_LATENCY_LIMIT_IN_MS = 500 } private var audioLatencyThresholdInMs = AUDIO_INIT_LATENCY_IN_MS private val ioScope = CoroutineScope(Dispatchers.IO + Job()) private var audioManager: AudioManager? = null // private var outputFormat: MediaFormat? = null private var frameCount = AtomicLong(0) private var dropFrameTimes = AtomicLong(0) private var playStartTimeInUs: Long = 0 private val rcvAudioDataQueue = ArrayBlockingQueue<ByteArray>(AUDIO_DATA_QUEUE_CAPACITY) private var audioTrack: AudioTrack? = null private var audioDecoder: MediaCodec? = null private var csd0: ByteArray? = null private fun initAudioTrack(ctx: Context) { runCatching { audioManager = ctx.getSystemService(Context.AUDIO_SERVICE) as AudioManager val bufferSize = AudioTrack.getMinBufferSize(audioDecoderInfo.sampleRate, audioDecoderInfo.channelConfig, audioDecoderInfo.audioFormat) val sessionId = audioManager!!.generateAudioSessionId() val audioAttributesBuilder = AudioAttributes.Builder().apply { // Speaker setUsage(AudioAttributes.USAGE_MEDIA) // AudioAttributes.USAGE_MEDIA AudioAttributes.USAGE_VOICE_COMMUNICATION setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) // AudioAttributes.CONTENT_TYPE_MUSIC AudioAttributes.CONTENT_TYPE_SPEECH setLegacyStreamType(AudioManager.STREAM_MUSIC) // Earphone // setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION) // AudioAttributes.USAGE_MEDIA AudioAttributes.USAGE_VOICE_COMMUNICATION // setContentType(AudioAttributes.CONTENT_TYPE_SPEECH) // AudioAttributes.CONTENT_TYPE_MUSIC AudioAttributes.CONTENT_TYPE_SPEECH // setLegacyStreamType(AudioManager.STREAM_VOICE_CALL) } val audioFormat = AudioFormat.Builder().setSampleRate(audioDecoderInfo.sampleRate) .setEncoding(audioDecoderInfo.audioFormat) .setChannelMask(audioDecoderInfo.channelConfig) .build() audioTrack = AudioTrack(audioAttributesBuilder.build(), audioFormat, bufferSize, AudioTrack.MODE_STREAM, sessionId) if (AudioTrack.STATE_INITIALIZED == audioTrack!!.state) { LogContext.log.i(TAG, "Start playing audio...") audioTrack!!.play() } else { LogContext.log.w(TAG, "AudioTrack state is not STATE_INITIALIZED") } }.onFailure { LogContext.log.e(TAG, "initAudioTrack error msg=${it.message}") } } @Suppress("unused") fun useSpeaker(ctx: Context, on: Boolean) { LogContext.log.w(TAG, "useSpeaker=$on") val audioManager = ctx.getSystemService(Context.AUDIO_SERVICE) as AudioManager if (on) { audioManager.mode = AudioManager.MODE_NORMAL audioManager.isSpeakerphoneOn = true } else { audioManager.mode = AudioManager.MODE_IN_COMMUNICATION audioManager.isSpeakerphoneOn = false } } // ByteBuffer key // AAC Profile 5bits | SampleRate 4bits | Channel Count 4bits | Others 3bits(Normally 0) // Example: AAC LC,44.1Khz,Mono. Separately values: 2,4,1. // Convert them to binary value: 0b10, 0b100, 0b1 // According to AAC required, convert theirs values to binary bits: // 00010 0100 0001 000 // The corresponding hex value: // 0001 0010 0000 1000 // So the csd_0 value is 0x12,0x08 // https://developer.android.com/reference/android/media/MediaCodec // AAC CSD: Decoder-specific information from ESDS // // ByteBuffer key // AAC Profile 5bits | SampleRate 4bits | Channel Count 4bits | Others 3bits(Normally 0) // Example: AAC LC,44.1Khz,Mono. Separately values: 2,4,1. // Convert them to binary value: 0b10, 0b100, 0b1 // According to AAC required, convert theirs values to binary bits: // 00010 0100 0001 000 // The corresponding hex value: // 0001 0010 0000 1000 // So the csd_0 value is 0x12,0x08 // https://developer.android.com/reference/android/media/MediaCodec // AAC CSD: Decoder-specific information from ESDS private fun initAudioDecoder(csd0: ByteArray) { runCatching { LogContext.log.i(TAG, "initAudioDecoder: $audioDecoderInfo") val csd0BB = ByteBuffer.wrap(csd0) audioDecoder = MediaCodec.createDecoderByType(MediaFormat.MIMETYPE_AUDIO_AAC) val mediaFormat = MediaFormat.createAudioFormat(MediaFormat.MIMETYPE_AUDIO_AAC, audioDecoderInfo.sampleRate, audioDecoderInfo.channelCount).apply { setInteger(MediaFormat.KEY_AAC_PROFILE, PROFILE_AAC_LC) setInteger(MediaFormat.KEY_IS_ADTS, 1) // Set ADTS decoder information. setByteBuffer("csd-0", csd0BB) } audioDecoder!!.configure(mediaFormat, null, null, 0) // outputFormat = audioDecoder?.outputFormat // option B // audioDecoder?.setCallback(mediaCodecCallback) audioDecoder?.start() ioScope.launch { runCatching { while (true) { ensureActive() val audioData = rcvAudioDataQueue.poll() // if (frameCount.get() % 30 == 0L) { LogContext.log.i(TAG, "Play AAC[${audioData?.size}]") // } if (audioData != null && audioData.isNotEmpty()) { decodeAndPlay(audioData) } delay(10) } }.onFailure { it.printStackTrace() } } }.onFailure { LogContext.log.e(TAG, "initAudioDecoder error msg=${it.message}") } } /** * If I use asynchronous MediaCodec, most of time in my phone(HuaWei Honor V20), it will not play sound due to MediaCodec state error. */ private fun decodeAndPlay(audioData: ByteArray) { try { val bufferInfo = MediaCodec.BufferInfo() // See the dequeueInputBuffer method in document to confirm the timeoutUs parameter. val inputIndex: Int = audioDecoder?.dequeueInputBuffer(0) ?: -1 if (inputIndex > -1) { audioDecoder?.getInputBuffer(inputIndex)?.run { // Clear exist data. clear() // Put pcm audio data to encoder. put(audioData) } val pts = computePresentationTimeUs(frameCount.incrementAndGet()) audioDecoder?.queueInputBuffer(inputIndex, 0, audioData.size, pts, 0) } // Start decoding and get output index var outputIndex: Int = audioDecoder?.dequeueOutputBuffer(bufferInfo, 0) ?: -1 val chunkPCM = ByteArray(bufferInfo.size) // Get decoded data in bytes while (outputIndex >= 0) { audioDecoder?.getOutputBuffer(outputIndex)?.run { get(chunkPCM) } // Must clear decoded data before next loop. Otherwise, you will get the same data while looping. if (chunkPCM.isNotEmpty()) { if (audioTrack == null || AudioTrack.STATE_UNINITIALIZED == audioTrack?.state) return if (AudioTrack.PLAYSTATE_PLAYING == audioTrack?.playState) { LogContext.log.i(TAG, "Play PCM[${chunkPCM.size}]") // Play decoded audio data in PCM audioTrack?.write(chunkPCM, 0, chunkPCM.size) } } audioDecoder?.releaseOutputBuffer(outputIndex, false) // Get data again. outputIndex = audioDecoder?.dequeueOutputBuffer(bufferInfo, 0) ?: -1 } } catch (e: Exception) { LogContext.log.e(TAG, "You can ignore this message safely. decodeAndPlay error") } } // private val mediaCodecCallback = object : MediaCodec.Callback() { // override fun onInputBufferAvailable(codec: MediaCodec, inputBufferId: Int) { // try { // val inputBuffer = codec.getInputBuffer(inputBufferId) // // fill inputBuffer with valid data // inputBuffer?.clear() // val data = rcvAudioDataQueue.poll()?.also { // inputBuffer?.put(it) // } // val dataSize = data?.size ?: 0 // val pts = computePresentationTimeUs(frameCount.incrementAndGet()) //// if (BuildConfig.DEBUG) { //// LogContext.log.d(TAG, "Data len=$dataSize\t pts=$pts") //// } // codec.queueInputBuffer(inputBufferId, 0, dataSize, pts, 0) // } catch (e: Exception) { // LogContext.log.e(TAG, "Audio Player onInputBufferAvailable error. msg=${e.message}") // } // } // // override fun onOutputBufferAvailable(codec: MediaCodec, outputBufferId: Int, info: MediaCodec.BufferInfo) { // try { // val outputBuffer = codec.getOutputBuffer(outputBufferId) // // val bufferFormat = codec.getOutputFormat(outputBufferId) // option A // // bufferFormat is equivalent to member variable outputFormat // // outputBuffer is ready to be processed or rendered. // outputBuffer?.let { // val decodedData = ByteArray(info.size) // it.get(decodedData) //// LogContext.log.w(TAG, "PCM[${decodedData.size}]") // when (info.flags) { // MediaCodec.BUFFER_FLAG_CODEC_CONFIG -> { // LogContext.log.w(TAG, "Found CSD0 frame: ${JsonUtil.toJsonString(decodedData)}") // } // MediaCodec.BUFFER_FLAG_END_OF_STREAM -> Unit // MediaCodec.BUFFER_FLAG_PARTIAL_FRAME -> Unit // else -> Unit // } // if (decodedData.isNotEmpty()) { // // Play decoded audio data in PCM // audioTrack?.write(decodedData, 0, decodedData.size) // } // } // codec.releaseOutputBuffer(outputBufferId, false) // } catch (e: Exception) { // LogContext.log.e(TAG, "Audio Player onOutputBufferAvailable error. msg=${e.message}") // } // } // // override fun onOutputFormatChanged(codec: MediaCodec, format: MediaFormat) { // LogContext.log.w(TAG, "onOutputFormatChanged format=$format") // // Subsequent data will conform to new format. // // Can ignore if using getOutputFormat(outputBufferId) // outputFormat = format // option B // } // // override fun onError(codec: MediaCodec, e: MediaCodec.CodecException) { // e.printStackTrace() // LogContext.log.e(TAG, "onError e=${e.message}", e) // } // } fun startPlayingStream(audioData: ByteArray, dropFrameCallback: () -> Unit) { // We should use a better way to check CSD0 if (audioData.size < 10) { runCatching { synchronized(this) { audioDecoder?.run { LogContext.log.w(TAG, "Found exist AAC Audio Decoder. Release it first") stop() release() } audioTrack?.run { LogContext.log.w(TAG, "Found exist AudioTrack. Release it first") stop() release() } frameCount.set(0) csd0 = byteArrayOf(audioData[audioData.size - 2], audioData[audioData.size - 1]) LogContext.log.w(TAG, "Audio csd0=HEX[${csd0?.toHexStringLE()}]") initAudioDecoder(csd0!!) initAudioTrack(ctx) playStartTimeInUs = SystemClock.elapsedRealtimeNanos() / 1000 ioScope.launch { delay(REASSIGN_LATENCY_TIME_THRESHOLD_IN_MS) audioLatencyThresholdInMs = AUDIO_ALLOW_LATENCY_LIMIT_IN_MS LogContext.log.w(TAG, "Change latency limit to $AUDIO_ALLOW_LATENCY_LIMIT_IN_MS") } LogContext.log.w(TAG, "Play audio at: $playStartTimeInUs") } }.onFailure { LogContext.log.e(TAG, "startPlayingStream error. msg=${it.message}") } return } if (csd0 == null) { LogContext.log.e(TAG, "csd0 is null. Can not play!") return } val latencyInMs = (SystemClock.elapsedRealtimeNanos() / 1000 - playStartTimeInUs) / 1000 - getAudioTimeUs() / 1000 // LogContext.log.d( // TAG, // "st=$playStartTimeInUs\t cal=${(SystemClock.elapsedRealtimeNanos() / 1000 - playStartTimeInUs) / 1000}\t play=${getAudioTimeUs() / 1000}\t latency=$latencyInMs" // ) if (rcvAudioDataQueue.size >= AUDIO_DATA_QUEUE_CAPACITY || abs(latencyInMs) > audioLatencyThresholdInMs) { dropFrameTimes.incrementAndGet() LogContext.log.w( TAG, "Drop[${dropFrameTimes.get()}]|full[${rcvAudioDataQueue.size}] latency[$latencyInMs] play=${getAudioTimeUs() / 1000}" ) rcvAudioDataQueue.clear() frameCount.set(0) runCatching { audioDecoder?.flush() }.getOrNull() runCatching { audioTrack?.pause() }.getOrNull() runCatching { audioTrack?.flush() }.getOrNull() runCatching { audioTrack?.play() }.getOrNull() if (dropFrameTimes.get() >= RESYNC_AUDIO_AFTER_DROP_FRAME_TIMES) { // If drop frame times exceeds RESYNC_AUDIO_AFTER_DROP_FRAME_TIMES-1 times, we need to do sync again. dropFrameTimes.set(0) dropFrameCallback.invoke() } playStartTimeInUs = SystemClock.elapsedRealtimeNanos() / 1000 } if (frameCount.get() % 50 == 0L) { LogContext.log.i(TAG, "AU[${audioData.size}][$latencyInMs]") } rcvAudioDataQueue.offer(audioData) } fun stopPlaying() { LogContext.log.w(TAG, "Stop playing audio") runCatching { ioScope.cancel() rcvAudioDataQueue.clear() frameCount.set(0) dropFrameTimes.set(0) audioTrack?.pause() audioTrack?.flush() audioTrack?.stop() audioTrack?.release() }.onFailure { LogContext.log.e(TAG, "audioTrack stop or release error. msg=${it.message}") }.also { audioTrack = null } LogContext.log.w(TAG, "Releasing AudioDecoder...") runCatching { // These are the magic lines for Samsung phone. DO NOT try to remove or refactor me. audioDecoder?.setCallback(null) audioDecoder?.release() }.onFailure { it.printStackTrace() LogContext.log.e(TAG, "audioDecoder() release1 error. msg=${it.message}") }.also { audioDecoder = null csd0 = null } LogContext.log.w(TAG, "stopPlaying() done") } @Suppress("unused") fun getPlayState() = audioTrack?.playState ?: AudioTrack.PLAYSTATE_STOPPED private fun computePresentationTimeUs(frameIndex: Long) = frameIndex * 1_000_000 / audioDecoderInfo.sampleRate private fun getAudioTimeUs(): Long = runCatching { val numFramesPlayed: Int = audioTrack?.playbackHeadPosition ?: 0 numFramesPlayed * 1_000_000L / audioDecoderInfo.sampleRate }.getOrDefault(0L) }
0
Kotlin
3
3
09e576e48566add29cf18d9bc2fe909563a83818
17,073
android
MIT License
foundation/src/commonMain/kotlin/net/ntworld/foundation/exception/CannotResolveException.kt
nhat-phan
201,625,092
false
null
package net.ntworld.foundation.exception class CannotResolveException(message: String) : Exception(message)
0
Kotlin
3
3
2fd4b0f0a4966e3aa687f7108d3b0a1cb800c6be
108
foundation
MIT License
app/src/main/java/dae/ddo/viewmodels/SettingsViewModel.kt
DavidEdwards
340,466,810
false
null
package dae.ddo.viewmodels import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class SettingsViewModel @Inject constructor( private val dataStore: DataStore<Preferences> ) : ViewModel() { fun get(key: String, default: Boolean = false): Flow<Boolean> = dataStore.data.map { it[booleanPreferencesKey(key)] ?: default } fun set(key: String, value: Boolean) { viewModelScope.launch { dataStore.edit { it[booleanPreferencesKey(key)] = value } } } }
0
Kotlin
0
1
7999dcf7dc8f7c8ba538b99341e48d993c017ef2
959
ddoparty
The Unlicense
boneslibrary/src/main/java/com/eudycontreras/boneslibrary/common/ContentLoader.kt
EudyContreras
253,115,353
false
null
package com.eudycontreras.boneslibrary.common /** * Copyright (C) 2020 Project X * * @Project ProjectX * @author <NAME>. * @since March 2020 */ internal interface ContentLoader { fun fadeContent(fraction: Float) fun prepareContentFade() fun concealContent() fun revealContent() fun restore() }
3
Kotlin
15
88
9608f59e023256419777c552f64ffc699433e070
321
Skeleton-Bones
MIT License
rop-sam/src/main/kotlin/com/github/funczz/kotlin/rop_sam/ISamAction.kt
funczz
526,097,483
false
null
package com.github.funczz.kotlin.rop_sam import com.github.funczz.kotlin.rop.result.RopResult /** * SAM Action インターフェイス: * SAM モデルを生成するクラス * @param D Any: SAM Action 入力データ * @param M ISamModel: SAM モデル * @author funczz */ interface ISamAction<D, M : ISamModel> { /** * 特定のビジネスロジックを適用した SAM モデルを生成する。 * @param present SAM Present 関数: SAM モデルを生成する関数 * @param data SAM Action 入力データ * @return RopResult M - ISamModel: SAM モデル */ fun execute(present: (D) -> RopResult<M>, data: D): RopResult<M> }
0
Kotlin
0
0
10d3ce606e7132bf12b7bc91b005d2efe79d24cb
534
kotlin-rop-sam
Apache License 2.0
app/src/main/java/com/example/weather/database/room_entities/LocationEntity.kt
nts0311
315,167,769
false
null
package com.example.weather.database.room_entities import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class LocationEntity( var lat: Double, var long: Double, ) { constructor() : this(0.0,0.0) @PrimaryKey(autoGenerate = true) var dbId: Long = 0 var name: String = "" }
0
Kotlin
0
0
9bec95c468995a76f9deb0a91b855c64239ce29a
319
Weather
Apache License 2.0
app/src/main/java/com/sharehands/sharehands_frontend/network/RetrofitClient.kt
kmkim2689
649,790,966
false
{"Kotlin": 714518}
package com.sharehands.sharehands_frontend.network import okhttp3.OkHttpClient import okhttp3.ResponseBody import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Converter import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.lang.reflect.Type object RetrofitClient { // TODO : Set Base URL after Decided // 정식aws "http://172.16.17.32:8080" // local db "http://127.0.0.1:8080" private const val BASE_URL = "https://www.sharehands.site" private val retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(OkHttpClient.Builder().addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }).build()) .build() // 여기서 상속을 받는 ApiService 인터페이스는, get, post 등 서버와 통신하기 위한 메소드들을 정의해놓은 인터페이스를 의미한다. fun createRetorfitClient(): ApiService { return retrofit.create(ApiService::class.java) } // TODO : 클라이언트를 사용하는 클래스에서, 다음과 같이 사용 // private val retrofitClient = RetrofitClient.createRetrofitClient() }
0
Kotlin
0
0
fa28733c4814bb0bcc42be23308c7cf23567e633
1,125
sharehands-android
The Unlicense
app/src/main/java/moe/fuqiuluo/portal/bdmap/Poi.kt
fuqiuluo
870,496,630
false
{"Kotlin": 280032, "AIDL": 21153, "Java": 3777}
package moe.fuqiuluo.portal.bdmap import kotlin.math.atan2 import kotlin.math.cos import kotlin.math.sin import kotlin.math.sqrt data class Poi( val name: String, var address: String, val longitude: Double, val latitude: Double, val tag: String, ) { companion object { const val KEY_NAME = "name" const val KEY_ADDRESS = "address" const val KEY_LONGITUDE = "longitude" const val KEY_LATITUDE = "latitude" const val KEY_TAG = "tag" } fun toMap(): Map<String, String> { return mapOf( KEY_NAME to name, KEY_ADDRESS to address, KEY_LONGITUDE to longitude.toString().take(5), KEY_LATITUDE to latitude.toString().take(5), KEY_TAG to tag, ) } /** * Calculate the distance between two points on the Earth's surface. * @param other The other point. * @return The distance in meters. */ fun distanceTo(other: Poi): Double { val earthRadius = 6371000.0 val dLat = Math.toRadians(other.latitude - latitude) val dLng = Math.toRadians(other.longitude - longitude) val a = sin(dLat / 2) * sin(dLat / 2) + cos(Math.toRadians(latitude)) * cos(Math.toRadians(other.latitude)) * sin(dLng / 2) * sin(dLng / 2) val c = 2 * atan2(sqrt(a), sqrt(1 - a)) return earthRadius * c } fun distanceTo(lat: Double, lng: Double): Double { val earthRadius = 6371000.0 val dLat = Math.toRadians(lat - latitude) val dLng = Math.toRadians(lng - longitude) val a = sin(dLat / 2) * sin(dLat / 2) + cos(Math.toRadians(latitude)) * cos(Math.toRadians(lat)) * sin(dLng / 2) * sin(dLng / 2) val c = 2 * atan2(sqrt(a), sqrt(1 - a)) return earthRadius * c } }
0
Kotlin
1
8
ded8017653fb6535cc71e421175d22867d2f12a2
1,873
Portal
Apache License 2.0
core/remote/food-data-central/src/test/kotlin/org/calamarfederal/messydiet/food/data/central/FoodDataCentralRepositoryUnitTest.kt
John-Tuesday
684,904,664
false
{"Kotlin": 351679}
package org.calamarfederal.messydiet.food.data.central import io.github.john.tuesday.nutrition.FoodNutrition import io.github.john.tuesday.nutrition.prettyPrint import io.github.john.tuesday.nutrition.scaleToPortion import kotlinx.coroutines.runBlocking import org.calamarfederal.messydiet.food.data.central.di.testDi import org.calamarfederal.messydiet.food.data.central.model.getResponseOrNull import org.calamarfederal.messydiet.food.data.central.model.getValueOrNull import org.calamarfederal.messydiet.food.data.central.model.isSuccess import org.calamarfederal.messydiet.test.food.data.central.FoodItemExpect import org.calamarfederal.messydiet.test.food.data.central.FoodItemExpectCase import org.kodein.di.direct import org.kodein.di.instance import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull internal class FoodDataCentralRepositoryUnitTest { private lateinit var repo: FoodDataCentralRepository @BeforeTest fun setUp() { repo = testDi.direct.instance() } fun testSearchByUpcGtin(expectCase: FoodItemExpectCase) { val result = runBlocking { repo.searchFoodWithUpcGtin(expectCase.gtinUpc) } assert(result.isSuccess()) { println("${result.getResponseOrNull()?.message}") } val searchResultFoods = result.getValueOrNull()!! assertEquals(1, searchResultFoods.size) val searchFood = searchResultFoods.single() assertEquals(expectCase.fdcId, searchFood.fdcId) assertEquals(expectCase.searchDescription, searchFood.description) } fun testGetDetails( expectCase: FoodItemExpectCase, expectNutrition: FoodNutrition = expectCase.nutritionPerServing, ) { val result = runBlocking { repo.getFoodDetails(expectCase.fdcId) } assert(result.isSuccess()) val foodItem = result.getValueOrNull()!! assertEquals(expectCase.fdcId, foodItem.fdcId) assertNotNull(foodItem.nutritionalInfo) val nutritionInfo = foodItem.nutritionalInfo!! prettyPrint(nutritionInfo) assertEquals(expectNutrition, nutritionInfo) } @Test fun `Search by UPC GTIN SpriteTest`() { testSearchByUpcGtin(FoodItemExpect.SpriteTest) } @Test fun `Get food details for SpriteTest`() { testGetDetails(FoodItemExpect.SpriteTest) } @Test fun `Get food details for CheeriosTestA`() { testGetDetails( FoodItemExpect.CheeriosTestA, FoodItemExpect.CheeriosTestA.nutritionPer100.scaleToPortion(FoodItemExpect.CheeriosTestA.nutritionPerServing.portion), ) } }
0
Kotlin
0
0
7b276382b02beeee7115fc72927683ff9a0d730e
2,718
messy-diet
MIT License
app/src/main/java/com/dubedivine/samples/data/model/StatusResponse.kt
dubeboy
102,972,979
false
null
package com.dubedivine.samples.data.model /** * Created by divine on 2017/10/01. */ data class StatusResponse<T>(var status: Boolean? = null, var message: String? = null, var entity: T? = null)
0
Kotlin
1
1
0dccd66d69fc3f1ae7cbecbab397d8de6f29cc5c
197
Peerlink-mobile
The Unlicense
mightypreferences/src/main/kotlin/com/illuzor/mightypreferences/Prefs.kt
illuzor
95,664,160
false
null
package com.illuzor.mightypreferences import android.content.SharedPreferences @Suppress("NOTHING_TO_INLINE") class Prefs(private val prefs: SharedPreferences) { class PutHelper internal constructor(prefs: SharedPreferences) { private val editor = prefs.edit() fun bool(key: String, value: Boolean) { editor.putBoolean(key, value) } fun byte(key: String, value: Byte) { editor.putInt(key, value.toInt()) } fun short(key: String, value: Short) { editor.putInt(key, value.toInt()) } fun int(key: String, value: Int) { editor.putInt(key, value) } fun long(key: String, value: Long) { editor.putLong(key, value) } fun float(key: String, value: Float) { editor.putFloat(key, value) } fun double(key: String, value: Double) { editor.putString(key, value.toString()) } fun string(key: String, value: String) { editor.putString(key, value) } fun <K : Any, V : Any> map( key: String, map: Map<K, V>, separator1: String = ":", separator2: String = "," ) { if (map.isEmpty()) return val keyClass = map.keys.iterator().next().javaClass.simpleName val valueClass = map.values.iterator().next().javaClass.simpleName editor.putString(key, mapToString(map, separator1, separator2)) editor.putString(key + M_POSTFIX, "$keyClass:$valueClass") } fun <T : Any> array(key: String, array: Array<T>, separator: String = ",") { if (array.isEmpty()) return val type = array.elementAt(0).javaClass.simpleName editor.putString(key, arrayToString(array, separator)) editor.putString(key + A_POSTFIX, type) } inline fun <reified T : Any> list(key: String, list: List<T>, separator: String = ",") = array(key, list.toTypedArray(), separator) inline fun <reified T : Any> set(key: String, set: Set<T>, separator: String = ",") = array(key, set.toTypedArray(), separator) internal fun save() = editor.apply() } companion object { var DEFAULT_BOOL = false var DEFAULT_BYTE: Byte = 0x00 var DEFAULT_SHORT: Short = 0 var DEFAULT_INT: Int = 0 var DEFAULT_LONG: Long = 0L var DEFAULT_FLOAT: Float = 0.0f var DEFAULT_DOUBLE: Double = 0.0 var DEFAULT_STRING = "undefined" private val M_POSTFIX = "_mapClasses" private val A_POSTFIX = "_arrayClasses" } private val listeners = mutableListOf<(SharedPreferences, String) -> Unit>() private val changeListener by lazy { SharedPreferences.OnSharedPreferenceChangeListener { prefs, key -> listeners.forEach { it(prefs, key) } } } fun put(actions: PutHelper.() -> Unit) = PutHelper(prefs).apply(actions).save() fun putBool(key: String, value: Boolean) = prefs.edit().putBoolean(key, value).apply() fun getBool(key: String, default: Boolean = DEFAULT_BOOL) = prefs.getBoolean(key, default) fun putByte(key: String, value: Byte) = prefs.edit().putInt(key, value.toInt()).apply() fun getByte(key: String, default: Byte = DEFAULT_BYTE) = prefs.getInt(key, default.toInt()).toByte() fun putShort(key: String, value: Short) = prefs.edit().putInt(key, value.toInt()).apply() fun getShort(key: String, default: Short = DEFAULT_SHORT) = prefs.getInt(key, default.toInt()).toShort() fun putInt(key: String, value: Int) = prefs.edit().putInt(key, value).apply() fun getInt(key: String, default: Int = DEFAULT_INT) = prefs.getInt(key, default) fun putLong(key: String, value: Long) = prefs.edit().putLong(key, value).apply() fun getLong(key: String, default: Long = DEFAULT_LONG) = prefs.getLong(key, default) fun putFloat(key: String, value: Float) = prefs.edit().putFloat(key, value).apply() fun getFloat(key: String, default: Float = DEFAULT_FLOAT) = prefs.getFloat(key, default) fun putDouble(key: String, value: Double) = prefs.edit() .putString(key, value.toString()) .apply() fun getDouble(key: String, default: Double = DEFAULT_DOUBLE) = prefs.getString(key, default.toString())!!.toDouble() fun putString(key: String, value: String) = prefs.edit().putString(key, value).apply() fun getString(key: String, default: String = DEFAULT_STRING) = prefs.getString(key, default)!! fun <K : Any, V : Any> putMap( key: String, map: Map<K, V>, separator1: String = ":", separator2: String = "," ) { if (map.isEmpty()) return val keyClass = map.keys.iterator().next().javaClass.simpleName val valueClass = map.values.iterator().next().javaClass.simpleName prefs.edit().apply { putString(key, mapToString(map, separator1, separator2)) putString(key + M_POSTFIX, "$keyClass:$valueClass") }.apply() } @Suppress("UNCHECKED_CAST") fun <K, V> getMap(key: String, separator1: String = ":", separator2: String = ","): Map<K, V> { if (notContains(key) || notContains(key + M_POSTFIX)) return emptyMap() val types = getString(key + M_POSTFIX) val keyType = types.substringBeforeLast(":").substringAfter(":") val valueType = types.substringAfterLast(":") return stringToMap<Any, Any>( getString(key), keyType, valueType, separator1, separator2 ) as Map<K, V> } fun <T : Any> putArray(key: String, array: Array<T>, separator: String = ",") { if (array.isEmpty()) return val type = array.elementAt(0).javaClass.simpleName prefs.edit().apply { putString(key, arrayToString(array, separator)) putString(key + A_POSTFIX, type) }.apply() } @Suppress("UNCHECKED_CAST") fun <T> getArray(key: String, separator: String = ","): Array<T> { if (notContains(key) || notContains(key + A_POSTFIX)) return emptyArray<Any>() as Array<T> val type = getString(key + A_POSTFIX) return stringToArray<Any>(getString(key), type, separator) as Array<T> } inline fun <reified T : Any> putList(key: String, list: List<T>, separator: String = ",") = putArray(key, list.toTypedArray(), separator) inline fun <T> getList(key: String, separator: String = ","): List<T> = getArray<T>(key, separator).toList() inline fun <reified T : Any> putSet(key: String, set: Set<T>, separator: String = ",") = putArray(key, set.toTypedArray(), separator) inline fun <T> getSet(key: String, separator: String = ","): Set<T> = getArray<T>(key, separator).toSet() fun contains(key: String) = prefs.contains(key) fun containsAll(keys: Iterable<String>) = keys.all { contains(it) } fun notContains(key: String) = !prefs.contains(key) fun clear() = prefs.edit().clear().apply() fun remove(key: String) { val editor = prefs.edit() editor.remove(key) when { contains(key + M_POSTFIX) -> editor.remove(key + M_POSTFIX) contains(key + A_POSTFIX) -> editor.remove(key + A_POSTFIX) } editor.apply() } fun addListener(listener: (SharedPreferences, String) -> Unit) { if (listeners.isEmpty()) { prefs.registerOnSharedPreferenceChangeListener(changeListener) } listeners.add(listener) } fun removeListener(listener: (SharedPreferences, String) -> Unit) { listeners.remove(listener) if (listeners.isEmpty()) { prefs.unregisterOnSharedPreferenceChangeListener(changeListener) } } fun clearListeners() { prefs.unregisterOnSharedPreferenceChangeListener(changeListener) listeners.clear() } }
0
Kotlin
0
1
0c9f1d392b66c82082e75dab8e65a0f3e8674af7
8,060
Mighty-Preferences
MIT License
src/main/kotlin/amaze/core/assets/Sounds.kt
dan-rusu-personal
161,058,720
true
null
package main.kotlin.amaze.core.assets import main.kotlin.amaze.core.assets.Sound.* import javax.sound.sampled.AudioSystem private const val SOUND_PATH = "/resources/sound" enum class Sound(name: String) { DYING("llama_dying.wav"), TELEPORTING("teleport.wav"), FALLING("falling.wav"), VICTORY_1("yippee1.wav"), VICTORY_2("yippee2.wav"), VICTORY_3("yippee3.wav"), VICTORY_4("yippee4.wav"); private val path = "$SOUND_PATH/$name" fun play() { try { val inputStream = AudioSystem.getAudioInputStream(javaClass.getResourceAsStream(path)) AudioSystem.getClip().run { open(inputStream) start() } } catch (e: Exception) { System.err.println("Cannot play $path due to: ${e.message}") } } } object Sounds { private val victorySounds = arrayOf(VICTORY_1, VICTORY_2, VICTORY_3, VICTORY_4) fun playVictoriousSound() { victorySounds.random().play() } }
0
Kotlin
3
17
9272fe53c6d8bbc82d9eb1d5e3f48fc655f64cc6
1,010
Kotlin-Waterloo-AMaze
MIT License
app/src/main/java/manwithandroid/learnit/models/Question.kt
Project-LearnIt
118,135,802
false
{"Kotlin": 87079}
package manwithandroid.learnit.models /** * Created by roi-amiel on 1/6/18. */ class Question { companion object { const val TYPE_CHOICE = 0 const val TYPE_OPEN = 1 const val TYPE_OPEN_SPECIFIC = 2 } var question: String = "" var description: String = "" var hint: String = "" var type: Int = TYPE_CHOICE var answers: MutableList<MutableList<String>?>? = null }
0
Kotlin
0
6
0b9d4f7bb3ca5aa81055a1ac635b1e9f4e2951ef
420
LearinIt-Android
Apache License 2.0
src/main/kotlin/com/lss233/minidb/networking/handler/mysql/command/QueryHandler.kt
lss233
535,925,912
false
null
package com.lss233.minidb.networking.handler.mysql.command import com.lss233.minidb.engine.Relation import com.lss233.minidb.engine.SQLParser import com.lss233.minidb.engine.StringUtils import com.lss233.minidb.engine.memory.Engine import com.lss233.minidb.engine.schema.Column import com.lss233.minidb.engine.visitor.CreateTableStatementVisitor import com.lss233.minidb.engine.visitor.InsertStatementVisitor import com.lss233.minidb.engine.visitor.SelectStatementVisitor import com.lss233.minidb.engine.visitor.UpdateStatementVisitor import com.lss233.minidb.networking.packets.mysql.ERRPacket import com.lss233.minidb.networking.packets.mysql.OKPacket import com.lss233.minidb.networking.packets.mysql.RequestQuery import com.lss233.minidb.networking.protocol.mysql.MySQLSession import hu.webarticum.treeprinter.printer.traditional.TraditionalTreePrinter import io.netty.channel.ChannelHandlerContext import io.netty.channel.SimpleChannelInboundHandler import miniDB.parser.ast.expression.primary.SysVarPrimary import miniDB.parser.ast.stmt.dal.* import miniDB.parser.ast.stmt.ddl.DDLCreateTableStatement import miniDB.parser.ast.stmt.ddl.DDLDropTableStatement import miniDB.parser.ast.stmt.dml.DMLInsertStatement import miniDB.parser.ast.stmt.dml.DMLQueryStatement import miniDB.parser.ast.stmt.dml.DMLReplaceStatement import miniDB.parser.ast.stmt.dml.DMLUpdateStatement import java.sql.SQLException import java.sql.SQLSyntaxErrorException class QueryHandler(val session: MySQLSession): SimpleChannelInboundHandler<RequestQuery>() { override fun channelRead0(ctx: ChannelHandlerContext?, msg: RequestQuery?) { try { Engine.session.set(session) val queryStrings = msg?.query?.split(";") for(queryString in queryStrings!!) { if(queryString.isBlank()) { continue } // 交给词法解析器 println(" Q: $queryString") val ast = SQLParser.parse(queryString) println(" Q(${ast.javaClass.simpleName}): $queryString") // 分析解析后的 SQL 语句,作出不同的反应 when(ast) { is DMLInsertStatement -> { val visitor = InsertStatementVisitor() try { ast.accept(visitor) } finally { TraditionalTreePrinter().print(visitor.rootNode) } ctx?.writeAndFlush(OKPacket())?.sync() } is DMLReplaceStatement -> { val visitor = InsertStatementVisitor() try { ast.accept(visitor) } finally { TraditionalTreePrinter().print(visitor.rootNode) } // ctx?.writeAndFlush(CommandComplete("SELECT 1"))?.sync() } is DMLUpdateStatement -> { val visitor = UpdateStatementVisitor() try { ast.accept(visitor) } finally { TraditionalTreePrinter().print(visitor.rootNode) } // ctx?.writeAndFlush(CommandComplete("UPDATE ${visitor.affects}"))?.sync() } is DDLCreateTableStatement -> { val visitor = CreateTableStatementVisitor() try { ast.accept(visitor) Engine[session.properties["database"] ?: "minidb"].createTable(visitor.relation!!, visitor.tableIdentifier!!) } finally { TraditionalTreePrinter().print(visitor.rootNode) } // ctx?.writeAndFlush(CommandComplete("SELECT 1"))?.sync() } is DDLDropTableStatement -> { val statement = ast as DDLDropTableStatement for(tableName in statement.tableNames) { Engine[session.properties["database"] ?: "minidb"].dropTable(tableName) } // ctx?.writeAndFlush(CommandComplete("DELETE 1"))?.sync() } is DMLQueryStatement -> { val relation: Relation? = if(queryString.lowercase() == "select version()") { Relation(mutableListOf(Column("version")), mutableListOf(arrayOf("1.0.0"))) } else { val visitor = SelectStatementVisitor() try { ast.accept(visitor) } finally { TraditionalTreePrinter().print(visitor.rootNode) } visitor.relation } println(relation) ctx?.writeAndFlush(relation)?.sync() } is ShowVariables -> { // 查下环境变量 val relation = Relation(mutableListOf( Column("Variable_name"), Column("Value") ), session .properties .filter { (key, _) -> StringUtils.like(key, ast.pattern.substring(1, ast.pattern.length - 1)) } .map { (key, value) -> arrayOf<Any>(key, value) } .toMutableList() ) println(relation) ctx?.writeAndFlush(relation)?.sync() } is ShowDatabases -> { // 查数据库列表 val relation = Relation(mutableListOf( Column("Database"), ), Engine.getDatabase().keys.map{ arrayOf<Any>(it)}.toMutableList() ) println(relation) ctx?.writeAndFlush(relation)?.sync() } is ShowTables -> { // 查表 val relation = Relation(mutableListOf( Column("Tables"), ), Engine[session.database!!].schemas["public"]?.views?.map{ arrayOf<Any>(it.key)}?.toMutableList() ?: mutableListOf() ) println(relation) ctx?.writeAndFlush(relation)?.sync() } is ShowTableStatus -> { val relation = Relation(mutableListOf( Column("Tables"), ), Engine[session.database!!].schemas["public"]?.views?.map{ arrayOf<Any>(it.key)}?.toMutableList() ?: mutableListOf() ) println(relation) ctx?.writeAndFlush(relation)?.sync() } is DALSetStatement -> { // 这是一条设置语句 for (pair in ast.assignmentList) { // 更新设置 session.properties[(pair.key as SysVarPrimary).varText] = pair.value.evaluation(emptyMap()).toString() // 告知客户端设置成功 // ctx?.writeAndFlush( // ParameterStatus( // (pair.key as SysVarPrimary).varText, // session.properties[(pair.key as SysVarPrimary).varText]!! // ) // )?.sync() // ctx?.writeAndFlush(CommandComplete("SET"))?.sync() ctx?.writeAndFlush(OKPacket(isEOF = false))?.sync() } } } } // 等待下一条语句 // ctx?.writeAndFlush(ReadyForQuery())?.sync() } catch (e: SQLSyntaxErrorException) { System.err.println(" Q(Error): ${msg?.query}") exceptionCaught(ctx, e) } finally { Engine.session.remove() } } override fun exceptionCaught(ctx: ChannelHandlerContext?, cause: Throwable?) { System.err.println(" Q(Error): ${cause?.message}") cause?.printStackTrace() // 告诉客户端你发的东西有问题 val err = if (cause is SQLException) ERRPacket( errorCode = cause.errorCode, sqlState = cause.sqlState, sqlStateMarker = "1", errorMessage = cause.message.toString() ) else ERRPacket( errorCode = 10000, sqlState = "12345", sqlStateMarker = "1", errorMessage = cause?.message.toString(), ) ctx?.writeAndFlush(err)?.sync() // ctx?.writeAndFlush(ReadyForQuery())?.sync() } }
1
Java
3
12
8ab3d263e57c61a648856aae269b474201746294
9,402
MiniDB
MIT License
matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/call/GetTurnServerTask.kt
aalzehla
287,565,471
false
null
/* * Copyright (c) 2020 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.matrix.android.internal.session.call import im.vector.matrix.android.api.session.call.TurnServerResponse import im.vector.matrix.android.internal.network.executeRequest import im.vector.matrix.android.internal.task.Task import org.greenrobot.eventbus.EventBus import javax.inject.Inject internal abstract class GetTurnServerTask : Task<GetTurnServerTask.Params, TurnServerResponse> { object Params } internal class DefaultGetTurnServerTask @Inject constructor(private val voipAPI: VoipApi, private val eventBus: EventBus) : GetTurnServerTask() { override suspend fun execute(params: Params): TurnServerResponse { return executeRequest(eventBus) { apiCall = voipAPI.getTurnServer() } } }
1
null
1
1
ee1d5faf0d59f9cc1c058d45fae3e811d97740fd
1,412
element-android
Apache License 2.0
android/src/main/java/com/alarmcontroller/AlarmControllerPackage.kt
Lu1sHenrique
684,331,744
false
{"Java": 7189, "Ruby": 3614, "Objective-C": 2599, "JavaScript": 1880, "Kotlin": 1194, "TypeScript": 877, "Objective-C++": 761, "Swift": 274, "C": 103}
package com.alarmcontroller import com.facebook.react.ReactPackage import com.facebook.react.bridge.NativeModule import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.uimanager.ViewManager class AlarmControllerPackage : ReactPackage { override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> { return listOf(AlarmControllerModule(reactContext)) } override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> { return emptyList() } }
1
null
1
1
de429f755b393d363ee5797b598befa077624c26
552
alarmController
MIT License
tmp/arrays/youTrackTests/9318.kt
DaniilStepanov
228,623,440
false
{"Git Config": 1, "Gradle": 6, "Text": 3, "INI": 5, "Shell": 2, "Ignore List": 3, "Batchfile": 2, "Markdown": 2, "Kotlin": 15942, "JavaScript": 4, "ANTLR": 2, "XML": 12, "Java": 4}
// Original bug: KT-14692 class A class D { operator fun A.component1() = 1.0 operator fun A.component2() = ' ' } fun foobar(block: D.(A) -> Unit) { } fun bar() { // Error: component functions are unresolved foobar { (a, b) -> } }
1
null
12
1
602285ec60b01eee473dcb0b08ce497b1c254983
251
bbfgradle
Apache License 2.0
kamp-core/src/main/kotlin/ch/leadrian/samp/kamp/core/api/callback/OnRconLoginAttemptListener.kt
Double-O-Seven
142,487,686
false
{"Kotlin": 3854710, "C": 23964, "C++": 23699, "Java": 4753, "Dockerfile": 769, "Objective-C": 328, "Batchfile": 189}
package ch.leadrian.samp.kamp.core.api.callback import ch.leadrian.samp.kamp.annotations.CallbackListener @CallbackListener(runtimePackageName = "ch.leadrian.samp.kamp.core.runtime.callback") interface OnRconLoginAttemptListener { fun onRconLoginAttempt(ipAddress: String, password: String, success: Boolean) }
1
Kotlin
1
7
af07b6048210ed6990e8b430b3a091dc6f64c6d9
319
kamp
Apache License 2.0
libraries/scripting/dependencies/src/kotlin/script/experimental/dependencies/CompoundDependenciesResolver.kt
prasenjitghose36
258,198,392
true
{"Kotlin": 46593414, "Java": 7626725, "JavaScript": 200386, "HTML": 77284, "Lex": 23805, "TypeScript": 21756, "Groovy": 11196, "CSS": 9270, "Swift": 8589, "Shell": 7220, "Batchfile": 5727, "Ruby": 1300, "Objective-C": 404, "Scala": 80}
/* * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package kotlin.script.experimental.dependencies import java.io.File import kotlin.script.experimental.api.ResultWithDiagnostics import kotlin.script.experimental.api.ScriptDiagnostic import kotlin.script.experimental.dependencies.impl.makeResolveFailureResult class CompoundDependenciesResolver(private val resolvers: List<ExternalDependenciesResolver>) : ExternalDependenciesResolver { constructor(vararg resolvers: ExternalDependenciesResolver) : this(resolvers.toList()) override fun acceptsArtifact(artifactCoordinates: String): Boolean { return resolvers.any { it.acceptsArtifact(artifactCoordinates) } } override fun acceptsRepository(repositoryCoordinates: RepositoryCoordinates): Boolean { return resolvers.any { it.acceptsRepository(repositoryCoordinates) } } override fun addRepository(repositoryCoordinates: RepositoryCoordinates) { if (resolvers.count { it.tryAddRepository(repositoryCoordinates) } == 0) throw Exception("Failed to detect repository type: $repositoryCoordinates") } override suspend fun resolve(artifactCoordinates: String): ResultWithDiagnostics<List<File>> { val reports = mutableListOf<ScriptDiagnostic>() for (resolver in resolvers) { if (resolver.acceptsArtifact(artifactCoordinates)) { when (val resolveResult = resolver.resolve(artifactCoordinates)) { is ResultWithDiagnostics.Failure -> reports.addAll(resolveResult.reports) else -> return resolveResult } } } return if (reports.count() == 0) { makeResolveFailureResult("No suitable dependency resolver found for artifact '$artifactCoordinates'") } else { ResultWithDiagnostics.Failure(reports) } } }
0
null
0
2
acced52384c00df5616231fa5ff7e78834871e64
2,047
kotlin
Apache License 2.0
app/src/main/java/jp/juggler/subwaytooter/PrefDevice.kt
geckour
143,372,698
true
{"Java": 1946657, "Kotlin": 1564260, "Perl": 42211}
package jp.juggler.subwaytooter import android.content.Context import android.content.SharedPreferences object PrefDevice { private const val file_name = "device" fun prefDevice(context : Context) : SharedPreferences { return context.getSharedPreferences(file_name, Context.MODE_PRIVATE) } internal const val KEY_DEVICE_TOKEN = "device_token" internal const val KEY_INSTALL_ID = "install_id" }
0
Java
0
0
881a9fda46051ae55630d9c8d473853e78a45ecc
410
SubwayTooter
Apache License 2.0
recovery/src/test/kotlin/com/kin/ecosystem/recovery/restore/presenter/RestoreCompletedPresenterImplTest.kt
kinecosystem
120,272,671
false
null
package com.kin.ecosystem.recovery.restore.presenter import android.os.Bundle import com.kin.ecosystem.recovery.restore.presenter.RestorePresenterImpl.KEY_ACCOUNT_INDEX import com.kin.ecosystem.recovery.restore.view.RestoreCompletedView import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.verify import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @Config(manifest = Config.NONE) @RunWith(RobolectricTestRunner::class) class RestoreCompletedPresenterImplTest { companion object { const val accountIndex = 1 } private val view: RestoreCompletedView = mock() private val parentPresenter: RestorePresenter = mock() private lateinit var presenter: RestoreCompletedPresenterImpl @Before fun setUp() { createPresenter() } @Test fun `back clicked go to previous step`() { presenter.onBackClicked() verify(parentPresenter).previousStep() } @Test fun `close flow with the correect account index`() { presenter.close() verify(parentPresenter).closeFlow(accountIndex) } @Test fun `onSaveInstanceState save the correct values`() { val bundle = Bundle() presenter.onSaveInstanceState(bundle) assertEquals(accountIndex, bundle.getInt(KEY_ACCOUNT_INDEX)) } private fun createPresenter() { presenter = RestoreCompletedPresenterImpl(accountIndex) presenter.onAttach(view, parentPresenter) } }
2
Java
12
30
8cbcffcf8192662ba760be043c0599e6ee3b5c77
1,621
kin-ecosystem-android-sdk
MIT License
src/main/kotlin/org/elm/lang/core/psi/elements/ElmTypeAnnotation.kt
zraktvor
221,007,094
true
{"Markdown": 22, "Java Properties": 1, "Gradle": 1, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "YAML": 3, "Text": 73, "INI": 1, "Java": 22, "Elm": 83, "JSON": 2, "Kotlin": 327, "XML": 5, "SVG": 9, "HTML": 12, "JFlex": 1}
package org.elm.lang.core.psi.elements import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.stubs.IStubElementType import org.elm.lang.core.psi.ElmStubbedElement import org.elm.lang.core.psi.ElmTypes.LOWER_CASE_IDENTIFIER import org.elm.lang.core.psi.ElmTypes.OPERATOR_IDENTIFIER import org.elm.lang.core.psi.stubDirectChildrenOfType import org.elm.lang.core.resolve.ElmReferenceElement import org.elm.lang.core.resolve.reference.ElmReference import org.elm.lang.core.resolve.reference.LexicalValueReference import org.elm.lang.core.resolve.reference.LocalTopLevelValueReference import org.elm.lang.core.stubs.ElmPlaceholderRefStub /** * A type annotation * * e.g. `length : String -> Int` * * Either [lowerCaseIdentifier] or [operatorIdentifier] is non-null */ class ElmTypeAnnotation : ElmStubbedElement<ElmPlaceholderRefStub>, ElmReferenceElement { constructor(node: ASTNode) : super(node) constructor(stub: ElmPlaceholderRefStub, stubType: IStubElementType<*, *>) : super(stub, stubType) /** * The left-hand side of the type annotation which names the value * * e.g. `length` in `length : String -> Int` */ val lowerCaseIdentifier: PsiElement? get() = findChildByType(LOWER_CASE_IDENTIFIER) /** * The left-hand side when the value is a binary operator instead of a normal identifier. * * e.g. `(++)` in `(++) : String -> String -> String` */ // TODO [drop 0.18] remove this property (and make lowerCaseIdentifier return non-null!) val operatorIdentifier: PsiElement? get() = findChildByType(OPERATOR_IDENTIFIER) /** * The right-hand side of the type annotation which describes the type of the value. * * e.g. `String -> Int` in `length : String -> Int` * * In a well-formed program, this will be non-null. */ val typeExpression: ElmTypeExpression? get() = stubDirectChildrenOfType<ElmTypeExpression>().singleOrNull() override val referenceNameElement: PsiElement get() = lowerCaseIdentifier ?: operatorIdentifier ?: throw RuntimeException("cannot determine type annotations's ref name element") override val referenceName: String get() = stub?.refName ?: referenceNameElement.text override fun getReference(): ElmReference = if (parent is PsiFile) LocalTopLevelValueReference(this) else LexicalValueReference(this) }
0
Kotlin
0
0
2b0952c22e54c479f9cf08971ce404e5b28d3622
2,549
intellij-elm
MIT License
breeze-core/src/main/kotlin/core/model/TypeReference.kt
DragonKnightOfBreeze
205,561,109
false
null
// Copyright (c) 2020-2021 DragonKnightOfBreeze Windea // Breeze is blowing... package icu.windea.breezeframework.core.model import java.lang.reflect.* //com.fasterxml.jackson.core.type.TypeReference //com.alibaba.fastjson.TypeReference /** * 类型引用。 */ abstract class TypeReference<T> { val type: Type init { val superClass = javaClass.genericSuperclass if(superClass !is ParameterizedType) { throw IllegalArgumentException("TypeReference must be constructed with actual type information.") } type = superClass.actualTypeArguments[0] } }
1
null
1
8
c8198c558117544eb65c1d01ec3f34172148b067
558
Breeze-Framework
MIT License
kapp/src/main/java/com/joyy/loadsir/target/KeepTitleActivity.kt
AdrianAndroid
400,467,910
true
{"Markdown": 8, "Gradle": 6, "INI": 1, "Shell": 1, "Ignore List": 5, "Batchfile": 1, "Java Properties": 1, "Proguard": 4, "XML": 63, "Java": 47, "JSON": 4, "Kotlin": 33}
package com.joyy.loadsir.target import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import com.joyy.loadsir.LoadSir import android.widget.FrameLayout import android.widget.LinearLayout import android.widget.TextView import androidx.annotation.Nullable import com.joyy.loadsir.R import com.joyy.loadsir.callback.ErrorCallback import com.joyy.loadsir.callback.LoadingCallback import com.joyy.loadsir.callback.SuccessCallback import com.joyy.loadsir.core.LoadService class KeepTitleActivity : BaseTitleActivity() { var mTvTitle: TextView? = null override fun getContentTitle(): String? { return "Title" } override fun getContentView(): Int { return R.layout.activity_content } override fun initView() { val mTvMsg = findViewById<TextView>(com.joyy.loadsir.R.id.tv_subTitle) mTvMsg?.text = "Keep Title In Activity" mTvTitle?.text = "Yes, Success" } override fun initNet() { mBaseLoadService.showCallback(ErrorCallback::class, 2000) } override fun onNetReload(v: View) { mBaseLoadService.showCallback(LoadingCallback::class) mBaseLoadService.showCallback(SuccessCallback::class, 2000) } } abstract class BaseTitleActivity : AppCompatActivity() { lateinit var rootView: View lateinit var mBaseLoadService: LoadService override fun onCreate(@Nullable savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) rootView = View.inflate(this, R.layout.activity_keep_title, null) addContent() setContentView(rootView) initView() initNet() } open fun addContent() { val flContent: FrameLayout = rootView.findViewById(R.id.fl_content) val tvTitleTitle: TextView = rootView.findViewById(R.id.tv_title_title) val llTitleBack: LinearLayout = rootView.findViewById(R.id.ll_title_back) tvTitleTitle.text = if (getContentTitle() == null) "" else getContentTitle() llTitleBack.setOnClickListener { v: View? -> backClick() } val content = View.inflate(this, getContentView(), null) if (content != null) { val params = FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT ) flContent.addView(content, params) mBaseLoadService = LoadSir.register(content) { loadService, view -> onNetReload(view) } // LoadSir.getDefault().register(content, ::onNetReload as Callback.OnReloadListener) } } private fun backClick() { finish() } protected abstract fun getContentTitle(): String? protected abstract fun getContentView(): Int protected abstract fun initView() protected abstract fun initNet() protected abstract fun onNetReload(v: View) }
0
Java
0
0
872b4cf65f2d446026df1b3582779bf1a743ccf0
2,937
LoadSir
Apache License 2.0
full/src/test/kotlin/apoc/nlp/azure/AzureVirtualSentimentGraphStoreTest.kt
neo4j-contrib
52,509,220
false
{"Java": 5702078, "Kotlin": 289604, "Cypher": 123048, "Roff": 44458, "HTML": 42496, "ANTLR": 1509, "JavaScript": 517}
/** * Copyright (c) "Neo4j" * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 apoc.nlp.azure import apoc.nlp.NodeMatcher import apoc.result.VirtualNode import junit.framework.Assert.assertEquals import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.hasItem import org.junit.AfterClass import org.junit.ClassRule import org.junit.Test import org.neo4j.graphdb.Label import org.neo4j.test.rule.ImpermanentDbmsRule class AzureVirtualSentimentGraphStoreTest { companion object { @ClassRule @JvmField val neo4j = ImpermanentDbmsRule() @AfterClass @JvmStatic fun afterClass() { neo4j.shutdown() } } @Test fun `create virtual graph from result with one entity`() { neo4j.beginTx().use { val sourceNode = VirtualNode(arrayOf(Label { "Person" }), mapOf("id" to 1234L)) val res = listOf( mapOf("id" to sourceNode.id.toString(), "score" to 0.75) ) val virtualGraph = AzureVirtualSentimentVirtualGraph(res, listOf(sourceNode)).createAndStore(it) val nodes = virtualGraph.graph["nodes"] as Set<*> assertEquals(1, nodes.size) assertThat(nodes, hasItem(sourceNode)) assertThat(nodes, hasItem(NodeMatcher(listOf(Label { "Person" }), mapOf( "sentimentScore" to 0.75, "id" to 1234L)))) } } }
142
Java
494
1,705
3f983de9c020ec444386ceaf39386616b6bb0071
2,015
neo4j-apoc-procedures
Apache License 2.0
src/main/kotlin/no/nav/k9brukerdialogapi/ytelse/pleiepengerlivetssluttfase/domene/UtenlandskNæring.kt
navikt
460,765,798
false
{"Kotlin": 836022, "Dockerfile": 103}
package no.nav.k9brukerdialogapi.ytelse.pleiepengerlivetssluttfase.domene import no.nav.k9brukerdialogapi.general.erLikEllerEtter import no.nav.k9brukerdialogapi.general.krever import no.nav.k9brukerdialogapi.ytelse.fellesdomene.Næringstype import java.time.LocalDate class UtenlandskNæring( private val næringstype: Næringstype, private val navnPåVirksomheten: String, private val land: no.nav.k9brukerdialogapi.ytelse.fellesdomene.Land, private val organisasjonsnummer: String? = null, private val fraOgMed: LocalDate, private val tilOgMed: LocalDate? = null ) { companion object { internal fun List<UtenlandskNæring>.valider(felt: String = "utenlandskNæring") = flatMapIndexed { index, utenlandskNæring -> utenlandskNæring.valider("$felt[$index]") } } internal fun valider(felt: String) = mutableListOf<String>().apply { tilOgMed?.let { krever(tilOgMed.erLikEllerEtter(fraOgMed), "$felt.tilOgMed må være lik eller etter fraOgMed.") } addAll(land.valider("$felt.land")) } }
2
Kotlin
0
0
65c4614f96ae9907167edfee1adab76f237308d5
1,065
k9-brukerdialog-api
MIT License
radar-commons/src/main/java/org/radarbase/producer/rest/ConnectionState.kt
RADAR-base
82,068,774
false
{"Kotlin": 339732, "Java": 33339}
/* * Copyright 2017 The Hyve and King's College London * * 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.radarbase.producer.rest import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.channels.BufferOverflow.DROP_OLDEST import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.shareIn import kotlinx.coroutines.flow.transformLatest import kotlinx.coroutines.plus import kotlin.coroutines.EmptyCoroutineContext import kotlin.time.Duration /** * Current connection status of a KafkaSender. After a timeout occurs this will turn to * disconnected. When the connection is dropped, the associated KafkaSender should set this to * disconnected, when it successfully connects, it should set it to connected. This class is * thread-safe. The state transition diagram is CONNECTED to and from DISCONNECTED with * [.didConnect] and [.didDisconnect]; CONNECTED to and from UNKNOWN with * [.getState] after a timeout occurs and [.didConnect]; and UNKNOWN to DISCONNECTED * with [.didDisconnect]. * * * A connection state could be shared with multiple HTTP clients if they are talking to the same * server. * * @param timeout timeout after which the connected state will be reset to unknown. * @throws IllegalArgumentException if the timeout is not strictly positive. */ class ConnectionState( private val timeout: Duration, scope: CoroutineScope = CoroutineScope(EmptyCoroutineContext), ) { /** State symbols of the connection. */ enum class State { CONNECTED, DISCONNECTED, UNKNOWN, UNAUTHORIZED } val scope = scope + Job() private val mutableState = MutableSharedFlow<State>( extraBufferCapacity = 1, onBufferOverflow = DROP_OLDEST, ) @OptIn(ExperimentalCoroutinesApi::class) val state: Flow<State> = mutableState .transformLatest { state -> emit(state) if (state == State.CONNECTED) { delay(timeout) emit(State.UNKNOWN) } } .distinctUntilChanged() .shareIn(this.scope + Dispatchers.Unconfined, SharingStarted.Eagerly, replay = 1) init { mutableState.tryEmit(State.UNKNOWN) } /** For a sender to indicate that a connection attempt succeeded. */ suspend fun didConnect() { mutableState.emit(State.CONNECTED) } /** For a sender to indicate that a connection attempt failed. */ suspend fun didDisconnect() { mutableState.emit(State.DISCONNECTED) } suspend fun wasUnauthorized() { mutableState.emit(State.UNAUTHORIZED) } suspend fun reset() { mutableState.emit(State.UNKNOWN) } }
3
Kotlin
3
2
b231a69ca289716bf3143bdba183aa993f112408
3,488
radar-commons
Apache License 2.0
src/main/kotlin/springrod/localrag/UploadController.kt
johnsonr
848,500,466
false
{"Kotlin": 15708, "HTML": 1601, "CSS": 1135}
package springrod.localrag import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.ai.reader.tika.TikaDocumentReader import org.springframework.ai.transformer.splitter.TokenTextSplitter import org.springframework.ai.vectorstore.VectorStore import org.springframework.core.io.ResourceLoader import org.springframework.web.bind.annotation.PutMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RestController data class DocumentUpload( val url: String ) @RestController class UploadController( private val vectorStore: VectorStore, private val resourceLoader: ResourceLoader, ) { private val logger: Logger = LoggerFactory.getLogger(UploadController::class.java) @PutMapping("/documents") fun addDocument(@RequestBody documentUpload: DocumentUpload): List<String> { logger.info("Adding document from '${documentUpload.url}'") val r = resourceLoader.getResource(documentUpload.url) val content = TikaDocumentReader(documentUpload.url).get() val documents = TokenTextSplitter().split(content) vectorStore.add(documents) return documents.map { it.id} } }
0
Kotlin
1
19
2a86afa3e31346bf4e6ba1a1ba845172fdaa2e4e
1,218
instrumented-rag
Apache License 2.0
plugins/kotlin/idea/tests/testData/refactoring/rename/renameKotlinClassConflictingWithJava/after/rename/test.kt
JetBrains
2,489,216
false
null
package rename class X { class /*rename*/JavaConflict { val b: JavaConflict = JavaConflict() val j: rename.JavaConflict = rename.JavaConflict() } }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
173
intellij-community
Apache License 2.0