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
feedparser/src/test/java/io/github/lazyengineer/feedparser/namespaces/ITunesParserTest.kt
lazy-engineer
294,155,514
false
null
package io.github.lazyengineer.feedparser.namespaces import io.github.lazyengineer.feedparser.FeedParser import io.github.lazyengineer.feedparser.model.feed.ItemGUID import io.github.lazyengineer.feedparser.model.feed.RSSFeed import org.amshove.kluent.`should equal` import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.junit.MockitoJUnitRunner import org.xmlpull.v1.XmlPullParser import org.xmlpull.v1.XmlPullParserFactory import java.io.BufferedReader import java.io.ByteArrayInputStream import java.io.InputStreamReader import java.io.Reader @RunWith(MockitoJUnitRunner::class) class ITunesParserTest { private lateinit var rssXML: String private lateinit var xmlPullParser: XmlPullParser private lateinit var feed: RSSFeed @Before fun setUp() { val rssXMLStream = this.javaClass.classLoader!!.getResourceAsStream("mock_itunes_rss_sample.xml") val rssReader = BufferedReader(InputStreamReader(rssXMLStream)) val stringBuilder = StringBuilder() var line: String? while (rssReader.readLine() .also { line = it } != null ) { stringBuilder.append(line) .append('\n') } rssXML = stringBuilder.toString() val factory = XmlPullParserFactory.newInstance() xmlPullParser = factory.newPullParser() val reader: Reader = InputStreamReader(ByteArrayInputStream(rssXML.toByteArray())) xmlPullParser.setInput(reader) feed = FeedParser.parseFeed(rssXML, xmlPullParser) as RSSFeed } @Test fun `parse xml string should return channel itunes element`() { feed.iTunes?.author `should equal` "The Sunset Explorers" feed.iTunes?.explicit `should equal` "false" feed.iTunes?.image?.attributes?.href `should equal` "https://applehosted.podcasts.apple.com/hiking_treks/artwork.png" feed.iTunes?.owner?.name `should equal` "Sunset Explorers" feed.iTunes?.owner?.email `should equal` "<EMAIL>" feed.iTunes?.type `should equal` "serial" feed.iTunes?.categories!![0].attributes?.text `should equal` "Sports" feed.iTunes?.categories!![0].subcategory?.attributes?.text `should equal` "Wilderness" } @Test fun `parse xml string should return itunes element of fourth item`() { feed.items[3].iTunes?.explicit `should equal` "false" feed.items[3].iTunes?.image?.attributes?.href `should equal` "http://example.com/podcasts/everything/AllAboutEverything/Episode3.jpg" feed.items[3].iTunes?.episode `should equal` 2 feed.items[3].iTunes?.season `should equal` 2 feed.items[3].iTunes?.duration `should equal` 2434 * 1000L feed.items[3].iTunes?.episodeType `should equal` "full" } @Test fun `parse xml string should return expected fifth item`() { feed.items[4].title `should equal` "S02 EP01 Stawamus Chief" feed.items[4].description `should equal` "We tackle Stawamus Chief outside of Vancouver, BC and you should too!" feed.items[4].media?.url `should equal` "http://example.com/podcasts/everything/AllAboutEverythingEpisode4.mp3" feed.items[4].media?.size `should equal` 498537 feed.items[4].media?.type `should equal` "audio/mpeg" feed.items[4].guid `should equal` ItemGUID(value = "aae20190516", isPermaLink = true) feed.items[4].iTunes?.explicit `should equal` "false" feed.items[4].iTunes?.episode `should equal` 1 feed.items[4].iTunes?.season `should equal` 2 feed.items[4].iTunes?.duration `should equal` (13 * 60 * 1000) + (24 * 1000).toLong() //"13:24" feed.items[4].iTunes?.episodeType `should equal` "full" } @Test fun `parse xml string should return itunes items`() { feed.items.size `should equal` 9 } }
0
Kotlin
0
0
e088bee87ab29db9ff781c7afb172f8a08500208
3,553
FeedParser
MIT License
common/src/main/java/com/idisfkj/awesome/common/utils/ToastUtils.kt
whistlexie
508,696,690
false
null
package com.idisfkj.awesome.common.utils import android.content.Context import android.widget.Toast fun Context.showToast(content: String, duration: Int = Toast.LENGTH_SHORT) { Toast.makeText(this, content,duration).show() }
0
Kotlin
0
0
3e239a39f9b3cbe0228a785118a4920d68f1ced9
230
GithubApp
Apache License 2.0
Chapter08/Activity08.01/app/src/main/java/com/example/mywatertracker/worker/WaterConsumptionWorker.kt
PacktPublishing
810,886,298
false
{"Kotlin": 1028530}
package com.example.mywatertracker.worker import android.annotation.SuppressLint import android.app.Notification.FOREGROUND_SERVICE_IMMEDIATE import android.app.NotificationChannel import android.app.NotificationManager import android.app.NotificationManager.IMPORTANCE_HIGH import android.app.PendingIntent import android.app.PendingIntent.FLAG_IMMUTABLE import android.content.Context import android.content.Intent import android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC import android.os.Build import android.os.Build.VERSION_CODES import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.content.ContextCompat import androidx.work.CoroutineWorker import androidx.work.ForegroundInfo import androidx.work.WorkerParameters import androidx.work.workDataOf import com.example.mywatertracker.MainActivity import com.example.mywatertracker.R import kotlinx.coroutines.delay import java.util.concurrent.atomic.AtomicInteger class WaterConsumptionWorker( context: Context, parameters: WorkerParameters ) : CoroutineWorker(context, parameters) { private val channelId by lazy { createNotificationChannel() } override suspend fun doWork(): Result { setForeground(getForegroundInfo()) while (true) { waterBalance.getAndAdd(-144) setProgress(workDataOf(DATA_KEY_WATER_BALANCE to waterBalanceInMilliliters())) updateNotification() delay(5000) } return Result.success() } override suspend fun getForegroundInfo(): ForegroundInfo { val notification = getNotification() return if (Build.VERSION.SDK_INT >= VERSION_CODES.Q) { ForegroundInfo( NOTIFICATION_ID, notification, FOREGROUND_SERVICE_TYPE_DATA_SYNC ) } else { ForegroundInfo(NOTIFICATION_ID, notification) } } @SuppressLint("MissingPermission") private fun updateNotification() { val notification = getNotification() NotificationManagerCompat .from(applicationContext) .notify(NOTIFICATION_ID, notification) } private fun getPendingIntent(): PendingIntent { val flag = if (Build.VERSION.SDK_INT >= VERSION_CODES.S) { FLAG_IMMUTABLE } else { 0 } return PendingIntent.getActivity( applicationContext, 0, Intent(applicationContext, MainActivity::class.java), flag ) } private fun getNotification() = getNotificationBuilder() .setContentText(String.format("Water level is %.3f", waterBalanceInMilliliters())) .build() private fun getNotificationBuilder(): NotificationCompat.Builder { val pendingIntent = getPendingIntent() return NotificationCompat.Builder( applicationContext, channelId ).setContentTitle("Water balance") .setSmallIcon( R.drawable.ic_launcher_foreground ).setContentIntent(pendingIntent) .setTicker( "Tracking water balance" ).setOngoing(true) .setForegroundServiceBehavior( FOREGROUND_SERVICE_IMMEDIATE ).setOnlyAlertOnce(true) } private fun createNotificationChannel(): String = if ( Build.VERSION.SDK_INT >= VERSION_CODES.O ) { val newChannelId = "WaterTracking" val channelName = applicationContext.getString(R.string.channel_name_water_tracking) val channel = NotificationChannel(newChannelId, channelName, IMPORTANCE_HIGH) val service = requireNotNull( ContextCompat.getSystemService(applicationContext, NotificationManager::class.java) ) service.createNotificationChannel(channel) newChannelId } else { "" } companion object { private const val NOTIFICATION_ID = 0x3A7E12 private val waterBalance: AtomicInteger = AtomicInteger(0) const val DATA_KEY_WATER_BALANCE = "WaterLevel" private fun waterBalanceInMilliliters() = waterBalance.toInt() / 1000f fun increaseBalance(amountInMilliliters: Float) { waterBalance.addAndGet((amountInMilliliters * 1000f).toInt()) } } }
0
Kotlin
3
2
7200427e273b8d0ef7c27991370f7541ae0f6a86
4,332
How-to-Build-Android-Apps-with-Kotlin-Third-Edition
MIT License
app/src/main/java/com/rockspin/androiddevtest/data/remote/APIServiceFactory.kt
RSDosev
145,824,954
false
null
package com.rockspin.androiddevtest.data.remote import com.google.gson.Gson import com.google.gson.GsonBuilder import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object APIServiceFactory { fun build() = buildRetrofit() .create(APIService::class.java) private fun buildRetrofit(): Retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create(buildGsonParser())) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() private fun buildGsonParser(): Gson = GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss") .create() }
0
Kotlin
0
0
3933e8fff74d4a075b59833c106fbae1d3291425
822
Rockspin-Android-Code-Test
Apache License 2.0
shared/src/commonMain/kotlin/by/game/binumbers/undo/data/source/local/GameUndoLocalDataSourceImpl.kt
alexander-kulikovskii
565,271,232
false
{"Kotlin": 454229, "Swift": 3274, "Ruby": 2480, "Shell": 622}
package by.game.binumbers.undo.data.source.local import by.game.binumbers.base.model.LevelId import by.game.binumbers.base.storage.KeyValueStorage class GameUndoLocalDataSourceImpl(private val keyValueStorage: KeyValueStorage) : GameUndoLocalDataSource { override suspend fun restoreUndoEnabled(levelId: LevelId): Boolean { return keyValueStorage.getBoolean("${levelId.toKey()}_enabled", false) } override suspend fun restoreUndoCount(levelId: LevelId): Long { return keyValueStorage.getLong("${levelId.toKey()}_count", -1L) } override suspend fun saveUndoEnabled(levelId: LevelId, enabled: Boolean) { keyValueStorage.saveBoolean("${levelId.toKey()}_enabled", enabled) } override suspend fun saveUndoCount(levelId: LevelId, count: Long) { keyValueStorage.saveLong("${levelId.toKey()}_count", count) } private fun LevelId.toKey(): String = "$KEY_PREFIX${this.id}" private companion object { private const val KEY_PREFIX = "Game_Undo_" } }
0
Kotlin
0
10
66b1678b47a96a52ebef467111d1d4854a37486a
1,033
2048-kmm
Apache License 2.0
app/src/main/kotlin/com/ivanovsky/passnotes/presentation/selectdb/cells/factory/SelectDatabaseCellViewModelFactory.kt
aivanovski
95,774,290
false
null
package com.ivanovsky.passnotes.presentation.selectdb.cells.factory import com.ivanovsky.passnotes.presentation.core.BaseCellViewModel import com.ivanovsky.passnotes.presentation.core.event.EventProvider import com.ivanovsky.passnotes.presentation.core.factory.CellViewModelFactory import com.ivanovsky.passnotes.presentation.core.model.BaseCellModel import com.ivanovsky.passnotes.presentation.selectdb.cells.model.DatabaseFileCellModel import com.ivanovsky.passnotes.presentation.selectdb.cells.viewmodel.DatabaseFileCellViewModel class SelectDatabaseCellViewModelFactory : CellViewModelFactory { override fun createCellViewModel( model: BaseCellModel, eventProvider: EventProvider ): BaseCellViewModel { return when (model) { is DatabaseFileCellModel -> DatabaseFileCellViewModel(model, eventProvider) else -> throwUnsupportedModelException(model) } } }
0
Kotlin
0
0
08df99c790087a252f05de76a75833ec538f6100
927
passnotes
Apache License 2.0
app/src/main/java/com/example/valorant/ui/login/LoginDialog.kt
JeeSeongDeok
390,180,251
false
null
package com.example.valorant.ui.login import android.app.Dialog import android.content.Context import android.widget.Button import android.widget.EditText import com.example.valorant.R class LoginDialog (context: Context) { private val dialog = Dialog(context) private lateinit var onClickedListener: ButtonClickListener fun callLoginDig(){ loginDig() dialog.show() } fun loginDig(){ dialog.setContentView(R.layout.dialog_signup) dialog.window!!.setBackgroundDrawableResource(android.R.color.transparent) dialog.setCanceledOnTouchOutside(true) dialog.setCancelable(true) // dialog 변수들 val id = dialog.findViewById<EditText>(R.id.dialog_id) val pw = dialog.findViewById<EditText>(R.id.dialog_pw) val btnLogin = dialog.findViewById<Button>(R.id.dialog_login) // 리스너 btnLogin.setOnClickListener{ onClickedListener.onClicked(id.text.toString(), pw.text.toString()) dialog.dismiss() } } interface ButtonClickListener{ fun onClicked(id: String, pw: String) } fun setOnClickedListener(listener: ButtonClickListener) { onClickedListener = listener } }
0
Kotlin
0
6
a29851214355c9cf3c0d41f22b2ececaabe6b113
1,229
valorantapp
MIT License
infra/preferences/src/commonMain/kotlin/com/taskodoro/storage/preferences/datastore/DataStorePreferences.kt
felipejoglar
457,288,734
false
{"Kotlin": 219381, "Swift": 9959}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.taskodoro.storage.preferences.datastore import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import com.taskodoro.storage.preferences.Preferences import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking internal class DataStorePreferences( private val dataStore: DataStore<androidx.datastore.preferences.core.Preferences>, ) : Preferences { override fun getBoolean(key: String): Boolean = runBlocking { return@runBlocking dataStore.data.first()[booleanPreferencesKey(key)] ?: false } override fun setBoolean(key: String, value: Boolean): Unit = runBlocking { dataStore.edit { preferences -> preferences[booleanPreferencesKey(key)] = value } } }
9
Kotlin
0
1
94ea60b6568cb58e0e97cdeed9cb183f3e9eea2d
1,457
taskodoro
Apache License 2.0
platform/lib/domain/src/main/kotlin/io/hamal/lib/domain/vo/Code.kt
hamal-io
622,870,037
false
{"Kotlin": 2265145, "C": 1398401, "TypeScript": 281481, "Lua": 117790, "C++": 40651, "Makefile": 11728, "Java": 7564, "CMake": 2810, "JavaScript": 2640, "CSS": 1567, "Shell": 977, "HTML": 903}
package io.hamal.lib.domain.vo import io.hamal.lib.common.domain.IntValueObject import io.hamal.lib.common.domain.IntValueObjectSerializer import io.hamal.lib.common.domain.StringValueObject import io.hamal.lib.common.domain.StringValueObjectSerializer import io.hamal.lib.common.snowflake.SnowflakeId import io.hamal.lib.kua.type.StringType import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable(with = CodeId.Serializer::class) class CodeId(override val value: SnowflakeId) : SerializableDomainId() { constructor(value: Int) : this(SnowflakeId(value.toLong())) constructor(value: String) : this(SnowflakeId(value.toLong(16))) internal object Serializer : SerializableDomainIdSerializer<CodeId>(::CodeId) } @SerialName("CodeValue") @Serializable(with = CodeValue.Serializer::class) class CodeValue(override val value: String) : StringValueObject() { constructor(str: StringType) : this(str.value) internal object Serializer : StringValueObjectSerializer<CodeValue>(::CodeValue) } @Serializable(with = CodeVersion.Serializer::class) class CodeVersion(override val value: Int) : IntValueObject() { init { require(value > 0) { "CodeVersion must be positive" } } internal object Serializer : IntValueObjectSerializer<CodeVersion>(::CodeVersion) }
21
Kotlin
0
0
90345f7663444dc8f067861e9ba72ec16350757d
1,333
hamal
Creative Commons Zero v1.0 Universal
domain/src/main/java/com/example/domain/entity/pharmacyResponse/PharmacyResponse.kt
YoussefmSaber
595,215,406
false
null
package com.example.domain.entity.pharmacyResponse class PharmacyResponse : ArrayList<PharmacyResponseItem>()
0
Kotlin
1
4
17b7c424241c68a44d74480cff60b510257c6981
110
Eshfeeny
MIT License
baserequest/src/main/java/com/pathmazing/baserequest/rest/RestClient.kt
Ulseyha
173,866,398
false
null
package com.pathmazing.baserequest.rest import android.content.Context import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import java.lang.NullPointerException import java.util.* class RestClient(private val context: Context? = null, private val baseUrl: String? = "", private val hashMap: HashMap<String, String>? = HashMap(), private val catchSize: Long = 0, private val connectionTimeout: Long = 0) { companion object { private const val CATCH_SIZE = 1024L private const val CONNECTION_TIME_OUT = 60L } data class Builder(private var context: Context? = null, private var baseUrl: String = "", private var hashMap: HashMap<String, String> = HashMap(), private var catchSize: Long = CATCH_SIZE, private var connectionTimeout: Long = CONNECTION_TIME_OUT) { fun baseUrl(baseUrl: String) = apply { this.baseUrl = baseUrl } fun header(header: HashMap<String, String>) = apply { this.hashMap = header } fun catchSize(catchSize: Long) = apply { this.catchSize = catchSize } fun connectionTimeout(connectionTimeout: Long) = apply { this.connectionTimeout = connectionTimeout } fun init() = RestClient(context, baseUrl, hashMap, catchSize, connectionTimeout) } inline fun <reified T> build(): T? { try { val okHttpClient = OkHttpManager. Builder(getContext()!!). catchSize(getCatchSize()). header(getHeader()!!). connectionTimeout(getConnectionTimeout()!!). init(). build() val retrofit = Retrofit.Builder() .baseUrl(getBaseUrl()!!) .addConverterFactory(GsonConverterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(okHttpClient) .build() return retrofit.create<T>(T::class.java) } catch (e: NullPointerException) { return null } } fun getContext(): Context? { return this.context } fun getCatchSize(): Long { return this.catchSize } fun getBaseUrl(): String? { return this.baseUrl } fun getConnectionTimeout(): Long? { return this.connectionTimeout } fun getHeader(): HashMap<String, String>? { return this.hashMap } }
0
Kotlin
0
0
b222145d691548c487496189b57d80dba0548b92
2,735
BaseRequest
MIT License
app/src/main/java/io/github/lekaha/currency/data/response/CurrenciesResponse.kt
lekaha
264,767,689
false
null
package io.github.lekaha.currency.data.response data class CurrenciesResponse( val success: Boolean, val terms: String?, val privacy: String?, val currencies: Map<String, String>?, val error: Map<String, Any>? )
0
Kotlin
0
1
907d926f42f1240eb870751d61e45a055832a06f
232
currency
MIT License
src/main/kotlin/com/eve/engine/esi4k/model/Alliance.kt
EveEngine
254,506,280
false
null
package com.eve.engine.esi4k.model import com.fasterxml.jackson.annotation.JsonProperty open class Alliance( @JsonProperty("creator_corporation_id") val creatorCorporationId: Int, @JsonProperty("creator_id") val creatorId: Int, @JsonProperty("date_founded") val dateFounded: String, @JsonProperty("executor_corporation_id") val executorCorporationId: Int?, @JsonProperty("faction_id") val factionId: Int?, @JsonProperty("name") val name: String, @JsonProperty("ticker") val ticker: String )
0
Kotlin
0
0
6aba2e43a8dc11b2c435d08b91dc9ed4baf9ea9b
520
esi4k
Apache License 2.0
cams-component-common/src/main/java/com/linwei/cams/component/common/utils/FileUtils.kt
WeiShuaiDev
496,946,272
false
{"Java": 582442, "Kotlin": 557761}
package com.linwei.cams.component.common.utils import android.os.Environment import java.io.File import java.math.BigDecimal object FileUtils { fun isSDCardAlive(): Boolean { return Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED } /** * 文件大小 */ fun getSize(file: File?): Long { var size: Long = 0 if(file==null){ return size } try { val fileList = file.listFiles() for (f in fileList) { size = if (f.isDirectory) { size + getSize(f) } else { size + f.length() } } } catch (ignore: Exception) { } return size } /** * 格式化单位 */ fun formatSize(size: Double): String { val kiloByte = size / 1024 if (kiloByte < 1) { return "0KB" } val megaByte = kiloByte / 1024 if (megaByte < 1) { val result1 = BigDecimal(java.lang.Double.toString(kiloByte)) return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB" } val gigaByte = megaByte / 1024 if (gigaByte < 1) { val result2 = BigDecimal(java.lang.Double.toString(megaByte)) return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB" } val teraBytes = gigaByte / 1024 if (teraBytes < 1) { val result3 = BigDecimal(java.lang.Double.toString(gigaByte)) return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB" } val result4 = BigDecimal(teraBytes) return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB" } /** * 删除文件 */ fun delete(file: File?): Boolean { if (file == null) { return false } if (file.isDirectory) { val children = file.list() for (c in children) { val success = delete(File(file, c)) if (!success) { return false } } } return file.delete() } }
1
null
1
1
0ff123efac31c81998b1868bff39046d9761dfd5
2,219
WSWanAndroidAppKotlin
Apache License 2.0
app/src/main/java/com/dujiajun/courseblock/LoginActivity.kt
dujiajun
178,798,441
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "YAML": 1, "Proguard": 2, "XML": 58, "Kotlin": 43, "INI": 1, "Java": 6}
package com.dujiajun.courseblock import android.content.Intent import android.os.Bundle import android.view.View import android.webkit.WebResourceRequest import android.webkit.WebResourceResponse import android.webkit.WebView import android.webkit.WebViewClient import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import com.dujiajun.courseblock.helper.CourseManager class LoginActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) val toolbar = findViewById<Toolbar>(R.id.toolbar) setSupportActionBar(toolbar) toolbar.setNavigationOnClickListener { v: View? -> finish() } val webView = findViewById<WebView>(R.id.webview) val settings = webView.settings settings.userAgentString = "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 Edg/89.0.4389.72" settings.javaScriptEnabled = true val courseManager = CourseManager.getInstance(applicationContext) webView.webViewClient = object : WebViewClient() { override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? { val headers = request.requestHeaders headers["Referer"]?.let { if (it != "") courseManager.setReferer(it) } return super.shouldInterceptRequest(view, request) } override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean { val uri = request.url try { if ("jaccount" == uri.scheme) { val intent = Intent(Intent.ACTION_VIEW, uri) startActivity(intent) return true } } catch (e: Exception) { return true } return false } override fun onPageFinished(view: WebView, url: String) { super.onPageFinished(view, url) if (url.contains(courseManager.afterLoginPattern)) { Toast.makeText(this@LoginActivity, R.string.already_logged_in, Toast.LENGTH_SHORT).show() finish() } } } val loginUrl = courseManager.loginUrl webView.loadUrl(loginUrl) } }
6
Kotlin
2
24
c79597cdd69cf788f06e12643f616e51fbf0bb4e
2,637
CourseBlock
MIT License
app/src/main/java/com/song/video/model/SeekEvent.kt
songmingwen
70,653,066
false
{"Gradle": 28, "Java Properties": 3, "Shell": 3, "Ignore List": 17, "Batchfile": 2, "Markdown": 6, "INI": 13, "Proguard": 12, "Kotlin": 171, "XML": 276, "JSON": 13, "Java": 578, "CMake": 2, "C++": 17, "C": 43, "GLSL": 10, "AIDL": 7, "YAML": 1, "Dart": 11, "OpenStep Property List": 4, "Objective-C": 5, "Ruby": 3, "Groovy": 1}
package com.song.video.model /** * <pre> * Author : songmingwen * </pre> */ class SeekEvent internal constructor(var position: Long)
0
Java
0
1
8735ab6b8bc4d48c38533d6a9b7e88cef18c8389
142
Comic
Apache License 2.0
app/src/main/java/com/example/blogoapp/ui/ActivityViewModel.kt
Marvel999
347,535,139
false
null
package com.example.blogoapp.ui import android.content.Context import androidx.core.content.edit import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.api.model.response.UserResponse import com.example.blogoapp.data.UserAuthRepo import com.example.blogoapp.data.UserSharedpreferences import kotlinx.coroutines.launch class ActivityViewModel:ViewModel() { private val _userRes= MutableLiveData<UserResponse>() val userRes: LiveData<UserResponse> =_userRes fun logout(context: Context):Boolean{ UserSharedpreferences(context).sharedPreferences.edit { remove("PREFS_KEY_TOKEN") }.let { return true } } fun getCurrentUserInfo(){ viewModelScope.launch { UserAuthRepo.getCurrentUser().let { _userRes.postValue(it.body()) } } } }
1
Kotlin
4
8
3709e521a897317d8cd90d1e89745aeeee2d9722
973
Conduit-Android-kotlin
MIT License
src/main/java/io/maliboot/www/hyperf/lombok/usages/SetterUsagesSearch.kt
maliboot
709,094,940
false
{"Kotlin": 158340, "Java": 370, "HTML": 72}
package io.maliboot.www.hyperf.lombok.usages import com.intellij.find.findUsages.FindUsagesHandler import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.jetbrains.php.lang.findUsages.PhpFindUsagesHandlerFactory import com.jetbrains.php.lang.findUsages.PhpFindUsagesOptions // todo: not use => to ReferenceSearch class SetterUsagesSearch(val project: Project) : PhpFindUsagesHandlerFactory(project) { override fun createFindUsagesHandler(element: PsiElement, forHighlightUsages: Boolean): FindUsagesHandler { return this.createFindUsagesHandler( element, if (forHighlightUsages) OperationMode.HIGHLIGHT_USAGES else OperationMode.DEFAULT ) } }
0
Kotlin
0
1
a96a106a49bf4c6642fe2cb01038067dfbd960f9
728
idea-hyperf-plugin
MIT License
app/src/main/java/com/example/compose_weather_app/data/remote/dto/Hourly.kt
Drakime
603,802,754
false
null
package com.example.compose_weather_app.data.remote.dto import com.squareup.moshi.Json data class Hourly( @Json(name = "temperature_2m") val temperature2m: List<Double>, @Json(name = "time") val time: List<String>, @Json(name = "weathercode") val weathercode: List<Int> )
0
Kotlin
0
0
b171e32f7841bd19a01591461d9bcff0b0bf33f4
298
Compose_Weather_App
The Unlicense
ast-model/src/org/jetbrains/dukat/astModel/expressions/LambdaExpressionModel.kt
Kotlin
159,510,660
false
{"Kotlin": 2656818, "WebIDL": 323681, "TypeScript": 135641, "JavaScript": 19475, "ANTLR": 11333}
package org.jetbrains.dukat.astModel.expressions import org.jetbrains.dukat.astModel.LambdaParameterModel import org.jetbrains.dukat.astModel.ParameterModel import org.jetbrains.dukat.astModel.statements.BlockStatementModel data class LambdaExpressionModel( val parameters: List<LambdaParameterModel>, val body: BlockStatementModel ) : ExpressionModel
244
Kotlin
42
535
d50b9be913ce8a2332b8e97fd518f1ec1ad7f69e
361
dukat
Apache License 2.0
app/src/main/java/io/github/pelmenstar1/digiDict/ui/stats/IntegerWithoutZeroValueFormatter.kt
pelmenstar1
512,710,767
false
{"Kotlin": 1238378, "Python": 531}
package io.github.pelmenstar1.digiDict.ui.stats import com.github.mikephil.charting.formatter.ValueFormatter /** * Represents a value formatter that truncates given [Float] value to [Int] and if that [Int] is zero, returns an empty string, * otherwise converts the [Int] to [String] using simple [Int.toString] method */ object IntegerWithoutZeroValueFormatter : ValueFormatter() { override fun getFormattedValue(value: Float): String { val iValue = value.toInt() return if (iValue == 0) "" else iValue.toString() } }
6
Kotlin
0
3
62f9519a065f1b9f27d200636b07e11d88a270f6
547
DigiDictionary
MIT License
android/src/main/kotlin/org/acyb/sayit/app/molecule/PopUpPicker.kt
a-cyborg
766,941,087
false
{"Kotlin": 165341}
/* * Copyright (c) 2024 <NAME> / All rights reserved. * * Use of this source code is governed by Apache v2.0 */ package org.acyb.sayit.app.molecule import androidx.compose.foundation.layout.Box import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberCoroutineScope import kotlinx.coroutines.launch import org.acyb.sayit.app.atom.DialogStandardFitContent import org.acyb.sayit.app.atom.SpacerMedium import org.acyb.sayit.app.atom.SpacerXLarge @Composable fun <T> PopUpPickerStandardWheel( title: String, info: String = "", pickerValues: List<T>, pickerInitIdx: Int = 0, pickerItemRow: @Composable (T) -> Unit, onDismiss: () -> Unit, onConfirm: (T) -> Unit, ) { val scope = rememberCoroutineScope() DialogStandardFitContent(onDismiss = onDismiss) { SpacerXLarge() TextRowTitleAndInfo(title = title, info = info) SpacerMedium() Box { WheelPicker( values = pickerValues, initIdx = pickerInitIdx, itemRow = { pickerItemRow(it) }, onCancel = onDismiss, onConfirm = { scope.launch { onConfirm(it) } .invokeOnCompletion { onDismiss() } }, ) } SpacerXLarge() } }
0
Kotlin
0
0
dc69c992895d0377dc6cc499dfc3e9e876758873
1,341
SayItAlarmMP
Apache License 2.0
orchestrator/rdfc-orchestrator/src/main/kotlin/runner/exception/UnsupportedRunnerTypeException.kt
rdf-connect
782,188,424
false
{"Kotlin": 119278, "TypeScript": 35127, "Python": 21679, "Shell": 1021, "Ruby": 601, "Dockerfile": 423}
package technology.idlab.runner.exception import technology.idlab.RDFCException import technology.idlab.rdfc.core.intermediate.runner.RunnerType /** * A known type was used, but it has no corresponding implementation. * * @param type The type which was used, but not implemented. */ class UnsupportedRunnerTypeException(private val type: RunnerType) : RDFCException()
13
Kotlin
0
1
5bd027413f54984938742c44aed6c3b09dfce403
374
orchestrator
MIT License
sync/sync-impl/src/main/java/com/duckduckgo/sync/impl/ui/SyncConnectViewModel.kt
hojat72elect
822,396,044
false
{"Kotlin": 11626231, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784}
package com.duckduckgo.sync.impl.ui import android.graphics.Bitmap import androidx.annotation.StringRes import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.duckduckgo.anvil.annotations.ContributesViewModel import com.duckduckgo.common.utils.DispatcherProvider import com.duckduckgo.di.scopes.ActivityScope import com.duckduckgo.sync.impl.AccountErrorCodes.ALREADY_SIGNED_IN import com.duckduckgo.sync.impl.AccountErrorCodes.CONNECT_FAILED import com.duckduckgo.sync.impl.AccountErrorCodes.CREATE_ACCOUNT_FAILED import com.duckduckgo.sync.impl.AccountErrorCodes.INVALID_CODE import com.duckduckgo.sync.impl.AccountErrorCodes.LOGIN_FAILED import com.duckduckgo.sync.impl.Clipboard import com.duckduckgo.sync.impl.QREncoder import com.duckduckgo.sync.impl.R import com.duckduckgo.sync.impl.R.dimen import com.duckduckgo.sync.impl.Result.Error import com.duckduckgo.sync.impl.Result.Success import com.duckduckgo.sync.impl.SyncAccountRepository import com.duckduckgo.sync.impl.getOrNull import com.duckduckgo.sync.impl.onFailure import com.duckduckgo.sync.impl.onSuccess import com.duckduckgo.sync.impl.pixels.SyncPixels import com.duckduckgo.sync.impl.ui.SyncConnectViewModel.Command.FinishWithError import com.duckduckgo.sync.impl.ui.SyncConnectViewModel.Command.LoginSuccess import com.duckduckgo.sync.impl.ui.SyncConnectViewModel.Command.ReadTextCode import com.duckduckgo.sync.impl.ui.SyncConnectViewModel.Command.ShowError import com.duckduckgo.sync.impl.ui.SyncConnectViewModel.Command.ShowMessage import javax.inject.* import kotlinx.coroutines.channels.BufferOverflow.DROP_OLDEST import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @ContributesViewModel(ActivityScope::class) class SyncConnectViewModel @Inject constructor( private val syncAccountRepository: SyncAccountRepository, private val qrEncoder: QREncoder, private val clipboard: Clipboard, private val syncPixels: SyncPixels, private val dispatchers: DispatcherProvider, ) : ViewModel() { private val command = Channel<Command>(1, DROP_OLDEST) fun commands(): Flow<Command> = command.receiveAsFlow() private val viewState = MutableStateFlow(ViewState()) fun viewState(): Flow<ViewState> = viewState.onStart { pollConnectionKeys() } private fun pollConnectionKeys() { viewModelScope.launch(dispatchers.io()) { showQRCode() var polling = true while (polling) { delay(POLLING_INTERVAL) syncAccountRepository.pollConnectionKeys() .onSuccess { success -> if (!success) return@onSuccess // continue polling syncPixels.fireSignupConnectPixel() command.send(LoginSuccess) polling = false }.onFailure { when (it.code) { CONNECT_FAILED.code, LOGIN_FAILED.code -> { command.send(ShowError(R.string.sync_connect_login_error, it.reason)) polling = false } } } } } } private suspend fun showQRCode() { syncAccountRepository.getConnectQR() .onSuccess { connectQR -> val qrBitmap = withContext(dispatchers.io()) { qrEncoder.encodeAsBitmap(connectQR, dimen.qrSizeSmall, dimen.qrSizeSmall) } viewState.emit(viewState.value.copy(qrCodeBitmap = qrBitmap)) }.onFailure { command.send(Command.FinishWithError) } } fun onErrorDialogDismissed() { viewModelScope.launch(dispatchers.io()) { command.send(FinishWithError) } } fun onCopyCodeClicked() { viewModelScope.launch(dispatchers.io()) { syncAccountRepository.getConnectQR().getOrNull()?.let { code -> clipboard.copyToClipboard(code) command.send(ShowMessage(R.string.sync_code_copied_message)) } ?: command.send(FinishWithError) } } data class ViewState( val qrCodeBitmap: Bitmap? = null, ) sealed class Command { object ReadTextCode : Command() object LoginSuccess : Command() data class ShowMessage(val messageId: Int) : Command() object FinishWithError : Command() data class ShowError(@StringRes val message: Int, val reason: String = "") : Command() } fun onReadTextCodeClicked() { viewModelScope.launch { command.send(ReadTextCode) } } fun onQRCodeScanned(qrCode: String) { viewModelScope.launch(dispatchers.io()) { when (val result = syncAccountRepository.processCode(qrCode)) { is Error -> { when (result.code) { ALREADY_SIGNED_IN.code -> R.string.sync_login_authenticated_device_error LOGIN_FAILED.code -> R.string.sync_connect_login_error CONNECT_FAILED.code -> R.string.sync_connect_generic_error CREATE_ACCOUNT_FAILED.code -> R.string.sync_create_account_generic_error INVALID_CODE.code -> R.string.sync_invalid_code_error else -> null }?.let { message -> command.send(ShowError(message = message, reason = result.reason)) } } is Success -> { syncPixels.fireLoginPixel() command.send(LoginSuccess) } } } } fun onLoginSuccess() { viewModelScope.launch { syncPixels.fireLoginPixel() command.send(LoginSuccess) } } companion object { const val POLLING_INTERVAL = 5000L } }
0
Kotlin
0
0
b89591136b60933d6a03fac43a38ee183116b7f8
6,263
DuckDuckGo
Apache License 2.0
src/jvmTest/kotlin/com/sunnychung/application/multiplatform/hellohttp/test/CollapseTransformationOffsetMappingTest.kt
sunny-chung
711,387,879
false
{"Kotlin": 1426494, "Shell": 3020}
package com.sunnychung.application.multiplatform.hellohttp.test import com.sunnychung.application.multiplatform.hellohttp.ux.transformation.CollapseTransformationOffsetMapping import kotlin.test.Test import kotlin.test.assertEquals class CollapseTransformationOffsetMappingTest { /** * 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 * a b c { d e f g h i j } k l { m n } o p * collapsedCharRanges [3, 11] [14, 17] * transformedText a b c { . . . } k l { . . . } o p * originalToTransformed 0 1 2 3 9 9 9 9 9 9 9 9 10 11 12 18 18 18 19 20 * transformedToOriginal 0 1 2 3 11 11 12 13 14 17 17 18 19 */ @Test fun test() { val mapping = CollapseTransformationOffsetMapping( listOf(3..11, 14..17) ) assertEquals( listOf(0, 1, 2, 3, 9, 9, 9, 9, 9, 9, 9, 9, 10, 11, 12, 18, 18, 18, 19, 20), (0..19).map { mapping.originalToTransformed(it) } ) assertEquals( listOf(0, 1, 2, 3, 11, 11, 11, 11, 11, 11, 12, 13, 14, 17, 17, 17, 17, 17, 17, 18, 19), (0..20).map { mapping.transformedToOriginal(it) } ) } }
0
Kotlin
0
72
a71b1bab930be2ecbf533c702ee44ef8c549a287
1,298
hello-http
Apache License 2.0
src/main/kotlin/com/lykke/matching/engine/daos/AssetPair.kt
bingoko
129,746,135
true
{"Kotlin": 797433, "Java": 33596}
package com.lykke.matching.engine.daos class AssetPair( val assetPairId: String, val baseAssetId: String, val quotingAssetId: String, val accuracy: Int, val minVolume: Double? = null, val minInvertedVolume: Double? = null ) { override fun toString(): String { return "AssetPair(" + "assetPairId='$assetPairId', " + "baseAssetId='$baseAssetId', " + "quotingAssetId='$quotingAssetId', " + "accuracy=$accuracy, " + "minVolume=$minVolume, " + "minInvertedVolume=$minInvertedVolume" } }
0
Kotlin
0
0
94c9fd250cfa67f7c54d31e20366e3cc97f110e0
642
MatchingEngine
MIT License
reactive-albums-api/src/main/kotlin/nl/juraji/reactive/albums/query/projections/DirectoryProjection.kt
Juraji
290,577,996
false
null
package nl.juraji.reactive.albums.query.projections import java.time.LocalDateTime import javax.persistence.Entity import javax.persistence.Id @Entity data class DirectoryProjection( @Id val id: String, val location: String, val displayName: String, val automaticScanEnabled: Boolean, override var createdAt: LocalDateTime? = null, override var lastModifiedAt: LocalDateTime? = null, ) : AuditedProjection(createdAt, lastModifiedAt)
0
Kotlin
0
1
205927ceb1ce19e27e2b2aa83f61eeda968613d1
483
reactive-albums
MIT License
kafka-streams-test/test/libs/kafka/Test.kt
navikt
483,940,923
false
{"Kotlin": 150856}
package libs.kafka import io.micrometer.core.instrument.simple.SimpleMeterRegistry import lib.kafka.StreamsMock import libs.kafka.serde.StringSerde import org.junit.jupiter.api.Test import kotlin.test.assertEquals internal class Test { @Test fun `join topic with table`() { val topology = topology { val table = consume(Tables.B) consume(Topics.A) .joinWith(table) .map { a, b -> b + a } .produce(Topics.C) } val kafka = StreamsMock() val registry = SimpleMeterRegistry() val config = StreamsConfig( applicationId = "app", brokers = "mock://kafka", ssl = SslConfig("", "", ""), schemaRegistry = SchemaRegistryConfig("", "", ""), ) kafka.connect(topology, config, registry) val a = kafka.testTopic(Topics.A) val b = kafka.testTopic(Topics.B) val c = kafka.testTopic(Topics.C) val key = "1" b.produce(key) { "B" } a.produce(key) { "A" }.produce("2") { "A" } val result = c.readValue() assertEquals("BA", result) println(kafka.visulize().uml()) } } internal object Topics { val A = Topic("A", StringSerde) val B = Topic("B", StringSerde) val C = Topic("C", StringSerde) } internal object Tables { val B = Table(Topics.B) }
0
Kotlin
0
0
56f10b9fd0701bbd8093665e839bb4aa78275344
1,407
aap-libs
MIT License
creator/src/commonMain/kotlin/ch/sourcemotion/tyr/creator/dto/QuizCategoryDto.kt
wem
617,579,274
false
null
package ch.sourcemotion.tyr.creator.dto import ch.sourcemotion.tyr.creator.dto.element.TextDto import ch.sourcemotion.tyr.creator.dto.question.QuestionDto import ch.sourcemotion.tyr.creator.dto.serializer.UuidSerializer import com.benasher44.uuid.Uuid import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable @SerialName("QuizCategoryDto") data class QuizCategoryDto( @Serializable(with = UuidSerializer::class) val id: Uuid, val title: String, val orderNumber: Int, val contextOrQuestionText: TextDto, val questions: List<QuestionDto> = emptyList() )
0
Kotlin
0
0
82aaee37798133bc81934933a1dc35a9e14ff8cb
613
tyr
MIT License
pleo-antaeus-models/src/main/kotlin/io/pleo/antaeus/models/InvoiceStatus.kt
jonnycampos
351,775,934
true
{"Kotlin": 37358, "Shell": 817, "Dockerfile": 770}
package io.pleo.antaeus.models enum class InvoiceStatus { PENDING, PAID, RETRY, FAIL }
0
Kotlin
0
0
06004844fc1d5bf484072965ef29b1ae9446e20e
104
antaeus
Creative Commons Zero v1.0 Universal
src/main/kotlin/io/github/dqualizer/dqlang/types/adapter/constants/resilienceTest/ResilienceTestConstants.kt
dqualizer
610,310,524
false
{"Kotlin": 110854, "HTML": 3542, "Python": 3352}
package io.github.dqualizer.dqlang.types.adapter.constants.resilienceTest import com.fasterxml.jackson.annotation.JsonProperty import io.github.dqualizer.dqlang.types.adapter.constants.SatisfactionValue data class ResilienceTestConstants( @JsonProperty("recovery_time") val recoveryTime: SatisfactionValue? = null, @JsonProperty("response_time") val responseTime: SatisfactionValue? = null, @JsonProperty("error_rate") val errorRate: SatisfactionValue? = null )
6
Kotlin
0
0
938543c2fd0602879492bd9183c668d98d631f3c
478
dqlang
Apache License 2.0
plugins/cloudopt-next-redis/src/main/kotlin/net/cloudopt/next/redis/RedisPlugin.kt
cloudoptlab
117,033,346
false
{"Kotlin": 438045, "HTML": 4325, "Python": 163, "Handlebars": 149, "FreeMarker": 148, "CSS": 23}
/* * Copyright 2017-2021 Cloudopt * * 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 net.cloudopt.next.redis import io.lettuce.core.RedisClient import io.lettuce.core.cluster.RedisClusterClient import io.lettuce.core.resource.ClientResources import io.lettuce.core.resource.DefaultClientResources import net.cloudopt.next.core.ConfigManager import net.cloudopt.next.core.Plugin import net.cloudopt.next.core.Worker import net.cloudopt.next.json.Jsoner.jsonToObjectList import net.cloudopt.next.json.Jsoner.toJsonString /* * Lettuce is a scalable Redis client for building non-blocking Reactive applications. * Next will automatically read the configuration file and initialize the lettuce, * and will modify the default EventLoop of the lettuce to be the EventLoop of the vertx. * */ class RedisPlugin : Plugin { override fun start(): Boolean { if (ConfigManager.configMap.contains("redis")) { val redisConfigList: MutableList<RedisConfig> = ConfigManager.configMap["redis"]!!.toJsonString().jsonToObjectList(RedisConfig::class) redisConfigList.forEach { redisConfig -> val res: ClientResources = DefaultClientResources.builder() .eventExecutorGroup(Worker.vertx.nettyEventLoopGroup()) .build() if (redisConfig.cluster) { startCluster(res, redisConfig) } else { startAlone(res, redisConfig) } RedisManager.configMap[redisConfig.name] = redisConfig } } else { throw RuntimeException("No redis related configuration was found in the configuration to initialize!") } return true } override fun stop(): Boolean { RedisManager.connectionMap.forEach { map -> map.value.close() } RedisManager.publishConnectionMap.forEach { map -> map.value.close() } RedisManager.subscribeConnectionMap.forEach { map -> map.value.close() } RedisManager.clusterConnectionMap.forEach { map -> map.value.close() } RedisManager.clusterPublishConnectionMap.forEach { map -> map.value.close() } RedisManager.clusterSubscribeConnectionMap.forEach { map -> map.value.close() } return true } private fun startAlone(res: ClientResources, redisConfig: RedisConfig) { val client = RedisClient.create(res, redisConfig.uri) RedisManager.clientMap[redisConfig.name] = client RedisManager.connectionMap[redisConfig.name] = client.connect() if (redisConfig.publish) { RedisManager.publishConnectionMap[redisConfig.name] = client.connectPubSub() } if (redisConfig.subscribe) { RedisManager.subscribeConnectionMap[redisConfig.name] = client.connectPubSub() } } private fun startCluster(res: ClientResources, redisConfig: RedisConfig) { val client = RedisClusterClient.create(res, redisConfig.uri) RedisManager.clusterClientMap[redisConfig.name] = client RedisManager.clusterConnectionMap[redisConfig.name] = client.connect() if (redisConfig.publish) { RedisManager.clusterPublishConnectionMap[redisConfig.name] = client.connectPubSub() } if (redisConfig.subscribe) { RedisManager.clusterSubscribeConnectionMap[redisConfig.name] = client.connectPubSub() } } }
3
Kotlin
49
335
b6d8f934357a68fb94ef511109a1a6043af4b5b6
4,074
cloudopt-next
Apache License 2.0
app/src/main/java/com/example/pokinfo/adapter/home/detail/PagerAdapter.kt
T1396
792,347,025
false
{"Kotlin": 440915}
package com.example.pokinfo.adapter.home.detail import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import coil.load import com.example.pokinfo.R class ImageViewPagerAdapter( private val images: List<Pair<String,String>> // name to url ) : RecyclerView.Adapter<ImageViewPagerAdapter.ImageViewHolder>() { inner class ImageViewHolder(view: View) : RecyclerView.ViewHolder(view) { val imageView: ImageView = view.findViewById(R.id.ivPokemonPager) val textView: TextView = view.findViewById(R.id.tvPokemonNamePager) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.pager_home_detail, parent, false) return ImageViewHolder(view) } override fun onBindViewHolder(holder: ImageViewHolder, position: Int) { holder.imageView.load(images[position].second) { error(R.drawable.image_not_found) } holder.textView.text = images[position].first } override fun getItemCount(): Int { return images.size } }
0
Kotlin
0
0
f6cb3ab047fb1b67d08db0eda2f138000402c91a
1,258
PokemonApp
Info-ZIP License
tests/codegen-tests/codegen-tests-jvm/src/test/kotlin/kotlinx/rpc/MainTest.kt
Kotlin
739,292,079
false
{"Kotlin": 366835, "JavaScript": 1134, "Dockerfile": 69}
/* * Copyright 2023-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.rpc import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.runBlocking import kotlin.test.Test interface MainServiceTest : RPC, EmptyService { override suspend fun empty() override val flow: Flow<Int> override val sharedFlow: SharedFlow<Int> override val stateFlow: StateFlow<Int> } class MainTest { @Test fun test() = testServices<MainService, MainServiceTest, CommonService>() private inline fun <reified S1, reified S2, reified S3> testServices() where S1 : RPC, S2 : RPC, S3 : RPC, S1 : EmptyService, S2 : EmptyService, S3 : EmptyService = runBlocking { testService<S1>() testService<S2>() testService<S3>() } }
12
Kotlin
0
68
9ca2708f560d0a6b686abcebfb140ac49699846d
967
kotlinx-rpc
Apache License 2.0
app/src/main/java/com/frogobox/basemusic/util/ConstHelper.kt
amirisback
240,663,454
false
{"Kotlin": 30777}
package com.frogobox.basemusic.util import android.Manifest import android.os.Environment import com.frogobox.basemusic.BuildConfig /** * Created by <NAME> * FrogoBox Inc License * ========================================= * PublicSpeakingBooster * Copyright (C) 16/08/2019. * All rights reserved * ----------------------------------------- * Name : <NAME> * E-mail : <EMAIL> * Github : github.com/amirisback * LinkedIn : linkedin.com/in/faisalamircs * ----------------------------------------- * FrogoBox Software Industries * com.frogobox.publicspeakingbooster.helper * */ class ConstHelper { object Extra { const val BASE_EXTRA = BuildConfig.APPLICATION_ID const val EXTRA_SONG = "$BASE_EXTRA.EXTRA_SONG" } object Ext { const val DEF_DRAWABLE = "drawable" const val DEF_RAW = "raw" const val MP4 = ".mp4" const val PNG = ".png" } }
0
Kotlin
0
5
f2f91a6db1140bc5cf2ae09e8a92a2aa3ecafde7
927
music-player
Apache License 2.0
lib/src/main/kotlin/dev/pellet/codec/http/HTTPRequestLine.kt
CarrotCodes
395,832,386
false
null
package dev.pellet.codec.http data class HTTPRequestLine( val method: HTTPMethod, val resourceUri: String, val httpVersion: String )
8
Kotlin
0
1
cbe849274214812b9c709be26dc58510d5ffc237
146
Pellet
Apache License 2.0
app/src/main/java/com/example/photospheremobile/views/CameraActivity.kt
thiagopereirasilva
217,548,066
false
null
package com.example.photospheremobile.views import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.os.Environment import android.util.Log import android.view.WindowManager import androidx.annotation.Nullable import androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.example.photospheremobile.R import com.example.photospheremobile.service.ImageSetServiceImpl import io.fotoapparat.Fotoapparat import io.fotoapparat.configuration.CameraConfiguration import io.fotoapparat.log.logcat import io.fotoapparat.log.loggers import io.fotoapparat.parameter.ScaleType import io.fotoapparat.result.WhenDoneListener import io.fotoapparat.selector.* import io.fotoapparat.view.CameraView import kotlinx.android.synthetic.main.content_camera.* import java.io.File import java.util.* class CameraActivity : AppCompatActivity() { private var fotoapparat: Fotoapparat? = null private val filename = "test" private var fotoapparatState: FotoapparatState? = null var cameraStatus: CameraState? = null var flashState: FlashState? = null var exposure: ExposureSelector? = null private val permissions = arrayOf( Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE ) @RequiresApi(Build.VERSION_CODES.O) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) supportActionBar!!.hide() window.setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN ) setContentView(R.layout.activity_camera) createFotoapparat() cameraStatus = CameraState.BACK flashState = FlashState.OFF fotoapparatState = FotoapparatState.OFF fab_camera.setOnClickListener { takePhoto() Log.i("Terminou", "SIM") } } private fun createFotoapparat() { val cameraView = findViewById<CameraView>(R.id.camera_view) fotoapparat = Fotoapparat( context = this, view = cameraView, scaleType = ScaleType.CenterCrop, lensPosition = back(), logger = loggers( logcat().also { highestExposure() }.also { lowestExposure() } ), cameraErrorCallback = { error -> println("Recorder errors: $error") } ) fotoapparat?.updateConfiguration( CameraConfiguration( pictureResolution = highestResolution() ) ) fotoapparat?.updateConfiguration( CameraConfiguration( jpegQuality = highestQuality() ) ) } @RequiresApi(Build.VERSION_CODES.O) fun encoder(filePath: String): String { val bytes = File(filePath).readBytes() return Base64.getEncoder().encodeToString(bytes) } @RequiresApi(Build.VERSION_CODES.O) private fun sendPhoto(filePath: String, uuid: UUID, imageName: String) { ImageSetServiceImpl().uploadImage( imageName, uuid.toString(), encoder(filePath) ) } @RequiresApi(Build.VERSION_CODES.O) private fun takePhoto() { if (hasNoPermissions()) { requestPermission() } else { var count = 0 val root = Environment.getExternalStorageDirectory().toString() val uuid = UUID.randomUUID() val dirs = mutableMapOf<String, String>() while (count < 7) { var myDir = File("$root/PhotoAppPicturesIMD") var imageName = filename + "_" + uuid + "_" + count + ".jpeg" if (!myDir.exists()) { myDir.mkdirs() } myDir = File(myDir, imageName) Log.i("PATH: ", myDir.absolutePath) fotoapparat?.updateConfiguration( CameraConfiguration( // exposureCompensation = manualExposure(count * 2) exposureCompensation = lowestExposure() ) ) fotoapparat ?.takePicture() ?.saveToFile(myDir)?.whenDone(object : WhenDoneListener<Unit> { override fun whenDone(@Nullable unit: Unit?) { if (unit != null) { Log.i("Done: ", "Done") sendPhoto(myDir.absolutePath, uuid, imageName) } } }) dirs.put(myDir.absolutePath, imageName) count++ } fotoapparat?.updateConfiguration( CameraConfiguration( exposureCompensation = manualExposure(0) ) ) } } override fun onStart() { super.onStart() if (hasNoPermissions()) { requestPermission() } else { fotoapparat?.start() fotoapparatState = FotoapparatState.ON } } private fun hasNoPermissions(): Boolean { return ContextCompat.checkSelfPermission( this, Manifest.permission.READ_EXTERNAL_STORAGE ) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission( this, Manifest.permission.WRITE_EXTERNAL_STORAGE ) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission( this, Manifest.permission.CAMERA ) != PackageManager.PERMISSION_GRANTED } private fun requestPermission() { ActivityCompat.requestPermissions(this, permissions, 0) } override fun onStop() { super.onStop() fotoapparat?.stop() FotoapparatState.OFF } override fun onResume() { super.onResume() if (!hasNoPermissions() && fotoapparatState == FotoapparatState.OFF) { val intent = Intent(baseContext, CameraActivity::class.java) startActivity(intent) finish() } } } enum class CameraState { FRONT, BACK } enum class FlashState { TORCH, OFF } enum class FotoapparatState { ON, OFF }
0
Kotlin
0
0
9af4a69fff40ba07d5db89e3e9e30aa4bc607ab9
6,582
photospheremobile
MIT License
chapter_eight/PagingJetpackExample/app/src/main/java/com/madonasyombua/pagingjetpackexample/data/NewsArticle.kt
PacktPublishing
561,786,526
false
null
package com.madonasyombua.pagingjetpackexample.data data class NewsArticle( val author: String, val content: String, val description: String, val publishedAt: String, val title: String, val url: String, val urlToImage: String )
0
Kotlin
1
7
3b3cd308f463bc9659ccf6860471f564a56d560f
257
Modern-Android-13-Development-Cookbook
MIT License
Cupcake/app/src/androidTest/java/com/example/cupcake/test/CupcakeScreenNavigationTest.kt
Undiy
702,074,527
false
{"Kotlin": 418636}
package com.example.cupcake.test import androidx.activity.ComponentActivity import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.navigation.compose.ComposeNavigator import androidx.navigation.testing.TestNavHostController import com.example.cupcake.CupcakeApp import com.example.cupcake.CupcakeScreen import com.example.cupcake.R import org.junit.Before import org.junit.Rule import org.junit.Test class CupcakeScreenNavigationTest { @get:Rule val composeTestRule = createAndroidComposeRule<ComponentActivity>() private lateinit var navController: TestNavHostController @Before fun setupCupcakeNavHost() { composeTestRule.setContent { navController = TestNavHostController(LocalContext.current).apply { navigatorProvider.addNavigator(ComposeNavigator()) } CupcakeApp(navController = navController) } } @Test fun cupcakeNavHost_verifyStartDestination() { navController.assertCurrentRouteName(CupcakeScreen.Start.name) } @Test fun cupcakeNavHost_verifyBackNavigationNotShownOnStartOrderScreen() { val backText = composeTestRule.activity.getString(R.string.back_button) composeTestRule.onNodeWithContentDescription(backText).assertDoesNotExist() } @Test fun cupcakeNavHost_clickOneCupcake_navigatesToSelectFlavorScreen() { composeTestRule.onNodeWithStringId(R.string.one_cupcake) .performClick() navController.assertCurrentRouteName(CupcakeScreen.Flavor.name) } @Test fun cupcakeNavHost_clickBackOnFlavorScreen_navigatesToStartScreen() { navigateToFlavorScreen() performNavigateUp() navController.assertCurrentRouteName(CupcakeScreen.Start.name) } @Test fun cupcakeNavHost_clickCancelOnFlavorScreen_navigatesToStartScreen() { navigateToFlavorScreen() composeTestRule.onNodeWithStringId(R.string.cancel).performClick() navController.assertCurrentRouteName(CupcakeScreen.Start.name) } @Test fun cupcakeNavHost_clickNextOnFlavorScreen_navigatesToPickupScreen() { navigateToFlavorScreen() composeTestRule.onNodeWithStringId(R.string.next).performClick() navController.assertCurrentRouteName(CupcakeScreen.Pickup.name) } @Test fun cupcakeNavHost_clickBackOnPickupScreen_navigatesToFlavorScreen() { navigateToPickupScreen() performNavigateUp() navController.assertCurrentRouteName(CupcakeScreen.Flavor.name) } @Test fun cupcakeNavHost_clickCancelOnPickupScreen_navigatesToStartScreen() { navigateToPickupScreen() composeTestRule.onNodeWithStringId(R.string.cancel).performClick() navController.assertCurrentRouteName(CupcakeScreen.Start.name) } @Test fun cupcakeNavHost_clickNextOnPickupScreen_navigatesToSummaryScreen() { navigateToPickupScreen() composeTestRule.onNodeWithStringId(R.string.next).performClick() navController.assertCurrentRouteName(CupcakeScreen.Summary.name) } @Test fun cupcakeNavHost_clickCancelOnSummaryScreen_navigatesToStartScreen() { navigateToSummaryScreen() composeTestRule.onNodeWithStringId(R.string.cancel).performClick() navController.assertCurrentRouteName(CupcakeScreen.Start.name) } private fun navigateToFlavorScreen() { composeTestRule.onNodeWithStringId(R.string.one_cupcake) .performClick() composeTestRule.onNodeWithStringId(R.string.chocolate) .performClick() } private fun navigateToPickupScreen() { navigateToFlavorScreen() composeTestRule.onNodeWithStringId(R.string.next) .performClick() composeTestRule.onNodeWithText(getFormattedDate()) .performClick() } private fun navigateToSummaryScreen() { navigateToPickupScreen() composeTestRule.onNodeWithStringId(R.string.next) .performClick() } private fun performNavigateUp() { val backText = composeTestRule.activity.getString(R.string.back_button) composeTestRule.onNodeWithContentDescription(backText).performClick() } }
0
Kotlin
0
0
d02fefda13f048378d711dd41d35b60c054e0a8e
4,450
android-basics-compose
MIT License
Cupcake/app/src/androidTest/java/com/example/cupcake/test/CupcakeScreenNavigationTest.kt
Undiy
702,074,527
false
{"Kotlin": 418636}
package com.example.cupcake.test import androidx.activity.ComponentActivity import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.navigation.compose.ComposeNavigator import androidx.navigation.testing.TestNavHostController import com.example.cupcake.CupcakeApp import com.example.cupcake.CupcakeScreen import com.example.cupcake.R import org.junit.Before import org.junit.Rule import org.junit.Test class CupcakeScreenNavigationTest { @get:Rule val composeTestRule = createAndroidComposeRule<ComponentActivity>() private lateinit var navController: TestNavHostController @Before fun setupCupcakeNavHost() { composeTestRule.setContent { navController = TestNavHostController(LocalContext.current).apply { navigatorProvider.addNavigator(ComposeNavigator()) } CupcakeApp(navController = navController) } } @Test fun cupcakeNavHost_verifyStartDestination() { navController.assertCurrentRouteName(CupcakeScreen.Start.name) } @Test fun cupcakeNavHost_verifyBackNavigationNotShownOnStartOrderScreen() { val backText = composeTestRule.activity.getString(R.string.back_button) composeTestRule.onNodeWithContentDescription(backText).assertDoesNotExist() } @Test fun cupcakeNavHost_clickOneCupcake_navigatesToSelectFlavorScreen() { composeTestRule.onNodeWithStringId(R.string.one_cupcake) .performClick() navController.assertCurrentRouteName(CupcakeScreen.Flavor.name) } @Test fun cupcakeNavHost_clickBackOnFlavorScreen_navigatesToStartScreen() { navigateToFlavorScreen() performNavigateUp() navController.assertCurrentRouteName(CupcakeScreen.Start.name) } @Test fun cupcakeNavHost_clickCancelOnFlavorScreen_navigatesToStartScreen() { navigateToFlavorScreen() composeTestRule.onNodeWithStringId(R.string.cancel).performClick() navController.assertCurrentRouteName(CupcakeScreen.Start.name) } @Test fun cupcakeNavHost_clickNextOnFlavorScreen_navigatesToPickupScreen() { navigateToFlavorScreen() composeTestRule.onNodeWithStringId(R.string.next).performClick() navController.assertCurrentRouteName(CupcakeScreen.Pickup.name) } @Test fun cupcakeNavHost_clickBackOnPickupScreen_navigatesToFlavorScreen() { navigateToPickupScreen() performNavigateUp() navController.assertCurrentRouteName(CupcakeScreen.Flavor.name) } @Test fun cupcakeNavHost_clickCancelOnPickupScreen_navigatesToStartScreen() { navigateToPickupScreen() composeTestRule.onNodeWithStringId(R.string.cancel).performClick() navController.assertCurrentRouteName(CupcakeScreen.Start.name) } @Test fun cupcakeNavHost_clickNextOnPickupScreen_navigatesToSummaryScreen() { navigateToPickupScreen() composeTestRule.onNodeWithStringId(R.string.next).performClick() navController.assertCurrentRouteName(CupcakeScreen.Summary.name) } @Test fun cupcakeNavHost_clickCancelOnSummaryScreen_navigatesToStartScreen() { navigateToSummaryScreen() composeTestRule.onNodeWithStringId(R.string.cancel).performClick() navController.assertCurrentRouteName(CupcakeScreen.Start.name) } private fun navigateToFlavorScreen() { composeTestRule.onNodeWithStringId(R.string.one_cupcake) .performClick() composeTestRule.onNodeWithStringId(R.string.chocolate) .performClick() } private fun navigateToPickupScreen() { navigateToFlavorScreen() composeTestRule.onNodeWithStringId(R.string.next) .performClick() composeTestRule.onNodeWithText(getFormattedDate()) .performClick() } private fun navigateToSummaryScreen() { navigateToPickupScreen() composeTestRule.onNodeWithStringId(R.string.next) .performClick() } private fun performNavigateUp() { val backText = composeTestRule.activity.getString(R.string.back_button) composeTestRule.onNodeWithContentDescription(backText).performClick() } }
0
Kotlin
0
0
d02fefda13f048378d711dd41d35b60c054e0a8e
4,450
android-basics-compose
MIT License
server/src/main/kotlin/example/bank/ModuleContext.kt
craigatk
332,464,235
false
null
package example.bank import com.zaxxer.hikari.HikariDataSource import org.jooq.DSLContext data class ModuleContext( val dataSource: HikariDataSource, val dslContext: DSLContext )
0
Kotlin
1
9
c3fef27f3c110c5bd319e8795b50ebf6a04add2b
189
bank-account-example
MIT License
build-logic/metrics/src/main/kotlin/com/vk/id/health/metrics/gitlab/GitlabApi.kt
VKCOM
696,297,549
false
{"Kotlin": 910593, "Shell": 17069, "AIDL": 3429, "JavaScript": 1182}
package com.vk.id.health.metrics.gitlab import retrofit2.http.Body import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.PUT import retrofit2.http.Path import retrofit2.http.Query internal interface GitlabApi { @GET("user") suspend fun getUser(): GitlabUserResponse @GET("projects/{project_id}/merge_requests/{merge_request_id}/notes") suspend fun listComments( @Path("project_id") projectId: String, @Path("merge_request_id") mergeRequestId: String, ): List<GitlabMergeRequestComment> @PUT("projects/{project_id}/merge_requests/{merge_request_id}/notes/{note_id}") suspend fun updateComment( @Path("project_id") projectId: String, @Path("merge_request_id") mergeRequestId: String, @Path("note_id") commentId: String, @Query("body") comment: String, ) @POST("projects/{project_id}/merge_requests/{merge_request_id}/notes") suspend fun postCommentToMr( @Path("project_id") projectId: String, @Path("merge_request_id") mergeRequestId: String, @Body body: GitlabPostCommentToMrBody, ) @GET("projects/{project_id}/merge_requests/{merge_request_id}") suspend fun getMergeRequest( @Path("project_id") projectId: String, @Path("merge_request_id") mergeRequestId: String, ): GitlabMergeRequestResponse }
0
Kotlin
3
28
9c1a13e3da07b45e868e8f6c12603eec37e52613
1,368
vkid-android-sdk
MIT License
src/test/kotlin/org/beckn/one/sandbox/bap/message/factories/ProtocolOnRatingMessageFeedbackFactory.kt
beckn
388,431,041
false
null
package org.beckn.one.sandbox.bap.message.factories import org.beckn.one.sandbox.bap.message.entities.OnRatingMessageFeedbackDao import org.beckn.protocol.schemas.ProtocolOnRatingMessageFeedback object ProtocolOnRatingMessageFeedbackFactory { fun create(index: Int = 1): ProtocolOnRatingMessageFeedback { return ProtocolOnRatingMessageFeedback( id = "item id $index", descriptor = "item id $index descriptor", parentId = "item id $index parent id $index" ) } fun createAsEntity(protocol: ProtocolOnRatingMessageFeedback?) = protocol?.let { OnRatingMessageFeedbackDao(protocol.id, protocol.descriptor, protocol.parentId) } }
3
Kotlin
7
0
8036db2551b94dcc9c5eb6e158d80f617597b7d4
657
biab-bap-protocol
MIT License
src/main/kotlin/no/nav/k9/los/nyoppgavestyring/ko/ReservasjonV3FraKøDto.kt
navikt
238,874,021
false
{"Kotlin": 1867972, "JavaScript": 741, "Shell": 657, "Dockerfile": 309, "PLpgSQL": 167}
package no.nav.k9.los.nyoppgavestyring.ko import no.nav.k9.los.domene.modell.Saksbehandler import no.nav.k9.los.nyoppgavestyring.reservasjon.ReservasjonV3 import no.nav.k9.los.nyoppgavestyring.visningoguttrekk.Oppgave import no.nav.k9.los.nyoppgavestyring.visningoguttrekk.OppgaveNøkkelDto import java.time.LocalDateTime data class ReservasjonV3FraKøDto ( val oppgaveNøkkelDto: OppgaveNøkkelDto, val reservasjonsnøkkel: String, val oppgavebehandlingsUrl: String?, val reservertAv: String, val reservertFra: LocalDateTime, val reservertTil: LocalDateTime?, ) { constructor(reservasjonV3: ReservasjonV3, oppgave: Oppgave, reservertAv: Saksbehandler) : this ( oppgaveNøkkelDto = OppgaveNøkkelDto(oppgave), reservasjonsnøkkel = reservasjonV3.reservasjonsnøkkel, oppgavebehandlingsUrl = oppgave.getOppgaveBehandlingsurl(), reservertAv = reservertAv.epost, reservertFra = reservasjonV3.gyldigFra, reservertTil = reservasjonV3.gyldigTil ) }
6
Kotlin
0
0
7829aba13b6955b441c9c28acc4a676dfc0c66b5
1,016
k9-los-api
MIT License
buildSrc/src/main/kotlin/Plugins.kt
BrianLusina
113,182,832
false
null
object Plugins { const val JAVA = "java" const val KOTLIN = "kotlin" const val JACOCO = "jacoco" val JACOCO_PLUGIN = "org.jacoco:org.jacoco.core:${Versions.JACOCO}" const val DETEKT = "io.gitlab.arturbosch.detekt" const val DETEKT_GRADLE = "io.gitlab.arturbosch.detekt:detekt-gradle-plugin" const val DETEKT_FORMATTING = "io.gitlab.arturbosch.detekt:detekt-formatting" const val KOTLIN_GRADLE = "org.jetbrains.kotlin:kotlin-gradle-plugin:${Versions.KOTLIN}" const val KOTLINX = "org.jetbrains.kotlinx" }
0
Kotlin
0
1
8c6dd7ab84714ccb10859beee962a6e574fa9de7
543
KotlinGround
MIT License
src/main/kotlin/com/amazon/opendistroforelasticsearch/indexmanagement/refreshanalyzer/RefreshSearchAnalyzerAction.kt
opendistro-for-elasticsearch
174,581,847
false
null
/* * Copyright 2019 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.indexmanagement.refreshanalyzer import org.elasticsearch.action.ActionType import org.elasticsearch.common.io.stream.Writeable class RefreshSearchAnalyzerAction : ActionType<RefreshSearchAnalyzerResponse>(NAME, reader) { companion object { const val NAME = "indices:admin/refresh_search_analyzers" val INSTANCE = RefreshSearchAnalyzerAction() val reader = Writeable.Reader { inp -> RefreshSearchAnalyzerResponse(inp) } } override fun getResponseReader(): Writeable.Reader<RefreshSearchAnalyzerResponse> = reader }
51
Kotlin
46
117
cda0eda35fc5da3816c407ad7a929d746edaf179
1,190
index-management
Apache License 2.0
app/src/main/java/database/ProjectUserConverter.kt
IdentyMaverick
673,264,323
false
{"Kotlin": 595511}
package database import android.graphics.Bitmap import android.graphics.BitmapFactory import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.asAndroidBitmap import androidx.compose.ui.graphics.asImageBitmap import androidx.room.TypeConverter import java.io.ByteArrayOutputStream class ProjectUserConverter { @TypeConverter fun fromImageBitmap(imageBitmap: ImageBitmap?): ByteArray? { if (imageBitmap == null) return null val stream = ByteArrayOutputStream() val bitmap = imageBitmap.asAndroidBitmap() bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream) return stream.toByteArray() } @TypeConverter fun toImageBitmap(bytes: ByteArray?): ImageBitmap? { if (bytes == null) return null val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) return bitmap.asImageBitmap() } }
6
Kotlin
0
2
b44c30a0f97e202843f0858df7d1d1a7542b6f93
904
ProjectFitness
Apache License 2.0
src/main/kotlin/lab/mars/rl/util/ui/GridWorldUI.kt
wumo
108,533,441
false
null
package lab.mars.rl.util.ui import javafx.application.Application import javafx.application.Platform import javafx.scene.Group import javafx.scene.Scene import javafx.scene.canvas.Canvas import javafx.scene.paint.Color import javafx.stage.Stage import lab.mars.rl.model.impl.mdp.ActionValueFunction import lab.mars.rl.model.impl.mdp.IndexedState import lab.mars.rl.model.impl.mdp.StateValueFunction import java.util.concurrent.CyclicBarrier class GridWorldUI: Application() { lateinit var canvas: Canvas companion object { var after: () -> Unit = {} var render: (ActionValueFunction, IndexedState) -> Unit = { _, _ -> } var width = 450.0 var height = 300.0 var grid_x = 9 var grid_y = 6 } override fun start(ps: Stage?) { val primaryStage = ps!! primaryStage.title = "Drawing Operations Test" val root = Group() canvas = Canvas(width, height) root.children.add(canvas) primaryStage.scene = Scene(root) primaryStage.show() render = this::render after() } val barrier = CyclicBarrier(2) var max = 1.0 var min = 0.0 fun render(V: StateValueFunction, s: IndexedState) { barrier.reset() Platform.runLater { val gc = canvas.graphicsContext2D gc.clearRect(0.0, 0.0, width, height) gc.stroke = Color.BLACK val u_x = width / grid_x val u_y = height / grid_y for ((dim, value) in V.withIndices()) { max = maxOf(max, value) min = minOf(min, value) val nx = dim[0] val ny = dim[1] gc.fill = Color.BLUE.interpolate(Color.RED, if (max == min) 0.5 else (value - min) / (max - min)) val x = u_x * nx val y = u_y * ny gc.fillRect(x, y, u_x, u_y) } gc.fill = Color.GREEN gc.fillRect(s[0] * u_x, s[1] * u_y, u_x, u_y) for ((dim, value) in V.withIndices()) { max = maxOf(max, value) val nx = dim[0] val ny = dim[1] val x = u_x * nx val y = u_y * ny gc.strokeRect(x, y, u_x, u_y) } barrier.await() } barrier.await() } }
1
null
10
33
d419efccdca9a7f34b7805929b41651b172a3ee7
2,092
Reinforcement-Learning-An-Introduction
MIT License
cccev-s2/concept/cccev-concept-api/src/main/kotlin/cccev/s2/concept/api/entity/InformationConceptAutomateConfig.kt
komune-io
746,816,569
false
{"Kotlin": 581952, "TypeScript": 94420, "MDX": 92741, "Gherkin": 21405, "Makefile": 5607, "JavaScript": 2459, "HTML": 1853, "Dockerfile": 1787, "CSS": 605}
package cccev.s2.concept.api.entity import cccev.projection.api.entity.concept.InformationConceptEntity import cccev.projection.api.entity.concept.InformationConceptEvolver import cccev.projection.api.entity.concept.InformationConceptSnapRepository import cccev.s2.concept.domain.InformationConceptEvent import cccev.s2.concept.domain.InformationConceptId import cccev.s2.concept.domain.InformationConceptState import cccev.s2.concept.domain.command.InformationConceptCreatedEvent import cccev.s2.concept.domain.s2InformationConcept import kotlin.reflect.KClass import kotlinx.serialization.json.Json import kotlinx.serialization.modules.SerializersModule import kotlinx.serialization.modules.polymorphic import org.springframework.context.annotation.Configuration import org.springframework.stereotype.Service import s2.spring.automate.sourcing.S2AutomateDeciderSpring import s2.spring.sourcing.ssm.S2SourcingSsmAdapter import ssm.chaincode.dsl.model.Agent import ssm.chaincode.dsl.model.uri.ChaincodeUri import ssm.chaincode.dsl.model.uri.from import ssm.sdk.sign.extention.loadFromFile @Configuration class InformationConceptAutomateConfig( automateExecutor: InformationConceptAutomateExecutor, informationConceptEvolver: InformationConceptEvolver, informationConceptSnapRepository: InformationConceptSnapRepository, ): S2SourcingSsmAdapter< InformationConceptEntity, InformationConceptState, InformationConceptEvent, InformationConceptId, InformationConceptAutomateExecutor >(automateExecutor, informationConceptEvolver, informationConceptSnapRepository) { override fun automate() = s2InformationConcept override fun entityType(): KClass<InformationConceptEvent> { return InformationConceptEvent::class } override var permisive: Boolean = true override fun json(): Json = Json { serializersModule = SerializersModule { classDiscriminator = "class" polymorphic(InformationConceptEvent::class) { subclass(InformationConceptCreatedEvent::class, InformationConceptCreatedEvent.serializer()) } } } override fun chaincodeUri(): ChaincodeUri { return ChaincodeUri.from( channelId = "sandbox", chaincodeId = "ssm", ) } override fun signerAgent(): Agent { return Agent.loadFromFile("ssm-admin","user/ssm-admin") } override fun preventOptimisticLocking(): Boolean = true } @Service class InformationConceptAutomateExecutor : S2AutomateDeciderSpring< InformationConceptEntity, InformationConceptState, InformationConceptEvent, InformationConceptId>()
0
Kotlin
0
0
8514b98e1d2b55f4611e664116526db3c8ad209f
2,517
connect-cccev
Apache License 2.0
app/src/main/java/pl/polsl/student/michaldomino/voice_command_controlled_application/logic/command_states/shared/SaveChangesCS.kt
michaldomino
190,876,845
false
{"Kotlin": 91815}
package pl.polsl.student.michaldomino.voice_command_controlled_application.logic.command_states.shared import pl.polsl.student.michaldomino.voice_command_controlled_application.R import pl.polsl.student.michaldomino.voice_command_controlled_application.logic.command_states.base.CSLeaf import pl.polsl.student.michaldomino.voice_command_controlled_application.ui.base.NotePresenter class SaveChangesCS(override val presenter: NotePresenter) : CSLeaf(presenter) { override val commandNameId: Int? = R.string.save_changes override fun initialize() { presenter.saveChanges() } }
0
Kotlin
0
0
ad114fd7594abcc29aff2374be226d3573352f70
599
Voice-command-controlled-application
MIT License
core/kotlinx-coroutines-io/src/main/kotlin/kotlinx/coroutines/experimental/io/packet/ByteWritePacketImpl.kt
sahlone
141,607,927
true
{"Kotlin": 1836603, "CSS": 8706, "JavaScript": 3487, "Ruby": 1927, "HTML": 1675, "Shell": 1308, "Java": 245}
package kotlinx.coroutines.experimental.io.packet import kotlinx.io.core.* internal typealias ByteWritePacket = BytePacketBuilder internal typealias ByteWritePacketImpl = BytePacketBuilder
0
Kotlin
0
1
dae510bba39181b93978f7878c033a50dccad62b
191
kotlinx.coroutines
Apache License 2.0
core/kotlinx-coroutines-io/src/main/kotlin/kotlinx/coroutines/experimental/io/packet/ByteWritePacketImpl.kt
sahlone
141,607,927
true
{"Kotlin": 1836603, "CSS": 8706, "JavaScript": 3487, "Ruby": 1927, "HTML": 1675, "Shell": 1308, "Java": 245}
package kotlinx.coroutines.experimental.io.packet import kotlinx.io.core.* internal typealias ByteWritePacket = BytePacketBuilder internal typealias ByteWritePacketImpl = BytePacketBuilder
0
Kotlin
0
1
dae510bba39181b93978f7878c033a50dccad62b
191
kotlinx.coroutines
Apache License 2.0
src/main/kotlin/shou/common/web/element/iggrid/ElementAction.kt
NSVN-NguyenDuyThang
661,492,559
false
null
package shou.common.web.element.iggrid import com.microsoft.playwright.Locator interface ElementAction { fun click() fun doubleClick() fun fill(locator: Locator, key: String) }
0
Kotlin
0
0
b375d9d2ebb4981209025e6052a3080324042e33
190
playwright-kotlin
MIT License
kotlin-electron/src/jsMain/generated/electron/PowerMonitor.kt
JetBrains
93,250,841
false
{"Kotlin": 12159121, "JavaScript": 330528}
// Generated by Karakum - do not modify it manually! package electron typealias PowerMonitor = electron.core.PowerMonitor
40
Kotlin
165
1,319
a8a1947d73e3ed26426f1e27b641bff427dfd6a0
126
kotlin-wrappers
Apache License 2.0
src/main/kotlin/marcombo/lcriadof/capitulo4/c4p1.kt
Marcombo
457,085,459
false
{"Kotlin": 233517, "HTML": 27291, "CSS": 7504}
/* El gran libro de Kotlin (para programadores de back end) Editorial: Marcombo (https://www.marcombo.com/) Autor: <NAME> (http://luis.criado.online/) CAPÍTULO 4: POCO CÓDIGO Y GRANDES RESULTADOS */ package marcombo.lcriadof.capitulo4 fun main() { println("¡Hola Mundo!"); // [1] }
0
Kotlin
3
6
e9ac80401dee92f5cdd2dafcb6ce470532470d4b
293
El-gran-libro-de-Kotlin
MIT License
app/src/main/java/com/example/android/pokedex/api/NetworkUtils.kt
quochuyhl99
704,825,857
false
{"Kotlin": 46836}
package com.example.android.pokedex.api import com.example.android.pokedex.model.Pokemon import org.json.JSONObject fun parsePokemonJsonResult(jsonResult: JSONObject): Pokemon { val id = jsonResult.getLong("id") val baseExperience = jsonResult.getInt("base_experience") val height = jsonResult.getInt("height") val name = jsonResult.getString("name") val weight = jsonResult.getInt("weight") val frontDefault = jsonResult.getJSONObject("sprites").getJSONObject("other").getJSONObject("official-artwork") .getString("front_default") val frontShiny = jsonResult.getJSONObject("sprites").getJSONObject("other").getJSONObject("official-artwork") .getString("front_shiny") val statsJsonArray = jsonResult.getJSONArray("stats") val hp = statsJsonArray.getJSONObject(0).getInt("base_stat") val attack = statsJsonArray.getJSONObject(1).getInt("base_stat") val defense = statsJsonArray.getJSONObject(2).getInt("base_stat") val specialAttack = statsJsonArray.getJSONObject(3).getInt("base_stat") val specialDefence = statsJsonArray.getJSONObject(4).getInt("base_stat") val speed = statsJsonArray.getJSONObject(5).getInt("base_stat") val typesJsonArray = jsonResult.getJSONArray("types") val types = mutableListOf<String>() for (i in 0 until typesJsonArray.length()) { val typeJson = typesJsonArray.getJSONObject(i) val typeDetailsJson = typeJson.getJSONObject("type") val typeName = typeDetailsJson.getString("name") types.add(typeName) } return Pokemon( id, baseExperience, height, name, weight, frontDefault, frontShiny, hp, attack, defense, specialAttack, specialDefence, speed, types ) }
0
Kotlin
0
0
baf077a0338be6e5ca0501979e51a0cf15eccf27
1,825
Pokedex
Apache License 2.0
src/main/java/graphene/rpc/SocketException.kt
abitmore
479,743,257
false
{"Kotlin": 447335, "Java": 97085}
package graphene.rpc import io.ktor.utils.io.errors.* sealed class SocketException : IOException() class SocketManualStopException : SocketException() class SocketClosedException : SocketException() class SocketErrorException(override val message: String) : SocketException() { constructor(error: SocketError): this(error.error.toString()) }
0
Kotlin
0
0
ddd17eb771eea649e681667b6d85e4f292e9e839
347
bitshares-kit
MIT License
PettCareAndroidApp/app/src/main/java/com/pettcare/app/profile/presentation/ProfileScreen.kt
antelukic
767,127,442
false
{"Kotlin": 305258}
package com.pettcare.app.profile.presentation import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.border import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.outlined.Logout import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.pettcare.app.R import com.pettcare.app.socialwall.presentation.SocialWallScreen import com.pettcare.app.socialwall.presentation.SocialWallUIState import com.pettcare.app.uicomponents.UserProfilePhoto import org.koin.androidx.compose.koinViewModel import org.koin.core.parameter.parametersOf @Composable fun ProfileScreen( id: String, modifier: Modifier = Modifier, ) { val viewModel = koinViewModel<ProfileViewModel>(parameters = { parametersOf(id) }) val uiState = viewModel.uiState.collectAsStateWithLifecycle().value ProfileScreen( uiState = uiState, onPostComment = viewModel::postComment, onLikePost = viewModel::likePost, onShowComments = viewModel::showComments, onDismissComments = viewModel::dismissComments, onCommentTextChanged = viewModel::updateComment, loadMore = viewModel::nextPage, onSignOut = viewModel::signOut, modifier = modifier.padding(dimensionResource(id = R.dimen.spacing_4)), ) } @Composable private fun ProfileScreen( uiState: ProfileUiState, onPostComment: () -> Unit, onLikePost: (String) -> Unit, onShowComments: (String) -> Unit, onDismissComments: () -> Unit, onCommentTextChanged: (String) -> Unit, loadMore: () -> Unit, onSignOut: () -> Unit, modifier: Modifier = Modifier, ) { Box(modifier = Modifier.fillMaxSize()) { AnimatedVisibility( visible = uiState.showLogout, modifier = Modifier .padding(dimensionResource(id = R.dimen.spacing_2)) .align(Alignment.TopEnd), ) { IconButton( onClick = onSignOut, ) { Icon(imageVector = Icons.AutoMirrored.Outlined.Logout, contentDescription = null) } } Column(modifier = modifier) { ProfileAvatar( name = uiState.name, photoUrl = uiState.photoUrl, modifier = Modifier.fillMaxWidth(), ) HorizontalDivider( thickness = dimensionResource(id = R.dimen.divider_thickness), color = MaterialTheme.colorScheme.onBackground, ) Spacer(modifier = Modifier.height(dimensionResource(id = R.dimen.spacing_2))) ProfileInformation(email = uiState.email, gender = uiState.gender, dateOfBirth = uiState.dateOfBirth) Spacer(modifier = Modifier.height(dimensionResource(id = R.dimen.spacing_2))) HorizontalDivider( thickness = dimensionResource(id = R.dimen.divider_thickness), color = MaterialTheme.colorScheme.onBackground, ) Spacer(modifier = Modifier.height(dimensionResource(id = R.dimen.spacing_2))) SocialWallScreen( uiState = SocialWallUIState(uiState.posts, uiState.comments, uiState.comment), onDismiss = onDismissComments, onProfileClick = {}, onLikeClick = onLikePost, onCommentsClick = onShowComments, onUpdateComment = onCommentTextChanged, onPostComment = onPostComment, loadMore = loadMore, title = stringResource(id = R.string.social_wall_title_profile), ) } } } @Composable private fun ProfileAvatar( name: String, photoUrl: String?, modifier: Modifier = Modifier, ) { Column( modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally, ) { UserProfilePhoto( photoUrl = photoUrl, size = dimensionResource(id = R.dimen.avatar_size_large), ) Spacer(modifier = Modifier.height(dimensionResource(id = R.dimen.spacing_2))) Text( text = name, style = MaterialTheme.typography.titleLarge, color = MaterialTheme.colorScheme.primary, ) } } @OptIn(ExperimentalLayoutApi::class) @Composable private fun ProfileInformation( email: String, gender: String, dateOfBirth: String, modifier: Modifier = Modifier, ) { val itemModifier = Modifier .padding(dimensionResource(id = R.dimen.spacing_1)) .border( width = dimensionResource(id = R.dimen.care_post_border_stroke_width), color = MaterialTheme.colorScheme.secondary, shape = CircleShape, ) .padding(dimensionResource(id = R.dimen.spacing_2)) FlowRow(modifier = modifier) { Text( text = email, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.secondary, modifier = itemModifier, ) Text( text = gender, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.secondary, modifier = itemModifier, ) Text( text = dateOfBirth, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.secondary, modifier = itemModifier, ) } }
0
Kotlin
0
0
ac51e9ad846a35479567cb77aa393d8e10fd7443
6,445
PettCareApp
Apache License 2.0
time/src/test/kotlin/xyz/tynn/hoppa/time/MonthTest.kt
tynn-xyz
280,739,124
false
null
// Copyright 2021 <NAME> // SPDX-License-Identifier: Apache-2.0 package xyz.tynn.hoppa.time import java.time.Month import kotlin.test.Test import kotlin.test.assertEquals import org.threeten.bp.Month as MonthBp internal class MonthTest { @Test fun `toJavaTime should convert MonthBp to Month`() { assertEquals( Month.of(4), MonthBp.of(4) .toJavaTime() ) } @Test fun `toThreeTenBp should convert Month to MonthBp`() { assertEquals( MonthBp.of(7), Month.of(7) .toThreeTenBp() ) } }
0
Kotlin
0
4
632bcb0748c30d6a459a0e777f62bfc6f8f8e4f8
623
Hoppa
Apache License 2.0
app/src/main/kotlin/com/g00fy2/developerwidget/activities/shortcut/ShortcutDiffUtilsCallback.kt
forbes30
226,480,456
true
{"Kotlin": 138842}
package com.g00fy2.developerwidget.activities.shortcut import android.content.pm.ShortcutInfo import androidx.recyclerview.widget.DiffUtil class ShortcutDiffUtilsCallback : DiffUtil.ItemCallback<ShortcutInfo>() { override fun areItemsTheSame(oldItem: ShortcutInfo, newItem: ShortcutInfo) = false override fun areContentsTheSame(oldItem: ShortcutInfo, newItem: ShortcutInfo) = false }
0
null
0
0
8c61f418dd539d7a2d96ea89193b6fb05438551a
390
DeveloperWidget
MIT License
src/main/java/eu/glatz/imagej/model/Square.kt
glatzan
248,865,728
false
null
package eu.glatz.imagej.model class Square(var start: Point, var width: Int, var heigth: Int)
0
Kotlin
0
1
f05084ae3b6f2d78922f4c8c349eaef24cf2529d
94
ImageJ-Heatmap-Creator
The Unlicense
app/src/main/java/com/example/mywechat/ui/fragment/MsgFragment.kt
HenryLEB
325,024,821
false
null
package com.example.viewpagertest import android.content.Context import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import com.example.mywechat.adapter.SessionAdapter import com.example.mywechat.model.Session import com.example.secondexperiment.R import com.example.secondexperiment.model.MSGDataBaseHelper import kotlinx.android.synthetic.main.item_session.* import kotlinx.android.synthetic.main.msg_page.* import kotlin.random.Random class MsgFragment : Fragment() { private val sessionList = ArrayList<Session>() private lateinit var msgHelper: MSGDataBaseHelper private val sessionHeadPortraitList = listOf<Int>(R.drawable.jfm, R.drawable.bianmu, R.drawable.hashiqi, R.drawable.jfm, R.drawable.taidi, R.drawable.samoye, R.drawable.kj) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { msgHelper = MSGDataBaseHelper(activity as Context, "chatDatabase", 2) return inflater.inflate(R.layout.msg_page, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initSessions() Log.d("aaaa",sessionList.size.toString()) val layoutManager = LinearLayoutManager(activity as Context) recycleList_session.layoutManager = layoutManager val adapter = SessionAdapter(sessionList) recycleList_session.adapter = adapter Log.d("bbbbb",layoutManager.toString()) } private fun initSessions() { // Log.d("aaaa","shda") val db = msgHelper.readableDatabase val cursor = db.rawQuery("select * from message where sender='哈士奇' group by recipient " + "union all " + "select * from message where recipient='哈士奇' group by sender", null) if (cursor.moveToFirst()) { while (cursor.moveToNext()) { val latestMsg = cursor.getString(cursor.getColumnIndex("content")) val sessionName = cursor.getString(cursor.getColumnIndex("recipient")) val sendTime = cursor.getString(cursor.getColumnIndex("send_time")) sessionList.add(Session(sessionHeadPortraitList[(0..6).random()], sessionName, latestMsg, sendTime)) } } // sessionList.add(Session(R.drawable.jfm, "喵星人", "在吗", "11:10")) // sessionList.add(Session(R.drawable.kj, "小柯基", "在吗", "11:10")) // sessionList.add(Session(R.drawable.jm, "哈哈哈", "在吗", "11:10")) // sessionList.add(Session(R.drawable.hashiqi, "哈士奇", "在吗", "11:10")) // sessionList.add(Session(R.drawable.bianmu, "边牧犬", "在吗", "11:10")) // sessionList.add(Session(R.drawable.taidi, "小泰迪", "在吗", "11:10")) // sessionList.add(Session(R.drawable.samoye, "萨摩耶", "在吗", "11:10")) // sessionList.add(Session(R.drawable.jsx, "小仓鼠", "在吗", "11:10")) // sessionList.add(Session(R.drawable.lggcs, "嘿嘿嘿", "在吗", "11:10")) // sessionList.add(Session(R.drawable.yd, "小祖宗", "在吗", "11:10")) } }
0
Kotlin
0
0
7a6d235fc21c47a551e14f9a880c2f9b24cabb6a
3,273
MyWechat
Apache License 2.0
src/test/kotlin/net/spark/coadjutor/cred/GradlePropertiesCredentialProviderTest.kt
Spark-Networks
515,031,142
false
null
package net.spark.coadjutor.cred import net.spark.coadjutor.cred.GradlePropertiesCredentialProvider.commonMasterPassword import net.spark.coadjutor.cred.GradlePropertiesCredentialProvider.getCredentials import org.assertj.core.api.Assertions.assertThat import org.gradle.api.Project import org.gradle.api.Project.GRADLE_PROPERTIES import org.gradle.api.invocation.Gradle import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir import org.mockito.Mock import org.mockito.MockitoAnnotations.openMocks import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import java.io.File class GradlePropertiesCredentialProviderTest { private val username = "admin" private val plainTextPassword = "<PASSWORD>" private val source = "gradle.properties" private val masterPassword = <PASSWORD> private val encryptedUserPassword = <PASSWORD>}" @Mock private lateinit var project: Project @Mock private lateinit var gradle: Gradle private lateinit var gradlePropFile: File @BeforeEach internal fun setUp(@TempDir tmpdir: File) { openMocks(this) whenever(project.gradle).thenReturn(gradle) whenever(project.logger).thenReturn(mock()) val gradleUserHome = tmpdir.resolve("userHome/.gradle") gradleUserHome.mkdirs() gradlePropFile = gradleUserHome.resolve(GRADLE_PROPERTIES) whenever(gradle.gradleUserHomeDir).thenReturn(gradleUserHome) } @Test fun `should return empty when gradle properties are not configured for the given repo name`() { val repoName = "affinitas" withGradleProperties("") val gotCredentials = getCredentials(project, repoName) assertThat(gotCredentials).isNotNull assertThat(gotCredentials).isEmpty } @Test fun `should return credential as it is when there is no master password configured`() { val repoName = "affinitas" withGradleProperties( """ ${repoName}Username=$username ${repoName}Password=$<PASSWORD> """ ) val gotCredentials = getCredentials(project, repoName) assertThat(gotCredentials).isNotNull assertThat(gotCredentials.get()).isEqualTo( MavenPasswordCredentials( username, plainTextPassword, source ) ) } @Test fun `should return decrypted creds using repo specific password`() { val repoName = "affinitas" withGradleProperties( """ ${repoName}Username=$username ${repoName}Password=$<PASSWORD> ${repoName}MasterPassword=$<PASSWORD> """ ) val gotCredentials = getCredentials(project, repoName) assertThat(gotCredentials).isNotNull assertThat(gotCredentials.get()).isEqualTo( MavenPasswordCredentials( username, plainTextPassword, source ) ) } @Test fun `should return decrypted creds using common password`() { val repoName = "affinitas" withGradleProperties( """ ${repoName}Username=$username ${repoName}Password=$<PASSWORD> $commonMasterPassword=$<PASSWORD> """ ) val gotCredentials = getCredentials(project, repoName) assertThat(gotCredentials).isNotNull assertThat(gotCredentials.get()).isEqualTo( MavenPasswordCredentials( username, plainTextPassword, source ) ) } @Test fun `should return credential for gradle generated repo names`() { val repoNameInGradleProperties = "affinitas" val generatedRepoNameByGradle = "affinitas1" withGradleProperties( """ ${repoNameInGradleProperties}Username=$username ${repoNameInGradleProperties}Password=$<PASSWORD> ${repoNameInGradleProperties}MasterPassword=$<PASSWORD> """ ) val gotCredentials = getCredentials(project, generatedRepoNameByGradle) assertThat(gotCredentials).isNotNull assertThat(gotCredentials.get()).isEqualTo( MavenPasswordCredentials( username, plainTextPassword, source ) ) } private fun withGradleProperties(content: String) { gradlePropFile.writeText(content.trimIndent().trim()) } }
0
Kotlin
0
0
fb26d850b0642679d70534cf92f5eb5d7f457b1d
4,614
coadjutor
Apache License 2.0
core/src/main/java/com/dicoding/core/domain/model/TvShow.kt
zakuby
331,148,528
false
null
package com.dicoding.core.domain.model data class Detail( val id: Int, val title: String?, val date: String?, val description: String?, val rate: String?, val posterImage: String?, val backgroundImage: String?, val isFavorite: Boolean = false, val genres: List<Genre>? = emptyList() )
0
Kotlin
0
0
78aed112a3356a9854a8b6fc1708a5f05ebb7a71
322
capstone-moviedb
Apache License 2.0
WebAPI/src/main/kotlin/dev/fstudio/mcworldstats/Build.kt
Kamillaova
463,396,605
false
{"Kotlin": 78372}
package dev.fstudio.mcworldstats object Build { const val VERSION = 1.0 }
0
Kotlin
0
1
a935ae2b1831949a347c954c70c3df6628d3dde5
78
Ellison
MIT License
src/main/kotlin/org/beckn/one/sandbox/bap/message/entities/OfferDao.kt
OSSVerse
853,138,400
false
{"Kotlin": 651081, "Jinja": 3324}
package org.beckn.one.sandbox.bap.message.entities import org.beckn.protocol.schemas.Default data class OfferDao @Default constructor( val id: String? = null, val descriptor: DescriptorDao? = null, val locationIds: List<String>? = null, val categoryIds: List<String>? = null, val itemIds: List<String>? = null, val time: TimeDao? = null )
0
Kotlin
0
8
b3ca6a6455f41b9d53bbb35f5c01e31c1fde2638
353
OSSVerse-buyer-app
Apache License 2.0
app/src/main/java/com/example/animeapp/ui/searchview/uistate/SearchUiState.kt
AdonayMejia
650,392,241
false
null
package com.example.animeapp.ui.searchview.uistate import com.example.domain.search.model.AnimeModel import com.example.domain.search.model.AnimeSort import com.example.domain.search.model.AnimeType data class SearchUiState( val addToFavorites: (AnimeModel) -> Unit = {}, val favoriteAnime: Set<Int> = emptySet(), val onTypeChanged: (AnimeType) -> Unit = {}, val onSortChanged: (AnimeSort) -> Unit = {}, val onSearchChanged: (String) -> Unit = {} )
0
Kotlin
0
0
c503837db31d61ed6dc1d516847e1604732c1b02
471
Compose_AnimeApp
MIT License
either-core/src/commonMain/kotlin/tz/co/asoft/Either.ktx.kt
aSoft-Ltd
319,525,074
false
null
package tz.co.asoft inline val <L, R> Either<L, R>.value get() = when (this) { is Either.Left -> value is Either.Right -> value } fun <L> Either<L, *>.left(): L = when (this) { is Either.Left -> value is Either.Right -> throw Exception("Can't get left side of either coz it is right side") } fun <L> Either<L, *>.leftOrNull(): L? = try { left() } catch (_: Throwable) { null } fun <R> Either<*, R>.right(): R = when (this) { is Either.Left -> throw Exception("Can't get right side of either coz it is left side") is Either.Right -> value } fun <R> Either<*, R>.rightOrNull(): R? = try { right() } catch (_: Throwable) { null } inline fun <reified L, reified R, A> A.asEither(): Either<L, R> = when (this) { is L -> Either.Left(this) is R -> Either.Right(this) else -> throw RuntimeException("$this is neither ${L::class.simpleName} nor ${R::class.simpleName}") } inline fun <reified L, reified R, A> A.asEitherOrNull(): Either<L, R>? = try { asEither() } catch (_: Throwable) { null }
0
Kotlin
1
1
5d75719518b347e0d65a252607d6a608f3bb2fbc
1,068
either
MIT License
core/src/main/kotlin/io/uvera/helmet/core/validation/DirectivesNotEmptyWhenUseDefaultIsFalse.kt
uvera
418,525,642
false
null
package io.uvera.helmet.core.validation import io.uvera.helmet.core.HelmetProperties import javax.validation.Constraint import javax.validation.ConstraintValidator import javax.validation.ConstraintValidatorContext import kotlin.reflect.KClass @Target(AnnotationTarget.CLASS) @MustBeDocumented @Retention(AnnotationRetention.RUNTIME) @Constraint(validatedBy = [DirectivesNotEmptyWhenUseDefaultIsFalseValidator::class]) annotation class DirectivesNotEmptyWhenUseDefaultIsFalse( val message: String = "Directives cannot be empty when use defaults is false", val groups: Array<KClass<out Any>> = [], val payload: Array<KClass<out Any>> = [], ) class DirectivesNotEmptyWhenUseDefaultIsFalseValidator : ConstraintValidator<DirectivesNotEmptyWhenUseDefaultIsFalse, HelmetProperties> { override fun isValid(value: HelmetProperties?, context: ConstraintValidatorContext?): Boolean { if (value == null) return true if (!value.contentSecurityPolicy.useDefault && value.contentSecurityPolicy.directives.isEmpty()) { return false } return true } }
0
Kotlin
0
1
2a879ad1d62a5e67b3c1fb47e28b7b624c3de63b
1,107
helmet-spring-boot-starter
MIT License
src/main/java/com/icoder0/groom/ui/GroomToolWindowPanel.kt
ICoder0
335,169,108
false
{"Kotlin": 127433, "Java": 987}
package com.icoder0.groom.ui import com.icoder0.groom.component.EditorManager import com.intellij.openapi.Disposable import com.intellij.openapi.project.Project import com.intellij.openapi.ui.SimpleToolWindowPanel import com.intellij.openapi.wm.ex.ToolWindowEx /** * @author bofa1ex * @since 2021/4/17 */ @SuppressWarnings("LeakingThisInConstructor") abstract class GroomToolWindowPanel(val project: Project, val toolWindow: ToolWindowEx) : SimpleToolWindowPanel(true), Disposable { init { EditorManager.initPanel(project, this) } override fun dispose() { removeAll() removeNotify() } abstract fun initUI(): GroomToolWindowPanel }
0
Kotlin
0
3
7d3b43eaea2b80178d81f8f501a106cc55f7076b
683
groom
MIT License
next/kmp/window/src/commonMain/kotlin/org/dweb_browser/sys/window/render/WindowsManagerRender.kt
BioforestChain
594,577,896
false
{"Kotlin": 3446191, "TypeScript": 818538, "Swift": 369625, "Vue": 156647, "SCSS": 39016, "Objective-C": 17350, "HTML": 16184, "Shell": 13534, "JavaScript": 3982, "Svelte": 3504, "CSS": 818}
package org.dweb_browser.sys.window.render import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import org.dweb_browser.sys.window.core.WindowController import org.dweb_browser.sys.window.core.WindowsManager @Composable expect fun <T : WindowController> WindowsManager<T>.SceneRender(modifier: Modifier = Modifier)
66
Kotlin
5
20
6db1137257e38400c87279f4ccf46511752cd45a
343
dweb_browser
MIT License
data/src/main/java/kr/genti/data/dataSourceImpl/InfoDataSourceImpl.kt
Genti2024
793,968,607
false
{"Kotlin": 277321}
package kr.genti.data.dataSourceImpl import kr.genti.data.dataSource.InfoDataSource import kr.genti.data.dto.BaseResponse import kr.genti.data.dto.request.SignupRequestDto import kr.genti.data.dto.response.SignUpUserDto import kr.genti.data.service.InfoService import javax.inject.Inject data class InfoDataSourceImpl @Inject constructor( private val infoService: InfoService, ) : InfoDataSource { override suspend fun postSignupData(request: SignupRequestDto): BaseResponse<SignUpUserDto> = infoService.postSignupData(request) override suspend fun postUserLogout(): BaseResponse<Boolean> = infoService.postUserLogout() override suspend fun deleteUser(): BaseResponse<Boolean> = infoService.deleteUser() }
1
Kotlin
1
7
7ae863faa8a1ec7bc5876b56dc3387a44b6f5b14
758
Genti-Android
MIT License
src/test/kotlin/com/theo/plugins/openapi/OpenApiPluginAcceptanceTest.kt
theochiu2010
521,088,018
false
{"Kotlin": 14544}
package com.theo.plugins.openapi import org.assertj.core.api.Assertions.assertThat import org.gradle.testkit.runner.GradleRunner import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import org.junit.runner.RunWith import org.mockito.Mockito.* import org.powermock.api.mockito.PowerMockito import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner import java.io.File @RunWith(PowerMockRunner::class) @PrepareForTest(Runtime::class) class OpenApiPluginAcceptanceTest { @Rule var testProjectDir = TemporaryFolder() private lateinit var buildFile: File private lateinit var gradleRunner: GradleRunner private var mockRuntime: Runtime = mock(Runtime::class.java) private var mockProcess: Process = mock(Process::class.java) @Before fun setup() { buildFile = testProjectDir.newFile("build.gradle.kts") buildFile.appendText(""" plugins { id("com.theo.openApiPlugin") id("org.openapi.generator") version "5.1.1" id("de.undercouch.download") version "5.1.0" } """.trimIndent()) gradleRunner = GradleRunner.create() .withPluginClasspath() .withProjectDir(testProjectDir.root) .withTestKitDir(testProjectDir.newFolder()) } @Test fun `can execute generateContract`() { PowerMockito.mockStatic(Runtime::class.java) `when`(Runtime.getRuntime()).thenReturn(mockRuntime) `when`(mockRuntime.exec(any<String>())).thenReturn(mockProcess) `when`(mockProcess.isAlive).thenReturn(false) val result = gradleRunner .withArguments("generateContract") .build() assertThat(result.task(":generateContract")!!.outcome.name).isEqualTo("SUCCESS") } @Test fun `can execute downloadContract`() { PowerMockito.mockStatic(Runtime::class.java) `when`(Runtime.getRuntime()).thenReturn(mockRuntime) `when`(mockRuntime.exec(any<String>())).thenReturn(mockProcess) `when`(mockProcess.isAlive).thenReturn(false) buildFile.appendText(""" configure<com.theo.plugins.openapi.OpenApiPluginExtension> { producers.set(listOf( "planet:planetAPI:1.0.0", "inventory:inventoryAPI:1.0.0" )) consumers.set(listOf( "nrs:nrsAPI:1.0.0", "pet:petAPI:1.0.0" )) } """.trimIndent()) val result = gradleRunner .withArguments("downloadContract") .build() assertThat(result.task(":downloadContract")!!.outcome.name).isEqualTo("SUCCESS") } }
0
Kotlin
0
0
200375063b86c201a2e08a7b7ede4a5228b6f600
2,846
OpenApiGradlePlugin
MIT License
core/src/main/java/org/openedx/core/data/model/Certificate.kt
openedx
613,282,821
false
{"Kotlin": 1313883}
package org.openedx.core.data.model import com.google.gson.annotations.SerializedName import org.openedx.core.data.model.room.discovery.CertificateDb import org.openedx.core.domain.model.Certificate data class Certificate( @SerializedName("url") val certificateURL: String? ) { fun mapToDomain(): Certificate { return Certificate( certificateURL = certificateURL ) } fun mapToRoomEntity() = CertificateDb(certificateURL) }
68
Kotlin
12
9
c736918608a5781f95d056f3494628c7e0bf7f19
473
openedx-app-android
Apache License 2.0
src/org/lukasj/idea/torquescript/completion/TSCaseCorrectingInsertHandler.kt
lukaspj
385,020,179
false
null
package org.lukasj.idea.torquescript.completion import com.intellij.codeInsight.completion.InsertHandler import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.lookup.LookupElement import com.intellij.openapi.editor.EditorModificationUtil class TSCaseCorrectingInsertHandler : InsertHandler<LookupElement> { override fun handleInsert(context: InsertionContext, item: LookupElement) { val elementBeingEdited = context.file.findElementAt(context.startOffset) if (elementBeingEdited != null) { // Remove the current element context.editor.document.deleteString(elementBeingEdited.textOffset, context.editor.caretModel.currentCaret.offset) // Insert the new element with proper casing EditorModificationUtil.insertStringAtCaret(context.editor, item.lookupString, true) } } companion object { val INSTANCE = TSCaseCorrectingInsertHandler() } }
3
Kotlin
0
1
8d84ad40a10f2d3994572ff9161cb400fbdeeaad
974
IDEA-TorqueScriptLanguage
MIT License
app/src/main/java/id/teman/app/mitra/domain/model/transport/TransportRequestType.kt
RifqiFadhell
681,463,824
false
null
package id.teman.app.mitra.domain.model.transport //requesting = customer pesan //accepted = mitra menyetujui //rejected = mitra menolak //onroute = mitra sudah menjemput customer dan mulai menuju ke lokasi //finished = ketika sudah sampai tujuan enum class TransportRequestType(val value: String) { REQUESTING("requesting"), ACCEPTED("accepted"), REJECTED("rejected"), ONROUTE("onroute"), ARRIVED("arrived"), FINISHED("finished"); companion object { fun from(value: String?) = when(value) { REQUESTING.value -> REQUESTING ACCEPTED.value -> ACCEPTED REJECTED.value -> REJECTED ONROUTE.value -> ONROUTE else -> FINISHED } } } fun TransportRequestType.nextLevel(): TransportRequestType = when (this) { TransportRequestType.REQUESTING -> TransportRequestType.ACCEPTED TransportRequestType.ACCEPTED -> TransportRequestType.ONROUTE else -> TransportRequestType.ARRIVED }
0
Kotlin
0
0
61a520bd14c97efcef108b0576760108f3f4a687
988
Teman-App-Mitra-Mobile
Apache License 2.0
example/src/main/java/com/skymavis/sdk/example/ExampleActivity.kt
skymavis
807,405,653
false
{"Kotlin": 13147}
package com.skymavis.sdk.example import android.content.Context import android.net.Uri import android.os.Bundle import android.os.Debug import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.skymavis.sdk.example.ui.theme.SkymavisandroidsdkTheme import com.skymavis.sdk.id.Client import com.skymavis.sdk.id.Result lateinit var client: Client; lateinit var redirectUri: String; class ExampleActivity : ComponentActivity() { var state = "" override fun onCreate(savedInstanceState: Bundle?) { val data: Uri? = intent?.data // Capture the URI data redirectUri = "axie://open" val clientId = "axie" val gateOrigin = "http://id.skymavis.com" val chainId = 2021; val rpcUrl = "https://saigon-testnet.roninchain.com/rpc" client = Client( gateOrigin, clientId, rpcUrl, chainId ); super.onCreate(savedInstanceState) setContent { SkymavisandroidsdkTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Column( modifier = Modifier .fillMaxSize() .padding(96.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { Spacer(modifier = Modifier.height(16.dp)) AuthButton(context = this@ExampleActivity) { newState -> state = newState } Spacer(modifier = Modifier.height(16.dp)) PersonalSignButton(context = this@ExampleActivity) { newState -> state = newState } Spacer(modifier = Modifier.height(16.dp)) SignTypedDataButton(context = this@ExampleActivity) { newState -> state = newState } Spacer(modifier = Modifier.height(16.dp)) SendTransactionButton(context = this@ExampleActivity) { newState -> state = newState } Spacer(modifier = Modifier.height(16.dp)) CallContractButton(context = this@ExampleActivity) { newState -> state = newState } ShowDialogResult(uri = data, state = state) } } } } } override fun onDestroy() { super.onDestroy() } } @Composable fun ShowDialogResult(uri: Uri?, state: String) { var showDialog by remember { mutableStateOf(true) } uri?.let { var result = Result.from(uri) println("Is success: ${result.isSuccess}") println("Method: ${result.method}") println("Address: ${result.address}") println("Data: ${result.data}") println("State: ${result.state}") if (result.state == state) { showDialog = true } if (showDialog) { AlertDialog( onDismissRequest = { showDialog = false }, title = { Text("Result") }, text = { Column { Text("Is success: ${result.isSuccess}") Text("Method: ${result.method}") Text("Address: ${result.address}") Text("Data: ${result.data}") Text("State: ${result.state}") } }, confirmButton = { Button(onClick = { showDialog = false }) { Text("OK") } } ) } } } @Composable fun AuthButton( context: Context, onStateChange : (String) -> Unit) { Button( onClick = { val state = client.authorize(context, redirectUri) // Example function call onStateChange(state) }, modifier = Modifier.fillMaxWidth() ) { Text("Authorize") } } @Composable fun CallContractButton( context: Context, onStateChange : (String) -> Unit) { Button( onClick = { val contractAddress = "0x3c4e17b9056272ce1b49f6900d8cfd6171a1869d"; // No RON is being sent val value = "0x0" // Approve data val data = "0x095ea7b30000000000000000000000006b190089ed7f75fe17b3b0a17f6ebd69f72c3f630000000000000000000000000000000000000000000000000de0b6b3a7640000"; val state = client.callContract( context, redirectUri, contractAddress, data, value ) onStateChange(state) }, modifier = Modifier.fillMaxWidth() ) { Text("Call contract") } } @Composable fun SendTransactionButton(context: Context, onStateChange : (String) -> Unit ) { Button(onClick = { val to = "0xD36deD8E1927dCDD76Bfe0CC95a5C1D65c0a807a"; val value = "100000000000000000"; val state = client.sendTransaction(context, redirectUri, to, value); onStateChange(state) }, modifier = Modifier.fillMaxWidth() ) { Text("Send Transaction") } } @Composable fun PersonalSignButton(context: Context, onStateChange : (String) -> Unit) { Button( onClick = { val message = "Hello Axie"; val state = client.personalSign(context, redirectUri, message) onStateChange(state) }, modifier = Modifier.fillMaxWidth() ) { Text("Personal Sign") } } @Composable fun SignTypedDataButton(context: Context, onStateChange : (String) -> Unit) { Button(onClick = { val typedData = """{"types":{"Asset":[{"name":"erc","type":"uint8"},{"name":"addr","type":"address"},{"name":"id","type":"uint256"},{"name":"quantity","type":"uint256"}],"Order":[{"name":"maker","type":"address"},{"name":"kind","type":"uint8"},{"name":"assets","type":"Asset[]"},{"name":"expiredAt","type":"uint256"},{"name":"paymentToken","type":"address"},{"name":"startedAt","type":"uint256"},{"name":"basePrice","type":"uint256"},{"name":"endedAt","type":"uint256"},{"name":"endedPrice","type":"uint256"},{"name":"expectedState","type":"uint256"},{"name":"nonce","type":"uint256"},{"name":"marketFeePercentage","type":"uint256"}],"EIP712Domain":[{"name":"name","type":"string"},{"name":"version","type":"string"},{"name":"chainId","type":"uint256"},{"name":"verifyingContract","type":"address"}]},"domain":{"name":"MarketGateway","version":"1","chainId":2021,"verifyingContract":"0xfff9ce5f71ca6178d3beecedb61e7eff1602950e"},"primaryType":"Order","message":{"maker":"0xd761024b4ef3336becd6e802884d0b986c29b35a","kind":"1","assets":[{"erc":"1","addr":"0x32950db2a7164ae833121501c797d79e7b79d74c","id":"2730069","quantity":"0"}],"expiredAt":"1721709637","paymentToken":"0xc99a6a985ed2cac1ef41640596c5a5f9f4e19ef5","startedAt":"1705984837","basePrice":"500000000000000000","endedAt":"0","endedPrice":"0","expectedState":"0","nonce":"0","marketFeePercentage":"425"}}"""; val state = client.signTypeData(context, redirectUri, typedData) onStateChange(state) }, modifier = Modifier.fillMaxWidth() ) { Text("Sign Typed Data") } }
0
Kotlin
1
3
b6857cfff72eefa5f9cc7575ad653bd722da54af
8,639
mavis-id-android
MIT License
string-resource-helper/src/main/java/com/lin/string/helper/ui/ResourceTestContent.kt
tanliner
640,299,913
false
null
package com.lin.string.helper.ui import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material3.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.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.lin.string.helper.R import com.lin.string.helper.TextForUI @Composable internal fun ResourceTestContent( title: String, subtitle: TextForUI?, modifier: Modifier = Modifier ) { Column(modifier = Modifier.padding(horizontal = 16.dp)) { Text( text = title, modifier = modifier.align(alignment = Alignment.CenterHorizontally), fontWeight = FontWeight.W900, color = Color.Black, fontSize = 30.sp ) Spacer(modifier = Modifier.height(64.dp)) Text( text = stringResource(id = R.string.user_current_state), fontWeight = FontWeight.Bold, fontSize = 16.sp, color = Color.Red ) Text( text = stringResource(id = R.string.show_formatted_tips), fontWeight = FontWeight.Bold, fontSize = 16.sp ) subtitle?.let { Spacer(modifier = Modifier.height(32.dp)) Text( text = it.asString(), fontWeight = FontWeight.Medium, fontSize = 22.sp, color = Color.Black ) } } } @Preview(showBackground = true) @Composable private fun GreetingPreview() { ResourceTestContent("Android", TextForUI(R.string.title)) }
0
Kotlin
0
0
8cb95df7fa38f107038d3f97d2001a60608a3a01
1,980
Android-String-Resource-Helper
Apache License 2.0
app/src/main/java/com/diegomedina/notesapp/data/repository/peliculas/PeliculasDataStore.kt
magelac94
221,345,236
false
null
package com.diegomedina.notesapp.data.repository.peliculas import com.diegomedina.notesapp.data.model.Pelicula interface PeliculasDataStore { suspend fun getPeliculas(): List<Pelicula> suspend fun searchPeliculas(query: String, voteAverage: Int?): List<Pelicula> }
0
Kotlin
0
0
2022fb7fcf73ee876f46852da3f8aebb78d4d055
276
Obligatorio2Android
MIT License
order-engine/src/main/kotlin/com/getchange/orderengine/OrderService.kt
aasaru
221,717,176
false
{"HTML": 204323, "Kotlin": 47684, "JavaScript": 15756, "CSS": 11340, "PLpgSQL": 447, "Shell": 79, "Assembly": 4}
package com.getchange.orderengine import java.math.BigDecimal import java.util.Date class OrderService( private val orderRepository: OrderRepository ) { fun createBuyOrder( userId: Long, amount: Double, currency: Currency ) { val order = OrderEntity( userId = userId, createdTime = Date(), amount = BigDecimal.valueOf(amount), fromCurrency = currency, toCurrency = currency, orderType = OrderType.BUY ) orderRepository.createorder(order) } fun createSellOrder( userId: Long, amount: Double, currency: Currency ) { val order = OrderEntity( userId = userId, createdTime = Date(), amount = BigDecimal.valueOf(amount), fromCurrency = currency, toCurrency = currency, orderType = OrderType.SELL ) orderRepository.createorder(order) } fun convert( userId: Long, amount: Double, fromCurrency: Currency, toCurrency: Currency ) { val order = OrderEntity( userId = userId, createdTime = Date(), amount = BigDecimal.valueOf(amount), fromCurrency = fromCurrency, toCurrency = toCurrency, orderType = OrderType.CONVERT ) orderRepository.createorder(order) } fun listOrdersForUser(userId: Long): List<OrderEntity> { return orderRepository.getOrdersForUser(userId) } }
0
null
0
0
a0308d7ef981339ceeb12953d8871d4edefe144a
1,585
tsw-serverless-template
Apache License 2.0
app/src/main/java/com/xatryx/aegisapp/util/OFuelInstance.kt
xatryx
372,538,724
false
null
package com.xatryx.aegisapp.util import com.github.kittinunf.fuel.core.FuelManager object OFuelInstance { internal fun init(): FuelManager = FuelManager() }
0
Kotlin
0
0
894183f604dad4965d2263d0f78c412ae833af44
162
kotlin-android-AegisApp
MIT License
app/src/main/java/com/xatryx/aegisapp/util/OFuelInstance.kt
xatryx
372,538,724
false
null
package com.xatryx.aegisapp.util import com.github.kittinunf.fuel.core.FuelManager object OFuelInstance { internal fun init(): FuelManager = FuelManager() }
0
Kotlin
0
0
894183f604dad4965d2263d0f78c412ae833af44
162
kotlin-android-AegisApp
MIT License
app/src/main/java/com/bngel/bcy/fragment/FollowFragment.kt
Bngel
389,700,084
false
null
package com.bngel.bcy.fragment; import android.content.Context import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.fragment.app.Fragment import com.bngel.bcy.R import com.bngel.bcy.service.CosControllerService import com.bngel.bcy.utils.ConstantRepository import com.bngel.bcy.utils.InfoRepository import com.bngel.bcy.widget.HomeFragment.DiscussCardHomeFragment import com.bngel.bcy.widget.others.DiscussCommentView import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout import kotlinx.android.synthetic.main.fragment_follow.* class FollowFragment: Fragment() { private val cosService = CosControllerService() val FOLLOW_COUNT = 5 var pageNow = 1 var parentContext: Context? = null private var discussLauncher: ActivityResultLauncher<Intent>? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) registerLaunch() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_follow, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) parentContext = context?.applicationContext initWidget() } private fun initWidget() { cardListEvent() refreshEvent() } private fun refreshEvent() { refresh_FollowFragment.setOnRefreshListener(object: RefreshListenerAdapter(){ override fun onRefresh(refreshLayout: TwinklingRefreshLayout?) { super.onRefresh(refreshLayout) if (ConstantRepository.loginStatus) { pageNow = 1 val acgFollowCos = cosService.getAcgFollowCos(InfoRepository.user.id, FOLLOW_COUNT, pageNow) if (acgFollowCos != null && acgFollowCos.msg == "success") { val data = acgFollowCos.data val cardInfoList = data.cosFollowList discuss_cards_FollowFragment.removeAllViews() for (follow in cardInfoList) { val card = DiscussCardHomeFragment( parentContext!!, follow.number, follow.id, follow.username ?: "", follow.photo, follow.cosPhoto, follow.label, follow.description, follow.createTime, discussLauncher ) discuss_cards_FollowFragment.addView(card) } } } ConstantRepository.followFragmentUpdate = true refresh_FollowFragment.finishRefreshing() } override fun onLoadMore(refreshLayout: TwinklingRefreshLayout?) { super.onLoadMore(refreshLayout) if (ConstantRepository.loginStatus) { pageNow += 1 val acgFollowCos = cosService.getAcgFollowCos(InfoRepository.user.id, FOLLOW_COUNT, pageNow) if (acgFollowCos != null && acgFollowCos.msg == "success") { val data = acgFollowCos.data val cardInfoList = data.cosFollowList for (follow in cardInfoList) { val card = DiscussCardHomeFragment( parentContext!!, follow.number, follow.id, follow.username ?: "", follow.photo, follow.cosPhoto, follow.label, follow.description, follow.createTime, discussLauncher ) discuss_cards_FollowFragment.addView(card) } } } ConstantRepository.followFragmentUpdate = true refresh_FollowFragment.finishLoadmore() } }) } override fun onResume() { super.onResume() if (!ConstantRepository.followFragmentUpdate) { cardListEvent() } } private fun registerLaunch() { discussLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> val data = result.data } } private fun cardListEvent() { if (ConstantRepository.loginStatus) { val acgFollowCos = cosService.getAcgFollowCos(InfoRepository.user.id, FOLLOW_COUNT, pageNow) if (acgFollowCos != null && acgFollowCos.msg == "success") { val data = acgFollowCos.data val cardInfoList = data.cosFollowList discuss_cards_FollowFragment.removeAllViews() for (follow in cardInfoList) { val card = DiscussCardHomeFragment( parentContext!!, follow.number, follow.id, follow.username ?: "", follow.photo, follow.cosPhoto, follow.label, follow.description, follow.createTime, discussLauncher ) discuss_cards_FollowFragment.addView(card) } } } ConstantRepository.followFragmentUpdate = true } }
0
Kotlin
0
0
f8091bdbb9d4b7720587def7411b72a9c2d6fe35
5,726
bcy
Apache License 2.0
app/src/main/java/com/opensource/marvelcharacters/presentation/_common/models/Character.kt
Mohammad-Tabbara
219,486,106
false
null
package com.opensource.marvelcharacters.presentation._common.models import android.os.Parcel import android.os.Parcelable data class Character(val id: Int,val name: String?, val description: String?, val url: String?, val thumbnail: String?) : Parcelable { constructor(parcel: Parcel) : this( parcel.readInt(), parcel.readString(), parcel.readString(), parcel.readString(), parcel.readString() ) override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeInt(id) parcel.writeString(name) parcel.writeString(description) parcel.writeString(url) parcel.writeString(thumbnail) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<Character> { override fun createFromParcel(parcel: Parcel): Character { return Character(parcel) } override fun newArray(size: Int): Array<Character?> { return arrayOfNulls(size) } } }
0
Kotlin
0
0
71b2036b6ee85c305c6fb3a66fe8d55f32a91245
1,049
MarvelAndroidApp
Apache License 2.0
core/src/main/java/rdx/works/core/sargon/DerivationPathExtensions.kt
radixdlt
513,047,280
false
{"Kotlin": 4905038, "HTML": 215350, "Ruby": 2757, "Shell": 1963}
package rdx.works.core.sargon import com.radixdlt.sargon.Bip44LikePath import com.radixdlt.sargon.Cap26KeyKind import com.radixdlt.sargon.Cap26Path import com.radixdlt.sargon.DerivationPath import com.radixdlt.sargon.GetIdPath import com.radixdlt.sargon.NetworkId import com.radixdlt.sargon.extensions.account import com.radixdlt.sargon.extensions.addressIndex import com.radixdlt.sargon.extensions.asGeneral import com.radixdlt.sargon.extensions.default import com.radixdlt.sargon.extensions.identity fun DerivationPath.Companion.getIdPath() = DerivationPath.Cap26(Cap26Path.GetId(GetIdPath.default())) fun Cap26Path.Account.toAuthSigningDerivationPath(): DerivationPath = DerivationPath.Cap26.account( networkId = value.networkId, keyKind = Cap26KeyKind.AUTHENTICATION_SIGNING, index = value.index ) fun Cap26Path.Identity.toAuthSigningDerivationPath(): DerivationPath = DerivationPath.Cap26.identity( networkId = value.networkId, keyKind = Cap26KeyKind.AUTHENTICATION_SIGNING, index = value.index ) fun Bip44LikePath.toAccountAuthSigningDerivationPath(networkId: NetworkId): DerivationPath = DerivationPath.Cap26.account( networkId = networkId, keyKind = Cap26KeyKind.AUTHENTICATION_SIGNING, index = asGeneral().addressIndex ) fun Bip44LikePath.toIdentityAuthSigningDerivationPath(networkId: NetworkId): DerivationPath = DerivationPath.Cap26.identity( networkId = networkId, keyKind = Cap26KeyKind.AUTHENTICATION_SIGNING, index = asGeneral().addressIndex )
6
Kotlin
6
9
a973af97556c2c3c5c800dac937d0007a13a3a1c
1,514
babylon-wallet-android
Apache License 2.0
src/main/kotlin/io/github/josemiguelmelo/lnd/bolt11/decoder/ChecksumVerifier.kt
josemiguelmelo
837,419,612
false
{"Kotlin": 38320}
package io.github.josemiguelmelo.lnd.bolt11.decoder import io.github.josemiguelmelo.lnd.bolt11.bech32.Bech32Util.bech32To5BitArray class ChecksumVerifier { private val GENERATOR = intArrayOf(0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3) fun verify( humanReadablePartRaw: String, data: String, checksum: String, ): Boolean { val dataByteArray = bech32To5BitArray(data + checksum).toTypedArray() val expandedHRP = expandHRP(humanReadablePartRaw) val all = expandedHRP + dataByteArray return polymod(all) == 1 } private fun expandHRP(humanReadablePartRaw: String): Array<Int> { val firstExpandedPart = humanReadablePartRaw.map { it.code shr 5 } val separator = 0 val secondExpandedPart = humanReadablePartRaw.map { it.code and 31 } val expandedHRPList = firstExpandedPart + separator + secondExpandedPart return expandedHRPList.toTypedArray() } private fun polymod(values: Array<Int>): Int { var chk = 1 for (v in values) { val top = chk shr 25 chk = (chk and 0x1ffffff) shl 5 xor (v.toInt() and 0xff) for (i in 0..4) { if ((top shr i and 1) != 0) { chk = chk xor GENERATOR[i] } } } return chk } }
0
Kotlin
0
0
fd6957380d5ca8fe2260fa0e07ae17a6a3e62675
1,399
bolt11-util
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/Airplay.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.filled import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Filled.Airplay: ImageVector get() { if (_airplay != null) { return _airplay!! } _airplay = Builder(name = "Airplay", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(21.612f, 23.0f) horizontalLineTo(2.388f) lineToRelative(7.302f, -8.914f) curveToRelative(0.577f, -0.692f, 1.417f, -1.086f, 2.31f, -1.086f) horizontalLineToRelative(0.0f) curveToRelative(0.893f, 0.0f, 1.733f, 0.394f, 2.304f, 1.08f) lineToRelative(7.308f, 8.92f) close() moveTo(3.079f, 19.0f) lineToRelative(5.063f, -6.182f) curveToRelative(0.967f, -1.16f, 2.37f, -1.818f, 3.857f, -1.818f) reflectiveCurveToRelative(2.89f, 0.656f, 3.842f, 1.801f) lineToRelative(5.079f, 6.199f) horizontalLineToRelative(3.08f) verticalLineTo(4.0f) curveToRelative(0.0f, -1.654f, -1.346f, -3.0f, -3.0f, -3.0f) horizontalLineTo(3.0f) curveTo(1.346f, 1.0f, 0.0f, 2.346f, 0.0f, 4.0f) verticalLineToRelative(15.0f) horizontalLineToRelative(3.079f) close() } } .build() return _airplay!! } private var _airplay: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,284
icons
MIT License
app/src/main/java/com/fingerprint/auth/FingerprintHandler.kt
Anuradha-Kaurav
286,990,114
false
null
package com.fingerprint.auth import android.annotation.TargetApi import android.app.Activity import android.content.Context import android.hardware.fingerprint.FingerprintManager import android.os.Build import android.os.CancellationSignal import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.core.content.ContextCompat @TargetApi(Build.VERSION_CODES.M) class FingerprintHandler(private val context: Context) : FingerprintManager.AuthenticationCallback() { fun startAuth( fingerprintManager: FingerprintManager, cryptoObject: FingerprintManager.CryptoObject? ) { val cancellationSignal = CancellationSignal() fingerprintManager.authenticate(cryptoObject, cancellationSignal, 0, this, null) } override fun onAuthenticationError( errorCode: Int, errString: CharSequence ) { update("There was an Auth Error. $errString", false) } override fun onAuthenticationFailed() { update("Auth Failed. ", false) } override fun onAuthenticationHelp( helpCode: Int, helpString: CharSequence ) { update("Error: $helpString", false) } override fun onAuthenticationSucceeded(result: FingerprintManager.AuthenticationResult?) { update("You can now access the app.", true) } private fun update(s: String, b: Boolean) { val paraLabel = (context as Activity).findViewById<View>(R.id.text) as TextView val imageView: ImageView = context.findViewById<View>(R.id.fingerprintImg) as ImageView paraLabel.text = s if (b == false) { paraLabel.setTextColor(ContextCompat.getColor(context, R.color.colorAccent)) } else { paraLabel.setTextColor(ContextCompat.getColor(context, R.color.colorPrimary)) imageView.setImageResource(R.mipmap.ic_check_circle_black_24dp) } } }
0
Kotlin
0
0
94bc181cf25a774518e94125a53a51beda734148
1,962
Fingerprint_Authentication
MIT License
presentation/src/main/java/com/anangkur/budgetku/presentation/mapper/Mapper.kt
anangkur
270,303,728
false
null
package com.anangkur.budgetku.presentation.mapper interface Mapper<VIEW, T> { fun mapToView(type: T): VIEW fun mapFromView(type: VIEW): T }
10
null
0
3
82dc439d0df25cc894de5fc8d2604f1670c6cf31
148
Budget-Ku
MIT License
hangul-tensordroid/app/src/main/java/yutori/tf/hangul/data/GetExamRecordResponse.kt
Yutori-Team
291,010,168
false
null
package yutori.tf.hangul.data data class GetExamRecordResponse( var id: Long, var userId: Long, var sentenceTypes: String, var levelTypes: String, var numTypes: String, var score: Int, var time: String )
1
null
1
1
7f6a982f09834d9be4c06eddb3ea93d6b0e2926b
260
Yutori-Data-Android
Apache License 2.0
src/main/kotlin/com/ins/gradle/plugin/android/appcenter/AppCenterPluginExtension.kt
pajato1
218,811,853
true
{"Kotlin": 21773}
package com.ins.gradle.plugin.android.appcenter import groovy.lang.Closure import org.gradle.api.Action import org.gradle.api.NamedDomainObjectContainer import org.gradle.api.Project const val APP_CENTER_EXTENSION = "appCenter" open class AppCenterPluginExtension(private val project: Project) { var productFlavors : NamedDomainObjectContainer<BuildVariantExtension> ?= null var buildTypes : NamedDomainObjectContainer<BuildVariantExtension> ?= null var defaultConfig : BuildVariantExtension ?= null /** * Default Configuration when not defined for a buildType or flavor */ fun defaultConfig(defaultDef: Closure<*>) : BuildVariantExtension?{ if (defaultConfig != null) { throw Exception("Only one default config allowed") } defaultConfig = BuildVariantExtension() project.configure(defaultConfig, defaultDef) defaultDef.delegate = defaultConfig return defaultConfig } /** * All buildType config can be defined here */ fun buildTypes(action: Action<in NamedDomainObjectContainer<BuildVariantExtension>>) { action.execute(buildTypes) } /** * All flavor config can be defined here */ fun productFlavors(action: Action<in NamedDomainObjectContainer<BuildVariantExtension>>) { action.execute(productFlavors) } }
0
Kotlin
0
1
59086ff9478c020021c462dd0af418902912ed30
1,370
appcenter-publish-plugin
MIT License
src/test/kotlin/com/muhron/kotlinq/ToLookupTest.kt
RyotaMurohoshi
53,187,022
false
null
package com.muhron.kotlinq import org.junit.Assert import org.junit.Test class ToLookupTest { @Test fun testA() { val result = sequenceOf(1, 2, 3, 4, 5, 1, 2, 3, 1).toLookup { it } Assert.assertEquals(result.count, 5); Assert.assertEquals(result[1].toList(), listOf(1, 1, 1)); Assert.assertEquals(result[2].toList(), listOf(2, 2)); Assert.assertEquals(result[3].toList(), listOf(3, 3)); Assert.assertEquals(result[4].toList(), listOf(4)); Assert.assertEquals(result[5].toList(), listOf(5)); Assert.assertEquals(result[6].toList(), emptyList<Int>()); Assert.assertEquals(result.elementAt(0).key, 1); Assert.assertEquals(result.elementAt(0).asSequence().toList(), listOf(1, 1, 1)); Assert.assertEquals(result.elementAt(1).key, 2); Assert.assertEquals(result.elementAt(1).asSequence().toList(), listOf(2, 2)); Assert.assertEquals(result.elementAt(2).key, 3); Assert.assertEquals(result.elementAt(2).asSequence().toList(), listOf(3, 3)); Assert.assertEquals(result.elementAt(3).key, 4); Assert.assertEquals(result.elementAt(3).asSequence().toList(), listOf(4)); Assert.assertEquals(result.elementAt(4).key, 5); Assert.assertEquals(result.elementAt(4).asSequence().toList(), listOf(5)); } @Test fun testB() { val result = sequenceOf(1, 2, 3, 4, 5, 1, 2, 3, 1).toLookup ({ it }, { it.toString() }) Assert.assertEquals(result.count, 5); Assert.assertEquals(result[1].toList(), listOf("1", "1", "1")); Assert.assertEquals(result[2].toList(), listOf("2", "2")); Assert.assertEquals(result[3].toList(), listOf("3", "3")); Assert.assertEquals(result[4].toList(), listOf("4")); Assert.assertEquals(result[5].toList(), listOf("5")); Assert.assertEquals(result[6].toList(), emptyList<Int>()); Assert.assertEquals(result.elementAt(0).key, 1); Assert.assertEquals(result.elementAt(0).asSequence().toList(), listOf("1", "1", "1")); Assert.assertEquals(result.elementAt(1).key, 2); Assert.assertEquals(result.elementAt(1).asSequence().toList(), listOf("2", "2")); Assert.assertEquals(result.elementAt(2).key, 3); Assert.assertEquals(result.elementAt(2).asSequence().toList(), listOf("3", "3")); Assert.assertEquals(result.elementAt(3).key, 4); Assert.assertEquals(result.elementAt(3).asSequence().toList(), listOf("4")); Assert.assertEquals(result.elementAt(4).key, 5); Assert.assertEquals(result.elementAt(4).asSequence().toList(), listOf("5")); } }
1
Kotlin
0
5
1bb201d7032cdcc302f342bc771ab356f1d96db2
2,652
KotLinq
MIT License
app/src/main/java/gr/exm/agroxm/ui/splash/SplashActivity.kt
LedgerProject
321,964,554
false
null
package gr.exm.agroxm.ui.splash import android.os.Bundle import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import gr.exm.agroxm.ui.Navigator import org.koin.core.component.KoinComponent import org.koin.core.component.inject import timber.log.Timber class SplashActivity : AppCompatActivity(), KoinComponent { private val model: SplashViewModel by viewModels() private val navigator: Navigator by inject() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) model.isLoggedIn().observe(this) { result -> result.mapLeft { Timber.d("Not logged in.") navigator.showLogin(this) }.map { username -> Timber.d("Already logged in as $username") navigator.showHome(this) } finish() overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out) } } }
0
Kotlin
2
2
381a02f1d0d891b7d1c08a03b5fd5b26063402d0
991
disemin-android
Apache License 2.0
kamp-core/src/main/kotlin/ch/leadrian/samp/kamp/core/api/data/Location.kt
Double-O-Seven
142,487,686
false
{"Kotlin": 3854710, "C": 23964, "C++": 23699, "Java": 4753, "Dockerfile": 769, "Objective-C": 328, "Batchfile": 189}
package ch.leadrian.samp.kamp.core.api.data interface Location : Vector3D { val interiorId: Int val virtualWorldId: Int fun toLocation(): Location fun toMutableLocation(): MutableLocation fun distanceTo(other: Location): Float { if (this.interiorId != other.interiorId || this.virtualWorldId != other.virtualWorldId) { return Float.POSITIVE_INFINITY } return distanceTo(other as Vector3D) } fun isInRange(other: Location, distance: Float): Boolean { if (this.interiorId != other.interiorId || this.virtualWorldId != other.virtualWorldId) { return false } return isInRange(other as Vector3D, distance) } override fun plus(other: Vector2D): Location override fun plus(other: Vector3D): Location override fun minus(other: Vector2D): Location override fun minus(other: Vector3D): Location override fun times(value: Float): Location override fun div(value: Float): Location }
1
Kotlin
1
7
af07b6048210ed6990e8b430b3a091dc6f64c6d9
1,012
kamp
Apache License 2.0
compiler/testData/diagnostics/tests/secondaryConstructors/kt6993.fir.kt
android
263,405,600
true
null
// !DIAGNOSTICS: -UNUSED_PARAMETER // !WITH_NEW_INFERENCE class X<T>(val t: T) { constructor(t: T, i: Int) : this(i) }
0
Kotlin
37
316
74126637a097f5e6b099a7b7a4263468ecfda144
122
kotlin
Apache License 2.0
server/src/main/kotlin/io/provenance/invoice/repository/InvoiceRepository.kt
hyperschwartz
446,950,410
false
{"Kotlin": 270514, "Shell": 2246, "Dockerfile": 263}
package io.provenance.invoice.repository import io.provenance.invoice.InvoiceProtos.Invoice import io.provenance.invoice.domain.dto.InvoiceDto import io.provenance.invoice.domain.entities.InvoiceRecord import io.provenance.invoice.domain.entities.InvoiceUpdateQueryParam import io.provenance.invoice.domain.entities.InvoiceWritesResponse import io.provenance.invoice.domain.exceptions.ResourceNotFoundException import org.jetbrains.exposed.sql.transactions.transaction import org.springframework.stereotype.Repository import io.provenance.invoice.util.enums.InvoiceStatus import io.provenance.invoice.util.extension.wrapListI import io.provenance.metadata.v1.MsgWriteRecordRequest import io.provenance.metadata.v1.MsgWriteScopeRequest import io.provenance.metadata.v1.MsgWriteSessionRequest import java.util.UUID @Repository class InvoiceRepository { fun findByUuidOrNull(uuid: UUID): Invoice? = transaction { InvoiceRecord.findById(uuid)?.invoice } fun findByUuid(uuid: UUID): Invoice = findByUuidOrNull(uuid) ?: throw ResourceNotFoundException("Failed to find invoice by uuid [$uuid]") fun findDtoByUuidOrNull(uuid: UUID): InvoiceDto? = transaction { InvoiceRecord.findById(uuid)?.toDto() } fun findDtoByUuid(uuid: UUID): InvoiceDto = findDtoByUuidOrNull(uuid) ?: throw ResourceNotFoundException("Failed to find invoice dto by uuid [$uuid]") fun insert( invoice: Invoice, status: InvoiceStatus, writeScopeRequest: MsgWriteScopeRequest, writeSessionRequest: MsgWriteSessionRequest, writeRecordRequest: MsgWriteRecordRequest, ): InvoiceDto = transaction { InvoiceRecord.insert( invoice = invoice, status = status, writeScopeRequest = writeScopeRequest, writeSessionRequest = writeSessionRequest, writeRecordRequest = writeRecordRequest, ).toDto() } fun update( invoice: Invoice, status: InvoiceStatus? = null, processingStatus: InvoiceStatus? = null, writeScopeRequest: MsgWriteScopeRequest? = null, writeSessionRequest: MsgWriteSessionRequest? = null, writeRecordRequest: MsgWriteRecordRequest? = null, ): InvoiceDto = transaction { InvoiceRecord.update( invoiceParam = InvoiceUpdateQueryParam.InvoiceProto(invoice), status = status, writeScopeRequest = writeScopeRequest, writeSessionRequest = writeSessionRequest, writeRecordRequest = writeRecordRequest, ).toDto() } fun update( uuid: UUID, status: InvoiceStatus? = null, processingStatus: InvoiceStatus? = null, writeScopeRequest: MsgWriteScopeRequest? = null, writeSessionRequest: MsgWriteSessionRequest? = null, writeRecordRequest: MsgWriteRecordRequest? = null, ): InvoiceDto = transaction { InvoiceRecord.update( invoiceParam = InvoiceUpdateQueryParam.InvoiceUuid(uuid), status = status, writeScopeRequest = writeScopeRequest, writeSessionRequest = writeSessionRequest, writeRecordRequest = writeRecordRequest, ).toDto() } fun findAllByFromAddress(fromAddress: String): List<InvoiceDto> = transaction { InvoiceRecord.findAllFromAddress(fromAddress) } fun findAllByToAddress(toAddress: String): List<InvoiceDto> = transaction { InvoiceRecord.findAllToAddresses(toAddress.wrapListI()) } fun findAllByToAddresses(toAddresses: Collection<String>): List<InvoiceDto> = transaction { InvoiceRecord.findAllToAddresses(toAddresses) } fun findInvoiceUuidsWithFailedOracleApprovals(onlyIncludeUuids: Collection<UUID>? = null): List<UUID> = transaction { InvoiceRecord.findInvoiceUuidsWithFailedOracleApprovals(onlyIncludeUuids) } fun findWritesOrNull(invoiceUuid: UUID): InvoiceWritesResponse? = transaction { InvoiceRecord.findWritesOrNull(invoiceUuid) } fun findWriteScopeRequestOrNull(invoiceUuid: UUID): MsgWriteScopeRequest? = transaction { InvoiceRecord.findWriteScopeRequestOrNull(invoiceUuid) } fun findWriteSessionRequestOrNull(invoiceUuid: UUID): MsgWriteSessionRequest? = transaction { InvoiceRecord.findWriteSessionRequestOrNull(invoiceUuid) } fun findWriteRecordRequestOrNull(invoiceUuid: UUID): MsgWriteRecordRequest? = transaction { InvoiceRecord.findWriteRecordRequestOrNull(invoiceUuid) } }
0
Kotlin
0
0
d69c623e3c0ae51a2bbb2dde73bcdc860a0b2a39
4,499
service-invoice
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/educationandworkplanapi/app/ciagmigration/resource/model/PreviousWorkResponse.kt
ministryofjustice
653,598,082
false
{"Kotlin": 1067595, "Mustache": 3118, "Dockerfile": 1346}
package uk.gov.justice.digital.hmpps.educationandworkplanapi.app.ciagmigration.resource.model import com.fasterxml.jackson.annotation.JsonProperty import io.swagger.v3.oas.annotations.media.Schema import jakarta.validation.Valid import jakarta.validation.constraints.Size /** * A Prisoner's previous work experience. This is a temporary class to allow us to import data from the CIAG API. */ data class PreviousWorkResponse( @Schema(example = "null", required = true, description = "") @get:JsonProperty("hasWorkedBefore", required = true) val hasWorkedBefore: Boolean, @Schema( example = "asmith_gen", required = true, description = "The DPS username of the person who last updated this Prisoner's previous work.", ) @get:JsonProperty("modifiedBy", required = true) val modifiedBy: String, @Schema( example = "2023-06-19T09:39:44Z", required = true, description = "An ISO-8601 timestamp representing when this Prisoner's previous work was last updated. This will be the same as the created date if it has not yet been updated.", ) @get:JsonProperty("modifiedDateTime", required = true) val modifiedDateTime: java.time.LocalDateTime, @field:Valid @get:Size(min = 1) @Schema(example = "null", description = "A list of the Prisoner's type of previous work experience.") @get:JsonProperty("typeOfWorkExperience") val typeOfWorkExperience: Set<WorkType>? = null, @Schema( example = "null", description = "A specific work experience type for the Prisoner. Mandatory when 'typeOfWorkExperience' includes 'OTHER'.", ) @get:JsonProperty("typeOfWorkExperienceOther") val typeOfWorkExperienceOther: String? = null, @field:Valid @get:Size(min = 1) @Schema(example = "null", description = "A list of the Prisoner's previous work experience details.") @get:JsonProperty("workExperience") val workExperience: Set<WorkExperience>? = null, @field:Valid @Schema(example = "null", description = "") @get:JsonProperty("workInterests") val workInterests: WorkInterestsResponse? = null, )
2
Kotlin
0
2
3caec0f4478a7cb3e30dfc85e1acb7b24f6e2d87
2,069
hmpps-education-and-work-plan-api
MIT License
src/test/kotlin/no/nav/meldeplikt/meldekortservice/mapper/MeldekortkontrollMapperTest.kt
navikt
207,759,254
false
null
package no.nav.meldeplikt.meldekortservice.mapper import no.nav.meldeplikt.meldekortservice.model.enum.KortType import no.nav.meldeplikt.meldekortservice.model.meldekortdetaljer.MeldekortDag import no.nav.meldeplikt.meldekortservice.model.meldekortdetaljer.Meldekortdetaljer import no.nav.meldeplikt.meldekortservice.model.meldekortdetaljer.Sporsmal import no.nav.meldeplikt.meldekortservice.model.meldekortdetaljer.kontroll.FravaerInn import org.junit.jupiter.api.Test import java.time.LocalDate import java.time.format.DateTimeFormatter class MeldekortkontrollMapperTest { private val meldekortkontrollMapper = MeldekortkontrollMapper() @Test fun testMeldekortkontrollMapper() { val meldekortDager = mutableListOf<MeldekortDag>() meldekortDager.add(MeldekortDag(1, 0F, true, true, true)) meldekortDager.add(MeldekortDag(2, 23.5F, false, false, false)) meldekortDager.add(MeldekortDag(3, 0F, true, true, true)) meldekortDager.add(MeldekortDag(4, 0F, true, true, true)) val sporsmal = Sporsmal(true, false, false, true, true, false, false, meldekortDager) val meldekortdetaljer = Meldekortdetaljer( "123", 335, "99999123", 123456, "202004", "DAGP", "nokkel", KortType.MASKINELT_OPPDATERT, LocalDate.now().minusDays(1), LocalDate.now().plusDays(1), sporsmal, "Begrunnelse" ) val meldekortkontroll = meldekortkontrollMapper.mapMeldekortTilMeldekortkontroll(meldekortdetaljer) assert(meldekortkontroll.meldekortId.equals(meldekortdetaljer.meldekortId)) assert(meldekortkontroll.fnr.equals(meldekortdetaljer.fodselsnr)) assert(meldekortkontroll.personId == meldekortdetaljer.personId) assert(meldekortkontroll.periodeFra == LocalDate.parse("2020-01-20", DateTimeFormatter.ISO_DATE)) assert(meldekortkontroll.periodeTil == LocalDate.parse("2020-02-02", DateTimeFormatter.ISO_DATE)) assert(meldekortkontroll.meldedato == LocalDate.now().minusDays(1)) assert(meldekortkontroll.meldegruppe.equals(meldekortdetaljer.meldegruppe)) assert(meldekortkontroll.personId.equals(meldekortdetaljer.personId)) assert(meldekortkontroll.annetFravaer == sporsmal.annetFravaer) assert(meldekortkontroll.arbeidet == sporsmal.arbeidet) assert(meldekortkontroll.arbeidssoker == sporsmal.arbeidssoker) assert(meldekortkontroll.kurs == sporsmal.kurs) assert(meldekortkontroll.syk == sporsmal.syk) assert(meldekortkontroll.meldekortdager.size == meldekortDager.size) sammenlignMeldekortDag( meldekortkontroll.meldekortdager[0], meldekortDager[0], meldekortkontroll.periodeFra!! ) assert(meldekortkontroll.meldekortdager[0].syk!!) sammenlignMeldekortDag( meldekortkontroll.meldekortdager[1], meldekortDager[1], meldekortkontroll.periodeFra!! ) assert(meldekortkontroll.meldekortdager[1].arbeidTimer!! > 0) assert(meldekortkontroll.begrunnelse == meldekortdetaljer.begrunnelse) } private fun sammenlignMeldekortDag(fra: FravaerInn, til: MeldekortDag, foersteDag: LocalDate) { assert(fra.arbeidTimer == til.arbeidetTimerSum!!.toDouble()) assert(fra.dato == foersteDag.plusDays(til.dag.toLong() - 1)) } }
1
Kotlin
1
0
f03cdca47a594dfdbb113edce3ded561ec55605e
3,475
meldekortservice
MIT License
uniflow-core/src/main/kotlin/io/uniflow/core/flow/ActionReducer.kt
niltsiar
252,766,233
true
{"Kotlin": 113585, "Shell": 236}
package io.uniflow.core.flow import io.uniflow.core.dispatcher.UniFlowDispatcher import io.uniflow.core.flow.data.UIState import io.uniflow.core.flow.error.BadOrWrongStateException import io.uniflow.core.logger.UniFlowLogger import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.actor /** * Action processor component, backed by a coroutine Actor to execute a queue of Actions * * enqueueAction - enqueue in incoming Action * reduceAction - Execute an action to proceed any state update or event push * * @author <NAME> */ class ActionReducer( private val defaultPublisher: () -> DataPublisher, private val coroutineScope: CoroutineScope, private val defaultDispatcher: CoroutineDispatcher, defaultCapacity: Int = Channel.BUFFERED, private val tag: String ) { @OptIn(ObsoleteCoroutinesApi::class) private val actor = coroutineScope.actor<Action>(UniFlowDispatcher.dispatcher.default(), capacity = defaultCapacity) { for (action in channel) { if (coroutineScope.isActive) { withContext(defaultDispatcher) { reduceAction(action) } } else { UniFlowLogger.debug("$tag - $action cancelled") } } } suspend fun enqueueAction(action: Action) { actor.send(action) } private suspend fun reduceAction(action: Action) { UniFlowLogger.debug("$tag - reduce: $action") val currentState: UIState = defaultPublisher().getState() try { action.targetState?.let { targetState -> if (targetState != currentState::class) { action.onError(BadOrWrongStateException(currentState, targetState), currentState) return } } action.onSuccess(currentState) UniFlowLogger.debug("$tag - completed: $action") } catch (e: Exception) { UniFlowLogger.debug("$tag - error: $action") action.onError(e, currentState) } } fun close() { actor.close() } }
0
Kotlin
0
0
17b23208257c4c8564a4da9ce7ce3dc4573f256d
2,172
uniflow-kt
Apache License 2.0
net/craftventure/bukkit/ktx/extension/SynchedEntityData.kt
Craftventure
770,049,457
false
{"Kotlin": 3656616, "Java": 684034}
package net.craftventure.bukkit.ktx.extension import net.minecraft.network.syncher.EntityDataAccessor import net.minecraft.network.syncher.SynchedEntityData //fun <T> SynchedEntityData.setMetadata(field: EntityMetadata.Interactor<T>, value: T) { // setMetadata(field.accessor, value, field.defaultValue) //} fun <T> SynchedEntityData.setMetadata(field: EntityDataAccessor<T>, value: T, defaultValue: T) { try { set(field, value) } catch (e: Exception) { define(field, defaultValue) set(field, value) } }
0
Kotlin
1
21
015687ff6687160835deacda57121480f542531b
547
open-plugin-parts
MIT License