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
feature/account/setup/src/main/kotlin/app/k9mail/feature/account/setup/ui/autodiscovery/view/AutoDiscoveryResultHeaderView.kt
thunderbird
1,326,671
false
null
package app.k9mail.feature.account.setup.ui.autodiscovery.view import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredSize import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import app.k9mail.core.ui.compose.designsystem.atom.icon.Icon import app.k9mail.core.ui.compose.designsystem.atom.icon.Icons import app.k9mail.core.ui.compose.designsystem.atom.text.TextBodyMedium import app.k9mail.core.ui.compose.designsystem.atom.text.TextTitleLarge import app.k9mail.core.ui.compose.theme2.MainTheme @Suppress("LongMethod") @Composable internal fun AutoDiscoveryResultHeaderView( state: AutoDiscoveryResultHeaderState, isExpanded: Boolean, modifier: Modifier = Modifier, ) { Row( modifier = Modifier .fillMaxWidth() .then(modifier), verticalAlignment = Alignment.CenterVertically, ) { Icon( imageVector = state.icon, tint = selectColor(state), modifier = Modifier .padding(MainTheme.spacings.default) .requiredSize(MainTheme.sizes.medium), ) Column( modifier = Modifier .weight(1f) .padding( start = MainTheme.spacings.default, top = MainTheme.spacings.half, bottom = MainTheme.spacings.half, ), ) { TextTitleLarge( text = stringResource(state.titleResourceId), ) TextBodyMedium( text = stringResource(state.subtitleResourceId), color = selectColor(state), ) } if (state.isExpandable) { Icon( imageVector = if (isExpanded) Icons.Outlined.ExpandLess else Icons.Outlined.ExpandMore, modifier = Modifier.padding(MainTheme.spacings.default), ) } } } @Composable private fun selectColor(state: AutoDiscoveryResultHeaderState): Color { return when (state) { AutoDiscoveryResultHeaderState.NoSettings -> MainTheme.colors.primary AutoDiscoveryResultHeaderState.Trusted -> MainTheme.colors.success AutoDiscoveryResultHeaderState.Untrusted -> MainTheme.colors.warning } }
846
null
2467
9,969
8b3932098cfa53372d8a8ae364bd8623822bd74c
2,599
thunderbird-android
Apache License 2.0
mobile/app/src/main/kotlin/com/radikal/pcnotifications/contracts/PairingContract.kt
tudor07
76,193,263
false
null
package com.radikal.pcnotifications.contracts import com.radikal.pcnotifications.model.domain.ServerDetails /** * Created by tudor on 17.02.2017. */ interface PairingContract { interface View : BaseView { fun showMessage(message: String) fun onServerFound() fun onServerFindFailed() } interface Presenter : BasePresenter<PairingContract.View> { fun attachStateListeners() fun onServerDetails(serverDetails: ServerDetails) fun isConnected(): Boolean } }
0
Kotlin
0
0
ce398601e6500c44119a867bbe72a6d7b0e6a301
521
pc-notifications
Apache License 2.0
src/test/kotlin/no/nav/syfo/testutil/HttpClientTest.kt
navikt
250,256,212
false
null
package no.nav.syfo.testutil import com.fasterxml.jackson.module.kotlin.registerKotlinModule import io.ktor.client.HttpClient import io.ktor.client.engine.mock.MockEngine import io.ktor.client.engine.mock.respond import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.http.Headers import io.ktor.http.HttpStatusCode import io.ktor.http.headersOf import io.ktor.serialization.jackson.jackson data class ResponseData(val httpStatusCode: HttpStatusCode, val content: String, val headers: Headers = headersOf("Content-Type", listOf("application/json"))) class HttpClientTest { var responseData: ResponseData? = null var responseDataOboToken: ResponseData? = null val httpClient = HttpClient(MockEngine) { install(ContentNegotiation) { jackson { registerKotlinModule() } } engine { addHandler { request -> if (request.url.host == "obo") { respond(responseDataOboToken!!.content, responseDataOboToken!!.httpStatusCode, responseDataOboToken!!.headers) } else { respond(responseData!!.content, responseData!!.httpStatusCode, responseData!!.headers) } } } } }
0
Kotlin
1
0
eddc543b209c2e003180e977a7619d0d694b740a
1,284
smregistrering-backend
MIT License
src/main/kotlin/com/autonomousapps/internal/graph/Topological.kt
autonomousapps
217,134,508
false
null
package com.autonomousapps.graph import com.google.common.graph.Graph import com.google.common.graph.Traverser import java.util.* /** With thanks to Algorithms, 4th Ed. See p582 for the explanation for why we want the reverse postorder. */ @Suppress("UnstableApiUsage") // Guava graphs public class Topological<N>( graph: Graph<N>, source: N ) where N : Any { public val order: Iterable<N> init { val postorder: Iterable<N> = Traverser.forGraph(graph).depthFirstPostOrder(source) val reverse = ArrayDeque<N>() for (node in postorder) reverse.push(node) order = reverse } }
41
null
55
910
da02a56a0b7a00a26876cdaa29321f8376bf7099
603
dependency-analysis-android-gradle-plugin
Apache License 2.0
multiplatform/src/commonMain/kotlin/com/vsevolodganin/clicktrack/utils/decompose/NavigationExtensions.kt
vganin
293,315,190
false
{"Kotlin": 627064, "C++": 4113, "Ruby": 2549, "Swift": 526, "CMake": 281}
package com.vsevolodganin.clicktrack.utils.decompose import com.arkivanov.decompose.router.stack.navigate import com.vsevolodganin.clicktrack.ScreenConfiguration import com.vsevolodganin.clicktrack.ScreenStackNavigation fun ScreenStackNavigation.resetTo(config: ScreenConfiguration) { navigate { stack -> listOf(stack.first(), config) } } fun ScreenStackNavigation.pushIfUnique(config: ScreenConfiguration) { navigate(transformer = { stack -> if (stack.last() == config) stack else stack + config }) }
10
Kotlin
1
22
e0de3d92ee1921eda2053064fd4ae082b831caa9
513
click-track
Apache License 2.0
database-postgres-jdbc-generator/src/commonMain/kotlin/com/github/mejiomah17/yasb/postgres/jdbc/generator/column/DoublePrecision.kt
MEJIOMAH17
492,593,605
false
{"Kotlin": 307256}
package com.github.mejiomah17.yasb.postgres.jdbc.generator.column import com.github.mejiomah17.yasb.dsl.generator.ColumnMetadata import com.github.mejiomah17.yasb.dsl.generator.toCamelCase class DoublePrecision(private val name: String, private val nullable: Boolean) : ColumnMetadata { override fun columnDefinition(): String { return if (!nullable) { "val ${name.toCamelCase()} = doublePrecision(\"$name\")" } else { "val ${name.toCamelCase()} = doublePrecisionNullable(\"$name\")" } } }
0
Kotlin
0
8
82116cd3674fedd789dd10463be5f22a9b4024c5
549
yasb
MIT License
exampleapp/android/app/src/main/kotlin/com/chandlernewman/goflutterexample/exampleapp/MainActivity.kt
csnewman
676,076,311
false
{"C": 172002, "Go": 46207, "Dart": 33464, "C++": 23771, "CMake": 19448, "Ruby": 2803, "Swift": 1715, "HTML": 1224, "Kotlin": 147, "Objective-C": 38}
package com.chandlernewman.goflutterexample.exampleapp import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity()
0
C
3
28
bf347b32a54127b6430aa1dcb35beaa486829e4b
147
flutter-go-bridge
MIT License
app/src/main/java/top/abr/androidexp6/StorageAccessor.kt
AndyBRoswell
418,013,299
false
null
package top.abr.androidexp6 import java.io.FileInputStream import java.io.FileOutputStream import java.io.ObjectInputStream import java.io.ObjectOutputStream import java.lang.NullPointerException open class StorageAccessor { companion object { fun ReadBookList(A: BooksAdapter, SerializedFile: String) { val BookListIStream = ObjectInputStream(FileInputStream(SerializedFile)) A.BookList.clear() var B: Book while (true) { try { B = BookListIStream.readObject() as Book A.BookList.add(B) } catch (E: NullPointerException) { break; } } BookListIStream.close() A.notifyItemChanged(0) } fun SaveBookList(A: BooksAdapter, TargetedFile: String) { val BookListOStream = ObjectOutputStream(FileOutputStream(TargetedFile)) for (B in A.BookList) { BookListOStream.writeObject(B) } BookListOStream.writeObject(null) BookListOStream.close() } } }
0
Kotlin
0
0
eb122ca55ce235261465e990205e3439915cc357
910
RecyclerViewDemo
MIT License
app/src/main/java/com/summer/base/library/demo/caidao/share/google/ActivityShareGoogle.kt
Summer-yang
135,402,976
false
{"Java": 189522, "Kotlin": 107188}
package com.summer.base.library.demo.caidao.share.google import android.app.Activity import android.content.Intent import android.graphics.BitmapFactory import android.net.Uri import android.os.Bundle import android.provider.MediaStore import com.google.android.gms.plus.PlusShare import com.summer.base.library.R import com.summer.base.library.base.BaseActivity import kotlinx.android.synthetic.main.activity_share_google.* /** * Google+ 分享 * 1.首先引入 * implementation 'com.google.android.gms:play-services-plus:15.0.1' * * */ class ActivityShareGoogle : BaseActivity() { private val REQ_SELECT_PHOTO = 1 private val REQ_START_SHARE = 2 override fun getDataFromLastView(bundle: Bundle?) { } override fun getLayout(): Int { return R.layout.activity_share_google } override fun initView() { val imagePath = MediaStore.Images.Media.insertImage(contentResolver, BitmapFactory.decodeStream(assets.open("icon_512.png")), "icon_512", "BaseLibrary") btnBasicShareGoogle.setOnClickListener { basicShareOnGooglePlus() } btnShareInteractive.setOnClickListener { shareInteractiveOnGooglePlus() } btnShareImageOrVideo.setOnClickListener { shareImageOrVideoOnGooglePlus() } } /** * 分享文本与连接 * You can mention specific people in the prefilled text by adding a plus sign (+) followed by their Google+ user ID or their email address */ private fun basicShareOnGooglePlus() { val shareIntent = PlusShare.Builder(this) .setType("text/plain") .setText("Heard about this restaurant from <EMAIL> #nomnomnom") .setContentUrl(Uri.parse("https://developers.google.com/+/")) .intent startActivityForResult(shareIntent, 0) } /** * 分享交互式帖子 */ private fun shareInteractiveOnGooglePlus() { val builder = PlusShare.Builder(this) // Set call-to-action metadata. builder.addCallToAction( "CREATE_ITEM", /** call-to-action button label */ Uri.parse("http://plus.google.com/pages/create"), /** call-to-action url (for desktop use) */ "/pages/create" /** call to action deep-link ID (for mobile use), 512 characters or fewer */) // Set the content url (for desktop use). builder.setContentUrl(Uri.parse("https://plus.google.com/pages/")) // Set the target deep-link ID (for mobile use). builder.setContentDeepLinkId("/pages/", null, null, null) // Set the share text. builder.setText("Create your Google+ Page too!") startActivityForResult(builder.intent, 0) } /** * When you share media to Google+, you cannot also use the setContentUrl method. * If you want to include a URL in the post with the media, * you should append the URL to the prefilled text in the setText() method. */ private fun shareImageOrVideoOnGooglePlus() { // 在相册里选择多媒体资源 val photoPicker = Intent(Intent.ACTION_PICK) photoPicker.type = "video/*, image/*" startActivityForResult(photoPicker, REQ_SELECT_PHOTO) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REQ_SELECT_PHOTO) { if (resultCode == Activity.RESULT_OK) { val selectedImage = intent.data val cr = this.contentResolver val mime = cr.getType(selectedImage) val share = PlusShare.Builder(this) share.setText("hello everyone!") share.addStream(selectedImage) share.setType(mime) startActivityForResult(share.intent, REQ_START_SHARE) } } } }
1
null
1
1
c33ccffeae94430bdfc4ab868415d5603d2ceaae
4,020
KotlinCaidao
Apache License 2.0
data/remote/src/main/java/com/harera/remote/service/MessageService.kt
hassan0shaban
289,748,566
false
null
package com.harera.remote.service import com.harera.model.response.ChatResponse import com.harera.model.response.MessageResponse import com.harera.remote.Routing import com.harera.remote.URL import com.harera.remote.request.MessageInsertRequest import io.ktor.client.* import io.ktor.client.request.* import io.ktor.http.* interface MessageService { suspend fun insertMessage(token: String, request: MessageInsertRequest): String suspend fun deleteMessage(token: String, messageId: Int): String suspend fun getMessage(token: String, messageId: Int): MessageResponse suspend fun getMessages(token: String, username: String): List<MessageResponse> suspend fun getChats(token: String): List<ChatResponse> } class MessageServiceImpl(private val client: HttpClient) : MessageService { override suspend fun insertMessage(token: String, request: MessageInsertRequest) = client.post<String> { url(Routing.INSERT_MESSAGE) header(HttpHeaders.Authorization, "Bearer $token") contentType(ContentType.Application.Json) body = request } override suspend fun deleteMessage(token: String, messageId: Int) = client.delete<String> { url(URL.BASE_URL.plus("/message/$messageId")) header(HttpHeaders.Authorization, "Bearer $token") } override suspend fun getMessage(token: String, messageId: Int): MessageResponse = client.get<MessageResponse> { url(URL.BASE_URL.plus("/message/$messageId")) header(HttpHeaders.Authorization, "Bearer $token") } override suspend fun getMessages(token: String, username: String): List<MessageResponse> = client.get<List<MessageResponse>> { url(URL.BASE_URL.plus("/chat/$username")) header(HttpHeaders.Authorization, "Bearer $token") } override suspend fun getChats(token: String): List<ChatResponse> = client.get<List<ChatResponse>> { url(URL.BASE_URL.plus("/chats")) header(HttpHeaders.Authorization, "Bearer $token") } }
0
Kotlin
0
0
94b13cdec71a77bb0e2167e2027e66bdf99ba09d
2,106
Insta
Apache License 2.0
app/src/main/java/io/nekohasekai/sagernet/fmt/naive/NaiveFmt.kt
xchacha20-poly1305
735,230,186
false
{"Kotlin": 870875, "Java": 202335, "Go": 110430, "Shell": 8239, "AIDL": 902, "Makefile": 304}
package io.nekohasekai.sagernet.fmt.naive import io.nekohasekai.sagernet.database.DataStore import io.nekohasekai.sagernet.fmt.LOCALHOST import io.nekohasekai.sagernet.ktx.* import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import org.json.JSONObject fun parseNaive(link: String): NaiveBean { val proto = link.substringAfter("+").substringBefore(":") val url = ("https://" + link.substringAfter("://")).toHttpUrlOrNull() ?: error("Invalid naive link: $link") return NaiveBean().also { it.proto = proto }.apply { serverAddress = url.host serverPort = url.port username = url.username password = <PASSWORD> sni = url.queryParameter("sni") extraHeaders = url.queryParameter("extra-headers")?.unUrlSafe()?.replace("\r\n", "\n") insecureConcurrency = url.queryParameter("insecure-concurrency")?.toIntOrNull() name = url.fragment initializeDefaultValues() } } fun NaiveBean.toUri(proxyOnly: Boolean = false): String { val builder = linkBuilder().host(finalAddress).port(finalPort) if (username.isNotBlank()) { builder.username(username) } if (password.isNotBlank()) { builder.password(password) } if (!proxyOnly) { if (sni.isNotBlank()) { builder.addQueryParameter("sni", sni) } if (extraHeaders.isNotBlank()) { builder.addQueryParameter("extra-headers", extraHeaders) } if (name.isNotBlank()) { builder.encodedFragment(name.urlSafe()) } if (insecureConcurrency > 0) { builder.addQueryParameter("insecure-concurrency", "$insecureConcurrency") } } return builder.toLink(if (proxyOnly) proto else "naive+$proto", false) } fun NaiveBean.buildNaiveConfig(port: Int): String { return JSONObject().apply { // process ipv6 finalAddress = finalAddress.wrapIPV6Host() serverAddress = serverAddress.wrapIPV6Host() // process sni if (sni.isNotBlank()) { put("host-resolver-rules", "MAP $sni $finalAddress") finalAddress = sni } else { if (serverAddress.isIpAddress()) { // for naive, using IP as SNI name hardly happens // and host-resolver-rules cannot resolve the SNI problem // so do nothing } else { put("host-resolver-rules", "MAP $serverAddress $finalAddress") finalAddress = serverAddress } } put("listen", "socks://$LOCALHOST:$port") put("proxy", toUri(true)) if (extraHeaders.isNotBlank()) { put("extra-headers", extraHeaders.split("\n").joinToString("\r\n")) } if (DataStore.logLevel > 0) { put("log", "") } if (insecureConcurrency > 0) { put("insecure-concurrency", insecureConcurrency) } }.toStringPretty() }
3
Kotlin
6
93
d574b8d42903686836d11ae524e378317e584a19
2,980
husi
BSD Source Code Attribution
src/main/kotlin/org/andrejs/cassandra/conditions/SelectCondition.kt
Bhanditz
168,960,693
true
{"Kotlin": 8277, "Java": 3791}
package org.andrejs.cassandra.conditions import org.apache.cassandra.cql3.QueryOptions import org.apache.cassandra.cql3.statements.ParsedStatement import org.apache.cassandra.cql3.statements.SelectStatement import org.apache.cassandra.service.QueryState class SelectCondition(val table: String) : Condition { override fun applies(state: QueryState, options: QueryOptions, prepared: ParsedStatement.Prepared): Boolean { val statement = prepared.statement return if(statement is SelectStatement) { table == statement.columnFamily() } else { false } } }
0
Kotlin
0
0
8f2bd4296b4b46828d9fe031504be1b13306dc31
618
cassandra-spy
Apache License 2.0
openapi-processor-core/src/main/kotlin/io/openapiprocessor/core/converter/mapping/steps/RootStepX.kt
openapi-processor
547,758,502
false
{"Kotlin": 903887, "Groovy": 178897, "Java": 119685, "ANTLR": 2598, "TypeScript": 1166, "Just": 263}
/* * Copyright 2024 https://github.com/openapi-processor-base/openapi-processor-core * PDX-License-Identifier: Apache-2.0 */ package io.openapiprocessor.core.converter.mapping.steps class RootStepX(val message: String = "", val extension: String) : ItemsStep() { override fun log(indent: String) { log("{} '{}'", message, extension) if (!hasMappings()) { log("$indent $NO_MATCH", "no mappings") return } steps.filter { it.hasMappings() } .forEach { it.log("$indent ") } } override fun isEqual(step: MappingStep): Boolean { return false } }
13
Kotlin
3
2
08038646bf84c910bd31e9bfc36c3ac7c45219c7
642
openapi-processor-base
Apache License 2.0
app/src/main/java/com/rarilabs/rarime/modules/passportScan/CircuitUseCase.kt
rarimo
775,551,013
false
{"Kotlin": 1003623, "Java": 86126, "C++": 17305, "C": 5321, "CMake": 1262}
package com.rarilabs.rarime.modules.passportScan import android.content.Context import android.util.Log import com.rarilabs.rarime.BaseConfig import com.rarilabs.rarime.modules.passportScan.models.RegisteredCircuitData import com.rarilabs.rarime.util.ErrorHandler import com.rarilabs.rarime.util.FileDownloaderInternal import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.suspendCancellableCoroutine import java.io.File data class DownloadRequest( val zkey: String, val zkeyLen: Long, val dat: String, val datLen: Long ) class CircuitUseCase(val context: Context) { private val fileDownloader = FileDownloaderInternal(context) @OptIn(ExperimentalCoroutinesApi::class) suspend fun download( circuitData: RegisteredCircuitData, onProgressUpdate: (Int, Boolean) -> Unit ): DownloadRequest? = suspendCancellableCoroutine { continuation -> val circuitURL = when (circuitData) { RegisteredCircuitData.REGISTER_IDENTITY_UNIVERSAL_RSA2048 -> BaseConfig.REGISTER_IDENTITY_CIRCUIT_DATA_RSA2048 RegisteredCircuitData.REGISTER_IDENTITY_UNIVERSAL_RSA4096 -> BaseConfig.REGISTER_IDENTITY_CIRCUIT_DATA_RSA4096 } continuation.invokeOnCancellation { // Handle coroutine cancellation if needed ErrorHandler.logError("Download", "Download coroutine cancelled") } if (fileExists(context, CIRCUIT_NAME_ARCHIVE)) { val zkeyLen = fileDownloader.getFileAbsolute(getZkeyFilePath(circuitData)).length() val datLen = fileDownloader.getFileAbsolute(getDatFilePath(circuitData)).length() val downloadRequest = DownloadRequest( zkey = getZkeyFilePath(circuitData), zkeyLen, dat = getDatFilePath(circuitData), datLen ) ErrorHandler.logDebug("Download", "Already downloaded") continuation.resume(downloadRequest) {} return@suspendCancellableCoroutine } fileDownloader.downloadFile( circuitURL, CIRCUIT_NAME_ARCHIVE ) { success, isFinished, progress -> if (success) { if (!isFinished) { onProgressUpdate(progress, false) } else { onProgressUpdate(100, true) Log.i("Download", "File Downloaded") val archive = fileDownloader.getFile(CIRCUIT_NAME_ARCHIVE) val resultOfUnzip = fileDownloader.unzipFile(archive) if (resultOfUnzip) { onProgressUpdate(100, true) fileDownloader.getFile(getZkeyFilePath(circuitData)).length() val zkeyLen = fileDownloader.getFileAbsolute(getZkeyFilePath(circuitData)).length() val datLen = fileDownloader.getFileAbsolute(getDatFilePath(circuitData)).length() val downloadRequest = DownloadRequest( zkey = getZkeyFilePath(circuitData), zkeyLen, dat = getDatFilePath(circuitData), datLen ) continuation.resume(downloadRequest) {} } else { ErrorHandler.logError("Download", "Unzip failed") continuation.resume(null) {} } } } else { ErrorHandler.logError("Download", "Download failed") continuation.resume(null) {} } } } fun getDatFilePath(circuitData: RegisteredCircuitData): String { return "${context.filesDir}/${circuitData.value}-download/${circuitData.value}.dat" } fun fileExists(context: Context, fileName: String): Boolean { val file = File(context.filesDir, fileName) return file.exists() } fun getZkeyFilePath(circuitData: RegisteredCircuitData): String { return "${context.filesDir}/${circuitData.value}-download/circuit_final.zkey" } private companion object { const val CIRCUIT_NAME_ARCHIVE = "CIRCUIT_ARCHIVE.zip" } }
2
Kotlin
0
5
4a6f02a529298467905c6929dedbc67e803f86f5
4,311
rarime-android-app
MIT License
src/main/kotlin/com/vonage/client/kt/Vonage.kt
Vonage
810,847,575
false
{"Kotlin": 150268}
/* * Copyright 2024 Vonage * * 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.vonage.client.kt import com.vonage.client.HttpConfig import com.vonage.client.VonageClient class Vonage(init: VonageClient.Builder.() -> Unit) { private val vonageClient : VonageClient = VonageClient.builder().apply(init).build(); val messages = Messages(vonageClient.messagesClient) val verify = Verify(vonageClient.verify2Client) val voice = Voice(vonageClient.voiceClient) val sms = Sms(vonageClient.smsClient) val conversion = Conversion(vonageClient.conversionClient) val redact = Redact(vonageClient.redactClient) val verifyLegacy = VerifyLegacy(vonageClient.verifyClient) val numberInsight = NumberInsight(vonageClient.insightClient) val simSwap = SimSwap(vonageClient.simSwapClient) val numberVerification = NumberVerification(vonageClient.numberVerificationClient) } fun VonageClient.Builder.authFromEnv(): VonageClient.Builder { val apiKey = env("VONAGE_API_KEY") val apiSecret = env("VONAGE_API_SECRET") val signatureSecret = env("VONAGE_SIGNATURE_SECRET") val applicationId = env("VONAGE_APPLICATION_ID") val privateKeyPath = env("VONAGE_PRIVATE_KEY_PATH") if (apiKey != null) apiKey(apiKey) if (apiSecret != null) apiSecret(apiSecret) if (signatureSecret != null) signatureSecret(signatureSecret) if (applicationId != null) applicationId(applicationId) if (privateKeyPath != null) privateKeyPath(privateKeyPath) return this } fun VonageClient.Builder.httpConfig(init: HttpConfig.Builder.() -> Unit): VonageClient.Builder = httpConfig(HttpConfig.builder().apply(init).build()) private fun env(variable: String) : String? = System.getenv(variable)
1
Kotlin
0
1
f4f1dfef1e5b52e9655ac905d7e4375aa852307a
2,279
vonage-kotlin-sdk
Apache License 2.0
src/main/kotlin/no/skatteetaten/aurora/gradle/plugins/extensions/Versions.kt
Skatteetaten
87,403,632
false
null
@file:Suppress("unused") package no.skatteetaten.aurora.gradle.plugins.extensions open class Versions { var javaSourceCompatibility: String? = null var groovy: String? = null var spock: String? = null var junit5: String? = null var jacocoTools: String? = null var cglib: String? = null var objenesis: String? = null var auroraSpringBootMvcStarter: String? = null var auroraSpringBootWebFluxStarter: String? = null var springCloudContract: String? = null var kotlinLogging: String? = null var checkstyleConfig: String? = null var checkstyleConfigFile: String? = null }
1
Kotlin
2
2
ec414d87869b825c10f16157549b560fcc92e26c
622
aurora-gradle-plugin
Apache License 2.0
aspoet/src/test/kotlin/com/google/androidstudiopoet/models/BazelWorkspaceBlueprintTest.kt
sagar-openxell
149,072,945
true
{"Kotlin": 285757}
package com.google.androidstudiopoet.models import com.google.androidstudiopoet.testutils.assertEquals import com.google.androidstudiopoet.utils.joinPath import org.junit.Test class BazelWorkspaceBlueprintTest { @Test fun `workspace path is at the root of the project`() { val blueprint = getBazelWorkspaceBlueprint("rootPath") blueprint.workspacePath.assertEquals("rootPath".joinPath("WORKSPACE")) } @Test fun `workspace file content contains android_sdk_repository declaration`() { val blueprint = getBazelWorkspaceBlueprint() val androidSdkRepositoryDeclaration = "android_sdk_repository(name = \"androidsdk\")" assert(blueprint.bazelWorkspaceContent.contains(androidSdkRepositoryDeclaration)) } private fun getBazelWorkspaceBlueprint( projectRoot: String = "foo" ) = BazelWorkspaceBlueprint(projectRoot) }
0
Kotlin
0
0
30358ab7ddaf248fe06d494791224744b0940cf5
859
android-studio-poet
Apache License 2.0
kia-lib/src/test/kotlin/com/faforever/ice/telemetry/TelemetryClientTest.kt
FAForever
683,758,214
false
{"Kotlin": 117426}
package com.faforever.ice.telemetry import com.faforever.ice.IceAdapter import com.faforever.ice.IceOptions import com.faforever.ice.game.GameState import com.faforever.ice.gpgnet.GpgnetProxy import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import io.mockk.every import io.mockk.impl.annotations.MockK import io.mockk.junit5.MockKExtension import io.mockk.mockkConstructor import io.mockk.mockkObject import io.mockk.mockkStatic import io.mockk.unmockkStatic import io.mockk.verify import org.awaitility.Awaitility.await import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import java.net.URI import java.time.Duration import java.util.UUID @ExtendWith(MockKExtension::class) class TelemetryClientTest { private lateinit var sut: TelemetryClient @MockK private lateinit var mockIceOptions: IceOptions private val messageUuid = UUID.fromString("000e8400-e29b-41d4-a716-446655440000") @BeforeEach fun beforeEach() { every { mockIceOptions.telemetryServer } returns "wss://mock-telemetryserver.xyz:" every { mockIceOptions.userName } returns "Player1" every { mockIceOptions.userId } returns 5000 every { mockIceOptions.gameId } returns 12345 mockkStatic(UUID::class) every { UUID.randomUUID() } returns messageUuid mockkObject(IceAdapter) every { IceAdapter.version } returns "9.9.9-SNAPSHOT" mockkConstructor(TelemetryClient.TelemetryWebsocketClient::class) every { anyConstructed<TelemetryClient.TelemetryWebsocketClient>().connectBlocking() } returns true every { anyConstructed<TelemetryClient.TelemetryWebsocketClient>().send(any<String>()) } returns Unit every { anyConstructed<TelemetryClient.TelemetryWebsocketClient>().isOpen } returns true } @AfterEach fun afterEach() { unmockkStatic(UUID::class) } @Test fun `test init connects and registers as peer`() { sut = TelemetryClient(mockIceOptions, jacksonObjectMapper()) await().untilAsserted { verify { anyConstructed<TelemetryClient.TelemetryWebsocketClient>().connectBlocking() val expected = """ { "messageType":"RegisterAsPeer", "adapterVersion":"kotlin-ice-adapter/9.9.9-SNAPSHOT", "userName":"Player1", "messageId":"$messageUuid" } """.trimIndent().replace("\n", "") anyConstructed<TelemetryClient.TelemetryWebsocketClient>().send(expected) } } } @Test fun `test update coturn servers`() { sut = TelemetryClient(mockIceOptions, jacksonObjectMapper()) val coturnServers: List<com.faforever.ice.peering.CoturnServer> = listOf( com.faforever.ice.peering.CoturnServer(URI.create("stun://coturn1.faforever.com:3478")), com.faforever.ice.peering.CoturnServer(URI.create("stun://fr-turn1.xirsys.com:80")), ) sut.updateCoturnList(coturnServers) await().untilAsserted { verify { val expected = """ { "messageType":"UpdateCoturnList", "connectedHost":"coturn1.faforever.com", "knownServers":[ {"region":"n/a","host":"coturn1.faforever.com","port":3478,"averageRTT":0.0}, {"region":"n/a","host":"fr-turn1.xirsys.com","port":80,"averageRTT":0.0}], "messageId":"$messageUuid" } """.trimIndent().replace("\n", "") anyConstructed<TelemetryClient.TelemetryWebsocketClient>().send(expected) } } } @Test fun `test update coturn servers empty`() { sut = TelemetryClient(mockIceOptions, jacksonObjectMapper()) val coturnServers: List<com.faforever.ice.peering.CoturnServer> = listOf() sut.updateCoturnList(coturnServers) await().untilAsserted { verify { val expected = """ { "messageType":"UpdateCoturnList", "connectedHost":"", "knownServers":[], "messageId":"$messageUuid" } """.trimIndent().replace("\n", "") anyConstructed<TelemetryClient.TelemetryWebsocketClient>().send(expected) } } } @Test fun `test reconnect after websocket closes`() { // Mock connections succeeding and websocket open. every { anyConstructed<TelemetryClient.TelemetryWebsocketClient>().connectBlocking() } returns true every { anyConstructed<TelemetryClient.TelemetryWebsocketClient>().reconnectBlocking() } returns true every { anyConstructed<TelemetryClient.TelemetryWebsocketClient>().isOpen } returns true every { anyConstructed<TelemetryClient.TelemetryWebsocketClient>().isClosed } returns false sut = TelemetryClient(mockIceOptions, jacksonObjectMapper()) // Wait for the initial connection and the first message to be sent. await().untilAsserted { verify { anyConstructed<TelemetryClient.TelemetryWebsocketClient>().send(any<String>()) } } // Mock the connection closing and add a message to the send queue. every { anyConstructed<TelemetryClient.TelemetryWebsocketClient>().isOpen } returns false every { anyConstructed<TelemetryClient.TelemetryWebsocketClient>().isClosed } returns true sut.updateCoturnList(listOf()) // There should get a reconnect attempt. await().untilAsserted { verify { anyConstructed<TelemetryClient.TelemetryWebsocketClient>().reconnectBlocking() } } // Mock that the reconnect succeeded. every { anyConstructed<TelemetryClient.TelemetryWebsocketClient>().isOpen } returns true every { anyConstructed<TelemetryClient.TelemetryWebsocketClient>().isClosed } returns false // The message in the queue should then be sent. await().untilAsserted { verify { anyConstructed<TelemetryClient.TelemetryWebsocketClient>().send(any<String>()) } } } @Test fun `test exhausting reconnect attempts`() { // Mock Connections failing and websocket closed. every { anyConstructed<TelemetryClient.TelemetryWebsocketClient>().connectBlocking() } returns false every { anyConstructed<TelemetryClient.TelemetryWebsocketClient>().reconnectBlocking() } returns false every { anyConstructed<TelemetryClient.TelemetryWebsocketClient>().isOpen } returns false every { anyConstructed<TelemetryClient.TelemetryWebsocketClient>().isClosed } returns true sut = TelemetryClient(mockIceOptions, jacksonObjectMapper(), connectionRetries = 2) // Exhaust the connection retries. await().untilAsserted { verify(exactly = 2) { anyConstructed<TelemetryClient.TelemetryWebsocketClient>().reconnectBlocking() } } // Another event happens which would normally add another message to the queue. sut.updateCoturnList(listOf()) // After waiting a bit the send queue shouldn't have done anything. There should only be the // initial two reconnect attempts. await().atLeast(Duration.ofSeconds(1)) verify(exactly = 2) { anyConstructed<TelemetryClient.TelemetryWebsocketClient>().reconnectBlocking() } } @Test fun `test update game state`() { sut = TelemetryClient(mockIceOptions, jacksonObjectMapper()) sut.updateGameState(GameState.IDLE) await().untilAsserted { verify { val expected = """ { "messageType":"UpdateGameState", "newState":"IDLE", "messageId":"$messageUuid" } """.trimIndent().replace("\n", "") anyConstructed<TelemetryClient.TelemetryWebsocketClient>().send(expected) } } } @Test fun `test update gpgnet connection state`() { sut = TelemetryClient(mockIceOptions, jacksonObjectMapper()) sut.updateGpgnetState(GpgnetProxy.ConnectionState.LISTENING) await().untilAsserted { verify { val expected = """ { "messageType":"UpdateGpgnetState", "newState":"WAITING_FOR_GAME", "messageId":"$messageUuid" } """.trimIndent().replace("\n", "") anyConstructed<TelemetryClient.TelemetryWebsocketClient>().send(expected) } } sut.updateGpgnetState(GpgnetProxy.ConnectionState.DISCONNECTED) await().untilAsserted { verify { val expected = """ { "messageType":"UpdateGpgnetState", "newState":"WAITING_FOR_GAME", "messageId":"$messageUuid" } """.trimIndent().replace("\n", "") anyConstructed<TelemetryClient.TelemetryWebsocketClient>().send(expected) } } sut.updateGpgnetState(GpgnetProxy.ConnectionState.CONNECTED) await().untilAsserted { verify { val expected = """ { "messageType":"UpdateGpgnetState", "newState":"GAME_CONNECTED", "messageId":"$messageUuid" } """.trimIndent().replace("\n", "") anyConstructed<TelemetryClient.TelemetryWebsocketClient>().send(expected) } } } }
2
Kotlin
3
2
ecaa19d8fe3207e592d66bd73ead2d3fc2181629
10,330
kotlin-ice-adapter
MIT License
data/api/src/commonMain/kotlin/io/github/droidkaigi/feeder/data/AppErros.kt
DroidKaigi
283,062,475
false
null
package io.github.droidkaigi.feeder.data import io.github.droidkaigi.feeder.AppError import io.ktor.client.features.ResponseException import io.ktor.network.sockets.SocketTimeoutException import io.ktor.util.cio.ChannelReadException import kotlinx.coroutines.TimeoutCancellationException fun Throwable.toAppError(): AppError { return when (this) { is AppError -> this is ResponseException -> return AppError.ApiException.ServerException(this) is ChannelReadException -> return AppError.ApiException.NetworkException(this) is TimeoutCancellationException, is SocketTimeoutException -> { AppError.ApiException .TimeoutException(this) } else -> AppError.UnknownException(this) } }
45
null
3
633
3fb47a7b7b245e5a7c7c66d6c18cb7d2a7b295f2
788
conference-app-2021
Apache License 2.0
src/main/kotlin/org/rust/toml/CargoTomlCompletionContributor.kt
qunlang
115,271,550
true
{"Kotlin": 2170316, "Rust": 76008, "Lex": 18854, "HTML": 9456, "Shell": 760, "Java": 586, "RenderScript": 318}
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.toml import com.intellij.codeInsight.completion.CompletionContributor import com.intellij.codeInsight.completion.CompletionType class CargoTomlCompletionContributor : CompletionContributor() { init { if (tomlPluginIsAbiCompatible()) { extend(CompletionType.BASIC, CargoTomlKeysCompletionProvider.elementPattern, CargoTomlKeysCompletionProvider()) } } }
0
Kotlin
0
0
a219f414368e652f7bb5c2689db03272647f96e8
516
intellij-rust
MIT License
src/main/kotlin/academy/jairo/ktor/exception/ExceptionHandler.kt
jairosoares
723,457,254
false
{"Kotlin": 29031}
package academy.jairo.ktor.exception import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.response.* object ExceptionHandler { suspend fun handle( call: ApplicationCall, cause: Throwable, developmentMode:Boolean ) { when (cause) { is EntityNotFoundException -> { call.respond( HttpStatusCode.NotFound, ExceptionResponse(cause.message ?: cause.toString(), HttpStatusCode.NotFound.value) ) } is ParameterException -> { call.respond( HttpStatusCode.BadRequest, ExceptionResponse(cause.message ?: cause.toString(), HttpStatusCode.BadRequest.value) ) } is BusinessException -> { call.respond( HttpStatusCode.PreconditionFailed, ExceptionResponse(cause.message ?: cause.toString(), cause.messageCode.value) ) } else -> { if (developmentMode) { cause.stackTrace.forEach { println(it) } call.respondText(text = "500: $cause", status = HttpStatusCode.InternalServerError) } else { // Production, only minimal info. call.respondText(text = "Internal Error", status = HttpStatusCode.InternalServerError) } } } } }
0
Kotlin
0
0
1e9480466001bc3ebf5e64b660f577ac7c6dc441
1,529
ktor-lab
MIT License
src/main/kotlin/dev/toastmc/toastclient/impl/module/render/TestModule.kt
RemainingToast
330,479,309
false
null
package dev.toastmc.toastclient.impl.module.render import dev.toastmc.toastclient.api.events.WorldRenderEvent import dev.toastmc.toastclient.api.managers.module.Module import dev.toastmc.toastclient.api.util.ToastColor import dev.toastmc.toastclient.api.util.WorldUtil import dev.toastmc.toastclient.api.util.render.RenderUtil import org.quantumclient.energy.Subscribe object TestModule : Module("TestModule", Category.RENDER) { @Subscribe fun on(event: WorldRenderEvent) { val tileEntities = WorldUtil.getTileEntitiesInChunk(mc.player!!.world, mc.player!!.chunkPos.x, mc.player!!.chunkPos.z) tileEntities.forEach { (pos, tile) -> if (pos.y <= 69) { RenderUtil.drawOutline( pos, ToastColor.rainbow(1), 2.5f ) } else { RenderUtil.drawBox( pos, ToastColor.rainbow(1) ) } RenderUtil.draw3DText( tile.name, pos.x + 0.5, pos.y + 0.5, pos.z + 0.5, 0.50, background = false, shadow = true ) } } }
0
Kotlin
15
26
5f7b86676fcea6bbee57e6a2caa8a7c87fe01e70
1,266
ToastClient
MIT License
app/src/main/java/org/treeo/treeo/adapters/TMSummaryAdapter.kt
fairventures-worldwide
498,242,730
false
{"Kotlin": 586304, "C++": 87995, "Java": 3688, "CMake": 2149}
package org.treeo.treeo.adapters import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import org.treeo.treeo.R import org.treeo.treeo.models.TMSummaryListItem class TMSummaryAdapter( private val listItems: List<TMSummaryListItem> ) : RecyclerView.Adapter<TMSummaryAdapter.ViewHolder>() { class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var itemTitle: TextView = itemView.findViewById(R.id.item_title) var itemValue: TextView = itemView.findViewById(R.id.item_value) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val itemView: View = LayoutInflater .from(parent.context) .inflate( R.layout.single_tree_info_row_item, parent, false ) return ViewHolder(itemView) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val summaryListItem: TMSummaryListItem = listItems[position] holder.itemTitle.text = summaryListItem.key holder.itemValue.text = summaryListItem.value } override fun getItemCount(): Int { return listItems.size } }
0
Kotlin
0
0
2e3e780e325cb97c72a79d9d22fc7ac053fee350
1,308
treeo2-mobile-app-open
Apache License 2.0
okio-wasifilesystem/src/wasmWasiMain/kotlin/okio/internal/ErrnoException.kt
square
17,812,502
false
null
/* * Copyright (C) 2023 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okio.internal import okio.IOException import okio.internal.preview1.Errno import okio.internal.preview1.errno class ErrnoException( val errno: Errno, ) : IOException(errno.name) { constructor(errno: errno) : this(Errno.entries[errno.toInt()]) }
89
null
1178
8,795
0f6c9cf31101483e6ee9602e80a10f7697c8f75a
860
okio
Apache License 2.0
app/src/main/java/com/example/cheesefinderapp/ui/cheeselist/CheeseListFragment.kt
fredouric
721,687,046
false
{"Kotlin": 30376}
package com.example.cheesefinderapp.ui.cheeselist import android.content.Intent 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 androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.example.cheesefinderapp.R import com.example.cheesefinderapp.model.Cheese import com.example.cheesefinderapp.model.pojo.UpdateCheeseRequest import com.example.cheesefinderapp.ui.InfoCheeseActivity import com.example.cheesefinderapp.ui.MainActivity import com.google.android.material.transition.MaterialFadeThrough import retrofit2.Call import retrofit2.Callback import retrofit2.Response private const val ARG_CHEESE_COLLECTION = "param_cheese_collection" /** * A simple [Fragment] subclass. * Use the [CheeseListFragment.newInstance] factory method to * create an instance of this fragment. */ class CheeseListFragment : Fragment() { private var cheeseCollection: ArrayList<Cheese>? = null private var filteredCheeseCollection: ArrayList<Cheese>? = null private lateinit var rootView: View private lateinit var recyclerView: RecyclerView private lateinit var adapter: CheeseListAdapter private lateinit var layoutManager: RecyclerView.LayoutManager override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { arguments?.let { cheeseCollection = arguments?.getSerializable(ARG_CHEESE_COLLECTION) as ArrayList<Cheese> } // Inflate the layout for this fragment rootView = inflater.inflate(R.layout.fragment_cheese_list, container, false) recyclerView = rootView.findViewById<RecyclerView>(R.id.fgt_cheese_list_view) adapter = CheeseListAdapter(cheeseCollection!!, { cheese -> val intent = Intent(requireContext(), InfoCheeseActivity::class.java) intent.putExtra("cheeseID", cheese.id) startActivity(intent) }, { cheeseID -> makeToggleFavoriteRequest(cheeseID) }) layoutManager = LinearLayoutManager(this.context) recyclerView.layoutManager = layoutManager recyclerView.adapter = adapter // val refreshLayout = rootView.findViewById<SwipeRefreshLayout>(R.id.fgt_cheese_list_swipe_refresh) refreshLayout.setOnRefreshListener { makeGetAllCheesesRequest() } exitTransition = MaterialFadeThrough() return rootView } fun filterDataLocally(query: String) { if (query.isEmpty()) { adapter.restoreData() } else { filteredCheeseCollection = cheeseCollection?.filter { it.fromage.contains(query, ignoreCase = true) || it.departement.contains(query, ignoreCase = true) } as ArrayList<Cheese> adapter.updateData(filteredCheeseCollection!!) } } fun filterDataWithAPIResponse(query: List<Cheese>) { adapter.updateData(query) } companion object { @JvmStatic fun newInstance(cheeseCollection: ArrayList<Cheese>) = CheeseListFragment().apply { arguments = Bundle().apply { putSerializable(ARG_CHEESE_COLLECTION, cheeseCollection) } } } private fun makeToggleFavoriteRequest(cheeseId: String) { val cheeseService = (requireActivity() as MainActivity).cheeseService cheeseService.toggleFavorite(updateCheeseRequest = UpdateCheeseRequest(cheeseId)) .enqueue(object : Callback<Cheese> { override fun onResponse( call: Call<Cheese>, response: Response<Cheese> ) { response.body()?.let { updatedCheese -> val updatedList = ArrayList(cheeseCollection) val position = updatedList.indexOfFirst { it.id == updatedCheese.id } if (position != -1) { updatedList[position] = updatedCheese adapter.updateData(updatedList) } } } override fun onFailure(call: Call<Cheese>, t: Throwable) { t.printStackTrace() } }) } private fun makeGetAllCheesesRequest() { val cheeseService = (requireActivity() as MainActivity).cheeseService val swipeRefreshLayout = rootView.findViewById<SwipeRefreshLayout>(R.id.fgt_cheese_list_swipe_refresh) cheeseService.getAllCheese() .enqueue(object : Callback<List<Cheese>> { override fun onResponse( call: Call<List<Cheese>>, response: Response<List<Cheese>> ) { cheeseCollection?.clear() response.body()?.forEach { val cheese = Cheese( it.id, it.departement, it.fromage, it.lait, it.geo_shape, it.geo_point_2d, it.favorite ) cheeseCollection?.add(cheese) } requireActivity().runOnUiThread { adapter.updateData(ArrayList(cheeseCollection)) swipeRefreshLayout.isRefreshing = false } } override fun onFailure(call: Call<List<Cheese>>, t: Throwable) { t.printStackTrace() } }) } }
0
Kotlin
0
0
bad9d080940266aee0dadf261b9f9021fd8e84aa
6,093
cheese-finder-app
MIT License
platform-tests/src/test/kotlin/org/nd4j/samediff/frameworkimport/reflect/ClassGraphHolderTest.kt
aetheriaxai
510,410,216
true
{"Shell": 32, "Batchfile": 1, "Markdown": 68, "Kotlin": 260, "Java": 4677, "Java Properties": 24, "Python": 26, "C++": 1826, "C": 14, "JavaScript": 33, "Ruby": 5, "Dockerfile": 1, "Scala": 1, "TypeScript": 27, "CSS": 3, "HTML": 3, "CMake": 23}
package org.nd4j.samediff.frameworkimport.reflect import org.apache.commons.io.FileUtils import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Test import java.io.File import java.nio.charset.Charset import kotlin.test.assertTrue class ClassGraphHolderTest { @Test fun testClassGraphHolder() { val jsonFile = File("scanned-classes.json") ClassGraphHolder.saveScannedClasses(jsonFile) val original = ClassGraphHolder.scannedClasses val loadedJson = FileUtils.readFileToString(jsonFile, Charset.defaultCharset()) assertTrue(loadedJson.length > 1,"Json was not written and is empty") val loaded = ClassGraphHolder.loadFromJson(loadedJson) assertEquals(original.toJSON(),loaded.toJSON()) assertNotNull(ClassGraphHolder.scannedClasses) } }
0
null
0
1
b45b4f6304ecc6e8150cb5fb1054ac9fafa06e83
897
deeplearning4j
Apache License 2.0
app/src/main/java/com/da_chelimo/whisper/auth/ui/screens/enter_code/EnterCodeViewModel.kt
DaChelimo
809,502,044
false
{"Kotlin": 61907}
package com.da_chelimo.whisper.auth.ui.screens.enter_code import android.app.Activity import androidx.lifecycle.ViewModel import com.google.firebase.FirebaseException import com.google.firebase.auth.PhoneAuthCredential import com.google.firebase.auth.PhoneAuthOptions import com.google.firebase.auth.PhoneAuthProvider import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import timber.log.Timber import java.util.concurrent.TimeUnit class EnterCodeViewModel: ViewModel() { private val _code = MutableStateFlow("") val code: StateFlow<String> = _code private var storedVerificationId: String? = null private var resendToken: PhoneAuthProvider.ForceResendingToken? = null private val _shouldNavigate = MutableStateFlow(false) val shouldNavigate: StateFlow<Boolean> = _shouldNavigate private val _isLoading = MutableStateFlow(false) val isLoading: StateFlow<Boolean> = _isLoading companion object { const val CODE_LENGTH = 6 } fun updateCode(newCode: String) { _code.value = newCode } private val callbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() { override fun onVerificationCompleted(authCredential: PhoneAuthCredential) { Firebase.auth.signInWithCredential(authCredential).addOnCompleteListener { task -> Timber.d("task.isSuccessful is ${task.isSuccessful}") if (task.isSuccessful) _shouldNavigate.value = true } _shouldNavigate.value = true } override fun onVerificationFailed(firebaseException: FirebaseException) { Timber.e(firebaseException) } override fun onCodeSent(verificationId: String, forceResendingToken: PhoneAuthProvider.ForceResendingToken) { super.onCodeSent(verificationId, forceResendingToken) storedVerificationId = verificationId resendToken = forceResendingToken } } fun authenticateWithNumber(phoneNumber: String, activity: Activity?) { val phoneAuthOptions = PhoneAuthOptions.newBuilder() .setPhoneNumber(phoneNumber) .setTimeout(30L, TimeUnit.SECONDS) .setActivity(activity!!) .setCallbacks(callbacks) .build() PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions) } fun submitCode() { _isLoading.value = true storedVerificationId?.let { val authCredential = PhoneAuthProvider.getCredential(it, code.value) Firebase.auth.signInWithCredential(authCredential).addOnCompleteListener { task -> Timber.d("task.isSuccessful is ${task.isSuccessful}") _isLoading.value = false if (task.isSuccessful) _shouldNavigate.value = true } } _isLoading.value = false } fun resetShouldNavigate() { _shouldNavigate.value = false } }
0
Kotlin
0
0
ed7c8c9f4f6bff1da7002809d3eb1d70e493d2e8
3,105
Whisper
MIT License
features/champions/src/main/java/com/leaguechampions/features/champions/presentation/champions/ChampionsAdapter.kt
matthieucoisne
94,946,625
false
null
package com.leaguechampions.features.champions.presentation.champions import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.leaguechampions.features.champions.databinding.ActivityChampionsItemBinding import com.leaguechampions.libraries.core.utils.loadChampionImage class ChampionsAdapter( private val listener: (ChampionUiModel) -> Unit ) : RecyclerView.Adapter<ChampionsAdapter.ViewHolder>() { private var data = ChampionsUiModel(emptyList()) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = ActivityChampionsItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) return ViewHolder(binding) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val champion = data.champions[position] holder.binding.tvChampionName.text = champion.name loadChampionImage(holder.binding.ivChampion, champion.id, champion.version) holder.binding.root.setOnClickListener { listener(champion) } } override fun getItemCount() = data.champions.size fun setData(data: ChampionsUiModel) { this.data = data notifyDataSetChanged() } class ViewHolder( val binding: ActivityChampionsItemBinding ) : RecyclerView.ViewHolder(binding.root) }
4
Kotlin
1
4
5512e1b21e86f27d51ab8ad76d6e5ad11faa81d2
1,404
LeagueChampions
Apache License 2.0
samples/kotlin-android-app/src/main/java/com/segment/analytics/next/plugins/AndroidRecordScreenPlugin.kt
segmentio
335,438,046
false
{"Kotlin": 516260}
package com.segment.analytics.next.plugins import android.app.Activity import android.content.pm.PackageManager import com.segment.analytics.kotlin.core.Analytics import com.segment.analytics.kotlin.core.platform.Plugin import com.segment.analytics.kotlin.android.plugins.AndroidLifecycle import com.segment.analytics.kotlin.core.platform.plugins.logger.* import com.segment.analytics.kotlin.core.reportInternalError class AndroidRecordScreenPlugin : Plugin, AndroidLifecycle { override val type: Plugin.Type = Plugin.Type.Utility override lateinit var analytics: Analytics override fun onActivityStarted(activity: Activity?) { val packageManager = activity?.packageManager try { val info = packageManager?.getActivityInfo( activity.componentName, PackageManager.GET_META_DATA ) val activityLabel = info?.loadLabel(packageManager) analytics.screen(activityLabel.toString()) } catch (e: PackageManager.NameNotFoundException) { val error = AssertionError("Activity Not Found: $e") analytics.reportInternalError(error) throw error } catch (e: Exception) { analytics.reportInternalError(e) Analytics.segmentLog( "Unable to track screen view for ${activity.toString()}", kind = LogKind.ERROR ) } } }
5
Kotlin
24
45
1ef79eaf035549d08f91bac4e0a1de8ca6793e7b
1,439
analytics-kotlin
MIT License
general-gossip/src/main/java/com/song/general/gossip/message/GossipDigestAck2Message.kt
aCoder2013
102,945,038
false
null
package com.song.general.gossip.message import com.song.general.gossip.EndpointState import java.io.Serializable import java.net.SocketAddress /** * Created by song on 2017/9/9. */ class GossipDigestAck2Message(val endpointStateMap: Map<SocketAddress, EndpointState>) : Serializable
0
Kotlin
0
1
a00ba170324038384f0147121197cfc93ff3ad8e
286
general
Apache License 2.0
compiler/testData/codegen/functions/referencesStaticInnerClassMethod.kt
chirino
3,596,099
true
null
fun box() = if (R.id.main == 17) "OK" else "fail"
0
Java
28
71
ac434d48525a0e5b57c66b9f61b388ccf3d898b5
54
kotlin
Apache License 2.0
libraries/tools/kotlin-gradle-plugin/src/common/kotlin/org/jetbrains/kotlin/gradle/targets/js/dsl/KotlinJsTargetDsl.kt
HardFatal
387,140,840
false
{"Markdown": 142, "Gradle": 445, "Gradle Kotlin DSL": 919, "Java Properties": 24, "Kotlin": 48716, "Shell": 42, "Ignore List": 21, "Batchfile": 20, "Git Attributes": 9, "XML": 786, "JSON": 189, "INI": 180, "Java": 3261, "Text": 17342, "JavaScript": 306, "JAR Manifest": 2, "Roff": 248, "Roff Manpage": 46, "Protocol Buffer": 16, "Proguard": 15, "AsciiDoc": 1, "YAML": 9, "EditorConfig": 1, "OpenStep Property List": 12, "C": 194, "Objective-C": 128, "C++": 350, "LLVM": 1, "Swift": 94, "Pascal": 1, "Python": 4, "CMake": 2, "Objective-C++": 18, "HTML": 15, "Groovy": 20, "Dockerfile": 4, "Diff": 4, "EJS": 1, "CSS": 6, "JSON with Comments": 50, "CODEOWNERS": 1, "JFlex": 2, "Graphviz (DOT)": 91, "Ant Build System": 32, "Dotenv": 5, "Maven POM": 82, "FreeMarker": 1, "Fluent": 2, "Ruby": 16, "Scala": 1}
/* * 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 org.jetbrains.kotlin.gradle.targets.js.dsl import org.gradle.api.Action import org.gradle.api.GradleException import org.gradle.api.NamedDomainObjectContainer import org.jetbrains.kotlin.gradle.dsl.KotlinJsDce import org.jetbrains.kotlin.gradle.plugin.KotlinTarget import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinJsCompilation import org.jetbrains.kotlin.gradle.targets.js.KotlinJsPlatformTestRun import org.jetbrains.kotlin.gradle.targets.js.KotlinJsReportAggregatingTestRun import org.jetbrains.kotlin.gradle.targets.js.ir.KotlinJsBinaryContainer import org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsExec import org.jetbrains.kotlin.gradle.targets.js.testing.KotlinJsTest import org.jetbrains.kotlin.gradle.targets.js.webpack.KotlinWebpack import org.jetbrains.kotlin.gradle.targets.js.webpack.KotlinWebpackConfig interface KotlinJsSubTargetContainerDsl : KotlinTarget { val nodejs: KotlinJsNodeDsl val browser: KotlinJsBrowserDsl val isNodejsConfigured: Boolean val isBrowserConfigured: Boolean fun whenNodejsConfigured(body: KotlinJsNodeDsl.() -> Unit) fun whenBrowserConfigured(body: KotlinJsBrowserDsl.() -> Unit) } interface KotlinJsTargetDsl : KotlinTarget { var moduleName: String? fun browser() = browser { } fun browser(body: KotlinJsBrowserDsl.() -> Unit) fun browser(fn: Action<KotlinJsBrowserDsl>) { browser { fn.execute(this) } } fun nodejs() = nodejs { } fun nodejs(body: KotlinJsNodeDsl.() -> Unit) fun nodejs(fn: Action<KotlinJsNodeDsl>) { nodejs { fn.execute(this) } } fun useCommonJs() fun useEsModules() fun generateTypeScriptDefinitions() val binaries: KotlinJsBinaryContainer @Deprecated( message = "produceExecutable() was changed on binaries.executable()", replaceWith = ReplaceWith("binaries.executable()"), level = DeprecationLevel.ERROR ) fun produceExecutable() { throw GradleException("Please change produceExecutable() on binaries.executable()") } val testRuns: NamedDomainObjectContainer<KotlinJsReportAggregatingTestRun> // Need to compatibility when users use KotlinJsCompilation specific in build script override val compilations: NamedDomainObjectContainer<out KotlinJsCompilation> } interface KotlinJsSubTargetDsl { @Deprecated("Please use distribution(Action)") @ExperimentalDistributionDsl fun distribution(body: Distribution.() -> Unit) { distribution(Action { it.body() }) } @ExperimentalDistributionDsl fun distribution(body: Action<Distribution>) @Deprecated("Please use testTask(Action)") fun testTask(body: KotlinJsTest.() -> Unit) { testTask(Action { it.body() }) } fun testTask(body: Action<KotlinJsTest>) val testRuns: NamedDomainObjectContainer<KotlinJsPlatformTestRun> } interface KotlinJsBrowserDsl : KotlinJsSubTargetDsl { @Deprecated("Please use commonWebpackConfig(Action)") fun commonWebpackConfig(body: KotlinWebpackConfig.() -> Unit) { commonWebpackConfig(Action { it.body() }) } fun commonWebpackConfig(body: Action<KotlinWebpackConfig>) @Deprecated("Please use runTask(Action)") fun runTask(body: KotlinWebpack.() -> Unit) { runTask(Action { it.body() }) } fun runTask(body: Action<KotlinWebpack>) @Deprecated("Please use webpackTask(Action)") fun webpackTask(body: KotlinWebpack.() -> Unit) { webpackTask(Action { it.body() }) } fun webpackTask(body: Action<KotlinWebpack>) @Deprecated("Please use dceTask(Action)") @ExperimentalDceDsl fun dceTask(body: KotlinJsDce.() -> Unit) { dceTask(Action { it.body() }) } @ExperimentalDceDsl fun dceTask(body: Action<KotlinJsDce>) } interface KotlinJsNodeDsl : KotlinJsSubTargetDsl { @Deprecated("Please use runTask(Action)") fun runTask(body: NodeJsExec.() -> Unit) { runTask(Action { it.body() }) } fun runTask(body: Action<NodeJsExec>) }
1
null
1
1
5424c54fae7b4836506ec711edc0135392b445d6
4,419
kotlin
Apache License 2.0
spring-boot-project/spring-boot-docs/src/main/kotlin/org/springframework/boot/docs/features/testing/springbootapplications/withrunningserver/MyRandomPortTestRestTemplateTests.kt
snicoll
16,165,420
false
null
/* * Copyright 2012-2022 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.docs.features.testing.springbootapplications.withrunningserver import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.context.SpringBootTest.WebEnvironment import org.springframework.boot.test.web.client.TestRestTemplate @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) class MyRandomPortTestRestTemplateTests { @Test fun exampleTest(@Autowired restTemplate: TestRestTemplate) { val body = restTemplate.getForObject("/", String::class.java) assertThat(body).isEqualTo("Hello World") } }
576
null
6
8
0934b68c6c234f32fc32c3b5f13f05d55a13a69b
1,354
spring-boot
Apache License 2.0
user-profile/src/main/kotlin/systemkern/profile/AuthenticationService.kt
systemkern-org
127,404,422
false
{"Kotlin": 84769, "Java": 14976, "Shell": 946, "Dockerfile": 135, "Batchfile": 26}
package systemkern.profile import org.springframework.security.core.Authentication import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder import org.springframework.stereotype.Service import java.time.LocalDateTime.now import java.util.UUID import javax.servlet.http.HttpServletRequest import kotlin.collections.HashMap import java.time.Duration import java.time.LocalDateTime @Service internal class AuthenticationService( val userProfileRepository: UserProfileRepository, val emailVerificationRepository: EmailVerificationRepository, val emailChangeRepository: EmailChangeRepository, val passwordEncoder: BCryptPasswordEncoder, val sessionTimeOut: Duration, val auxNumToConvertSecstoMillis: Int = 1000 ) { val tokens : HashMap<UUID, AuthenticationResponse> = HashMap() internal fun findByUsername(username : String) = userProfileRepository.findByUsername(username) internal fun isValidToken(token : UUID, request : HttpServletRequest) : Boolean { val inactiveInterval = System.currentTimeMillis() - request.session.lastAccessedTime val maxInactiveIntervalMilis = request.session.maxInactiveInterval * auxNumToConvertSecstoMillis if (tokens.containsKey(token)) { return inactiveInterval <= maxInactiveIntervalMilis } return false } internal fun saveToken(token : UUID, auth : AuthenticationResponse) { tokens[token] = auth } internal fun deleteToken(token : UUID) { tokens.remove(token) } @Throws(UserNotFoundException::class) internal fun authenticationProcess( auth : Authentication, password : String ) : AuthenticationResponse { val user = findByUsername(auth.principal.toString()) val emailVerification = user.emailVerificationList.last() if (!passwordEncoder.matches(password, user.password) && emailVerification.completionDate <= emailVerification.creationDate) throw UserNotFoundException("UserNotFoundException") return buildResponseAndSave( authenticationToken = UUID.fromString(auth.credentials.toString()), username = user.username, userId = user.id, validUntil = now().plusMinutes(sessionTimeOut.toMinutes())) } internal fun authProcessEmailVerification(verifyEmailToken : UUID) : AuthenticationResponse { val emailVerification = emailVerificationRepository.findById(verifyEmailToken).get() val userProfile = emailVerification.userProfile return buildResponseAndSave( authenticationToken = UUID.randomUUID(), username = userProfile.username, userId = userProfile.id, validUntil = now().plusMinutes(sessionTimeOut.toMinutes())) } internal fun authProcessEmailChange(emailChangeToken: UUID) : AuthenticationResponse { val emailChangeEntity = emailChangeRepository.findById(emailChangeToken).get() val userProfile = emailChangeEntity.userProfile return buildResponseAndSave( authenticationToken = UUID.randomUUID(), username = userProfile.username, userId = userProfile.id, validUntil = now().plusMinutes(sessionTimeOut.toMinutes())) } internal fun authProcessPasswordReset( passwordResetEntity : PasswordResetEntity, completionDate : LocalDateTime ) : AuthenticationResponse { val userProfile = passwordResetEntity.userProfile return buildResponseAndSave( authenticationToken = UUID.randomUUID(), username = userProfile.username, userId = userProfile.id, validUntil = now().plusMinutes(sessionTimeOut.toMinutes())) } private fun buildResponseAndSave( authenticationToken : UUID, validUntil : LocalDateTime, username : String, userId : UUID ) : AuthenticationResponse { val authResp = AuthenticationResponse( token = authenticationToken, username = username, userId = userId, validUntil = validUntil ) saveToken(authenticationToken, authResp) return authResp } }
11
Kotlin
3
2
4d69820a83a297c85c602d811655b048362d9575
4,276
launcher
The Unlicense
concert-demos-rest-service-mvc/src/test/kotest/org/jesperancinha/concerts/mvc/controllers/ConcertControllerImplITKoTest.kt
jesperancinha
232,411,155
false
null
package org.jesperancinha.concerts.mvc.controllers import io.kotest.core.spec.style.WordSpec import io.kotest.core.test.TestCase import io.kotest.extensions.spring.SpringExtension import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.nulls.shouldNotBeNull import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.assertj.core.api.Assertions.assertThat import org.jesperancinha.concerts.data.ArtistDto import org.jesperancinha.concerts.data.ConcertDto import org.jesperancinha.concerts.data.ListingDto import org.jesperancinha.concerts.data.MusicDto import org.jesperancinha.concerts.mvc.controllers.TestKUtils.Companion.HEY_MAMA import org.jesperancinha.concerts.mvc.daos.ArtistRepository import org.jesperancinha.concerts.mvc.daos.ConcertRepository import org.jesperancinha.concerts.mvc.daos.ListingRepository import org.jesperancinha.concerts.mvc.daos.MusicRepository import org.jesperancinha.concerts.types.Gender.FEMALE import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT import org.springframework.core.ParameterizedTypeReference import org.springframework.core.env.Environment import org.springframework.http.HttpMethod import org.springframework.http.RequestEntity import org.springframework.test.context.ActiveProfiles import org.springframework.web.client.RestTemplate import org.springframework.web.client.getForObject import org.springframework.web.client.postForEntity import java.net.URI import java.time.LocalDateTime import kotlin.properties.Delegates @SpringBootTest(webEnvironment = RANDOM_PORT) @ActiveProfiles("test") class ConcertControllerImplITKoTest : WordSpec() { @Autowired lateinit var environment: Environment @Autowired lateinit var listingRepository: ListingRepository @Autowired lateinit var artistRepository: ArtistRepository @Autowired lateinit var musicRepository: MusicRepository @Autowired lateinit var concertRepository: ConcertRepository final var port by Delegates.notNull<Int>() override fun extensions() = listOf(SpringExtension) init { "concert controller" should { "retrieve all concerts" { val uri = "http://localhost:${port}/concerts/data/listings" val restTemplate = RestTemplate() val result: List<ConcertDto> = restTemplate.getForObject(uri, List::class) result.shouldBeEmpty() } "create concerts" { val artistsUri = "http://localhost:${port}/concerts/data/artists" val musicsUri = "http://localhost:${port}/concerts/data/musics" val listingsUri = "http://localhost:${port}/concerts/data/listings" val concertsUri = "http://localhost:${port}/concerts/data/concerts" val musicDto = MusicDto( name = "<NAME>", lyrics = HEY_MAMA ) val artistDto = ArtistDto( name = "<NAME>", gender = FEMALE, careerStart = 1000L, birthDate = LocalDateTime.now().toString(), birthCity = "Port of Spain", country = "Trinidad en Tobago", keywords = "Rap" ) val restTemplate = RestTemplate() val savedArtistDto = restTemplate.postForEntity<ArtistDto>(artistsUri, artistDto, ArtistDto::class).body val savedMusicDto = restTemplate.postForEntity<MusicDto>(musicsUri, musicDto, MusicDto::class).body savedArtistDto.shouldNotBeNull() savedMusicDto.shouldNotBeNull() val listingDto = ListingDto( 0, savedArtistDto, savedMusicDto, mutableListOf(savedMusicDto) ) val savedListingDto = restTemplate.postForEntity<ListingDto>(listingsUri, listingDto, ListingDto::class).body val concertDto = ConcertDto( name = "<NAME>", location = "Amsterdam", date = LocalDateTime.of(2019, 3, 25, 0, 0, 0).toString(), listingDtos = mutableListOf(savedListingDto) ) val savedConcertDto = restTemplate.postForEntity<ConcertDto>(concertsUri, concertDto, ConcertDto::class).body val request = RequestEntity<Any>(HttpMethod.GET, URI.create(concertsUri)) val respType = object : ParameterizedTypeReference<List<ConcertDto>>() {} val response = restTemplate.exchange(request, respType) val result: List<ConcertDto> = response.body ?: listOf() assertThat(result).isNotEmpty assertThat(result).hasSize(1) val concertDtoResult = result.getOrNull(0) assertThat(concertDtoResult?.id).isNotEqualTo(0) assertThat(concertDtoResult?.id).isEqualTo(savedConcertDto?.id) assertThat(concertDtoResult?.name).isEqualTo("<NAME>") assertThat(concertDtoResult?.location).isEqualTo("Amsterdam") assertThat(concertDtoResult?.listingDtos).hasSize(1) val listingDtoResult = concertDtoResult?.listingDtos?.getOrNull(0) assertThat(listingDtoResult).isNotNull assertThat(listingDtoResult?.artistDto).isEqualTo(savedArtistDto) assertThat(listingDtoResult?.referenceMusicDto).isEqualTo(savedMusicDto) assertThat(listingDtoResult?.musicDtos).hasSize(1) assertThat(listingDtoResult?.musicDtos?.getOrNull(0)).isEqualTo(savedMusicDto) } } } override suspend fun beforeEach(testCase: TestCase) { withContext(Dispatchers.IO) { concertRepository.deleteAll() listingRepository.deleteAll() artistRepository.deleteAll() musicRepository.deleteAll() } port = environment.getProperty("local.server.port")?.toInt() ?: -1 super.beforeEach(testCase) } }
1
null
2
8
ad824677a7487a3b973bfe5eb6bcff42b7fbb521
6,378
concert-demos-root
Apache License 2.0
data/src/main/java/com/paydaybank/data/model/CustomerEntity.kt
kemalatli
285,489,756
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 60, "XML": 31, "Java": 3, "Gradle Kotlin DSL": 1, "INI": 1}
package com.paydaybank.data.model import androidx.room.Entity import androidx.room.Ignore import androidx.room.PrimaryKey import com.google.gson.annotations.SerializedName import java.util.* @Entity(tableName = "customer") data class CustomerEntity( @SerializedName("id") @PrimaryKey val id:Int = 0, @SerializedName("First Name") val firstName:String = "", @SerializedName("Last Name") val lastName:String = "", val gender:String = "", val email:String = "", val dob: Date = Date(), val phone:String = "" ){ @Ignore var password:String? = null }
1
null
1
1
3c28cf9f37e86c281348cdc271baf5467b6ee323
602
PayDayBank
Apache License 2.0
domain/src/test/kotlin/com/arturogutierrez/openticator/domain/otp/time/TimeCalculatorTest.kt
dandycheung
239,232,057
false
{"Gradle": 6, "Markdown": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "YAML": 1, "Kotlin": 166, "Java": 1, "Proguard": 2, "XML": 40}
package com.arturogutierrez.openticator.domain.otp.time import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import org.junit.Test class TimeCalculatorTest { @Test fun testFirstStep() { val timeCalculator = TimeCalculator(30, 0) val step = timeCalculator.getCurrentTimeStep(28L) assertThat(step, equalTo(0L)) } @Test fun testSecondStep() { val timeCalculator = TimeCalculator(30, 0) val step = timeCalculator.getCurrentTimeStep(50L) assertThat(step, equalTo(1L)) } @Test fun testTimeStepUsingCorrection() { val timeCalculator = TimeCalculator(30, -15) val step = timeCalculator.getCurrentTimeStep(65L) assertThat(step, equalTo(1L)) } @Test fun testValidTimeStep() { val timeCalculator = TimeCalculator(30, 0) val step = timeCalculator.getCurrentTimeStep(65L) val validUntilInSeconds = timeCalculator.getValidUntilInSeconds(step) assertThat(step, equalTo(2L)) assertThat(validUntilInSeconds, equalTo(90L)) } }
1
null
1
1
ccbbd93291eee705948752089c03b386d1fb81cf
1,038
Openticator
Apache License 2.0
idea/testData/codeInsight/generate/testFrameworkSupport/junit3/tearDownExists.kt
JakeWharton
99,388,807
true
null
// ACTION_CLASS: org.jetbrains.kotlin.idea.actions.generate.KotlinGenerateTestSupportActionBase$TearDown // NOT_APPLICABLE // CONFIGURE_LIBRARY: JUnit@lib/junit-4.12.jar import junit.framework.TestCase class A : TestCase() {<caret> override fun tearDown() { super.tearDown() } }
0
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
295
kotlin
Apache License 2.0
inforeader/src/main/java/uk/co/alt236/floatinginfo/inforeader/network/NetworkInfoReader.kt
alt236
21,360,038
false
null
/* * Copyright 2016 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.alt236.floatinginfo.inforeader.network import android.app.Application import android.content.Context import android.net.ConnectivityManager import android.net.NetworkInfo import android.net.wifi.WifiInfo import android.net.wifi.WifiManager /*package*/ internal class NetworkInfoReader(context: Context) { private val mConnectivityManager: ConnectivityManager? private val mWifiManager: WifiManager? init { val application = context.applicationContext as Application mConnectivityManager = application.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager? mWifiManager = application.getSystemService(Context.WIFI_SERVICE) as WifiManager? } val currentWifiInfo: WifiInfo? get() = mWifiManager?.connectionInfo val activeNetInfo: NetworkInfo? get() = mConnectivityManager?.activeNetworkInfo }
1
null
10
37
81239735ea9e1e477dbf1ba57f4acea5621fa2ac
1,476
Floating-Info---Android
Apache License 2.0
okio/src/test/java/okio/ByteStringKotlinTest.kt
liushaofang
131,119,325
false
null
/* * Copyright (C) 2018 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okio import okio.ByteString.Companion.decodeBase64 import okio.ByteString.Companion.decodeHex import org.assertj.core.api.Assertions.assertThat import org.junit.Test class ByteStringKotlinTest { @Test fun decodeBase64() { val actual = "YfCfjalj".decodeBase64() val expected = ByteString.encodeUtf8("a\uD83C\uDF69c") assertThat(actual).isEqualTo(expected) } @Test fun decodeBase64Invalid() { val actual = ";-)".decodeBase64() assertThat(actual).isNull() } @Test fun decodeHex() { val actual = "CAFEBABE".decodeHex() val expected = ByteString.of(-54, -2, -70, -66) assertThat(actual).isEqualTo(expected) } }
1
null
1
1
5ccb9daadcef9ad7db1caceea9dbf0194cdd6f1f
1,262
okio
Apache License 2.0
UniDArchitecture/app/src/main/java/cz/vojta/unidarchitecture/UniDViewModel.kt
planarvoid
93,836,402
false
null
package cz.vojta.unidarchitecture import android.arch.lifecycle.ViewModel import android.util.Log import cz.vojta.unidarchitecture.tracks.Model import io.reactivex.Observable import io.reactivex.Scheduler import io.reactivex.disposables.CompositeDisposable import io.reactivex.functions.Consumer import io.reactivex.observables.ConnectableObservable import io.reactivex.subjects.PublishSubject import javax.inject.Inject import javax.inject.Named abstract class UniDViewModel<T> : ViewModel() { @Inject @field:Named(NEW_THREAD) lateinit var scheduler: Scheduler @Inject @field:Named(UI_THREAD) lateinit var uiScheduler: Scheduler protected val disposable = CompositeDisposable() private val viewModelDisposable = CompositeDisposable() private val sourceDisposable = CompositeDisposable() private val viewAction: PublishSubject<ViewAction> = PublishSubject.create() private val loader = viewAction.map { when (it) { is Params -> { val load = load(it).map<LoadResult<T>> { Data(it) } .startWith(Loading()) .onErrorReturn { Error(it) } .replay() sourceDisposable.clear() sourceDisposable.add(load.connect()) it to load } is Refresh -> { val refresh = refresh(it).map<LoadResult<T>> { Data(it) } .startWith(Refreshing()) .onErrorReturn { Error(it) } .replay() sourceDisposable.clear() sourceDisposable.add(refresh.connect()) it to refresh } is LoadNext -> { val nextPage = nextPage(it).map<LoadResult<T>> { Data(it) } .startWith(LoadingNextPage()) .onErrorReturn { Error(it) } .replay() sourceDisposable.add(nextPage.connect()) it to nextPage } } } .scan(listOf<ConnectableObservable<LoadResult<T>>>()) { observables, (action, observable) -> when (action) { is Params -> listOf(observable) is Refresh -> listOf(observable) is LoadNext -> observables + observable } } .flatMap { Observable.combineLatest(it) { t -> t.map { it as LoadResult<T> } } } .scan(Model<T>(), { accumulatedModel, loadResults -> val fold = loadResults.fold(Model<T>()) { model, partialState -> model.apply(partialState) } accumulatedModel.update(fold) }) .replay() init { viewModelDisposable.add(loader.connect()) } fun attachView(view: View<T>) { disposable.addAll( Observable.merge(view.firstLoad(), view.refresh(), view.nextPage()) .subscribe { viewAction.onNext(it) }, loader.subscribeOn(scheduler) .observeOn(uiScheduler) .doOnNext { System.out.println("VM: $it") } .subscribe(view)) } fun detachView() { disposable.clear() sourceDisposable.clear() } private fun Model<T>.update(newmodel: Model<T>): Model<T> { return if (newmodel.data != null) newmodel else newmodel.copy(data = data) } private fun Model<T>.apply(partialResult: LoadResult<T>): Model<T> { return when (partialResult) { is Loading -> this.copy( loading = true, loadingNextPage = false, refreshing = false, error = null ) is LoadingNextPage -> this.copy(loading = true, loadingNextPage = true, error = null) is Refreshing -> this.copy(refreshing = true, loading = false, error = null) is Error -> this.copy(loading = false, refreshing = false, error = partialResult.throwable) is Data -> Model(data = combineNullableData(data, partialResult.data)) } } abstract fun combineData(oldData: T, newData: T): T private fun combineNullableData(oldData: T?, newData: T?): T? { return if (oldData != null && newData != null) { combineData(oldData, newData) } else newData ?: oldData } abstract fun load(params: Params): Observable<T> abstract fun refresh(refreshParams: Refresh): Observable<T> abstract fun nextPage(nextPageParams: LoadNext): Observable<T> interface View<T> : Consumer<Model<T>> { fun firstLoad(): Observable<Params> fun refresh(): Observable<Refresh> fun nextPage(): Observable<LoadNext> } } sealed class LoadResult<T> class Loading<T> : LoadResult<T>() class LoadingNextPage<T> : LoadResult<T>() class Refreshing<T> : LoadResult<T>() data class Error<T>(val throwable: Throwable) : LoadResult<T>() data class Data<T>(val data: T) : LoadResult<T>()
1
null
1
1
0c7c7c0e7d27295922b4ae6834a08e170db4d7b4
5,169
uni-d-architecture
MIT License
app/src/main/java/io/zhuliang/photopicker/sample/SampleApp.kt
Pigcasso
125,020,235
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "INI": 3, "Proguard": 2, "XML": 38, "Kotlin": 29, "Java": 2}
package io.zhuliang.photopicker.sample import android.app.Application import android.graphics.Color import androidx.core.content.ContextCompat import io.zhuliang.photopicker.PhotoPicker import io.zhuliang.photopicker.ThemeConfig import timber.log.Timber /** * @author <NAME> */ class SampleApp : Application() { companion object { private const val TAG = "SampleApp" } override fun onCreate() { super.onCreate() Timber.plant(Timber.DebugTree()) Timber.tag(TAG) Timber.d("onCreate: ") // 应用内使用 PhotoPicker 时,需要在 Application 里初始化 initPhotoPicker() } private fun initPhotoPicker() { PhotoPicker.themeConfig = ThemeConfig() .radioCheckedColor(ContextCompat.getColor(this, R.color.colorAccent)) .bottomBarBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimary)) .bottomBarTextColor(Color.WHITE) .arrowDropColor(Color.WHITE) .checkboxColor(ContextCompat.getColor(this, R.color.colorAccent)) .checkboxOutlineColor(ContextCompat.getColor(this, R.color.colorAccent)) .orderedCheckedBackground(R.drawable.ic_app_badge_checked_24dp) .orderedUncheckedBackground(R.drawable.ic_app_badge_unchecked_24dp) .actionBarBackground(ContextCompat.getColor(this, R.color.colorPrimary)) .statusBarColor(ContextCompat.getColor(this, R.color.colorPrimaryDark)) .albumPickerItemTextColor(Color.GRAY) .albumPickerBackgroundColor(Color.WHITE) PhotoPicker.authority = "${BuildConfig.APPLICATION_ID}.provider" PhotoPicker.photoLoader = GlidePhotoLoader() } }
1
null
1
1
6b13a78275948b0df6630ee0e291108766802d39
1,743
PhotoPicker
Apache License 2.0
DnDReorderTree/src/main/kotlin/example/App.kt
aterai
158,348,575
false
{"Kotlin": 4334797, "JavaScript": 241284, "Java": 14467, "HTML": 378}
package example import java.awt.* import java.awt.datatransfer.DataFlavor import java.awt.datatransfer.Transferable import java.awt.datatransfer.UnsupportedFlavorException import java.awt.event.ActionEvent import java.util.concurrent.atomic.AtomicInteger import javax.swing.* import javax.swing.tree.DefaultMutableTreeNode import javax.swing.tree.DefaultTreeModel import javax.swing.tree.MutableTreeNode import javax.swing.tree.TreePath import javax.swing.tree.TreeSelectionModel fun makeUI(): Component { val tree = JTree() tree.dragEnabled = true tree.dropMode = DropMode.ON_OR_INSERT tree.transferHandler = TreeTransferHandler() tree.selectionModel.selectionMode = TreeSelectionModel.CONTIGUOUS_TREE_SELECTION val empty: Action = object : AbstractAction() { override fun actionPerformed(e: ActionEvent) { // do nothing } } tree.actionMap.put(TransferHandler.getCutAction().getValue(Action.NAME), empty) expandTree(tree) return JPanel(BorderLayout()).also { it.add(JScrollPane(tree)) it.preferredSize = Dimension(320, 240) } } private fun expandTree(tree: JTree) { var row = 0 while (row < tree.rowCount) { tree.expandRow(row) row++ } } private class TreeTransferHandler : TransferHandler() { private val nodesFlavor = DataFlavor(MutableList::class.java, "List of TreeNode") override fun getSourceActions(c: JComponent) = if (c is JTree && canStartDrag(c)) COPY_OR_MOVE else NONE override fun createTransferable(c: JComponent): Transferable? { var transferable: Transferable? = null (c as? JTree)?.selectionPaths?.also { selPaths -> val copies = mutableListOf<MutableTreeNode>() selPaths.forEach { path -> (path.lastPathComponent as? DefaultMutableTreeNode)?.also { node -> val clone = DefaultMutableTreeNode(node.userObject) copies.add(deepCopy(node, clone)) } } transferable = object : Transferable { override fun getTransferDataFlavors() = arrayOf(nodesFlavor) override fun isDataFlavorSupported(flavor: DataFlavor) = nodesFlavor == flavor @Throws(UnsupportedFlavorException::class) override fun getTransferData(flavor: DataFlavor): Any { if (isDataFlavorSupported(flavor)) { return copies } else { throw UnsupportedFlavorException(flavor) } } } } return transferable } override fun canImport(support: TransferSupport): Boolean { val dl = support.dropLocation val c = support.component return support.isDrop && support.isDataFlavorSupported(nodesFlavor) && c is JTree && dl is JTree.DropLocation && canImportDropLocation(c, dl) } override fun importData(support: TransferSupport): Boolean { val c = support.component val dl = support.dropLocation val transferable = support.transferable return canImport(support) && c is JTree && dl is JTree.DropLocation && insertNode(c, dl, transferable) } private fun insertNode( tree: JTree, dl: JTree.DropLocation, transferable: Transferable, ): Boolean { val path = dl.path val parent = path.lastPathComponent val model = tree.model val nodes = getTransferData(transferable) if (parent is MutableTreeNode && model is DefaultTreeModel) { val index = AtomicInteger(getDropIndex(parent, dl.childIndex)) nodes.filterIsInstance<MutableTreeNode>() .forEach { model.insertNodeInto(it, parent, index.getAndIncrement()) } } return nodes.isNotEmpty() } private fun getTransferData(t: Transferable) = runCatching { t.getTransferData(nodesFlavor) as? List<*> }.getOrNull() ?: emptyList<Any>() override fun exportDone(src: JComponent, data: Transferable, action: Int) { if (src is JTree && action and MOVE == MOVE) { cleanup(src) } } private fun cleanup(tree: JTree) { val model = tree.model val selectionPaths = tree.selectionPaths if (selectionPaths != null && model is DefaultTreeModel) { for (path in selectionPaths) { model.removeNodeFromParent(path.lastPathComponent as? MutableTreeNode) } } } } private fun getDropIndex(parent: MutableTreeNode, childIndex: Int): Int { var index = childIndex // DropMode.INSERT if (childIndex == -1) { // DropMode.ON index = parent.childCount } return index } fun canStartDrag(tree: JTree) = tree.selectionPaths?.let { canStartDragPaths(it) } ?: false fun canStartDragPaths(paths: Array<TreePath>) = paths.asSequence() .map { it.lastPathComponent } .filterIsInstance<DefaultMutableTreeNode>() .map { it.level } .distinct() .count { it != 0 } == 1 fun canImportDropLocation(tree: JTree, dl: JTree.DropLocation): Boolean { val pt = dl.dropPoint val dropRow = tree.getRowForLocation(pt.x, pt.y) return tree.selectionRows?.asSequence()?.none { it == dropRow || isDescendant(tree, it, dropRow) } ?: false } private fun isDescendant(tree: JTree, selRow: Int, dropRow: Int): Boolean { val node = tree.getPathForRow(selRow).lastPathComponent return node is DefaultMutableTreeNode && isDescendant2(tree, dropRow, node) } private fun isDescendant2(tree: JTree, dropRow: Int, node: DefaultMutableTreeNode): Boolean { return node.depthFirstEnumeration() .asSequence() .filterIsInstance<DefaultMutableTreeNode>() .map { it.path } .map { TreePath(it) } .toList() .map { tree.getRowForPath(it) } .any { it == dropRow } } fun deepCopy(src: MutableTreeNode, tgt: DefaultMutableTreeNode): DefaultMutableTreeNode { src.children() .asSequence() .filterIsInstance<DefaultMutableTreeNode>() .forEach { val clone = DefaultMutableTreeNode(it.userObject) tgt.add(clone) if (!it.isLeaf) { deepCopy(it, clone) } } return tgt } fun main() { EventQueue.invokeLater { runCatching { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()) }.onFailure { it.printStackTrace() Toolkit.getDefaultToolkit().beep() } JFrame().apply { defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE contentPane.add(makeUI()) pack() setLocationRelativeTo(null) isVisible = true } } }
0
Kotlin
5
28
d3fc0182d87489e382364c9e13f50f8d4517795a
6,306
kotlin-swing-tips
MIT License
Entity-master/src/main/kotlin/org/cavepvp/entity/menu/npc/menu/NPCAnimationMenu.kt
yakutwrld
701,531,968
false
{"Java": 17373091, "Kotlin": 339998, "Shell": 5518, "Batchfile": 329}
package org.cavepvp.entity.menu.npc.menu import cc.fyre.proton.menu.Button import cc.fyre.proton.menu.buttons.BackButton import cc.fyre.proton.menu.pagination.PaginatedMenu import org.bukkit.Material import org.bukkit.enchantments.Enchantment import org.bukkit.entity.Player import org.bukkit.event.inventory.ClickType import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.inventory.ItemStack import org.cavepvp.entity.animation.EntityAnimationRegistry import org.cavepvp.entity.menu.npc.NPCMenu import org.cavepvp.entity.type.npc.NPC import org.cavepvp.entity.util.ItemBuilder import java.util.* class NPCAnimationMenu(private val npc: NPC) : PaginatedMenu() { override fun getMaxItemsPerPage(player: Player): Int { return 2*9 } override fun getGlobalButtons(player: Player): MutableMap<Int, Button> { return mutableMapOf( 4 to BackButton(NPCMenu(this.npc)) ) } override fun getPrePaginatedTitle(p0: Player?): String { return "Animations" } override fun getAllPagesButtons(player: Player): MutableMap<Int, Button> { return EntityAnimationRegistry.getAllAnimations() .withIndex() .associate{it.index to object : Button() { override fun getName(p0: Player?): String { return "" } override fun getDescription(p0: Player?): MutableList<String> { return Collections.emptyList() } override fun getMaterial(p0: Player?): Material { return Material.AIR } override fun getButtonItem(player: Player): ItemStack { var item = ItemBuilder.copyOf(it.value.getDisplayItem().clone()) .name(it.value.getDisplayName()) if ([email protected](it.value)) { item = item.enchant(Enchantment.DURABILITY, 10) } return item.build() } override fun clicked(player: Player, slot: Int, clickType: ClickType) { if ([email protected](it.value)) { [email protected](it.value) } else { [email protected](it.value) } } }} .toMutableMap() } }
1
null
1
1
086e2351283d7efa3c50eb52aad95adefb74d173
2,555
CavePvP
MIT License
src/main/kotlin/HelpMenu.kt
ThatOtherShadow
726,155,679
false
{"Kotlin": 4754}
class HelpMenu { fun showMenu() { println(""" Enter 1, R, or Rock to choose rock Enter 2, P, or Paper to choose paper Enter 3, S, or Scissors to choose scissors Press enter to return... """.trimIndent()) readln() } }
0
Kotlin
0
0
58eee8cefaee67d4f8facd72faa99bd0c14d804e
294
Rock-Paper-Scissors
MIT License
app/src/main/kotlin/jp/co/yumemi/android/code_check/utils/DialogUtils.kt
charithvithanage
792,017,950
false
{"Kotlin": 193124}
package jp.co.yumemi.android.code_check.utils import android.content.Context import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.DialogFragment import jp.co.yumemi.android.code_check.ui.customdialogs.ConfirmDialogButtonClickListener import jp.co.yumemi.android.code_check.ui.customdialogs.CustomAlertDialogFragment import jp.co.yumemi.android.code_check.ui.customdialogs.CustomAlertDialogListener import jp.co.yumemi.android.code_check.ui.customdialogs.CustomConfirmAlertDialogFragment import jp.co.yumemi.android.code_check.ui.customdialogs.CustomProgressDialogFragment /** * Utility class for managing custom dialogs in application. * This class provides methods to show custom alert dialogs and progress dialogs. */ class DialogUtils { /** * A companion object to provide static methods for creating custom dialogs. */ companion object { /** * Represents a success dialog. */ const val SUCCESS = "success" /** * Represents a fail dialog. */ const val FAIL = "fail" /** * Represents a warn dialog. */ const val WARN = "warn" /** * Represents the tag for a custom alert dialog fragment. */ const val ALERT_DIALOG_FRAGMENT_TAG = "CustomAlertDialogFragmentTag" /** * Represents the tag for a progress dialog fragment. */ const val PROGRESS_DIALOG_FRAGMENT_TAG = "ProgressDialogFragmentTag" /** * Represents the tag for a custom confirm dialog fragment. */ const val CONFIRM_DIALOG_FRAGMENT_TAG = "ConfirmDialogFragmentTag" /** * Show a custom alert dialog without any button click event. * * @param context The context in which the dialog should be shown. * @param type The type of the dialog (Success, Fail, or Warn Alert). * @param message The message body to be displayed in the dialog. * @param dialogButtonClickListener The listener for dialog button click events. */ fun showAlertDialog( context: Context, type: String, message: String?, dialogButtonClickListener: CustomAlertDialogListener ) { (context as? AppCompatActivity)?.supportFragmentManager?.let { fragmentManager -> CustomAlertDialogFragment.newInstance(message, type, dialogButtonClickListener) .show( fragmentManager, ALERT_DIALOG_FRAGMENT_TAG ) } } /** * Show a progress dialog inside a fragment. * * @param activity The fragment in which the progress dialog should be shown. * @param message The progress message to be displayed. * @return The created progress dialog fragment. */ fun showProgressDialog(context: Context, message: String?): DialogFragment? { return (context as? AppCompatActivity)?.supportFragmentManager?.let { fragmentManager -> CustomProgressDialogFragment.newInstance(message).apply { show(fragmentManager, PROGRESS_DIALOG_FRAGMENT_TAG) } } } /** * Show a custom confirm alert dialog with an icon inside an activity. * * @param context The context in which the dialog should be shown. * @param message The message body to be displayed in the dialog. * @param dialogButtonClickListener The listener for dialog button click events. */ fun showConfirmAlertDialog( context: Context, message: String?, dialogButtonClickListener: ConfirmDialogButtonClickListener ) { (context as? AppCompatActivity)?.supportFragmentManager?.let { fragmentManager -> CustomConfirmAlertDialogFragment.newInstance(message, dialogButtonClickListener) .show( fragmentManager, CONFIRM_DIALOG_FRAGMENT_TAG ) } } } }
0
Kotlin
0
0
61c92d4cad86bbfebcf0f7c6b5fd0404732362d4
4,217
android-engineer-codecheck
Apache License 2.0
src/client/kotlin/dev/kikugie/techutils/impl/worldedit/WorldEditNetworkHandler.kt
kikugie
594,759,871
false
{"Kotlin": 97285, "Java": 19004}
package dev.kikugie.techutils.impl.worldedit import com.mojang.brigadier.CommandDispatcher import dev.kikugie.techutils.TechUtilsClient import io.netty.buffer.Unpooled import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking import net.minecraft.client.MinecraftClient import net.minecraft.command.CommandSource import net.minecraft.network.PacketByteBuf import net.minecraft.util.Identifier import net.minecraft.util.math.BlockPos import java.nio.charset.StandardCharsets class WorldEditNetworkHandler { val storage = WorldEditStorage() var connected = false var available = false var yoinkPackets = false var initialized = false val shouldTick get() = connected && available init { requireNotNull(MinecraftClient.getInstance().world) { "Registering WorldEdit handler in non-world context" } if (CHANNEL in ClientPlayNetworking.getGlobalReceivers()) yoinkPackets = true else { ClientPlayNetworking.registerReceiver(CHANNEL) { _, _, it, _ -> onDataPacket(it) } handshake() } } fun tick() { if (initialized) return if (shouldTick) WorldEditSync.onConnected() initialized = shouldTick } fun onCommandTreePacket(dispatcher: CommandDispatcher<CommandSource>) { available = dispatcher.findNode(listOf("/pos1")) != null } fun onDataPacket(data: PacketByteBuf) { if (!connected) { TechUtilsClient.LOGGER.info("WorldEdit connected!") connected = true } val bytes = data.readableBytes() if (bytes == 0) { TechUtilsClient.LOGGER.warn("Received CUI packet of length zero") return } val message = data.toString(0, data.readableBytes(), StandardCharsets.UTF_8) val split = message.split('|') val multi = split[0].startsWith("+") val type = split[0].substring(if (multi) 1 else 0) val args = message.substring(type.length + (if (multi) 2 else 1)).split('|').toTypedArray() TechUtilsClient.LOGGER.debug(message) handlePacket(type, *args) } private fun handlePacket(type: String, vararg args: String) { if (args.isEmpty()) TechUtilsClient.LOGGER.info("Received CUI packet with no arguments") else if (type == "s") storage.cuboid = args.first() == "cuboid" else if (type == "p" && storage.cuboid) try { val index = args[0].toInt() val pos = BlockPos(args[1].toInt(), args[2].toInt(), args[3].toInt()) if (index == 0) storage.pos1 = pos else storage.pos2 = pos } catch (e: Exception) { TechUtilsClient.LOGGER.warn("Failed to parse CUI args [${args.joinToString(", ")}], type $type", e) } } private fun handshake() { val message = "v|$PROTOCOL" val buf = Unpooled.copiedBuffer(message, StandardCharsets.UTF_8) ClientPlayNetworking.send(CHANNEL, PacketByteBuf(buf)) } companion object { val CHANNEL = Identifier("worldedit", "cui") val PROTOCOL = 4 var INSTANCE: WorldEditNetworkHandler? = null private set fun init() { INSTANCE = WorldEditNetworkHandler() } fun close() { INSTANCE = null } } }
1
Kotlin
3
16
38be30186eef91ed2b261fef036d4be4a7bbe7d4
3,397
techutils
Creative Commons Zero v1.0 Universal
processor/src/main/java/com/aniketbhoite/assume/processor/KotlinProcessingEnvironment.kt
aniketbhoite
363,671,797
false
null
package me.eugeniomarletti.kotlin.processing import java.util.* import javax.annotation.processing.Filer import javax.annotation.processing.Messager import javax.annotation.processing.ProcessingEnvironment import javax.lang.model.SourceVersion import javax.lang.model.util.Elements import javax.lang.model.util.Types /** * Wraps [processingEnv] and exposes it at the top level. * Useful for creating extensions with a receiver that also need to access stuff inside [ProcessingEnvironment]. */ interface KotlinProcessingEnvironment { val processingEnv: ProcessingEnvironment val options: Map<String, String> get() = processingEnv.options val messager: Messager get() = processingEnv.messager val filer: Filer get() = processingEnv.filer val elementUtils: Elements get() = processingEnv.elementUtils val typeUtils: Types get() = processingEnv.typeUtils val sourceVersion: SourceVersion get() = processingEnv.sourceVersion val locale: Locale get() = processingEnv.locale }
7
null
15
25
b162398998de8e859dfd57ad35f587c99f5b9c46
1,008
Assume
Apache License 2.0
app/src/main/java/com/example/a7minutesworkout/BmiFragment.kt
aryankshl
863,579,928
false
{"Kotlin": 29349}
package com.example.a7minutesworkout import android.app.Dialog import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.example.a7minutesworkout.databinding.DialogCustomBackConfirmationBinding import com.example.a7minutesworkout.databinding.FragmentBmiBinding import java.math.BigDecimal import java.math.RoundingMode class BmiFragment : Fragment() { companion object { private const val METRIC_UNITS_VIEW = "METRIC_UNIT_VIEW" private const val US_UNITS_VIEW = "US_UNIT_VIEW" } private var _binding: FragmentBmiBinding? = null private val binding get() = _binding!! private var currentVisibleView: String = METRIC_UNITS_VIEW override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentBmiBinding.inflate(inflater, container, false) // Inflate the layout for this fragment // (activity as AppCompatActivity?)!!.setSupportActionBar(binding.toolbarBmiActivity) // if ((activity as AppCompatActivity?)!!.supportActionBar != null) { // (activity as AppCompatActivity?)!!.supportActionBar?.setDisplayHomeAsUpEnabled(true) // } return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { // binding.toolbarBmiActivity.setNavigationOnClickListener { // activity?.onBackPressed() // } makeVisibleMetricUnitsView() binding.rgUnits.setOnCheckedChangeListener { _, checkedId: Int -> if (checkedId == R.id.rbMetricUnits) { makeVisibleMetricUnitsView() } else { makeVisibleUsUnitsView() } } binding.btnCalculateUnits.setOnClickListener { calculateUnits() } } private fun makeVisibleMetricUnitsView(){ currentVisibleView = METRIC_UNITS_VIEW binding.etMetricUnitWeight.hint = "Weight (in Kgs)" binding.etMetricUnitWeight.text!!.clear() binding.etMetricUnitHeight.visibility = View.VISIBLE binding.etUSUnitHeight.text!!.clear() binding.etUSUnitHeightInches.text!!.clear() binding.USUnitsHeight.visibility = View.GONE binding.displayBMIResult.visibility = View.INVISIBLE } private fun makeVisibleUsUnitsView(){ currentVisibleView = US_UNITS_VIEW binding.etMetricUnitWeight.hint = "Weight (in Pounds)" binding.etMetricUnitWeight.text!!.clear() binding.etMetricUnitHeight.visibility = View.GONE binding.etMetricUnitHeight.text!!.clear() binding.USUnitsHeight.visibility = View.VISIBLE binding.displayBMIResult.visibility = View.INVISIBLE } private fun displayBMIResult(bmi: Float){ val bmiType: String val bmiDescription: String if(bmi.compareTo(16f)<=0){ bmiType = "Severely UnderWeight" bmiDescription = "Oops! You really need to take better care of yourself! Take good Diet." } else if(bmi.compareTo(18.5f)<=0){ bmiType = "UnderWeight" bmiDescription = "You have to take yourself a little more.Eat little more" } else if(bmi.compareTo(25f)<=0){ bmiType = "Normal" bmiDescription = "You are in a good shape.Maintain this posture of yourself" } else{ bmiType = "Overweight" bmiDescription = "Loose adequate amount of fat to get fit." } binding.displayBMIResult.visibility = View.VISIBLE binding.tvBMIValue.text = BigDecimal(bmi.toDouble()).setScale(2, RoundingMode.HALF_EVEN).toString() binding.tvBMIType.text = bmiType binding.tvBMIDescription.text = bmiDescription } private fun validateMetricUnits(): Boolean{ var isValid = true if(binding.etMetricUnitWeight.text.toString().isEmpty()){ isValid = false } else if(binding.etMetricUnitHeight.text.toString().isEmpty()){ isValid= false } return isValid } private fun validateUSUnits(): Boolean{ var isValid = true when { binding.etMetricUnitWeight.text.toString().isEmpty() -> { isValid = false } binding.etUSUnitHeight.text.toString().isEmpty() -> { isValid = false } binding.etUSUnitHeightInches.text.toString().isEmpty() ->{ isValid = false } } return isValid } private fun calculateUnits(){ val weight :Float = binding.etMetricUnitWeight.text.toString().toFloat() if(currentVisibleView == METRIC_UNITS_VIEW){ if(validateMetricUnits()){ val height : Float = binding.etMetricUnitHeight.text.toString().toFloat() /100 val bmi = weight/(height*height) displayBMIResult(bmi) } else{ Toast.makeText(this.requireContext(),"Please Enter Valid Values.", Toast.LENGTH_SHORT).show() } } else{ if(validateUSUnits()){ val heightFeet: String= binding.etUSUnitHeight.text.toString() val heightInches: String= binding.etUSUnitHeightInches.text.toString() val heightInInches = heightInches.toFloat() + heightFeet.toFloat() *12 val bmi = 703 *(weight/(heightInInches*heightInInches)) displayBMIResult(bmi) } else{ Toast.makeText(this.requireContext(),"Please Enter valid values.", Toast.LENGTH_SHORT).show() } } } override fun onDestroy() { super.onDestroy() _binding = null } }
0
Kotlin
0
0
0a5ecc4a40046e3ff7642e8f84a788647d5438ce
6,091
FitPulse
MIT License
library/core/stereotyped/src/test/kotlin/de/lise/fluxflow/stereotyped/step/StepDefinitionBuilderTest.kt
lisegmbh
740,936,659
false
{"Kotlin": 687104}
package de.lise.fluxflow.stereotyped.step import de.lise.fluxflow.api.step.stateful.StatefulStepDefinition import de.lise.fluxflow.api.step.stateful.data.DataDefinition import de.lise.fluxflow.api.step.stateful.data.DataKind import de.lise.fluxflow.stereotyped.job.Job import de.lise.fluxflow.stereotyped.metadata.MetadataBuilder import de.lise.fluxflow.stereotyped.step.action.ActionDefinitionBuilder import de.lise.fluxflow.stereotyped.step.automation.Automated import de.lise.fluxflow.stereotyped.step.automation.OnCreated import de.lise.fluxflow.stereotyped.step.automation.Trigger import de.lise.fluxflow.stereotyped.step.data.DataDefinitionBuilder import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.mockito.kotlin.* import kotlin.reflect.KProperty1 @Suppress("unused") class StepDefinitionBuilderTest { @Test fun `build should not return null`() { // Arrange val builder = StepDefinitionBuilder( mock {}, mock { on { buildDataDefinitionFromProperty<Any>(any(), any()) }.doReturn { _ -> mock<DataDefinition<Any>> {} } }, mock {}, mock {}, mutableMapOf() ) // Act val result = builder.build(TestClass("", "")) // Assert assertThat(result).isNotNull } @Test fun `build should return a data object for all properties`() { // Arrange val builder = StepDefinitionBuilder( mock {}, mockDataBuilder(), mock {}, mock {}, mutableMapOf(), ) // Act val result = builder.build(TestClass("", "")) as StatefulStepDefinition // Assert assertThat(result.data.map { it.kind.value }) .containsExactlyInAnyOrder("readOnlyProp", "modifiableProp") } @Test fun `build should ignore private properties`() { // Arrange val builder = StepDefinitionBuilder( mock {}, mockDataBuilder(), mock {}, mock {}, mutableMapOf() ) // Act val result = builder.build( TestClassWithPrivate( "public", "private" ) ) as StatefulStepDefinition // Assert val props = result.data.map { it.kind.value } assertThat(props).doesNotContain("privateField") assertThat(props).containsExactlyInAnyOrder("publicField") } @Test fun `build should ignore properties that are classes with @Job annotation`() { // Arrange val builder = StepDefinitionBuilder( mock {}, mockDataBuilder(), mock {}, mock {}, mutableMapOf() ) // Act val result = builder.build( TestClassWithJob( "some string", SomeJob() ) ) as StatefulStepDefinition // Assert val props = result.data.map { it.kind.value } assertThat(props).doesNotContain("job") assertThat(props).containsExactlyInAnyOrder("publicField") } @Test fun `build should not consider automated functions to be actions`() { // Arrange val actionDefinitionBuilder = mock<ActionDefinitionBuilder> {} val builder = StepDefinitionBuilder( actionDefinitionBuilder, mockDataBuilder(), mock {}, mock { on { isAutomation(any()) } doReturn true }, mutableMapOf() ) // Act val result = builder.build(TestClassWithAutomation()) // Assert verify(actionDefinitionBuilder, never()).build<Any>(any(), any()) assertThat((result as StatefulStepDefinition).actions).isEmpty() } @Test fun `build should use the metadata builder to obtain the step metadata`() { // Arrange val testMetadata = mock<Map<String, Any>>() val metadataBuilder = mock<MetadataBuilder> { on { build(eq(TestClass::class)) } doReturn testMetadata } val builder = StepDefinitionBuilder( mock {}, mockDataBuilder(), metadataBuilder, mock {}, mutableMapOf() ) // Act val result = builder.build(TestClass("stringProp", "modifiableProp")) // Assert verify(metadataBuilder, times(1)).build(TestClass::class) assertThat(result.metadata).isSameAs(testMetadata) } private fun mockDataBuilder(): DataDefinitionBuilder { return mock<DataDefinitionBuilder> { on { buildDataDefinitionFromProperty<Any>(any(), any()) }.doAnswer { answer -> { _ -> mock<DataDefinition<Any>> { on { kind }.doReturn( DataKind( answer.getArgument(1, KProperty1::class.java).name ) ) } } } on { isDataProperty<Any>(any()) }.thenCallRealMethod() } } class TestClass( val readOnlyProp: String, var modifiableProp: String ) {} class TestClassWithPrivate( val publicField: String, private val privateField: String ) @Job class SomeJob class TestClassWithJob( val publicField: String, val job: SomeJob ) class TestClassWithAutomation { @Automated(Trigger.OnCreated) fun `automated function`() { } @OnCreated fun `onStarted function`() { } } }
16
Kotlin
0
6
e3207e265651c628e498debbae8d2d87a12d9951
5,826
fluxflow
Apache License 2.0
app/src/main/java/com/example/wish/Model.kt
HeartArmy
540,291,950
false
null
package com.example.wish data class Model(val itemName: String, val storeName: String, val price: Float)
0
Kotlin
0
0
0cbd4b9fd42ac4cd050311236e883a53385335fd
105
Wish
Apache License 2.0
src/main/kotlin/com/plugin/frege/stubs/types/FregeStubElementType.kt
psurkov
343,041,006
false
null
package com.plugin.frege.stubs.types import com.intellij.lang.Language import com.intellij.psi.stubs.IStubElementType import com.intellij.psi.stubs.StubElement import com.plugin.frege.FregeLanguage import com.plugin.frege.psi.FregeCompositeElement import org.jetbrains.annotations.NonNls abstract class FregeStubElementType<StubT : StubElement<*>, PsiT : FregeCompositeElement?>(@NonNls debugName: String) : IStubElementType<StubT, PsiT>(debugName, FregeLanguage.INSTANCE) { override fun getLanguage(): Language = FregeLanguage.INSTANCE override fun getExternalId(): String = "frege." + super.toString() }
25
null
1
40
20c3653b79b0d9c45c32d44b30f3cc6bbe275727
622
intellij-frege
Apache License 2.0
plugins/src/main/java/com/jraska/github/client/release/ReleasePlugin.kt
kassiend
344,438,866
true
{"Kotlin": 252636}
package com.jraska.github.client.release import org.gradle.api.Plugin import org.gradle.api.Project import java.io.File class ReleasePlugin : Plugin<Project> { override fun apply(project: Project) { project.afterEvaluate { addTasks(it) } } private fun addTasks(project: Project) { project.tasks.register("incrementPatch") { it.doFirst { updatePatchVersionInBuildGradle(project) } } } private fun updatePatchVersionInBuildGradle(project: Project) { val buildGradleFile = File(project.projectDir, "build.gradle") val buildGradleText = buildGradleFile.readText() val incrementVersionCode = GradleFileVersionIncrement.incrementVersionCode(buildGradleText) val newContent = GradleFileVersionIncrement.incrementVersionNamePatch(incrementVersionCode) buildGradleFile.writeText(newContent) } }
0
null
0
0
924b3d1d937ae285c5b5ea7db0c5012b325deda7
866
github-client
Apache License 2.0
src/main/java/dsr/amm/homebudget/data/repository/TransactionRepository.kt
petrovMA
159,924,497
true
{"Java": 42342, "Kotlin": 35763, "Shell": 2365}
package dsr.amm.homebudget.data.repository import dsr.amm.homebudget.data.entity.Account import dsr.amm.homebudget.data.entity.tx.Transaction import org.springframework.data.domain.Page import org.springframework.data.domain.Pageable import org.springframework.data.jpa.repository.Modifying import org.springframework.data.jpa.repository.Query import org.springframework.data.repository.PagingAndSortingRepository import org.springframework.data.repository.query.Param import org.springframework.stereotype.Repository import java.time.OffsetDateTime /** * Created by knekrasov on 10/16/2018. */ @Repository interface TransactionRepository<T : Transaction> : PagingAndSortingRepository<T, Long> { @Query("from #{#entityName} tx where src = ?1 order by tx.createDate") fun findAllByAccount(pageable: Pageable, account: Account): Page<T> @Query("from #{#entityName} tx where src = ?1 and id = ?2") fun findByAccountAndId(account: Account, id: Long): Account? @Query("SELECT * from TRANSACTION where src_id = ?1 order by create_Date desc, amount desc, new_value desc, reason desc limit 1", nativeQuery = true) fun findLastByAccount(account: Account): T? @Query("from #{#entityName} tx where src = ?1 and tx.createDate between ?2 and ?3 order by tx.createDate") fun findAllByAccountWithTimeFilter(pageable: Pageable, account: Account, from: OffsetDateTime, to: OffsetDateTime): Page<T> @Query("from #{#entityName} tx where src = ?1 and tx.createDate >= ?2 order by tx.createDate") fun findAllByAccountWithTimeFilterFrom(pageable: Pageable, account: Account, from: OffsetDateTime): Page<T> @Query("from #{#entityName} tx where src = ?1 and tx.createDate <= ?2 order by tx.createDate") fun findAllByAccountWithTimeFilterTo(pageable: Pageable, account: Account, to: OffsetDateTime): Page<T> @Query("SELECT * from TRANSACTION where src_id = ?1 and create_Date < ?2 order by create_Date desc, amount desc, new_value desc, reason desc limit 1", nativeQuery = true) fun findLastEarlierThan(account: Account, earlierThan: OffsetDateTime): T? @Query("SELECT * from TRANSACTION where src_id = ?1 and create_Date >= ?2 order by create_Date, amount desc, new_value desc, reason desc", nativeQuery = true) fun findAllLaterThan(pageable: Pageable, account: Account, from: OffsetDateTime): Page<T> @Modifying @Query("delete from #{#entityName} tx where src = :account and tx.id = :id") fun deleteById(@Param("account") account: Account, @Param("id") transactionId: Long) }
0
Java
0
0
3dd95e74d6abe00b08b29a5b07f667f0e0252333
2,542
home-budget-amm2018
MIT License
leetcode/kotlin/merge-two-sorted-lists.kt
PaiZuZe
629,690,446
false
{"Java": 67758, "Kotlin": 64055}
/** * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ class Solution { fun mergeTwoLists(list1: ListNode?, list2: ListNode?): ListNode? { var head: ListNode? = null var current: ListNode? = head var list1Node = list1 var list2Node = list2 while (list1Node != null && list2Node != null) { if (list1Node.`val` < list2Node.`val`) { if (head == null) { head = ListNode(list1Node.`val`) current = head } else { current?.next = ListNode(list1Node.`val`) current = current?.next } list1Node = list1Node.next } else { if (head == null) { head = ListNode(list2Node.`val`) current = head } else { current?.next = ListNode(list2Node.`val`) current = current?.next } list2Node = list2Node.next } } while (list1Node != null) { if (head == null) { head = ListNode(list1Node.`val`) current = head } else { current?.next = ListNode(list1Node.`val`) current = current?.next } list1Node = list1Node.next } while (list2Node != null) { if (head == null) { head = ListNode(list2Node.`val`) current = head } else { current?.next = ListNode(list2Node.`val`) current = current?.next } list2Node = list2Node.next } return head } }
1
null
1
1
8540f385c3118e96184b6a7129e9a1802808099b
1,880
interprep
MIT License
input_validator/src/main/java/dev/seabat/android/inputvalidator/ErrorMessage.kt
seabat
622,191,653
false
null
package dev.seabat.android.inputvalidator import androidx.annotation.StringRes /** * Validation で不適合と判断された場合のメッセージ * * メッセージは resId と string のどちらかに指定すること * * @param resId アプリの文字列リソースのID * @param string エラーメッセージ */ data class ErrorMessage( @StringRes val resId: Int? = null, val string: String? = null )
0
Kotlin
0
0
45b11384e38a2e29e663bfc27d735b00f64c1515
319
hello-login-validation
Apache License 2.0
src/androidTest/java/org/cru/godtools/tool/internal/-AndroidTestingPlatform.kt
gyasistory
370,391,711
true
{"Kotlin": 31456, "Ruby": 66}
package org.cru.godtools.tool.internal import androidx.test.ext.junit.runners.AndroidJUnit4 import org.cru.godtools.tool.xml.AndroidXmlPullParserFactory import org.cru.godtools.tool.xml.XmlPullParserFactory actual val UsesResources.TEST_XML_PULL_PARSER_FACTORY: XmlPullParserFactory get() = object : AndroidXmlPullParserFactory() { override fun openFile(fileName: String) = this@TEST_XML_PULL_PARSER_FACTORY::class.java.getResourceAsStream(fileName)!! } // region Android Robolectric actual typealias RunOnAndroidWith = org.junit.runner.RunWith actual typealias Runner = org.junit.runner.Runner actual typealias AndroidJUnit4 = AndroidJUnit4 // endregion Android Robolectric
0
null
0
0
f4084eb41b746c080c1407abb2edf9625c5b2c5e
706
kotlin-mpp-godtools-tool-parser
MIT License
src/main/kotlin/io/github/riej/lsl/psi/LslStateCustom.kt
riej
597,798,011
false
{"Kotlin": 200816, "Java": 199569, "ANTLR": 5887, "Lex": 3385, "HTML": 90}
package io.github.riej.lsl.psi import com.intellij.lang.ASTNode import com.intellij.navigation.ItemPresentation import com.intellij.psi.PsiElement import io.github.riej.lsl.LslIcons import javax.swing.Icon class LslStateCustom(node: ASTNode) : ASTWrapperLslNamedElement(node), LslState, ItemPresentation, LslScopedElement { override fun getPresentableText(): String = "state $name" override fun getIcon(unused: Boolean): Icon = LslIcons.STATE override fun getNavigationElement(): PsiElement = this.identifyingElement ?: this }
5
Kotlin
2
4
c341386601dd0cdb062a82ed1c06a20c3997587f
550
lsl
MIT License
demo/Movieous/app/src/main/java/com/movieous/media/MyApplication.kt
movieous-team
174,439,175
false
null
package com.movieous.media import android.app.Application import android.content.Context import com.movieous.media.mvp.model.VideoDataUtil import com.movieous.media.utils.DisplayManager import iknow.android.utils.BaseUtils import video.movieous.droid.player.MovieousPlayerEnv import video.movieous.media.ULog import video.movieous.shortvideo.UShortVideoEnv import kotlin.properties.Delegates class MyApplication : Application() { companion object { private val TAG = "MyApplication" var context: Context by Delegates.notNull() } override fun onCreate() { super.onCreate() context = applicationContext DisplayManager.init(this) initShortVideoEnv() initMovieousPlayerEnv() BaseUtils.init(this) // 获取播放列表 VideoDataUtil.doGetVideoList() } // 初始化短视频 SDK 运行环境 private fun initShortVideoEnv() { UShortVideoEnv.setLogLevel(ULog.I) UShortVideoEnv.init(context, Constants.MOVIEOUS_SHORTVIDEO_SIGN) } // 初始化播放器 SDK 运行环境 private fun initMovieousPlayerEnv() { // 初始化 SDK,必须第一个调用,否则会出现异常 MovieousPlayerEnv.init(context, Constants.MOVIEOUS_PLAYER_SIGN) // 开启本地缓存,可以离线播放, 需要 okhttp 支持 MovieousPlayerEnv.setCacheInfo(cacheDir, null, (100 * 1024 * 1024).toLong(), "MovieousPlayer20", true) } }
1
null
8
20
7c24e5da1c2966e67cabab98e5824cc2b68e0c45
1,353
MovieousShortVideo-Android-Release
MIT License
app/src/main/java/viach/apps/dicing/di/AIModule.kt
viacheslav-chugunov
540,847,909
false
null
package viach.apps.dicing.di import org.koin.dsl.module import viach.apps.ai.ai.AI import viach.apps.ai.ai.TwoPlayersEasyAI import viach.apps.ai.ai.TwoPlayersHardAI import viach.apps.ai.ai.TwoPlayersNormalAI import viach.apps.dicing.model.AIDifficulty import viach.apps.dicing.model.GameType import viach.apps.dicing.player.FirstPlayer import viach.apps.dicing.player.SecondPlayer val aiModule = module { factory<AI>(AIDifficulty.EASY.qualifier) { TwoPlayersEasyAI( game = get(GameType.USER_VS_AI.qualifier), ownPlayerPosition = SecondPlayer().position, opponentPlayerPosition = FirstPlayer().position ) } factory<AI>(AIDifficulty.NORMAL.qualifier) { TwoPlayersNormalAI( game = get(GameType.USER_VS_AI.qualifier), ownPlayerPosition = SecondPlayer().position, opponentPlayerPosition = FirstPlayer().position ) } factory<AI>(AIDifficulty.HARD.qualifier) { TwoPlayersHardAI( game = get(GameType.USER_VS_AI.qualifier), ownPlayerPosition = SecondPlayer().position, opponentPlayerPosition = FirstPlayer().position ) } }
0
Kotlin
1
1
7f75f995254c645c08e5492e3b409dc0b9bb0354
1,203
dicing-game
MIT License
template/Main.kt
Bluesy1
572,214,020
false
null
package template import java.io.File fun part1(input: List<String>) { print("Part 1: $input") } fun part2(input: List<String>) { print("Part 2: $input") } fun main(){ val inputFile = File("2022/inputs/input.txt") print("\n----- Part 1 -----\n") part1(inputFile.readLines()) print("\n----- Part 2 -----\n") part2(inputFile.readLines()) }
0
Kotlin
0
0
bedad03001a837d7a9190414219c82be5bec268f
368
AdventofCode
MIT License
microservices/payment/src/main/kotlin/org/shared/utils/UuidUtils.kt
Jason952742
717,304,260
false
{"Rust": 765683, "Kotlin": 105553, "Python": 19917, "Scala": 9034, "Shell": 8342, "Dockerfile": 2469, "HTML": 2067, "CSS": 1036, "Go": 338, "Java": 123}
package org.shared.utils import java.nio.ByteBuffer import java.util.* object UuidUtils { fun generatorShortUUID(uuid: UUID): String { // UUID to byteBuffer val byteBuffer = ByteBuffer.wrap(ByteArray(16)) byteBuffer.putLong(uuid.mostSignificantBits) byteBuffer.putLong(uuid.leastSignificantBits) val uuidBytes = byteBuffer.array() // Converting byte arrays to strings using Base64 encoding val shortenedUUID = Base64.getUrlEncoder().withoutPadding().encodeToString(uuidBytes) return shortenedUUID } fun uuidTobase64() { val uuid = UUID.randomUUID() val encodedString = encodeUUID(uuid) println(uuid) println("Encoded UUID: $encodedString") val decodedUUID = decodeUUID(encodedString) println(encodedString) println("Decoded UUID: $decodedUUID") } /** * Convert UUID to Base64 * * @sample uuidTobase64 */ fun encodeUUID(uuid: UUID): String { val uuidBytes = toBytes(uuid) val encodedBytes = Base64.getUrlEncoder().encode(uuidBytes) return removePadding(String(encodedBytes)) } fun decodeUUID(encodedString: String): UUID { val decodedBytes = Base64.getUrlDecoder().decode(addPadding(encodedString)) val uuidBytes = toUUIDBytes(decodedBytes) return toUUID(uuidBytes) } private fun removePadding(encodedString: String): String { return encodedString.removeSuffix("==") } private fun addPadding(encodedString: String): String { val paddingLength = encodedString.length % 4 return encodedString + "=".repeat(paddingLength) } private fun toBytes(uuid: UUID): ByteArray { val mostSigBits = uuid.mostSignificantBits val leastSigBits = uuid.leastSignificantBits val bytes = ByteArray(16) for (i in 0..7) { bytes[i] = (mostSigBits shr 8 * (7 - i)).toByte() bytes[8 + i] = (leastSigBits shr 8 * (7 - i)).toByte() } return bytes } private fun toUUIDBytes(bytes: ByteArray): ByteArray { val uuidBytes = ByteArray(16) for (i in 0..7) { uuidBytes[i] = bytes[i] uuidBytes[8 + i] = bytes[8 + i] } return uuidBytes } private fun toUUID(bytes: ByteArray): UUID { val mostSigBits = bytesToLong(bytes, 0) val leastSigBits = bytesToLong(bytes, 8) return UUID(mostSigBits, leastSigBits) } private fun bytesToLong(bytes: ByteArray, offset: Int): Long { var result: Long = 0 for (i in offset until offset + 8) { result = result shl 8 or (bytes[i].toLong() and 0xFF) } return result } }
0
Rust
0
2
5b1791b9b5beb8e7e4b7f4845df16c97a3f99b57
2,770
multi-language-microservices-boilerplate
MIT License
common/src/main/java/de/nicidienase/chaosflix/common/entities/recording/Conference.kt
NiciDieNase
108,323,397
false
null
package de.nicidienase.chaosflix.common.entities.recording import android.arch.persistence.room.Ignore import android.os.Parcel import android.os.Parcelable import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty @JsonIgnoreProperties(ignoreUnknown = true) data class Conference( var acronym: String = "", @JsonProperty("aspect_ratio") var aspectRatio: String = "", var title: String = "", var slug: String = "", @JsonProperty("webgen_location") var webgenLocation: String = "", @JsonProperty("schedule_url") var scheduleUrl: String? = "", @JsonProperty("logo_url") var logoUrl: String = "", @JsonProperty("images_url") var imagesUrl: String = "", @JsonProperty("recordings_url") var recordingsUrl: String = "", var url: String = "", @JsonProperty("updated_at") var updatedAt: String, var events: List<Event>? ) : Comparable<Conference> { var conferenceID: Long val eventsByTags: HashMap<String, MutableList<Event>> val sensibleTags: MutableSet<String> = HashSet() var tagsUsefull: Boolean; init { eventsByTags = HashMap<String, MutableList<Event>>() val untagged = ArrayList<Event>() val events = this.events if (events != null) { for (event in events) { if (event.tags?.isNotEmpty() ?: false) { for (tag in event.tags!!) { if (tag != null) { val list: MutableList<Event> if (eventsByTags.keys.contains(tag)) { list = eventsByTags[tag]!! } else { list = ArrayList<Event>() eventsByTags.put(tag, list) } list.add(event) } else { untagged.add(event) } } } else { untagged.add(event) } } if (untagged.size > 0) { eventsByTags.put("untagged", untagged) } } val strings = url.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() conferenceID = (strings[strings.size - 1]).toLong() for (s in eventsByTags.keys) { if (!(acronym.equals(s) || s.matches(Regex.fromLiteral("\\d+")))) { sensibleTags.add(s) } } tagsUsefull = sensibleTags.size > 0 } override fun compareTo(conference: Conference): Int { return slug.compareTo(conference.slug) } }
0
Kotlin
0
0
de677e55c8d87731c554b814f19a703c71ccd33a
2,849
chaosflix-common
MIT License
infrastructure/database/src/main/java/com/ayatk/biblio/infrastructure/database/dao/EpisodeDao.kt
ayatk
101,084,816
false
null
/* * Copyright (c) 2016-2018 ayatk. * * 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.ayatk.biblio.infrastructure.database.dao import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.ayatk.biblio.infrastructure.database.entity.EpisodeEntity import io.reactivex.Flowable import io.reactivex.Maybe @Dao interface EpisodeDao { @Query("SELECT * FROM episode WHERE novel_code = :code") fun getAllEpisodeByCode(code: String): Flowable<List<EpisodeEntity>> @Query("SELECT * FROM episode WHERE novel_code = :code AND page = :page LIMIT 1") fun findEpisodeByCodeAndPage(code: String, page: Int): Maybe<EpisodeEntity> @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(episode: EpisodeEntity) @Delete fun delete(episode: EpisodeEntity) }
31
Kotlin
1
5
61f23685042860379cce53635207452b14afae22
1,388
biblio
Apache License 2.0
serialization/src/main/java/com/github/kacso/androidcommons/serialization/extensions/GsonExtensions.kt
kacso
204,923,341
false
{"Gradle": 16, "Java Properties": 2, "Shell": 1, "Text": 4, "Ignore List": 13, "Batchfile": 1, "Markdown": 616, "Kotlin": 181, "XML": 69, "INI": 8, "Proguard": 9, "Java": 1}
package com.github.kacso.androidcommons.serialization.extensions import com.github.kacso.androidcommons.serialization.typeadapters.* import com.google.gson.GsonBuilder import org.threeten.bp.* fun GsonBuilder.registerJavaTimeTypeAdapters(): GsonBuilder { registerTypeAdapter(Duration::class.java, DurationTypeAdapter()) registerTypeAdapter(Instant::class.java, InstantTypeAdapter()) registerTypeAdapter(LocalDateTime::class.java, LocalDateTimeTypeAdapter()) registerTypeAdapter(LocalDate::class.java, LocalDateTypeAdapter()) registerTypeAdapter(LocalTime::class.java, LocalTimeTypeAdapter()) registerTypeAdapter(ZonedDateTime::class.java, ZonedDateTimeTypeAdapter()) return this }
0
Kotlin
1
5
9620f80428f4b00a8b683f4e94294e9e64c85b99
711
android-commons
Apache License 2.0
buildSrc/src/main/kotlin/Dependencies.kt
Dragote
718,160,762
false
{"Kotlin": 147679}
import org.gradle.api.artifacts.dsl.DependencyHandler object Dependencies { const val composeBom = "androidx.compose:compose-bom:${Versions.composeBom}" const val composeUI = "androidx.compose.ui:ui" const val composeGraphics = "androidx.compose.ui:ui-graphics" const val composeToolingPreview = "androidx.compose.ui:ui-tooling-preview" const val material3 = "androidx.compose.material3:material3:${Versions.material3}" const val materialIcons = "androidx.compose.material:material-icons-extended" const val uiTooling = "androidx.compose.ui:ui-tooling" const val uiTestManifest = "androidx.compose.ui:ui-test-manifest" const val activityCompose = "androidx.activity:activity-compose:${Versions.activityCompose}" const val navigationCompose = "androidx.navigation:navigation-compose:${Versions.navigationCompose}" const val composeDestinationsCore = "io.github.raamcosta.compose-destinations:animations-core:${Versions.destinations}" const val composeDestinationsKsp = "io.github.raamcosta.compose-destinations:ksp:${Versions.destinations}" const val coroutines = "org.jetbrains.kotlinx:kotlinx-coroutines-core:${Versions.coroutines}" const val coroutinesTest = "org.jetbrains.kotlinx:kotlinx-coroutines-test:${Versions.coroutines}" const val turbine = "app.cash.turbine:turbine:${Versions.turbine}" const val hiltAndroid = "com.google.dagger:hilt-android:${Versions.hilt}" const val hiltCompiler = "com.google.dagger:hilt-android-compiler:${Versions.hilt}" const val hiltNavigationCompose = "androidx.hilt:hilt-navigation-compose:${Versions.hiltNavigationCompose}" const val roomRuntime = "androidx.room:room-runtime:${Versions.room}" const val roomCompiler = "androidx.room:room-compiler:${Versions.room}" const val roomKtx = "androidx.room:room-ktx:${Versions.room}" const val coil = "io.coil-kt:coil-compose:${Versions.coil}" const val coilSvg = "io.coil-kt:coil-svg:${Versions.coilSvg}" const val junitExt = "androidx.test.ext:junit${Versions.junitExt}" const val junitJupiter = "org.junit.jupiter:junit-jupiter:${Versions.junit5}" const val junitApi = "org.junit.jupiter:junit-jupiter-api:${Versions.junit5}" const val junitParams = "org.junit.jupiter:junit-jupiter-params:${Versions.junit5}" const val junitEngine = "org.junit.jupiter:junit-jupiter-engine:${Versions.junit5}" const val mockito = "org.mockito.kotlin:mockito-kotlin:${Versions.mockito}" } fun DependencyHandler.compose() { implementation(platform(Dependencies.composeBom)) implementation(Dependencies.composeUI) implementation(Dependencies.composeToolingPreview) implementation(Dependencies.composeGraphics) implementation(Dependencies.material3) implementation(Dependencies.materialIcons) androidTestImplementation(Dependencies.composeBom) debugImplementation(Dependencies.uiTooling) debugImplementation(Dependencies.uiTestManifest) } fun DependencyHandler.composeNavigation() { implementation(Dependencies.navigationCompose) implementation(Dependencies.composeDestinationsCore) ksp(Dependencies.composeDestinationsKsp) } fun DependencyHandler.coil() { implementation(Dependencies.coil) implementation(Dependencies.coilSvg) } fun DependencyHandler.coroutines() { implementation(Dependencies.coroutines) implementation(Dependencies.coroutinesTest) testImplementation(Dependencies.coroutinesTest) testImplementation(Dependencies.turbine) } fun DependencyHandler.room() { implementation(Dependencies.roomRuntime) implementation(Dependencies.roomKtx) ksp(Dependencies.roomCompiler) } fun DependencyHandler.hilt() { implementation(Dependencies.hiltAndroid) implementation(Dependencies.hiltNavigationCompose) ksp(Dependencies.hiltCompiler) } fun DependencyHandler.testUtils() { androidTestImplementation(Dependencies.junitExt) implementation(Dependencies.junitJupiter) testImplementation(Dependencies.junitApi) testImplementation(Dependencies.junitParams) testRuntimeOnly(Dependencies.junitEngine) testImplementation(Dependencies.mockito) }
0
Kotlin
0
2
59d44860a9a74bd8824e6e617f834102a3a1f7b1
4,214
Flapp
MIT License
collection-utils-sample/src/main/java/com/guardanis/collections/sample/glide/SingleX509TrustManager.kt
mattsilber
48,820,964
false
{"Java": 93592, "Kotlin": 40943}
package com.guardanis.collections.sample.glide import java.security.KeyStore import java.security.cert.CertificateException import java.security.cert.X509Certificate import javax.net.ssl.TrustManagerFactory import javax.net.ssl.X509TrustManager class SingleX509TrustManager @Throws(CertificateException::class) constructor(): X509TrustManager { private var x509TrustManagers: MutableList<X509TrustManager> = ArrayList<X509TrustManager>() init { val factories = ArrayList<TrustManagerFactory>() try { val original = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) original.init(null as KeyStore?) factories.add(original) } catch (e: Exception) { throw CertificateException(e) } factories.flatMap({ it.trustManagers.toList() }) .mapNotNull({ it as? X509TrustManager }) .forEach({ x509TrustManagers.add(it) }) if (x509TrustManagers.isEmpty()) throw CertificateException("Couldn't find any X509TrustManagers") } @Throws(CertificateException::class) override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) { for (tm in x509TrustManagers) { try { tm.checkClientTrusted(chain, authType) return } catch (e: CertificateException) { } } throw CertificateException() } @Throws(CertificateException::class) override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) { for (tm in x509TrustManagers) { try { tm.checkServerTrusted(chain, authType) return } catch (e: CertificateException) { } } throw CertificateException() } override fun getAcceptedIssuers(): Array<X509Certificate> { return x509TrustManagers .flatMap({ it.acceptedIssuers.toList() }) .toTypedArray() } }
5
Java
1
0
50853d4ed712d7b406cf51eb632e08834e8975dc
2,070
collection-utils
Apache License 2.0
backend/mlreef-rest/src/main/kotlin/com/mlreef/rest/api/v1/dto/ParameterInstanceDto.kt
wgisss
445,092,431
true
{"Kotlin": 1792703, "JavaScript": 1383596, "Python": 165260, "SCSS": 145217, "Shell": 122988, "Ruby": 100068, "TypeScript": 56139, "ANTLR": 27697, "CSS": 19114, "Dockerfile": 18068, "HTML": 8912, "PLpgSQL": 3248, "Batchfile": 310}
package com.mlreef.rest.api.v1.dto import com.mlreef.rest.domain.ParameterInstance import javax.validation.constraints.NotEmpty data class ParameterInstanceDto( @get:NotEmpty val name: String, @get:NotEmpty val value: String, val type: String? = null, val required: Boolean = true, val description: String = "" ) internal fun ParameterInstance.toDto(): ParameterInstanceDto = ParameterInstanceDto( name = this.parameter.name, value = this.value, type = this.parameter.parameterType?.name ?: this.parameterType?.name, description = this.parameter.description ?: "", required = this.parameter.required )
0
null
0
1
80c9af03f324c929b8f8889256c13c865afa95c1
672
mlreef
MIT License
app/src/main/java/com/revosleap/samplemusicplayer/utils/Utils.kt
carloscj6
170,602,407
false
null
package com.revosleap.samplemusicplayer.utils import android.content.ContentUris import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.media.MediaMetadataRetriever import android.os.Handler import android.provider.MediaStore import androidx.appcompat.app.AppCompatActivity import android.util.Log import com.revosleap.samplemusicplayer.R import java.io.ByteArrayInputStream import java.io.File import java.io.InputStream import java.util.* import java.util.concurrent.TimeUnit object Utils { fun songArt(path: String, context: Context): Bitmap { val retriever = MediaMetadataRetriever() val inputStream: InputStream retriever.setDataSource(path) if (retriever.embeddedPicture != null) { inputStream = ByteArrayInputStream(retriever.embeddedPicture) val bitmap = BitmapFactory.decodeStream(inputStream) retriever.release() return bitmap } else { return getLargeIcon(context) } } private fun getLargeIcon(context: Context): Bitmap { return BitmapFactory.decodeResource(context.resources, R.drawable.headphones) } fun formatDuration(duration: Int): String { return String.format(Locale.getDefault(), "%02d:%02d", TimeUnit.MILLISECONDS.toMinutes(duration.toLong()), TimeUnit.MILLISECONDS.toSeconds(duration.toLong()) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration.toLong()))) } fun formatTrack(trackNumber: Int): Int { var formatted = trackNumber if (trackNumber >= 1000) { formatted = trackNumber % 1000 } return formatted } fun delete(activity: AppCompatActivity, imageFile: File){ val handler = Handler() handler.postDelayed({ // Set up the projection (we only need the ID) val projection = arrayOf(MediaStore.Audio.Media._ID) // Match on the file path val selection = MediaStore.Audio.Media.DATA + " = ?" val selectionArgs = arrayOf<String>(imageFile.absolutePath) // Query for the ID of the media matching the file path val queryUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI val contentResolver = activity.contentResolver val c = contentResolver.query(queryUri, projection, selection, selectionArgs, null) if (c!!.moveToFirst()) { // We found the ID. Deleting the item via the content provider will also remove the file val id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)) val deleteUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id) contentResolver.delete(deleteUri, null, null) } else { Log.w("Media ", "Media not found!!") } c.close() }, 70) } }
0
Kotlin
22
59
ec998f31f7b856dd37e3b0987eabc294b7206011
3,024
SampleMusicPlayer
MIT License
app/src/main/java/com/moneytree/app/repository/network/responses/NSChangePasswordResponse.kt
Dishantraiyani
459,687,387
true
{"Kotlin": 469435}
package com.moneytree.app.repository.network.responses import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName /** * The class representing the response body of change password */ data class NSChangePasswordResponse( @SerializedName("status") @Expose var status: Boolean = false, @SerializedName("message") @Expose var message: String? = null )
0
Kotlin
0
0
9d220d9b7e07f787002c1ef7e1cde071a6ae59e0
408
moneytree
Apache License 2.0
app/src/main/java/com/cesarmauri/clean_architecture/application/navigation/Navigator.kt
cmauri
304,640,986
false
null
/* * Copyright 2020 by Cesar Mauri Loba * * 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.cesarmauri.clean_architecture.application.navigation import android.content.ActivityNotFoundException import android.content.Intent import androidx.fragment.app.FragmentActivity import com.cesarmauri.clean_architecture.application.exception.YouTubeNotInstalled import com.cesarmauri.clean_architecture.application.service.AuthenticationService import com.cesarmauri.clean_architecture.presentation.entity.BandViewEntity import com.cesarmauri.clean_architecture.presentation.view.activity.BandDetailsActivity import com.cesarmauri.clean_architecture.presentation.view.activity.BandsActivity import javax.inject.Inject import javax.inject.Singleton @Singleton class Navigator @Inject constructor(private val authenticationService: AuthenticationService) { fun showMain(activity: FragmentActivity) { when (authenticationService.isAuthenticated) { true -> showOther(activity) false -> showLogin() } } private fun showLogin() { // Open here your own login experience } private fun showOther(activity: FragmentActivity) { activity.startActivity(BandsActivity.intent(activity)) } fun showBandDetails(activity: FragmentActivity, bandViewEntity: BandViewEntity) { val intent = BandDetailsActivity.intent(activity, bandViewEntity) activity.startActivity(intent) } fun openYouTubeSearch(activity: FragmentActivity, query: String) { val intent = Intent(Intent.ACTION_SEARCH) intent.setPackage("com.google.android.youtube") intent.putExtra("query", query) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK try { activity.startActivity(intent) } catch (e: ActivityNotFoundException) { throw YouTubeNotInstalled(e) } } }
0
Kotlin
2
7
af2a8c574eae3b89e56e4849509af6f62a6688ab
2,456
android-clean-architecture
Apache License 2.0
RunningApp/app/src/main/java/com/sandy/runningapp/ui/fragments/CancelTrackingDialog.kt
SANDY-9
612,978,825
false
null
package com.sandy.runningapp.ui.fragments import android.app.Dialog import android.os.Bundle import androidx.fragment.app.DialogFragment import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.sandy.runningapp.R /** * @author SANDY * @email [email protected] * @created 2021-10-09 * @desc */ class CancelTrackingDialog : DialogFragment() { private var yesListener: (() -> Unit)? = null fun setYesListener(listener: () -> Unit) { yesListener = listener } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { return MaterialAlertDialogBuilder(requireContext(), R.style.AlertDialogTheme) .setTitle("Cancel the Run?") .setMessage("Are you sure to cancel the current run and delete all its data?") .setIcon(R.drawable.ic_delete) .setPositiveButton("Yes") { _, _ -> yesListener?.let { yes-> yes() } } .setNegativeButton("No") { dialogInterface, _ -> dialogInterface.cancel() } .create() dialog!!.show() } }
0
Kotlin
0
0
e0816a39903f415aa09837bd689e71c17439b9e6
1,158
Project_MyRuns
Apache License 2.0
uranium-swing/src/main/kotlin/pl/karol202/uranium/swing/layout/gridbag/SwingGridBagScope.kt
karol-202
269,320,433
false
null
package pl.karol202.uranium.swing.layout.gridbag interface SwingGridBagScope
0
Kotlin
0
0
d15bbc869a1dac11285d9329a49caee32345f63b
78
uranium-swing
MIT License
composed/src/test/kotlin/com/w2sv/composed/DisposableEffectsKtTest.kt
w2sv
765,250,608
false
{"Kotlin": 41285, "Makefile": 405}
package com.w2sv.composed import androidx.activity.ComponentActivity import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.lifecycle.Lifecycle import org.junit.Assert.assertEquals import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class DisposableEffectsKtTest { @get:Rule val composeTestRule = createAndroidComposeRule<ComponentActivity>() @Test fun `OnRemoveFromComposition basic functionality`() { var callbackTriggerCount = 0 var removeFromComposition by mutableStateOf(false) composeTestRule.setContent { println("Composing") if (!removeFromComposition) { OnDispose { println("Running callback") callbackTriggerCount += 1 } } LaunchedEffect(Unit) { println("Removing") removeFromComposition = true println("Removed") } } assertEquals(1, callbackTriggerCount) } @Test fun `OnRemoveFromComposition updates callback`() { var originalCallbackTriggerCount = 0 var changedCallbackTriggerCount = 0 val originalCallback = { println("Original callback triggered") originalCallbackTriggerCount += 1 } val changedCallback = { println("Changed callback triggered") changedCallbackTriggerCount += 1 } var removeFromComposition by mutableStateOf(false) var callback by mutableStateOf(originalCallback) composeTestRule.setContent { println("Composing") LaunchedEffect(callback) { if (callback.hashCode() == changedCallback.hashCode()) { removeFromComposition = true println("Set removeFromComposition=true") } } if (!removeFromComposition) { OnDispose(callback = callback) } LaunchedEffect(Unit) { callback = changedCallback println("Changed callback") } } assertEquals(0, originalCallbackTriggerCount) assertEquals(1, changedCallbackTriggerCount) } @Test fun `onLifecycleEvent basic functionality`() { var triggerCount = 0 composeTestRule.setContent { OnLifecycleEvent( callback = { triggerCount += 1 }, lifecycleEvent = Lifecycle.Event.ON_DESTROY ) } composeTestRule.activityRule.scenario.moveToState(Lifecycle.State.DESTROYED) assertEquals(1, triggerCount) } @Test fun `onLifecycleEvent updates event`() { var receivedTriggerState: String? = null var triggerEvent by mutableStateOf(Lifecycle.Event.ON_START) composeTestRule.setContent { val lifecycleOwner = LocalLifecycleOwner.current OnLifecycleEvent( callback = { receivedTriggerState = lifecycleOwner.lifecycle.currentState.toString() }, lifecycleEvent = triggerEvent ) LaunchedEffect(Unit) { triggerEvent = Lifecycle.Event.ON_DESTROY } } composeTestRule.activityRule.scenario.moveToState(Lifecycle.State.DESTROYED) assertEquals("DESTROYED", receivedTriggerState) } }
0
Kotlin
0
20
d91fa95da920c7b513e216cbe52eaf425297d3b3
3,813
Composed
Apache License 2.0
presentation/src/main/java/co/kr/hoyaho/presentation/ui/main/MainViewModel.kt
hoyahozz
532,912,636
false
null
package co.kr.hoyaho.presentation.ui.main import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class MainViewModel @Inject constructor() : ViewModel() { private val _toolbarState: MutableLiveData<Pair<String, Boolean>> = MutableLiveData() val toolbarState: LiveData<Pair<String, Boolean>> get() = _toolbarState fun updateToolbarState(title: String, isBackVisible: Boolean) { _toolbarState.postValue(Pair(title, isBackVisible)) } }
0
Kotlin
0
0
8c2a5a62772e0a0634eadaf683d42748107eb69f
612
newsApp
Apache License 2.0
app/src/main/java/com/lhwdev/selfTestMacro/ui/pages/main/EditSchedule.kt
lhwdev
289,257,684
false
null
package com.lhwdev.selfTestMacro.ui.pages.main import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.* import androidx.compose.runtime.* 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.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.dp import com.lhwdev.selfTestMacro.R import com.lhwdev.selfTestMacro.database.DbTestGroup import com.lhwdev.selfTestMacro.database.DbTestSchedule import com.lhwdev.selfTestMacro.navigation.LocalNavigator import com.lhwdev.selfTestMacro.navigation.Navigator import com.lhwdev.selfTestMacro.repository.GroupInfo import com.lhwdev.selfTestMacro.repository.LocalSelfTestManager import com.lhwdev.selfTestMacro.repository.dayOf import com.lhwdev.selfTestMacro.showToast import com.lhwdev.selfTestMacro.ui.EmptyRestartable import com.lhwdev.selfTestMacro.ui.MediumContentColor import com.lhwdev.selfTestMacro.ui.common.CheckBoxListItem import com.lhwdev.selfTestMacro.ui.common.SimpleIconButton import com.lhwdev.selfTestMacro.ui.common.TestTargetListItem import com.lhwdev.selfTestMacro.ui.primarySurfaceColored import com.lhwdev.selfTestMacro.ui.systemUi.AutoSystemUi import com.lhwdev.selfTestMacro.ui.systemUi.Scrims import com.lhwdev.selfTestMacro.ui.systemUi.TopAppBar import com.lhwdev.selfTestMacro.ui.utils.AnimateHeight import com.lhwdev.selfTestMacro.ui.utils.ClickableTextFieldDecoration import com.lhwdev.selfTestMacro.ui.utils.TimePickerDialog import com.lhwdev.selfTestMacro.utils.headToLocalizedString import com.lhwdev.selfTestMacro.utils.rememberTimeStateOf import com.lhwdev.selfTestMacro.utils.tailToLocalizedString import com.vanpra.composematerialdialogs.* import java.util.Calendar import java.util.concurrent.TimeUnit import kotlin.math.max import kotlin.math.min private class Time(val hour: Int, val minute: Int) private fun DbTestSchedule.Fixed.toTime() = Time(hour, minute) private fun Time.toFixed() = DbTestSchedule.Fixed(hour, minute) internal fun Navigator.showScheduleSelfTest( info: GroupInfo ): Unit = showFullDialogAsync { dismiss -> Surface(color = MaterialTheme.colors.background) { AutoSystemUi { scrims -> @Suppress("ExplicitThis") [email protected](info, dismiss, scrims) } } } @Composable private fun FullMaterialDialogScope.ScheduleContent(info: GroupInfo, dismiss: () -> Unit, scrims: Scrims) = Column { val context = LocalContext.current val selfTestManager = LocalSelfTestManager.current val navigator = LocalNavigator val group = info.group val target = group.target var type by remember { mutableStateOf( when(group.schedule) { DbTestSchedule.None -> ScheduleType.none is DbTestSchedule.Fixed -> ScheduleType.fixed is DbTestSchedule.Random -> ScheduleType.random } ) } var fixedTime by remember { mutableStateOf((group.schedule as? DbTestSchedule.Fixed)?.toTime()) } val random = group.schedule as? DbTestSchedule.Random var randomFrom by remember { mutableStateOf(random?.from?.toTime()) } var randomTo by remember { mutableStateOf(random?.to?.toTime()) } var excludeWeekend by remember { mutableStateOf(group.excludeWeekend) } var altogether by remember { mutableStateOf(group.schedule.altogether) } TopAppBar( navigationIcon = { SimpleIconButton(icon = R.drawable.ic_clear_24, contentDescription = "닫기", onClick = dismiss) }, title = { Text("자가진단 예약") }, backgroundColor = Color.Transparent, elevation = 0.dp, statusBarScrim = scrims.statusBars ) Divider() Column( modifier = Modifier .verticalScroll(rememberScrollState()) .weight(1f) ) { @Composable fun Header(text: String) { Text( text = text, style = MaterialTheme.typography.subtitle1, modifier = Modifier.padding(top = 12.dp, bottom = 8.dp, start = 20.dp) ) } TestTargetListItem(target) Spacer(Modifier.height(12.dp)) Header("자가진단 예약") @Composable fun ScheduleTypeHead(targetType: ScheduleType, text: String) { ListItem( icon = { RadioButton(selected = type == targetType, onClick = null) }, modifier = Modifier.clickable { if(targetType == ScheduleType.random && targetType != type) { altogether = false // good default? } type = targetType } ) { Text(text) } } @Composable fun ScheduleTime( label: String, time: Time?, initialTimeForPicker: Time = Time(hour = 7, minute = 0), setTime: (Time) -> Unit, modifier: Modifier = Modifier ) { ClickableTextFieldDecoration( onClick = { navigator.showDialogAsync { dismiss -> TimePickerDialog( initialHour = time?.hour ?: initialTimeForPicker.hour, initialMinute = time?.minute ?: initialTimeForPicker.minute, setTime = { h, m -> setTime(Time(h, m)) dismiss() }, cancel = dismiss ) } }, isEmpty = time == null, label = { Text(label) }, modifier = modifier.padding(8.dp) ) { if(time != null) { val text = buildAnnotatedString { append(if(time.hour == 0) "12" else "${time.hour}".padStart(2, padChar = '0')) withStyle(SpanStyle(color = MediumContentColor)) { append(":") } append("${time.minute}".padStart(2, padChar = '0')) } Text(text) } } } /// none ScheduleTypeHead(ScheduleType.none, "꺼짐") /// fixed ScheduleTypeHead(ScheduleType.fixed, "매일 특정 시간") AnimateHeight( visible = type == ScheduleType.fixed, modifier = Modifier.padding(horizontal = 16.dp) ) { ScheduleTime( label = "시간 설정", time = fixedTime, setTime = { fixedTime = it }, modifier = Modifier.fillMaxWidth() ) } /// random ScheduleTypeHead(ScheduleType.random, "매일 렌덤 시간") AnimateHeight( visible = type == ScheduleType.random, modifier = Modifier.padding(horizontal = 16.dp) ) { Column(modifier = Modifier.padding(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { Text( "시작 시간과 끝 시간 사이 임의의 시간에 자가진단을 합니다.", style = MaterialTheme.typography.body2 ) Row(verticalAlignment = Alignment.CenterVertically) { ScheduleTime( label = "범위 시작", time = randomFrom, setTime = { randomFrom = it }, modifier = Modifier.weight(1f) ) Text("~", style = MaterialTheme.typography.body1) ScheduleTime( label = "범위 끝", time = randomTo, initialTimeForPicker = randomFrom ?: Time(hour = 7, minute = 0), modifier = Modifier.weight(1f), setTime = { randomTo = it } ) } // I don't think this feature is needed // if(target is DbTestTarget.Group) { // TextCheckbox( // text = { Text("그룹원들을 동시에 자가진단") }, // checked = altogether, // setChecked = { altogether = it } // ) // // if(altogether) // Text("임의의 시간이 정해지면 그 때 그룹원들을 모두 자가진단합니다. 이 옵션이 체크되어 있지 않다면 정해진 범위 내에서 각각 따로 실행됩니다.") // } } } } Spacer(Modifier.height(16.dp)) // ListItem { // TextCheckbox( // text = { Text("주말에는 자가진단하지 않기") }, // checked = excludeWeekend, // setChecked = { excludeWeekend = it } // ) // } CheckBoxListItem( checked = !excludeWeekend, onCheckChanged = { excludeWeekend = !it } ) { Text("주말에도 자가진단하기") } EmptyRestartable { val tasks = selfTestManager.schedules.getTasks(group) if(tasks.isNotEmpty()) Surface( color = MaterialTheme.colors.primarySurfaceColored, contentColor = MaterialTheme.colors.onPrimary ) { val now by rememberTimeStateOf(unit = TimeUnit.DAYS) val range = tasks.fold(Long.MAX_VALUE to Long.MIN_VALUE) { range, task -> min(range.first, task.timeMillis) to max(range.second, task.timeMillis) } val first = Calendar.getInstance().also { it.timeInMillis = range.first } val last = Calendar.getInstance().also { it.timeInMillis = range.second } val sameDay = dayOf(range.first) == dayOf(range.second) ListItem( text = { val text = if(sameDay) { "${first.headToLocalizedString(now)} " + "${first.tailToLocalizedString(now)}~${last.tailToLocalizedString(now)}" } else { val a = first.headToLocalizedString(now) + " " + first.tailToLocalizedString(now) val b = last.headToLocalizedString(now) + " " + last.tailToLocalizedString(now) "$a~$b" } Text(text) } ) } } Spacer(Modifier.height(4.dp)) Buttons { PositiveButton(onClick = submit@{ val schedule = when(type) { ScheduleType.none -> DbTestSchedule.None ScheduleType.fixed -> { val time = fixedTime if(time == null) { context.showToast("시간을 선택해주세요.") return@submit } time.toFixed() } ScheduleType.random -> { val from = randomFrom val to = randomTo if(from == null || to == null) { context.showToast("시간을 선택해주세요.") return@submit } DbTestSchedule.Random( from = from.toFixed(), to = to.toFixed(), altogether = altogether ) } } selfTestManager.updateSchedule( target = group, new = DbTestGroup( id = group.id, target = group.target, schedule = schedule, excludeWeekend = excludeWeekend ) ) dismiss() }) NegativeButton(onClick = requestClose) } scrims.navigationBars() }
2
Kotlin
7
50
06ada78bb235a170f74c9a3f06dc9b5ea99e0a8d
9,623
covid-selftest-macro
Apache License 2.0
client/src/vr/network/RestClient.kt
tlaukkan
62,936,064
false
{"Gradle": 3, "Text": 2, "Ignore List": 1, "YAML": 1, "Markdown": 1, "Kotlin": 108, "INI": 1, "HTML": 2, "Wavefront Object": 4, "COLLADA": 1, "JavaScript": 6, "Java": 2, "JSON": 156}
package vr.network import org.w3c.dom.events.Event import org.w3c.xhr.XMLHttpRequest import vr.util.fromJson /** * Created by tlaukkan on 1/7/2017. */ class RestClient(var apiUrl: String) { fun <T : Any> get(resourceUrlFragment: String, callback: (response: T?) -> Unit) : Unit { val url = "$apiUrl/$resourceUrlFragment" val xmlHttp = XMLHttpRequest() xmlHttp.onreadystatechange = fun (event : Event) : Unit { if (xmlHttp.readyState as Int == 4) { if (xmlHttp.status as Int == 200) { callback(fromJson<T>(xmlHttp.responseText)) } else { error("Response code not 200 for REST API GET at $url: ${xmlHttp.status}.") callback(null) } } return } xmlHttp.open("GET", "$apiUrl/$resourceUrlFragment", true) xmlHttp.send() } }
0
JavaScript
0
1
4067f653eef50e93aeaa7a5171709e6eb9dee005
925
kotlin-web-vr
MIT License
app/src/main/java/com/example/week3sample/ActivityA.kt
lfwells
465,855,134
false
{"Kotlin": 3011}
package com.example.week3sample import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.example.week3sample.databinding.ActivityABinding class ActivityA : AppCompatActivity() { private lateinit var ui : ActivityABinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ui = ActivityABinding.inflate(layoutInflater) setContentView(ui.root) ui.btnOpenB.setOnClickListener { val intent = Intent(this, ActivityB::class.java) startActivity(intent) } ui.btnOpenC.setOnClickListener { val intent = Intent(this, ActivityC::class.java) startActivity(intent) } } }
0
Kotlin
0
1
f1df1b2aac62d637da30efd2436a49db97e0eddb
772
kit305-week3-sample
Apache License 2.0
app/src/main/java/br/com/gladson/pokedex/util/ViewExtentions.kt
gladson-sza
460,100,673
false
{"Kotlin": 49252}
package br.com.gladson.pokedex.util import android.app.Activity import android.graphics.Color import android.graphics.drawable.Drawable import android.view.View import android.view.WindowManager import android.view.inputmethod.InputMethodManager import androidx.appcompat.app.AppCompatActivity import androidx.core.graphics.drawable.DrawableCompat import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat import androidx.core.view.WindowInsetsControllerCompat import androidx.fragment.app.Fragment fun View.setBackgroundTintColor(hexColor: String) { var drawable: Drawable = this.background drawable = DrawableCompat.wrap(drawable) DrawableCompat.setTint(drawable, Color.parseColor(hexColor)) this.background = drawable } fun View.setIsVisible(isVisible: Boolean) { if (isVisible) { this.visibility = View.VISIBLE } else { this.visibility = View.GONE } } fun Fragment.setStatusBarColor(color: Int) { val window = this.activity?.window window?.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) window?.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window?.statusBarColor = color } fun View.hideSoftKeyboard() { val imm = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(windowToken, 0) } fun AppCompatActivity.setFullScreen(rootView: View) { WindowCompat.setDecorFitsSystemWindows(window, false) WindowInsetsControllerCompat(window, rootView).let { controller -> controller.hide(WindowInsetsCompat.Type.systemBars()) controller.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE } }
0
Kotlin
0
2
78df9a6275e6e62e081a95d4e6e34c8819fd0ec8
1,742
pokedex-kotlin
MIT License
app/src/main/java/com/lobo/repogit/core/extension/Extensions.kt
viniciuslobo21
287,349,405
false
null
package com.lobo.repogit.core.extension import android.annotation.SuppressLint import android.text.Editable import android.text.TextWatcher import android.widget.EditText import androidx.lifecycle.LiveData import androidx.lifecycle.Observer import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.async import java.math.RoundingMode import java.text.DecimalFormat import java.text.Normalizer import java.text.NumberFormat import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException private const val PHONE_NUMBER_PATTERN = "^\\([1-9]{2}\\) 9 [0-9]{4} [0-9]{4}" fun String.validatePhoneNumber(): Boolean { return this.matches(PHONE_NUMBER_PATTERN.toRegex()) } fun String?.removeNull(): String = this ?: "" fun Double.toBrCurrency(): String { val nf = NumberFormat.getInstance(Locale.GERMANY) nf.minimumFractionDigits = 2 return "R$ ${nf.format(this)}" } fun Int.toBrCurrencyWithoutDecimal(): String { val nf = NumberFormat.getInstance(Locale.GERMANY) return "R$ ${nf.format(this)}" } fun String.removeBrCurrency(): String { return this.replace("R$ ", "") } @SuppressLint("SimpleDateFormat") fun String.toDateUSAFormat(): String { val pattern = "yyyy/mm/dd" val format = SimpleDateFormat(pattern) return format.format(this) } fun EditText.afterTextChanged(afterTextChanged: (String) -> Unit) { this.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { } override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { } override fun afterTextChanged(editable: Editable?) { afterTextChanged.invoke(editable.toString()) } }) } fun String.removeAccentuation(): String { val regexUnaccent = "[^\\p{ASCII}]".toRegex() val temp = Normalizer.normalize(this, Normalizer.Form.NFD) return regexUnaccent.replace(temp, "") } fun String.removeSpecialCharacters(): String { val re = Regex("[^A-Za-z ]") return re.replace(this, " ") } fun String.CPFMask(): String { return this.substring(0, 3) + "." + this.substring(3, 6) + "." + this.substring( 6, 9 ) + "-" + this.substring(9, 11) } fun Double.toPercentage(decimalPlaces: Int): String { val insuranceFormat = when { decimalPlaces == 1 -> DecimalFormat("##.#") decimalPlaces >= 2 -> DecimalFormat("##.##") else -> DecimalFormat("##") } return insuranceFormat.format(this).toString().plus("%") .replace(".", ",") } fun String.unmask(): String { return this.replace("[\\W]*".toRegex(), "") } fun String?.cutDecimals(): Double? { return this?.toBigDecimal()?.setScale(2, RoundingMode.DOWN)?.toDouble() } fun <T> T.toDeferred() = GlobalScope.async { this@toDeferred } fun <T> LiveData<T>.getOrAwaitValue( time: Long = 2, timeUnit: TimeUnit = TimeUnit.SECONDS ): T { var data: T? = null val latch = CountDownLatch(1) val observer = object : Observer<T> { override fun onChanged(o: T?) { data = o latch.countDown() [email protected](this) } } this.observeForever(observer) // Don't wait indefinitely if the LiveData is not set. if (!latch.await(time, timeUnit)) { throw TimeoutException("LiveData value was never set.") } @Suppress("UNCHECKED_CAST") return data as T }
0
Kotlin
0
0
25071cbb035b41e372763b5bfc2eac3269bea297
3,585
RepoGit
Apache License 1.1
cmpe/plugin/desktop/cohesive-cohesive/src/main/kotlin/xyz/mcxross/cohesive/c/MainView.kt
mcxross
514,846,313
false
null
package com.mcxross.cohesive.c import androidx.compose.runtime.Composable import com.mcxross.cohesive.common.frontend.api.ui.view.CohesiveView import com.mcxross.cohesive.csp.annotation.Cohesive import com.mcxross.cohesive.csp.annotation.Net /** * Default implementation of [CohesiveView] that is used when no other implementation is provided. * * It implements all abstract methods of [CohesiveView] with "generic" UIs. * @since 0.1.0 */ @Cohesive( platform = "Cohesive", version = "0.1.0", nets = [ Net( k = "Mainnet", v = "https://mainnet.cohesive.network", ), Net( k = "Testnet", v = "https://testnet.cohesive.network", ), Net( k = "Localhost", v = "http://localhost:3998", ), ], ) open class MainView : CohesiveView { @Composable override fun Explorer() { com.mcxross.cohesive.c.view.Explorer() } @Composable override fun Wallet() { com.mcxross.cohesive.c.view.Wallet() } }
0
Kotlin
0
3
29bc632d6e9ce746b3eedacdfe18e617ebcad175
1,006
cohesive
Apache License 2.0
app/src/main/java/com/aregyan/github/views/userDetails/UserDetailsViewModel.kt
Zubair189
582,278,293
false
null
package com.aregyan.github.views.userDetails import androidx.databinding.ObservableParcelable import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.aregyan.github.domain.UserDetails import com.aregyan.github.repository.UserDetailsRepository import com.aregyan.github.views.base.BaseViewModel import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class UserDetailsViewModel @Inject constructor( private val userDetailsRepository: UserDetailsRepository ) : BaseViewModel() { val userDetails = ObservableParcelable(UserDetails()) fun getUserDetails(user: String) = userDetailsRepository.getUserDetails(user) fun refreshUserDetails(user: String) = viewModelScope.launch(Dispatchers.IO) { userDetailsRepository.refreshUserDetails(user) } }
0
Kotlin
0
0
abbb67d3adb33a6fe0f6a8436b03a28e67cc774e
912
Boilerplate_Hilt
MIT License
app/src/main/java/com/phz/dev/api/service/WanAndroidApiService.kt
PengHaiZhuo
395,591,581
false
{"Kotlin": 429882, "Java": 59576, "HTML": 10034}
package com.phz.dev.api.service import com.phz.dev.api.BaseJsonFormFeedBack import com.phz.dev.data.model.UserBean import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.GET import retrofit2.http.POST /** * @author phz * @description 网络Api接口文档类 */ interface WanAndroidApiService { @FormUrlEncoded @POST("user/login") suspend fun login( @Field("username") username: String, @Field("password") pwd: String ): BaseJsonFormFeedBack<UserBean> @GET("user/logout/json") suspend fun logout(): BaseJsonFormFeedBack<String> @FormUrlEncoded @POST("user/register") suspend fun register( @Field("username") username: String, @Field("password") pwd: String, @Field("repassword") repwd: String ):BaseJsonFormFeedBack<UserBean> }
0
Kotlin
0
0
baf65155052ad759f01b24921c859dee181deaf6
834
lapAndroid
Apache License 2.0
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/ShieldPlus.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Bold.ShieldPlus: ImageVector get() { if (_shieldPlus != null) { return _shieldPlus!! } _shieldPlus = Builder(name = "ShieldPlus", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(15.0f, 9.5f) horizontalLineTo(13.5f) verticalLineTo(8.0f) arcToRelative(1.5f, 1.5f, 0.0f, false, false, -3.0f, 0.0f) verticalLineTo(9.5f) horizontalLineTo(9.0f) arcToRelative(1.5f, 1.5f, 0.0f, false, false, 0.0f, 3.0f) horizontalLineToRelative(1.5f) verticalLineTo(14.0f) arcToRelative(1.5f, 1.5f, 0.0f, false, false, 3.0f, 0.0f) verticalLineTo(12.5f) horizontalLineTo(15.0f) arcToRelative(1.5f, 1.5f, 0.0f, false, false, 0.0f, -3.0f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 24.0f) arcToRelative(1.5f, 1.5f, 0.0f, false, true, -0.609f, -0.129f) curveTo(11.0f, 23.7f, 1.909f, 19.569f, 1.909f, 12.0f) verticalLineTo(7.247f) arcTo(5.492f, 5.492f, 0.0f, false, true, 5.67f, 2.029f) lineTo(11.525f, 0.077f) arcToRelative(1.513f, 1.513f, 0.0f, false, true, 0.95f, 0.0f) lineTo(18.33f, 2.029f) arcToRelative(5.493f, 5.493f, 0.0f, false, true, 3.761f, 5.218f) verticalLineTo(12.0f) curveToRelative(0.0f, 8.618f, -9.224f, 11.792f, -9.616f, 11.923f) arcTo(1.49f, 1.49f, 0.0f, false, true, 12.0f, 24.0f) close() moveTo(12.0f, 3.081f) lineTo(6.619f, 4.875f) arcToRelative(2.5f, 2.5f, 0.0f, false, false, -1.71f, 2.372f) verticalLineTo(12.0f) curveToRelative(0.0f, 4.735f, 5.421f, 7.952f, 7.168f, 8.865f) curveToRelative(1.757f, -0.733f, 7.014f, -3.383f, 7.014f, -8.865f) verticalLineTo(7.247f) arcToRelative(2.5f, 2.5f, 0.0f, false, false, -1.71f, -2.372f) close() } } .build() return _shieldPlus!! } private var _shieldPlus: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,522
icons
MIT License
workshopspace/src/main/kotlin/de/tarent/academy/kotlin/section1/Nullable.kt
msch0304
139,429,663
true
{"Kotlin": 34655}
package de.tarent.academy.kotlin.section1 import session1.JavaCustomer fun main(args: Array<String>) { val customer: JavaCustomer = JavaCustomer() val baseFee: Double = customer.getContract()?.getBaseFee() ?: 0.0 // val baseFee2: Double = customer.getContract()!!.getBaseFee()!! var notNullable: String = "Hallo" var nullable: String? = null // notNullable = nullable!! println(baseFee) val foo = Foo() foo.myFunction() Bar.myStaticStuff() } class Foo { fun myFunction() { println("Hallo Welt") } } object Bar { fun myStaticStuff() { println("I'm static") } }
0
Kotlin
0
0
4010ea00f42766e7a3a8fb236a827cef95103bf3
642
kotlin-workshop
MIT License
main/src/main/java/st/slex/messenger/main/ui/settings/SettingsFragment.kt
stslex
378,152,043
false
null
package st.slex.messenger.main.ui.settings import android.content.ContentValues.TAG import android.content.Context import android.content.Intent import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.viewModels import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import dagger.Lazy import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import st.slex.core.Resource import st.slex.messenger.main.R import st.slex.messenger.main.databinding.FragmentSettingsBinding import st.slex.messenger.main.ui.MainActivity import st.slex.messenger.main.ui.core.BaseFragment import st.slex.messenger.main.ui.core.UIExtensions.changeVisibility import st.slex.messenger.main.utilites.funs.setSupportActionBar import javax.inject.Inject @ExperimentalCoroutinesApi class SettingsFragment : BaseFragment() { private var _binding: FragmentSettingsBinding? = null private val binding: FragmentSettingsBinding get() = checkNotNull(_binding) private lateinit var viewModelFactory: Lazy<ViewModelProvider.Factory> private val viewModel: SettingsViewModel by viewModels { viewModelFactory.get() } @Inject fun injection(viewModelFactory: Lazy<ViewModelProvider.Factory>) { this.viewModelFactory = viewModelFactory } override fun onAttach(context: Context) { (requireActivity() as MainActivity).activityComponent.inject(this) super.onAttach(context) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentSettingsBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.settingsToolbar.title = getString(R.string.title_contacts) setSupportActionBar(binding.settingsToolbar) binding.settingsSignOut.setOnClickListener(signOutClickListener) } private val signOutClickListener: View.OnClickListener = View.OnClickListener { viewLifecycleOwner.lifecycleScope.launch(Dispatchers.IO) { viewModel.signOut().collect { it.collector() } } } private suspend fun Resource<Nothing?>.collector() { viewLifecycleOwner.lifecycleScope.launch(Dispatchers.Main) { when (this@collector) { is Resource.Success -> signOutResult() is Resource.Failure -> signOutResult() is Resource.Loading -> loading() } } } private suspend fun signOutResult() { binding.SHOWPROGRESS.changeVisibility() val intent = Intent().setClassName(requireContext(), SPLASH_ACTIVITY) requireActivity().startActivity(intent) requireActivity().finish() } private suspend fun Resource.Failure<Nothing?>.signOutResult() { binding.SHOWPROGRESS.changeVisibility() Log.e(TAG, exception.message, exception.cause) } private suspend fun loading() { binding.SHOWPROGRESS.changeVisibility() } override fun onDestroyView() { super.onDestroyView() _binding = null } companion object { private const val SPLASH_ACTIVITY: String = "st.slex.messenger.splashscreen.SplashActivity" } }
1
Kotlin
0
0
8cb7aa0df9f90e57bbb9b096ef21c7c8ceb1a287
3,603
Messenger
Apache License 2.0
mqtt/src/main/kotlin/org/sheedon/mqtt/internal/connection/responsibility/UnSubscribePlan.kt
Sheedon
253,232,370
false
null
package org.sheedon.mqtt.internal.connection.responsibility import org.eclipse.paho.client.mqttv3.IMqttActionListener import org.eclipse.paho.client.mqttv3.IMqttToken import org.eclipse.paho.client.mqttv3.internal.wire.MqttSubscribe import org.sheedon.mqtt.* import org.sheedon.mqtt.internal.IDispatchManager import org.sheedon.mqtt.internal.connection.* import org.sheedon.mqtt.utils.Logger /** * 订阅职责环节 plan * @Author: sheedon * @Email: <EMAIL> * @Date: 2022/3/27 9:48 下午 */ class UnSubscribePlan( call: RealObservable, nextPlan: Plan? ) : RealPlan(call, nextPlan), IMqttActionListener { // 是否完成取消订阅 private var unSubscribed = false private var canceled = false private var subscribed = false /** * 流程执行,取消订阅 * */ override fun proceed() { val observable = call as RealObservable // 以Request继续调度流程 if (observable.originalRequest != null) { proceedRequest(observable) return } // 以Subscribe继续调度流程 if (observable.originalSubscribe != null) { proceedSubscribe(observable) return } throw IllegalAccessException("Not support by observable:$observable") } /** * 执行 RealObservable 中 持有Request 流程 */ private fun proceedRequest(observable: RealObservable) { val request = observable.originalRequest!! if (observable.isCanceled()) { Logger.info( "Dispatcher", "subscribePlan to cancel proceed by $request" ) return } Logger.info("Dispatcher", "subscribePlan to proceed by $request") val relation = request.relation val dispatcher = observable.dispatcher proceed(relation, dispatcher) } /** * 执行 RealObservable 中 持有Subscribe 流程 */ private fun proceedSubscribe(observable: RealObservable) { // subscribe 订阅数据 val subscribe = observable.originalSubscribe if (observable.isCanceled()) { Logger.info( "Dispatcher", "subscribePlan to cancel proceed by $subscribe" ) return } Logger.info("Dispatcher", "subscribePlan to proceed by $subscribe") val topicArray = subscribe?.run { Logger.info("Dispatcher", "subscribePlan to proceed by $this") // 关联者,得到主题集合 relations }?.mapNotNull { if (it.topics?.headers?.subscriptionType == SubscriptionType.REMOTE) { it.topics } else { null } } if (topicArray.isNullOrEmpty()) { super.proceed() return } // 取消订阅 val dispatcher = observable.dispatcher dispatcher.requestHandler().unsubscribe(*topicArray.toTypedArray(), listener = this) } /** * 根据「relation」和「dispatcher」调度流程 * * @param relation 关联对象,若存在订阅主题,并且订阅类型为远程订阅,则执行取消订阅mqtt流程 * @param dispatcher 调度管理者,执行请求行为 * */ private fun proceed(relation: Relation, dispatcher: IDispatchManager) { // 若不存在订阅主题,则直接调用下一个流程 // 否则,执行订阅操作 val topics = relation.topics if (topics?.topic.isNullOrEmpty() || topics?.headers?.subscriptionType == SubscriptionType.REMOTE ) { super.proceed() return } // 取消订阅主题 dispatcher.requestHandler().unsubscribe(relation.topics!!, listener = this) } /** * 取消「取消订阅」 */ override fun cancel() { if (unSubscribed) { realCancel() } super.cancel() } /** * 取消订阅成功 */ override fun onSuccess(asyncActionToken: IMqttToken?) { unSubscribed = true if (call.isCanceled()) { realCancel() return } // 回调成功订阅的反馈 if (call is RealObservable) { val callback = call.back if (callback is SubscribeBack) { val (topicArray, qosArray) = call.originalSubscribe?.getTopicArray() ?: Pair( arrayOf(), intArrayOf() ) callback.onResponse(MqttSubscribe(topicArray, qosArray)) } // 无需结果反馈,则不需要执行下一步 if (callback !is Callback && callback !is ObservableBack) { return } } // 若不需要取消,则执行下一步 super.proceed() } /** * 订阅失败 */ override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable?) { subscribe() if (call is RealObservable) { call.back?.onFailure(exception) } } /** * 订阅 RealObservable 所发起的请求行为 * * @param observable 真实的观察者对象,将内部的request/subscribe订阅 * */ private fun realCancel() { if (canceled) { return } canceled = true subscribe() } /** * 执行订阅,对于取消订阅的取消。在以下两种情况下执行调用, * 1.取消订阅失败,相对应的订阅主题取消。 * 2.执行取消(取消订阅),相对应的取消订阅主题取消。 */ private fun subscribe() { if (subscribed) return subscribed = true val observable = call as RealObservable // request 取消订阅行为 val request = observable.originalRequest if (request != null) { Logger.info("Dispatcher", "subscribePlan to cancel by $request") val relation = request.relation val dispatcher = observable.dispatcher dispatcher.requestHandler().subscribe(relation.topics!!) return } // subscribe 取消订阅行为 val subscribe = observable.originalSubscribe subscribe?.run { Logger.info("Dispatcher", "subscribePlan to cancel by $this") // 关联者,得到主题集合 relations }?.mapNotNull { it.topics }?.run { // 取消订阅 val dispatcher = observable.dispatcher dispatcher.requestHandler().subscribe(*this.toTypedArray()) } } }
0
null
3
6
82bfdf15b61f0cd08d3ff2f751e516d1116ce711
6,062
MqttDispatcher
Apache License 2.0
advent-of-code-2021/src/main/kotlin/eu/janvdb/aoc2021/day22/Day22.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2021.day22 import eu.janvdb.aocutil.kotlin.readLines import kotlin.math.max import kotlin.math.min const val FILENAME = "input22.txt" fun main() { val instructions = readLines(2021, FILENAME).map(Instruction::parse) part(instructions.filter { it.region.xMin>=-50 && it.region.xMax<=50 && it.region.yMin>=-50 && it.region.yMax<=50 && it.region.zMin>=-50 && it.region.zMax<=50}) part(instructions) } private fun part(instructions: List<Instruction>) { var currentRegion = CombinedRegion() instructions.forEach { currentRegion = currentRegion.apply(it) } println(currentRegion.volume) } data class Region(val xMin: Int, val xMax: Int, val yMin: Int, val yMax: Int, val zMin: Int, val zMax: Int) { val notEmpty get() = xMin <= xMax && yMin <= yMax && zMin <= zMax val volume get() = 1L * (xMax - xMin + 1) * (yMax - yMin + 1) * (zMax - zMin + 1) fun subtract(other: Region): Sequence<Region> { if (other.xMin > xMax || other.xMax < xMin || other.yMin > yMax || other.yMax < yMin || other.zMin > zMax || other.zMax < zMin) return sequenceOf(this) return sequenceOf( Region(xMin, other.xMin - 1, yMin, yMax, zMin, zMax), Region(other.xMax + 1, xMax, yMin, yMax, zMin, zMax), Region(max(other.xMin, xMin), min(other.xMax, xMax), yMin, other.yMin - 1, zMin, zMax), Region(max(other.xMin, xMin), min(other.xMax, xMax), other.yMax + 1, yMax, zMin, zMax), Region(max(other.xMin, xMin), min(other.xMax, xMax), max(other.yMin, yMin), min(other.yMax, yMax), zMin, other.zMin - 1), Region(max(other.xMin, xMin), min(other.xMax, xMax), max(other.yMin, yMin), min(other.yMax, yMax), other.zMax + 1, zMax), ).filter(Region::notEmpty) } fun subtract(others: List<Region>): List<Region> { var current = listOf(this) others.forEach { other -> current = current.flatMap { it.subtract(other) } } return current } } data class CombinedRegion(val regions: List<Region> = listOf()) { val volume get() = regions.map(Region::volume).sum() fun apply(instruction: Instruction): CombinedRegion { val newRegions = if (instruction.isAdd) regions + instruction.region.subtract(regions) else regions.flatMap { it.subtract(instruction.region) } return CombinedRegion(newRegions) } } class Instruction(val region: Region, val isAdd: Boolean) { companion object { val regex = Regex("(on|off) x=(-?\\d+)..(-?\\d+),y=(-?\\d+)..(-?\\d+),z=(-?\\d+)..(-?\\d+)") fun parse(line: String): Instruction { val matchResult = regex.matchEntire(line)!! return Instruction( Region( matchResult.groupValues[2].toInt(), matchResult.groupValues[3].toInt(), matchResult.groupValues[4].toInt(), matchResult.groupValues[5].toInt(), matchResult.groupValues[6].toInt(), matchResult.groupValues[7].toInt() ), isAdd = matchResult.groupValues[1] == "on" ) } } }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
2,840
advent-of-code
Apache License 2.0
src/main/kotlin/one/devos/nautical/softerpastels/common/blocks/GlassBlocks.kt
devOS-Sanity-Edition
564,647,059
false
{"Kotlin": 240112, "Java": 4177}
package one.devos.nautical.softerpastels.common.blocks import gay.asoji.innerpastels.register.registerBlockItem import gay.asoji.innerpastels.register.registerGlassBlock import gay.asoji.innerpastels.register.registerGlassPaneBlock import net.minecraft.world.item.BlockItem import net.minecraft.world.item.DyeColor import net.minecraft.world.level.block.Block import one.devos.nautical.softerpastels.SofterPastels object GlassBlocks { val WHITE_GLASS: Block = DyeColor.WHITE.registerGlassBlock(SofterPastels.MOD_ID, "white_glass") val WHITE_GLASS_PANE: Block = DyeColor.WHITE.registerGlassPaneBlock(SofterPastels.MOD_ID, "white_glass_pane") val WHITE_GLASS_ITEM: BlockItem = WHITE_GLASS.registerBlockItem(SofterPastels.MOD_ID, "white_glass") val WHITE_GLASS_PANE_ITEM: BlockItem = WHITE_GLASS_PANE.registerBlockItem(SofterPastels.MOD_ID, "white_glass_pane") val LIGHT_RED_GLASS: Block = DyeColor.PINK.registerGlassBlock(SofterPastels.MOD_ID, "light_red_glass") val LIGHT_RED_GLASS_PANE: Block = DyeColor.PINK.registerGlassPaneBlock(SofterPastels.MOD_ID, "light_red_glass_pane") val LIGHT_RED_GLASS_ITEM: BlockItem = LIGHT_RED_GLASS.registerBlockItem(SofterPastels.MOD_ID, "light_red_glass") val LIGHT_RED_GLASS_PANE_ITEM: BlockItem = LIGHT_RED_GLASS_PANE.registerBlockItem(SofterPastels.MOD_ID, "light_red_glass_pane") val RED_GLASS: Block = DyeColor.RED.registerGlassBlock(SofterPastels.MOD_ID, "red_glass") val RED_GLASS_PANE: Block = DyeColor.RED.registerGlassPaneBlock(SofterPastels.MOD_ID, "red_glass_pane") val RED_GLASS_ITEM: BlockItem = RED_GLASS.registerBlockItem(SofterPastels.MOD_ID, "red_glass") val RED_GLASS_PANE_ITEM: BlockItem = RED_GLASS_PANE.registerBlockItem(SofterPastels.MOD_ID, "red_glass_pane") val ORANGE_GLASS: Block = DyeColor.ORANGE.registerGlassBlock(SofterPastels.MOD_ID, "orange_glass") val ORANGE_GLASS_PANE: Block = DyeColor.ORANGE.registerGlassPaneBlock(SofterPastels.MOD_ID, "orange_glass_pane") val ORANGE_GLASS_ITEM: BlockItem = ORANGE_GLASS.registerBlockItem(SofterPastels.MOD_ID, "orange_glass") val ORANGE_GLASS_PANE_ITEM: BlockItem = ORANGE_GLASS_PANE.registerBlockItem(SofterPastels.MOD_ID, "orange_glass_pane") val YELLOW_GLASS: Block = DyeColor.YELLOW.registerGlassBlock(SofterPastels.MOD_ID, "yellow_glass") val YELLOW_GLASS_PANE: Block = DyeColor.YELLOW.registerGlassPaneBlock(SofterPastels.MOD_ID, "yellow_glass_pane") val YELLOW_GLASS_ITEM: BlockItem = YELLOW_GLASS.registerBlockItem(SofterPastels.MOD_ID, "yellow_glass") val YELLOW_GLASS_PANE_ITEM: BlockItem = YELLOW_GLASS_PANE.registerBlockItem(SofterPastels.MOD_ID, "yellow_glass_pane") val LIGHT_GREEN_GLASS: Block = DyeColor.LIME.registerGlassBlock(SofterPastels.MOD_ID, "light_green_glass") val LIGHT_GREEN_GLASS_PANE: Block = DyeColor.LIME.registerGlassPaneBlock(SofterPastels.MOD_ID, "light_green_glass_pane") val LIGHT_GREEN_GLASS_ITEM: BlockItem = LIGHT_GREEN_GLASS.registerBlockItem(SofterPastels.MOD_ID, "light_green_glass") val LIGHT_GREEN_GLASS_PANE_ITEM: BlockItem = LIGHT_GREEN_GLASS_PANE.registerBlockItem(SofterPastels.MOD_ID, "light_green_glass_pane") val GREEN_GLASS: Block = DyeColor.GREEN.registerGlassBlock(SofterPastels.MOD_ID, "green_glass") val GREEN_GLASS_PANE: Block = DyeColor.GREEN.registerGlassPaneBlock(SofterPastels.MOD_ID, "green_glass_pane") val GREEN_GLASS_ITEM: BlockItem = GREEN_GLASS.registerBlockItem(SofterPastels.MOD_ID, "green_glass") val GREEN_GLASS_PANE_ITEM: BlockItem = GREEN_GLASS_PANE.registerBlockItem(SofterPastels.MOD_ID, "green_glass_pane") val LIGHT_BLUE_GLASS: Block = DyeColor.LIGHT_BLUE.registerGlassBlock(SofterPastels.MOD_ID, "light_blue_glass") val LIGHT_BLUE_GLASS_PANE: Block = DyeColor.LIGHT_BLUE.registerGlassPaneBlock(SofterPastels.MOD_ID, "light_blue_glass_pane") val LIGHT_BLUE_GLASS_ITEM: BlockItem = LIGHT_BLUE_GLASS.registerBlockItem(SofterPastels.MOD_ID, "light_blue_glass") val LIGHT_BLUE_GLASS_PANE_ITEM: BlockItem = LIGHT_BLUE_GLASS_PANE.registerBlockItem(SofterPastels.MOD_ID, "light_blue_glass_pane") val BLUE_GLASS: Block = DyeColor.BLUE.registerGlassBlock(SofterPastels.MOD_ID, "blue_glass") val BLUE_GLASS_PANE: Block = DyeColor.BLUE.registerGlassPaneBlock(SofterPastels.MOD_ID, "blue_glass_pane") val BLUE_GLASS_ITEM: BlockItem = BLUE_GLASS.registerBlockItem(SofterPastels.MOD_ID, "blue_glass") val BLUE_GLASS_PANE_ITEM: BlockItem = BLUE_GLASS_PANE.registerBlockItem(SofterPastels.MOD_ID, "blue_glass_pane") val PURPLE_GLASS: Block = DyeColor.PURPLE.registerGlassBlock(SofterPastels.MOD_ID, "purple_glass") val PURPLE_GLASS_PANE: Block = DyeColor.PURPLE.registerGlassPaneBlock(SofterPastels.MOD_ID, "purple_glass_pane") val PURPLE_GLASS_ITEM: BlockItem = PURPLE_GLASS.registerBlockItem(SofterPastels.MOD_ID, "purple_glass") val PURPLE_GLASS_PANE_ITEM: BlockItem = PURPLE_GLASS_PANE.registerBlockItem(SofterPastels.MOD_ID, "purple_glass_pane") val MAGENTA_GLASS: Block = DyeColor.MAGENTA.registerGlassBlock(SofterPastels.MOD_ID, "magenta_glass") val MAGENTA_GLASS_PANE: Block = DyeColor.MAGENTA.registerGlassPaneBlock(SofterPastels.MOD_ID, "magenta_glass_pane") val MAGENTA_GLASS_ITEM: BlockItem = MAGENTA_GLASS.registerBlockItem(SofterPastels.MOD_ID, "magenta_glass") val MAGENTA_GLASS_PANE_ITEM: BlockItem = MAGENTA_GLASS_PANE.registerBlockItem(SofterPastels.MOD_ID, "magenta_glass_pane") val BROWN_GLASS: Block = DyeColor.BROWN.registerGlassBlock(SofterPastels.MOD_ID, "brown_glass") val BROWN_GLASS_PANE: Block = DyeColor.BROWN.registerGlassPaneBlock(SofterPastels.MOD_ID, "brown_glass_pane") val BROWN_GLASS_ITEM: BlockItem = BROWN_GLASS.registerBlockItem(SofterPastels.MOD_ID, "brown_glass") val BROWN_GLASS_PANE_ITEM: BlockItem = BROWN_GLASS_PANE.registerBlockItem(SofterPastels.MOD_ID, "brown_glass_pane") val BLACK_GLASS: Block = DyeColor.BLACK.registerGlassBlock(SofterPastels.MOD_ID, "black_glass") val BLACK_GLASS_PANE: Block = DyeColor.BLACK.registerGlassPaneBlock(SofterPastels.MOD_ID, "black_glass_pane") val BLACK_GLASS_ITEM: BlockItem = BLACK_GLASS.registerBlockItem(SofterPastels.MOD_ID, "black_glass") val BLACK_GLASS_PANE_ITEM: BlockItem = BLACK_GLASS_PANE.registerBlockItem(SofterPastels.MOD_ID, "black_glass_pane") val LIGHT_GRAY_GLASS: Block = DyeColor.LIGHT_GRAY.registerGlassBlock(SofterPastels.MOD_ID, "light_gray_glass") val LIGHT_GRAY_GLASS_PANE: Block = DyeColor.LIGHT_GRAY.registerGlassPaneBlock(SofterPastels.MOD_ID, "light_gray_glass_pane") val LIGHT_GRAY_GLASS_ITEM: BlockItem = LIGHT_GRAY_GLASS.registerBlockItem(SofterPastels.MOD_ID, "light_gray_glass") val LIGHT_GRAY_GLASS_PANE_ITEM: BlockItem = LIGHT_GRAY_GLASS_PANE.registerBlockItem(SofterPastels.MOD_ID, "light_gray_glass_pane") val GRAY_GLASS: Block = DyeColor.GRAY.registerGlassBlock(SofterPastels.MOD_ID, "gray_glass") val GRAY_GLASS_PANE: Block = DyeColor.GRAY.registerGlassPaneBlock(SofterPastels.MOD_ID, "gray_glass_pane") val GRAY_GLASS_ITEM: BlockItem = GRAY_GLASS.registerBlockItem(SofterPastels.MOD_ID, "gray_glass") val GRAY_GLASS_PANE_ITEM: BlockItem = GRAY_GLASS_PANE.registerBlockItem(SofterPastels.MOD_ID, "gray_glass_pane") fun init() {} }
0
Kotlin
3
3
975170cfc7eadfc30f3c5e0051f46cfec416aa45
7,285
SofterPastels
MIT License
src/main/kotlin/day10/Day10.kt
afTrolle
572,960,379
false
{"Kotlin": 33530}
package day10 import Day fun main() { Day10("Day10").solve() } class Day10(input: String) : Day<List<Int>>(input) { override fun parseInput(): List<Int> { return inputByLines.map { val (a, b) = (it.split(" ") + " ") a to b.toIntOrNull() }.flatMap { (action, num) -> when (action) { "noop" -> listOf(0) else -> listOf(0, num!!) } } } override fun part1(input: List<Int>): Any? { val register = input.runningFold(1) { acc: Int, i: Int -> acc + i } return listOf(20, 60, 100, 140, 180, 220).map { register[it - 1] * it }.sumOf { it } } override fun part2(input: List<Int>): String { val width = 40 val spritePos: List<Pair<Int, Boolean>> = input.runningFoldIndexed(1 to false) { index: Int, (acc: Int, _: Boolean), i: Int -> val crt = index % width val spirePosition = acc + i val sprite = (acc - 1)..(acc + 1) spirePosition to sprite.contains(crt) }.drop(1) return "\n" + spritePos.map { it.second }.chunked(width) .joinToString(System.lineSeparator()) { line -> line.joinToString("") { if (it) "#" else "." } } } }
0
Kotlin
0
0
4ddfb8f7427b8037dca78cbf7c6b57e2a9e50545
1,381
aoc-2022
Apache License 2.0
src/main/java/net/oxyopia/vice/features/bosses/ViceBoss.kt
Oxyopiia
689,119,282
false
{"Kotlin": 183841, "Java": 58982, "HTML": 7791}
package net.oxyopia.vice.features.bosses import net.oxyopia.vice.Vice import net.oxyopia.vice.events.BossBarEvents import net.oxyopia.vice.events.core.SubscribeEvent import net.oxyopia.vice.utils.DevUtils import net.oxyopia.vice.data.World import net.oxyopia.vice.utils.TimeUtils.formatTimer object ViceBoss : Boss( World.Vice, phaseTimesSec = listOf(5 * 60) ) { @SubscribeEvent override fun onBossBarModifyEvent(event: BossBarEvents.Override) { if (!Vice.config.BOSS_DESPAWN_TIMERS || !world.isInWorld()) return if (event.original.string.contains("VICE")) { if (lastKnownUUID != event.instance.uuid) { lastSpawned = System.currentTimeMillis() lastKnownUUID = event.instance.uuid DevUtils.sendDebugChat("&&9BOSS CHANGE &&rDetected Vice change", "BOSS_DETECTION_INFO") } val diff = System.currentTimeMillis() - lastSpawned val style = event.original.siblings.first().style.withObfuscated(false) val timer = diff.formatTimer(getPhaseTimeSec()) event.setReturnValue(event.original.copy().append(timer).setStyle(style)) lastBarUpdate = System.currentTimeMillis() } } override fun getPhaseTimeSec() = phaseTimesSec[0] }
6
Kotlin
1
1
37191353953b44915865e26675fb7a59807e55eb
1,166
ViceMod
MIT License
app/src/main/java/org/sil/storyproducer/service/SlideService.kt
chris-kalaam
313,961,445
true
{"Kotlin": 443947, "HTML": 194010, "Java": 70493, "Dockerfile": 1612, "Shell": 770}
package org.sil.storyproducer.service import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import org.sil.storyproducer.R import org.sil.storyproducer.model.PhaseType import org.sil.storyproducer.model.Story import org.sil.storyproducer.tools.file.getStoryChildInputStream class SlideService(val context: Context) { fun getImage(slideNum: Int, sampleSize: Int, story: Story): Bitmap { if (shouldShowDefaultImage(slideNum, story)) { return genDefaultImage() } else { return getImage(story.slides[slideNum].imageFile, sampleSize, false, story) } } fun shouldShowDefaultImage(slideNum: Int, story: Story): Boolean { return story.title.isNullOrEmpty() || story.slides.getOrNull(slideNum)?.imageFile.isNullOrEmpty() } fun getImage(relPath: String, sampleSize: Int = 1, useAllPixels: Boolean = false, story: Story): Bitmap { val iStream = getStoryChildInputStream(context, relPath, story.title) if (iStream === null || iStream.available() == 0) { return genDefaultImage() } val options = BitmapFactory.Options() options.inSampleSize = sampleSize if (useAllPixels) { options.inTargetDensity = 1 } val bmp = BitmapFactory.decodeStream(iStream, null, options)!! if (useAllPixels) { bmp.density = Bitmap.DENSITY_NONE } return bmp } fun genDefaultImage(): Bitmap { return BitmapFactory.decodeResource(context.resources, R.drawable.greybackground) } }
0
null
0
0
0ca086e0bbb37e3b19f5136e0b44e963dcaca97a
1,632
StoryProducer
MIT License
app/src/main/kotlin/ir/erfansn/nsmavpn/ui/util/preview/PreviewLightDarkLandscape.kt
erfansn
547,180,309
false
null
/* * Copyright 2022-2023 SOPT - Shout Our Passion Together * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sopt.stamp.util import androidx.compose.ui.tooling.preview.Preview @Preview( name = "phone", device = "spec:shape=Normal,width=360,height=800,unit=dp,dpi=480", showBackground = true, showSystemUi = true ) @Preview( name = "tablet", device = "spec:shape=Normal,width=1280,height=800,unit=dp,dpi=480", showBackground = true, showSystemUi = true ) annotation class MultiFormFactorPreviews
9
null
1
35
230181bfc03b19bd5bb52818ee0b8b19078a4ec1
1,055
NsmaVPN
Apache License 2.0
src/main/kotlin/org/example/yajic/DetailedToolResults.kt
mazhukinevgeniy
651,066,833
false
null
package org.example.yajic class DetailedToolResults { var compiledFiles: List<String> = emptyList() var errors = ArrayList<String>() }
6
Kotlin
0
0
a18d8dc08b4901abb97840420b83c6eba92ba31c
144
yajic
MIT License
cinescout/watchlist/data/remote/src/commonMain/kotlin/cinescout/watchlist/data/remote/sample/TraktScreenplayWatchlistMetadataBodySample.kt
fardavide
280,630,732
false
null
package cinescout.watchlist.data.remote.sample import cinescout.watchlist.data.remote.model.TraktMovieWatchlistMetadataBody import cinescout.watchlist.data.remote.model.TraktTvShowWatchlistMetadataBody import screenplay.data.remote.trakt.sample.TraktScreenplayMetadataBodySample object TraktScreenplayWatchlistMetadataBodySample { val BreakingBad = TraktTvShowWatchlistMetadataBody( tvShow = TraktScreenplayMetadataBodySample.BreakingBad ) val Dexter = TraktTvShowWatchlistMetadataBody( tvShow = TraktScreenplayMetadataBodySample.Dexter ) val Grimm = TraktTvShowWatchlistMetadataBody( tvShow = TraktScreenplayMetadataBodySample.Grimm ) val Inception = TraktMovieWatchlistMetadataBody( movie = TraktScreenplayMetadataBodySample.Inception ) val TheWolfOfWallStreet = TraktMovieWatchlistMetadataBody( movie = TraktScreenplayMetadataBodySample.TheWolfOfWallStreet ) val War = TraktMovieWatchlistMetadataBody( movie = TraktScreenplayMetadataBodySample.War ) }
8
Kotlin
2
6
dcbd0a0b70d6203a2ba1959b797038564d0f04c4
1,059
CineScout
Apache License 2.0
common-ui/src/main/java/com/lighthouse/android/common_ui/dialog/ErrorDialog.kt
soma-lighthouse
658,620,687
false
{"Kotlin": 444678}
package com.lighthouse.android.common_ui.dialog import android.content.Context import android.content.DialogInterface import androidx.appcompat.app.AlertDialog import com.lighthouse.android.common_ui.R fun showOKDialog( context: Context, title: String, message: String, negative: Boolean = true, positiveListener: DialogInterface.OnClickListener? = null, ) { val builder = AlertDialog.Builder(context) builder.setTitle(title) builder.setMessage(message) builder.setPositiveButton(R.string.ok, positiveListener) if (negative) { builder.setNegativeButton(R.string.cancel, null) } builder.show() }
0
Kotlin
0
0
f6c297f85086b6df358948a26aac563b79e543a7
653
FE-lingo-swap
Apache License 2.0
src/main/kotlin/com/lss233/minidb/engine/memory/internal/catalog/InheritsView.kt
lss233
535,925,912
false
null
package com.lss233.minidb.engine.memory.internal.catalog import com.lss233.minidb.engine.memory.Database import com.lss233.minidb.engine.schema.Column import miniDB.parser.ast.fragment.ddl.datatype.DataType class InheritsView(database: Database): PostgresCatalogView(database) { override fun getColumns(): MutableList<Column> = mutableListOf( Column("inhrelid", DataType.DataTypeName.INT), Column("inhparent", DataType.DataTypeName.CHAR), Column("inhseqno", DataType.DataTypeName.CHAR) ) override fun generateData(): MutableList<Array<Any>> = mutableListOf() }
1
null
3
12
8ab3d263e57c61a648856aae269b474201746294
607
MiniDB
MIT License
src/Day15_pt2.kt
jwklomp
572,195,432
false
null
import kotlin.math.abs import kotlin.math.max import kotlin.math.min fun main() { /** * Solution of part one with ranges is way too slow, would take in the order of 90 days, so need to start from scratch * Steps: * - for each of the lines between 0 and 4000000 (= y position): * - for each sensor-beacon combinations, calculate the interval on the line between 0 and 4000000 (x-from and x-t0), if any * - sort the intervals and merge them using the algorithm described here: * see https://scicomp.stackexchange.com/questions/26258/the-easiest-way-to-find-intersection-of-two-intervals * - In the result there should be 1 line, where the merged result is not 1 interval but 2 intervals with a gap of 1 * This gap is the distress signal position. Frequency = x-pos * 4000000 + y-pos */ fun part2(input: List<String>) { val maxCoordinate = if (input.size == 14) 20 else 4000000 val readings = makeReadings(input) (0..maxCoordinate).toList() .forEach { y -> val intervals = readings.mapNotNull { reading -> val mdBeaconSensor = manhattanDistance(reading.sensor, reading.beacon) val distance = abs(y - reading.sensor.y) - mdBeaconSensor // negative when useful if (distance <= 0) return@mapNotNull Interval( from = reading.sensor.x + distance, to = reading.sensor.x - distance ) else return@mapNotNull null } val mergedIntervals = mergeIntervals(intervals) val intervalsInRange = mergedIntervals .filter { interval -> interval.from <= maxCoordinate && interval.to >= 0 } .map { interval -> Interval(from = max(interval.from, 0), to = min(interval.to, maxCoordinate)) } if (intervalsInRange.size > 1) { val x = intervalsInRange[0].to + 1 val frequency: Long = (x * 4000000L) + y println("frequency: $frequency") // 12525726647448 } } } //val testInput = readInput("Day15_test") //part2(testInput) val input = readInput("Day15") part2(input) }
0
Kotlin
0
0
b0a8f39680318a2e0ad1c720a080b83499b09394
2,320
aoc-2022-in-kotlin
Apache License 2.0
android/src/main/java/com/reactnativeaudiowaveform/audio/recorder/writer/NoiseRecordWriter.kt
Krunal-K-SimformSolutions
436,591,065
false
null
package com.reactnativeaudiowaveform.audio.recorder.writer import android.media.AudioRecord import com.reactnativeaudiowaveform.audio.recorder.chunk.AudioChunk import com.reactnativeaudiowaveform.audio.recorder.chunk.ShortArrayAudioChunk import com.reactnativeaudiowaveform.audio.recorder.constants.AudioConstants import com.reactnativeaudiowaveform.audio.recorder.extensions.checkChunkAvailable import com.reactnativeaudiowaveform.audio.recorder.extensions.runOnUiThread import com.reactnativeaudiowaveform.audio.recorder.listener.OnSilentDetectedListener import com.reactnativeaudiowaveform.audio.recorder.source.AudioSource import com.reactnativeaudiowaveform.audio.recorder.source.DefaultAudioSource import java.io.OutputStream /** * Default settings + NoiseSuppressor of [RecordWriter] */ open class NoiseRecordWriter(audioSource: AudioSource = DefaultAudioSource()) : DefaultRecordWriter(audioSource) { private var firstSilenceMoment: Long = 0 private var noiseRecordedAfterFirstSilenceThreshold = 0 private var silentDetectedListener: OnSilentDetectedListener? = null /** * see [DefaultRecordWriter.write] */ override fun write(audioRecord: AudioRecord, bufferSize: Int, outputStream: OutputStream) { val audioChunk = ShortArrayAudioChunk(ShortArray(bufferSize)) while (getAudioSource().isRecordAvailable()) { val shorts = audioChunk.shorts audioChunk.setReadCount(audioRecord.read(shorts, 0, shorts.size)) if (!audioChunk.checkChunkAvailable()) continue runOnUiThread { chunkAvailableListener?.onChunkAvailable(audioChunk) } if (audioChunk.findFirstIndex() > -1) { outputStream.write(audioChunk.toByteArray()) firstSilenceMoment = 0 noiseRecordedAfterFirstSilenceThreshold++ } else { processSilentTime(audioChunk, outputStream) } } } /** * set [OnSilentDetectedListener] to get silent time */ fun setOnSilentDetectedListener(listener: OnSilentDetectedListener?) = this.apply { silentDetectedListener = listener } private fun processSilentTime(audioChunk: AudioChunk, outputStream: OutputStream) { if (firstSilenceMoment == 0L) firstSilenceMoment = System.currentTimeMillis() val silentTime = System.currentTimeMillis() - firstSilenceMoment if (firstSilenceMoment != 0L && silentTime > AudioConstants.SILENCE_THRESHOLD) { if (silentTime > 1000L && noiseRecordedAfterFirstSilenceThreshold >= 3) { noiseRecordedAfterFirstSilenceThreshold = 0 runOnUiThread { silentDetectedListener?.onSilence(silentTime) } } } else { outputStream.write(audioChunk.toByteArray()) } } }
0
Kotlin
1
1
f9dcec02ed302148253c5da50b7d1e3c75ae66ce
2,834
react-native-audio-waveform
MIT License
app/src/main/java/com/example/webtoon/Activities/LoginActivity.kt
gokkutamu
659,536,266
false
null
package com.example.webtoon.Activities import androidx.appcompat.app.AppCompatActivity class LoginActivity : AppCompatActivity() { }
0
Kotlin
0
0
76fc4064a1774f1387521b10160d55337cd31006
134
android_webtoon
Apache License 2.0