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
favorite/src/main/java/com/example/made/favorite/FavoriteViewModel.kt
shidqimlna
332,420,780
false
{"Kotlin": 51923}
package com.example.made.favorite import androidx.lifecycle.ViewModel import androidx.lifecycle.asLiveData import com.example.made.core.domain.usecase.MovieUseCase class FavoriteViewModel(movieUseCase: MovieUseCase) : ViewModel() { val favoriteMovie = movieUseCase.getFavoriteMovie().asLiveData() }
0
Kotlin
0
0
45d26e19b4560dc419185a3c216855db274f5f60
306
The-Movie
MIT License
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/bulk/Arrowswaphorizontal.kt
Tlaster
560,394,734
false
{"Kotlin": 25133302}
package moe.tlaster.icons.vuesax.vuesaxicons.bulk import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import moe.tlaster.icons.vuesax.vuesaxicons.BulkGroup public val BulkGroup.Arrowswaphorizontal: ImageVector get() { if (_arrowswaphorizontal != null) { return _arrowswaphorizontal!! } _arrowswaphorizontal = Builder(name = "Arrowswaphorizontal", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF292D32)), stroke = null, fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(7.81f, 2.0f) horizontalLineTo(16.18f) curveTo(19.83f, 2.0f, 22.0f, 4.17f, 22.0f, 7.81f) verticalLineTo(16.18f) curveTo(22.0f, 19.82f, 19.83f, 21.99f, 16.19f, 21.99f) horizontalLineTo(7.81f) curveTo(4.17f, 22.0f, 2.0f, 19.83f, 2.0f, 16.19f) verticalLineTo(7.81f) curveTo(2.0f, 4.17f, 4.17f, 2.0f, 7.81f, 2.0f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(17.69f, 13.4798f) curveTo(17.61f, 13.2998f, 17.47f, 13.1498f, 17.28f, 13.0698f) curveTo(17.19f, 13.0298f, 17.09f, 13.0098f, 16.99f, 13.0098f) horizontalLineTo(7.0f) curveTo(6.59f, 13.0098f, 6.25f, 13.3498f, 6.25f, 13.7598f) curveTo(6.25f, 14.1698f, 6.59f, 14.5098f, 7.0f, 14.5098f) horizontalLineTo(15.19f) lineTo(13.52f, 16.1798f) curveTo(13.23f, 16.4698f, 13.23f, 16.9498f, 13.52f, 17.2398f) curveTo(13.67f, 17.3898f, 13.86f, 17.4598f, 14.05f, 17.4598f) curveTo(14.24f, 17.4598f, 14.43f, 17.3898f, 14.58f, 17.2398f) lineTo(17.53f, 14.2898f) curveTo(17.6f, 14.2198f, 17.65f, 14.1398f, 17.69f, 14.0498f) curveTo(17.77f, 13.8598f, 17.77f, 13.6598f, 17.69f, 13.4798f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(6.31f, 10.52f) curveTo(6.39f, 10.7f, 6.53f, 10.85f, 6.72f, 10.93f) curveTo(6.81f, 10.97f, 6.9f, 10.99f, 7.0f, 10.99f) horizontalLineTo(17.0f) curveTo(17.41f, 10.99f, 17.75f, 10.65f, 17.75f, 10.24f) curveTo(17.75f, 9.83f, 17.41f, 9.49f, 17.0f, 9.49f) horizontalLineTo(8.81f) lineTo(10.48f, 7.82f) curveTo(10.77f, 7.53f, 10.77f, 7.05f, 10.48f, 6.76f) curveTo(10.19f, 6.47f, 9.71f, 6.47f, 9.42f, 6.76f) lineTo(6.47f, 9.71f) curveTo(6.4f, 9.78f, 6.35f, 9.86f, 6.31f, 9.95f) curveTo(6.23f, 10.14f, 6.23f, 10.34f, 6.31f, 10.52f) close() } } .build() return _arrowswaphorizontal!! } private var _arrowswaphorizontal: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
4,143
VuesaxIcons
MIT License
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/bulk/Arrowswaphorizontal.kt
Tlaster
560,394,734
false
{"Kotlin": 25133302}
package moe.tlaster.icons.vuesax.vuesaxicons.bulk import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import moe.tlaster.icons.vuesax.vuesaxicons.BulkGroup public val BulkGroup.Arrowswaphorizontal: ImageVector get() { if (_arrowswaphorizontal != null) { return _arrowswaphorizontal!! } _arrowswaphorizontal = Builder(name = "Arrowswaphorizontal", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF292D32)), stroke = null, fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(7.81f, 2.0f) horizontalLineTo(16.18f) curveTo(19.83f, 2.0f, 22.0f, 4.17f, 22.0f, 7.81f) verticalLineTo(16.18f) curveTo(22.0f, 19.82f, 19.83f, 21.99f, 16.19f, 21.99f) horizontalLineTo(7.81f) curveTo(4.17f, 22.0f, 2.0f, 19.83f, 2.0f, 16.19f) verticalLineTo(7.81f) curveTo(2.0f, 4.17f, 4.17f, 2.0f, 7.81f, 2.0f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(17.69f, 13.4798f) curveTo(17.61f, 13.2998f, 17.47f, 13.1498f, 17.28f, 13.0698f) curveTo(17.19f, 13.0298f, 17.09f, 13.0098f, 16.99f, 13.0098f) horizontalLineTo(7.0f) curveTo(6.59f, 13.0098f, 6.25f, 13.3498f, 6.25f, 13.7598f) curveTo(6.25f, 14.1698f, 6.59f, 14.5098f, 7.0f, 14.5098f) horizontalLineTo(15.19f) lineTo(13.52f, 16.1798f) curveTo(13.23f, 16.4698f, 13.23f, 16.9498f, 13.52f, 17.2398f) curveTo(13.67f, 17.3898f, 13.86f, 17.4598f, 14.05f, 17.4598f) curveTo(14.24f, 17.4598f, 14.43f, 17.3898f, 14.58f, 17.2398f) lineTo(17.53f, 14.2898f) curveTo(17.6f, 14.2198f, 17.65f, 14.1398f, 17.69f, 14.0498f) curveTo(17.77f, 13.8598f, 17.77f, 13.6598f, 17.69f, 13.4798f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(6.31f, 10.52f) curveTo(6.39f, 10.7f, 6.53f, 10.85f, 6.72f, 10.93f) curveTo(6.81f, 10.97f, 6.9f, 10.99f, 7.0f, 10.99f) horizontalLineTo(17.0f) curveTo(17.41f, 10.99f, 17.75f, 10.65f, 17.75f, 10.24f) curveTo(17.75f, 9.83f, 17.41f, 9.49f, 17.0f, 9.49f) horizontalLineTo(8.81f) lineTo(10.48f, 7.82f) curveTo(10.77f, 7.53f, 10.77f, 7.05f, 10.48f, 6.76f) curveTo(10.19f, 6.47f, 9.71f, 6.47f, 9.42f, 6.76f) lineTo(6.47f, 9.71f) curveTo(6.4f, 9.78f, 6.35f, 9.86f, 6.31f, 9.95f) curveTo(6.23f, 10.14f, 6.23f, 10.34f, 6.31f, 10.52f) close() } } .build() return _arrowswaphorizontal!! } private var _arrowswaphorizontal: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
4,143
VuesaxIcons
MIT License
compiler/frontend/src/org/jetbrains/kotlin/resolve/BodyResolveCache.kt
staltz
38,581,975
true
{"Markdown": 34, "XML": 687, "Ant Build System": 40, "Ignore List": 8, "Git Attributes": 1, "Kotlin": 18510, "Java": 4307, "Protocol Buffer": 4, "Text": 4085, "JavaScript": 63, "JAR Manifest": 3, "Roff": 30, "Roff Manpage": 10, "INI": 7, "HTML": 135, "Groovy": 20, "Maven POM": 50, "Gradle": 71, "Java Properties": 10, "CSS": 3, "Proguard": 1, "JFlex": 2, "Shell": 9, "Batchfile": 8, "ANTLR": 1}
/* * Copyright 2010-2015 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 org.jetbrains.kotlin.resolve import org.jetbrains.kotlin.psi.KtNamedFunction public interface BodyResolveCache { public open fun resolveFunctionBody(function: KtNamedFunction): BindingContext public object ThrowException : BodyResolveCache { public override fun resolveFunctionBody(function: KtNamedFunction): BindingContext { throw UnsupportedOperationException() } } }
0
Java
0
1
ff00bde607d605c4eba2d98fbc9e99af932accb6
1,025
kotlin
Apache License 2.0
app/src/main/kotlin/com/gdgnantes/devfest/android/http/JsonConverters.kt
cyrilmottier
96,089,951
false
null
package com.gdgnantes.devfest.android.http import com.gdgnantes.devfest.android.model.Session import com.gdgnantes.devfest.android.model.SocialNetwork import com.google.gson.FieldNamingPolicy import com.google.gson.Gson import com.google.gson.GsonBuilder import com.google.gson.TypeAdapter import com.google.gson.stream.JsonReader import com.google.gson.stream.JsonWriter object JsonConverters { val main: Gson = GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") .registerTypeAdapter(Session.Track::class.java, SessionTrackTypeAdapter().nullSafe()) .registerTypeAdapter(Session.Type::class.java, SessionTypeTypeAdapter().nullSafe()) .registerTypeAdapter(SocialNetwork::class.java, SocialNetworkTypeAdapter().nullSafe()) .create() private class SessionTrackTypeAdapter : TypeAdapter<Session.Track>() { override fun write(writer: JsonWriter, sessionTrack: Session.Track) { writer.value(sessionTrack.apiValue) } override fun read(reader: JsonReader): Session.Track? { return Session.Track.get(reader.nextString()) } } private class SessionTypeTypeAdapter : TypeAdapter<Session.Type>() { override fun write(writer: JsonWriter, sessionType: Session.Type) { writer.value(sessionType.apiValue) } override fun read(reader: JsonReader): Session.Type? { return Session.Type.get(reader.nextString()) } } private class SocialNetworkTypeAdapter : TypeAdapter<SocialNetwork>() { override fun write(writer: JsonWriter, socialNetwork: SocialNetwork) { writer.value(socialNetwork.apiValue) } override fun read(reader: JsonReader): SocialNetwork? { return SocialNetwork.get(reader.nextString()) } } }
1
null
1
3
014abd7b53ab82858a3144d5962682da73408286
1,934
devfest-android
Apache License 2.0
sdk/core/src/main/java/com/ownid/sdk/internal/feature/nativeflow/steps/otp/OtpAuthStepUI.kt
OwnID
414,235,878
false
{"Kotlin": 706134}
package com.ownid.sdk.internal.flow.steps.otp import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.content.DialogInterface import android.graphics.drawable.LayerDrawable import android.os.Bundle import android.text.Editable import android.text.InputFilter import android.text.TextWatcher import android.view.View import android.widget.Button import android.widget.TextView import androidx.annotation.RestrictTo import androidx.appcompat.content.res.AppCompatResources import androidx.core.content.ContextCompat import androidx.core.view.isVisible import androidx.fragment.app.FragmentManager import com.google.android.material.progressindicator.CircularProgressIndicator import com.ownid.sdk.InternalOwnIdAPI import com.ownid.sdk.R import com.ownid.sdk.exception.OwnIdFlowCanceled import com.ownid.sdk.exception.OwnIdUserError import com.ownid.sdk.internal.OwnIdInternalLogger import com.ownid.sdk.internal.flow.AbstractStepUI import com.ownid.sdk.internal.flow.OwnIdFlowError import com.ownid.sdk.internal.locale.OwnIdLocaleKey @InternalOwnIdAPI @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) internal class OtpAuthStepUI : AbstractStepUI<OtpAuthStep>(R.layout.com_ownid_sdk_internal_ui_otp) { @InternalOwnIdAPI internal companion object { private const val TAG = "com.ownid.sdk.internal.tag.OtpAuthStepUI" internal fun show(fragmentManager: FragmentManager): OtpAuthStepUI = OtpAuthStepUI().apply { OwnIdInternalLogger.logD(this, "show", "Invoked") show(fragmentManager, TAG) } } private val titleTextView: TextView by lazy(LazyThreadSafetyMode.NONE) { requireView().findViewById(R.id.com_ownid_sdk_internal_ui_otp_title) } private val messageTextView: TextView by lazy(LazyThreadSafetyMode.NONE) { requireView().findViewById(R.id.com_ownid_sdk_internal_ui_otp_message) } private val unspecifiedErrorTextView: TextView by lazy(LazyThreadSafetyMode.NONE) { requireView().findViewById(R.id.com_ownid_sdk_internal_ui_otp_unspecified_error) } private val descriptionTextView: TextView by lazy(LazyThreadSafetyMode.NONE) { requireView().findViewById(R.id.com_ownid_sdk_internal_ui_otp_description) } private val otpEditText: OwnIdAppCompatEditText by lazy(LazyThreadSafetyMode.NONE) { requireView().findViewById(R.id.com_ownid_sdk_internal_ui_otp) } private val resendButton: Button by lazy(LazyThreadSafetyMode.NONE) { requireView().findViewById(R.id.com_ownid_sdk_internal_ui_otp_resend) } private val cancelButton: Button by lazy(LazyThreadSafetyMode.NONE) { requireView().findViewById(R.id.com_ownid_sdk_internal_ui_otp_cancel) } private val notYouButton: Button by lazy(LazyThreadSafetyMode.NONE) { requireView().findViewById(R.id.com_ownid_sdk_internal_ui_otp_not_you) } private val progress: CircularProgressIndicator by lazy(LazyThreadSafetyMode.NONE) { requireView().findViewById(R.id.com_ownid_sdk_internal_ui_otp_progress) } private val errorTextView: TextView by lazy(LazyThreadSafetyMode.NONE) { requireView().findViewById(R.id.com_ownid_sdk_internal_ui_otp_error) } private val backgroundDrawable by lazy(LazyThreadSafetyMode.NONE) { AppCompatResources.getDrawable(requireContext(), R.drawable.com_ownid_sdk_internal_ui_otp_input_background) } private val backgroundErrorDrawable by lazy(LazyThreadSafetyMode.NONE) { val errorColor = ContextCompat.getColor(requireContext(), R.color.com_ownid_sdk_internal_ui_color_error) val drawable = AppCompatResources.getDrawable(requireContext(), R.drawable.com_ownid_sdk_internal_ui_otp_input_background) (drawable as LayerDrawable).apply { mutate(); this.getDrawable(0).setTint(errorColor) } } private val otpTextWatcher = object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit override fun afterTextChanged(s: Editable?) = currentStep.onOtp(otpEditText.text.toString()) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) if (isInitSuccessful.not()) return otpEditText.apply { flowType = currentStep.ownIdFlowData.flowType eventsService = currentStep.ownIdFlowData.ownIdCore.eventsService filters = arrayOf(InputFilter.LengthFilter(currentStep.data.otpLength)) maxEms = currentStep.data.otpLength minEms = currentStep.data.otpLength } resendButton.setOnClickListener { currentStep.onResend() } notYouButton.setOnClickListener { currentStep.onNotYou() } cancelButton.setOnClickListener { cancelButton.isEnabled = false currentStep.onCancel(OwnIdFlowCanceled.OTP) dismissAllowingStateLoss() } currentStep.state.observe(viewLifecycleOwner) { state -> OwnIdInternalLogger.logD(this, "onViewCreated.state", state.toString()) progress.isVisible = state.isBusy notYouButton.isEnabled = state.isBusy.not() resendButton.visibility = when { state.isBusy -> View.INVISIBLE state.resendVisible -> View.VISIBLE else -> View.INVISIBLE } if (state.error == null) { errorTextView.visibility = View.INVISIBLE otpEditText.background = backgroundDrawable showUnspecifiedError(false) } else { otpEditText.removeTextChangedListener(otpTextWatcher) otpEditText.setText(state.otp) otpEditText.addTextChangedListener(otpTextWatcher) val ownIdUserError = when (state.error) { is OwnIdFlowError -> state.error.toOwnIdUserError(getString(OwnIdLocaleKey.UNSPECIFIED_ERROR)) else -> { val userMessage = getString(OwnIdLocaleKey.UNSPECIFIED_ERROR) OwnIdUserError(OwnIdUserError.Code.UNSPECIFIED, userMessage, "Something went wrong. Please try again.", state.error) } } if (state.error is OwnIdFlowError && state.error.flowFinished) { otpEditText.isEnabled = false } if (ownIdUserError.isUnspecified()) { showUnspecifiedError(true) } else { resendButton.visibility = View.INVISIBLE errorTextView.text = ownIdUserError.userMessage errorTextView.visibility = View.VISIBLE otpEditText.background = backgroundErrorDrawable } } if (state.done) dismissAllowingStateLoss() } } override fun onStart() { super.onStart() otpEditText.addTextChangedListener(otpTextWatcher) } override fun onResume() { super.onResume() otpEditText.focusAndShowKeyboard() } override fun onStop() { otpEditText.removeTextChangedListener(otpTextWatcher) super.onStop() } override fun onCancel(dialog: DialogInterface) { if (isInitSuccessful) currentStep.onCancel(OwnIdFlowCanceled.OTP) super.onCancel(dialog) } override fun setStrings() { if (isInitSuccessful.not()) return titleTextView.text = getString(LocaleKeys.getTitleKey(currentStep.data)) messageTextView.text = getString(LocaleKeys.getMessageKey(currentStep.data)) .replace("%CODE_LENGTH%", currentStep.data.otpLength.toString()) .replace("%LOGIN_ID%", currentStep.ownIdFlowData.loginId.value) descriptionTextView.text = getString(LocaleKeys.getDescriptionKey(currentStep.data)) resendButton.text = getString(LocaleKeys.getResendKey(currentStep.data)) cancelButton.text = getString(LocaleKeys.getCancelKey(currentStep.data)) notYouButton.text = getString(LocaleKeys.getNotYouKey(currentStep.data)) unspecifiedErrorTextView.text = getString(OwnIdLocaleKey.UNSPECIFIED_ERROR) } private fun showUnspecifiedError(show: Boolean) { if (show) { unspecifiedErrorTextView.apply { if (visibility == View.VISIBLE) return alpha = 0f visibility = View.VISIBLE animate().alpha(1f).setDuration(400L).setListener(null) } } else { if (unspecifiedErrorTextView.visibility == View.GONE) return unspecifiedErrorTextView.animate().alpha(0f).setDuration(300L).setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { unspecifiedErrorTextView.visibility = View.GONE } }) } } private object LocaleKeys { private val prefix = arrayOf("steps", "otp") @JvmStatic internal fun getTitleKey(data: OtpAuthStep.Data) = OwnIdLocaleKey( *prefix, data.operationType.name.lowercase(), data.verificationType.name.lowercase(), "title", ).withFallback( when (data.operationType) { OtpAuthStep.OperationType.Sign -> R.string.com_ownid_sdk_internal_ui_steps_otp_title_sign OtpAuthStep.OperationType.Verify -> when (data.verificationType) { OtpAuthStep.VerificationType.Email -> R.string.com_ownid_sdk_internal_ui_steps_otp_title_verify_email OtpAuthStep.VerificationType.Sms -> R.string.com_ownid_sdk_internal_ui_steps_otp_title_verify_sms } } ) @JvmStatic internal fun getMessageKey(data: OtpAuthStep.Data) = OwnIdLocaleKey( *prefix, data.verificationType.name.lowercase(), data.operationType.name.lowercase(), "message" ).withFallback( when (data.verificationType) { OtpAuthStep.VerificationType.Email -> R.string.com_ownid_sdk_internal_ui_steps_otp_message_email OtpAuthStep.VerificationType.Sms -> R.string.com_ownid_sdk_internal_ui_steps_otp_message_sms } ) @JvmStatic internal fun getDescriptionKey(data: OtpAuthStep.Data) = OwnIdLocaleKey( *prefix, data.verificationType.name.lowercase(), data.operationType.name.lowercase(), "description" ).withFallback(R.string.com_ownid_sdk_internal_ui_steps_otp_description) @JvmStatic internal fun getResendKey(data: OtpAuthStep.Data): OwnIdLocaleKey = OwnIdLocaleKey( *prefix, data.verificationType.name.lowercase(), data.operationType.name.lowercase(), "resend", ).withFallback( when (data.verificationType) { OtpAuthStep.VerificationType.Email -> R.string.com_ownid_sdk_internal_ui_steps_otp_resend_email OtpAuthStep.VerificationType.Sms -> R.string.com_ownid_sdk_internal_ui_steps_otp_resend_sms } ) @JvmStatic internal fun getCancelKey(data: OtpAuthStep.Data) = OwnIdLocaleKey( *prefix, data.verificationType.name.lowercase(), data.operationType.name.lowercase(), "cancel" ).withFallback(R.string.com_ownid_sdk_internal_ui_steps_cancel) @JvmStatic internal fun getNotYouKey(data: OtpAuthStep.Data) = OwnIdLocaleKey( *prefix, data.verificationType.name.lowercase(), data.operationType.name.lowercase(), "not-you" ).withFallback(R.string.com_ownid_sdk_internal_ui_steps_otp_not_you) } }
0
Kotlin
1
2
35970df713993da255a866915a65ebefe3d5c958
11,711
ownid-android-sdk
Apache License 2.0
tmp/arrays/kotlinAndJava/23.kt
mandelshtamd
249,374,670
false
{"Git Config": 1, "Gradle": 6, "Text": 3, "INI": 5, "Shell": 2, "Ignore List": 3, "Batchfile": 2, "Markdown": 2, "Kotlin": 15942, "JavaScript": 4, "ANTLR": 2, "XML": 12, "Java": 4}
//File B.java import kotlin.Metadata; import kotlin.jvm.internal.Intrinsics; import kotlin.jvm.internal.Ref.ObjectRef; import org.jetbrains.annotations.NotNull; public final class B { @NotNull private String x; @NotNull public final String foo() { final ObjectRef s = new ObjectRef(); s.element = "OK"; final class Z extends C { public Z() { super((String)s.element); } } return (new Z()).test(); } @NotNull public final String foo2() { final class Y extends C { public Y() { super(B.this.getX()); } } return (new Y()).test(); } @NotNull public final String getX() { return this.x; } public final void setX(@NotNull String var1) { this.x = var1; } public B(@NotNull String x) { super(); this.x = x; } } //File Main.kt fun box(): String { val b = B("OK") if (b.foo() != "OK") return "fail: ${b.foo()}" return b.foo2() } //File C.java import kotlin.Metadata; import kotlin.jvm.internal.Intrinsics; import org.jetbrains.annotations.NotNull; public class C { @NotNull private final String s; @NotNull public final String test() { return this.s; } @NotNull public final String getS() { return this.s; } public C(@NotNull String s) { super(); this.s = s; } }
1
null
1
1
da010bdc91c159492ae74456ad14d93bdb5fdd0a
1,417
bbfgradle
Apache License 2.0
core/src/main/java/com/kevinmost/koolbelt/util/SelfReference.kt
kevinmost
57,383,899
false
null
package com.kevinmost.koolbelt.util class SelfReference<T> { val self: T by lazy { __self ?: throw IllegalStateException("Do not use `self` until initialized.") } var __self: T? = null } /** * Allows referencing "this" (via the "self" variable) while initializing this value * * See: http://stackoverflow.com/q/35100389 for the idea and a sample. Rewritten slightly to * allow the [initializer] block to be inlined. */ inline fun <T> selfReference(initializer: SelfReference<T>.() -> T): T { return SelfReference<T>().apply { __self = initializer() }.self }
0
Kotlin
2
3
2a35ac39f57810f7fbc044e780b9a838562e4554
579
koolbelt
Apache License 2.0
app/src/main/java/com/app/myarticleapp/localStorage/ArticleDatabase.kt
sunday58
531,985,278
false
{"Kotlin": 44667}
package com.app.myarticleapp.localStorage import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters import com.app.myarticleapp.apiSource.converter.ArticleConverter import com.app.myarticleapp.apiSource.converter.MediaArticleConverter import com.app.myarticleapp.apiSource.converter.SubMediaArticleConverter import com.app.myarticleapp.apiSource.responseEntity.ArticleResponse @Database( entities = [ArticleResponse::class], version = 1 ) @TypeConverters(ArticleConverter::class, MediaArticleConverter::class, SubMediaArticleConverter::class) abstract class ArticleDatabase: RoomDatabase() { abstract fun articleDao(): ArticleDao companion object{ val DATABASE_NAME: String = "article_db" } }
0
Kotlin
0
0
6fd20d7dfed82dcfed6cd90bbe0a1b4b9c669cfc
767
MyArticleApp
Apache License 2.0
widgetssdk/src/main/java/com/glia/widgets/chat/domain/IsSecureConversationsChatAvailableUseCase.kt
salemove
312,288,713
false
null
package com.glia.widgets.chat.domain import com.glia.widgets.core.engagement.GliaEngagementConfigRepository import com.glia.widgets.core.secureconversations.domain.IsMessagingAvailableUseCase import io.reactivex.Observable internal class IsSecureConversationsChatAvailableUseCase( private val engagementConfigRepository: GliaEngagementConfigRepository, private val isMessagingAvailableUseCase: IsMessagingAvailableUseCase ) { operator fun invoke(): Observable<Boolean> = isMessagingAvailableUseCase(engagementConfigRepository.queueIds) }
6
null
1
6
53b926baa0c69502c4f4f5eea37ac6e18a934308
560
android-sdk-widgets
MIT License
app/src/main/java/com/example/appstore/data/server/ApiService.kt
rezakardan
779,591,568
false
{"Kotlin": 353707, "Java": 16027}
package com.example.appstore.data.server import com.example.appstore.data.model.SimpleResponse import com.example.appstore.data.model.cart.* import com.example.appstore.data.model.category.ResponseCategory import com.example.appstore.data.model.comment.ResponseDeleteComments import com.example.appstore.data.model.comment.ResponseGetComment import com.example.appstore.data.model.detail.* import com.example.appstore.data.model.favorite.ResponseDeleteFavorite import com.example.appstore.data.model.favorite.ResponseGetFavorite import com.example.appstore.data.model.home.ResponseBanners import com.example.appstore.data.model.home.ResponseDiscount import com.example.appstore.data.model.home.ResponseProducts import com.example.appstore.data.model.login.BodyResponseLogin import com.example.appstore.data.model.login.ResponseLogin import com.example.appstore.data.model.login.ResponseVerify import com.example.appstore.data.model.product.ResponseProductCategory import com.example.appstore.data.model.profile.ResponseProfile import com.example.appstore.data.model.profile.BodyUpdateProfile import com.example.appstore.data.model.profile_order.ResponseProfileOrders import com.example.appstore.data.model.search.ResponseSearch import com.example.appstore.data.model.shipping.* import com.example.appstore.data.model.wallet.ResponseGetWallet import com.example.appstore.data.model.wallet.BodyIncreaseWallet import com.example.appstore.data.model.wallet.ResponseIncreaseWallet import com.example.appstore.data.profile_address.BodyResponseInsertOrUpdate import com.example.appstore.data.profile_address.ResponseInsertOrUpdateAddress import com.example.appstore.data.profile_address.ResponseProfileAddresses import com.example.appstore.data.profile_address.ResponseProvinceOrCity import okhttp3.RequestBody import retrofit2.Response import retrofit2.http.Body import retrofit2.http.DELETE import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.PUT import retrofit2.http.Path import retrofit2.http.Query interface ApiService { @POST("auth/login") suspend fun postLogin(@Body body: BodyResponseLogin): Response<ResponseLogin> @POST("auth/login/verify") suspend fun postVerifyLogin(@Body body: BodyResponseLogin): Response<ResponseVerify> @GET("auth/detail") suspend fun getProfile(): Response<ResponseProfile> @GET("ad/swiper/{slug}") suspend fun getBannersListHome(@Path("slug") slug: String): Response<ResponseBanners> @GET("offers/discount/{slug}") suspend fun getDiscount(@Path("slug") slug: String): Response<ResponseDiscount> @GET("category/pro/{slug}") suspend fun getMobilesList( @Path("slug") slug: String, @Query("sort") sort: String ): Response<ResponseProducts> @GET("category/pro/{slug}") suspend fun getShoesList( @Path("slug") slug: String, @Query("sort") sort: String ): Response<ResponseProducts> @GET("category/pro/{slug}") suspend fun getLapTopList( @Path("slug") slug: String, @Query("sort") sort: String ): Response<ResponseProducts> @GET("category/pro/{slug}") suspend fun getStationaryList( @Path("slug") slug: String, @Query("sort") sort: String ): Response<ResponseProducts> @GET("search") suspend fun getSearch( @Query("q") q: String, @Query("sort") sort: String ): Response<ResponseSearch> @GET("menu") suspend fun getCategory(): Response<ResponseCategory> @GET("category/pro/{slug}") suspend fun getProductCategory( @Path("slug") slug: String, @Query("search") search: String? = null, @Query("sort") sort: String? = null, @Query("minPrice") minPrice: String? = null, @Query("maxPrice") maxPrice: String? = null, @Query("selectedBrands") selectedBrands: String? = null, @Query("selectedColors") selectedColors: String? = null, @Query("page ") page: String? = "1", @Query("onlyAvailable") onlyAvailable: Boolean? = null, ): Response<ResponseProductCategory> @GET("auth/wallet") suspend fun getWallet(): Response<ResponseGetWallet> @POST("auth/avatar") suspend fun postUploadAvatar(@Body body: RequestBody): Response<Unit> @PUT("auth/update") suspend fun updateProfile(@Body body: BodyUpdateProfile): Response<ResponseProfile> @POST("auth/wallet") suspend fun postIncreaseWallet(@Body body: BodyIncreaseWallet): Response<ResponseIncreaseWallet> @GET("auth/comments") suspend fun getComment(): Response<ResponseGetComment> @DELETE("auth/comment/{commentId}") suspend fun deleteComments(@Path("commentId") commentId: Int): Response<ResponseDeleteComments> @GET("auth/favorites") suspend fun getFavorites(): Response<ResponseGetFavorite> @DELETE("auth/favorite/{favoriteId}") suspend fun deleteFavorites(@Path("favoriteId") favoriteId: Int): Response<ResponseDeleteFavorite> @GET("auth/addresses") suspend fun profileAddresses(): Response<ResponseProfileAddresses> @GET("auth/address/provinces") suspend fun getProvinceAddress(): Response<ResponseProvinceOrCity> @GET("auth/address/provinces") suspend fun getCityAddress(@Query("provinceId") provinceId: Int): Response<ResponseProvinceOrCity> @POST("auth/address") suspend fun insertOrUpdateAddress(@Body body: BodyResponseInsertOrUpdate): Response<ResponseInsertOrUpdateAddress> @DELETE("auth/address/remove/{address_Id}") suspend fun deleteAddress(@Path("address_Id") address_Id: Int): Response<ResponseDeleteComments> @GET("auth/orders") suspend fun profileOrders(@Query("status")status:String):Response<ResponseProfileOrders> @GET("product/{id}") suspend fun getDetailProducts(@Path("id")id:Int):Response<ResponseDetail> @POST("product/{id}/like") suspend fun postFavoriteDetail(@Path("id")id:Int):Response<ResponseFavoriteDetail> @POST("product/{id}/add_to_cart") suspend fun addToCartDetail(@Path("id")id:Int,@Body body:BodyAddToCart):Response<SimpleResponse> @GET("product/{id}/features") suspend fun detailFeatures(@Path("id")id:Int):Response<ResponseDetailFeatures> @GET("product/{id}/comments") suspend fun getDetailComment(@Path("id")id:Int):Response<ResponseGetDetailComment> @POST("product/{id}/comments") suspend fun postDetailAddComment(@Path("id")id:Int,@Body body:BodyDetailAddComment):Response<SimpleResponse> @GET("product/{id}/price-chart") suspend fun detailPriceChart(@Path("id")id:Int):Response<ResponseDetailPriceChart> @GET("cart") suspend fun getCartList():Response<ResponseGetCartList> @PUT("cart/{id}/increment") suspend fun putIncrementCart(@Path("id")id:Int):Response<ResponseUpdateCart> @PUT("cart/{id}/decrement") suspend fun putDecrementCart(@Path("id")id:Int):Response<ResponseUpdateCart> @DELETE("cart/{id}") suspend fun deleteProductFromCart(@Path("id")id:Int):Response<ResponseUpdateCart> @GET("cart/continue") suspend fun cartContinue():Response<ResponseCartContinue> @GET("shipping") suspend fun getShippingList():Response<ResponseShippingList> @PUT("shipping/set/address") suspend fun setAddress(@Body body:BodySetAddress):Response<ResponseSetAddress> @POST("check/coupon") suspend fun callCouponShippingApi(@Body body:BodyCouponShipping):Response<ResponseCouponShipping> @POST("payment") suspend fun postPayment(@Body body: BodyCouponShipping): Response<ResponseIncreaseWallet> }
0
Kotlin
0
0
c64368f08faae5b50d158dadb79a8a1a3cd3e140
7,452
AppStore__Git
MIT License
node/src/main/java/me/interair/wi/node/api/WordController.kt
interair
249,382,868
false
null
package me.interair.wi.node.api import me.interair.wi.word.WordData import me.interair.wi.word.WordReport import me.interair.wi.word.WordsRepository import org.springframework.util.MimeTypeUtils import org.springframework.web.bind.annotation.* import reactor.core.publisher.Mono @RequestMapping(path = ["/word"], produces = [MimeTypeUtils.APPLICATION_JSON_VALUE]) @RestController class WordController( val repository: WordsRepository ) { @GetMapping(path = ["/{word}"]) fun get(@PathVariable("word") word: String): Mono<WordReport> { return repository.findByDocumentWord(word) } @PutMapping fun save(@RequestBody wordData: WordData) { repository.saveWord(wordData) } }
0
Kotlin
0
0
5895de71c48a04724d49f25247b468a584416832
719
word-indexer
Apache License 2.0
test/src/me/anno/tests/ui/FileExplorerLag.kt
AntonioNoack
456,513,348
false
{"Kotlin": 10736182, "C": 236426, "Java": 6754, "Lua": 4404, "C++": 3070, "GLSL": 2698}
package me.anno.tests.ui import me.anno.config.DefaultConfig.style import me.anno.image.raw.IntImage import me.anno.io.files.inner.InnerFolder import me.anno.ui.debug.TestEngine.Companion.testUI3 import me.anno.ui.editor.files.FileExplorer import me.anno.utils.OS.desktop fun main() { // todo file explorer seems to be lagging from Thumbnails, but also from text rendering -> eliminate that val format = "Grand Theft Auto V XXXX-XX-XX XX-XX-XX.mp4" val folder = InnerFolder(desktop.getChild("tmp")) val image = IntImage(2, 2, intArrayOf(1, 2, -1, 0), false) for (i in 0 until 10_000) { folder.createImageChild( format .map { if (it == 'X') "0123456789".random() else it }.joinToString(""), image ) } testUI3("FileExplorerLag", FileExplorer(folder, true, style)) }
0
Kotlin
3
24
63377c2e684adf187a31af0f4e5dd0bfde1d050e
893
RemsEngine
Apache License 2.0
model/src/main/kotlin/org/ethereum/lists/chains/model/Explorer.kt
Thegaram
443,286,749
true
{"Kotlin": 19613}
package org.ethereum.lists.chains.model import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class Explorer( val name: String, val url: String, val standard: String )
0
null
1
1
fc51b2ebf2ab3492d5b74069a87c9a58109f2c43
203
chains
MIT License
compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/transformers/plugin/FirCompilerRequiredAnnotationsResolveTransformer.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.fir.resolve.transformers.plugin import com.google.common.collect.LinkedHashMultimap import com.google.common.collect.Multimap import kotlinx.collections.immutable.PersistentList import kotlinx.collections.immutable.persistentListOf import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.fir.FirElement import org.jetbrains.kotlin.fir.FirSession import org.jetbrains.kotlin.fir.declarations.* import org.jetbrains.kotlin.fir.declarations.FirResolvePhase.COMPILER_REQUIRED_ANNOTATIONS import org.jetbrains.kotlin.fir.expressions.FirAnnotation import org.jetbrains.kotlin.fir.expressions.FirAnnotationCall import org.jetbrains.kotlin.fir.expressions.FirStatement import org.jetbrains.kotlin.fir.extensions.* import org.jetbrains.kotlin.fir.languageVersionSettings import org.jetbrains.kotlin.fir.resolve.ResolutionMode import org.jetbrains.kotlin.fir.resolve.ScopeSession import org.jetbrains.kotlin.fir.resolve.fqName import org.jetbrains.kotlin.fir.resolve.providers.FirSymbolProviderInternals import org.jetbrains.kotlin.fir.resolve.transformers.* import org.jetbrains.kotlin.fir.types.ConeClassLikeType import org.jetbrains.kotlin.fir.types.FirUserTypeRef import org.jetbrains.kotlin.fir.types.coneTypeSafe import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.name.StandardClassIds.Annotations.Deprecated import org.jetbrains.kotlin.name.StandardClassIds.Annotations.DeprecatedSinceKotlin import org.jetbrains.kotlin.name.StandardClassIds.Annotations.WasExperimental class FirCompilerRequiredAnnotationsResolveProcessor( session: FirSession, scopeSession: ScopeSession ) : FirTransformerBasedResolveProcessor(session, scopeSession) { override val transformer = FirCompilerRequiredAnnotationsResolveTransformer(session, scopeSession) @OptIn(FirSymbolProviderInternals::class) override fun beforePhase() { session.generatedDeclarationsSymbolProvider?.disable() } @OptIn(FirSymbolProviderInternals::class) override fun afterPhase() { session.generatedDeclarationsSymbolProvider?.enable() } } open class FirCompilerRequiredAnnotationsResolveTransformer( final override val session: FirSession, scopeSession: ScopeSession ) : FirAbstractPhaseTransformer<Any?>(COMPILER_REQUIRED_ANNOTATIONS) { private val annotationTransformer = FirAnnotationResolveTransformer(session, scopeSession) private val importTransformer = FirPartialImportResolveTransformer(session) val extensionService = session.extensionService override fun <E : FirElement> transformElement(element: E, data: Any?): E { throw IllegalStateException("Should not be here") } override fun transformFile(file: FirFile, data: Any?): FirFile { checkSessionConsistency(file) val registeredPluginAnnotations = session.registeredPluginAnnotations val newAnnotations = file.resolveAnnotations(registeredPluginAnnotations.annotations, registeredPluginAnnotations.metaAnnotations) if (!newAnnotations.isEmpty) { for (metaAnnotation in newAnnotations.keySet()) { registeredPluginAnnotations.registerUserDefinedAnnotation(metaAnnotation, newAnnotations[metaAnnotation]) } val newAnnotationsFqns = newAnnotations.values().mapTo(mutableSetOf()) { it.symbol.classId.asSingleFqName() } file.resolveAnnotations(newAnnotationsFqns, emptySet()) } return file } fun <T> withFile(file: FirFile, f: () -> T): T = annotationTransformer.withFile(file, f) fun <T> withFileAndScopes(file: FirFile, f: () -> T): T { annotationTransformer.withFile(file) { return annotationTransformer.withFileScopes(file, f) } } override fun transformRegularClass(regularClass: FirRegularClass, data: Any?): FirStatement { return annotationTransformer.transformRegularClass(regularClass, LinkedHashMultimap.create()) } override fun transformTypeAlias(typeAlias: FirTypeAlias, data: Any?): FirStatement { return annotationTransformer.transformTypeAlias(typeAlias, LinkedHashMultimap.create()) } private fun FirFile.resolveAnnotations( annotations: Set<AnnotationFqn>, metaAnnotations: Set<AnnotationFqn> ): Multimap<AnnotationFqn, FirRegularClass> { importTransformer.acceptableFqNames = annotations this.transformImports(importTransformer, null) annotationTransformer.acceptableFqNames = annotations annotationTransformer.metaAnnotations = metaAnnotations val newAnnotations = LinkedHashMultimap.create<AnnotationFqn, FirRegularClass>() this.transform<FirFile, Multimap<AnnotationFqn, FirRegularClass>>(annotationTransformer, newAnnotations) return newAnnotations } } private class FirPartialImportResolveTransformer( session: FirSession ) : FirImportResolveTransformer(session, COMPILER_REQUIRED_ANNOTATIONS) { var acceptableFqNames: Set<FqName> = emptySet() override val FqName.isAcceptable: Boolean get() = this in acceptableFqNames } private class FirAnnotationResolveTransformer( session: FirSession, scopeSession: ScopeSession ) : FirAbstractAnnotationResolveTransformer<Multimap<AnnotationFqn, FirRegularClass>, PersistentList<FirDeclaration>>( session, scopeSession ) { companion object { private val REQUIRED_ANNOTATIONS: Set<ClassId> = setOf( Deprecated, DeprecatedSinceKotlin, WasExperimental ) private val REQUIRED_ANNOTATION_NAMES: Set<Name> = REQUIRED_ANNOTATIONS.mapTo(mutableSetOf()) { it.shortClassName } } private val predicateBasedProvider = session.predicateBasedProvider var acceptableFqNames: Set<AnnotationFqn> = emptySet() var metaAnnotations: Set<AnnotationFqn> = emptySet() private val typeResolverTransformer: FirSpecificTypeResolverTransformer = FirSpecificTypeResolverTransformer( session, errorTypeAsResolved = false ) private val argumentsTransformer = FirAnnotationArgumentsResolveTransformer(session, scopeSession, COMPILER_REQUIRED_ANNOTATIONS) private var owners: PersistentList<FirDeclaration> = persistentListOf() private val classDeclarationsStack = ArrayDeque<FirClass>() override fun beforeTransformingChildren(parentDeclaration: FirDeclaration): PersistentList<FirDeclaration> { val current = owners owners = owners.add(parentDeclaration) return current } override fun afterTransformingChildren(state: PersistentList<FirDeclaration>?) { requireNotNull(state) owners = state } override fun transformAnnotationCall(annotationCall: FirAnnotationCall, data: Multimap<AnnotationFqn, FirRegularClass>): FirStatement { return transformAnnotation(annotationCall, data) } override fun transformAnnotation( annotation: FirAnnotation, data: Multimap<AnnotationFqn, FirRegularClass> ): FirStatement { val annotationTypeRef = annotation.annotationTypeRef if (annotationTypeRef !is FirUserTypeRef) return annotation val name = annotationTypeRef.qualifier.last().name if (name !in REQUIRED_ANNOTATION_NAMES && acceptableFqNames.none { it.shortName() == name }) return annotation val transformedAnnotation = annotation.transformAnnotationTypeRef( typeResolverTransformer, ScopeClassDeclaration(scopes.asReversed(), classDeclarationsStack) ) // TODO: what if we have type alias here? if (transformedAnnotation.annotationTypeRef.coneTypeSafe<ConeClassLikeType>()?.lookupTag?.classId == Deprecated) { argumentsTransformer.transformAnnotation(transformedAnnotation, ResolutionMode.ContextDependent) } return transformedAnnotation } override fun transformRegularClass( regularClass: FirRegularClass, data: Multimap<AnnotationFqn, FirRegularClass> ): FirStatement { withClassDeclarationCleanup(classDeclarationsStack, regularClass) { return super.transformRegularClass(regularClass, data).also { if (regularClass.classKind == ClassKind.ANNOTATION_CLASS && metaAnnotations.isNotEmpty()) { val annotations = regularClass.annotations.mapNotNull { it.fqName(session) } for (annotation in annotations.filter { it in metaAnnotations }) { data.put(annotation, regularClass) } } calculateDeprecations(regularClass) } } } override fun transformTypeAlias(typeAlias: FirTypeAlias, data: Multimap<AnnotationFqn, FirRegularClass>): FirTypeAlias { return super.transformTypeAlias(typeAlias, data).also { calculateDeprecations(typeAlias) } } override fun transformDeclaration(declaration: FirDeclaration, data: Multimap<AnnotationFqn, FirRegularClass>): FirDeclaration { return super.transformDeclaration(declaration, data).also { predicateBasedProvider.registerAnnotatedDeclaration(declaration, owners) } } override fun transformFile(file: FirFile, data: Multimap<AnnotationFqn, FirRegularClass>): FirFile { withFile(file) { return super.transformFile(file, data) } } inline fun <T> withFile(file: FirFile, f: () -> T): T { typeResolverTransformer.withFile(file) { argumentsTransformer.context.withFile(file, argumentsTransformer.components) { return f() } } } private fun calculateDeprecations(classLikeDeclaration: FirClassLikeDeclaration) { if (classLikeDeclaration.deprecation == null) { classLikeDeclaration.replaceDeprecation(classLikeDeclaration.getDeprecationInfos(session.languageVersionSettings.apiVersion)) } } }
9
Kotlin
5209
42,102
65f712ab2d54e34c5b02ffa3ca8c659740277133
10,242
kotlin
Apache License 2.0
core/src/com/lyeeedar/AI/BehaviourTree/Actions/ActionPick.kt
Lyeeedar
83,986,995
false
null
package com.lyeeedar.AI.BehaviourTree.Actions import com.badlogic.ashley.core.Entity import com.badlogic.gdx.utils.XmlReader import com.lyeeedar.AI.BehaviourTree.ExecutionState import com.lyeeedar.Components.stats import com.lyeeedar.Components.tile import com.lyeeedar.Global import com.lyeeedar.Systems.level import com.lyeeedar.Util.Point import java.util.* /** * Created by Philip on 21-Mar-16. */ class ActionPick(): AbstractAction() { lateinit var input: String lateinit var output: String lateinit var criteria: String var lowest: Boolean = true val ran: Random = Random() override fun evaluate(entity: Entity): ExecutionState { state = ExecutionState.FAILED val tile = entity.tile() ?: return ExecutionState.FAILED val obj = getData<Any>(input, null) if (obj == null || obj !is Iterable<*>) { state = ExecutionState.FAILED } else { if (obj.count() == 0) { state = ExecutionState.FAILED } else { if (criteria == "random" || criteria == "ran" || criteria == "rnd") { val index = ran.nextInt(obj.count()) setData(output, obj.elementAt(index)) state = ExecutionState.COMPLETED } else if (criteria == "distance" || criteria == "dist" || criteria == "dst") { obj.sortedBy { (it as? Point)?.taxiDist(tile) ?: (it as? Entity)?.tile()?.taxiDist(tile) } val item = if (lowest) obj.first() else obj.last() setData(output, item) state = ExecutionState.COMPLETED } else if (criteria == "player") { for (e in obj) { if (e === Global.engine.level!!.player) { setData(output, e) state = ExecutionState.COMPLETED break } } } else { obj.sortedBy { (it as? Entity)?.stats()?.get(criteria, 0f) } val item = if (lowest) obj.first() else obj.last() setData(output, item); state = ExecutionState.COMPLETED; } } } return state } override fun parse(xml: XmlReader.Element) { input = xml.getAttribute("Input").toLowerCase() output = xml.getAttribute("Output").toLowerCase() criteria = xml.getAttribute("Criteria", "Distance").toLowerCase() lowest = xml.getBooleanAttribute("Lowest", true) } override fun cancel(entity: Entity) { } }
0
Kotlin
3
12
e8e58ab6d24cbfa25e40751b6b8f85139afe9129
2,253
TheAbyssOfSouls
Apache License 2.0
generator/src/main/kotlin/name/anton3/vkapi/generator/json/TypeSchemaDeserializer.kt
Anton3
159,801,334
true
{"Kotlin": 1382186}
package name.anton3.vkapi.generator.json import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.deser.std.StdDeserializer import kotlin.reflect.KClass class TypeSchemaDeserializer : StdDeserializer<TypeSchema>(TypeSchema::class.java) { override fun deserialize(p: JsonParser, ctxt: DeserializationContext): TypeSchema { val oc = p.codec if (p.isExpectedStartObjectToken) p.nextToken() val node: JsonNode = oc.readTree(p) val kind: KClass<out TypeSchema> = when { node.has("\$ref") -> RefType::class node.has("oneOf") -> OneOfType::class node.has("allOf") -> AllOfType::class node.has("type") && node["type"].isArray -> SimpleMultiType::class node.has("type") && node["type"].textValue() == "array" -> ArrayType::class node.has("enum") -> EnumType::class node.has("type") && node["type"].textValue() == "string" -> SimpleType::class node.has("patternProperties") -> PatternPropertiesType::class (node.has("type") && node["type"].textValue() == "object") -> ObjectType::class node.has("properties") -> ObjectType::class else -> SimpleType::class } return oc.treeToValue(node, kind.java) } }
2
Kotlin
0
8
773c89751c4382a42f556b6d3c247f83aabec625
1,417
kotlin-vk-api
MIT License
sdk-lib/src/main/java/cash/z/ecc/android/sdk/exception/Exceptions.kt
zcash
151,763,639
false
null
package cash.z.ecc.android.sdk.exception import cash.z.ecc.android.sdk.internal.model.Checkpoint import cash.z.ecc.android.sdk.model.BlockHeight import cash.z.ecc.android.sdk.type.ZcashNetwork import cash.z.wallet.sdk.rpc.Service import io.grpc.Status import io.grpc.Status.Code.UNAVAILABLE /** * Marker for all custom exceptions from the SDK. Making it an interface would result in more typing * so it's a supertype, instead. */ open class SdkException(message: String, cause: Throwable?) : RuntimeException(message, cause) /** * Exceptions thrown in the Rust layer of the SDK. We may not always be able to surface details about this * exception so it's important for the SDK to provide helpful messages whenever these errors are encountered. */ sealed class RustLayerException(message: String, cause: Throwable? = null) : SdkException(message, cause) { class BalanceException(cause: Throwable) : RustLayerException( "Error while requesting the current balance over " + "JNI. This might mean that the database has been corrupted and needs to be rebuilt. Verify that " + "blocks are not missing or have not been scanned out of order.", cause ) } /** * User-facing exceptions thrown by the transaction repository. */ sealed class RepositoryException(message: String, cause: Throwable? = null) : SdkException(message, cause) { object FalseStart : RepositoryException( "The channel is closed. Note that once a repository has stopped it " + "cannot be restarted. Verify that the repository is not being restarted." ) object Unprepared : RepositoryException( "Unprepared repository: Data cannot be accessed before the repository is prepared." + " Ensure that things have been properly initialized. If you see this error it most" + " likely means that you are accessing transactions or other data before starting the" + " Synchronizer. Previously, this was a silent bug that would cause problems later." + " Mostly, during database migrations. Now, we catch this early and explicitly prevent" + " it from happening." ) } /** * High-level exceptions thrown by the synchronizer, which do not fall within the umbrella of a * child component. */ sealed class SynchronizerException(message: String, cause: Throwable? = null) : SdkException(message, cause) { object FalseStart : SynchronizerException( "This synchronizer was already started. Multiple calls to start are not" + "allowed and once a synchronizer has stopped it cannot be restarted." ) object NotYetStarted : SynchronizerException( "The synchronizer has not yet started. Verify that" + " start has been called prior to this operation and that the coroutineScope is not" + " being accessed before it is initialized." ) } /** * Potentially user-facing exceptions that occur while processing compact blocks. */ sealed class CompactBlockProcessorException(message: String, cause: Throwable? = null) : SdkException(message, cause) { class DataDbMissing(path: String) : CompactBlockProcessorException( "No data db file found at path $path. Verify " + "that the data DB has been initialized via `rustBackend.initDataDb(path)`" ) open class ConfigurationException(message: String, cause: Throwable?) : CompactBlockProcessorException(message, cause) class FileInsteadOfPath(fileName: String) : ConfigurationException( "Invalid Path: the given path appears to be a" + " file name instead of a path: $fileName. The RustBackend expects the absolutePath to the database rather" + " than just the database filename because Rust does not access the app Context." + " So pass in context.getDatabasePath(dbFileName).absolutePath instead of just dbFileName alone.", null ) class FailedReorgRepair(message: String) : CompactBlockProcessorException(message) class FailedDownload(cause: Throwable? = null) : CompactBlockProcessorException( "Error while downloading blocks. This most " + "likely means the server is down or slow to respond. See logs for details.", cause ) class FailedScan(cause: Throwable? = null) : CompactBlockProcessorException( "Error while scanning blocks. This most " + "likely means a block was missed or a reorg was mishandled. See logs for details.", cause ) class Disconnected(cause: Throwable? = null) : CompactBlockProcessorException("Disconnected Error. Unable to download blocks due to ${cause?.message}", cause) object Uninitialized : CompactBlockProcessorException( "Cannot process blocks because the wallet has not been" + " initialized. Verify that the seed phrase was properly created or imported. If so, then this problem" + " can be fixed by re-importing the wallet." ) object NoAccount : CompactBlockProcessorException( "Attempting to scan without an account. This is probably a setup error or a race condition." ) open class EnhanceTransactionError(message: String, val height: BlockHeight?, cause: Throwable) : CompactBlockProcessorException(message, cause) { class EnhanceTxDownloadError(height: BlockHeight?, cause: Throwable) : EnhanceTransactionError("Error while attempting to download a transaction to enhance", height, cause) class EnhanceTxDecryptError(height: BlockHeight?, cause: Throwable) : EnhanceTransactionError("Error while attempting to decrypt and store a transaction to enhance", height, cause) } class MismatchedNetwork(clientNetwork: String?, serverNetwork: String?) : CompactBlockProcessorException( "Incompatible server: this client expects a server using $clientNetwork but it was $serverNetwork! Try updating the client or switching servers." ) class MismatchedBranch(clientBranch: String?, serverBranch: String?, networkName: String?) : CompactBlockProcessorException( "Incompatible server: this client expects a server following consensus branch $clientBranch on $networkName but it was $serverBranch! Try updating the client or switching servers." ) } /** * Exceptions related to the wallet's birthday. */ sealed class BirthdayException(message: String, cause: Throwable? = null) : SdkException(message, cause) { object UninitializedBirthdayException : BirthdayException( "Error the birthday cannot be" + " accessed before it is initialized. Verify that the new, import or open functions" + " have been called on the initializer." ) class MissingBirthdayFilesException(directory: String) : BirthdayException( "Cannot initialize wallet because no birthday files were found in the $directory directory." ) class ExactBirthdayNotFoundException internal constructor(birthday: BlockHeight, nearestMatch: Checkpoint? = null) : BirthdayException( "Unable to find birthday that exactly matches $birthday.${ if (nearestMatch != null) { " An exact match was request but the nearest match found was ${nearestMatch.height}." } else "" }" ) class BirthdayFileNotFoundException(directory: String, height: BlockHeight?) : BirthdayException( "Unable to find birthday file for $height verify that $directory/$height.json exists." ) class MalformattedBirthdayFilesException(directory: String, file: String, cause: Throwable?) : BirthdayException( "Failed to parse file $directory/$file verify that it is formatted as #####.json, " + "where the first portion is an Int representing the height of the tree contained in the file", cause ) } /** * Exceptions thrown by the initializer. */ sealed class InitializerException(message: String, cause: Throwable? = null) : SdkException(message, cause) { class FalseStart(cause: Throwable?) : InitializerException("Failed to initialize accounts due to: $cause", cause) class AlreadyInitializedException(cause: Throwable, dbPath: String) : InitializerException( "Failed to initialize the blocks table" + " because it already exists in $dbPath", cause ) object MissingBirthdayException : InitializerException( "Expected a birthday for this wallet but failed to find one. This usually means that " + "wallet setup did not happen correctly. A workaround might be to interpret the " + "birthday, based on the contents of the wallet data but it is probably better " + "not to mask this error because the root issue should be addressed." ) object MissingViewingKeyException : InitializerException( "Expected a unified viewingKey for this wallet but failed to find one. This usually means" + " that wallet setup happened incorrectly. A workaround might be to derive the" + " unified viewingKey from the seed or seedPhrase, if they exist, but it is probably" + " better not to mask this error because the root issue should be addressed." ) class MissingAddressException(description: String, cause: Throwable? = null) : InitializerException( "Expected a $description address for this wallet but failed to find one. This usually" + " means that wallet setup happened incorrectly. If this problem persists, a" + " workaround might be to go to settings and WIPE the wallet and rescan. Doing so" + " will restore any missing address information. Meanwhile, please report that" + " this happened so that the root issue can be uncovered and corrected." + if (cause != null) "\nCaused by: $cause" else "" ) object DatabasePathException : InitializerException( "Critical failure to locate path for storing databases. Perhaps this device prevents" + " apps from storing data? We cannot initialize the wallet unless we can store" + " data." ) class InvalidBirthdayHeightException(birthday: BlockHeight?, network: ZcashNetwork) : InitializerException( "Invalid birthday height of ${birthday?.value}. The birthday height must be at least the height of" + " Sapling activation on ${network.networkName} (${network.saplingActivationHeight})." ) object MissingDefaultBirthdayException : InitializerException( "The birthday height is missing and it is unclear which value to use as a default." ) } /** * Exceptions thrown while interacting with lightwalletd. */ sealed class LightWalletException(message: String, cause: Throwable? = null) : SdkException(message, cause) { object InsecureConnection : LightWalletException( "Error: attempted to connect to lightwalletd" + " with an insecure connection! Plaintext connections are only allowed when the" + " resource value for 'R.bool.lightwalletd_allow_very_insecure_connections' is true" + " because this choice should be explicit." ) class ConsensusBranchException(sdkBranch: String, lwdBranch: String) : LightWalletException( "Error: the lightwalletd server is using a consensus branch" + " (branch: $lwdBranch) that does not match the transactions being created" + " (branch: $sdkBranch). This probably means the SDK and Server are on two" + " different chains, most likely because of a recent network upgrade (NU). Either" + " update the SDK to match lightwalletd or use a lightwalletd that matches the SDK." ) open class ChangeServerException(message: String, cause: Throwable? = null) : SdkException(message, cause) { class ChainInfoNotMatching(val propertyNames: String, val expectedInfo: Service.LightdInfo, val actualInfo: Service.LightdInfo) : ChangeServerException( "Server change error: the $propertyNames values did not match." ) class StatusException(val status: Status, cause: Throwable? = null) : SdkException(status.toMessage(), cause) { companion object { private fun Status.toMessage(): String { return when (this.code) { UNAVAILABLE -> { "Error: the new server is unavailable. Verify that the host and port are correct. Failed with $this" } else -> "Changing servers failed with status $this" } } } } } } /** * Potentially user-facing exceptions thrown while encoding transactions. */ sealed class TransactionEncoderException(message: String, cause: Throwable? = null) : SdkException(message, cause) { class FetchParamsException(message: String) : TransactionEncoderException("Failed to fetch params due to: $message") object MissingParamsException : TransactionEncoderException( "Cannot send funds due to missing spend or output params and attempting to download them failed." ) class TransactionNotFoundException(transactionId: Long) : TransactionEncoderException( "Unable to find transactionId " + "$transactionId in the repository. This means the wallet created a transaction and then returned a row ID " + "that does not actually exist. This is a scenario where the wallet should have thrown an exception but failed " + "to do so." ) class TransactionNotEncodedException(transactionId: Long) : TransactionEncoderException( "The transaction returned by the wallet," + " with id $transactionId, does not have any raw data. This is a scenario where the wallet should have thrown" + " an exception but failed to do so." ) class IncompleteScanException(lastScannedHeight: BlockHeight) : TransactionEncoderException( "Cannot" + " create spending transaction because scanning is incomplete. We must scan up to the" + " latest height to know which consensus rules to apply. However, the last scanned" + " height was $lastScannedHeight." ) }
83
null
42
51
45f1c473b2531ca47213657c9ef26d25fffeda1d
14,291
zcash-android-wallet-sdk
MIT License
cache-core/src/test/kotlin/im/toss/util/serializer/SerializerTest.kt
toss
228,551,924
false
null
package im.toss.util.serializer import im.toss.test.equalsTo import im.toss.util.data.encoding.GZipCompressionCodec import im.toss.util.data.serializer.EncodingSerializer import im.toss.util.data.serializer.KryoSerializer import org.junit.jupiter.api.Test class SerializerTest { @Test fun serializerName() { EncodingSerializer( KryoSerializer(), GZipCompressionCodec() ).name equalsTo "encoding(kryo-4, [gzip])" } }
1
Kotlin
3
7
006062a4cc9548d57c09c11cbccdf1811de73589
469
cache
Apache License 2.0
app/src/main/java/com/personal/weathering/weather/presenation/forecast/components/DaylightPanel.kt
Avvami
702,061,643
false
{"Kotlin": 348568}
package com.personal.weathering.weather.presenation.forecast.components import androidx.compose.foundation.background 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.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.State import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.personal.weathering.R import com.personal.weathering.core.presentation.PreferencesState import com.personal.weathering.core.util.timeFormat import com.personal.weathering.weather.domain.models.DailyWeatherData @Composable fun DaylightPanel( preferencesState: State<PreferencesState>, dailyWeatherData: DailyWeatherData ) { Column( modifier = Modifier .fillMaxWidth() .clip(MaterialTheme.shapes.extraLarge) .background(MaterialTheme.colorScheme.surfaceContainer) .padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Row( horizontalArrangement = Arrangement.spacedBy(6.dp, Alignment.CenterHorizontally) ) { dailyWeatherData.sunrise?.let { sunrise -> Column( modifier = Modifier.padding(top = 8.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Icon( modifier = Modifier.size(28.dp), painter = painterResource(id = R.drawable.icon_wb_sunny_fill0_wght400), contentDescription = stringResource(id = R.string.sunrise) ) Spacer(modifier = Modifier.height(8.dp)) Text( text = stringResource(id = R.string.sunrise), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurface.copy(.7f) ) Text( text = timeFormat(time = sunrise, use12hour = preferencesState.value.use12hour), style = MaterialTheme.typography.titleMedium ) } } dailyWeatherData.daylightDuration?.let { daylightDuration -> Column( horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = stringResource(id = R.string.daylight_duration), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurface.copy(.7f) ) Text( text = stringResource( id = R.string.hours_minutes, daylightDuration.toHours(), daylightDuration.toMinutesPart() ), style = MaterialTheme.typography.titleMedium ) } } dailyWeatherData.sunset?.let { sunset -> Column( modifier = Modifier.padding(top = 8.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Icon( modifier = Modifier.size(28.dp), painter = painterResource(id = R.drawable.icon_wb_twilight_fill0_wght400), contentDescription = stringResource(id = R.string.sunset) ) Spacer(modifier = Modifier.height(8.dp)) Text( text = stringResource(id = R.string.sunset), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurface.copy(.7f) ) Text( text = timeFormat(time = sunset, use12hour = preferencesState.value.use12hour), style = MaterialTheme.typography.titleMedium ) } } } } }
0
Kotlin
1
2
eb6c7b47d90bde7fb0b35f985b20ea06872de0df
4,769
Weathering
MIT License
src/main/kotlin/com/github/thake/logminer/kafka/connect/SourceConnectorConfig.kt
thake
238,628,890
false
null
package com.github.thake.logminer.kafka.connect import mu.KotlinLogging import org.apache.kafka.common.config.AbstractConfig import org.apache.kafka.common.config.ConfigDef import org.apache.kafka.common.config.ConfigDef.Importance import java.sql.Connection import java.sql.DriverManager import java.sql.SQLException import java.time.Duration import java.time.ZoneId private val logger = KotlinLogging.logger {} sealed class LogMinerSelector data class TableSelector(val owner: String, val tableName: String) : LogMinerSelector() data class SchemaSelector(val owner: String) : LogMinerSelector() enum class LogminerDictionarySource { ONLINE, REDO_LOG } class SourceConnectorConfig( config: ConfigDef?, parsedConfig: Map<String, String> ) : AbstractConfig(config, parsedConfig) { constructor(parsedConfig: Map<String, String>) : this( conf(), parsedConfig ) fun openConnection() : Connection? { val dbUri = "${dbHostName}:${dbPort}/${dbSid}" fun doOpenConnection(): Connection { return DriverManager.getConnection( "jdbc:oracle:thin:@$dbUri", dbUser, dbPassword ).also { logger.info { "Connected to database at $dbUri" } } } var currentAttempt = 0 var connection: Connection? = null while (currentAttempt < dbAttempts && connection == null) { if (currentAttempt > 0) { logger.info { "Waiting ${dbBackoff.toMillis()} ms before next attempt to acquire a connection" } Thread.sleep(dbBackoff.toMillis()) } currentAttempt++ try { connection = doOpenConnection() } catch (e: SQLException) { logger.error(e) { "Couldn't connect to database with url $dbUri. Attempt $currentAttempt." } } } return connection } val dbSid: String get() = getString(DB_SID) val dbHostName: String get() = getString(DB_HOST) val dbPort: Int get() = getInt(DB_PORT) val dbUser: String get() = getString(DB_USERNAME) val dbPassword: String get() = getString(DB_PASSWORD) val dbName: String get() = getString(DB_NAME) val dbZoneId: ZoneId get() = ZoneId.of(getString(DB_TIMEZONE)) val logminerDictionarySource: LogminerDictionarySource get() = LogminerDictionarySource.valueOf(getString(DB_LOGMINER_DICTIONARY)) val monitoredTables: List<String> get() = getString(MONITORED_TABLES).split(",").map { it.trim() } val logMinerSelectors: List<LogMinerSelector> get() = monitoredTables.map { val parts = it.split(".") if (parts.size > 1) { TableSelector(parts[0], parts[1]) } else { SchemaSelector(parts[0]) } } val batchSize: Int get() = getInt(BATCH_SIZE) val dbFetchSize: Int get() = getInt(DB_FETCH_SIZE) ?: batchSize val startScn: Long get() = getLong(START_SCN) ?: 0 val pollInterval: Duration get() = Duration.ofMillis(getLong(POLL_INTERVAL_MS)) val dbBackoff: Duration get() = Duration.ofMillis(getLong(DB_BACKOFF_MS)) val dbAttempts: Int get() = getInt(DB_ATTEMPTS) val isTombstonesOnDelete : Boolean get() = getBoolean(TOMBSTONES_ON_DELETE) companion object { const val DB_NAME = "db.name" const val DB_SID = "db.sid" const val DB_HOST = "db.hostname" const val DB_PORT = "db.port" const val DB_USERNAME = "db.user" const val DB_PASSWORD = "<PASSWORD>" const val DB_ATTEMPTS = "db.attempts" const val DB_BACKOFF_MS = "db.backoff.ms" const val DB_LOGMINER_DICTIONARY = "db.logminer.dictionary" const val DB_TIMEZONE = "db.timezone" const val MONITORED_TABLES = "table.whitelist" const val DB_FETCH_SIZE = "db.fetch.size" const val START_SCN = "start.scn" const val BATCH_SIZE = "batch.size" const val POLL_INTERVAL_MS = "poll.interval.ms" const val TOMBSTONES_ON_DELETE = "tombstones.on.delete" fun conf(): ConfigDef { return ConfigDef() .define( DB_NAME, ConfigDef.Type.STRING, Importance.HIGH, "Logical name of the database. This name will be used as a prefix for the topic. You can choose this name as you like." ) .define( DB_SID, ConfigDef.Type.STRING, Importance.HIGH, "Database SID" ) .define( DB_HOST, ConfigDef.Type.STRING, Importance.HIGH, "Database hostname" ) .define( DB_PORT, ConfigDef.Type.INT, Importance.HIGH, "Database port (usually 1521)" ) .define( DB_USERNAME, ConfigDef.Type.STRING, Importance.HIGH, "Database user" ) .define( DB_PASSWORD, ConfigDef.Type.STRING, Importance.HIGH, "Database password" ) .define( DB_LOGMINER_DICTIONARY, ConfigDef.Type.STRING, LogminerDictionarySource.ONLINE.name, Importance.LOW, "Type of logminer dictionary that should be used. Valid values: " + LogminerDictionarySource.values() .joinToString { it.name } ) .define( DB_TIMEZONE, ConfigDef.Type.STRING, "UTC", Importance.HIGH, "The timezone in which TIMESTAMP columns (without any timezone information) should be interpreted as. Valid values are all values that can be passed to https://docs.oracle.com/javase/8/docs/api/java/time/ZoneId.html#of-java.lang.String-" ) .define( MONITORED_TABLES, ConfigDef.Type.STRING, "", Importance.HIGH, "Tables that should be monitored, separated by ','. Tables have to be specified with schema. Table names are case-sensitive (e.g. if your table name is an unquoted identifier, you'll need to specify it in all caps). You can also just " + "specify a schema to indicate that all tables within that schema should be monitored. Examples: 'MY_USER.TABLE, OTHER_SCHEMA'." ) .define( TOMBSTONES_ON_DELETE, ConfigDef.Type.BOOLEAN, true, Importance.HIGH, "If set to false, no tombstone records will be emitted after a delete operation." ) .define( BATCH_SIZE, ConfigDef.Type.INT, 1000, Importance.HIGH, "Batch size of rows that should be fetched in one batch" ) .define( DB_FETCH_SIZE, ConfigDef.Type.INT, null, Importance.MEDIUM, "JDBC result set prefetch size. If not set, it will be defaulted to batch.size. The fetch" + " should not be smaller than the batch size." ) .define( START_SCN, ConfigDef.Type.LONG, 0L, Importance.HIGH, "Start SCN, if set to 0 an initial intake from the tables will be performed." ) .define( DB_ATTEMPTS, ConfigDef.Type.INT, 3, Importance.LOW, "Maximum number of attempts to retrieve a valid JDBC connection." ) .define( DB_BACKOFF_MS, ConfigDef.Type.LONG, 10000L, Importance.LOW, "Backoff time in milliseconds between connection attempts." ) .define( POLL_INTERVAL_MS, ConfigDef.Type.LONG, 2000L, Importance.LOW, "Positive integer value that specifies the number of milliseconds the connector should wait after a polling attempt didn't retrieve any results." ) } } } fun main() { println(SourceConnectorConfig.conf().toEnrichedRst()) }
17
Kotlin
20
30
82373d8e10c4999457fc2646b868e20eb0c5abeb
9,165
logminer-kafka-connect
Apache License 2.0
app/src/main/java/com/rs/codingexercisegyg/network/GYGReviewsApi.kt
ranjeetsinha13
238,456,800
false
null
package com.rs.codingexercisegyg.network import com.rs.codingexercisegyg.network.data.Reviews import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query interface GYGReviewsApi { @GET("/activities/{activityID}/reviews") suspend fun getReviews( @Path("activityID") activityID: Int = 23776, @Query("limit") limit: Int = 50, @Query("offset") offset: Int ): Reviews }
0
Kotlin
0
0
f39314bb2962648ade3530e996f4ad05c5749f3b
424
CodingExerciseGYG
MIT License
test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAssertAImpl.kt
tuProlog
230,784,338
false
null
package it.unibo.tuprolog.solve import it.unibo.tuprolog.dsl.theory.logicProgramming import it.unibo.tuprolog.solve.exception.error.DomainError import it.unibo.tuprolog.solve.exception.error.InstantiationError import it.unibo.tuprolog.solve.exception.error.PermissionError import it.unibo.tuprolog.solve.exception.error.TypeError internal class TestAssertAImpl(private val solverFactory: SolverFactory) : TestAssertA { override fun testAssertAClause() { logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() val query = asserta(("bar"("X") `if` "X")) and clause("bar"("X"), "B") val solutions = solver.solve(query, mediumDuration).toList() assertSolutionEquals( listOf(query.yes("B" to call("X"))), solutions, ) } } override fun testAssertAAny() { logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() val query = asserta(`_`) val solutions = solver.solve(query, mediumDuration).toList() assertSolutionEquals( listOf( query.halt( InstantiationError.forArgument( DummyInstances.executionContext, Signature("asserta", 1), `_`, index = 0, ), ), ), solutions, ) } } override fun testAssertANumber() { logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() val query = asserta(4) val solutions = solver.solve(query, mediumDuration).toList() assertSolutionEquals( listOf( query.halt( TypeError.forArgument( DummyInstances.executionContext, Signature("asserta", 1), TypeError.Expected.CALLABLE, numOf(4), index = 0, ), ), ), solutions, ) } } override fun testAssertAFooNumber() { logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() val query = asserta("foo" `if` 4) val solutions = solver.solve(query, mediumDuration).toList() assertSolutionEquals( listOf( query.halt( DomainError.forArgument( DummyInstances.executionContext, Signature("asserta", 1), DomainError.Expected.CLAUSE, ("foo" `if` 4), index = 0, ), ), ), solutions, ) } } override fun testAssertAAtomTrue() { logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() val query = asserta(atom(`_`) `if` true) val solutions = solver.solve(query, mediumDuration).toList() assertSolutionEquals( listOf( query.halt( PermissionError.of( DummyInstances.executionContext, Signature("asserta", 1), PermissionError.Operation.MODIFY, PermissionError.Permission.PRIVATE_PROCEDURE, "atom" / 1, ), ), ), solutions, ) } } }
92
null
8
93
3223ffc302e5da0efe2b254045fa1b6a1a122519
3,905
2p-kt
Apache License 2.0
app/src/main/java/com/da_chelimo/whisper/chats/presentation/actual_chat/screens/ActualChatViewModel.kt
DaChelimo
809,502,044
false
{"Kotlin": 381270}
package com.da_chelimo.whisper.chats.presentation.actual_chat.screens import android.content.Context import androidx.compose.runtime.mutableStateListOf import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.input.TextFieldValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.da_chelimo.whisper.chats.domain.Chat import com.da_chelimo.whisper.chats.domain.Message import com.da_chelimo.whisper.chats.domain.MessageType import com.da_chelimo.whisper.chats.presentation.utils.toActualChatSeparatorTime import com.da_chelimo.whisper.chats.repo.audio_messages.player.AndroidAudioPlayer import com.da_chelimo.whisper.chats.repo.audio_messages.player.AudioPlayer import com.da_chelimo.whisper.chats.repo.audio_messages.player.PlayerState import com.da_chelimo.whisper.chats.repo.audio_messages.recorder.AndroidAudioRecorder import com.da_chelimo.whisper.chats.repo.audio_messages.recorder.AudioRecorder import com.da_chelimo.whisper.chats.repo.audio_messages.recorder.RecorderState import com.da_chelimo.whisper.chats.repo.chats.ChatRepo import com.da_chelimo.whisper.chats.repo.chats.ChatRepoImpl import com.da_chelimo.whisper.chats.repo.contacts.ContactsRepo import com.da_chelimo.whisper.chats.repo.messages.MessagesRepo import com.da_chelimo.whisper.chats.repo.messages.MessagesRepoImpl import com.da_chelimo.whisper.core.domain.MiniUser import com.da_chelimo.whisper.core.domain.toMiniUser import com.da_chelimo.whisper.core.repo.user.UserRepo import com.da_chelimo.whisper.core.repo.user.UserRepoImpl import com.da_chelimo.whisper.core.utils.formatDurationInMillis import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import timber.log.Timber class ActualChatViewModel( private val userRepo: UserRepo = UserRepoImpl(), private val chatRepo: ChatRepo = ChatRepoImpl(userRepo), private val messagesRepo: MessagesRepo = MessagesRepoImpl(chatRepo), private val contactsRepo: ContactsRepo, private val audioRecorder: AudioRecorder = AndroidAudioRecorder(), private val audioPlayer: AudioPlayer = AndroidAudioPlayer() ) : ViewModel() { private val _textMessage = MutableStateFlow(TextFieldValue("")) val textMessage: StateFlow<TextFieldValue> = _textMessage var chatID: String? = null private set val chat = MutableStateFlow<Chat?>(null) val messages = mutableStateListOf<Message>() val mapOfMessageIDAndDateInString = mutableMapOf<String, String>() val audioBeingPlayed = audioPlayer.audioBeingPlayed val playerState = audioPlayer.playerState val playerTimeLeftInMillis = audioPlayer.timeLeftInMillis val recorderState = audioRecorder.recorderState private val recordingDurationInMillis = audioRecorder.durationInMillis val formattedRecordingDuration = recordingDurationInMillis.map { it.formatDurationInMillis() } private val _otherUser = MutableStateFlow<MiniUser?>(null) val otherUser: StateFlow<MiniUser?> = _otherUser private val _openMediaPicker = MutableStateFlow(false) val openMediaPicker: StateFlow<Boolean> = _openMediaPicker private val _isEditing = MutableStateFlow<String?>(null) val isEditing: StateFlow<String?> = _isEditing val doesOtherUserAccountExist = MutableStateFlow(true) suspend fun loadChat(chatID: String?) { if (chatID != null) { chat.value = chatRepo.getChatFromChatID(chatID) Timber.d("chat.value is ${chat.value}") Timber.d("chat.value?.isDisabled is ${chat.value?.isDisabled}") } } /** * Gets the other user's profile either using the chatID (existing chat) or newContact (new chat) */ suspend fun loadOtherUser(chatID: String?, newContactUID: String?) { Timber.d("chatID in loadOtherUser is $chatID") _otherUser.value = if (chatID == null) { contactsRepo.getContactFromUID(newContactUID!!)?.toMiniUser() } else { val chat = chat.value if (chat?.firstMiniUser?.uid == Firebase.auth.uid) chat?.secondMiniUser else chat?.firstMiniUser } Timber.d("otherUser.value is ${otherUser.value}") val otherUserID = otherUser.value?.uid doesOtherUserAccountExist.value = otherUserID?.let { userRepo.getUserFromUID(it) } != null } /** * Fetch chats from a given chatID * * @param paramChatID ~ if chatID == null, it means this is a new conversation being created. * Therefore, we need to generate a chatID and update it on the personalized chats in Fire DB * if chatID != null, this is an existing conversation, so you can fetch the messages. */ fun fetchChats(paramChatID: String?) = viewModelScope.launch { chatID = paramChatID if (chatID != null) { Timber.d("chatID is $chatID") messagesRepo.getMessagesFromChatID(chatID!!) .onEach { // TODO: Improve this coz this is TERRIBLEEEEEE :) Timber.d("chatRepo.getMessagesFromChatID(chatID!!).collect is $it") it.reversed().forEach { message -> val timeTitle = message.timeSent.toActualChatSeparatorTime() ?: return@forEach val isDateInMap = mapOfMessageIDAndDateInString.values.contains(timeTitle) if (!isDateInMap) mapOfMessageIDAndDateInString[message.messageID] = timeTitle } messages.clear() messages.addAll(it) } .launchIn(viewModelScope) /** * If chats have been opened by the user who had unread messages, * reset the unreadMessagesCount to 0 */ chatRepo.resetUnreadMessagesCount(chatID!!) } } private suspend fun createConversation() { Timber.d("otherUser.value in createConversation() is ${otherUser.value}") otherUser.value?.let { chatID = chatRepo.createConversation(it) fetchChats(chatID) } } fun sendOrEditMessage() = viewModelScope.launch { if (textMessage.value.text.isBlank()) // You can't send an empty message return@launch if (isEditing.value != null) editMessage() else sendMessage() } private suspend fun sendMessage() { if (chatID == null) // If it's a new person, create a new chat createConversation() if (chat.value?.isDisabled == true) { // Chat disabled; do not send & clear message bar _textMessage.value = TextFieldValue("") } else { val message = textMessage.value.text _textMessage.value = TextFieldValue("") messagesRepo.sendMessage(chatID!!, MessageType.Text(message)) } } fun launchMessageEditing(messageID: String, oldMessage: String) { _isEditing.value = messageID updateComposeMessage( TextFieldValue( oldMessage, selection = TextRange(index = oldMessage.length) ) ) } private suspend fun editMessage() { val editedMessageID = isEditing.value!! val editedMessage = textMessage.value.text _isEditing.value = null _textMessage.value = TextFieldValue("") messagesRepo.editMessage( chatID = chatID!!, messageID = editedMessageID, newMessage = editedMessage ) } fun unsendMessage(messageID: String) = viewModelScope.launch { messagesRepo.unsendMessage(chatID!!, messageID) } fun updateComposeMessage(newMessage: TextFieldValue) { _textMessage.value = newMessage } fun updateOpenMediaPicker(shouldOpen: Boolean) { _openMediaPicker.value = shouldOpen } fun resetUnreadMessagesCountOnChatExit() = viewModelScope.launch { Timber.d("resetUnreadMessagesCountOnChatExit with chatID as $chatID") chatID?.let { chatRepo.resetUnreadMessagesCount(it) } } /** * Stop any audio recording that may be playing * Start recording */ fun startRecording(context: Context) { audioPlayer.stopAudio() audioRecorder.startRecording(context) } private fun resumeRecording() { audioRecorder.resumeRecording() } private fun pauseRecording() { audioRecorder.pauseRecording() } fun cancelRecording() { audioRecorder.cancelRecording() } fun pauseOrResumeRecording() { if (recorderState.value is RecorderState.Paused) resumeRecording() else pauseRecording() } fun sendRecording() = viewModelScope.launch { if (chatID == null) // If it's a new person, create a new chat createConversation() val audioFileUri = audioRecorder.endRecording() messagesRepo.sendAudioMessage( chatID = chatID!!, audioUri = audioFileUri?.toString() ?: return@launch, duration = recordingDurationInMillis.value ) } fun playOrPauseAudio(context: Context, audioUrl: String) = viewModelScope.launch { /** * If the urls are different, it means the user is trying to play another vn * { Do not resume; instead start playing it a fresh } */ if (audioUrl != audioPlayer.audioBeingPlayed.value) audioPlayer.playAudio(context, audioUrl) else // Otherwise, handle it normally when (playerState.value) { PlayerState.None -> audioPlayer.playAudio(context, audioUrl) PlayerState.Paused -> audioPlayer.resumeAudio() PlayerState.Ongoing -> audioPlayer.pauseAudio() } } override fun onCleared() { super.onCleared() audioRecorder.cancelRecording() audioPlayer.stopAudio() } }
0
Kotlin
0
1
86c51d4ac324b91dc62d9a2cce1b350d9c566edc
10,389
Whisper
MIT License
kotlinx-coroutines-test/native/src/TestBuilders.kt
hltj
151,721,407
false
null
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.test import kotlinx.coroutines.* @Suppress("ACTUAL_WITHOUT_EXPECT") public actual typealias TestResult = Unit internal actual fun createTestResult(testProcedure: suspend CoroutineScope.() -> Unit) { runBlocking { testProcedure() } }
295
null
1827
255
9565dc2d1bc33056dd4321f9f74da085e6c0f39e
389
kotlinx.coroutines-cn
Apache License 2.0
app/src/main/java/com/tradingview/lightweightcharts/example/app/data/static_data.kt
grietzercs
347,772,208
true
{"Kotlin": 112058, "JavaScript": 21903, "HTML": 142}
package com.tradingview.lightweightcharts.example.app.data import com.tradingview.lightweightcharts.api.options.enums.PriceAxisPosition import com.tradingview.lightweightcharts.api.options.models.* import com.tradingview.lightweightcharts.api.series.common.SeriesData import com.tradingview.lightweightcharts.api.series.enums.LineStyle import com.tradingview.lightweightcharts.api.series.enums.LineWidth import com.tradingview.lightweightcharts.api.series.enums.SeriesMarkerPosition import com.tradingview.lightweightcharts.api.series.enums.SeriesMarkerShape import com.tradingview.lightweightcharts.api.series.models.* @Suppress("LongMethod") fun listBarSeriesData(): MutableList<SeriesData> { return mutableListOf( BarData( time = Time.StringTime("2019-07-19"), open = 141.77f, high = 170.39f, low = 120.25f, close = 145.72f ), BarData( time = Time.StringTime("2019-07-20"), open = 145.72f, high = 147.99f, low = 100.11f, close = 108.19f ), BarData( time = Time.StringTime("2019-07-21"), open = 108.19f, high = 118.43f, low = 74.22f, close = 75.16f ), BarData( time = Time.StringTime("2019-07-22"), open = 75.16f, high = 82.84f, low = 36.16f, close = 45.72f ), BarData( time = Time.StringTime("2019-07-23"), open = 45.12f, high = 53.90f, low = 45.12f, close = 48.09f ), BarData( time = Time.StringTime("2019-07-24"), open = 60.71f, high = 60.71f, low = 53.39f, close = 59.29f ), BarData( time = Time.StringTime("2019-07-25"), open = 68.26f, high = 68.26f, low = 59.04f, close = 60.50f ), BarData( time = Time.StringTime("2019-07-26"), open = 67.71f, high = 105.85f, low = 66.67f, close = 91.04f ), BarData( time = Time.StringTime("2019-07-27"), open = 91.04f, high = 121.40f, low = 82.70f, close = 111.40f ), BarData( time = Time.StringTime("2019-07-28"), open = 111.51f, high = 142.83f, low = 103.34f, close = 131.25f ), BarData( time = Time.StringTime("2019-07-29"), open = 131.33f, high = 151.17f, low = 77.68f, close = 96.43f ), BarData( time = Time.StringTime("2019-07-30"), open = 106.33f, high = 110.20f, low = 90.39f, close = 98.10f ), BarData( time = Time.StringTime("2019-07-31"), open = 109.87f, high = 114.69f, low = 85.66f, close = 111.26f ) ) } fun listAreaSeriesData(): MutableList<SeriesData> { return mutableListOf( LineData(Time.Utc(1560211200), 40.01f), LineData(Time.Utc(1560297600), 52.38f), LineData(Time.Utc(1560384000), 36.30f), LineData(Time.Utc(1560470400), 34.48f), LineData(Time.Utc(1560556800), 40.06f), LineData(Time.Utc(1560643200), 56.94f), LineData(Time.Utc(1560729600), 41.50f), LineData(Time.Utc(1560816000), 34.82f) ) } fun listHistogramSeriesData(): MutableList<SeriesData> { return mutableListOf( HistogramData(Time.BusinessDay(2019, 6, 11), 40.01f), HistogramData(Time.BusinessDay(2019, 6, 12), 52.38f), HistogramData(Time.BusinessDay(2019, 6, 13), 36.30f), HistogramData(Time.BusinessDay(2019, 6, 14), 34.48f), WhitespaceData(Time.BusinessDay(2019, 6, 15)), WhitespaceData(Time.BusinessDay(2019, 6, 16)), HistogramData(Time.BusinessDay(2019, 6, 17), 41.50f), HistogramData(Time.BusinessDay(2019, 6, 18), 34.82f) ) } @Suppress("LongMethod") fun listCandlestickSeriesData(): MutableList<SeriesData> { return mutableListOf( BarData( time = Time.StringTime("2019-12-15"), open = 145.72f, high = 147.99f, low = 100.11f, close = 108.19f ), BarData( time = Time.StringTime("2019-12-16"), open = 108.19f, high = 118.43f, low = 74.22f, close = 75.16f ), BarData( time = Time.StringTime("2019-12-17"), open = 75.16f, high = 82.84f, low = 36.16f, close = 45.72f ), BarData( time = Time.StringTime("2019-12-18"), open = 60.71f, high = 60.71f, low = 53.39f, close = 59.29f ), BarData( time = Time.StringTime("2019-12-19"), open = 68.26f, high = 68.26f, low = 59.04f, close = 60.50f ), BarData( time = Time.StringTime("2019-12-20"), open = 91.04f, high = 121.40f, low = 82.70f, close = 111.40f ), BarData( time = Time.StringTime("2019-12-21"), open = 131.33f, high = 151.17f, low = 77.68f, close = 96.43f ), BarData( time = Time.StringTime("2019-12-22"), open = 109.87f, high = 114.69f, low = 85.66f, close = 111.26f ) ) } fun priceScaleOptions() = PriceScaleOptions(autoScale = false, position = PriceAxisPosition.LEFT) fun timeScaleOptions() = TimeScaleOptions(visible = false) fun priceLineOptionsWith(price: Float): PriceLineOptions { return PriceLineOptions( price = price, color = 0xFF016309.toInt(), lineWidth = LineWidth.TWO, lineStyle = LineStyle.DOTTED ) } fun priceLineOptions(): PriceLineOptions { return PriceLineOptions( price = 140f, color = 0xFF0F2FFF.toInt(), lineWidth = LineWidth.ONE, lineStyle = LineStyle.SOLID ) } fun singleLineData() = LineData(Time.StringTime("2019-04-11"), 90.01f) fun listSeriesMarker(): MutableList<SeriesMarker> { return mutableListOf( SeriesMarker( time = Time.StringTime("2019-04-11"), position = SeriesMarkerPosition.ABOVE_BAR, shape = SeriesMarkerShape.SQUARE, color = 0xFFFF1115.toInt(), id = "1" ), SeriesMarker( time = Time.StringTime("2019-04-18"), position = SeriesMarkerPosition.IN_BAR, shape = SeriesMarkerShape.CIRCLE, color = 0xFFFF1115.toInt(), id = "2" ), SeriesMarker( time = Time.StringTime("2019-04-13"), position = SeriesMarkerPosition.BELOW_BAR, shape = SeriesMarkerShape.ARROW_DOWN, color = 0xFFFF1115.toInt(), id = "3" ) ) } fun listLineSeriesData(): MutableList<SeriesData> { return mutableListOf( LineData(Time.StringTime("2019-04-11"), 80.01f), LineData(Time.StringTime("2019-04-12"), 92.38f), LineData(Time.StringTime("2019-04-13"), 76.30f), LineData(Time.StringTime("2019-04-14"), 74.48f), LineData(Time.StringTime("2019-04-15"), 80.06f), LineData(Time.StringTime("2019-04-16"), 96.94f), LineData(Time.StringTime("2019-04-17"), 81.50f), LineData(Time.StringTime("2019-04-18"), 74.82f) ) }
0
null
0
0
ec11bbc916385fa8b0291566db72db9bb41370da
7,847
lightweight-charts-android
Apache License 2.0
wandroid/src/main/java/com/cgy/wandroid/mvp/contract/TodoContract.kt
cgy0905
208,779,222
false
null
package com.cgy.wandroid.mvp.contract import com.cgy.wandroid.mvp.model.entity.ApiPagerResponse import com.cgy.wandroid.mvp.model.entity.ApiResponse import com.cgy.wandroid.mvp.model.entity.TodoResponse import com.jess.arms.mvp.IModel import com.jess.arms.mvp.IView import io.reactivex.Observable interface TodoContract { //对于经常使用的关于UI的方法可以定义到IView中,如显示隐藏进度条,和显示文字消息 interface View : IView { fun requestDataSuccess(articles : ApiPagerResponse<MutableList<TodoResponse>>) fun requestDataFailed(errorMsg : String) fun updateTodoDataSuccess(position : Int) fun deleteTodoDataSuccess(position: Int) fun updateTodoDataFailed(errorMsg: String) } //Model层定义接口,外部只需关心Model返回的数据,无需关心内部细节,即是否使用缓存 interface Model : IModel { fun getTodoData(pageNo : Int) : Observable<ApiResponse<ApiPagerResponse<MutableList<TodoResponse>>>> fun updateTodoData(id : Int, status : Int) : Observable<ApiResponse<Any>> fun deleteTodoData(id: Int) : Observable<ApiResponse<Any>> } }
0
Kotlin
0
0
59ea8bd93e3718ebfed8e9a4400a626a671a3336
1,045
WanAndroid
Apache License 2.0
app/src/test/java/uk/nhs/nhsx/covid19/android/app/network/TrafficLengthObfuscationInterceptorTest.kt
nhsx-mirror
289,296,773
true
{"Kotlin": 2761696, "Shell": 1098, "Ruby": 847, "Batchfile": 197}
package uk.nhs.nhsx.covid19.android.app.network import io.mockk.every import io.mockk.mockk import io.mockk.slot import io.mockk.verify import io.mockk.verifyOrder import okhttp3.Interceptor import okhttp3.Request import okhttp3.RequestBody import okhttp3.Response import org.junit.Before import org.junit.Test import uk.nhs.nhsx.covid19.android.app.util.Base64Encoder import java.security.SecureRandom import java.util.Base64 import kotlin.test.assertEquals class TrafficLengthObfuscationInterceptorTest { private val mockRandom = mockk<SecureRandom>() private val mockBase64Encoder = mockk<Base64Encoder>() private val testSubject = TrafficLengthObfuscationInterceptor(mockRandom, mockBase64Encoder) private val mockChain = mockk<Interceptor.Chain>(relaxed = true) private val mockRequest = mockk<Request>(relaxed = true) private val mockResponse = mockk<Response>(relaxed = true) private val mockUpdatedRequest = mockk<Request>(relaxed = true) private val mockRequestBuilder = mockk<Request.Builder>(relaxed = true) private val mockBody = mockk<RequestBody>() private val headerOneSlot = slot<String>() private val headerTwoSlot = slot<String>() @Before fun setUp() { every { mockChain.request() } returns mockRequest every { mockChain.proceed(mockUpdatedRequest) } returns mockResponse every { mockRandom.nextInt(any()) } returns 500 every { mockRequest.newBuilder() } returns mockRequestBuilder every { mockRequest.body } returns mockBody every { mockRequestBuilder.addHeader(any(), any()) } returns mockRequestBuilder every { mockRequestBuilder.build() } returns mockUpdatedRequest val byteSlot = slot<ByteArray>() every { mockRandom.nextBytes(capture(byteSlot)) } answers { byteSlot.captured.fill('a'.toByte()) } val encoderSlot = slot<ByteArray>() every { mockBase64Encoder.encodeUrl(capture(encoderSlot)) } answers { Base64.getEncoder().encodeToString(encoderSlot.captured) } } @Test fun `generates multiple headers`() { every { mockBody.contentLength() } returns 600 val response = testSubject.intercept(mockChain) assertEquals(mockResponse, response) verifyOrder { mockRequestBuilder.addHeader("X-Randomised-1", capture(headerOneSlot)) mockRequestBuilder.addHeader("X-Randomised-2", capture(headerTwoSlot)) mockRequestBuilder.build() mockChain.proceed(mockUpdatedRequest) } assertEquals(2000, headerOneSlot.captured.length) assertEquals(1900, headerTwoSlot.captured.length) } @Test fun `generates one header`() { every { mockBody.contentLength() } returns 2500 val response = testSubject.intercept(mockChain) assertEquals(mockResponse, response) verifyOrder { mockRequestBuilder.addHeader("X-Randomised-1", capture(headerOneSlot)) mockRequestBuilder.build() mockChain.proceed(mockUpdatedRequest) } assertEquals(2000, headerOneSlot.captured.length) } @Test fun `generates no header when body is larger than target`() { every { mockBody.contentLength() } returns 5500 val response = testSubject.intercept(mockChain) assertEquals(mockResponse, response) verify(exactly = 0) { mockRequestBuilder.addHeader(any(), any()) } } @Test fun `generates two headers when body is empty`() { every { mockBody.contentLength() } returns 0 val response = testSubject.intercept(mockChain) assertEquals(mockResponse, response) verifyOrder { mockRequestBuilder.addHeader("X-Randomised-1", capture(headerOneSlot)) mockRequestBuilder.addHeader("X-Randomised-2", capture(headerTwoSlot)) mockRequestBuilder.build() mockChain.proceed(mockUpdatedRequest) } assertEquals(2000, headerOneSlot.captured.length) assertEquals(2000, headerTwoSlot.captured.length) } }
0
Kotlin
0
0
296c9decde1b5ed904b760ff77b05afc51f24281
4,159
covid-19-app-android-ag-public
MIT License
app/src/main/kotlin/day09/Day09.kt
henningBunk
432,843,259
false
null
package day09 import common.InputRepo import common.readSessionCookie import common.solve fun main(args: Array<String>) { val day = 9 val input = InputRepo(args.readSessionCookie()).get(day = day) solve(day, input, ::solveDay09Part1, ::solveDay09Part2) } fun solveDay09Part1(input: List<String>): Int { TODO() } fun solveDay09Part2(input: List<String>): Int { TODO() }
0
Kotlin
0
2
c55fa51954186d937f4776639564d314f92d7a5b
394
advent-of-code-kotlin-template
Apache License 2.0
klock/src/commonMain/kotlin/com/soywiz/klock/KlockLocaleContext.kt
korlibs
108,193,127
false
null
package korlibs.time data class KlockLocaleContext(val gender: KlockLocaleGender = KlockLocaleGender.Neuter) { companion object { val Default = KlockLocaleContext() } } enum class KlockLocaleGender { Neuter, Masculine, }
444
null
52
679
9bbef7aca8018d7b64d971a777d03b9bac07686e
249
klock
Creative Commons Zero v1.0 Universal
core/src/main/java/app/allever/android/lib/core/function/network/response/NetResponse.kt
devallever
446,030,743
false
null
package app.allever.android.lib.core.function.network.response import app.allever.android.lib.core.function.network.HttpConfig abstract class NetResponse<DATA> { var data: DATA? = null abstract fun getCode(): Int abstract fun getMsg(): String abstract fun setData(code: Int, msg: String, data: DATA?) /** * 只能判断基础成功,某些情况下不是successCode, 也要处理相应的业务 */ fun success(): Boolean = getCode() == HttpConfig.successCode // abstract fun <T : NetResponse<DATA>> generateResponse(code: Int, msg: String, data: DATA?): T }
1
null
8
52
b5ec21078c8a6f509822c763fc90d6106b64bde3
551
AndroidBaseLibs
Apache License 2.0
core/network/src/test/java/com/nyinyihtunlwin/network/datasource/SurveyDataSourceImplTest.kt
nyinyihtunlwin-codigo
802,104,160
false
{"Kotlin": 149133}
package com.nyinyihtunlwin.network.datasource import com.nyinyihtunlwin.data.datasource.remote.SurveyDataSource import com.nyinyihtunlwin.data.model.response.SurveyResponse import com.nyinyihtunlwin.network.service.SurveyService import io.kotest.matchers.shouldBe import io.mockk.coEvery import io.mockk.mockk import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Test class SurveyDataSourceImplTest { private lateinit var surveyService: SurveyService private lateinit var surveyDataSource: SurveyDataSource @Before fun setUp() { surveyService = mockk(relaxed = true) surveyDataSource = SurveyDataSourceImpl(surveyService) } @Test fun `return survey data when getSurveyList success`() = runTest { val surveyResponse = listOf( SurveyResponse( id = "1", title = "Title", surveyType = "Restaurant", description = "This is description.", coverImageUrl = "www.google.com", isActive = true, activeAt = "2017-01-20T10:08:42.512Z", createdAt = "2017-01-20T10:08:42.512Z", inactiveAt = "2018-01-20T10:08:42.512Z", thankEmailAboveThreshold = "", thankEmailBelowThreshold = "" ) ) val survey = SurveyResponse( id = "1", title = "Title", surveyType = "Restaurant", description = "This is description.", coverImageUrl = "www.google.com", isActive = true, activeAt = "2017-01-20T10:08:42.512Z", createdAt = "2017-01-20T10:08:42.512Z", inactiveAt = "2018-01-20T10:08:42.512Z", thankEmailAboveThreshold = "", thankEmailBelowThreshold = "" ) coEvery { surveyService.getSurveyList() } returns surveyResponse surveyDataSource.getSurveyList(pageNumber = 1, pageSize = 5).collectLatest { it.first() shouldBe survey } } @Test fun `return emptyList when getSurveyList is empty`() = runTest { val response = emptyList<SurveyResponse>() coEvery { surveyService.getSurveyList() } returns emptyList() surveyDataSource.getSurveyList(pageNumber = 1, pageSize = 5).collectLatest { it shouldBe emptyList() } } @Test fun `return exception when getSurveyList fails`() = runTest { val exception = Exception() coEvery { surveyService.getSurveyList() } throws exception surveyDataSource.getSurveyList(pageNumber = 1, pageSize = 5).catch { it shouldBe exception }.collect() } @Test fun `return survey when getSurveyDetails success`() = runTest { val surveyResponse = SurveyResponse( id = "123456", title = "Title", surveyType = "Restaurant", description = "This is description.", coverImageUrl = "www.google.com", isActive = true, activeAt = "2017-01-20T10:08:42.512Z", createdAt = "2017-01-20T10:08:42.512Z", inactiveAt = "2018-01-20T10:08:42.512Z", thankEmailAboveThreshold = "", thankEmailBelowThreshold = "" ) val survey = SurveyResponse( id = "123456", title = "Title", surveyType = "Restaurant", description = "This is description.", coverImageUrl = "www.google.com", isActive = true, activeAt = "2017-01-20T10:08:42.512Z", createdAt = "2017-01-20T10:08:42.512Z", inactiveAt = "2018-01-20T10:08:42.512Z", thankEmailAboveThreshold = "", thankEmailBelowThreshold = "" ) coEvery { surveyService.getSurveyDetails("1") } returns surveyResponse surveyDataSource.getSurveyDetails("1").collectLatest { it shouldBe survey } } @Test fun `return exception when getSurveyDetails fails`() = runTest { val exception = Exception() coEvery { surveyService.getSurveyDetails("1") } throws exception surveyDataSource.getSurveyDetails("1").catch { it shouldBe exception }.collect() } }
1
Kotlin
0
0
afadf7187c23f4abee41e9ff16c5d0544af4b996
4,542
nimble-survey
Apache License 2.0
idea/testData/quickfix/typeAddition/afterPublicFunWithoutReturnTypeCaretOnParameter.kt
udalov
10,645,710
false
null
// "Specify return type explicitly" "true" package a class A() { public fun foo(): String<caret> = "a" }
0
null
1
6
3958b4a71d8f9a366d8b516c4c698aae80ecfe57
109
kotlin-objc-diploma
Apache License 2.0
app/src/main/java/com/cyb3rko/logviewerforopenhab/App.kt
cyb3rko
260,164,275
false
{"Kotlin": 62766, "HTML": 10580}
package com.cyb3rko.logviewerforopenhab import android.app.ActivityManager import android.app.Application import android.content.Context import android.os.Build import android.os.Process import android.webkit.WebView import androidx.appcompat.app.AppCompatDelegate class App: Application() { override fun onCreate() { super.onCreate() val mySPR = getSharedPreferences(SHARED_PREFERENCE, MODE_PRIVATE) AppCompatDelegate.setDefaultNightMode( mySPR.getString( NIGHTMODE, AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM.toString() )!!.toInt() ) setWebViewDataDirectorySuffix() } private fun setWebViewDataDirectorySuffix() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { val processName = getProcessName(this) if (processName != "com.cyb3rko.logviewerforopenhab" && processName != null) { WebView.setDataDirectorySuffix(processName) } } } private fun getProcessName(context: Context?): String? { if (context == null) return null val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager for (processInfo in manager.runningAppProcesses) { if (processInfo.pid == Process.myPid()) { return processInfo.processName } } return null } }
0
Kotlin
0
7
1f46261fc9148cbcbf5e0355a6af70f6436bb423
1,430
logviewer-for-openhab-app
Apache License 2.0
katarina-core/src/main/kotlin/com/hubtwork/riot/dto/api/v4/league/MiniSeriesDTO.kt
muscleJoah
339,934,054
false
null
package com.hubtwork.katarinaapi.dto.riotapi.v4.league /** * get summoner LeagueEntry DATA by Encrypted Summoner ID * * > 승급전 정보 * * response about "https://kr.api.riotgames.com/lol/league/v4/entries/by-summoner/{Encrypted Summoner Id}" */ data class MiniSeriesDTO( var progress: String, // 현재 승급전 진행상황 joined String ( Y: 승리, L : 패배, N: 남은 게임 ) var target: Int, // 다음 승급전 라운드 var wins: Int, // 승리 횟수 var loses: Int // 패배 횟수 )
0
Kotlin
0
0
42ac132e48c3743eb3cbafa170c614bbdef63dc3
506
KatarinaDataCrawling
MIT License
app/src/main/java/com/omk/MainScreen/ui/components/Card.kt
Omarmasudkalam
581,336,636
false
{"Kotlin": 116898}
package com.omk.MainScreen.ui.components import androidx.compose.foundation.BorderStroke import androidx.compose.material.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.omk.MainScreen.ui.theme.AppTheme @Composable fun Card( modifier: Modifier = Modifier, shape: Shape = MaterialTheme.shapes.medium, color: Color = AppTheme.colors.uiBackground, contentColor: Color = AppTheme.colors.textPrimary, border: BorderStroke? = null, elevation: Dp = 1.dp, content: @Composable () -> Unit ) { Surface( modifier = modifier, shape = shape, color = color, contentColor = contentColor, elevation = elevation, border = border, content = content ) }
0
Kotlin
0
0
317ba76eebfdbd9737a73e4eaec4935ad72f8def
907
MovieApp
Apache License 2.0
ktor-features/ktor-locations/src/org/jetbrains/ktor/locations/OAuth.kt
hallefy
94,839,121
false
null
package org.jetbrains.ktor.locations import org.jetbrains.ktor.application.* import org.jetbrains.ktor.auth.* import org.jetbrains.ktor.client.* import org.jetbrains.ktor.features.* import java.util.concurrent.* import kotlin.reflect.* inline fun <reified T: Any> Authentication.Pipeline.oauthAtLocation(client: HttpClient, exec: ExecutorService, noinline providerLookup: ApplicationCall.(T) -> OAuthServerSettings?, noinline urlProvider: ApplicationCall.(T, OAuthServerSettings) -> String) { oauthWithType(T::class, client, exec, providerLookup, urlProvider) } fun <T: Any> Authentication.Pipeline.oauthWithType(type: KClass<T>, client: HttpClient, exec: ExecutorService, providerLookup: ApplicationCall.(T) -> OAuthServerSettings?, urlProvider: ApplicationCall.(T, OAuthServerSettings) -> String) { fun ApplicationCall.resolve(): T { return application.feature(Locations).resolve<T>(type, this) } fun ApplicationCall.providerLookupLocal(): OAuthServerSettings? = providerLookup(resolve()) fun ApplicationCall.urlProviderLocal(s: OAuthServerSettings): String = urlProvider(resolve(), s) oauth(client, exec, ApplicationCall::providerLookupLocal, ApplicationCall::urlProviderLocal) }
0
null
0
1
b5dcbe5b740c2d25c7704104e01e0a01bf53d675
1,584
ktor
Apache License 2.0
plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenDistribution.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.maven.server import com.intellij.execution.wsl.WSLDistribution import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtil import org.jetbrains.idea.maven.project.MavenWorkspaceSettingsComponent import org.jetbrains.idea.maven.utils.MavenUtil import java.nio.file.Path import kotlin.io.path.Path interface MavenDistribution { val name: String val mavenHome: Path val version: String? fun isValid(): Boolean fun compatibleWith(mavenDistribution: MavenDistribution): Boolean } class LocalMavenDistribution(override val mavenHome: Path, override val name: String) : MavenDistribution { override val version: String? by lazy { MavenUtil.getMavenVersion(mavenHome.toFile()) } override fun compatibleWith(mavenDistribution: MavenDistribution): Boolean { return mavenDistribution == this || FileUtil.pathsEqual(mavenDistribution.mavenHome.toString(), mavenHome.toString()) } override fun isValid() = version != null override fun toString(): String { return "$name($mavenHome) v $version" } } internal class WslMavenDistribution(private val wslDistribution: WSLDistribution, private val pathToMaven: String, override val name: String) : MavenDistribution { override val version: String? by lazy { MavenUtil.getMavenVersion(wslDistribution.getWindowsPath(pathToMaven)) } override val mavenHome = Path(wslDistribution.getWindowsPath(pathToMaven)) override fun compatibleWith(mavenDistribution: MavenDistribution): Boolean { if (mavenDistribution == this) return true val another = mavenDistribution as? WslMavenDistribution ?: return false return another.wslDistribution == wslDistribution && another.pathToMaven == pathToMaven } override fun isValid() = version != null override fun toString(): String { return "$name($mavenHome) v $version" } }
229
null
4931
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
2,087
intellij-community
Apache License 2.0
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/emr/CfnClusterJobFlowInstancesConfigPropertyDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package cloudshift.awscdk.dsl.services.emr import cloudshift.awscdk.common.CdkDslMarker import kotlin.Any import kotlin.Boolean import kotlin.String import kotlin.collections.Collection import kotlin.collections.MutableList import software.amazon.awscdk.IResolvable import software.amazon.awscdk.services.emr.CfnCluster /** * `JobFlowInstancesConfig` is a property of the `AWS::EMR::Cluster` resource. * * `JobFlowInstancesConfig` defines the instance groups or instance fleets that comprise the * cluster. `JobFlowInstancesConfig` must contain either `InstanceFleetConfig` or * `InstanceGroupConfig` . They cannot be used together. * * You can now define task instance groups or task instance fleets using the `TaskInstanceGroups` * and `TaskInstanceFleets` subproperties. Using these subproperties reduces delays in provisioning * task nodes compared to specifying task nodes with the `InstanceFleetConfig` and * `InstanceGroupConfig` resources. * * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.emr.*; * ConfigurationProperty configurationProperty_; * JobFlowInstancesConfigProperty jobFlowInstancesConfigProperty = * JobFlowInstancesConfigProperty.builder() * .additionalMasterSecurityGroups(List.of("additionalMasterSecurityGroups")) * .additionalSlaveSecurityGroups(List.of("additionalSlaveSecurityGroups")) * .coreInstanceFleet(InstanceFleetConfigProperty.builder() * .instanceTypeConfigs(List.of(InstanceTypeConfigProperty.builder() * .instanceType("instanceType") * // the properties below are optional * .bidPrice("bidPrice") * .bidPriceAsPercentageOfOnDemandPrice(123) * .configurations(List.of(ConfigurationProperty.builder() * .classification("classification") * .configurationProperties(Map.of( * "configurationPropertiesKey", "configurationProperties")) * .configurations(List.of(configurationProperty_)) * .build())) * .customAmiId("customAmiId") * .ebsConfiguration(EbsConfigurationProperty.builder() * .ebsBlockDeviceConfigs(List.of(EbsBlockDeviceConfigProperty.builder() * .volumeSpecification(VolumeSpecificationProperty.builder() * .sizeInGb(123) * .volumeType("volumeType") * // the properties below are optional * .iops(123) * .build()) * // the properties below are optional * .volumesPerInstance(123) * .build())) * .ebsOptimized(false) * .build()) * .weightedCapacity(123) * .build())) * .launchSpecifications(InstanceFleetProvisioningSpecificationsProperty.builder() * .onDemandSpecification(OnDemandProvisioningSpecificationProperty.builder() * .allocationStrategy("allocationStrategy") * .build()) * .spotSpecification(SpotProvisioningSpecificationProperty.builder() * .timeoutAction("timeoutAction") * .timeoutDurationMinutes(123) * // the properties below are optional * .allocationStrategy("allocationStrategy") * .blockDurationMinutes(123) * .build()) * .build()) * .name("name") * .targetOnDemandCapacity(123) * .targetSpotCapacity(123) * .build()) * .coreInstanceGroup(InstanceGroupConfigProperty.builder() * .instanceCount(123) * .instanceType("instanceType") * // the properties below are optional * .autoScalingPolicy(AutoScalingPolicyProperty.builder() * .constraints(ScalingConstraintsProperty.builder() * .maxCapacity(123) * .minCapacity(123) * .build()) * .rules(List.of(ScalingRuleProperty.builder() * .action(ScalingActionProperty.builder() * .simpleScalingPolicyConfiguration(SimpleScalingPolicyConfigurationProperty.builder() * .scalingAdjustment(123) * // the properties below are optional * .adjustmentType("adjustmentType") * .coolDown(123) * .build()) * // the properties below are optional * .market("market") * .build()) * .name("name") * .trigger(ScalingTriggerProperty.builder() * .cloudWatchAlarmDefinition(CloudWatchAlarmDefinitionProperty.builder() * .comparisonOperator("comparisonOperator") * .metricName("metricName") * .period(123) * .threshold(123) * // the properties below are optional * .dimensions(List.of(MetricDimensionProperty.builder() * .key("key") * .value("value") * .build())) * .evaluationPeriods(123) * .namespace("namespace") * .statistic("statistic") * .unit("unit") * .build()) * .build()) * // the properties below are optional * .description("description") * .build())) * .build()) * .bidPrice("bidPrice") * .configurations(List.of(ConfigurationProperty.builder() * .classification("classification") * .configurationProperties(Map.of( * "configurationPropertiesKey", "configurationProperties")) * .configurations(List.of(configurationProperty_)) * .build())) * .customAmiId("customAmiId") * .ebsConfiguration(EbsConfigurationProperty.builder() * .ebsBlockDeviceConfigs(List.of(EbsBlockDeviceConfigProperty.builder() * .volumeSpecification(VolumeSpecificationProperty.builder() * .sizeInGb(123) * .volumeType("volumeType") * // the properties below are optional * .iops(123) * .build()) * // the properties below are optional * .volumesPerInstance(123) * .build())) * .ebsOptimized(false) * .build()) * .market("market") * .name("name") * .build()) * .ec2KeyName("ec2KeyName") * .ec2SubnetId("ec2SubnetId") * .ec2SubnetIds(List.of("ec2SubnetIds")) * .emrManagedMasterSecurityGroup("emrManagedMasterSecurityGroup") * .emrManagedSlaveSecurityGroup("emrManagedSlaveSecurityGroup") * .hadoopVersion("hadoopVersion") * .keepJobFlowAliveWhenNoSteps(false) * .masterInstanceFleet(InstanceFleetConfigProperty.builder() * .instanceTypeConfigs(List.of(InstanceTypeConfigProperty.builder() * .instanceType("instanceType") * // the properties below are optional * .bidPrice("bidPrice") * .bidPriceAsPercentageOfOnDemandPrice(123) * .configurations(List.of(ConfigurationProperty.builder() * .classification("classification") * .configurationProperties(Map.of( * "configurationPropertiesKey", "configurationProperties")) * .configurations(List.of(configurationProperty_)) * .build())) * .customAmiId("customAmiId") * .ebsConfiguration(EbsConfigurationProperty.builder() * .ebsBlockDeviceConfigs(List.of(EbsBlockDeviceConfigProperty.builder() * .volumeSpecification(VolumeSpecificationProperty.builder() * .sizeInGb(123) * .volumeType("volumeType") * // the properties below are optional * .iops(123) * .build()) * // the properties below are optional * .volumesPerInstance(123) * .build())) * .ebsOptimized(false) * .build()) * .weightedCapacity(123) * .build())) * .launchSpecifications(InstanceFleetProvisioningSpecificationsProperty.builder() * .onDemandSpecification(OnDemandProvisioningSpecificationProperty.builder() * .allocationStrategy("allocationStrategy") * .build()) * .spotSpecification(SpotProvisioningSpecificationProperty.builder() * .timeoutAction("timeoutAction") * .timeoutDurationMinutes(123) * // the properties below are optional * .allocationStrategy("allocationStrategy") * .blockDurationMinutes(123) * .build()) * .build()) * .name("name") * .targetOnDemandCapacity(123) * .targetSpotCapacity(123) * .build()) * .masterInstanceGroup(InstanceGroupConfigProperty.builder() * .instanceCount(123) * .instanceType("instanceType") * // the properties below are optional * .autoScalingPolicy(AutoScalingPolicyProperty.builder() * .constraints(ScalingConstraintsProperty.builder() * .maxCapacity(123) * .minCapacity(123) * .build()) * .rules(List.of(ScalingRuleProperty.builder() * .action(ScalingActionProperty.builder() * .simpleScalingPolicyConfiguration(SimpleScalingPolicyConfigurationProperty.builder() * .scalingAdjustment(123) * // the properties below are optional * .adjustmentType("adjustmentType") * .coolDown(123) * .build()) * // the properties below are optional * .market("market") * .build()) * .name("name") * .trigger(ScalingTriggerProperty.builder() * .cloudWatchAlarmDefinition(CloudWatchAlarmDefinitionProperty.builder() * .comparisonOperator("comparisonOperator") * .metricName("metricName") * .period(123) * .threshold(123) * // the properties below are optional * .dimensions(List.of(MetricDimensionProperty.builder() * .key("key") * .value("value") * .build())) * .evaluationPeriods(123) * .namespace("namespace") * .statistic("statistic") * .unit("unit") * .build()) * .build()) * // the properties below are optional * .description("description") * .build())) * .build()) * .bidPrice("bidPrice") * .configurations(List.of(ConfigurationProperty.builder() * .classification("classification") * .configurationProperties(Map.of( * "configurationPropertiesKey", "configurationProperties")) * .configurations(List.of(configurationProperty_)) * .build())) * .customAmiId("customAmiId") * .ebsConfiguration(EbsConfigurationProperty.builder() * .ebsBlockDeviceConfigs(List.of(EbsBlockDeviceConfigProperty.builder() * .volumeSpecification(VolumeSpecificationProperty.builder() * .sizeInGb(123) * .volumeType("volumeType") * // the properties below are optional * .iops(123) * .build()) * // the properties below are optional * .volumesPerInstance(123) * .build())) * .ebsOptimized(false) * .build()) * .market("market") * .name("name") * .build()) * .placement(PlacementTypeProperty.builder() * .availabilityZone("availabilityZone") * .build()) * .serviceAccessSecurityGroup("serviceAccessSecurityGroup") * .taskInstanceFleets(List.of(InstanceFleetConfigProperty.builder() * .instanceTypeConfigs(List.of(InstanceTypeConfigProperty.builder() * .instanceType("instanceType") * // the properties below are optional * .bidPrice("bidPrice") * .bidPriceAsPercentageOfOnDemandPrice(123) * .configurations(List.of(ConfigurationProperty.builder() * .classification("classification") * .configurationProperties(Map.of( * "configurationPropertiesKey", "configurationProperties")) * .configurations(List.of(configurationProperty_)) * .build())) * .customAmiId("customAmiId") * .ebsConfiguration(EbsConfigurationProperty.builder() * .ebsBlockDeviceConfigs(List.of(EbsBlockDeviceConfigProperty.builder() * .volumeSpecification(VolumeSpecificationProperty.builder() * .sizeInGb(123) * .volumeType("volumeType") * // the properties below are optional * .iops(123) * .build()) * // the properties below are optional * .volumesPerInstance(123) * .build())) * .ebsOptimized(false) * .build()) * .weightedCapacity(123) * .build())) * .launchSpecifications(InstanceFleetProvisioningSpecificationsProperty.builder() * .onDemandSpecification(OnDemandProvisioningSpecificationProperty.builder() * .allocationStrategy("allocationStrategy") * .build()) * .spotSpecification(SpotProvisioningSpecificationProperty.builder() * .timeoutAction("timeoutAction") * .timeoutDurationMinutes(123) * // the properties below are optional * .allocationStrategy("allocationStrategy") * .blockDurationMinutes(123) * .build()) * .build()) * .name("name") * .targetOnDemandCapacity(123) * .targetSpotCapacity(123) * .build())) * .taskInstanceGroups(List.of(InstanceGroupConfigProperty.builder() * .instanceCount(123) * .instanceType("instanceType") * // the properties below are optional * .autoScalingPolicy(AutoScalingPolicyProperty.builder() * .constraints(ScalingConstraintsProperty.builder() * .maxCapacity(123) * .minCapacity(123) * .build()) * .rules(List.of(ScalingRuleProperty.builder() * .action(ScalingActionProperty.builder() * .simpleScalingPolicyConfiguration(SimpleScalingPolicyConfigurationProperty.builder() * .scalingAdjustment(123) * // the properties below are optional * .adjustmentType("adjustmentType") * .coolDown(123) * .build()) * // the properties below are optional * .market("market") * .build()) * .name("name") * .trigger(ScalingTriggerProperty.builder() * .cloudWatchAlarmDefinition(CloudWatchAlarmDefinitionProperty.builder() * .comparisonOperator("comparisonOperator") * .metricName("metricName") * .period(123) * .threshold(123) * // the properties below are optional * .dimensions(List.of(MetricDimensionProperty.builder() * .key("key") * .value("value") * .build())) * .evaluationPeriods(123) * .namespace("namespace") * .statistic("statistic") * .unit("unit") * .build()) * .build()) * // the properties below are optional * .description("description") * .build())) * .build()) * .bidPrice("bidPrice") * .configurations(List.of(ConfigurationProperty.builder() * .classification("classification") * .configurationProperties(Map.of( * "configurationPropertiesKey", "configurationProperties")) * .configurations(List.of(configurationProperty_)) * .build())) * .customAmiId("customAmiId") * .ebsConfiguration(EbsConfigurationProperty.builder() * .ebsBlockDeviceConfigs(List.of(EbsBlockDeviceConfigProperty.builder() * .volumeSpecification(VolumeSpecificationProperty.builder() * .sizeInGb(123) * .volumeType("volumeType") * // the properties below are optional * .iops(123) * .build()) * // the properties below are optional * .volumesPerInstance(123) * .build())) * .ebsOptimized(false) * .build()) * .market("market") * .name("name") * .build())) * .terminationProtected(false) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-emr-cluster-jobflowinstancesconfig.html) */ @CdkDslMarker public class CfnClusterJobFlowInstancesConfigPropertyDsl { private val cdkBuilder: CfnCluster.JobFlowInstancesConfigProperty.Builder = CfnCluster.JobFlowInstancesConfigProperty.builder() private val _additionalMasterSecurityGroups: MutableList<String> = mutableListOf() private val _additionalSlaveSecurityGroups: MutableList<String> = mutableListOf() private val _ec2SubnetIds: MutableList<String> = mutableListOf() private val _taskInstanceFleets: MutableList<Any> = mutableListOf() private val _taskInstanceGroups: MutableList<Any> = mutableListOf() /** * @param additionalMasterSecurityGroups A list of additional Amazon EC2 security group IDs for * the master node. */ public fun additionalMasterSecurityGroups(vararg additionalMasterSecurityGroups: String) { _additionalMasterSecurityGroups.addAll(listOf(*additionalMasterSecurityGroups)) } /** * @param additionalMasterSecurityGroups A list of additional Amazon EC2 security group IDs for * the master node. */ public fun additionalMasterSecurityGroups(additionalMasterSecurityGroups: Collection<String>) { _additionalMasterSecurityGroups.addAll(additionalMasterSecurityGroups) } /** * @param additionalSlaveSecurityGroups A list of additional Amazon EC2 security group IDs for * the core and task nodes. */ public fun additionalSlaveSecurityGroups(vararg additionalSlaveSecurityGroups: String) { _additionalSlaveSecurityGroups.addAll(listOf(*additionalSlaveSecurityGroups)) } /** * @param additionalSlaveSecurityGroups A list of additional Amazon EC2 security group IDs for * the core and task nodes. */ public fun additionalSlaveSecurityGroups(additionalSlaveSecurityGroups: Collection<String>) { _additionalSlaveSecurityGroups.addAll(additionalSlaveSecurityGroups) } /** * @param coreInstanceFleet Describes the EC2 instances and instance configurations for the core * instance fleet when using clusters with the instance fleet configuration. */ public fun coreInstanceFleet(coreInstanceFleet: IResolvable) { cdkBuilder.coreInstanceFleet(coreInstanceFleet) } /** * @param coreInstanceFleet Describes the EC2 instances and instance configurations for the core * instance fleet when using clusters with the instance fleet configuration. */ public fun coreInstanceFleet(coreInstanceFleet: CfnCluster.InstanceFleetConfigProperty) { cdkBuilder.coreInstanceFleet(coreInstanceFleet) } /** * @param coreInstanceGroup Describes the EC2 instances and instance configurations for core * instance groups when using clusters with the uniform instance group configuration. */ public fun coreInstanceGroup(coreInstanceGroup: IResolvable) { cdkBuilder.coreInstanceGroup(coreInstanceGroup) } /** * @param coreInstanceGroup Describes the EC2 instances and instance configurations for core * instance groups when using clusters with the uniform instance group configuration. */ public fun coreInstanceGroup(coreInstanceGroup: CfnCluster.InstanceGroupConfigProperty) { cdkBuilder.coreInstanceGroup(coreInstanceGroup) } /** * @param ec2KeyName The name of the Amazon EC2 key pair that can be used to connect to the * master node using SSH as the user called "hadoop.". */ public fun ec2KeyName(ec2KeyName: String) { cdkBuilder.ec2KeyName(ec2KeyName) } /** * @param ec2SubnetId Applies to clusters that use the uniform instance group configuration. To * launch the cluster in Amazon Virtual Private Cloud (Amazon VPC), set this parameter to the * identifier of the Amazon VPC subnet where you want the cluster to launch. If you do not * specify this value and your account supports EC2-Classic, the cluster launches in * EC2-Classic. */ public fun ec2SubnetId(ec2SubnetId: String) { cdkBuilder.ec2SubnetId(ec2SubnetId) } /** * @param ec2SubnetIds Applies to clusters that use the instance fleet configuration. When * multiple Amazon EC2 subnet IDs are specified, Amazon EMR evaluates them and launches * instances in the optimal subnet. * * The instance fleet configuration is available only in Amazon EMR releases 4.8.0 and later, * excluding 5.0.x versions. */ public fun ec2SubnetIds(vararg ec2SubnetIds: String) { _ec2SubnetIds.addAll(listOf(*ec2SubnetIds)) } /** * @param ec2SubnetIds Applies to clusters that use the instance fleet configuration. When * multiple Amazon EC2 subnet IDs are specified, Amazon EMR evaluates them and launches * instances in the optimal subnet. * * The instance fleet configuration is available only in Amazon EMR releases 4.8.0 and later, * excluding 5.0.x versions. */ public fun ec2SubnetIds(ec2SubnetIds: Collection<String>) { _ec2SubnetIds.addAll(ec2SubnetIds) } /** * @param emrManagedMasterSecurityGroup The identifier of the Amazon EC2 security group for the * master node. If you specify `EmrManagedMasterSecurityGroup` , you must also specify * `EmrManagedSlaveSecurityGroup` . */ public fun emrManagedMasterSecurityGroup(emrManagedMasterSecurityGroup: String) { cdkBuilder.emrManagedMasterSecurityGroup(emrManagedMasterSecurityGroup) } /** * @param emrManagedSlaveSecurityGroup The identifier of the Amazon EC2 security group for the * core and task nodes. If you specify `EmrManagedSlaveSecurityGroup` , you must also specify * `EmrManagedMasterSecurityGroup` . */ public fun emrManagedSlaveSecurityGroup(emrManagedSlaveSecurityGroup: String) { cdkBuilder.emrManagedSlaveSecurityGroup(emrManagedSlaveSecurityGroup) } /** * @param hadoopVersion Applies only to Amazon EMR release versions earlier than 4.0. The Hadoop * version for the cluster. Valid inputs are "0.18" (no longer maintained), "0.20" (no longer * maintained), "0.20.205" (no longer maintained), "1.0.3", "2.2.0", or "2.4.0". If you do not * set this value, the default of 0.18 is used, unless the `AmiVersion` parameter is set in * the RunJobFlow call, in which case the default version of Hadoop for that AMI version is * used. */ public fun hadoopVersion(hadoopVersion: String) { cdkBuilder.hadoopVersion(hadoopVersion) } /** * @param keepJobFlowAliveWhenNoSteps Specifies whether the cluster should remain available * after completing all steps. Defaults to `true` . For more information about configuring * cluster termination, see * [Control Cluster Termination](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-plan-termination.html) * in the *EMR Management Guide* . */ public fun keepJobFlowAliveWhenNoSteps(keepJobFlowAliveWhenNoSteps: Boolean) { cdkBuilder.keepJobFlowAliveWhenNoSteps(keepJobFlowAliveWhenNoSteps) } /** * @param keepJobFlowAliveWhenNoSteps Specifies whether the cluster should remain available * after completing all steps. Defaults to `true` . For more information about configuring * cluster termination, see * [Control Cluster Termination](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-plan-termination.html) * in the *EMR Management Guide* . */ public fun keepJobFlowAliveWhenNoSteps(keepJobFlowAliveWhenNoSteps: IResolvable) { cdkBuilder.keepJobFlowAliveWhenNoSteps(keepJobFlowAliveWhenNoSteps) } /** * @param masterInstanceFleet Describes the EC2 instances and instance configurations for the * master instance fleet when using clusters with the instance fleet configuration. */ public fun masterInstanceFleet(masterInstanceFleet: IResolvable) { cdkBuilder.masterInstanceFleet(masterInstanceFleet) } /** * @param masterInstanceFleet Describes the EC2 instances and instance configurations for the * master instance fleet when using clusters with the instance fleet configuration. */ public fun masterInstanceFleet(masterInstanceFleet: CfnCluster.InstanceFleetConfigProperty) { cdkBuilder.masterInstanceFleet(masterInstanceFleet) } /** * @param masterInstanceGroup Describes the EC2 instances and instance configurations for the * master instance group when using clusters with the uniform instance group configuration. */ public fun masterInstanceGroup(masterInstanceGroup: IResolvable) { cdkBuilder.masterInstanceGroup(masterInstanceGroup) } /** * @param masterInstanceGroup Describes the EC2 instances and instance configurations for the * master instance group when using clusters with the uniform instance group configuration. */ public fun masterInstanceGroup(masterInstanceGroup: CfnCluster.InstanceGroupConfigProperty) { cdkBuilder.masterInstanceGroup(masterInstanceGroup) } /** @param placement The Availability Zone in which the cluster runs. */ public fun placement(placement: IResolvable) { cdkBuilder.placement(placement) } /** @param placement The Availability Zone in which the cluster runs. */ public fun placement(placement: CfnCluster.PlacementTypeProperty) { cdkBuilder.placement(placement) } /** * @param serviceAccessSecurityGroup The identifier of the Amazon EC2 security group for the * Amazon EMR service to access clusters in VPC private subnets. */ public fun serviceAccessSecurityGroup(serviceAccessSecurityGroup: String) { cdkBuilder.serviceAccessSecurityGroup(serviceAccessSecurityGroup) } /** * @param taskInstanceFleets Describes the EC2 instances and instance configurations for the * task instance fleets when using clusters with the instance fleet configuration. These task * instance fleets are added to the cluster as part of the cluster launch. Each task instance * fleet must have a unique name specified so that CloudFormation can differentiate between * the task instance fleets. * * You can currently specify only one task instance fleet for a cluster. After creating the * cluster, you can only modify the mutable properties of `InstanceFleetConfig` , which are * `TargetOnDemandCapacity` and `TargetSpotCapacity` . Modifying any other property results in * cluster replacement. &gt; To allow a maximum of 30 Amazon EC2 instance types per fleet, * include `TaskInstanceFleets` when you create your cluster. If you create your cluster without * `TaskInstanceFleets` , Amazon EMR uses its default allocation strategy, which allows for a * maximum of five Amazon EC2 instance types. */ public fun taskInstanceFleets(vararg taskInstanceFleets: Any) { _taskInstanceFleets.addAll(listOf(*taskInstanceFleets)) } /** * @param taskInstanceFleets Describes the EC2 instances and instance configurations for the * task instance fleets when using clusters with the instance fleet configuration. These task * instance fleets are added to the cluster as part of the cluster launch. Each task instance * fleet must have a unique name specified so that CloudFormation can differentiate between * the task instance fleets. * * You can currently specify only one task instance fleet for a cluster. After creating the * cluster, you can only modify the mutable properties of `InstanceFleetConfig` , which are * `TargetOnDemandCapacity` and `TargetSpotCapacity` . Modifying any other property results in * cluster replacement. &gt; To allow a maximum of 30 Amazon EC2 instance types per fleet, * include `TaskInstanceFleets` when you create your cluster. If you create your cluster without * `TaskInstanceFleets` , Amazon EMR uses its default allocation strategy, which allows for a * maximum of five Amazon EC2 instance types. */ public fun taskInstanceFleets(taskInstanceFleets: Collection<Any>) { _taskInstanceFleets.addAll(taskInstanceFleets) } /** * @param taskInstanceFleets Describes the EC2 instances and instance configurations for the * task instance fleets when using clusters with the instance fleet configuration. These task * instance fleets are added to the cluster as part of the cluster launch. Each task instance * fleet must have a unique name specified so that CloudFormation can differentiate between * the task instance fleets. * * You can currently specify only one task instance fleet for a cluster. After creating the * cluster, you can only modify the mutable properties of `InstanceFleetConfig` , which are * `TargetOnDemandCapacity` and `TargetSpotCapacity` . Modifying any other property results in * cluster replacement. &gt; To allow a maximum of 30 Amazon EC2 instance types per fleet, * include `TaskInstanceFleets` when you create your cluster. If you create your cluster without * `TaskInstanceFleets` , Amazon EMR uses its default allocation strategy, which allows for a * maximum of five Amazon EC2 instance types. */ public fun taskInstanceFleets(taskInstanceFleets: IResolvable) { cdkBuilder.taskInstanceFleets(taskInstanceFleets) } /** * @param taskInstanceGroups Describes the EC2 instances and instance configurations for task * instance groups when using clusters with the uniform instance group configuration. These * task instance groups are added to the cluster as part of the cluster launch. Each task * instance group must have a unique name specified so that CloudFormation can differentiate * between the task instance groups. * * After creating the cluster, you can only modify the mutable properties of * `InstanceGroupConfig` , which are `AutoScalingPolicy` and `InstanceCount` . Modifying any * other property results in cluster replacement. */ public fun taskInstanceGroups(vararg taskInstanceGroups: Any) { _taskInstanceGroups.addAll(listOf(*taskInstanceGroups)) } /** * @param taskInstanceGroups Describes the EC2 instances and instance configurations for task * instance groups when using clusters with the uniform instance group configuration. These * task instance groups are added to the cluster as part of the cluster launch. Each task * instance group must have a unique name specified so that CloudFormation can differentiate * between the task instance groups. * * After creating the cluster, you can only modify the mutable properties of * `InstanceGroupConfig` , which are `AutoScalingPolicy` and `InstanceCount` . Modifying any * other property results in cluster replacement. */ public fun taskInstanceGroups(taskInstanceGroups: Collection<Any>) { _taskInstanceGroups.addAll(taskInstanceGroups) } /** * @param taskInstanceGroups Describes the EC2 instances and instance configurations for task * instance groups when using clusters with the uniform instance group configuration. These * task instance groups are added to the cluster as part of the cluster launch. Each task * instance group must have a unique name specified so that CloudFormation can differentiate * between the task instance groups. * * After creating the cluster, you can only modify the mutable properties of * `InstanceGroupConfig` , which are `AutoScalingPolicy` and `InstanceCount` . Modifying any * other property results in cluster replacement. */ public fun taskInstanceGroups(taskInstanceGroups: IResolvable) { cdkBuilder.taskInstanceGroups(taskInstanceGroups) } /** * @param terminationProtected Specifies whether to lock the cluster to prevent the Amazon EC2 * instances from being terminated by API call, user intervention, or in the event of a * job-flow error. */ public fun terminationProtected(terminationProtected: Boolean) { cdkBuilder.terminationProtected(terminationProtected) } /** * @param terminationProtected Specifies whether to lock the cluster to prevent the Amazon EC2 * instances from being terminated by API call, user intervention, or in the event of a * job-flow error. */ public fun terminationProtected(terminationProtected: IResolvable) { cdkBuilder.terminationProtected(terminationProtected) } public fun build(): CfnCluster.JobFlowInstancesConfigProperty { if (_additionalMasterSecurityGroups.isNotEmpty()) cdkBuilder.additionalMasterSecurityGroups(_additionalMasterSecurityGroups) if (_additionalSlaveSecurityGroups.isNotEmpty()) cdkBuilder.additionalSlaveSecurityGroups(_additionalSlaveSecurityGroups) if (_ec2SubnetIds.isNotEmpty()) cdkBuilder.ec2SubnetIds(_ec2SubnetIds) if (_taskInstanceFleets.isNotEmpty()) cdkBuilder.taskInstanceFleets(_taskInstanceFleets) if (_taskInstanceGroups.isNotEmpty()) cdkBuilder.taskInstanceGroups(_taskInstanceGroups) return cdkBuilder.build() } }
4
null
0
3
c59c6292cf08f0fc3280d61e7f8cff813a608a62
31,019
awscdk-dsl-kotlin
Apache License 2.0
scopemob/src/commonTest/kotlin/com/github/mustafaozhan/scopemob/SameAsScopeTest.kt
SubMob
246,882,156
false
null
/* Copyright (c) 2020 Mustafa Ozhan. All rights reserved. */ package com.github.mustafaozhan.scopemob import com.github.mustafaozhan.scopemob.extension.failTest import com.github.mustafaozhan.scopemob.extension.passTest import com.github.mustafaozhan.scopemob.main.MainScopeTest import kotlin.test.Test class SameAsScopeTest : MainScopeTest() { @Test fun same() { subjectFunction?.trueCondition ?.sameAs { true } ?.let { passTest() } ?: run { failTest() } subjectFunction?.falseCondition ?.sameAs { false } ?.let { passTest() } ?: run { failTest() } } @Test fun notSame() { subjectFunction?.falseCondition ?.notSameAs { true } ?.let { passTest() } ?: run { failTest() } subjectFunction?.trueCondition ?.notSameAs { false } ?.let { passTest() } ?: run { failTest() } } }
0
Kotlin
0
2
7a4d419d47a00ec4be6f1cad4c127e90abd46b61
978
ScopeMob
Apache License 2.0
scopemob/src/commonTest/kotlin/com/github/mustafaozhan/scopemob/SameAsScopeTest.kt
SubMob
246,882,156
false
null
/* Copyright (c) 2020 Mustafa Ozhan. All rights reserved. */ package com.github.mustafaozhan.scopemob import com.github.mustafaozhan.scopemob.extension.failTest import com.github.mustafaozhan.scopemob.extension.passTest import com.github.mustafaozhan.scopemob.main.MainScopeTest import kotlin.test.Test class SameAsScopeTest : MainScopeTest() { @Test fun same() { subjectFunction?.trueCondition ?.sameAs { true } ?.let { passTest() } ?: run { failTest() } subjectFunction?.falseCondition ?.sameAs { false } ?.let { passTest() } ?: run { failTest() } } @Test fun notSame() { subjectFunction?.falseCondition ?.notSameAs { true } ?.let { passTest() } ?: run { failTest() } subjectFunction?.trueCondition ?.notSameAs { false } ?.let { passTest() } ?: run { failTest() } } }
0
Kotlin
0
2
7a4d419d47a00ec4be6f1cad4c127e90abd46b61
978
ScopeMob
Apache License 2.0
app/src/main/java/moe/feng/danmaqua/model/OnlinePatternRules.kt
danmaqua
237,640,502
false
null
package moe.feng.danmaqua.model import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize data class OnlinePatternRules( val version: Int, val data: List<PatternRulesItem> ) : Parcelable
1
Kotlin
9
137
68694b9f1e575af8541680afe96e2a3108338828
219
danmaqua-android
Apache License 2.0
app/src/main/java/moe/feng/danmaqua/model/OnlinePatternRules.kt
danmaqua
237,640,502
false
null
package moe.feng.danmaqua.model import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize data class OnlinePatternRules( val version: Int, val data: List<PatternRulesItem> ) : Parcelable
1
Kotlin
9
137
68694b9f1e575af8541680afe96e2a3108338828
219
danmaqua-android
Apache License 2.0
feature-staking-impl/src/main/java/jp/co/soramitsu/feature_staking_impl/domain/StakingInteractor.kt
trustex
385,920,487
true
{"Kotlin": 1715024}
package jp.co.soramitsu.feature_staking_impl.domain import jp.co.soramitsu.common.utils.networkType import jp.co.soramitsu.common.utils.sumByBigInteger import jp.co.soramitsu.core.model.Node import jp.co.soramitsu.fearless_utils.extensions.toHexString import jp.co.soramitsu.feature_account_api.domain.interfaces.AccountRepository import jp.co.soramitsu.feature_staking_api.domain.api.AccountIdMap import jp.co.soramitsu.feature_staking_api.domain.api.IdentityRepository import jp.co.soramitsu.feature_staking_api.domain.api.StakingRepository import jp.co.soramitsu.feature_staking_api.domain.model.Election import jp.co.soramitsu.feature_staking_api.domain.model.Exposure import jp.co.soramitsu.feature_staking_api.domain.model.IndividualExposure import jp.co.soramitsu.feature_staking_api.domain.model.RewardDestination import jp.co.soramitsu.feature_staking_api.domain.model.StakingAccount import jp.co.soramitsu.feature_staking_api.domain.model.StakingState import jp.co.soramitsu.feature_staking_api.domain.model.StakingStory import jp.co.soramitsu.feature_staking_api.domain.model.isUnbondingIn import jp.co.soramitsu.feature_staking_impl.data.mappers.mapAccountToStakingAccount import jp.co.soramitsu.feature_staking_impl.data.model.Payout import jp.co.soramitsu.feature_staking_impl.data.repository.PayoutRepository import jp.co.soramitsu.feature_staking_impl.data.repository.StakingConstantsRepository import jp.co.soramitsu.feature_staking_impl.data.repository.StakingRewardsRepository import jp.co.soramitsu.feature_staking_impl.domain.common.isWaiting import jp.co.soramitsu.feature_staking_impl.domain.model.NetworkInfo import jp.co.soramitsu.feature_staking_impl.domain.model.NominatorStatus import jp.co.soramitsu.feature_staking_impl.domain.model.PendingPayout import jp.co.soramitsu.feature_staking_impl.domain.model.PendingPayoutsStatistics import jp.co.soramitsu.feature_staking_impl.domain.model.StakeSummary import jp.co.soramitsu.feature_staking_impl.domain.model.StashNoneStatus import jp.co.soramitsu.feature_staking_impl.domain.model.Unbonding import jp.co.soramitsu.feature_staking_impl.domain.model.ValidatorStatus import jp.co.soramitsu.feature_wallet_api.domain.interfaces.WalletConstants import jp.co.soramitsu.feature_wallet_api.domain.interfaces.WalletRepository import jp.co.soramitsu.feature_wallet_api.domain.model.Asset import jp.co.soramitsu.feature_wallet_api.domain.model.Token import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.filterIsInstance import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.map import kotlinx.coroutines.withContext import java.math.BigInteger import kotlin.time.ExperimentalTime import kotlin.time.days import kotlin.time.milliseconds class EraRelativeInfo( val daysLeft: Int, val daysPast: Int, val erasLeft: BigInteger, val erasPast: BigInteger, ) class StakingInteractor( private val walletRepository: WalletRepository, private val accountRepository: AccountRepository, private val stakingRepository: StakingRepository, private val stakingRewardsRepository: StakingRewardsRepository, private val stakingConstantsRepository: StakingConstantsRepository, private val identityRepository: IdentityRepository, private val walletConstants: WalletConstants, private val payoutRepository: PayoutRepository, ) { @OptIn(ExperimentalTime::class) suspend fun calculatePendingPayouts(): Result<PendingPayoutsStatistics> = withContext(Dispatchers.Default) { runCatching { val currentStakingState = selectedAccountStakingStateFlow().first() require(currentStakingState is StakingState.Stash) val erasPerDay = currentStakingState.stashAddress.networkType().runtimeConfiguration.erasPerDay val activeEraIndex = stakingRepository.getActiveEraIndex() val historyDepth = stakingRepository.getHistoryDepth() val payouts = payoutRepository.calculateUnpaidPayouts(currentStakingState) val allValidatorAddresses = payouts.map(Payout::validatorAddress).distinct() val identityMapping = identityRepository.getIdentitiesFromAddresses(allValidatorAddresses) val pendingPayouts = payouts.map { val relativeInfo = eraRelativeInfo(it.era, activeEraIndex, historyDepth, erasPerDay) val estimatedCreatedAt = System.currentTimeMillis().milliseconds - relativeInfo.daysPast.days val closeToExpire = relativeInfo.erasLeft < historyDepth / 2.toBigInteger() with(it) { val validatorIdentity = identityMapping[validatorAddress] val validatorInfo = PendingPayout.ValidatorInfo(validatorAddress, validatorIdentity?.display) PendingPayout(validatorInfo, era, amount, estimatedCreatedAt.toLongMilliseconds(), relativeInfo.daysLeft, closeToExpire) } } PendingPayoutsStatistics( payouts = pendingPayouts, totalAmountInPlanks = pendingPayouts.sumByBigInteger(PendingPayout::amountInPlanks) ) } } suspend fun syncStakingRewards(accountAddress: String) = withContext(Dispatchers.IO) { runCatching { stakingRewardsRepository.sync(accountAddress) } } suspend fun observeStashSummary( stashState: StakingState.Stash.None ): Flow<StakeSummary<StashNoneStatus>> = observeStakeSummary(stashState) { when { it.electionStatus == Election.OPEN -> StashNoneStatus.ELECTION else -> StashNoneStatus.INACTIVE } } suspend fun observeValidatorSummary( validatorState: StakingState.Stash.Validator, ): Flow<StakeSummary<ValidatorStatus>> = observeStakeSummary(validatorState) { when { it.electionStatus == Election.OPEN -> ValidatorStatus.Election isValidatorActive(validatorState.stashId, it.eraStakers) -> ValidatorStatus.Active else -> ValidatorStatus.Inactive } } suspend fun observeNominatorSummary( nominatorState: StakingState.Stash.Nominator, ): Flow<StakeSummary<NominatorStatus>> = observeStakeSummary(nominatorState) { val existentialDeposit = walletConstants.existentialDeposit() val eraStakers = it.eraStakers.values when { it.electionStatus == Election.OPEN -> NominatorStatus.Election isNominationActive(nominatorState.stashId, it.eraStakers.values) -> NominatorStatus.Active nominatorState.nominations.isWaiting(it.activeEraIndex) -> NominatorStatus.Waiting else -> { val inactiveReason = when { it.asset.bondedInPlanks < minimumStake(eraStakers, existentialDeposit) -> NominatorStatus.Inactive.Reason.MIN_STAKE else -> NominatorStatus.Inactive.Reason.NO_ACTIVE_VALIDATOR } NominatorStatus.Inactive(inactiveReason) } } } suspend fun observeNetworkInfoState(networkType: Node.NetworkType): Flow<NetworkInfo> { val lockupPeriod = getLockupPeriodInDays(networkType) return stakingRepository.observeActiveEraIndex(networkType).map { eraIndex -> val exposures = stakingRepository.getElectedValidatorsExposure(eraIndex).values NetworkInfo( lockupPeriodInDays = lockupPeriod, minimumStake = minimumStake(exposures, walletConstants.existentialDeposit()), totalStake = totalStake(exposures), nominatorsCount = activeNominators(exposures), ) } } suspend fun getLockupPeriodInDays() = getLockupPeriodInDays(getSelectedNetworkType()) fun stakingStoriesFlow(): Flow<List<StakingStory>> { return stakingRepository.stakingStoriesFlow() } fun selectedAccountStakingStateFlow() = accountRepository.selectedAccountFlow() .flatMapLatest { stakingRepository.stakingStateFlow(it.address) } suspend fun getAccountsInCurrentNetwork() = withContext(Dispatchers.Default) { val account = accountRepository.getSelectedAccount() accountRepository.getAccountsByNetworkType(account.network.type) .map(::mapAccountToStakingAccount) } fun currentAssetFlow() = accountRepository.selectedAccountFlow() .flatMapLatest { assetFlow(it.address) } fun assetFlow(accountAddress: String): Flow<Asset> { return walletRepository.assetsFlow(accountAddress) .filter { it.isNotEmpty() } .map { it.first() } } suspend fun getSelectedNetworkType(): Node.NetworkType { return accountRepository.getSelectedNode().networkType } fun selectedAccountFlow(): Flow<StakingAccount> { return accountRepository.selectedAccountFlow() .map { mapAccountToStakingAccount(it) } } fun selectedNetworkTypeFLow() = accountRepository.selectedNetworkTypeFlow() suspend fun getAccount(address: String) = mapAccountToStakingAccount(accountRepository.getAccount(address)) suspend fun getSelectedAccount(): StakingAccount = withContext(Dispatchers.Default) { val account = accountRepository.getSelectedAccount() mapAccountToStakingAccount(account) } suspend fun isAccountInApp(accountAddress: String): Boolean { return accountRepository.isAccountExists(accountAddress) } suspend fun getRewardDestination(accountStakingState: StakingState.Stash): RewardDestination { return stakingRepository.getRewardDestination(accountStakingState) } fun currentUnbondingsFlow(): Flow<List<Unbonding>> { return selectedAccountStakingStateFlow() .filterIsInstance<StakingState.Stash>() .flatMapLatest { stash -> val networkType = stash.stashAddress.networkType() combine( stakingRepository.ledgerFlow(stash), stakingRepository.observeActiveEraIndex(networkType) ) { ledger, activeEraIndex -> val erasPerDay = networkType.runtimeConfiguration.erasPerDay val unbondingDuration = stakingConstantsRepository.lockupPeriodInEras() ledger.unlocking .filter { it.isUnbondingIn(activeEraIndex) } .map { val createdAtEra = it.era - unbondingDuration val relativeInfo = eraRelativeInfo(createdAtEra, activeEraIndex, unbondingDuration, erasPerDay) Unbonding(it.amount, relativeInfo.daysLeft) } } } } private fun eraRelativeInfo( createdAtEra: BigInteger, activeEra: BigInteger, lifespanInEras: BigInteger, erasPerDay: Int, ): EraRelativeInfo { val erasPast = activeEra - createdAtEra val erasLeft = lifespanInEras - erasPast val daysPast = erasPast.toInt() / erasPerDay val daysLeft = erasLeft.toInt() / erasPerDay return EraRelativeInfo(daysLeft, daysPast, erasLeft, erasPast) } private suspend fun <S> observeStakeSummary( state: StakingState.Stash, statusResolver: suspend (StatusResolutionContext) -> S, ): Flow<StakeSummary<S>> = withContext(Dispatchers.Default) { val networkType = state.accountAddress.networkType() val tokenType = Token.Type.fromNetworkType(networkType) combine( stakingRepository.electionFlow(networkType), stakingRepository.observeActiveEraIndex(networkType), walletRepository.assetFlow(state.accountAddress, tokenType), stakingRewardsRepository.stakingTotalRewards(state.accountAddress) ) { electionStatus, activeEraIndex, asset, totalReward -> val totalStaked = asset.bonded val eraStakers = stakingRepository.getElectedValidatorsExposure(activeEraIndex) val statusResolutionContext = StatusResolutionContext(eraStakers, activeEraIndex, electionStatus, asset) val status = statusResolver(statusResolutionContext) StakeSummary( status = status, totalStaked = totalStaked, totalRewards = totalReward.totalReward, currentEra = activeEraIndex.toInt() ) } } private fun isNominationActive(stashId: ByteArray, exposures: Collection<Exposure>): Boolean { return exposures.any { exposure -> exposure.others.any { it.who.contentEquals(stashId) } } } private fun isValidatorActive(stashId: ByteArray, exposures: AccountIdMap<Exposure>): Boolean { val stashIdHex = stashId.toHexString() return stashIdHex in exposures.keys } @OptIn(ExperimentalTime::class) private suspend fun activeNominators(exposures: Collection<Exposure>): Int { val activeNominatorsPerValidator = stakingConstantsRepository.maxRewardedNominatorPerValidatorPrefs() return exposures.fold(mutableSetOf<String>()) { acc, exposure -> acc += exposure.others.sortedByDescending(IndividualExposure::value) .take(activeNominatorsPerValidator) .map { it.who.toHexString() } acc }.size } private fun totalStake(exposures: Collection<Exposure>): BigInteger { return exposures.sumOf(Exposure::total) } private fun minimumStake( exposures: Collection<Exposure>, existentialDeposit: BigInteger, ): BigInteger { val stakeByNominator = exposures .map(Exposure::others) .flatten() .fold(mutableMapOf<String, BigInteger>()) { acc, individualExposure -> val currentExposure = acc.getOrDefault(individualExposure.who.toHexString(), BigInteger.ZERO) acc[individualExposure.who.toHexString()] = currentExposure + individualExposure.value acc } return stakeByNominator.values.minOrNull()!!.coerceAtLeast(existentialDeposit) } private suspend fun getLockupPeriodInDays(networkType: Node.NetworkType): Int { return stakingConstantsRepository.lockupPeriodInEras().toInt() / networkType.runtimeConfiguration.erasPerDay } private class StatusResolutionContext( val eraStakers: AccountIdMap<Exposure>, val activeEraIndex: BigInteger, val electionStatus: Election, val asset: Asset, ) }
0
null
0
0
cdb76cfdc1486e171c98aae3650e1d2e224a185a
14,839
fearless-Android
Apache License 2.0
app/src/test/kotlin/com/ne1c/gitteroid/presenters/TestMainPresenter.kt
fullstackenviormentss
131,682,557
true
{"Kotlin": 222987}
package com.ne1c.gitteroid.presenters import com.ne1c.gitteroid.TestExecutorService import com.ne1c.gitteroid.TestSharedPreferences import com.ne1c.gitteroid.api.GitterApi import com.ne1c.gitteroid.api.responses.StatusResponse import com.ne1c.gitteroid.dataproviders.DataManger import com.ne1c.gitteroid.di.base.NetworkService import com.ne1c.gitteroid.models.data.RoomModel import com.ne1c.gitteroid.models.data.UserModel import com.ne1c.gitteroid.models.view.RoomViewModel import com.ne1c.gitteroid.ui.views.MainView import com.nhaarman.mockito_kotlin.capture import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Matchers import org.mockito.Mock import org.mockito.Mockito.* import org.mockito.runners.MockitoJUnitRunner import rx.Observable import java.util.* @RunWith(MockitoJUnitRunner::class) class TestMainPresenter { @Mock var view: MainView? = null @Mock var gitterApi: GitterApi? = null @Mock var networkService: NetworkService? = null private var presenter: MainPresenter? = null private var dataManager: DataManger? = null private var prefs = TestSharedPreferences() @Before fun setup() { dataManager = spy(DataManger(gitterApi!!, prefs)) presenter = MainPresenter(TestExecutorService(), dataManager!!, networkService!!) presenter?.bindView(view) } @Test fun loadProfile_withNetwork_success() { val userModel = UserModel() `when`(networkService?.isConnected()).thenReturn(true) `when`(gitterApi?.getCurrentUser(anyString())).thenReturn(Observable.just(arrayListOf(userModel))) presenter?.loadProfile() verify(view)?.showProfile(userModel) verify(view, never())?.showError(anyInt()) } @Test fun loadProfile_withNetwork_failed() { `when`(networkService?.isConnected()).thenReturn(true) `when`(gitterApi?.getCurrentUser(anyString())).thenReturn(Observable.error(Throwable())) presenter?.loadProfile() verify(view)?.showProfile(UserModel()) verify(view, never())?.showError(anyInt()) } @Test fun loadProfile_noNetwork_success() { `when`(networkService?.isConnected()).thenReturn(false) } @Test fun loadProfile_noNetwork_failed() { `when`(networkService?.isConnected()).thenReturn(false) `when`(gitterApi?.getCurrentUser(anyString())).thenReturn(Observable.error(Throwable())) presenter?.loadProfile() verify(view, never())?.showProfile(createUserProfile()) verify(view)?.showError(anyInt()) } @Test fun leaveFromRoom_noNetwork_failed() { `when`(networkService?.isConnected()).thenReturn(false) presenter?.leaveFromRoom("room_id") verify(view, never())?.leavedFromRoom() verify(view)?.showError(anyInt()) } @Test fun leaveFromRoom_withNetwork_failed() { `when`(networkService?.isConnected()).thenReturn(true) val response = StatusResponse() response.success = false `when`(gitterApi?.leaveRoom(anyString(), anyString(), anyString())) .thenReturn(Observable.just(response)) `when`(dataManager?.leaveFromRoom("room_id")).thenReturn(Observable.just(true)) presenter?.leaveFromRoom("room_id") verify(view, never())?.leavedFromRoom() verify(view)?.showError(anyInt()) } @Test fun leaveFromRoom_withNetwork_success() { `when`(networkService?.isConnected()).thenReturn(true) val roomId = "room_id" val response = StatusResponse() response.success = true `when`(gitterApi?.leaveRoom(anyString(), anyString(), anyString())) .thenReturn(Observable.just(response)) presenter?.leaveFromRoom(roomId) verify(view)?.leavedFromRoom() verify(view, never())?.showError(anyInt()) } @Test fun loadRooms_withNetwork_fresh_success_with_5_unreadRooms() { `when`(networkService?.isConnected()).thenReturn(true) `when`(gitterApi?.getCurrentUserRooms(anyString())).thenReturn(Observable.just(generateRooms(unreadCountRooms = 5))) presenter?.loadRooms(true) verify(view)?.showRooms(capture { assert(it.size == 5) for (room in it) { assert(room.unreadItems > 0) } }) verify(view)?.saveAllRooms(capture { assert(it.size == 10) }) verify(view, never())?.errorLoadRooms() verify(view, never())?.showError(anyInt()) } @Test fun loadRooms_withNetwork_fresh_success_with_noUnreadRooms() { `when`(networkService?.isConnected()).thenReturn(true) `when`(gitterApi?.getCurrentUserRooms(anyString())).thenReturn(Observable.just(generateRooms())) presenter?.loadRooms(true) verify(view)?.showRooms(capture { assert(it.size == 4) for (room in it) { assert(room.unreadItems == 0) } }) verify(view)?.saveAllRooms(capture { assert(it.size == 10) for (room in it) { assert(room.unreadItems == 0) } }) verify(view, never())?.errorLoadRooms() verify(view, never())?.showError(anyInt()) } @Test fun loadRooms_withNetwork_fresh_success_with_oneToOneRooms() { `when`(networkService?.isConnected()).thenReturn(true) `when`(gitterApi?.getCurrentUserRooms(anyString())).thenReturn(Observable.just(generateOneToOneRooms())) presenter?.loadRooms(true) verify(view)?.showRooms(capture { assert(it.size == 4) for (room in it) { assert(room.oneToOne == true) } }) verify(view)?.saveAllRooms(capture { assert(it.size == 10) for (room in it) { assert(room.oneToOne == true) } }) verify(view, never())?.errorLoadRooms() verify(view, never())?.showError(anyInt()) } @Test fun loadRooms_withNetwork_error() { `when`(networkService?.isConnected()).thenReturn(true) `when`(gitterApi?.getCurrentUserRooms(anyString())).thenReturn(Observable.error(Throwable())) presenter?.loadRooms() verify(view)?.showError(Matchers.anyInt()) verify(view)?.errorLoadRooms() verify(view, never())?.showRooms(arrayListOf<RoomViewModel>()) } @After fun end() { prefs.edit().clear().commit() presenter?.unbindView() } private fun createUserProfile(): UserModel { val user = UserModel(id = "test_id", username = "Ne1c") return user } private fun generateRooms(countRooms: Int = 10, unreadCountRooms: Int = 0): ArrayList<RoomModel> { val rooms = ArrayList<RoomModel>(countRooms) // Generate rooms with unread messages for (i: Int in 1..unreadCountRooms) { val room = RoomModel() room.unreadItems = (Math.random() + 1).toInt() rooms.add(room) } // Generate default rooms for (i: Int in 1..(countRooms - unreadCountRooms)) { val room = RoomModel() rooms.add(room) } return rooms } private fun generateOneToOneRooms(oneToOne: Boolean = true, countRooms: Int = 10, countOneToOneRooms: Int = 10): ArrayList<RoomModel> { val rooms = generateRooms(countRooms = countRooms) for (i: Int in 0..countOneToOneRooms - 1) { rooms[i].oneToOne = oneToOne } return rooms } }
0
Kotlin
0
0
bf1af85eae715a168668ab472b406b8997c3c1c4
7,782
GitterClient
Apache License 2.0
customviews/src/main/java/dev/funkymuse/customviews/CustomizableCardView.kt
FunkyMuse
168,687,007
false
{"Kotlin": 1728002}
package dev.funkymuse.customviews import android.content.Context import android.util.AttributeSet import androidx.annotation.Keep import dev.funkymuse.setofusefulkotlinextensions.customviews.R import dev.funkymuse.setofusefulkotlinextensions.customviews.databinding.CustomizableCardViewBinding import com.google.android.material.card.MaterialCardView @Keep class CustomizableCardView : MaterialCardView { private val view = inflate(context, R.layout.customizable_card_view, this) val binding get() = CustomizableCardViewBinding.bind(view) constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { initView(attrs) } constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { initView(attrs) } private fun initView(attrs: AttributeSet?) { attrs ?: return val attributeValues = context.obtainStyledAttributes(attrs, R.styleable.CustomizableCardView) with(attributeValues) { try { binding.image.setImageDrawable(getDrawable(R.styleable.CustomizableCardView_ic_icon)) binding.title.text = getString(R.styleable.CustomizableCardView_ic_title) binding.content.text = getString(R.styleable.CustomizableCardView_ic_content) } finally { recycle() } } } }
6
Kotlin
92
818
fe984e6bdeb95fb5819f27dcb12001dcfd911819
1,455
KAHelpers
MIT License
app/src/main/java/com/network/clever/data/datasource/network/LiveDataCallAdapterFactory.kt
meuus90
268,465,690
false
null
/* * Copyright (C) 2020 MeUuS90 * * 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.network.clever.data.datasource.network import androidx.lifecycle.LiveData import com.meuus.base.network.ApiResponse import retrofit2.CallAdapter import retrofit2.Retrofit import java.lang.reflect.ParameterizedType import java.lang.reflect.Type class LiveDataCallAdapterFactory : CallAdapter.Factory() { override fun get(returnType: Type, annotations: Array<Annotation>, retrofit: Retrofit): CallAdapter<*, *>? { if (getRawType(returnType) != LiveData::class.java) { return null } val observableType = getParameterUpperBound(0, returnType as ParameterizedType) val rawObservableType = getRawType(observableType) require(rawObservableType == ApiResponse::class.java) { "type must be a resource" } require(observableType is ParameterizedType) { "resource must be parameterized" } val bodyType = getParameterUpperBound(0, observableType) return LiveDataCallAdapter<Any>(bodyType) } }
0
Kotlin
0
0
a4c5e970ab60f978c4ad6c3bbfdb22090d4238e3
1,579
CleverPlayer
MIT License
src/main/kotlin/com/dp/advancedgunnerycontrol/typesandvalues/ShipModes.kt
DesperatePeter
361,380,141
false
null
package com.dp.advancedgunnerycontrol.typesandvalues import com.dp.advancedgunnerycontrol.settings.Settings import com.dp.advancedgunnerycontrol.utils.InShipShipModeStorage import com.dp.advancedgunnerycontrol.utils.doesShipHaveLocalShipModes import com.dp.advancedgunnerycontrol.utils.generateUniversalFleetMemberId import com.dp.advancedgunnerycontrol.weaponais.shipais.* import com.fs.starfarer.api.combat.ShipAPI import com.fs.starfarer.combat.ai.BasicShipAI import java.lang.ref.WeakReference enum class ShipModes { DEFAULT, FORCE_AUTOFIRE, SHIELDS_OFF, VENT, VENT_AGGRESSIVE, RETREAT, NO_SYSTEM, SHIELDS_UP, SPAM_SYSTEM } const val defaultShipMode = "DEFAULT" val shipModeFromString = mapOf( "DEFAULT" to ShipModes.DEFAULT, "ForceAF" to ShipModes.FORCE_AUTOFIRE, "LowShields" to ShipModes.SHIELDS_OFF, "Vent(Flx>75%)" to ShipModes.VENT, "VntA(Flx>25%)" to ShipModes.VENT_AGGRESSIVE, "Run(HP<50%)" to ShipModes.RETREAT, "NoSystem" to ShipModes.NO_SYSTEM, "ShieldsUp" to ShipModes.SHIELDS_UP, "SpamSystem" to ShipModes.SPAM_SYSTEM ) val shipModeToString = shipModeFromString.map { it.value to it.key }.toMap() val detailedShipModeDescriptions = mapOf( ShipModes.DEFAULT to "Overwrites all other ship modes and forces default ship AI. Use to quickly turn off all ship mode tags.", ShipModes.FORCE_AUTOFIRE to "Forces autofire for all weapon groups. Use this to make ships obey all modes literally (99% of the time)." + "\nUse with caution and make sure to combine with HoldFire-suffixes to prevent the ship from fluxing out.", ShipModes.SHIELDS_OFF to "Force turn off the shield when ship flux exceeds ${(Settings.shieldsOffThreshold() * 100f).toInt()}%. " + "Make sure you have enough armor/PD to pull this off.", ShipModes.VENT to "Vent when ship flux exceeds ${(Settings.ventFluxThreshold() * 100f).toInt()}%. The ship will try to evaluate " + "the situation and only vent if it believes" + " that it will survive doing so.\nThe ship will feel safer if it has high armor/hull and enemies lack high DPS HE weapons" + " and finisher missiles and/or if there are many allies nearby. Works best on big, heavily armored, ships.", ShipModes.VENT_AGGRESSIVE to "Similar to ${shipModeToString[ShipModes.VENT]}, but at " + "${(Settings.aggressiveVentFluxThreshold() * 100f).toInt()}% flux and with much less concern for" + " the ship's survival. It will also prevent the AI from backing off while venting. Use with caution!", ShipModes.RETREAT to "Order a retreat command to the ship if hull < ${(Settings.retreatHullThreshold() * 100f).toInt()}%. This WILL use a CP.", ShipModes.NO_SYSTEM to "Ship will not use its ship system.", ShipModes.SHIELDS_UP to "Ship will not turn its shields off while flux < 90% and enemies are within weapon range.", ShipModes.SPAM_SYSTEM to "Ship will always use the ship system when available." ).withDefault { it.toString() } private fun generateCommander(mode: ShipModes, ship: ShipAPI): ShipCommandGenerator { return when (mode) { ShipModes.FORCE_AUTOFIRE -> AutofireShipAI(ship) ShipModes.SHIELDS_OFF -> ShieldsOffShipAI(ship, Settings.shieldsOffThreshold()) ShipModes.VENT -> VentShipAI(ship, Settings.ventFluxThreshold(), Settings.ventSafetyFactor(), false) ShipModes.VENT_AGGRESSIVE -> VentShipAI( ship, Settings.aggressiveVentFluxThreshold(), Settings.aggressiveVentSafetyFactor(), true ) ShipModes.RETREAT -> RetreatShipAI(ship, Settings.retreatHullThreshold()) ShipModes.NO_SYSTEM -> NoSystemAI(ship) ShipModes.SHIELDS_UP -> ShieldsUpAI(ship, 0.9f) ShipModes.SPAM_SYSTEM -> SpamSystemAI(ship) else -> ShipCommandGenerator(ship) } } fun assignShipMode(modes: List<String>, ship: ShipAPI, forceAssign: Boolean = false) { if (ship.shipAI == null) return ship.resetDefaultAI() if (ship.customData.containsKey(Values.CUSTOM_SHIP_DATA_SHIP_AI_KEY)) { ship.customData.remove(Values.CUSTOM_SHIP_DATA_SHIP_AI_KEY) } val shipModes = modes.mapNotNull { shipModeFromString[it] } if (!forceAssign && (shipModes.contains(ShipModes.DEFAULT) || shipModes.isEmpty())) return val baseAI = ship.shipAI ?: return val commanders = shipModes.map { generateCommander(it, ship) } val customAI = CustomShipAI(baseAI, ship, commanders) ship.setCustomData(Values.CUSTOM_SHIP_DATA_SHIP_AI_KEY, WeakReference(customAI)) ship.shipAI = customAI } fun hasCustomAI(ship: ShipAPI): Boolean { if (!ship.customData.containsKey(Values.CUSTOM_SHIP_DATA_SHIP_AI_KEY)) return false if (ship.shipAI is BasicShipAI) return false return (ship.customData[Values.CUSTOM_SHIP_DATA_SHIP_AI_KEY] as? WeakReference<*>)?.get() != null } fun getCustomShipAI(ship: ShipAPI): CustomShipAI? { if (!hasCustomAI(ship)) return null return ((ship.customData[Values.CUSTOM_SHIP_DATA_SHIP_AI_KEY] as? WeakReference<*>)?.get() as? CustomShipAI) } fun persistShipModes(shipId: String, loadoutIndex: Int, tags: List<String>) { Settings.shipModeStorage[loadoutIndex].modesByShip[shipId] = mutableMapOf() tags.forEachIndexed { index, s -> Settings.shipModeStorage[loadoutIndex].modesByShip[shipId]?.set(index, s) } } fun saveShipModesInShip(ship: ShipAPI, tags: List<String>, storageIndex: Int) { if (!ship.customData.containsKey(Values.CUSTOM_SHIP_DATA_SHIP_MODES_KEY)) { ship.setCustomData(Values.CUSTOM_SHIP_DATA_SHIP_MODES_KEY, InShipShipModeStorage()) } (ship.customData[Values.CUSTOM_SHIP_DATA_WEAPONS_TAG_KEY] as? InShipShipModeStorage)?.modes?.set( storageIndex, tags.toMutableList() ) } fun saveShipModes(ship: ShipAPI, loadoutIndex: Int, tags: List<String>) { if (Settings.enableCombatChangePersistance()) { val shipId = generateUniversalFleetMemberId(ship) persistShipModes(shipId, loadoutIndex, tags) } else { saveShipModesInShip(ship, tags, loadoutIndex) } } fun loadPersistedShipModes(shipId: String, loadoutIndex: Int): List<String> { return Settings.shipModeStorage[loadoutIndex].modesByShip[shipId]?.values?.toList() ?: emptyList() } fun loadShipModesFromShip(ship: ShipAPI, storageIndex: Int): List<String> { return (ship.customData[Values.CUSTOM_SHIP_DATA_SHIP_MODES_KEY] as? InShipShipModeStorage)?.modes?.get(storageIndex) ?: emptyList() } fun loadShipModes(ship: ShipAPI, loadoutIndex: Int): List<String> { if (Settings.enableCombatChangePersistance() || !doesShipHaveLocalShipModes(ship, loadoutIndex)) { val shipId = generateUniversalFleetMemberId(ship) return loadPersistedShipModes(shipId, loadoutIndex) } return loadShipModesFromShip(ship, loadoutIndex) }
2
Kotlin
3
9
514c3a1b9bd3f16ad6d0c602c9d9bdd9b50fb9fb
6,883
starsector-advanced-weapon-control
MIT License
native/commonizer/src/org/jetbrains/kotlin/commonizer/core/UnsafeNumberAnnotationUtils.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
/* * 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.commonizer.core import org.jetbrains.kotlin.commonizer.CommonizerSettings import org.jetbrains.kotlin.commonizer.CommonizerTarget import org.jetbrains.kotlin.commonizer.OptimisticNumberCommonizationEnabledKey import org.jetbrains.kotlin.commonizer.allLeaves import org.jetbrains.kotlin.commonizer.cir.* import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull fun createUnsafeNumberAnnotationIfNecessary( targets: List<CommonizerTarget>, settings: CommonizerSettings, inputDeclarations: List<CirHasAnnotations>, inputTypes: List<CirType>, commonizedType: CirType, ): CirAnnotation? { if (!shouldCreateAnnotation(settings, commonizedType, inputDeclarations)) return null val actualPlatformTypes = mutableMapOf<String, RenderedType>() inputTypes.zip(targets).forEach { (type, target) -> target.allLeaves().forEach { leafCommonizerTarget -> actualPlatformTypes[leafCommonizerTarget.name] = renderTypeForUnsafeNumberAnnotation(type) } } inputDeclarations.forEach { annotated -> val existingAnnotation = annotated.annotations.firstIsInstanceOrNull<UnsafeNumberAnnotation>() if (existingAnnotation != null) { actualPlatformTypes.putAll(existingAnnotation.actualPlatformTypes) } } if (actualPlatformTypes.values.distinct().size > 1) { return UnsafeNumberAnnotation(actualPlatformTypes) } return null } private fun shouldCreateAnnotation( settings: CommonizerSettings, commonizedType: CirType, inputDeclarations: List<CirHasAnnotations>, ): Boolean { if (!settings.getSetting(OptimisticNumberCommonizationEnabledKey)) return false val isDerivedFromOptimisticallyCommonizedType = inputDeclarations.any { declaration -> declaration.annotations.any { annotation -> annotation is UnsafeNumberAnnotation } } var isOptimisticallyCommonizedType = false var isOptimisticallyCommonizableNumberType = false commonizedType.accept(object : BasicCirTypeVisitor() { override fun visit(classType: CirClassType) { if (classType.getAttachment<OptimisticNumbersTypeCommonizer.OptimisticCommonizationMarker>() != null) { isOptimisticallyCommonizedType = true } if (OptimisticNumbersTypeCommonizer.isOptimisticallyCommonizableNumber(classType.classifierId)) { isOptimisticallyCommonizableNumberType = true } super.visit(classType) } }) return isOptimisticallyCommonizedType || (isDerivedFromOptimisticallyCommonizedType && isOptimisticallyCommonizableNumberType) } private typealias RenderedType = String private class UnsafeNumberAnnotation(val actualPlatformTypes: Map<String, RenderedType>) : CirAnnotation { override val type: CirClassType = UnsafeNumberAnnotation.type override val annotationValueArguments: Map<CirName, CirAnnotation> = emptyMap() override val constantValueArguments: Map<CirName, CirConstantValue> = mapOf( CirName.create("actualPlatformTypes") to CirConstantValue.ArrayValue( actualPlatformTypes.toSortedMap().map { (platform, type) -> CirConstantValue.StringValue("$platform: $type") } ) ) companion object { private val type = CirClassType.createInterned( classId = CirEntityId.create("kotlinx/cinterop/UnsafeNumber"), outerType = null, arguments = emptyList(), isMarkedNullable = false ) } }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
3,806
kotlin
Apache License 2.0
android/src/main/kotlin/com/app/rtmp_publisher/AppVideoEncoder.kt
emiliodallatorre
366,068,475
true
{"Kotlin": 117874, "Dart": 80052, "Objective-C": 47559, "Swift": 8062, "Ruby": 2419, "Shell": 100}
package com.app.rtmp_publisher import android.media.MediaCodec import android.media.MediaCodecInfo import android.media.MediaFormat import android.os.Build import android.os.Bundle import android.os.Handler import android.os.HandlerThread import android.util.Log import android.util.Pair import android.view.Surface import androidx.annotation.RequiresApi import com.pedro.encoder.input.video.FpsLimiter import com.pedro.encoder.utils.CodecUtil import com.pedro.encoder.utils.yuv.YUVUtil import com.pedro.encoder.video.FormatVideoEncoder import com.pedro.encoder.video.GetVideoData import java.io.IOException import java.nio.ByteBuffer import java.util.List /* * Encodes the data going over the wire to the backend system, this handles talking * with the media encoder framework and shuttling this over to the rtmp system itself. */ class AppVideoEncoder( val getVideoData: GetVideoData, val width: Int, val height: Int, var fps: Int, var bitrate: Int, val rotation: Int, val doRotation: Boolean, val iFrameInterval: Int, val formatVideoEncoder: FormatVideoEncoder, val avcProfile: Int = -1, val avcProfileLevel: Int = -1, val aspectRatio: Double = 1.0) { private var spsPpsSetted = false // surface to buffer encoder var surface: Surface? = null // for disable video private val fpsLimiter: FpsLimiter = FpsLimiter() var type: String = CodecUtil.H264_MIME private var handlerThread: HandlerThread = HandlerThread(TAG) protected var codec: MediaCodec? = null private var callback: MediaCodec.Callback? = null private var isBufferMode: Boolean = false protected var presentTimeUs: Long = 0 var force: CodecUtil.Force = CodecUtil.Force.FIRST_COMPATIBLE_FOUND private val bufferInfo: MediaCodec.BufferInfo = MediaCodec.BufferInfo() @kotlin.jvm.Volatile public var running = false // The fps to limit at var limitFps = fps /** * Prepare encoder. */ fun prepare(): Boolean { val encoder: MediaCodecInfo? = chooseEncoder(type) var videoEncoder: FormatVideoEncoder? = this.formatVideoEncoder return try { if (encoder != null) { codec = MediaCodec.createByCodecName(encoder.getName()) if (videoEncoder == FormatVideoEncoder.YUV420Dynamical) { videoEncoder = chooseColorDynamically(encoder) if (videoEncoder == null) { Log.e(TAG, "YUV420 dynamical choose failed") return false } } } else { Log.e(TAG, "Valid encoder not found") return false } val videoFormat: MediaFormat // if you don't use mediacodec rotation you need swap width and height in rotation 90 or 270 // for correct encoding resolution val ratioWidth = width val ratioHeight = height val resolution: String = "" + ratioWidth + "x" + ratioHeight videoFormat = MediaFormat.createVideoFormat(type, ratioWidth, ratioHeight) Log.i(TAG, "Prepare video info: " + videoEncoder!!.name.toString() + ", " + resolution) videoFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, videoEncoder!!.getFormatCodec()) videoFormat.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 0) videoFormat.setInteger(MediaFormat.KEY_BIT_RATE, bitrate) videoFormat.setInteger(MediaFormat.KEY_FRAME_RATE, fps) videoFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, iFrameInterval) videoFormat.setInteger(MediaFormat.KEY_ROTATION, rotation) if (this.avcProfile > 0 && this.avcProfileLevel > 0) { // MediaFormat.KEY_PROFILE, API > 21 videoFormat.setInteger(MediaFormat.KEY_PROFILE, this.avcProfile) // MediaFormat.KEY_LEVEL, API > 23 videoFormat.setInteger(MediaFormat.KEY_LEVEL, this.avcProfileLevel) } codec!!.configure(videoFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE) running = false isBufferMode = false surface = codec!!.createInputSurface() Log.i(TAG, "prepared") true } catch (e: IOException) { Log.e(TAG, "Create VideoEncoder failed.", e) false } catch (e: IllegalStateException) { Log.e(TAG, "Create VideoEncoder failed.", e) false } } fun start() { spsPpsSetted = false presentTimeUs = System.nanoTime() / 1000 fpsLimiter.setFPS(limitFps) if (formatVideoEncoder !== FormatVideoEncoder.SURFACE) { YUVUtil.preAllocateBuffers(width * height * 3 / 2) } handlerThread.start() val handler = Handler(handlerThread.getLooper()) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { createAsyncCallback() codec!!.setCallback(callback, handler) codec!!.start() } else { codec!!.start() handler.post(Runnable { while (running) { try { getDataFromEncoder() } catch (e: IllegalStateException) { Log.i(TAG, "Encoding error", e) } } }) } running = true Log.i(TAG, "started") } protected fun stopImp() { if (handlerThread != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { handlerThread.quitSafely() } else { handlerThread.quit() } } spsPpsSetted = false surface = null Log.i(TAG, "stopped") } fun stop() { running = false codec = try { codec!!.stop() codec!!.release() stopImp() null } catch (e: IllegalStateException) { null } catch (e: NullPointerException) { null } } fun reset() { stop() prepare() start() } private fun chooseColorDynamically(mediaCodecInfo: MediaCodecInfo): FormatVideoEncoder? { for (color in mediaCodecInfo.getCapabilitiesForType(type).colorFormats) { if (color == FormatVideoEncoder.YUV420PLANAR.getFormatCodec()) { return FormatVideoEncoder.YUV420PLANAR } else if (color == FormatVideoEncoder.YUV420SEMIPLANAR.getFormatCodec()) { return FormatVideoEncoder.YUV420SEMIPLANAR } } return null } @RequiresApi(api = Build.VERSION_CODES.KITKAT) fun setVideoBitrateOnFly(bitrate: Int) { if (running) { this.bitrate = bitrate val bundle = Bundle() bundle.putInt(MediaCodec.PARAMETER_KEY_VIDEO_BITRATE, bitrate) try { codec!!.setParameters(bundle) } catch (e: IllegalStateException) { Log.e(TAG, "encoder need be running", e) } } } @RequiresApi(api = Build.VERSION_CODES.KITKAT) fun forceSyncFrame() { if (running) { val bundle = Bundle() bundle.putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0) try { codec!!.setParameters(bundle) } catch (e: IllegalStateException) { Log.e(TAG, "encoder need be running", e) } } } private fun sendSPSandPPS(mediaFormat: MediaFormat) { //H265 if (type!!.equals(CodecUtil.H265_MIME)) { val byteBufferList = mediaFormat.getByteBuffer("csd-0") ?.let { extractVpsSpsPpsFromH265(it) } getVideoData.onSpsPpsVps(byteBufferList!![1], byteBufferList[2], byteBufferList[0]) //H264 } else { getVideoData.onSpsPps(mediaFormat.getByteBuffer("csd-0"), mediaFormat.getByteBuffer("csd-1")) } } /** * choose the video encoder by mime. */ protected fun chooseEncoder(mime: String): MediaCodecInfo? { val mediaCodecInfoList: List<MediaCodecInfo>? = if (force === CodecUtil.Force.HARDWARE) { CodecUtil.getAllHardwareEncoders(mime) as List<MediaCodecInfo> } else if (force === CodecUtil.Force.SOFTWARE) { CodecUtil.getAllSoftwareEncoders(mime) as List<MediaCodecInfo> } else { CodecUtil.getAllEncoders(mime) as List<MediaCodecInfo> } for (mci in mediaCodecInfoList!!) { Log.i(TAG, String.format("VideoEncoder %s", mci.getName())) val codecCapabilities: MediaCodecInfo.CodecCapabilities = mci.getCapabilitiesForType(mime) for (color in codecCapabilities.colorFormats) { Log.i(TAG, "Color supported: $color") if (formatVideoEncoder === FormatVideoEncoder.SURFACE) { if (color == FormatVideoEncoder.SURFACE.getFormatCodec()) return mci } else { //check if encoder support any yuv420 color if (color == FormatVideoEncoder.YUV420PLANAR.getFormatCodec() || color == FormatVideoEncoder.YUV420SEMIPLANAR.getFormatCodec()) { return mci } } } } return null } /** * decode sps and pps if the encoder never call to MediaCodec.INFO_OUTPUT_FORMAT_CHANGED */ private fun decodeSpsPpsFromBuffer(outputBuffer: ByteBuffer, length: Int): Pair<ByteBuffer, ByteBuffer>? { var mSPS: ByteArray? = null var mPPS: ByteArray? = null val csd = ByteArray(length) outputBuffer.get(csd, 0, length) var i = 0 var spsIndex = -1 var ppsIndex = -1 while (i < length - 4) { if (csd[i].toInt() == 0 && csd[i + 1].toInt() == 0 && csd[i + 2].toInt() == 0 && csd[i + 3].toInt() == 1) { if (spsIndex.toInt() == -1) { spsIndex = i } else { ppsIndex = i break } } i++ } if (spsIndex != -1 && ppsIndex != -1) { mSPS = ByteArray(ppsIndex) System.arraycopy(csd, spsIndex, mSPS, 0, ppsIndex) mPPS = ByteArray(length - ppsIndex) System.arraycopy(csd, ppsIndex, mPPS, 0, length - ppsIndex) } return if (mSPS != null && mPPS != null) { Pair(ByteBuffer.wrap(mSPS), ByteBuffer.wrap(mPPS)) } else null } /** * You need find 0 0 0 1 byte sequence that is the initiation of vps, sps and pps * buffers. * * @param csd0byteBuffer get in mediacodec case MediaCodec.INFO_OUTPUT_FORMAT_CHANGED * @return list with vps, sps and pps */ private fun extractVpsSpsPpsFromH265(csd0byteBuffer: ByteBuffer): List<ByteBuffer> { val byteBufferList: MutableList<ByteBuffer> = mutableListOf<ByteBuffer>() var vpsPosition = -1 var spsPosition = -1 var ppsPosition = -1 var contBufferInitiation = 0 val csdArray: ByteArray = csd0byteBuffer.array() for (i in csdArray.indices) { if (contBufferInitiation.toInt() == 3 && csdArray[i].toInt() == 1) { if (vpsPosition.toInt() == -1) { vpsPosition = i - 3 } else if (spsPosition.toInt() == -1) { spsPosition = i - 3 } else { ppsPosition = i - 3 } } if (csdArray[i].toInt() == 0) { contBufferInitiation++ } else { contBufferInitiation = 0 } } val vps = ByteArray(spsPosition) val sps = ByteArray(ppsPosition - spsPosition) val pps = ByteArray(csdArray.size - ppsPosition) for (i in csdArray.indices) { if (i < spsPosition) { vps[i] = csdArray[i] } else if (i < ppsPosition) { sps[i - spsPosition] = csdArray[i] } else { pps[i - ppsPosition] = csdArray[i] } } byteBufferList.add(ByteBuffer.wrap(vps)) byteBufferList.add(ByteBuffer.wrap(sps)) byteBufferList.add(ByteBuffer.wrap(pps)) return byteBufferList as List<ByteBuffer> } @kotlin.jvm.Throws(IllegalStateException::class) protected fun getDataFromEncoder() { Log.i(TAG, "getDataFromEncoder") while (running) { val outBufferIndex: Int = codec!!.dequeueOutputBuffer(bufferInfo, 1) if (outBufferIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { val mediaFormat: MediaFormat = codec!!.getOutputFormat() formatChanged(codec!!, mediaFormat) } else if (outBufferIndex >= 0) { outputAvailable(codec!!, outBufferIndex, bufferInfo) } else { break } } } fun formatChanged(mediaCodec: MediaCodec, mediaFormat: MediaFormat) { getVideoData.onVideoFormat(mediaFormat) sendSPSandPPS(mediaFormat) spsPpsSetted = true } protected fun checkBuffer(byteBuffer: ByteBuffer, bufferInfo: MediaCodec.BufferInfo) { if (bufferInfo.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG !== 0) { if (!spsPpsSetted) { val buffers: Pair<ByteBuffer, ByteBuffer>? = decodeSpsPpsFromBuffer(byteBuffer.duplicate(), bufferInfo.size) if (buffers != null) { getVideoData.onSpsPps(buffers.first, buffers.second) spsPpsSetted = true } } } } protected fun sendBuffer(byteBuffer: ByteBuffer, bufferInfo: MediaCodec.BufferInfo) { bufferInfo.presentationTimeUs = System.nanoTime() / 1000 - presentTimeUs getVideoData.getVideoData(byteBuffer, bufferInfo) } @kotlin.jvm.Throws(IllegalStateException::class) private fun processOutput(byteBuffer: ByteBuffer, mediaCodec: MediaCodec, outBufferIndex: Int, bufferInfo: MediaCodec.BufferInfo) { if (running) { checkBuffer(byteBuffer, bufferInfo) sendBuffer(byteBuffer, bufferInfo) } Log.e(TAG, "releaseOutputBuffer " + outBufferIndex) mediaCodec.releaseOutputBuffer(outBufferIndex, false) } @RequiresApi(api = Build.VERSION_CODES.M) private fun createAsyncCallback() { Log.i(TAG, "createAsyncCallback") callback = object : MediaCodec.Callback() { override fun onInputBufferAvailable(mediaCodec: MediaCodec, inBufferIndex: Int) { Log.i(TAG, "onInputBufferAvailable ignored") } override fun onOutputBufferAvailable(mediaCodec: MediaCodec, outBufferIndex: Int, bufferInfo: MediaCodec.BufferInfo) { try { outputAvailable(mediaCodec, outBufferIndex, bufferInfo) } catch (e: IllegalStateException) { Log.i(TAG, "Encoding error", e) } } override fun onError(mediaCodec: MediaCodec, e: MediaCodec.CodecException) { Log.e(TAG, "Error", e) } override fun onOutputFormatChanged(mediaCodec: MediaCodec, mediaFormat: MediaFormat) { formatChanged(mediaCodec, mediaFormat) } } } fun outputAvailable(mediaCodec: MediaCodec, outBufferIndex: Int, bufferInfo: MediaCodec.BufferInfo) { Log.e(TAG, "outputAvailable " + outBufferIndex) val byteBuffer = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mediaCodec.getOutputBuffer(outBufferIndex) } else { mediaCodec.getOutputBuffers().get(outBufferIndex) } if (byteBuffer != null) { processOutput(byteBuffer, mediaCodec, outBufferIndex, bufferInfo) } } companion object { private val TAG: String? = "VideoEncoder" } }
7
Kotlin
6
4
6980d15016841160d0bb3a27611c4d02de488b7b
16,548
flutter_rtmp_broadcaster
MIT License
src/main/kotlin/com/fintecsystems/xs2a/java/models/risk/checks/Xs2aBalanceOverviewResponse.kt
FinTecSystems
399,112,589
false
null
package com.fintecsystems.xs2a.java.models.risk.checks import com.fintecsystems.xs2a.java.models.common.CurrencyId import com.squareup.moshi.Json import java.time.OffsetDateTime /** * * @param balance Current balance * @param available Current available * @param limit Current limit (overdraft) * @param currencyId Currency id of above values * @param createdAt Creation date of the object */ data class Xs2aBalanceOverviewResponse( @Json(name = "balance") var balance: Float, @Json(name = "available") var available: Float? = null, @Json(name = "limit") var limit: Float? = null, @Json(name = "currency_id") var currencyId: CurrencyId, @Json(name = "created_at") var createdAt: OffsetDateTime )
0
Kotlin
3
3
442715946fa34f6947a6eaa97adb00278dc7d09b
748
xs2a-java
MIT License
compiler/testData/codegen/box/literals/strdedup1.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ // WITH_STDLIB import kotlin.test.* fun box(): String { val str1 = "Hello" val str2 = "Hello" if (!(str1 == str2)) return "FAIL ==" if (!(str1 === str2)) return "FAIL ===" return "OK" }
181
Kotlin
5771
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
376
kotlin
Apache License 2.0
common/src/commonMain/kotlin/nolambda/aichat/common/home/view/ChatItemView.kt
esafirm
625,126,393
false
null
package nolambda.aichat.common.home.view import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer 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.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import nolambda.aichat.common.LocalImage import nolambda.aichat.common.LocalImages import nolambda.aichat.common.home.model.ChatElement import nolambda.aichat.common.home.model.Message @Composable internal fun ChatItemView( actor: Message.Actor, chatElements: List<ChatElement>, modifier: Modifier = Modifier, ) { Row( modifier = modifier.composed { if (actor == Message.Actor.Person) { Modifier.background(Color.LightGray.copy(0.5F)) .padding(16.dp) .fillMaxWidth() } else { Modifier.padding(16.dp) .fillMaxWidth() } } ) { val image = when (actor) { Message.Actor.Person -> LocalImages.Person Message.Actor.Bot -> LocalImages.Robot } LocalImage( imageResourceName = image, contentDescription = "Actor", modifier = Modifier.size(24.dp) ) Spacer(modifier = Modifier.width(16.dp)) Column( modifier = Modifier.fillMaxWidth() ) { chatElements.forEachIndexed { index, el -> // Add spacing between each element if (index > 0) { Spacer(modifier = Modifier.height(8.dp)) } when (el) { is ChatElement.CodeBlock -> CodeBlockTextView(chatElement = el) is ChatElement.Text -> SimpleMarkdownTextView(chatElement = el) } } } } } @Composable internal fun CodeBlockTextView(chatElement: ChatElement.CodeBlock) { Text( text = chatElement.value, modifier = Modifier.fillMaxWidth() .background(Color.LightGray.copy(0.8F), shape = RoundedCornerShape(8.dp)) .padding(16.dp), fontFamily = FontFamily.Monospace, ) } @Composable internal fun SimpleMarkdownTextView(chatElement: ChatElement.Text) { val annotatedString = remember(chatElement) { createAnnotatedString(chatElement.value) } Text(text = annotatedString) } private val backtickPattern = "`(.+?)`".toRegex() private fun createAnnotatedString(text: String): AnnotatedString { val annotatedSpans = mutableListOf<AnnotatedString.Range<SpanStyle>>() .apply { val result = backtickPattern.findAll(text) result.forEach { match -> add( AnnotatedString.Range( SpanStyle( fontWeight = FontWeight.SemiBold, background = Color.LightGray.copy(0.5F), ), start = match.range.first, end = match.range.last + 1 ) ) } } return buildAnnotatedString { append(text) annotatedSpans.forEach { range -> addStyle( style = range.item, start = range.start, end = range.end ) } } }
0
Kotlin
0
8
7b50df377ecca1c01b9b8717cd5a0ba15cb88ed8
4,185
compose-ai-chat
Apache License 2.0
src/main/kotlin/org/cascadebot/cascadebot/utils/interactions/CascadeLinkButton.kt
CascadeBot
148,109,341
false
null
package org.cascadebot.cascadebot.utils.interactions import net.dv8tion.jda.api.entities.Emoji import net.dv8tion.jda.api.interactions.components.Button import net.dv8tion.jda.api.interactions.components.ButtonStyle import net.dv8tion.jda.api.interactions.components.Component class CascadeLinkButton private constructor (val link: String, val label: String?, val emoji: Emoji?) : CascadeComponent(link) { override val discordComponent: Component = Button.of(ButtonStyle.LINK, link, label, emoji) init { require(label != null || emoji != null) { "Label and emoji cannot both be null" } } companion object { @JvmStatic fun of(link: String, label: String) = CascadeLinkButton(link, label, null) @JvmStatic fun of(link: String, emoji: Emoji) = CascadeLinkButton(link, null, emoji) @JvmStatic fun of(link: String, label: String, emoji: Emoji) = CascadeLinkButton(link, label, emoji) } }
19
Java
8
42
0736e27dc226a3f9e48bbdbccf7a5222fd685976
963
CascadeBot
MIT License
app/src/main/java/ceui/pixiv/ui/common/DataSource.kt
CeuiLiSA
178,835,117
false
{"Java": 1983271, "Kotlin": 618050, "CSS": 1258}
package ceui.pixiv.ui.common import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import ceui.lisa.utils.Common import ceui.loxia.Client import ceui.loxia.KListShow import ceui.loxia.RefreshHint import ceui.loxia.RefreshState import com.google.gson.Gson import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.withContext open class DataSource<Item, T: KListShow<Item>>( private val dataFetcher: suspend () -> T, itemMapper: (Item) -> List<ListItemHolder>, private val filter: (Item) -> Boolean = { _ -> true } ) { private var _variableItemMapper: ((Item) -> List<ListItemHolder>)? = null init { this._variableItemMapper = itemMapper } private val currentProtoItems = mutableListOf<Item>() private val _itemHolders = MutableLiveData<List<ListItemHolder>>() val itemHolders: LiveData<List<ListItemHolder>> = _itemHolders private val _liveNextUrl = MutableLiveData<String>() val liveNextUrl: LiveData<String> = _liveNextUrl private var _nextPageUrl: String? = null private val gson = Gson() private var responseClass: Class<T>? = null private val _refreshState = MutableLiveData<RefreshState>() val refreshState: LiveData<RefreshState> = _refreshState open suspend fun refreshData(hint: RefreshHint) { _refreshState.value = RefreshState.LOADING(refreshHint = hint) try { if (hint == RefreshHint.ErrorRetry) { delay(300L) } val response = withContext(Dispatchers.IO) { dataFetcher() } currentProtoItems.clear() responseClass = response::class.java as Class<T> _nextPageUrl = response.nextPageUrl _liveNextUrl.value = response.nextPageUrl currentProtoItems.addAll(response.displayList) mapProtoItemsToHolders() _refreshState.value = RefreshState.LOADED( hasContent = _itemHolders.value?.isNotEmpty() == true, hasNext = _nextPageUrl?.isNotEmpty() == true ) } catch (ex: Exception) { _refreshState.value = RefreshState.ERROR(ex) ex.printStackTrace() } } open suspend fun loadMoreData() { val nextPageUrl = _nextPageUrl ?: return _refreshState.value = RefreshState.LOADING(refreshHint = RefreshHint.LoadMore) try { val response = withContext(Dispatchers.IO) { val responseBody = Client.appApi.generalGet(nextPageUrl) val responseJson = responseBody.string() gson.fromJson(responseJson, responseClass) } _nextPageUrl = response.nextPageUrl _liveNextUrl.value = response.nextPageUrl if (response.displayList.isNotEmpty()) { currentProtoItems.addAll(response.displayList) mapProtoItemsToHolders() } _refreshState.value = RefreshState.LOADED( hasContent = _itemHolders.value?.isNotEmpty() == true, hasNext = _nextPageUrl?.isNotEmpty() == true ) } catch (ex: Exception) { _refreshState.value = RefreshState.ERROR(ex) ex.printStackTrace() } } private fun updateOffsetInUrl(url: String, newOffset: Int): String { val regex = """(offset=)(\d+)""".toRegex() return if (regex.containsMatchIn(url)) { // 替换现有的 offset 参数 regex.replace(url) { matchResult -> "${matchResult.groupValues[1]}$newOffset" } } else { // 如果 URL 中没有 offset 参数,直接添加它 if (url.contains("?")) { "$url&offset=$newOffset" } else { "$url?offset=$newOffset" } } } suspend fun loadOffsetData(pageIndex: Int) { val nextPageUrl = _nextPageUrl ?: return Common.showLog("dasasds aaa ${nextPageUrl}") val newNextUrl = updateOffsetInUrl(nextPageUrl, pageIndex * 30) _nextPageUrl = newNextUrl _liveNextUrl.value = newNextUrl currentProtoItems.clear() Common.showLog("dasasds bbb ${newNextUrl}") loadMoreData() } private fun mapProtoItemsToHolders() { val mapper = _variableItemMapper ?: return val holders = currentProtoItems .filter { item -> filter(item) } .flatMap(mapper) _itemHolders.value = holders } fun pickProtoItems(): List<Item> { return currentProtoItems } fun updateMapper(mapper: (Item) -> List<ListItemHolder>) { _itemHolders.value = listOf() this._variableItemMapper = mapper mapProtoItemsToHolders() } protected fun pickItemHolders(): MutableLiveData<List<ListItemHolder>> { return _itemHolders } open fun initialLoad(): Boolean { return true } }
99
Java
188
4,490
ee2afee674fb4c8a2871970427cf81bb8362292f
5,017
Pixiv-Shaft
MIT License
src/main/java/com/tianyisoft/database/grammar/MysqlGrammar.kt
tianyirenjian
512,697,155
false
null
package com.tianyisoft.database.grammar import com.tianyisoft.database.Builder class MysqlGrammar: Grammar() { override val operators = listOf<String>("sounds like") override fun compileInsertOrIgnore(builder: Builder, values: List<Map<String, Any?>>): String { return compileInsert(builder, values).replaceFirst("insert", "insert ignore") } override fun compileUpsert( builder: Builder, values: List<Map<String, Any?>>, update: Map<String, Any?>, uniqueBy: List<String> ): String { val sql = compileInsert(builder, values) + " on duplicate key update " val columns = update.map { "${wrap(it.key)} = ${parameter(it.value)}" }.joinToString() return sql + columns } override fun compileRandom(seed: String): String { return "rand($seed)" } }
0
Kotlin
0
1
af5f19b7277a9c482a402c8c837c0719986fdbd8
869
querybuilder
Apache License 2.0
twitter-clone/app/src/main/java/io/github/vnicius/twitterclone/ui/common/fragments/LoaderFragment.kt
Vnicius
200,317,783
false
null
package io.github.vnicius.twitterclone.ui.common.fragments import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import io.github.vnicius.twitterclone.R /** * [Fragment] to show the loader animation */ class LoaderFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_loader, container, false) } companion object { @JvmStatic fun newInstance() = LoaderFragment() } }
1
Kotlin
0
3
fac5e8cacf4d6e11f711121ca7c1dd3ac44f2d03
720
twitter-clone-android
MIT License
app/src/main/java/org/wikipedia/suggestededits/provider/EditingSuggestionsProvider.kt
dbrant
28,157,306
true
{"Java": 2472470, "Kotlin": 315335, "Python": 20806, "Shell": 1800, "HTML": 1233}
package org.wikipedia.suggestededits.provider import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.schedulers.Schedulers import org.wikipedia.WikipediaApp import org.wikipedia.dataclient.Service import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.dataclient.WikiSite import org.wikipedia.dataclient.mwapi.MwQueryPage import org.wikipedia.dataclient.page.PageSummary import org.wikipedia.dataclient.restbase.ImageRecommendationResponse import org.wikipedia.page.PageTitle import org.wikipedia.settings.Prefs import java.io.BufferedReader import java.io.InputStreamReader import java.util.* import java.util.concurrent.Semaphore import kotlin.collections.ArrayList import kotlin.random.Random object EditingSuggestionsProvider { private val mutex: Semaphore = Semaphore(1) private val articlesWithMissingDescriptionCache: Stack<String> = Stack() private var articlesWithMissingDescriptionCacheLang: String = "" private val articlesWithTranslatableDescriptionCache: Stack<Pair<PageTitle, PageTitle>> = Stack() private var articlesWithTranslatableDescriptionCacheFromLang: String = "" private var articlesWithTranslatableDescriptionCacheToLang: String = "" private val imagesWithMissingCaptionsCache: Stack<String> = Stack() private var imagesWithMissingCaptionsCacheLang: String = "" private val imagesWithTranslatableCaptionCache: Stack<Pair<String, String>> = Stack() private var imagesWithTranslatableCaptionCacheFromLang: String = "" private var imagesWithTranslatableCaptionCacheToLang: String = "" private val imagesWithMissingTagsCache: Stack<MwQueryPage> = Stack() private val articlesWithMissingImagesCache = mutableListOf<String>() private var articlesWithMissingImagesCacheLang: String = "" private const val MAX_RETRY_LIMIT: Long = 50 fun getNextArticleWithMissingDescription(wiki: WikiSite, retryLimit: Long = MAX_RETRY_LIMIT): Observable<PageSummary> { return Observable.fromCallable { mutex.acquire() }.flatMap { var cachedTitle = "" if (articlesWithMissingDescriptionCacheLang != wiki.languageCode()) { // evict the cache if the language has changed. articlesWithMissingDescriptionCache.clear() } if (!articlesWithMissingDescriptionCache.empty()) { cachedTitle = articlesWithMissingDescriptionCache.pop() } if (cachedTitle.isNotEmpty()) { Observable.just(cachedTitle) } else { ServiceFactory.getRest(WikiSite(Service.WIKIDATA_URL)).getArticlesWithoutDescriptions(WikiSite.normalizeLanguageCode(wiki.languageCode())) .flatMap { pages -> val titleList = ArrayList<String>() pages.forEach { titleList.add(it.title()) } ServiceFactory.get(wiki).getDescription(titleList.joinToString("|")).subscribeOn(Schedulers.io()) } .map { pages -> var title: String? = null articlesWithMissingDescriptionCacheLang = wiki.languageCode() pages.query()!!.pages()!!.forEach { if (it.description().isNullOrEmpty()) { articlesWithMissingDescriptionCache.push(it.title()) } } if (!articlesWithMissingDescriptionCache.empty()) { title = articlesWithMissingDescriptionCache.pop() } if (title == null) { throw ListEmptyException() } title } .retry(retryLimit) { t: Throwable -> t is ListEmptyException } } }.flatMap { title -> ServiceFactory.getRest(wiki).getSummary(null, title) } .doFinally { mutex.release() } } fun getNextArticleWithMissingDescription(sourceWiki: WikiSite, targetLang: String, sourceLangMustExist: Boolean, retryLimit: Long = MAX_RETRY_LIMIT): Observable<Pair<PageSummary, PageSummary>> { return Observable.fromCallable { mutex.acquire() }.flatMap { val targetWiki = WikiSite.forLanguageCode(targetLang) var cachedPair: Pair<PageTitle, PageTitle>? = null if (articlesWithTranslatableDescriptionCacheFromLang != sourceWiki.languageCode() || articlesWithTranslatableDescriptionCacheToLang != targetLang) { // evict the cache if the language has changed. articlesWithTranslatableDescriptionCache.clear() } if (!articlesWithTranslatableDescriptionCache.empty()) { cachedPair = articlesWithTranslatableDescriptionCache.pop() } if (cachedPair != null) { Observable.just(cachedPair) } else { ServiceFactory.getRest(WikiSite(Service.WIKIDATA_URL)).getArticlesWithTranslatableDescriptions(WikiSite.normalizeLanguageCode(sourceWiki.languageCode()), WikiSite.normalizeLanguageCode(targetLang)) .flatMap({ pages -> if (pages.isEmpty()) { throw ListEmptyException() } val titleList = ArrayList<String>() pages.forEach { titleList.add(it.title()) } ServiceFactory.get(WikiSite.forLanguageCode(targetLang)).getDescription(titleList.joinToString("|")) }, { pages, response -> Pair(pages, response) }) .map { pair -> val pages = pair.first val mwPages = pair.second.query()!!.pages()!! var targetAndSourcePageTitles: Pair<PageTitle, PageTitle>? = null articlesWithTranslatableDescriptionCacheFromLang = sourceWiki.languageCode() articlesWithTranslatableDescriptionCacheToLang = targetLang for (page in pages) { val mwPage = mwPages.find { it.title() == page.title() } if (mwPage != null && !mwPage.description().isNullOrEmpty()) { continue } val entity = page.entity if (entity == null || entity.descriptions().containsKey(targetLang) || sourceLangMustExist && !entity.descriptions().containsKey(sourceWiki.languageCode()) || !entity.sitelinks().containsKey(sourceWiki.dbName()) || !entity.sitelinks().containsKey(targetWiki.dbName())) { continue } val sourceTitle = PageTitle(entity.sitelinks()[sourceWiki.dbName()]!!.title, sourceWiki) sourceTitle.description = entity.descriptions()[sourceWiki.languageCode()]?.value() articlesWithTranslatableDescriptionCache.push(PageTitle(entity.sitelinks()[targetWiki.dbName()]!!.title, targetWiki) to sourceTitle) } if (!articlesWithTranslatableDescriptionCache.empty()) { targetAndSourcePageTitles = articlesWithTranslatableDescriptionCache.pop() } if (targetAndSourcePageTitles == null) { throw ListEmptyException() } targetAndSourcePageTitles } .retry(retryLimit) { t: Throwable -> t is ListEmptyException } } }.flatMap { getSummary(it) } .doFinally { mutex.release() } } private fun getSummary(targetAndSourcePageTitles: Pair<PageTitle, PageTitle>): Observable<Pair<PageSummary, PageSummary>> { return Observable.zip(ServiceFactory.getRest(targetAndSourcePageTitles.first.wikiSite).getSummary(null, targetAndSourcePageTitles.first.prefixedText), ServiceFactory.getRest(targetAndSourcePageTitles.second.wikiSite).getSummary(null, targetAndSourcePageTitles.second.prefixedText), { target, source -> if (target.description.isNullOrEmpty()) { target.description = targetAndSourcePageTitles.first.description } Pair(source, target) }) } fun getNextImageWithMissingCaption(lang: String, retryLimit: Long = MAX_RETRY_LIMIT): Observable<String> { return Observable.fromCallable { mutex.acquire() }.flatMap { var cachedTitle: String? = null if (imagesWithMissingCaptionsCacheLang != lang) { // evict the cache if the language has changed. imagesWithMissingCaptionsCache.clear() } if (!imagesWithMissingCaptionsCache.empty()) { cachedTitle = imagesWithMissingCaptionsCache.pop() } if (cachedTitle != null) { Observable.just(cachedTitle) } else { ServiceFactory.getRest(WikiSite(Service.COMMONS_URL)).getImagesWithoutCaptions(WikiSite.normalizeLanguageCode(lang)) .map { pages -> imagesWithMissingCaptionsCacheLang = lang pages.forEach { imagesWithMissingCaptionsCache.push(it.title()) } var item: String? = null if (!imagesWithMissingCaptionsCache.empty()) { item = imagesWithMissingCaptionsCache.pop() } if (item == null) { throw ListEmptyException() } item } .retry(retryLimit) { t: Throwable -> t is ListEmptyException } } }.doFinally { mutex.release() } } fun getNextImageWithMissingCaption(sourceLang: String, targetLang: String, retryLimit: Long = MAX_RETRY_LIMIT): Observable<Pair<String, String>> { return Observable.fromCallable { mutex.acquire() }.flatMap { var cachedPair: Pair<String, String>? = null if (imagesWithTranslatableCaptionCacheFromLang != sourceLang || imagesWithTranslatableCaptionCacheToLang != targetLang) { // evict the cache if the language has changed. imagesWithTranslatableCaptionCache.clear() } if (!imagesWithTranslatableCaptionCache.empty()) { cachedPair = imagesWithTranslatableCaptionCache.pop() } if (cachedPair != null) { Observable.just(cachedPair) } else { ServiceFactory.getRest(WikiSite(Service.COMMONS_URL)).getImagesWithTranslatableCaptions(WikiSite.normalizeLanguageCode(sourceLang), WikiSite.normalizeLanguageCode(targetLang)) .map { pages -> imagesWithTranslatableCaptionCacheFromLang = sourceLang imagesWithTranslatableCaptionCacheToLang = targetLang var item: Pair<String, String>? = null for (page in pages) { if (!page.captions.containsKey(sourceLang) || page.captions.containsKey(targetLang)) { continue } imagesWithTranslatableCaptionCache.push((page.captions[sourceLang] ?: error("")) to page.title()) } if (!imagesWithTranslatableCaptionCache.empty()) { item = imagesWithTranslatableCaptionCache.pop() } if (item == null) { throw ListEmptyException() } item } .retry(retryLimit) { t: Throwable -> t is ListEmptyException } } }.doFinally { mutex.release() } } fun getNextImageWithMissingTags(retryLimit: Long = MAX_RETRY_LIMIT): Observable<MwQueryPage> { return Observable.fromCallable { mutex.acquire() }.flatMap { var cachedItem: MwQueryPage? = null if (!imagesWithMissingTagsCache.empty()) { cachedItem = imagesWithMissingTagsCache.pop() } if (cachedItem != null) { Observable.just(cachedItem) } else { ServiceFactory.get(WikiSite(Service.COMMONS_URL)).randomWithImageInfo .map { response -> for (page in response.query()!!.pages()!!) { if (page.imageInfo()!!.mimeType != "image/jpeg") { continue } if (page.revisions().none { "P180" in it.getContentFromSlot("mediainfo") }) { imagesWithMissingTagsCache.push(page) } } var item: MwQueryPage? = null if (!imagesWithMissingTagsCache.empty()) { item = imagesWithMissingTagsCache.pop() } if (item == null) { throw ListEmptyException() } item } .retry(retryLimit) { t: Throwable -> t is ListEmptyException } } }.doFinally { mutex.release() } } fun getNextArticleWithMissingImage(lang: String, sequence: Int): Observable<ImageRecommendationResponse> { return Observable.fromCallable { mutex.acquire() }.flatMap { var cachedItem: ImageRecommendationResponse? = null if (articlesWithMissingImagesCacheLang != lang) { // evict the cache if the language has changed. articlesWithMissingImagesCache.clear() } val installIdMod = 500 val installId = Prefs.getAppInstallId().orEmpty() // Initialize the random number generator based on the user's install ID, modulo the // total size of the expected test group. val random = Random(installId.substring(installId.length - 4).toInt(16) % installIdMod) var seqOffset = 0 // and seek to the appropriate position in the random sequence. for (i in 0..sequence) { seqOffset = random.nextInt(Int.MAX_VALUE) } articlesWithMissingImagesCacheLang = lang if (articlesWithMissingImagesCache.isNotEmpty()) { cachedItem = buildImageRecommendation(articlesWithMissingImagesCache[seqOffset % articlesWithMissingImagesCache.size]) } if (cachedItem != null) { Observable.just(cachedItem) } else { val stream = WikipediaApp.getInstance().assets.open("imagerecs/" + lang + "wiki_image_candidates.tsv") val reader = BufferedReader(InputStreamReader(stream)) while (true) { val line = reader.readLine() if (line.isNullOrEmpty()) { break } articlesWithMissingImagesCache.add(line) } var item: ImageRecommendationResponse? = null if (articlesWithMissingImagesCache.isNotEmpty()) { item = buildImageRecommendation(articlesWithMissingImagesCache[seqOffset % articlesWithMissingImagesCache.size]) } Observable.just(item!!) } }.doFinally { mutex.release() } } private fun buildImageRecommendation(str: String): ImageRecommendationResponse { val arr = str.split('\t') return ImageRecommendationResponse(arr[0].toInt(), arr[1], arr[2].split(",").toList()) } class ListEmptyException : RuntimeException() }
0
Java
0
2
33d4c162b0847ef4814d9ae7a6229d4877d8eb80
16,937
apps-android-wikipedia
Apache License 2.0
app/src/main/java/com/ucsm/tylersai/amsucsm/adapters/NotiListViewAdapter.kt
hanlinag
290,553,252
false
null
package com.ucsm.tylersai.amsucsm.adapters import android.content.Context import android.content.Intent import android.database.DataSetObserver import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ListAdapter import android.widget.TextView import androidx.core.content.ContextCompat.startActivity import com.ucsm.tylersai.amsucsm.NotiDetailActivity import com.ucsm.tylersai.amsucsm.R import com.ucsm.tylersai.amsucsm.models.Notifications class NotiListViewAdapter(context: Context, arrayList: ArrayList<Notifications>) : ListAdapter { var context: Context? = context var arrayList: ArrayList<Notifications>? = arrayList override fun isEmpty(): Boolean { return false } override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { var noti: Notifications = arrayList!!.get(position) var inflater = LayoutInflater.from(context) var rowView = inflater.inflate(R.layout.view_noti_row_item, null, true) var titleTv = rowView.findViewById<TextView>(R.id.noti_title) var messageTv = rowView.findViewById<TextView>(R.id.noti_body) var dateTv = rowView.findViewById<TextView>(R.id.noti_date) titleTv.text = noti.title messageTv.text = noti.body dateTv.text = noti.date rowView.setOnClickListener { val title = arrayList!!.get(position).title val body = arrayList!!.get(position).body val date = arrayList!!.get(position).date // Toast.makeText(rowView.context, "Hello $text ", Toast.LENGTH_LONG).show() val intent = Intent(rowView.context, NotiDetailActivity::class.java) intent.putExtra("title", title) intent.putExtra("body", body) intent.putExtra("date", date) startActivity(rowView.context, intent, null) } return rowView } override fun registerDataSetObserver(p0: DataSetObserver?) { } override fun getItemViewType(position: Int): Int { return position } override fun getItem(position: Int): Any { return position } override fun getViewTypeCount(): Int { return arrayList!!.size } override fun isEnabled(p0: Int): Boolean { return true } override fun getItemId(position: Int): Long { return position.toLong() } override fun hasStableIds(): Boolean { return false } override fun areAllItemsEnabled(): Boolean { return false } override fun unregisterDataSetObserver(p0: DataSetObserver?) { } override fun getCount(): Int { return arrayList!!.size } }
0
Kotlin
3
5
473407e66ede82a189c759b0ec1fb51696e93683
2,744
ams-student
MIT License
packages/patrol/android/src/main/kotlin/pl/leancode/patrol/contracts/WaitUntilVisibleRequestKt.kt
leancodepl
496,206,645
false
null
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: contracts.proto // Generated files should ignore deprecation warnings @file:Suppress("DEPRECATION") package pl.leancode.patrol.contracts; @kotlin.jvm.JvmName("-initializewaitUntilVisibleRequest") public inline fun waitUntilVisibleRequest(block: pl.leancode.patrol.contracts.WaitUntilVisibleRequestKt.Dsl.() -> kotlin.Unit): pl.leancode.patrol.contracts.Contracts.WaitUntilVisibleRequest = pl.leancode.patrol.contracts.WaitUntilVisibleRequestKt.Dsl._create(pl.leancode.patrol.contracts.Contracts.WaitUntilVisibleRequest.newBuilder()).apply { block() }._build() /** * Protobuf type `patrol.WaitUntilVisibleRequest` */ public object WaitUntilVisibleRequestKt { @kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class) @com.google.protobuf.kotlin.ProtoDslMarker public class Dsl private constructor( private val _builder: pl.leancode.patrol.contracts.Contracts.WaitUntilVisibleRequest.Builder ) { public companion object { @kotlin.jvm.JvmSynthetic @kotlin.PublishedApi internal fun _create(builder: pl.leancode.patrol.contracts.Contracts.WaitUntilVisibleRequest.Builder): Dsl = Dsl(builder) } @kotlin.jvm.JvmSynthetic @kotlin.PublishedApi internal fun _build(): pl.leancode.patrol.contracts.Contracts.WaitUntilVisibleRequest = _builder.build() /** * `.patrol.Selector selector = 1;` */ public var selector: pl.leancode.patrol.contracts.Contracts.Selector @JvmName("getSelector") get() = _builder.getSelector() @JvmName("setSelector") set(value) { _builder.setSelector(value) } /** * `.patrol.Selector selector = 1;` */ public fun clearSelector() { _builder.clearSelector() } /** * `.patrol.Selector selector = 1;` * @return Whether the selector field is set. */ public fun hasSelector(): kotlin.Boolean { return _builder.hasSelector() } /** * `string appId = 2;` */ public var appId: kotlin.String @JvmName("getAppId") get() = _builder.getAppId() @JvmName("setAppId") set(value) { _builder.setAppId(value) } /** * `string appId = 2;` */ public fun clearAppId() { _builder.clearAppId() } } } public inline fun pl.leancode.patrol.contracts.Contracts.WaitUntilVisibleRequest.copy(block: pl.leancode.patrol.contracts.WaitUntilVisibleRequestKt.Dsl.() -> kotlin.Unit): pl.leancode.patrol.contracts.Contracts.WaitUntilVisibleRequest = pl.leancode.patrol.contracts.WaitUntilVisibleRequestKt.Dsl._create(this.toBuilder()).apply { block() }._build() public val pl.leancode.patrol.contracts.Contracts.WaitUntilVisibleRequestOrBuilder.selectorOrNull: pl.leancode.patrol.contracts.Contracts.Selector? get() = if (hasSelector()) getSelector() else null
177
null
62
515
b2872ec307a95b81b0e0b81e048dafb73770cccd
2,896
patrol
Apache License 2.0
library/src/main/java/de/tobiasschuerg/weekview/data/EventCreator.kt
Bobinho44
588,772,073
false
null
package de.tobiasschuerg.weekview.data import android.annotation.SuppressLint import android.graphics.Color import android.os.Build import android.widget.TextView import androidx.annotation.RequiresApi import de.tobiasschuerg.weekview.util.TimeSpan import org.jsoup.Jsoup import org.jsoup.nodes.Document import org.jsoup.parser.Parser import org.threeten.bp.DayOfWeek import org.threeten.bp.LocalDate import org.threeten.bp.LocalTime import java.util.* object EventCreator { private const val url = "https://edt.univ-nantes.fr/sciences/g351176.xml" private val doc: Document = Jsoup.connect(url).parser(Parser.xmlParser()).get() private val random = Random() private fun cleanRoomName(room: String) : String { return room .removePrefix("visio ") .removePrefix("salle ") .removePrefix("sa ") .replace("-(.*?)\\(".toRegex(), " (") .replace("-.*?\\)".toRegex(), ")") .replace("/(.*?)\\(".toRegex(), ")") } @SuppressLint("SetTextI18n") @RequiresApi(Build.VERSION_CODES.O) fun daysData(days: List<LocalDate>, textView: TextView): List<Event.Single> { return days .flatMap { date -> val firstWeekDay = date.minusDays(date.dayOfWeek.value - 1L) val week = doc.select("span") .filter { it -> val dateInformation = it.attr("date").split("/") LocalDate.of( dateInformation[2].toInt(), dateInformation[1].toInt(), dateInformation[0].toInt() ).equals(firstWeekDay) } .map { if (date == days[0]) { textView.text = "Semaine " + it.select("title").text() } it.select("alleventweeks").text() } .first() val excludeModules = listOf("X1LI010", "X2I4010", "X2I4020", "X2I5010", "X2I5020") val warningClass = listOf("Gr", "gr", "groupe", "Groupe") doc.select("event") .filter { it -> it.select("rawweeks").text() == week } .filter { it.select("day").text().toInt() + 1 == date.dayOfWeek.value } .filter { excludeModules.stream().noneMatch { w -> it.select("module").text().contains(w)}} .map { val name = it.select("module").text().split("(")[1].replace(")", "") val subTitle = cleanRoomName(it.select("room").text()) val day = DayOfWeek.of((1 + days.indexOf(date))) //val staff = element.select("staff").text() val startTimeInt = it.select("starttime").text().split(":").map { a -> a.toInt() } val endTimeInt = it.select("endtime").text().split(":").map { a -> a.toInt() } var color = Color.parseColor("#" + it.attr("colour")) if (warningClass.stream().anyMatch {w -> it.select("notes").text().contains(w)} ) { color = Color.rgb(255, 165, 0) } val startTime = LocalTime.of(startTimeInt[0], startTimeInt[1]) val endTime = LocalTime.of(endTimeInt[0], endTimeInt[1]) createEntry(name, subTitle, day, startTime, endTime, color) } } .toList() } @RequiresApi(Build.VERSION_CODES.O) private fun createEntry(name: String, subTitle: String, day: DayOfWeek, startTime: LocalTime, endTime: LocalTime, color: Int): Event.Single { return Event.Single( id = random.nextLong(), date = LocalDate.now().with(day), title = name, shortTitle = name, timeSpan = TimeSpan(startTime, endTime), lowerText = subTitle, textColor = Color.BLACK, backgroundColor = color ) } }
0
Kotlin
0
0
300cbdd843d7ce6295bb5c65775306aa209e4be4
4,212
BTimetable
MIT License
sample/composeApp/src/commonMain/kotlin/com/arjunjadeja/texty/design_system/properties/AppFonts.kt
ArjunJadeja
856,742,242
false
{"Kotlin": 112862}
package com.arjunjadeja.texty.design_system.properties import androidx.compose.runtime.Composable import androidx.compose.ui.text.font.FontFamily import org.jetbrains.compose.resources.Font import texty.sample.composeapp.generated.resources.Res import texty.sample.composeapp.generated.resources.indie_flower_regular import texty.sample.composeapp.generated.resources.inter_variable import texty.sample.composeapp.generated.resources.inter_variable_italic @Composable fun InterFont() = FontFamily(Font(Res.font.inter_variable)) @Composable fun InterFontItalic() = FontFamily(Font(Res.font.inter_variable_italic)) @Composable fun JetbrainsMonoFont() = FontFamily(Font(Res.font.inter_variable)) @Composable fun JetbrainsMonoFontItalic() = FontFamily(Font(Res.font.inter_variable_italic)) @Composable fun IndieFlowerFont() = FontFamily(Font(Res.font.indie_flower_regular))
3
Kotlin
3
50
6c95fa3c63898620cbec73ba99238c4832335740
876
texty
Apache License 2.0
src/main/kotlin/com/demonwav/mcdev/error/ErrorReporter.kt
thiakil
111,409,916
false
null
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2017 minecraft-dev * * MIT License */ package com.demonwav.mcdev.error import com.intellij.diagnostic.IdeErrorsDialog import com.intellij.diagnostic.LogMessageEx import com.intellij.diagnostic.ReportMessages import com.intellij.errorreport.bean.ErrorBean import com.intellij.ide.DataManager import com.intellij.ide.plugins.PluginManager import com.intellij.idea.IdeaLogger import com.intellij.notification.NotificationListener import com.intellij.notification.NotificationType import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.ex.ApplicationInfoEx import com.intellij.openapi.diagnostic.ErrorReportSubmitter import com.intellij.openapi.diagnostic.IdeaLoggingEvent import com.intellij.openapi.diagnostic.SubmittedReportInfo import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.util.Consumer import java.awt.Component class ErrorReporter : ErrorReportSubmitter() { val baseUrl = "https://github.com/minecraft-dev/MinecraftDev/issues" override fun getReportActionText() = "Report to Minecraft Dev GitHub Issue Tracker" override fun submit(events: Array<out IdeaLoggingEvent>, additionalInfo: String?, parentComponent: Component, consumer: Consumer<SubmittedReportInfo>): Boolean { val event = events[0] val bean = ErrorBean(event.throwable, IdeaLogger.ourLastActionId) val dataContext = DataManager.getInstance().getDataContext(parentComponent) bean.description = additionalInfo bean.message = event.message val throwable = event.throwable if (throwable != null) { val pluginId = IdeErrorsDialog.findPluginId(throwable) if (pluginId != null) { val ideaPluginDescriptor = PluginManager.getPlugin(pluginId) if (ideaPluginDescriptor != null && !ideaPluginDescriptor.isBundled) { bean.pluginName = ideaPluginDescriptor.name bean.pluginVersion = ideaPluginDescriptor.version } } } val data = event.data if (data is LogMessageEx) { bean.attachments = data.includedAttachments } val reportValues = IdeaITNProxy.getKeyValuePairs(bean, ApplicationInfoEx.getInstanceEx(), ApplicationNamesInfo.getInstance()) val project = CommonDataKeys.PROJECT.getData(dataContext) val task = AnonymousFeedbackTask(project, "Submitting error report", true, reportValues, { token -> val url = "$baseUrl/$token" val reportInfo = SubmittedReportInfo(url, "Issue #$token", SubmittedReportInfo.SubmissionStatus.NEW_ISSUE) consumer.consume(reportInfo) val message = "<html>Created Issue #$token successfully.<br>" + "<a href=\"$url\">View issue.</a></html>" ReportMessages.GROUP.createNotification( ReportMessages.ERROR_REPORT, message, NotificationType.INFORMATION, NotificationListener.URL_OPENING_LISTENER ).setImportant(false).notify(project) }, { e -> val message = "<html>Error Submitting Issue: ${e.message}<br>Consider opening an issue on " + "<a href=\"$baseUrl\">the GitHub issue tracker.</a></html>" ReportMessages.GROUP.createNotification( ReportMessages.ERROR_REPORT, message, NotificationType.ERROR, NotificationListener.URL_OPENING_LISTENER ).setImportant(false).notify(project) }) if (project == null) { task.run(EmptyProgressIndicator()) } else { ProgressManager.getInstance().run(task) } return true } }
1
Kotlin
1
1
9b91deed668fce98cd21474b9135ec9b92212c2b
4,052
MinecraftDev
MIT License
arc-agents/src/test/kotlin/dsl/AgentSystemPromptTest.kt
lmos-ai
790,083,697
false
null
// SPDX-FileCopyrightText: 2024 Deutsche Telekom AG // // SPDX-License-Identifier: Apache-2.0 package io.github.lmos.arc.agents.dsl import io.github.lmos.arc.agents.ChatAgent import io.github.lmos.arc.agents.TestBase import kotlinx.coroutines.runBlocking import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class AgentSystemPromptTest : TestBase() { @Test fun `test SystemPrompt output`(): Unit = runBlocking { val agent = agent { name = "" description = "" systemPrompt = { +"""first""" if (false) +"error" if (true) +"second" """third""" } } val (input, _) = executeAgent(agent as ChatAgent, "bad stuff here") assertThat(input.first().content).isEqualTo("firstsecondthird") } @Test fun `test SystemPrompt has access to context beans`(): Unit = runBlocking { val testString = "testString" val agent = agent { name = "" description = "" systemPrompt = { get<String>() } } testBeanProvider.setContext(setOf(testString)) { val (input, _) = executeAgent(agent as ChatAgent, "bad stuff here") assertThat(input.first().content).isEqualTo("testString") } } }
7
null
3
56
680603e0ef25432e59b36431a77bea5c2b1b8fda
1,386
arc
Apache License 2.0
arc-agents/src/test/kotlin/dsl/AgentSystemPromptTest.kt
lmos-ai
790,083,697
false
null
// SPDX-FileCopyrightText: 2024 Deutsche Telekom AG // // SPDX-License-Identifier: Apache-2.0 package io.github.lmos.arc.agents.dsl import io.github.lmos.arc.agents.ChatAgent import io.github.lmos.arc.agents.TestBase import kotlinx.coroutines.runBlocking import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class AgentSystemPromptTest : TestBase() { @Test fun `test SystemPrompt output`(): Unit = runBlocking { val agent = agent { name = "" description = "" systemPrompt = { +"""first""" if (false) +"error" if (true) +"second" """third""" } } val (input, _) = executeAgent(agent as ChatAgent, "bad stuff here") assertThat(input.first().content).isEqualTo("firstsecondthird") } @Test fun `test SystemPrompt has access to context beans`(): Unit = runBlocking { val testString = "testString" val agent = agent { name = "" description = "" systemPrompt = { get<String>() } } testBeanProvider.setContext(setOf(testString)) { val (input, _) = executeAgent(agent as ChatAgent, "bad stuff here") assertThat(input.first().content).isEqualTo("testString") } } }
7
null
3
56
680603e0ef25432e59b36431a77bea5c2b1b8fda
1,386
arc
Apache License 2.0
schema-kenerator-core/src/main/kotlin/io/github/smiley4/schemakenerator/core/data/TypeId.kt
SMILEY4
729,430,513
false
{"Kotlin": 808327}
package io.github.smiley4.schemakenerator.core.data import kotlin.math.abs import kotlin.random.Random /** * Identifier of a type */ class TypeId( /** * the base name (e.g. the qualified class-name */ val base: String, /** * ids of type parameters, i.e. generics (order is relevant) */ val typeParameters: List<TypeId>, /** * optional (random) additional id to avoid collisions */ val additionalId: String? ) { companion object { /** * @return id for a wildcard type */ fun wildcard() = TypeId("*", emptyList(), null) /** * @param name the (qualified) name of the type * @return id with the given name */ fun build(name: String) = TypeId(name, emptyList(), null) /** * @param name the (qualified) name of the type * @param typeParameters the list of ids of the type parameters * @param withAdditionalId whether set the [TypeId.additionalId] to a random value * @return id with the given name and type parameters */ fun build(name: String, typeParameters: List<TypeId>, withAdditionalId: Boolean = false) = TypeId(name, typeParameters, if (withAdditionalId) abs(Random.nextLong()).toString() else null) /** * @param fullTypeId id of a type as a formatted string, i.e. the output of [TypeId.full] * @return a id with the data from the given string */ fun parse(fullTypeId: String): TypeId { return TypeId( base = parseBase(fullTypeId), typeParameters = parseTypeParameters(fullTypeId), additionalId = parseAdditionalId(fullTypeId) ) } private fun parseBase(fullTypeId: String): String { return fullTypeId .let { if (it.contains("<")) { it.split("<").first() } else { it } } .let { if (it.contains("#")) { it.split("#") .toMutableList().also { parts -> parts.removeLast() } .joinToString("#") } else { it } } } private fun parseTypeParameters(fullTypeId: String): List<TypeId> { if (!fullTypeId.contains("<") || !fullTypeId.contains(">")) { return emptyList() } val paramList = fullTypeId .split("<") .toMutableList().also { it.removeFirst() } .joinToString("<") .let { if (it.contains("#")) { it .split("#") .toMutableList() .also { l -> l.removeLast() } .joinToString("#") } else { it } } .let { it.substring(0, it.length - 1) } val paramFullIds = mutableListOf<String>() var current = "" var nestedLevel = 0 paramList.toCharArray().forEach { c -> when (c) { ',' -> if (nestedLevel == 0) { paramFullIds.add(current) current = "" } else { current += c } '<' -> { nestedLevel++ current += c } '>' -> { nestedLevel-- current += c } else -> current += c } } paramFullIds.add(current) return paramFullIds.map { parse(it) } } private fun parseAdditionalId(fullTypeId: String): String? { return if (fullTypeId.contains("#")) { fullTypeId.split("#").last() } else { null } } } /** * @return this id as a formatted string containing all information */ fun full(): String { return base .let { if (typeParameters.isNotEmpty()) { it + "<" + typeParameters.joinToString(",") { p -> p.full() } + ">" } else { it } } .let { if (additionalId != null) { "$it#$additionalId" } else { it } } } /** * @return this id as a simpler, shorter formatted string */ fun simple(): String { var title = base.split(".").last() if (typeParameters.isNotEmpty()) { title = title + "<" + typeParameters.joinToString(",") { it.simple() } + ">" } if (additionalId != null) { title = "$title#$additionalId" } return title } override fun equals(other: Any?): Boolean { if (other !is TypeId) return false if (base != other.base) return false if (additionalId != other.additionalId) return false if (typeParameters.size != other.typeParameters.size) return false if (typeParameters.zip(other.typeParameters).any { (a, b) -> a != b }) return false return true } override fun hashCode(): Int { var result = base.hashCode() result = 31 * result + typeParameters.hashCode() result = 31 * result + (additionalId?.hashCode() ?: 0) return result } }
6
Kotlin
4
9
28f02706ccdfba235654c33738001ab98588c015
5,882
schema-kenerator
Apache License 2.0
app/src/main/java/com/sonphil/canadarecallsandsafetyalerts/receiver/NotificationActionReceiver.kt
Sonphil
237,512,399
false
null
package com.sonphil.canadarecallsandsafetyalerts.receiver import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import com.sonphil.canadarecallsandsafetyalerts.presentation.recall.details.RecallDetailsActivityArgs import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject /** * Created by Sonphil on 26-02-20. */ @AndroidEntryPoint class NotificationActionReceiver : BroadcastReceiver() { @Inject lateinit var notificationActionHandler: NotificationActionHandler override fun onReceive(context: Context, intent: Intent) { val action = intent.action val recall = intent.extras?.run { RecallDetailsActivityArgs.fromBundle(this).recall } notificationActionHandler.handleRecallAction(context, recall, action) } }
0
Kotlin
0
1
7c7e02702861ce87c5a058a05acfcc61cb8f78f6
839
CanadaRecallsAndSafetyAlerts
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/OddEvenList.kt
ashtanko
203,993,092
false
null
/* * Copyright 2022 Oleksii Shtanko * * 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 dev.shtanko.algorithms.leetcode /** * 328. Odd Even Linked List * @see <a href="https://leetcode.com/problems/odd-even-linked-list/description/">leetcode page</a> */ interface OddEvenList { fun perform(head: ListNode): ListNode } class OddEvenListImpl : OddEvenList { override fun perform(head: ListNode): ListNode { var odd: ListNode? = head var even = head.next val evenHead = even while (even?.next != null) { odd?.next = even.next odd = odd?.next even.next = odd?.next even = even.next } odd?.next = evenHead return head } }
4
null
0
19
dd8ee7dc420c608d4a46d5dc5a19b11e6d3c7b9d
1,258
kotlab
Apache License 2.0
ficbookApi/src/commonMain/kotlin/ru/blays/ficbookapi/ajax/ActionChangeMark.kt
B1ays
710,470,973
false
{"Kotlin": 749323}
package ru.blays.ficbookapi.ajax import kotlinx.serialization.json.Json import okhttp3.CookieJar import okhttp3.FormBody import ru.blays.ficbookapi.dataModels.AjaxSimpleResult import ru.blays.ficbookapi.ficbookConnection.buildFicbookRequest import ru.blays.ficbookapi.ficbookConnection.buildFicbookURL import ru.blays.ficbookapi.ficbookConnection.href import ru.blays.ficbookapi.getHtmlBody suspend fun actionChangeMark( mark: Boolean, cookieJar: CookieJar? = null, fanficID: String ): Boolean { val href = "/ajax/mark" val action = if(mark) "add" else "remove" val url = buildFicbookURL { href(href) } val bodyBuilder = FormBody.Builder() .add("fanfic_id", fanficID) .add("action", action) .build() val request = buildFicbookRequest { post(bodyBuilder) header("Referer", "https://ficbook.net/readfic/$fanficID") url(url) } val responseBody = getHtmlBody( request = request, cookieJar = cookieJar ).value return if(responseBody != null) { try { Json.decodeFromString<AjaxSimpleResult>(responseBody).result } catch (e: Exception) { false } } else { false } }
0
Kotlin
0
2
d311da576a35365bc72e1646e7ae8b946eac6690
1,249
ficbook-reader
MIT License
src/lang-xquery/test/uk/co/reecedunn/intellij/plugin/xquery/tests/lang/editor/declaration/XQueryDeclarationRangeHandlerTest.kt
rhdunn
62,201,764
false
{"Kotlin": 8262637, "XQuery": 996770, "HTML": 39377, "XSLT": 6853}
/* * Copyright (C) 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.xquery.tests.lang.editor.declaration import com.intellij.openapi.extensions.PluginId import org.hamcrest.CoreMatchers.`is` import org.hamcrest.CoreMatchers.nullValue import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import uk.co.reecedunn.intellij.plugin.core.tests.assertion.assertThat import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryFunctionDecl import uk.co.reecedunn.intellij.plugin.xquery.lang.editor.declaration.XQueryFunctionDeclRangeHandler import uk.co.reecedunn.intellij.plugin.xquery.tests.parser.ParserTestCase @Suppress("RedundantVisibilityModifier") @DisplayName("IntelliJ - Custom Language Support - Declaration Range Handler") class XQueryDeclarationRangeHandlerTest : ParserTestCase() { override val pluginId: PluginId = PluginId.getId("XQueryDeclarationRangeHandlerTest") @Nested @DisplayName("XQuery 3.1 EBNF (32) FunctionDecl") internal inner class FunctionDecl { @Test @DisplayName("external") fun external() { val decl = parse<XQueryFunctionDecl>(" (::) declare function fn:true() external;")[0] val range = XQueryFunctionDeclRangeHandler().getDeclarationRange(decl) assertThat(range, `is`(nullValue())) } @Test @DisplayName("missing FunctionBody") fun missingBody() { val decl = parse<XQueryFunctionDecl>(" (::) declare function fn:true()")[0] val range = XQueryFunctionDeclRangeHandler().getDeclarationRange(decl) assertThat(range, `is`(nullValue())) } @Test @DisplayName("with FunctionBody") fun functionBody() { val decl = parse<XQueryFunctionDecl>(" (::) declare function fn:true() {};")[0] val range = XQueryFunctionDeclRangeHandler().getDeclarationRange(decl) assertThat(range?.startOffset, `is`(6)) assertThat(range?.endOffset, `is`(33)) } } }
49
Kotlin
9
25
d8d460d31334e8b2376a22f3832a20b2845bacab
2,621
xquery-intellij-plugin
Apache License 2.0
android/navigation/src/main/kotlin/io/chefbook/navigation/navigators/BaseNavigator.kt
mephistolie
379,951,682
false
{"Kotlin": 1334117, "Ruby": 16819, "Swift": 352}
package io.chefbook.navigation.navigators interface BaseNavigator { fun popBackStackToCurrent() = Unit fun navigateUp(skipAnimation: Boolean = false) }
0
Kotlin
0
12
ddaf82ee3142f30aee8920d226a8f07873cdcffe
158
chefbook-mobile
Apache License 2.0
src/jvmMain/kotlin/util/LoggerUtil.kt
flben233
680,857,766
false
{"Kotlin": 83989, "Java": 135}
package util import java.io.BufferedWriter import java.io.File import java.io.FileWriter sealed class LoggerUtil { companion object Default: LoggerUtil() private val logFile = File("./tyu_share.log") init { if (!logFile.exists()) { logFile.createNewFile() } } fun logStackTrace(e: Exception) { e.printStackTrace() val stackTrace: Array<StackTraceElement> = e.stackTrace val writer = BufferedWriter(FileWriter(logFile, true)) writer.append(e.message) for (traceElement in stackTrace) { writer.append("${DateUtil.getDateString()}: at $traceElement \n") } writer.close() } }
2
Kotlin
1
64
ba35ca7e2102241537ffad65afab5144ae2f6fa0
697
TyuShare
Apache License 2.0
common/src/main/kotlin/org/kotlinacademy/DateTimeSerializer.kt
MaurizioX
113,477,274
true
{"CSS": 389213, "Kotlin": 113380, "JavaScript": 5134, "HTML": 1738}
package org.kotlinacademy import kotlinx.serialization.KInput import kotlinx.serialization.KOutput import kotlinx.serialization.KSerializer import kotlinx.serialization.internal.SerialClassDescImpl object DateTimeSerializer : KSerializer<DateTime> { override val serialClassDesc = SerialClassDescImpl("org.kotlinacademy.DateTime") override fun save(output: KOutput, obj: DateTime) { output.writeStringValue(obj.toDateFormatString()) } override fun load(input: KInput): DateTime = input.readStringValue().parseDate() }
0
CSS
0
2
ff2ef2c3ec8aff0673077c350734435cf7ea6a39
546
KotlinAcademyApp
Apache License 2.0
buildSrc/src/main/kotlin/ch/acanda/gradle/fabrikt/build/generator/EnumSetPropertyGenerator.kt
acanda
687,155,869
false
{"Kotlin": 104277}
package ch.acanda.gradle.fabrikt.build.generator import ch.acanda.gradle.fabrikt.build.ExtensionGenerator import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.PropertySpec import com.squareup.kotlinpoet.TypeSpec import org.gradle.api.provider.SetProperty import kotlin.reflect.KClass internal fun TypeSpec.Builder.enumSetProperty(name: String, enumType: KClass<out Enum<*>>) = apply { addProperty( PropertySpec.builder(name, SetProperty::class.parameterizedBy(enumType)) .initializer( "%1N.setProperty(%2T::class.java).convention(null·as·Set<%2T>?)", ExtensionGenerator.PROP_OBJECTS, enumType ) .build() ) addFunction( FunSpec.builder(name) .addParameter(name, enumType, KModifier.VARARG) .addStatement("this.%1N.set(%1N.toSet())", name) .build() ) addFunction( FunSpec.builder(name) .addParameter(name, Iterable::class.parameterizedBy(enumType)) .addStatement("this.%1N.set(%1N.toSet())", name) .build() ) addFunction( FunSpec.builder(name) .addParameter(name, provider(Iterable::class.parameterizedBy(enumType))) .addStatement("this.%1N.set(%1N)", name) .build() ) addPropertiesForEnumValues(enumType) }
2
Kotlin
0
2
138b8acccf5f4f255ab42f25dae00d4bd889c3b5
1,505
fabrikt-gradle-plugin
Apache License 2.0
src/main/kotlin/ru/nick252/types/results/services/ServicesEntity.kt
nick2525
344,564,064
false
null
package ru.nick252.types.results.services class ServicesEntity { }
0
Kotlin
0
1
b599b5e2567b939dd1326f8ddbfee8040ae49367
67
KotlinHAApi
MIT License
ftc-ext/src/main/java/com/addonovan/ftcext/hardware/ContinuousServo.kt
addonovan
60,988,347
false
null
/** * The MIT License (MIT) * * Copyright (c) 2016 Austin Donovan (addonovan) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.addonovan.ftcext.hardware import com.qualcomm.robotcore.hardware.Servo /** * A class which serves to distinguish a regular servo from a * continuous (aka 360°) one. A few additions are made, such * as the [stop] method and the [StopPosition] property, but * it's identical to a regular [Servo] for the most part. * * @author addonovan * @since 6/26/16 */ @HardwareExtension( Servo::class ) open class ContinuousServo(servo: Servo ) : Servo( servo.controller, servo.portNumber ) { // // Vals // /** The position to use to tell the servo to stop moving. */ val StopPosition = 0.5; // // Actions // /** * Sets the position of the servo to [StopPosition] so that * the continuous servo stops moving. */ fun stop() { position = StopPosition; } }
1
Kotlin
1
1
ccfc952ee7fd40e36509e6aa6f90ee6ddc39958a
1,999
ftc-ext
MIT License
waltid-web3login-microservice/src/main/kotlin/id/walt/nft/NftService.kt
walt-id
701,058,624
false
null
package id.walt.webwallet.service.nft import id.walt.webwallet.service.dto.* import id.walt.webwallet.service.nft.fetchers.parameters.* interface NftService { suspend fun getChains(ecosystem: String): List<ChainDataTransferObject> suspend fun getMarketPlace(parameter: TokenMarketPlaceParameter): MarketPlaceDataTransferObject? suspend fun getExplorer(parameter: ChainExplorerParameter): ChainExplorerDataTransferObject? suspend fun filterTokens(tenant: String?, parameter: FilterParameter): List<FilterNftDataTransferObject> suspend fun getTokens(tenant: String?, parameter: ListFetchParameter): List<NftDetailDataTransferObject> suspend fun getTokenDetails(tenant: String?, parameter: DetailFetchParameter): NftDetailDataTransferObject }
24
null
5
98
a86bd0c843d594f6afe6e747d3c4de7d8a4789a8
766
waltid-identity
Apache License 2.0
android/app/src/main/java/now/fortuitous/thanos/service/SuSupportService.kt
Tornaco
228,014,878
false
null
package now.fortuitous.thanos.service import android.app.Service import android.content.Intent import android.os.IBinder import androidx.annotation.Keep import com.elvishew.xlog.XLog import com.topjohnwu.superuser.Shell import github.tornaco.android.thanos.core.app.ThanosManagerNative import github.tornaco.android.thanos.core.su.ISu import github.tornaco.android.thanos.core.su.SuRes @Keep class SuSupportService : Service() { companion object { init { XLog.w("Init shell") Shell.enableVerboseLogging = true Shell.setDefaultBuilder( Shell.Builder.create() .setFlags(Shell.FLAG_REDIRECT_STDERR or Shell.FLAG_MOUNT_MASTER) .setTimeout(10) ) } } override fun onBind(intent: Intent?): IBinder { return object : ISu.Stub() { override fun exe(command: Array<out String>): SuRes { val customCommand: String? = ThanosManagerNative .getDefault() .profileManager .customSuCommand if (!customCommand.isNullOrEmpty()) { XLog.w("Execute shell with custom command: $customCommand") val shell = com.topjohnwu.superuser.fallback.Shell.newInstance(customCommand) val result = shell.newJob().add(*command).exec() XLog.w( "Custom SuSupportService, su: %s, exe: %s, result: %s", customCommand, command.contentToString(), result ) kotlin.runCatching { shell.waitAndClose() } .onFailure { XLog.e(it, "Shell close err") } return result.toSuRes() } else { XLog.w("Execute shell with default command") return Shell.cmd(*command) .exec().apply { XLog.w("Shell res: out: ${this.out} err: ${this.err}") }.toSuRes() } } } } } fun Shell.Result.toSuRes() = SuRes(this.out, this.err, this.code) fun com.topjohnwu.superuser.fallback.Shell.Result.toSuRes() = SuRes(this.out, this.err, this.code)
392
null
87
2,145
b8b756152e609c96fd07f1f282b77582d8cde647
2,344
Thanox
Apache License 2.0
platform/lang-impl/src/com/intellij/lang/documentation/ide/impl/DocumentationUsageCollector.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.lang.documentation.ide.impl import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector object DocumentationUsageCollector: CounterUsagesCollector() { override fun getGroup(): EventLogGroup = GROUP private val GROUP = EventLogGroup("documentation", 1) val QUICK_DOC_SHOWN = GROUP.registerEvent("quick.doc.shown") }
251
null
5079
16,158
831d1a4524048aebf64173c1f0b26e04b61c6880
553
intellij-community
Apache License 2.0
app/src/main/java/social/entourage/android/api/model/BaseEntourage.kt
ReseauEntourage
30,242,877
false
{"Kotlin": 1949183}
package social.entourage.android.api.model import android.content.Context import android.graphics.PorterDuff import android.graphics.drawable.Drawable import androidx.annotation.ColorRes import androidx.annotation.StringRes import androidx.appcompat.content.res.AppCompatResources import androidx.core.content.ContextCompat import com.google.android.gms.maps.model.LatLng import com.google.gson.* import com.google.gson.annotations.SerializedName import social.entourage.android.R import social.entourage.android.api.model.feed.FeedItem import social.entourage.android.base.location.EntLocation import social.entourage.android.entourage.category.EntourageCategoryManager import timber.log.Timber import java.io.Serializable import java.lang.reflect.Type import java.text.SimpleDateFormat import java.util.* import kotlin.math.floor /** * Created by Mihai Ionescu on 06/07/2018. */ open class BaseEntourage : FeedItem, Serializable { // ---------------------------------- // Attributes // ---------------------------------- @SerializedName("created_at") var createdTime: Date = Date() private set @SerializedName("group_type") private var groupType: String @SerializedName("entourage_type") var actionGroupType: String @SerializedName("display_category") var category: String? = null private var title: String? = null private var description: String? = null var location: LocationPoint? = null var outcome: EntourageCloseOutcome? = null var metadata: Metadata? = null @SerializedName("recipient_consent_obtained") var isRecipientConsentObtained = true @SerializedName("public") var isPublic = false @SerializedName("image_url") var eventImageUrl:String? = null @SerializedName("online") var isOnlineEvent:Boolean = false @SerializedName("event_url") var eventUrl:String? = null // ---------------------------------- // CONSTRUCTORS // ---------------------------------- //needed for deserialize constructor() : super() { this.groupType = GROUPTYPE_ACTION this.actionGroupType = GROUPTYPE_ACTION_CONTRIBUTION } constructor(groupType: String, actionGroupType: String) : super() { this.groupType = groupType this.actionGroupType = actionGroupType } constructor(groupType: String, actionGroupType: String, category: String?, title: String, description: String, location: LocationPoint) : super() { this.groupType = groupType this.actionGroupType = actionGroupType this.category = category this.title = title this.description = description this.location = location } // ---------------------------------- // GETTERS & SETTERS // ---------------------------------- override fun getDescription(): String? { return description } fun setDescription(description: String) { this.description = description } override fun getTitle(): String? { return title } fun setTitle(title: String) { this.title = title } fun getGroupType(): String { return groupType } fun setGroupType(groupType: String) { this.groupType = groupType } // ---------------------------------- // PUBLIC METHODS // ---------------------------------- fun isSame(entourage: BaseEntourage): Boolean { if (id != entourage.id) return false if (status != entourage.status) return false if (joinStatus != entourage.joinStatus) return false if (numberOfPeople != entourage.numberOfPeople) return false if (numberOfUnreadMessages != entourage.numberOfUnreadMessages) return false if (actionGroupType != entourage.actionGroupType) return false if (category != null && category != entourage.category) return false if (isPublic != entourage.isPublic) return false return (author?.isSame(entourage.author)==true) } open fun isEvent() : Boolean { return false } /** * Returns the distance from the entourage starting point to the current location * If the current location or the starting point is null, it returns zero * @return distance in kilometers */ fun distanceToCurrentLocation(): Int { val newLocation = EntLocation.currentLocation ?: return 0 val distance = this.location?.distanceTo(LocationPoint(newLocation.latitude, newLocation.longitude)) ?:0.0f return floor(distance /1000.0f).toInt() } /** * Returns the distance from the entourage starting point to the given location * If the location or the starting point is null, it returns Integer.MAX_VALUE * @return distance in meters */ fun distanceToLocation(newLocation: LatLng?): Int { if (newLocation == null) { return Int.MAX_VALUE } val distance: Float = this.location?.distanceTo(LocationPoint(newLocation.latitude, newLocation.longitude)) ?: return Int.MAX_VALUE return floor(distance).toInt() } // ---------------------------------- // FeedItem overrides // ---------------------------------- override fun getFeedTypeLong(context: Context): String { return "" } override fun getFeedTypeColor(): Int { return EntourageCategoryManager.findCategory(this).typeColorRes } override fun getEndTime(): Date? { return updatedTime } override fun setEndTime(endTime: Date) {} override fun getStartPoint(): LocationPoint? { return location } override fun getIconDrawable(context: Context): Drawable? { val entourageCategory = EntourageCategoryManager.findCategory(this) AppCompatResources.getDrawable(context, entourageCategory.iconRes)?.let { categoryIcon -> categoryIcon.mutate() categoryIcon.clearColorFilter() categoryIcon.setColorFilter(ContextCompat.getColor(context, entourageCategory.typeColorRes), PorterDuff.Mode.SRC_IN) return categoryIcon } return super.getIconDrawable(context) } @StringRes override fun getClosedCTAText(): Int { if (isEvent()) return R.string.entourage_cell_button_freezed_success_cancel return if (outcome?.success==true) R.string.entourage_cell_button_freezed_success else super.getClosedCTAText() } @ColorRes override fun getClosedCTAColor(): Int { return if (outcome?.success==true) R.color.accent else super.getClosedCTAColor() } override fun getClosingLoaderMessage(): Int { return R.string.loader_title_action_finish } // ---------------------------------- // TimestampedObject overrides // ---------------------------------- override val timestamp: Date get() = createdTime override fun hashString(): String { return HASH_STRING_HEAD + id } override fun equals(other: Any?): Boolean { return !(other == null || other.javaClass != this.javaClass) && id == (other as BaseEntourage).id } override val type: Int get() = ENTOURAGE_CARD // ---------------------------------- // INNER CLASSES // ---------------------------------- class EntourageJoinInfo(var distance: Int) class Metadata : Serializable { @SerializedName("starts_at") var startDate: Date? = null private set @SerializedName("ends_at") var endDate: Date? = null private set @SerializedName("display_address") var displayAddress: String? = null @SerializedName("place_name") var placeName: String? = null @SerializedName("street_address") var streetAddress: String? = null @SerializedName("google_place_id") var googlePlaceId: String? = null private set @SerializedName("portrait_url") var portrait_url: String? = null @SerializedName("landscape_url") var landscape_url: String? = null var close_message:String? = null fun setStartDate(startDate: Date) { this.startDate = startDate } fun getStartDateAsString(context: Context): String { startDate?.let { val locale = Locale.getDefault() return SimpleDateFormat(context.getString(R.string.entourage_metadata_startAt_format), locale) .format(it) } return "" } fun getStartDateFullAsString(context: Context): String { startDate?.let { val locale = Locale.getDefault() return SimpleDateFormat(context.getString(R.string.entourage_metadata_startAt_format_full), locale) .format(it) } return "" } fun getStartTimeAsString(context: Context): String { startDate?.let { //round the minutes to multiple of 15 val calendar = Calendar.getInstance(Locale.getDefault()) calendar.time = it calendar[Calendar.MINUTE] = calendar[Calendar.MINUTE] / 15 * 15 //format it val locale = Locale.getDefault() val df = SimpleDateFormat(context.getString(R.string.entourage_metadata_startAt_time_format), locale) return df.format(calendar.time) } return "" } fun setEndDate(endDate: Date) { this.endDate = endDate } fun getEndDateFullAsString(context: Context): String { endDate?.let { val locale = Locale.getDefault() val df = SimpleDateFormat(context.getString(R.string.entourage_metadata_startAt_format_full), locale) return df.format(it) } return "" } fun getEndTimeAsString(context: Context): String { endDate?.let { //round the minutes to multiple of 15 val calendar = Calendar.getInstance(Locale.getDefault()) calendar.time = it calendar[Calendar.MINUTE] = calendar[Calendar.MINUTE] / 15 * 15 //format it val locale = Locale.getDefault() val df = SimpleDateFormat(context.getString(R.string.entourage_metadata_startAt_time_format), locale) return df.format(calendar.time) } return "" } fun getStartEndDatesAsString(context: Context): String { startDate?.let { start-> endDate?.let{ end -> val locale = Locale.getDefault() val df = SimpleDateFormat("dd/MM", locale) return String.format(context.getString(R.string.entourage_metadata_date_startAt_endAt), df.format(start), df.format(end)) } } return "" } fun getStartEndTimesAsString(context: Context): String { val calendarStart = Calendar.getInstance(Locale.getDefault()) val calendarEnd = Calendar.getInstance(Locale.getDefault()) calendarStart.time = startDate ?: return "" calendarEnd.time = endDate ?: return "" calendarStart[Calendar.MINUTE] = calendarStart[Calendar.MINUTE] / 15 * 15 calendarEnd[Calendar.MINUTE] = calendarEnd[Calendar.MINUTE] / 15 * 15 val locale = Locale.getDefault() val df = SimpleDateFormat("HH'h'mm", locale) return String.format(context.resources.getString(R.string.entourage_metadata_time_startAt_endAt), df.format(calendarStart.time), df.format(calendarEnd.time)) } fun setGooglePlaceId(googlePlaceId: String) { this.googlePlaceId = googlePlaceId } } class EntourageCloseOutcome(val success: Boolean) : Serializable { companion object { private const val serialVersionUID = 4175623577343446888L } } class BaseEntourageJsonAdapter : JsonDeserializer<BaseEntourage> { @Throws(JsonParseException::class) override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): BaseEntourage? { val jsonData = json.asJsonObject if (jsonData !=null) { try { val entourageClass = getClassFromString( jsonData["group_type"]?.asString, jsonData["entourage_type"]?.asString) val gson = GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") .create() val entourage = gson.fromJson<BaseEntourage>(jsonData, entourageClass) //HACK we force Date when API gives us NULL created_at if(entourage.createdTime == null) { entourage.createdTime = Date() } return entourage } catch (e: Exception) { Timber.e(e) } } return null } } companion object { private const val HASH_STRING_HEAD = "Entourage-" const val GROUPTYPE_ACTION_CONTRIBUTION = "contribution" const val GROUPTYPE_ACTION_DEMAND = "ask_for_help" const val GROUPTYPE_CONVERSATION = "conversation" const val GROUPTYPE_OUTING = "outing" const val GROUPTYPE_ACTION = "action" const val HEATMAP_SIZE = 500f //meters private var MARKER_SIZE = 0 fun getMarkerSize(context: Context): Int { if (MARKER_SIZE == 0) { MARKER_SIZE = context.resources.getDimensionPixelOffset(R.dimen.entourage_map_marker) } return MARKER_SIZE } fun getClassFromString(groupType: String?, actionGroupType: String?): Class<*> { return when(groupType) { GROUPTYPE_ACTION -> { when(actionGroupType) { GROUPTYPE_ACTION_CONTRIBUTION -> EntourageContribution::class.java GROUPTYPE_ACTION_DEMAND -> EntourageDemand::class.java else -> EntourageDemand::class.java } } GROUPTYPE_CONVERSATION -> EntourageConversation::class.java GROUPTYPE_OUTING -> EntourageEvent::class.java else -> EntourageDemand::class.java } } fun create(groupType: String?, actionGroupType: String?, category: String?, title: String, description: String, location: LocationPoint) : BaseEntourage { return when(groupType) { GROUPTYPE_ACTION -> { when(actionGroupType) { GROUPTYPE_ACTION_CONTRIBUTION -> EntourageContribution(category, title, description, location) GROUPTYPE_ACTION_DEMAND -> EntourageDemand(category, title, description, location) else -> EntourageDemand(category, title, description, location) } } GROUPTYPE_CONVERSATION -> EntourageConversation(category, title, description, location) GROUPTYPE_OUTING -> EntourageEvent(category, title, description, location) else -> EntourageDemand(category, title, description, location) } } private const val serialVersionUID = -1228955044085412292L const val NEWSFEED_TYPE = "Entourage" } }
2
Kotlin
2
9
0e3fffb32fed8ca833c4cf2db632ae7afe3939ba
15,800
entourage-android
MIT License
src/nativeGen/kotlin/godot/VisualShaderNodeVectorRefract.kt
piiertho
237,614,467
true
{"Kotlin": 5300589}
// DO NOT EDIT, THIS FILE IS GENERATED FROM api.json package godot import gdnative.godot_method_bind import godot.core.Godot import godot.core.Variant import godot.core.VariantArray import kotlin.reflect.KCallable import kotlinx.cinterop.CFunction import kotlinx.cinterop.COpaquePointer import kotlinx.cinterop.cstr import kotlinx.cinterop.invoke import kotlinx.cinterop.memScoped import kotlinx.cinterop.reinterpret open class VisualShaderNodeVectorRefract( _handle: COpaquePointer ) : VisualShaderNode(_handle) { companion object { fun new(): VisualShaderNodeVectorRefract = memScoped { val fnPtr = checkNotNull(Godot.gdnative.godot_get_class_constructor)("VisualShaderNodeVectorRefract".cstr.ptr) requireNotNull(fnPtr) { "No instance found for VisualShaderNodeVectorRefract" } val fn = fnPtr.reinterpret<CFunction<() -> COpaquePointer>>() VisualShaderNodeVectorRefract( fn() ) } fun from(ptr: COpaquePointer): VisualShaderNodeVectorRefract = VisualShaderNodeVectorRefract(ptr) /** * Container for method_bind pointers for VisualShaderNodeVectorRefract */ private object __method_bind } }
0
null
0
1
3a8c598040f9b47b2b8cf8f5432543f61d6f83e8
1,183
godot-kotlin
MIT License
graph/graph-application/src/main/kotlin/eu/tib/orkg/prototype/paperswithcode/application/port/output/Queries.kt
TIBHannover
197,416,205
false
{"Kotlin": 2433821, "Cypher": 215872, "Python": 4880, "Groovy": 1936, "Shell": 1803, "HTML": 240}
package eu.tib.orkg.prototype.paperswithcode.application.port.output import eu.tib.orkg.prototype.community.domain.model.ResearchField import eu.tib.orkg.prototype.paperswithcode.application.domain.BenchmarkSummary import eu.tib.orkg.prototype.paperswithcode.application.domain.Dataset import eu.tib.orkg.prototype.paperswithcode.application.domain.DatasetSummary import eu.tib.orkg.prototype.researchproblem.application.domain.ResearchProblem import eu.tib.orkg.prototype.statements.domain.model.ThingId import org.springframework.data.domain.Page import org.springframework.data.domain.Pageable interface SummarizeBenchmarkQuery { fun byResearchField(id: ThingId, pageable: Pageable): Page<BenchmarkSummary> fun getAll(pageable: Pageable): Page<BenchmarkSummary> } interface FindDatasetsQuery { fun forResearchProblem(id: ThingId, pageable: Pageable): Page<Dataset> } interface SummarizeDatasetQuery { fun by(id: ThingId, pageable: Pageable): Page<DatasetSummary> fun byAndProblem(id: ThingId, problemId: ThingId, pageable: Pageable): Page<DatasetSummary> } interface FindResearchFieldsQuery { /** * Find all research fields that have benchmarks. * * @return This list of research fields, or an empty list otherwise. */ fun withBenchmarks(pageable: Pageable): Page<ResearchField> } interface FindResearchProblemQuery { fun findResearchProblemForDataset(datasetId: ThingId, pageable: Pageable): Page<ResearchProblem> }
0
Kotlin
2
5
13cd2ba723dbd061e0dad8e9a9aa02378dd9166d
1,478
orkg-backend
MIT License
src/main/kotlin/jp/entdecken/crafttools/action/Action.kt
kigawa-net
507,474,266
false
null
package jp.entdecken.crafttools.action import jp.entdecken.crafttools.CraftTools import jp.entdecken.crafttools.ServerTicks import org.bukkit.Bukkit import org.bukkit.Material import org.bukkit.block.Block import org.bukkit.block.data.BlockData import org.bukkit.entity.Player import org.bukkit.scheduler.BukkitTask abstract class Action { private val changedBlocks: MutableMap<Block, BlockData> = LinkedHashMap() var task: BukkitTask? = null protected set fun setBlock(block: Block, material: Material) { changedBlocks[block] = block.blockData block.type = material } open fun redo(player: Player): String { task?.cancel() task = Bukkit.getScheduler().runTaskTimer(CraftTools.PLUGIN, Runnable { redoTask(player) }, 1, 1) return "redo started" } private fun redoTask(player: Player) { while (!ServerTicks.isOverMaxTick()) { if (changedBlocks.isEmpty()) { task?.cancel() player.sendMessage("redo ended") return } val block = changedBlocks.keys.first() block.blockData = changedBlocks[block] ?: continue changedBlocks.remove(block) } } }
0
Kotlin
1
0
95c452b5adc1c7ef6351d7088afa7d1a61a99191
1,246
craft-tools
MIT License
android-animations/app/src/main/java/com/rafaelneiva/androidanimations/ui/main/DrawableFragment.kt
rafaelneiva
216,042,607
false
null
package com.rafaelneiva.androidanimations.ui.main import android.graphics.drawable.Animatable2 import android.graphics.drawable.AnimatedVectorDrawable import android.graphics.drawable.AnimationDrawable import android.graphics.drawable.Drawable import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.rafaelneiva.androidanimations.R import kotlinx.android.synthetic.main.fragment_drawable.view.* class DrawableFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val root = inflater.inflate(R.layout.fragment_drawable, container, false) animationDrawable(root) animatedVectorDrawableDots(root) root.ivSearch.setOnClickListener { (root.ivSearch.drawable as AnimatedVectorDrawable).start() } val animals: AnimatedVectorDrawable = (root.ivAnimals.drawable as AnimatedVectorDrawable) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { animals.registerAnimationCallback(object : Animatable2.AnimationCallback() { override fun onAnimationEnd(drawable: Drawable) { super.onAnimationEnd(drawable) animals.start() } }) } animals.start() return root } private fun animatedVectorDrawableDots(root: View) { val dots: AnimatedVectorDrawable = (root.ivAnimVecDrawable.drawable as AnimatedVectorDrawable) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { dots.registerAnimationCallback(object : Animatable2.AnimationCallback() { override fun onAnimationEnd(drawable: Drawable) { super.onAnimationEnd(drawable) dots.start() } }) } dots.start() } private fun animationDrawable(root: View) { root.ivAnimationDrawable.setBackgroundResource(R.drawable.animation_running); val frameAnimation: AnimationDrawable = root.ivAnimationDrawable.background as AnimationDrawable; frameAnimation.start(); } companion object { fun newInstance(): DrawableFragment { return DrawableFragment() } } }
0
Kotlin
1
3
949c0b0b532fa4238ed3b18bfe41e555a7faa89e
2,439
AndroidAnimationsMeetup
Apache License 2.0
src/test/aoc2023/Day1Test.kt
nibarius
154,152,607
false
{"Kotlin": 825565}
package test.aoc2023 import aoc2023.Day1 import org.junit.Assert.assertEquals import org.junit.Test import resourceAsList class Day1Test { private val exampleInput = """ 1abc2 pqr3stu8vwx a1b2c3d4e5f treb7uchet """.trimIndent().split("\n") private val exampleInput2 = """ two1nine eightwothree abcone2threexyz xtwone3four 4nineeightseven2 zoneight234 7pqrstsixteen """.trimIndent().split("\n") @Test fun testPartOneExample1() { val day1 = Day1(exampleInput) assertEquals(142, day1.solvePart1()) } @Test fun partOneRealInput() { val day1 = Day1(resourceAsList("2023/day1.txt")) assertEquals(54561, day1.solvePart1()) } @Test fun testPartTwoExample1() { val day1 = Day1(exampleInput2) assertEquals(281, day1.solvePart2()) } @Test fun testPartTwoExtraTest() { // Index of the last three is before the two // 1threethree2three // 133two3 // So generating 9 strings, each with one digit replaced and then looking for the // largest index won't work. val day1 = Day1(listOf("1threethreetwothree")) assertEquals(13, day1.solvePart2()) } @Test fun partTwoRealInput() { val day1 = Day1(resourceAsList("2023/day1.txt")) assertEquals(54076, day1.solvePart2()) } }
0
Kotlin
0
6
890fd063f34a3536d7ad7e2c2627ca41cacfced6
1,443
aoc
MIT License
kotlin-node/src/jsMain/generated/node/v8/PromiseHooks.kt
JetBrains
93,250,841
false
null
// Generated by Karakum - do not modify it manually! package node.v8 sealed external interface PromiseHooks { /** * The `init` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. * @since v17.1.0, v16.14.0 * @param init The {@link Init | `init` callback} to call when a promise is created. * @return Call to stop the hook. */ var onInit: (init: Init) -> Function<*> /** * The `settled` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. * @since v17.1.0, v16.14.0 * @param settled The {@link Settled | `settled` callback} to call when a promise is created. * @return Call to stop the hook. */ var onSettled: (settled: Settled) -> Function<*> /** * The `before` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. * @since v17.1.0, v16.14.0 * @param before The {@link Before | `before` callback} to call before a promise continuation executes. * @return Call to stop the hook. */ var onBefore: (before: Before) -> Function<*> /** * The `after` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. * @since v17.1.0, v16.14.0 * @param after The {@link After | `after` callback} to call after a promise continuation executes. * @return Call to stop the hook. */ var onAfter: (after: After) -> Function<*> /** * Registers functions to be called for different lifetime events of each promise. * The callbacks `init()`/`before()`/`after()`/`settled()` are called for the respective events during a promise's lifetime. * All callbacks are optional. For example, if only promise creation needs to be tracked, then only the init callback needs to be passed. * The hook callbacks must be plain functions. Providing async functions will throw as it would produce an infinite microtask loop. * @since v17.1.0, v16.14.0 * @param callbacks The {@link HookCallbacks | Hook Callbacks} to register * @return Used for disabling hooks */ var createHook: (callbacks: HookCallbacks) -> Function<*> }
40
null
165
1,347
997ed3902482883db4a9657585426f6ca167d556
2,328
kotlin-wrappers
Apache License 2.0
kotlin-csstype/src/main/generated/csstype/OffsetRotate.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:Suppress( "NAME_CONTAINS_ILLEGAL_CHARS", "NESTED_CLASS_IN_EXTERNAL_INTERFACE", ) package csstype // language=JavaScript @JsName("""(/*union*/{reverse: 'reverse'}/*union*/)""") sealed external interface OffsetRotate { companion object { val reverse: OffsetRotate } }
12
Kotlin
6
983
372c0e4bdf95ba2341eda473d2e9260a5dd47d3b
343
kotlin-wrappers
Apache License 2.0
api/src/test/kotlin/org/jetbrains/kotlinx/dl/api/core/layer/Cropping3DTest.kt
JetBrains
249,948,572
false
null
/* * Copyright 2021 JetBrains s.r.o. and Kotlin Deep Learning project contributors. All Rights Reserved. * Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE.txt file. */ package org.jetbrains.kotlinx.dl.api.core.layer import org.jetbrains.kotlinx.dl.api.core.layer.reshaping.Cropping3D import org.jetbrains.kotlinx.dl.api.core.shape.shape import org.jetbrains.kotlinx.dl.api.core.shape.toLongArray import org.junit.jupiter.api.Test internal class Cropping3DTest : LayerTest() { private val input = arrayOf( arrayOf( arrayOf( arrayOf( floatArrayOf(1.0f, 2.0f, 3.0f), floatArrayOf(4.0f, 5.0f, 6.0f), floatArrayOf(7.0f, 8.0f, 9.0f), floatArrayOf(10.0f, 11.0f, 12.0f), ), arrayOf( floatArrayOf(11.0f, 12.0f, 13.0f), floatArrayOf(14.0f, 15.0f, 16.0f), floatArrayOf(17.0f, 18.0f, 19.0f), floatArrayOf(20.0f, 21.0f, 22.0f), ), ), arrayOf( arrayOf( floatArrayOf(-1.0f, -2.0f, -3.0f), floatArrayOf(-4.0f, -5.0f, -6.0f), floatArrayOf(-7.0f, -8.0f, -9.0f), floatArrayOf(-10.0f, -11.0f, -12.0f), ), arrayOf( floatArrayOf(-11.0f, -12.0f, -13.0f), floatArrayOf(-14.0f, -15.0f, -16.0f), floatArrayOf(-17.0f, -18.0f, -19.0f), floatArrayOf(-20.0f, -21.0f, -22.0f), ) ) ) ) private val inputShape = input.shape.toLongArray() @Test fun testWithCroppingSize() { val layer = Cropping3D( cropping = arrayOf(intArrayOf(1, 0), intArrayOf(0, 1), intArrayOf(1, 1)) ) val expected = arrayOf( arrayOf( arrayOf( arrayOf( floatArrayOf(-4.0f, -5.0f, -6.0f), floatArrayOf(-7.0f, -8.0f, -9.0f), ) ) ) ) assertLayerOutputIsCorrect(layer, input, expected) val expectedShape = longArrayOf( inputShape[0], inputShape[1] - 1, inputShape[2] - 1, inputShape[3] - 1 - 1, inputShape[4] ) assertLayerComputedOutputShape(layer, inputShape, expectedShape) } }
81
null
79
806
efaa1ebdf7bf9a131826d3ded42e1eb178e4fd19
2,536
KotlinDL
Apache License 2.0
app/src/main/java/com/elhady/movies/core/data/repository/mappers/domain/movie/DomainInWatchHistoryMoviesMapper.kt
islamelhady
301,591,032
false
{"Kotlin": 584524}
package com.elhady.movies.core.data.repository.mappers.domain.movie import com.elhady.movies.core.mapper.Mapper import com.elhady.movies.core.data.local.database.dto.movie.MovieInWatchHistoryLocalDto import com.elhady.movies.core.domain.entities.MovieInWatchHistoryEntity import javax.inject.Inject class DomainInWatchHistoryMoviesMapper @Inject constructor() : Mapper<MovieInWatchHistoryLocalDto, MovieInWatchHistoryEntity> { override fun map(input: MovieInWatchHistoryLocalDto): MovieInWatchHistoryEntity { return MovieInWatchHistoryEntity( id = input.id, title = input.title, description = input.title, voteAverage = input.voteAverage, dateWatched = input.dateWatched, posterPath = input.posterPath, year = input.year ) } }
1
Kotlin
0
0
d9b6c3f241b5de6c334fa2dcc9f2653de3c04762
840
movie-night-v2
Apache License 2.0
kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/v2/SpringPluginInitializer.kt
spinnaker
19,836,152
false
null
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.kork.plugins.v2 import com.netflix.spinnaker.kork.exceptions.SystemException import com.netflix.spinnaker.kork.plugins.config.ConfigFactory import com.netflix.spinnaker.kork.plugins.v2.context.ComponentScanningCustomizer import com.netflix.spinnaker.kork.plugins.v2.context.PluginConfigurationRegisteringCustomizer import com.netflix.spinnaker.kork.plugins.v2.context.PluginSdksRegisteringCustomizer import org.pf4j.Plugin import org.pf4j.PluginWrapper import org.slf4j.LoggerFactory import org.springframework.context.ApplicationContext import org.springframework.context.ApplicationContextAware import org.springframework.context.ConfigurableApplicationContext import org.springframework.context.support.GenericApplicationContext import org.springframework.core.io.DefaultResourceLoader /** * Initializes the given [plugin]'s [pluginApplicationContext] after being connected to the service's * own [ApplicationContext]. */ class SpringPluginInitializer( private val plugin: Plugin, private val pluginWrapper: PluginWrapper, private val pluginApplicationContext: GenericApplicationContext, ) : ApplicationContextAware { private val log by lazy { LoggerFactory.getLogger(javaClass) } override fun setApplicationContext(applicationContext: ApplicationContext) { if (applicationContext !is ConfigurableApplicationContext) { throw SystemException("ApplicationContext must be configurable") } log.info("Initializing '${pluginWrapper.pluginId}'") pluginApplicationContext.classLoader = pluginWrapper.pluginClassLoader pluginApplicationContext.setResourceLoader(DefaultResourceLoader(pluginWrapper.pluginClassLoader)) pluginApplicationContext .beanFactory .addBeanPostProcessor(ApplicationEventListenerBeanPostProcessor()) listOf( PluginConfigurationRegisteringCustomizer(applicationContext.getBean(ConfigFactory::class.java)), PluginSdksRegisteringCustomizer(applicationContext), ComponentScanningCustomizer() ).forEach { it.accept(plugin, pluginApplicationContext) } pluginApplicationContext.refresh() } }
16
null
174
41
9960290a589ae6f6d05faaac1856289936ee2fb3
2,733
kork
Apache License 2.0
app/src/main/java/com/sinxn/youtify/ytmibrary/mixins/SearchMixin.kt
sinan-q
684,392,709
false
{"Kotlin": 130459}
package com.sinxn.youtify.ytmibrary.mixins import com.google.gson.JsonArray import com.google.gson.JsonElement import com.google.gson.JsonObject import com.sinxn.youtify.ytmibrary.YTAuth import com.sinxn.youtify.ytmibrary.YTMusic import com.sinxn.youtify.ytmibrary.getContinuations import com.sinxn.youtify.ytmibrary.nav import com.sinxn.youtify.ytmibrary.parsers.Parser import com.sinxn.youtify.ytmibrary.parsers.getSearchParams import com.sinxn.youtify.ytmibrary.parsers.parseSearchResults import com.sinxn.youtify.ytmibrary.parsers.parseTopResult import java.util.Locale open class SearchMixin(private val yTMusic: YTMusic) { private var body: JsonObject = JsonObject() private var endpoint: String = "" private val parser = Parser() suspend fun search( query: String, filterParam: String? = null, scope: String? = null, limit: Int = 20, ignoreSpelling: Boolean = false ): JsonArray { var filter = filterParam body = JsonObject().apply { addProperty("query", query) } endpoint = "search" val results: JsonObject val searchResults = JsonArray() val filters = listOf( "albums", "artists", "playlists", "community_playlists", "featured_playlists", "songs", "videos", "profiles" ) if (filter != null && filter !in filters) { throw Exception( "Invalid filter provided. Please use one of the following filters or leave out the parameter: " + filters.joinToString(", ") ) } val scopes = listOf("library", "uploads") if (scope != null && scope !in scopes) { throw Exception( "Invalid scope provided. Please use one of the following scopes or leave out the parameter: " + scopes.joinToString(", ") ) } if (scope == scopes[1] && filter != null) { throw Exception( "No filter can be set when searching uploads. Please unset the filter parameter when scope is set to " + "uploads." ) } if (scope == scopes[0] && filter in filters.subList(3, 5)) { throw Exception( "$filter cannot be set when searching library. Please use one of the following filters or leave out the parameter: " + filters.subList(0, 3) + filters.subList(5, filters.size).joinToString(", ") ) } val params = getSearchParams(filter, scope, ignoreSpelling) if (params != null) { body.addProperty("params", params) } val response = yTMusic.sendRequest(endpoint, body) // Check for no results if (!response.has("contents")) { return searchResults } val tabbedSearchResults = response.getAsJsonObject("contents") results = if (tabbedSearchResults.has("tabbedSearchResultsRenderer")) { val tabbedSearchResultsRenderer = tabbedSearchResults.getAsJsonObject("tabbedSearchResultsRenderer") val tabIndex = if (scope == null || filter == null) 0 else scopes.indexOf(scope) + 1 val tabs = tabbedSearchResultsRenderer["tabs"].asJsonArray val tabRenderer = tabs[tabIndex].asJsonObject["tabRenderer"].asJsonObject tabRenderer["content"].asJsonObject } else { response["contents"].asJsonObject } val resultsArray = nav(results, YTAuth.SECTION_LIST)?.asJsonArray // Check for no results if (resultsArray != null) { if ((resultsArray.size() == 1 && resultsArray.first().asJsonObject.has("itemSectionRenderer")) ) { return searchResults } } // Set filter for parser if (filter != null && "playlists" in filter) { filter = "playlists" } else if (scope == scopes[1]) { filter = scopes[1] } if (resultsArray != null) { for (res in resultsArray) { var contents: JsonElement? var category: JsonElement? = null var type: String? = null if (res.asJsonObject.has("musicCardShelfRenderer")) { val topResult = parseTopResult( res.asJsonObject["musicCardShelfRenderer"].asJsonObject, parser.getSearchResultTypes() ) searchResults.add(topResult) contents = nav( res.asJsonObject, listOf("musicCardShelfRenderer", "contents"), true ) if (contents != null) { val category1 = contents.asJsonArray?.firstOrNull()?.asJsonObject if (category1?.has("messageRenderer") == true) category = nav(category1, listOf("messageRenderer") + YTAuth.TEXT_RUN_TEXT) } } else if (res.asJsonObject.has("musicShelfRenderer")) { contents = res.asJsonObject["musicShelfRenderer"].asJsonObject["contents"].asJsonArray var typeFilter = filter category = nav( res.asJsonObject, YTAuth.MUSIC_SHELF + YTAuth.TITLE_TEXT, true ) if (typeFilter == null && scope == scopes[0]) { typeFilter = category?.asString } type = typeFilter?.substring(0, typeFilter.length - 1)?.lowercase(Locale.ROOT) } else continue val searchResultTypes = parser.getSearchResultTypes() searchResults.addAll( parseSearchResults( contents?.asJsonArray, searchResultTypes, type, category?.asString ) ) if (filter != null) { val requestFunc: suspend (String) -> JsonObject = { yTMusic.sendRequest(endpoint, body, it) } val parseFunc: (JsonArray) -> JsonArray? = { parseSearchResults( it, searchResultTypes, type, category?.asString ) } searchResults.addAll( getContinuations( res.asJsonObject["musicShelfRenderer"].asJsonObject, "musicShelfContinuation", limit - searchResults.size(), requestFunc, parseFunc ) ) } } } return searchResults } }
0
Kotlin
0
0
ae7909cbdb8b05b31121f5983f857558f5c83211
7,228
Youtify
MIT License
app/src/main/java/arira/co/id/mesinatrian/ui/activity/onboarding/OnBoardingActivity.kt
ramcona
295,104,924
false
null
package arira.co.id.mesinatrian.ui.activity.onboarding import android.content.Intent import android.os.Bundle import android.view.WindowManager import androidx.fragment.app.Fragment import androidx.viewpager.widget.ViewPager import arira.co.id.mesinatrian.R import arira.co.id.mesinatrian.adapter.OnBoardingViewPagerAdapter import arira.co.id.mesinatrian.app.App.Companion.pref import arira.co.id.mesinatrian.helper.BaseActivity import arira.co.id.mesinatrian.ui.activity.dataBaru.DataActivity import arira.co.id.mesinatrian.ui.activity.main.MainActivity import arira.co.id.mesinatrian.ui.fragment.onboarding.OnBoardingFragment import kotlinx.android.synthetic.main.activity_on_boarding.* class OnBoardingActivity : BaseActivity(), OnBoardingFragment.OnBoardingListener { private var currentPage = 0 private val fragments = ArrayList<Fragment>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN) setContentView(R.layout.activity_on_boarding) statusPutih() val adapter = OnBoardingViewPagerAdapter(supportFragmentManager) for (i in 1 until 4) { fragments.add(OnBoardingFragment.newInstance(i.toString(), this, onboard_vp)) } adapter.addFragments(fragments) onboard_vp.adapter = adapter onboard_vp.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrollStateChanged(state: Int) { } override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { } override fun onPageSelected(position: Int) { currentPage = position } }) } override fun onNextClick() { if (currentPage == fragments.size - 1) { startActivity(Intent(this, MainActivity::class.java)) pref.setIsFirstLaunchToFalse() finish() } else { onboard_vp.setCurrentItem(currentPage + 1, true) } } override fun onFinishClick() { startActivity(Intent(this, DataActivity::class.java)) pref.setIsFirstLaunchToFalse() finish() } }
0
Kotlin
0
0
ed95c8b13f6e2aa2a64087b08719ca16b7cdb08c
2,317
mesin-antrian
Apache License 2.0
source/packages/pix/src/test/kotlin/com/gabrielcora/pix/payment/domain/commands/handlers/UpdatePaymentCommandHandlerTest.kt
gabrielcora20
781,071,020
false
{"Kotlin": 118392, "Dockerfile": 757, "JavaScript": 147}
package com.gabrielcora.pix.payment.domain.commands.handlers import com.gabrielcora.pix.payment.domain.commands.UpdatePaymentCommand import com.gabrielcora.pix.payment.domain.exceptions.PaymentNotFoundException import com.gabrielcora.pix.payment.domain.interfaces.UnitOfWork import com.gabrielcora.pix.payment.domain.models.Payment import com.gabrielcora.pix.payment.domain.models.enums.StatusEnum import com.gabrielcora.pix.payment.infra.crosscutting.helpers.interfaces.PixKeyHelper import com.gabrielcora.pix.payment.infra.data.repository.read.PaymentReadRepository import com.gabrielcora.pix.payment.infra.data.repository.write.PaymentWriteRepository import com.gabrielcora.pix.payment.mocks.* import com.nhaarman.mockitokotlin2.anyOrNull import com.nhaarman.mockitokotlin2.whenever import kotlinx.coroutines.test.runTest import org.apache.coyote.BadRequestException import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.extension.ExtendWith import org.mockito.Mockito.* import org.mockito.junit.jupiter.MockitoExtension import org.mockito.junit.jupiter.MockitoSettings import org.mockito.quality.Strictness import java.time.LocalDateTime @ExtendWith(MockitoExtension::class) @MockitoSettings(strictness = Strictness.LENIENT) class UpdatePaymentCommandHandlerTest { @Test fun `test command handler`() { runTest { val readRepository = mock<PaymentReadRepository>() val writeRepository = mock<PaymentWriteRepository>() val pixKeyHelper = mock<PixKeyHelper>() val currentDate = LocalDateTime.now() mockStatic(LocalDateTime::class.java, CALLS_REAL_METHODS).use { `when`(LocalDateTime.now()).then{currentDate} } `when`(pixKeyHelper.getTypeFromPixKey(destinationMock.pixKey)).then { destinationMock.keyType } `when`(paymentScheduledMock.getStatusByPaymentDate(currentDate)).then { StatusEnum.SCHEDULED } val unitOfWork = mock<UnitOfWork>() whenever(unitOfWork.commit()).then { true } whenever(writeRepository.unitOfWork).then { unitOfWork } val command = UpdatePaymentCommand( paymentScheduledMock.id.toString(), paymentScheduledMock.paymentDate, paymentScheduledMock.value, paymentScheduledMock.description, paymentScheduledMock.recurrence, destinationMock.pixKey) val commandHandler = UpdatePaymentCommandHandler(writeRepository, readRepository, pixKeyHelper) whenever(readRepository.findById(paymentScheduledMock.id.toString())).then{ paymentScheduledMock } whenever(readRepository.findSimilarPayments(anyOrNull())).then{ listOf<Payment>() } val commandResult = commandHandler.handle(command) Assertions.assertEquals(commandResult.updatedPayment, paymentScheduledMock) Assertions.assertNull(commandResult.warnings) } } @Test fun `test command handler with null payment date`() { val readRepository = mock<PaymentReadRepository>() val writeRepository = mock<PaymentWriteRepository>() val pixKeyHelper = mock<PixKeyHelper>() val currentDate = LocalDateTime.now() mockStatic(LocalDateTime::class.java, CALLS_REAL_METHODS).use { `when`(LocalDateTime.now()).then{currentDate} } `when`(pixKeyHelper.getTypeFromPixKey(destinationMock.pixKey)).then { destinationMock.keyType } `when`(paymentScheduledMock.getStatusByPaymentDate(currentDate)).then { StatusEnum.SCHEDULED } runTest { val unitOfWork = mock<UnitOfWork>() whenever(unitOfWork.commit()).then { true } whenever(writeRepository.unitOfWork).then { unitOfWork } } val command = UpdatePaymentCommand( paymentScheduledMock.id.toString(), null, paymentScheduledMock.value, paymentScheduledMock.description, paymentScheduledMock.recurrence, destinationMock.pixKey) val commandHandler = UpdatePaymentCommandHandler(writeRepository, readRepository, pixKeyHelper) runTest { whenever(readRepository.findById(paymentScheduledMock.id.toString())).then{ paymentScheduledMock } whenever(readRepository.findSimilarPayments(anyOrNull())).then{ listOf<Payment>() } val commandResult = commandHandler.handle(command) Assertions.assertEquals(commandResult.updatedPayment, paymentScheduledMock) Assertions.assertNull(commandResult.warnings) } } @Test fun `test command handler with similar payments found warning`() { val readRepository = mock<PaymentReadRepository>() val writeRepository = mock<PaymentWriteRepository>() val pixKeyHelper = mock<PixKeyHelper>() val currentDate = LocalDateTime.now() mockStatic(LocalDateTime::class.java, CALLS_REAL_METHODS).use { `when`(LocalDateTime.now()).then{currentDate} } `when`(pixKeyHelper.getTypeFromPixKey(destinationMock.pixKey)).then { destinationMock.keyType } `when`(paymentScheduledMock.getStatusByPaymentDate(currentDate)).then { StatusEnum.SCHEDULED } runTest { val unitOfWork = mock<UnitOfWork>() whenever(unitOfWork.commit()).then { true } whenever(writeRepository.unitOfWork).then { unitOfWork } } val command = UpdatePaymentCommand( paymentScheduledMock.id.toString(), paymentScheduledMock.paymentDate, paymentScheduledMock.value, paymentScheduledMock.description, paymentScheduledMock.recurrence, destinationMock.pixKey) val commandHandler = UpdatePaymentCommandHandler(writeRepository, readRepository, pixKeyHelper) runTest { whenever(readRepository.findById(paymentScheduledMock.id.toString())).then{ paymentScheduledMock } whenever(readRepository.findSimilarPayments(anyOrNull())).then{ paymentsScheduledMock } val commandResult = commandHandler.handle(command) Assertions.assertEquals(commandResult.updatedPayment, paymentScheduledMock) Assertions.assertNotNull(commandResult.warnings) } } @Test fun `test command handler with exception on commit changes`() { val readRepository = mock<PaymentReadRepository>() val writeRepository = mock<PaymentWriteRepository>() val pixKeyHelper = mock<PixKeyHelper>() val currentDate = LocalDateTime.now() mockStatic(LocalDateTime::class.java, CALLS_REAL_METHODS).use { `when`(LocalDateTime.now()).then{currentDate} } `when`(pixKeyHelper.getTypeFromPixKey(destinationMock.pixKey)).then { destinationMock.keyType } `when`(paymentScheduledMock.getStatusByPaymentDate(currentDate)).then { StatusEnum.SCHEDULED } runTest { val unitOfWork = mock<UnitOfWork>() whenever(unitOfWork.commit()).then { false } whenever(writeRepository.unitOfWork).then { unitOfWork } } val command = UpdatePaymentCommand( paymentScheduledMock.id.toString(), paymentScheduledMock.paymentDate, paymentScheduledMock.value, paymentScheduledMock.description, paymentScheduledMock.recurrence, destinationMock.pixKey) val commandHandler = UpdatePaymentCommandHandler(writeRepository, readRepository, pixKeyHelper) runTest { whenever(readRepository.findById(paymentScheduledMock.id.toString())).then{ paymentScheduledMock } whenever(readRepository.findSimilarPayments(anyOrNull())).then{ listOf<Payment>() } assertThrows<BadRequestException> {commandHandler.handle(command)} } } @Test fun `test command handler with exception on find payment by id`() { val readRepository = mock<PaymentReadRepository>() val writeRepository = mock<PaymentWriteRepository>() val pixKeyHelper = mock<PixKeyHelper>() runTest { val unitOfWork = mock<UnitOfWork>() whenever(unitOfWork.commit()).then { true } whenever(writeRepository.unitOfWork).then { unitOfWork } } val command = UpdatePaymentCommand( paymentScheduledMock.id.toString(), paymentScheduledMock.paymentDate, paymentScheduledMock.value, paymentScheduledMock.description, paymentScheduledMock.recurrence, destinationMock.pixKey) val commandHandler = UpdatePaymentCommandHandler(writeRepository, readRepository, pixKeyHelper) runTest { whenever(readRepository.findById(paymentScheduledMock.id.toString())).then{ null } assertThrows<PaymentNotFoundException> {commandHandler.handle(command)} } } @Test fun `test command handler with exception on pix key cast`() { val readRepository = mock<PaymentReadRepository>() val writeRepository = mock<PaymentWriteRepository>() val pixKeyHelper = mock<PixKeyHelper>() `when`(pixKeyHelper.getTypeFromPixKey(destinationMock.pixKey)).thenThrow(IllegalArgumentException("A chave pix fornecida é inválida")) val currentDate = LocalDateTime.now() mockStatic(LocalDateTime::class.java, CALLS_REAL_METHODS).use { `when`(LocalDateTime.now()).then{currentDate} } `when`(paymentScheduledMock.getStatusByPaymentDate(currentDate)).then { StatusEnum.SCHEDULED } runTest { val unitOfWork = mock<UnitOfWork>() whenever(unitOfWork.commit()).then { false } whenever(writeRepository.unitOfWork).then { unitOfWork } } val command = UpdatePaymentCommand( paymentScheduledMock.id.toString(), paymentScheduledMock.paymentDate, paymentScheduledMock.value, paymentScheduledMock.description, paymentScheduledMock.recurrence, destinationMock.pixKey) val commandHandler = UpdatePaymentCommandHandler(writeRepository, readRepository, pixKeyHelper) runTest { whenever(readRepository.findById(paymentScheduledMock.id.toString())).then{ paymentScheduledMock } whenever(readRepository.findSimilarPayments(anyOrNull())).then{ listOf<Payment>() } assertThrows<IllegalArgumentException> {commandHandler.handle(command)} } } }
0
Kotlin
0
0
d27b1b42bf88e66c2cfdf5cee01f704774b4953b
10,758
pix-demo-project
MIT License
backend/src/test/kotlin/com/hyosakura/analyzer/grammar/detector/LeftCommonFactorDetectorTest.kt
LovesAsuna
424,087,963
false
{"Kotlin": 41173}
package com.hyosakura.analyzer.grammar.detector import com.hyosakura.analyzer.parser.GrammarScanner import org.junit.jupiter.api.Test internal class LeftCommonFactorDetectorTest { @Test fun detect() { val str = "S -> cAd | cB\nA -> ab | a\nB -> aa" val grammar = GrammarScanner().parse(str) val detector = LeftCommonFactorDetector() detector.detect(grammar) } }
0
Kotlin
0
1
f2a28ff9f2b6e2bc8be5b480d2a535d1aa550159
408
LLAnalyzer
MIT License
app/src/main/java/com/coffeeandsand/gimmeaclue/GimmeAClue.kt
BGundlach
854,769,724
false
{"Kotlin": 11872}
package com.coffeeandsand.gimmeaclue import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class GimmeAClue : Application()
0
Kotlin
0
0
f70815fd85a4eda24c424ecc23737b6861051a02
160
Gimme-A-Clue
Apache License 2.0
libraries/rib-base-test-rx2/src/main/java/com/badoo/common/ribs/rx2/InteractorTestHelper.kt
badoo
170,855,556
false
null
package com.badoo.common.ribs.rx2 import android.view.ViewGroup import com.badoo.ribs.clienthelper.interactor.Interactor import com.badoo.ribs.core.Rib import com.badoo.ribs.core.view.RibView import com.badoo.ribs.rx2.clienthelper.connector.Connectable import com.badoo.ribs.test.InteractorTestHelper import com.jakewharton.rxrelay2.PublishRelay import com.jakewharton.rxrelay2.Relay import io.reactivex.ObservableSource import io.reactivex.Observer import org.mockito.ArgumentMatchers.any import org.mockito.Mockito import org.mockito.Mockito.mock import org.mockito.Mockito.`when` as whenever @Deprecated("Use RibInteractorTestHelper") inline fun <reified View, ViewEvent> createInteractorTestHelper( interactor: Interactor<*, View>, viewEventRelay: Relay<ViewEvent> ): InteractorTestHelper<View> where View : RibView, View : ObservableSource<ViewEvent> { val view: View = viewEventRelay.subscribedView() return InteractorTestHelper(interactor, { view }) } @Deprecated("Use RibInteractorTestHelper") inline fun <reified R, reified Input, reified Output> Interactor<R, *>.mockIO( inputRelay: Relay<Input> = PublishRelay.create(), outputRelay: Relay<Output> = PublishRelay.create() ) where R : Rib, R : Connectable<Input, Output> { val rib = mock(R::class.java).apply { whenever(input).thenReturn(inputRelay) whenever(output).thenReturn(outputRelay) } init(rib) } @Deprecated("Use RibInteractorTestHelper") inline fun <reified RView, ViewEvent> Relay<ViewEvent>.subscribedView(): RView where RView : RibView, RView : ObservableSource<ViewEvent> = mock(RView::class.java).apply { Mockito.`when`(this.androidView).thenReturn(mock(ViewGroup::class.java)) Mockito.`when`(this.subscribe(any())).thenAnswer { val observer = it.getArgument<Observer<ViewEvent>>(0) this@subscribedView.subscribe(observer) } }
34
null
49
161
35e137ce521b40e2dc25730f303f644faf2b50d7
1,913
RIBs
Apache License 2.0
app/src/main/java/com/robertomiranda/app/features/postdetail/adapter/models/CommentListItem.kt
RoberMiranda92
259,187,177
false
null
package com.robertomiranda.app.features.postdetail.adapter.models import com.robertomiranda.app.core.list.ListItem import com.robertomiranda.data.models.Comment data class CommentListItem(val comment: Comment) : ListItem { override fun getType(): Int = CommentBundle.VIEW_TYPE_COMMENT override fun getID(): Int = comment.id override fun equals(other: Any?): Boolean { return if (other is CommentListItem) { other.comment == this.comment } else { false } } override fun hashCode(): Int { return javaClass.hashCode() } }
0
Kotlin
0
0
b37b413cf2f26596294040938a089998cfd6d93f
612
Post-List
Apache License 2.0
demoProjects/ComposeMail/app/src/main/java/com/example/composemail/ui/mails/MailList.kt
camaelon
505,900,439
true
{"Java": 6238576, "Kotlin": 1478648, "Shell": 1512}
/* * Copyright (C) 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 com.example.composemail.ui.mails import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.paging.PagingData import androidx.paging.compose.LazyPagingItems import androidx.paging.compose.collectAsLazyPagingItems import androidx.paging.compose.itemsIndexed import com.example.composemail.model.data.MailEntryInfo import kotlinx.coroutines.flow.Flow @Composable fun MailList( modifier: Modifier = Modifier, listState: MailListState, observableConversations: Flow<PagingData<MailEntryInfo>> ) { // The items provided through the model using Pager through a Flow val lazyMailItems: LazyPagingItems<MailEntryInfo> = observableConversations.collectAsLazyPagingItems() LazyColumn( modifier = modifier, verticalArrangement = Arrangement.spacedBy(4.dp) ) { itemsIndexed(lazyMailItems) { _, mailInfo -> // The Pager, configured with placeholders may initially provide // a null mailInfo when it reaches the current end of the list, // it will then provide a non-null mailInfo for the same Composable, // MailItem animates the transition from those two values MailItem( info = mailInfo, state = listState.stateFor(mailInfo?.id) ) } } }
0
Java
0
0
dcc3342f021f65b00de57265fe10e40695d0ba1e
2,109
constraintlayout
Apache License 2.0
src/main/kotlin/ray/mintcat/heritage/KetherUtil.kt
BingZi-233
582,377,670
false
null
package ray.mintcat.heritage import org.bukkit.command.CommandSender import taboolib.common.platform.function.adaptPlayer import taboolib.library.kether.LocalizedException import taboolib.module.kether.KetherShell import taboolib.module.kether.printKetherErrorMessage /** * Kether eval * Kether执行器 * * @param sender 执行者 */ fun List<String>.ketherEval(sender: CommandSender) { try { KetherShell.eval(this) { this.sender = adaptPlayer(sender) } } catch (e: LocalizedException) { e.printKetherErrorMessage() } catch (e: Throwable) { e.printKetherErrorMessage() } } /** * Kether eval * Kether执行器 * * @param sender 执行者 */ fun String.ketherEval(sender: CommandSender) { try { KetherShell.eval(this) { this.sender = adaptPlayer(sender) } } catch (e: LocalizedException) { e.printKetherErrorMessage() } catch (e: Throwable) { e.printKetherErrorMessage() } }
0
Kotlin
0
0
bb041ac18de8e1fbe0d607761b550a4634b5f44e
982
Heritage
Creative Commons Zero v1.0 Universal
data/src/test/kotlin/cz/eman/kaalsample/data/DataArchTest.kt
eManPrague
189,150,450
false
{"Kotlin": 130007, "Java": 794}
package cz.eman.kaalsample.data import com.tngtech.archunit.core.domain.JavaClasses import com.tngtech.archunit.core.importer.ImportOption import com.tngtech.archunit.junit.AnalyzeClasses import com.tngtech.archunit.junit.ArchTest import com.tngtech.archunit.junit.ArchUnitRunner import com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes import com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses import org.junit.runner.RunWith @RunWith(ArchUnitRunner::class) @AnalyzeClasses(packagesOf = [DataArchTest::class], importOptions = [ImportOption.DoNotIncludeTests::class, ImportOption.DoNotIncludeJars::class]) class DataArchTest { @ArchTest fun androidDependencyCheck(importedClasses: JavaClasses) { val dependencyCheck = noClasses() .that() .resideInAnyPackage("..data..") .should() .dependOnClassesThat() .resideInAnyPackage("android..", "androidx..") dependencyCheck.check(importedClasses) } @ArchTest fun appDependencyCheck(importedClasses: JavaClasses) { val dependencyCheck = noClasses() .that() .resideInAPackage("..data..") .should() .dependOnClassesThat() .resideInAPackage("..app..") dependencyCheck.check(importedClasses) } @ArchTest fun infrastructureDependencyCheck(importedClasses: JavaClasses) { val dependencyCheck = noClasses() .that() .resideInAPackage("..data..") .should() .dependOnClassesThat() .resideInAPackage("..infrastructure..") dependencyCheck.check(importedClasses) } @ArchTest fun repositoryResideInAPackageCheck(importedClasses: JavaClasses) { val resideInAPackage = classes() .that() .haveSimpleNameEndingWith("RepositoryImpl") .should() .resideInAPackage("..repository") resideInAPackage.check(importedClasses) } }
1
Kotlin
3
6
2f3464f4d466e4d6ea6a29fb8bdfbf6f73b5c544
2,085
kaal-sample
MIT License