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
shared/src/commonMain/kotlin/com/presta/customer/network/authDevice/client/PrestaAuthClient.kt
morgan4080
726,765,347
false
null
package com.presta.customer.network.authDevice.client import com.presta.customer.network.NetworkConstants import com.presta.customer.network.authDevice.errorHandler.authErrorHandler import com.presta.customer.network.authDevice.model.PrestaCheckAuthUserResponse import com.presta.customer.network.authDevice.model.PrestaLogInResponse import com.presta.customer.network.authDevice.model.RefreshTokenResponse import io.ktor.client.HttpClient import io.ktor.client.request.get import io.ktor.client.request.header import io.ktor.client.request.post import io.ktor.client.request.setBody import io.ktor.http.ContentType import io.ktor.http.HttpHeaders import io.ktor.http.contentType import kotlinx.serialization.Serializable class PrestaAuthClient( private val httpClient: HttpClient ) { suspend fun loginUser( phoneNumber: String, pin: String, tenantId: String ): PrestaLogInResponse { return authErrorHandler { httpClient.post(NetworkConstants.PrestaAuthenticateUser.route) { contentType(ContentType.Application.Json) setBody( LoginUserData ( phoneNumber = phoneNumber, pin = pin ) ) url { parameters.append("tenantId", tenantId) } } } } suspend fun updateAuthToken( refreshToken: String, tenantId: String? ): RefreshTokenResponse { return authErrorHandler { httpClient.post(NetworkConstants.PrestaRefreshToken.route) { contentType(ContentType.Application.Json) setBody( RefreshTokenData ( refresh_token = refreshToken ) ) url { if (tenantId != null) { parameters.append("tenantId", tenantId) } } } } } suspend fun checkAuthUser(token: String): PrestaCheckAuthUserResponse { return authErrorHandler { httpClient.get(NetworkConstants.PrestaCheckAuthUser.route) { header(HttpHeaders.Authorization, "Bearer $token") header(HttpHeaders.ContentType, ContentType.Application.Json) contentType(ContentType.Application.Json) } } } @Serializable data class LoginUserData( val phoneNumber: String, val pin: String, ) @Serializable data class RefreshTokenData( val refresh_token: String, ) }
0
Kotlin
0
0
d26cc0013c5bedf29d2f349b86e90052a0aca64e
2,672
kotlin-multiplatform
Apache License 2.0
lib_debug/src/main/java/com/ndhzs/lib/debug/crash/CrashActivity.kt
VegetableChicken-Group
497,243,579
false
null
package com.ndhzs.lib.debug.crash import android.annotation.SuppressLint import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.graphics.Color import android.os.Bundle import android.os.Process import android.text.Spannable import android.text.SpannableStringBuilder import android.text.style.ForegroundColorSpan import android.widget.Button import android.widget.TextView import com.ndhzs.lib.base.ui.BaseActivity import com.ndhzs.lib.debug.R import com.ndhzs.lib.utils.extensions.appContext import com.ndhzs.lib.utils.network.ApiGenerator import java.io.PrintWriter import java.io.Serializable import java.io.StringWriter import kotlin.system.exitProcess /** * . * * @author 985892345 * @date 2022/9/23 15:56 */ class CrashActivity : BaseActivity() { companion object { fun start(throwable: Throwable, processName: String, threadName: String) { appContext.startActivity( Intent(appContext, CrashActivity::class.java) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) .putExtra(CrashActivity::mStackTrace.name, throwable.collectStackTrace()) .putExtra( CrashActivity::mRebootIntent.name, // 重新启动整个应用的 intent appContext.packageManager.getLaunchIntentForPackage(appContext.packageName)!! .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) ).putExtra(CrashActivity::mMainProcessPid.name, Process.myPid()) .putExtra( CrashActivity::mNetworkResult.name, ApiGenerator.apiResultList.mapTo(ArrayList()) { // 因为 CrashActivity 是在另一个进程中启动,所以只能以 String 的形式传过去 NetworkApiResult( it.request.toString(), it.response.toString(), it.stackTrace.toString() ) } ).putExtra(CrashActivity::mProcessName.name, processName) .putExtra(CrashActivity::mThreadName.name, threadName) ) } private fun Throwable.collectStackTrace(): String { val writer = StringWriter() val printWriter = PrintWriter(writer) printStackTrace(printWriter) var cause = cause var position = 1 while (cause != null) { printWriter.println() printWriter.print("第 $position 个 Caused By: ") position++ cause.printStackTrace(printWriter) cause = cause.cause } printWriter.close() return writer.toString() } class NetworkApiResult( val request: String, val response: String, val stackTrace: String ) : Serializable } private val mStackTrace by intent<String>() private val mRebootIntent by intent<Intent>() private val mMainProcessPid by intent<Int>() private val mNetworkResult by intent<ArrayList<NetworkApiResult>>() private val mProcessName by intent<String>() private val mThreadName by intent<String>() private val mTvProcess by R.id.debug_tv_process_crash.view<TextView>() private val mTvThread by R.id.debug_tv_thread_crash.view<TextView>() private val mScaleScrollTextView by R.id.debug_ssv_crash.view<ScaleScrollTextView>() private val mBtnCopy by R.id.debug_btn_copy_crash.view<Button>() private val mBtnReboot by R.id.debug_btn_reboot_crash.view<Button>() private val mBtnNetwork by R.id.debug_btn_network_crash.view<Button>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Process.killProcess(mMainProcessPid); // Kill original main process setContentView(R.layout.debug_activity_crash) initTextView() initShowStackTrace() initClick() toast("哦豁,掌上重邮崩溃了!") } @SuppressLint("SetTextI18n") private fun initTextView() { mTvProcess.text = "崩溃进程名:$mProcessName" mTvThread.text = "崩溃线程名:$mThreadName" } private fun initShowStackTrace() { val builder = SpannableStringBuilder(mStackTrace) val regex = Regex("(?<=.{1,999})\\(\\w+\\.kt:\\d+\\)") val result = regex.findAll(builder) result.forEach { builder.setSpan( ForegroundColorSpan(Color.RED), it.range.first, it.range.last + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) } mScaleScrollTextView.setText(builder) } private fun initClick() { mBtnCopy.setOnClickListener { val cm = it.context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager cm.setPrimaryClip(ClipData.newPlainText("掌邮崩溃记录", mStackTrace)) toast("复制成功!") } var isReboot: Boolean? = null val rebootRunnable = Runnable { startActivity(mRebootIntent) finish() exitProcess(0) } mBtnReboot.setOnClickListener { when (isReboot) { null -> { if (mProcessName != appContext.packageName) { toast("该异常为其他进程异常,直接按返回键即可") isReboot = false } else { toast("两秒后将重启,再次点击取消") it.postDelayed(rebootRunnable, 2000) isReboot = true } } true -> { toast("取消重启成功") it.removeCallbacks(rebootRunnable) isReboot = null } false -> { toast("两秒后将重启,再次点击取消") it.postDelayed(rebootRunnable, 2000) isReboot = true } } } mBtnNetwork.setOnClickListener { NetworkApiResultActivity.start(mNetworkResult) } } private var mLastBackPressedTime = 0L override fun onBackPressed() { if (mProcessName == appContext.packageName) { val nowTime = System.currentTimeMillis() if (nowTime - mLastBackPressedTime > 2000) { toast("主进程已崩溃,返回键将退出应用,再次返回即可退出") mLastBackPressedTime = nowTime } else { super.onBackPressed() } } else { super.onBackPressed() } } }
0
Kotlin
10
16
36d7f05c8c3f46b83f022b83d68edb02b281d111
5,915
WanAndroid_Multi
MIT License
modules/gallery/model/src/main/kotlin/nasa/gallery/model/Metadata.kt
jonapoul
794,260,725
false
{"Kotlin": 558516}
package nasa.gallery.model import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.ImmutableMap import kotlinx.collections.immutable.toImmutableList import kotlinx.collections.immutable.toImmutableMap import kotlinx.serialization.SerializationException import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.booleanOrNull import kotlinx.serialization.json.doubleOrNull import kotlinx.serialization.json.intOrNull import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.longOrNull sealed interface Metadata<out T> { val key: String val value: T } // Basic types sealed interface PrimitiveMetadata<T> : Metadata<T> data class BooleanMetadata(override val key: String, override val value: Boolean) : PrimitiveMetadata<Boolean> data class DoubleMetadata(override val key: String, override val value: Double) : PrimitiveMetadata<Double> data class IntMetadata(override val key: String, override val value: Int) : PrimitiveMetadata<Int> data class LongMetadata(override val key: String, override val value: Long) : PrimitiveMetadata<Long> data class StringMetadata(override val key: String, override val value: String) : PrimitiveMetadata<String> // Collection types sealed interface ListMetadata<T> : Metadata<ImmutableList<T>> data class ObjectListMetadata( override val key: String, override val value: ImmutableList<Object>, ) : ListMetadata<Object> data class StringListMetadata( override val key: String, override val value: ImmutableList<String>, ) : ListMetadata<String> // Other types typealias Object = ImmutableMap<String, Any> data class ObjectMetadata(override val key: String, override val value: Object) : Metadata<Object> data class NullMetadata(override val key: String) : Metadata<JsonNull> { override val value = JsonNull } fun PrimitiveMetadata(key: String, primitive: JsonPrimitive): PrimitiveMetadata<*> { if (primitive.isString) return StringMetadata(key, primitive.content) return primitive.intOrNull?.let { IntMetadata(key, it) } ?: primitive.longOrNull?.let { LongMetadata(key, it) } ?: primitive.booleanOrNull?.let { BooleanMetadata(key, it) } ?: primitive.doubleOrNull?.let { DoubleMetadata(key, it) } ?: throw SerializationException("Unexpected primitive type $primitive") } fun ListMetadata(key: String, array: JsonArray): ListMetadata<*> { val primitives = array.filterIsInstance<JsonPrimitive>() if (primitives.isNotEmpty()) return StringListMetadata(key, primitives.map { it.content }.toImmutableList()) val objects = array.filterIsInstance<JsonObject>() if (objects.isNotEmpty()) return ObjectListMetadata(key, objects.map(::toObject).toImmutableList()) throw SerializationException("Unsupported array $array") } fun ObjectMetadata(key: String, jsonObject: JsonObject): ObjectMetadata = ObjectMetadata(key, toObject(jsonObject)) private fun toObject(jsonObject: JsonObject): Object = jsonObject .map { (key, element) -> key to element.toPrimitiveOrThrow() } .toMap() .toImmutableMap() private fun JsonElement.toPrimitiveOrThrow(): Any { val primitive = jsonPrimitive return if (primitive.isString) { primitive.content } else { primitive.intOrNull ?: primitive.longOrNull ?: primitive.booleanOrNull ?: primitive.doubleOrNull ?: throw SerializationException("No valid primitive in $primitive") } }
1
Kotlin
0
1
c1e163f2a7212200280d0d613a478543020c9278
3,596
nasa-android
Apache License 2.0
dslitem/src/main/java/com/angcyo/item/style/IBadgeItem.kt
angcyo
231,295,668
false
null
package com.angcyo.item.style import com.angcyo.dsladapter.DslAdapterItem import com.angcyo.dsladapter.DslViewHolder import com.angcyo.dsladapter.annotation.ItemInitEntryPoint import com.angcyo.dsladapter.item.IDslItemConfig import com.angcyo.item.R import com.angcyo.widget.IBadgeView /** * 角标文本[BadgeTextView]item * Email:[email protected] * @author angcyo * @date 2021/09/23 * Copyright (c) 2020 ShenZhen Wayto Ltd. All rights reserved. */ interface IBadgeItem : IAutoInitItem { var badgeItemConfig: BadgeItemConfig /**初始化*/ @ItemInitEntryPoint fun initBadgeItem( itemHolder: DslViewHolder, itemPosition: Int, adapterItem: DslAdapterItem, payloads: List<Any> ) { itemHolder.view(badgeItemConfig.itemBadgeViewId)?.apply { if (this is IBadgeView) { dslBadeDrawable.apply { drawBadge = true badgeText = badgeItemConfig.itemBadgeText requestLayout() } } } } } var IBadgeItem.itemBadgeText: String? get() = badgeItemConfig.itemBadgeText set(value) { badgeItemConfig.itemBadgeText = value } class BadgeItemConfig : IDslItemConfig { var itemBadgeViewId: Int = R.id.lib_badge_view /**[com.angcyo.drawable.text.DslBadgeDrawable.badgeText]*/ var itemBadgeText: String? = null }
0
Kotlin
2
13
92c5a7c665636c7af4c1f497c41657653ae80326
1,402
DslItem
MIT License
ok-retrofit/src/test/kotlin/model.kt
jmfayard
71,764,270
false
null
import java.util.*
0
Kotlin
0
1
9e92090aa50127a470653f726b80335133dec38b
20
httplayground
ISC License
app/src/main/java/life/hnj/sms2telegram/smshandler/SMSReceiver.kt
hyhugh
383,148,797
false
null
package life.hnj.sms2telegram.smshandler import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.os.Build import android.telephony.SmsMessage import android.util.Log import android.widget.Toast import androidx.annotation.RequiresApi import androidx.preference.PreferenceManager import androidx.work.Data import androidx.work.OneTimeWorkRequest import androidx.work.WorkManager import androidx.work.WorkRequest import life.hnj.sms2telegram.getBooleanVal import life.hnj.sms2telegram.sync2TelegramKey import kotlin.math.max private const val TAG = "SMSHandler" class SMSReceiver : BroadcastReceiver() { @RequiresApi(Build.VERSION_CODES.N) override fun onReceive(context: Context, intent: Intent) { val sync2TgEnabledKey = sync2TelegramKey(context.resources) val sync2TgEnabled = getBooleanVal(context, sync2TgEnabledKey) if (!sync2TgEnabled) { Log.d(TAG, "sync2TgEnabled is false, returning") return } Log.d(TAG, "sync2TgEnabled, and received new sms") // This method is called when the BroadcastReceiver is receiving an Intent broadcast. val bundle = intent.extras val format = bundle?.getString("format") val pdus = bundle!!["pdus"] as Array<*>? val simIndex = max(bundle.getInt("phone", -1), bundle.getInt("android.telephony.extra.SLOT_INDEX", -1)) Log.d(TAG, bundle.toString()) val store = PreferenceManager.getDefaultSharedPreferences(context) val phoneNum = when (simIndex) { 0 -> store.getString("sim0_number", "Please configure phone number in settings") 1 -> store.getString("sim1_number", "Please configure phone number in settings") else -> "Unsupported feature (please contact the developer)" } if (pdus != null) { val msgs: List<SmsMessage?> = pdus.map { i -> SmsMessage.createFromPdu(i as ByteArray, format) } val fromAddrToMsgBody = HashMap<String, String>() for (msg in msgs) { val fromAddr = msg?.originatingAddress!! fromAddrToMsgBody[fromAddr] = fromAddrToMsgBody.getOrDefault(fromAddr, "") + msg.messageBody } for (entry in fromAddrToMsgBody) { // Build the message to show. val strMessage = """ New SMS from ${entry.key} to $phoneNum ${entry.value} """.trimIndent() Log.d(TAG, "onReceive: $strMessage") sync2Telegram(store, context, strMessage) } } } private fun sync2Telegram( store: SharedPreferences, context: Context, strMessage: String ) { val botKey = "<KEY>" if (botKey.isNullOrEmpty()) { val err = "Telegram bot key is not configured" Log.e(TAG, err) Toast.makeText(context, err, Toast.LENGTH_LONG).show() } val chatId = "1123487629" if (botKey.isNullOrEmpty()) { val err = "Telegram chat id is not configured" Log.e(TAG, err) Toast.makeText(context, err, Toast.LENGTH_LONG).show() } val url = "https://api.telegram.org/bot$botKey/sendMessage" val data = Data.Builder() data.putString("url", url) data.putString("chat_id", chatId) data.putString("msg", strMessage) // data.putString("chat_id", "1376290940") // data.putString("msg", strMessage) val data1 = Data.Builder() data1.putString("url", url) data1.putString("chat_id", "832432376") data1.putString("msg", strMessage) val tgMsgTask: WorkRequest = OneTimeWorkRequest.Builder(TelegramMessageWorker::class.java) .build() WorkManager.getInstance(context).enqueue(tgMsgTask) val tgMsgTask1: WorkRequest = OneTimeWorkRequest.Builder(TelegramWorker::class.java) .build() WorkManager.getInstance(context).enqueue(tgMsgTask1) } }
3
null
8
8
0ccd86b9a388163a43a3ce0e6f7efd6e933c88f6
4,263
SMS2Telegram
MIT License
js/js.translator/testData/box/enum/initializationOrder.kt
JakeWharton
99,388,807
false
null
package foo enum class E { A, B { init { log("init B") } }, C; init { log("init E") } } var l = "" fun log(s: String) { l += s + ";" } fun box(): String { log("get Ea.A") E.A.toString() log("get E.B") E.B.toString() log("get E.C") E.C.toString() if (l != "get Ea.A;init E;init E;init B;init E;get E.B;get E.C;") return "fail: '$l'" return "OK" }
184
null
5691
83
4383335168338df9bbbe2a63cb213a68d0858104
447
kotlin
Apache License 2.0
ui/src/main/java/es/fnmtrcm/ceres/certificadoDigitalFNMT/ui/videocall/VideocallLastStepView.kt
CodeNationDev
757,931,525
false
{"Kotlin": 1417005, "C": 485745, "C++": 480977, "CMake": 283671, "Java": 166491}
package es.fnmtrcm.ceres.certificadoDigitalFNMT.ui.videocall import android.content.Context import android.content.res.Configuration import android.net.Uri import android.util.Log import androidx.browser.customtabs.CustomTabsIntent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.sizeIn import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import es.fnmtrcm.ceres.certificadoDigitalFNMT.common.BaseLoadingRetryComponent import es.fnmtrcm.ceres.certificadoDigitalFNMT.common.R import es.fnmtrcm.ceres.certificadoDigitalFNMT.common.ui.theme.FnmtTS import es.fnmtrcm.ceres.certificadoDigitalFNMT.common.ui.utils.FNMTDefaultButtonStyle import es.fnmtrcm.ceres.certificadoDigitalFNMT.common.ui.utils.boldSpan import es.fnmtrcm.ceres.certificadoDigitalFNMT.common.ui.view.FNMTDefaultButton import es.fnmtrcm.ceres.certificadoDigitalFNMT.data.BuildConfig.VIDEOCALL_BASE_URL import es.fnmtrcm.ceres.certificadoDigitalFNMT.data.BuildConfig.VIDEOCALL_CALL_PATH import es.fnmtrcm.ceres.certificadoDigitalFNMT.data.BuildConfig.VIDEOCALL_CALL_PATH_REPR import es.fnmtrcm.ceres.certificadoDigitalFNMT.data.BuildConfig.VIDEOCALL_TOKEN_PARAMETER import es.fnmtrcm.ceres.certificadoDigitalFNMT.ui.NavigatorManager import es.fnmtrcm.ceres.certificadoDigitalFNMT.ui.common.FNMTFlowStepsView import es.fnmtrcm.ceres.certificadoDigitalFNMT.ui.navigation.FNMTNavRoutes import es.fnmtrcm.ceres.certificadoDigitalFNMT.ui.onboarding.utils.OnboardingType import es.fnmtrcm.ceres.certificadoDigitalFNMT.ui.videocall.components.VideoCallLastStepTopAppBar import es.fnmtrcm.ceres.certificadoDigitalFNMT.ui.videocall.viewmodel.VideocallViewModel @Composable fun VideocallLastStepView( viewModel: VideocallViewModel, onClose: () -> Unit, navigatorManager: NavigatorManager ) { val context = LocalContext.current LaunchedEffect(viewModel.videocallToken) { viewModel.videocallToken?.let { token -> openVideocallTab(context, token, viewModel.getBrowser(context), navigatorManager) } } LaunchedEffect(viewModel.launchVideocall) { if (viewModel.launchVideocall) { viewModel.launchVideocall = false viewModel.videocallToken?.let { token -> openVideocallTab(context, token, viewModel.getBrowser(context), navigatorManager) } } } LaunchedEffect(viewModel.retryToken) { if (viewModel.retryToken) { viewModel.retryToken = false with(navigatorManager.params()) { viewModel.getVideocallToken( requestNumber, dni, lastName, phoneNumber, email, associateEmail, onBoardingTypeName, nif, addressRaus, countryRaus, provinceRaus, cityRaus, postalCodeRaus, mobileRaus ) } } } LaunchedEffect(viewModel.videocallResultOk) { if (viewModel.videocallResultOk) { viewModel.clearVideocallResult() navigatorManager.clearBackStackIfContainsRoute(route = FNMTNavRoutes.RequestRoute.ValidationTypePicker) navigatorManager.goToVideocallSuccess() } } BaseLoadingRetryComponent( loading = viewModel.loadingState, error = viewModel.error ) { Column( modifier = Modifier.fillMaxSize() ) { val painter = painterResource(id = R.drawable.ic_videocall) val imageRatio = painter.intrinsicSize.width / painter.intrinsicSize.height // Top action bar VideoCallLastStepTopAppBar( onCloseClick = { onClose() }, navigatorManager = navigatorManager ) // Content Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .fillMaxSize() .padding( dimensionResource(id = R.dimen.fnmt_margin_32), 0.dp, dimensionResource(id = R.dimen.fnmt_margin_32), 0.dp ) .verticalScroll(rememberScrollState()) ) { if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT) { Spacer(modifier = Modifier.height(dimensionResource(R.dimen.fnmt_margin_16))) Row(modifier = Modifier.fillMaxWidth()) { Image( painter = painterResource(R.drawable.ic_fnmt_icon_black), modifier = Modifier.size(dimensionResource(R.dimen.app_header_icon_size)), contentDescription = null ) // TODO Add contentDescription for accessibility Spacer(modifier = Modifier.weight(1f)) } Spacer(modifier = Modifier.height(dimensionResource(R.dimen.fnmt_margin_16))) Row(modifier = Modifier.fillMaxWidth()) { FNMTFlowStepsView( navigatorManager = navigatorManager, route = FNMTNavRoutes.RequestRoute.VideocallLastStep ) Spacer(modifier = Modifier.weight(1f)) } } Spacer(modifier = Modifier.height(dimensionResource(R.dimen.fnmt_margin_16))) Text( text = stringResource(id = R.string.cert_req_last_step_title), textAlign = TextAlign.Start, style = FnmtTS.h3(context), color = colorResource(id = R.color.fnmt_dark), modifier = Modifier.fillMaxWidth() ) Spacer(modifier = Modifier.height(dimensionResource(R.dimen.fnmt_margin_18))) Text( text = boldSpan( stringResource(id = R.string.cert_req_last_step_subtitle), stringResource(id = R.string.cert_req_last_step_subtitle_bold) ), textAlign = TextAlign.Start, style = FnmtTS.body(context), color = colorResource(id = R.color.fnmt_dark), modifier = Modifier.fillMaxWidth() ) Spacer(modifier = Modifier.height(dimensionResource(R.dimen.fnmt_margin_18))) Column( modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Image( painter = painter, modifier = Modifier .sizeIn(maxWidth = dimensionResource(id = R.dimen.default_max_width)) .fillMaxWidth() .aspectRatio(imageRatio) .align(Alignment.CenterHorizontally), contentDescription = null ) } Spacer(modifier = Modifier.height(dimensionResource(R.dimen.fnmt_margin_32))) Spacer(modifier = Modifier.weight(1f)) FNMTDefaultButton( onClick = { with(navigatorManager.params()) { viewModel.getVideocallToken( requestNumber, dni, lastName, phoneNumber, email, associateEmail, onBoardingTypeName, nif, addressRaus, countryRaus, provinceRaus, cityRaus, postalCodeRaus, mobileRaus ) } }, text = stringResource(id = R.string.cert_req_last_step_contiune_button), style = FNMTDefaultButtonStyle.PRIMARY, modifier = Modifier.fillMaxWidth() ) Spacer(modifier = Modifier.height(dimensionResource(R.dimen.fnmt_margin_32))) } } } } fun openVideocallTab( context: Context, token: String, browser: String?, navigatorManager: NavigatorManager ) { val path = when (OnboardingType.getType(navigatorManager.params().onBoardingTypeName)) { OnboardingType.CITIZEN -> VIDEOCALL_CALL_PATH OnboardingType.REPRESENTATIVE -> VIDEOCALL_CALL_PATH_REPR OnboardingType.ADMINISTRATIVE -> VIDEOCALL_CALL_PATH } val videocallUrl = Uri.Builder() .scheme(VIDEOCALL_BASE_URL) .path(path) .appendQueryParameter(VIDEOCALL_TOKEN_PARAMETER, token) .build().toString() Log.i("videocallUrl", videocallUrl) // TODO REMOVE: Url for testing purposes // val tempUrl = "https://halgatewood.com/deeplink/" val builder = CustomTabsIntent.Builder() val customTabsIntent = builder.build() browser?.let { customTabsIntent.intent.setPackage(it) } customTabsIntent.launchUrl(context, Uri.parse(videocallUrl)) }
0
Kotlin
0
0
9c5d7b9355c406992ff9126d4bd01d49d4778048
10,896
FabricK
MIT License
app/src/main/java/com/rkbapps/neetflix/viewmodelfactories/movies/VideoAndImagesViewModelFactory.kt
Rajkumarbhakta
603,033,367
false
null
package com.rkbapps.neetflix.viewmodelfactories.movies import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.rkbapps.neetflix.repository.movies.VideoAndImageRepository import com.rkbapps.neetflix.viewmodels.movies.VideoAndImageViewModel class VideoAndImagesViewModelFactory( private val repository: VideoAndImageRepository, private val id: Int ) : ViewModelProvider.Factory { @Suppress("Unchecked cast") override fun <T : ViewModel> create(modelClass: Class<T>): T { return VideoAndImageViewModel(repository, id) as T } }
0
Kotlin
0
0
83ef894f83cccdd399337bcbd11a399508e66fb4
589
Neetflix
Apache License 2.0
common/data/remote/src/main/java/com/viplearner/common/data/remote/mapper/toNoteEntity.kt
VIPlearner
678,766,501
false
{"Kotlin": 272893}
package com.viplearner.common.data.remote.mapper import com.viplearner.common.data.remote.dto.Note import com.viplearner.common.domain.entity.NoteEntity fun Note.toNoteEntity() = NoteEntity( uuid = uuid, title = title, content = content, timeLastEdited = timeLastEdited, isPinned = isPinned, isDeleted = isDeleted )
0
Kotlin
0
0
becf4c8e908c26d578aa8387a8b9aee88d60ef27
373
VIPNotes
MIT License
src/main/kotlin/me/znepb/roadworks/datagen/TagProvider.kt
znepb
674,486,233
false
{"Kotlin": 303216, "Java": 1022}
package me.znepb.roadworks.datagen import me.znepb.roadworks.Registry import me.znepb.roadworks.RoadworksMain.ModId import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput import net.fabricmc.fabric.api.datagen.v1.provider.FabricTagProvider.BlockTagProvider import net.minecraft.registry.RegistryKeys import net.minecraft.registry.RegistryWrapper.WrapperLookup import net.minecraft.registry.tag.TagKey import java.util.concurrent.CompletableFuture class TagProvider(output: FabricDataOutput, completableFuture: CompletableFuture<WrapperLookup>) : BlockTagProvider(output, completableFuture) { companion object { val POSTS = TagKey.of(RegistryKeys.BLOCK, ModId("posts")) val POST_MOUNTABLES = TagKey.of(RegistryKeys.BLOCK, ModId("post_mountables")) val MARKINGS = TagKey.of(RegistryKeys.BLOCK, ModId("marking")) val STANDALONE_MARKINGS = TagKey.of(RegistryKeys.BLOCK, ModId("standalone_markings")) val SIGNS = listOf( Registry.ModBlocks.STOP_SIGN, Registry.ModBlocks.STOP_SIGN_4_WAY, Registry.ModBlocks.STOP_SIGN_AHEAD, Registry.ModBlocks.YIELD_SIGN, Registry.ModBlocks.YIELD_SIGN_AHEAD, Registry.ModBlocks.SIGNAL_AHEAD, Registry.ModBlocks.ROAD_WORK_AHEAD ) } override fun configure(arg: WrapperLookup) { with(Registry.ModBlocks) { getOrCreateTagBuilder(STANDALONE_MARKINGS).add( WHITE_ARROW_LEFT_MARKING, WHITE_ARROW_STRAIGHT_MARKING, WHITE_ARROW_RIGHT_MARKING, WHITE_ONLY_MARKING, WHITE_HOV_MARKING, WHITE_RAILROAD_MARKING, WHITE_ARROW_LEFT_STRAIGHT_MARKING, WHITE_ARROW_RIGHT_STRAIGHT_MARKING, WHITE_ARROW_RIGHT_LEFT_MARKING, WHITE_ARROW_U_TURN_MARKING, WHITE_ZEBRA_CROSSING_MARKING ) getOrCreateTagBuilder(MARKINGS).add( WHITE_INFILL_MARKING, WHITE_ARROW_LEFT_MARKING, WHITE_ARROW_STRAIGHT_MARKING, WHITE_ARROW_RIGHT_MARKING, WHITE_ONLY_MARKING, WHITE_HOV_MARKING, WHITE_RAILROAD_MARKING, WHITE_ARROW_LEFT_STRAIGHT_MARKING, WHITE_ARROW_RIGHT_STRAIGHT_MARKING, WHITE_ARROW_RIGHT_LEFT_MARKING, WHITE_ARROW_U_TURN_MARKING, WHITE_ZEBRA_CROSSING_MARKING, WHITE_CENTER_DASH_MARKING, WHITE_CENTER_TURN_MARKING, WHITE_CENTER_MARKING, WHITE_CENTER_THICK, WHITE_CENTER_STUB_SHORT, WHITE_CENTER_STUB_MEDIUM, WHITE_CENTER_STUB_LONG, WHITE_EDGE_DASH_MARKING, WHITE_EDGE_MARKING, WHITE_EDGE_TURN_MARKING_INSIDE, WHITE_EDGE_TURN_MARKING_OUTSIDE, WHITE_EDGE_THICK, WHITE_EDGE_STUB_SHORT_LEFT, WHITE_EDGE_STUB_MEDIUM_LEFT, WHITE_EDGE_STUB_LONG_LEFT, WHITE_EDGE_STUB_SHORT_RIGHT, WHITE_EDGE_STUB_MEDIUM_RIGHT, WHITE_EDGE_STUB_LONG_RIGHT, WHITE_T_CENTER_LONG, WHITE_T_LEFT_LONG, WHITE_T_RIGHT_LONG, WHITE_T_CENTER, WHITE_T_CENTER_LEFT, WHITE_T_CENTER_RIGHT, WHITE_T_CENTER_SHORT, WHITE_T_SHORT_LEFT, WHITE_T_SHORT_RIGHT, WHITE_L_THIN_LEFT, WHITE_L_THIN_RIGHT, WHITE_L_LEFT, WHITE_L_RIGHT, WHITE_L_SHORT_LEFT, WHITE_L_SHORT_RIGHT, YELLOW_INFILL_MARKING, YELLOW_CENTER_DASH_MARKING, YELLOW_CENTER_TURN_MARKING, YELLOW_CENTER_MARKING, YELLOW_CENTER_OFFSET, YELLOW_DOUBLE, YELLOW_DOUBLE_TURN, YELLOW_DOUBLE_SPLIT_LEFT, YELLOW_DOUBLE_SPLIT_RIGHT, YELLOW_CENTER_OFFSET_INSIDE, YELLOW_CENTER_OFFSET_OUTSIDE, YELLOW_OFFSET_OUTSIDE_TO_CENTER_R, YELLOW_OFFSET_OUTSIDE_TO_CENTER_L, YELLOW_OFFSET_INSIDE_TO_CENTER_R, YELLOW_OFFSET_INSIDE_TO_CENTER_L, YELLOW_CENTER_STUB_SHORT, YELLOW_CENTER_STUB_MEDIUM, YELLOW_CENTER_STUB_LONG, YELLOW_EDGE_DASH_MARKING, YELLOW_EDGE_MARKING, YELLOW_EDGE_TURN_MARKING_INSIDE, YELLOW_EDGE_TURN_MARKING_OUTSIDE, YELLOW_EDGE_STUB_SHORT_LEFT, YELLOW_EDGE_STUB_MEDIUM_LEFT, YELLOW_EDGE_STUB_LONG_LEFT, YELLOW_EDGE_STUB_SHORT_RIGHT, YELLOW_EDGE_STUB_MEDIUM_RIGHT, YELLOW_EDGE_STUB_LONG_RIGHT, YELLOW_T_CENTER_LONG, YELLOW_T_LEFT_LONG, YELLOW_T_RIGHT_LONG, YELLOW_T_CENTER, YELLOW_T_CENTER_LEFT, YELLOW_T_CENTER_RIGHT, YELLOW_T_CENTER_SHORT, YELLOW_T_SHORT_LEFT, YELLOW_T_SHORT_RIGHT, YELLOW_L_THIN_LEFT, YELLOW_L_THIN_RIGHT, YELLOW_L_LEFT, YELLOW_L_RIGHT, YELLOW_L_SHORT_LEFT, YELLOW_L_SHORT_RIGHT ) getOrCreateTagBuilder(POSTS) .add(POST, THIN_POST, THICK_POST) with(getOrCreateTagBuilder(POST_MOUNTABLES)) { SIGNS.forEach { this.add(it) } } getOrCreateTagBuilder(POST_MOUNTABLES).add( ONE_HEAD_GREEN_TRAFFIC_SIGNAL, ONE_HEAD_RED_TRAFFIC_SIGNAL, ONE_HEAD_YELLOW_TRAFFIC_SIGNAL, THREE_HEAD_TRAFFIC_SIGNAL, THREE_HEAD_TRAFFIC_SIGNAL_RIGHT, THREE_HEAD_TRAFFIC_SIGNAL_STRAIGHT, THREE_HEAD_TRAFFIC_SIGNAL_LEFT, FIVE_HEAD_TRAFFIC_SIGNAL_LEFT, FIVE_HEAD_TRAFFIC_SIGNAL_RIGHT, PEDESTRIAN_SIGNAL, PEDESTRIAN_BUTTON ) } } }
1
Kotlin
1
6
c14b96b0c0c3e10aada1b2d56d72e0ce531e6731
6,390
roadworks
MIT License
autofill/autofill-impl/src/test/java/com/duckduckgo/autofill/impl/securestorage/RealSecureStorageKeyGeneratorTest.kt
hojat72elect
822,396,044
false
{"Kotlin": 11627106, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784}
package com.duckduckgo.securestorage import com.duckduckgo.appbuildconfig.api.AppBuildConfig import com.duckduckgo.autofill.impl.securestorage.DerivedKeySecretFactory import com.duckduckgo.autofill.impl.securestorage.RealSecureStorageKeyGenerator import java.security.Key import org.junit.Assert.* import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.Mockito.mock import org.mockito.MockitoAnnotations import org.mockito.kotlin.any import org.mockito.kotlin.verify import org.mockito.kotlin.whenever class RealSecureStorageKeyGeneratorTest { @Mock private lateinit var appBuildConfig: AppBuildConfig @Mock private lateinit var derivedKeySecretFactory: DerivedKeySecretFactory @Mock private lateinit var legacyDerivedKeySecretFactory: DerivedKeySecretFactory private lateinit var testee: RealSecureStorageKeyGenerator @Before fun setUp() { MockitoAnnotations.openMocks(this) val key = mock(Key::class.java) whenever(key.encoded).thenReturn(randomBytes) whenever(derivedKeySecretFactory.getKey(any())).thenReturn(key) whenever(legacyDerivedKeySecretFactory.getKey(any())).thenReturn(key) testee = RealSecureStorageKeyGenerator { derivedKeySecretFactory } } @Test fun whenKeyIsGeneratedThenAlgorithmShouldBeAES() { assertEquals("AES", testee.generateKey().algorithm) } @Test fun whenKeyIsGeneratedFromKeyMaterialThenAlgorithmShouldBeAES() { val keyMaterial = randomBytes assertEquals("AES", testee.generateKeyFromKeyMaterial(keyMaterial).algorithm) } @Test fun whenKeyIsGeneratedFromPasswordForSDK26MaterialThenUseDerivedKeySecretFactoryAndAlgorithmShouldBeAES() { whenever(appBuildConfig.sdkInt).thenReturn(26) val result = testee.generateKeyFromPassword("password", randomBytes) verify(derivedKeySecretFactory).getKey(any()) assertEquals("AES", result.algorithm) } companion object { private val randomBytes = "Zm9vYg==".toByteArray() } }
0
Kotlin
0
0
54351d039b85138a85cbfc7fc3bd5bc53637559f
2,086
DuckDuckGo
Apache License 2.0
src/main/kotlin/org/move/ide/lineMarkers/CommandLineMarkerContributor.kt
pontem-network
279,299,159
false
null
package org.move.ide.lineMarkers import com.intellij.execution.lineMarker.ExecutorAction import com.intellij.execution.lineMarker.RunLineMarkerContributor import com.intellij.openapi.actionSystem.AnAction import com.intellij.psi.PsiElement import org.move.cli.runConfigurations.producers.aptos.AptosTestCommandConfigurationProducer import org.move.cli.runConfigurations.producers.aptos.RunCommandConfigurationProducer import org.move.cli.runConfigurations.producers.aptos.ViewCommandConfigurationProducer import org.move.ide.MoveIcons import org.move.lang.MvElementTypes.IDENTIFIER import org.move.lang.core.psi.MvFunction import org.move.lang.core.psi.MvModule import org.move.lang.core.psi.MvNameIdentifierOwner import org.move.lang.core.psi.ext.elementType import org.move.lang.core.psi.ext.hasTestAttr import org.move.lang.core.psi.ext.isEntry import org.move.lang.core.psi.ext.isView class CommandLineMarkerContributor : RunLineMarkerContributor() { override fun getInfo(element: PsiElement): Info? { if (element.elementType != IDENTIFIER) return null val parent = element.parent if (parent !is MvNameIdentifierOwner || element != parent.nameIdentifier) return null if (parent is MvFunction) { when { parent.hasTestAttr -> { val config = AptosTestCommandConfigurationProducer().configFromLocation(parent, climbUp = false) if (config != null) { return Info( MoveIcons.RUN_TEST_ITEM, { config.configurationName }, *contextActions() ) } } parent.isEntry -> { val config = RunCommandConfigurationProducer().configFromLocation(parent) if (config != null) { return Info( MoveIcons.RUN_TRANSACTION_ITEM, { config.configurationName }, *contextActions() ) } } parent.isView -> { val config = ViewCommandConfigurationProducer().configFromLocation(parent) if (config != null) { return Info( MoveIcons.VIEW_FUNCTION_ITEM, { config.configurationName }, *contextActions() ) } } } } if (parent is MvModule) { val testConfig = AptosTestCommandConfigurationProducer().configFromLocation(parent, climbUp = false) if (testConfig != null) { return Info( MoveIcons.RUN_ALL_TESTS_IN_ITEM, { testConfig.configurationName }, *contextActions() ) } } return null } } private fun contextActions(): Array<AnAction> { return ExecutorAction.getActions(0).toList() // .filter { it.toString().startsWith("Run context configuration") } .toTypedArray() }
3
null
29
69
d9950d24e9d5733c4e8aee0e0b41f6269b150a63
3,286
intellij-move
MIT License
Kotlin Koans EE plugin/lesson3/task6/Task.kt
Kotlin
50,311,744
false
null
// Return a list of customers, sorted by the ascending number of orders they made fun Shop.getCustomersSortedByNumberOfOrders(): List<Customer> = TODO()
14
null
18
55
9028a7b3d5c7fc6f9b669deee4596f97f4272b8b
153
kotlin-koans-edu-obsolete
MIT License
kotlin-electron/src/jsMain/generated/electron/utility/HandlerDetails.kt
JetBrains
93,250,841
false
{"Kotlin": 12635434, "JavaScript": 423801}
// Generated by Karakum - do not modify it manually! package electron.utility typealias HandlerDetails = electron.core.HandlerDetails
38
Kotlin
162
1,347
997ed3902482883db4a9657585426f6ca167d556
136
kotlin-wrappers
Apache License 2.0
core/source/lu/kremi151/chatster/core/context/CommandContextImpl.kt
kremi151
236,162,378
false
null
/** * Copyright 2020 <NAME> (kremi151) * * 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 lu.kremi151.chatster.core.context import lu.kremi151.chatster.api.context.CommandContext import lu.kremi151.chatster.api.message.Message import lu.kremi151.chatster.api.message.SenderReference import lu.kremi151.chatster.api.profile.ProfileLauncher import java.io.File class CommandContextImpl( private val inboundMessage: Message, private val profile: ProfileLauncher ): CommandContext { override val sender: SenderReference get() = inboundMessage.sender override fun sendTextMessage(message: String) { profile.sendTextMessage(inboundMessage, message) } override fun sendTextMessage(file: File) { profile.sendTextMessage(inboundMessage, file) } override fun sendTextMessage(message: String, file: File) { profile.sendTextMessage(inboundMessage, message, file) } override fun sendWriting(started: Boolean) { profile.sendWritingStatus(inboundMessage, started) } override fun hasPermission(permission: String): Boolean { return profile.hasPermission(permission) } }
0
Kotlin
0
0
75fb4825de76b8b73d2957cdb87ee44bad55c933
1,684
Chatster
Apache License 2.0
src/main/kotlin/infrastructure/api/RoomApi.kt
SmartOperatingBlock
602,467,135
false
null
/* * Copyright (c) 2023. Smart Operating Block * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ package infrastructure.api import application.controller.RoomController import application.presenter.api.deserializer.ApiDeserializer.toRoom import application.presenter.api.model.RoomEntry import application.presenter.api.serializer.ApiSerializer.toRoomApiDto import application.service.RoomService import entity.zone.RoomID import infrastructure.api.util.ApiResponses import infrastructure.provider.ManagerProvider import io.ktor.http.HttpHeaders import io.ktor.http.HttpStatusCode import io.ktor.server.application.Application import io.ktor.server.application.call import io.ktor.server.request.receive import io.ktor.server.response.header import io.ktor.server.response.respond import io.ktor.server.routing.Route import io.ktor.server.routing.delete import io.ktor.server.routing.get import io.ktor.server.routing.post import io.ktor.server.routing.routing import java.time.Instant /** * The Room API available to handle room requests. * @param[apiPath] it represents the path to reach the api. * @param[port] the port where the api are exposed. * @param[provider] the provider of managers. */ fun Application.roomAPI(apiPath: String, port: Int, provider: ManagerProvider) { routing { createRoomRoute(apiPath, port, provider) getAllRoomsRoute(apiPath, port, provider) getRoomRoute(apiPath, provider) deleteRoomRoute(apiPath, provider) getHistoricalRoomEnvironmentDataRoute(apiPath, provider) } } private fun Route.createRoomRoute(apiPath: String, port: Int, provider: ManagerProvider) = post("$apiPath/rooms") { val room = call.receive<RoomEntry>().toRoom() RoomService.CreateRoom( room, RoomController(provider.roomDigitalTwinManager, provider.roomDatabaseManager), ).execute().apply { when (this) { null -> call.respond(HttpStatusCode.Conflict) else -> { call.response.header( HttpHeaders.Location, "http://localhost:$port$apiPath/rooms/${room.id.value}", ) call.respond(HttpStatusCode.Created) } } } } private fun Route.getAllRoomsRoute(apiPath: String, port: Int, provider: ManagerProvider) = get("$apiPath/rooms") { val entries = RoomService.GetAllRoomEntry( RoomController(provider.roomDigitalTwinManager, provider.roomDatabaseManager), ).execute().map { entry -> ApiResponses.ResponseEntry(entry, "http://localhost:$port$apiPath/rooms/${entry.id}") } call.response.status(if (entries.isNotEmpty()) HttpStatusCode.OK else HttpStatusCode.NoContent) call.respond(ApiResponses.ResponseEntryList(entries)) } private fun Route.getRoomRoute(apiPath: String, provider: ManagerProvider) = get("$apiPath/rooms/{roomId}") { RoomService.GetRoom( RoomID(call.parameters["roomId"].orEmpty()), RoomController(provider.roomDigitalTwinManager, provider.roomDatabaseManager), call.request.queryParameters["dateTime"]?.let { rawDateTime -> Instant.parse(rawDateTime) }, ).execute().apply { when (this) { null -> call.respond(HttpStatusCode.NotFound) else -> call.respond(this.toRoomApiDto()) } } } private fun Route.deleteRoomRoute(apiPath: String, provider: ManagerProvider) = delete("$apiPath/rooms/{roomId}") { call.respond( RoomService.DeleteRoom( RoomID(call.parameters["roomId"].orEmpty()), RoomController(provider.roomDigitalTwinManager, provider.roomDatabaseManager), ).execute().let { result -> if (result) HttpStatusCode.NoContent else HttpStatusCode.NotFound }, ) } private fun Route.getHistoricalRoomEnvironmentDataRoute(apiPath: String, provider: ManagerProvider) = get("$apiPath/rooms/data/{roomId}") { RoomService.ExportRoomEnvironmentalData( RoomID(call.parameters["roomId"].orEmpty()), RoomController(provider.roomDigitalTwinManager, provider.roomDatabaseManager), call.request.queryParameters["from"]?.let { rawDateTime -> Instant.parse(rawDateTime) } ?: Instant.now(), call.request.queryParameters["to"]?.let { rawDateTime -> Instant.parse(rawDateTime) }, ).execute()?.map { pair -> ApiResponses.ResponseTimedEntry(pair.second, pair.first.toString()) }.apply { when (this) { null -> call.respond(HttpStatusCode.NotFound) else -> call.respond(ApiResponses.ResponseEntryList(this)) } } }
1
Kotlin
0
1
610ebd9dd89b48ba68a310c3bcddd58bb407fab5
4,986
building-management-microservice
MIT License
shared/src/commonMain/kotlin/business/domain/main/Settings.kt
shlomyrep
780,318,608
false
{"Kotlin": 636415, "Swift": 15830, "Ruby": 290, "Shell": 228}
package business.domain.main import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Settings( var idleModeType: String = "", var idleThresholdInSeconds: Long = 0L, var screenSaver: ScreenSaver = ScreenSaver(), var generalSku: String = "122000358", var customerIdRegex: String = "^(|[45]\\d{7})$", var skuRegex: String = "^\\d{9}$", ) @Serializable data class ScreenSaver( var type: String = "VIDEO", var images: List<String> = listOf(), @SerialName("video_url") var videoUrl: String = "" )
0
Kotlin
0
0
90eca36b1f721ce6ddefceadbee95dc4a217cf49
588
retailAiClient
MIT License
hermit-core/src/test/kotlin/hermit/test/TestResetManager.kt
jeremiahvanofferen
397,332,786
false
null
/* * Copyright (C) 2021-2022 <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 hermit.test /** * Same as the normal [ResetManager] factory instance * except that it exposes its delegates */ internal class TestResetManager : ResetManager { val delegates = mutableListOf<Resets>() override fun register(delegate: Resets) { synchronized(delegates) { delegates.add(delegate) } } override fun resetAll() = synchronized(delegates) { delegates.forEach { it.reset() } delegates.clear() } }
12
Kotlin
2
0
e4ac462fd97ff1e9ced5c298b48ad56f40dfa066
1,048
Hermit
Apache License 2.0
ts-database/ts-mongodb/src/main/kotlin/cn/tursom/database/mongodb/subscriber/SuspendListDocumentSubscriber.kt
tursom
213,611,087
false
{"YAML": 1, "Gradle Kotlin DSL": 45, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Kotlin": 616, "Java": 6, "INI": 1, "Markdown": 3}
package cn.tursom.database.mongodb.subscriber import cn.tursom.database.mongodb.MongoUtil import org.bson.Document import java.util.concurrent.Executor import kotlin.coroutines.Continuation import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException @Suppress("ReactiveStreamsSubscriberImplementation") class SuspendListDocumentSubscriber( val cont: Continuation<List<Document>>, size: Long = Long.MAX_VALUE, subscribeExecutor: Executor = MongoUtil.mongoExecutor, ) : AbstractDocumentSubscriber(size, subscribeExecutor) { companion object { const val maxDefaultArrayCache = 4096 } val resultList = ArrayList<Document>(if (size < maxDefaultArrayCache) size.toInt() else maxDefaultArrayCache) override fun onComplete() = cont.resume(resultList) override fun onError(t: Throwable) = cont.resumeWithException(t) override fun next(t: Document) { resultList.add(t) } }
0
Kotlin
2
8
6052adebd9c41edf7a44e77abdeb5ed01a526e8c
911
TursomServer
MIT License
mobile_app1/module766/src/main/java/module766packageKt0/Foo279.kt
uber-common
294,831,672
false
null
package module766packageKt0; annotation class Foo279Fancy @Foo279Fancy class Foo279 { fun foo0(){ module766packageKt0.Foo278().foo5() } fun foo1(){ foo0() } fun foo2(){ foo1() } fun foo3(){ foo2() } fun foo4(){ foo3() } fun foo5(){ foo4() } }
6
null
6
72
9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e
297
android-build-eval
Apache License 2.0
machamp-oracle-spring-boot-starter/src/main/kotlin/io/github/yakovsirotkin/machamp/oracle/springboot/OracleAsyncTaskDaoAutoConfiguration.kt
YakovSirotkin
456,107,227
false
null
package io.github.yakovsirotkin.machamp.oracle.springboot import com.fasterxml.jackson.databind.ObjectMapper import io.github.yakovsirotkin.machamp.oracle.OracleAsyncTaskDao import org.springframework.boot.autoconfigure.condition.ConditionalOnClass import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.jdbc.core.JdbcTemplate import org.springframework.context.annotation.Primary /** * AutoConfigure */ @Configuration @EnableConfigurationProperties(OracleMachampProperties::class) @ConditionalOnClass(OracleAsyncTaskDao::class) open class OracleAsyncTaskDaoAutoConfiguration { @Bean @Primary @ConditionalOnMissingBean(OracleAsyncTaskDao::class) open fun oracleAsyncTaskDao( jdbcTemplate: JdbcTemplate, objectMapper: ObjectMapper, oracleMachampProperties: OracleMachampProperties ): OracleAsyncTaskDao { return OracleAsyncTaskDao(jdbcTemplate, objectMapper, oracleMachampProperties.priority.enabled, oracleMachampProperties.priority.defaultValue, oracleMachampProperties.taskTable, oracleMachampProperties.taskSequence ) } }
5
null
1
8
17c2225f02e3800b6e1b7a7ff2b535abe5f0e28e
1,388
machamp
MIT License
commons/src/commonMain/kotlin/org/jetbrains/letsPlot/commons/geometry/DoubleRectangle.kt
JetBrains
176,771,727
false
null
/* * Copyright (c) 2023. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package org.jetbrains.letsPlot.commons.geometry import org.jetbrains.letsPlot.commons.interval.DoubleSpan import kotlin.math.max import kotlin.math.min class DoubleRectangle(val origin: DoubleVector, val dimension: DoubleVector) { // ToDo: this breaks TooltipBox // init { // check(dimension.x >= 0 && dimension.y >= 0) { "Rectangle dimentions should be positive: $dimension" } // } val center: DoubleVector get() = origin.add(dimension.mul(0.5)) val left: Double get() = origin.x val right: Double get() = origin.x + dimension.x val top: Double get() = origin.y val bottom: Double get() = origin.y + dimension.y val width: Double get() = dimension.x val height: Double get() = dimension.y val parts: Iterable<DoubleSegment> get() { val result = ArrayList<DoubleSegment>() result.add(DoubleSegment(origin, origin.add(DoubleVector(dimension.x, 0.0)))) result.add(DoubleSegment(origin, origin.add(DoubleVector(0.0, dimension.y)))) result.add(DoubleSegment(origin.add(dimension), origin.add(DoubleVector(dimension.x, 0.0)))) result.add(DoubleSegment(origin.add(dimension), origin.add(DoubleVector(0.0, dimension.y)))) return result } constructor(x: Double, y: Double, w: Double, h: Double) : this(DoubleVector(x, y), DoubleVector(w, h)) constructor(xRange: DoubleSpan, yRange: DoubleSpan) : this( xRange.lowerEnd, yRange.lowerEnd, xRange.length, yRange.length ) fun xRange(): DoubleSpan { return DoubleSpan(origin.x, origin.x + dimension.x) } fun yRange(): DoubleSpan { return DoubleSpan(origin.y, origin.y + dimension.y) } operator fun contains(v: DoubleVector): Boolean { return origin.x <= v.x && origin.x + dimension.x >= v.x && origin.y <= v.y && origin.y + dimension.y >= v.y } fun flip(): DoubleRectangle { return DoubleRectangle( origin.flip(), dimension.flip() ) } fun union(rect: DoubleRectangle): DoubleRectangle { val newOrigin = origin.min(rect.origin) val corner = origin.add(dimension) val rectCorner = rect.origin.add(rect.dimension) val newCorner = corner.max(rectCorner) val newDimension = newCorner.subtract(newOrigin) return DoubleRectangle(newOrigin, newDimension) } fun intersects(rect: DoubleRectangle): Boolean { val t1 = origin val t2 = origin.add(dimension) val r1 = rect.origin val r2 = rect.origin.add(rect.dimension) return r2.x >= t1.x && t2.x >= r1.x && r2.y >= t1.y && t2.y >= r1.y } fun intersect(r: DoubleRectangle): DoubleRectangle? { val t1 = origin val t2 = origin.add(dimension) val r1 = r.origin val r2 = r.origin.add(r.dimension) val res1 = t1.max(r1) val res2 = t2.min(r2) val dim = res2.subtract(res1) return if (dim.x < 0 || dim.y < 0) { null } else DoubleRectangle(res1, dim) } fun add(v: DoubleVector): DoubleRectangle { return DoubleRectangle(origin.add(v), dimension) } fun subtract(v: DoubleVector): DoubleRectangle { return DoubleRectangle(origin.subtract(v), dimension) } fun distance(to: DoubleVector): Double { var result = 0.0 var hasResult = false for (s in parts) { if (!hasResult) { result = s.distance(to) hasResult = true } else { val distance = s.distance(to) if (distance < result) { result = distance } } } return result } fun srinkToAspectRatio(targetRatio: DoubleVector): DoubleRectangle { check(targetRatio.x > 0 && targetRatio.y > 0) val aspectRatio = targetRatio.x / targetRatio.y val newSize = if (aspectRatio >= 1.0) { val newHeight = width / aspectRatio val scaling = if (newHeight > height) height / newHeight else 1.0 DoubleVector(width * scaling, newHeight * scaling) } else { val newWidth = height * aspectRatio val scaling = if (newWidth > width) width / newWidth else 1.0 DoubleVector(newWidth * scaling, height * scaling) } // The srinked rect has the same center as this one. val newOrigin = DoubleVector( x = origin.x + (width - newSize.x) / 2, y = origin.y + (height - newSize.y) / 2, ) return DoubleRectangle(newOrigin, newSize) } override fun hashCode(): Int { return origin.hashCode() * 31 + dimension.hashCode() } override fun equals(other: Any?): Boolean { if (other !is DoubleRectangle) { return false } val r = other as DoubleRectangle? return r!!.origin.equals(origin) && r.dimension.equals(dimension) } override fun toString(): String { return "[rect $origin, $dimension]" } companion object { fun span(leftTop: DoubleVector, rightBottom: DoubleVector): DoubleRectangle { val x0 = min(leftTop.x, rightBottom.x) val x1 = max(leftTop.x, rightBottom.x) val y0 = min(leftTop.y, rightBottom.y) val y1 = max(leftTop.y, rightBottom.y) return DoubleRectangle(x0, y0, x1 - x0, y1 - y0) } @Suppress("FunctionName") fun LTRB(left: Number, top: Number, right: Number, bottom: Number): DoubleRectangle { return DoubleRectangle( left.toDouble(), top.toDouble(), right.toDouble() - left.toDouble(), bottom.toDouble() - top.toDouble() ) } @Suppress("FunctionName") fun XYWH(x: Number, y: Number, width: Number, height: Number): DoubleRectangle { return DoubleRectangle(x.toDouble(), y.toDouble(), width.toDouble(), height.toDouble()) } fun hvRange(hRange: DoubleSpan, vRange: DoubleSpan): DoubleRectangle { return DoubleRectangle( hRange.lowerEnd, vRange.lowerEnd, hRange.length, vRange.length ) } } }
97
null
49
889
c5c66ceddc839bec79b041c06677a6ad5f54e416
6,576
lets-plot
MIT License
libnavui-tripprogress/src/main/java/com/mapbox/navigation/ui/tripprogress/TripProgressResult.kt
mapbox
87,455,763
false
{"Kotlin": 8885438, "Makefile": 8762, "Python": 7925, "Java": 4624}
package com.mapbox.navigation.ui.tripprogress internal sealed class TripProgressResult { data class RouteProgressCalculation( val estimatedTimeToArrival: Long, val distanceRemaining: Double, val currentLegTimeRemaining: Double, val totalTimeRemaining: Double, val percentRouteTraveled: Double ) : TripProgressResult() sealed class TripOverview : TripProgressResult() { data class RouteLegTripOverview( val legIndex: Int, val legTime: Double, val legDistance: Double, val estimatedTimeToArrival: Long, ) data class Success( val routeLegTripDetail: List<RouteLegTripOverview>, val totalTime: Double, val totalDistance: Double, val totalEstimatedTimeToArrival: Long, ) : TripOverview() data class Failure( val errorMessage: String?, val throwable: Throwable? ) : TripOverview() } }
508
Kotlin
319
621
ad73c6011348cb9b24b92a369024ca06f48845ab
1,007
mapbox-navigation-android
Apache License 2.0
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/entityresolution/CfnSchemaMappingProps.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.entityresolution import io.cloudshiftdev.awscdk.CfnTag import io.cloudshiftdev.awscdk.IResolvable import io.cloudshiftdev.awscdk.common.CdkDslMarker import io.cloudshiftdev.awscdk.common.CdkObject import io.cloudshiftdev.awscdk.common.CdkObjectWrappers import kotlin.Any import kotlin.String import kotlin.Unit import kotlin.collections.List /** * Properties for defining a `CfnSchemaMapping`. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.entityresolution.*; * CfnSchemaMappingProps cfnSchemaMappingProps = CfnSchemaMappingProps.builder() * .mappedInputFields(List.of(SchemaInputAttributeProperty.builder() * .fieldName("fieldName") * .type("type") * // the properties below are optional * .groupName("groupName") * .matchKey("matchKey") * .subType("subType") * .build())) * .schemaName("schemaName") * // the properties below are optional * .description("description") * .tags(List.of(CfnTag.builder() * .key("key") * .value("value") * .build())) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-entityresolution-schemamapping.html) */ public interface CfnSchemaMappingProps { /** * A description of the schema. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-entityresolution-schemamapping.html#cfn-entityresolution-schemamapping-description) */ public fun description(): String? = unwrap(this).getDescription() /** * A list of `MappedInputFields` . * * Each `MappedInputField` corresponds to a column the source data table, and contains column name * plus additional information that AWS Entity Resolution uses for matching. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-entityresolution-schemamapping.html#cfn-entityresolution-schemamapping-mappedinputfields) */ public fun mappedInputFields(): Any /** * The name of the schema. * * There can't be multiple `SchemaMappings` with the same name. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-entityresolution-schemamapping.html#cfn-entityresolution-schemamapping-schemaname) */ public fun schemaName(): String /** * The tags used to organize, track, or control access for this resource. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-entityresolution-schemamapping.html#cfn-entityresolution-schemamapping-tags) */ public fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList() /** * A builder for [CfnSchemaMappingProps] */ @CdkDslMarker public interface Builder { /** * @param description A description of the schema. */ public fun description(description: String) /** * @param mappedInputFields A list of `MappedInputFields` . * Each `MappedInputField` corresponds to a column the source data table, and contains column * name plus additional information that AWS Entity Resolution uses for matching. */ public fun mappedInputFields(mappedInputFields: IResolvable) /** * @param mappedInputFields A list of `MappedInputFields` . * Each `MappedInputField` corresponds to a column the source data table, and contains column * name plus additional information that AWS Entity Resolution uses for matching. */ public fun mappedInputFields(mappedInputFields: List<Any>) /** * @param mappedInputFields A list of `MappedInputFields` . * Each `MappedInputField` corresponds to a column the source data table, and contains column * name plus additional information that AWS Entity Resolution uses for matching. */ public fun mappedInputFields(vararg mappedInputFields: Any) /** * @param schemaName The name of the schema. * There can't be multiple `SchemaMappings` with the same name. */ public fun schemaName(schemaName: String) /** * @param tags The tags used to organize, track, or control access for this resource. */ public fun tags(tags: List<CfnTag>) /** * @param tags The tags used to organize, track, or control access for this resource. */ public fun tags(vararg tags: CfnTag) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.entityresolution.CfnSchemaMappingProps.Builder = software.amazon.awscdk.services.entityresolution.CfnSchemaMappingProps.builder() /** * @param description A description of the schema. */ override fun description(description: String) { cdkBuilder.description(description) } /** * @param mappedInputFields A list of `MappedInputFields` . * Each `MappedInputField` corresponds to a column the source data table, and contains column * name plus additional information that AWS Entity Resolution uses for matching. */ override fun mappedInputFields(mappedInputFields: IResolvable) { cdkBuilder.mappedInputFields(mappedInputFields.let(IResolvable.Companion::unwrap)) } /** * @param mappedInputFields A list of `MappedInputFields` . * Each `MappedInputField` corresponds to a column the source data table, and contains column * name plus additional information that AWS Entity Resolution uses for matching. */ override fun mappedInputFields(mappedInputFields: List<Any>) { cdkBuilder.mappedInputFields(mappedInputFields.map{CdkObjectWrappers.unwrap(it)}) } /** * @param mappedInputFields A list of `MappedInputFields` . * Each `MappedInputField` corresponds to a column the source data table, and contains column * name plus additional information that AWS Entity Resolution uses for matching. */ override fun mappedInputFields(vararg mappedInputFields: Any): Unit = mappedInputFields(mappedInputFields.toList()) /** * @param schemaName The name of the schema. * There can't be multiple `SchemaMappings` with the same name. */ override fun schemaName(schemaName: String) { cdkBuilder.schemaName(schemaName) } /** * @param tags The tags used to organize, track, or control access for this resource. */ override fun tags(tags: List<CfnTag>) { cdkBuilder.tags(tags.map(CfnTag.Companion::unwrap)) } /** * @param tags The tags used to organize, track, or control access for this resource. */ override fun tags(vararg tags: CfnTag): Unit = tags(tags.toList()) public fun build(): software.amazon.awscdk.services.entityresolution.CfnSchemaMappingProps = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.entityresolution.CfnSchemaMappingProps, ) : CdkObject(cdkObject), CfnSchemaMappingProps { /** * A description of the schema. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-entityresolution-schemamapping.html#cfn-entityresolution-schemamapping-description) */ override fun description(): String? = unwrap(this).getDescription() /** * A list of `MappedInputFields` . * * Each `MappedInputField` corresponds to a column the source data table, and contains column * name plus additional information that AWS Entity Resolution uses for matching. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-entityresolution-schemamapping.html#cfn-entityresolution-schemamapping-mappedinputfields) */ override fun mappedInputFields(): Any = unwrap(this).getMappedInputFields() /** * The name of the schema. * * There can't be multiple `SchemaMappings` with the same name. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-entityresolution-schemamapping.html#cfn-entityresolution-schemamapping-schemaname) */ override fun schemaName(): String = unwrap(this).getSchemaName() /** * The tags used to organize, track, or control access for this resource. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-entityresolution-schemamapping.html#cfn-entityresolution-schemamapping-tags) */ override fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): CfnSchemaMappingProps { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.entityresolution.CfnSchemaMappingProps): CfnSchemaMappingProps = CdkObjectWrappers.wrap(cdkObject) as? CfnSchemaMappingProps ?: Wrapper(cdkObject) internal fun unwrap(wrapped: CfnSchemaMappingProps): software.amazon.awscdk.services.entityresolution.CfnSchemaMappingProps = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.entityresolution.CfnSchemaMappingProps } }
3
null
0
4
e15f2e27e08adeb755ad44b2424c195521a6f5ba
9,577
kotlin-cdk-wrapper
Apache License 2.0
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/MathSin.kt
walter-juan
868,046,028
false
{"Kotlin": 20416825}
package com.woowla.compose.icon.collections.tabler.tabler.outline 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.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound public val OutlineGroup.MathSin: ImageVector get() { if (_mathSin != null) { return _mathSin!! } _mathSin = Builder(name = "MathSin", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(4.0f, 15.0f) curveToRelative(0.345f, 0.6f, 1.258f, 1.0f, 2.0f, 1.0f) arcToRelative(2.0f, 2.0f, 0.0f, true, false, 0.0f, -4.0f) arcToRelative(2.0f, 2.0f, 0.0f, true, true, 0.0f, -4.0f) curveToRelative(0.746f, 0.0f, 1.656f, 0.394f, 2.0f, 1.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 8.0f) verticalLineToRelative(8.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(16.0f, 16.0f) verticalLineToRelative(-8.0f) lineToRelative(4.0f, 8.0f) verticalLineToRelative(-8.0f) } } .build() return _mathSin!! } private var _mathSin: ImageVector? = null
0
Kotlin
0
1
b037895588c2f62d069c724abe624b67c0889bf9
2,502
compose-icon-collections
MIT License
core/src/integration/kotlin/io/github/serpro69/kfaker/FakerIT.kt
serpro69
174,969,439
false
null
package io.github.serpro69.kfaker import io.github.serpro69.kfaker.provider.FakeDataProvider import io.github.serpro69.kfaker.provider.Money import io.github.serpro69.kfaker.provider.misc.StringProvider import io.kotest.assertions.assertSoftly import io.kotest.core.spec.style.DescribeSpec import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import org.junit.jupiter.api.assertDoesNotThrow import java.io.File import kotlin.reflect.KProperty import kotlin.reflect.KVisibility import kotlin.reflect.full.declaredMemberFunctions import kotlin.reflect.full.declaredMemberProperties import kotlin.reflect.full.isSubtypeOf import kotlin.reflect.full.starProjectedType class FakerIT : DescribeSpec({ describe("every public function in each provider is invoked without exceptions") { val faker = Faker() // Get a list of all publicly visible providers val providers: List<KProperty<*>> = faker::class.declaredMemberProperties.filter { it.visibility == KVisibility.PUBLIC && it.returnType.isSubtypeOf(FakeDataProvider::class.starProjectedType) && it.returnType.classifier != Money::class // Ignore Money provider as it's a special case && it.returnType.classifier != StringProvider::class // Ignore String provider } // Get a list of all publicly visible functions in each provider val providerFunctions = providers.associateBy { provider -> provider.getter.call(faker)!!::class.declaredMemberFunctions.filter { it.visibility == KVisibility.PUBLIC && !it.annotations.any { ann -> ann is Deprecated } } } assertSoftly { providerFunctions.forEach { (functions, provider) -> functions.forEach { context("result value for ${provider.name} ${it.name} is resolved correctly") { val regex = Regex("""#\{.*}|#++""") val value = when (it.parameters.size) { 1 -> it.call(provider.getter.call(faker)).toString() 2 -> { if (it.parameters[1].isOptional) { // optional params are enum typed (see functions in Dune, Finance or Tron, for example) it.callBy(mapOf(it.parameters[0] to provider.getter.call(faker))).toString() } else it.call(provider.getter.call(faker), "").toString() } 3 -> it.call(provider.getter.call(faker), "", "").toString() else -> throw IllegalArgumentException("") } it("resolved value should not contain yaml expression") { if ( !value.contains("#chuck and #norris") && (provider.name != "markdown" && it.name != "headers") && value !in valuesWithHashKey ) { if (value.contains(regex)) { throw AssertionError("Value '$value' for '${provider.name} ${it.name}' should not contain regex '$regex'") } } } it("resolved value should not be empty string") { if (value == "") { throw AssertionError("Value for '${provider.name} ${it.name}' should not be empty string") } } it("resolved value should not contain duplicates") { val values = value.split(" ") // Accounting for some exceptional cases where values are repeated // in resolved expression if ( (provider.name != "coffee" && it.name != "notes") && (provider.name != "onePiece" && it.name != "akumasNoMi") && (provider.name != "lorem" && it.name != "punctuation" && value != " ") && value !in duplicatedValues ) { // Since there's no way to modify assertion message in KotlinTest it's better to throw a custom error if (values.odds() == values.evens()) { throw AssertionError("Value '$value' for '${provider.name} ${it.name}' should not contain duplicates") } } } } } } } } describe("Faker instance is initialized with default locale") { val faker = Faker() val defaultCountryUS = faker.address.defaultCountry() val peruOne = faker.address.countryByCode("PE") context("it is re-initialized with another locale value") { val config = fakerConfig { locale = "nb-NO" } val otherFaker = Faker(config) it("matching keys should be overwritten in the re-initialized dictionary") { val defaultCountryNO = otherFaker.address.defaultCountry() assertSoftly { defaultCountryNO shouldBe "Norge" defaultCountryNO shouldNotBe defaultCountryUS } } it("non-matching default keys should be present in the re-initialized dictionary") { val peruTwo = otherFaker.address.countryByCode("PE") peruOne shouldBe peruTwo } } /* context("it is again re-initialized with default locale") { Faker.init() it("matching keys should be overwritten back to defaults") { val defaultCountry = Faker.address.defaultCountry() val peruThree = Faker.address.countryByCode("PE") assertSoftly { defaultCountry shouldBe defaultCountryUS peruThree shouldBe peruOne } } }*/ } describe("Faker instance is initialized with custom locale") { val localeDir = requireNotNull(this::class.java.classLoader.getResource("locales/")) val locales = File(localeDir.toURI()).listFiles().mapNotNull { if ((it.isFile && it.extension == "yml") || (it.isDirectory && it.name != "en")) { it.nameWithoutExtension } else null } locales.forEach { it("Faker with locale '$it' should be initialized without exceptions") { assertDoesNotThrow { faker { fakerConfig { locale = it } } } } } } }) private fun List<String>.odds() = this.mapIndexedNotNull { index, s -> if (index % 2 == 0) s else null } private fun List<String>.evens() = this.mapIndexedNotNull { index, s -> if (index % 2 != 0) s else null } private val duplicatedValues = listOf( "Tiger! Tiger!", // book#title "Girls Girls", // kPop#girlsGroups "Two Two", // kPop#firstGroups "woof woof", // creature#dog#sound "Duran Duran", // rockBand#name "Li Li", // heroesOfTheStorm#heroes "Dee Dee", // theFreshPrinceOfBelAir#characters "Lola Lola", // cannabis#brands "Hail Hail", // pearlJam#songs "Help Help", // pearlJam#songs "Mr. Mr.", // kPop#thirdGroups "Chitty Chitty Bang Bang", // show#adultMusical "etc. etc.", // marketing#buzzwords "Ook Ook", // ventureBros#character "Mahi Mahi", // food#ingredients "Cous Cous", // food#ingredients "Boom Boom", // superMario#characters "Pom Pom", // superMario#characters "Min Min", // superSmashBros#fighter ) private val valuesWithHashKey = listOf( "A# .NET", // programmingLanguage#name "A# (Axiom)", // programmingLanguage#name "C# – ISO/I EC 23270", //programmingLanguage#name "F#", // programmingLanguage#name "J#", // programmingLanguage#name "M#", // programmingLanguage#name "P#", // programmingLanguage#name "Q# (Microsoft programming language)", // programmingLanguage#name "Visual J#", // programmingLanguage#name "Acoustic #1", // pearlJam#songs "I am downloading some NP# music.", // michaelScott#quotes "Cooler #6", // dragonBall#planets "Cooler #98", // dragonBall#planets "Cooler #256", // dragonBall#planets "Frieza #17", // dragonBall#planets "Frieza #79", // dragonBall#planets "Frieza #448", // dragonBall#planets "tL&^J@24CVF=zP46Lxixk`_a#=o6c5", // device#serial "S#arp", // kPop#firstGroups )
33
null
40
394
01f7d376282911f90d085ac69be42b4e9cdb7f26
8,897
kotlin-faker
MIT License
src/main/kotlin/com/keygenqt/patterns/pattern/behavioral/chain_of_responsibility/ChainValidate.kt
keygenqt
358,650,463
false
null
package com.keygenqt.patterns.pattern.behavioral.chain_of_responsibility class ChainValidate : HandlerBase() { override fun handle(email: String, password: String) { if (email.isBlank() || password.isBlank()) { throw Exception("Error ChainValidate") } else { println("ChainValidate successfully") super.handle(email, password) } } }
0
Kotlin
2
1
44863628b21f1bbacd5014b91d4be5998f8e6bbc
401
skill-patterns
Apache License 2.0
app/src/main/java/red/tetrakube/redcube/domain/models/MinimalActiveHub.kt
TetraKube-Red
854,436,080
false
{"Kotlin": 84315}
package red.tetrakube.redcube.domain.models data class MinimalActiveHub ( val slug: String, val name: String, val token: String, val apiURI: String )
0
Kotlin
0
0
69b1a6d22f581a9aa12cb8d8a52847e61674de54
166
RedCube-Home
MIT License
app/src/main/java/com/dluvian/voyage/ui/components/text/SmallHeader.kt
dluvian
766,355,809
false
{"Kotlin": 1049080}
package com.dluvian.voyage.ui.components.text import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier @Composable fun SmallHeader(header: String, modifier: Modifier = Modifier) { Text(modifier = modifier, text = header, style = MaterialTheme.typography.titleMedium) }
36
Kotlin
4
40
e117d2d00f1e92bc0d5117055169b03906feb479
384
voyage
MIT License
app/src/main/java/com/kylecorry/trail_sense/tools/maps/infrastructure/create/CreateMapFromFileCommand.kt
kylecorry31
215,154,276
false
{"Kotlin": 2589968, "Python": 22919, "HTML": 18863, "Shell": 5290, "CSS": 5120, "JavaScript": 3814, "Batchfile": 2553}
package com.kylecorry.trail_sense.tools.maps.infrastructure.create import android.content.Context import com.kylecorry.andromeda.alerts.loading.ILoadingIndicator import com.kylecorry.trail_sense.shared.extensions.onIO import com.kylecorry.trail_sense.shared.io.UriPicker import com.kylecorry.trail_sense.tools.maps.domain.PhotoMap import com.kylecorry.trail_sense.tools.maps.infrastructure.IMapRepo class CreateMapFromFileCommand( private val context: Context, private val uriPicker: UriPicker, private val repo: IMapRepo, private val loadingIndicator: ILoadingIndicator ) : ICreateMapCommand { override suspend fun execute(): PhotoMap? = onIO { val uri = uriPicker.open(listOf("image/*", "application/pdf")) ?: return@onIO null CreateMapFromUriCommand(context, repo, uri, loadingIndicator).execute() } }
456
Kotlin
66
989
41176d17b498b2dcecbbe808fbe2ac638e90d104
846
Trail-Sense
MIT License
src/util/iterators/filterInPlace.kt
JBWills
291,822,812
false
null
package util.iterators fun <T, R : Comparable<R>> MutableList<T>.filterInPlace( by: (T) -> Boolean ) { var currIndex = 0 while (currIndex < size) { if (by(get(currIndex))) { currIndex += 1 } else { removeAt(currIndex) } } }
0
Kotlin
0
0
569b27c1cb1dc6b2c37e79dfa527b9396c7a2f88
258
processing-sketches
MIT License
app/src/main/java/com/cv4j/app/activity/GridViewFilterActivity.kt
imageprocessor
76,771,374
false
null
package com.cv4j.app.activity import android.content.res.Resources import android.graphics.BitmapFactory import android.os.Bundle import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import com.cv4j.app.R import com.cv4j.app.adapter.GridViewFilterAdapter import com.cv4j.app.app.BaseActivity import com.cv4j.app.ui.DividerGridItemDecoration import kotlinx.android.synthetic.main.activity_gridview_filter.* import java.util.* /** * * @FileName: * com.cv4j.app.activity.GridViewFilterActivity * @author: <NAME> * @date: 2020-05-05 16:21 * @version: V1.0 <描述当前版本功能> */ class GridViewFilterActivity : BaseActivity() { var title: String? = null private val list: MutableList<String> = ArrayList() companion object { private val myPool: RecyclerView.RecycledViewPool = RecyclerView.RecycledViewPool() init { myPool.setMaxRecycledViews(0, 10) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_gridview_filter) initViews() initData() } private fun initViews() { toolbar.title = "< $title" } private fun initData() { val res: Resources = getResources() val filterNames = res.getStringArray(R.array.filterNames) val bitmap = BitmapFactory.decodeResource(res, R.drawable.test_mm) for (filter in filterNames) { list.add(filter) } val manager = GridLayoutManager(this@GridViewFilterActivity, 3) manager.setRecycleChildrenOnDetach(true) recyclerview.layoutManager = manager recyclerview.adapter = GridViewFilterAdapter(list, bitmap) recyclerview.addItemDecoration(DividerGridItemDecoration(this@GridViewFilterActivity)) recyclerview.setRecycledViewPool(myPool) } }
15
Java
153
831
09b371cdfb402ab81c7d9fd2e5667902ea46e334
1,917
cv4j
Apache License 2.0
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/BookFont.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.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.rounded.Icons public val Icons.Bold.BookFont: ImageVector get() { if (_bookFont != null) { return _bookFont!! } _bookFont = Builder(name = "BookFont", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(17.5f, 0.0f) lineTo(6.5f, 0.0f) curveTo(3.47f, 0.0f, 1.0f, 2.47f, 1.0f, 5.5f) verticalLineToRelative(14.0f) curveToRelative(0.0f, 2.48f, 2.02f, 4.5f, 4.5f, 4.5f) horizontalLineToRelative(12.0f) curveToRelative(3.03f, 0.0f, 5.5f, -2.47f, 5.5f, -5.5f) lineTo(23.0f, 5.5f) curveToRelative(0.0f, -3.03f, -2.47f, -5.5f, -5.5f, -5.5f) close() moveTo(20.0f, 5.5f) lineTo(20.0f, 15.0f) lineTo(10.0f, 15.0f) lineTo(10.0f, 3.0f) horizontalLineToRelative(7.5f) curveToRelative(1.38f, 0.0f, 2.5f, 1.12f, 2.5f, 2.5f) close() moveTo(6.5f, 3.0f) horizontalLineToRelative(0.5f) lineTo(7.0f, 15.0f) horizontalLineToRelative(-1.5f) curveToRelative(-0.53f, 0.0f, -1.03f, 0.09f, -1.5f, 0.26f) lineTo(4.0f, 5.5f) curveToRelative(0.0f, -1.38f, 1.12f, -2.5f, 2.5f, -2.5f) close() moveTo(17.5f, 21.0f) lineTo(5.5f, 21.0f) curveToRelative(-0.83f, 0.0f, -1.5f, -0.67f, -1.5f, -1.5f) reflectiveCurveToRelative(0.67f, -1.5f, 1.5f, -1.5f) horizontalLineToRelative(14.5f) verticalLineToRelative(0.5f) curveToRelative(0.0f, 1.38f, -1.12f, 2.5f, -2.5f, 2.5f) close() moveTo(12.15f, 13.5f) curveToRelative(0.42f, 0.0f, 0.8f, -0.27f, 0.95f, -0.67f) lineToRelative(0.3f, -0.83f) horizontalLineToRelative(3.22f) lineToRelative(0.3f, 0.83f) curveToRelative(0.14f, 0.4f, 0.52f, 0.67f, 0.95f, 0.67f) horizontalLineToRelative(0.0f) curveToRelative(0.7f, 0.0f, 1.18f, -0.69f, 0.95f, -1.34f) lineToRelative(-2.39f, -6.66f) curveToRelative(-0.22f, -0.6f, -0.77f, -0.99f, -1.41f, -0.99f) reflectiveCurveToRelative(-1.19f, 0.39f, -1.41f, 1.0f) lineToRelative(-2.39f, 6.66f) curveToRelative(-0.23f, 0.65f, 0.25f, 1.34f, 0.95f, 1.34f) close() moveTo(15.9f, 10.0f) horizontalLineToRelative(-1.79f) lineToRelative(0.9f, -2.51f) lineToRelative(0.9f, 2.51f) close() } } .build() return _bookFont!! } private var _bookFont: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,758
icons
MIT License
demo1/src/main/kotlin/com/example/application/RoomHandler.kt
brandonlamb
140,188,502
false
{"Kotlin": 45565, "C#": 16796, "Shell": 203, "GDScript": 61}
package com.example.application import akka.actor.ActorRef import akka.actor.ActorRef.noSender import com.example.domain.core.player.AddPlayer import net.engio.mbassy.listener.Handler import net.engio.mbassy.listener.Listener import org.pmw.tinylog.Logger @Listener class RoomHandler(private val room: ActorRef) { @Handler fun handle(cmd: AddPlayer) { Logger.info("Handling command") room.tell(cmd, noSender()) } }
0
Kotlin
1
1
88c7fc66e7841318bc94d6fa753f2d783f467275
431
kotlin-smartfoxserver-demos
MIT License
bot/admin/server/src/main/kotlin/model/UserSearchQuery.kt
theopenconversationkit
84,538,053
false
null
/* * Copyright (C) 2017 VSCT * * 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 fr.vsct.tock.bot.admin.model import fr.vsct.tock.bot.admin.user.UserReportQuery import fr.vsct.tock.nlp.admin.model.PaginatedQuery import java.time.ZonedDateTime /** * */ data class UserSearchQuery( val name: String?, val from: ZonedDateTime?, val to: ZonedDateTime?, val flags: Set<String> = emptySet(), val displayTests:Boolean = false) : PaginatedQuery() { fun toUserReportQuery(): UserReportQuery { return UserReportQuery( namespace, applicationName, currentLanguage, start, size, name, from, to, flags.map { it to null }.toMap(), displayTests) } }
163
null
127
475
890f69960997ae9146747d082d808d92ee407fcb
1,372
tock
Apache License 2.0
knowledgebase-gui/src/main/java/ru/usedesk/knowledgebase_gui/screens/categories/IOnCategoryClickListener.kt
usedesk
127,645,126
false
null
package ru.usedesk.knowledgebase_gui.screens.categories internal interface IOnCategoryClickListener { fun onCategoryClick(categoryId: Long, articleTitle: String) }
0
Kotlin
4
3
3ee34eaeeaa0668e94cf8dadf78afad6901b52c4
192
Android_SDK
MIT License
codelabs/image_generation_basic/android/start/app/src/main/java/com/google/mediapipe/examples/imagegeneration/ImageGenerationHelper.kt
googlesamples
555,519,447
false
{"Jupyter Notebook": 940565, "JavaScript": 116392, "Kotlin": 46206, "HTML": 6974, "Python": 1494, "CSS": 1381}
package com.google.mediapipe.examples.imagegeneration import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import com.google.mediapipe.framework.image.BitmapExtractor import com.google.mediapipe.framework.image.MPImage import com.google.mediapipe.tasks.core.BaseOptions import com.google.mediapipe.tasks.core.Delegate import com.google.mediapipe.tasks.vision.imagegenerator.ImageGenerator import com.google.mediapipe.tasks.vision.imagegenerator.ImageGenerator.ConditionOptions import com.google.mediapipe.tasks.vision.imagegenerator.ImageGenerator.ConditionOptions.ConditionType import com.google.mediapipe.tasks.vision.imagegenerator.ImageGenerator.ConditionOptions.EdgeConditionOptions import com.google.mediapipe.tasks.vision.imagegenerator.ImageGenerator.ConditionOptions.FaceConditionOptions import com.google.mediapipe.tasks.vision.imagegenerator.ImageGenerator.ImageGeneratorOptions class ImageGenerationHelper( val context: Context ) { lateinit var imageGenerator: ImageGenerator fun initializeImageGenerator(modelPath: String) { // Step 2 - initialize the image generator } fun setInput(prompt: String, iteration: Int, seed: Int) { // Step 3 - accept inputs } fun generate(prompt: String, iteration: Int, seed: Int): Bitmap { // Step 4 - generate without showing iterations return Bitmap.createBitmap(256, 256, Bitmap.Config.ARGB_8888) } fun execute(showResult: Boolean): Bitmap { // Step 5 - generate with iterations return Bitmap.createBitmap(256, 256, Bitmap.Config.ARGB_8888) } fun close() { try { imageGenerator.close() } catch (e: Exception) { e.printStackTrace() } } }
48
Jupyter Notebook
257
988
0fc6e2b809b13b7cb1de1792288409624f5f6007
1,838
mediapipe
Apache License 2.0
src/test/MinorChordsTest.kt
UrielSarrazin
243,283,788
false
null
import Note.* import Quality.* import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test @DisplayName("Minor Chords") class MinorChordsTest { @Test fun keyOfC() { val notes = listOf(C, D_SHARP, G) val chord = resolve(notes) assertMinor(chord, C) } @Test fun keyOfD() { val notes = listOf(D, F, A) val chord = resolve(notes) assertMinor(chord, D) } @Test fun keyOfE() { val notes = listOf(E, G, B) val chord = resolve(notes) assertMinor(chord, E) } @Test fun keyOfF() { val notes = listOf(F, G_SHARP, C) val chord = resolve(notes) assertMinor(chord, F) } @Test fun keyOfG() { val notes = listOf(G, A_SHARP, D) val chord = resolve(notes) assertMinor(chord, G) } @Test fun keyOfA() { val notes = listOf(A, C, E) val chord = resolve(notes) assertMinor(chord, A) } @Test fun keyOfB() { val notes = listOf(B, D, F_SHARP) val chord = resolve(notes) assertMinor(chord, B) } private fun assertMinor(chord: Chord, expectedKey: Note) { assertChordEquals(chord, expectedKey, MINOR) } }
1
Kotlin
0
0
407934faeafd420244d37be9f03b49b8e1b40bf9
1,266
chords
Apache License 2.0
core/network/src/main/java/com/wei/picquest/core/network/pagingsource/PixabayImagePagingSource.kt
azrael8576
725,428,435
false
{"Kotlin": 346858}
package com.wei.picquest.core.network.pagingsource import androidx.paging.PagingSource import androidx.paging.PagingState import com.wei.picquest.core.network.PqNetworkDataSource import com.wei.picquest.core.network.model.NetworkImageDetail class PixabayImagePagingSource( private val pqNetworkDataSource: PqNetworkDataSource, private val query: String, ) : PagingSource<Int, NetworkImageDetail>() { override suspend fun load(params: LoadParams<Int>): LoadResult<Int, NetworkImageDetail> { try { val currentPage = params.key ?: 1 val response = pqNetworkDataSource.searchImages( query = query, page = currentPage, perPage = 20, ) val endOfPaginationReached = response.hits.isEmpty() return LoadResult.Page( data = response.hits, prevKey = if (currentPage == 1) null else currentPage - 1, nextKey = if (endOfPaginationReached) null else currentPage + 1, ) } catch (exception: Exception) { return LoadResult.Error(exception) } } override fun getRefreshKey(state: PagingState<Int, NetworkImageDetail>): Int? { return state.anchorPosition } }
11
Kotlin
0
8
f6a0698aa72141fc64ee87fd9301e4ac923684de
1,281
picquest
Apache License 2.0
basick/src/main/java/com/mozhimen/basick/elemk/kotlin/properties/VarProperty.kt
mozhimen
353,952,154
false
{"Kotlin": 1460326, "Java": 3916, "AIDL": 964}
package com.mozhimen.basick.elemk.kotlin.properties import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty /** * @ClassName PropertyDelegate * @Description TODO * @Author Mozhimen & <NAME> * @Version 1.0 */ open class VarProperty<T>(default: T) : ReadWriteProperty<Any?, T> { private var _field = default override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { _field = value } override fun getValue(thisRef: Any?, property: KProperty<*>): T { return _field } }
1
Kotlin
6
118
bbdd6ab9b945f04036c27add35c1cbd70c1b49f7
543
SwiftKit
Apache License 2.0
app/src/main/java/com/michaelcarrano/detectivedroid/domain/GetAppListUseCase.kt
michaelcarrano
23,555,546
false
{"Kotlin": 65136, "Ruby": 2946, "Shell": 709}
package com.michaelcarrano.detectivedroid.domain import com.michaelcarrano.detectivedroid.data.AppRepository import com.michaelcarrano.detectivedroid.presentation.model.AppMapper import com.michaelcarrano.detectivedroid.presentation.model.AppUiModel import io.reactivex.Single import javax.inject.Inject class GetAppListUseCase @Inject constructor( private val repo: AppRepository, private val mapper: AppMapper ) { fun loadApps(showSystemApp: Boolean): Single<List<AppUiModel>> = repo.getApplications() .map { apps -> apps.filter { showSystemApp || it.userApp } } .map { apps -> apps.map { mapper.mapToUiModel(it) } } fun searchApps(query: String, showSystemApp: Boolean): Single<List<AppUiModel>> = loadApps(showSystemApp) .map { apps -> apps.filter { it.name.contains(query, true) } } }
9
Kotlin
8
81
59b80d2a4b89d1be224281ad43709f5204fe5b67
945
detective-droid
Apache License 2.0
onsenui-kitchensink/src/main/kotlin/com/example/FormsPage.kt
adamint
331,784,168
true
{"Kotlin": 790864, "JavaScript": 29894, "HTML": 14557, "CSS": 3495, "Handlebars": 402}
package com.example import pl.treksoft.kvision.core.onEvent import pl.treksoft.kvision.form.text.TextInputType import pl.treksoft.kvision.html.Align import pl.treksoft.kvision.html.TAG import pl.treksoft.kvision.html.label import pl.treksoft.kvision.html.span import pl.treksoft.kvision.html.tag import pl.treksoft.kvision.onsenui.core.page import pl.treksoft.kvision.onsenui.form.onsCheckBoxInput import pl.treksoft.kvision.onsenui.form.onsRadioInput import pl.treksoft.kvision.onsenui.form.onsRangeInput import pl.treksoft.kvision.onsenui.form.onsSelectInput import pl.treksoft.kvision.onsenui.form.onsSwitchInput import pl.treksoft.kvision.onsenui.form.onsTextInput import pl.treksoft.kvision.onsenui.grid.col import pl.treksoft.kvision.onsenui.grid.row import pl.treksoft.kvision.onsenui.list.DividerType import pl.treksoft.kvision.onsenui.list.header import pl.treksoft.kvision.onsenui.list.item import pl.treksoft.kvision.onsenui.list.onsList import pl.treksoft.kvision.onsenui.tabbar.Tab import pl.treksoft.kvision.onsenui.visual.icon import pl.treksoft.kvision.state.ObservableValue import pl.treksoft.kvision.state.bind import pl.treksoft.kvision.state.observableSetOf import pl.treksoft.kvision.utils.perc import pl.treksoft.kvision.utils.px object FormsModel { val textValue = ObservableValue<String?>(null) val volume = ObservableValue(25) val switch1 = ObservableValue(true) val selectOptions = listOf("KVision" to "KVision", "Vue" to "Vue", "React" to "React") val select = ObservableValue<String?>("KVision") val vegetables = listOf("Apples", "Bananas", "Oranges") val selectedVegetable = ObservableValue("Bananas") val colors = listOf("Red", "Green", "Blue") val selectedColors = observableSetOf("Green", "Blue") } fun Tab.formsPage(app: App) { page { onsList { header("Text input") item(divider = if (app.isMD) DividerType.NONE else null) { left { icon("md-face", className = "list-item__icon") } center { onsTextInput(placeholder = "Name", floatLabel = true) { maxlength = 20 bind(FormsModel.textValue) { value = it } onEvent { input = { FormsModel.textValue.value = self.value } } } } } item(divider = if (app.isMD) DividerType.NONE else null) { left { icon("fa-question-circle", className = "far list-item__icon") } center { onsTextInput(TextInputType.SEARCH, placeholder = "Search") { maxlength = 20 bind(FormsModel.textValue) { value = it } onEvent { input = { FormsModel.textValue.value = self.value } } } } } item { right { addCssClass("right-label") bind(FormsModel.textValue) { +"Hello ${it ?: "anonymous"}! " icon("fa-hand-spock", size = "lg", className = "far right-icon") } } } header("Range slider") item { +"Adjust the volume:" row { col(align = Align.CENTER, colWidth = 40.px) { lineHeight = 31.px icon("md-volume-down") } col { onsRangeInput(value = FormsModel.volume.value) { width = 100.perc onEvent { input = { FormsModel.volume.value = self.value?.toInt() ?: 0 } } } } col(align = Align.CENTER, colWidth = 40.px) { lineHeight = 31.px icon("md-volume-up") } } span().bind(FormsModel.volume) { content = "Volume: $it" + if (it > 80) " (careful, that's loud)" else "" } } header("Switches") item { center { label(forId = "switch1").bind(FormsModel.switch1) { width = 100.perc content = "Switch (" + (if (it) "on" else "off") + ")" } } right { onsSwitchInput(FormsModel.switch1.value, "switch1").onClick { FormsModel.switch1.value = this.value } } } item { center { label(forId = "switch2").bind(FormsModel.switch1) { width = 100.perc content = if (it) "Enabled switch" else "Disabled switch" } } right { onsSwitchInput(inputId = "switch2").bind(FormsModel.switch1) { disabled = !it } } } header("Select") item { onsSelectInput(FormsModel.selectOptions, FormsModel.select.value) { width = 120.px onEvent { change = { FormsModel.select.value = self.value } } } right { addCssClass("right-label") rich = true bind(FormsModel.select) { if (it != "KVision") tag(TAG.S, it) +"&nbsp;KVision is awesome!" } } } header("Radio buttons") FormsModel.vegetables.forEachIndexed { index, vegetable -> item( tappable = true, divider = if (index == FormsModel.vegetables.size - 1) DividerType.LONG else null ) { left { onsRadioInput(FormsModel.selectedVegetable.value == vegetable, inputId = "radio-$index") { name = "vegetables" onClick { if (this.value) FormsModel.selectedVegetable.value = vegetable } } } center { label(vegetable, forId = "radio-$index") { width = 100.perc } } } } item().bind(FormsModel.selectedVegetable) { content = "I love $it!" } header().bind(FormsModel.selectedColors) { content = "Checkboxes - [${it.joinToString(", ")}]" } FormsModel.colors.forEachIndexed { index, color -> item(tappable = true) { left { onsCheckBoxInput(FormsModel.selectedColors.contains(color), inputId = "checkbox-$index") { onClick { if (this.value) FormsModel.selectedColors.add(color) else FormsModel.selectedColors.remove(color) } } } center { label(color, forId = "checkbox-$index") { width = 100.perc } } } } } } }
0
null
0
0
3bd7767240f299ffd9233bac4963ad31c13750d5
8,326
kvision-examples
MIT License
src/test/kotlin/org/rustSlowTests/RsCompilerSourcesLazyBlockStubCreationTest.kt
intellij-rust
42,619,487
false
{"Gradle Kotlin DSL": 2, "Java Properties": 5, "Markdown": 11, "TOML": 19, "Shell": 2, "Text": 124, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "XML": 140, "Kotlin": 2284, "INI": 3, "ANTLR": 1, "Rust": 362, "YAML": 131, "RenderScript": 1, "JSON": 6, "HTML": 198, "SVG": 136, "JFlex": 1, "Java": 1, "Python": 37}
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rustSlowTests import com.intellij.openapi.vfs.VirtualFile import org.rust.ProjectDescriptor import org.rust.WithStdlibRustProjectDescriptor import org.rust.lang.core.stubs.RsLazyBlockStubCreationTestBase @ProjectDescriptor(WithStdlibRustProjectDescriptor::class) class RsCompilerSourcesLazyBlockStubCreationTest : RsLazyBlockStubCreationTestBase() { fun `test stdlib source`() { val sources = rustSrcDir() checkRustFiles( sources, ignored = setOf("tests", "test", "doc", "etc", "grammar") ) } private fun rustSrcDir(): VirtualFile = WithStdlibRustProjectDescriptor.stdlib!! }
1,841
Kotlin
380
4,528
c6657c02bb62075bf7b7ceb84d000f93dda34dc1
760
intellij-rust
MIT License
src/main/java/ru/hollowhorizon/hollowengine/common/npcs/IHollowNPC.kt
HollowHorizon
586,593,959
false
{"Kotlin": 190114, "Java": 99904}
package ru.hollowhorizon.hollowengine.common.npcs import kotlinx.coroutines.runBlocking import net.minecraft.nbt.CompoundTag import ru.hollowhorizon.hc.client.models.gltf.Transform import ru.hollowhorizon.hc.client.models.gltf.animations.PlayType import ru.hollowhorizon.hc.client.models.gltf.manager.AnimatedEntityCapability import ru.hollowhorizon.hc.common.capabilities.CapabilityStorage import ru.hollowhorizon.hollowengine.common.entities.NPCEntity import ru.hollowhorizon.hollowengine.common.npcs.tasks.HollowNPCTask import ru.hollowhorizon.hollowengine.common.scripting.story.StoryEvent interface IHollowNPC : ICharacter { val npcEntity: NPCEntity override val entityType: NPCEntity get() = npcEntity override val characterName: String get() = npcEntity.displayName.string fun makeTask(task: HollowNPCTask.() -> Unit) { val pendingTask = HollowNPCTask(this) npcEntity.goalQueue.add(pendingTask) //npcEntity.goalSelector.addGoal(0, pendingTask) pendingTask.task() } infix fun play(animation: String) { npcEntity.manager.startAnimation(animation) } fun setTransform(transform: Transform) { npcEntity.getCapability(CapabilityStorage.getCapability(AnimatedEntityCapability::class.java)) .orElseThrow { IllegalStateException("AnimatedEntityCapability not found!") } .transform = transform } fun getTransform() = npcEntity.getCapability(CapabilityStorage.getCapability(AnimatedEntityCapability::class.java)) .orElseThrow { IllegalStateException("AnimatedEntityCapability not found!") } .transform fun play(name: String, priority: Float = 1.0f, playType: PlayType = PlayType.ONCE, speed: Float = 1.0f) { npcEntity.manager.startAnimation(name, priority, playType, speed) } infix fun stop(animation: String) { npcEntity.manager.stopAnimation(animation) } fun waitInteract(icon: IconType) { synchronized(npcEntity.interactionWaiter) { npcEntity.interactionWaiter.wait() } } fun asyncTask(task: HollowNPCTask.() -> Unit) { val pendingTask = HollowNPCTask(this) runBlocking { // Необходимо, чтобы игра не зависла, пока внутренние действия не будут выполнены pendingTask.task() } npcEntity.goalSelector.addGoal(0, pendingTask) pendingTask.async() } } enum class IconType { NONE, DIALOGUE, WARNING, QUESTION }
0
Kotlin
3
3
05a539a76504d0d409071de3d8222aafe93870f3
2,474
HollowEngine
MIT License
src/main/kotlin/me/melijn/melijnbot/database/embed/EmbedColorWrapper.kt
ToxicMushroom
107,187,088
false
null
package me.melijn.melijnbot.database.embed import me.melijn.melijnbot.database.HIGHER_CACHE import me.melijn.melijnbot.database.NORMAL_CACHE class EmbedColorWrapper(private val embedColorDao: EmbedColorDao) { suspend fun getColor(guildId: Long): Int { val cached = embedColorDao.getCacheEntry(guildId, HIGHER_CACHE)?.toInt() if (cached != null) return cached val color = embedColorDao.get(guildId) embedColorDao.setCacheEntry(guildId, color, NORMAL_CACHE) return color } fun setColor(guildId: Long, color: Int) { embedColorDao.set(guildId, color) embedColorDao.setCacheEntry(guildId, color, NORMAL_CACHE) } fun removeColor(guildId: Long) { embedColorDao.remove(guildId) embedColorDao.setCacheEntry(guildId, 0, NORMAL_CACHE) } }
5
Kotlin
22
80
01107bbaad0e343d770b1e4124a5a9873b1bb5bd
829
Melijn
MIT License
ktor-io/common/src/io/ktor/utils/io/core/Copy.kt
jakobkmar
323,173,348
false
null
package io.ktor.utils.io.core import io.ktor.utils.io.core.internal.* /** * Copy all bytes to the [output]. * Depending on actual input and output implementation it could be zero-copy or copy byte per byte. * All regular types such as [ByteReadPacket], [BytePacketBuilder], [AbstractInput] and [AbstractOutput] * are always optimized so no bytes will be copied. */ public fun Input.copyTo(output: Output): Long { if (this !is AbstractInput || output !is AbstractOutput) { // slow-path return copyToFallback(output) } var copied = 0L do { val head = stealAll() if (head == null) { if (prepareRead(1) == null) break continue } copied += head.remainingAll() output.appendChain(head) } while (true) return copied } private fun Input.copyToFallback(output: Output): Long { val buffer = ChunkBuffer.Pool.borrow() var copied = 0L try { do { buffer.resetForWrite() val rc = readAvailable(buffer) if (rc == -1) break copied += rc output.writeFully(buffer) } while (true) return copied } finally { buffer.release(ChunkBuffer.Pool) } }
0
null
0
7
ea35658a05cc085b97297a303a7c0de37efe0024
1,254
ktor
Apache License 2.0
src/test/kotlin/no/nav/familie/ef/sak/infotrygd/InfotrygdPeriodeParser.kt
navikt
206,805,010
false
null
package no.nav.familie.ef.sak.infotrygd import com.github.doyaaaaaken.kotlincsv.dsl.csvReader import no.nav.familie.kontrakter.ef.infotrygd.InfotrygdEndringKode import no.nav.familie.kontrakter.ef.infotrygd.InfotrygdPeriode import java.net.URL import java.time.LocalDate import java.time.format.DateTimeFormatter object InfotrygdPeriodeParser { data class InfotrygdTestData(val input: List<InfotrygdPeriode>, val output: List<InternPeriode>) private const val KEY_TYPE = "type" private const val KEY_STØNAD_ID = "stonad_id" private const val KEY_VEDTAK_ID = "vedtak_id" //private const val KEY_STØNAD_BELØP = "stonad_belop" private const val KEY_INNT_FRADRAG = "innt_fradrag" private const val KEY_SUM_FRADRAG = "sam_fradrag" private const val KEY_NETTO_BELØP = "netto_belop" private const val KEY_STØNAD_FOM = "dato_innv_fom" private const val KEY_STØNAD_TOM = "dato_innv_tom" private const val KEY_DATO_OPPHØR = "dato_opphor" private val DATO_FORMATTERER = DateTimeFormatter.ofPattern("dd.MM.yyyy") fun parse(url: URL): InfotrygdTestData { val fileContent = url.openStream()!! val rows: List<Map<String, String>> = csvReader().readAllWithHeader(fileContent) val inputOutput = rows .map { row -> row.entries.associate { it.key.trim() to it.value } } .map { row -> getValue(row, KEY_TYPE)!! to parseInfotrygdPeriode(row) }.groupBy({ it.first }, { it.second }) return InfotrygdTestData(inputOutput["INPUT"]!!, inputOutput["OUTPUT"]!! .map(InfotrygdPeriode::tilInternPeriode) .sortedBy(InternPeriode::stønadFom)) } private fun parseInfotrygdPeriode(row: Map<String, String>) = InfotrygdPeriode(stønadId = getValue(row, KEY_STØNAD_ID)!!.toLong(), vedtakId = getValue(row, KEY_VEDTAK_ID)!!.toLong(), inntektsreduksjon = getValue(row, KEY_INNT_FRADRAG)!!.toInt(), samordningsfradrag = getValue(row, KEY_SUM_FRADRAG)!!.toInt(), beløp = getValue(row, KEY_NETTO_BELØP)!!.toInt(), stønadFom = LocalDate.parse(getValue(row, KEY_STØNAD_FOM)!!, DATO_FORMATTERER), stønadTom = LocalDate.parse(getValue(row, KEY_STØNAD_TOM)!!, DATO_FORMATTERER), opphørsdato = getValue(row, KEY_DATO_OPPHØR) ?.let { emptyAsNull(it) } ?.let { LocalDate.parse(it, DATO_FORMATTERER) }, personIdent = "", brukerId = "", kode = InfotrygdEndringKode.ENDRING_BEREGNINGSGRUNNLAG, startDato = LocalDate.now(), stønadBeløp = 0 // kanskje fjerne ? ) private fun getValue(row: Map<String, String>, key: String) = row[key]?.trim() private fun emptyAsNull(s: String): String? = s.ifEmpty { null } }
8
Kotlin
2
0
cc43ffc5d00f8a2ff011cf20d7c2e76844164477
3,308
familie-ef-sak
MIT License
renshi-fragments/src/test/kotlin/com/damianchodorek/renshi/utils/impl/StateTestImpl.kt
DamianChodorek
129,797,476
false
null
package com.damianchodorek.renshi.utils.impl import com.damianchodorek.renshi.store.state.State /** * @author <NAME> */ data class StateTestImpl( override val lastActionMark: Any? = null ) : State { override fun clone(lastActionMark: Any?): State = copy(lastActionMark = lastActionMark) }
0
Kotlin
0
2
c72df09782cdb9483bbde3503a167f2d5bc760b4
305
renshi-redux
Apache License 2.0
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/filled/ImageGlobe.kt
Konyaco
574,321,009
false
null
package com.konyaco.fluent.icons.filled import androidx.compose.ui.graphics.vector.ImageVector import com.konyaco.fluent.icons.Icons import com.konyaco.fluent.icons.fluentIcon import com.konyaco.fluent.icons.fluentPath public val Icons.Filled.ImageGlobe: ImageVector get() { if (_imageGlobe != null) { return _imageGlobe!! } _imageGlobe = fluentIcon(name = "Filled.ImageGlobe") { fluentPath { moveTo(5.0f, 6.0f) curveToRelative(0.05f, -1.41f, 0.25f, -2.67f, 0.56f, -3.58f) curveToRelative(0.17f, -0.52f, 0.36f, -0.9f, 0.55f, -1.14f) curveToRelative(0.2f, -0.25f, 0.33f, -0.28f, 0.39f, -0.28f) reflectiveCurveToRelative(0.2f, 0.03f, 0.39f, 0.28f) curveToRelative(0.19f, 0.24f, 0.38f, 0.62f, 0.55f, 1.14f) curveToRelative(0.3f, 0.91f, 0.51f, 2.17f, 0.55f, 3.58f) horizontalLineTo(5.01f) close() } fluentPath { moveTo(4.61f, 2.1f) curveToRelative(0.1f, -0.32f, 0.23f, -0.62f, 0.37f, -0.89f) arcTo(5.5f, 5.5f, 0.0f, false, false, 1.02f, 6.0f) horizontalLineToRelative(2.99f) curveToRelative(0.04f, -1.5f, 0.26f, -2.87f, 0.6f, -3.9f) close() } fluentPath { moveTo(8.39f, 2.1f) curveToRelative(-0.1f, -0.32f, -0.23f, -0.62f, -0.37f, -0.89f) arcTo(5.5f, 5.5f, 0.0f, false, true, 11.98f, 6.0f) horizontalLineTo(8.99f) curveToRelative(-0.04f, -1.5f, -0.26f, -2.87f, -0.6f, -3.9f) close() } fluentPath { moveTo(9.0f, 7.0f) horizontalLineToRelative(2.98f) arcToRelative(5.5f, 5.5f, 0.0f, false, true, -3.96f, 4.79f) curveToRelative(0.14f, -0.27f, 0.26f, -0.57f, 0.37f, -0.89f) curveToRelative(0.34f, -1.03f, 0.56f, -2.4f, 0.6f, -3.9f) close() } fluentPath { moveTo(6.89f, 11.72f) curveToRelative(-0.2f, 0.25f, -0.33f, 0.28f, -0.39f, 0.28f) reflectiveCurveToRelative(-0.2f, -0.03f, -0.39f, -0.28f) arcToRelative(3.84f, 3.84f, 0.0f, false, true, -0.55f, -1.14f) curveToRelative(-0.3f, -0.91f, -0.51f, -2.17f, -0.55f, -3.58f) horizontalLineToRelative(2.98f) arcToRelative(12.92f, 12.92f, 0.0f, false, true, -0.55f, 3.58f) curveToRelative(-0.17f, 0.52f, -0.36f, 0.9f, -0.55f, 1.14f) close() } fluentPath { moveTo(1.02f, 7.0f) arcToRelative(5.5f, 5.5f, 0.0f, false, false, 3.96f, 4.79f) arcToRelative(6.13f, 6.13f, 0.0f, false, true, -0.37f, -0.89f) curveToRelative(-0.34f, -1.03f, -0.56f, -2.4f, -0.6f, -3.9f) horizontalLineTo(1.02f) close() } fluentPath { moveTo(15.75f, 7.5f) arcToRelative(0.75f, 0.75f, 0.0f, true, true, 0.0f, 1.5f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.0f, -1.5f) close() } fluentPath { moveTo(6.5f, 13.0f) arcToRelative(6.5f, 6.5f, 0.0f, false, false, 5.48f, -10.0f) horizontalLineToRelative(5.77f) curveTo(19.55f, 3.0f, 21.0f, 4.46f, 21.0f, 6.25f) verticalLineToRelative(11.5f) curveToRelative(0.0f, 0.63f, -0.18f, 1.21f, -0.49f, 1.7f) lineToRelative(-6.93f, -6.8f) lineToRelative(-0.13f, -0.12f) curveToRelative(-0.83f, -0.7f, -2.06f, -0.7f, -2.9f, 0.0f) lineToRelative(-0.13f, 0.12f) lineToRelative(-6.93f, 6.8f) curveToRelative(-0.31f, -0.49f, -0.49f, -1.07f, -0.49f, -1.7f) verticalLineToRelative(-5.77f) arcTo(6.47f, 6.47f, 0.0f, false, false, 6.5f, 13.0f) close() moveTo(15.75f, 6.0f) arcToRelative(2.25f, 2.25f, 0.0f, true, false, 0.0f, 4.5f) arcToRelative(2.25f, 2.25f, 0.0f, false, false, 0.0f, -4.5f) close() } fluentPath { moveToRelative(11.47f, 13.72f) lineToRelative(0.09f, -0.07f) curveToRelative(0.26f, -0.2f, 0.61f, -0.2f, 0.87f, -0.01f) lineToRelative(0.1f, 0.08f) lineToRelative(6.92f, 6.8f) curveToRelative(-0.5f, 0.3f, -1.08f, 0.48f, -1.7f, 0.48f) horizontalLineTo(6.25f) curveToRelative(-0.62f, 0.0f, -1.2f, -0.18f, -1.7f, -0.48f) lineToRelative(6.92f, -6.8f) close() } } return _imageGlobe!! } private var _imageGlobe: ImageVector? = null
1
null
3
83
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
5,061
compose-fluent-ui
Apache License 2.0
core/src/main/java/com/infinitepower/newquiz/core/math/evaluator/internal/Expr.kt
joaomanaia
443,198,327
false
null
package com.infinitepower.newquiz.core.math.evaluator.internal import java.math.BigDecimal internal sealed class Expr { abstract fun <R> accept(visitor: ExprVisitor<R>): R } internal class AssignExpr( val name: Token, val value: Expr ) : Expr() { override fun <R> accept(visitor: ExprVisitor<R>): R { return visitor.visitAssignExpr(this) } } internal class LogicalExpr( val left: Expr, val operator: Token, val right: Expr ) : Expr() { override fun <R> accept(visitor: ExprVisitor<R>): R { return visitor.visitLogicalExpr(this) } } internal class BinaryExpr( val left: Expr, val operator: Token, val right: Expr ) : Expr() { override fun <R> accept(visitor: ExprVisitor<R>): R { return visitor.visitBinaryExpr(this) } } internal class UnaryExpr( val operator: Token, val right: Expr ) : Expr() { override fun <R> accept(visitor: ExprVisitor<R>): R { return visitor.visitUnaryExpr(this) } } internal class LeftExpr( val operator: Token, val left: Expr ) : Expr() { override fun <R> accept(visitor: ExprVisitor<R>): R { return visitor.visitLeftExpr(this) } } internal class CallExpr( val name: String, val arguments: List<Expr> ) : Expr() { override fun <R> accept(visitor: ExprVisitor<R>): R { return visitor.visitCallExpr(this) } } internal class LiteralExpr(val value: BigDecimal) : Expr() { override fun <R> accept(visitor: ExprVisitor<R>): R { return visitor.visitLiteralExpr(this) } } internal class VariableExpr(val name: Token) : Expr() { override fun <R> accept(visitor: ExprVisitor<R>): R { return visitor.visitVariableExpr(this) } } internal class GroupingExpr(val expression: Expr) : Expr() { override fun <R> accept(visitor: ExprVisitor<R>): R { return visitor.visitGroupingExpr(this) } } internal interface ExprVisitor<out R> { fun visitAssignExpr(expr: AssignExpr): R fun visitLogicalExpr(expr: LogicalExpr): R fun visitBinaryExpr(expr: BinaryExpr): R fun visitUnaryExpr(expr: UnaryExpr): R fun visitLeftExpr(expr: LeftExpr): R fun visitCallExpr(expr: CallExpr): R fun visitLiteralExpr(expr: LiteralExpr): R fun visitVariableExpr(expr: VariableExpr): R fun visitGroupingExpr(expr: GroupingExpr): R }
388
null
30
99
4741a80f1db8073c7d33499523117b446489bbf0
2,372
newquiz
Apache License 2.0
src/main/kotlin/io/github/ydwk/ydwk/entities/guild/enums/MessageNotificationLevel.kt
YDWK
527,250,343
false
null
/* * Copyright 2022 YDWK inc. * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.ydwk.ydwk.entities.guild.enums enum class MessageNotificationLevel(private val value: Int) { /** Members will receive notifications for all messages by default. */ ALL_MESSAGES(0), /** Members will receive notifications only for messages that @mention them by default. */ ONLY_MENTIONS(1), /** An unknown value. */ UNKNOWN(-1); companion object { /** * The [MessageNotificationLevel] by its [value]. * * @param value The value to get the [MessageNotificationLevel] by. * @return The [MessageNotificationLevel] by the given [value]. */ fun fromInt(value: Int): MessageNotificationLevel { return values().firstOrNull { it.value == value } ?: UNKNOWN } } /** * The value of the [MessageNotificationLevel]. * * @return The value of the [MessageNotificationLevel]. */ fun getValue(): Int { return value } }
9
null
1
2
7e479b29ddca2e0d9093ab8c5dae6892f5640d80
1,577
YDWK
Apache License 2.0
feature_book_details/src/androidTest/java/com/allsoftdroid/feature/book_details/presentation/utils/FakeTrackListRepository.kt
pravinyo
209,936,085
false
null
package com.allsoftdroid.feature.book_details.presentation.utils import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.allsoftdroid.feature.book_details.data.model.TrackFormat import com.allsoftdroid.feature.book_details.domain.model.AudioBookTrackDomainModel import com.allsoftdroid.feature.book_details.domain.repository.ITrackListRepository class FakeTrackListRepository : ITrackListRepository { private var trackList = MutableLiveData<List<AudioBookTrackDomainModel>>() override suspend fun loadTrackListData(format: TrackFormat) { val tracks = mutableListOf<AudioBookTrackDomainModel>() tracks.add(AudioBookTrackDomainModel(filename = "sample.mp3",title = "sample track",trackNumber = 0,trackAlbum = "Intro", length = "1",format = "64KB",size = "2MB",trackId = "1")) tracks.add(AudioBookTrackDomainModel(filename = "sample2.mp3",title = "sample2 track",trackNumber = 1,trackAlbum = "Intro", length = "1",format = "64KB",size = "2MB",trackId = "2")) trackList.value = tracks } override fun getTrackList(): LiveData<List<AudioBookTrackDomainModel>> { return trackList } }
3
Kotlin
4
12
8358f69c0cf8dbde18904b0c3a304ec89b518c9b
1,200
AudioBook
MIT License
src/test/kotlin/no/nav/pensjon/kalkulator/simulering/api/map/SimuleringMapperTest.kt
navikt
596,104,195
false
{"Kotlin": 591963, "Java": 1630, "Dockerfile": 153}
package no.nav.pensjon.kalkulator.simulering.api.map import no.nav.pensjon.kalkulator.general.Alder import no.nav.pensjon.kalkulator.general.Uttaksgrad import no.nav.pensjon.kalkulator.person.Sivilstand import no.nav.pensjon.kalkulator.simulering.* import no.nav.pensjon.kalkulator.simulering.api.dto.* import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import java.time.LocalDate class SimuleringMapperTest { @Test fun `resultatDto maps domain object to data transfer object`() { val dto = SimuleringMapper.resultatDto( Simuleringsresultat( alderspensjon = listOf( SimulertAlderspensjon(67, 1001), SimulertAlderspensjon(68, 1002) ), afpPrivat = listOf( SimulertAfpPrivat(62, 2001), SimulertAfpPrivat(63, 2002) ) ) ) with(dto.alderspensjon[0]) { assertEquals(67, alder) assertEquals(1001, beloep) } with(dto.alderspensjon[1]) { assertEquals(68, alder) assertEquals(1002, beloep) } with(dto.afpPrivat[0]) { assertEquals(62, alder) assertEquals(2001, beloep) } with(dto.afpPrivat[1]) { assertEquals(63, alder) assertEquals(2002, beloep) } assertTrue(dto.vilkaarErOppfylt) } @Test fun `fromIngressSimuleringSpecV2 maps data transfer object to domain object`() { val spec: ImpersonalSimuleringSpec = SimuleringMapper.fromIngressSimuleringSpecV2( IngressSimuleringSpecV2( simuleringstype = SimuleringType.ALDERSPENSJON_MED_AFP_PRIVAT, foedselsdato = LocalDate.of(1969, 3, 2), epsHarInntektOver2G = true, aarligInntektFoerUttakBeloep = 123_000, sivilstand = Sivilstand.REGISTRERT_PARTNER, gradertUttak = IngressSimuleringGradertUttakV2( grad = 40, uttaksalder = IngressSimuleringAlderV2(aar = 68, maaneder = 2), aarligInntektVsaPensjonBeloep = 234_000 ), heltUttak = IngressSimuleringHeltUttakV2( uttaksalder = IngressSimuleringAlderV2(70, 4), aarligInntektVsaPensjon = IngressSimuleringInntektV2( beloep = 1_000, sluttAlder = IngressSimuleringAlderV2(aar = 75, maaneder = 0) ), ) ) ) with(spec) { assertEquals(SimuleringType.ALDERSPENSJON_MED_AFP_PRIVAT, simuleringType) assertTrue(epsHarInntektOver2G) assertEquals(123_000, forventetAarligInntektFoerUttak) assertEquals(Sivilstand.REGISTRERT_PARTNER, sivilstand) with(gradertUttak!!) { assertEquals(Uttaksgrad.FOERTI_PROSENT, grad) assertEquals(234_000, aarligInntekt) with(uttakFomAlder) { assertEquals(68, aar) assertEquals(2, maaneder) } with(uttakFomAlder) { assertEquals(68, aar) assertEquals(2, maaneder) } } with(heltUttak) { with(uttakFomAlder!!) { assertEquals(70, aar) assertEquals(4, maaneder) } with(inntekt!!) { assertEquals(1_000, aarligBeloep) with(tomAlder) { assertEquals(75, aar) assertEquals(0, maaneder) } } assertEquals(Alder(70, 4), uttakFomAlder) } } } }
3
Kotlin
0
0
759755891dc9ceca519515c7b54b5543fcd76088
3,968
pensjonskalkulator-backend
MIT License
app/src/main/java/com/dicoding/asclepius/data/retrofit/ApiService.kt
xirf
791,855,561
false
{"Kotlin": 38984}
package com.dicoding.asclepius.data.retrofit import com.dicoding.asclepius.data.response.NewsResponse import retrofit2.Call import retrofit2.http.GET interface ApiService { @GET("top-headlines?country=id&category=health&q=kanker") fun getNews(): Call<NewsResponse> }
0
Kotlin
0
0
74d5bfae46ec8328f7c02e05f3d7b6e7d698b2fe
276
asclepius
MIT License
app/src/main/java/com/shannan/converter/data/source/local/RatesDatabase.kt
mohamedshanan
359,087,790
false
null
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.shannan.converter.data.source.local import androidx.room.Database import androidx.room.RoomDatabase import com.shannan.converter.data.Rate /** * The Room Database that contains the Rates table. * * Note that exportSchema should be true in production databases. */ @Database(entities = [Rate::class], version = 1, exportSchema = false) abstract class RatesDatabase : RoomDatabase() { abstract fun ratesDao(): RatesDao }
0
Kotlin
0
0
64fa3f1a2a11e8b56d8e7ae7daf224d17392b79c
1,063
CurrencyConverter
Apache License 2.0
compose/ui/ui-text/src/androidAndroidTest/kotlin/androidx/compose/ui/text/font/AndroidFontTest.kt
RikkaW
389,105,112
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text.font import android.content.Context import android.os.ParcelFileDescriptor import androidx.compose.ui.text.ExperimentalTextApi import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import androidx.test.platform.app.InstrumentationRegistry import com.google.common.truth.Truth.assertThat import org.junit.After import org.junit.Before import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith import java.io.File @MediumTest @RunWith(AndroidJUnit4::class) @OptIn(ExperimentalTextApi::class) class AndroidFontTest { private val context = InstrumentationRegistry.getInstrumentation().context private val assetFontPath = "subdirectory/asset_font.ttf" private val tmpFontPath = "tmp_file_font.ttf" @Before fun setup() { deleteFile() writeFile() } @After fun cleanupAfter() { deleteFile() } private fun deleteFile() { val fontFile = File(context.filesDir, tmpFontPath) if (fontFile.exists()) { fontFile.delete() } } private fun writeFile() { context.assets.open(assetFontPath).use { input -> val bytes = input.readBytes() context.openFileOutput(tmpFontPath, Context.MODE_PRIVATE).use { output -> output.write(bytes) } } } @Test fun test_load_from_assets() { val font = Font(assetManager = context.assets, path = assetFontPath) as AndroidFont assertThat(font.typeface).isNotNull() } @Test fun test_load_from_file() { val fontFile = File(context.filesDir, tmpFontPath) val font = Font(file = fontFile) as AndroidFont assertThat(font.typeface).isNotNull() } @Ignore @Test @MediumTest fun test_load_from_file_descriptor() { context.openFileInput(tmpFontPath).use { inputStream -> val font = Font(ParcelFileDescriptor.dup(inputStream.fd)) as AndroidFont val typeface = font.typeface assertThat(typeface).isNotNull() } } }
0
null
0
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
2,743
androidx
Apache License 2.0
ananas/src/main/java/iamutkarshtiwari/github/io/ananas/editimage/ImageEditorIntentBuilder.kt
iamutkarshtiwari
125,080,173
false
null
package iamutkarshtiwari.github.io.ananas.editimage import android.content.Context import android.content.Intent class ImageEditorIntentBuilder @JvmOverloads constructor(private val context: Context, private val sourcePath: String?, private val outputPath: String?, private val intent: Intent = Intent( context, EditImageActivity::class.java ) ) { fun withAddText(): ImageEditorIntentBuilder { intent.putExtra(ADD_TEXT_FEATURE, true) return this } fun withPaintFeature(): ImageEditorIntentBuilder { intent.putExtra(PAINT_FEATURE, true) return this } fun withFilterFeature(): ImageEditorIntentBuilder { intent.putExtra(FILTER_FEATURE, true) return this } fun withRotateFeature(): ImageEditorIntentBuilder { intent.putExtra(ROTATE_FEATURE, true) return this } fun withCropFeature(): ImageEditorIntentBuilder { intent.putExtra(CROP_FEATURE, true) return this } fun withBrightnessFeature(): ImageEditorIntentBuilder { intent.putExtra(BRIGHTNESS_FEATURE, true) return this } fun withSaturationFeature(): ImageEditorIntentBuilder { intent.putExtra(SATURATION_FEATURE, true) return this } fun withBeautyFeature(): ImageEditorIntentBuilder { intent.putExtra(BEAUTY_FEATURE, true) return this } fun withStickerFeature(): ImageEditorIntentBuilder { intent.putExtra(STICKER_FEATURE, true) return this } fun withSourcePath(sourcePath: String): ImageEditorIntentBuilder { intent.putExtra(SOURCE_PATH, sourcePath) return this } fun withOutputPath(outputPath: String): ImageEditorIntentBuilder { intent.putExtra(OUTPUT_PATH, outputPath) return this } fun forcePortrait(isForcePortrait: Boolean): ImageEditorIntentBuilder { intent.putExtra(FORCE_PORTRAIT, isForcePortrait) return this } @Throws(Exception::class) fun build(): Intent { if (sourcePath.isNullOrBlank()) { throw Exception("Output image path required. Use withOutputPath(path) to provide the output image path.") } else { intent.putExtra(SOURCE_PATH, sourcePath) } if (outputPath.isNullOrBlank()) { throw Exception("Output image path required. Use withOutputPath(path) to provide the output image path.") } else { intent.putExtra(OUTPUT_PATH, outputPath) } return intent } companion object { const val ADD_TEXT_FEATURE = "add_text_feature" const val PAINT_FEATURE = "paint_feature" const val FILTER_FEATURE = "filter_feature" const val ROTATE_FEATURE = "rotate_feature" const val CROP_FEATURE = "crop_feature" const val BRIGHTNESS_FEATURE = "brightness_feature" const val SATURATION_FEATURE = "saturation_feature" const val BEAUTY_FEATURE = "beauty_feature" const val STICKER_FEATURE = "sticker_feature" const val SOURCE_PATH = "source_path" const val OUTPUT_PATH = "output_path" const val FORCE_PORTRAIT = "force_portrait" } }
43
null
106
235
4ca9b159ec798946b437183f69eba89b823ae561
3,560
Ananas
MIT License
ktx-account-annotations/src/main/java/co/windly/ktxaccount/annotation/DefaultDouble.kt
tommus
220,719,220
false
null
package co.windly.ktxaccount.annotation /** * Indicates a wrapper methods for given Double property should be generated. * <p> * One can configure what default value will be used in case if given property was * not set previously, */ @Target(AnnotationTarget.FIELD) annotation class DefaultDouble( /** * The default value for given Double property. * @return the default value for given Double property */ val value: Double )
1
Kotlin
3
3
f379ee6d1528af6a9eea8ccac01a124e835b0d6e
446
ktx-account
Apache License 2.0
plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/templates/JsClientTemplate.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.tools.projectWizard.templates import org.jetbrains.annotations.NonNls import org.jetbrains.kotlin.tools.projectWizard.WizardGradleRunConfiguration import org.jetbrains.kotlin.tools.projectWizard.WizardRunConfiguration import org.jetbrains.kotlin.tools.projectWizard.core.Reader import org.jetbrains.kotlin.tools.projectWizard.core.buildList import org.jetbrains.kotlin.tools.projectWizard.core.safeAs import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.* import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle.* import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle.multiplatform.DefaultTargetConfigurationIR import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.* import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemPlugin import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ModuleSubType import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ModuleType import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ProjectKind import org.jetbrains.kotlin.tools.projectWizard.plugins.projectName import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Module import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.ModuleKind import org.jetbrains.kotlin.tools.projectWizard.transformers.interceptors.TemplateInterceptor import org.jetbrains.kotlin.tools.projectWizard.transformers.interceptors.interceptTemplate abstract class JsClientTemplate : Template() { override fun isApplicableTo(module: Module, projectKind: ProjectKind, reader: Reader): Boolean = module.configurator.moduleType == ModuleType.js && when (module.configurator) { JsBrowserTargetConfigurator, MppLibJsBrowserTargetConfigurator -> true BrowserJsSinglePlatformModuleConfigurator -> { with(reader) { inContextOfModuleConfigurator(module, module.configurator) { JSConfigurator.kind.reference.notRequiredSettingValue == JsTargetKind.APPLICATION } } } else -> false } override fun Reader.createRunConfigurations(module: ModuleIR): List<WizardRunConfiguration> = buildList { if (module.originalModule.kind == ModuleKind.singlePlatformJsBrowser) { +WizardGradleRunConfiguration( org.jetbrains.kotlin.tools.projectWizard.KotlinNewProjectWizardBundle.message("module.template.js.simple.run.configuration.dev"), "browserDevelopmentRun", listOf("--continuous") ) +WizardGradleRunConfiguration( org.jetbrains.kotlin.tools.projectWizard.KotlinNewProjectWizardBundle.message("module.template.js.simple.run.configuration.prod"), "browserProductionRun", listOf("--continuous") ) } } override fun Reader.createInterceptors(module: ModuleIR): List<TemplateInterceptor> = buildList { +interceptTemplate(KtorServerTemplate) { applicableIf { buildFileIR -> if (module !is MultiplatformModuleIR) return@applicableIf false val tasks = buildFileIR.irsOfTypeOrNull<GradleConfigureTaskIR>() ?: return@applicableIf true tasks.none { it.taskAccess.safeAs<GradleNamedTaskAccessIR>()?.name?.endsWith("Jar") == true } } interceptAtPoint(template.routes) { value -> if (value.isNotEmpty()) return@interceptAtPoint value buildList { +value +""" static("/static") { resources() } """.trimIndent() } } interceptAtPoint(template.elements) { value -> if (value.isNotEmpty()) return@interceptAtPoint value buildList { +value +""" div { id = "root" } """.trimIndent() +"""script(src = "/static/${indexFileName(module.originalModule)}.js") {}""" } } transformBuildFile { buildFileIR -> val jsSourceSetName = module.safeAs<MultiplatformModuleIR>()?.name ?: return@transformBuildFile null val jvmTarget = buildFileIR.targets.firstOrNull { target -> target.safeAs<DefaultTargetConfigurationIR>()?.targetAccess?.type == ModuleSubType.jvm } as? DefaultTargetConfigurationIR ?: return@transformBuildFile null val jvmTargetName = jvmTarget.targetName val distributionTaskName = "$jsSourceSetName$BROWSER_DISTRIBUTION_TASK_SUFFIX" val jvmProcessResourcesTaskAccess = GradleNamedTaskAccessIR( "${jvmTargetName}ProcessResources", "Copy" ) val jvmProcessResourcesTaskConfiguration = run { val distributionTaskVariable = CreateGradleValueIR( distributionTaskName, GradleNamedTaskAccessIR(distributionTaskName) ) val from = GradleCallIr( "from", listOf( GradlePropertyAccessIR(distributionTaskName) ) ) GradleConfigureTaskIR( jvmProcessResourcesTaskAccess, irs = listOf( distributionTaskVariable, from ) ) } val jvmJarTaskAccess = GradleNamedTaskAccessIR( "${jvmTargetName}Jar", "Jar" ) val runTaskConfiguration = run { val taskAccess = GradleNamedTaskAccessIR("run", "JavaExec") val classpath = GradleCallIr("classpath", listOf(jvmJarTaskAccess)) GradleConfigureTaskIR( taskAccess, dependsOn = listOf(jvmJarTaskAccess), irs = listOf(classpath) ) } buildFileIR.withIrs(jvmProcessResourcesTaskConfiguration, runTaskConfiguration) } } } override fun Reader.getAdditionalSettings(module: Module): Map<String, Any> = withSettingsOf(module) { jsSettings(module) } protected fun Reader.jsSettings(module: Module): Map<String, String> { return mapOf("indexFile" to indexFileName(module)) } private fun Reader.indexFileName( module: Module ): String { val buildFiles = BuildSystemPlugin.buildFiles.propertyValue return if (buildFiles.size == 1) projectName else module.parent?.name ?: module.name } protected fun hasKtorServNeighbourTarget(module: ModuleIR) = module.safeAs<MultiplatformModuleIR>() ?.neighbourTargetModules() .orEmpty() .any { it.template is KtorServerTemplate } companion object { @NonNls private const val BROWSER_DISTRIBUTION_TASK_SUFFIX = "BrowserDistribution" } }
191
null
4372
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
7,707
intellij-community
Apache License 2.0
app/src/main/kotlin/com/absinthe/libchecker/features/applist/detail/ui/view/AppPropItemView.kt
LibChecker
248,400,799
false
null
package com.absinthe.libchecker.view.detail import android.content.Context import android.util.TypedValue import android.view.ContextThemeWrapper import android.view.ViewGroup import android.widget.ImageView import androidx.appcompat.widget.AppCompatImageButton import androidx.appcompat.widget.AppCompatTextView import androidx.core.view.isVisible import com.absinthe.libchecker.R import com.absinthe.libchecker.utils.extensions.getDrawableByAttr import com.absinthe.libchecker.view.AViewGroup class AppPropItemView(context: Context) : AViewGroup(context) { private val tip = AppCompatTextView( ContextThemeWrapper( context, R.style.TextView_SansSerif ) ).apply { layoutParams = LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, -1) setTextSize(TypedValue.COMPLEX_UNIT_SP, 11f) alpha = 0.85f } val key = AppCompatTextView( ContextThemeWrapper( context, R.style.TextView_SansSerifCondensedMedium ) ).apply { layoutParams = LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) setTextSize(TypedValue.COMPLEX_UNIT_SP, 13f) } val value = AppCompatTextView( ContextThemeWrapper( context, R.style.TextView_SansSerifCondensedMedium ) ).apply { layoutParams = LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) setTextSize(TypedValue.COMPLEX_UNIT_SP, 13f) alpha = 0.65f } val linkToIcon = AppCompatImageButton(context).apply { layoutParams = LayoutParams(24.dp, 24.dp).also { it.marginStart = 8.dp } scaleType = ImageView.ScaleType.CENTER_CROP setImageResource(R.drawable.ic_outline_change_circle_24) setBackgroundDrawable(context.getDrawableByAttr(com.google.android.material.R.attr.selectableItemBackgroundBorderless)) isVisible = false } init { addView(tip) addView(key) addView(value) addView(linkToIcon) } fun setTipText(text: String) { tip.text = text tip.layoutParams = tip.layoutParams.apply { height = if (text.isEmpty()) { -1 } else { ViewGroup.LayoutParams.WRAP_CONTENT } } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val textWidth = measuredWidth - paddingStart - paddingEnd tip.measure(textWidth.toExactlyMeasureSpec(), tip.defaultHeightMeasureSpec(this)) key.measure(textWidth.toExactlyMeasureSpec(), key.defaultHeightMeasureSpec(this)) value.measure(textWidth.toExactlyMeasureSpec(), value.defaultHeightMeasureSpec(this)) linkToIcon.autoMeasure() setMeasuredDimension( measuredWidth, paddingTop + paddingBottom + tip.measuredHeight + key.measuredHeight + value.measuredHeight ) } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { tip.layout(paddingStart, paddingTop) key.layout(paddingStart, tip.bottom) value.layout(paddingStart, key.bottom) linkToIcon.layout(paddingEnd, linkToIcon.toVerticalCenter(this), true) } }
38
null
307
4,430
6a05bb1cff75020fd2f9f2421dfdb25b4e2cc0a9
3,113
LibChecker
Apache License 2.0
eco-core/core-plugin/src/main/kotlin/com/willfp/eco/internal/spigot/data/profiles/ProfileWriter.kt
Auxilor
325,856,799
false
{"Kotlin": 784230, "Java": 740080}
package com.willfp.eco.internal.spigot.data.profiles import com.willfp.eco.core.EcoPlugin import com.willfp.eco.core.data.keys.PersistentDataKey import java.util.UUID import java.util.concurrent.ConcurrentHashMap /* The profile writer exists as an optimization to batch writes to the database. This is necessary because values frequently change multiple times per tick, and we don't want to write to the database every time a value changes. Instead, we only commit the last value that was set every interval (default 1 tick). */ class ProfileWriter( private val plugin: EcoPlugin, private val handler: ProfileHandler ) { private val saveInterval = plugin.configYml.getInt("save-interval").toLong() private val autosaveInterval = plugin.configYml.getInt("autosave-interval").toLong() private val valuesToWrite = ConcurrentHashMap<WriteRequest<*>, Any>() fun <T : Any> write(uuid: UUID, key: PersistentDataKey<T>, value: T) { valuesToWrite[WriteRequest(uuid, key)] = value } fun startTickingSaves() { plugin.scheduler.runTimer(20, saveInterval) { val iterator = valuesToWrite.iterator() while (iterator.hasNext()) { val (request, value) = iterator.next() iterator.remove() val dataHandler = if (request.key.isSavedLocally) handler.localHandler else handler.defaultHandler // Pass the value to the data handler @Suppress("UNCHECKED_CAST") dataHandler.write(request.uuid, request.key as PersistentDataKey<Any>, value) } } } fun startTickingAutosave() { plugin.scheduler.runTimer(autosaveInterval, autosaveInterval) { if (handler.localHandler.shouldAutosave()) { handler.localHandler.save() } } } private data class WriteRequest<T>(val uuid: UUID, val key: PersistentDataKey<T>) } val PersistentDataKey<*>.isSavedLocally: Boolean get() = this.isLocal || EcoPlugin.getPlugin(this.key.namespace)?.isUsingLocalStorage == true
82
Kotlin
53
156
81de46a1c122a3cd6be06696b5b02d55fd9a73e5
2,097
eco
MIT License
base/src/main/kotlin/OpenSavvyBasePlugin.kt
CLOVIS-AI
864,973,196
false
{"Kotlin": 13992, "Shell": 556, "Dockerfile": 54}
package dev.opensavvy.conventions import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.provideDelegate @Suppress("unused") class OpenSavvyBasePlugin : Plugin<Project> { override fun apply(target: Project) { val appVersion: String? by target val appGroup: String? by target target.version = appVersion ?: "DEV" appGroup?.let { target.group = it } ?: target.logger.warn("Missing group declaration; you should add 'appGroup=<your group name>' in the gradle.properties file") } }
0
Kotlin
0
0
f8d3f1e184dd28dd6cea7e4e00efb6fb2fdb2ad1
530
Gradle-conventions
Apache License 2.0
src/main/java/io/sc3/plethora/api/method/ArgumentExt.kt
SwitchCraftCC
491,699,521
false
null
package io.sc3.plethora.api.method import dan200.computercraft.api.lua.IArguments import dan200.computercraft.api.lua.LuaValues.badArgumentOf import net.minecraft.util.math.Vec3d import io.sc3.plethora.gameplay.modules.glasses.GlassesArgumentHelper import io.sc3.plethora.util.Vec2d fun IArguments.getVec2d(startIndex: Int = 0): Vec2d = getVec2dNullable(startIndex) ?: throw badArgumentOf(startIndex, "number", get(startIndex)) fun IArguments.getVec2dNullable(startIndex: Int = 0): Vec2d? = if (count() < startIndex || count() == startIndex && this[0] == null) { null } else { Vec2d(getDouble(startIndex), getDouble(startIndex + 1)) } fun IArguments.getVec2dTable(index: Int = 0): Vec2d = GlassesArgumentHelper.getVec2dTable(getTable(index)) fun IArguments.getVec3dNullable(startIndex: Int = 0): Vec3d? = if (count() < startIndex || count() == startIndex && this[0] == null) { null } else { Vec3d(getDouble(startIndex), getDouble(startIndex + 1), getDouble(startIndex + 2)) } fun IArguments.getVec3d(startIndex: Int = 0): Vec3d = getVec3dNullable(startIndex) ?: throw badArgumentOf(startIndex, "number", get(startIndex)) fun IArguments.getVec3dTable(index: Int = 0): Vec3d = GlassesArgumentHelper.getVec3dTable(getTable(index))
18
null
5
11
600451a6db8aecb8e6e006a14783e7d8910ca1d3
1,271
Plethora-Fabric
MIT License
sdk/src/main/java/app/knock/client/KnockFeed.kt
knocklabs
712,054,463
false
{"Kotlin": 39486}
package app.knock.client import android.util.Log import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import org.phoenixframework.Channel import org.phoenixframework.Message import org.phoenixframework.Socket import java.time.ZonedDateTime @JsonIgnoreProperties(ignoreUnknown = true) data class Block( var content: String, var name: String, var rendered: String, ) @JsonIgnoreProperties(ignoreUnknown = true) data class FeedItem( @JsonProperty("__cursor") var feedCursor: String, var activities: List<KnockActivity>?, var actors: List<KnockUser>, var blocks: List<Block>, var data: Map<String, Any> = hashMapOf(), var id: String, var insertedAt: ZonedDateTime?, var clickedAt: ZonedDateTime?, var interactedAt: ZonedDateTime?, var linkClickedAt: ZonedDateTime?, var readAt: ZonedDateTime?, var seenAt: ZonedDateTime?, var tenant: String?, var totalActivities: Int, var totalActors: Int, var updatedAt: ZonedDateTime?, ) @JsonIgnoreProperties(ignoreUnknown = true) data class KnockActivity( var id: String, var actor: KnockUser?, var recipient: KnockUser?, var data: Map<String, Any> = hashMapOf(), var insertedAt: ZonedDateTime?, var updatedAt: ZonedDateTime? ) @JsonIgnoreProperties(ignoreUnknown = true) data class PageInfo( var before: String? = null, var after: String? = null, var pageSize: Int = 0, ) @JsonIgnoreProperties(ignoreUnknown = true) data class FeedMetadata( var totalCount: Int = 0, var unreadCount: Int = 0, var unseenCount: Int = 0, ) @JsonIgnoreProperties(ignoreUnknown = true) data class Feed( var entries: List<FeedItem> = listOf(), var meta: FeedMetadata = FeedMetadata(), var pageInfo: PageInfo = PageInfo(), ) enum class BulkOperationStatus { @JsonProperty("queued") QUEUED, @JsonProperty("processing") PROCESSING, @JsonProperty("completed") COMPLETED, @JsonProperty("failed") FAILED, } @JsonIgnoreProperties(ignoreUnknown = true) data class BulkOperation( var id: String, var name: String, var status: BulkOperationStatus, var estimatedTotalRows: Int, var processedRows: Int, var startedAt: ZonedDateTime?, var completedAt: ZonedDateTime?, var failedAt: ZonedDateTime?, ) enum class FeedItemScope { @JsonProperty("all") ALL, @JsonProperty("unread") UNREAD, @JsonProperty("read") READ, @JsonProperty("unseen") UNSEEN, @JsonProperty("seen") SEEN, } enum class FeedItemArchivedScope { @JsonProperty("include") INCLUDE, @JsonProperty("exclude") EXCLUDE, @JsonProperty("only") ONLY, } enum class BulkChannelMessageStatusUpdateType { @JsonProperty("seen") SEEN, @JsonProperty("read") READ, @JsonProperty("archived") ARCHIVED, @JsonProperty("unseen") UNSEEN, @JsonProperty("unread") UNREAD, @JsonProperty("unarchived") UNARCHIVED, } @JsonIgnoreProperties(ignoreUnknown = true) data class FeedClientOptions( var before: String? = null, var after: String? = null, var pageSize: Int? = null, var status: FeedItemScope? = null, var source: String? = null, // Optionally scope all notifications to a particular source only var tenant: String? = null, // Optionally scope all requests to a particular tenant var hasTenant: Boolean? = null, // Optionally scope to notifications with any tenancy or no tenancy var archived: FeedItemArchivedScope? = null, // Optionally scope to a given archived status (defaults to `exclude`) var triggerData: Map<String, Any>? = null, ) { /** * Merge new options to the exiting ones, if the new ones are nil, only a copy of `self` will be returned * * @param options the options to merge with the current struct, if they are nil, only a copy of `self` will be returned * @return a new struct of type `FeedClientOptions` with the options passed as the parameter merged into it. */ fun mergeOptions(options: FeedClientOptions? = null): FeedClientOptions { // initialize a new `mergedOptions` as a copy of `this` val mergedOptions = this.copy() // check if the passed options are not nil if (options == null) { return mergedOptions } // for each one of the properties `not nil` in the parameter `options`, override the ones in the new struct if (options.before != null) { mergedOptions.before = options.before } if (options.after != null) { mergedOptions.after = options.after } if (options.pageSize != null) { mergedOptions.pageSize = options.pageSize } if (options.status != null) { mergedOptions.status = options.status } if (options.source != null) { mergedOptions.source = options.source } if (options.tenant != null) { mergedOptions.tenant = options.tenant } if (options.hasTenant != null) { mergedOptions.hasTenant = options.hasTenant } if (options.archived != null) { mergedOptions.archived = options.archived } if (options.triggerData != null) { mergedOptions.triggerData = options.triggerData } return mergedOptions } } class FeedManager( client: Knock, private var feedId: String, options: FeedClientOptions = FeedClientOptions() ) { private var api: KnockAPI = client.api private var socket: Socket private var feedChannel: Channel? = null private var userId: String = client.userId private var feedTopic: String = "feeds:$feedId:${client.userId}" private var defaultFeedOptions: FeedClientOptions = options private val loggerTag = "app.knock.kotlin_client" init { // use regex and circumflex accent to mark only the starting http to be replaced and not any others val websocketHostname = client.api.hostname.replace(Regex("^http"), "ws") // default: wss://api.knock.app val websocketPath = "$websocketHostname/ws/v1/websocket" // default: wss://api.knock.app/ws/v1/websocket val params = hashMapOf( "vsn" to "2.0.0", "api_key" to client.publishableKey, "user_token" to (client.userToken ?: "") ) this.socket = Socket(websocketPath, params) } /** * Connect to the feed via socket. * * This will initialize the connection. * * You should also call the `on(eventName, completionHandler)` function to delegate what should * be executed on certain received events and the `disconnectFromFeed()` function to terminate the connection. * * @param options options of type `FeedClientOptions` to merge with the default ones (set on the constructor) * and scope as much as possible the results */ fun connectToFeed(options: FeedClientOptions? = null) { // Setup the socket to receive open/close events socket.logger = { Log.d(loggerTag, it) } socket.onOpen { Log.d(loggerTag, "Socket Opened") } socket.onClose { Log.d(loggerTag, "Socket Closed") } socket.onError { throwable, response -> Log.d(loggerTag, "Socket Error ${response?.code}", throwable) } val mergedOptions = defaultFeedOptions.mergeOptions(options) val params = paramsFromOptions(mergedOptions) // Setup the Channel to receive and send messages val channel = socket.channel(feedTopic, params) // Now connect the socket and join the channel this.feedChannel = channel this.feedChannel?.join()?.receive("ok") { Log.d(loggerTag, "CHANNEL: ${channel.topic} joined") }?.receive("error") { Log.d(loggerTag, "CHANNEL: ${channel.topic} failed to join. ${it.payload}") } socket.connect() } fun on(eventName: String, callback: (Message) -> Unit) { if (this.feedChannel != null) { val channel = this.feedChannel!! channel.on(eventName, callback) } else { Log.d(loggerTag, "Feed channel is nil. You should call first connectToFeed()") } } fun disconnectFromFeed() { Log.d(loggerTag, "Disconnecting from feed") if (feedChannel != null) { val channel = feedChannel!! channel.leave() socket.remove(channel) } socket.disconnect() } /** * Gets the content of the user feed * * @param options options of type `FeedClientOptions` to merge with the default * ones (set on the constructor) and scope as much as possible the results * @param completionHandler the code to execute when the response is received */ fun getUserFeedContent(options: FeedClientOptions? = null, completionHandler: (Result<Feed>) -> Unit) { val mergedOptions = defaultFeedOptions.mergeOptions(options) val queryItems: List<URLQueryItem> = listOf( URLQueryItem("page_size", mergedOptions.pageSize), URLQueryItem("after", mergedOptions.after), URLQueryItem("before", mergedOptions.before), URLQueryItem("source", mergedOptions.source), URLQueryItem("tenant", mergedOptions.tenant), URLQueryItem("has_tenant", mergedOptions.hasTenant), URLQueryItem("status", mergedOptions.status), URLQueryItem("archived", mergedOptions.archived), URLQueryItem("trigger_data", mergedOptions.triggerData), ) api.decodeFromGet("/users/$userId/feeds/$feedId", queryItems, completionHandler) } /** * Updates feed messages in bulk * * **Attention:** : The base scope for the call should take into account all of the options * currently set on the feed, as well as being scoped for the current user. * We do this so that we **ONLY** make changes to the messages that are currently in view on * this feed, and not all messages that exist. * * @param type the kind of update * @param options all the options currently set on the feed to scope as much as possible the bulk update * @param completionHandler the code to execute when the response is received */ fun makeBulkStatusUpdate(type: BulkChannelMessageStatusUpdateType, options: FeedClientOptions, completionHandler: (Result<BulkOperation>) -> Unit) { // TODO: check https://docs.knock.app/reference#bulk-update-channel-message-status // older_than: ISO-8601, check milliseconds // newer_than: ISO-8601, check milliseconds // delivery_status: one of `queued`, `sent`, `delivered`, `delivery_attempted`, `undelivered`, `not_sent` // engagement_status: one of `seen`, `unseen`, `read`, `unread`, `archived`, `unarchived`, `interacted` // Also check if the parameters sent here are valid val engagementStatus = if (options.status != null && options.status!! != FeedItemScope.ALL) { api.serializeValueAsString(options.status!!) } else { "" } val tenants = if (options.tenant != null) { listOf(options.tenant!!) } else { null } val body = mapOf( "user_ids" to listOf(userId), "engagement_status" to engagementStatus, "archived" to options.archived, "has_tenant" to options.hasTenant, "tenants" to tenants, ) val typeValue = api.serializeValueAsString(type) api.decodeFromPost("/channels/$feedId/messages/bulk/$typeValue", body, completionHandler) } private fun paramsFromOptions(options: FeedClientOptions): Map<String, Any> { val params: Map<String, Any> = hashMapOf() if (options.before != null) { params["before"] to options.before!! } if (options.after != null) { params["after"] to options.after!! } if (options.pageSize != null) { params["page_size"] to options.pageSize!! } if (options.status != null) { params["status"] to options.status!! } if (options.source != null) { params["source"] to options.source!! } if (options.tenant != null) { params["tenant"] to options.tenant!! } if (options.hasTenant != null) { params["has_tenant"] to options.hasTenant!! } if (options.archived != null) { params["archived"] to options.archived!! } if (options.triggerData != null) { params["trigger_data"] to options.triggerData!! } return params } }
1
Kotlin
0
0
881fbc99c35d2ae8a7ead8b8d6afe22d0a237081
12,919
knock-android
MIT License
embedded_video_lib/src/main/java/com/gapps/library/api/models/video/facebook/FacebookResponse.kt
TalbotGooday
225,641,422
false
{"Kotlin": 118314}
package com.gapps.library.api.models.video.facebook import com.gapps.library.api.models.video.VideoPreviewModel import com.gapps.library.api.models.video.base.BaseVideoResponse import com.google.gson.annotations.SerializedName data class FacebookResponse( @SerializedName("author_name") val authorName: String = "", @SerializedName("author_url") val authorUrl: String = "", @SerializedName("provider_url") val providerUrl: String = "", @SerializedName("provider_name") val providerName: String = "", @SerializedName("success") val success: Boolean = false, @SerializedName("height") val height: Int? = 0, @SerializedName("html") val html: String = "", @SerializedName("type") val type: String = "", @SerializedName("version") val version: String = "", @SerializedName("url") val url: String = "", @SerializedName("width") val width: Int? = 0 ) : BaseVideoResponse { override fun toPreview( url: String?, linkToPlay: String, hostingName: String, videoId: String ): VideoPreviewModel { return VideoPreviewModel(url, linkToPlay, hostingName, videoId).apply { this.thumbnailUrl = "https://graph.facebook.com/${videoId}/thumbnails" this.videoTitle = [email protected] this.width = [email protected] ?: 0 this.height = [email protected] ?: 0 } } }
3
Kotlin
5
38
39b1de22842a1d2ebee6edf5c2802ababd6b4f9f
1,476
Android-Oembed-Video
Apache License 2.0
admin/app/src/main/java/com/yazan98/groupyadmin/screens/TasksContainerScreen.kt
Yazan98
226,006,997
false
{"Gradle": 6, "Java Properties": 4, "Shell": 2, "Text": 1, "Ignore List": 4, "Batchfile": 2, "Markdown": 1, "JSON": 2, "Proguard": 2, "Kotlin": 72, "XML": 143, "Java": 1}
package com.yazan98.groupyadmin.screens import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.yazan98.groupyadmin.R class TasksContainerScreen : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.screen_tasks_container) supportFragmentManager?.beginTransaction().add(R.id.TasksContainer, TasksScreen()) .commit() } }
1
null
1
1
bbefd5b4a567982d31cfb70ec2adb2a9fbb35ca2
476
Groupy
Apache License 2.0
intellij-plugin/src/test/testData/migration/compat-to-operationbased/reworkInlineFragmentFields_after.kt
apollographql
69,469,299
false
{"Kotlin": 3463807, "Java": 198208, "CSS": 34435, "HTML": 5844, "JavaScript": 1191}
package com.example import com.apollographql.apollo3.ApolloClient import com.apollographql.apollo3.api.Adapter import com.apollographql.apollo3.api.CompiledField import com.apollographql.apollo3.api.CustomScalarAdapters import com.apollographql.apollo3.api.Query import com.apollographql.apollo3.api.json.JsonWriter import com.example.FruitListQuery.OnGranny public class FruitListQuery() : Query<FruitListQuery.Data> { public override fun id(): String = TODO() public override fun document(): String = TODO() public override fun name(): String = TODO() public override fun serializeVariables( writer: JsonWriter, customScalarAdapters: CustomScalarAdapters ): Unit { } public override fun adapter(): Adapter<Data> = TODO() public override fun rootField(): CompiledField = TODO() public data class Data( public val fruitList: FruitList?, ) : Query.Data public data class FruitList( public val ok: Boolean, public val list: kotlin.collections.List<List>, ) public data class List( public val __typename: String, public val id: String, /** * Synthetic field for inline fragment on Cherry */ public val asCherry: OnCherry?, /** * Synthetic field for inline fragment on Apple */ public val asApple: OnApple?, ) public data class AsCherry( public val __typename: String, public val id: String, public val pit: Boolean, ) public data class AsApple( public val __typename: String, public val id: String, public val color: String, /** * Synthetic field for inline fragment on Golden */ public val asGolden: OnGolden?, /** * Synthetic field for inline fragment on Granny */ public val asGranny: OnGranny?, ) public data class AsGolden( public val __typename: String, public val id: String, public val color: String, public val isGolden: Boolean, ) public data class AsGranny( public val __typename: String, public val id: String, public val color: String, public val isGranny: Boolean, ) } suspend fun main() { val apolloClient: ApolloClient? = null val data = apolloClient!!.query(FruitListQuery()) .execute() .data!! val asApple: FruitListQuery.OnApple = data.fruitList!!.list[0].onApple!! val color = asApple.color val id = data.fruitList.list[0].onApple!!.id val asGranny: OnGranny = data.fruitList.list[0].onApple!!.onGranny!! val isGranny = asGranny.isGranny val id2 = data.fruitList.list[0].onApple!!.onGranny!!.id val newAsGranny: FruitListQuery.OnApple = FruitListQuery.OnApple( __typename = "Apple", id = "id", color = "color", onGolden = FruitListQuery.OnGolden( __typename = "Golden", id = "id", color = "color", isGolden = true, ), onGranny = FruitListQuery.OnGranny( __typename = "Granny", id = "id", color = "color", isGranny = true, ), ) }
164
Kotlin
654
3,750
174cb227efe76672cf2beac1affc7054f6bb2892
3,125
apollo-kotlin
MIT License
investigacionkotlin/app/src/main/java/com/example/investigacion/RecursoApi.kt
Goecamp
868,163,784
false
{"Kotlin": 13710}
package com.example.investigacion import retrofit2.Call import retrofit2.http.* interface RecursoApi { @GET("recursos") fun getRecursos(): Call<List<Recurso>> @GET("recursos/{id}") fun getRecurso(@Path("id") id: Int): Call<Recurso> @POST("recursos") fun createRecurso(@Body recurso: Recurso): Call<Recurso> @PUT("recursos/{id}") fun updateRecurso(@Path("id") id: Int, @Body recurso: Recurso): Call<Recurso> @DELETE("recursos/{id}") fun deleteRecurso(@Path("id") id: Int): Call<Void> } //por el momento esta cosa no sirve de mucho pero aca se tiene idea de las peticiones que deben hacerse
0
Kotlin
0
0
cf2431ffd804d204f0d24522a737d553e8de7b11
635
Desafio3DMS
MIT License
src/main/kotlin/org/move/cli/settings/PerProjectAptosConfigurable.kt
pontem-network
279,299,159
false
{"Kotlin": 2002896, "Move": 32503, "Lex": 5466, "HTML": 1904, "Java": 1275}
package org.move.cli.settings import com.intellij.openapi.externalSystem.service.settings.ExternalSystemGroupConfigurable import com.intellij.openapi.options.BoundConfigurable import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.util.Disposer import com.intellij.ui.components.JBCheckBox import com.intellij.ui.dsl.builder.AlignX import com.intellij.ui.dsl.builder.bindSelected import com.intellij.ui.dsl.builder.panel import com.intellij.ui.layout.selected import org.move.cli.settings.aptos.ChooseAptosCliPanel import org.move.openapiext.showSettingsDialog // panels needs not to be bound to the Configurable itself, as it's sometimes created without calling the `createPanel()` class PerProjectAptosConfigurable(val project: Project): BoundConfigurable("Aptos") { override fun createPanel(): DialogPanel { val chooseAptosCliPanel = ChooseAptosCliPanel(versionUpdateListener = null) val configurablePanel = panel { val settings = project.moveSettings val state = settings.state.copy() chooseAptosCliPanel.attachToLayout(this) group { row { checkBox("Fetch external dependencies on project reload") .bindSelected(state::fetchAptosDeps) link("Configure project reload schedule") { ProjectManager.getInstance().defaultProject.showSettingsDialog<ExternalSystemGroupConfigurable>() } .align(AlignX.RIGHT) } val compilerV2Box = JBCheckBox("Enable V2 compiler") row { cell(compilerV2Box) .comment( "Enables features of the Aptos V2 compiler " + "(receiver style functions, access control, etc.)" ) .bindSelected(state::isCompilerV2) } indent { row { checkBox("Set Compiler V2 in CLI commands") .comment("Adds `--compiler-version v2 --language-version 2.0` to all generated Aptos CLI commands") .enabledIf(compilerV2Box.selected) .bindSelected(state::addCompilerV2Flags) } } group("Command Line Options") { row { checkBox("Disable telemetry for new Run Configurations") .comment( "Adds APTOS_DISABLE_TELEMETRY=true to every generated Aptos command." ) .bindSelected(state::disableTelemetry) } row { checkBox("Skip updating to the latest git dependencies") .comment( "Adds --skip-fetch-latest-git-deps to the sync and test runs." ) .bindSelected(state::skipFetchLatestGitDeps) } row { checkBox("Dump storage to console on test failures") .comment( "Adds --dump to generated test runs." ) .bindSelected(state::dumpStateOnTestFailure) } } } if (!project.isDefault) { row { link("Set default project settings") { ProjectManager.getInstance().defaultProject.showSettingsDialog<PerProjectAptosConfigurable>() } .align(AlignX.RIGHT) } } // saves values from Swing form back to configurable (OK / Apply) onApply { settings.modify { it.aptosExecType = chooseAptosCliPanel.data.aptosExecType val localAptosSdkPath = chooseAptosCliPanel.data.localAptosPath if (localAptosSdkPath != null) { chooseAptosCliPanel.updateAptosSdks(localAptosSdkPath) } it.localAptosPath = localAptosSdkPath it.disableTelemetry = state.disableTelemetry it.skipFetchLatestGitDeps = state.skipFetchLatestGitDeps it.dumpStateOnTestFailure = state.dumpStateOnTestFailure it.isCompilerV2 = state.isCompilerV2 it.addCompilerV2Flags = state.addCompilerV2Flags it.fetchAptosDeps = state.fetchAptosDeps } } // loads settings from configurable to swing form onReset { chooseAptosCliPanel.data = ChooseAptosCliPanel.Data(state.aptosExecType, state.localAptosPath) } /// checks whether any settings are modified (should be fast) onIsModified { val aptosPanelData = chooseAptosCliPanel.data aptosPanelData.aptosExecType != settings.aptosExecType || aptosPanelData.localAptosPath != settings.localAptosPath } } this.disposable?.let { Disposer.register(it, chooseAptosCliPanel) } return configurablePanel } // override fun disposeUIResources() { // super.disposeUIResources() // Disposer.dispose(chooseAptosCliPanel) // } }
8
Kotlin
25
66
34295007fb55b40012c87269b4720a1e018991b0
6,155
intellij-move
MIT License
koin-projects/koin-androidx-viewmodel/src/main/java/org/koin/androidx/viewmodel/compat/ViewModelCompat.kt
henriquehorbovyi
277,036,450
true
{"AsciiDoc": 5, "Markdown": 53, "Text": 3, "Ignore List": 6, "Gradle": 27, "Shell": 9, "Java Properties": 2, "Batchfile": 1, "INI": 9, "XML": 54, "Kotlin": 267, "Java": 6, "HTML": 2, "CSS": 1, "JavaScript": 2, "Proguard": 1, "YAML": 1}
/* * Copyright 2017-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.koin.android.viewmodel.compat import android.arch.lifecycle.LifecycleOwner import android.arch.lifecycle.ViewModel import org.koin.android.viewmodel.ext.android.getViewModel import org.koin.android.viewmodel.ext.android.viewModel import org.koin.core.parameter.ParametersDefinition import org.koin.core.qualifier.Qualifier /** * LifecycleOwner functions to help for ViewModel in Java * * @author <NAME> */ object ViewModelCompat { /** * Lazy get a viewModel instance * * @param owner - LifecycleOwner * @param clazz - viewModel class dependency * @param qualifier - Koin BeanDefinition qualifier (if have several ViewModel beanDefinition of the same type) * @param parameters - parameters to pass to the BeanDefinition */ @JvmOverloads @JvmStatic fun <T : ViewModel> viewModel( owner: LifecycleOwner, clazz: Class<T>, qualifier: Qualifier? = null, parameters: ParametersDefinition? = null ): Lazy<T> = owner.viewModel(clazz.kotlin, qualifier, parameters) /** * Get a viewModel instance * * @param owner - LifecycleOwner * @param clazz - Class of the BeanDefinition to retrieve * @param qualifier - Koin BeanDefinition qualifier (if have several ViewModel beanDefinition of the same type) * @param parameters - parameters to pass to the BeanDefinition */ @JvmOverloads @JvmStatic fun <T : ViewModel> getViewModel( owner: LifecycleOwner, clazz: Class<T>, qualifier: Qualifier? = null, parameters: ParametersDefinition? = null ): T { return owner.getViewModel(clazz.kotlin, qualifier, parameters) } }
1
Kotlin
1
1
f981f3810090b5e5e729f2f2d9aa2c077e74b0d7
2,357
koin
Apache License 2.0
src/main/kotlin/di/Module.kt
numq
518,925,394
false
{"Kotlin": 86245}
package di import file.* import folder.* import navigation.NavigationViewModel import org.koin.dsl.bind import org.koin.dsl.module import transfer.* import websocket.SocketClient import websocket.SocketServer import websocket.SocketService val socket = module { single { SocketClient() } bind SocketService.Client::class single { SocketServer() } bind SocketService.Server::class } val file = module { single { FileRepository.Implementation(get()) } bind FileRepository::class factory { GetFileEvents(get()) } factory { RefreshFiles(get()) } factory { ShareFile(get()) } factory { RemoveFile(get()) } } val folder = module { single { FolderRepository.Implementation(get(), get()) } bind FolderRepository::class factory { GetSharingStatus(get()) } factory { StartClient(get()) } factory { StartServer(get()) } factory { StopSharing(get()) } single { FolderViewModel( get(), get(), get(), get(), get(), get(), get(), get(), get() ) } } val transfer = module { single { TransferService.Implementation() } bind TransferService::class factory { GetTransferActions(get()) } bind GetTransferActions::class factory { RequestTransfer(get()) } bind RequestTransfer::class factory { UploadFile(get()) } bind UploadFile::class factory { DownloadFile(get()) } bind DownloadFile::class factory { DownloadZip(get()) } bind DownloadZip::class } val navigation = module { single { NavigationViewModel(get(), get(), get(), get()) } } val appModule = socket + file + folder + transfer + navigation
0
Kotlin
0
2
d4e2c9888328657a0500b1b2e863926b9a122f9a
1,693
stash-desktop
MIT License
play-services-core/src/main/kotlin/org/microg/gms/ui/PushNotificationFragment.kt
alexandruchircu
230,924,375
true
{"INI": 2, "YAML": 1, "Makefile": 1, "Gradle": 33, "Shell": 1, "Markdown": 1, "Text": 3, "Ignore List": 1, "Java Properties": 17, "XML": 162, "AIDL": 338, "Java": 656, "Protocol Buffer": 6, "Kotlin": 53, "SVG": 5, "Diff": 5, "Proguard": 2}
/* * SPDX-FileCopyrightText: 2020, microG Project Team * SPDX-License-Identifier: Apache-2.0 */ package org.microg.gms.ui import android.os.Bundle import android.view.* import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import com.google.android.gms.R import com.google.android.gms.databinding.PushNotificationFragmentBinding import org.microg.gms.checkin.CheckinPrefs import org.microg.gms.gcm.GcmPrefs class PushNotificationFragment : Fragment(R.layout.push_notification_fragment) { lateinit var binding: PushNotificationFragmentBinding override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = PushNotificationFragmentBinding.inflate(inflater, container, false) binding.switchBarCallback = object : PreferenceSwitchBarCallback { override fun onChecked(newStatus: Boolean) { GcmPrefs.setEnabled(context, newStatus) binding.gcmEnabled = newStatus } } return binding.root } override fun onResume() { super.onResume() lifecycleScope.launchWhenResumed { binding.gcmEnabled = GcmPrefs.get(context).isEnabled binding.checkinEnabled = CheckinPrefs.get(context).isEnabled } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { menu.add(0, MENU_ADVANCED, 0, R.string.menu_advanced) super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { MENU_ADVANCED -> { findNavController().navigate(R.id.openGcmAdvancedSettings) true } else -> super.onOptionsItemSelected(item) } } companion object { private const val MENU_ADVANCED = Menu.FIRST } }
0
Java
0
1
2076970d4052dd6438896f35319018202c6d7b73
2,131
GmsCore
Apache License 2.0
app/src/main/java/com/ncs/o2/UI/Tasks/TaskPage/TaskDetailActivity.kt
arpitmx
647,358,015
false
{"Kotlin": 1345292}
package com.ncs.o2.UI.Tasks.TaskPage import android.content.Intent import android.content.IntentFilter import android.net.ConnectivityManager import android.os.Bundle import android.os.Handler import android.os.Looper import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import com.ncs.o2.Domain.Models.User import com.ncs.o2.Domain.Models.UserInMessage import com.ncs.o2.Domain.Utility.ExtensionsUtil.gone import com.ncs.o2.Domain.Utility.ExtensionsUtil.setOnClickThrottleBounceListener import com.ncs.o2.Domain.Utility.ExtensionsUtil.visible import com.ncs.o2.Domain.Utility.GlobalUtils import com.ncs.o2.HelperClasses.NetworkChangeReceiver import com.ncs.o2.HelperClasses.PrefManager import com.ncs.o2.R import com.ncs.o2.UI.MainActivity import com.ncs.o2.UI.Tasks.TaskPage.Details.TaskDetailsFragment import com.ncs.o2.UI.UIComponents.BottomSheets.BottomSheet import com.ncs.o2.UI.UIComponents.BottomSheets.MoreOptionsBottomSheet import com.ncs.o2.databinding.ActivityTaskDetailBinding import com.ncs.versa.Constants.Endpoints import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class TaskDetailActivity : AppCompatActivity(), TaskDetailsFragment.ViewVisibilityListner, NetworkChangeReceiver.NetworkChangeCallback { @Inject lateinit var utils : GlobalUtils.EasyElements val binding: ActivityTaskDetailBinding by lazy { ActivityTaskDetailBinding.inflate(layoutInflater) } lateinit var taskId:String var type: String? =null var index:String?=null lateinit var isworkspace:String var users:MutableList<UserInMessage> = mutableListOf() val sharedViewModel: SharedViewModel by viewModels() var moderatorsList: MutableList<String> = mutableListOf() var moderators: MutableList<User> = mutableListOf() var assignee:String="" private val networkChangeReceiver = NetworkChangeReceiver(this,this) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) registerReceiver(true) taskId = intent.getStringExtra("task_id")!! val _type=intent.getStringExtra("type") if (_type!=null){ type=_type } val _index= intent.getStringExtra("index") if (_index!=null){ index=_index } setActionbar() binding.gioActionbar.btnBack.setOnClickThrottleBounceListener { onBackPressed() } binding.gioActionbar.btnFav.setOnClickThrottleBounceListener{ binding.gioActionbar.btnFav.setImageDrawable(resources.getDrawable(R.drawable.star_filled)) } binding.gioActionbar.btnMore.setOnClickListener { val moreOptionBottomSheet = MoreOptionsBottomSheet() moreOptionBottomSheet.show(supportFragmentManager, "more") } } @Deprecated("Deprecated in Java") override fun onBackPressed() { super.onBackPressed() if (type=="shareTask" || type=="notifications" ){ startActivity(Intent(this@TaskDetailActivity, MainActivity::class.java)) overridePendingTransition(R.anim.slide_in_right, me.shouheng.utils.R.anim.slide_out_right) } else{ overridePendingTransition(R.anim.slide_in_right, me.shouheng.utils.R.anim.slide_out_right) } } private fun setActionbar() { binding.gioActionbar.titleTv.text = taskId binding.gioActionbar.doneItem.gone() } override fun showProgressbar(show: Boolean) { if (show) binding.progressbarBottomTab.visible() else binding.progressbarBottomTab.gone() } private var receiverRegistered = false private val intentFilter by lazy{ IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) } fun registerReceiver(flag : Boolean){ if (flag){ if (!receiverRegistered) { registerReceiver(networkChangeReceiver,intentFilter) receiverRegistered = true } }else{ if (receiverRegistered){ unregisterReceiver(networkChangeReceiver) receiverRegistered = false } } } override fun onPause() { super.onPause() registerReceiver(false) } override fun onDestroy() { super.onDestroy() registerReceiver(false) } override fun onStart() { super.onStart() registerReceiver(true) } override fun onStop() { super.onStop() registerReceiver(false) } override fun onResume() { super.onResume() registerReceiver(true) } override fun onOnlineModePositiveSelected() { PrefManager.setAppMode(Endpoints.ONLINE_MODE) utils.restartApp() } override fun onOfflineModePositiveSelected() { startActivity(intent) PrefManager.setAppMode(Endpoints.OFFLINE_MODE) } override fun onOfflineModeNegativeSelected() { networkChangeReceiver.retryNetworkCheck() } }
1
Kotlin
2
2
3e92ac9f38735961aab7f415c85c35523d40d1bf
5,220
Oxygen
MIT License
src/main/kotlin/com/pambrose/srcref/pages/Edit.kt
pambrose
494,865,253
false
null
package com.pambrose.srcref.pages import com.github.pambrose.common.response.PipelineCall import com.github.pambrose.common.response.respondWith import com.pambrose.srcref.Api import com.pambrose.srcref.Endpoints.EDIT import com.pambrose.srcref.Endpoints.WHAT import com.pambrose.srcref.QueryParams.ACCOUNT import com.pambrose.srcref.QueryParams.BEGIN_OCCURRENCE import com.pambrose.srcref.QueryParams.BEGIN_OFFSET import com.pambrose.srcref.QueryParams.BEGIN_REGEX import com.pambrose.srcref.QueryParams.BEGIN_TOPDOWN import com.pambrose.srcref.QueryParams.BRANCH import com.pambrose.srcref.QueryParams.END_OCCURRENCE import com.pambrose.srcref.QueryParams.END_OFFSET import com.pambrose.srcref.QueryParams.END_REGEX import com.pambrose.srcref.QueryParams.END_TOPDOWN import com.pambrose.srcref.QueryParams.PATH import com.pambrose.srcref.QueryParams.REPO import com.pambrose.srcref.Urls import com.pambrose.srcref.pages.Common.SrcRefDslTag import com.pambrose.srcref.pages.Common.URL_PREFIX import com.pambrose.srcref.pages.Common.commonHead import com.pambrose.srcref.pages.Common.githubIcon import com.pambrose.srcref.pages.Common.hasValues import com.pambrose.srcref.pages.Common.widthVal import kotlinx.html.* import kotlinx.html.dom.* object Edit { internal suspend fun PipelineCall.displayEdit(params: Map<String, String?>) { // This is called early because it is suspending, and we cannot suspend inside document construction val (githubUrl, msg) = Urls.githubRangeUrl(params, URL_PREFIX) respondWith { document { append.html { head { commonHead() script { src = "js/copyUrl.js" } title { +"srcref" } } body { githubIcon() div("page-indent") { h2 { span { +"srcref - Dynamic Line-Specific GitHub Permalinks" a { href = "/$WHAT"; style = "padding-left: 25px; font-size: 75%;"; +"(What is srcref?)" } } } val textWidth = "40" val offsetWidth = "6" form { action = "/$EDIT" method = FormMethod.get table { formElement("Username/Org Name:", "GitHub username or organization name") { textInput { name = ACCOUNT.arg; size = textWidth; required = true value = ACCOUNT.defaultIfNull(params) } } formElement("Repo Name:", "GitHub repository name") { textInput { name = REPO.arg; size = textWidth; required = true value = REPO.defaultIfNull(params) } } formElement("Branch Name:", "GitHub branch name") { textInput { name = BRANCH.arg; size = textWidth; required = true value = BRANCH.defaultIfNull(params) } } formElement("File Path:", "File path in repository") { textInput { name = PATH.arg; size = "70"; required = true value = PATH.defaultIfNull(params) } } formElement("Begin Regex:", "Regex used to determine the beginning match") { textInput { name = BEGIN_REGEX.arg; size = textWidth; required = true value = BEGIN_REGEX.defaultIfNull(params) } } formElement("Begin Occurrence:", "Number of matches for the beginning match") { val isSelected = BEGIN_OCCURRENCE.defaultIfBlank(params).toInt() select("occurrence") { name = BEGIN_OCCURRENCE.arg; size = "1"; occurrenceOptions(isSelected) } } formElement("Begin Offset:", "Number of lines above or below the beginning match") { textInput { name = BEGIN_OFFSET.arg; size = offsetWidth; required = true value = BEGIN_OFFSET.defaultIfNull(params) } } formElement("Begin Search Direction:", "Direction to evaluate the file for the beginning match") { span { val isChecked = BEGIN_TOPDOWN.defaultIfBlank(params).toBoolean() style = "text-align:center" "begin_topdown".also { lab -> radioInput { id = lab; name = BEGIN_TOPDOWN.arg; value = "true"; checked = isChecked } label { htmlFor = lab; +" Top-down " } } "begin_bottomup".also { lab -> radioInput { id = lab; name = BEGIN_TOPDOWN.arg; value = "false"; checked = !isChecked } label { htmlFor = lab; +" Bottom-up " } } } } formElement("End Regex:", "Optional regex used to determine the ending match") { textInput { name = END_REGEX.arg; size = textWidth; value = END_REGEX.defaultIfNull(params) } } formElement("End Occurrence:", "Optional number of matches for the ending match") { val isSelected = END_OCCURRENCE.defaultIfBlank(params).toInt() select("occurrence") { name = END_OCCURRENCE.arg; size = "1"; occurrenceOptions(isSelected) } } formElement("End Offset:", "Optional number of lines above or below the ending match") { textInput { name = END_OFFSET.arg; size = offsetWidth; value = END_OFFSET.defaultIfNull(params) } } formElement("End Search Direction:", "Optional direction to evaluate the file for the ending match") { span { val isChecked = END_TOPDOWN.defaultIfBlank(params).toBoolean() style = "text-align:center" "end_topdown".also { lab -> radioInput { id = lab; name = END_TOPDOWN.arg; value = "true"; checked = isChecked } label { htmlFor = lab; +" Top-down " } } "end_bottomup".also { lab -> radioInput { id = lab; name = END_TOPDOWN.arg; value = "false"; checked = !isChecked } label { htmlFor = lab; +" Bottom-up " } } } } formElement("") { style = "padding-top:10" submitInput(classes = "button") { value = "Generate URL" } } } } div { style = "padding-top: 15px" if (params.hasValues()) { val srcrefUrl = Urls.srcrefToGithubUrl(params, prefix = URL_PREFIX) val isValid = msg.isEmpty() span { button(classes = "button") { onClick = "window.open('$EDIT', '_self')" +"Reset Values" } if (isValid) { button(classes = "button") { style = "margin-left: 10px;" onClick = "copyUrl()" +"Copy URL" } button(classes = "button") { style = "margin-left: 10px;" onClick = "window.open('$srcrefUrl', '_blank')" +"View GitHub Permalink" } div { id = "snackbar"; +"URL Copied!" } } } if (isValid) { div { style = "padding-top: 17px; padding-bottom: 10px;"; +"Embed this URL in your docs:" } textArea { id = "srcrefUrl"; rows = "4"; +srcrefUrl; cols = widthVal; readonly = true } div { style = "padding-top: 10px; padding-bottom: 10px;" +"To dynamically generate this GitHub permalink:" } textArea { rows = "2"; +githubUrl; cols = widthVal; readonly = true } } else { h2 { +"Exception:" } textArea { rows = "3"; cols = widthVal; readonly = true; +msg } } } else { button(classes = "button") { val url = Api.srcrefUrl( account = "pambrose", repo = "srcref", branch = "master", path = "src/main/kotlin/com/pambrose/srcref/Main.kt", beginRegex = "install\\(CallLogging\\)", beginOccurrence = 1, beginOffset = 0, beginTopDown = true, endRegex = "install\\(Compression\\)", endOccurrence = 1, endOffset = 3, endTopDown = true, prefix = "", ) onClick = "window.open('${"$url&edit=true"}','_self')" +"Example Values" } } } } } } }.serialize() } } @SrcRefDslTag private inline fun TABLE.formElement(label: String, crossinline block: TD.() -> Unit) = tr { td { +label } td { block() } } @SrcRefDslTag internal inline fun TABLE.formElement( label: String, tooltip: String, crossinline block: FlowOrPhrasingContent.() -> Unit ) = formElement(label) { withToolTip(tooltip) { block() } } @SrcRefDslTag private inline fun FlowOrPhrasingContent.withToolTip( msg: String, crossinline block: FlowOrPhrasingContent.() -> Unit ) = span { block() span("tooltip") { span("spacer") {} img { src = "images/question.png"; width = "18"; height = "18" } span("tooltiptext") { +msg } } } private fun SELECT.occurrenceOptions(isSelected: Int) { option { +" 1st "; value = "1"; selected = isSelected == 1 } option { +" 2nd "; value = "2"; selected = isSelected == 2 } option { +" 3rd "; value = "3"; selected = isSelected == 3 } option { +" 4th "; value = "4"; selected = isSelected == 4 } option { +" 5th "; value = "5"; selected = isSelected == 5 } option { +" 6th "; value = "6"; selected = isSelected == 6 } option { +" 7th "; value = "7"; selected = isSelected == 7 } option { +" 8th "; value = "8"; selected = isSelected == 8 } option { +" 9th "; value = "9"; selected = isSelected == 9 } option { +" 10th "; value = "10"; selected = isSelected == 10 } } }
0
Kotlin
0
0
1820a6a709151dc0a03d38bdc4c00c0856bcaeba
11,309
srcref
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/notificationsalertsvsip/service/listeners/notifiers/PrisonVisitCanclledEventNotifier.kt
ministryofjustice
603,045,531
false
{"Kotlin": 110537, "Dockerfile": 1157}
package uk.gov.justice.digital.hmpps.notificationsalertsvsip.service.listeners.notifiers import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import org.springframework.stereotype.Component import uk.gov.justice.digital.hmpps.notificationsalertsvsip.enums.VisitEventType import uk.gov.justice.digital.hmpps.notificationsalertsvsip.service.NotificationService import uk.gov.justice.digital.hmpps.notificationsalertsvsip.service.listeners.events.DomainEvent import uk.gov.justice.digital.hmpps.notificationsalertsvsip.service.listeners.events.additionalinfo.VisitAdditionalInfo const val PRISON_VISIT_CANCELLED = "prison-visit.cancelled" @Component(value = PRISON_VISIT_CANCELLED) class PrisonVisitCancelledEventNotifier( private val notificationService: NotificationService, private val objectMapper: ObjectMapper, ) : EventNotifier(objectMapper) { override fun processEvent(domainEvent: DomainEvent) { val visitAdditionalInfo: VisitAdditionalInfo = objectMapper.readValue(domainEvent.additionalInformation) LOG.debug("Enter cancel event with info {}", visitAdditionalInfo) notificationService.sendMessage(VisitEventType.CANCELLED, visitAdditionalInfo.bookingReference) } }
3
Kotlin
0
1
b8dcc8ace665a5d5760fc432550c161bce2f7ff4
1,247
hmpps-notifications-alerts-vsip
MIT License
src/main/kotlin/kotlinmud/helper/string/Matches.kt
danielmunro
241,230,796
false
null
package kotlinmud.helper.string fun String.matches(name: String): Boolean { return name.toLowerCase().split(" ").any { it.length > 1 && it.startsWith(this.toLowerCase()) } }
0
Kotlin
1
8
5560223c09f84fb79411391b301a8740e343ed4e
179
kotlinmud
MIT License
server/src/main/kotlin/in/procyk/shin/db/ShortUrl.kt
avan1235
752,385,367
false
{"Kotlin": 98746, "HTML": 3752, "Swift": 3219, "Dockerfile": 1187, "Makefile": 849}
package `in`.procyk.shin.db import `in`.procyk.shin.shared.RedirectType import org.jetbrains.exposed.dao.Entity import org.jetbrains.exposed.dao.EntityClass import org.jetbrains.exposed.dao.id.EntityID import org.jetbrains.exposed.dao.id.IdTable import org.jetbrains.exposed.sql.kotlin.datetime.timestamp import org.postgresql.util.PGobject internal object ShortUrls : IdTable<String>() { override val id = varchar("id", 44).entityId() override val primaryKey = PrimaryKey(id) val url = text("url") val expirationAt = timestamp("expiration_at").nullable() val redirectType = customEnumeration( name = "redirect_type", sql = "redirect_type", fromDb = { value -> RedirectType.valueOf(value as String) }, toDb = { PGEnum("redirect_type", it) }, ) val usageCount = long("usage_count").default(0) } internal class ShortUrl(id: EntityID<String>) : Entity<String>(id) { companion object : EntityClass<String, ShortUrl>(ShortUrls) var url by ShortUrls.url var expirationAt by ShortUrls.expirationAt var redirectType by ShortUrls.redirectType var usageCount by ShortUrls.usageCount } val CREATE_REDIRECT_TYPE = """ DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'redirect_type') THEN CREATE TYPE redirect_type AS ENUM ( ${RedirectType.entries.joinToString { "'$it'" }} ); END IF; END$$; """ private class PGEnum<T : Enum<T>>(enumTypeName: String, enumValue: T?) : PGobject() { init { value = enumValue?.name type = enumTypeName } }
0
Kotlin
1
1
8900b7ae6150a76bc4fbd956b184e01bf2724193
1,592
shin
MIT License
inference/inference-tfjs/src/jsMain/kotlin/io.kinference.tfjs/operators/tensor/ArgMax.kt
JetBrains-Research
244,400,016
false
null
package io.kinference.tfjs.operators.tensor import io.kinference.attribute.Attribute import io.kinference.data.ONNXData import io.kinference.graph.Contexts import io.kinference.ndarray.arrays.NumberNDArrayTFJS import io.kinference.operator.* import io.kinference.protobuf.message.AttributeProto import io.kinference.protobuf.message.TensorProto import io.kinference.tfjs.data.tensors.TFJSTensor import io.kinference.tfjs.data.tensors.asTensor sealed class ArgMax(name: String, info: OperatorInfo, attributes: Map<String, Attribute<Any>>, inputs: List<String>, outputs: List<String>) : Operator<TFJSTensor, TFJSTensor>(name, info, attributes, inputs, outputs) { companion object { private val DEFAULT_VERSION = VersionInfo(sinceVersion = 1) operator fun invoke(name: String, version: Int?, attributes: Map<String, Attribute<Any>>, inputs: List<String>, outputs: List<String>) = when (version ?: DEFAULT_VERSION.sinceVersion) { in ArgMaxVer12.VERSION.asRange() -> ArgMaxVer12(name, attributes, inputs, outputs) else -> error("Unsupported version of ArgMax operator: $version") } } } class ArgMaxVer12(name: String, attributes: Map<String, Attribute<Any>>, inputs: List<String>, outputs: List<String>) : ArgMax(name, INFO, attributes, inputs, outputs) { companion object { private val ATTRIBUTES_INFO = listOf( AttributeInfo("axis", setOf(AttributeProto.AttributeType.INT), required = false, default = 0), AttributeInfo("keepdims", setOf(AttributeProto.AttributeType.INT), required = false, default = 1), AttributeInfo("select_last_index", setOf(AttributeProto.AttributeType.INT), required = false, default = 0), ) private val INPUTS_INFO = listOf( IOInfo(0, PRIMITIVE_DATA_TYPES + TensorProto.DataType.BFLOAT16, "data", differentiable = false) ) private val OUTPUTS_INFO = listOf(IOInfo(0, setOf(TensorProto.DataType.INT64), "reduced", optional = false)) internal val VERSION = VersionInfo(sinceVersion = 1) private val INFO = OperatorInfo("ArgMax", ATTRIBUTES_INFO, INPUTS_INFO, OUTPUTS_INFO, VERSION, OperatorInfo.DEFAULT_DOMAIN) } private val axis: Int by attribute { it: Number -> it.toInt() } private val keepDims: Boolean by attribute("keepdims") { it: Number -> it.toInt() != 0 } private val selectLastIndex: Boolean by attribute("select_last_index") { it: Number -> it.toInt() != 0 } override suspend fun <D : ONNXData<*, *>> apply(contexts: Contexts<D>, inputs: List<TFJSTensor?>): List<TFJSTensor?> { val input = inputs[0]!!.data as NumberNDArrayTFJS return listOf(input.argmax(axis, keepDims, selectLastIndex).asTensor("reduced")) } }
7
null
7
95
e47129b6f1e2a60bf12404d8126701ce7ef4db3a
2,791
kinference
Apache License 2.0
runtime/common/src/test/kotlin/kotlinx/serialization/protobuf/ProtobufReaderTest.kt
fvasco
166,839,520
true
{"Kotlin": 289081, "HTML": 2948, "Java": 1372}
/* * Copyright 2017 JetBrains s.r.o. * * 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 kotlinx.serialization.protobuf import kotlin.test.Test class ProtobufReaderTest { @Test fun readSimpleObject() { ProtoBuf.loads<TestInt>("08ab02") shouldBe t1 } @Test fun readObjectWithString() { ProtoBuf.loads<TestString>("120774657374696E67") shouldBe t3 } @Test fun readObjectWithList() { ProtoBuf.loads<TestList>("08960108E40108B90A") shouldBe t2 } @Test fun readInnerObject() { ProtoBuf.loads<TestInner>("1a0308ab02") shouldBe t4 } @Test fun readObjectWithUnorderedTags() { ProtoBuf.loads<TestComplex>("120774657374696E67D0022A") shouldBe t5 } @Test fun readObjectsWithEmptyValues() { ProtoBuf.loads<TestInt>("0800") shouldBe t1e ProtoBuf.loads<TestList>("") shouldBe t2e ProtoBuf.loads<TestString>("1200") shouldBe t3e } @Test fun readObjectWithUnknownFields() { ProtoBuf.loads<TestInt>("08960108E40108B90A08ab02120774657374696E67") shouldBe t1 } @Test fun readNumbers() { ProtoBuf.loads<TestNumbers>("0d9488010010ffffffffffffffff7f") shouldBe t6 } }
1
Kotlin
0
0
e97b4f1f06c9522eae74cb886f109e3b2dceb6f0
1,747
kotlinx.serialization
Apache License 2.0
app/src/main/java/dev/shorthouse/coinwatch/data/source/local/CoinLocalDataSource.kt
shorthouse
655,260,745
false
{"Kotlin": 359954}
package dev.shorthouse.coinwatch.data.source.local import dev.shorthouse.coinwatch.data.source.local.model.FavouriteCoin import kotlinx.coroutines.flow.Flow class CoinLocalDataSource(private val favouriteCoinDao: FavouriteCoinDao) { fun getFavouriteCoins(): Flow<List<FavouriteCoin>> { return favouriteCoinDao.getFavouriteCoins() } fun isCoinFavourite(coinId: String): Flow<Boolean> { return favouriteCoinDao.isCoinFavourite(coinId = coinId) } suspend fun insert(favouriteCoin: FavouriteCoin) { favouriteCoinDao.insert(favouriteCoin) } suspend fun delete(favouriteCoin: FavouriteCoin) { favouriteCoinDao.delete(favouriteCoin) } }
0
Kotlin
0
9
ec946062b37a8c675798db0af440394a3c253d1d
699
CoinWatch
Apache License 2.0
mobile_app1/module994/src/main/java/module994packageKt0/Foo17.kt
uber-common
294,831,672
false
null
package module449packageKt0; annotation class Foo17Fancy @Foo17Fancy class Foo17 { fun foo0(){ module449packageKt0.Foo16().foo3() } fun foo1(){ foo0() } fun foo2(){ foo1() } fun foo3(){ foo2() } }
6
null
6
72
9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e
233
android-build-eval
Apache License 2.0
app/src/main/java/com/example/androiddevchallenge/MainActivity.kt
mbertram
342,853,590
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge import android.os.Bundle import androidx.activity.compose.setContent import androidx.annotation.PluralsRes import androidx.appcompat.app.AppCompatActivity import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.material.TopAppBar import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Favorite import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.navigation.NavController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.navigate import androidx.navigation.compose.rememberNavController import com.example.androiddevchallenge.model.PuppyProvider import com.example.androiddevchallenge.ui.PuppyDetails import com.example.androiddevchallenge.ui.PuppyList import com.example.androiddevchallenge.ui.theme.MyTheme class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MyTheme { MyApp() } } } } // Start building your app here! @Composable fun MyApp() { MaterialTheme { Surface(color = MaterialTheme.colors.background) { val navController = rememberNavController() val actions = remember(navController) { Actions(navController) } Scaffold( topBar = { TopAppBar( title = { Text( text = stringResource(R.string.app_name) ) }, actions = { IconButton(onClick = { /* doSomething() */ }) { Icon(Icons.Filled.Favorite, contentDescription = null) } } ) } ) { NavHost(navController, startDestination = "puppyList") { composable("puppyList") { PuppyList( PuppyProvider.PUPPIES, actions.puppyDetails ) } composable("puppyDetails/{puppyId}") { backStackEntry -> val puppyId = backStackEntry.arguments?.getString("puppyId") PuppyDetails(PuppyProvider.getById(puppyId)) } } } } } } class Actions(navController: NavController) { val puppyDetails: (String) -> Unit = { puppyId -> navController.navigate("puppyDetails/$puppyId") } } @Composable fun quantityStringResource(@PluralsRes id: Int, quantity: Int, vararg formatArgs: Any): String { return LocalContext.current.resources.getQuantityString(id, quantity, *formatArgs) }
0
Kotlin
0
0
6f865528e61b5f8f9e2bf6f715de7c566a15365b
3,910
jetpack-compose-challenge-week1
Apache License 2.0
compiler/testData/codegen/box/external/jvmStaticExternalPrivate.kt
JakeWharton
99,388,807
false
null
// IGNORE_BACKEND: JVM_IR // IGNORE_BACKEND: JS_IR // TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_RUNTIME // FULL_JDK class C { companion object { private @JvmStatic external fun foo() } fun bar() { foo() } } fun box(): String { try { C().bar() return "Link error expected" } catch (e: java.lang.UnsatisfiedLinkError) { if (e.message != "C.foo()V") return "Fail 1: " + e.message } return "OK" }
3
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
540
kotlin
Apache License 2.0
app/src/main/java/com/example/belindas_closet/screen/IndividualProductUpdate.kt
SeattleColleges
656,918,420
false
{"Kotlin": 132693}
package com.example.belindas_closet.screen import androidx.compose.foundation.Image import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Check import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Edit import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.material3.TopAppBar 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.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.window.Dialog import androidx.navigation.NavController import com.example.belindas_closet.MainActivity import com.example.belindas_closet.R import com.example.belindas_closet.Routes import com.example.belindas_closet.data.Datasource import com.example.belindas_closet.model.Product import com.example.belindas_closet.model.Sizes @OptIn(ExperimentalMaterial3Api::class) @Composable fun IndividualProductUpdatePage(navController: NavController, productId: String) { Scaffold( modifier = Modifier .fillMaxSize(), topBar = { /* Back arrow that navigates back to login page */ TopAppBar( title = { Text("Home") }, navigationIcon = { IconButton( onClick = { navController.navigate(Routes.IndividualProduct.route+"/${productId}") } ) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = "Back to Home page" ) } } ) }, ) { innerPadding -> val modifier = Modifier.padding(innerPadding) Column( modifier = modifier .fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { CustomTextField(text = productId) val product = Datasource().loadProducts().find { it.name == productId }!! UpdateIndividualProductCard(product = product, navController = navController) } } } @Composable fun UpdateIndividualProductCard(product: Product, navController: NavController) { var isEditing by remember { mutableStateOf(false) } var isDelete by remember { mutableStateOf(false) } var isSave by remember { mutableStateOf(false) } var isCancel by remember { mutableStateOf(false) } Card( modifier = Modifier .padding(8.dp) ) { Column( modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.CenterHorizontally ) { Image( painter = painterResource(id = product.image.toInt()), contentDescription = stringResource(id = R.string.product_image_description), modifier = Modifier .size(200.dp) .padding(16.dp), ) Text( text = "Name: ${product.name}", style = TextStyle( fontSize = 15.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Default, ), modifier = Modifier.wrapContentSize() ) Text(text = "Size: ${product.size}") Text(text = "Description: ${product.description}") // Display the text fields and buttons if (isEditing) { TextFieldEditableIndividual( initialName = product.name, initialDescription = product.description, initialSize = product.size ) Row { Button(onClick = { isCancel = !isCancel }) { Icon( imageVector = Icons.Default.Close, contentDescription = "Cancel" ) } if (isCancel) { ConfirmCancelDialogIndividual(onConfirm = { // TODO: Cancel the edit // Keep the original data isCancel = false }, onDismiss = { isCancel = false }, navController = navController, productId = product.name) } Spacer(modifier = Modifier.padding(8.dp)) Button(onClick = { isSave = !isSave }) { Icon( imageVector = Icons.Default.Check, contentDescription = "Save" ) } if (isSave) { ConfirmSaveDialogIndividual(onConfirm = { // TODO: Save the product to the database // Update the product with the new data isSave = false }, onDismiss = { isSave = false }) } } } else { Row( modifier = Modifier .wrapContentSize() .padding(16.dp), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { Button(onClick = { isDelete = !isDelete }) { Icon( imageVector = Icons.Default.Delete, contentDescription = "Delete" ) } if (isDelete) { ConfirmationDialogIndividual(onConfirm = { val hidden = MainActivity.getPref().getStringSet("hidden", mutableSetOf(product.name)) hidden?.add(product.name) val editor = MainActivity.getPref().edit() editor.putStringSet("hidden", hidden) editor.apply() navController.navigate(Routes.ProductDetail.route) // TODO: Delete the product from the database // Remove the product from the database isDelete = false }, onDismiss = { isDelete = false }) } Spacer(modifier = Modifier.padding(16.dp)) Button(onClick = { isEditing = !isEditing }) { Icon( imageVector = Icons.Default.Edit, contentDescription = "Edit" ) } } } } } } @Composable fun TextFieldEditableIndividual( initialName: String, initialDescription: String, initialSize: Sizes ) { var updateName by remember { mutableStateOf(initialName) } var updateDescription by remember { mutableStateOf(initialDescription) } var selectedSize by remember { mutableStateOf(initialSize) } var isDropdownMenuExpanded by remember { mutableStateOf(false) } val sizes = Sizes.values() TextField( value = updateName, onValueChange = { editName -> updateName = editName }, label = { Text("Name") }, singleLine = true, modifier = Modifier .padding(8.dp) ) TextField( value = updateDescription, onValueChange = { newDescription -> updateDescription = newDescription }, label = { Text("Description") }, singleLine = true, modifier = Modifier .padding(8.dp) ) Box(modifier = Modifier .fillMaxWidth() .clickable { isDropdownMenuExpanded = !isDropdownMenuExpanded }) { Text( text = "Size: ${selectedSize.name}", modifier = Modifier.padding(horizontal = 48.dp, vertical = 16.dp) ) DropdownMenu(expanded = isDropdownMenuExpanded, onDismissRequest = { isDropdownMenuExpanded = false }) { sizes.forEach { size -> DropdownMenuItem(text = { Text(size.name) }, onClick = { selectedSize = size isDropdownMenuExpanded = false }) } } } //TODO: Add image field, can be called from the AddProduct.kt } @Composable fun ConfirmationDialogIndividual( onConfirm: () -> Unit, onDismiss: () -> Unit ) { Dialog(onDismissRequest = { onDismiss() }) { Card( modifier = Modifier .padding(16.dp) .border(1.dp, Color.White) ) { Column( modifier = Modifier .padding(16.dp) .fillMaxWidth(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text(stringResource(R.string.update_delete_confirm_text)) Spacer(modifier = Modifier.padding(8.dp)) Row( modifier = Modifier .fillMaxWidth() .padding(8.dp), horizontalArrangement = Arrangement.Center ) { Button( onClick = { onDismiss() }, modifier = Modifier.padding(8.dp) ) { Text("No") } Button( onClick = { onConfirm() }, modifier = Modifier.padding(8.dp) ) { Text("Yes") } } } } } } @Composable fun ConfirmSaveDialogIndividual( onConfirm: () -> Unit, onDismiss: () -> Unit ) { Dialog(onDismissRequest = { onDismiss() }) { Card( modifier = Modifier .padding(16.dp) .border(1.dp, Color.White), ) { Column( modifier = Modifier .padding(16.dp) .fillMaxWidth(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text(stringResource(R.string.update_save_confirm_text)) Spacer(modifier = Modifier.padding(8.dp)) Row( modifier = Modifier .fillMaxWidth() .padding(8.dp), horizontalArrangement = Arrangement.Center ) { Button( onClick = { onDismiss() }, modifier = Modifier.padding(8.dp) ) { Text("No") } Button( onClick = { onConfirm() }, modifier = Modifier.padding(8.dp) ) { Text("Yes") } } } } } } @Composable fun ConfirmCancelDialogIndividual( onConfirm: () -> Unit, onDismiss: () -> Unit, navController: NavController, productId: String ) { Dialog(onDismissRequest = { onDismiss() }) { Card( modifier = Modifier .padding(16.dp) .border(1.dp, Color.White), ) { Column( modifier = Modifier .padding(16.dp) .fillMaxWidth(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text(stringResource(R.string.update_cancel_confirm_text)) Spacer(modifier = Modifier.padding(8.dp)) Row( modifier = Modifier .fillMaxWidth() .padding(8.dp), horizontalArrangement = Arrangement.Center ) { Button( onClick = { onDismiss() }, modifier = Modifier.padding(8.dp) ) { Text("No") } Button( onClick = { onConfirm() navController.navigate(Routes.IndividualProduct.route+"/${productId}") }, modifier = Modifier.padding(8.dp) ) { Text("Yes") } } } } } }
39
Kotlin
4
5
e4cb53c1fc86d44ea0ef34020215f91fb469763c
14,771
belindas-closet-android
MIT License
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/resources/testProject/expect-actual-fun-or-class-ic/src/commonMain/kotlin/ExpectFunFoo.kt
JetBrains
3,432,266
false
null
expect fun foo(): Any fun fooImpl() = secret
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
45
kotlin
Apache License 2.0
src/main/kotlin/com/quasar/dorm/persistence/entity/AttributeEntity.kt
coolsamson7
856,851,180
false
{"Kotlin": 131719, "ANTLR": 26817}
package com.quasar.dorm.persistence.entity /* * @COPYRIGHT (C) 2023 <NAME> * * All rights reserved */ import jakarta.persistence.* import java.io.Serializable data class AttributeId(private val entity: Int = 0, private val attribute: String = "") : Serializable @Entity @Table(name="ATTRIBUTE", indexes = [ Index(columnList = "TYPE"), Index(columnList = "INT_VALUE"), Index(columnList = "DOUBLE_VALUE"), Index(columnList = "STRING_VALUE") ] ) @IdClass(AttributeId::class) data class AttributeEntity( @ManyToOne(fetch = FetchType.LAZY) @MapsId @JoinColumn(name = "ENTITY") var entity : EntityEntity, @Column(name = "ATTRIBUTE") @Id var attribute : String, @Column(name = "TYPE") var type : String, @Column(name = "STRING_VALUE") var stringValue : String, @Column(name = "INT_VALUE") var intValue : Int, @Column(name = "DOUBLE_VALUE") var doubleValue : Double, @ManyToMany(fetch = FetchType.LAZY) @JoinTable( name = "ATTRIBUTE_ENTITY", joinColumns = [JoinColumn(name = "ENTITY"), JoinColumn(name = "ATTRIBUTE")], inverseJoinColumns = [JoinColumn(name = "ID")] ) val relations : MutableSet<EntityEntity> = HashSet() )
0
Kotlin
0
0
8a0fa2f86c2e92c6b192c53bd485d2a078e1e27e
1,267
dorm
Apache License 2.0
src/main/kotlin/jp/assasans/araumi/tx/server/ecs/components/entrance/SessionSecurityPublicComponent.kt
AraumiTX
604,259,602
false
null
package jp.assasans.araumi.tx.server.ecs.components.entrance import jp.assasans.araumi.tx.server.ecs.components.IComponent import jp.assasans.araumi.tx.server.protocol.ProtocolId @ProtocolId(1439792100478) data class SessionSecurityPublicComponent( val publicKey: String ) : IComponent
0
Kotlin
2
3
6adc36adc5f7d83c965143f5d3108f6d6ceaf186
290
game-server
MIT License
app/src/main/java/com/example/tiptime/UserRegister.kt
adorain
786,890,454
false
{"Kotlin": 365003}
package com.example.tiptime import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.semantics.SemanticsProperties.Password import androidx.lifecycle.ViewModel import com.example.tiptime.Data.Booking import com.example.tiptime.Data.Login import com.example.tiptime.Data.User import com.example.tiptime.Data.room import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import java.util.Date class UserRegister : ViewModel(){ private val _uiState = MutableStateFlow(Login()) val uiState: StateFlow<Login> = _uiState.asStateFlow() var userPassword by mutableStateOf("") var userEmail by mutableStateOf("") private val _uiRegisterState = MutableStateFlow(Login()) val uiRegisterState: StateFlow<Login> = _uiRegisterState.asStateFlow() fun insertNewU_User(Password: String, Email: String) { val userData = Login( Password, Email, ) } fun setUserPassword() : String{ _uiRegisterState.update { uiRegisterState -> uiRegisterState.copy( Password = <PASSWORD> ) } return userPassword } fun updateUserPassword(Password : String){ userPassword = Password } fun setUserEmail() : String{ _uiRegisterState.update { uiRegisterState -> uiRegisterState.copy( Email = userEmail ) } return userEmail } fun updateUserEmail(Email : String){ userEmail = Email } }
0
Kotlin
1
0
2405735cc1d0476e65157ddd05302ba8d0a6c6dc
1,742
development
Apache License 2.0
firebase-inappmessaging-display/src/test/java/com/google/firebase/inappmessaging/display/ktx/InAppMessagingDisplayTests.kt
firebase
146,941,185
false
null
// Copyright 2019 Google LLC // // 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.google.firebase.inappmessaging.display.ktx import androidx.test.core.app.ApplicationProvider import com.google.common.truth.Truth.assertThat import com.google.firebase.FirebaseApp import com.google.firebase.FirebaseOptions import com.google.firebase.inappmessaging.display.FirebaseInAppMessagingDisplay import com.google.firebase.ktx.Firebase import com.google.firebase.ktx.app import com.google.firebase.ktx.initialize import com.google.firebase.platforminfo.UserAgentPublisher import java.util.UUID import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner internal const val APP_ID = "APP:ID" internal val API_KEY = "ABC" + UUID.randomUUID().toString() const val EXISTING_APP = "existing" abstract class BaseTestCase { @Before fun setUp() { Firebase.initialize( ApplicationProvider.getApplicationContext(), FirebaseOptions.Builder() .setApplicationId(APP_ID) .setApiKey(API_KEY) .setProjectId("123") .build() ) Firebase.initialize( ApplicationProvider.getApplicationContext(), FirebaseOptions.Builder() .setApplicationId(APP_ID) .setApiKey(API_KEY) .setProjectId("123") .build(), EXISTING_APP ) } @After fun cleanUp() { FirebaseApp.clearInstancesForTest() } } @RunWith(RobolectricTestRunner::class) class InAppMessagingDisplayTests : BaseTestCase() { @Test fun `inAppMessagingDisplay should delegate to FirebaseInAppMessagingDisplay#getInstance()`() { assertThat(Firebase.inAppMessagingDisplay) .isSameInstanceAs(FirebaseInAppMessagingDisplay.getInstance()) } } @RunWith(RobolectricTestRunner::class) class LibraryVersionTest : BaseTestCase() { @Test fun `library version should be registered with runtime`() { val publisher = Firebase.app.get(UserAgentPublisher::class.java) } }
442
null
575
2,270
0697dd3aadd6c13d9e2d321c75173992bfbaac3b
2,533
firebase-android-sdk
Apache License 2.0
imx-core-sdk-kotlin-jvm/src/main/kotlin/com/immutable/sdk/ImmutableX.kt
immutable
467,767,205
false
null
package com.immutable.sdk import com.google.common.annotations.VisibleForTesting import com.immutable.sdk.Constants.DEFAULT_MOONPAY_COLOUR_CODE import com.immutable.sdk.api.AssetsApi import com.immutable.sdk.api.BalancesApi import com.immutable.sdk.api.CollectionsApi import com.immutable.sdk.api.DepositsApi import com.immutable.sdk.api.MetadataApi import com.immutable.sdk.api.MintsApi import com.immutable.sdk.api.ProjectsApi import com.immutable.sdk.api.EncodingApi import com.immutable.sdk.api.UsersApi import com.immutable.sdk.api.WithdrawalsApi import com.immutable.sdk.api.OrdersApi import com.immutable.sdk.api.TradesApi import com.immutable.sdk.api.TokensApi import com.immutable.sdk.api.TransfersApi import com.immutable.sdk.api.model.* import com.immutable.sdk.api.model.Collection import com.immutable.sdk.model.AssetModel import com.immutable.sdk.model.Erc721Asset import com.immutable.sdk.workflows.TransferData import com.immutable.sdk.workflows.call import com.immutable.sdk.workflows.imxTimestampRequest import com.immutable.sdk.workflows.isRegisteredOnChain import okhttp3.logging.HttpLoggingInterceptor import org.openapitools.client.infrastructure.ClientException import org.openapitools.client.infrastructure.ServerException import org.web3j.tx.gas.DefaultGasProvider import org.web3j.tx.gas.StaticGasProvider import java.util.concurrent.CompletableFuture /** * An enum for defining the environment the SDK will communicate with */ enum class ImmutableXBase { Production, Ropsten, Sandbox } /** * An enum for defining the log level of the API HTTP calls */ enum class ImmutableXHttpLoggingLevel { /** * No logs * * @see [HttpLoggingInterceptor.Level.NONE] */ None, /** * Logs request and response lines * * @see [HttpLoggingInterceptor.Level.BASIC] */ Basic, /** * Logs request and response lines and their respective headers * * @see [HttpLoggingInterceptor.Level.HEADERS] */ Headers, /** * Logs request and response lines and their respective headers and bodies (if present). * * @see [HttpLoggingInterceptor.Level.BODY] */ Body } @VisibleForTesting internal const val KEY_BASE_URL = "org.openapitools.client.baseUrl" /** * This is the entry point for the Immutable X SDK. * * You can configure the environment or use any of the provided utility workflows which chain * the necessary calls to perform standard actions (e.g. buy, sell etc). * * @param base the environment the SDK will communicate with * @param nodeUrl (optional) Ethereum node URL. This is only required for smart contract interactions. */ @Suppress("TooManyFunctions", "LargeClass") class ImmutableX( private val base: ImmutableXBase = ImmutableXBase.Production, private val nodeUrl: String? = null ) { val assetsApi by lazy { AssetsApi() } val balancesApi by lazy { BalancesApi() } val collectionsApi by lazy { CollectionsApi() } val depositsApi by lazy { DepositsApi() } val metadataApi by lazy { MetadataApi() } val mintsApi by lazy { MintsApi() } val ordersApi by lazy { OrdersApi() } val projectsApi by lazy { ProjectsApi() } val tokensApi by lazy { TokensApi() } val tradesApi by lazy { TradesApi() } val transfersApi by lazy { TransfersApi() } val usersApi by lazy { UsersApi() } val withdrawalsApi by lazy { WithdrawalsApi() } val encodingApi by lazy { EncodingApi() } init { setBaseUrl() } private fun setBaseUrl() { System.getProperties() .setProperty(KEY_BASE_URL, ImmutableConfig.getPublicApiUrl(base)) } /** * Sets the API HTTP logging level. The default is [ImmutableXHttpLoggingLevel.None]. */ fun setHttpLoggingLevel(level: ImmutableXHttpLoggingLevel) { httpLoggingLevel = level } /** * Deposit based on a token type. * For unregistered users, the deposit will be combined with a registration in order to * register the user first. * @param token the token type amount in its corresponding unit * @param signer the L1 signer * @param gasProvider the gas provider to be used when interacting with smart contracts * @returns a [CompletableFuture] that will provide the transaction hash if successful. */ fun deposit( token: AssetModel, signer: Signer, gasProvider: StaticGasProvider = DefaultGasProvider() ): CompletableFuture<String> { checkNotNull(nodeUrl) { "nodeUrl cannot be null" } return com.immutable.sdk.workflows.deposit( base, nodeUrl, token, signer, depositsApi, usersApi, encodingApi, gasProvider ) } /** * Get details of a Deposit with the given ID * @parem the deposit ID * @throws [ImmutableException.apiError] */ fun getDeposit(id: String): Deposit = apiCall("getDeposit") { depositsApi.getDeposit(id) } /** * Get a list of deposits * @param pageSize Page size of the result (optional) * @param cursor Cursor (optional) * @param orderBy Property to sort by (optional) * @param direction Direction to sort (asc/desc) (optional) * @param user Ethereum address of the user who submitted this deposit (optional) * @param status Status of this deposit (optional) * @param updatedMinTimestamp Minimum timestamp for this deposit, in ISO 8601 UTC format. Example: &#39;2022-05-27T00:10:22Z&#39; (optional) * @param updatedMaxTimestamp Maximum timestamp for this deposit, in ISO 8601 UTC format. Example: &#39;2022-05-27T00:10:22Z&#39; (optional) * @param tokenType Token type of the deposited asset (optional) * @param tokenId ERC721 Token ID of the minted asset (optional) * @param assetId Internal IMX ID of the minted asset (optional) * @param tokenAddress Token address of the deposited asset (optional) * @param tokenName Token name of the deposited asset (optional) * @param minQuantity Min quantity for the deposited asset (optional) * @param maxQuantity Max quantity for the deposited asset (optional) * @param metadata JSON-encoded metadata filters for the deposited asset (optional) * @return ListDepositsResponse * @throws [ImmutableException.apiError] */ @Suppress("LongParameterList") fun listDeposits( pageSize: Int? = null, cursor: String? = null, orderBy: String? = null, direction: String? = null, user: String? = null, status: String? = null, updatedMinTimestamp: String? = null, updatedMaxTimestamp: String? = null, tokenType: String? = null, tokenId: String? = null, assetId: String? = null, tokenAddress: String? = null, tokenName: String? = null, minQuantity: String? = null, maxQuantity: String? = null, metadata: String? = null ): ListDepositsResponse = apiCall("listDeposits") { depositsApi.listDeposits( pageSize, cursor, orderBy, direction, user, status, updatedMinTimestamp, updatedMaxTimestamp, tokenType, tokenId, assetId, tokenAddress, tokenName, minQuantity, maxQuantity, metadata ) } /** * This is a utility function that will register a user to Immutable X if they aren't already. * * @param signer represents the users L1 wallet to get the address and sign the registration * * @return a [CompletableFuture] with the value [Unit] being provided on success. If it failed * a [Throwable] will be given. */ fun registerOffChain(signer: Signer, starkSigner: StarkSigner): CompletableFuture<Unit> = com.immutable.sdk.workflows.registerOffChain(signer, starkSigner) /** * Checks if a user is registered on on-chain * * @param signer represents the users L1 wallet to get the address * @param gasProvider the gas provider to be used when interacting with smart contracts * @returns a [CompletableFuture] with the the value true if the user is registered. */ fun isRegisteredOnChain( signer: Signer, gasProvider: StaticGasProvider = DefaultGasProvider() ): CompletableFuture<Boolean> { checkNotNull(nodeUrl) { "nodeUrl cannot be null" } return isRegisteredOnChain(base, nodeUrl, signer, usersApi, gasProvider) } /** * Get stark keys for a registered user * @param ethAddress The user's Ethereum address * @return GetUsersApiResponse * @throws [ImmutableException.apiError] */ fun getUser(ethAddress: String) = apiCall("getUser") { usersApi.getUsers(ethAddress) } /** * Get details of an asset * * @param tokenAddress Address of the ERC721 contract * @param tokenId Either ERC721 token ID or internal IMX ID * @param includeFees Set flag to include fees associated with the asset (optional) * @return Asset * @throws [ImmutableException.apiError] */ fun getAsset(tokenAddress: String, tokenId: String, includeFees: Boolean? = null) = apiCall("getAsset") { assetsApi.getAsset(tokenAddress, tokenId, includeFees) } /** * Get a list of assets * * @param pageSize Page size of the result (optional) * @param cursor Cursor (optional) * @param orderBy Property to sort by (optional) * @param direction Direction to sort (asc/desc) (optional) * @param user Ethereum address of the user who owns these assets (optional) * @param status Status of these assets (optional) * @param name Name of the asset to search (optional) * @param metadata JSON-encoded metadata filters for these asset. Example: {&#39;proto&#39;:[&#39;1147&#39;],&#39;quality&#39;:[&#39;Meteorite&#39;]} (optional) * @param sellOrders Set flag to true to fetch an array of sell order details with accepted status associated with the asset (optional) * @param buyOrders Set flag to true to fetch an array of buy order details with accepted status associated with the asset (optional) * @param includeFees Set flag to include fees associated with the asset (optional) * @param collection Collection contract address (optional) * @param updatedMinTimestamp Minimum timestamp for when these assets were last updated, in ISO 8601 UTC format. Example: &#39;2022-05-27T00:10:22Z&#39; (optional) * @param updatedMaxTimestamp Maximum timestamp for when these assets were last updated, in ISO 8601 UTC format. Example: &#39;2022-05-27T00:10:22Z&#39; (optional) * @param auxiliaryFeePercentages Comma separated string of fee percentages that are to be paired with auxiliary_fee_recipients (optional) * @param auxiliaryFeeRecipients Comma separated string of fee recipients that are to be paired with auxiliary_fee_percentages (optional) * @return ListAssetsResponse * @throws [ImmutableException.apiError] */ @Suppress("LongParameterList") fun listAssets( pageSize: Int? = null, cursor: String? = null, orderBy: String? = null, direction: String? = null, user: String? = null, status: String? = null, name: String? = null, metadata: String? = null, sellOrders: Boolean? = null, buyOrders: Boolean? = null, includeFees: Boolean? = null, collection: String? = null, updatedMinTimestamp: String? = null, updatedMaxTimestamp: String? = null, auxiliaryFeePercentages: String? = null, auxiliaryFeeRecipients: String? = null ) = apiCall("listAssets") { assetsApi.listAssets( pageSize, cursor, orderBy, direction, user, status, name, metadata, sellOrders, buyOrders, includeFees, collection, updatedMinTimestamp, updatedMaxTimestamp, auxiliaryFeePercentages, auxiliaryFeeRecipients ) } /** * Create collection * * @param createCollectionRequest create a collection * @param signer represents the users L1 wallet to get the address and sign the registration * @return CompletableFuture<Collection> */ fun createCollection( request: CreateCollectionRequest, signer: Signer ): CompletableFuture<Collection> = imxTimestampRequest(signer) { timestamp -> call("createCollection") { collectionsApi.createCollection(timestamp.signature, timestamp.timestamp, request) } } /** * Get details of a collection at the given address * * @param address Collection contract address * @return Collection * @throws [ImmutableException.apiError] */ fun getCollection(address: String) = apiCall("getCollection") { collectionsApi.getCollection(address) } /** * Get a list of collection filters * * @param address Collection contract address * @param pageSize Page size of the result (optional) * @param nextPageToken Next page token (optional) * @return CollectionFilter * @throws [ImmutableException.apiError] */ fun listCollectionFilters( address: String, pageSize: Int? = null, nextPageToken: String? = null ) = apiCall("listCollectionFilters") { collectionsApi.listCollectionFilters(address, pageSize, nextPageToken) } /** * Get a list of collections * * @param pageSize Page size of the result (optional) * @param cursor Cursor (optional) * @param orderBy Property to sort by (optional) * @param direction Direction to sort (asc/desc) (optional) * @param blacklist List of collections not to be included, separated by commas (optional) * @param whitelist List of collections to be included, separated by commas (optional) * @param keyword Keyword to search in collection name and description (optional) * @return ListCollectionsResponse * @throws [ImmutableException.apiError] */ @Suppress("LongParameterList") fun listCollections( pageSize: Int? = null, cursor: String? = null, orderBy: String? = null, direction: String? = null, blacklist: String? = null, whitelist: String? = null, keyword: String? = null ) = apiCall("listCollections") { collectionsApi.listCollections( pageSize, cursor, orderBy, direction, blacklist, whitelist, keyword ) } /** * Update collection * * @param address Collection contract address * @param updateCollectionRequest update a collection * @param signer represents the users L1 wallet to get the address and sign the registration * @return CompletableFuture<Collection> */ fun updateCollection( address: String, updateCollectionRequest: UpdateCollectionRequest, signer: Signer ) = imxTimestampRequest(signer) { timestamp -> call("updateCollection") { collectionsApi.updateCollection( address, timestamp.signature, timestamp.timestamp, updateCollectionRequest ) } } /** * Add metadata schema to collection * * @param address Collection contract address * @param addMetadataSchemaToCollectionRequest add metadata schema to a collection * @param signer represents the users L1 wallet to get the address and sign the registration * @return CompletableFuture<SuccessResponse> * @throws UnsupportedOperationException If the API returns an informational or redirection response * @throws ClientException If the API returns a client error response * @throws ServerException If the API returns a server error response */ fun addMetadataSchemaToCollection( address: String, addMetadataSchemaToCollectionRequest: AddMetadataSchemaToCollectionRequest, signer: Signer ) = imxTimestampRequest(signer) { timestamp -> call("addMetadataSchemaToCollection") { metadataApi.addMetadataSchemaToCollection( address, timestamp.signature, timestamp.timestamp, addMetadataSchemaToCollectionRequest ) } } /** * Get collection metadata schema * * @param address Collection contract address * @return kotlin.collections.List<MetadataSchemaProperty> * @throws [ImmutableException.apiError] */ fun getMetadataSchema(address: String) = apiCall("getMetadataSchema") { metadataApi.getMetadataSchema(address) } /** * Update metadata schema by name * * @param address Collection contract address * @param name Metadata schema name * @param metadataSchemaRequest update metadata schema * @param signer represents the users L1 wallet to get the address and sign the registration * @return CompletableFuture<SuccessResponse> * @throws UnsupportedOperationException If the API returns an informational or redirection response * @throws ClientException If the API returns a client error response * @throws ServerException If the API returns a server error response */ fun updateMetadataSchemaByName( address: String, name: String, metadataSchemaRequest: MetadataSchemaRequest, signer: Signer ) = imxTimestampRequest(signer) { timestamp -> call("updateMetadataSchemaByName") { metadataApi.updateMetadataSchemaByName( address, name, timestamp.signature, timestamp.timestamp, metadataSchemaRequest ) } } /** * Create a project * * @param createProjectRequest create a project * @param signer represents the users L1 wallet to get the address and sign the registration * @return CompletableFuture<CreateProjectResponse> * @throws UnsupportedOperationException If the API returns an informational or redirection response * @throws ClientException If the API returns a client error response * @throws ServerException If the API returns a server error response */ fun createProject( createProjectRequest: CreateProjectRequest, signer: Signer ) = imxTimestampRequest(signer) { timestamp -> call("createProject") { projectsApi.createProject( timestamp.signature, timestamp.timestamp, createProjectRequest ) } } /** * Get a project * * @param id Project ID * @param signer represents the users L1 wallet to get the address and sign the registration * @return CompletableFuture<Project> * @throws UnsupportedOperationException If the API returns an informational or redirection response * @throws ClientException If the API returns a client error response * @throws ServerException If the API returns a server error response */ fun getProject(id: String, signer: Signer) = imxTimestampRequest(signer) { timestamp -> call("getProject") { projectsApi.getProject( id, timestamp.signature, timestamp.timestamp ) } } /** * Get projects * * @param pageSize Page size of the result (optional) * @param cursor Cursor (optional) * @param orderBy Property to sort by (optional) * @param direction Direction to sort (asc/desc) (optional) * * @param signer represents the users L1 wallet to get the address and sign the registration * @return CompletableFuture<GetProjectsResponse> * @throws UnsupportedOperationException If the API returns an informational or redirection response * @throws ClientException If the API returns a client error response * @throws ServerException If the API returns a server error response */ fun getProjects( pageSize: Int? = null, cursor: String? = null, orderBy: String? = null, direction: String? = null, signer: Signer ) = imxTimestampRequest(signer) { timestamp -> call("getProjects") { projectsApi.getProjects( timestamp.signature, timestamp.timestamp, pageSize, cursor, orderBy, direction ) } } /** * Fetches the token balances of the user * * @param owner Address of the owner/user * @param address Token address * @return Balance * @throws [ImmutableException.apiError] */ fun getBalance(owner: String, address: String) = apiCall("getBalance") { balancesApi.getBalance(owner, address) } /** * Get a list of balances for given user * * @param owner Ethereum wallet address for user * @return ListBalancesResponse * @throws [ImmutableException.apiError] */ fun listBalances(owner: String) = apiCall("listBalances") { balancesApi.listBalances(owner) } /** * Get details of a mint with the given ID * * @param id Mint ID. This is the transaction_id returned from listMints * @return Mint * @throws [ImmutableException.apiError] */ fun getMint(id: String) = apiCall("getMint") { mintsApi.getMint(id) } /** * Get a list of mints * * @param pageSize Page size of the result (optional) * @param cursor Cursor (optional) * @param orderBy Property to sort by (optional) * @param direction Direction to sort (asc/desc) (optional) * @param user Ethereum address of the user who submitted this mint (optional) * @param status Status of this mint (optional) * @param updatedMinTimestamp Minimum timestamp for this mint, in ISO 8601 UTC format. Example: &#39;2022-05-27T00:10:22Z&#39; (optional) * @param updatedMaxTimestamp Maximum timestamp for this mint, in ISO 8601 UTC format. Example: &#39;2022-05-27T00:10:22Z&#39; (optional) * @param tokenType Token type of the minted asset (optional) * @param tokenId ERC721 Token ID of the minted asset (optional) * @param assetId Internal IMX ID of the minted asset (optional) * @param tokenName Token Name of the minted asset (optional) * @param tokenAddress Token address of the minted asset (optional) * @param minQuantity Min quantity for the minted asset (optional) * @param maxQuantity Max quantity for the minted asset (optional) * @param metadata JSON-encoded metadata filters for the minted asset (optional) * @return ListMintsResponse * @throws [ImmutableException.apiError] */ @Suppress("LongParameterList") fun listMints( pageSize: Int? = null, cursor: String? = null, orderBy: String? = null, direction: String? = null, user: String? = null, status: String? = null, updatedMinTimestamp: String? = null, updatedMaxTimestamp: String? = null, tokenType: String? = null, tokenId: String? = null, assetId: String? = null, tokenName: String? = null, tokenAddress: String? = null, minQuantity: String? = null, maxQuantity: String? = null, metadata: String? = null ) = apiCall("listMints") { mintsApi.listMints( pageSize, cursor, orderBy, direction, user, status, updatedMinTimestamp, updatedMaxTimestamp, tokenType, tokenId, assetId, tokenName, tokenAddress, minQuantity, maxQuantity, metadata ) } /** * Mint tokens in a batch with fees * @param request - the request object to be provided in the API request * @param signer - the L1 signer * @returns a [CompletableFuture] that will provide all minting results if successful. */ fun mint(request: UnsignedMintRequest, signer: Signer): CompletableFuture<List<MintResultDetails>> { return com.immutable.sdk.workflows.mint(request, signer, mintsApi) } /** * Get a list of withdrawals * * @param withdrawnToWallet Withdrawal has been transferred to user&#39;s Layer 1 wallet (optional) * @param rollupStatus Status of the on-chain batch confirmation for this withdrawal (optional) * @param pageSize Page size of the result (optional) * @param cursor Cursor (optional) * @param orderBy Property to sort by (optional) * @param direction Direction to sort (asc/desc) (optional) * @param user Ethereum address of the user who submitted this withdrawal (optional) * @param status Status of this withdrawal (optional) * @param minTimestamp Minimum timestamp for this deposit, in ISO 8601 UTC format. Example: &#39;2022-05-27T00:10:22Z&#39; (optional) * @param maxTimestamp Maximum timestamp for this deposit, in ISO 8601 UTC format. Example: &#39;2022-05-27T00:10:22Z&#39; (optional) * @param tokenType Token type of the withdrawn asset (optional) * @param tokenId ERC721 Token ID of the minted asset (optional) * @param assetId Internal IMX ID of the minted asset (optional) * @param tokenAddress Token address of the withdrawn asset (optional) * @param tokenName Token name of the withdrawn asset (optional) * @param minQuantity Min quantity for the withdrawn asset (optional) * @param maxQuantity Max quantity for the withdrawn asset (optional) * @param metadata JSON-encoded metadata filters for the withdrawn asset (optional) * @return ListWithdrawalsResponse * @throws [ImmutableException.apiError] */ @Suppress("LongParameterList") fun listWithdrawals( withdrawnToWallet: Boolean? = null, rollupStatus: String? = null, pageSize: Int? = null, cursor: String? = null, orderBy: String? = null, direction: String? = null, user: String? = null, status: String? = null, minTimestamp: String? = null, maxTimestamp: String? = null, tokenType: String? = null, tokenId: String? = null, assetId: String? = null, tokenAddress: String? = null, tokenName: String? = null, minQuantity: String? = null, maxQuantity: String? = null, metadata: String? = null ) = apiCall("listWithdrawals") { withdrawalsApi.listWithdrawals( withdrawnToWallet, rollupStatus, pageSize, cursor, orderBy, direction, user, status, minTimestamp, maxTimestamp, tokenType, tokenId, assetId, tokenAddress, tokenName, minQuantity, maxQuantity, metadata ) } /** * Gets details of withdrawal with the given ID * * @param id Withdrawal ID * @return Withdrawal * @throws [ImmutableException.apiError] */ fun getWithdrawal(id: String) = apiCall("getWithdrawal") { withdrawalsApi.getWithdrawal(id) } /** * Create a Withdrawal * @param token the token type amount in its corresponding unit * @param signer the L1 signer * @param starkSigner represents the users L2 wallet used to sign and verify the L2 transaction * @returns a [CompletableFuture] that will provide the transaction hash if successful. */ fun prepareWithdrawal( token: AssetModel, signer: Signer, starkSigner: StarkSigner ): CompletableFuture<CreateWithdrawalResponse> = com.immutable.sdk.workflows.withdrawal.prepareWithdrawal( token, signer, starkSigner, withdrawalsApi ) /** * Completes a Withdrawal * @param token the token * @param signer the L1 signer * @param starkPublicKey the L2 stark public key * @param gasProvider the gas provider to be used when interacting with smart contracts * @returns a [CompletableFuture] that will provide the transaction hash if successful. */ fun completeWithdrawal( token: AssetModel, signer: Signer, starkPublicKey: String, gasProvider: StaticGasProvider = DefaultGasProvider() ): CompletableFuture<String> { checkNotNull(nodeUrl) { "nodeUrl cannot be null" } return com.immutable.sdk.workflows.completeWithdrawal( base, nodeUrl, token, signer, starkPublicKey, usersApi, encodingApi, mintsApi, gasProvider ) } /** * Get details of an order with the given ID * * @param id Order ID * @param includeFees Set flag to true to include fee body for the order (optional) * @param auxiliaryFeePercentages Comma separated string of fee percentages that are to be paired with auxiliary_fee_recipients (optional) * @param auxiliaryFeeRecipients Comma separated string of fee recipients that are to be paired with auxiliary_fee_percentages (optional) * @return Order * @throws [ImmutableException.apiError] */ fun getOrder( id: String, includeFees: Boolean? = null, auxiliaryFeePercentages: String? = null, auxiliaryFeeRecipients: String? = null ) = apiCall("getOrder") { ordersApi.getOrder(id, includeFees, auxiliaryFeePercentages, auxiliaryFeeRecipients) } /** * Get a list of orders * * @param pageSize Page size of the result (optional) * @param cursor Cursor (optional) * @param orderBy Property to sort by (optional) * @param direction Direction to sort (asc/desc) (optional) * @param user Ethereum address of the user who submitted this order (optional) * @param status Status of this order (optional) * @param minTimestamp Minimum created at timestamp for this order, in ISO 8601 UTC format. Example: &#39;2022-05-27T00:10:22Z&#39; (optional) * @param maxTimestamp Maximum created at timestamp for this order, in ISO 8601 UTC format. Example: &#39;2022-05-27T00:10:22Z&#39; (optional) * @param updatedMinTimestamp Minimum updated at timestamp for this order, in ISO 8601 UTC format. Example: &#39;2022-05-27T00:10:22Z&#39; (optional) * @param updatedMaxTimestamp Maximum updated at timestamp for this order, in ISO 8601 UTC format. Example: &#39;2022-05-27T00:10:22Z&#39; (optional) * @param buyTokenType Token type of the asset this order buys (optional) * @param buyTokenId ERC721 Token ID of the asset this order buys (optional) * @param buyAssetId Internal IMX ID of the asset this order buys (optional) * @param buyTokenAddress Comma separated string of token addresses of the asset this order buys (optional) * @param buyTokenName Token name of the asset this order buys (optional) * @param buyMinQuantity Min quantity for the asset this order buys (optional) * @param buyMaxQuantity Max quantity for the asset this order buys (optional) * @param buyMetadata JSON-encoded metadata filters for the asset this order buys (optional) * @param sellTokenType Token type of the asset this order sells (optional) * @param sellTokenId ERC721 Token ID of the asset this order sells (optional) * @param sellAssetId Internal IMX ID of the asset this order sells (optional) * @param sellTokenAddress Comma separated string of token addresses of the asset this order sells (optional) * @param sellTokenName Token name of the asset this order sells (optional) * @param sellMinQuantity Min quantity for the asset this order sells (optional) * @param sellMaxQuantity Max quantity for the asset this order sells (optional) * @param sellMetadata JSON-encoded metadata filters for the asset this order sells (optional) * @param auxiliaryFeePercentages Comma separated string of fee percentages that are to be paired with auxiliary_fee_recipients (optional) * @param auxiliaryFeeRecipients Comma separated string of fee recipients that are to be paired with auxiliary_fee_percentages (optional) * @param includeFees Set flag to true to include fee object for orders (optional) * @return ListOrdersResponse * @throws [ImmutableException.apiError] */ @Suppress("LongParameterList") fun listOrders( pageSize: Int? = null, cursor: String? = null, orderBy: String? = null, direction: String? = null, user: String? = null, status: String? = null, minTimestamp: String? = null, maxTimestamp: String? = null, updatedMinTimestamp: String? = null, updatedMaxTimestamp: String? = null, buyTokenType: String? = null, buyTokenId: String? = null, buyAssetId: String? = null, buyTokenAddress: String? = null, buyTokenName: String? = null, buyMinQuantity: String? = null, buyMaxQuantity: String? = null, buyMetadata: String? = null, sellTokenType: String? = null, sellTokenId: String? = null, sellAssetId: String? = null, sellTokenAddress: String? = null, sellTokenName: String? = null, sellMinQuantity: String? = null, sellMaxQuantity: String? = null, sellMetadata: String? = null, auxiliaryFeePercentages: String? = null, auxiliaryFeeRecipients: String? = null, includeFees: Boolean? = null ) = apiCall("listOrders") { ordersApi.listOrders( pageSize, cursor, orderBy, direction, user, status, minTimestamp, maxTimestamp, updatedMinTimestamp, updatedMaxTimestamp, buyTokenType, buyTokenId, buyAssetId, buyTokenAddress, buyTokenName, buyMinQuantity, buyMaxQuantity, buyMetadata, sellTokenType, sellTokenId, sellAssetId, sellTokenAddress, sellTokenName, sellMinQuantity, sellMaxQuantity, sellMetadata, auxiliaryFeePercentages, auxiliaryFeeRecipients, includeFees ) } /** * This is a utility function that will chain the necessary calls to create an order for an ERC721 asset. * * @param asset the ERC721 asset to sell * @param sellToken the type of token and how much of it to sell the ERC721 asset for * @param fees maker fees information to be used in the sell order. * @param signer represents the users L1 wallet to get the address * @param starkSigner represents the users L2 wallet used to sign and verify the L2 transaction * * @return a [CompletableFuture] that will provide the Order id if successful. */ @Suppress("LongParameterList") fun createOrder( asset: Erc721Asset, sellToken: AssetModel, fees: List<FeeEntry> = emptyList(), signer: Signer, starkSigner: StarkSigner ): CompletableFuture<CreateOrderResponse> { return com.immutable.sdk.workflows.createOrder( asset, sellToken, fees, signer, starkSigner ) } /** * This is a utility function that will chain the necessary calls to cancel an existing order. * * @param orderId the id of an existing order to be bought * @param starkSigner represents the users L2 wallet used to sign and verify the L2 transaction * * @return a [CompletableFuture] that will provide the cancelled Order id if successful. */ @Suppress("LongParameterList") fun cancelOrder( orderId: String, signer: Signer, starkSigner: StarkSigner ): CompletableFuture<CancelOrderResponse> = com.immutable.sdk.workflows.cancelOrder(orderId, signer, starkSigner) /** * Get details of a trade with the given ID * * @param id Trade ID * @return Trade * @throws [ImmutableException.apiError] */ fun getTrade(id: String) = apiCall("getTrade") { tradesApi.getTrade(id) } /** * Get a list of trades * * @param partyATokenType Party A&#39;s sell token type (optional) * @param partyATokenAddress Party A&#39;s sell token address (optional) * @param partyATokenId Party A&#39;s sell token id (optional) * @param partyBTokenType Party B&#39;s sell token type (optional) * @param partyBTokenAddress Party B&#39;s sell token address (optional) * @param partyBTokenId Party B&#39;s sell token id (optional) * @param pageSize Page size of the result (optional) * @param cursor Cursor (optional) * @param orderBy Property to sort by (optional) * @param direction Direction to sort (asc/desc) (optional) * @param minTimestamp Minimum timestamp for this trade, in ISO 8601 UTC format. Example: &#39;2022-05-27T00:10:22Z&#39; (optional) * @param maxTimestamp Maximum timestamp for this trade, in ISO 8601 UTC format. Example: &#39;2022-05-27T00:10:22Z&#39; (optional) * @return ListTradesResponse * @throws [ImmutableException.apiError] */ @Suppress("LongParameterList") fun listTrades( partyATokenType: String? = null, partyATokenAddress: String? = null, partyATokenId: String? = null, partyBTokenType: String? = null, partyBTokenAddress: String? = null, partyBTokenId: String? = null, pageSize: Int? = null, cursor: String? = null, orderBy: String? = null, direction: String? = null, minTimestamp: String? = null, maxTimestamp: String? = null ) = apiCall("listTrades") { tradesApi.listTrades( partyATokenType, partyATokenAddress, partyATokenId, partyBTokenType, partyBTokenAddress, partyBTokenId, pageSize, cursor, orderBy, direction, minTimestamp, maxTimestamp ) } /** * This is a utility function that will chain the necessary calls to fulfill an existing order. * * @param orderId the id of an existing order to be bought * @param fees taker fees information to be used in the buy order. * @param signer represents the users L1 wallet to get the address * @param starkSigner represents the users L2 wallet used to sign and verify the L2 transaction * * @return a [CompletableFuture] that will provide the Trade id if successful. */ fun createTrade( orderId: String, fees: List<FeeEntry> = emptyList(), signer: Signer, starkSigner: StarkSigner ): CompletableFuture<CreateTradeResponse> = com.immutable.sdk.workflows.createTrade(orderId, fees, signer, starkSigner) /** * Get details of a token * * @param address Token Contract Address * @return TokenDetails * @throws [ImmutableException.apiError] */ fun getToken(address: String) = apiCall("getToken") { tokensApi.getToken(address) } /** * Get a list of tokens * * @param address Contract address of the token (optional) * @param symbols Token symbols for the token, e.g. ?symbols&#x3D;IMX,ETH (optional) * @return ListTokensResponse * @throws [ImmutableException.apiError] */ fun listTokens(address: String? = null, symbols: String? = null) = apiCall("listTokens") { tokensApi.listTokens(address, symbols) } /** * Get details of a transfer with the given ID * * @param id Transfer ID * @return Transfer * @throws [ImmutableException.apiError] */ fun getTransfer(id: String) = apiCall("getTransfer") { transfersApi.getTransfer(id) } /** * Get a list of transfers * * @param pageSize Page size of the result (optional) * @param cursor Cursor (optional) * @param orderBy Property to sort by (optional) * @param direction Direction to sort (asc/desc) (optional) * @param user Ethereum address of the user who submitted this transfer (optional) * @param `receiver` Ethereum address of the user who received this transfer (optional) * @param status Status of this transfer (optional) * @param minTimestamp Minimum timestamp for this transfer, in ISO 8601 UTC format. Example: &#39;2022-05-27T00:10:22Z&#39; (optional) * @param maxTimestamp Maximum timestamp for this transfer, in ISO 8601 UTC format. Example: &#39;2022-05-27T00:10:22Z&#39; (optional) * @param tokenType Token type of the transferred asset (optional) * @param tokenId ERC721 Token ID of the minted asset (optional) * @param assetId Internal IMX ID of the minted asset (optional) * @param tokenAddress Token address of the transferred asset (optional) * @param tokenName Token name of the transferred asset (optional) * @param minQuantity Max quantity for the transferred asset (optional) * @param maxQuantity Max quantity for the transferred asset (optional) * @param metadata JSON-encoded metadata filters for the transferred asset (optional) * @return ListTransfersResponse * @throws [ImmutableException.apiError] */ @Suppress("LongParameterList") fun listTransfers( pageSize: Int? = null, cursor: String? = null, orderBy: String? = null, direction: String? = null, user: String? = null, receiver: String? = null, status: String? = null, minTimestamp: String? = null, maxTimestamp: String? = null, tokenType: String? = null, tokenId: String? = null, assetId: String? = null, tokenAddress: String? = null, tokenName: String? = null, minQuantity: String? = null, maxQuantity: String? = null, metadata: String? = null ) = apiCall("listTransfers") { transfersApi.listTransfers( pageSize, cursor, orderBy, direction, user, receiver, status, minTimestamp, maxTimestamp, tokenType, tokenId, assetId, tokenAddress, tokenName, minQuantity, maxQuantity, metadata ) } /** * This is a utility function that will chain the necessary calls to transfer a token. * * @param data as to what token is to be transferred (ETH, ERC20, or ERC721) and the address of the receiving wallet * @param starkSigner represents the users L2 wallet used to sign and verify the L2 transaction * @param signer represents the users L1 wallet to get the address * * @return a [CompletableFuture] that will provide the transfer id if successful. */ @Suppress("LongParameterList") fun transfer( data: TransferData, signer: Signer, starkSigner: StarkSigner, ): CompletableFuture<CreateTransferResponse> = com.immutable.sdk.workflows.transfer(listOf(data), signer, starkSigner) /** * This is a utility function that will chain the necessary calls to transfer a token. * * @param transfers list of all transfers and their individual tokens and recipients * @param starkSigner represents the users L2 wallet used to sign and verify the L2 transaction * @param signer represents the users L1 wallet to get the address * * @return a [CompletableFuture] that will provide the transfer id if successful. */ @Suppress("LongParameterList") fun batchTransfer( transfers: List<TransferData>, signer: Signer, starkSigner: StarkSigner, ): CompletableFuture<CreateTransferResponse> = com.immutable.sdk.workflows.transfer(transfers, signer, starkSigner) /** * Gets a URL to MoonPay that provides a service for buying crypto directly on Immutable in exchange for fiat. * * It is recommended to open this URL in a Chrome Custom Tab. * * @param signer represents the users L1 wallet to get the address * @param colourCodeHex The color code in hex (e.g. #00818e) for the Moon pay widget main color. It is used for buttons, * links and highlighted text. * @throws Throwable if any error occurs */ fun buyCrypto( signer: Signer, colourCodeHex: String = DEFAULT_MOONPAY_COLOUR_CODE ): CompletableFuture<String> = com.immutable.sdk.workflows.buyCrypto( base = base, signer = signer, colourCodeHex = colourCodeHex ) @Suppress("TooGenericExceptionCaught") private fun <T> apiCall(callName: String, call: () -> T): T { try { return call() } catch (e: Exception) { throw ImmutableException.apiError(callName, e) } } companion object { internal var httpLoggingLevel = ImmutableXHttpLoggingLevel.None } }
2
null
2
5
4a823d30db92356c325140874f5ba708547585ca
46,200
imx-core-sdk-kotlin-jvm
Apache License 2.0
app/src/main/java/eu/kanade/tachiyomi/data/preference/PreferenceKeys.kt
WorldHeaven777
329,142,416
false
null
package eu.kanade.tachiyomi.data.preference /** * This class stores the keys for the preferences in the application. */ object PreferenceKeys { const val theme = "pref_theme_key" const val rotation = "pref_rotation_type_key" const val enableTransitions = "pref_enable_transitions_key" const val doubleTapAnimationSpeed = "pref_double_tap_anim_speed" const val showPageNumber = "pref_show_page_number_key" const val trueColor = "pref_true_color_key" const val fullscreen = "fullscreen" const val keepScreenOn = "pref_keep_screen_on_key" const val customBrightness = "pref_custom_brightness_key" const val customBrightnessValue = "custom_brightness_value" const val colorFilter = "pref_color_filter_key" const val colorFilterValue = "color_filter_value" const val colorFilterMode = "color_filter_mode" const val defaultViewer = "pref_default_viewer_key" const val imageScaleType = "pref_image_scale_type_key" const val zoomStart = "pref_zoom_start_key" const val readerTheme = "pref_reader_theme_key" const val cropBorders = "crop_borders" const val cropBordersWebtoon = "crop_borders_webtoon" const val readWithTapping = "reader_tap" const val readWithLongTap = "reader_long_tap" const val readWithVolumeKeys = "reader_volume_keys" const val readWithVolumeKeysInverted = "reader_volume_keys_inverted" const val webtoonSidePadding = "webtoon_side_padding" const val webtoonDisableZoom = "webtoon_disable_zoom" const val updateOnlyNonCompleted = "pref_update_only_non_completed_key" const val autoUpdateTrack = "pref_auto_update_manga_sync_key" const val lastUsedCatalogueSource = "last_catalogue_source" const val lastUsedCategory = "last_used_category" const val catalogueAsList = "pref_display_catalogue_as_list" const val enabledLanguages = "source_languages" const val sourcesSort = "sources_sort" const val backupDirectory = "backup_directory" const val downloadsDirectory = "download_directory" const val downloadOnlyOverWifi = "pref_download_only_over_wifi_key" const val numberOfBackups = "backup_slots" const val backupInterval = "backup_interval" const val removeAfterReadSlots = "remove_after_read_slots" const val deleteRemovedChapters = "delete_removed_chapters" const val removeAfterMarkedAsRead = "pref_remove_after_marked_as_read_key" const val libraryUpdateInterval = "pref_library_update_interval_key" const val libraryUpdateRestriction = "library_update_restriction" const val libraryUpdateCategories = "library_update_categories" const val libraryUpdatePrioritization = "library_update_prioritization" const val filterDownloaded = "pref_filter_downloaded_key" const val filterUnread = "pref_filter_unread_key" const val filterCompleted = "pref_filter_completed_key" const val filterTracked = "pref_filter_tracked_key" const val filterMangaType = "pref_filter_manga_type_key" const val librarySortingMode = "library_sorting_mode" const val automaticUpdates = "automatic_updates" const val automaticExtUpdates = "automatic_ext_updates" const val downloadNew = "download_new" const val downloadNewCategories = "download_new_categories" const val libraryLayout = "pref_display_library_layout" const val gridSize = "grid_size" const val uniformGrid = "uniform_grid" const val libraryAsSingleList = "library_as_single_list" const val lang = "app_language" const val dateFormat = "app_date_format" const val defaultCategory = "default_category" const val skipRead = "skip_read" const val downloadBadge = "display_download_badge" const val useBiometrics = "use_biometrics" const val lockAfter = "lock_after" const val lastUnlock = "last_unlock" const val secureScreen = "secure_screen" const val removeArticles = "remove_articles" const val skipPreMigration = "skip_pre_migration" const val refreshCoversToo = "refresh_covers_too" const val updateOnRefresh = "update_on_refresh" const val alwaysShowChapterTransition = "always_show_chapter_transition" @Deprecated("Use the preferences of the source") fun sourceUsername(sourceId: Long) = "pref_source_username_$sourceId" @Deprecated("Use the preferences of the source") fun sourcePassword(sourceId: Long) = "pref_source_password_$sourceId" fun sourceSharedPref(sourceId: Long) = "source_$sourceId" fun trackUsername(syncId: Int) = "pref_mangasync_username_$syncId" fun trackPassword(syncId: Int) = "pref_mangasync_password_$syncId" fun trackToken(syncId: Int) = "track_token_$syncId" }
0
null
1
2
7ef9dcbc12905f66966a7c561809f469b9c3d9db
4,747
MangaDesu
Apache License 2.0
analysis/analysis-api-impl-base/src/org/jetbrains/kotlin/analysis/api/impl/base/util/LibraryUtils.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.analysis.api.impl.base.util import com.intellij.openapi.vfs.StandardFileSystems import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.impl.jar.CoreJarFileSystem import com.intellij.util.io.URLUtil.JAR_SEPARATOR import java.nio.file.Path object LibraryUtils { /** * Get all [VirtualFile]s inside the given [jar] (of [Path]) * * Note that, if [CoreJarFileSystem] is not given, a fresh instance will be used, which will create fresh instances of [VirtualFile], * resulting in potential hash mismatch (e.g., if used in scope membership check). */ fun getAllVirtualFilesFromJar( jar: Path, jarFileSystem: CoreJarFileSystem = CoreJarFileSystem(), ): Collection<VirtualFile> { return jarFileSystem.refreshAndFindFileByPath(jar.toAbsolutePath().toString() + JAR_SEPARATOR) ?.let { getAllVirtualFilesFromRoot(it) } ?: emptySet() } /** * Get all [VirtualFile]s inside the given [dir] (of [Path]) */ fun getAllVirtualFilesFromDirectory( dir: Path, ): Collection<VirtualFile> { val fs = StandardFileSystems.local() return fs.findFileByPath(dir.toAbsolutePath().toString())?.let { getAllVirtualFilesFromRoot(it) } ?: return emptySet() } private fun getAllVirtualFilesFromRoot( root: VirtualFile ): Collection<VirtualFile> { val files = mutableSetOf<VirtualFile>() VfsUtilCore.iterateChildrenRecursively( root, /*filter=*/{ true }, /*iterator=*/{ virtualFile -> if (!virtualFile.isDirectory) { files.add(virtualFile) } true } ) return files } }
9
null
4980
40,442
817f9f13b71d4957d8eaa734de2ac8369ad64770
2,037
kotlin
Apache License 2.0
buildSrc/src/main/kotlin/trikita/anvilgen/DSLGeneratorTask.kt
anvil-ui
29,293,245
false
null
package trikita.anvilgen import androidx.annotation.NonNull import com.squareup.javapoet.* import groovy.lang.Closure import org.gradle.api.DefaultTask import org.gradle.api.tasks.TaskAction import java.io.File import java.lang.Deprecated import java.lang.reflect.Method import java.net.URL import java.net.URLClassLoader import java.util.jar.JarFile import javax.lang.model.element.Modifier import com.squareup.javapoet.AnnotationSpec import androidx.annotation.Nullable import java.util.jar.JarEntry open class DSLGeneratorTask : DefaultTask() { lateinit var jarFiles: List<File> lateinit var nullabilitySourceFiles: List<File> lateinit var dependencies: List<File> lateinit var taskName: String lateinit var javadocContains: String lateinit var outputDirectory: String lateinit var outputClassName: String lateinit var packageName: String var superclass: ClassName? = null lateinit var nullabilityHolder : NullabilityHolder @TaskAction fun generate() { var attrsBuilder = TypeSpec.classBuilder(outputClassName) .addJavadoc("DSL for creating views and settings their attributes.\n" + "This file has been generated by " + "{@code gradle $taskName}.\n" + "$javadocContains.\n" + "Please, don't edit it manually unless for debugging.\n") .addModifiers(Modifier.PUBLIC, Modifier.FINAL) if (superclass != null) { attrsBuilder = attrsBuilder.superclass(superclass) } attrsBuilder.addSuperinterface(ClassName.get("trikita.anvil", "Anvil", "AttributeSetter")) attrsBuilder.addStaticBlock(CodeBlock.of( "Anvil.registerAttributeSetter(new \$L());\n", outputClassName)) val attrSwitch = MethodSpec.methodBuilder("set") .addParameter(ClassName.get("android.view", "View"), "v") .addParameter(ClassName.get("java.lang", "String"), "name") .addParameter(ParameterSpec.builder(TypeName.OBJECT, "arg") .addModifiers(Modifier.FINAL).build()) .addParameter(ParameterSpec.builder(TypeName.OBJECT, "old") .addModifiers(Modifier.FINAL).build()) .returns(TypeName.BOOLEAN) .addModifiers(Modifier.PUBLIC) val attrCases = CodeBlock.builder().beginControlFlow("switch (name)") val attrs = mutableListOf<Attr>() nullabilityHolder = NullabilityHolder(outputClassName == "DSL") forEachView { view -> processViews(attrsBuilder, view) forEachMethod(view) { m, name, arg, isListener, isNullable -> val attr: Attr? if (isListener) { attr = listener(name, m, arg) } else { attr = setter(name, m, arg, isNullable) } if (attr != null) { attrs.add(attr) } } } finalizeAttrs(attrs, attrsBuilder, attrCases) attrCases.endControlFlow() attrSwitch.addCode(attrCases.build()).addCode("return false;\n") attrsBuilder.addMethod(attrSwitch.build()) JavaFile.builder(packageName, attrsBuilder.build()) .build() .writeTo(project.file("src/$outputDirectory/java")) } fun forEachView(cb: (Class<*>) -> Unit) { val urls = jarFiles.map { URL("jar", "", "file:${it.absolutePath}!/") }.toMutableList() for (dep in dependencies) { urls.add(URL("jar", "", "file:${dep.absolutePath}!/")) } val loader = URLClassLoader(urls.toTypedArray(), javaClass.classLoader) val viewClass = loader.loadClass("android.view.View") val nullabilityClassLoader = URLClassLoader(nullabilitySourceFiles.map { URL("jar", "", "file:${it.absolutePath}!/") }.toTypedArray(), javaClass.classLoader) val jarEntriesList = mutableListOf<JarEntry>() jarFiles.map { JarFile(it).entries() }.forEach { jarEntriesList.addAll(it.toList()) } jarEntriesList.sortBy { it.name } for (e in jarEntriesList) { if (e.name.endsWith(".class")) { val className = e.name.replace(".class", "").replace("/", ".") // Skip inner classes if (className.contains('$')) { continue } try { val c = loader.loadClass(className) nullabilityHolder.fillClassNullabilityInfo(nullabilityClassLoader, e.name) if (viewClass.isAssignableFrom(c) && java.lang.reflect.Modifier.isPublic(c.modifiers)) { cb(c) } } catch (ignored: NoClassDefFoundError) { // Simply skip this class. ignored.printStackTrace() } } } } fun forEachMethod(c: Class<*>, cb: (Method, String, Class<*>, Boolean, Boolean?) -> Unit) { val declaredMethods = c.declaredMethods.clone() declaredMethods.sortBy { it.name } for (m in declaredMethods) { if (!java.lang.reflect.Modifier.isPublic(m.modifiers) || m.isSynthetic || m.isBridge) { continue } val parameterType = getMethodParameterType(m) ?: continue val isNullable = nullabilityHolder.isParameterNullable(m) val formattedMethodName = formatMethodName(m.name, m.parameterCount) formattedMethodName?.let { if (formattedMethodName.isListener) { cb(m, formattedMethodName.formattedName, parameterType, formattedMethodName.isListener, true) } else { cb(m, formattedMethodName.formattedName, parameterType, formattedMethodName.isListener, isNullable) } } } } fun getMethodParameterType(m: Method): Class<*>? { if (m.parameterTypes.size == 0) { return null } val parameterType = m.parameterTypes[0] if (!java.lang.reflect.Modifier.isPublic(parameterType.modifiers)) { // If the parameter is not public then the method is inaccessible for us. return null } else if (m.annotations != null) { for (a in m.annotations) { // Don't process deprecated methods. if (a.annotationClass.equals(Deprecated::class)) { return null } } } else if (m.declaringClass.canonicalName == "android.view.View") { return parameterType } // Check if the method overrode from a super class. var supClass = m.declaringClass.superclass while (true) { if (supClass == null) { break } try { supClass.getMethod(m.name, *m.parameterTypes) return null } catch (ignored: NoSuchMethodException) { // Intended to occur } if (supClass.canonicalName == "android.view.View") { break } supClass = supClass.superclass } return parameterType } // // Views generator functions: // For each view generates a function that calls v(C), where C is a view // class, e.g. FrameLayout.class => frameLayout() { v(FrameLayout.class) } // fun processViews(builder: TypeSpec.Builder, view: Class<*>) { val className = view.canonicalName var name = view.simpleName val extension = project.extensions.getByName("anvilgen") as AnvilGenPluginExtension val quirk = extension.quirks[className] if (quirk != null) { val alias = quirk["__viewAlias"] // if the whole view class is banned - do nothing if (alias == false) { return } else if (alias != null) { name = alias as String } } name = toCase(name, { c -> Character.toLowerCase(c) }) val baseDsl = ClassName.get("trikita.anvil", "BaseDSL") val result = ClassName.get("trikita.anvil", "BaseDSL", "ViewClassResult") builder.addMethod(MethodSpec.methodBuilder(name) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(result) .addStatement("return \$T.v(\$T.class)", baseDsl, view) .build()) builder.addMethod(MethodSpec.methodBuilder(name) .addParameter(ParameterSpec.builder(ClassName.get("trikita.anvil", "Anvil", "Renderable"), "r").build()) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(TypeName.VOID.box()) .addStatement("return \$T.v(\$T.class, r)", baseDsl, view) .build()) } // // Attrs generator functions // fun listener(name: String, m: Method, listenerClass: Class<*>): Attr? { val viewClass = m.declaringClass.canonicalName val listener = TypeSpec.anonymousClassBuilder("") .addSuperinterface(listenerClass) val declaredMethods = listenerClass.declaredMethods.clone() declaredMethods.sortBy { it.name } declaredMethods.forEach { lm -> val methodBuilder = MethodSpec.methodBuilder(lm.name) .addModifiers(Modifier.PUBLIC) .returns(lm.returnType) var args = "" lm.parameterTypes.forEachIndexed { i, v -> methodBuilder.addParameter(v, "a$i") args += (if (i != 0) ", " else "") + "a$i" } if (lm.returnType.equals(Void.TYPE)) { methodBuilder .addStatement("((\$T) arg).\$L($args)", listenerClass, lm.name) .addStatement("\$T.render()", ClassName.get("trikita.anvil", "Anvil")) } else { methodBuilder .addStatement("\$T r = ((\$T) arg).\$L($args)", lm.returnType, listenerClass, lm.name) .addStatement("\$T.render()", ClassName.get("trikita.anvil", "Anvil")) .addStatement("return r") } listener.addMethod(methodBuilder.build()) } val attr = Attr(name, listenerClass, m) if (viewClass == "android.view.View") { attr.code.beginControlFlow("if (arg != null)", m.declaringClass) .addStatement("v.${m.name}(\$L)", listener.build()) .nextControlFlow("else") .addStatement("v.${m.name}((\$T) null)", listenerClass) .endControlFlow() .addStatement("return true") attr.unreachableBreak = true } else { attr.code.beginControlFlow("if (v instanceof \$T && arg instanceof \$T)", m.declaringClass, listenerClass) .beginControlFlow("if (arg != null)", m.declaringClass) .addStatement("((\$T) v).${m.name}(\$L)", m.declaringClass, listener.build()) .nextControlFlow("else") .addStatement("((\$T) v).${m.name}((\$T) null)", m.declaringClass, listenerClass) .endControlFlow() .addStatement("return true") .endControlFlow() } return attr } fun setter(name: String, m: Method, argClass: Class<*>, isNullable : Boolean?): Attr? { val viewClass = m.declaringClass.canonicalName val attr = Attr(name, argClass, m) val extension = project.extensions.getByName("anvilgen") as AnvilGenPluginExtension val quirks = extension.quirks[viewClass] if (quirks != null) { val closure = quirks["${m.name}:${argClass.canonicalName}"] if (closure != null) { return (closure as Closure<Attr?>).call(attr) } else { val nameClosure = quirks[m.name] if (nameClosure != null) { return (nameClosure as Closure<Attr?>).call(attr) } } } val argBoxed = TypeName.get(argClass).box() if (viewClass == "android.view.View") { attr.code.beginControlFlow("if (arg instanceof \$T)", argBoxed) .addStatement("v.${m.name}((\$T) arg)", argClass) .addStatement("return true") .endControlFlow() } else { val checkArgLiteral = if (isNullable == true) { "(arg == null || arg instanceof \$T)" } else { "arg instanceof \$T" } attr.code.beginControlFlow("if (v instanceof \$T && $checkArgLiteral)", m.declaringClass, argBoxed) .addStatement("((\$T) v).${m.name}((\$T) arg)", m.declaringClass, argClass) .addStatement("return true") .endControlFlow() } return attr } fun addWrapperMethod(builder: TypeSpec.Builder, name: String, argClass: Class<*>, className: String) { val baseDsl = ClassName.get("trikita.anvil", "BaseDSL") val nullableAnnotation: AnnotationSpec? = when (nullabilityHolder.isParameterNullable(className, name, argClass.typeName)) { true -> AnnotationSpec .builder(Nullable::class.java) .build() false -> AnnotationSpec .builder(NonNull::class.java) .build() else -> null } val parameterBuilder = ParameterSpec.builder(argClass, "arg") if (nullableAnnotation != null) { parameterBuilder.addAnnotation(nullableAnnotation) } val wrapperMethod = MethodSpec.methodBuilder(name) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addParameter(parameterBuilder.build()) .returns(TypeName.VOID.box()) .addStatement("return \$T.attr(\$S, arg)", baseDsl, name) builder.addMethod(wrapperMethod.build()) } fun finalizeAttrs(attrs: List<Attr>, dsl: TypeSpec.Builder, cases: CodeBlock.Builder) { attrs.sortedBy { it.name }.groupBy { it.name }.forEach { var all = it.value.sortedBy { it.param.name } var filered = all.filter { a -> !all.any { b -> a != b && a.param == b.param && a.setter.declaringClass.isAssignableFrom(b.setter.declaringClass) } } cases.add("case \$S:\n", it.key) cases.indent() filered.filter { it.setter.declaringClass.canonicalName != "android.view.View" }.forEach { cases.add(it.code.build()) } val common = filered.firstOrNull { it.setter.declaringClass.canonicalName == "android.view.View" } if (common != null) { cases.add(common.code.build()) } if (common == null || !common.unreachableBreak) { cases.add("break;\n") } cases.unindent() } attrs.sortedBy { it.name }.groupBy { it.name }.forEach { val name = it.key val className = it.value.firstOrNull()?.setter?.declaringClass?.canonicalName ?: "" it.value.sortedBy { it.param.name }.groupBy { it.param }.forEach { addWrapperMethod(dsl, name, it.key, className) } } } fun toCase(s: String, fn: (Char) -> Char): String { return fn(s[0]).toString() + s.substring(1) } data class Attr(val name: String, val param: Class<*>, val setter: Method, var unreachableBreak: Boolean = false, val code: CodeBlock.Builder = CodeBlock.builder()) } data class FormattedMethod(val formattedName : String, val isListener : Boolean) fun formatMethodName(originalMethodName : String, parameterCount : Int) : FormattedMethod? { return if (originalMethodName.matches(Regex("^setOn.*Listener$"))) { FormattedMethod( "on" + originalMethodName.substring(5, originalMethodName.length - 8), true ) } else if (originalMethodName.startsWith("set") && originalMethodName.length > 3 && parameterCount == 1) { FormattedMethod( Character.toLowerCase(originalMethodName[3]).toString() + originalMethodName.substring( 4 ), false ) } else null }
41
null
93
1,446
0825ae9556aac5dcae81c4bf176a2a1c1580f585
17,035
anvil
MIT License
chain-adapter/src/main/kotlin/com/d3/chainadapter/adapter/ChainAdapter.kt
BulatSaif
188,790,713
true
{"Kotlin": 952326, "Java": 385476, "Dockerfile": 6699, "Shell": 5689, "HTML": 5232, "Python": 4228, "Groovy": 449}
package com.d3.chainadapter.adapter import com.d3.chainadapter.CHAIN_ADAPTER_SERVICE_NAME import com.d3.chainadapter.provider.LastReadBlockProvider import com.d3.commons.config.RMQConfig import com.d3.commons.sidechain.iroha.IrohaChainListener import com.d3.commons.sidechain.iroha.util.getBlockRawResponse import com.d3.commons.sidechain.iroha.util.getErrorMessage import com.d3.commons.util.createPrettySingleThreadPool import com.github.kittinunf.result.Result import com.github.kittinunf.result.map import com.rabbitmq.client.Channel import com.rabbitmq.client.ConnectionFactory import com.rabbitmq.client.MessageProperties import io.reactivex.schedulers.Schedulers import iroha.protocol.BlockOuterClass import iroha.protocol.QryResponses import jp.co.soramitsu.iroha.java.QueryAPI import mu.KLogging import java.io.Closeable import java.util.concurrent.CountDownLatch import java.util.concurrent.atomic.AtomicLong private const val BAD_IROHA_BLOCK_HEIGHT_ERROR_CODE = 3 /** * Chain adapter service * It reads Iroha blocks and sends them to recipients via RabbitMQ */ class ChainAdapter( private val rmqConfig: RMQConfig, private val queryAPI: QueryAPI, private val irohaChainListener: IrohaChainListener, private val lastReadBlockProvider: LastReadBlockProvider ) : Closeable { private val connectionFactory = ConnectionFactory() private val lastReadBlock = AtomicLong() private val publishUnreadLatch = CountDownLatch(1) private val subscriberExecutorService = createPrettySingleThreadPool( CHAIN_ADAPTER_SERVICE_NAME, "iroha-chain-subscriber" ) init { connectionFactory.host = rmqConfig.host } private val connection = connectionFactory.newConnection() /** * Initiates and runs chain adapter */ fun init(): Result<Unit, Exception> { return init({}) } /** * Initiates and runs chain adapter * @param onIrohaListenError - function that will be called on Iroha chain listener error */ fun init(onIrohaListenError: () -> Unit): Result<Unit, Exception> { return Result.of { lastReadBlock.set(lastReadBlockProvider.getLastBlockHeight()) val channel = connection.createChannel() channel.exchangeDeclare(rmqConfig.irohaExchange, "fanout", true) logger.info { "Listening Iroha blocks" } initIrohaChainListener(channel, onIrohaListenError) publishUnreadIrohaBlocks(channel) } } /** * Initiates Iroha chain listener logic * @param channel - channel that is used to publish Iroha blocks * @param onIrohaListenError - function that will be called on Iroha chain listener error */ private fun initIrohaChainListener(channel: Channel, onIrohaListenError: () -> Unit) { irohaChainListener.getBlockObservable() .map { observable -> observable.subscribeOn(Schedulers.from(subscriberExecutorService)) .subscribe({ block -> publishUnreadLatch.await() // Send only not read Iroha blocks if (block.blockV1.payload.height > lastReadBlock.get()) { onNewBlock(channel, block) } }, { ex -> logger.error("Error on Iroha chain listener occurred", ex) onIrohaListenError() }) } } /** * Publishes unread blocks * @param channel - RabbitMQ channel that is used to publish Iroha blocks */ private fun publishUnreadIrohaBlocks(channel: Channel) { var lastProcessedBlock = lastReadBlockProvider.getLastBlockHeight() while (true) { lastProcessedBlock++ logger.info { "Try read Iroha block $lastProcessedBlock" } val response = getBlockRawResponse(queryAPI, lastProcessedBlock) if (response.hasErrorResponse()) { val errorResponse = response.errorResponse if (isNoMoreBlocksError(errorResponse)) { logger.info { "Done publishing unread blocks" } break } else { throw Exception("Cannot get block. ${getErrorMessage(errorResponse)}") } } else if (response.hasBlockResponse()) { onNewBlock(channel, response.blockResponse!!.block) } } publishUnreadLatch.countDown() } /** * Checks if no more blocks * @param errorResponse - error response to check * @return true if no more blocks to read */ private fun isNoMoreBlocksError(errorResponse: QryResponses.ErrorResponse) = errorResponse.errorCode == BAD_IROHA_BLOCK_HEIGHT_ERROR_CODE /** * Publishes new block to RabbitMQ * @param channel - channel that is used to publish blocks * @param block - Iroha block to publish */ private fun onNewBlock(channel: Channel, block: BlockOuterClass.Block) { val message = block.toByteArray() channel.basicPublish( rmqConfig.irohaExchange, "", MessageProperties.MINIMAL_PERSISTENT_BASIC, message ) logger.info { "Block pushed" } val height = block.blockV1.payload.height // Save last read block lastReadBlockProvider.saveLastBlockHeight(height) lastReadBlock.set(height) } /** * Returns height of last read Iroha block */ fun getLastReadBlock() = lastReadBlock.get() override fun close() { subscriberExecutorService.shutdownNow() queryAPI.api.close() irohaChainListener.close() connection.close() } companion object : KLogging() }
0
Kotlin
0
0
11f0109480372549542f59f71b7e9b1bab604e30
5,834
notary
Apache License 2.0
app/src/main/java/com/jacktor/batterylab/ApplicationBackup.kt
jacktor-stan
773,048,759
false
{"Kotlin": 705997, "Java": 4558, "C++": 3298, "C": 458, "CMake": 284}
package com.jacktor.batterylab import android.app.backup.BackupAgent import android.app.backup.BackupDataInput import android.app.backup.BackupDataOutput import android.os.ParcelFileDescriptor import com.jacktor.batterylab.utilities.PreferencesKeys.BATTERY_LEVEL_TO import com.jacktor.batterylab.utilities.PreferencesKeys.BATTERY_LEVEL_WITH import com.jacktor.batterylab.utilities.PreferencesKeys.CAPACITY_ADDED import com.jacktor.batterylab.utilities.PreferencesKeys.DESIGN_CAPACITY import com.jacktor.batterylab.utilities.PreferencesKeys.LAST_CHARGE_TIME import com.jacktor.batterylab.utilities.PreferencesKeys.NUMBER_OF_CHARGES import com.jacktor.batterylab.utilities.PreferencesKeys.NUMBER_OF_CYCLES import com.jacktor.batterylab.utilities.PreferencesKeys.PERCENT_ADDED import com.jacktor.batterylab.utilities.PreferencesKeys.RESIDUAL_CAPACITY import com.jacktor.batterylab.utilities.Prefs class ApplicationBackup : BackupAgent() { private var pref: Prefs? = null private var prefArrays: MutableMap<String, *>? = null override fun onCreate() { super.onCreate() val pref = Prefs(this) prefArrays = pref.all() } override fun onBackup( oldState: ParcelFileDescriptor?, data: BackupDataOutput?, newState: ParcelFileDescriptor? ) { } override fun onRestore( data: BackupDataInput?, appVersionCode: Int, newState: ParcelFileDescriptor? ) { } override fun onRestoreFinished() { super.onRestoreFinished() val prefsTempList = arrayListOf( BATTERY_LEVEL_TO, BATTERY_LEVEL_WITH, DESIGN_CAPACITY, CAPACITY_ADDED, LAST_CHARGE_TIME, PERCENT_ADDED, RESIDUAL_CAPACITY ) prefsTempList.forEach { with(prefArrays) { when { this?.containsKey(it) == false -> pref?.remove(it) else -> { this?.forEach { when (it.key) { NUMBER_OF_CHARGES -> pref?.setLong( it.key, it.value as Long ) BATTERY_LEVEL_TO, BATTERY_LEVEL_WITH, LAST_CHARGE_TIME, DESIGN_CAPACITY, RESIDUAL_CAPACITY, PERCENT_ADDED -> pref ?.setInt(it.key, it.value as Int) CAPACITY_ADDED, NUMBER_OF_CYCLES -> pref?.setFloat( it.key, it.value as Float ) } } } } } } } }
0
Kotlin
1
3
6409caae85d430339d94b8802c3a8ecfb7ab746f
2,787
battery-lab
Apache License 2.0
compiler/testData/diagnostics/tests/inference/regressions/kt1718.kt
JakeWharton
99,388,807
false
null
// !CHECK_TYPE //KT-1718 compiler error when not using temporary variable package n import java.util.ArrayList import checkSubtype fun test() { val list = arrayList("foo", "bar") + arrayList("cheese", "wine") checkSubtype<List<String>>(list) //check it's not an error type checkSubtype<Int>(<!TYPE_MISMATCH!>list<!>) } //from library fun <T> arrayList(vararg <!UNUSED_PARAMETER!>values<!>: T) : ArrayList<T> {<!NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY!>}<!> operator fun <T> Iterable<T>.plus(<!UNUSED_PARAMETER!>elements<!>: Iterable<T>): List<T> {<!NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY!>}<!>
0
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
611
kotlin
Apache License 2.0
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/component/impl/DefaultLogArea.kt
Hexworks
94,116,947
false
null
package org.hexworks.zircon.internal.component.impl import org.hexworks.cobalt.logging.api.LoggerFactory import org.hexworks.zircon.api.builder.component.ParagraphBuilder import org.hexworks.zircon.api.builder.component.TextBoxBuilder import org.hexworks.zircon.api.component.* import org.hexworks.zircon.api.component.data.ComponentMetadata import org.hexworks.zircon.api.component.renderer.ComponentRenderingStrategy import org.hexworks.zircon.api.data.Position import org.hexworks.zircon.api.extensions.abbreviate import kotlin.jvm.Synchronized class DefaultLogArea constructor( componentMetadata: ComponentMetadata, renderingStrategy: ComponentRenderingStrategy<LogArea> ) : LogArea, DefaultContainer( componentMetadata = componentMetadata, renderer = renderingStrategy) { private var currentInlineBuilder = createTextBoxBuilder() private val logElements = mutableListOf<AttachedComponent>() init { render() } override fun addHeader(text: String, withNewLine: Boolean) { LOGGER.debug("Adding header text ($text) to LogArea (id=${id.abbreviate()}).") addLogElement(createTextBoxBuilder() .addHeader(text, withNewLine) .build()) } override fun addParagraph(paragraph: String, withNewLine: Boolean, withTypingEffectSpeedInMs: Long) { LOGGER.debug("Adding paragraph text ($paragraph) to LogArea (id=${id.abbreviate()}).") addLogElement(createTextBoxBuilder() .addParagraph(paragraph, withNewLine, withTypingEffectSpeedInMs) .build()) } override fun addParagraph(paragraphBuilder: ParagraphBuilder, withNewLine: Boolean) { LOGGER.debug("Adding paragraph from builder to LogArea (id=${id.abbreviate()}).") addLogElement(createTextBoxBuilder() .addParagraph(paragraphBuilder, withNewLine) .build(), false) } override fun addListItem(item: String) { LOGGER.debug("Adding list item ($item) to LogArea (id=${id.abbreviate()}).") addLogElement(createTextBoxBuilder() .addListItem(item) .build()) } override fun addInlineText(text: String) { LOGGER.debug("Adding inline text ($text) to LogArea (id=${id.abbreviate()}).") currentInlineBuilder.addInlineText(text) } override fun addInlineComponent(component: Component) { LOGGER.debug("Adding inline component ($component) to LogArea (id=${id.abbreviate()}).") currentInlineBuilder.addInlineComponent(component) } override fun commitInlineElements() { LOGGER.debug("Committing inline elements of LogArea (id=${id.abbreviate()}).") val builder = currentInlineBuilder currentInlineBuilder = createTextBoxBuilder() addLogElement(builder.commitInlineElements().build()) } override fun addNewRows(numberOfRows: Int) { LOGGER.debug("Adding new rows ($numberOfRows) to LogArea (id=${id.abbreviate()}).") (0 until numberOfRows).forEach { _ -> addLogElement(createTextBoxBuilder() .addNewLine() .build()) } } @Synchronized override fun clear() { logElements.forEach { it.detach() } logElements.clear() } override fun convertColorTheme(colorTheme: ColorTheme) = colorTheme.toContainerStyle() @Synchronized private fun addLogElement(element: TextBox, applyTheme: Boolean = true) { var currentHeight = children.map { it.height }.fold(0, Int::plus) val maxHeight = contentSize.height val elementHeight = element.height val remainingHeight = maxHeight - currentHeight require(elementHeight <= contentSize.height) { "Can't add an element which has a bigger height than this LogArea." } if (currentHeight + elementHeight > maxHeight) { val linesToFree = elementHeight - remainingHeight var currentFreedSpace = 0 while (currentFreedSpace < linesToFree) { logElements.firstOrNull()?.let { topChild -> currentFreedSpace += topChild.height topChild.detach() logElements.remove(topChild) } } logElements.forEach { child -> child.moveUpBy(currentFreedSpace) } currentHeight -= currentFreedSpace } element.moveTo(Position.create(0, currentHeight)) logElements.add(addComponent(element)) if (applyTheme) { element.theme = theme } render() } private fun createTextBoxBuilder(): TextBoxBuilder { return TextBoxBuilder .newBuilder(contentSize.width) .withTileset(tileset) } companion object { val LOGGER = LoggerFactory.getLogger(LogArea::class) } }
42
null
138
735
9eeabb2b30e493189c9931f40d48bae877cf3554
4,961
zircon
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/qbusiness/IndexStatisticsPropertyDsl.kt
F43nd1r
643,016,506
false
{"Kotlin": 5432532}
package com.faendir.awscdkkt.generated.services.qbusiness import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.qbusiness.CfnIndex @Generated public fun buildIndexStatisticsProperty(initializer: @AwsCdkDsl CfnIndex.IndexStatisticsProperty.Builder.() -> Unit = {}): CfnIndex.IndexStatisticsProperty = CfnIndex.IndexStatisticsProperty.Builder().apply(initializer).build()
1
Kotlin
0
4
3d0f80e3da7d0d87d9a23c70dda9f278dbd3f763
458
aws-cdk-kt
Apache License 2.0
app/src/test/java/com/example/cupcake/ViewModelTests.kt
rsl50
552,575,222
false
{"Kotlin": 22178}
package com.example.cupcake import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.example.cupcake.model.OrderViewModel import org.junit.Assert.assertEquals import org.junit.Rule import org.junit.Test class ViewModelTests { @get:Rule var instantTaskExecutorRule = InstantTaskExecutorRule() @Test fun quantity_twelve_cupcakes() { // Instantiate the viewModel val viewModel = OrderViewModel() // Observe the LiveData value that will be changed viewModel.quantity.observeForever{} viewModel.setQuantity(12) // Check if the value is correct assertEquals(12, viewModel.quantity.value) } @Test fun price_twelve_cupcakes() { // Instantiate the viewModel val viewModel = OrderViewModel() // Observe the LiveData value that will be changed, otherwise the test will fail because // the Transformation only is executed if needed viewModel.price.observeForever{} // Set test cupcake quantity viewModel.setQuantity(12) // Each cupcake costs $2.00 and same day pickup is selected by default addin $3.00, thus // we have 12 * 2 = 24 + 3 = 27 assertEquals("R$ 27,00", viewModel.price.value) } }
0
Kotlin
0
0
fffa31a0bf7f4c20cb7c633f9b531d2b2634e12e
1,280
android-basics-kotlin-cupcake-app
Apache License 2.0