path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/main/kotlin/day13/day13.kt
corneil
572,437,852
false
{"Kotlin": 93311, "Shell": 595}
package day13 import utils.groupLines import utils.readFile import utils.readLines import utils.separator import java.util.* fun main() { val test = readLines( """[1,1,3,1,1] [1,1,5,1,1] [[1],[2,3,4]] [[1],4] [9] [[8,7,6]] [[4,4],4,4] [[4,4],4,4,4] [7,7,7,7] [7,7,7] [] [3] [[[]]] [[]] [1,[2,[3,[4,[5,6,7]]]],8,9] [1,[2,[3,[4,[5,6,0]]]],8,9] """.trimIndent() ) val input = readFile("day13") abstract class Item data class Value(val value: Int) : Item() { fun compareTo(right: Value): Int { return value.compareTo(right.value) } override fun toString(): String { return value.toString() } } data class Packet(val items: List<Item>) : Item(), List<Item> by items { constructor(value: Item) : this(listOf(value)) {} } fun parsePacket(input: String): Packet { val value = StringBuilder() var list: MutableList<Item> = mutableListOf() fun checkAdd() { if (value.isNotBlank()) { list.add(Value(value.toString().toInt())) } value.clear() } val lists = Stack<List<Item>>() var index = 1 // skip first [ while (index < input.lastIndex) { when (val c = input[index]) { ',', ' ' -> checkAdd() '[' -> { lists.push(list) list = mutableListOf() } ']' -> { checkAdd() val v = list list = lists.pop().toMutableList() list.add(Packet(v)) } '-' -> value.append('-') '+' -> value.append('+') else -> { if (c.isDigit()) { value.append(c) } else { error("Unexpected $c") } } } index += 1 } checkAdd() return Packet(list.toList()) } fun Packet.compareTo(right: Packet): Int { var result = 0 for (index in indices) { val item = this[index] val rightItem = right.getOrNull(index) result = when { rightItem == null -> 1 item is Value && rightItem is Value -> item.compareTo(rightItem) item is Packet && rightItem is Value -> item.compareTo(Packet(rightItem)) item is Packet && rightItem is Packet -> item.compareTo(rightItem) item is Value && rightItem is Packet -> Packet(item).compareTo(rightItem) else -> 1 } if (result != 0) { break } } if (result == 0 && size < right.size) { result = -1 } return result } fun Item.isOrdered(right: Item?): Int { return when { right == null -> 1 this is Value && right is Value -> compareTo(right) this is Packet && right is Packet -> this.compareTo(right) this is Packet && right is Value -> this.compareTo(Packet(right)) this is Value && right is Packet -> Packet(this).compareTo(right) else -> 1 } } fun isIndexOrdered(index: Int, input: List<String>): Boolean { check(input.size == 2) val (left, right) = input.map { parsePacket(it) } var result = 0 for (index in left.indices) { val item = left[index] val rightItem = if (index <= right.lastIndex) right[index] else null result = item.isOrdered(rightItem) if (result != 0) { break } } val ordered = result <= 0 if (result == 0) { println("Pair $index: was the same") } else if (result < 0) { println("Pair $index: left was lower") } return ordered } fun calcSolution1(input: List<List<String>>): Int { return input.mapIndexedNotNull { index, inputs -> if (isIndexOrdered(index, inputs)) index + 1 else null }.sum() } fun calcSolution2(input: List<String>): Int { val extra1 = "[[2]]" val extra2 = "[[6]]" val packets = input.filter { it.isNotBlank() }.toMutableList() packets.add(extra1) packets.add(extra2) val sorted = packets.map { it to parsePacket(it) } .sortedWith { o1, o2 -> o1.second.compareTo(o2.second) } .map { it.first } val index1 = sorted.indexOf(extra1) + 1 val index2 = sorted.indexOf(extra2) + 1 return index1 * index2 } fun part1() { val testResult = calcSolution1(groupLines(test)) println("Part 1 Test Answer = $testResult") check(testResult == 13) separator() val result = calcSolution1(groupLines(input)) println("Part 1 Answer = $result") check(result == 4643) } fun part2() { val testResult = calcSolution2(test) println("Part 2 Test Answer = $testResult") check(testResult == 140) separator() val result = calcSolution2(input) println("Part 2 Answer = $result") check(result == 21614) } println("Day - 13") part1() separator() part2() }
0
Kotlin
0
0
dd79aed1ecc65654cdaa9bc419d44043aee244b2
4,854
aoc-2022-in-kotlin
Apache License 2.0
app/src/main/java/com/kusamaru/standroid/nicolive/compose/JCNicoLiveInfoFragment.kt
kusamaru
442,642,043
false
{"Kotlin": 1954774}
package com.kusamaru.standroid.nicolive.compose import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.material.Surface import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Modifier import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.core.net.toUri import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import com.kusamaru.standroid.MainActivity import com.kusamaru.standroid.R import com.kusamaru.standroid.nicoad.NicoAdBottomFragment import com.kusamaru.standroid.nicolive.bottomfragment.NicoLiveGiftBottomFragment import com.kusamaru.standroid.nicolive.bottomfragment.NicoLiveKonomiTagEditBottomFragment import com.kusamaru.standroid.nicolive.bottomfragment.NicoLiveTagBottomFragment import com.kusamaru.standroid.nicolive.viewmodel.NicoLiveViewModel import com.kusamaru.standroid.nicovideo.NicoAccountFragment import com.kusamaru.standroid.nicovideo.compose.DarkColors import com.kusamaru.standroid.nicovideo.compose.LightColors import com.kusamaru.standroid.nicovideo.compose.NicoVideoUserCard import com.kusamaru.standroid.tool.NicoVideoDescriptionText import com.kusamaru.standroid.tool.isDarkMode /** * 番組詳細Fragment * */ class JCNicoLiveInfoFragment : Fragment() { /** ViewModel */ private val viewModel by viewModels<NicoLiveViewModel>({ requireParentFragment() }) override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return ComposeView(requireContext()).apply { setContent { MaterialTheme( colors = if (isDarkMode(LocalContext.current)) DarkColors else LightColors, ) { // 番組情報 val programData = viewModel.nicoLiveProgramData.observeAsState() // 説明文 val description = viewModel.nicoLiveProgramDescriptionLiveData.observeAsState() // ユーザー情報 val userData = viewModel.nicoLiveUserDataLiveData.observeAsState() // コミュ、チャンネル情報 val communityOrChannelData = viewModel.nicoLiveCommunityOrChannelDataLiveData.observeAsState() // コミュ、チャンネルフォロー中か val isCommunityOrChannelFollow = viewModel.isCommunityOrChannelFollowLiveData.observeAsState(initial = false) // タグ val tagData = viewModel.nicoLiveTagDataListLiveData.observeAsState() // 好みタグ val konomiTagList = viewModel.nicoLiveKonomiTagListLiveData.observeAsState(initial = arrayListOf()) // 統計情報LiveData val statisticsLiveData = viewModel.statisticsLiveData.observeAsState() // タイムシフト予約済みかどうか(なお予約済みかどうかはAPIを叩くまでわからん) val isRegisteredTimeShift = viewModel.isTimeShiftRegisteredLiveData.observeAsState(initial = false) // タイムシフト予約が可能かどうか val isAllowTSRegister = viewModel.isAllowTSRegister.observeAsState(initial = true) // コメント一覧表示中か val isVisibleCommentList = viewModel.commentListShowLiveData.observeAsState(initial = false) Surface { Scaffold { /** コメント一覧表示中は情報表示させても意味ないので消す? */ if (!isVisibleCommentList.value) { /** スクロールできるColumn。LazyColumnがサイズ変わったときになんかおかしくなる */ Column(modifier = Modifier.verticalScroll(rememberScrollState())) { // 番組情報 if (programData.value != null && description.value != null) { NicoLiveInfoCard( nicoLiveProgramData = programData.value!!, programDescription = description.value!!, isRegisteredTimeShift = isRegisteredTimeShift.value, isAllowTSRegister = isAllowTSRegister.value!!, onClickTimeShift = { registerTimeShift() }, descriptionClick = { link, type -> if (type == NicoVideoDescriptionText.DESCRIPTION_TYPE_URL) { val intent = Intent(Intent.ACTION_VIEW, link.toUri()) startActivity(intent) } } ) } // ユーザー情報。ニコ動用のがそのまま使えた if (userData.value != null) { NicoVideoUserCard(userData = userData.value!!, onUserOpenClick = { setAccountFragment(userData.value!!.userId) }) } // コミュ、番組情報 if (communityOrChannelData.value != null) { NicoLiveCommunityCard( communityOrChannelData = communityOrChannelData.value!!, isFollow = isCommunityOrChannelFollow.value, onFollowClick = { if (isCommunityOrChannelFollow.value) { // 解除 requestRemoveCommunityFollow(communityOrChannelData.value!!.id) } else { // コミュをフォローする requestCommunityFollow(communityOrChannelData.value!!.id) } }, onCommunityOpenClick = { launchBrowser("https://com.nicovideo.jp/community/${communityOrChannelData.value!!.id}") } ) } // タグ if (tagData.value != null) { NicoLiveTagCard( tagItemDataList = tagData.value!!.tagList, onClickTag = { openBrowser("https://live.nicovideo.jp/search?keyword=${it.tagName}&isTagSearch=true") }, isEditable = !tagData.value!!.isLocked, onClickEditButton = { showTagEditBottomFragment() }, onClickNicoPediaButton = { openBrowser(it) } ) } // 好みタグ NicoLiveKonomiCard(konomiTagList = konomiTagList.value, onClickEditButton = { showKonomiTagEditBottomFragment() }) // メニュー NicoLiveMenuScreen(requireParentFragment()) if (statisticsLiveData.value != null) { // ニコニ広告 投げ銭 NicoLivePointCard( totalNicoAdPoint = statisticsLiveData.value!!.adPoints, totalGiftPoint = statisticsLiveData.value!!.giftPoints, onClickNicoAdOpen = { showNicoAdBottomFragment() }, onClickGiftOpen = { showGiftBottomFragment() } ) } // スペース Spacer(modifier = Modifier.height(100.dp)) } } } } } } } } /** 好みタグの編集画面を出す。*/ private fun showKonomiTagEditBottomFragment() { NicoLiveKonomiTagEditBottomFragment().apply { arguments = Bundle().apply { putString("broadcaster_user_id", viewModel.nicoLiveUserDataLiveData.value?.userId) } }.show(parentFragmentManager, "konomi_tag") } /** * ブラウザを開く * @param url リンク * */ private fun openBrowser(url: String) { Intent(Intent.ACTION_VIEW, url.toUri()).apply { startActivity(this) } } /** 投げ銭のBottomFragment表示 */ private fun showGiftBottomFragment() { NicoLiveGiftBottomFragment().apply { arguments = Bundle().apply { putString("live_id", viewModel.nicoLiveProgramData.value?.programId) } }.show(parentFragmentManager, "gift") } /** ニコニ広告BottomFragmentを表示させる */ private fun showNicoAdBottomFragment() { NicoAdBottomFragment().apply { arguments = Bundle().apply { putString("content_id", viewModel.nicoLiveProgramData.value?.programId) } }.show(parentFragmentManager, "nicoad") } /** タグ編集画面を出す */ private fun showTagEditBottomFragment() { NicoLiveTagBottomFragment().show(parentFragmentManager, "edit_tag") } /** * ブラウザを開く * @param url うらる。 * */ private fun launchBrowser(url: String) { val intent = Intent(Intent.ACTION_VIEW, url.toUri()) startActivity(intent) } /** * アカウント情報Fragmentを表示 * @param userId ゆーざーID * */ private fun setAccountFragment(userId: String) { val accountFragment = NicoAccountFragment().apply { arguments = Bundle().apply { putString("userId", userId) } } setFragment(accountFragment, "account") } /** * Fragmentを置く関数 * * @param fragment 置くFragment * @param backstack Fragmentを積み上げる場合は適当な値を入れて * */ private fun setFragment(fragment: Fragment, backstack: String) { // Fragment設置 (requireActivity() as MainActivity).setFragment(fragment, backstack, true) // ミニプレイヤー化 viewModel.isMiniPlayerMode.postValue(true) } /** コミュをフォローする関数 */ private fun requestCommunityFollow(communityId: String) { (requireParentFragment() as? JCNicoLiveFragment)?.showSnackBar(getString(R.string.nicovideo_account_follow_message_message), getString(R.string.follow_count)) { viewModel.requestCommunityFollow(communityId) } } /** コミュのフォローを解除する関数 */ private fun requestRemoveCommunityFollow(communityId: String) { (requireParentFragment() as? JCNicoLiveFragment)?.showSnackBar(getString(R.string.nicovideo_account_remove_follow_message), getString(R.string.nicovideo_account_remove_follow)) { viewModel.requestRemoveCommunityFollow(communityId) } } /** TS予約、解除を行う関数 */ fun registerTimeShift() { val isRegisteredTS = viewModel.isTimeShiftRegisteredLiveData.value ?: false val message = if (isRegisteredTS) getString(R.string.nicolive_time_shift_un_register_message) else getString(R.string.nicolive_time_shift_register_message) val action = if (isRegisteredTS) getString(R.string.nicolive_time_shift_un_register_short) else getString(R.string.nicolive_time_shift_register_short) (requireParentFragment() as JCNicoLiveFragment).showSnackBar(message, action) { if (isRegisteredTS) { // 登録解除APIを叩く viewModel.unRegisterTimeShift() } else { // 登録APIを叩く viewModel.registerTimeShift() } } } }
0
Kotlin
0
3
5c58707eecc7a994fbd4bc900b22106697bf3806
12,863
StanDroid
Apache License 2.0
yasha-compose/src/main/java/zlc/season/yasha/compose/ComposeDataSource.kt
ssseasonnn
135,985,766
false
{"Kotlin": 84640}
package zlc.season.yasha.compose import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.onSubscription import kotlinx.coroutines.flow.update import zlc.season.sange.datasource.DataSource import zlc.season.sange.datasource.FetchState open class ComposeDataSource( coroutineScope: CoroutineScope, invalidate: Boolean = true, private val enableDefaultState: Boolean = false ) : DataSource<ComposeItem>(coroutineScope) { private val loadAround: (Int) -> Unit = { dispatchLoadAround(it) } private val _dataFlow = MutableStateFlow<List<ComposeItem>>(emptyList()) val dataFlow = _dataFlow.onSubscription { if (invalidate) { invalidate(false) } } override fun notifySubmitList(submitNow: Boolean) { _dataFlow.update { DataList(toList(), loadAround) } } override fun onFetchStateChanged(newState: FetchState) { if (enableDefaultState) { setState(ComposeStateItem(newState, ::retry)) } } }
5
Kotlin
55
520
96db2547a1d071b83a7c183bb97656c3322bd5e4
1,077
Yasha
Apache License 2.0
app/src/main/java/ru/sshex/exchange/di/app/module/NetworkModule.kt
ShadyRover
182,038,832
false
null
package ru.sshex.exchange.di.app.module import dagger.Module import dagger.Provides import dagger.Reusable import io.reactivex.schedulers.Schedulers import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import ru.sshex.exchange.network.Api @Module object NetworkModule { private const val BASE_URL = "https://revolut.duckdns.org/" /** * Provides the Post service implementation. * @param retrofit the Retrofit object used to instantiate the service * @return the Post service implementation. */ @Provides @Reusable @JvmStatic internal fun providePostApi(retrofit: Retrofit): Api { return retrofit.create(Api::class.java) } /** * Provides the Retrofit object. * @return the Retrofit object */ @Provides @Reusable @JvmStatic internal fun provideRetrofitInterface(): Retrofit { return Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io())) .build() } }
0
Kotlin
0
0
d050e45e413ea60057f3103bf249603b51b8cebe
1,209
Exchange
Apache License 2.0
app/src/main/java/edu/uw/acevedoj/sos/WelcomeActivity.kt
amjadz
161,661,449
false
{"Kotlin": 63090}
package edu.uw.acevedoj.sos import android.content.Intent import android.content.pm.PackageManager import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.preference.PreferenceManager import android.support.v4.app.ActivityCompat import android.support.v4.content.ContextCompat import android.widget.TextView class WelcomeActivity : AppCompatActivity() { private val MY_PERMISSIONS_REQUEST_CALL_PHONE = 4 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_welcome) val button = findViewById<TextView>(R.id.welcome_next) checkForCallPermission() button.setOnClickListener { val intent = Intent(this, WelcomeSettingActivity::class.java) startActivity(intent) } } // Sees if this is the first time the user has started the app // if it isn't activity won't be shown. override fun onStart() { super.onStart() val prefs = PreferenceManager.getDefaultSharedPreferences(this) if (!prefs.getBoolean("first_launch", true)) { val intent = Intent(this, MainActivity::class.java) startActivity(intent) } } // Sets the permissions at runtime private fun checkForCallPermission() { if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) { if(ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.CALL_PHONE)){ } else { ActivityCompat.requestPermissions( this, arrayOf(android.Manifest.permission.CALL_PHONE, android.Manifest.permission.SEND_SMS, android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION), MY_PERMISSIONS_REQUEST_CALL_PHONE ) } } } }
0
Kotlin
0
0
b6092a1083f856828a20347f1543b8fc26f6a938
2,002
SOS
MIT License
src/main/kotlin/io/github/riej/lsl/KwdbData.kt
riej
597,798,011
false
{"Kotlin": 199607, "Java": 199569, "ANTLR": 5887, "Lex": 3385, "HTML": 90}
package io.github.riej.lsl import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.vfs.VfsUtil import com.intellij.psi.PsiManager import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.xml.XmlFile import com.intellij.psi.xml.XmlTag import com.intellij.util.ResourceUtil import com.intellij.xml.util.XmlUtil import io.github.riej.lsl.psi.* import io.github.riej.lsl.scope.LslScope class KwdbData(project: Project) { val data: XmlFile val lang = "en" val generated: LslFile val functions: Map<String, LslFunction> val constants: Map<String, LslGlobalVariable> val events: Map<String, LslEvent> val scope: LslScope companion object { val KWDB_DATA_KEY = Key.create<KwdbData>("KWDB_DATA") fun getInstance(project: Project): KwdbData = project.getUserData(KWDB_DATA_KEY) ?: let { val data = KwdbData(project) project.putUserData(KWDB_DATA_KEY, data) data } } init { val resource = ResourceUtil.getResource(javaClass.classLoader, ".", "kwdb.xml") val file = VfsUtil.findFileByURL(resource) data = PsiManager.getInstance(project).findFile(file!!) as XmlFile generated = LslElementFactory.createFile(project, generateSource()) functions = generated.children.filterIsInstance<LslFunction>().associateBy { it.name!! } constants = generated.children.filterIsInstance<LslGlobalVariable>().associateBy { it.name!! } events = PsiTreeUtil.collectElementsOfType(generated, LslEvent::class.java).associateBy { it.name!! } scope = LslScope(null, emptyList<LslNamedElement>().plus(constants.values).plus(functions.values)) } fun commentDescription(description: String): String = description.trim().split('\n').filter { it != "<!-- TODO: add documentation -->" } .joinToString("\n") { "// $it" } fun isSLGrid(tag: XmlTag): Boolean = (tag.getAttributeValue("grid") ?: "sl").split(' ').contains("sl") /** * Generates LSL source code for KWDB file. * All descriptions will be put as comments before declaration. */ fun generateSource(): String { val sb = StringBuilder() val subtags = data.rootTag?.subTags?.filter { isSLGrid(it) } subtags?.forEach { tag -> when (tag.name) { "constant" -> let { tag.findSubTags("description").forEach { description -> sb.append("${commentDescription(description.value.text)}\n") } val type = tag.getAttributeValue("type") val value = when (type) { "string", "key" -> "\"${tag.getAttributeValue("value")}\"" "vector", "rotation", "quaternion" -> XmlUtil.unescape(tag.getAttributeValue("value") ?: "") else -> tag.getAttributeValue("value") } sb.append("$type ${tag.getAttributeValue("name")} = $value;\n") } "function" -> let { tag.findSubTags("description").forEach { description -> sb.append("${commentDescription(description.value.text)}\n") } val type = tag.getAttributeValue("type") if (type != null) { sb.append("$type ") } sb.append("${tag.getAttributeValue("name")}(") tag.findSubTags("param").forEachIndexed { index, param -> if (index != 0) { sb.append(", ") } sb.append("${param.getAttributeValue("type")} ${param.getAttributeValue("name")}") } sb.append(") {}\n") } } } sb.append("default {\n") subtags?.filter { it.name == "event" }?.forEach { tag -> tag.findSubTags("description").forEach { description -> sb.append(" ${commentDescription(description.value.text)}\n") } sb.append(" ${tag.getAttributeValue("name")} (") tag.findSubTags("param").forEachIndexed { index, param -> if (index != 0) { sb.append(", ") } sb.append("${param.getAttributeValue("type")} ${param.getAttributeValue("name")}") } sb.append(") {}\n") } sb.append("}\n") return sb.toString() } }
2
Kotlin
1
2
0720929467d598d866c27ca016cb7e9f2733ab1d
4,694
lsl
MIT License
network/src/main/java/androidx/essentials/network/Builder.kt
kunal26das
282,238,393
false
null
package androidx.essentials.network @Suppress("PropertyName") abstract class Builder<T> { @Volatile private var value: Any? = UninitializedValue val INSTANCE: T @Suppress("UNCHECKED_CAST") get() { val v1 = value if (v1 !== UninitializedValue) { return v1 as T } return synchronized(this) { val v2 = value if (v2 !== UninitializedValue) { v2 as T } else { val typedValue = initialize() value = typedValue typedValue } } } protected abstract fun initialize(): T }
5
Kotlin
0
3
4968a43c341f728c905d3db7a124fd8b6e05041a
718
androidx-essentials
Apache License 2.0
app/src/main/java/com/onlinemadrasa/model/StoryModel.kt
samsadch
282,285,809
false
{"Kotlin": 104434, "Java": 48689, "CMake": 1745, "Rich Text Format": 400, "C++": 2}
package com.onlinemadrasa.model import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize data class StoryModel( var storyTitle: String = "", var storyList: List<StoryItem>? = null, var createdDate: String = "", var updatedDate: String = "", var refrence: String? = "", var refrences: List<String>? = null ) : Parcelable @Parcelize data class StoryItem( var title: String = "", var partTitle: String? = "", var content: String = "", var addedDate: String = "" ) : Parcelable
0
Kotlin
0
0
08832f4e322133fd0102349cb8a8752376b89e0e
539
OnlineMadrasa
Apache License 2.0
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/editor/headers/RequestHeadersDialogState.kt
Waboodoo
34,525,124
false
{"Kotlin": 1970466, "HTML": 200869, "CSS": 2316, "Python": 1548}
package ch.rmy.android.http_shortcuts.activities.editor.headers import androidx.compose.runtime.Stable @Stable sealed class RequestHeadersDialogState { @Stable data object AddHeader : RequestHeadersDialogState() @Stable data class EditHeader( val id: String, val key: String, val value: String, ) : RequestHeadersDialogState() }
31
Kotlin
105
999
34ec1652d431d581c3c275335eb4dbcf24ced9f5
376
HTTP-Shortcuts
MIT License
modern-treasury-kotlin-core/src/test/kotlin/com/moderntreasury/api/models/AsyncResponseTest.kt
Modern-Treasury
665,762,762
false
{"Kotlin": 8612635, "Shell": 3666, "Dockerfile": 399}
package com.moderntreasury.api.models import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class AsyncResponseTest { @Test fun createAsyncResponse() { val asyncResponse = AsyncResponse.builder() .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .object_("string") .build() assertThat(asyncResponse).isNotNull assertThat(asyncResponse.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(asyncResponse.object_()).isEqualTo("string") } }
1
Kotlin
2
2
37b7af4a5ae3088434ceca856942b20619b57f82
582
modern-treasury-kotlin
MIT License
MyJetPackApplication/businesses/business-video/src/alone/java/com/example/myjetpackapplication/business/video/SingleVideoItemAdapter.kt
seelikes
154,868,585
false
{"Markdown": 4, "Batchfile": 11, "Ignore List": 58, "JSON": 5, "Text": 1, "Gradle": 72, "reStructuredText": 1, "Java Properties": 14, "Shell": 8, "Proguard": 42, "Java": 57, "XML": 265, "INI": 29, "Kotlin": 311, "C++": 1, "CMake": 1, "Groovy": 26, "Fluent": 40, "FreeMarker": 11}
package com.example.myjetpackapplication.business.video import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import com.example.myjetpackapplication.annotationprocessor.business.annotation.BusinessItem import com.example.myjetpackapplication.business.video.databinding.ItemSingleVideoBinding import com.github.seelikes.android.mvvm.basic.BasicRecyclerAdapter import java.lang.ref.WeakReference /** * Created by liutiantian on 2019-12-22 22:04 星期日 */ class SingleVideoItemAdapter( context: Context, items: List<BusinessItem>?, itemClickListener: (BusinessItem?, Int) -> Unit ) : BasicRecyclerAdapter<BusinessItem, SingleVideoItemHolder>( context, items, itemClickListener ) { override fun onCreateViewHolder(view: ViewGroup, itemType: Int): SingleVideoItemHolder = SingleVideoItemHolder(WeakReference(context), ItemSingleVideoBinding.inflate(LayoutInflater.from(context))) }
1
null
1
1
7b3bc00c2e98f11b0798a97474a28fb63c0b53ae
956
MyAndroidSet
MIT License
android/libraries/rib-coroutines/src/main/kotlin/com/uber/rib/core/RibCoroutineScopes.kt
uber
105,686,726
false
null
/* * Copyright (C) 2022. Uber Technologies * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.uber.rib.core import android.app.Application import com.uber.autodispose.ScopeProvider import com.uber.autodispose.coroutinesinterop.asCoroutineScope import java.util.WeakHashMap import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext import kotlin.reflect.KProperty import kotlinx.coroutines.CoroutineName import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.job /** * [CoroutineScope] tied to this [ScopeProvider]. This scope will be canceled when ScopeProvider is * completed * * This scope is bound to * [RibDispatchers.Main.immediate][kotlinx.coroutines.MainCoroutineDispatcher.immediate] */ public val ScopeProvider.coroutineScope: CoroutineScope by LazyCoroutineScope<ScopeProvider> { val context: CoroutineContext = SupervisorJob() + RibDispatchers.Main.immediate + CoroutineName("${this::class.simpleName}:coroutineScope") + (RibCoroutinesConfig.exceptionHandler ?: EmptyCoroutineContext) asCoroutineScope(context) } /** * [CoroutineScope] tied to this [Application]. This scope will not be cancelled, it lives for the * full application process. * * This scope is bound to * [RibDispatchers.Main.immediate][kotlinx.coroutines.MainCoroutineDispatcher.immediate] */ public val Application.coroutineScope: CoroutineScope by LazyCoroutineScope<Application> { val context: CoroutineContext = SupervisorJob() + RibDispatchers.Main.immediate + CoroutineName("${this::class.simpleName}:coroutineScope") + (RibCoroutinesConfig.exceptionHandler ?: EmptyCoroutineContext) CoroutineScope(context) } internal class LazyCoroutineScope<This : Any>(val initializer: This.() -> CoroutineScope) { companion object { private val values = WeakHashMap<Any, CoroutineScope>() // Used to get and set Test overrides from rib-coroutines-test utils operator fun get(provider: Any) = values[provider] operator fun set(provider: Any, scope: CoroutineScope?) { values[provider] = scope } } operator fun getValue(thisRef: This, property: KProperty<*>): CoroutineScope = synchronized(LazyCoroutineScope) { return values.getOrPut(thisRef) { thisRef.initializer().apply { coroutineContext.job.invokeOnCompletion { synchronized(LazyCoroutineScope) { values.remove(thisRef) } } } } } }
124
null
905
7,754
08b95b6d0ee16c1b5e02a769d8b40f0310add73a
3,069
RIBs
Apache License 2.0
VCL/src/main/java/io/velocitycareerlabs/impl/domain/infrastructure/keys/KeyService.kt
velocitycareerlabs
525,006,413
false
null
/** * Created by <NAME> on 15/05/2023. * * Copyright 2022 Velocity Career Labs inc. * SPDX-License-Identifier: Apache-2.0 */ package io.velocitycareerlabs.impl.domain.infrastructure.keys import com.nimbusds.jose.jwk.ECKey import io.velocitycareerlabs.api.entities.VCLDidJwk internal interface KeyService { fun generateDidJwk(): VCLDidJwk fun generateKey(): ECKey fun retrieveKey(keyId: String): ECKey fun retrievePublicJwk(ecKey: ECKey): ECKey }
0
Kotlin
0
0
149dea21a7ff83a45a68b4a6102d1f2e3885443c
470
WalletAndroid
Apache License 2.0
app/src/main/java/com/items/bim/dto/LotteryAwardCountDto.kt
losebai
800,799,665
false
{"Kotlin": 644896, "Java": 11455}
package com.items.bim.dto data class LotteryAwardCountDto ( var id: String? = null, var name: String = "", var sumCount: Int = 0, var star5Count: Int = 0, var star4Count: Int = 0, var avgRoleCount: Double = 0.0, var avgWeaponCount: Double = 0.0, var up: Double = 0.0, var avgUpCount : Double = 0.0, var upCount: Int = 0, var avgCount: Double = 0.0, var tag: String? = null, // 池子类型 var poolLotteryAwards: List<PoolLotteryAward> = arrayListOf(), // 池子 var userPoolLotteryAwards: List<UserPoolLotteryAward> = arrayListOf(), ) data class PoolLotteryAward ( var poolType: Int? = null, var poolName: String = "", var count: Long = 0, var okCount: Long = 0, var upCount: Long = 0, var avgCount: Double = 0.0, var avgUpCount: Double = 0.0, var up : Double= 0.0, var tag: String? = null, var hookAwards: List<HookAward> = ArrayList() ) data class UserPoolLotteryAward ( var id: String? = null, var imageUri: String? = null, var poolId: Int? = null, var poolName: String? = null, var count: Long = 0, var okCount: Long = 0, var upCount: Long = 0, var avgCount: Double = 0.0, var avgUpCount: Double = 0.0, var tag: String? = null, var hookAwards: List<HookAward> = ArrayList() ) data class HookAward ( var name: String? = null, var imageUri: String? = null, var isUp: Boolean = false, var count: Int = 0, )
0
Kotlin
0
0
86f8cb939b3671158e568638b0c8e3b82df87fa1
1,465
B-Im
Apache License 2.0
sentry-spring/src/test/kotlin/io/sentry/spring/SentryRequestHttpServletRequestProcessorTest.kt
PaulWoitaschek
315,937,144
false
null
package io.sentry.spring.reactive import io.sentry.SentryEvent import io.sentry.SentryOptions import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue import org.springframework.http.MediaType import org.springframework.mock.http.server.reactive.MockServerHttpRequest class SentryReactiveWebRequestProcessorTest { @Test fun `attaches basic information from HTTP request to SentryEvent`() { val request = MockServerHttpRequest.get("http://example.com?param1=xyz") .header("some-header", "some-header value") .accept(MediaType.APPLICATION_JSON) .build() val eventProcessor = SentryReactiveWebRequestProcessor(request, SentryOptions()) val event = SentryEvent() eventProcessor.process(event, null) assertEquals("GET", event.request.method) assertEquals(mapOf( "some-header" to "some-header value", "Accept" to "application/json" ), event.request.headers) assertEquals("http://example.com", event.request.url) assertEquals("param1=xyz", event.request.queryString) } @Test fun `attaches header with multiple values`() { val request = MockServerHttpRequest.get("http://example.com?param1=xyz") .header("another-header", "another value") .header("another-header", "another value2") .build() val eventProcessor = SentryReactiveWebRequestProcessor(request, SentryOptions()) val event = SentryEvent() eventProcessor.process(event, null) assertEquals(mapOf( "another-header" to "another value,another value2" ), event.request.headers) } @Test fun `when sendDefaultPii is set to true, attaches cookies information`() { val request = MockServerHttpRequest.get("http://example.com?param1=xyz") .header("Cookie", "name=value") .header("Cookie", "name2=value2") .accept(MediaType.APPLICATION_JSON) .build() val sentryOptions = SentryOptions() sentryOptions.isSendDefaultPii = true val eventProcessor = SentryReactiveWebRequestProcessor(request, sentryOptions) val event = SentryEvent() eventProcessor.process(event, null) assertEquals("name=value,name2=value2", event.request.cookies) } @Test fun `when sendDefaultPii is set to false, does not attach cookies`() { val request = MockServerHttpRequest.get("http://example.com?param1=xyz") .header("Cookie", "name=value") .build() val sentryOptions = SentryOptions() sentryOptions.isSendDefaultPii = false val eventProcessor = SentryReactiveWebRequestProcessor(request, sentryOptions) val event = SentryEvent() eventProcessor.process(event, null) assertNull(event.request.cookies) } @Test fun `when sendDefaultPii is set to false, does not attach sensitive headers`() { val request = MockServerHttpRequest.get("http://example.com?param1=xyz") .header("some-header", "some-header value") .header("X-FORWARDED-FOR", "192.168.0.1") .header("authorization", "Token") .header("Authorization", "Token") .header("Cookie", "some cookies") .build() val sentryOptions = SentryOptions() sentryOptions.isSendDefaultPii = false val eventProcessor = SentryReactiveWebRequestProcessor(request, sentryOptions) val event = SentryEvent() eventProcessor.process(event, null) assertFalse(event.request.headers.containsKey("X-FORWARDED-FOR")) assertFalse(event.request.headers.containsKey("Authorization")) assertFalse(event.request.headers.containsKey("authorization")) assertFalse(event.request.headers.containsKey("Cookie")) assertTrue(event.request.headers.containsKey("some-header")) } }
1
null
1
1
8f9b3923f6ae79bdbaedfbce6a8f4df5e9158150
4,042
sentry-java
MIT License
app/src/main/java/com/eyther/lumbridge/features/expenses/viewmodel/overview/delegate/ExpensesOverviewScreenSortByDelegate.kt
ruialmeida51
249,223,684
false
{"Kotlin": 687400}
package com.eyther.lumbridge.features.expenses.viewmodel.overview.delegate import com.eyther.lumbridge.features.expenses.model.overview.ExpensesOverviewSortBy import com.eyther.lumbridge.model.expenses.ExpensesMonthUi import javax.inject.Inject class ExpensesOverviewScreenSortByDelegate @Inject constructor(): IExpensesOverviewScreenSortByDelegate { override fun applySortBy(expenses: List<ExpensesMonthUi>, sortBy: ExpensesOverviewSortBy): List<ExpensesMonthUi> { return when(sortBy) { ExpensesOverviewSortBy.SpentAscending -> expenses.applyAscendingByAmount() ExpensesOverviewSortBy.SpentDescending -> expenses.applyDescendingByAmount() ExpensesOverviewSortBy.DateAscending -> expenses.applyAscendingByDate() ExpensesOverviewSortBy.DateDescending -> expenses.applyDescendingByDate() } } private fun List<ExpensesMonthUi>.applyAscendingByAmount(): List<ExpensesMonthUi> { return sortedBy { it.spent } } private fun List<ExpensesMonthUi>.applyDescendingByAmount(): List<ExpensesMonthUi> { return sortedByDescending { it.spent } } private fun List<ExpensesMonthUi>.applyAscendingByDate(): List<ExpensesMonthUi> { return sortedWith(compareBy({ it.year.value }, { it.month.value })) } private fun List<ExpensesMonthUi>.applyDescendingByDate(): List<ExpensesMonthUi> { return sortedWith(compareBy({ it.year.value }, { it.month.value })).reversed() } }
8
Kotlin
0
7
8e35f83c34e4b29eae1b048d3fda6aaa81b04858
1,492
lumbridge-android
MIT License
SingleModuleApp/app/src/main/java/com/github/yamamotoj/singlemoduleapp/package66/Foo06621.kt
yamamotoj
163,851,411
false
{"Text": 1, "Ignore List": 30, "Markdown": 1, "Gradle": 34, "Java Properties": 11, "Shell": 6, "Batchfile": 6, "Proguard": 22, "Kotlin": 36021, "XML": 93, "INI": 1, "Java": 32, "Python": 2}
package com.github.yamamotoj.singlemoduleapp.package66 class Foo06621 { fun method0() { Foo06620().method5() } fun method1() { method0() } fun method2() { method1() } fun method3() { method2() } fun method4() { method3() } fun method5() { method4() } }
0
Kotlin
0
9
2a771697dfebca9201f6df5ef8441578b5102641
355
android_multi_module_experiment
Apache License 2.0
WebView/app/src/main/java/com/android/samples/webviewdemo/JsObject.kt
android
206,877,845
false
{"Java": 469931, "Kotlin": 289433, "JavaScript": 2890, "CSS": 1896, "HTML": 1663}
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.slions.webviewdemo import android.os.Handler import android.os.Looper import android.webkit.JavascriptInterface import android.webkit.WebView import androidx.webkit.WebViewCompat import androidx.webkit.WebViewFeature // Create a handler that runs on the UI thread private val handler: Handler = Handler(Looper.getMainLooper()) /** * Injects a JavaScript object which supports a {@code postMessage()} method. * A feature check is used to determine if the preferred API, WebMessageListener, is supported. * If it is, then WebMessageListener will be used to create a JavaScript object. The object will be * injected into all of the frames that have an origin matching those in {@code allowedOriginRules}. * <p> * If WebMessageListener is not supported then the method will defer to using JavascriptInterface * to create the JavaScript object. * <p> * The {@code postMessage()} methods in the Javascript objects created by WebMessageListener and * JavascriptInterface both make calls to the same callback, {@code onMessageReceived()}. * In this case, the callback invokes native Android sharing. * <p> * The WebMessageListener invokes callbacks on the UI thread by default. However, * JavascriptInterface invokes callbacks on a background thread by default. In order to * guarantee thread safety and that the caller always gets consistent behavior the the callback * should always be called on the UI thread. To change the default behavior of JavascriptInterface, * the callback is wrapped in a handler which will tell it to run on the UI thread instead of the default * background thread it would otherwise be invoked on. * <p> * @param webview the component that WebMessageListener or JavascriptInterface will be added to * @param jsObjName the name that will be given to the Javascript objects created by either * WebMessageListener or JavascriptInterface * @param allowedOriginRules a set of origins used only by WebMessageListener, if a frame matches an * origin in this set then it will have the JS object injected into it * @param onMessageReceived invoked on UI thread with message passed in from JavaScript postMessage() call */ fun createJsObject( webview: WebView, jsObjName: String, allowedOriginRules: Set<String>, onMessageReceived: (message: String) -> Unit ) { if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) { WebViewCompat.addWebMessageListener( webview, jsObjName, allowedOriginRules ) { _, message, _, _, _ -> onMessageReceived(message.data!!) } } else { webview.addJavascriptInterface(object { @JavascriptInterface fun postMessage(message: String) { // Use the handler to invoke method on UI thread handler.post { onMessageReceived(message) } } }, jsObjName) } }
180
Java
3009
5,038
64bd334762dbe479aae285cadb0d8b2d976381a8
3,516
views-widgets-samples
Apache License 2.0
app/src/main/java/com/gonodono/smssender/MainActivity.kt
shageldi-dev
813,416,302
false
{"Kotlin": 37778}
package com.gonodono.smssender import android.content.pm.PackageManager.PERMISSION_GRANTED import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts.RequestMultiplePermissions import androidx.activity.viewModels import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.lifecycle.flowWithLifecycle import androidx.lifecycle.lifecycleScope import com.gonodono.smssender.sms.SmsPermissions import com.google.gson.Gson import dagger.hilt.android.AndroidEntryPoint import io.socket.client.IO import io.socket.client.Socket import io.socket.emitter.Emitter import io.socket.engineio.client.transports.WebSocket import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import org.json.JSONObject import java.net.URI @AndroidEntryPoint class MainActivity : ComponentActivity() { private val defaultHost = "http://192.168.127.12:5010" private val eventName = "onMessage" private var mSocket: Socket? = null private val defaultHost2 = "http://192.168.127.12:5010" private val eventName2 = "onMessage" private var mSocket2: Socket? = null // This will just end up blank if the permissions aren't granted. override fun onCreate(savedInstanceState: Bundle?) { val request = registerForActivityResult(RequestMultiplePermissions()) { grants -> if (grants.all { it.value }) setUpUi() } super.onCreate(savedInstanceState) val permissions = SmsPermissions if (permissions.any { checkSelfPermission(it) != PERMISSION_GRANTED }) { request.launch(permissions) } else { createSocket() connectWebSocket() setUpUi() } } private fun createSocket() { try { val options = IO.Options() options.forceNew = false options.multiplex = true options.transports = arrayOf(WebSocket.NAME) options.upgrade = true options.rememberUpgrade = false options.query = null options.reconnection = true options.reconnectionAttempts = Int.MAX_VALUE options.reconnectionDelay = 1000 options.reconnectionDelayMax = 5000 options.randomizationFactor = 0.5 options.timeout = 20000 mSocket = IO.socket(URI.create(defaultHost), options) mSocket2 = IO.socket(URI.create(defaultHost2), options) } catch (e: Exception) { e.printStackTrace() } } private fun disconnect() { mSocket!!.disconnect() mSocket!!.off(Socket.EVENT_CONNECT_ERROR, onConnectError) mSocket!!.off(Socket.EVENT_CONNECT, onConnect) mSocket!!.off(Socket.EVENT_DISCONNECT, onDisconnect) mSocket!!.off(eventName, onNewMessage) mSocket2!!.disconnect() mSocket2!!.off(Socket.EVENT_CONNECT_ERROR, onConnectError) mSocket2!!.off(Socket.EVENT_CONNECT, onConnect) mSocket2!!.off(Socket.EVENT_DISCONNECT, onDisconnect) mSocket2!!.off(eventName2, onNewMessage2) } private fun connectWebSocket() { mSocket!!.on(Socket.EVENT_CONNECT_ERROR, onConnectError) mSocket!!.on(Socket.EVENT_CONNECT, onConnect) mSocket!!.on(Socket.EVENT_DISCONNECT, onDisconnect) mSocket!!.on(eventName, onNewMessage) mSocket!!.connect() mSocket2!!.on(Socket.EVENT_CONNECT_ERROR, onConnectError) mSocket2!!.on(Socket.EVENT_CONNECT, onConnect) mSocket2!!.on(Socket.EVENT_DISCONNECT, onDisconnect) mSocket2!!.on(eventName2, onNewMessage2) mSocket2!!.connect() } var onConnect = Emitter.Listener { Log.d("TAG", "Socket Connected!") try { mSocket!!.off(eventName, onNewMessage) } catch (ex: java.lang.Exception) { ex.printStackTrace() } mSocket!!.emit("joinRoom", "otp_room") mSocket!!.on(eventName, onNewMessage) setStatus("Connected") } private val onConnectError = Emitter.Listener { args -> setStatus("Connection error!") } private val onDisconnect = Emitter.Listener { setStatus("Disconnected") } private fun setStatus(status: String) { val viewModel: MainViewModel by viewModels() Log.e("Status", status) viewModel.changeStatus(status) } private val onNewMessage = Emitter.Listener { args -> try { val viewModel: MainViewModel by viewModels() // val s = args[0].toString() Log.e("VALUE", args[0].toString()) val obj = args[0] as JSONObject // val gson = Gson() // String res= (String) args[0]; // String[] s=res.split(","); viewModel.sendSms(obj.getString("number"), obj.getString("text")) // JSONObject obj = (JSONObject) args[0]; // Gson gson = new Gson(); // String res= (String) args[0]; // val ss: Array<String> = // s.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() // viewModel.sendSms(ss[0], ss[1]) } catch (e: java.lang.Exception) { e.printStackTrace() } } private val onNewMessage2 = Emitter.Listener { args -> try { val viewModel: MainViewModel by viewModels() // val s = args[0].toString() val obj = args[0] as JSONObject // val gson = Gson() // String res= (String) args[0]; // String[] s=res.split(","); viewModel.sendSms(obj.getString("phoneNumber"), obj.getString("code")) // JSONObject obj = (JSONObject) args[0]; // Gson gson = new Gson(); // String res= (String) args[0]; // val ss: Array<String> = // s.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() // viewModel.sendSms(ss[0], ss[1]) } catch (e: java.lang.Exception) { e.printStackTrace() } } private fun setUpUi() { val viewModel: MainViewModel by viewModels() var uiState: UiState by mutableStateOf(UiState.Loading) lifecycleScope.launch { viewModel.uiState .flowWithLifecycle(lifecycle) .onEach { uiState = it } .collect() } // lifecycleScope.launch { // viewModel.status.flowWithLifecycle(lifecycle).onEach { status.value = it }.collect() // } setContent { Column( Modifier .fillMaxSize() .padding(10.dp) ) { val status = viewModel.status.collectAsState() Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { Text(text = "OTP") Text(text = status.value) } when (val state = uiState) { is UiState.Active -> { val msgs = state.messages.split("\n\n") LazyColumn( modifier = Modifier .fillMaxWidth() .weight(1f), contentPadding = PaddingValues(vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(12.dp) ) { items(msgs.size) { Column( modifier = Modifier .fillMaxWidth() .background(Color(0xFF03045e), RoundedCornerShape(8.dp)) .padding(12.dp) ) { Text(msgs[it], color = Color.White) } } } val info = when { state.isSending -> "Sending…" else -> state.lastError } if (info != null) { Text(info, Modifier.padding(10.dp), Color.Red) } // TextButton({ viewModel.queueDemoMessagesAndSend() }) { // Text("Queue messages & send") // } // TextButton({ viewModel.resetFailedAndRetry() }) { // Text("Reset failed & retry") // } } else -> Text("Loading…") } // Row(modifier = Modifier // .fillMaxWidth() // .background(Color.DarkGray) // .padding(6.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center){ // Text(text = "Developed By: @shageldi-dev", color = Color.White, style = MaterialTheme.typography.body1.copy(fontWeight = FontWeight.Bold)) // } } } } override fun onDestroy() { super.onDestroy() disconnect() } }
0
Kotlin
0
0
23fb69fb82537cdaa55090843e3a9f8523834dfe
10,956
sms
MIT License
ggdsl-echarts/src/main/kotlin/org/jetbrains/kotlinx/ggdsl/echarts/layers/PieContextImmutable.kt
Kotlin
502,039,936
false
null
/* * Copyright 2020-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package org.jetbrains.kotlinx.ggdsl.echarts.layers import org.jetbrains.kotlinx.ggdsl.dsl.internal.LayerCollectorContextImmutable // import org.jetbrains.kotlinx.ggdsl.dsl.internal.PlotDslMarker import org.jetbrains.kotlinx.ggdsl.echarts.features.animation.AnimationEasing import org.jetbrains.kotlinx.ggdsl.echarts.features.animation.AnimationPie import org.jetbrains.kotlinx.ggdsl.echarts.features.animation.AnimationType /*@PlotDslMarker*/ public class PieContextImmutable(parent: LayerCollectorContextImmutable) : EchartsLayerContextImmutable(parent) { /** * Animation options settings for [pie][pie]. * If a property isn't set or set to null, a default value will be used. * * * [enable][AnimationPie.enable] - responsible for enabling animation. * By default `true`. * * [type][AnimationPie.type] - initial [animation type][AnimationType]. * By default `expansion`. * * [threshold][AnimationPie.threshold] - sets a graphic number threshold for animation. * Animation will be disabled when graphic number exceeds a threshold. * By default `2000`. * * [duration][AnimationPie.duration] - duration of the first animation. * By default `1000`. * * [easing][AnimationPie.easing] - [easing effect][AnimationEasing] used for the first animation. * By default `cubicOut`. * * [delay][AnimationPie.delay] - delay before updating the first animation. * By default `0`. * * ```kotlin * plot { * pie { * animation { * enable = true * type = AnimationType.EXPANSION * threshold = 2000 * duration = 1000 * easing = AnimationEasing.CUBIC_OUT * delay = 0 * } * } * } * ``` * * @see AnimationEasing */ public val animation: AnimationPie = AnimationPie() }
55
Kotlin
2
44
8a161098d0d946c28bde3cf3c7bea6a1eeba073c
2,000
ggdsl
Apache License 2.0
app/src/main/java/io/agora/flat/ui/viewmodel/RtcVideoController.kt
netless-io
358,147,122
false
{"Kotlin": 1090689, "Shell": 2529, "HTML": 452}
package io.agora.flat.ui.viewmodel import android.view.TextureView import android.view.View import android.widget.FrameLayout import androidx.core.view.isVisible import dagger.hilt.android.scopes.ActivityRetainedScoped import io.agora.flat.di.interfaces.RtcApi import io.agora.rtc.RtcEngine import io.agora.rtc.video.VideoCanvas import javax.inject.Inject import kotlin.collections.set @ActivityRetainedScoped class RtcVideoController @Inject constructor(private val rtcApi: RtcApi) { private var textureMap = HashMap<Int, TextureView>() var fullScreenUid: Int = 0 var shareScreenContainer: FrameLayout? = null var localUid: Int = 0 var shareScreenUid: Int = 0 fun setupUid(uid: Int, ssUid: Int) { localUid = uid shareScreenUid = ssUid } fun enterFullScreen(uid: Int) { this.fullScreenUid = uid } fun exitFullScreen() { fullScreenUid = 0 } fun updateFullScreenVideo(videoContainer: FrameLayout, uid: Int) { if (fullScreenUid == uid) { setupUserVideo(videoContainer, uid) } } fun setupUserVideo(container: FrameLayout, uid: Int) { if (textureMap[uid] == null) { textureMap[uid] = RtcEngine.CreateTextureView(container.context) } val textureView = textureMap[uid]!! if (textureView.parent == container) { setupVideo(textureView, uid) } else { (textureView.parent as? FrameLayout)?.removeAllViews() with(container) { removeAllViews() addView(textureView, generateLayoutParams()) setupVideo(textureView, uid) } } } private fun generateLayoutParams() = FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT ) private fun releaseVideo(uid: Int) { setupVideoByVideoCanvas(uid, VideoCanvas(null, VideoCanvas.RENDER_MODE_HIDDEN, uid)) } private fun setupVideo(textureView: View, uid: Int) { setupVideoByVideoCanvas(uid, VideoCanvas(textureView, VideoCanvas.RENDER_MODE_HIDDEN, uid)) } private fun setupVideoByVideoCanvas(uid: Int, videoCanvas: VideoCanvas) { if (uid == localUid) { rtcApi.setupLocalVideo(videoCanvas) } else { rtcApi.setupRemoteVideo(videoCanvas) } } fun handleOffline(uid: Int) { releaseVideo(uid) if (uid == shareScreenUid) { shareScreenContainer?.run { removeAllViews() isVisible = false } } } fun handlerJoined(uid: Int) { if (uid == shareScreenUid) { shareScreenContainer?.run { val textureView = RtcEngine.CreateTextureView(context) rtcApi.setupRemoteVideo(VideoCanvas(textureView, VideoCanvas.RENDER_MODE_FIT, uid)) addView(textureView, generateLayoutParams()) isVisible = true } } } }
0
Kotlin
67
99
989efad4ad2b05d8c106c9eb66a068c30127e35c
3,053
flat-android
MIT License
simpleinterceptor-debug/src/main/java/com/kangaroo/simpleinterceptor/internal/tools/FormatUtils.kt
smartbackme
369,059,807
false
null
package com.kangaroo.simpleinterceptor.internal.tools import android.content.Context import android.text.TextUtils import com.google.gson.JsonParser import com.kangaroo.simpleinterceptor.R import com.kangaroo.simpleinterceptor.internal.data.HttpHeader import com.kangaroo.simpleinterceptor.internal.data.HttpTransaction import com.kangaroo.simpleinterceptor.internal.tools.JsonConvertor.instance import org.xml.sax.InputSource import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.util.* import javax.xml.transform.OutputKeys import javax.xml.transform.Source import javax.xml.transform.sax.SAXSource import javax.xml.transform.sax.SAXTransformerFactory import javax.xml.transform.stream.StreamResult internal object FormatUtils { @JvmStatic fun formatHeaders(httpHeaders: List<HttpHeader>?, withMarkup: Boolean): String { var out = "" if (httpHeaders != null) { for ((name, value) in httpHeaders) { out += (if (withMarkup) "<b>" else "") + name + ": " + (if (withMarkup) "</b>" else "") + value + if (withMarkup) "<br />" else "\n" } } return out } @JvmStatic fun formatByteCount(bytes: Long, si: Boolean): String { val unit = if (si) 1000 else 1024 if (bytes < unit) return "$bytes B" val exp = (Math.log(bytes.toDouble()) / Math.log(unit.toDouble())).toInt() val pre = (if (si) "kMGTPE" else "KMGTPE")[exp - 1].toString() + if (si) "" else "i" return String.format( Locale.US, "%.1f %sB", bytes / Math.pow(unit.toDouble(), exp.toDouble()), pre ) } @JvmStatic fun formatJson(json: String?): String? { return try { val je = JsonParser.parseString(json) instance.toJson(je) } catch (e: Exception) { json } } @JvmStatic fun formatXml(xml: String): String { return try { val serializer = SAXTransformerFactory.newInstance().newTransformer() serializer.setOutputProperty(OutputKeys.INDENT, "yes") serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2") val xmlSource: Source = SAXSource(InputSource(ByteArrayInputStream(xml.toByteArray()))) val res = StreamResult(ByteArrayOutputStream()) serializer.transform(xmlSource, res) String((res.outputStream as ByteArrayOutputStream).toByteArray()) } catch (e: Exception) { xml } } fun getShareText(context: Context, transaction: HttpTransaction): String { val text = StringBuilder("") text.append( """ ${context.getString(R.string.interceptor_url)}: ${v(transaction.url)} """.trimIndent() ) text.append( """ ${context.getString(R.string.interceptor_method)}: ${v(transaction.method)} """.trimIndent() ) text.append( """ ${context.getString(R.string.interceptor_protocol)}: ${v(transaction.protocol)} """.trimIndent() ) text.append( """ ${context.getString(R.string.interceptor_status)}: ${v(transaction.status.toString())} """.trimIndent() ) text.append( """ ${context.getString(R.string.interceptor_response)}: ${v(transaction.responseSummaryText)} """.trimIndent() ) text.append( """ ${context.getString(R.string.interceptor_ssl)}: ${v(context.getString(if (transaction.isSsl) R.string.interceptor_yes else R.string.interceptor_no))} """.trimIndent() ) text.append("\n") text.append( """ ${context.getString(R.string.interceptor_request_time)}: ${v(transaction.requestDateString)} """.trimIndent() ) text.append( """ ${context.getString(R.string.interceptor_response_time)}: ${v(transaction.responseDateString)} """.trimIndent() ) text.append( """ ${context.getString(R.string.interceptor_duration)}: ${v(transaction.durationString)} """.trimIndent() ) text.append("\n") text.append( """ ${context.getString(R.string.interceptor_request_size)}: ${v(transaction.requestSizeString)} """.trimIndent() ) text.append( """ ${context.getString(R.string.interceptor_response_size)}: ${v(transaction.responseSizeString)} """.trimIndent() ) text.append( """ ${context.getString(R.string.interceptor_total_size)}: ${v(transaction.totalSizeString)} """.trimIndent() ) text.append("\n") text.append( """---------- ${context.getString(R.string.interceptor_request)} ---------- """ ) var headers = formatHeaders(transaction.getRequestHeaders(), false) if (!TextUtils.isEmpty(headers)) { text.append( """ $headers """.trimIndent() ) } text.append( if (transaction.requestBodyIsPlainText()) v(transaction.formattedRequestBody) else context.getString( R.string.interceptor_body_omitted ) ) text.append("\n\n") text.append( """---------- ${context.getString(R.string.interceptor_response)} ---------- """ ) headers = formatHeaders(transaction.getResponseHeaders(), false) if (!TextUtils.isEmpty(headers)) { text.append( """ $headers """.trimIndent() ) } text.append( if (transaction.responseBodyIsPlainText()) v(transaction.formattedResponseBody) else context.getString( R.string.interceptor_body_omitted ) ) return text.toString() } fun getShareCurlCommand(transaction: HttpTransaction): String { var compressed = false var curlCmd = "curl" curlCmd += " -X " + transaction.method val headers = transaction.getRequestHeaders() var i = 0 val count = headers.size while (i < count) { val name = headers[i].name val value = headers[i].value if ("Accept-Encoding".equals(name, ignoreCase = true) && "gzip".equals( value, ignoreCase = true ) ) { compressed = true } curlCmd += " -H \"$name: $value\"" i++ } val requestBody = transaction.requestBody if (requestBody != null && requestBody.length > 0) { // try to keep to a single line and use a subshell to preserve any line breaks curlCmd += " --data $'" + requestBody.replace("\n", "\\n") + "'" } curlCmd += (if (compressed) " --compressed " else " ") + transaction.url return curlCmd } private fun v(string: String?): String { return string ?: "" } }
1
null
1
25
966e3420e52c8aba3e8e6980c592ab66f79767b9
7,183
SimpleInterceptor
Apache License 2.0
src/main/kotlin/com/github/mikedepies/ConnectionGenome.kt
MikeDepies
776,556,570
false
{"Kotlin": 1710}
package com.github.mikedepies data class ConnectionGenome(val id: Int, val inputNode: NodeGenome, val outputNode: NodeGenome, val weight: Double, val enabled: Boolean)
0
Kotlin
0
0
28f31d78eddd083c7f9d1958e04864fb28c07e20
168
hyperNeatKotlin
MIT License
platform/platform-api/src/com/intellij/openapi/progress/tasks.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Experimental package com.intellij.openapi.progress import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts.ProgressTitle import com.intellij.util.concurrency.annotations.RequiresEdt import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import org.jetbrains.annotations.ApiStatus.Experimental suspend fun <T> withBackgroundProgress( project: Project, title: @ProgressTitle String, action: suspend CoroutineScope.() -> T ): T { return withBackgroundProgress(project, title, TaskCancellation.cancellable(), action) } suspend fun <T> withBackgroundProgress( project: Project, title: @ProgressTitle String, cancellable: Boolean, action: suspend CoroutineScope.() -> T ): T { val cancellation = if (cancellable) TaskCancellation.cancellable() else TaskCancellation.nonCancellable() return withBackgroundProgress(project, title, cancellation, action) } /** * Shows a background progress indicator, and runs the specified [action]. * The action receives [ProgressReporter] in the coroutine context, reporter updates are reflected in the UI during the execution. * The progress is not shown in the UI immediately to avoid flickering, * i.e. the user won't see anything if the [action] completes within the given timeout. * * @param project in which frame the progress should be shown * @param cancellation controls the UI appearance, e.g. [TaskCancellation.nonCancellable] or [TaskCancellation.cancellable] * @throws CancellationException if the calling coroutine was cancelled, or if the indicator was cancelled by the user in the UI */ suspend fun <T> withBackgroundProgress( project: Project, title: @ProgressTitle String, cancellation: TaskCancellation, action: suspend CoroutineScope.() -> T ): T { return taskSupport().withBackgroundProgressInternal(project, title, cancellation, action) } suspend fun <T> withModalProgress( project: Project, title: @ProgressTitle String, action: suspend CoroutineScope.() -> T, ): T { return withModalProgress(ModalTaskOwner.project(project), title, TaskCancellation.cancellable(), action) } /** * Shows a modal progress indicator, and runs the specified [action]. * The action receives [ProgressReporter] in the coroutine context, reporter updates are reflected in the UI during the execution. * The progress dialog is not shown in the UI immediately to avoid flickering, * i.e. the user won't see anything if the [action] completes within the given timeout. * * Switches to [Dispatchers.EDT][com.intellij.openapi.application.EDT] are allowed inside the action, * as they are automatically scheduled with the correct modality, which is the newly entered one. * * @param owner in which frame the progress should be shown * @param cancellation controls the UI appearance, e.g. [TaskCancellation.nonCancellable] or [TaskCancellation.cancellable] * @throws CancellationException if the calling coroutine was cancelled, * or if the indicator was cancelled by the user in the UI */ suspend fun <T> withModalProgress( owner: ModalTaskOwner, title: @ProgressTitle String, cancellation: TaskCancellation, action: suspend CoroutineScope.() -> T, ): T { return taskSupport().withModalProgressInternal(owner, title, cancellation, action) } @RequiresEdt fun <T> runBlockingModal( project: Project, title: @ProgressTitle String, action: suspend CoroutineScope.() -> T, ): T { return runBlockingModal(ModalTaskOwner.project(project), title, TaskCancellation.cancellable(), action) } /** * Shows a modal progress indicator, and runs the specified [action]. * The action receives [ProgressReporter] in the coroutine context, reporter updates are reflected in the UI during the execution. * The progress dialog is not shown in the UI immediately to avoid flickering, * i.e. the user won't see anything if the [action] completes within the given timeout. * * Switches to [Dispatchers.EDT][com.intellij.openapi.application.EDT] are allowed inside the action, * as they are automatically scheduled with the correct modality, which is the newly entered one. * * ### Difference with [withModalProgressIndicator]. * * This method blocks the called and doesn't return until the [action] is completed. * Runnables, scheduled by various `invokeLater` calls within the given modality, are processed by the nested event loop. * * Usually the usage look like this: * ``` * // on EDT * fun actionPerformed() { * * // this will schedule a new coroutine in default dispatcher * myCoroutineScope.launch(Dispatchers.Default) { * * // the coroutine will schedule modal action, * // which will enter the modality some time later * withModalProgressIndicator(...) { * * // continue execution on Dispatchers.Default * ... * } * } * } * ``` * * [runBlockingModal] is designed for cases when the caller requires the modality, * and the caller cannot afford to let go of the current EDT event: * ``` * // on EDT * fun actionPerformed() { * * // will enter the new modality synchronously in the current EDT event * runBlockingModal(...) { * * // continue execution on Dispatchers.Default * ... * } * } * ``` * * @param owner in which frame the progress should be shown * @param cancellation controls the UI appearance, e.g. [TaskCancellation.nonCancellable] or [TaskCancellation.cancellable] * @throws CancellationException if the calling coroutine was cancelled, * or if the indicator was cancelled by the user in the UI */ @RequiresEdt fun <T> runBlockingModal( owner: ModalTaskOwner, title: @ProgressTitle String, cancellation: TaskCancellation = TaskCancellation.cancellable(), action: suspend CoroutineScope.() -> T, ): T { return taskSupport().runBlockingModalInternal(owner, title, cancellation, action) } private fun taskSupport(): TaskSupport = ApplicationManager.getApplication().service() @Deprecated( message = "This function installs `RawProgressReporter` into action context. " + "Migrate to `ProgressReporter` via `withBackgroundProgress`, " + "and use `withRawProgressReporter` to switch to raw reporter only if needed.", replaceWith = ReplaceWith("withBackgroundProgress(project, title) { withRawProgressReporter (action) }"), ) suspend fun <T> withBackgroundProgressIndicator( project: Project, title: @ProgressTitle String, action: suspend CoroutineScope.() -> T ): T { return withBackgroundProgressIndicator(project, title, cancellable = true, action) } @Deprecated( message = "This function installs `RawProgressReporter` into action context. " + "Migrate to `ProgressReporter` via `withBackgroundProgress`, " + "and use `withRawProgressReporter` to switch to raw reporter only if needed.", replaceWith = ReplaceWith("withBackgroundProgress(project, title, cancellable) { withRawProgressReporter (action) }"), ) suspend fun <T> withBackgroundProgressIndicator( project: Project, title: @ProgressTitle String, cancellable: Boolean, action: suspend CoroutineScope.() -> T ): T { val cancellation = if (cancellable) TaskCancellation.cancellable() else TaskCancellation.nonCancellable() return withBackgroundProgressIndicator(project, title, cancellation, action) } @Deprecated( message = "This function installs `RawProgressReporter` into action context. " + "Migrate to `ProgressReporter` via `withBackgroundProgress`, " + "and use `withRawProgressReporter` to switch to raw reporter only if needed.", replaceWith = ReplaceWith("withBackgroundProgress(project, title, cancellation) { withRawProgressReporter (action) }"), ) suspend fun <T> withBackgroundProgressIndicator( project: Project, title: @ProgressTitle String, cancellation: TaskCancellation = TaskCancellation.cancellable(), action: suspend CoroutineScope.() -> T ): T { return taskSupport().withBackgroundProgressInternal(project, title, cancellation) { withRawProgressReporter(action) } } @Deprecated( message = "This function installs `RawProgressReporter` into action context. " + "Migrate to `ProgressReporter` via `withModalProgress`, " + "and use `withRawProgressReporter` to switch to raw reporter only if needed.", replaceWith = ReplaceWith("withModalProgress(project, title) { withRawProgressReporter(action) }"), ) suspend fun <T> withModalProgressIndicator( project: Project, title: @ProgressTitle String, action: suspend CoroutineScope.() -> T, ): T { return withModalProgressIndicator(owner = ModalTaskOwner.project(project), title = title, action = action) } @Deprecated( message = "This function installs `RawProgressReporter` into action context. " + "Migrate to `ProgressReporter` via `withModalProgress`, " + "and use `withRawProgressReporter` to switch to raw reporter only if needed.", replaceWith = ReplaceWith("withModalProgress(owner, title, cancellation) { withRawProgressReporter(action) }"), ) suspend fun <T> withModalProgressIndicator( owner: ModalTaskOwner, title: @ProgressTitle String, cancellation: TaskCancellation = TaskCancellation.cancellable(), action: suspend CoroutineScope.() -> T, ): T { return taskSupport().withModalProgressInternal(owner, title, cancellation) { withRawProgressReporter(action) } } @Deprecated( message = "This function installs `RawProgressReporter` into action context. " + "Migrate to `ProgressReporter` via `runBlockingModal`, " + "and use `withRawProgressReporter` to switch to raw reporter only if needed.", replaceWith = ReplaceWith("runBlockingModal(project, title) { withRawProgressReporter(action) }"), ) @RequiresEdt fun <T> runBlockingModalWithRawProgressReporter( project: Project, title: @ProgressTitle String, action: suspend CoroutineScope.() -> T, ): T { return runBlockingModalWithRawProgressReporter(ModalTaskOwner.project(project), title, TaskCancellation.cancellable(), action) } @Deprecated( message = "This function installs `RawProgressReporter` into action context. " + "Migrate to `ProgressReporter` via `runBlockingModal`, " + "and use `withRawProgressReporter` to switch to raw reporter only if needed.", replaceWith = ReplaceWith("runBlockingModal(owner, title, cancellation) { withRawProgressReporter(action) }"), ) @RequiresEdt fun <T> runBlockingModalWithRawProgressReporter( owner: ModalTaskOwner, title: @ProgressTitle String, cancellation: TaskCancellation = TaskCancellation.cancellable(), action: suspend CoroutineScope.() -> T, ): T { return taskSupport().runBlockingModalInternal(owner, title, cancellation) { withRawProgressReporter(action) } }
214
null
4829
15,129
5578c1c17d75ca03071cc95049ce260b3a43d50d
11,002
intellij-community
Apache License 2.0
wgpu4k/src/jsMain/kotlin/io.ygdrasil.wgpu/CommandBuffer.js.kt
wgpu4k
773,068,055
false
{"Kotlin": 1936202, "TypeScript": 1001930, "HTML": 93097, "WGSL": 70068, "JavaScript": 8101, "CSS": 5773, "Shell": 253}
package io.ygdrasil.wgpu import io.ygdrasil.wgpu.internal.js.GPUCommandBuffer @JsExport actual class CommandBuffer(internal val handler: GPUCommandBuffer) : AutoCloseable { override fun close() { // Nothing to do } }
0
Kotlin
1
0
56fa04c130dac55f96d61edb3376072a0584bb64
224
wgpu4k
MIT License
app/src/main/java/com/infoskillstechnology/fluperpaginationdemo/DemoApp.kt
Computer-Programming-Tube
264,425,610
false
null
package com.infoskillstechnology.fluperpaginationdemo import android.app.Application class DemoApp:Application(){ override fun onCreate() { super.onCreate() } }
0
Kotlin
0
0
0254da32086267263fb0dcbab1d6cd751c864728
179
FluperPaginationDemo
Apache License 2.0
src/test/kotlin/io/github/smaugfm/lunchmoney/TestBase.kt
smaugfm
609,011,135
false
{"Kotlin": 189664, "Shell": 1786}
package io.github.smaugfm.lunchmoney import org.junit.jupiter.api.BeforeAll import reactor.tools.agent.ReactorDebugAgent open class TestBase { companion object { @BeforeAll @JvmStatic fun initReactorTools() { ReactorDebugAgent.init() } } }
0
Kotlin
0
1
0f30a77a92d72b15c9dbeca44de4ad769def3224
294
lunchmoney
MIT License
src/Day01.kt
Advice-Dog
436,116,275
true
{"Kotlin": 25836}
fun main() { object : CodeRunner("Day01") { override val part1Result: Long get() = 7 override val part2Result: Long get() = 5 override fun part1(input: List<String>): Int { return input .map { it.toInt() } .windowed(2, 1) .count { it.last() > it.first() } } override fun part2(input: List<String>): Int { return input .asSequence() .map { it.toInt() } .windowed(3, 1) .map { it.sum() } .windowed(2, 1) .count { it.last() > it.first() } } } }
0
Kotlin
0
0
2a2a4767e7f0976dba548d039be148074dce85ce
695
advent-of-code-kotlin-template
Apache License 2.0
worldwind/src/commonMain/kotlin/earth/worldwind/globe/elevation/CacheSourceFactory.kt
WorldWindEarth
488,505,165
false
null
package earth.worldwind.globe.elevation import earth.worldwind.geom.Sector import kotlinx.datetime.Instant interface CacheSourceFactory : ElevationSourceFactory { /** * Unique key of this layer in the cache */ val contentKey: String /** * Path to cache content storage root */ val contentPath: String /** * Bounding sector of cache content or null, if it is not specified */ val boundingSector: Sector? /** * Last update date of cache content */ val lastUpdateDate: Instant /** * Returns true if elevation coverage cache is stored in float, or false if it is in integer */ val isFloat: Boolean /** * Estimated cache content size in bytes */ suspend fun contentSize(): Long /** * Deletes all tiles from current cache content. * * @param deleteMetadata also delete cache metadata * @throws IllegalStateException In case of read-only database. */ suspend fun clearContent(deleteMetadata: Boolean) }
24
null
12
98
b5ee69cdd30f6c6a90bf3bec638a3bc5bdb0fbc2
1,040
WorldWindKotlin
Apache License 2.0
src/main/java/de/jotbepunkt/blackbook/masterdata/eventType/EventTypeView.kt
JotBePunkt
125,917,618
false
null
package de.jotbepunkt.blackbook.masterdata.eventType import com.vaadin.spring.annotation.SpringView import com.vaadin.spring.annotation.ViewScope import com.vaadin.ui.CheckBox import com.vaadin.ui.TextArea import com.vaadin.ui.TextField import com.vaadin.ui.TwinColSelect import de.jotbepunkt.blackbook.masterdata.MasterDataEditController import de.jotbepunkt.blackbook.masterdata.MasterDataEditView import de.jotbepunkt.blackbook.service.EventTypeBo import de.jotbepunkt.blackbook.service.EventTypeService import de.jotbepunkt.blackbook.service.TagBo import de.jotbepunkt.blackbook.service.TagService import de.jotbepunkt.blackbook.vaadin.Binding import de.jotbepunkt.blackbook.vaadin.to import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Component /** * Created by bait on 18.07.17. */ @SpringView(name = "eventTypes") class EventTypeView @Autowired constructor(controller: EventTypeController) : MasterDataEditView<EventTypeBo, EventTypeView, EventTypeController>(EventTypeBo::class.java, controller) { // title, comment, tags, publicEvent private val titleField = TextField("Title") private val comment = TextArea("comment") internal val tags = TwinColSelect<TagBo>("tags") private val publicEvent = CheckBox("public") override val formElements: List<Binding<EventTypeBo, out Any>> get() = bind( EventTypeBo::title to titleField, EventTypeBo::comment to comment, EventTypeBo::tags to tags, EventTypeBo::publicEvent to publicEvent ) } @Component @ViewScope class EventTypeController @Autowired constructor(override val dataService: EventTypeService) : MasterDataEditController<EventTypeBo, EventTypeView, EventTypeController>() { @Autowired lateinit var tagService: TagService override fun onShow() { view.tags.setItems(tagService.findAll()) } }
0
Kotlin
0
0
e8a34b839435e88c9b7a48d28b30f2448d5f1835
1,940
blackbook
Apache License 2.0
build-logic/convention/src/main/kotlin/EasterEggApp.kt
hushenghao
306,645,388
false
{"Kotlin": 766881, "Java": 579645, "Python": 13697, "Ruby": 7903}
import com.android.build.gradle.internal.dsl.BaseAppModuleExtension import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.dependencies import org.gradle.kotlin.dsl.project class EasterEggApp : Plugin<Project> { override fun apply(target: Project) { with(target) { pluginManager.apply { apply("com.android.application") apply("com.google.dagger.hilt.android") apply("org.jetbrains.kotlin.android") apply("com.google.devtools.ksp") } dependencies { "implementation"(project(path = ":basic")) "implementation"(catalog.findLibrary("hilt.android").get()) "ksp"(catalog.findLibrary("hilt.compiler").get()) } configureAndroid<BaseAppModuleExtension> { defaultConfig { targetSdk = Versions.TARGET_SDK } buildFeatures { buildConfig = true } lint { fatal += listOf("NewApi", "InlineApi") } } } } }
4
Kotlin
31
626
e1874513fbf03f7b1fbb2c89ce093dc97728e162
1,191
AndroidEasterEggs
Apache License 2.0
shared/src/commonMain/kotlin/com/san/englishbender/data/local/dataStore/IDataStore.kt
SanEffect
661,043,037
false
null
package com.san.englishbender.data.local.dataStore import com.san.englishbender.data.local.dataStore.models.AppSettings import com.san.englishbender.data.local.dataStore.models.UserSettings import kotlinx.coroutines.flow.Flow import org.koin.core.component.KoinComponent interface IDataStore : KoinComponent { fun getAppSettings(): AppSettings fun saveAppSettings(appSettings: AppSettings) fun getUserSettings(): UserSettings fun getUserSettingsAsFlow(): Flow<UserSettings> fun saveUserSettings(userSettings: UserSettings) }
0
Kotlin
0
0
39469ca2231b2cc1e6869d0d1461d32d87f1abef
549
EngApp
MIT License
bot/connector-businesschat/src/main/kotlin/model/csp/listPicker/ListPicker.kt
theopenconversationkit
84,538,053
false
{"Kotlin": 6173880, "TypeScript": 1286450, "HTML": 532576, "Python": 376720, "SCSS": 79512, "CSS": 66318, "Shell": 12085, "JavaScript": 1849}
/* * Copyright (C) 2017/2021 e-voyageurs technologies * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ai.tock.bot.connector.businesschat.model.csp.listPicker import ai.tock.bot.connector.businesschat.model.common.MessageType import ai.tock.bot.connector.businesschat.model.csp.BusinessChatCommonModel import java.util.UUID /** * See [https://developer.apple.com/documentation/businesschatapi/messages_sent/interactive_messages/list_picker] */ const val BID: String = "com.apple.messages.MSMessageExtensionBalloonPlugin:0000000000:com.apple.icloud.apps.messages.business.extension" class ListPickerMessage( sourceId: String, destinationId: String, val interactiveData: InteractiveData ) : BusinessChatCommonModel( sourceId = sourceId, destinationId = destinationId, type = MessageType.interactive ) class InteractiveData( val data: ListPickerData, val receivedMessage: ReceivedMessage ) { val bid: String = BID } class ReceivedMessage( val title: String, val subtitle: String? ) { val style: String = "icon" } class ListPickerData( val listPicker: ListPicker, val images: List<Image?>? ) { val version: String = "1.0" val requestIdentifier: String = UUID.randomUUID().toString() } class Image(val identifier: String, val data: String) class ListPicker( val sections: List<ListPickerSection> = emptyList() ) class ListPickerSection( val items: List<ListPickerItem> = emptyList(), val order: Int, val title: String, val multipleSelection: Boolean = false ) class ListPickerItem( val identifier: String, val imageIdentifier: String? = null, val order: Int, val subtitle: String?, val title: String ) { val style: String = "default" }
163
Kotlin
127
475
890f69960997ae9146747d082d808d92ee407fcb
2,274
tock
Apache License 2.0
domain/src/commonMain/kotlin/uk/co/sentinelweb/cuer/domain/PlayerStateDomain.kt
sentinelweb
220,796,368
false
{"Kotlin": 2627352, "CSS": 205156, "Java": 98919, "Swift": 85812, "HTML": 19322, "JavaScript": 12105, "Ruby": 2170}
package uk.co.sentinelweb.cuer.domain import kotlinx.serialization.Serializable @Serializable enum class PlayerStateDomain { UNKNOWN, UNSTARTED, ENDED, PLAYING, PAUSED, BUFFERING, VIDEO_CUED, ERROR }
94
Kotlin
0
2
f74e211570fe3985ba45848b228e91a3a8593788
233
cuer
Apache License 2.0
mvvm-core/src/androidMain/kotlin/dev/icerock/moko/mvvm/ViewModelFactory.kt
icerockdev
204,883,322
false
null
/* * Copyright 2019 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license. */ package dev.icerock.moko.mvvm import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelStoreOwner class ViewModelFactory( private val viewModelBlock: () -> ViewModel ) : ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { @Suppress("UNCHECKED_CAST") return viewModelBlock() as T } } inline fun <reified T : ViewModel> ViewModelStoreOwner.getViewModel( noinline viewModelBlock: () -> T ): T = ViewModelProvider( this, ViewModelFactory { viewModelBlock() } ).get(T::class.java) inline fun <reified T : ViewModel> ViewModelStoreOwner.createViewModelFactory( noinline viewModelBlock: () -> T ): ViewModelFactory = ViewModelFactory { viewModelBlock() }
35
Kotlin
77
675
4ab6dee9a53c1a5b5e6eac3f913d403be1cb89f5
904
moko-mvvm
Apache License 2.0
src/backend/codecc/core/defect/biz-defect/src/main/kotlin/com/tencent/bk/codecc/defect/service/impl/DefectAuthTaskServiceImpl.kt
Florence-y
466,159,327
false
null
package com.tencent.bk.codecc.codeccjob.service.impl import com.tencent.bk.codecc.task.api.ServiceTaskRestResource import com.tencent.devops.common.api.QueryTaskListReqVO import com.tencent.devops.common.auth.api.external.AuthTaskService import com.tencent.devops.common.auth.api.pojo.external.KEY_CREATE_FROM import com.tencent.devops.common.auth.api.pojo.external.KEY_PIPELINE_ID import com.tencent.devops.common.auth.api.pojo.external.PREFIX_TASK_INFO import com.tencent.devops.common.client.Client import com.tencent.devops.common.pojo.GongfengBaseInfo import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Primary import org.springframework.data.redis.core.RedisTemplate import org.springframework.stereotype.Component @Component @Primary class JobAuthTaskServiceImpl @Autowired constructor( private val client: Client, private val redisTemplate: RedisTemplate<String, String> ) : AuthTaskService { /** * 查询任务创建来源 */ override fun getTaskCreateFrom( taskId: Long ): String { var createFrom = redisTemplate.opsForHash<String, String>().get(PREFIX_TASK_INFO + taskId, KEY_CREATE_FROM) if (createFrom.isNullOrEmpty()) { val taskInfo = client.get(ServiceTaskRestResource::class.java).getTaskInfoById(taskId) if (taskInfo?.data != null) { val taskInfoEntity = taskInfo.data if (taskInfoEntity != null && !taskInfoEntity.createFrom.isNullOrEmpty()) { createFrom = taskInfoEntity.createFrom redisTemplate.opsForHash<String, String>().put(PREFIX_TASK_INFO + taskId, KEY_CREATE_FROM, createFrom) } } } return createFrom } override fun getGongfengProjInfo(taskId: Long): GongfengBaseInfo? { // TODO("Not yet implemented") return null } /** * 获取任务所属流水线ID */ override fun getTaskPipelineId( taskId: Long ): String { var pipelineId = redisTemplate.opsForHash<String, String>().get(PREFIX_TASK_INFO + taskId, KEY_PIPELINE_ID) if (pipelineId.isNullOrEmpty()) { val taskInfo = client.get(ServiceTaskRestResource::class.java).getTaskInfoById(taskId) if (taskInfo != null && taskInfo.data != null) { val taskInfoEntity = taskInfo.data if (taskInfoEntity != null && !taskInfoEntity.pipelineId.isNullOrEmpty()) { pipelineId = taskInfoEntity.pipelineId redisTemplate.opsForHash<String, String>().put(PREFIX_TASK_INFO + taskId, KEY_PIPELINE_ID, pipelineId) } } } return pipelineId } override fun getGongfengCIProjInfo(gongfengId: Int): GongfengBaseInfo? { // TODO("Not yet implemented") return null } override fun queryPipelineListForUser(user: String, projectId: String, actions: Set<String>): Set<String> { val request = QueryTaskListReqVO() request.projectId = projectId return client.get(ServiceTaskRestResource::class.java).batchGetTaskList(request).data?.map { it.pipelineId }?.toSet() ?: setOf() } override fun queryPipelineListForUser(user: String, projectId: String): Set<String> { val request = QueryTaskListReqVO() request.projectId = projectId request.userId = user return client.get(ServiceTaskRestResource::class.java).batchGetTaskList(request).data?.map { it.pipelineId }?.toSet() ?: setOf() } override fun queryTaskListForUser(user: String, projectId: String, actions: Set<String>): Set<String> { val request = QueryTaskListReqVO() request.projectId = projectId return client.get(ServiceTaskRestResource::class.java).batchGetTaskList(request).data?.map { it.taskId.toString() }?.toSet() ?: setOf() } override fun queryTaskUserListForAction(taskId: String, projectId: String, actions: Set<String>): List<String> { val result = mutableListOf<String>() val request = QueryTaskListReqVO() request.projectId = projectId client.get(ServiceTaskRestResource::class.java).batchGetTaskList(request).data?.forEach { result.addAll(it.taskOwner) } return result } override fun queryTaskListByPipelineIds(pipelineIds: Set<String>): Set<String> { return client.get(ServiceTaskRestResource::class.java).queryTaskListByPipelineIds(pipelineIds).data ?: setOf() } companion object { private val logger = LoggerFactory.getLogger(JobAuthTaskServiceImpl::class.java) } }
0
null
0
2
58baee8fabd09ff8e42885162a3b894bab1577da
4,718
bk-ci
MIT License
zxscanner/android/app/src/androidTest/java/com/markosyan/zxscanner/JUnit4StyleTests.kt
khoren93
472,074,535
false
{"Dart": 145723, "C++": 41271, "CMake": 21237, "Swift": 17133, "Ruby": 9596, "C": 2026, "Kotlin": 1981, "HTML": 1818, "Shell": 854, "Objective-C": 76}
package com.markosyan.zxscanner import androidx.test.ext.junit.rules.ActivityScenarioRule import org.junit.* import org.junit.runner.RunWith import org.junit.runners.JUnit4 import tools.fastlane.screengrab.Screengrab import tools.fastlane.screengrab.UiAutomatorScreenshotStrategy import tools.fastlane.screengrab.cleanstatusbar.BluetoothState import tools.fastlane.screengrab.cleanstatusbar.CleanStatusBar import tools.fastlane.screengrab.cleanstatusbar.MobileDataType import tools.fastlane.screengrab.locale.LocaleTestRule @RunWith(JUnit4::class) class JUnit4StyleTests { companion object { @JvmStatic @BeforeClass fun beforeAll() { Screengrab.setDefaultScreenshotStrategy(UiAutomatorScreenshotStrategy()) CleanStatusBar() .setMobileNetworkDataType(MobileDataType.LTE) .setBluetoothState(BluetoothState.DISCONNECTED) .enable() } @JvmStatic @AfterClass fun afterAll() { CleanStatusBar.disable() } } @get:Rule var activityRule = ActivityScenarioRule(MainActivity::class.java) @Rule @JvmField val localeTestRule = LocaleTestRule() @Test fun testTakeScannerScreenshot() { Thread.sleep(3000) Screengrab.screenshot("01_scanner_screen") Thread.sleep(3000) Assert.assertTrue(true) } }
42
Dart
56
98
8678ebf7e13a447416a486b0c7bca52ce832cdc9
1,401
flutter_zxing
MIT License
backend/src/main/kotlin/be/osoc/team1/backend/util/Serializers.kt
SELab-2
457,425,785
false
null
package be.osoc.team1.backend.util import be.osoc.team1.backend.entities.Position import be.osoc.team1.backend.entities.Project import be.osoc.team1.backend.entities.Student import be.osoc.team1.backend.entities.User import com.fasterxml.jackson.core.JsonGenerator import com.fasterxml.jackson.databind.SerializerProvider /** * This class is used to serialize a [T] object when it is used as a reference. * This makes sure it gets turned into the rest API url. */ open class Serializer<T>(private val genFunc: (T) -> String) : BaseSerializer<T>() { fun toUrl(item: T): String = baseUrl + genFunc(item) override fun serialize(item: T?, gen: JsonGenerator?, provider: SerializerProvider?) = gen!!.writeObject(toUrl(item!!)) } class PositionSerializer : Serializer<Position>({ "/positions/${it.id}" }) class StudentSerializer : Serializer<Student>({ "/${it.edition}/students/${it.id}" }) class ProjectSerializer : Serializer<Project>({ "/${it.edition}/projects/${it.id}" }) class UserSerializer : Serializer<User>({ "/users/${it.id}" })
2
Kotlin
0
8
66692b6c5ceb2cf9852e1fd051a7d62ea7bcd27e
1,061
OSOC-1
MIT License
libraries/core/src/main/java/com/n27/core/presentation/detail/adapters/ResultsAdapter.kt
Narsuf
52,900,182
false
{"Kotlin": 247331}
package com.n27.core.presentation.detail.adapters import android.graphics.Color import android.view.LayoutInflater import android.view.ViewGroup import android.widget.TextView import androidx.constraintlayout.widget.ConstraintLayout import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.n27.core.Constants import com.n27.core.R import com.n27.core.domain.election.models.Election import com.n27.core.extensions.divide import java.text.NumberFormat class ResultsAdapter : RecyclerView.Adapter<ResultsAdapter.MyViewHolder>() { internal var election = Election() class MyViewHolder(val layout: ConstraintLayout) : RecyclerView.ViewHolder(layout) fun updateItems(newItem: Election) { val diffCallback = ResultsDiff(election.results, newItem.results) val diffResult = DiffUtil.calculateDiff(diffCallback) election = newItem diffResult.dispatchUpdatesTo(this) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val layout = LayoutInflater.from(parent.context) .inflate(R.layout.list_item_activity_detail, parent, false) as ConstraintLayout return MyViewHolder(layout) } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { val layout = holder.layout val result = election.results[position] val color = Color.parseColor("#${result.party.color}") val votes = NumberFormat.getNumberInstance().format(result.votes) val percentage = if (election.chamberName == Constants.KEY_SENATE) "- %" else result.votes.divide(election.validVotes) + " %" layout.findViewById<TextView>(R.id.color_list_item_activity_detail).setBackgroundColor(color) layout.findViewById<TextView>(R.id.party_list_item_activity_detail).text = result.party.name layout.findViewById<TextView>(R.id.votes_list_item_activity_detail).text = votes layout.findViewById<TextView>(R.id.percentage_list_item_activity_detail).text = percentage layout.findViewById<TextView>(R.id.elects_list_item_activity_detail).text = result.elects.toString() } override fun getItemCount() = election.results.size }
1
Kotlin
0
2
ef21ef7e7ef0b132224e6d40f316e960932ee895
2,267
Elections
Apache License 2.0
src/main/kotlin/net/sonmoosans/dui/listeners/ComponentListener.kt
fuma-nama
529,182,440
false
{"Kotlin": 85867}
package net.sonmoosans.dui.listeners import net.sonmoosans.dui.Component import net.sonmoosans.dui.Data import net.dv8tion.jda.api.events.interaction.ModalInteractionEvent import net.dv8tion.jda.api.events.interaction.component.GenericComponentInteractionCreateEvent import net.dv8tion.jda.api.hooks.ListenerAdapter import net.sonmoosans.dui.context.* import net.sonmoosans.dui.utils.createId typealias Handler<E> = E.() -> Unit /** * dynamic listeners will only be used When no matching listeners in data */ fun<E: EventContext<*, D, P>, D: Data<P>, P : Any> RenderContext<D, P>.on( id: String? = null, dynamic: Boolean, handler: Handler<E>, ): String { val listenerId = createId(id, handler) if (dynamic) component.listen( listenerId, handler as Handler<EventContext<*, D, P>> ) else { data.listeners[listenerId] = handler as Handler<EventContext<*, Data<P>, P>> } return ComponentListener.listen(component, component.encodeData(data), listenerId) } data class RawId(val comp: Int, val dataId: String, val listenerId: String) { fun<D: Data<P>, P: Any, E> build(): DynamicId<D, P, E>? { val comp = ComponentListener.components[this.comp]?: return null val data = comp.parseData(this.dataId)?: return null val listener = data.listeners[listenerId]?: comp.listeners[listenerId] listener?: return null return DynamicId(comp as Component<D, P>, data as D, listener as Handler<E>) } } data class DynamicId<D: Data<P>, P: Any, E>(val comp: Component<D, P>, val data: D, val listener: Handler<E>) object ComponentListener : ListenerAdapter() { /** Pair<ComponentId, Component> **/ val components = hashMapOf<Int, Component<*, *>>() var encoder: Encoder = DefaultEncoder() fun listen(component: Component<*, *>, data: String, listener: String): String { components[component.hashCode()] = component return encoder.encodeId(component, data, listener) } override fun onGenericComponentInteractionCreate(event: GenericComponentInteractionCreateEvent) = handle<Any>(event) override fun onModalInteraction(event: ModalInteractionEvent) = handle<Any>(event) private fun<P: Any> handle(event: GenericComponentInteractionCreateEvent) { val id = encoder.decodeId(event.componentId)?: return val (comp, data, listener) = id.build<Data<P>, P, InteractionContext<*, *, P>>()?: return listener.invoke( InteractionContext(event, data, comp) ) } private fun<P: Any> handle(event: ModalInteractionEvent) { val id = encoder.decodeId(event.modalId)?: return val (comp, data, listener) = id.build<Data<P>, P, ModalContext<Data<P>, P>>()?: return listener.invoke( ModalContext(event, data, comp) ) } } interface Encoder { fun encodeId(comp: Component<*, *>, data: String, listenerId: String): String fun decodeId(id: String): RawId? } class DefaultEncoder : Encoder { override fun encodeId(comp: Component<*, *>, data: String, listenerId: String): String { if (listenerId.contains("-")) error( "Listener Id cannot contains '-'" ) val id = "${comp.hashCode()}-$data-$listenerId" if (id.length > 100) error( "Your Listener ID is too long: $id, try reduce Scopes amount or Listener ID length" ) return id } override fun decodeId(id: String): RawId? { val (compId, dataId, listenerId) = id.split("-").verify { return null } return RawId(compId.toInt(), dataId, listenerId) } private inline fun List<String>.verify(onFail: () -> Unit): List<String> { if (size != 3) onFail() return this } }
0
Kotlin
0
6
743c74ccfcef8681111d4653c8f99605d399f2f0
3,795
discord-ui
MIT License
collaboration-suite-glass-ui/src/main/java/com/kaleyra/collaboration_suite_glass_ui/participants/ParticipantStateTextView.kt
Bandyer
337,367,845
false
null
/* * Copyright 2023 Kaleyra @ https://www.kaleyra.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.kaleyra.collaboration_suite_glass_ui.participants import android.content.Context import android.util.AttributeSet import com.kaleyra.collaboration_suite_glass_ui.R import com.kaleyra.collaboration_suite_core_ui.utils.Iso8601 import com.google.android.material.textview.MaterialTextView import com.kaleyra.collaboration_suite.chatbox.ChatParticipant /** * A TextView defining the user online state * * @constructor */ internal class ParticipantStateTextView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : MaterialTextView(context, attrs, defStyleAttr) { private var state: ChatParticipant.State = ChatParticipant.State.Joined.Offline(ChatParticipant.State.Joined.Offline.LastLogin.Never) /** * Define the user online state * * @param state The user state */ fun setUserState(state: ChatParticipant.State) { this.state = state text = when (state) { is ChatParticipant.State.Invited -> resources.getString(R.string.kaleyra_glass_invited) is ChatParticipant.State.Joined.Online -> resources.getString(R.string.kaleyra_glass_online) is ChatParticipant.State.Joined.Offline -> { val lastLogin = state.lastLogin if (lastLogin is ChatParticipant.State.Joined.Offline.LastLogin.At) resources.getString( R.string.kaleyra_glass_last_seen_pattern, Iso8601.parseTimestamp(context, lastLogin.date.time) ) else resources.getString(R.string.kaleyra_glass_last_seen_never) } } } }
1
null
2
2
2a9dc8f493337a466bdfb0c94b9a8c7c9077a312
2,283
Bandyer-Android-Design
Apache License 2.0
core-starter/src/main/kotlin/com/labijie/application/configuration/ApplicationDefaultsAutoConfiguration.kt
hongque-pro
309,874,586
false
{"Kotlin": 1081011, "Java": 72766}
/** * @author <NAME> * @date 2024-05-28 */ package com.labijie.application.configuration import com.labijie.application.component.IEmailAddressValidator import com.labijie.application.component.IPhoneValidator import com.labijie.application.component.impl.NationalPhoneValidator import com.labijie.application.component.impl.EmailAddressValidator import org.springframework.boot.autoconfigure.AutoConfigureOrder import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.core.Ordered @Configuration(proxyBeanMethods = false) @AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE) class ApplicationDefaultsAutoConfiguration { @Bean @ConditionalOnMissingBean(IPhoneValidator::class) fun phoneValidator(): NationalPhoneValidator { return NationalPhoneValidator() } @Bean @ConditionalOnMissingBean(IEmailAddressValidator::class) fun emailAddressValidator(): EmailAddressValidator { return EmailAddressValidator() } }
0
Kotlin
0
7
db1ab039b44d9c9f710bf74ac31a85ad95ef94cc
1,120
application-framework
Apache License 2.0
examples/KotlinMP-Example/app/src/main/java/presentation/adapters/DeviceAdapter.kt
jamesjmtaylor
319,074,911
true
null
package presentation.adapters import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import org.jetbrains.anko.linearLayout import org.jetbrains.anko.padding import org.jetbrains.anko.textView import presentation.viewmodels.device.DeviceServiceViewModel class DeviceAdapter(var deviceServiceViewModels : List<DeviceServiceViewModel>) : BaseAdapter() { override fun getView(i : Int, v : View?, parent : ViewGroup?) : View { val item = getItem(i) return with(parent!!.context) { linearLayout { textView(item.displayName) { textSize = 20f padding = 10 } } } } override fun getItem(position : Int) : DeviceServiceViewModel = deviceServiceViewModels[position] override fun getCount() : Int = deviceServiceViewModels.size override fun getItemId(position : Int) : Long = position.toLong() }
0
Kotlin
1
8
68a9ccfad87809b9c4ecd657be3bdecca58ad65d
964
blue-falcon-ftms
MIT License
app/src/main/java/org/md/pegpixel/pegboard/Peg.kt
PegPixel
153,925,429
false
{"Kotlin": 30541}
package org.md.pegpixel.pegboard data class Peg( val columnIndex: Int, val rowIndex: Int, var selected: Boolean, var color: Int) { fun toggleSelect() { selected = !selected } }
0
Kotlin
0
1
8a8c78b53c5bedb43194b27f0fb1cef83956bf8e
226
pegpixel-app
MIT License
app/src/main/java/se/locutus/sl/realtidhem/service/WakeLockReceiever.kt
ovelius
157,601,439
false
{"Kotlin": 210551, "Batchfile": 162}
package se.locutus.sl.realtidhem.service import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import java.util.logging.Logger internal class WakeLockReceiever(val service : BackgroundUpdaterService) : BroadcastReceiver() { companion object { val LOG = Logger.getLogger(WakeLockReceiever::class.java.name) } override fun onReceive(context: Context, intent: Intent) { if (Intent.ACTION_SCREEN_OFF == intent.action) { service.stopAutoUpdateSequence() } else if (Intent.ACTION_SCREEN_ON == intent.action) { service.startAutoUpdateSequence(true, false) } LOG.info("Intent received $intent") } }
2
Kotlin
0
3
ff49106e55980bed22375d3465d21d2180e78b9e
721
SlRealtidwidget-ng
Apache License 2.0
app/src/main/java/com/dokja/mizumi/repository/AppRepository.kt
shrimpyvongue
761,620,637
false
{"Kotlin": 144521}
package com.dokja.mizumi.repository import android.content.Context import androidx.core.net.toUri import com.dokja.mizumi.data.Response import com.dokja.mizumi.data.local.MizumiDatabase import com.dokja.mizumi.data.local.chapter.Chapter import com.dokja.mizumi.data.local.library.LibraryItem import com.dokja.mizumi.epub.epubParser import com.dokja.mizumi.isContentUri import com.dokja.mizumi.utils.tryAsResponse import dagger.hilt.android.qualifiers.ApplicationContext import epubImporter import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import javax.inject.Inject class AppRepository @Inject constructor( private val db: MizumiDatabase, @ApplicationContext private val context: Context, val name: String, val libraryBooks: LibraryBookRepository, val bookChapters: BookChaptersRepository, val chapterBody: ChapterBodyRepository, private val appFileResolver: AppFileResolver, ) { suspend fun libraryUpdate(bookUrl: String, bookTitle: String): Boolean { val realUrl = appFileResolver.getLocalIfContentType(bookUrl, bookFolderName = bookTitle) return if (bookUrl.isContentUri && libraryBooks.get(realUrl) == null) { importEpubFromContentUri( contentUri = bookUrl, bookTitle = bookTitle, addToLibrary = true ) is Response.Success } else { libraryBooks.toggleBookmark(bookUrl = realUrl, bookTitle = bookTitle) } } suspend fun importEpubFromContentUri( contentUri: String, bookTitle: String, addToLibrary: Boolean = false ) = tryAsResponse { val inputStream = context.contentResolver.openInputStream(contentUri.toUri()) ?: return@tryAsResponse val epub = inputStream.use { epubParser(inputStream = inputStream) } epubImporter( storageFolderName = bookTitle, appFileResolver = appFileResolver, appRepository = this, epub = epub, addToLibrary = addToLibrary ) } suspend fun getDatabaseSizeBytes() = withContext(Dispatchers.IO) { context.getDatabasePath(name).length() } fun close() = db.close() fun delete() = context.deleteDatabase(name) fun clearAllTables() = db.clearAllTables() suspend fun vacuum() = withContext(Dispatchers.IO) { db.openHelper.writableDatabase.execSQL("VACUUM") } suspend fun <T> withTransaction(fn: suspend () -> T) = db.transaction(fn) inner class Settings { suspend fun clearNonLibraryData() = withContext(Dispatchers.IO) { db.getLibraryDao().removeAllNonLibraryRows() db.getChapterDao().removeAllNonLibraryRows() db.getChapterBody().removeAllNonChapterRows() } /** * Folder where additional book data like images is stored. * Each subfolder must be an unique folder for each book. * Each book folder can have an arbitrary structure internally. */ val folderBooks = appFileResolver.folderBooks } } fun isValid(book: LibraryItem): Boolean = book.url.matches("""^(https?|local)://.*""".toRegex()) fun isValid(chapter: Chapter): Boolean = chapter.url.matches("""^(https?|local)://.*""".toRegex())
0
Kotlin
1
1
eabf20688848d6896430de4e271bec46fe6a0b98
3,309
Mizumi
MIT License
app/src/main/java/com/hercan/rickandmortyapp/ui/home/HomeViewModel.kt
hanifeercan
623,656,170
false
null
package com.hercan.rickandmortyapp.ui.home import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.paging.PagingData import androidx.paging.liveData import com.hercan.rickandmortyapp.domain.repository.RickAndMortyRepository import com.hercan.rickandmortyapp.domain.utils.Status import com.hercan.rickandmortyapp.presentation.model.LocationUIModel import com.hercan.rickandmortyapp.presentation.model.ResidentUIModel import com.hercan.rickandmortyapp.presentation.model.toResidentUIModel import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.onCompletion import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class HomeViewModel @Inject constructor(private val repository: RickAndMortyRepository) : ViewModel() { private val _residentList: MutableLiveData<List<ResidentUIModel?>?> = MutableLiveData() val residentList: LiveData<List<ResidentUIModel?>?> = _residentList private val _isOnLoading: MutableLiveData<Boolean> = MutableLiveData() val isOnLoading: LiveData<Boolean> = _isOnLoading private val _isOnError: MutableLiveData<String?> = MutableLiveData(null) val isOnError: LiveData<String?> = _isOnError var isFirstCall = true fun getLocations(): LiveData<PagingData<LocationUIModel>> { isFirstCall = false return repository.getLocations().liveData } fun getResidents(ids: ArrayList<Int>) { viewModelScope.launch(Dispatchers.IO) { repository.getResidents(ids) .onStart { _isOnLoading.postValue(true) } .onCompletion { _isOnLoading.postValue(false) } .collect { if (it.status == Status.SUCCESS) { it.data?.toResidentUIModel()?.let { _residentList.postValue(it) } } else { _isOnError.postValue(it.message) } } } } }
0
Kotlin
0
0
6b760f229d08dbfb6486f9b0d5d79540ccf91860
2,253
RickAndMortyApp
MIT License
app/src/main/java/com/revolgenx/anilib/user/fragment/AnimeUserStatsStaffFragment.kt
AniLibApp
244,410,204
false
{"Kotlin": 1593083, "Shell": 52}
package com.revolgenx.anilib.user.fragment class AnimeUserStatsStaffFragment : UserStatsStaffFragment()
36
Kotlin
3
76
b3caec5c00779c878e4cf22fb7d2034aefbeee54
105
AniLib
Apache License 2.0
bot/storage-mongo/target/generated-sources/kapt/compile/ai/tock/bot/mongo/ArchivedEntityValuesCol_Deserializer.kt
theopenconversationkit
84,538,053
false
null
package ai.tock.bot.mongo import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.core.JsonToken import com.fasterxml.jackson.core.type.TypeReference import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.JsonDeserializer import com.fasterxml.jackson.databind.module.SimpleModule import java.time.Instant import kotlin.String import kotlin.collections.List import kotlin.collections.Map import kotlin.collections.MutableList import kotlin.reflect.KFunction import kotlin.reflect.KParameter import kotlin.reflect.full.findParameterByName import kotlin.reflect.full.primaryConstructor import org.litote.jackson.JacksonModuleServiceLoader import org.litote.kmongo.Id internal class ArchivedEntityValuesCol_Deserializer : JsonDeserializer<ArchivedEntityValuesCol>(), JacksonModuleServiceLoader { override fun module() = SimpleModule().addDeserializer(ArchivedEntityValuesCol::class.java, this) override fun deserialize(p: JsonParser, ctxt: DeserializationContext): ArchivedEntityValuesCol { with(p) { var __id_: Id<ArchivedEntityValuesCol>? = null var __id_set : Boolean = false var _values_: MutableList<ArchivedEntityValuesCol.ArchivedEntityValueWrapper>? = null var _values_set : Boolean = false var _lastUpdateDate_: Instant? = null var _lastUpdateDate_set : Boolean = false var _token_ : JsonToken? = currentToken while (_token_?.isStructEnd != true) { if(_token_ != JsonToken.FIELD_NAME) { _token_ = nextToken() if (_token_?.isStructEnd == true) break } val _fieldName_ = currentName _token_ = nextToken() when (_fieldName_) { "_id" -> { __id_ = if(_token_ == JsonToken.VALUE_NULL) null else p.readValueAs(__id__reference); __id_set = true } "values" -> { _values_ = if(_token_ == JsonToken.VALUE_NULL) null else p.readValueAs(_values__reference); _values_set = true } "lastUpdateDate" -> { _lastUpdateDate_ = if(_token_ == JsonToken.VALUE_NULL) null else p.readValueAs(Instant::class.java); _lastUpdateDate_set = true } else -> { if (_token_?.isStructStart == true) p.skipChildren() nextToken() } } _token_ = currentToken } return if(__id_set && _values_set && _lastUpdateDate_set) ArchivedEntityValuesCol(_id = __id_!!, values = _values_!!, lastUpdateDate = _lastUpdateDate_!!) else { val map = mutableMapOf<KParameter, Any?>() if(__id_set) map[parameters.getValue("_id")] = __id_ if(_values_set) map[parameters.getValue("values")] = _values_ if(_lastUpdateDate_set) map[parameters.getValue("lastUpdateDate")] = _lastUpdateDate_ primaryConstructor.callBy(map) } } } companion object { private val primaryConstructor: KFunction<ArchivedEntityValuesCol> by lazy(LazyThreadSafetyMode.PUBLICATION) { ArchivedEntityValuesCol::class.primaryConstructor!! } private val parameters: Map<String, KParameter> by lazy(LazyThreadSafetyMode.PUBLICATION) { kotlin.collections.mapOf("_id" to primaryConstructor.findParameterByName("_id")!!, "values" to primaryConstructor.findParameterByName("values")!!, "lastUpdateDate" to primaryConstructor.findParameterByName("lastUpdateDate")!!) } private val __id__reference: TypeReference<Id<ArchivedEntityValuesCol>> = object : TypeReference<Id<ArchivedEntityValuesCol>>() {} private val _values__reference: TypeReference<List<ArchivedEntityValuesCol.ArchivedEntityValueWrapper>> = object : TypeReference<List<ArchivedEntityValuesCol.ArchivedEntityValueWrapper>>() {} } }
163
null
127
475
890f69960997ae9146747d082d808d92ee407fcb
4,678
tock
Apache License 2.0
src/commonMain/kotlin/uk/org/jurg/yakl/engine/v2/exceptions/DuplicateKeyException.kt
jurgc11
250,645,845
false
null
/* * Copyright (c) 2018, http://www.snakeyaml.org * Copyright (c) 2020, <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.org.jurg.yakl.engine.v2.exceptions /** * Indicate duplicate keys in the same mapping */ class DuplicateKeyException ( contextMark: Mark?, key: Any?, problemMark: Mark? ) : ConstructorException( "while constructing a mapping", contextMark, "found duplicate key $key", problemMark )
2
Kotlin
0
3
5677967ab51f4bc6096bd6b953248f389898aa9d
962
yakl
Apache License 2.0
app/src/main/java/dev/arkbuilders/rate/presentation/summary/SummaryViewModel.kt
ARK-Builders
515,514,394
false
null
package space.taran.arkrate.presentation.summary import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import space.taran.arkrate.data.GeneralCurrencyRepo import space.taran.arkrate.data.assets.AssetsRepo import javax.inject.Inject import javax.inject.Singleton class SummaryViewModel( private val assetsRepo: AssetsRepo, private val currencyRepo: GeneralCurrencyRepo ) : ViewModel() { var total = MutableStateFlow<Map<String, Double>?>(null) var exchange = MutableStateFlow<Map<String, Double>?>(null) init { viewModelScope.launch { calculateTotal() calculateExchange() } assetsRepo.allCurrencyAmountFlow().onEach { calculateTotal() calculateExchange() }.launchIn(viewModelScope) } private suspend fun calculateTotal() { val count = assetsRepo.allCurrencyAmount().map { it.code to it.amount }.toMap() val rates = currencyRepo.getCurrencyRate().associate { it.code to it.rate } val result = mutableMapOf<String, Double>() var USD = 0.0 count.forEach { USD += it.value * rates[it.key]!! } count.forEach { result[it.key] = USD / rates[it.key]!! } total.emit(result) } private suspend fun calculateExchange() { val count = assetsRepo.allCurrencyAmount().map { it.code to it.amount }.toMap() val rates = currencyRepo.getCurrencyRate().associate { it.code to it.rate } val result = mutableMapOf<String, Double>() count.forEach { i -> count.forEach { j -> if (j.key != i.key) { result["${i.key}/${j.key}"] = rates[i.key]!! / rates[j.key]!! } } } exchange.emit(result) } } @Singleton class SummaryViewModelFactory @Inject constructor( private val assetsRepo: AssetsRepo, private val currencyRepo: GeneralCurrencyRepo ) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return SummaryViewModel(assetsRepo, currencyRepo) as T } }
6
Kotlin
1
2
2f3c9b160016954df658d354bb3dbbc83df22ea5
2,404
ARK-Rate
MIT License
lib/src/main/kotlin/model/Statement.kt
sschuberth
110,685,170
false
null
@file:UseSerializers( dev.schuberth.stan.utils.LocaleSerializer::class, dev.schuberth.stan.utils.LocalDateSerializer::class ) package dev.schuberth.stan.model import java.time.LocalDate import java.util.Locale import kotlinx.serialization.Serializable import kotlinx.serialization.UseSerializers @Serializable @Suppress("LongParameterList") data class Statement( val filename: String, val locale: Locale, val bankId: String, val accountId: String, val fromDate: LocalDate, val toDate: LocalDate, val balanceOld: Float, val balanceNew: Float, val sumIn: Float, val sumOut: Float, val bookings: MutableList<BookingItem> ) : Comparable<Statement> { override fun compareTo(other: Statement) = fromDate.compareTo(other.fromDate) }
0
Kotlin
2
9
c7fe4feaaf5dfdd4fc197b16ff40ed7fb0790b48
786
stan
Apache License 2.0
src/main/kotlin/site/xiaocao/genshin/dto/QueryRole.kt
git-xiaocao
458,071,305
false
null
package site.xiaocao.genshin.dto import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class QueryRole( @SerialName("character_ids") val characterIds: List<Int>, @SerialName("role_id") val roleId: String, val server: String, )
0
Kotlin
1
8
8bacbda35cc9008339ae197ddfa069765e668a54
296
genshin-query
MIT License
data/src/main/java/com/youhajun/data/models/dto/gpt/ChatGptResponse.kt
YeonjunNotPed
757,175,597
false
{"Kotlin": 402548}
package com.youhajun.model_data.gpt import com.google.gson.annotations.SerializedName data class ChatGptResponse( @SerializedName("id") val id: String, @SerializedName("choices") val messageList: List<ChatGptMessageInfoResponse>, @SerializedName("created") val created: Long, @SerializedName("model") val model: String, )
0
Kotlin
0
0
d097fe886b1d8d030569765d8a10edd461e89830
358
MyTask
Apache License 2.0
airbyte-data/src/test/kotlin/io/airbyte/data/services/impls/data/DeclarativeManifestImageVersionServiceDataImplTest.kt
airbytehq
592,970,656
false
null
package io.airbyte.data.services.impls.data import io.airbyte.data.repositories.DeclarativeManifestImageVersionRepository import io.airbyte.data.repositories.entities.DeclarativeManifestImageVersion import io.mockk.clearAllMocks import io.mockk.confirmVerified import io.mockk.every import io.mockk.mockk import io.mockk.verify import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import java.util.Optional internal class DeclarativeManifestImageVersionServiceDataImplTest { private val declarativeManifestImageVersionRepository = mockk<DeclarativeManifestImageVersionRepository>() private val declarativeManifestImageVersionService = DeclarativeManifestImageVersionServiceDataImpl(declarativeManifestImageVersionRepository) @BeforeEach fun reset() { clearAllMocks() } @Test fun `test write new declarative manifest image version`() { val majorVersion = 0 val declarativeManifestImageVersion = "0.0.1" val version = DeclarativeManifestImageVersion(majorVersion, declarativeManifestImageVersion) every { declarativeManifestImageVersionRepository.existsById(majorVersion) } returns false every { declarativeManifestImageVersionRepository.save(version) } returns version val result = declarativeManifestImageVersionService.writeDeclarativeManifestImageVersion(majorVersion, declarativeManifestImageVersion) assert(result == version) verify { declarativeManifestImageVersionRepository.existsById(majorVersion) declarativeManifestImageVersionRepository.save(version) } confirmVerified(declarativeManifestImageVersionRepository) } @Test fun `test write existing declarative manifest image version`() { val majorVersion = 0 val declarativeManifestImageVersion = "0.0.2" val newVersion = DeclarativeManifestImageVersion(majorVersion, declarativeManifestImageVersion) every { declarativeManifestImageVersionRepository.existsById(majorVersion) } returns true every { declarativeManifestImageVersionRepository.update(newVersion) } returns newVersion val result = declarativeManifestImageVersionService.writeDeclarativeManifestImageVersion(majorVersion, declarativeManifestImageVersion) assert(result == newVersion) verify { declarativeManifestImageVersionRepository.existsById(majorVersion) declarativeManifestImageVersionRepository.update(newVersion) } confirmVerified(declarativeManifestImageVersionRepository) } @Test fun `test get declarative manifest image version by major version`() { val majorVersion = 0 val declarativeManifestImageVersion = "0.0.1" val version = DeclarativeManifestImageVersion(majorVersion, declarativeManifestImageVersion) every { declarativeManifestImageVersionRepository.findById(majorVersion) } returns Optional.of(version) val result = declarativeManifestImageVersionService.getImageVersionByMajorVersion(majorVersion) assert(result == declarativeManifestImageVersion) verify { declarativeManifestImageVersionRepository.findById(majorVersion) } confirmVerified(declarativeManifestImageVersionRepository) } @Test fun `test get declarative manifest image version by major version not found`() { val majorVersion = 0 every { declarativeManifestImageVersionRepository.findById(majorVersion) } returns Optional.empty() assertThrows<IllegalStateException> { declarativeManifestImageVersionService.getImageVersionByMajorVersion(majorVersion) } verify { declarativeManifestImageVersionRepository.findById(majorVersion) } confirmVerified(declarativeManifestImageVersionRepository) } @Test fun `test list declarative manifest image versions`() { val declarativeManifestImageVersion0 = DeclarativeManifestImageVersion(0, "0.0.1") val declarativeManifestImageVersion1 = DeclarativeManifestImageVersion(1, "1.0.0") val declarativeManifestImageVersion2 = DeclarativeManifestImageVersion(2, "2.0.0") every { declarativeManifestImageVersionRepository.findAll() } returns listOf(declarativeManifestImageVersion0, declarativeManifestImageVersion1, declarativeManifestImageVersion2) val result = declarativeManifestImageVersionService.listDeclarativeManifestImageVersions() assert(result == listOf(declarativeManifestImageVersion0, declarativeManifestImageVersion1, declarativeManifestImageVersion2)) } }
54
null
249
205
a2e58f1b60ea79ec96546c98f712077c82de373a
4,449
airbyte-platform
MIT License
app/src/main/java/com/merttoptas/composebase/features/component/RickAndMortySearchBar.kt
merttoptas
467,006,657
false
null
package com.berger.baseapp.features.component import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.shadow import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.berger.baseapp.R /** * Created by merttoptas on 9.04.2022 */ @Composable fun RickAndMortySearchBar( modifier: Modifier = Modifier, text: String, onTextChange: (text: String) -> Unit, onClickSearch: () -> Unit ) { Box( modifier = modifier .fillMaxWidth() .wrapContentHeight() .shadow(elevation = 10.dp) ) { RickAndMortyTextField( value = text, onValueChange = { onTextChange(it) }, placeholder = { RickAndMortyText( text = "Search character for name", color = colorResource(R.color.light_gray), ) }, ) Box( Modifier .background( color = MaterialTheme.colors.onPrimary, shape = RoundedCornerShape(14.dp) ) .size(56.dp) .clickable { onClickSearch() } .align(Alignment.CenterEnd), contentAlignment = Alignment.Center ) { Image( painter = painterResource(id = R.drawable.ic_baseline_search_24), contentDescription = null ) } } } @Preview @Composable fun PreviewMinimaSearchBar() { RickAndMortySearchBar(text = "", onTextChange = {}, onClickSearch = {}) }
2
null
25
227
84ce69aaab69ca351c09712bc7213da0dcbf7639
2,228
BaseApp-Jetpack-Compose-Android-Kotlin
Apache License 2.0
core/src/main/kotlin/net/rikarin/options/OptionsManager.kt
Rikarin
586,107,122
false
null
package net.rikarin.options class OptionsManager<TOptions : Any>(private val factor: OptionsFactory<TOptions>) : Options<TOptions>, OptionsSnapshot<TOptions> { private val _cache = OptionsCache<TOptions>() override fun get(name: String?): TOptions { val n = name ?: Options.DEFAULT_NAME TODO("Not yet implemented") } override val value: TOptions get() = get(Options.DEFAULT_NAME) }
0
Kotlin
0
0
ae49fd70b3a46c5e74e161758f6e7eeaed08ed88
421
kotlin
MIT License
core/src/commonMain/kotlin/work/socialhub/kmisskey/api/request/files/FilesCreateRequest.kt
uakihir0
756,689,268
false
{"Kotlin": 248708, "Shell": 2141, "Makefile": 316}
package work.socialhub.kmisskey.api.request.files import kotlinx.serialization.Serializable import work.socialhub.kmisskey.api.model.TokenRequest import kotlin.js.JsExport @JsExport @Serializable class FilesCreateRequest : TokenRequest() { var folderId: String? = null var name: String? = null var comment: String? = null var sensitive: Boolean? = null var force: Boolean? = null var bytes: ByteArray? = null }
0
Kotlin
1
6
f59e9296d3e1976cd92fe853b5811f63a38b8d41
439
kmisskey
MIT License
plugins/pill/pill-importer/src/render.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2020 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.pill import org.jetbrains.kotlin.pill.model.* import org.jetbrains.kotlin.pill.util.* import java.io.File class PFile(val path: File, private val text: String) { constructor(path: File, xml: XmlNode) : this(path, xml.toString()) fun write() { path.parentFile.mkdirs() path.writeText(text) } } fun render(project: PProject): List<PFile> { val files = mutableListOf<PFile>() files += renderModulesFile(project) project.modules.forEach { files += renderModule(project, it) } project.libraries.forEach { files += renderLibrary(project, it) } return files } private fun renderModulesFile(project: PProject) = PFile( File(project.rootDirectory, ".idea/modules.xml"), xml("project", "version" to 4) { xml("component", "name" to "ProjectModuleManager") { xml("modules") { val pathContext = ProjectContext(project) for (module in project.modules) { val moduleFilePath = pathContext(module.moduleFile) xml("module", "fileurl" to "file://$moduleFilePath", "filepath" to moduleFilePath) } } } } ) private fun renderModule(project: PProject, module: PModule) = PFile( module.moduleFile, xml( "module", "type" to "JAVA_MODULE", "version" to 4 ) { val moduleForProductionSources = module.moduleForProductionSources if (moduleForProductionSources != null) { xml("component", "name" to "TestModuleProperties", "production-module" to moduleForProductionSources.name) } val kotlinCompileOptions = module.kotlinOptions val pathContext = ModuleContext(project, module) val platformVersion = (kotlinCompileOptions?.jvmTarget ?: "1.8") val classesDirectory = File(project.rootDirectory, "out/production/${module.name}") if (kotlinCompileOptions != null) { xml("component", "name" to "FacetManager") { xml("facet", "type" to "kotlin-language", "name" to "Kotlin") { xml("configuration", "version" to 3, "platform" to "JVM $platformVersion", "useProjectSettings" to "false") { xml("compilerSettings") { xml( "option", "name" to "additionalArguments", "value" to kotlinCompileOptions.extraArguments.joinToString(" ") ) } xml("compilerArguments") { xml("option", "name" to "destination", "value" to pathContext(classesDirectory)) fun Any?.option(name: String) { if (this != null) xml("option", "name" to name, "value" to this.toString()) } kotlinCompileOptions.noStdlib.option("noStdlib") kotlinCompileOptions.noReflect.option("noReflect") module.name.option("moduleName") xml("option", "name" to "jvmTarget", "value" to platformVersion) kotlinCompileOptions.languageVersion.option("languageVersion") kotlinCompileOptions.apiVersion.option("apiVersion") xml("option", "name" to "pluginOptions") { xml("array") } xml("option", "name" to "pluginClasspaths") { xml("array") { for (path in kotlinCompileOptions.pluginClasspath) { xml("option", "value" to path) } } } } } } } } xml( "component", "name" to "NewModuleRootManager", "LANGUAGE_LEVEL" to "JDK_${platformVersion.replace('.', '_')}", "inherit-compiler-output" to "true" ) { xml("exclude-output") for (contentRoot in module.contentRoots.filter { it.path.exists() }) { xml("content", pathContext.url(contentRoot.path)) { for (sourceRoot in contentRoot.sourceRoots) { var args = arrayOf(pathContext.url(sourceRoot.directory)) args += when (sourceRoot.kind) { PSourceRoot.Kind.PRODUCTION -> ("isTestSource" to "false") PSourceRoot.Kind.TEST -> ("isTestSource" to "true") PSourceRoot.Kind.RESOURCES -> ("type" to "java-resource") PSourceRoot.Kind.TEST_RESOURCES -> ("type" to "java-test-resource") } xml("sourceFolder", *args) } for (excludedDir in contentRoot.excludedDirectories) { xml("excludeFolder", pathContext.url(excludedDir)) } } } when (val javaLanguageVersion = module.javaLanguageVersion) { null -> xml("orderEntry", "type" to "inheritedJdk") else -> xml("orderEntry", "type" to "jdk", "jdkName" to javaLanguageVersion.toString(), "jdkType" to "JavaSDK") } xml("orderEntry", "type" to "sourceFolder", "forTests" to "false") for (orderRoot in module.orderRoots) { val dependency = orderRoot.dependency val args = when (dependency) { is PDependency.ModuleLibrary -> mutableListOf( "type" to "module-library" ) is PDependency.Module -> mutableListOf( "type" to "module", "module-name" to dependency.name ) is PDependency.Library -> mutableListOf( "type" to "library", "name" to dependency.name, "level" to "project" ) } if (orderRoot.scope != POrderRoot.Scope.COMPILE) { args.add(1, "scope" to orderRoot.scope.toString()) } if (dependency is PDependency.Module && orderRoot.isProductionOnTestDependency) { args += ("production-on-test" to "") } if (orderRoot.isExported) { args += ("exported" to "") } xml("orderEntry", *args.toTypedArray()) { if (dependency is PDependency.ModuleLibrary) { add(renderLibraryToXml(dependency.library, pathContext, named = false)) } } } } } ) private fun renderLibrary(project: PProject, library: PLibrary): PFile { val pathContext = ProjectContext(project) // TODO find how IDEA escapes library names val escapedName = library.renderName().replace(" ", "_").replace(".", "_").replace("-", "_") return PFile( File(project.rootDirectory, ".idea/libraries/$escapedName.xml"), xml("component", "name" to "libraryTable") { add(renderLibraryToXml(library, pathContext)) }) } private fun renderLibraryToXml(library: PLibrary, pathContext: PathContext, named: Boolean = true): XmlNode { val args = if (named) arrayOf("name" to library.renderName()) else emptyArray() return xml("library", *args) { xml("CLASSES") { library.classes.forEach { xml("root", pathContext.url(it)) } } xml("JAVADOC") { library.javadoc.forEach { xml("root", pathContext.url(it)) } } xml("SOURCES") { library.sources.forEach { xml("root", pathContext.url(it)) } } } } fun PLibrary.renderName() = name.takeIf { it != "unspecified" } ?: classes.first().nameWithoutExtension
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
8,435
kotlin
Apache License 2.0
idea/testData/quickfix/typeMismatch/typeMismatchOnReturnedExpression/beforeDontChangeFunctionReturnTypeToErrorType.kt
develar
4,304,550
false
null
// "Change 'foo' function return type to '([ERROR : NoSuchType]) -> Int'" "false" // ERROR: <html>Type mismatch.<table><tr><td>Required:</td><td>kotlin.Int</td></tr><tr><td>Found:</td><td>([ERROR : NoSuchType]) &rarr; kotlin.Int</td></tr></table></html> // ERROR: Unresolved reference: NoSuchType fun foo(): Int { return { (x: NoSuchType<caret>) -> 42 } }
0
null
0
1
bf5b387580265cba01efc8fd30d1d0c0b41ac5a9
359
kotlin
Apache License 2.0
compiler/testData/loadJava/compiledKotlin/annotations/classes/Simple.kt
JakeWharton
99,388,807
false
null
package test annotation class Anno @Anno class X
179
null
5640
83
4383335168338df9bbbe2a63cb213a68d0858104
51
kotlin
Apache License 2.0
src/main/kotlin/com/ex_dock/ex_dock/frontend/text_pages/router/textPagesRouter.kt
rensPols
849,499,548
false
{"Kotlin": 36915, "Dockerfile": 511}
package com.ex_dock.ex_dock.frontend.text_pages.router import io.vertx.ext.web.Router import io.vertx.core.Vertx fun Router.initTextPages(vertx: Vertx) { val textPagesRouter = Router.router(vertx) textPagesRouter.get("/").handler { ctx -> ctx.end("request to textPagesRouter successful") } this.route("/text-pages*").subRouter(textPagesRouter) }
14
Kotlin
0
2
54268d24375a78e50a2cb78235256e391674927f
362
ex-dock
Apache License 2.0
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/columns/renderers/PackageScoreTableCellRenderer.kt
ingokegel
72,937,917
true
null
/******************************************************************************* * Copyright 2000-2023 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.renderers import com.intellij.ui.components.JBLabel import com.intellij.ui.hover.TableHoverListener import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.PackagesTableItem import net.miginfocom.swing.MigLayout import org.jetbrains.idea.packagesearch.SortMetric import java.text.DecimalFormat import javax.swing.JComponent import javax.swing.JPanel import javax.swing.JTable import javax.swing.table.TableCellRenderer internal object PackageScoreTableCellRenderer : TableCellRenderer { private var sortMetric = SortMetric.NONE fun updateData(sortMetric: SortMetric) { this.sortMetric = sortMetric } private val suffix = arrayOf("", "k", "m", "b", "t") private const val MAX_LENGTH = 4 private fun formatScore(score: Number): String { var r: String = DecimalFormat("##0E0").format(score) r = r.replace("E[0-9]".toRegex(), suffix[Character.getNumericValue(r[r.length - 1]) / 3]) while (r.length > MAX_LENGTH || r.matches("[0-9]+\\.[a-z]".toRegex())) { r = r.substring(0, r.length - 2) + r.substring(r.length - 1) } return r } override fun getTableCellRendererComponent( table: JTable, value: Any, isSelected: Boolean, hasFocus: Boolean, row: Int, column: Int ) = JPanel(MigLayout("al left center, insets 0 8 0 0")).apply { require(value is PackagesTableItem<*>) { "The value $value is expected to be a PackagesTableItem, but wasn't." } val sortMetricValue = value.packageModel.getSortMetricValue(sortMetric) val formattedMetricValue = formatScore(sortMetricValue) val scoreString: String = when (sortMetric) { SortMetric.GITHUB_STARS -> "$formattedMetricValue ★" SortMetric.OSS_HEALTH, SortMetric.DEPENDENCY_RATING, SortMetric.STACKOVERFLOW_HEALTH -> formattedMetricValue else -> "" } val isHover = TableHoverListener.getHoveredRow(table) == row val isSearchResult = value is PackagesTableItem.InstallablePackage val colors = computeColors(isSelected, isHover, isSearchResult) colors.applyTo(this) val labelComponent: JComponent = JBLabel().apply { text = scoreString background = colors.background foreground = colors.foreground } add(labelComponent) } }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
3,348
intellij-community
Apache License 2.0
Corona-Warn-App/src/test/java/de/rki/coronawarnapp/submission/auto/AutoSubmissionTest.kt
corona-warn-app
268,027,139
false
null
package de.rki.coronawarnapp.submission.auto import androidx.work.ExistingPeriodicWorkPolicy import androidx.work.NetworkType import androidx.work.WorkManager import de.rki.coronawarnapp.coronatest.type.BaseCoronaTest import de.rki.coronawarnapp.submission.SubmissionSettings import de.rki.coronawarnapp.submission.task.SubmissionTask import de.rki.coronawarnapp.task.TaskController import de.rki.coronawarnapp.task.TaskRequest import de.rki.coronawarnapp.task.TaskState import de.rki.coronawarnapp.task.common.DefaultTaskRequest import de.rki.coronawarnapp.task.submitBlocking import de.rki.coronawarnapp.util.TimeStamper import io.mockk.Called import io.mockk.MockKAnnotations import io.mockk.Runs import io.mockk.coEvery import io.mockk.coVerifySequence import io.mockk.every import io.mockk.impl.annotations.MockK import io.mockk.just import io.mockk.mockk import io.mockk.mockkStatic import io.mockk.slot import io.mockk.verify import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.flowOf import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import testhelpers.BaseTest import testhelpers.coroutines.runTest2 import java.time.Instant class AutoSubmissionTest : BaseTest() { @MockK lateinit var timeStamper: TimeStamper @MockK lateinit var submissionSettings: SubmissionSettings @MockK lateinit var workManager: WorkManager @MockK lateinit var taskController: TaskController private val autoSubmissionEnabled: Flow<Boolean> = flowOf(false) private val lastSubmissionUserActivityUTC: Flow<Instant> = flowOf(Instant.EPOCH) private val autoSubmissionAttemptsCount: Flow<Int> = flowOf(0) private val autoSubmissionAttemptsLast: Flow<Instant> = flowOf(Instant.EPOCH) @BeforeEach fun setup() { MockKAnnotations.init(this) every { workManager.cancelAllWorkByTag(any()) } returns mockk() every { workManager.enqueueUniquePeriodicWork(any(), any(), any()) } returns mockk() every { submissionSettings.autoSubmissionEnabled } returns autoSubmissionEnabled every { submissionSettings.lastSubmissionUserActivityUTC } returns lastSubmissionUserActivityUTC every { submissionSettings.autoSubmissionAttemptsCount } returns autoSubmissionAttemptsCount every { submissionSettings.autoSubmissionAttemptsLast } returns autoSubmissionAttemptsLast coEvery { submissionSettings.updateAutoSubmissionEnabled(any()) } just Runs coEvery { submissionSettings.updateLastSubmissionUserActivityUTC(any()) } just Runs coEvery { submissionSettings.updateAutoSubmissionAttemptsCount(any()) } just Runs coEvery { submissionSettings.updateAutoSubmissionAttemptsLast(any()) } just Runs every { taskController.tasks } returns emptyFlow() every { timeStamper.nowUTC } returns Instant.ofEpochMilli(123456789) mockkStatic("de.rki.coronawarnapp.task.TaskControllerExtensionsKt") } private fun createInstance(appScope: CoroutineScope) = AutoSubmission( appScope = appScope, timeStamper = timeStamper, submissionSettings = submissionSettings, workManager = workManager, taskController = taskController ) @Test fun `init is sideeffect free`() = runTest2 { createInstance(this) verify { workManager wasNot Called } } @Test fun `update mode DISABLED`() = runTest2 { val instance = createInstance(this) instance.updateMode(AutoSubmission.Mode.DISABLED) coVerifySequence { workManager.cancelAllWorkByTag("AutoSubmissionWorker") submissionSettings.updateAutoSubmissionEnabled(false) submissionSettings.updateLastSubmissionUserActivityUTC(Instant.EPOCH) submissionSettings.updateAutoSubmissionAttemptsCount(0) submissionSettings.updateAutoSubmissionAttemptsLast(Instant.EPOCH) } } @Test fun `update mode MONITOR`() = runTest2 { val instance = createInstance(this) instance.updateMode(AutoSubmission.Mode.MONITOR) coVerifySequence { submissionSettings.updateLastSubmissionUserActivityUTC(Instant.ofEpochMilli(123456789)) submissionSettings.updateAutoSubmissionEnabled(true) workManager.enqueueUniquePeriodicWork( "AutoSubmissionWorker", ExistingPeriodicWorkPolicy.KEEP, any() ) } } @Test fun `update mode SUBMIT_ASAP`() = runTest2 { val instance = createInstance(this) instance.updateMode(AutoSubmission.Mode.SUBMIT_ASAP) coVerifySequence { submissionSettings.updateLastSubmissionUserActivityUTC(Instant.EPOCH) submissionSettings.updateAutoSubmissionEnabled(true) workManager.enqueueUniquePeriodicWork( "AutoSubmissionWorker", ExistingPeriodicWorkPolicy.KEEP, match { it.workSpec.constraints.requiredNetworkType == NetworkType.CONNECTED && it.workSpec.intervalDuration == 15 * 60 * 1000L } ) } } @Test fun `blocking submission successful`() = runTest2 { val instance = createInstance(this) val slot = slot<TaskRequest>() val taskResult = mockk<TaskState>().apply { every { isSuccessful } returns true } coEvery { taskController.submitBlocking(capture(slot)) } returns taskResult instance.runSubmissionNow(BaseCoronaTest.Type.PCR) coVerifySequence { taskController.submitBlocking( DefaultTaskRequest( id = slot.captured.id, type = SubmissionTask::class, arguments = SubmissionTask.Arguments(checkUserActivity = false, testType = BaseCoronaTest.Type.PCR), originTag = "AutoSubmission" ) ) } } @Test fun `blocking submission failure sets up SUBMIT_ASAP`() = runTest2 { val instance = createInstance(this) val slot = slot<TaskRequest>() val taskResult = mockk<TaskState>().apply { every { isSuccessful } returns false every { error } returns Exception() } coEvery { taskController.submitBlocking(capture(slot)) } returns taskResult instance.runSubmissionNow(BaseCoronaTest.Type.PCR) coVerifySequence { submissionSettings.updateLastSubmissionUserActivityUTC(Instant.EPOCH) submissionSettings.updateAutoSubmissionEnabled(true) workManager.enqueueUniquePeriodicWork( "AutoSubmissionWorker", ExistingPeriodicWorkPolicy.KEEP, any() ) } } }
6
Kotlin
504
2,486
7b0eee8d53a090ee0ca585c6a90c4cec570e51d6
6,930
cwa-app-android
Apache License 2.0
compiler/testData/codegen/box/invokedynamic/sam/builtinMemberReference.kt
JetBrains
3,432,266
false
null
// TARGET_BACKEND: JVM // JVM_TARGET: 1.8 // SAM_CONVERSIONS: INDY // CHECK_BYTECODE_TEXT // 0 java/lang/invoke/LambdaMetafactory // 1 final synthetic class BuiltinMemberReferenceKt\$box\$test\$1 fun interface IntFun { fun invoke(i: Int): Int } fun invoke1(intFun: IntFun) = intFun.invoke(1) fun box(): String { val test = invoke1(41::plus) if (test != 42) return "Failed: $test" return "OK" }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
415
kotlin
Apache License 2.0
gradle/apps/kotlin-portlet/src/main/kotlin/com/liferay/blade/samples/portlet/kotlin/KotlinGreeterPortletKt.kt
roberto1073
116,287,398
true
{"Java": 2581793, "JavaScript": 13795, "Shell": 7592, "FreeMarker": 5931, "Batchfile": 5630, "CSS": 3504, "Kotlin": 3457, "TypeScript": 3113, "HTML": 982, "PLSQL": 930}
/** * Copyright 2000-present Liferay, 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 com.liferay.blade.samples.portlet.kotlin import com.liferay.portal.kernel.portlet.bridges.mvc.MVCPortlet import javax.portlet.Portlet import org.osgi.service.component.annotations.Component /** * @author Liferay */ @Component( immediate = true, property = arrayOf( "com.liferay.portlet.css-class-wrapper=portlet-greeter", "com.liferay.portlet.display-category=category.sample", "com.liferay.portlet.instanceable=true", "javax.portlet.display-name=Kotlin Greeter Portlet", "javax.portlet.init-param.template-path=/", "javax.portlet.init-param.view-template=/view.jsp", "javax.portlet.name=KotlinGreeterPortletKt", "javax.portlet.security-role-ref=power-user,user" ), service = arrayOf(Portlet::class)) class KotlinGreeterPortletKt : MVCPortlet()
0
Java
0
0
d12954a751aa2f0c940d5f5782b589523ed4ba73
1,385
liferay-blade-samples
Apache License 2.0
clientprotocol/src/commonMain/generated/org/inthewaves/kotlinsignald/clientprotocol/v1/structures/SendRequest.kt
inthewaves
398,221,861
false
null
// File is generated by ./gradlew generateSignaldClasses --- do not edit unless reformatting package org.inthewaves.kotlinsignald.clientprotocol.v1.structures import kotlinx.serialization.KSerializer import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import org.inthewaves.kotlinsignald.clientprotocol.SocketCommunicator import org.inthewaves.kotlinsignald.clientprotocol.SuspendSocketCommunicator import org.inthewaves.kotlinsignald.clientprotocol.v1.requests.JsonMessageWrapper import org.inthewaves.kotlinsignald.clientprotocol.v1.requests.Send @Serializable @SerialName("send") public data class SendRequest( /** * Example: "+12024561414" */ public val username: String, public val recipientAddress: JsonAddress? = null, /** * Example: "<KEY> */ public val recipientGroupId: String? = null, /** * Example: "hello" */ public val messageBody: String? = null, public val attachments: List<JsonAttachment>? = null, public val quote: JsonQuote? = null, public val timestamp: Long? = null, public val mentions: List<JsonMention>? = null, public val previews: List<JsonPreview>? = null, /** * Optionally set to a sub-set of group members. Ignored if recipientGroupId isn't specified */ public val members: List<JsonAddress>? = null ) : SignaldRequestBodyV1<SendResponse>() { internal override val responseWrapperSerializer: KSerializer<Send> get() = Send.serializer() internal override val responseDataSerializer: KSerializer<SendResponse> get() = SendResponse.serializer() internal override fun getTypedResponseOrNull(responseWrapper: JsonMessageWrapper<*>): SendResponse? = if (responseWrapper is Send && responseWrapper.data is SendResponse) { responseWrapper.data } else { null } /** * @throws org.inthewaves.kotlinsignald.clientprotocol.RequestFailedException if the signald * socket sends a bad or error response, or unable to serialize our request * @throws org.inthewaves.kotlinsignald.clientprotocol.SignaldException if an I/O error occurs * during socket communication * @throws NoSuchAccountError * @throws ServerNotFoundError * @throws InvalidProxyError * @throws NoSendPermissionError * @throws InvalidAttachmentError * @throws InternalError * @throws InvalidRequestError * @throws UnknownGroupError * @throws RateLimitError * @throws InvalidRecipientError * @throws AttachmentTooLargeError */ public override fun submit(socketCommunicator: SocketCommunicator, id: String): SendResponse = super.submit(socketCommunicator, id) /** * @throws org.inthewaves.kotlinsignald.clientprotocol.RequestFailedException if the signald * socket sends a bad or error response, or unable to serialize our request * @throws org.inthewaves.kotlinsignald.clientprotocol.SignaldException if an I/O error occurs * during socket communication * @throws NoSuchAccountError * @throws ServerNotFoundError * @throws InvalidProxyError * @throws NoSendPermissionError * @throws InvalidAttachmentError * @throws InternalError * @throws InvalidRequestError * @throws UnknownGroupError * @throws RateLimitError * @throws InvalidRecipientError * @throws AttachmentTooLargeError */ public override suspend fun submitSuspend( socketCommunicator: SuspendSocketCommunicator, id: String ): SendResponse = super.submitSuspend(socketCommunicator, id) }
2
Kotlin
1
2
9259e3f41e87f32b4bf2e6f88179489e4f36d8ca
3,621
kotlin-signald
MIT License
core-starter/src/main/kotlin/com/labijie/application/data/pojo/FileIndex.kt
hongque-pro
309,874,586
false
{"Kotlin": 1021178, "Java": 72766}
@file:Suppress("RedundantVisibilityModifier") package com.labijie.application.`data`.pojo import kotlin.Long import kotlin.String /** * POJO for FileIndexTable * * This class made by a code generation tool (https://github.com/hongque-pro/infra-orm). * * Don't modify these codes !! * * Origin Exposed Table: * @see com.labijie.application.data.FileIndexTable */ public open class FileIndex { public var path: String = "" public var timeCreated: Long = 0L public var fileType: String = "" public var entityId: Long = 0L public var id: Long = 0L }
0
Kotlin
0
7
9cb2b41de76734d1743f61419a5a31c9546f5d79
572
application-framework
Apache License 2.0
app/src/main/java/com/searchit/hastime/receiver/ScreenStateReceiver.kt
AmanBang
876,281,406
false
{"Kotlin": 31218}
package com.searchit.hastime.receiver import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.util.Log import com.searchit.hastime.Room.MyDatabase import com.searchit.hastime.Room.model.EventLog import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import java.text.SimpleDateFormat import java.util.Date import java.util.Locale class ScreenStateReceiver : BroadcastReceiver() { private val TAG = "ScreenStateReceiver" override fun onReceive(context: Context, intent: Intent) { val eventType = when (intent.action) { Intent.ACTION_SCREEN_OFF -> "LOCK" Intent.ACTION_SCREEN_ON -> "UNLOCK" else -> null } if (eventType != null) { val currentTimeMillis = System.currentTimeMillis() val timeFormated = SimpleDateFormat("HH:mm:ss", Locale.getDefault()) val formattedTime = timeFormated.format(Date(currentTimeMillis)) val currentDate = Date() val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()) val formattedDate = dateFormat.format(currentDate) val RTime = "$formattedDate | $formattedTime" Log.i(TAG, "onReceive: Event :" + eventType + "| "+ RTime) val eventLog = EventLog(eventType = eventType, timestamp = RTime) CoroutineScope(Dispatchers.IO).launch { MyDatabase.getDatabase(context).eventLogDao().insertEventLog(eventLog) } } } }
0
Kotlin
0
0
1fcb15dc177b3f634ff7cc27437169b68934015d
1,599
HasTime
MIT License
list/src/testCommon/kotlin/com/rey/movies/data/source/remote/FakeMovieRemoteDataImpl.kt
stefanus-dany
371,651,162
false
{"Kotlin": 30424}
package com.rey.movies.data.source.remote import com.rey.lib.cleanarch.domain.dto.Result import com.rey.lib.cleanarch.domain.dto.UNKNOWN_ERROR import com.rey.lib.cleanarch.domain.dto.suspendTryCatch import com.rey.list.data.repository.source.remote.MovieRemoteData import com.rey.movies.domain.dto.MovieResponse class FakeMovieRemoteDataImpl( private val throwError: Boolean = false, private val movieList: List<MovieResponse> = emptyList() ) : MovieRemoteData { override suspend fun getMovies(): Result<List<MovieResponse>> = suspendTryCatch { if (throwError) throw Exception(UNKNOWN_ERROR) Result.Success(movieList) } }
0
Kotlin
1
0
9d910b5e9d52fc5cf7e752a709f9c3e21fcc80be
655
android-movies-sample
Apache License 2.0
shared/src/commonMain/kotlin/WelcomeScreen.kt
Pireeee
721,595,517
false
{"Kotlin": 27812, "Swift": 580, "Shell": 228}
import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Button import androidx.compose.material.ButtonDefaults import androidx.compose.material.Card import androidx.compose.material.Text 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.layout.ContentScale import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import moe.tlaster.precompose.navigation.Navigator import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.painterResource @OptIn(ExperimentalResourceApi::class) @Composable() internal fun welcomeScreen(navigator: Navigator) { Box( contentAlignment = Alignment.Center, modifier = Modifier.fillMaxWidth().fillMaxHeight() ) { background("Background.png") Card( shape = RoundedCornerShape(8.dp), modifier = Modifier.padding(10.dp).size(200.dp), backgroundColor = Color.Gray ) { Column(horizontalAlignment = Alignment.CenterHorizontally) { Column(horizontalAlignment = Alignment.CenterHorizontally) { Text( text = "Quiz", fontSize = 30.sp, modifier = Modifier.padding(all = 10.dp) ) Text( modifier = Modifier.padding(all = 10.dp), text = "A simple Quiz to discovers KMP and compose.", ) Button( modifier = Modifier.padding(bottom = 20.dp), colors = ButtonDefaults.buttonColors( Color(0xff70b237), Color(0xff854f2b), Color(0xff8fca5c), Color(0xff854f2b) ), onClick = { navigator.navigate(route = "/quiz") } ) { Text("Start the Quiz") } } } } } }
0
Kotlin
0
0
0136aeff324b4e7833430238a1aab42762451668
2,991
MineQuizProjet
Apache License 2.0
microservices/edge/src/main/kotlin/kr/revfactory/edge/controller/CrmRestController.kt
revfactory
437,314,629
false
null
package kr.revfactory.edge.controller import kr.revfactory.edge.service.CrmService import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.ResponseBody @Controller @ResponseBody class CrmRestController(private val crmService: CrmService) { @GetMapping("/customerProfiles") suspend fun customerProfiles() = this.crmService.customerProfiles() }
0
Kotlin
0
0
01f567d7a3bfd24c7cbdb6423a61ac85610eb1b6
452
reactive-programming
Apache License 2.0
app/src/main/java/com/suihan74/hatenaLib/EntriesType.kt
suihan74
207,459,108
false
{"Kotlin": 1729040, "Java": 10330}
package com.suihan74.hatenaLib import androidx.annotation.StringRes import com.suihan74.satena.R enum class EntriesType(val id: Int) { Hot(0), Recent(1); // for Gson private constructor() : this(0) companion object { fun fromId(id: Int) = values().firstOrNull { it.id == id } ?: Hot fun fromOrdinal(idx: Int) = values().getOrElse(idx) { Hot } } } enum class SearchType( val id: Int, @StringRes val textId: Int ) { Tag(0, R.string.search_type_tag), Title(2, R.string.search_type_title), Text(1, R.string.search_type_text); // ------ // // for Gson private constructor() : this(0, 0) companion object { fun fromId(i: Int) = values().firstOrNull { it.id == i } ?: Tag fun fromOrdinal(i: Int) = values().getOrElse(i) { Tag } } }
14
Kotlin
1
7
ee29a0ed1d60c9ee35bb03f128d0e39c58e3a4c4
832
Satena
MIT License
App/app/src/main/java/com/app/appellas/viewmodel/user/HomeViewModel.kt
spocasangre
656,841,017
false
null
/* Copyright 2023 WeGotYou! 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.app.appellas.viewmodel.user import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.app.appellas.R import com.app.appellas.data.models.dtos.response.LocationResponse import com.app.appellas.data.network.AppAPI import com.app.appellas.data.network.UIState import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import okio.IOException class HomeViewModel(): ViewModel() { private val _goAlertDetail = MutableLiveData<Boolean?>() val goAlertDetail: LiveData<Boolean?> = _goAlertDetail var notificationId = MutableLiveData("") fun goAlertDetail(id: String) { _goAlertDetail.value = true notificationId.value = id } fun endGoAlertDetail() { _goAlertDetail.value = null } private val _stateUI = MutableLiveData<UIState<Int>?>() val stateUI: LiveData<UIState<Int>?> = _stateUI val alertDetail = MutableLiveData<LocationResponse>() fun getAlertDetail(token: String, id: Int) { viewModelScope.launch(Dispatchers.IO) { try { val call = AppAPI.locationService.getAlertDetail("Bearer $token", id) val response = call.body() val errorCode = response?.code ?: 0 val data = response?.data val message = response?.message ?: "Error" withContext(Dispatchers.Main) { if(call.isSuccessful) { if(errorCode == 1) { alertDetail.value = data?.let { it } _stateUI.value = UIState.Success _stateUI.value = null } else { _stateUI.value = UIState.Error(message) _stateUI.value = null } } else { _stateUI.value = UIState.Error("Error de coneccion") } } } catch (e: IOException) { withContext(Dispatchers.Main) { _stateUI.value = UIState.Error("Error de coneccion") } } } } }
0
Kotlin
0
0
2d91163f417b8f56a334d16abcad4aec3dc28ab3
2,894
proyecto_aca_2023
Apache License 2.0
src/test/kotlin/com/aquivalabs/force/ant/reporters/CoberturaCoverageReporterTestCase.kt
valmaev
70,699,743
false
null
package com.aquivalabs.force.ant.reporters import com.aquivalabs.force.ant.codeCoverageResult import com.aquivalabs.force.ant.codeLocation import com.aquivalabs.force.ant.deployResult import com.aquivalabs.force.ant.runTestsResult import com.aquivalabs.force.ant.reporters.cobertura.Coverage import com.aquivalabs.force.ant.reporters.cobertura.Packages import com.sforce.soap.metadata.CodeCoverageResult import org.hamcrest.MatcherAssert.* import org.hamcrest.core.IsEqual.* import org.testng.annotations.DataProvider import org.testng.annotations.Test import java.io.File class CoberturaCoverageReporterTestCase { @Test(dataProvider = "createCoberturaReportPackagesTestData") fun createCoberturaReport_forEachCodeCoverageType_shouldCreatePackage( codeCoverage: Array<CodeCoverageResult>, projectRootPath: String, expected: Packages, reason: String) { val sut = createSystemUnderTest(projectRootPath) val testResult = runTestsResult(codeCoverage = codeCoverage) val report = sut.createCoberturaReport(deployResult(testResult)) val actual = report .children.filterIsInstance<Coverage>().single() .children.filterIsInstance<Packages>().single() assertThat(reason, actual, equalTo(expected)) } @DataProvider fun createCoberturaReportPackagesTestData(): Array<Array<out Any>> { return arrayOf( arrayOf( arrayOf<CodeCoverageResult>(), "", Packages(), "Should create empty packages element for empty array of CodeCoverageResult"), arrayOf( arrayOf( codeCoverageResult(type = "Class"), codeCoverageResult(type = "Trigger")), "", Coverage().packages { `package`("Class", `line-rate` = 1.0) { classes { `class`(`line-rate` = 1.0) { methods() lines() } } } `package`("Trigger", `line-rate` = 1.0) { classes { `class`(`line-rate` = 1.0) { methods() lines() } } } }, "Should create two packages for two types of CodeCoverageResult"), arrayOf( arrayOf( codeCoverageResult(type = null)), "", Coverage().packages { `package`(name = "", `line-rate` = 1.0) { classes { `class`(`line-rate` = 1.0) { methods() lines() } } } }, "Should create package with empty name if type of CodeCoverageResult is null"), arrayOf( arrayOf( codeCoverageResult( type = "Class", name = "Book"), codeCoverageResult( type = "Class", name = "BookBuilder", namespace = "foo"), codeCoverageResult( type = "Trigger", name = "AccountTrigger"), codeCoverageResult( type = "Trigger", name = "BookTrigger", namespace = "bar")), "", Coverage().packages { `package`("Class", `line-rate` = 1.0) { classes { `class`( name = "Book", filename = "classes/Book.cls", `line-rate` = 1.0) { methods() lines() } `class`( name = "foo.BookBuilder", filename = "classes/BookBuilder.cls", `line-rate` = 1.0) { methods() lines() } } } `package`("Trigger", `line-rate` = 1.0) { classes { `class`( name = "AccountTrigger", filename = "triggers/AccountTrigger.trigger", `line-rate` = 1.0) { methods() lines() } `class`( name = "bar.BookTrigger", filename = "triggers/BookTrigger.trigger", `line-rate` = 1.0) { methods() lines() } } } }, "Should create class tag using name and namespace of CodeCoverageResult"), arrayOf( arrayOf( codeCoverageResult( name = "BookBuilder", type = "Class", numLocations = 3, locationsNotCovered = arrayOf( codeLocation(line = 5, numExecutions = 0), codeLocation(line = 26, numExecutions = 0), codeLocation(line = 17, numExecutions = 0)))), "", Coverage().packages { `package`("Class", `line-rate` = 0.0) { classes { `class`( name = "BookBuilder", filename = "classes/BookBuilder.cls", `line-rate` = 0.0) { methods() lines { line(number = 5, hits = 0) line(number = 17, hits = 0) line(number = 26, hits = 0) } } } } }, "Should create line for each not covered location in CodeCoverageResult " + "in ascending order (numLocations == locationsNotCovered.size)"), arrayOf( arrayOf( codeCoverageResult( name = "BookBuilder", type = "Class", numLocations = 13, locationsNotCovered = arrayOf( codeLocation(line = 5, numExecutions = 0), codeLocation(line = 7, numExecutions = 0), codeLocation(line = 10, numExecutions = 0)))), "", Coverage().packages { `package`("Class", `line-rate` = 10.0 / 13) { classes { `class`( name = "BookBuilder", filename = "classes/BookBuilder.cls", `line-rate` = 10.0 / 13) { methods() lines { line(number = 1, hits = 1) line(number = 2, hits = 1) line(number = 3, hits = 1) line(number = 4, hits = 1) line(number = 5, hits = 0) line(number = 6, hits = 1) line(number = 7, hits = 0) line(number = 8, hits = 1) line(number = 9, hits = 1) line(number = 10, hits = 0) line(number = 11, hits = 1) line(number = 12, hits = 1) line(number = 13, hits = 1) } } } } }, "Should create line for each not covered location in CodeCoverageResult " + "in ascending order (numLocations > locationsNotCovered.size; " + "first notCoveredLocation on line 5)"), arrayOf( arrayOf( codeCoverageResult( name = "BookBuilder", type = "Class", numLocations = 10, locationsNotCovered = arrayOf( codeLocation(line = 1, numExecutions = 0), codeLocation(line = 2, numExecutions = 0), codeLocation(line = 4, numExecutions = 0)))), "", Coverage().packages { `package`("Class", `line-rate` = 0.7) { classes { `class`( name = "BookBuilder", filename = "classes/BookBuilder.cls", `line-rate` = 0.7) { methods() lines { line(number = 1, hits = 0) line(number = 2, hits = 0) line(number = 3, hits = 1) line(number = 4, hits = 0) line(number = 5, hits = 1) line(number = 6, hits = 1) line(number = 7, hits = 1) line(number = 8, hits = 1) line(number = 9, hits = 1) line(number = 10, hits = 1) } } } } }, "Should create line for each not covered location in CodeCoverageResult " + "in ascending order (numLocations > locationsNotCovered.size; " + "first notCoveredLocation on line 1)"), arrayOf( arrayOf( codeCoverageResult( name = "BookBuilder", type = "Class")), "/foo/bar/myDirectory", Coverage().packages { `package`("Class", `line-rate` = 1.0) { classes { `class`( filename = "classes/BookBuilder.cls", name = "BookBuilder", `line-rate` = 1.0) { methods() lines() } } } }, "Should properly construct file names for Classes – {projectRootPath}/classes/{name}.cls"), arrayOf( arrayOf( codeCoverageResult( name = "BookTrigger", type = "Trigger")), "/foo/bar/myDirectory", Coverage().packages { `package`("Trigger", `line-rate` = 1.0) { classes { `class`( filename = "triggers/BookTrigger.trigger", name = "BookTrigger", `line-rate` = 1.0) { methods() lines() } } } }, "Should properly construct file names for Triggers – {projectRootPath}/triggers/{name}.trigger"), arrayOf( arrayOf( codeCoverageResult( name = "BookBuilder", namespace = "foo", type = "Class")), "/foo/bar/myDirectory", Coverage().packages { `package`("Class", `line-rate` = 1.0) { classes { `class`( filename = "classes/BookBuilder.cls", name = "foo.BookBuilder", `line-rate` = 1.0) { methods() lines() } } } }, "Should generate fileName for coverage results with non-empty namespace"), arrayOf( arrayOf( codeCoverageResult( name = null, type = "Class"), codeCoverageResult( name = "", type = "Class")), "/foo/bar/myDirectory", Coverage().packages { `package`("Class", `line-rate` = 1.0) { classes { `class`( filename = "", name = "", `line-rate` = 1.0) { methods() lines() } `class`( filename = "", name = "", `line-rate` = 1.0) { methods() lines() } } } }, "Should not generate fileName for coverage results with null or empty name"), arrayOf( arrayOf( codeCoverageResult( name = "Book", type = "Class")), "/foo/bar/myDirectory/", Coverage().packages { `package`("Class", `line-rate` = 1.0) { classes { `class`( name = "Book", filename = "classes/Book.cls", `line-rate` = 1.0) { methods() lines() } } } }, "Should properly handle trailing slash in projectRootPath")) } fun createSystemUnderTest(projectRootPath: String?) = CoberturaCoverageReporter( outputFile = File("foo"), projectRootPath = projectRootPath) }
3
null
2
2
d48f151782bd343aa635d706b4806b3e499ed384
15,830
antforce
Apache License 2.0
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/CompilerOutput.kt
horita-yuya
158,491,258
false
null
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package org.jetbrains.kotlin.backend.konan import llvm.LLVMLinkModules2 import llvm.LLVMWriteBitcodeToFile import org.jetbrains.kotlin.backend.konan.library.impl.buildLibrary import org.jetbrains.kotlin.backend.konan.llvm.parseBitcodeFile import org.jetbrains.kotlin.konan.target.CompilerOutputKind val CompilerOutputKind.isNativeBinary: Boolean get() = when (this) { CompilerOutputKind.PROGRAM, CompilerOutputKind.DYNAMIC, CompilerOutputKind.STATIC, CompilerOutputKind.FRAMEWORK -> true CompilerOutputKind.LIBRARY, CompilerOutputKind.BITCODE -> false } internal fun produceOutput(context: Context, phaser: PhaseManager) { val llvmModule = context.llvmModule!! val config = context.config.configuration val tempFiles = context.config.tempFiles val produce = config.get(KonanConfigKeys.PRODUCE) when (produce) { CompilerOutputKind.STATIC, CompilerOutputKind.DYNAMIC, CompilerOutputKind.FRAMEWORK, CompilerOutputKind.PROGRAM -> { val output = tempFiles.nativeBinaryFileName context.bitcodeFileName = output val generatedBitcodeFiles = if (produce == CompilerOutputKind.DYNAMIC || produce == CompilerOutputKind.STATIC) { produceCAdapterBitcode( context.config.clang, tempFiles.cAdapterCppName, tempFiles.cAdapterBitcodeName) listOf(tempFiles.cAdapterBitcodeName) } else emptyList() val nativeLibraries = context.config.nativeLibraries + context.config.defaultNativeLibraries + generatedBitcodeFiles phaser.phase(KonanPhase.BITCODE_LINKER) { for (library in nativeLibraries) { val libraryModule = parseBitcodeFile(library) val failed = LLVMLinkModules2(llvmModule, libraryModule) if (failed != 0) { throw Error("failed to link $library") // TODO: retrieve error message from LLVM. } } } LLVMWriteBitcodeToFile(llvmModule, output) } CompilerOutputKind.LIBRARY -> { val output = context.config.outputFiles.outputName val libraryName = context.config.moduleId val neededLibraries = context.llvm.librariesForLibraryManifest val abiVersion = context.config.currentAbiVersion val target = context.config.target val nopack = config.getBoolean(KonanConfigKeys.NOPACK) val manifest = config.get(KonanConfigKeys.MANIFEST_FILE) val library = buildLibrary( context.config.nativeLibraries, context.config.includeBinaries, neededLibraries, context.serializedLinkData!!, abiVersion, target, output, libraryName, llvmModule, nopack, manifest, context.dataFlowGraph) context.library = library context.bitcodeFileName = library.mainBitcodeFileName } CompilerOutputKind.BITCODE -> { val output = context.config.outputFile context.bitcodeFileName = output LLVMWriteBitcodeToFile(llvmModule, output) } } }
0
null
0
1
6d141ba87d576e87d87f905627b83f3dac7202b0
3,638
kotlin-native
Apache License 2.0
app/src/main/java/com/example/buynow/presentation/seller/adapter/OrderSellerAdapter.kt
Shanan23
794,368,317
false
{"Kotlin": 220243}
package com.example.buynow.presentation.seller.adapter import android.content.Context import android.content.Intent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Filter import android.widget.Filterable import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.example.buynow.R import com.example.buynow.data.local.room.cart.ProductEntity import com.example.buynow.data.local.room.sale.SaleEntity import com.example.buynow.data.model.SaleCart import com.example.buynow.presentation.seller.activity.ConfirmOrderActivity import com.google.gson.Gson import java.text.DecimalFormat class OrderSellerAdapter( context: Context ) : RecyclerView.Adapter<OrderSellerAdapter.ViewHolder>(), Filterable { private lateinit var saleEntities: Collection<SaleCart> val ctx: Context = context var decimalFormat = DecimalFormat("#,###.##") private var filteredList: ArrayList<SaleCart> = arrayListOf() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val productView = LayoutInflater.from(parent.context) .inflate(R.layout.order_seller_single, parent, false) return ViewHolder(productView) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val saleCartEntity = filteredList[position] holder.orderStatus.text = saleCartEntity.saleEntity.status holder.orderDate.text = saleCartEntity.saleEntity.date holder.orderTotal.text = decimalFormat.format(saleCartEntity.productEntity.subTotal).toString() holder.orderDetail.text = saleCartEntity.productEntity.name + " x " + saleCartEntity.productEntity.qua holder.icDetail.setOnClickListener { saleCartEntity.productEntity.id.let { it1 -> goDetailsPage(saleCartEntity) } } holder.icDelete.setOnClickListener { saleCartEntity.productEntity.id.let { it1 -> goDetailsPage(saleCartEntity) } } } override fun getItemCount(): Int { return filteredList.size } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val orderStatus: TextView = itemView.findViewById(R.id.orderStatus) val orderDate: TextView = itemView.findViewById(R.id.orderDate) val orderDetail: TextView = itemView.findViewById(R.id.orderDetail) val orderTotal: TextView = itemView.findViewById(R.id.orderTotal) val icDetail: ImageView = itemView.findViewById(R.id.icDetail) val icDelete: ImageView = itemView.findViewById(R.id.icDelete) } private fun goDetailsPage(saleCart: SaleCart) { val intent = Intent(ctx, ConfirmOrderActivity::class.java) intent.putExtra("saleCart", Gson().toJson(saleCart)) ctx.startActivity(intent) } fun updateList(saleEntityList: List<SaleEntity>, productEntityList: List<ProductEntity>) { var saleCarts: ArrayList<SaleCart> = arrayListOf() productEntityList.forEach { productEntity -> var saleByCart = saleEntityList.find { sale -> sale.sId.equals(productEntity.saleId) } var saleCart = SaleCart(productEntity, saleByCart!!) saleCarts.add(saleCart) } filteredList.clear() filteredList.addAll(saleCarts) notifyDataSetChanged() } override fun getFilter(): Filter { return object : Filter() { override fun performFiltering(constraint: CharSequence?): FilterResults { val filteredResults = mutableListOf<SaleCart>() if (constraint.isNullOrEmpty()) { filteredResults.addAll(saleEntities) } else { val filterPattern = constraint.toString().toLowerCase().trim() for (item in saleEntities) { if (item.saleEntity.status.toLowerCase().contains(filterPattern)) { filteredResults.add(item) } } } val filterResults = FilterResults() filterResults.values = filteredResults return filterResults } override fun publishResults(constraint: CharSequence?, results: FilterResults?) { filteredList = results?.values as? ArrayList<SaleCart> ?: arrayListOf() notifyDataSetChanged() } } } }
0
Kotlin
0
0
072435120a602f1818e692ad95a58b0c887b496a
4,565
ToSerba
MIT License
demo/src/main/java/com/bytedance/scenedemo/animation/TransitionListDemo.kt
bytedance
213,812,935
false
{"Java": 2232337, "Kotlin": 42131}
package com.bytedance.scenedemo.animation import android.os.Build import androidx.annotation.RequiresApi import android.view.LayoutInflater import android.view.ViewGroup import android.os.Bundle import com.bytedance.scenedemo.R import android.view.View import android.widget.Button import android.widget.LinearLayout import android.widget.Space import android.widget.TextView import com.bytedance.scene.ktx.requireNavigationScene import com.bytedance.scene.ui.template.AppCompatScene import com.bytedance.scenedemo.animation.grid.GridMainScene /** * Created by JiangQi on 8/23/18. */ @RequiresApi(api = Build.VERSION_CODES.O) class TransitionListDemo : AppCompatScene() { override fun onCreateContentView( inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle? ): View? { val layout = LinearLayout(activity) layout.orientation = LinearLayout.VERTICAL addSpace(layout, 12) addTitle(layout, getString(R.string.main_title_basic)) addButton( layout, getString(R.string.main_anim_btn_share_element), View.OnClickListener { requireNavigationScene().push(GridMainScene::class.java) }) addSpace(layout, 100) return layout } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) setTitle(R.string.main_anim_btn_share_element) } private fun addTitle(parent: LinearLayout, text: String) { val textView = TextView(activity) textView.textSize = 14f textView.text = text val lp = LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) lp.leftMargin = 30 lp.rightMargin = 30 lp.topMargin = 24 lp.bottomMargin = 24 parent.addView(textView, lp) } private fun addButton( parent: LinearLayout, text: String, onClickListener: View.OnClickListener ): Button { val button = Button(activity) button.isAllCaps = false button.text = text button.setOnClickListener(onClickListener) val lp = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 150) lp.leftMargin = 20 lp.rightMargin = 20 parent.addView(button, lp) return button } private fun addSpace(parent: LinearLayout, height: Int) { val space = Space(activity) parent.addView(space, ViewGroup.LayoutParams.MATCH_PARENT, height) } }
2
Java
197
2,067
61ffdf4c4aff627afb8e3b2cf615dbd6704b3cb5
2,595
scene
Apache License 2.0
app/src/main/java/com/csc2007/notetaker/ui/Theme.kt
mcdulltii
741,826,311
false
{"Kotlin": 457049}
package com.csc2007.notetaker.ui import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme ( primary = Color(0XFFECEEF4), secondary = Teal200 ) private val LightColorScheme = lightColorScheme ( primary = Color(0xFF30628C), onPrimary = Color(0XFFFFFFFF), secondary = Color(0XFF526070), onSecondary = Color(0XFFFFFFFF), onBackground = Color(0XFF181C20), onSurface = Color(0XFF181C20), background = Color.White, surface = Color(0xFFF7F9FF) /* Other default colors to override background = Color.White, surface = Color.White, onPrimary = Color.White, onSecondary = Color.Black, onBackground = Color.Black, onSurface = Color.Black, */ ) //@Composable //fun ComposePhotoIntegrationTheme( // darkTheme: Boolean = isSystemInDarkTheme(), // content: @Composable() () -> Unit //) { // val colors = if (darkTheme) { // DarkColorPalette // } else { // LightColorPalette // } // // MaterialTheme( // colors = colors, // typography = Typography, // shapes = Shapes, // content = content // ) //} @Composable fun NoteTakerTheme( windowSizeClass: WindowSizeClass, darkTheme: Boolean = isSystemInDarkTheme(), dynamicColor: Boolean = true, content: @Composable() () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } val orientation = when { windowSizeClass.width.size > windowSizeClass.height.size -> Orientation.Landscape else -> Orientation.Portrait } val sizeThatMatters = when(orientation) { Orientation.Portrait -> windowSizeClass.width else -> windowSizeClass.height } val dimensions = when(sizeThatMatters) { is WindowSize.Small -> smallDimensions is WindowSize.Compact -> compactDimensions is WindowSize.Medium -> mediumDimensions else -> largeDimensions } ProvideAppUtils(dimensions = dimensions, orientation = orientation) { MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) } } object AppTheme { val dimens: Dimensions @Composable get() = LocalAppDimens.current val orientation: Orientation @Composable get() = LocalOrientationMode.current }
31
Kotlin
0
1
c07db1b27d15debb98735cbb020799a6e17c55e2
3,602
CSC2007
MIT License
app/src/main/java/com/rangganf/storyappearly/ui/maps/MapViewModel.kt
RanggaNf
820,492,762
false
{"Kotlin": 84236}
package com.rangganf.storyappearly.ui.maps import androidx.lifecycle.ViewModel import com.rangganf.storyappearly.data.StoryRepository /** * ViewModel untuk menangani logika terkait tampilan peta (maps) dan data cerita. * * @param storyRepository Repository untuk mengakses data cerita. */ class MapViewModel(private val storyRepository: StoryRepository) : ViewModel() { /** * Mengambil daftar cerita dengan informasi lokasi dari repository. * * @return LiveData<Result<List<Story>>> yang berisi hasil operasi. */ fun getStoriesWithLocation() = storyRepository.getStoriesWithLocation() }
0
Kotlin
0
1
2d25b89fe8cc3f335d6078e3c6c7735a2fda05b0
622
StoryApp
MIT License
src/test/java/ar/edu/unq/eperdemic/utils/DataService.kt
Dominikowivan
257,255,510
false
null
package ar.edu.unq.eperdemic.utils interface DataService { fun crearSetDeDatosIniciales() fun eliminarTodo() }
0
Kotlin
0
0
d0b012c8cd6d6aed07fdc054f40573dee6fc08be
119
EPERdemic_Backend
MIT License
kotlin-micronaut/src/main/kotlin/x/domainpersistencemodeling/PersistedChanges.kt
binkley
227,846,529
false
{"Markdown": 2, "CODEOWNERS": 1, "Batchfile": 3, "Shell": 7, "Maven POM": 3, "Dockerfile": 1, "YAML": 6, "Ignore List": 3, "Git Attributes": 3, "INI": 6, "Java": 42, "Java Properties": 1, "Kotlin": 73, "XML": 3, "SQL": 2, "PLpgSQL": 4}
package x.domainpersistencemodeling import io.micronaut.data.annotation.Repository import io.micronaut.data.exceptions.DataAccessException import javax.inject.Singleton import javax.transaction.Transactional /** * @todo Generic repository needs `@Repository` but crud does not * @todo Why does kotlin open plugin not fix this? */ @Repository @Singleton internal open class PersistedChangeFactory( private val repository: ChangeRepository ) : ChangeFactory { @Transactional override fun <T> groupAs(name: String, block: () -> T): T { val revision = repository.updateByChangeBegin(name) try { val result = block() repository.updateByChangeCommit() return result } catch (e: DataAccessException) { // TODO: Loses `e` if rollback fails repository.updateByChangeRollback(revision) throw e } } }
1
null
1
1
22dc7763ef1cffb63ffb0f18f7bbe5f6fb975b4e
917
domain-persistence-modeling
The Unlicense
android/src/main/kotlin/org/acyb/sayit/app/SayIt.kt
a-cyborg
766,941,087
false
{"Kotlin": 64500}
/* * Copyright (c) 2024 <NAME> / All rights reserved. * * Use of this source code is governed by Apache v2.0 */ package org.acyb.sayit.app import android.app.Application class SayIt : Application()
0
Kotlin
0
0
dc69c992895d0377dc6cc499dfc3e9e876758873
205
SayItAlarmMP
Apache License 2.0
src/main/kotlin/dev/itv/itv_proyecto/di/Modulo.kt
AlvaroDVA
641,823,911
false
null
package dev.itv.itv_proyecto.di import dev.itv.itv_proyecto.config.AppConfig import dev.itv.itv_proyecto.repositories.InformeRepositoryImpl import dev.itv.itv_proyecto.repositories.PropietarioRepositoryImpl import dev.itv.itv_proyecto.repositories.TrabajadorRepositoryImpl import dev.itv.itv_proyecto.repositories.VehiculoRepositoryImpl import dev.itv.itv_proyecto.routes.RoutesManager import dev.itv.itv_proyecto.services.database.DatabaseManager import dev.itv.itv_proyecto.services.storages.CsvTrabajadoresStorage import dev.itv.itv_proyecto.services.storages.HtmlInformesStorage import dev.itv.itv_proyecto.services.storages.JsonInformesStorage import dev.itv.itv_proyecto.viewmodels.EditarViewModel import dev.itv.itv_proyecto.viewmodels.MainViewModel import org.koin.core.module.dsl.factoryOf import org.koin.core.module.dsl.singleOf import org.koin.dsl.module val Modulo = module { single { AppConfig() } single { DatabaseManager() } single { RoutesManager } // Repositorios factory { InformeRepositoryImpl() } factory { PropietarioRepositoryImpl() } factory { TrabajadorRepositoryImpl() } factory { VehiculoRepositoryImpl() } // Storages factory { JsonInformesStorage() } factory { CsvTrabajadoresStorage() } factory { HtmlInformesStorage() } // ViewModel singleOf(::MainViewModel) factoryOf(::EditarViewModel) }
0
Kotlin
1
1
c63907fde55a46c2d54bf04a985b1cab41c45a35
1,390
Proyecto_ITV
Creative Commons Zero v1.0 Universal
app/src/main/kotlin/com/peecock/ymusic/ui/screens/searchresult/SearchResultScreen.kt
geekeie
852,991,746
false
{"Kotlin": 3810622, "Batchfile": 445}
package com.peecock.ymusic.ui.screens.searchresult import android.annotation.SuppressLint import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.clickable import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveableStateHolder import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.hapticfeedback.HapticFeedbackType import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalHapticFeedback import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.ExperimentalTextApi import androidx.compose.ui.unit.dp import androidx.media3.common.util.UnstableApi import androidx.media3.exoplayer.offline.Download import androidx.navigation.NavController import com.peecock.compose.persist.PersistMapCleanup import com.peecock.compose.persist.persist import com.peecock.compose.persist.persistMap import com.peecock.compose.routing.RouteHandler import com.peecock.innertube.Innertube import com.peecock.innertube.models.bodies.BrowseBody import com.peecock.innertube.models.bodies.ContinuationBody import com.peecock.innertube.models.bodies.SearchBody import com.peecock.innertube.requests.albumPage import com.peecock.innertube.requests.searchPage import com.peecock.innertube.utils.from import com.peecock.ymusic.Database import com.peecock.ymusic.LocalPlayerServiceBinder import com.peecock.ymusic.R import com.peecock.ymusic.enums.NavRoutes import com.peecock.ymusic.enums.UiType import com.peecock.ymusic.models.Album import com.peecock.ymusic.models.Song import com.peecock.ymusic.models.SongAlbumMap import com.peecock.ymusic.query import com.peecock.ymusic.ui.components.LocalMenuState import com.peecock.ymusic.ui.components.Scaffold import com.peecock.ymusic.ui.components.SwipeableAlbumItem import com.peecock.ymusic.ui.components.SwipeablePlaylistItem import com.peecock.ymusic.ui.components.themed.Header import com.peecock.ymusic.ui.components.themed.NonQueuedMediaItemMenu import com.peecock.ymusic.ui.items.AlbumItem import com.peecock.ymusic.ui.items.AlbumItemPlaceholder import com.peecock.ymusic.ui.items.ArtistItem import com.peecock.ymusic.ui.items.ArtistItemPlaceholder import com.peecock.ymusic.ui.items.PlaylistItem import com.peecock.ymusic.ui.items.PlaylistItemPlaceholder import com.peecock.ymusic.ui.items.SongItem import com.peecock.ymusic.ui.items.SongItemPlaceholder import com.peecock.ymusic.ui.items.VideoItem import com.peecock.ymusic.ui.items.VideoItemPlaceholder import com.peecock.ymusic.ui.screens.globalRoutes import com.peecock.ymusic.ui.styling.Dimensions import com.peecock.ymusic.ui.styling.px import com.peecock.ymusic.utils.UiTypeKey import com.peecock.ymusic.utils.addNext import com.peecock.ymusic.utils.asMediaItem import com.peecock.ymusic.utils.downloadedStateMedia import com.peecock.ymusic.utils.enqueue import com.peecock.ymusic.utils.forcePlay import com.peecock.ymusic.utils.getDownloadState import com.peecock.ymusic.utils.manageDownload import com.peecock.ymusic.utils.rememberPreference import com.peecock.ymusic.utils.searchResultScreenTabIndexKey import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.combine import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @ExperimentalMaterialApi @ExperimentalTextApi @SuppressLint("SuspiciousIndentation") @ExperimentalFoundationApi @ExperimentalAnimationApi @ExperimentalComposeUiApi @UnstableApi @Composable fun SearchResultScreen( navController: NavController, playerEssential: @Composable () -> Unit = {}, query: String, onSearchAgain: () -> Unit ) { val context = LocalContext.current val binder = LocalPlayerServiceBinder.current val saveableStateHolder = rememberSaveableStateHolder() val (tabIndex, onTabIndexChanges) = rememberPreference(searchResultScreenTabIndexKey, 0) var downloadState by remember { mutableStateOf(Download.STATE_STOPPED) } val hapticFeedback = LocalHapticFeedback.current var loadAlbum by remember { mutableStateOf(false) } PersistMapCleanup(tagPrefix = "searchResults/$query/") RouteHandler(listenToGlobalEmitter = true) { globalRoutes() host { val headerContent: @Composable (textButton: (@Composable () -> Unit)?) -> Unit = { Header( title = query, modifier = Modifier .pointerInput(Unit) { detectTapGestures { context.persistMap?.keys?.removeAll { it.startsWith("searchResults/$query/") } onSearchAgain() } } ) } val emptyItemsText = stringResource(R.string.no_results_found) val uiType by rememberPreference(UiTypeKey, UiType.RiMusic) Scaffold( navController = navController, playerEssential = playerEssential, topIconButtonId = R.drawable.chevron_back, onTopIconButtonClick = pop, showButton1 = if (uiType == UiType.RiMusic) false else true, topIconButton2Id = R.drawable.chevron_back, onTopIconButton2Click = pop, showButton2 = false, tabIndex = tabIndex, onHomeClick = { navController.navigate(NavRoutes.home.name) }, onTabChanged = onTabIndexChanges, tabColumnContent = { Item -> Item(0, stringResource(R.string.songs), R.drawable.musical_notes) Item(1, stringResource(R.string.albums), R.drawable.album) Item(2, stringResource(R.string.artists), R.drawable.artist) Item(3, stringResource(R.string.videos), R.drawable.video) Item(4, stringResource(R.string.playlists), R.drawable.playlist) Item(5, stringResource(R.string.featured), R.drawable.featured_playlist) Item(6, stringResource(R.string.podcasts), R.drawable.podcast) } ) { tabIndex -> saveableStateHolder.SaveableStateProvider(tabIndex) { when (tabIndex) { 0 -> { val binder = LocalPlayerServiceBinder.current val menuState = LocalMenuState.current val thumbnailSizeDp = Dimensions.thumbnails.song val thumbnailSizePx = thumbnailSizeDp.px ItemsPage( tag = "searchResults/$query/songs", itemsPageProvider = { continuation -> if (continuation == null) { Innertube.searchPage( body = SearchBody( query = query, params = Innertube.SearchFilter.Song.value ), fromMusicShelfRendererContent = Innertube.SongItem.Companion::from ) } else { Innertube.searchPage( body = ContinuationBody(continuation = continuation), fromMusicShelfRendererContent = Innertube.SongItem.Companion::from ) } }, emptyItemsText = emptyItemsText, headerContent = headerContent, itemContent = { song -> //Log.d("mediaItem",song.toString()) SwipeablePlaylistItem( mediaItem = song.asMediaItem, onSwipeToRight = { binder?.player?.addNext(song.asMediaItem) } ) { downloadState = getDownloadState(song.asMediaItem.mediaId) val isDownloaded = downloadedStateMedia(song.asMediaItem.mediaId) SongItem( song = song, isDownloaded = isDownloaded, onDownloadClick = { binder?.cache?.removeResource(song.asMediaItem.mediaId) query { Database.insert( Song( id = song.asMediaItem.mediaId, title = song.asMediaItem.mediaMetadata.title.toString(), artistsText = song.asMediaItem.mediaMetadata.artist.toString(), thumbnailUrl = song.thumbnail?.url, durationText = null ) ) } manageDownload( context = context, songId = song.asMediaItem.mediaId, songTitle = song.asMediaItem.mediaMetadata.title.toString(), downloadState = isDownloaded ) }, downloadState = downloadState, thumbnailSizePx = thumbnailSizePx, thumbnailSizeDp = thumbnailSizeDp, modifier = Modifier .combinedClickable( onLongClick = { menuState.display { NonQueuedMediaItemMenu( navController = navController, onDismiss = menuState::hide, mediaItem = song.asMediaItem, ) }; hapticFeedback.performHapticFeedback( HapticFeedbackType.LongPress ) }, onClick = { binder?.stopRadio() binder?.player?.forcePlay(song.asMediaItem) binder?.setupRadio(song.info?.endpoint) } ) ) } }, itemPlaceholderContent = { SongItemPlaceholder(thumbnailSizeDp = thumbnailSizeDp) } ) } 1 -> { val thumbnailSizeDp = 108.dp val thumbnailSizePx = thumbnailSizeDp.px ItemsPage( tag = "searchResults/$query/albums", itemsPageProvider = { continuation -> if (continuation == null) { Innertube.searchPage( body = SearchBody( query = query, params = Innertube.SearchFilter.Album.value ), fromMusicShelfRendererContent = Innertube.AlbumItem::from ) } else { Innertube.searchPage( body = ContinuationBody(continuation = continuation), fromMusicShelfRendererContent = Innertube.AlbumItem::from ) } }, emptyItemsText = emptyItemsText, headerContent = headerContent, itemContent = { album -> var albumPage by persist<Innertube.PlaylistOrAlbumPage?>("album/${album.key}/albumPage") SwipeableAlbumItem( albumItem = album, onSwipeToLeft = { CoroutineScope(Dispatchers.IO).launch { Database .album(album.key) .combine(snapshotFlow { tabIndex }) { album, tabIndex -> album to tabIndex } .collect { (currentAlbum) -> if (albumPage == null) withContext(Dispatchers.IO) { Innertube.albumPage( BrowseBody( browseId = album.key ) ) ?.onSuccess { currentAlbumPage -> albumPage = currentAlbumPage println("mediaItem success home album songsPage ${currentAlbumPage?.songsPage} description ${currentAlbumPage?.description} year ${currentAlbumPage?.year}") albumPage ?.songsPage ?.items ?.map( Innertube.SongItem::asMediaItem ) ?.let { it1 -> withContext(Dispatchers.Main) { binder?.player?.enqueue( it1, context ) } } println("mediaItem success add in queue album songsPage ${albumPage ?.songsPage ?.items?.size}") } ?.onFailure { println("mediaItem error searchResultScreen album ${it.stackTraceToString()}") } } //} } } }, onSwipeToRight = { CoroutineScope(Dispatchers.IO).launch { Database .album(album.key) .combine(snapshotFlow { tabIndex }) { album, tabIndex -> album to tabIndex } .collect { (currentAlbum) -> if (albumPage == null) withContext(Dispatchers.IO) { Innertube.albumPage( BrowseBody( browseId = album.key ) ) ?.onSuccess { currentAlbumPage -> albumPage = currentAlbumPage println("mediaItem success home album songsPage ${currentAlbumPage?.songsPage} description ${currentAlbumPage?.description} year ${currentAlbumPage?.year}") Database.upsert( Album( id = album.key, title = currentAlbumPage?.title, thumbnailUrl = currentAlbumPage?.thumbnail?.url, year = currentAlbumPage?.year, authorsText = currentAlbumPage?.authors ?.joinToString( "" ) { it.name ?: "" }, shareUrl = currentAlbumPage?.url, timestamp = System.currentTimeMillis(), bookmarkedAt = System.currentTimeMillis() ), currentAlbumPage ?.songsPage ?.items ?.map( Innertube.SongItem::asMediaItem ) ?.onEach( Database::insert ) ?.mapIndexed { position, mediaItem -> SongAlbumMap( songId = mediaItem.mediaId, albumId = album.key, position = position ) } ?: emptyList() ) } ?.onFailure { println("mediaItem error searchResultScreen album ${it.stackTraceToString()}") } } //} } } } ) { AlbumItem( yearCentered = false, album = album, thumbnailSizePx = thumbnailSizePx, thumbnailSizeDp = thumbnailSizeDp, modifier = Modifier .combinedClickable( onClick = { navController.navigate("${NavRoutes.album.name}/${album.key}") }, onLongClick = {} ) ) } }, itemPlaceholderContent = { AlbumItemPlaceholder(thumbnailSizeDp = thumbnailSizeDp) } ) } 2 -> { val thumbnailSizeDp = 64.dp val thumbnailSizePx = thumbnailSizeDp.px ItemsPage( tag = "searchResults/$query/artists", itemsPageProvider = { continuation -> if (continuation == null) { Innertube.searchPage( body = SearchBody( query = query, params = Innertube.SearchFilter.Artist.value ), fromMusicShelfRendererContent = Innertube.ArtistItem::from ) } else { Innertube.searchPage( body = ContinuationBody(continuation = continuation), fromMusicShelfRendererContent = Innertube.ArtistItem::from ) } }, emptyItemsText = emptyItemsText, headerContent = headerContent, itemContent = { artist -> ArtistItem( artist = artist, thumbnailSizePx = thumbnailSizePx, thumbnailSizeDp = thumbnailSizeDp, modifier = Modifier .clickable(onClick = { //artistRoute(artist.key) navController.navigate("${NavRoutes.artist.name}/${artist.key}") }) ) }, itemPlaceholderContent = { ArtistItemPlaceholder(thumbnailSizeDp = thumbnailSizeDp) } ) } 3 -> { val binder = LocalPlayerServiceBinder.current val menuState = LocalMenuState.current val thumbnailHeightDp = 72.dp val thumbnailWidthDp = 128.dp ItemsPage( tag = "searchResults/$query/videos", itemsPageProvider = { continuation -> if (continuation == null) { Innertube.searchPage( body = SearchBody( query = query, params = Innertube.SearchFilter.Video.value ), fromMusicShelfRendererContent = Innertube.VideoItem::from ) } else { Innertube.searchPage( body = ContinuationBody(continuation = continuation), fromMusicShelfRendererContent = Innertube.VideoItem::from ) } }, emptyItemsText = emptyItemsText, headerContent = headerContent, itemContent = { video -> SwipeablePlaylistItem( mediaItem = video.asMediaItem, onSwipeToRight = { binder?.player?.addNext(video.asMediaItem) } ) { VideoItem( video = video, thumbnailWidthDp = thumbnailWidthDp, thumbnailHeightDp = thumbnailHeightDp, modifier = Modifier .combinedClickable( onLongClick = { menuState.display { NonQueuedMediaItemMenu( navController = navController, mediaItem = video.asMediaItem, onDismiss = menuState::hide ) }; hapticFeedback.performHapticFeedback( HapticFeedbackType.LongPress ) }, onClick = { binder?.stopRadio() binder?.player?.forcePlay(video.asMediaItem) binder?.setupRadio(video.info?.endpoint) } ) ) } }, itemPlaceholderContent = { VideoItemPlaceholder( thumbnailHeightDp = thumbnailHeightDp, thumbnailWidthDp = thumbnailWidthDp ) } ) } 4, 5 -> { val thumbnailSizeDp = Dimensions.thumbnails.playlist val thumbnailSizePx = thumbnailSizeDp.px //val thumbnailSizeDp = 108.dp //val thumbnailSizePx = thumbnailSizeDp.px ItemsPage( tag = "searchResults/$query/${ when (tabIndex) { 4 -> "playlists" else -> "featured" } }", itemsPageProvider = { continuation -> if (continuation == null) { val filter = when (tabIndex) { 4 -> Innertube.SearchFilter.CommunityPlaylist else -> Innertube.SearchFilter.FeaturedPlaylist } Innertube.searchPage( body = SearchBody(query = query, params = filter.value), fromMusicShelfRendererContent = Innertube.PlaylistItem::from ) } else { Innertube.searchPage( body = ContinuationBody(continuation = continuation), fromMusicShelfRendererContent = Innertube.PlaylistItem::from ) } }, emptyItemsText = emptyItemsText, headerContent = headerContent, itemContent = { playlist -> PlaylistItem( playlist = playlist, thumbnailSizePx = thumbnailSizePx, thumbnailSizeDp = thumbnailSizeDp, showSongsCount = false, modifier = Modifier .clickable(onClick = { //playlistRoute(playlist.key) navController.navigate("${NavRoutes.playlist.name}/${playlist.key}") }) ) }, itemPlaceholderContent = { PlaylistItemPlaceholder(thumbnailSizeDp = thumbnailSizeDp) } ) } 6 -> { val thumbnailSizeDp = Dimensions.thumbnails.playlist val thumbnailSizePx = thumbnailSizeDp.px //val thumbnailSizeDp = 108.dp //val thumbnailSizePx = thumbnailSizeDp.px ItemsPage( tag = "searchResults/$query/podcasts", itemsPageProvider = { continuation -> if (continuation == null) { val filter = Innertube.SearchFilter.Podcast Innertube.searchPage( body = SearchBody(query = query, params = filter.value), fromMusicShelfRendererContent = Innertube.PlaylistItem::from ) } else { Innertube.searchPage( body = ContinuationBody(continuation = continuation), fromMusicShelfRendererContent = Innertube.PlaylistItem::from ) } }, emptyItemsText = emptyItemsText, headerContent = headerContent, itemContent = { playlist -> PlaylistItem( playlist = playlist, thumbnailSizePx = thumbnailSizePx, thumbnailSizeDp = thumbnailSizeDp, showSongsCount = false, modifier = Modifier .clickable(onClick = { //playlistRoute(playlist.key) println("mediaItem searchResultScreen playlist key ${playlist.key}") navController.navigate("${NavRoutes.podcast.name}/${playlist.key}") }) ) }, itemPlaceholderContent = { PlaylistItemPlaceholder(thumbnailSizeDp = thumbnailSizeDp) } ) } } } } } } }
0
Kotlin
0
0
bcc8e691579ea2c6f04e9287e45056e9fb85c532
37,982
YMusic
Apache License 2.0
app/src/main/java/com/germanautolabs/acaraus/screens/articles/list/ArticleListScreen.kt
alexandrucaraus
836,093,916
false
{"Kotlin": 57869}
package com.germanautolabs.acaraus.screens.articles.list import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.FilterList import androidx.compose.material.icons.filled.Mic import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar 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.unit.dp import com.germanautolabs.acaraus.models.Article import com.germanautolabs.acaraus.screens.articles.list.components.ArticleFilter import com.germanautolabs.acaraus.screens.articles.list.components.ArticleFilterState import com.germanautolabs.acaraus.screens.articles.list.components.ArticleList import com.germanautolabs.acaraus.screens.articles.list.components.ArticleListState @OptIn(ExperimentalMaterial3Api::class) @Composable fun ArticleListScreen( modifier: Modifier = Modifier, articleListState: ArticleListState, articleFilterState: ArticleFilterState, onNavigateToDetails: (article: Article) -> Unit, ) = Scaffold(modifier = modifier, topBar = { TopAppBar( title = { Text("News") }, actions = { IconButton(onClick = articleFilterState.show) { Box { if (articleFilterState.isSet) { Box( modifier = Modifier.align(Alignment.BottomCenter) .background(Color.Red, shape = CircleShape) .size(8.dp), ) } Icon( imageVector = Icons.Default.FilterList, null, ) } } }, ) }, floatingActionButton = { FloatingActionButton(onClick = articleListState.toggleListening) { Icon(Icons.Default.Mic, contentDescription = "Listen commands") } }, content = { padding -> Column { ArticleList( modifier = Modifier.padding(padding), listState = articleListState, onNavigateToDetails = onNavigateToDetails, ) ArticleFilter(filterState = articleFilterState) } })
0
Kotlin
0
0
9e42bdc964fd9fd82598bd8558f11f8d36f3644f
2,820
germanautolabs
MIT License
example-v8/src/main/kotlin/com/github/vok/karibudsl/example/CommonElementsView.kt
tcbuddy
384,814,707
true
{"Kotlin": 423344, "HTML": 16485, "CSS": 3191}
package com.github.vok.karibudsl.example import com.github.vok.karibudsl.* import com.vaadin.event.ShortcutAction import com.vaadin.icons.VaadinIcons import com.vaadin.navigator.View import com.vaadin.navigator.ViewChangeListener import com.vaadin.server.AbstractErrorMessage import com.vaadin.server.Page import com.vaadin.server.UserError import com.vaadin.shared.Position import com.vaadin.shared.ui.ErrorLevel import com.vaadin.ui.* import com.vaadin.ui.themes.ValoTheme @AutoView class CommonElementsView : VerticalLayout(), View { init { isSpacing = false title("Common UI Elements") gridLayout(2, 3) { w = fillParent; isSpacing = true panel("Loading Indicator") { verticalLayout { label("You can test the loading indicator by pressing the buttons.") cssLayout { caption = "Show the loading indicator for…" styleName = ValoTheme.LAYOUT_COMPONENT_GROUP button("0.8") { onLeftClick { Thread.sleep(800) } } button("3") { onLeftClick { Thread.sleep(3000) } } button("15") { onLeftClick { Thread.sleep(15000) } styleName = "last" } label { html("&nbsp;&nbsp; seconds") w = wrapContent } } label("The theme also provides a mixin that you can use to include a spinner anywhere in your application. Below is a Label with a custom style name, for which the spinner mixin is added.") { w = fillParent styleName = ValoTheme.LABEL_SMALL caption = "Spinner" } spinner() } } addComponent(Panel("Notifications").apply { verticalLayout { val notification = Notification("") var typeString: String = "" var styleString: String = "" fun updateTypeStyle() { notification.styleName = "$typeString $styleString".trim() } textField("Title") { w = fillParent; placeholder = "Title for the notification" addValueChangeListener { event -> notification.caption = if (event.value.isNullOrBlank()) null else event.value } value = "Notification Title" } textArea("Description") { w = fillParent; styleName = ValoTheme.TEXTAREA_SMALL addValueChangeListener { event -> notification.description = if (event.value.isNullOrBlank()) null else event.value } value = "A more informative message about what has happened. Nihil hic munitissimus habendi senatus locus, nihil horum? Inmensae subtilitatis, obscuris et malesuada fames. Hi omnes lingua, institutis, legibus inter se differunt." } menuBar { caption = "Type"; styleName = ValoTheme.MENUBAR_SMALL val typeCommand = { selectedItem: MenuBar.MenuItem -> typeString = if (selectedItem.text == "Humanized") "" else selectedItem.text.toLowerCase() updateTypeStyle() items.forEach { item -> item.isChecked = false } selectedItem.isChecked = true } item("Humanized", menuSelected = typeCommand) { isCheckable = true isChecked = true } item("Tray", menuSelected = typeCommand) { isCheckable = true } item("Warning", menuSelected = typeCommand) { isCheckable = true } item("Error", menuSelected = typeCommand) { isCheckable = true } item("System", menuSelected = typeCommand) { isCheckable = true } } menuBar { caption = "Additional style"; styleName = ValoTheme.MENUBAR_SMALL val styleCommand = MenuBar.Command { styleString = items.filter { it.isChecked }.joinToString(" ", transform = { it.text.toLowerCase() }) updateTypeStyle() } addItem("Dark", styleCommand).isCheckable = true addItem("Success", styleCommand).isCheckable = true addItem("Failure", styleCommand).isCheckable = true addItem("Bar", styleCommand).isCheckable = true addItem("Small", styleCommand).isCheckable = true addItem("Closable", styleCommand).isCheckable = true } cssLayout { caption = "Fade delay" styleName = ValoTheme.LAYOUT_COMPONENT_GROUP val delay = textField { placeholder = "Infinite"; w = 7.em addStyleNames(ValoTheme.TEXTFIELD_ALIGN_RIGHT, ValoTheme.TEXTFIELD_SMALL) addValueChangeListener { event -> notification.delayMsec = event.value.toIntOrNull() ?: -1 if (notification.delayMsec < 0) value = "" } value = "1000" } button { // clear icon = VaadinIcons.CLOSE_CIRCLE addStyleNames("last", ValoTheme.BUTTON_SMALL, ValoTheme.BUTTON_ICON_ONLY) onLeftClick { delay.value = "" } } label { html("&nbsp; msec") } } gridLayout(3, 3) { caption = "Show in position"; isSpacing = true fun buttonWhichShows(position: Position) = button { styleName = ValoTheme.BUTTON_SMALL onLeftClick { notification.position = position notification.show(Page.getCurrent()) } } Position.values().sliceArray(0..8).forEach { buttonWhichShows(it) } } } }, 1, 0, 1, 2) panel("Dialogs") { verticalLayout { val win = DemoDialog() win.footerVisible = true isSpacing = true; isMargin = true menuBar { caption = "Content"; styleName = ValoTheme.MENUBAR_SMALL item("Auto Height", { win.autoHeight = it.isChecked }).isCheckable = true item("Tabs", { win.tabsVisible = it.isChecked }).isCheckable = true item("Footer", { win.footerVisible = it.isChecked }) { isCheckable = true isChecked = true } } menuBar { caption = "Toolbars"; styleName = ValoTheme.MENUBAR_SMALL item("Footer Toolbar", { win.footerToolbar = it.isChecked }).isCheckable = true item("Top Toolbar", { win.toolbarVisible = it.isChecked }).isCheckable = true item("Borderless Toolbars", { win.toolbarStyle = if (it.isChecked) ValoTheme.MENUBAR_BORDERLESS else null }).isCheckable = true } menuBar { caption = "Options"; styleName = ValoTheme.MENUBAR_SMALL item("Caption", { win.win.caption = if (it.isChecked) "Window Caption" else null }) { isCheckable = true isChecked = true } item("Closable", { win.win.isClosable = it.isChecked }).isCheckable = true item("Resizable", { win.win.isResizable = it.isChecked }).isCheckable = true item("Modal", { win.win.isModal = it.isChecked }).isCheckable = true } val show = button("Open Window") { onLeftClick { event -> win.show() event.button.isEnabled = false } setPrimary() } checkBox("Hidden") { addValueChangeListener { event -> win.win.isVisible = !event.value } } win.win.addCloseListener { show.isEnabled = true } } } panel("Tooltips") { horizontalLayout { isMargin = true; styleName = ValoTheme.LAYOUT_HORIZONTAL_WRAPPING label("Try out different tooltips/descriptions by hovering over the labels.") label("Simple") { styleName = ValoTheme.LABEL_BOLD description = "Simple tooltip message" } label("Long") { styleName = ValoTheme.LABEL_BOLD description = "Long tooltip message. Inmensae subtilitatis, obscuris et malesuada fames. Salutantibus vitae elit libero, a pharetra augue." } label("HTML tooltip") { styleName = ValoTheme.LABEL_BOLD description = "<div><h1>Ut enim ad minim veniam, quis nostrud exercitation</h1><p><span>Morbi fringilla convallis sapien, id pulvinar odio volutpat.</span> <span>Vivamus sagittis lacus vel augue laoreet rutrum faucibus.</span> <span>Donec sed odio operae, eu vulputate felis rhoncus.</span> <span>At nos hinc posthac, sitientis piros Afros.</span> <span>Tu quoque, Brute, fili mi, nihil timor populi, nihil!</span></p><p><span>Gallia est omnis divisa in partes tres, quarum.</span> <span>Praeterea iter est quasdam res quas ex communi.</span> <span>Cum ceteris in veneratione tui montes, nascetur mus.</span> <span>Quam temere in vitiis, legem sancimus haerentia.</span> <span>Idque Caesaris facere voluntate liceret: sese habere.</span></p></div>" } label("With an error message") { styleName = ValoTheme.LABEL_BOLD description = "Simple tooltip message" componentError = UserError("Something terrible has happened") } label("With a long error message") { styleName = ValoTheme.LABEL_BOLD description = "Simple tooltip message" componentError = UserError( "<h2>Contra legem facit qui id facit quod lex prohibet <span>Tityre, tu patulae recubans sub tegmine fagi dolor.</span> <span>Tityre, tu patulae recubans sub tegmine fagi dolor.</span> <span>Prima luce, cum quibus mons aliud consensu ab eo.</span> <span>Quid securi etiam tamquam eu fugiat nulla pariatur.</span> <span>Fabio vel iudice vincam, sunt in culpa qui officia.</span> <span>Nihil hic munitissimus habendi senatus locus, nihil horum?</span></p><p><span>Plura mihi bona sunt, inclinet, amari petere vellent.</span> <span>Integer legentibus erat a ante historiarum dapibus.</span> <span>Quam diu etiam furor iste tuus nos eludet?</span> <span>Nec dubitamus multa iter quae et nos invenerat.</span> <span>Quisque ut dolor gravida, placerat libero vel, euismod.</span> <span>Quae vero auctorem tractata ab fiducia dicuntur.</span></h2>", AbstractErrorMessage.ContentMode.HTML, ErrorLevel.CRITICAL) } label("Error message only") { styleName = ValoTheme.LABEL_BOLD componentError = UserError("Something terrible has happened") } } } } } override fun enter(event: ViewChangeListener.ViewChangeEvent?) { } } private class DemoDialog { val win = Window("Window Caption").apply { w = 380.px h = 300.px isClosable = false isResizable = false setCloseShortcut(ShortcutAction.KeyCode.ESCAPE) } var footerVisible: Boolean = false set(value) { field = value; updateContent() } var autoHeight: Boolean = false set(value) { field = value win.h = if (value) wrapContent else 300.px updateContent() } var tabsVisible: Boolean = false set(value) { field = value; updateContent() } var toolbarVisible: Boolean = false set(value) { field = value; updateContent() } var footerToolbar: Boolean = false set(value) { field = value; updateContent() } var toolbarStyle: String? = null set(value) { field = value; updateContent() } private fun updateContent() { win.content = windowContent() } private fun windowContent() = VerticalLayout().apply { val content: Component if (toolbarVisible) { sampleToolBar { w = wrapContent addStyleNames(toolbarStyle ?: "", ValoTheme.WINDOW_TOP_TOOLBAR) } } if (tabsVisible) { content = tabSheet { setSizeFull(); styleName = ValoTheme.TABSHEET_PADDED_TABBAR verticalLayout { isMargin = true label { w = fillParent html("<h2>Subtitle</h2><p>Normal type for plain text. Etiam at risus et justo dignissim congue. Phasellus laoreet lorem vel dolor tempus vehicula.</p><p>Quisque ut dolor gravida, placerat libero vel, euismod. Etiam habebis sem dicantur magna mollis euismod. Nihil hic munitissimus habendi senatus locus, nihil horum? Curabitur est gravida et libero vitae dictum. Ullamco laboris nisi ut aliquid ex ea commodi consequat. Morbi odio eros, volutpat ut pharetra vitae, lobortis sed nibh.</p>") } } lastTab.caption = "Selected" addTab(Label(), "Another") addTab(Label(), "One more") } } else if (!autoHeight) { content = panel { setSizeFull() addStyleNames(ValoTheme.PANEL_BORDERLESS, ValoTheme.PANEL_SCROLL_INDICATOR) verticalLayout { isMargin = true label { w = fillParent html("<h2>Subtitle</h2><p>Normal type for plain text. Etiam at risus et justo dignissim congue. Phasellus laoreet lorem vel dolor tempus vehicula.</p><p>Quisque ut dolor gravida, placerat libero vel, euismod. Etiam habebis sem dicantur magna mollis euismod. Nihil hic munitissimus habendi senatus locus, nihil horum? Curabitur est gravida et libero vitae dictum. Ullamco laboris nisi ut aliquid ex ea commodi consequat. Morbi odio eros, volutpat ut pharetra vitae, lobortis sed nibh.</p>") } } } } else { content = label { w = fillParent html("<h2>Subtitle</h2><p>Normal type for plain text. Etiam at risus et justo dignissim congue. Phasellus laoreet lorem vel dolor tempus vehicula.</p><p>Quisque ut dolor gravida, placerat libero vel, euismod. Etiam habebis sem dicantur magna mollis euismod. Nihil hic munitissimus habendi senatus locus, nihil horum? Curabitur est gravida et libero vitae dictum. Ullamco laboris nisi ut aliquid ex ea commodi consequat. Morbi odio eros, volutpat ut pharetra vitae, lobortis sed nibh.</p>") } isMargin = true } if (footerVisible) { if (!footerToolbar) { horizontalLayout { w = fillParent; isSpacing = true; styleName = ValoTheme.WINDOW_BOTTOM_TOOLBAR label("Footer text") { w = wrapContent; isExpanded = true } button("OK") { setPrimary() } button("Cancel") } } else { sampleToolBar { styleName = toolbarStyle; w = wrapContent } } } if (!autoHeight) { setSizeFull() setExpandRatio(content, 1f) } } fun show() { updateContent() UI.getCurrent().addWindow(win) win.center() win.focus() } }
0
Kotlin
0
0
a1b1dfbf3cb6bd0cefe741e2fbaf6ede08f0fe36
17,502
karibu-dsl
MIT License
router/src/main/java/com/fzm/chat/router/main/SimpleTx.kt
txchat
507,831,442
false
{"Kotlin": 2234450, "Java": 384844}
package com.fzm.chat.router.main import java.io.Serializable /** * @author zhengjy * @since 2021/08/13 * Description: */ data class SimpleTx( val hash: String, /** * 交易时间 */ val blockTime: Long, /** * 矿工费 */ val fee: String, /** * 转账地址 */ val from: String, /** * 收款地址 */ val to: String, /** * 区块高度 */ val height: Int, /** * 交易状态 * 失败:-1,确认中:0,成功:1 */ var status: String, /** * 交易金额 */ val value: String, /** * 上链备注 */ val note: String?, ) : Serializable { companion object { const val FAIL = "-1" const val PENDING = "0" const val SUCCESS = "1" } } val SimpleTx.isSuccess: Boolean get() = status == SimpleTx.SUCCESS val SimpleTx.isPending: Boolean get() = status == SimpleTx.PENDING val SimpleTx.isFail: Boolean get() = status == SimpleTx.FAIL
0
Kotlin
1
1
6a3c6edf6ae341199764d4d08dffd8146877678b
949
ChatPro-Android
MIT License
src/main/kotlin/de/sambalmueslie/openevent/storage/location/LocationData.kt
Black-Forrest-Development
542,810,521
false
{"Kotlin": 334759, "TypeScript": 179633, "HTML": 73007, "SCSS": 3950, "Batchfile": 202}
package de.sambalmueslie.openevent.storage.location import de.sambalmueslie.openevent.core.model.Event import de.sambalmueslie.openevent.core.model.Location import de.sambalmueslie.openevent.core.model.LocationChangeRequest import de.sambalmueslie.openevent.storage.SimpleDataObject import jakarta.persistence.* import java.time.LocalDateTime @Entity(name = "Location") @Table(name = "location") data class LocationData( @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) var id: Long = 0, @Column var eventId: Long, @Column var street: String, @Column var streetNumber: String, @Column var zip: String, @Column var city: String, @Column var country: String, @Column var additionalInfo: String, @Column var lat: Double, @Column var lon: Double, @Column var size: Int, @Column var created: LocalDateTime = LocalDateTime.now(), @Column var updated: LocalDateTime? = null ) : SimpleDataObject<Location> { companion object { fun create( event: Event, request: LocationChangeRequest, timestamp: LocalDateTime ): LocationData { return LocationData( 0, event.id, request.street, request.streetNumber, request.zip, request.city, request.country, request.additionalInfo, request.lat, request.lon, request.size, timestamp ) } } override fun convert(): Location { return Location(id, eventId, street, streetNumber, zip, city, country, additionalInfo, lat, lon, size) } fun update(request: LocationChangeRequest, timestamp: LocalDateTime): LocationData { street = request.street streetNumber = request.streetNumber zip = request.zip city = request.city country = request.country additionalInfo = request.additionalInfo lat = request.lat lon = request.lon size = request.size updated = timestamp return this } }
6
Kotlin
0
1
43cf66668db937150ae8f14078437c1e5a7287e2
2,162
open-event
Apache License 2.0
eartho-one/src/main/java/com/eartho/one/request/ErrorAdapter.kt
eartho-group
499,781,444
false
null
package com.auth0.android.request import java.io.IOException import java.io.Reader /** * Adapter that converts from different sources into the <T> class that represents an error. */ public interface ErrorAdapter<T> { /** * Converts the JSON input given in the Reader to the <T> instance. * @param statusCode the response HTTP status code. * @param reader the reader that contains the JSON encoded string. * @throws IOException could be thrown to signal that the input was invalid. */ @Throws(IOException::class) public fun fromJsonResponse(statusCode: Int, reader: Reader): T /** * Converts the raw input to a <T> instance. * @param statusCode the response HTTP status code. * @param bodyText the plain text received in the response body. * @param headers the response headers received. */ public fun fromRawResponse( statusCode: Int, bodyText: String, headers: Map<String, List<String>> ): T /** * Constructs a <T> instance from the given stack trace. * @param cause the cause of this error. */ public fun fromException(cause: Throwable): T }
5
null
136
5
c57130f02e3765969aeb16d8156daa749f536710
1,171
one-client-kotlin
MIT License
alerting/src/main/kotlin/com/amazon/opendistroforelasticsearch/alerting/action/IndexMonitorAction.kt
marshell0
400,442,979
false
null
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file 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.amazon.opendistroforelasticsearch.alerting.action import org.elasticsearch.action.ActionType class IndexMonitorAction private constructor() : ActionType<IndexMonitorResponse>(NAME, ::IndexMonitorResponse) { companion object { val INSTANCE = IndexMonitorAction() const val NAME = "cluster:admin/opendistro/alerting/monitor/write" } }
15
null
82
3
e571571c7abd4ade9fc230c0d449423f947ae0ea
984
alerting
Apache License 2.0
app/src/main/java/com/projectbyzakaria/animes/ui/component/ErrorShow.kt
HmidouZaka
680,457,944
false
null
package com.projectbyzakaria.animes.ui.component import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Button import androidx.compose.material.ButtonDefaults import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.projectbyzakaria.animes.R import com.projectbyzakaria.animes.ui.theme.blue @Composable fun ErrorShow( error: String, isImageShown: Boolean = true, onClick: (() -> Unit)?, modifier: Modifier = Modifier, image: Int = R.drawable.error ) { Column( modifier, verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { if (isImageShown){ Image( painter = painterResource(id = image), contentDescription = "error image", modifier = Modifier.size(100.dp).clip(RoundedCornerShape(10.dp)) ) } Text(text = error, textAlign = TextAlign.Center,modifier=Modifier.padding(top = 8.dp)) onClick?.let { Button(onClick = it, colors = ButtonDefaults.buttonColors(backgroundColor = blue)) { Text(text = "Refresh") } } } } @Preview(showBackground = true) @Composable fun ErrorPreview() { ErrorShow(error = "no iNternet", onClick = { /*TODO*/ }, image = R.drawable.finish) }
0
Kotlin
0
1
32a6a8131e0659379ca0d76dd86f9b57bb7e1bb8
1,927
Anime-Android-App
MIT License
kotlin/samples/dungeon/common/src/main/java/com/squareup/sample/dungeon/board/BoardCell.kt
arriolac
208,501,497
true
{"Kotlin": 713665, "Swift": 410693, "Ruby": 13608, "Shell": 5606, "Java": 2817}
/* * Copyright 2019 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 com.squareup.sample.dungeon.board import kotlin.streams.asSequence data class BoardCell(val codePoint: Int) { constructor(emoji: String) : this(emoji.codePointAt(0)) init { require(Character.isValidCodePoint(codePoint)) } private val string = String(Character.toChars(codePoint)) val isEmpty get() = this == EMPTY_FLOOR val isWall get() = this in WALL_CELLS val isToxic get() = this in TOXIC override fun toString(): String = string companion object { val EMPTY_FLOOR = BoardCell(" ") val WALL_CELLS = "🌳🧱".asBoardCells() val TOXIC = "🔥🌊".asBoardCells() } } fun String.asBoardCells(): List<BoardCell> = codePoints() .asSequence() .map(::BoardCell) .toList()
0
null
0
1
8acff486c2fc80b1de2e1956170819f03fa0eafd
1,317
workflow
Apache License 2.0
app/src/main/java/com/fracta7/csgostats/presentation/main_screen/MainScreenState.kt
fracta7
529,130,175
false
null
package com.fracta7.csgostats.presentation.main_screen import com.fracta7.csgostats.domain.model.UserStats data class MainScreenState( val stats: List<UserStats> = emptyList(), val status: String = "", val showStats: Boolean = false )
0
Kotlin
0
1
a2e05cd665925a695351cf3838794cf1c6aa3aea
249
CSGO-Stats-Android
MIT License
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/GridGraph.kt
Danilo-Araujo-Silva
271,904,885
false
null
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction /** *```` * * Name: GridGraph * * Full name: System`GridGraph * * GridGraph[{m, n}] gives the grid graph with m × n vertices G . * m, n * GridGraph[{n , n , …, n }] gives the k-dimensional grid graph with n × n × ⋯ × n vertices G . * 1 2 k 1 2 k n , n , …, n * Usage: 1 2 k * * AlignmentPoint -> Center * AnnotationRules -> {} * AspectRatio -> Automatic * Axes -> False * AxesLabel -> None * AxesOrigin -> Automatic * AxesStyle -> {} * Background -> None * BaselinePosition -> Automatic * BaseStyle -> {} * ContentSelectable -> Automatic * DirectedEdges -> Automatic * EdgeCapacity -> Automatic * EdgeCost -> Automatic * EdgeLabels -> None * EdgeLabelStyle -> Automatic * EdgeShapeFunction -> Automatic * EdgeStyle -> Automatic * EdgeWeight -> Automatic * Editable -> False * Epilog -> {} * FormatType -> TraditionalForm * Frame -> False * FrameLabel -> None * FrameStyle -> {} * FrameTicks -> None * FrameTicksStyle -> {} * GraphHighlight -> {} * GraphHighlightStyle -> Automatic * GraphLayout -> Automatic * GraphRoot -> Automatic * GraphStyle -> Automatic * GridLines -> None * GridLinesStyle -> {} * ImageMargins -> 0. * ImagePadding -> All * ImageSize -> Automatic * LabelStyle -> {} * PerformanceGoal -> Automatic * PlotLabel -> None * PlotRange -> All * PlotRangeClipping -> False * PlotRangePadding -> Automatic * PlotRegion -> Automatic * PlotTheme -> Automatic * Prolog -> {} * Properties -> {} * RotateLabel -> True * Ticks -> Automatic * TicksStyle -> {} * VertexCapacity -> Automatic * VertexCoordinates -> Automatic * VertexLabels -> None * VertexLabelStyle -> Automatic * VertexShape -> Automatic * VertexShapeFunction -> Automatic * VertexSize -> Automatic * VertexStyle -> Automatic * Options: VertexWeight -> Automatic * * NHoldAll * Protected * Attributes: ReadProtected * * local: paclet:ref/GridGraph * Documentation: web: http://reference.wolfram.com/language/ref/GridGraph.html * * Definitions: None * * Own values: None * * Down values: None * * Up values: None * * Sub values: None * * Default value: None * * Numeric values: None */ fun gridGraph(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction { return MathematicaFunction("GridGraph", arguments.toMutableList(), options) }
2
Kotlin
0
3
4fcf68af14f55b8634132d34f61dae8bb2ee2942
4,027
mathemagika
Apache License 2.0
library/src/main/java/dev/storeforminecraft/skinviewandroid/library/libs/BufferUtil.kt
storeforminecraft
517,862,529
false
{"Kotlin": 44552}
package dev.storeforminecraft.skinviewandroid.library.libs import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.FloatBuffer import java.nio.ShortBuffer /** * GL ES buffer related utils */ object BufferUtil { fun createFloatBuffer(array: FloatArray) : FloatBuffer{ // (number of coordinate values * 4 bytes per float) return ByteBuffer.allocateDirect(array.size * 4).run { // use the device hardware's native byte order order(ByteOrder.nativeOrder()) // create a floating point buffer from the ByteBuffer asFloatBuffer().apply { // add the coordinates to the FloatBuffer put(array) // set the buffer to read the first coordinate position(0) } } } fun createShortBuffer(array: ShortArray) : ShortBuffer{ // (# of coordinate values * 2 bytes per short) return ByteBuffer.allocateDirect(array.size * 2).run { order(ByteOrder.nativeOrder()) asShortBuffer().apply { put(array) position(0) } } } }
0
Kotlin
0
7
13669724f73798ce873e4ea3f95807086e48a2a7
1,168
SkinViewAndroid
MIT License
src/main/kotlin/com/refinedmods/refinedstorage/apiimpl/storage/disk/factory/ItemStorageDiskFactory.kt
thinkslynk
290,596,653
true
{"Kotlin": 695976, "Shell": 456}
package com.refinedmods.refinedstorage.apiimpl.storage.disk.factory import com.refinedmods.refinedstorage.RS import com.refinedmods.refinedstorage.api.storage.disk.IStorageDisk import com.refinedmods.refinedstorage.api.storage.disk.IStorageDiskFactory import com.refinedmods.refinedstorage.apiimpl.storage.disk.ItemStorageDisk import com.refinedmods.refinedstorage.extensions.Constants import com.refinedmods.refinedstorage.util.StackUtils.deserializeStackFromNbt import net.minecraft.item.ItemStack import net.minecraft.nbt.CompoundTag import net.minecraft.nbt.ListTag import net.minecraft.server.world.ServerWorld import net.minecraft.util.Identifier class ItemStorageDiskFactory : IStorageDiskFactory<ItemStack> { override fun createFromNbt(world: ServerWorld, tag: CompoundTag): IStorageDisk<ItemStack> { val disk = ItemStorageDisk(world, tag.getInt(ItemStorageDisk.NBT_CAPACITY)) val list: ListTag = tag.getList(ItemStorageDisk.NBT_ITEMS, Constants.NBT.COMPOUND_TAG) for (i in 0 until list.size) { val stack = deserializeStackFromNbt(list.getCompound(i)) if (!stack.isEmpty) { disk.rawStacks.put(stack.item, stack) } } return disk } override fun create(world: ServerWorld, capacity: Int): IStorageDisk<ItemStack> { return ItemStorageDisk(world, capacity) } companion object { val ID: Identifier = Identifier(RS.ID, "item") } }
1
Kotlin
0
2
c92afa51af0e5e08caded00882f91171652a89e3
1,467
refinedstorage
MIT License
common/src/main/kotlin/tech/sethi/pebbles/cobbledhunters/data/DatabaseHandlerInterface.kt
navneetset
770,120,520
false
{"Kotlin": 258730}
package tech.sethi.pebbles.cobbledhunters.data import com.cobblemon.mod.common.item.PokemonItem import com.cobblemon.mod.common.pokemon.Pokemon import net.minecraft.item.ItemStack import tech.sethi.pebbles.cobbledhunters.config.exp.ExpConfigLoader import tech.sethi.pebbles.cobbledhunters.hunt.type.* import tech.sethi.pebbles.cobbledhunters.util.PM interface DatabaseHandlerInterface { fun reload() fun getRewards(): List<HuntReward> fun getReward(id: String): HuntReward? fun getGlobalHunts(): List<GlobalHunt> fun getGlobalHuntPools(): List<HuntPool> fun getGlobalHuntSessions(): Map<String, GlobalHuntSession> fun getPersonalHunts(): List<Hunt> fun getPersonalHuntSessions(): Map<String, PersonalHunts> fun addGlobalHuntSession(huntSession: GlobalHuntSession): Boolean fun updateGlobalHuntSession(huntSession: GlobalHuntSession) fun initPlayerRewardStorage(playerUUID: String, playerName: String) fun getPlayerRewardStorage(playerUUID: String): RewardStorage? fun addPlayerRewards(playerUUID: String, rewards: List<HuntReward>, exp: Int = 0) fun removePlayerRewards(playerUUID: String, uuids: List<String>) fun removePlayerExp(playerUUID: String) fun initPlayerExpProgress(playerUUID: String, playerName: String) fun getPlayerExpProgress(playerUUID: String): ExpConfigLoader.ExpProgress? fun addPlayerExp(playerUUID: String, exp: Int) fun playerLevel(playerUUID: String): Int fun ping() fun close() } //fun Pokemon.toHuntDisplayStack(hunt: Hunt): ItemStack { // val pokemonStack = PokemonItem.from(this) // val species = this.species.translatedName.string // // val huntballType = pokeballMap[hunt.huntFeature.ball] // var huntballName: String? = "Any Ball" // // if (huntballType != null) { // huntballName = PM.getLocaleText(PM.getItem(huntballType).translationKey) // } // // val levelRangeString = // hunt.huntFeature.levelRange.min.toString() + " - " + hunt.huntFeature.levelRange.max.toString() // // val placeholderMap = mapOf( // "{huntball}" to huntballName, // "{shiny}" to if (hunt.huntFeature.shiny) "<gold>★</gold>" else "", // "{level_range}" to levelRangeString, // "{ability}" to hunt.huntFeature.ability?.let { PM.getLocaleText(it) }, // "{gender}" to hunt.huntFeature.gender.name, // "{form}" to hunt.huntFeature.form, // ) // // return pokemonStack //}
0
Kotlin
0
0
f01b9c51cc97a97e9a0d396b4e63c1ad4bb468c7
2,452
pebbles-cobbledhunters-multiplatform
Creative Commons Zero v1.0 Universal
src/test/kotlin/fm/force/quiz/security/service/PasswordHashGeneratorServiceTest.kt
night-crawler
207,094,425
false
null
package fm.force.quiz.security.service import fm.force.quiz.AbstractBootTest import io.kotlintest.matchers.boolean.shouldBeTrue import io.kotlintest.matchers.string.shouldNotBeBlank import io.kotlintest.matchers.types.shouldNotBeNull import io.kotlintest.specs.WordSpec open class PasswordHashGeneratorServiceTest( private val passwordHashGeneratorService: PasswordHashGeneratorService ) : AbstractBootTest, WordSpec() { init { "PasswordHashGeneratorService" should { "generate hashes" { val hash = passwordHashGeneratorService.encode("my password") hash.shouldNotBeBlank() hash.shouldNotBeNull() val matches = passwordHashGeneratorService.matches("my password", hash) matches.shouldBeTrue() } } } }
1
Kotlin
1
7
0e34f5ff4cd85f877e739260a6055ada933364e2
836
quiz
MIT License
app/src/main/java/com/example/fitnesslog/program/view/adapter/ProgramAdapter.kt
Mark-Vasquez
684,065,542
false
{"Kotlin": 34321}
package com.example.fitnesslog.program.ui.program.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.example.fitnesslog.R import com.example.fitnesslog.program.data.entity.Program class ProgramAdapter(private val programs: List<Program>) : RecyclerView.Adapter<ProgramAdapter.ViewHolder>() { class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val tvProgramName: TextView = view.findViewById(R.id.tvProgramName) val tvNumberOfWorkouts: TextView = view.findViewById(R.id.tvNumberOfWorkouts) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.program_item, parent, false) return ViewHolder(view) } override fun getItemCount(): Int { return programs.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val program = programs[position] holder.apply { // tvProgramName.text = program.programName // tvNumberOfWorkouts.text = "${program.numberOfWorkouts} workouts" } } }
2
Kotlin
0
0
7434cc4407995a79283f5fb9eced2e3f79ca70b6
1,272
Fitness-Log
Apache License 2.0