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
app/src/main/java/ru/tech/imageresizershrinker/presentation/draw_screen/viewModel/DrawViewModel.kt
T8RIN
478,710,402
false
null
package ru.tech.imageresizershrinker.presentation.draw_screen.viewModel import android.content.pm.ActivityInfo import android.graphics.Bitmap import android.net.Uri import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.exifinterface.media.ExifInterface import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.t8rin.drawbox.domain.DrawController import dagger.hilt.android.lifecycle.HiltViewModel import dev.olshevski.navigation.reimagined.navController import dev.olshevski.navigation.reimagined.navigate import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import ru.tech.imageresizershrinker.domain.image.ImageManager import ru.tech.imageresizershrinker.domain.image.Transformation import ru.tech.imageresizershrinker.domain.model.ImageData import ru.tech.imageresizershrinker.domain.model.ImageFormat import ru.tech.imageresizershrinker.domain.model.ImageInfo import ru.tech.imageresizershrinker.domain.model.ResizeType import ru.tech.imageresizershrinker.domain.saving.FileController import ru.tech.imageresizershrinker.domain.saving.SaveResult import ru.tech.imageresizershrinker.domain.saving.model.ImageSaveTarget import ru.tech.imageresizershrinker.presentation.draw_screen.components.DrawBehavior import ru.tech.imageresizershrinker.presentation.root.transformation.UpscaleTransformation import javax.inject.Inject @HiltViewModel class DrawViewModel @Inject constructor( private val fileController: FileController, private val imageManager: ImageManager<Bitmap, ExifInterface> ) : ViewModel() { var drawController: DrawController? by mutableStateOf(null) private set val navController = navController<DrawBehavior>(DrawBehavior.None) val drawBehavior get() = navController.backstack.entries.last().destination private val _uri = mutableStateOf(Uri.EMPTY) val uri: Uri by _uri val isBitmapChanged: Boolean get() = !drawController?.paths.isNullOrEmpty() private val _imageFormat = mutableStateOf(ImageFormat.Default()) val imageFormat by _imageFormat private val _isImageLoading: MutableState<Boolean> = mutableStateOf(false) val isImageLoading: Boolean by _isImageLoading private val _isSaving: MutableState<Boolean> = mutableStateOf(false) val isSaving: Boolean by _isSaving fun updateMimeType(imageFormat: ImageFormat) { _imageFormat.value = imageFormat } fun saveBitmap( onComplete: (saveResult: SaveResult) -> Unit ) = viewModelScope.launch { _isSaving.value = true withContext(Dispatchers.IO) { when (drawBehavior) { is DrawBehavior.Image -> { getBitmapFromUriWithTransformations( uri = uri, originalSize = false, transformations = listOf(UpscaleTransformation()) )?.let { bitmap -> drawController?.getBitmap()?.let { imageManager.overlayImage( image = bitmap, overlay = imageManager.resize( image = it, width = bitmap.width, height = bitmap.height, resizeType = ResizeType.Explicit )!! ) }?.let { localBitmap -> onComplete( fileController.save( ImageSaveTarget<ExifInterface>( imageInfo = ImageInfo( imageFormat = imageFormat, width = localBitmap.width, height = localBitmap.height ), originalUri = _uri.value.toString(), sequenceNumber = null, data = imageManager.compress( ImageData( image = localBitmap, imageInfo = ImageInfo( imageFormat = imageFormat, width = localBitmap.width, height = localBitmap.height ) ) ) ), keepMetadata = true ) ) } } } is DrawBehavior.Background -> { drawController?.getBitmap()?.let { imageManager.resize( image = it, width = (drawBehavior as DrawBehavior.Background).width, height = (drawBehavior as DrawBehavior.Background).height, resizeType = ResizeType.Explicit ) }?.let { localBitmap -> onComplete( fileController.save( saveTarget = ImageSaveTarget<ExifInterface>( imageInfo = ImageInfo( imageFormat = imageFormat, width = localBitmap.width, height = localBitmap.height ), originalUri = "drawing", sequenceNumber = null, data = imageManager.compress( ImageData( image = localBitmap, imageInfo = ImageInfo( imageFormat = imageFormat, width = localBitmap.width, height = localBitmap.height ) ) ) ), keepMetadata = true ) ) } } else -> null } } _isSaving.value = false } private suspend fun calculateScreenOrientationBasedOnUri(uri: Uri): Int { val bmp = imageManager.getImage(uri = uri.toString(), originalSize = false)?.image val imageRatio = (bmp?.width ?: 0) / (bmp?.height?.toFloat() ?: 1f) return if (imageRatio <= 1f) { ActivityInfo.SCREEN_ORIENTATION_PORTRAIT } else { ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE } } fun setUri(uri: Uri) { viewModelScope.launch { drawController?.clearPaths() _uri.value = uri navController.navigate( DrawBehavior.Image(calculateScreenOrientationBasedOnUri(uri)) ) } } fun updateDrawController(drawController: DrawController) { this.drawController = drawController } private suspend fun getBitmapForSharing(): Bitmap? = withContext(Dispatchers.IO) { if (drawBehavior is DrawBehavior.Image) { imageManager.getImageWithTransformations( uri = uri.toString(), originalSize = false, transformations = listOf(UpscaleTransformation()) )?.image?.let { bitmap -> return@withContext drawController?.getBitmap()?.let { imageManager.overlayImage( image = bitmap, overlay = imageManager.resize( image = it, width = bitmap.width, height = bitmap.height, resizeType = ResizeType.Explicit )!! ) } } } else if (drawBehavior is DrawBehavior.Background) { return@withContext drawController?.getBitmap()?.let { imageManager.resize( image = it, width = (drawBehavior as DrawBehavior.Background).width, height = (drawBehavior as DrawBehavior.Background).height, resizeType = ResizeType.Explicit ) } } return@withContext null } fun resetDrawBehavior() { drawController?.apply { setDrawBackground(Color.Transparent) setColor(Color.Black.toArgb()) setAlpha(100) setStrokeWidth(8f) clearPaths() } navController.navigate(DrawBehavior.None) _uri.value = Uri.EMPTY } fun startDrawOnBackground(reqWidth: Int, reqHeight: Int, color: Color) { val width = reqWidth.takeIf { it > 0 } ?: 1 val height = reqHeight.takeIf { it > 0 } ?: 1 val imageRatio = width / height.toFloat() navController.navigate( DrawBehavior.Background( orientation = if (imageRatio <= 1f) { ActivityInfo.SCREEN_ORIENTATION_PORTRAIT } else { ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE }, width = width, height = height ) ) viewModelScope.launch { withContext(Dispatchers.IO) { while (drawController?.backgroundColor != color) { drawController?.setDrawBackground(color) } } } } fun shareBitmap(onComplete: () -> Unit) { _isSaving.value = true viewModelScope.launch { getBitmapForSharing()?.let { imageManager.shareImage( ImageData( image = it, imageInfo = ImageInfo( imageFormat = imageFormat, width = it.width, height = it.height ) ), onComplete = onComplete ) } ?: onComplete() _isSaving.value = false } } suspend fun getBitmapFromUriWithTransformations( uri: Uri, transformations: List<Transformation<Bitmap>>, originalSize: Boolean = false ): Bitmap? = imageManager.getImageWithTransformations( uri.toString(), transformations, originalSize )?.image fun overlayImage( image: Bitmap, overlay: Bitmap ): Bitmap = imageManager.overlayImage(image, overlay) }
9
null
47
514
c039548b804f7d716972bd5f3648fac26a17e806
11,561
ImageToolbox
Apache License 2.0
app/src/main/java/com/example/arvag/fragments/FilterMenuFragment.kt
wahbimo
621,399,495
false
null
package com.example.arvag.fragments import android.content.Context import android.graphics.drawable.Drawable import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.Menu import android.view.View import android.view.ViewGroup import android.widget.Button import androidx.core.content.ContextCompat import androidx.fragment.app.DialogFragment import com.example.arvag.R import com.example.arvag.activities.MainActivity import com.google.android.material.button.MaterialButton /** * A dialog fragment that displays a filter menu with various sorting and filtering options. */ class FilterMenuFragment : DialogFragment() { /** * Button for sorting the items in ascending order. */ private lateinit var sortByAlphaButtonAZ: Button /** * Button for sorting the items in descending order. */ private lateinit var sortByAlphaButtonZA: Button /** * Button for sorting the items by eco score. */ private lateinit var sortByEcoScoreButton: Button /** * Button for filtering the items by nutri score. */ private lateinit var filterByNutriScoreButton: Button /** * Listener for filter icon changes. */ private var onFilterIconChangedListener: OnFilterIconChangedListener? = null /** * Listener for filter button clicks. */ private var onFilterButtonsListener: OnClickFilterButtons? = null /** * Listener for filter icon changes. */ private var listener: OnFilterIconChangedListener? = null /** * Listener for filter button clicks. */ private var listenerButtons:OnClickFilterButtons? = null /** * Sets the listener for filter icon changes. * * @param listener The listener to set. */ fun setListener(listener: OnFilterIconChangedListener) { this.listener = listener } /** * Sets the listener for filter buttons clicks. * * @param listener The listener to set. */ fun setListenerButtons(listener: OnClickFilterButtons) { this.listenerButtons = listener } /** * Called when the fragment view is created. * * @param inflater The layout inflater. * @param container The view group container. * @param savedInstanceState The saved instance state. * @return The created view. */ override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_filter_menu, container, false) } /** * Called when the fragment view is created and ready to be used. * * @param view The created view. * @param savedInstanceState The saved instance state. */ override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) sortByAlphaButtonAZ = view.findViewById(R.id.sort_by_alpha_az_button) sortByAlphaButtonZA = view.findViewById(R.id.sort_by_alpha_za_button) sortByEcoScoreButton = view.findViewById(R.id.sort_by_ecoscore_button) filterByNutriScoreButton = view.findViewById(R.id.filter_by_nutriscore_button) // Set click listeners for the buttons sortByAlphaButtonAZ.setOnClickListener { // Handle click for "Sort by A-Z" button listenerButtons?.onSortByAlphaButtonAZ() dismiss() } sortByAlphaButtonZA.setOnClickListener { // Handle click for "Sort by Z-A" button listenerButtons?.onSortByAlphaButtonZA() dismiss() } sortByEcoScoreButton.setOnClickListener { // Handle click for "Sort by Eco Score" button listenerButtons?.onSortByEcoScoreButton() dismiss() } filterByNutriScoreButton.setOnClickListener { // Handle click for "Filter by Nutri Score" button listenerButtons?.onFilterByNutriScoreButton() dismiss() } } /** * Called when the fragment is attached to a context. * * @param context The context to which the fragment is attached. */ override fun onAttach(context: Context) { super.onAttach(context) if (context is OnFilterIconChangedListener) { onFilterIconChangedListener = context } if (context is OnClickFilterButtons) { onFilterButtonsListener = context } } /** * Called when the fragment view is destroyed. */ override fun onDestroyView() { super.onDestroyView() Log.d(tag,"destroyed") listener?.onFilterIconChanged() } } /** * Listener interface for filter icon changes. */ interface OnFilterIconChangedListener { fun onFilterIconChanged() } /** * Listener interface for filter button clicks. */ interface OnClickFilterButtons{ fun onSortByAlphaButtonAZ() fun onSortByAlphaButtonZA() fun onSortByEcoScoreButton() fun onFilterByNutriScoreButton() }
3
Kotlin
0
0
b53dea1cb71f5a888707cf88a58f4617d6bb6e26
5,145
Arvag
MIT License
app/src/main/java/in/snbapps/vidmeet/ui/pages/Connection.kt
Developer-Harsh
850,676,425
false
{"Kotlin": 376020}
package `in`.snbapps.vidmeet.ui.pages import android.app.Activity import android.content.Intent import android.provider.Settings import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.ime import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Button import androidx.compose.material3.ButtonColors import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavHostController import `in`.snbapps.vidmeet.R import `in`.snbapps.vidmeet.ui.theme.dark import `in`.snbapps.vidmeet.ui.theme.high import `in`.snbapps.vidmeet.ui.theme.low import `in`.snbapps.vidmeet.ui.theme.unfocused import `in`.snbapps.vidmeet.ui.theme.white import `in`.snbapps.vidmeet.ui.theme.yellow @Composable fun ConnectionScreen(navHostController: NavHostController) { val imeInsets = WindowInsets.ime val density = LocalDensity.current val scrollState = rememberScrollState() val context = LocalContext.current Column( modifier = Modifier .background(Color.White) .fillMaxSize() .verticalScroll(scrollState) .padding(start = 20.dp, end = 20.dp, top = 40.dp, bottom = with(density) { imeInsets .getBottom(density) .toDp() }), horizontalAlignment = Alignment.CenterHorizontally, ) { IconButton(onClick = { (context as Activity).finish() }, modifier = Modifier .border(BorderStroke(1.dp, unfocused), CircleShape) .align(Alignment.Start) ) { Icon( painter = painterResource(id = R.drawable.close), contentDescription = "back", tint = dark ) } Text( text = "Internet not Connected", fontFamily = FontFamily(Font(R.font.readex_pro_bold)), fontSize = 30.sp, color = high, textAlign = TextAlign.Center, modifier = Modifier.padding(top = 40.dp) ) Text( text = "Sorry, to inform but internet is needed to operate voila application, please connect to the network to use voila app.", fontFamily = FontFamily(Font(R.font.readex_pro)), fontSize = 16.sp, color = low, textAlign = TextAlign.Center, modifier = Modifier.padding(top = 10.dp, bottom = 50.dp) ) Spacer(modifier = Modifier.weight(1f)) Button( onClick = { navHostController.popBackStack() }, modifier = Modifier.fillMaxWidth(), colors = ButtonColors(yellow, Color.Black, low, Color.Black) ) { Text( text = "Recheck Config", fontFamily = FontFamily(Font(R.font.readex_pro_medium)), fontSize = 16.sp, modifier = Modifier.padding(6.dp) ) } Spacer(modifier = Modifier.padding(top = 20.dp)) OutlinedButton( onClick = { val intent = Intent(Settings.ACTION_WIRELESS_SETTINGS) context.startActivity(intent) }, modifier = Modifier.fillMaxWidth(), border = BorderStroke(1.dp, unfocused), colors = ButtonColors(white, Color.Black, low, Color.Black) ) { Text( text = "Connect Now", fontFamily = FontFamily(Font(R.font.readex_pro_medium)), fontSize = 16.sp, modifier = Modifier.padding(6.dp) ) } Spacer(modifier = Modifier.height(70.dp)) } }
0
Kotlin
0
1
4ab351f6168e064ccb4428da2888abb65bf309a8
4,921
Voila
Apache License 2.0
compose/foundation/foundation/src/androidAndroidTest/kotlin/androidx/compose/foundation/text/selection/SelectionHandleTestUtils.kt
RikkaW
389,105,112
true
{"Java": 49060640, "Kotlin": 36832495, "Python": 336507, "AIDL": 179831, "Shell": 150493, "C++": 38342, "ANTLR": 19860, "HTML": 10802, "TypeScript": 6933, "CMake": 3330, "JavaScript": 1343}
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.text.selection import android.view.View import androidx.compose.ui.node.ExperimentalLayoutNodeApi import androidx.compose.ui.node.Owner import androidx.compose.ui.platform.AndroidOwner import androidx.compose.ui.test.junit4.ComposeTestRule import androidx.compose.ui.test.onRoot import androidx.compose.ui.unit.Dp import androidx.compose.ui.window.isPopupLayout import androidx.test.espresso.Espresso import androidx.test.espresso.Root import androidx.test.espresso.assertion.ViewAssertions import org.hamcrest.CoreMatchers import org.hamcrest.Description import org.hamcrest.Matcher import org.hamcrest.TypeSafeMatcher internal fun ComposeTestRule.doubleSelectionHandleMatches( index: Int, viewMatcher: Matcher<in View> ) { // Make sure that current measurement/drawing is finished runOnIdle { } Espresso.onView(CoreMatchers.instanceOf(Owner::class.java)) .inRoot(DoubleSelectionHandleMatcher(index)) .check(ViewAssertions.matches(viewMatcher)) } internal class DoubleSelectionHandleMatcher(val index: Int) : TypeSafeMatcher<Root>() { var popupsMatchedSoFar: Int = 0 override fun describeTo(description: Description?) { description?.appendText("DoubleSelectionHandleMatcher") } override fun matchesSafely(item: Root?): Boolean { val matches = item != null && isPopupLayout(item.decorView) if (matches) { popupsMatchedSoFar++ } return matches && popupsMatchedSoFar == index + 1 } } internal fun ComposeTestRule.rootWidth(): Dp { val nodeInteraction = onRoot() val node = nodeInteraction.fetchSemanticsNode("Failed to get screen width") @OptIn(ExperimentalLayoutNodeApi::class) val owner = node.componentNode.owner as AndroidOwner return with(owner.density) { owner.view.width.toDp() } }
0
Java
0
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
2,488
androidx
Apache License 2.0
project/src/main/kotlin/cga/exercise/game/Animation.kt
BoomGoesDaBaam
515,991,731
false
null
package cga.exercise.game class AnimatedCharacter(var duration: Float = 1f, charType: Int): Character(charType) { var frames = mutableListOf<KeyFrame>() var curKeyFrame = 0 var passedTime = 0.0f var AnimationStoppedKeyFrame = KeyFrame(0f,0f,0f,0f,0f,0f,0f,0f,0f,0f,0f,0f,0f) var animationStopped = true class KeyFrame(var leftFootRotation: Float, var rightFootRotation: Float, var leftLowerLegRotation: Float, var rightLowerLegRotation: Float, var leftUpperLegRotation: Float, var rightUpperLegRotation: Float, var leftHandRotation: Float, var rightHandRotation: Float, var leftLowerArmRotation: Float, var rightLowerArmRotation: Float, var leftUpperArmRotation: Float, var rightUpperArmRotation: Float, var headrotation: Float) fun stopAnimation() { animationStopped = true } fun startAnimation() { animationStopped = false passedTime = 0.0f } fun addKeyFrame(frame: KeyFrame) { frames.add(frame) } fun getNextKeyFrame(): KeyFrame { if(animationStopped) { return AnimationStoppedKeyFrame } return if(curKeyFrame+1 <= frames.size-1) frames[curKeyFrame+1] else frames[0] } fun getInterpolation(lastAngle: Float, nextAngle: Float, factor: Float):Float { var sign = 1 if(nextAngle < lastAngle ) sign = -1 var angle = Math.abs(lastAngle - nextAngle) return lastAngle + angle * factor * sign } fun update(dt: Float) { if(!animationStopped) { passedTime += dt while (passedTime > duration) { curKeyFrame++ passedTime -= duration } if (curKeyFrame == frames.size) curKeyFrame = 0 var vertexdata: FloatArray = player!!.meshes[0].vertexdata.clone() var lastKeyFrame = frames[curKeyFrame] var nextKeyFrame = getNextKeyFrame() var factor = passedTime / duration //abs(45-(-45)) = 90 //oldAngle + 90*factor*sign var interpolated = getInterpolation(lastKeyFrame.leftFootRotation, nextKeyFrame.leftFootRotation, factor) rotateLeftFoot(interpolated, vertexdata) interpolated = getInterpolation(lastKeyFrame.rightFootRotation, nextKeyFrame.rightFootRotation, factor) rotateRightFoot(interpolated, vertexdata) interpolated = getInterpolation(lastKeyFrame.leftLowerLegRotation, nextKeyFrame.leftLowerLegRotation, factor) rotateLeftLowerLeg(interpolated, vertexdata) interpolated = getInterpolation(lastKeyFrame.rightLowerLegRotation, nextKeyFrame.rightLowerLegRotation, factor) rotateRightLowerLeg(interpolated, vertexdata) interpolated = getInterpolation(lastKeyFrame.leftUpperLegRotation, nextKeyFrame.leftUpperLegRotation, factor) rotateLeftUpperLeg(interpolated, vertexdata) interpolated = getInterpolation(lastKeyFrame.rightUpperLegRotation, nextKeyFrame.rightUpperLegRotation, factor) rotateRightUpperLeg(interpolated, vertexdata) //interpolated = getInterpolation(lastKeyFrame.rightHandRotation, nextKeyFrame.rightHandRotation, factor) //rotateLeftHand(interpolated, vertexdata) interpolated = getInterpolation(lastKeyFrame.rightHandRotation, nextKeyFrame.rightHandRotation, factor) rotateRightHand(interpolated, vertexdata) interpolated = getInterpolation(lastKeyFrame.leftHandRotation, nextKeyFrame.leftHandRotation, factor) rotateLeftHand(interpolated, vertexdata) interpolated = getInterpolation(lastKeyFrame.leftLowerArmRotation, nextKeyFrame.leftLowerArmRotation, factor) rotateLeftLowerArm(interpolated, vertexdata) interpolated = getInterpolation(lastKeyFrame.rightLowerArmRotation, nextKeyFrame.rightLowerArmRotation, factor) rotateRightLowerArm(interpolated, vertexdata) interpolated = getInterpolation(lastKeyFrame.leftUpperArmRotation, nextKeyFrame.leftUpperArmRotation, factor) rotateLeftUpperArm(interpolated, vertexdata) interpolated = getInterpolation(lastKeyFrame.rightUpperArmRotation, nextKeyFrame.rightUpperArmRotation, factor) rotateRightUpperArm(interpolated, vertexdata) interpolated = getInterpolation(lastKeyFrame.headrotation, nextKeyFrame.headrotation, factor) rotateHead(interpolated, vertexdata) //rotateRightLowerLeg(-45.0f, vertexdata) //rotateLeftLowerLeg(-45.0f, vertexdata) player!!.meshes[0].updateVertecies(vertexdata) } else if(passedTime != -1f) { passedTime = -1f var vertexdata: FloatArray = player!!.meshes[0].vertexdata.clone() rotateLeftFoot(0f, vertexdata) rotateRightFoot(0f, vertexdata) rotateLeftLowerLeg(0f, vertexdata) rotateRightLowerLeg(0f, vertexdata) rotateLeftUpperLeg(0f, vertexdata) rotateRightUpperLeg(0f, vertexdata) rotateRightHand(0f, vertexdata) rotateLeftHand(0f, vertexdata) rotateRightLowerArm(0f, vertexdata) rotateLeftUpperArm(0f, vertexdata) rotateRightUpperArm(0f, vertexdata) rotateHead(0f, vertexdata) //rotateRightLowerLeg(-45.0f, vertexdata) //rotateLeftLowerLeg(-45.0f, vertexdata) player!!.meshes[0].updateVertecies(vertexdata) } } }
0
Kotlin
0
0
aa403ddf3bf91e1bf0b85b83cb687ab7d3f0d203
5,869
CGA-Abschlussprojekt
MIT License
src/app/src/main/java/com/example/pzar/linguisticstoolbox/LinguisticsToolbox.kt
dpurge
99,100,264
false
null
package com.example.pzar.linguisticstoolbox import android.Manifest import android.view.ViewGroup import android.widget.LinearLayout import android.support.v4.app.ActivityCompat import android.os.Bundle import android.media.MediaRecorder import android.media.MediaPlayer import android.content.pm.PackageManager import android.support.annotation.NonNull import android.Manifest.permission import android.Manifest.permission.RECORD_AUDIO import android.content.Context import android.support.design.widget.BottomNavigationView import android.support.v7.app.AppCompatActivity import android.util.Log import android.view.View import android.widget.Button import java.io.IOException import android.view.MenuItem; import android.widget.FrameLayout import android.widget.TextView /** * Created by pzar on 15.07.2017. */ class LinguisticsToolbox : AppCompatActivity() { private val LOG_TAG = "AudioRecordTest1" private val REQUEST_RECORD_AUDIO_PERMISSION = 200 private var mFileName: String? = null private var mRecordButton: RecordButton? = null private var mRecorder: MediaRecorder? = null private var mPlayButton: PlayButton? = null private var mPlayer: MediaPlayer? = null // Requesting permission to RECORD_AUDIO private var permissionToRecordAccepted = false private val permissions = arrayOf<String>(Manifest.permission.RECORD_AUDIO) private var mTextMessage: TextView? = null private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item -> when (item.itemId) { R.id.navigation_home -> { mTextMessage!!.setText(R.string.title_home) return@OnNavigationItemSelectedListener true } R.id.navigation_dashboard -> { mTextMessage!!.setText(R.string.title_dashboard) return@OnNavigationItemSelectedListener true } R.id.navigation_notifications -> { mTextMessage!!.setText(R.string.title_notifications) return@OnNavigationItemSelectedListener true } } false } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { REQUEST_RECORD_AUDIO_PERMISSION -> permissionToRecordAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED } if (!permissionToRecordAccepted) finish() } private fun onRecord(start: Boolean) { if (start) { startRecording() } else { stopRecording() } } private fun onPlay(start: Boolean) { if (start) { startPlaying() } else { stopPlaying() } } private fun startPlaying() { mPlayer = MediaPlayer() try { mPlayer!!.setDataSource(mFileName) mPlayer!!.prepare() mPlayer!!.start() } catch (e: IOException) { Log.e(LOG_TAG, "prepare() failed") } } private fun stopPlaying() { mPlayer!!.release() mPlayer = null } private fun startRecording() { mRecorder = MediaRecorder() mRecorder!!.setAudioSource(MediaRecorder.AudioSource.MIC) mRecorder!!.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP) mRecorder!!.setOutputFile(mFileName) mRecorder!!.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB) try { mRecorder!!.prepare() } catch (e: IOException) { Log.e(LOG_TAG, "prepare() failed") } mRecorder!!.start() } private fun stopRecording() { mRecorder!!.stop() mRecorder!!.reset() mRecorder!!.release() mRecorder = null } internal inner class RecordButton(ctx: Context) : Button(ctx) { var mStartRecording = true var clicker: OnClickListener = View.OnClickListener { onRecord(mStartRecording) if (mStartRecording) { setText("Stop recording") } else { setText("Start recording") } mStartRecording = !mStartRecording } init { setText("Start recording") setOnClickListener(clicker) } } internal inner class PlayButton(ctx: Context) : Button(ctx) { var mStartPlaying = true var clicker: OnClickListener = View.OnClickListener { onPlay(mStartPlaying) if (mStartPlaying) { setText("Stop playing") } else { setText("Start playing") } mStartPlaying = !mStartPlaying } init { setText("Start playing") setOnClickListener(clicker) } } override fun onCreate(icicle: Bundle?) { super.onCreate(icicle) setContentView(R.layout.activity_linguistics_toolbox) // Record to the external cache directory for visibility mFileName = getExternalCacheDir().getAbsolutePath() mFileName += "/audiorecordtest.3gp" ActivityCompat.requestPermissions(this, permissions, REQUEST_RECORD_AUDIO_PERMISSION) val ll = LinearLayout(this) mRecordButton = RecordButton(this) ll.addView(mRecordButton, LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0f)) mPlayButton = PlayButton(this) ll.addView(mPlayButton, LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0f)) val content = findViewById(R.id.content) as FrameLayout content.addView(ll) val navigation = findViewById(R.id.navigation) as BottomNavigationView navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener) } override fun onStop() { super.onStop() if (mRecorder != null) { mRecorder!!.release() mRecorder = null } if (mPlayer != null) { mPlayer!!.release() mPlayer = null } } }
0
Kotlin
0
0
375688fd59fb139523ad8fe0edd54653c690423f
6,461
LinguisticsToolbox
MIT License
network-protection/network-protection-subscription-internal/src/main/java/com/duckduckgo/networkprotection/subscription/ui/NetpVpnAccessRevokedDialogMonitor.kt
duckduckgo
78,869,127
false
{"Kotlin": 11702036, "HTML": 63593, "Ruby": 14445, "JavaScript": 8619, "C++": 1813, "CMake": 1286, "Shell": 784}
/* * Copyright (c) 2023 DuckDuckGo * * 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.duckduckgo.networkprotection.subscription.ui import android.app.Activity import com.duckduckgo.app.di.AppCoroutineScope import com.duckduckgo.browser.api.ActivityLifecycleCallbacks import com.duckduckgo.common.ui.view.dialog.TextAlertDialogBuilder import com.duckduckgo.common.ui.view.dialog.TextAlertDialogBuilder.EventListener import com.duckduckgo.common.utils.DispatcherProvider import com.duckduckgo.di.scopes.AppScope import com.duckduckgo.navigation.api.GlobalActivityStarter import com.duckduckgo.networkprotection.impl.store.NetworkProtectionRepository import com.duckduckgo.networkprotection.subscription.R.string import com.duckduckgo.subscriptions.api.SubscriptionScreens.SubscriptionScreenNoParams import com.squareup.anvil.annotations.ContributesMultibinding import dagger.SingleInstanceIn import javax.inject.Inject import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @ContributesMultibinding(AppScope::class) @SingleInstanceIn(AppScope::class) class NetpVpnAccessRevokedDialogMonitor @Inject constructor( private val networkProtectionRepository: NetworkProtectionRepository, private val globalActivityStarter: GlobalActivityStarter, @AppCoroutineScope private val coroutineScope: CoroutineScope, private val dispatcherProvider: DispatcherProvider, ) : ActivityLifecycleCallbacks { override fun onActivityResumed(activity: Activity) { super.onActivityResumed(activity) coroutineScope.launch(dispatcherProvider.io()) { if (networkProtectionRepository.vpnAccessRevoked) { withContext(dispatcherProvider.main()) { TextAlertDialogBuilder(activity) .setTitle(string.netpDialogVpnAccessRevokedTitle) .setMessage(string.netpDialogVpnAccessRevokedBody) .setPositiveButton(string.netpDialogVpnAccessRevokedPositiveAction) .setNegativeButton(string.netpDialogVpnAccessRevokedNegativeAction) .addEventListener( object : EventListener() { override fun onPositiveButtonClicked() { globalActivityStarter.start(activity, SubscriptionScreenNoParams) resetVpnAccessRevokedState() } override fun onNegativeButtonClicked() { resetVpnAccessRevokedState() } }, ) .show() } } } } private fun resetVpnAccessRevokedState() { coroutineScope.launch(dispatcherProvider.io()) { networkProtectionRepository.vpnAccessRevoked = false } } }
52
Kotlin
844
3,497
a2e3a26a33a9a077308a33b763eabdd63b1717b1
3,519
Android
Apache License 2.0
app/src/main/java/com/bitrise/app/managers/preferences/FilePreference.kt
andrespaez90
295,899,832
false
null
package com.bitrise.app.managers.preferences enum class FilePreference(val fileName: String) { DefaultPreference("SETTINGS"), InformationPreference("APPINFORMATION") }
1
Kotlin
1
0
e5e6c71041fa3c153aba6c239c76ed55b24124da
179
BitriseApp
MIT License
compose-pdf-viewer/app/src/main/java/dev/seabat/android/composepdfviewer/domain/usecase/DeleteFavoriteUseCaseContract.kt
seabat
685,948,686
false
{"Kotlin": 119827}
package dev.seabat.android.composepdfviewer.domain.usecase import dev.seabat.android.composepdfviewer.domain.entity.PdfEntity interface DeleteFavoriteUseCaseContract { suspend operator fun invoke(pdf: PdfEntity) }
0
Kotlin
0
0
ee37b6071d31a8cc027f32f1a58d2f19c3bd00ae
219
pdf-viewer
Apache License 2.0
app/src/main/java/com/example/trackmysleepquality/sleepquality/SleepQualityViewModelFactory.kt
sdadasdasdwa
648,535,226
false
null
package com.example.trackmysleepquality.sleepquality class SleepQualityViewModelFactory { }
0
Kotlin
0
0
eaa440f019bcfef7f1badd25bc257fbd607dba36
92
TrackMySleepQuality
Apache License 2.0
src/test/kotlin/com/lykke/matching/engine/utils/balance/ReservedVolumesRecalculatorTest.kt
rgrativol
117,153,696
false
null
package com.lykke.matching.engine.utils.balance import com.lykke.matching.engine.daos.Asset import com.lykke.matching.engine.daos.AssetPair import com.lykke.matching.engine.database.TestBackOfficeDatabaseAccessor import com.lykke.matching.engine.database.TestFileOrderDatabaseAccessor import com.lykke.matching.engine.database.TestReservedVolumesDatabaseAccessor import com.lykke.matching.engine.database.TestWalletDatabaseAccessor import com.lykke.matching.engine.database.buildWallet import com.lykke.matching.engine.utils.MessageBuilder.Companion.buildLimitOrder import org.junit.Before import org.junit.Test import kotlin.test.assertEquals class ReservedVolumesRecalculatorTest { private val testWalletDatabaseAccessor = TestWalletDatabaseAccessor() private val testBackOfficeDatabaseAccessor = TestBackOfficeDatabaseAccessor() private val orderBookDatabaseAccessor = TestFileOrderDatabaseAccessor() private val reservedVolumesDatabaseAccessor = TestReservedVolumesDatabaseAccessor() @Before fun setUp() { testBackOfficeDatabaseAccessor.addAsset(Asset("USD", 2)) testBackOfficeDatabaseAccessor.addAsset(Asset("EUR", 2)) testWalletDatabaseAccessor.addAssetPair(AssetPair("EURUSD", "EUR", "USD", 5)) testBackOfficeDatabaseAccessor.addAsset(Asset("BTC", 8)) testWalletDatabaseAccessor.addAssetPair(AssetPair("BTCUSD", "BTC", "USD", 8)) testWalletDatabaseAccessor.insertOrUpdateWallet(buildWallet("trustedClient", "BTC", balance = 10.0, reservedBalance = 2.0)) testWalletDatabaseAccessor.insertOrUpdateWallet(buildWallet("Client1", "USD", balance = 10.0, reservedBalance = 1.0)) testWalletDatabaseAccessor.insertOrUpdateWallet(buildWallet("Client1", "BTC", balance = 10.0, reservedBalance = 2.0)) testWalletDatabaseAccessor.insertOrUpdateWallet(buildWallet("Client1", "EUR", balance = 10.0, reservedBalance = 3.0)) testWalletDatabaseAccessor.insertOrUpdateWallet(buildWallet("Client2", "EUR", balance = 10.0, reservedBalance = 0.0)) testWalletDatabaseAccessor.insertOrUpdateWallet(buildWallet("Client2", "BTC", balance = 10.0, reservedBalance = 1.0)) orderBookDatabaseAccessor.addLimitOrder(buildLimitOrder(clientId = "trustedClient", assetId = "BTCUSD", price = 10000.0, volume = -1.0, reservedVolume = 0.5)) orderBookDatabaseAccessor.addLimitOrder(buildLimitOrder(clientId = "Client1", assetId = "BTCUSD", price = 10000.0, volume = -1.0, reservedVolume = 0.5)) orderBookDatabaseAccessor.addLimitOrder(buildLimitOrder(uid = "1", clientId = "Client1", assetId = "EURUSD", price = 10000.0, volume = -1.0, reservedVolume = 0.4)) orderBookDatabaseAccessor.addLimitOrder(buildLimitOrder(uid = "2", clientId = "Client1", assetId = "EURUSD", price = 10000.0, volume = -1.0, reservedVolume = 0.3)) orderBookDatabaseAccessor.addLimitOrder(buildLimitOrder(clientId = "Client2", assetId = "BTCUSD", price = 10000.0, volume = -1.0, reservedVolume = 1.0)) } @Test fun testRecalculateTrusted() { val recalculator = ReservedVolumesRecalculator(testWalletDatabaseAccessor, testBackOfficeDatabaseAccessor, orderBookDatabaseAccessor, reservedVolumesDatabaseAccessor, setOf("trustedClient")) recalculator.recalculate() assertEquals(0.0, testWalletDatabaseAccessor.getReservedBalance("trustedClient", "BTC")) assertEquals(0.5, testWalletDatabaseAccessor.getReservedBalance("Client1", "BTC")) assertEquals(0.0, testWalletDatabaseAccessor.getReservedBalance("Client1", "USD")) assertEquals(0.7, testWalletDatabaseAccessor.getReservedBalance("Client1", "EUR")) assertEquals(1.0, testWalletDatabaseAccessor.getReservedBalance("Client2", "BTC")) assertEquals(0.0, testWalletDatabaseAccessor.getReservedBalance("Client2", "EUR")) assertEquals(4, reservedVolumesDatabaseAccessor.corrections.size) assertEquals("1,2", reservedVolumesDatabaseAccessor.corrections.first { it.newReserved == 0.7 }.orderIds) } }
0
null
0
1
3cc9b02bf8989d3da5908533288d83097afd24e3
4,040
MatchingEngine
MIT License
compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/intrinsics/IsArrayOf.kt
JakeWharton
99,388,807
true
null
/* * Copyright 2010-2016 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.backend.jvm.intrinsics import org.jetbrains.kotlin.backend.jvm.JvmBackendContext import org.jetbrains.kotlin.ir.expressions.IrMemberAccessExpression import org.jetbrains.kotlin.resolve.descriptorUtil.module import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature import org.jetbrains.kotlin.types.Variance class IsArrayOf : IntrinsicMethod() { override fun toCallable(expression: IrMemberAccessExpression, signature: JvmMethodSignature, context: JvmBackendContext): IrIntrinsicFunction { val typeMapper = context.state.typeMapper val descriptor = expression.descriptor val builtIns = descriptor.module.builtIns assert(descriptor.typeParameters.size == 1) { "Expected only one type parameter for Any?.isArrayOf(), got: ${descriptor.typeParameters}" } /*TODO original?*/ val elementType = expression.getTypeArgument(descriptor.original.typeParameters.first())!! val arrayKtType = builtIns.getArrayType(Variance.INVARIANT, elementType) val arrayType = typeMapper.mapType(arrayKtType) return IrIntrinsicFunction.create(expression, signature, context) { it.instanceOf(arrayType) } } }
0
Kotlin
4
83
4383335168338df9bbbe2a63cb213a68d0858104
1,850
kotlin
Apache License 2.0
app/src/main/java/com/xdmpx/routesp/services/LocationService.kt
xDMPx
748,894,967
false
{"Kotlin": 52046}
package com.xdmpx.routesp.services import android.Manifest import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.Service import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.os.Binder import android.os.IBinder import android.os.Looper import android.util.Log import androidx.core.app.NotificationCompat import com.google.android.gms.location.* import com.xdmpx.routesp.R import org.osmdroid.util.GeoPoint import java.util.Calendar import java.util.Date class LocationService : Service() { private var recordedGeoPoints: ArrayList<GeoPoint> = ArrayList() private var recordedAltitudes: ArrayList<Double> = ArrayList() private lateinit var startDate: Date private lateinit var fusedLocationClient: FusedLocationProviderClient private lateinit var locationCallback: LocationCallback private var latestLocationTime: Long = 0 override fun onCreate() { super.onCreate() createNotificationChanel() } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { super.onStartCommand(intent, flags, startId) if (!::fusedLocationClient.isInitialized) { startDate = Calendar.getInstance().time latestLocationTime = startDate.time setRequestLocationUpdates() } return Service.START_STICKY } private val localBinder = LocalBinder() inner class LocalBinder : Binder() { fun getService(): LocationService = this@LocationService } override fun onBind(intent: Intent?): IBinder { return localBinder } override fun onDestroy() { fusedLocationClient.removeLocationUpdates(locationCallback) super.onDestroy() } private fun setRequestLocationUpdates() { val locationRequest = LocationRequest.Builder(2500).setPriority(Priority.PRIORITY_HIGH_ACCURACY) .setWaitForAccurateLocation(true).setGranularity(Granularity.GRANULARITY_FINE) .build() locationCallback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult) { val locations = locationResult.locations for (location in locations) { if (location.time < latestLocationTime) continue val newGeoPoint = GeoPoint(location.latitude, location.longitude) Log.d( "LocationService", "Location Updated: $location altitude: ${location.altitude}" ) recordedGeoPoints.add(newGeoPoint) recordedAltitudes.add(location.altitude) } } } fusedLocationClient = LocationServices.getFusedLocationProviderClient(this) if (checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED) fusedLocationClient.requestLocationUpdates( locationRequest, locationCallback, Looper.getMainLooper() ) } private fun createNotificationChanel() { val NOTIFICATION_CHANNEL_ID = "com.xdmpx.routesp" val channelName = "RouteSP LocationService" val channel = NotificationChannel( NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_HIGH ) channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC val manager = (getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager) manager.createNotificationChannel(channel) val notificationBuilder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID) val notification: Notification = notificationBuilder.setOngoing(true).setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("RouteSP is running").setCategory(Notification.CATEGORY_NAVIGATION) .setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE) .setOngoing(true).build() startForeground(2, notification) } fun getRecordedGeoPoints(): ArrayList<GeoPoint> { return recordedGeoPoints } fun getStartDate(): Date { return startDate } fun getRecordedGeoPointsArray(): Array<GeoPoint> { return recordedGeoPoints.toTypedArray() } fun getRecordedAltitudesArray(): Array<Double> { return recordedAltitudes.toTypedArray() } }
0
Kotlin
0
0
a60a4eb11aea160d5f4f724c736723a419e57db5
4,581
RouteSP
Apache License 2.0
app/src/main/java/com/devspacecinenow/common/model/MovieResponse.kt
Wpompeo
867,803,934
false
{"Kotlin": 22921}
package com.devspacecinenow.common.model import com.devspacecinenow.common.model.MovieDto data class MovieResponse ( val results: List<MovieDto> )
0
Kotlin
0
0
0c1c4e018c3cebb3a488a78a552da12ed0f86778
152
CineNow
The Unlicense
src/test/kotlin/io/inbot/eskotlinwrapper/manual/BulkManualTest.kt
goodhoko
281,151,501
false
null
@file:Suppress("unused") package io.inbot.eskotlinwrapper.manual import com.fasterxml.jackson.databind.ObjectMapper import io.inbot.eskotlinwrapper.AbstractElasticSearchTest import io.inbot.eskotlinwrapper.BulkIndexingSession import io.inbot.eskotlinwrapper.BulkOperation import io.inbot.eskotlinwrapper.JacksonModelReaderAndWriter import org.elasticsearch.action.bulk.BulkItemResponse import org.elasticsearch.action.support.WriteRequest import org.elasticsearch.client.indexRepository import org.elasticsearch.common.xcontent.XContentType import org.junit.jupiter.api.Test class BulkManualTest : AbstractElasticSearchTest(indexPrefix = "manual") { private data class Thing(val name: String, val amount: Long = 42) @Test fun `explain bulk indexing`() { // we have to do this twice once for printing and once for using :-) val modelReaderAndWriter = JacksonModelReaderAndWriter(Thing::class, ObjectMapper().findAndRegisterModules()) // Create a Data Access Object val thingRepository = esClient.indexRepository("things", modelReaderAndWriter) // make sure we get rid of the things index before running the rest of this thingRepository.deleteIndex() thingRepository.createIndex { source( """ { "settings": { "index": { "number_of_shards": 3, "number_of_replicas": 0, "blocks": { "read_only_allow_delete": "false" } } }, "mappings": { "properties": { "name": { "type": "text" }, "amount": { "type": "long" } } } } """, XContentType.JSON ) } KotlinForExample.markdownPageWithNavigation(bulkPage) { +""" An important part of working with Elasticsearch is adding content. While the CRUD support is useful for manipulating individual objects in an index, it is not suitable for sending large amounts of data. For that, bulk indexing should be used. The bulk API in Elasticsearch is one of the more complex APIs in ES. The Kotlin client provides a few key abstractions to make bulk indexing easy, robust, and straightforward. ## Using the Repository to bulk index Again we use our `Thing` class and `thingRepository` """ block { data class Thing(val name: String, val amount: Long = 42) } +""" To make this easy, the library comes with a ${mdLink(BulkIndexingSession::class)}. This takes care of all the boiler plate of constructing and sending bulk requests. Of course, our `IndexRepository` provides a simple `bulk` method that creates a session for you: """ blockWithOutput { // creates a BulkIndexingSession<Thing> and passes it to the block thingRepository.bulk { 1.rangeTo(500).forEach { index("doc-$it", Thing("indexed $it", 666)) } } println("Lets get one of them " + thingRepository.get("doc-100")) } +""" The `BulkIndexingSession` aggregates our `index` operations into `BulkRequest` requests and sends them to Elasticsearch for us. You can control how many operations are sent with each request by setting the `bulkSize` parameter. BulkIndexingSession implements `AutoClosable` and will send the last request when it is closed. All this is taken care off by the `bulk` method of course. In addition to `index` we have a few more operations. """ blockWithOutput { thingRepository.bulk(bulkSize = 50) { // setting create=false overwrites and is the appropriate thing // to do if you are replacing documents in bulk index("doc-1", Thing("upserted 1", 666), create = false) // you can do a safe bulk update similar to the CRUD update. // this has the disadvantage of doing 1 get per item and may not scale getAndUpdate("doc-2") { currentVersion -> // this works just like the update on the repository and it will retry a // configurable number of times. currentVersion.copy(name = "updated 2") } // if you already have the seqNo, primary term, and current version // there you can skip the get. A good way to get these efficiently would be // a scrolling search. update( id = "doc-3", // yes, these two values are wrong; but it falls back to doing a // getAndUpdate. seqNo = 12, primaryTerms = 34, original = Thing("indexed $it", 666) ) { currentVersion -> currentVersion.copy(name = "safely updated 3") } // and of course you can delete items delete("doc-4") } println(thingRepository.get("doc-1")) println(thingRepository.get("doc-2")) println(thingRepository.get("doc-3")) // should print null println(thingRepository.get("doc-4")) } +""" ## Item Callbacks An important aspect of bulk indexing is actually inspecting the response. The `BulkIndexingSession` uses a callback mechanism that allows you to respond to do something. The default implementation for this does two things: - it logs failures - it retries conflicting updates For most users this should be OK but if you want, you can do something custom: """ blockWithOutput { thingRepository.bulk( itemCallback = object : (BulkOperation<Thing>, BulkItemResponse) -> Unit { // Elasticsearch confirms what it did for each item in a bulk request // and you can implement this callback to do something custom override fun invoke(op: BulkOperation<Thing>, response: BulkItemResponse) { if (response.isFailed) { println( "${op.id}: ${op.operation.opType().name} failed, " + "code: ${response.failure.status}" ) } else { println("${op.id}: ${op.operation.opType().name} succeeded!") } } } ) { update( id = "doc-2", // these values are wrong and this will now fail instead of retry seqNo = 12, primaryTerms = 34, original = Thing("updated 2", 666) ) { currentVersion -> currentVersion.copy(name = "safely updated 3") } } println("" + thingRepository.get("doc-2")) +""" # Other parameters There are a few more parameters that you can override. """ blockWithOutput { thingRepository.bulk( // controls the number of items to send to Elasticsearch // what is optimal depends on the size of your documents and // your cluster setup. bulkSize = 10, // controls how often documents are retried by the default // item callback retryConflictingUpdates = 3, // controls how Elasticsearch refreshes and whether // the bulk request blocks until ES has refreshed or not refreshPolicy = WriteRequest.RefreshPolicy.IMMEDIATE ) { delete("doc-1") update( id = "doc-2", // these values are wrong so this will be retried seqNo = 12, primaryTerms = 34, original = Thing("updated 2", 666) ) { currentVersion -> currentVersion.copy(name = "safely updated 3") } } } } } } }
1
null
1
1
f9d50ac67d6607be78cf294aff72ed15f01aa729
9,924
es-kotlin-wrapper-client
MIT License
data/src/main/java/org/michaelbel/data/local/model/ReviewLocal.kt
Takeshi-24
304,005,827
true
{"Kotlin": 308219}
package org.michaelbel.data.local.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import java.io.Serializable @Entity(tableName = "reviews") data class ReviewLocal( @ColumnInfo(name = "review_id") @PrimaryKey val id: String = "", @ColumnInfo(name = "review_author") val author: String? = null ): Serializable
0
null
0
0
d46976dee3c1f1b2513f421fbdb630a24a533f5c
376
Moviemade
Apache License 2.0
PhoneDialHW/app/src/main/java/com/example/phonedialhw/Contact.kt
PFig420
571,829,473
false
null
package com.example.phonedialhw class Contact { var name = "Name" var number = "Phone Number" }
0
Kotlin
0
0
99dd67308b14608077f3d5982045b587120a8c7d
106
Android_HW
Apache License 2.0
src/main/java/me/shadowalzazel/mcodyssey/mobs/hostile/Ruined.kt
ShadowAlzazel
511,383,377
false
{"Kotlin": 997651}
package me.shadowalzazel.mcodyssey.mobs.hostile import me.shadowalzazel.mcodyssey.items.Weapons import me.shadowalzazel.mcodyssey.mobs.utility.OdysseyMob import net.kyori.adventure.text.Component import net.kyori.adventure.text.format.TextColor import org.bukkit.Location import org.bukkit.World import org.bukkit.enchantments.Enchantment import org.bukkit.entity.EntityType import org.bukkit.entity.Zombie import org.bukkit.potion.PotionEffect import org.bukkit.potion.PotionEffectType object Ruined : OdysseyMob("Ruined", EntityType.STRAY, 30.0) { override fun createMob(someWorld: World, spawningLocation: Location): Zombie { val savageEntity = (super.createMob(someWorld, spawningLocation) as Zombie).apply { // Effects addPotionEffects(listOf( PotionEffect(PotionEffectType.INCREASE_DAMAGE, 99999, 4), PotionEffect(PotionEffectType.FAST_DIGGING, 99999, 8) )) // Miscellaneous health = 50.0 canPickupItems = true clearActiveItem() customName(Component.text(odysseyName, TextColor.color(220, 216, 75))) // Dagger val newClaymore = Weapons.DIAMOND_CLAYMORE.createItemStack(1).apply { addUnsafeEnchantment(Enchantment.DURABILITY, 3) addUnsafeEnchantment(Enchantment.DAMAGE_ALL, 5) addUnsafeEnchantment(Enchantment.KNOCKBACK, 3) itemMeta.displayName(Component.text("Maligned Claymore")) } // Add Items equipment.also { // TODO: Custom Models it.setItemInMainHand(newClaymore) it.itemInMainHandDropChance = 0F it.itemInOffHandDropChance = 0F it.helmetDropChance = 0F it.chestplateDropChance = 0F it.leggingsDropChance = 0F it.bootsDropChance = 0F } } return savageEntity } }
0
Kotlin
0
3
c3b46fa8589efdae68224d423af3b8b33a7fc26a
2,004
MinecraftOdyssey
MIT License
beam-common/src/commonMain/kotlin/dev/d1s/beam/commons/Translation.kt
d1snin
632,895,652
false
{"Kotlin": 558952, "Shell": 2444, "JavaScript": 2406}
/* * Copyright 2023-2024 <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 dev.d1s.beam.commons import kotlinx.serialization.Serializable public typealias TranslationQualifier = String public typealias Template = String public typealias LanguageCode = String public typealias LanguageName = String public typealias TextLocation = String public typealias TranslatedText = String public typealias TranslationMap = Map<TextLocation, TranslatedText> public typealias Translations = List<Translation> public val TextLocation.asTemplate: Template get() = "\${$this}" public sealed interface AbstractTranslation { public val languageName: LanguageName? public val default: Boolean public val translations: TranslationMap } @Serializable public data class Translation( val languageCode: LanguageCode, override val languageName: LanguageName, override val default: Boolean, override val translations: TranslationMap ) : AbstractTranslation @Serializable public data class TranslationModification( override val languageName: LanguageName?, override val default: Boolean, override val translations: TranslationMap ) : AbstractTranslation
6
Kotlin
0
5
934806a6a5315092922478995aa0390c3fae4727
1,710
beam
Apache License 2.0
Smart Farming Monitor - MobileApp/app/src/main/java/com/ipv/farmmonitor/models/NotificationModel.kt
andrelopes301
588,998,139
false
null
package com.ipv.farmmonitor.models import java.io.Serializable data class Notification( var title: String = "", var body: String = "", var type: String = "", var time: Long = 0, ) : Serializable
0
Kotlin
0
1
765b27d823bc108f88f97e54fe23c12156b456b6
220
SmartFarmMonitoring
MIT License
app/src/main/java/org/covidwatch/android/presentation/util/FragmentExtensions.kt
covidwatchorg
246,964,242
false
null
package org.covidwatch.android.presentation.util import android.app.DatePickerDialog import androidx.fragment.app.Fragment import java.util.* fun Fragment.showDatePicker(callback: (date: Date) -> Unit) { val calendar = Calendar.getInstance() val dialog = DatePickerDialog( requireContext(), DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth -> calendar.set(Calendar.YEAR, year) calendar.set(Calendar.MONTH, monthOfYear) calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth) callback(calendar.time) }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH) ) dialog.datePicker.maxDate = Date().time dialog.show() }
14
Kotlin
24
52
7bb2464e5aa94842ae71a2150a5357c6c5a9fe22
787
covidwatch-android-tcn
Apache License 2.0
app/src/test/java/com/buchi/listdetail/MainViewModelTest.kt
SunnyBe
333,439,178
false
null
package com.buchi.listdetail import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.buchi.listdetail.data.model.MainEntity import com.buchi.listdetail.data.repository.MainRepository import com.buchi.listdetail.data.repository.MainRepositoryImpl import com.buchi.listdetail.presentation.MainViewModel import com.buchi.listdetail.presentation.MainViewState import com.buchi.listdetail.utils.MainCoroutineScopeRule import com.buchi.listdetail.utils.ResultState import com.buchi.listdetail.utils.getValueForTest import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.flow import kotlinx.coroutines.test.runBlockingTest import org.junit.* import org.mockito.Mock import org.mockito.Mockito import org.mockito.MockitoAnnotations @ExperimentalCoroutinesApi class MainViewModelTest { private lateinit var viewModel: MainViewModel @get:Rule val instantExecutorRule = InstantTaskExecutorRule() @get:Rule val coroutineScope = MainCoroutineScopeRule() @Mock lateinit var mainRepo: MainRepository @Before fun setUp() { MockitoAnnotations.initMocks(this) viewModel = MainViewModel(mainRepo) } @After fun cleanUp() { } @Test fun fetchUserList_Successfully_updates_dataState_withEmptyList() { coroutineScope.runBlockingTest { val testFlow = flow { emit(ResultState.data(null, MainViewState(allUser = listOf()))) } // Process viewModel.fetchAllUsers() Mockito.`when`(mainRepo.allList()).thenReturn(testFlow) // Test val expected = listOf<MainEntity.User>() Assert.assertEquals(expected, viewModel.dataState.getValueForTest()?.data?.getContentIfNotHandled()?.allUser) } } @Test fun fetchUserList_Successfully_updates_dataState_withListValidFirstItem() { coroutineScope.runBlockingTest { val testFlow = flow { emit(ResultState.data(null, MainViewState(allUser = MainEntity.User.listTestUser()))) } // Process viewModel.fetchAllUsers() Mockito.`when`(mainRepo.allList()).thenReturn(testFlow) // Test val expectedFirstItemId = "user00" Assert.assertEquals(expectedFirstItemId, viewModel.dataState.getValueForTest()?.data?.getContentIfNotHandled()?.allUser?.first()?.id) } } @Test fun fetchUserList_Successfully_updates_dataState_withListValidLastItem() { coroutineScope.runBlockingTest { val testFlow = flow { emit(ResultState.data(null, MainViewState(allUser = MainEntity.User.listTestUser()))) } // Process viewModel.fetchAllUsers() Mockito.`when`(mainRepo.allList()).thenReturn(testFlow) // Test val expectedLastItemId = "user04" Assert.assertEquals(expectedLastItemId, viewModel.dataState.getValueForTest()?.data?.getContentIfNotHandled()?.allUser?.last()?.id) } } @Test(expected = Throwable::class) fun fetchUserList_Failedto_updates_dataState_withError() { // Process viewModel.fetchAllUsers() Mockito.`when`(mainRepo.allList()).thenThrow(Throwable("A test issue occurred")) // Test val expectedErrorMsg = "A test issue occurred" Assert.assertEquals(expectedErrorMsg, (viewModel.dataState.getValueForTest()?.data?.getContentIfNotHandled()?.allUser as Throwable).message) } @Test fun fetchUserDetail_Successfully_updates_dataState_withValidUserDetail() { coroutineScope.runBlockingTest { val testFlow = flow { emit(ResultState.data(null, MainViewState(user = MainEntity.User.testUser("user03")))) } // Process viewModel.fetchUserDetail("user03") Mockito.`when`(mainRepo.userDetail("user03")).thenReturn(testFlow) // Test val expectedEmail = "<EMAIL>" Assert.assertEquals(expectedEmail, viewModel.dataState.getValueForTest()?.data?.getContentIfNotHandled()?.user?.email) } } @Test(expected = Throwable::class) fun fetchUserDetail_Failedto_updates_dataState_withError() { // Process viewModel.fetchUserDetail("user03") Mockito.`when`(mainRepo.userDetail("user03")).thenThrow(Throwable("A test issue occurred")) // Test val expectedErrorMsg = "A test issue occurred" Assert.assertEquals(expectedErrorMsg, (viewModel.dataState.getValueForTest()?.data?.getContentIfNotHandled()?.allUser as Throwable).message) } }
0
Kotlin
0
5
500d76ecac74a367fc149b4fa58a994e17fdf034
4,706
ListDetail
The Unlicense
nebulosa-indi-device/src/main/kotlin/nebulosa/indi/device/DevicePropertyChanged.kt
tiagohm
568,578,345
false
null
package nebulosa.indi.device data class DevicePropertyChanged( override val device: Device, override val property: PropertyVector<*, *>, ) : DevicePropertyEvent
2
Kotlin
0
2
9ccdfa8049d8ff034d282c065e71aec1a6ea6ab8
170
nebulosa
MIT License
MiaSample/app/src/main/java/eu/nets/miasample/network/response/PaymentResponse.kt
Nets-eCom
248,162,830
false
null
package eu.nets.miasample.network.response import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName /** * *****Copyright (c) 2020 Nets Denmark A/S***** * * 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. * */ class PaymentResponse { @Expose @SerializedName("payment") var payment: Payment? = null } class Payment { @Expose @SerializedName("orderDetails") var orderDetails: OrderDetails? = null @Expose @SerializedName("summary") var summary: Summary? = null @Expose @SerializedName("created") var created: String? = null @Expose @SerializedName("subscription") var subscription: Subscription? = null fun paymentReserved(): Boolean { return summary?.reservedAmount != null && orderDetails?.amount != null && summary?.reservedAmount == orderDetails?.amount } fun paymentCharged(): Boolean { return summary?.chargedAmount != null && orderDetails?.amount != null && summary?.chargedAmount == orderDetails?.amount } fun paymentCancelled(): Boolean { return summary?.reservedAmount == null && summary?.cancelledAmount == null && summary?.chargedAmount == null && summary?.refundedAmount == null } } class OrderDetails { @Expose @SerializedName("amount") var amount: Long? = null @Expose @SerializedName("currency") var currency: String? = null @Expose @SerializedName("reference") var reference: String? = null } class Summary { @Expose @SerializedName("cancelledAmount") var cancelledAmount: Long? = null @Expose @SerializedName("chargedAmount") var chargedAmount: Long? = null @Expose @SerializedName("refundedAmount") var refundedAmount: Long? = null @Expose @SerializedName("reservedAmount") var reservedAmount: Long? = null } class Subscription { @Expose @SerializedName("id") var id: String? = null }
16
null
3
8
c3fa84a0b50b9aa7d0d31b608dd47ff371328064
3,017
Easy-Android-SDK
RSA Message-Digest License
developer/src/main/kotlin/house/RealEstateDeveloper.kt
droidchef
574,382,897
false
{"Kotlin": 2149}
package house import dev.droidchef.contractors.WallContractor import dev.droidchef.foundation.StrongFoundation import dev.droidchef.wall.Wall class RealEstateDeveloper { fun buildASimpleRoom(): FourByFourRoom { println("Changing Something in Developer Class") val foundation = StrongFoundation() val walls = ArrayList<Wall>() for (i in 1..4) { walls.add(WallContractor.buildDryWall(5.0, 5.0, 2.0)) } return FourByFourRoom(foundation, walls) } }
0
Kotlin
0
1
7a0e9ffdcb14ecb72b5f055e38e46ac8cf2a81bd
519
dep-height-example
The Unlicense
sample/src/main/java/com/originsdigital/compositeadapter/sample/ui/sample/cell/viewbinding/SampleViewBindingMessageCell.kt
netcosports
382,011,704
false
null
package com.originsdigital.compositeadapter.sample.ui.sample.cell.viewbinding import androidx.recyclerview.widget.RecyclerView import com.originsdigital.compositeadapter.cell.Cell import com.originsdigital.compositeadapter.cell.ClickItem import com.originsdigital.compositeadapter.decoration.ItemDecoration import com.originsdigital.compositeadapter.sample.R import com.originsdigital.compositeadapter.sample.databinding.SampleViewbindingMessageListItemBinding import com.originsdigital.compositeadapter.sample.domain.entity.MessageEntity import com.originsdigital.compositeadapter.utils.getViewBinding data class SampleViewBindingMessageCell( override val data: MessageEntity, override val decoration: ItemDecoration<out Cell<*>>?, override val onClickListener: ((ClickItem<MessageEntity>) -> Unit)? ) : SampleViewBindingCell<MessageEntity> { override val uniqueId: String = data.id override val layoutId: Int = R.layout.sample_viewbinding_message_list_item override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { (holder.getViewBinding(SampleViewbindingMessageListItemBinding::bind)).apply { text.text = data.text } } }
0
Kotlin
0
10
584af1b42a89d4564f8e265d0e405f9d4913d6df
1,205
CompositeAdapter_Android
Apache License 2.0
modules/hir/src/main/kotlin/org/acornlang/hir/lower/AstLoweringVisitor.kt
mworzala
506,414,489
false
null
package org.acornlang.hir.lower import org.acornlang.ast.* import org.acornlang.hir.* class AstLoweringVisitor : AstVisitor<Unit, HirNode> { override val default: HirNode get() = HirNode.None // SECTION: Module // =============== override fun visitModule(module: AstModule, p: Unit): HirNode { val decls = module.decls.map { visit(it, p) as HirDecl } return HirModule(decls) } // SECTION: Declaration // ==================== override fun visitConstDecl(constDecl: AstConstDecl, p: Unit): HirNode { val name = constDecl.name!!.text var type: HirExpr? = null val constType = constDecl.type if (constType != null) type = visit(constType, p) as HirExpr val init = visit(constDecl.init, p) as HirExpr return HirConstDecl(name, type, init) } override fun visitNamedFnDecl(namedFnDecl: AstNamedFnDecl, p: Unit): HirNode { val paramList = namedFnDecl.params!! val params = paramList.params.map { visit(it, p) as HirFnParam } val retType = visit(namedFnDecl.retType, p) as HirExpr val body = visit(namedFnDecl.body, p) as HirBlock val fnDecl = HirFnDecl(params, retType, body) // Wrap in const val name = namedFnDecl.name!!.text return HirConstDecl(name, null, fnDecl) } override fun visitFnDecl(fnDecl: AstFnDecl, p: Unit): HirNode { val paramList = fnDecl.params!! val params = paramList.params.map { visit(it, p) as HirFnParam } val retType = visit(fnDecl.retType, p) as HirExpr val body = visit(fnDecl.body, p) as HirBlock return HirFnDecl(params, retType, body) } override fun visitFnType(fnType: AstFnType, p: Unit): HirNode { val paramList = fnType.params!! val params = paramList.params.map { visit(it, p) as HirFnParam } val retType = visit(fnType.retType, p) as HirExpr return HirFnType(params, retType) } override fun visitFnParam(fnParam: AstFnParam, p: Unit): HirNode { val name = fnParam.name!!.text val type = visit(fnParam.type, p) as? HirExpr return HirFnParam(name, type) } override fun visitNamedEnumDecl(namedEnumDecl: AstNamedEnumDecl, p: Unit): HirNode { val caseList = namedEnumDecl.cases!! val cases = caseList.cases.map { visit(it, p) as HirEnumCase } val enumDecl = HirEnumDecl(cases) // Wrap in const val name = namedEnumDecl.name!!.text return HirConstDecl(name, null, enumDecl) } override fun visitEnumDecl(enumDecl: AstEnumDecl, p: Unit): HirNode { val caseList = enumDecl.cases!! val cases = caseList.cases.map { visit(it, p) as HirEnumCase } return HirEnumDecl(cases) } override fun visitEnumCase(enumCase: AstEnumCase, p: Unit): HirNode { val name = enumCase.name!!.text return HirEnumCase(name) } override fun visitNamedStructDecl(namedStructDecl: AstNamedStructDecl, p: Unit): HirNode { val fieldList = namedStructDecl.fields!! val fields = fieldList.fields.map { visit(it, p) as HirStructField } val decls = namedStructDecl.decls.map { visit(it, p) as HirDecl } val structDecl = HirStructDecl(fields, decls) // Wrap in const val name = namedStructDecl.name!!.text return HirConstDecl(name, null, structDecl) } override fun visitStructDecl(structDecl: AstStructDecl, p: Unit): HirNode { val fieldList = structDecl.fields!! val fields = fieldList.fields.map { visit(it, p) as HirStructField } val decls = structDecl.decls.map { visit(it, p) as HirDecl } return HirStructDecl(fields, decls) } override fun visitStructField(structField: AstStructField, p: Unit): HirNode { val name = structField.name!!.text val type = visit(structField.type, p) as HirExpr return HirStructField(name, type) } override fun visitNamedUnionDecl(namedUnionDecl: AstNamedUnionDecl, p: Unit): HirNode { val memberList = namedUnionDecl.members!! val members = memberList.members.map { visit(it, p) as HirUnionMember } val decls = namedUnionDecl.decls.map { visit(it, p) as HirDecl } val unionDecl = HirUnionDecl(members, decls) // Wrap in const val name = namedUnionDecl.name!!.text return HirConstDecl(name, null, unionDecl) } override fun visitUnionDecl(unionDecl: AstUnionDecl, p: Unit): HirNode { val memberList = unionDecl.members!! val members = memberList.members.map { visit(it, p) as HirUnionMember } val decls = unionDecl.decls.map { visit(it, p) as HirDecl } return HirUnionDecl(members, decls) } override fun visitUnionMember(unionMember: AstUnionMember, p: Unit): HirNode { val name = unionMember.name!!.text val type = visit(unionMember.type, p) as HirExpr return HirUnionMember(name, type) } override fun visitNamedSpecDecl(namedSpecDecl: AstNamedSpecDecl, p: Unit): HirNode { val members = namedSpecDecl.members.map { visit(it, p) as HirDecl } val specDecl = HirSpecDecl(members) // Wrap in const val name = namedSpecDecl.name!!.text return HirConstDecl(name, null, specDecl) } override fun visitSpecDecl(specDecl: AstSpecDecl, p: Unit): HirNode { val members = specDecl.members.map { visit(it, p) as HirDecl } return HirSpecDecl(members) } // SECTION: Statement // ================== override fun visitExprStmt(exprStmt: AstExprStmt, p: Unit): HirNode { return HirExprStmt(visit(exprStmt.expr, p) as HirExpr) } override fun visitVarDecl(varDecl: AstVarDecl, p: Unit): HirNode { val name = varDecl.name!!.text val type = visit(varDecl.type, p) as? HirExpr val init = visit(varDecl.init, p) as HirExpr return HirVarDecl(name, varDecl.mut, type, init) } override fun visitReturn(returnStmt: AstReturn, p: Unit): HirNode { val expr = visit(returnStmt.expr, p) as? HirExpr return HirReturn(expr) } override fun visitBreak(breakStmt: AstBreak, p: Unit): HirNode { return HirBreak() } override fun visitContinue(continueStmt: AstContinue, p: Unit): HirNode { return HirContinue() } // SECTION: Expression // =================== override fun visitLiteral(literal: AstLiteral, p: Unit): HirNode { return when (literal.type) { AstLiteral.Type.NUMBER -> { val strValue = literal.value!!.text val longValue = strValue.toLong() //todo handle overflow and switch to bigint return HirIntLiteral(longValue) } AstLiteral.Type.BOOL -> HirBoolLiteral(literal.value!!.text == "true") AstLiteral.Type.STRING -> { val value = literal.value!!.text HirStringLiteral(value.substring(1, value.length - 1)) } } } override fun visitVarRef(varRef: AstVarRef, p: Unit): HirNode { return HirVarRef(varRef.name!!.text) } override fun visitIntrinsic(intrinsic: AstIntrinsic, p: Unit): HirNode { val name = intrinsic.name!!.text // Cut off the `!` suffix on the name, we know it is intrinsic at this point. return HirIntrinsicRef(name.substring(0, name.length - 1)) } override fun visitReference(reference: AstReference, p: Unit): HirNode { val expr = visit(reference.expr, p) as HirExpr return HirReference(reference.mut, expr) } override fun visitUnary(unary: AstUnary, p: Unit): HirNode { val operator = when (val operatorStr = unary.operator!!.text) { "-" -> HirUnary.Operator.NEG "!" -> HirUnary.Operator.NOT else -> throw IllegalArgumentException("Unknown unary operator: $operatorStr") } val operand = visit(unary.operand, p) as HirExpr return HirUnary(operator, operand) } override fun visitBinary(binary: AstBinary, p: Unit): HirNode { val operator = when (val operatorStr = binary.operator!!.text) { "+" -> HirBinary.Operator.ADD "-" -> HirBinary.Operator.SUB "*" -> HirBinary.Operator.MUL "/" -> HirBinary.Operator.DIV "==" -> HirBinary.Operator.EQ "!=" -> HirBinary.Operator.NE "<" -> HirBinary.Operator.LT "<=" -> HirBinary.Operator.LE ">" -> HirBinary.Operator.GT ">=" -> HirBinary.Operator.GE "&&" -> HirBinary.Operator.AND "||" -> HirBinary.Operator.OR else -> throw IllegalArgumentException("Unknown binary operator: $operatorStr") } val lhs = visit(binary.lhs, p) as HirExpr val rhs = visit(binary.rhs, p) as HirExpr return HirBinary(operator, lhs, rhs) } override fun visitParenGroup(parenGroup: AstParenGroup, p: Unit): HirNode { return visit(parenGroup.expr, p) as HirExpr } override fun visitAssign(assign: AstAssign, p: Unit): HirNode { val target = visit(assign.target, p) as HirExpr val value = visit(assign.expr, p) as HirExpr return HirAssign(target, value) } override fun visitMemberAccess(memberAccess: AstMemberAccess, p: Unit): HirNode { val target = visit(memberAccess.target, p) as HirExpr val memberAst = memberAccess.member as AstVarRef // It must be a var ref, only strings are allowed. val member = memberAst.name!!.text return HirMemberAccess(target, member) } override fun visitTypeUnion(typeUnion: AstTypeUnion, p: Unit): HirNode { val lhs = visit(typeUnion.lhs, p) as HirExpr val rhs = visit(typeUnion.rhs, p) as HirExpr return HirTypeUnion(lhs, rhs) } override fun visitIndex(index: AstIndex, p: Unit): HirNode { val target = visit(index.target, p) as HirExpr val value = visit(index.expr, p) as HirExpr return HirIndex(target, value) } override fun visitArrayLiteral(arrayLiteral: AstArrayLiteral, p: Unit): HirNode { val values = arrayLiteral.exprs.map { visit(it, p) as HirExpr } return HirArrayLiteral(values) } override fun visitTupleLiteral(tupleLiteral: AstTupleLiteral, p: Unit): HirNode { val values = tupleLiteral.exprs.map { visit(it, p) as HirExpr } return HirTupleLiteral(values) } override fun visitBlock(block: AstBlock, p: Unit): HirNode { val stmts = block.stmts.map { visit(it, p) as HirStmt } return HirBlock(stmts) } override fun visitImplicitReturn(implicitReturn: AstImplicitReturn, p: Unit): HirNode { val expr = visit(implicitReturn.expr, p) as HirExpr return HirImplicitReturn(expr) } override fun visitConstruct(construct: AstConstruct, p: Unit): HirNode { val target = visit(construct.target, p) as HirExpr val fields = construct.fields!! val args = fields.fields.map { visit(it, p) as HirConstructArg } return HirConstruct(target, args) } override fun visitConstructField(constructField: AstConstructField, p: Unit): HirNode { val name = constructField.name!!.text val value = visit(constructField.expr, p) as HirExpr return HirConstructArg(name, value) } override fun visitCall(call: AstCall, p: Unit): HirNode { val target = visit(call.target, p) as HirExpr val argList = call.args!! val args = argList.args.map { visit(it, p) as HirExpr } return HirCall(target, args) } override fun visitIf(ifStmt: AstIf, p: Unit): HirNode { val cond = visit(ifStmt.cond, p) as HirExpr val thenBranch = visit(ifStmt.thenBranch, p) as HirBlock val elseBranch = visit(ifStmt.elseBranch, p) as? HirBlock return HirIf(cond, thenBranch, elseBranch) } override fun visitWhile(whileStmt: AstWhile, p: Unit): HirNode { val cond = visit(whileStmt.cond, p) as HirExpr val body = visit(whileStmt.body, p) as HirBlock return HirWhile(cond, body) } }
1
Kotlin
0
0
f1b2565aa7c3f0d17f516ce594f96c3eb27a7407
12,317
acorn-interpreter
Apache License 2.0
starter/sisyphus-grpc-server-starter/src/main/kotlin/com/bybutter/sisyphus/starter/grpc/support/SisyphusGrpcServerInterceptor.kt
ButterCam
264,589,207
false
null
package com.bybutter.sisyphus.starter.grpc.support import com.bybutter.sisyphus.protobuf.Message import com.bybutter.sisyphus.starter.grpc.StatusRenderer import io.grpc.Context import io.grpc.Contexts import io.grpc.ForwardingServerCall import io.grpc.ForwardingServerCallListener import io.grpc.Metadata import io.grpc.ServerCall import io.grpc.ServerCallHandler import io.grpc.ServerInterceptor import io.grpc.Status import org.springframework.beans.factory.annotation.Autowired import org.springframework.core.Ordered import org.springframework.core.annotation.Order import org.springframework.stereotype.Component @Component @Order(Ordered.HIGHEST_PRECEDENCE + 1000) class SisyphusGrpcServerInterceptor : ServerInterceptor { @Autowired(required = false) private var loggers: List<RequestLogger> = listOf() @Autowired(required = false) private var statusRenderers: List<StatusRenderer> = listOf() private val uniqueLoggers: List<RequestLogger> by lazy { val addedLogger = mutableSetOf<String>() loggers.mapNotNull { if (it.id.isNotEmpty() && addedLogger.contains(it.id)) return@mapNotNull null addedLogger += it.id it } } private val uniqueIncomingLoggers: List<IncomingRequestLogger> by lazy { val addedLogger = mutableSetOf<String>() loggers.mapNotNull { if (it !is IncomingRequestLogger) return@mapNotNull null if (it.id.isNotEmpty() && addedLogger.contains(it.id)) return@mapNotNull null addedLogger += it.id it } } override fun <ReqT : Any, RespT : Any> interceptCall( call: ServerCall<ReqT, RespT>, headers: Metadata, next: ServerCallHandler<ReqT, RespT> ): ServerCall.Listener<ReqT> { val context = Context.current().withValue(RequestLogger.REQUEST_CONTEXT_KEY, RequestInfo(headers)) logIncomingRequest(call, headers) return try { Contexts.interceptCall( context, SisyphusGrpcServerCall(call, uniqueLoggers, statusRenderers), headers ) { call, headers -> SisyphusGrpcServerCallListener(next.startCall(call, headers)) } } catch (e: Exception) { throw e } } private class SisyphusGrpcServerCall<ReqT, RespT>( call: ServerCall<ReqT, RespT>, private val loggers: List<RequestLogger>, private val statusRenderers: List<StatusRenderer> ) : ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT>(call) { private val requestNanoTime = System.nanoTime() private fun renderStatus(status: Status, trailers: Metadata): Status { statusRenderers.forEach { if (it.canRender(status)) { it.render(status, trailers)?.let { return it } } } return status } override fun close(status: Status, trailers: Metadata) { val status = renderStatus(status, trailers) RequestLogger.REQUEST_CONTEXT_KEY.get().apply { outputTrailers = trailers logRequest(status, this) } return super.close(status, trailers) } override fun sendMessage(message: RespT) { RequestLogger.REQUEST_CONTEXT_KEY.get()?.outputMessage?.apply { this += message as Message<*, *> } super.sendMessage(message) } private fun logRequest(status: Status, requestInfo: RequestInfo) { val cost = System.nanoTime() - requestNanoTime try { for (logger in loggers) { logger.log(this, requestInfo, status, cost) } } catch (e: Exception) { // Ignore } } } private fun logIncomingRequest(call: ServerCall<*, *>, headers: Metadata) { try { for (logger in uniqueIncomingLoggers) { logger.log(call, headers) } } catch (e: Exception) { // Ignore } } private class SisyphusGrpcServerCallListener<T>(listener: ServerCall.Listener<T>) : ForwardingServerCallListener.SimpleForwardingServerCallListener<T>(listener) { override fun onMessage(message: T) { RequestLogger.REQUEST_CONTEXT_KEY.get()?.inputMessage?.apply { this += message as Message<*, *> } super.onMessage(message) } } }
9
null
11
92
1f9851c7c45030fa08e018e961110851e029f940
4,642
sisyphus
MIT License
app/src/main/java/ru/tech/imageresizershrinker/presentation/single_edit_screen/SingeEditScreen.kt
T8RIN
478,710,402
false
null
package ru.tech.imageresizershrinker.presentation.single_edit_screen import android.content.res.Configuration import android.net.Uri import androidx.activity.ComponentActivity import androidx.activity.compose.BackHandler import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.scaleIn import androidx.compose.animation.scaleOut import androidx.compose.foundation.LocalIndication import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.indication import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.PressInteraction import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.asPaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.ime import androidx.compose.foundation.layout.navigationBars import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.rounded.ArrowBack import androidx.compose.material.icons.outlined.Share import androidx.compose.material.icons.rounded.Compare import androidx.compose.material.icons.rounded.History import androidx.compose.material.icons.rounded.RestartAlt import androidx.compose.material.icons.rounded.ZoomIn import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.LargeTopAppBar import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.rememberTopAppBarState import androidx.compose.material3.surfaceColorAtElevation import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.t8rin.dynamic.theme.LocalDynamicThemeState import dev.olshevski.navigation.reimagined.hilt.hiltViewModel import kotlinx.coroutines.delay import kotlinx.coroutines.launch import ru.tech.imageresizershrinker.R import ru.tech.imageresizershrinker.presentation.root.utils.confetti.LocalConfettiController import ru.tech.imageresizershrinker.presentation.root.utils.helper.Picker import ru.tech.imageresizershrinker.presentation.root.utils.helper.localImagePickerMode import ru.tech.imageresizershrinker.presentation.root.utils.helper.parseSaveResult import ru.tech.imageresizershrinker.presentation.root.utils.helper.rememberImagePicker import ru.tech.imageresizershrinker.presentation.root.widget.buttons.BottomButtonsBlock import ru.tech.imageresizershrinker.presentation.root.widget.controls.ExtensionGroup import ru.tech.imageresizershrinker.presentation.root.widget.controls.ImageExtraTransformBar import ru.tech.imageresizershrinker.presentation.root.widget.controls.ImageTransformBar import ru.tech.imageresizershrinker.presentation.root.widget.controls.PresetWidget import ru.tech.imageresizershrinker.presentation.root.widget.controls.QualityWidget import ru.tech.imageresizershrinker.presentation.root.widget.controls.ResizeImageField import ru.tech.imageresizershrinker.presentation.root.widget.controls.resize_group.ResizeGroup import ru.tech.imageresizershrinker.presentation.root.widget.dialogs.ExitWithoutSavingDialog import ru.tech.imageresizershrinker.presentation.root.widget.dialogs.ResetDialog import ru.tech.imageresizershrinker.presentation.root.widget.image.ImageContainer import ru.tech.imageresizershrinker.presentation.root.widget.image.ImageNotPickedWidget import ru.tech.imageresizershrinker.presentation.root.widget.image.imageStickyHeader import ru.tech.imageresizershrinker.presentation.root.widget.modifier.container import ru.tech.imageresizershrinker.presentation.root.widget.modifier.drawHorizontalStroke import ru.tech.imageresizershrinker.presentation.root.widget.modifier.navBarsLandscapePadding import ru.tech.imageresizershrinker.presentation.root.widget.other.LoadingDialog import ru.tech.imageresizershrinker.presentation.root.widget.other.LocalToastHost import ru.tech.imageresizershrinker.presentation.root.widget.other.TopAppBarEmoji import ru.tech.imageresizershrinker.presentation.root.widget.other.showError import ru.tech.imageresizershrinker.presentation.root.widget.sheets.CompareSheet import ru.tech.imageresizershrinker.presentation.root.widget.sheets.ZoomModalSheet import ru.tech.imageresizershrinker.presentation.root.widget.text.TopAppBarTitle import ru.tech.imageresizershrinker.presentation.root.widget.utils.LocalSettingsState import ru.tech.imageresizershrinker.presentation.root.widget.utils.LocalWindowSizeClass import ru.tech.imageresizershrinker.presentation.root.widget.utils.isExpanded import ru.tech.imageresizershrinker.presentation.root.widget.utils.middleImageState import ru.tech.imageresizershrinker.presentation.single_edit_screen.components.CropEditOption import ru.tech.imageresizershrinker.presentation.single_edit_screen.components.DrawEditOption import ru.tech.imageresizershrinker.presentation.single_edit_screen.components.EditExifSheet import ru.tech.imageresizershrinker.presentation.single_edit_screen.components.EraseBackgroundEditOption import ru.tech.imageresizershrinker.presentation.single_edit_screen.components.FilterEditOption import ru.tech.imageresizershrinker.presentation.single_edit_screen.viewModel.SingleEditViewModel @OptIn(ExperimentalMaterial3Api::class) @Composable fun SingleEditScreen( uriState: Uri?, onGoBack: () -> Unit, viewModel: SingleEditViewModel = hiltViewModel(), ) { val settingsState = LocalSettingsState.current val toastHostState = LocalToastHost.current val context = LocalContext.current as ComponentActivity val themeState = LocalDynamicThemeState.current val allowChangeColor = settingsState.allowChangeColorByImage val scope = rememberCoroutineScope() val confettiController = LocalConfettiController.current val showConfetti: () -> Unit = { scope.launch { confettiController.showEmpty() } } LaunchedEffect(uriState) { uriState?.let { viewModel.setUri(it) viewModel.decodeBitmapByUri( uri = it, onGetMimeType = viewModel::setMime, onGetExif = viewModel::updateExif, onGetBitmap = viewModel::updateBitmap, onError = { scope.launch { toastHostState.showError(context, it) } } ) } } LaunchedEffect(viewModel.bitmap) { viewModel.bitmap?.let { if (allowChangeColor) { themeState.updateColorByImage(it) } } } val focus = LocalFocusManager.current var showResetDialog by rememberSaveable { mutableStateOf(false) } var showOriginal by rememberSaveable { mutableStateOf(false) } var showExitDialog by rememberSaveable { mutableStateOf(false) } val bitmapInfo = viewModel.imageInfo val pickImageLauncher = rememberImagePicker( mode = localImagePickerMode(Picker.Single) ) { uris -> uris.takeIf { it.isNotEmpty() }?.firstOrNull()?.let { viewModel.setUri(it) viewModel.decodeBitmapByUri( uri = it, onGetMimeType = viewModel::setMime, onGetExif = viewModel::updateExif, onGetBitmap = viewModel::updateBitmap, onError = { scope.launch { toastHostState.showError(context, it) } } ) } } val pickImage = pickImageLauncher::pickImage val saveBitmap: () -> Unit = { viewModel.saveBitmap { saveResult -> parseSaveResult( saveResult = saveResult, onSuccess = showConfetti, toastHostState = toastHostState, scope = scope, context = context ) } } val imageInside = LocalConfiguration.current.orientation != Configuration.ORIENTATION_LANDSCAPE || LocalWindowSizeClass.current.widthSizeClass == WindowWidthSizeClass.Compact var imageState by remember { mutableStateOf(middleImageState()) } val imageBlock = @Composable { ImageContainer( imageInside = imageInside, showOriginal = showOriginal, previewBitmap = viewModel.previewBitmap, originalBitmap = viewModel.initialBitmap, isLoading = viewModel.isImageLoading, shouldShowPreview = viewModel.shouldShowPreview ) } val actions: @Composable RowScope.() -> Unit = { IconButton( onClick = { viewModel.shareBitmap( onComplete = showConfetti ) }, enabled = viewModel.previewBitmap != null ) { Icon(Icons.Outlined.Share, null) } val interactionSource = remember { MutableInteractionSource() } IconButton( enabled = viewModel.bitmap != null, onClick = { showResetDialog = true } ) { Icon( imageVector = Icons.Rounded.RestartAlt, contentDescription = null ) } if (viewModel.bitmap != null && viewModel.canShow()) { Box( modifier = Modifier .clip(CircleShape) .indication( interactionSource, LocalIndication.current ) .pointerInput(Unit) { detectTapGestures( onPress = { val press = PressInteraction.Press(it) interactionSource.emit(press) if (viewModel.canShow()) { showOriginal = true } tryAwaitRelease() showOriginal = false interactionSource.emit( PressInteraction.Release( press ) ) } ) } ) { Icon( Icons.Rounded.History, null, tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier .align(Alignment.Center) .padding(8.dp) ) } } else { IconButton( enabled = false, onClick = {} ) { Icon(Icons.Rounded.History, null) } } } val buttons = @Composable { BottomButtonsBlock( targetState = (viewModel.bitmap == null) to imageInside, onPickImage = pickImage, onSaveBitmap = saveBitmap, actions = { if (imageInside) actions() } ) } val topAppBarState = rememberTopAppBarState() val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior( state = topAppBarState, canScroll = { !imageState.isExpanded() && !showOriginal } ) LaunchedEffect(imageState, showOriginal) { if (imageState.isExpanded() || showOriginal) { while (topAppBarState.heightOffset > topAppBarState.heightOffsetLimit) { topAppBarState.heightOffset -= 5f delay(1) } } } val showSheet = rememberSaveable { mutableStateOf(false) } val zoomButton = @Composable { AnimatedVisibility( visible = viewModel.bitmap != null && viewModel.shouldShowPreview, enter = fadeIn() + scaleIn(), exit = fadeOut() + scaleOut() ) { IconButton( onClick = { showSheet.value = true } ) { Icon(Icons.Rounded.ZoomIn, null) } } } val showCompareSheet = rememberSaveable { mutableStateOf(false) } val compareButton = @Composable { AnimatedVisibility( visible = viewModel.bitmap != null && viewModel.shouldShowPreview, enter = fadeIn() + scaleIn(), exit = fadeOut() + scaleOut() ) { IconButton( onClick = { showCompareSheet.value = true } ) { Icon(Icons.Rounded.Compare, null) } } } CompareSheet( data = viewModel.initialBitmap to viewModel.previewBitmap, visible = showCompareSheet ) ZoomModalSheet( bitmap = viewModel.previewBitmap, visible = showSheet ) val onBack = { if (bitmapInfo.haveChanges(viewModel.bitmap)) showExitDialog = true else onGoBack() } var showCropper by rememberSaveable { mutableStateOf(false) } var showFiltering by rememberSaveable { mutableStateOf(false) } var showDrawing by rememberSaveable { mutableStateOf(false) } var showEraseBackground by rememberSaveable { mutableStateOf(false) } val controls: @Composable () -> Unit = { val showEditExifDialog = rememberSaveable { mutableStateOf(false) } ImageTransformBar( onEditExif = { showEditExifDialog.value = true }, imageFormat = viewModel.imageInfo.imageFormat, onRotateLeft = viewModel::rotateLeft, onFlip = viewModel::flip, onRotateRight = viewModel::rotateRight ) Spacer(Modifier.size(8.dp)) ImageExtraTransformBar( onCrop = { showCropper = true }, onFilter = { showFiltering = true }, onDraw = { showDrawing = true }, onEraseBackground = { showEraseBackground = true } ) Spacer(Modifier.size(16.dp)) PresetWidget( selectedPreset = viewModel.presetSelected, includeTelegramOption = true, onPresetSelected = viewModel::setPreset ) Spacer(Modifier.size(8.dp)) ResizeImageField( imageInfo = bitmapInfo, originalSize = viewModel.originalSize, onHeightChange = viewModel::updateHeight, onWidthChange = viewModel::updateWidth, showWarning = viewModel.showWarning ) if (bitmapInfo.imageFormat.canChangeCompressionValue) Spacer( Modifier.height(8.dp) ) QualityWidget( imageFormat = bitmapInfo.imageFormat, enabled = viewModel.bitmap != null, quality = bitmapInfo.quality.coerceIn(0f, 100f), onQualityChange = viewModel::setQuality ) Spacer(Modifier.height(8.dp)) ExtensionGroup( enabled = viewModel.bitmap != null, imageFormat = bitmapInfo.imageFormat, onFormatChange = viewModel::setMime ) Spacer(Modifier.height(8.dp)) ResizeGroup( enabled = viewModel.bitmap != null, resizeType = bitmapInfo.resizeType, onResizeChange = viewModel::setResizeType ) EditExifSheet( visible = showEditExifDialog, exif = viewModel.exif, onClearExif = viewModel::clearExif, onUpdateTag = viewModel::updateExifByTag, onRemoveTag = viewModel::removeExifTag ) } Surface( color = MaterialTheme.colorScheme.background, modifier = Modifier .fillMaxSize() .pointerInput(Unit) { detectTapGestures( onTap = { focus.clearFocus() } ) } ) { Box( Modifier .fillMaxSize() .nestedScroll(scrollBehavior.nestedScrollConnection) ) { Column(Modifier.fillMaxSize()) { LargeTopAppBar( scrollBehavior = scrollBehavior, modifier = Modifier.drawHorizontalStroke(), title = { TopAppBarTitle( title = stringResource(R.string.single_edit), input = viewModel.bitmap, isLoading = viewModel.isImageLoading, size = viewModel.imageInfo.sizeInBytes.toLong() ) }, colors = TopAppBarDefaults.centerAlignedTopAppBarColors( containerColor = MaterialTheme.colorScheme.surfaceColorAtElevation( 3.dp ) ), navigationIcon = { IconButton( onClick = onBack ) { Icon(Icons.AutoMirrored.Rounded.ArrowBack, null) } }, actions = { if (viewModel.bitmap == null) { TopAppBarEmoji() } compareButton() zoomButton() if (!imageInside && viewModel.bitmap != null) actions() } ) Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center, ) { if (!imageInside && viewModel.bitmap != null) { Box( Modifier .container( RectangleShape, color = MaterialTheme.colorScheme.surfaceContainer ) .weight(1.2f) .padding(20.dp) ) { Box(Modifier.align(Alignment.Center)) { imageBlock() } } } LazyColumn( contentPadding = PaddingValues( bottom = WindowInsets .navigationBars .asPaddingValues() .calculateBottomPadding() + WindowInsets.ime .asPaddingValues() .calculateBottomPadding() + (if (!imageInside && viewModel.bitmap != null) 20.dp else 100.dp), top = if (viewModel.bitmap == null || !imageInside) 20.dp else 0.dp, start = 20.dp, end = 20.dp ), modifier = Modifier .weight(1f) .clipToBounds() ) { imageStickyHeader( visible = imageInside && viewModel.bitmap != null, expanded = showOriginal, imageState = imageState, onStateChange = { imageState = it }, imageBlock = imageBlock ) item { Column( modifier = Modifier .fillMaxSize() .navBarsLandscapePadding(viewModel.bitmap == null), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { if (imageInside && viewModel.bitmap == null) imageBlock() if (viewModel.bitmap != null) { controls() } else if (!viewModel.isImageLoading) { ImageNotPickedWidget(onPickImage = pickImage) } } } } if (!imageInside && viewModel.bitmap != null) { buttons() } } } if (imageInside || viewModel.bitmap == null) { Box( modifier = Modifier.align(settingsState.fabAlignment) ) { buttons() } } ResetDialog( visible = showResetDialog, onDismiss = { showResetDialog = false }, onReset = { viewModel.resetValues(true) } ) ExitWithoutSavingDialog( onExit = onGoBack, onDismiss = { showExitDialog = false }, visible = showExitDialog ) if (viewModel.isSaving) LoadingDialog(onCancelLoading = viewModel::cancelSaving) BackHandler(onBack = onBack) } } CropEditOption( visible = showCropper, onDismiss = { showCropper = false }, useScaffold = imageInside, bitmap = viewModel.previewBitmap, onGetBitmap = viewModel::updateBitmapAfterEditing, cropProperties = viewModel.cropProperties, setCropAspectRatio = viewModel::setCropAspectRatio, setCropMask = viewModel::setCropMask, loadImage = viewModel::loadImage ) FilterEditOption( visible = showFiltering, onDismiss = { showFiltering = false viewModel.clearFilterList() }, useScaffold = imageInside, bitmap = viewModel.previewBitmap, onGetBitmap = viewModel::updateBitmapAfterEditing, imageManager = viewModel.getImageManager(), filterList = viewModel.filterList, updateOrder = viewModel::updateOrder, updateFilter = viewModel::updateFilter, removeAt = viewModel::removeFilterAtIndex, addFilter = viewModel::addFilter ) DrawEditOption( imageManager = viewModel.getImageManager(), visible = showDrawing, onDismiss = { showDrawing = false viewModel.clearDrawing() }, useScaffold = imageInside, bitmap = viewModel.previewBitmap, onGetBitmap = { viewModel.updateBitmapAfterEditing(it) viewModel.clearDrawing() }, orientation = remember(viewModel.previewBitmap) { viewModel.calculateScreenOrientationBasedOnBitmap(viewModel.previewBitmap) }, undo = viewModel::undoDraw, redo = viewModel::redoDraw, paths = viewModel.drawPaths, lastPaths = viewModel.drawLastPaths, undonePaths = viewModel.drawUndonePaths, addPath = viewModel::addPathToDrawList ) EraseBackgroundEditOption( visible = showEraseBackground, onDismiss = { showEraseBackground = false viewModel.clearErasing() }, useScaffold = imageInside, bitmap = viewModel.previewBitmap, orientation = remember(viewModel.previewBitmap) { viewModel.calculateScreenOrientationBasedOnBitmap(viewModel.previewBitmap) }, onGetBitmap = viewModel::updateBitmapAfterEditing, clearErasing = viewModel::clearErasing, undo = viewModel::undoErase, redo = viewModel::redoErase, paths = viewModel.erasePaths, lastPaths = viewModel.eraseLastPaths, undonePaths = viewModel.eraseUndonePaths, addPath = viewModel::addPathToEraseList, imageManager = viewModel.getImageManager() ) }
21
null
77
979
7d164a02c463afede47c785f8b182c954abfcde9
26,009
ImageToolbox
Apache License 2.0
domain/src/main/java/com/duyp/architecture/clean/redux/domain/Constants.kt
duyp
204,230,842
false
{"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 2, "XML": 49, "Fluent": 9, "FreeMarker": 1, "Kotlin": 88, "INI": 2, "Proguard": 2, "Java": 6, "JSON": 2}
package com.duyp.architecture.clean.redux.domain object DomainConstants { const val FIRST_PAGE = 1 }
0
Kotlin
1
2
881bf42f3d5c5c285174aede9645c91994e80095
106
android-redux
MIT License
Newsify/app/src/main/java/com/example/newsify/adapters/OnAdapterClickListener.kt
Shubh-1-am
605,701,193
false
null
package com.example.newsify.adapters import com.example.newsify.retrofit.response.Article interface OnAdapterClickListener { fun onAdapterClick(article : Article); }
0
Kotlin
0
0
639165d684768525203ce06e9eb76f8b0409a5a7
171
Newsify
MIT License
src/main/kotlin/ro/sorin/todolist/service/TodoListService.kt
sorinirimies
158,558,072
false
null
package ro.sorin.todolist.service import org.jetbrains.exposed.sql.* import ro.sorin.todolist.model.ChangeType import ro.sorin.todolist.model.DbUpdater import ro.sorin.todolist.model.TodoItem import ro.sorin.todolist.model.TodoItems import ro.sorin.todolist.util.dbQuery class TodoListService : TodoListApi { private val listeners = mutableMapOf<Int, suspend (DbUpdater<TodoItem?>) -> Unit>() override fun addChangeListener(id: Int, listener: suspend (DbUpdater<TodoItem?>) -> Unit) { listeners[id] = listener } override fun removeChangeListener(id: Int) = listeners.remove(id) private suspend fun onChange(type: ChangeType, id: Int, entity: TodoItem? = null) { listeners.values.forEach { it.invoke(DbUpdater(type, id, entity)) } } override suspend fun getAllTodoItems(): List<TodoItem> = dbQuery { TodoItems.selectAll().asSequence().map { toTodoItem(it) }.toList() } private fun toTodoItem(row: ResultRow): TodoItem = TodoItem( id = row[TodoItems.id], name = row[TodoItems.name], quantity = row[TodoItems.quantity], dateUpdated = row[TodoItems.dateUpdated] ) override suspend fun getTodoItem(id: Int): TodoItem? = dbQuery { TodoItems.select { TodoItems.id.eq(id) }.asSequence().mapNotNull { toTodoItem(it) }.singleOrNull() } override suspend fun addTodoItem(message: TodoItem): TodoItem? { var key: Int? = 0 dbQuery { key = TodoItems.insert { it -> it[name] = message.name it[quantity] = message.quantity it[dateUpdated] = message.dateUpdated } get TodoItems.id } return key?.let { getTodoItem(it) } } override suspend fun updateTodoItem(todoItem: TodoItem): TodoItem? { val id = todoItem.id return if (id == null) { addTodoItem(todoItem) } else { dbQuery { TodoItems.update({ TodoItems.id eq id }) { it[name] = todoItem.name it[quantity] = todoItem.quantity it[dateUpdated] = System.currentTimeMillis() } } getTodoItem(id).also { onChange(ChangeType.UPDATE, id, it) } } } override suspend fun deleteTodoItem(id: Int): Boolean = dbQuery { TodoItems.deleteWhere { TodoItems.id eq id } > 0 } }
0
Kotlin
1
0
ea0e1c9f150f07210c95b6807945ebc9ad4c077f
2,472
todolist
Apache License 2.0
common/src/main/java/com/allsoftdroid/common/base/network/StoreUtils.kt
pravinyo
209,936,085
false
null
package com.allsoftdroid.common.base.network import android.content.Context object StoreUtils { fun getStoreUrl(context:Context) : String{ return "https://play.google.com/store/apps/details?id=${context.packageName}" } }
3
null
4
12
8358f69c0cf8dbde18904b0c3a304ec89b518c9b
238
AudioBook
MIT License
app/src/main/java/com/geovnn/meteoapuane/di/AppModule.kt
geovnn
806,232,559
false
{"Kotlin": 242411}
package com.geovnn.meteoapuane.di import com.geovnn.meteoapuane.data.remote.MeteoapuaneApi import com.geovnn.meteoapuane.data.repository.MeteoRepositoryImplementation import com.geovnn.meteoapuane.domain.repository.MeteoRepository import com.geovnn.meteoapuane.domain.use_cases.GetConfiniPage import com.geovnn.meteoapuane.domain.use_cases.GetHomePage import com.geovnn.meteoapuane.domain.use_cases.GetMontagnaPage import com.geovnn.meteoapuane.domain.use_cases.GetProvinciaPage import com.geovnn.meteoapuane.domain.use_cases.GetViabilitaPage import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object AppModule { @Provides @Singleton fun provideMeteoapuaneApi(): MeteoapuaneApi { return MeteoapuaneApi() } @Provides @Singleton fun provideMeteoRepository(api: MeteoapuaneApi): MeteoRepository { return MeteoRepositoryImplementation(api) } @Provides @Singleton fun provideGetHomePageUseCase(repository: MeteoRepository): GetHomePage { return GetHomePage(repository) } @Provides @Singleton fun provideGetConfiniPageUseCase(repository: MeteoRepository): GetConfiniPage { return GetConfiniPage(repository) } @Provides @Singleton fun provideGetMontagnaPageUseCase(repository: MeteoRepository): GetMontagnaPage { return GetMontagnaPage(repository) } @Provides @Singleton fun provideGetProvinciaPageUseCase(repository: MeteoRepository): GetProvinciaPage { return GetProvinciaPage(repository) } @Provides @Singleton fun provideGetViabilitaPageUseCase(repository: MeteoRepository): GetViabilitaPage { return GetViabilitaPage(repository) } }
0
Kotlin
0
0
4f1706bb9e6cc6d05646367705a5ab032402641c
1,857
MeteoApuane-App
MIT License
app/src/main/java/io/github/rin_da/ucsynews/data/source/DataSource.kt
Rin-Da
67,884,113
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "JSON": 1, "Proguard": 1, "Java": 2, "XML": 123, "Kotlin": 43}
package io.github.rin_da.ucsynews.data.source import io.github.rin_da.ucsynews.data.source.local.LocalBaseSource import io.github.rin_da.ucsynews.data.source.local.RemoteBaseSource import io.github.rin_da.ucsynews.presentation.abstract.model.People import io.github.rin_da.ucsynews.presentation.abstract.model.Post import io.reactivex.Completable import javax.inject.Inject /** * Created by user on 12/13/16. */ class DataSource : DataBaseSource { @Inject lateinit var localSource: LocalBaseSource @Inject lateinit var remote: RemoteBaseSource @Inject constructor() { } override fun post(post: Post, uuid: String): Completable = remote.post(post, uuid) override fun addUserIfExists(people: People) = remote.addPeopleIfNotExists(people) override fun getUser(): String? = localSource.getUserPreferences() override fun toString(): String { return "DataSource(localSource=$localSource)" } }
1
null
1
1
274da9a457c473604fd5b576cb5c857af79f8a83
967
UCSY-News
MIT License
skellig-test-step-processing/src/main/kotlin/org/skellig/teststep/processing/value/property/DefaultPropertyExtractor.kt
skellig-framework
263,021,995
false
{"Kotlin": 1283314, "CSS": 525991, "Java": 270216, "FreeMarker": 66859, "HTML": 11313, "ANTLR": 6165}
package org.skellig.teststep.processing.value.property /** * DefaultPropertyExtractor is a class that implements the [PropertyExtractor] interface for extracting properties from various sources. * The sources of properties it extracts from are (in this order): * 1) [propertyExtractorFunction] if defined * 2) parameters, provided as argument of [DefaultPropertyExtractor.extractFrom]. These are parameters provided for a test step * from any sources (ex. feature file) as well as values of the test steps, extracted parameters from a name of the test step and * any other data which may be added during processing of the test step. * 3) [System.getProperty] * 4) [System.getenv] * 5) If the extracted property is [String] "null" then a null object is returned. * * @property propertyExtractorFunction A function that takes a property key as input and returns the corresponding property value. * It can be null if there is no custom extraction logic. */ class DefaultPropertyExtractor(private val propertyExtractorFunction: ((String) -> Any?)?) : PropertyExtractor { companion object { private const val NULL = "null" } override fun extractFrom(propertyKey: String, parameters: Map<String, Any?>): Any? { var propertyValue: Any? = null if (propertyExtractorFunction != null) { propertyValue = propertyExtractorFunction.invoke(propertyKey) } if (propertyValue == null && parameters.containsKey(propertyKey)) { propertyValue = parameters[propertyKey] } if (propertyValue == null) { propertyValue = System.getProperty(propertyKey) } if (propertyValue == null) { propertyValue = System.getenv(propertyKey) } return if (propertyValue == NULL) null else propertyValue } }
8
Kotlin
0
3
ed375268b0e444f1928f22f4ac27603e9d1fb66b
1,833
skellig-core
Apache License 2.0
idea/tests/testData/inspectionsLocal/equalsBetweenInconvertibleTypes/enumEqEnum.kt
JetBrains
278,369,660
false
null
// PROBLEM: none fun test(x: E1, y: E1): Boolean { return x.<caret>equals(y) } enum class E1
0
Kotlin
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
100
intellij-kotlin
Apache License 2.0
app/src/main/java/com/example/mvvmsampleapp/data/network/responses/ResponseParser.kt
Lekhanshlkr
580,987,224
false
null
package com.example.mvvmsampleapp.data.network.responses import android.os.AsyncTask import android.util.Log import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LiveData import com.example.mvvmsampleapp.data.db.AppDatabase import com.example.mvvmsampleapp.data.db.entities.User import org.json.JSONArray import org.json.JSONObject class ResponseParser { fun stringTOJson(owner: LifecycleOwner, response:LiveData<String>):User?{ response.observe(owner) { val json = JSONObject(it) val msg = json.getString("msg") if(msg == "pass login"){ val userInfo = JSONArray(json.getString("info")) val userCredentials = userInfo.getJSONObject(0) val user_id = userCredentials.getString("USER_ID") val fulll_name = userCredentials.getString("FULLL_NAME") val email = userCredentials.getString("EMAIL") val password = userCredentials.getString("PASSWORD") val picture_path = userCredentials.getString("PICTURE_PATH") user = User(user_id,fulll_name,email,password,picture_path) }else{ user = User() } } return user } companion object{ var user:User?=null } }
0
Kotlin
0
0
a9e167cc15116c1e7c993e075990fc9b3f8176b0
1,318
MVVMSampleApp
MIT License
src/commonMain/kotlin/io/rebble/libpebblecommon/structmapper/StructMappable.kt
pebble-dev
264,919,199
false
{"Kotlin": 217944}
package io.rebble.libpebblecommon.structmapper import io.rebble.libpebblecommon.util.DataBuffer import io.rebble.libpebblecommon.util.Endian abstract class StructMappable(endianness: Endian = Endian.Unspecified) : Mappable(endianness) { val m = StructMapper(endianness = endianness, debugTag = this::class.simpleName) override fun toBytes(): UByteArray { return m.toBytes() } override fun fromBytes(bytes: DataBuffer) { m.fromBytes(bytes) } override val size get() = m.size }
1
Kotlin
4
3
55cb810a5d4f0fab123100a91f5d71b91aeb9d64
520
libpebblecommon
Apache License 2.0
src/main/kotlin/dev/arbjerg/lavalink/client/LavalinkPlayer.kt
lavalink-devs
642,292,256
false
null
package dev.arbjerg.lavalink.client import dev.arbjerg.lavalink.protocol.v4.* import kotlin.math.min class LavalinkPlayer(private val node: LavalinkNode, protocolPlayer: Player) : IUpdatablePlayer { val guildId = protocolPlayer.guildId.toLong() /** * Gets the current track that is playing on the player. * * To get the current position of the track, use [position]. */ var track = protocolPlayer.track internal set /** * Number between 0 and 1000, where 100 is 100% volume. */ val volume = protocolPlayer.volume val paused = protocolPlayer.paused /** * Gets the current state of the player. * See [PlayerState] for more info. */ var state = protocolPlayer.state internal set val voiceState = protocolPlayer.voice val filters = protocolPlayer.filters val position: Long get() { val checkedTrack = track return when { checkedTrack == null -> 0 paused -> state.position else -> min(state.position + (System.currentTimeMillis() - state.time), checkedTrack.info.length) } } override fun setTrack(track: Track?) = PlayerUpdateBuilder(node, guildId) .setTrack(track) override fun stopTrack() = PlayerUpdateBuilder(node, guildId) .stopTrack() override fun setEncodedTrack(encodedTrack: String?) = PlayerUpdateBuilder(node, guildId) .setEncodedTrack(encodedTrack) override fun omitEncodedTrack() = PlayerUpdateBuilder(node, guildId) .omitEncodedTrack() override fun setIdentifier(identifier: String?) = PlayerUpdateBuilder(node, guildId) .setIdentifier(identifier) override fun setPosition(position: Long?) = PlayerUpdateBuilder(node, guildId) .setPosition(position) override fun setEndTime(endTime: Long?) = PlayerUpdateBuilder(node, guildId) .setEndTime(endTime) override fun omitEndTime() = PlayerUpdateBuilder(node, guildId) .omitEndTime() override fun setVolume(volume: Int) = PlayerUpdateBuilder(node, guildId) .setVolume(volume) override fun setPaused(paused: Boolean) = PlayerUpdateBuilder(node, guildId) .setPaused(paused) override fun setFilters(filters: Filters) = PlayerUpdateBuilder(node, guildId) .setFilters(filters) override fun setVoiceState(state: VoiceState) = PlayerUpdateBuilder(node, guildId) .setVoiceState(state) // For re-creating the player internal fun stateToBuilder() = PlayerUpdateBuilder(node, guildId) .setEncodedTrack(track?.encoded) .setIdentifier(null) .setPosition(position) .setEndTime(null) // TODO Should we keep track of the end time? .setVolume(volume) .setPaused(paused) .setFilters(filters) .setVoiceState(voiceState) }
3
null
5
9
c6d430fefbab72a456a38afa5640f82c9ec32324
2,896
lavalink-client
MIT License
src/main/kotlin/com/sourcegraph/cody/context/ui/ContextNotifications.kt
sourcegraph
702,947,607
false
{"Kotlin": 914689, "Java": 201176, "Shell": 4636, "TypeScript": 2153, "Nix": 1122, "JavaScript": 436, "HTML": 294}
package com.sourcegraph.cody.context.ui import com.intellij.ide.util.PropertiesComponent import com.intellij.notification.Notification import com.intellij.notification.NotificationAction import com.intellij.notification.NotificationType import com.intellij.notification.impl.NotificationFullContent import com.intellij.openapi.actionSystem.AnActionEvent import com.sourcegraph.Icons import com.sourcegraph.common.CodyBundle import com.sourcegraph.common.CodyBundle.fmt import com.sourcegraph.common.NotificationGroups class RemoteRepoResolutionFailedNotification : Notification( NotificationGroups.SOURCEGRAPH_ERRORS, CodyBundle.getString("context-panel.remote-repo.error-resolution-failed.title"), CodyBundle.getString("context-panel.remote-repo.error-resolution-failed.detail"), NotificationType.WARNING), NotificationFullContent { init { icon = Icons.RepoHostGeneric addAction( object : NotificationAction( CodyBundle.getString( "context-panel.remote-repo.error-resolution-failed.do-not-show-again")) { override fun actionPerformed(event: AnActionEvent, notification: Notification) { PropertiesComponent.getInstance().setValue(ignore, true) notification.expire() } }) } companion object { val ignore = CodyBundle.getString("context-panel.remote-repo.error-resolution-failed.ignore") } } class RemoteRepoLimitNotification : Notification( NotificationGroups.SOURCEGRAPH_ERRORS, CodyBundle.getString("context-panel.remote-repo.error-too-many-repositories.tooltip"), CodyBundle.getString("context-panel.remote-repo.error-too-many-repositories") .fmt(MAX_REMOTE_REPOSITORY_COUNT.toString()), NotificationType.WARNING), NotificationFullContent { init { icon = Icons.RepoHostGeneric } }
230
Kotlin
16
55
1eb25809c3e51b64f08e851c8da09778000540c6
1,918
jetbrains
Apache License 2.0
app/src/main/java/ru/app/olimp/adapters/pager/list/SignalViewHolder.kt
metalink94
155,099,732
false
{"Gradle": 3, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "INI": 1, "Proguard": 1, "JSON": 1, "Kotlin": 20, "XML": 23, "Java": 1}
package ru.app.olimp.adapters.pager.list import android.support.v7.widget.RecyclerView import android.view.View import com.bumptech.glide.Glide import kotlinx.android.synthetic.main.row_signal.view.* import ru.app.olimp.signal.SignalModel class SignalViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) { fun bind(model: SignalModel) { Glide.with(itemView.context).load(model.imageRes).into(itemView.icon) itemView.tag = model } }
0
Kotlin
0
0
814070216541991102bf2e4445af9fc7c2257c12
468
Olimp
Apache License 2.0
core/designsystem/src/main/java/com/hankki/core/designsystem/component/chip/HankkiChipWithIcon.kt
Team-Hankki
816,081,730
false
null
package com.hankki.core.designsystem.component.chip import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer 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.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import com.hankki.core.common.extension.bounceClick import com.hankki.core.designsystem.theme.Gray200 import com.hankki.core.designsystem.theme.Gray400 import com.hankki.core.designsystem.theme.Gray700 import com.hankki.core.designsystem.theme.HankkiTheme import com.hankki.core.designsystem.theme.HankkijogboTheme import com.hankki.core.designsystem.theme.White import com.hankki.core.designsystem.theme.Yellow500 import com.hankki.core.designsystem.theme.Yellow300 @Composable fun HankkiChipWithIcon( iconUrl: String, title: String, isSelected: Boolean = false, onClick: () -> Unit = {}, ) { Row( modifier = Modifier .bounceClick( scaleDown = 0.88f, radius = 100f, onClick = onClick ) .clip(RoundedCornerShape(100.dp)) .border(1.dp, if (isSelected) Yellow500 else Gray200, RoundedCornerShape(100.dp)) .background(if (isSelected) Yellow300 else White) .padding(vertical = 4.dp) .padding(start = 8.dp, end = 10.dp), verticalAlignment = Alignment.CenterVertically ) { AsyncImage( model = iconUrl, contentDescription = "icon", modifier = Modifier.size(28.dp), contentScale = ContentScale.Crop ) Spacer(modifier = Modifier.width(2.dp)) Text( text = title, style = if (isSelected) HankkiTheme.typography.body4 else HankkiTheme.typography.body5, color = if (isSelected) Gray700 else Gray400 ) } } @Preview @Composable fun HankkiChipWithIconPreview() { HankkijogboTheme { Column { HankkiChipWithIcon( iconUrl = "https://picsum.photos/200/300", title = "한식", isSelected = false ) Spacer(modifier = Modifier.height(10.dp)) HankkiChipWithIcon( iconUrl = "https://picsum.photos/200/300", title = "한식", isSelected = true ) } } }
9
null
0
43
e83ea4cf5cfd0b23d71da164090c29ba0e253b18
2,997
hankki-android
Apache License 2.0
client/src/main/kotlin/com/ecwid/upsource/rpc/users/BindVcsUsernameRequestDTO.kt
turchenkoalex
266,583,029
false
null
// Generated by the codegen. Please DO NOT EDIT! // source: message.ftl package com.ecwid.upsource.rpc.users /** * @param userId User ID to register as an alias of the currently logged-in user */ @Suppress("unused") data class BindVcsUsernameRequestDTO( /** * User ID to register as an alias of the currently logged-in user (required) */ val userId: String ) { @Suppress("unused") internal constructor() : this( userId = "" ) }
0
Kotlin
0
3
0e2ce7aae14a98e1bbdcf6dcb23a3ae089cebaa4
444
upsource-rpc
Apache License 2.0
kronor_webview_payment_gateway/src/main/java/io/kronor/component/webview_payment_gateway/WebviewGatewayComponent.kt
kronor-io
592,811,971
false
null
package io.kronor.component.webview_payment_gateway import android.annotation.SuppressLint import android.content.ActivityNotFoundException import android.content.ContentResolver import android.content.Context import android.content.Intent import android.database.Cursor import android.media.MediaDrm import android.net.Uri import android.os.Build import android.os.Looper import android.provider.Settings import android.util.Log import android.view.ViewGroup import android.webkit.WebResourceRequest import android.webkit.WebView import android.webkit.WebViewClient import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalInspectionMode import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import androidx.core.content.ContextCompat.startActivity import androidx.lifecycle.Lifecycle import androidx.lifecycle.Lifecycle.Event.* import androidx.lifecycle.repeatOnLifecycle import io.kronor.api.KronorError import io.kronor.api.PaymentMethod import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.newSingleThreadContext import kotlinx.coroutines.withContext import okhttp3.Dispatcher import java.lang.Exception import java.lang.Thread.sleep import java.security.MessageDigest import java.util.UUID @Composable fun WebviewGatewayComponent( viewModel: WebviewGatewayViewModel, modifier: Modifier = Modifier ) { val context = LocalContext.current if (!LocalInspectionMode.current) { LaunchedEffect(Unit) { withContext(Dispatchers.Default) { viewModel.setDeviceFingerPrint(getWeakFingerprint(context)) } } val lifecycle = LocalLifecycleOwner.current.lifecycle LaunchedEffect(viewModel.subscribe) { if (viewModel.subscribe) { lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { withContext(Dispatchers.IO) { viewModel.subscription() } } } } } WebviewGatewayScreen( viewModel::transition, viewModel.webviewGatewayState, viewModel.paymentGatewayUrl, viewModel.paymentMethod, modifier = modifier ) } @Composable private fun WebviewGatewayScreen( transition: (WebviewGatewayStatechart.Companion.Event) -> Unit, state: State<WebviewGatewayStatechart.Companion.State>, paymentGatewayUrl: Uri, paymentMethod: PaymentMethod, modifier: Modifier = Modifier ) { Surface( modifier = modifier, color = MaterialTheme.colors.background ) { when (state.value) { WebviewGatewayStatechart.Companion.State.Initializing -> { LaunchedEffect(Unit) { transition(WebviewGatewayStatechart.Companion.Event.Initialize) } WebviewGatewayWrapper { WebviewGatewayInitializing(modifier = Modifier.fillMaxSize()) } } WebviewGatewayStatechart.Companion.State.CreatingPaymentRequest -> { WebviewGatewayWrapper { WebviewGatewayInitializing(modifier = Modifier.fillMaxSize()) } } WebviewGatewayStatechart.Companion.State.WaitingForPaymentRequest -> { WebviewGatewayWrapper { WebviewGatewayInitializing(modifier = Modifier.fillMaxSize()) } } is WebviewGatewayStatechart.Companion.State.Errored -> { WebviewGatewayWrapper { WebviewGatewayErrored(error = (state.value as WebviewGatewayStatechart.Companion.State.Errored).error, onPaymentRetry = { transition(WebviewGatewayStatechart.Companion.Event.Retry) }, onGoBack = { transition(WebviewGatewayStatechart.Companion.Event.CancelFlow) } , modifier = Modifier.fillMaxSize()) } } is WebviewGatewayStatechart.Companion.State.PaymentRequestInitialized -> { PaymentGatewayView(gatewayUrl = paymentGatewayUrl.toString(), paymentMethod = paymentMethod, onPaymentCancel = { transition(WebviewGatewayStatechart.Companion.Event.WaitForCancel) }, modifier = Modifier.fillMaxSize()) } is WebviewGatewayStatechart.Companion.State.WaitingForPayment -> { WebviewGatewayWrapper { WebviewGatewayWaitingForPayment(modifier = Modifier.fillMaxSize()) } } is WebviewGatewayStatechart.Companion.State.PaymentRejected -> { WebviewGatewayWrapper { WebviewGatewayPaymentRejected(modifier = Modifier.fillMaxSize()) } } is WebviewGatewayStatechart.Companion.State.PaymentCompleted -> { WebviewGatewayWrapper { WebviewGatewayPaymentCompleted(modifier = Modifier.fillMaxSize()) } } } } } @Composable private fun WebviewGatewayWrapper(modifier: Modifier = Modifier, content: @Composable () -> Unit) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.SpaceBetween, modifier = modifier ) { content.invoke() } } @SuppressLint("SetJavaScriptEnabled") @Composable private fun PaymentGatewayView( gatewayUrl: String, paymentMethod: PaymentMethod, onPaymentCancel: () -> Unit, modifier: Modifier = Modifier ) { Column( modifier.fillMaxSize() ) { val context = LocalContext.current AndroidView(factory = { WebView(it).apply { layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, ) webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading( view: WebView?, request: WebResourceRequest ): Boolean { Log.d("WebviewGatewayComponent", "Request URL received: ${request.url}") if (request.url.queryParameterNames.contains("cancel")) { onPaymentCancel() return false } if (request.url.scheme == "http" || request.url.scheme == "https") { return false } return try { startActivity( context, Intent( Intent.ACTION_VIEW, request.url ), null ) true } catch (e : ActivityNotFoundException) { true } } } settings.javaScriptEnabled = true settings.domStorageEnabled = true } }, update = { it.loadUrl(gatewayUrl) }) } } @Composable private fun WebviewGatewayErrored( error: KronorError, onPaymentRetry: () -> Unit, onGoBack: () -> Unit, modifier: Modifier = Modifier ) { Column( modifier = modifier, verticalArrangement = Arrangement.SpaceBetween, horizontalAlignment = Alignment.CenterHorizontally ) { Spacer(modifier = Modifier.height(100.dp)) when (error) { is KronorError.NetworkError -> { Text( stringResource(R.string.network_error), textAlign = TextAlign.Center ) } is KronorError.GraphQlError -> { Text( stringResource(R.string.graphql_error), textAlign = TextAlign.Center ) } } Button(onClick = { onPaymentRetry() }) { Text(stringResource(R.string.try_again)) } Button(onClick = { onGoBack() }) { Text(stringResource(R.string.go_back)) } } } @Composable private fun WebviewGatewayInitializing(modifier: Modifier = Modifier) { Column( modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text(stringResource(R.string.secure_connection)) Spacer(modifier = Modifier.height(30.dp)) CircularProgressIndicator() } } @Composable private fun WebviewGatewayWaitingForPayment(modifier: Modifier = Modifier) { Column( modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text(stringResource(R.string.waiting_for_payment)) Spacer(Modifier.height(30.dp)) CircularProgressIndicator() } } @Composable private fun WebviewGatewayPaymentCompleted(modifier: Modifier = Modifier) { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = modifier ) { Text(stringResource(R.string.payment_completed)) } } @Composable private fun WebviewGatewayPaymentRejected(modifier: Modifier = Modifier) { Column( modifier = modifier, verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Spacer(Modifier.height(100.dp)) Text(stringResource(R.string.payment_rejected)) } } @SuppressLint("HardwareIds") private fun getWeakFingerprint(context: Context) : String { val contentResolver : ContentResolver = context.contentResolver!! val androidId: String? by lazy { try { Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID) } catch (e: Exception) { null } } fun getGsfId(): String? { val URI = Uri.parse("content://com.google.android.gsf.gservices") val params = arrayOf("android_id") return try { val cursor: Cursor = contentResolver .query(URI, null, null, params, null) ?: return null if (!cursor.moveToFirst() || cursor.columnCount < 2) { cursor.close() return null } try { val result = java.lang.Long.toHexString(cursor.getString(1).toLong()) cursor.close() result } catch (e: NumberFormatException) { cursor.close() null } } catch (e: Exception) { null } } val gsfId : String? by lazy { try { getGsfId() } catch (e: Exception) { null } } fun releaseMediaDRM(mediaDrm: MediaDrm) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { mediaDrm.close() } else { mediaDrm.release() } } fun mediaDrmId(): String { val wIDEWINE_UUID_MOST_SIG_BITS = -0x121074568629b532L val wIDEWINE_UUID_LEAST_SIG_BITS = -0x5c37d8232ae2de13L val widevineUUID = UUID(wIDEWINE_UUID_MOST_SIG_BITS, wIDEWINE_UUID_LEAST_SIG_BITS) val wvDrm: MediaDrm? wvDrm = MediaDrm(widevineUUID) val mivevineId = wvDrm.getPropertyByteArray(MediaDrm.PROPERTY_DEVICE_UNIQUE_ID) releaseMediaDRM(wvDrm) val md: MessageDigest = MessageDigest.getInstance("SHA-256") md.update(mivevineId) return md.digest().joinToString("") { java.lang.String.format("%02x", it) } } val drmId : String? by lazy { try { mediaDrmId() } catch (e: Exception) { null } } return gsfId ?: drmId ?: androidId ?: "nofingerprintandroid" }
3
Kotlin
0
0
f3bf51ac690ae115e848df56bdbcebe028321900
12,456
kronor-android
MIT License
src/main/kotlin/anissia/domain/board/core/ports/inbound/GetTicker.kt
anissia-net
319,510,882
false
{"Kotlin": 255675, "HTML": 5480, "HCL": 794}
package anissia.domain.board.core.ports.inbound import anissia.domain.board.core.model.BoardTickerItem import anissia.domain.board.core.model.GetTickerCommand interface GetTicker { fun handle(cmd: GetTickerCommand): BoardTickerItem }
4
Kotlin
4
13
2ae6753685dc26aa5905d98e6088ffdda0c5cce3
240
anissia-core
Creative Commons Attribution 4.0 International
blockball-bukkit-plugin/src/main/java/com/github/shynixn/blockball/bukkit/logic/business/commandexecutor/menu/AreaProtectionPage.kt
yoloyolicko
184,437,057
true
{"Kotlin": 564411, "Java": 290209}
package com.github.shynixn.blockball.bukkit.logic.business.commandexecutor.menu import com.github.shynixn.blockball.api.persistence.entity.Arena import com.github.shynixn.blockball.bukkit.logic.business.extension.ChatBuilder import com.github.shynixn.blockball.core.logic.persistence.entity.PositionEntity import org.bukkit.entity.Player /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * 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. */ class AreaProtectionPage : Page(AreaProtectionPage.ID, MiscSettingsPage.ID) { companion object { /** Id of the page. */ const val ID = 26 } /** * Returns the key of the command when this page should be executed. * * @return key */ override fun getCommandKey(): PageKey { return PageKey.AREAPROTECTION } /** * Executes actions for this page. * * @param cache cache * @param args */ override fun execute(player: Player, command: BlockBallCommand, cache: Array<Any?>, args: Array<String>): CommandResult { val arena = cache[0] as Arena if (command == BlockBallCommand.AREAPROTECTION_TOGGLE_ENTITYFORCEFIELD) { arena.meta.protectionMeta.entityProtectionEnabled = !arena.meta.protectionMeta.entityProtectionEnabled } else if (command == BlockBallCommand.AREAPROTECTION_TOGGLE_PLAYERJOINFORCEFIELD) { arena.meta.protectionMeta.rejoinProtectionEnabled = !arena.meta.protectionMeta.rejoinProtectionEnabled } else if (command == BlockBallCommand.AREAPROTECTION_SET_ENTITYFORCEFIELD && args.size >= 5 && args[2].toDoubleOrNull() != null && args[3].toDoubleOrNull() != null && args[4].toDoubleOrNull() != null) { arena.meta.protectionMeta.entityProtection = PositionEntity(args[2].toDouble(), args[3].toDouble(), args[4].toDouble()) } else if (command == BlockBallCommand.AREAPROTECTION_SET_PLAYERJOINFORCEFIELD && args.size >= 5 && args[2].toDoubleOrNull() != null && args[3].toDoubleOrNull() != null && args[4].toDoubleOrNull() != null) { arena.meta.protectionMeta.rejoinProtection = PositionEntity(args[2].toDouble(), args[3].toDouble(), args[4].toDouble()) } return super.execute(player, command, cache, args) } /** * Builds this page for the player. * * @return page */ override fun buildPage(cache: Array<Any?>): ChatBuilder? { val arena = cache[0] as Arena val meta = arena.meta.protectionMeta return ChatBuilder() .component("- Animal and Monster protection enabled: " + meta.entityProtectionEnabled).builder() .component(ClickableComponent.TOGGLE.text).setColor(ClickableComponent.TOGGLE.color) .setClickAction(ChatBuilder.ClickAction.RUN_COMMAND, BlockBallCommand.AREAPROTECTION_TOGGLE_ENTITYFORCEFIELD.command) .setHoverText("Toggles allowing animals and monsters to run inside of the arena.") .builder().nextLine() .component("- Animal and Monster protection velocity: " + meta.entityProtection).builder() .component(ClickableComponent.EDIT.text).setColor(ClickableComponent.EDIT.color) .setClickAction(ChatBuilder.ClickAction.SUGGEST_COMMAND, BlockBallCommand.AREAPROTECTION_SET_ENTITYFORCEFIELD.command) .setHoverText("Changes the velocity being applied to animals and monsters when they try to enter the arena." + "\nEnter 3 values when using this command.\n/blockball aprot enprot <x> <y> <z>") .builder().nextLine() .component("- Join protection enabled: " + meta.rejoinProtectionEnabled).builder() .component(ClickableComponent.TOGGLE.text).setColor(ClickableComponent.TOGGLE.color) .setClickAction(ChatBuilder.ClickAction.RUN_COMMAND, BlockBallCommand.AREAPROTECTION_TOGGLE_PLAYERJOINFORCEFIELD.command) .setHoverText("Toggles the protection to move players outside of the arena.") .builder().nextLine() .component("- Join protection velocity: " + meta.rejoinProtection).builder() .component(ClickableComponent.EDIT.text).setColor(ClickableComponent.EDIT.color) .setClickAction(ChatBuilder.ClickAction.SUGGEST_COMMAND, BlockBallCommand.AREAPROTECTION_SET_PLAYERJOINFORCEFIELD.command) .setHoverText("Changes the velocity being applied to players when they try to enter the arena." + "\nEnter 3 values when using this command.\n/blockball aprot plprot <x> <y> <z>") .builder().nextLine() } }
0
Kotlin
0
0
d64bdbb78fc730cfb52e7cb0d5c55808e69370ac
5,809
BlockBall
Apache License 2.0
kotlinx-coroutines-core/common/src/internal/Synchronized.common.kt
Kotlin
61,722,736
false
{"Kotlin": 3835333, "Java": 34700, "Python": 3107, "Shell": 2685}
package kotlinx.coroutines.internal import kotlinx.coroutines.* import kotlin.contracts.* /** * @suppress **This an internal API and should not be used from general code.** */ @InternalCoroutinesApi public expect open class SynchronizedObject() // marker abstract class /** * @suppress **This an internal API and should not be used from general code.** */ @InternalCoroutinesApi public expect inline fun <T> synchronizedImpl(lock: SynchronizedObject, block: () -> T): T /** * @suppress **This an internal API and should not be used from general code.** */ @OptIn(ExperimentalContracts::class) @InternalCoroutinesApi public inline fun <T> synchronized(lock: SynchronizedObject, block: () -> T): T { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } return synchronizedImpl(lock, block) }
295
Kotlin
1850
13,033
6c6df2b850382887462eeaf51f21f58bd982491d
829
kotlinx.coroutines
Apache License 2.0
feature/feature_current_weather/src/main/java/com/farshatov/feature_current_weather/domain/usecase/GetCurrentWeatherUseCase.kt
timma
512,421,711
false
null
package com.farshatov.feature_current_weather.domain.usecase import com.farshatov.common.network.Result import com.farshatov.feature_current_weather.domain.model.CurrentWeatherModel import com.farshatov.feature_current_weather.domain.repository.CurrentWeatherRepository import kotlinx.coroutines.flow.Flow class GetCurrentWeatherUseCase( private val repository: CurrentWeatherRepository ) { suspend operator fun invoke(): Flow<Result<CurrentWeatherModel>> { return repository.fetchWeather() } }
0
Kotlin
0
0
d297259885e02f4b57641f3214b8d41ab3ccca7a
518
weatherapiproject
Apache License 2.0
libraries/scripting/common/src/kotlin/script/experimental/host/hostConfiguration.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2018 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 kotlin.script.experimental.host import kotlin.reflect.KClass import kotlin.script.experimental.api.KotlinType import kotlin.script.experimental.api.ScriptDependency import kotlin.script.experimental.api.ScriptEvaluationContextData import kotlin.script.experimental.util.PropertiesCollection interface ScriptingHostConfigurationKeys /** * The container for script evaluation configuration * For usages see actual code examples */ class ScriptingHostConfiguration(baseScriptingConfigurations: Iterable<ScriptingHostConfiguration>, body: Builder.() -> Unit) : PropertiesCollection(Builder(baseScriptingConfigurations).apply(body).data) { constructor(body: Builder.() -> Unit = {}) : this(emptyList(), body) constructor( vararg baseConfigurations: ScriptingHostConfiguration, body: Builder.() -> Unit = {} ) : this(baseConfigurations.asIterable(), body) class Builder internal constructor(baseScriptingHostConfigurations: Iterable<ScriptingHostConfiguration>) : ScriptingHostConfigurationKeys, PropertiesCollection.Builder(baseScriptingHostConfigurations) companion object : ScriptingHostConfigurationKeys } /** * An alternative to the constructor with base configuration, which returns a new configuration only if [body] adds anything * to the original one, otherwise returns original */ fun ScriptingHostConfiguration?.with(body: ScriptingHostConfiguration.Builder.() -> Unit): ScriptingHostConfiguration { val newConfiguration = if (this == null) ScriptingHostConfiguration(body = body) else ScriptingHostConfiguration(this, body = body) return if (newConfiguration != this) newConfiguration else this } /** * The list of all dependencies required for the script base class and refinement callbacks */ val ScriptingHostConfigurationKeys.configurationDependencies by PropertiesCollection.key<List<ScriptDependency>>() /** * The pointer to the generic "class loader" for the types used in the script configurations */ val ScriptingHostConfigurationKeys.getScriptingClass by PropertiesCollection.key<GetScriptingClass>(isTransient = true) /** * Evaluation context getter, allows to provide data to the evaluation configuration refinement functions */ val ScriptingHostConfigurationKeys.getEvaluationContext by PropertiesCollection.key<GetEvaluationContext>(isTransient = true) /** * The interface to the generic "class loader" for the types used in the script configurations */ interface GetScriptingClass { operator fun invoke(classType: KotlinType, contextClass: KClass<*>, hostConfiguration: ScriptingHostConfiguration): KClass<*> } /** * A helper to enable passing lambda directly to the getEvaluationContext "keyword" */ fun ScriptingHostConfiguration.Builder.getEvaluationContext(handler: GetEvaluationContext) { ScriptingHostConfiguration.getEvaluationContext.put(handler) } /** * The interface to an evaluation context getter */ typealias GetEvaluationContext = (hostConfiguration: ScriptingHostConfiguration) -> ScriptEvaluationContextData // helper method fun ScriptingHostConfiguration.getScriptingClass(type: KotlinType, contextClass: KClass<*>): KClass<*> { val getClass = get(ScriptingHostConfiguration.getScriptingClass) ?: throw IllegalArgumentException("Expecting 'getScriptingClass' property in the scripting host configuration: unable to load scripting class $type") return getClass(type, contextClass, this) } // helper method fun ScriptingHostConfiguration.getScriptingClass(type: KotlinType, context: Any): KClass<*> = getScriptingClass(type, context::class)
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
3,829
kotlin
Apache License 2.0
io-core/src/main/kotlin/io/github/nickacpt/abst/io/sockets/endpoint/TcpEndpointReceiverThread.kt
abst-lib
499,280,485
false
null
package io.github.nickacpt.abst.io.sockets.endpoint import io.github.nickacpt.abst.io.utils.BufferFramer import org.msgpack.core.MessagePack import org.msgpack.core.MessageUnpacker import org.msgpack.core.buffer.InputStreamBufferInput internal class TcpEndpointReceiverThread<T>(private val endpoint: T) : Runnable where T : ConnectionEndpoint, T : InternalConnectionEndpoint { private val inputStreamBuffer = InputStreamBufferInput(endpoint.inputStream) private val unpacker: MessageUnpacker = MessagePack.newDefaultUnpacker(inputStreamBuffer) override fun run() { while (endpoint.isConnected) { try { if (!unpacker.hasNext()) { Thread.sleep(1) continue } // While the endpoint is connected, read from the socket and give the data to it for processing val message = BufferFramer.unframeMessage(unpacker, false) endpoint.onMessageReceived(message) unpacker.reset(inputStreamBuffer) } catch (e: Exception) { if (endpoint.isConnected) { endpoint.onError(e) if (endpoint.disconnectOnError) { // If an exception is thrown, the client is disconnected if the disconnectOnError flag is set endpoint.disconnect() } } } } unpacker.close() endpoint.onConnectionClosed() } }
0
Kotlin
0
0
4bdfb5b78139bd9a814412d629627b84ea33b24b
1,533
abst-lib-jvm
MIT License
app/src/main/java/com/vaibhav/taskify/ui/mainScreen/home/upComing/UpComingViewModel.kt
Vaibhav2002
375,697,442
false
null
package com.vaibhav.taskify.ui.mainScreen.home.upComing import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.vaibhav.taskify.data.repo.TaskRepo import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.stateIn import javax.inject.Inject @HiltViewModel class UpComingViewModel @Inject constructor(private val taskRepo: TaskRepo) : ViewModel() { val upComingTasks = taskRepo.getAllUpComingTasksOfToday() .stateIn(viewModelScope, SharingStarted.WhileSubscribed(), emptyList()) }
1
null
29
89
664a4cd4600a6bfc12082f9f083897fb8b4001c7
607
Taskify
MIT License
src/main/kotlin/waffle/domain/model/WebSnapshot.kt
tmyksj
571,796,959
false
null
package waffle.domain.model import waffle.core.type.Blob import java.net.URL /** * Snapshot of a page. */ data class WebSnapshot( /** * URL for a page. */ val resource: URL, /** * Window width for a page (pixels). */ val widthPx: Long = 1920, /** * Window height for a page (pixels). */ val heightPx: Long = 1080, /** * Screenshot of a page. */ val screenshot: Blob = Blob(), ) { init { // widthPx must be in range from 100 to 4000. if (widthPx !in 100..4000) { throw IllegalArgumentException() } // heightPx must be in range from 100 to 4000. if (heightPx !in 100..4000) { throw IllegalArgumentException() } } }
0
Kotlin
0
0
f9465b3a6096afcbfd9f6a2f98d7501613e2d54a
781
waffle
Apache License 2.0
domain/src/main/java/com/synrgyacademy/domain/usecase/auth/IsLoginUseCase.kt
Synrgy-Academy-Final-Project
738,116,027
false
{"Kotlin": 429514, "Ruby": 1824}
package com.synrgyacademy.domain.usecase.auth import com.synrgyacademy.common.Resource import com.synrgyacademy.domain.repository.AuthRepository import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flow import javax.inject.Inject class IsLoginUseCase @Inject constructor(private val authRepository: AuthRepository) { operator fun invoke(): Flow<Resource<Boolean>> = flow { emit(Resource.Loading) try { val result = authRepository.isLogin().first() emit(Resource.Success(result)) } catch (e: Exception) { emit(Resource.Error("An unexpected error occurred")) } } }
0
Kotlin
0
0
d7fefca1200efd6eae4a33a34ef0511d90dfd54a
691
Android
MIT License
beam-bundle/src/main/kotlin/dev/d1s/beam/bundle/html/CounterScriptIndexModule.kt
d1snin
632,895,652
false
null
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.d1s.beam.bundle.html import io.ktor.server.config.* import kotlinx.html.HEAD import kotlinx.html.unsafe import org.koin.core.component.KoinComponent import org.koin.core.component.inject class CounterScriptIndexModule : IndexModule, KoinComponent { private val config by inject<ApplicationConfig>() private val vkAdsId get() = config.propertyOrNull("bundle.counter.vk-ads")?.getString() override fun HEAD.render(renderParameters: RenderParameters) { vkAdsId?.let { renderVkAdsScript(it) } } private fun HEAD.renderVkAdsScript(counterId: String) { unsafe { +""" <!-- Top.Mail.Ru counter --> <script type="text/javascript"> var _tmr = window._tmr || (window._tmr = []); _tmr.push({id: "$counterId", type: "pageView", start: (new Date()).getTime()}); (function (d, w, id) { if (d.getElementById(id)) return; var ts = d.createElement("script"); ts.type = "text/javascript"; ts.async = true; ts.id = id; ts.src = "https://top-fwz1.mail.ru/js/code.js"; var f = function () {var s = d.getElementsByTagName("script")[0]; s.parentNode.insertBefore(ts, s);}; if (w.opera == "[object Opera]") { d.addEventListener("DOMContentLoaded", f, false); } else { f(); } })(document, window, "tmr-code"); </script> <noscript><div><img src="https://top-fwz1.mail.ru/counter?id=$counterId;js=na" style="position:absolute;left:-9999px;" alt="Top.Mail.Ru" /></div></noscript> <!-- /Top.Mail.Ru counter --> """.trimIndent() } } }
6
null
0
5
ee4d8f17b77f23edfb513ac374474151a8a8fcb9
2,346
beam
Apache License 2.0
moshi-kotlin-codegen/src/test/java/com/squareup/moshi/kotlin/codegen/ksp/JsonClassSymbolProcessorTest.kt
square
22,789,601
false
null
/* * Copyright (C) 2018 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.moshi.kotlin.codegen.apt import com.google.common.truth.Truth.assertThat import com.squareup.moshi.JsonAdapter import com.squareup.moshi.JsonReader import com.squareup.moshi.kotlin.codegen.api.Options.OPTION_GENERATED import com.squareup.moshi.kotlin.codegen.api.Options.OPTION_GENERATE_PROGUARD_RULES import com.tschuchort.compiletesting.KotlinCompilation import com.tschuchort.compiletesting.SourceFile import com.tschuchort.compiletesting.SourceFile.Companion.kotlin import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import kotlin.reflect.KClass import kotlin.reflect.KClassifier import kotlin.reflect.KType import kotlin.reflect.KTypeProjection import kotlin.reflect.KVariance import kotlin.reflect.KVariance.INVARIANT import kotlin.reflect.full.createType import kotlin.reflect.full.declaredMemberProperties /** Execute kotlinc to confirm that either files are generated or errors are printed. */ class JsonClassCodegenProcessorTest { @Rule @JvmField val temporaryFolder: TemporaryFolder = TemporaryFolder() @Test fun privateConstructor() { val result = compile( kotlin( "source.kt", """ import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) class PrivateConstructor private constructor(val a: Int, val b: Int) { fun a() = a fun b() = b companion object { fun newInstance(a: Int, b: Int) = PrivateConstructor(a, b) } } """ ) ) assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR) assertThat(result.messages).contains("constructor is not internal or public") } @Test fun privateConstructorParameter() { val result = compile( kotlin( "source.kt", """ import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) class PrivateConstructorParameter(private var a: Int) """ ) ) assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR) assertThat(result.messages).contains("property a is not visible") } @Test fun privateProperties() { val result = compile( kotlin( "source.kt", """ import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) class PrivateProperties { private var a: Int = -1 private var b: Int = -1 } """ ) ) assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR) assertThat(result.messages).contains("property a is not visible") } @Test fun interfacesNotSupported() { val result = compile( kotlin( "source.kt", """ import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) interface Interface """ ) ) assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR) assertThat(result.messages).contains( "error: @JsonClass can't be applied to Interface: must be a Kotlin class" ) } @Test fun interfacesDoNotErrorWhenGeneratorNotSet() { val result = compile( kotlin( "source.kt", """ import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true, generator="customGenerator") interface Interface """ ) ) assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.OK) } @Test fun abstractClassesNotSupported() { val result = compile( kotlin( "source.kt", """ import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) abstract class AbstractClass(val a: Int) """ ) ) assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR) assertThat(result.messages).contains( "error: @JsonClass can't be applied to AbstractClass: must not be abstract" ) } @Test fun sealedClassesNotSupported() { val result = compile( kotlin( "source.kt", """ import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) sealed class SealedClass(val a: Int) """ ) ) assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR) assertThat(result.messages).contains( "error: @JsonClass can't be applied to SealedClass: must not be sealed" ) } @Test fun innerClassesNotSupported() { val result = compile( kotlin( "source.kt", """ import com.squareup.moshi.JsonClass class Outer { @JsonClass(generateAdapter = true) inner class InnerClass(val a: Int) } """ ) ) assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR) assertThat(result.messages).contains( "error: @JsonClass can't be applied to Outer.InnerClass: must not be an inner class" ) } @Test fun enumClassesNotSupported() { val result = compile( kotlin( "source.kt", """ import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) enum class KotlinEnum { A, B } """ ) ) assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR) assertThat(result.messages).contains( "error: @JsonClass with 'generateAdapter = \"true\"' can't be applied to KotlinEnum: code gen for enums is not supported or necessary" ) } // Annotation processors don't get called for local classes, so we don't have the opportunity to @Ignore @Test fun localClassesNotSupported() { val result = compile( kotlin( "source.kt", """ import com.squareup.moshi.JsonClass fun outer() { @JsonClass(generateAdapter = true) class LocalClass(val a: Int) } """ ) ) assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR) assertThat(result.messages).contains( "error: @JsonClass can't be applied to LocalClass: must not be local" ) } @Test fun privateClassesNotSupported() { val result = compile( kotlin( "source.kt", """ import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) private class PrivateClass(val a: Int) """ ) ) assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR) assertThat(result.messages).contains( "error: @JsonClass can't be applied to PrivateClass: must be internal or public" ) } @Test fun objectDeclarationsNotSupported() { val result = compile( kotlin( "source.kt", """ import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) object ObjectDeclaration { var a = 5 } """ ) ) assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR) assertThat(result.messages).contains( "error: @JsonClass can't be applied to ObjectDeclaration: must be a Kotlin class" ) } @Test fun objectExpressionsNotSupported() { val result = compile( kotlin( "source.kt", """ import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) val expression = object : Any() { var a = 5 } """ ) ) assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR) assertThat(result.messages).contains( "error: @JsonClass can't be applied to getExpression\$annotations(): must be a Kotlin class" ) } @Test fun requiredTransientConstructorParameterFails() { val result = compile( kotlin( "source.kt", """ import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) class RequiredTransientConstructorParameter(@Json(ignore = true) var a: Int) """ ) ) assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR) assertThat(result.messages).contains( "error: No default value for transient/ignored property a" ) } @Test fun requiredIgnoredConstructorParameterFails() { val result = compile( kotlin( "source.kt", """ import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) class RequiredIgnoredConstructorParameter(@Json(ignore = true) var a: Int) """ ) ) assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR) assertThat(result.messages).contains( "error: No default value for transient/ignored property a" ) } @Test fun nonPropertyConstructorParameter() { val result = compile( kotlin( "source.kt", """ import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) class NonPropertyConstructorParameter(a: Int, val b: Int) """ ) ) assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR) assertThat(result.messages).contains( "error: No property for required constructor parameter a" ) } @Test fun badGeneratedAnnotation() { val result = prepareCompilation( kotlin( "source.kt", """ import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class Foo(val a: Int) """ ) ).apply { kaptArgs[OPTION_GENERATED] = "javax.annotation.GeneratedBlerg" }.compile() assertThat(result.messages).contains( "Invalid option value for $OPTION_GENERATED" ) } @Test fun disableProguardRulesGenerating() { val result = prepareCompilation( kotlin( "source.kt", """ import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class Foo(val a: Int) """ ) ).apply { kaptArgs[OPTION_GENERATE_PROGUARD_RULES] = "false" }.compile() assertThat(result.generatedFiles.filter { it.endsWith(".pro") }).isEmpty() } @Test fun multipleErrors() { val result = compile( kotlin( "source.kt", """ import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) class Class1(private var a: Int, private var b: Int) @JsonClass(generateAdapter = true) class Class2(private var c: Int) """ ) ) assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR) assertThat(result.messages).contains("property a is not visible") assertThat(result.messages).contains("property c is not visible") } @Test fun extendPlatformType() { val result = compile( kotlin( "source.kt", """ import com.squareup.moshi.JsonClass import java.util.Date @JsonClass(generateAdapter = true) class ExtendsPlatformClass(var a: Int) : Date() """ ) ) assertThat(result.messages).contains("supertype java.util.Date is not a Kotlin type") } @Test fun extendJavaType() { val result = compile( kotlin( "source.kt", """ import com.squareup.moshi.JsonClass import com.squareup.moshi.kotlin.codegen.JavaSuperclass @JsonClass(generateAdapter = true) class ExtendsJavaType(var b: Int) : JavaSuperclass() """ ) ) assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR) assertThat(result.messages) .contains("supertype com.squareup.moshi.kotlin.codegen.JavaSuperclass is not a Kotlin type") } @Test fun nonFieldApplicableQualifier() { val result = compile( kotlin( "source.kt", """ import com.squareup.moshi.JsonClass import com.squareup.moshi.JsonQualifier import kotlin.annotation.AnnotationRetention.RUNTIME import kotlin.annotation.AnnotationTarget.PROPERTY import kotlin.annotation.Retention import kotlin.annotation.Target @Retention(RUNTIME) @Target(PROPERTY) @JsonQualifier annotation class UpperCase @JsonClass(generateAdapter = true) class ClassWithQualifier(@UpperCase val a: Int) """ ) ) // We instantiate directly so doesn't need to be FIELD assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.OK) } @Test fun nonRuntimeQualifier() { val result = compile( kotlin( "source.kt", """ import com.squareup.moshi.JsonClass import com.squareup.moshi.JsonQualifier import kotlin.annotation.AnnotationRetention.BINARY import kotlin.annotation.AnnotationTarget.FIELD import kotlin.annotation.AnnotationTarget.PROPERTY import kotlin.annotation.Retention import kotlin.annotation.Target @Retention(BINARY) @Target(PROPERTY, FIELD) @JsonQualifier annotation class UpperCase @JsonClass(generateAdapter = true) class ClassWithQualifier(@UpperCase val a: Int) """ ) ) assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR) assertThat(result.messages).contains("JsonQualifier @UpperCase must have RUNTIME retention") } @Test fun `TypeAliases with the same backing type should share the same adapter`() { val result = compile( kotlin( "source.kt", """ import com.squareup.moshi.JsonClass typealias FirstName = String typealias LastName = String @JsonClass(generateAdapter = true) data class Person(val firstName: FirstName, val lastName: LastName, val hairColor: String) """ ) ) assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.OK) // We're checking here that we only generate one `stringAdapter` that's used for both the // regular string properties as well as the the aliased ones. val adapterClass = result.classLoader.loadClass("PersonJsonAdapter").kotlin assertThat(adapterClass.declaredMemberProperties.map { it.returnType }).containsExactly( JsonReader.Options::class.createType(), JsonAdapter::class.parameterizedBy(String::class) ) } @Test fun `Processor should generate comprehensive proguard rules`() { val result = compile( kotlin( "source.kt", """ package testPackage import com.squareup.moshi.JsonClass import com.squareup.moshi.JsonQualifier typealias FirstName = String typealias LastName = String @JsonClass(generateAdapter = true) data class Aliases(val firstName: FirstName, val lastName: LastName, val hairColor: String) @JsonClass(generateAdapter = true) data class Simple(val firstName: String) @JsonClass(generateAdapter = true) data class Generic<T>(val firstName: T, val lastName: String) @JsonQualifier annotation class MyQualifier @JsonClass(generateAdapter = true) data class UsingQualifiers(val firstName: String, @MyQualifier val lastName: String) @JsonClass(generateAdapter = true) data class MixedTypes(val firstName: String, val otherNames: MutableList<String>) @JsonClass(generateAdapter = true) data class DefaultParams(val firstName: String = "") @JsonClass(generateAdapter = true) data class Complex<T>(val firstName: FirstName = "", @MyQualifier val names: MutableList<String>, val genericProp: T) object NestedType { @JsonQualifier annotation class NestedQualifier @JsonClass(generateAdapter = true) data class NestedSimple(@NestedQualifier val firstName: String) } @JsonClass(generateAdapter = true) class MultipleMasks( val arg0: Long = 0, val arg1: Long = 1, val arg2: Long = 2, val arg3: Long = 3, val arg4: Long = 4, val arg5: Long = 5, val arg6: Long = 6, val arg7: Long = 7, val arg8: Long = 8, val arg9: Long = 9, val arg10: Long = 10, val arg11: Long, val arg12: Long = 12, val arg13: Long = 13, val arg14: Long = 14, val arg15: Long = 15, val arg16: Long = 16, val arg17: Long = 17, val arg18: Long = 18, val arg19: Long = 19, @Suppress("UNUSED_PARAMETER") arg20: Long = 20, val arg21: Long = 21, val arg22: Long = 22, val arg23: Long = 23, val arg24: Long = 24, val arg25: Long = 25, val arg26: Long = 26, val arg27: Long = 27, val arg28: Long = 28, val arg29: Long = 29, val arg30: Long = 30, val arg31: Long = 31, val arg32: Long = 32, val arg33: Long = 33, val arg34: Long = 34, val arg35: Long = 35, val arg36: Long = 36, val arg37: Long = 37, val arg38: Long = 38, @Json(ignore = true) val arg39: Long = 39, val arg40: Long = 40, val arg41: Long = 41, val arg42: Long = 42, val arg43: Long = 43, val arg44: Long = 44, val arg45: Long = 45, val arg46: Long = 46, val arg47: Long = 47, val arg48: Long = 48, val arg49: Long = 49, val arg50: Long = 50, val arg51: Long = 51, val arg52: Long = 52, @Json(ignore = true) val arg53: Long = 53, val arg54: Long = 54, val arg55: Long = 55, val arg56: Long = 56, val arg57: Long = 57, val arg58: Long = 58, val arg59: Long = 59, val arg60: Long = 60, val arg61: Long = 61, val arg62: Long = 62, val arg63: Long = 63, val arg64: Long = 64, val arg65: Long = 65 ) """ ) ) assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.OK) result.generatedFiles.filter { it.extension == "pro" }.forEach { generatedFile -> when (generatedFile.nameWithoutExtension) { "moshi-testPackage.Aliases" -> assertThat(generatedFile.readText()).contains( """ -if class testPackage.Aliases -keepnames class testPackage.Aliases -if class testPackage.Aliases -keep class testPackage.AliasesJsonAdapter { public <init>(com.squareup.moshi.Moshi); } """.trimIndent() ) "moshi-testPackage.Simple" -> assertThat(generatedFile.readText()).contains( """ -if class testPackage.Simple -keepnames class testPackage.Simple -if class testPackage.Simple -keep class testPackage.SimpleJsonAdapter { public <init>(com.squareup.moshi.Moshi); } """.trimIndent() ) "moshi-testPackage.Generic" -> assertThat(generatedFile.readText()).contains( """ -if class testPackage.Generic -keepnames class testPackage.Generic -if class testPackage.Generic -keep class testPackage.GenericJsonAdapter { public <init>(com.squareup.moshi.Moshi,java.lang.reflect.Type[]); } """.trimIndent() ) "moshi-testPackage.UsingQualifiers" -> { assertThat(generatedFile.readText()).contains( """ -if class testPackage.UsingQualifiers -keepnames class testPackage.UsingQualifiers -if class testPackage.UsingQualifiers -keep class testPackage.UsingQualifiersJsonAdapter { public <init>(com.squareup.moshi.Moshi); } """.trimIndent() ) } "moshi-testPackage.MixedTypes" -> assertThat(generatedFile.readText()).contains( """ -if class testPackage.MixedTypes -keepnames class testPackage.MixedTypes -if class testPackage.MixedTypes -keep class testPackage.MixedTypesJsonAdapter { public <init>(com.squareup.moshi.Moshi); } """.trimIndent() ) "moshi-testPackage.DefaultParams" -> assertThat(generatedFile.readText()).contains( """ -if class testPackage.DefaultParams -keepnames class testPackage.DefaultParams -if class testPackage.DefaultParams -keep class testPackage.DefaultParamsJsonAdapter { public <init>(com.squareup.moshi.Moshi); } -if class testPackage.DefaultParams -keepnames class kotlin.jvm.internal.DefaultConstructorMarker -if class testPackage.DefaultParams -keepclassmembers class testPackage.DefaultParams { public synthetic <init>(java.lang.String,int,kotlin.jvm.internal.DefaultConstructorMarker); } """.trimIndent() ) "moshi-testPackage.Complex" -> { assertThat(generatedFile.readText()).contains( """ -if class testPackage.Complex -keepnames class testPackage.Complex -if class testPackage.Complex -keep class testPackage.ComplexJsonAdapter { public <init>(com.squareup.moshi.Moshi,java.lang.reflect.Type[]); } -if class testPackage.Complex -keepnames class kotlin.jvm.internal.DefaultConstructorMarker -if class testPackage.Complex -keepclassmembers class testPackage.Complex { public synthetic <init>(java.lang.String,java.util.List,java.lang.Object,int,kotlin.jvm.internal.DefaultConstructorMarker); } """.trimIndent() ) } "moshi-testPackage.MultipleMasks" -> assertThat(generatedFile.readText()).contains( """ -if class testPackage.MultipleMasks -keepnames class testPackage.MultipleMasks -if class testPackage.MultipleMasks -keep class testPackage.MultipleMasksJsonAdapter { public <init>(com.squareup.moshi.Moshi); } -if class testPackage.MultipleMasks -keepnames class kotlin.jvm.internal.DefaultConstructorMarker -if class testPackage.MultipleMasks -keepclassmembers class testPackage.MultipleMasks { public synthetic <init>(long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,int,int,int,kotlin.jvm.internal.DefaultConstructorMarker); } """.trimIndent() ) "moshi-testPackage.NestedType.NestedSimple" -> { assertThat(generatedFile.readText()).contains( """ -if class testPackage.NestedType${'$'}NestedSimple -keepnames class testPackage.NestedType${'$'}NestedSimple -if class testPackage.NestedType${'$'}NestedSimple -keep class testPackage.NestedType_NestedSimpleJsonAdapter { public <init>(com.squareup.moshi.Moshi); } """.trimIndent() ) } else -> error("Unexpected proguard file! ${generatedFile.name}") } } } private fun prepareCompilation(vararg sourceFiles: SourceFile): KotlinCompilation { return KotlinCompilation() .apply { workingDir = temporaryFolder.root annotationProcessors = listOf(JsonClassCodegenProcessor()) inheritClassPath = true sources = sourceFiles.asList() verbose = false } } private fun compile(vararg sourceFiles: SourceFile): KotlinCompilation.Result { return prepareCompilation(*sourceFiles).compile() } private fun KClassifier.parameterizedBy(vararg types: KClass<*>): KType { return parameterizedBy(*types.map { it.createType() }.toTypedArray()) } private fun KClassifier.parameterizedBy(vararg types: KType): KType { return createType( types.map { it.asProjection() } ) } private fun KType.asProjection(variance: KVariance? = INVARIANT): KTypeProjection { return KTypeProjection(variance, this) } }
9
null
744
9,534
7f36bdff42fadb041722d2c8f5292d5e01cf84cf
26,135
moshi
Apache License 2.0
platform/workspace/jps/src/com/intellij/platform/workspace/jps/serialization/impl/CustomFacetRelatedEntitySerializer.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.ide.impl.jps.serialization import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.workspaceModel.ide.JpsImportedEntitySource import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.bridgeEntities.ModuleEntity import org.jdom.Element import org.jetbrains.annotations.ApiStatus import org.jetbrains.jps.model.serialization.facet.FacetState import org.jetbrains.jps.model.serialization.facet.JpsFacetSerializer /** * Originally, [com.intellij.facet.Facet] were made to support custom setting for the module, but this solution is not * rather flexible and thanks to the workspace model we have an opportunity to make custom entities describing additional * module settings. To have a sort of bridge between new approach with declaring custom module settings and [com.intellij.facet.Facet] * several extension points were introduced: * 1) [CustomFacetRelatedEntitySerializer] to add support custom entity * serialization/deserialization as facet tag. * 2) [com.intellij.workspaceModel.ide.legacyBridge.WorkspaceFacetContributor] to have an option to fire different sorts of event related to the [com.intellij.facet.Facet] during * the changes of your custom entity this extension point should be implemented. * * If you want to use your custom module setting entity under the hood of your facet you also need to implement * [com.intellij.workspaceModel.ide.impl.legacyBridge.facet.FacetBridge] to be properly updated. * * **N.B. Most of the time you need to implement them all to have a correct support all functionality relying on Facets.** */ @ApiStatus.Internal @ApiStatus.OverrideOnly interface CustomFacetRelatedEntitySerializer<T: WorkspaceEntity> { /** * Declare class for the main entity associated with [com.intellij.facet.Facet]. */ val rootEntityType: Class<T> /** * Facet type [com.intellij.facet.FacetType.getStringId] this extension point can serialization/deserialization. * The result of deserialization, entities of the type declared at [rootEntityType] in the [com.intellij.workspaceModel.storage.EntityStorage] */ val supportedFacetType: String /** * Method for deserialization [org.jetbrains.jps.model.serialization.facet.FacetState] read from external source. Facet state is * an intermediate representation to avoid core communication with tags directly. * @param moduleEntity module to which these settings belong * @param facetState intermediate representation of facet related data read out from external sources * @param evaluateEntitySource function which should be invoked to get [com.intellij.workspaceModel.storage.EntitySource] * for your entities and externalSystemId which should be stored somewhere in your entities */ fun loadEntitiesFromFacetState(moduleEntity: ModuleEntity, facetState: FacetState, evaluateEntitySource: (FacetState) -> EntitySource) /** * Create intermediate representation from entities of declared at [rootEntityType] type which will be used for serialization on disk. * @param entities list of certain type entities * @param storeExternally indicator which tells where this data will be store, under `.idea` or in external system folder */ fun createFacetStateFromEntities(entities: List<T>, storeExternally: Boolean): List<FacetState> { return entities.map { settingsEntity -> val state = FacetState().apply { name = getEntityName(settingsEntity) facetType = supportedFacetType configuration = Element(JpsFacetSerializer.CONFIGURATION_TAG) val externalSystemIdValue = (settingsEntity.entitySource as? JpsImportedEntitySource)?.externalSystemId if (storeExternally) { externalSystemId = externalSystemIdValue } else { externalSystemIdInInternalStorage = externalSystemIdValue } } state.configuration = serializeIntoXml(settingsEntity) return@map state } } fun getEntityName(entity: T): String /** * Method for creation facet XML tag from root type entity passed as a parameter */ fun serializeIntoXml(entity: T): Element companion object { val EP_NAME: ExtensionPointName<CustomFacetRelatedEntitySerializer<WorkspaceEntity>> = ExtensionPointName.create("com.intellij.workspaceModel.customFacetRelatedEntitySerializer") } }
284
null
5162
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
4,591
intellij-community
Apache License 2.0
shared/src/commonMain/kotlin/ui/theme/MyFonts.kt
EvertW
629,878,605
false
null
package ui.theme import androidx.compose.runtime.Composable import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import ui.resources.font internal object MyFonts { private const val SORA = "Space Grotesk" private const val DM_SANS = "DM Sans" val Sora @Composable get() = FontFamily( font( name = SORA, res = "sora_extrabold", weight = FontWeight.ExtraBold, style = FontStyle.Normal ), font( name = SORA, res = "sora_bold", weight = FontWeight.Bold, style = FontStyle.Normal ), font( name = SORA, res = "sora_medium", weight = FontWeight.Medium, style = FontStyle.Normal ), font( name = SORA, res = "sora_semibold", weight = FontWeight.SemiBold, style = FontStyle.Normal ), font( name = SORA, res = "sora_regular", weight = FontWeight.Normal, style = FontStyle.Normal ), font( name = SORA, res = "sora_light", weight = FontWeight.Light, style = FontStyle.Normal ), font( name = SORA, res = "sora_extralight", weight = FontWeight.ExtraLight, style = FontStyle.Normal ), font( name = SORA, res = "sora_thin", weight = FontWeight.Thin, style = FontStyle.Normal ), ) val DmSans @Composable get() = FontFamily( font( name = DM_SANS, res = "dmsans_bold", weight = FontWeight.Bold, style = FontStyle.Normal ), font( name = DM_SANS, res = "dmsans_medium", weight = FontWeight.Medium, style = FontStyle.Normal ), font( name = DM_SANS, res = "dmsans_regular", weight = FontWeight.Normal, style = FontStyle.Normal ), ) }
0
Kotlin
0
1
89e3a06d6fcaeca0a8b3ef3604b36a62607f8772
2,535
ComposeMultiplatformExperiment
Apache License 2.0
network/src/main/java/com/example/network/Dispatcher.kt
victory316
660,866,016
false
null
package com.example.network import javax.inject.Qualifier @Qualifier @Retention(AnnotationRetention.RUNTIME) annotation class Dispatcher(val dispatcher: Dispatchers) enum class Dispatchers { Default, IO, }
10
Kotlin
0
0
3772673c8a7426f2260cd60481c57107b673475d
216
LatestEffort
Apache License 2.0
src/main/kotlin/com/github/sam0delkin/intellijpsa/completion/AnyCompletionContributor.kt
sam0delkin
602,200,047
false
{"Kotlin": 35630}
package com.github.sam0delkin.intellijpsa.completion import com.github.sam0delkin.intellijpsa.icons.Icons import com.github.sam0delkin.intellijpsa.services.CompletionService import com.github.sam0delkin.intellijpsa.services.RequestType import com.intellij.codeInsight.completion.* import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.codeInsight.navigation.actions.GotoDeclarationHandler import com.intellij.notification.NotificationGroupManager import com.intellij.notification.NotificationType import com.intellij.openapi.components.service import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.guessProjectDir import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.patterns.PlatformPatterns import com.intellij.psi.PsiElement import com.intellij.psi.PsiManager import com.intellij.psi.util.elementType import com.intellij.util.ProcessingContext import com.jetbrains.rd.util.string.printToString import kotlinx.serialization.json.* import org.apache.commons.lang3.StringUtils class AnyCompletionContributor() { class Completion : CompletionContributor() { init { extend( CompletionType.BASIC, PlatformPatterns.psiElement(), object : CompletionProvider<CompletionParameters>() { override fun addCompletions( parameters: CompletionParameters, context: ProcessingContext, resultSet: CompletionResultSet ) { val project = parameters.position.project val completionService = project.service<CompletionService>() val settings = completionService.getSettings() val language = parameters.originalFile.language var languageString = language.id if (language.baseLanguage !== null && !settings.isLanguageSupported(languageString)) { languageString = language.baseLanguage!!.id } val json = completionService.getCompletions( settings, parameters.originalPosition, parameters.originalFile, RequestType.Completion, languageString, parameters.offset ) if (null === json) { return } if (null !== json.get("completions")) { for (i in json.get("completions") as JsonArray) { var priority = 0.0 var element = LookupElementBuilder.create(i.jsonObject.get("text")?.jsonPrimitive!!.content) element = element.withIcon(Icons.PluginIcon) if (i.jsonObject.get("bold")?.jsonPrimitive!!.boolean) { element = element.bold() priority = 100.0 } element = element.withTypeText(i.jsonObject.get("type")?.jsonPrimitive!!.content) if (i.jsonObject.containsKey("priority")) { priority = i.jsonObject.get("priority")?.jsonPrimitive!!.long.toDouble() } resultSet.addElement(PrioritizedLookupElement.withPriority(element, priority)) } } if (null !== json.get("notifications")) { for (i in json.get("notifications") as JsonArray) { var notificationType = NotificationType.INFORMATION when (i.jsonObject.get("type")?.jsonPrimitive!!.content) { "info" -> notificationType = NotificationType.INFORMATION "warning" -> notificationType = NotificationType.WARNING "error" -> notificationType = NotificationType.ERROR } NotificationGroupManager.getInstance() .getNotificationGroup("PSA Notification") .createNotification( i.jsonObject.get("text")?.jsonPrimitive!!.content, notificationType ) .notify(parameters.originalFile.project) } } } } ) } } class GotoDeclaration : GotoDeclarationHandler { override fun getGotoDeclarationTargets( sourceElement: PsiElement?, offset: Int, editor: Editor? ): Array<PsiElement>? { if (sourceElement === null) { return null } val project = sourceElement.project val completionService = project.service<CompletionService>() val settings = completionService.getSettings() val language = sourceElement.containingFile.language var languageString = language.id if (language.baseLanguage !== null && !settings.isLanguageSupported(languageString)) { languageString = language.baseLanguage!!.id } if (!settings.isElementTypeMatchingFilter(sourceElement.elementType.printToString())) { return null } val json = completionService.getCompletions( settings, sourceElement, sourceElement.containingFile, RequestType.GoTo, languageString, offset ) if (null === json) { return null } val psiElements = ArrayList<PsiElement>() val fm = VirtualFileManager.getInstance() val pm = PsiManager.getInstance(project) if (json.containsKey("completions")) { for (i in json.get("completions") as JsonArray) { val linkData = i.jsonObject.get("link")?.jsonPrimitive!!.content val link = linkData.split(':') val path = settings.replacePathMappings(link[0]) val virtualFile = fm.findFileByUrl(project.guessProjectDir().toString() + path) if (null !== virtualFile) { val psiFile = pm.findFile(virtualFile) if (null !== psiFile) { if (link.count() > 1) { val position = StringUtils.ordinalIndexOf(psiFile.originalFile.text, "\n", link[1].toInt()) val element = psiFile.findElementAt(position) if (null !== element) { psiElements.add(element) } else { psiElements.add(psiFile.firstChild) } } else { psiElements.add(psiFile.firstChild) } } } } } if (json.containsKey("goto_element_filter")) { val filter = (json.get("goto_element_filter") as JsonArray).map { i -> i.jsonPrimitive.content }.joinToString(",") settings.setElementFilter(filter) } if (json.containsKey("notifications")) { for (i in json.get("notifications") as JsonArray) { var notificationType = NotificationType.INFORMATION when (i.jsonObject.get("type")?.jsonPrimitive!!.content) { "info" -> notificationType = NotificationType.INFORMATION "warning" -> notificationType = NotificationType.WARNING "error" -> notificationType = NotificationType.ERROR } NotificationGroupManager.getInstance() .getNotificationGroup("PSA Notification") .createNotification(i.jsonObject.get("text")?.jsonPrimitive!!.content, notificationType) .notify(sourceElement.containingFile.project) } } return psiElements.toList().toTypedArray() } } }
0
Kotlin
0
3
cf644d5d3c5c4ada4409805e44a58489eb3c4234
9,016
intellij-psa
MIT License
app/src/main/java/com/fracta7/e_bookshelf/presentation/reading_list/ReadingListAllViewModel.kt
fracta7
532,576,663
false
{"Kotlin": 157376}
package com.fracta7.e_bookshelf.presentation.reading_list import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.fracta7.e_bookshelf.domain.repository.AppRepository import com.fracta7.e_bookshelf.util.Resource import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class ReadingListAllViewModel @Inject constructor( repository: AppRepository ) : ViewModel() { var state by mutableStateOf(ReadingListAllState()) init { viewModelScope.launch { repository.getAllBooks().collect { state = when (it) { is Resource.Success -> { state.copy(books = it.data!!, isDbEmpty = false, isLoading = false) } is Resource.Error -> { state.copy(isDbEmpty = true, isLoading = false) } is Resource.Loading -> { state.copy(isLoading = true) } } } } viewModelScope.launch { repository.getDarkSettings().collect { state = state.copy(darkTheme = it) } } viewModelScope.launch { repository.getDynamicSettings().collect { state = state.copy(dynamicTheme = it) } } } }
0
Kotlin
0
2
43e1b6fafa6fc7a55bccf83dfc3a9f4b781c77f7
1,568
e-bookshelf
MIT License
src/main/kotlin/csense/idea/base/bll/psiWrapper/class/operations/is/IsSubtypeOfRuntimeException.kt
csense-oss
226,373,994
false
{"Kotlin": 165209}
@file:Suppress("unused") package csense.idea.base.bll.psiWrapper.`class`.operations.`is` import csense.idea.base.bll.psiWrapper.`class`.* import csense.idea.base.bll.psiWrapper.`class`.operations.* fun KtPsiClass.isSubtypeOfRuntimeException(): Boolean = isSubtypeOfKotlinRuntimeException() || isSubtypeOfJavaRuntimeException() fun KtPsiClass.isSubtypeOfJavaRuntimeException(): Boolean = isSubTypeOf(KtPsiClass.javaRuntimeExceptionFqName) fun KtPsiClass.isSubtypeOfKotlinRuntimeException(): Boolean = isSubTypeOf(KtPsiClass.kotlinRuntimeExceptionFqName) fun List<KtPsiClass>.filterNotSubTypeOfRuntimeException(): List<KtPsiClass> = filterNot { it: KtPsiClass -> it.isSubtypeOfRuntimeException() }
1
Kotlin
0
0
2888dfc8991ba5eb6d9df5facd4d1ad375d67e81
719
idea-kotlin-shared-base
MIT License
vector/src/main/java/varta/cdac/app/features/crypto/keys/KeysExporter.kt
sb-child
395,765,587
false
null
/* * Copyright 2019 New Vector Ltd * * 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 im.vector.app.features.crypto.keys import android.content.Context import android.net.Uri import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.matrix.android.sdk.api.session.Session import javax.inject.Inject class KeysExporter @Inject constructor( private val session: Session, private val context: Context ) { /** * Export keys and write them to the provided uri */ suspend fun export(password: String, uri: Uri) { return withContext(Dispatchers.IO) { val data = session.cryptoService().exportRoomKeys(password) context.contentResolver.openOutputStream(uri) ?.use { it.write(data) } ?: throw IllegalStateException("Unable to open file for writting") } } }
55
null
0
1
ef17804af2f134cfbeca5645579f2fbb4b685944
1,418
element-android
Apache License 2.0
examples/http-clients/src/test/kotlin/example/spring/boot/http/clients/gateways/libraryservice/LibraryServiceContract.kt
test-automation-in-practice
506,693,260
false
null
package example.spring.boot.http.clients.gateways.libraryservice import ch.qos.logback.classic.Level.convertAnSLF4JLevel import ch.qos.logback.classic.Logger import com.github.tomakehurst.wiremock.client.MappingBuilder import com.github.tomakehurst.wiremock.client.WireMock.aResponse import com.github.tomakehurst.wiremock.client.WireMock.containing import com.github.tomakehurst.wiremock.client.WireMock.equalToJson import com.github.tomakehurst.wiremock.client.WireMock.post import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.ValueSource import org.slf4j.Logger.ROOT_LOGGER_NAME import org.slf4j.LoggerFactory.getLogger import org.slf4j.event.Level import org.slf4j.event.Level.INFO import org.slf4j.event.Level.TRACE import org.springframework.http.HttpHeaders.ACCEPT import org.springframework.http.HttpHeaders.CONTENT_TYPE import org.springframework.http.MediaType.APPLICATION_JSON_VALUE import org.springframework.http.MediaType.TEXT_PLAIN_VALUE /** * When testing HTTP interaction, in this case calling another service's API, the tests should be written as * block-box tests. The tests only need to verify that correct requests are sent and responses are processed * correctly. It does not matter which client technology is actually used to make those calls, as long as * all relevant cases are handled as they should be. * * Using Wiremock is essential here, because it allows us to simulate the other service in every aspect without * having to mock our actually used client technology. * * Trying to write these tests as unit tests using mocking to simulate the underlying client technology only * makes them harder to write, understand and maintain in case we want to change which client we use. */ internal abstract class LibraryServiceContract( private val wireMockInfo: WireMockRuntimeInfo ) { private val cut: LibraryService by lazy { createClassUnderTest(LibraryServiceProperties(baseUrl = wireMockInfo.httpBaseUrl)) } protected abstract fun createClassUnderTest(properties: LibraryServiceProperties): LibraryService @BeforeEach fun setLogLevels() { setLogLevel(ROOT_LOGGER_NAME, INFO) setLogLevel("org.zalando.logbook", TRACE) } private fun setLogLevel(loggerName: String, level: Level) { (getLogger(loggerName) as Logger).level = convertAnSLF4JLevel(level) } @ParameterizedTest @ValueSource(ints = [200, 201]) fun `sends correct request and parses successful responses`(status: Int) { stub { post("/api/books") .withHeader(ACCEPT, containing(APPLICATION_JSON_VALUE)) .withHeader(CONTENT_TYPE, containing(APPLICATION_JSON_VALUE)) .withRequestBody( equalToJson( """ { "title": "Clean Code", "isbn": "9780132350884" } """ ) ) .willReturn( aResponse() .withStatus(status) .withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE) .withBody( """ { "id": "be64192f-879c-4346-8aff-76582117a42d", "title": "Clean Code", "isbn": "9780132350884", "unknown": true } """ ) // includes unknown property to make sure, that our clients are parsing leniently ) } val book = Book( title = "Clean Code", isbn = "9780132350884" ) val expected = CreatedBook( id = "be64192f-879c-4346-8aff-76582117a42d", title = "Clean Code", isbn = "9780132350884" ) assertThat(cut.addBook(book)).isEqualTo(expected) } @ParameterizedTest @ValueSource(ints = [400, 401, 403, 404, 500, 502, 504]) fun `throws exception for failed responses`(status: Int) { stub { post("/api/books").willReturn(aResponse().withStatus(status)) } val book = Book( title = "Clean Architecture", isbn = "9780134494166" ) assertThrows<LibraryServiceException> { cut.addBook(book) } } @Test fun `throws exception for no-content response`() { stub { post("/api/books").willReturn( aResponse().withHeader(CONTENT_TYPE, TEXT_PLAIN_VALUE).withStatus(204) ) } val book = Book( title = "Clean Architecture", isbn = "9780134494166" ) assertThrows<LibraryServiceException> { cut.addBook(book) } } private fun stub(supplier: () -> MappingBuilder) { wireMockInfo.wireMock.register(supplier()) } }
0
null
0
54
5a4b1fc0cc693a1af50a88057d04516a1303afa9
5,280
cnt-spring-boot
Apache License 2.0
src/main/kotlin/com/github/raink1208/radiobot/util/ApplicationIDs.kt
raink1208
443,625,927
false
null
package com.github.raink1208.radiobot.util enum class ApplicationIDs(val id: Long) { YOUTUBE_TOGETHER(755600276941176913), POKER(755827207812677713), CHESS(832012774040141894), BETRAYAL(773336526917861400), FISHING(814288819477020702); }
3
Kotlin
0
0
b45f283196ee064406af7888cf67668bdd2a6db0
258
radioBot
MIT License
src/main/kotlin/poc/fileio/writeFile/app/web/FileController.kt
marco-aurelioo
452,042,508
false
{"Kotlin": 13548}
package poc.fileio.writeFile.app.web import org.springframework.core.io.InputStreamResource import org.springframework.core.io.Resource import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RestController import poc.fileio.writeFile.domain.file.WriteFileService import java.io.FileInputStream @RestController class FileController(var writeFileService: WriteFileService) { @GetMapping("/file") fun getFileBoleto(): ResponseEntity<Resource>{ var file = writeFileService.createBoletoFile() val i = InputStreamResource(FileInputStream(file)) return ResponseEntity.ok().contentLength(file.length()) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(i); } @GetMapping("/file2") fun getFileBoleto2(): ResponseEntity<Resource>{ var file = writeFileService.createBoletoFileV2() val i = InputStreamResource(FileInputStream(file)) return ResponseEntity.ok().contentLength(file.length()) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(i); } @GetMapping("/file3") fun getFileBoleto3(): ResponseEntity<Resource>{ var file = writeFileService.createBoletoFileV3() val i = InputStreamResource(FileInputStream(file)) return ResponseEntity.ok().contentLength(file.length()) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(i); } @GetMapping("/file4") fun getFileBoleto4(): ResponseEntity<Resource>{ var file = writeFileService.createBoletoFileV4() val i = InputStreamResource(FileInputStream(file)) return ResponseEntity.ok().contentLength(file.length()) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(i); } @GetMapping("/file5") fun getFileBoleto5(): ResponseEntity<Resource>{ var file = writeFileService.createBoletoFileV4() val i = InputStreamResource(FileInputStream(file)) return ResponseEntity.ok().contentLength(file.length()) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(i); } @GetMapping("/file6") fun getFileBoleto6(): ResponseEntity<Resource>{ var file = writeFileService.createBoletoFileV6() val i = InputStreamResource(FileInputStream(file)) return ResponseEntity.ok().contentLength(file.length()) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(i); } @GetMapping("/file7") fun getFileBoleto7(): ResponseEntity<Resource>{ var file = writeFileService.createBoletoFileV7() val i = InputStreamResource(FileInputStream(file)) return ResponseEntity.ok().contentLength(file.length()) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(i); } }
0
Kotlin
0
0
755add3bd3bca6bc3f586cad5a67c218233e2eea
3,075
POCArquivos
MIT License
common/user/domain/src/commonTest/kotlin/dev/alvr/katana/common/user/domain/usecases/ObserveUserInfoUseCaseTest.kt
alvr
446,535,707
false
null
package dev.alvr.katana.common.user.domain.usecases import app.cash.turbine.test import arrow.core.left import arrow.core.right import dev.alvr.katana.common.user.domain.failures.UserFailure import dev.alvr.katana.common.user.domain.repositories.UserRepository import dev.alvr.katana.common.user.domain.userInfoMock import dev.alvr.katana.core.common.coroutines.KatanaDispatcher import dev.alvr.katana.core.domain.usecases.invoke import dev.alvr.katana.core.tests.di.coreTestsModule import dev.alvr.katana.core.tests.koinExtension import dev.alvr.katana.core.tests.shouldBeLeft import dev.alvr.katana.core.tests.shouldBeRight import dev.mokkery.answering.returns import dev.mokkery.every import dev.mokkery.mock import dev.mokkery.verify import io.kotest.core.spec.style.FreeSpec import io.kotest.core.test.TestCase import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.flow.flowOf import org.koin.test.KoinTest import org.koin.test.inject internal class ObserveUserInfoUseCaseTest : FreeSpec(), KoinTest { private val dispatcher by inject<KatanaDispatcher>() private val repo = mock<UserRepository>() private lateinit var useCase: ObserveUserInfoUseCase init { "successfully observing user info" { every { repo.userInfo } returns flowOf(userInfoMock.right()) useCase() useCase.flow.test(5.seconds) { awaitItem().shouldBeRight(userInfoMock) cancelAndConsumeRemainingEvents() } verify { repo.userInfo } } "failure observe user info" { every { repo.userInfo } returns flowOf(UserFailure.GettingUserInfo.left()) useCase() useCase.flow.test(5.seconds) { awaitItem().shouldBeLeft(UserFailure.GettingUserInfo) cancelAndConsumeRemainingEvents() } verify { repo.userInfo } } } override suspend fun beforeEach(testCase: TestCase) { useCase = ObserveUserInfoUseCase(dispatcher, repo) } override fun extensions() = listOf(koinExtension(coreTestsModule)) }
5
null
0
59
32cd2606337f7073ee274959fdec1a2180177921
2,132
katana
Apache License 2.0
app/src/main/java/destinum/tech/pruebawesend/Data/Local/TestDB.kt
ispam
163,337,826
false
null
package destinum.tech.pruebawesend.Data.Local import androidx.room.Database import androidx.room.RoomDatabase import destinum.tech.pruebawesend.Data.Local.DAOs.ListDataDAO import destinum.tech.pruebawesend.Data.Local.DAOs.LogDAO import destinum.tech.pruebawesend.Data.Local.Entities.ListData import destinum.tech.pruebawesend.Data.Local.Entities.Log @Database(entities = arrayOf(Log::class, ListData::class), version = 1, exportSchema = false) abstract class TestDB: RoomDatabase() { abstract fun logsDAO(): LogDAO abstract fun listDataDAO(): ListDataDAO }
0
Kotlin
0
0
994ff12645a58d01040e13b37af7564ef9866833
568
PruebaWeSend
Apache License 2.0
app/src/main/java/com/zacharee1/systemuituner/dialogs/SeekBarOptionDialog.kt
zacharee
221,786,635
false
{"Kotlin": 681812, "AIDL": 1172}
package com.zacharee1.systemuituner.dialogs import android.os.Bundle import android.view.View import com.zacharee1.systemuituner.R import kotlinx.coroutines.launch import tk.zwander.seekbarpreference.SeekBarView class SeekBarOptionDialog : BaseOptionDialog(), SeekBarView.SeekBarListener { companion object { const val ARG_MIN = "minValue" const val ARG_MAX = "maxValue" const val ARG_UNITS = "units" const val ARG_DEFAULT = "defaultValue" const val ARG_SCALE = "scale" const val ARG_INITIAL_VALUE = "initial_value" fun newInstance(key: String, min: Int = 0, max: Int = 100, default: Int = min, units: String? = null, scale: Float = 1.0f, initialValue: Int = 100): SeekBarOptionDialog { return SeekBarOptionDialog().apply { arguments = Bundle().apply { putString(ARG_KEY, key) putInt(ARG_MIN, min) putInt(ARG_MAX, max) putInt(ARG_DEFAULT, default) putString(ARG_UNITS, units) putFloat(ARG_SCALE, scale) putInt(ARG_INITIAL_VALUE, initialValue) } } } } override val layoutRes = R.layout.seekbar_dialog private val min by lazy { arguments?.getInt(ARG_MIN, 0) ?: 0 } private val max by lazy { arguments?.getInt(ARG_MAX, 100) ?: 100 } private val default by lazy { arguments?.getInt(ARG_DEFAULT, min) ?: min } private val units by lazy { arguments?.getString(ARG_UNITS) } private val scale by lazy { arguments?.getFloat(ARG_SCALE, 1.0f) ?: 1.0f } private val initialValue by lazy { arguments?.getInt(ARG_INITIAL_VALUE, default) ?: default } private val seekbarView: SeekBarView? get() = dialog?.findViewById(R.id.seekbar_view) override fun onBindDialogView(view: View) { super.onBindDialogView(view) launch { seekbarView?.onBind(min, max, initialValue, default, scale, units, "",this@SeekBarOptionDialog) } } override fun onProgressAdded() {} override fun onProgressReset() {} override fun onProgressSubtracted() {} override fun onProgressChanged(newValue: Int, newScaledValue: Float) { launch { if (!notifyChanged(if (scale == 1f) newValue else newScaledValue)) { seekbarView?.listener = null seekbarView?.setValue(initialValue.toFloat(), false) seekbarView?.listener = this@SeekBarOptionDialog } } } }
25
Kotlin
174
994
27672d3a0ad7caf1dce360dc1a0651926903b8a8
2,567
Tweaker
MIT License
app/src/main/java/org/simple/clinic/instantsearch/InstantSearchUiRenderer.kt
simpledotorg
132,515,649
false
null
package org.simple.clinic.instantsearch import org.simple.clinic.instantsearch.InstantSearchProgressState.* import org.simple.clinic.mobius.ViewRenderer class InstantSearchUiRenderer( private val ui: InstantSearchUi ) : ViewRenderer<InstantSearchModel> { override fun render(model: InstantSearchModel) { ui.hideProgress() when (model.instantSearchProgressState) { IN_PROGRESS -> ui.showProgress() DONE -> renderResults() NO_RESULTS -> renderNoResults(model) null -> { // No-op } } } private fun renderNoResults(model: InstantSearchModel) { ui.hideResults() if (model.hasSearchQuery) { ui.hideNoPatientsInFacility() ui.showNoSearchResults() } else { ui.hideNoSearchResults() ui.showNoPatientsInFacility(model.facility!!.name) } } private fun renderResults() { ui.showResults() ui.hideNoSearchResults() ui.hideNoPatientsInFacility() } }
13
null
73
236
ff699800fbe1bea2ed0492df484777e583c53714
960
simple-android
MIT License
app/src/main/java/com/ledboot/toffee/di/androidx/HasAndroidxFragmentInjector.kt
ledboot
102,470,734
false
{"C": 3295767, "Shell": 1139239, "Makefile": 382024, "C++": 216570, "HTML": 210960, "Objective-C": 167873, "Kotlin": 141631, "M4": 65721, "Assembly": 40776, "CSS": 18145, "Java": 13473, "Perl": 10762, "Batchfile": 789}
package com.ledboot.toffee.di.androidx import androidx.fragment.app.Fragment import dagger.android.AndroidInjector import dagger.internal.Beta @Beta interface HasAndroidxFragmentInjector { fun androidxFragmentInjector(): AndroidInjector<Fragment> }
0
C
0
0
e3c1fd8dd4e9f70464d36fa10c78184c6ada55f3
255
Toffee
Apache License 2.0
plugins/kotlin/refactorings/kotlin.refactorings.common/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinFunctionProcessor.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.refactoring.rename import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.application.runReadAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.Pass import com.intellij.psi.* import com.intellij.psi.search.PsiSearchHelper import com.intellij.psi.search.SearchScope import com.intellij.refactoring.listeners.RefactoringElementListener import com.intellij.refactoring.rename.* import com.intellij.refactoring.util.CommonRefactoringUtil import com.intellij.refactoring.util.RefactoringUtil import com.intellij.usageView.UsageInfo import com.intellij.util.SmartList import org.jetbrains.kotlin.asJava.elements.KtLightElement import org.jetbrains.kotlin.asJava.elements.KtLightMethod import org.jetbrains.kotlin.asJava.namedUnwrappedElement import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.refactoring.KotlinCommonRefactoringSettings import org.jetbrains.kotlin.idea.refactoring.conflicts.checkRedeclarationConflicts import org.jetbrains.kotlin.idea.references.KtReference import org.jetbrains.kotlin.idea.search.ExpectActualUtils import org.jetbrains.kotlin.idea.search.ExpectActualUtils.actualsForExpected import org.jetbrains.kotlin.idea.search.ExpectActualUtils.withExpectedActuals import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded class RenameKotlinFunctionProcessor : RenameKotlinPsiProcessor() { private val javaMethodProcessorInstance = RenameJavaMethodProcessor() override fun canProcessElement(element: PsiElement): Boolean { return element is KtNamedFunction || (element is KtLightMethod && element.kotlinOrigin is KtNamedFunction) || element is FunctionWithSupersWrapper } override fun isToSearchInComments(psiElement: PsiElement) = KotlinCommonRefactoringSettings.getInstance().RENAME_SEARCH_IN_COMMENTS_FOR_FUNCTION override fun setToSearchInComments(element: PsiElement, enabled: Boolean) { KotlinCommonRefactoringSettings.getInstance().RENAME_SEARCH_IN_COMMENTS_FOR_FUNCTION = enabled } override fun isToSearchForTextOccurrences(element: PsiElement) = KotlinCommonRefactoringSettings.getInstance().RENAME_SEARCH_FOR_TEXT_FOR_FUNCTION override fun setToSearchForTextOccurrences(element: PsiElement, enabled: Boolean) { KotlinCommonRefactoringSettings.getInstance().RENAME_SEARCH_FOR_TEXT_FOR_FUNCTION = enabled } private fun getJvmName(element: PsiElement): String? { return renameRefactoringSupport.getJvmName(element) } private fun processFoundReferences( element: PsiElement, allReferences: Collection<PsiReference> ): Collection<PsiReference> { return when { getJvmName(element) == null -> allReferences element is KtElement -> allReferences.filterIsInstance<KtReference>() element is KtLightElement<*, *> -> allReferences.filterNot { it is KtReference } else -> emptyList() } } override fun findCollisions( element: PsiElement, newName: String, allRenames: Map<out PsiElement, String>, result: MutableList<UsageInfo> ) { val declaration = element.unwrapped as? KtNamedFunction ?: return checkConflictsAndReplaceUsageInfos(element, allRenames, result) result += SmartList<UsageInfo>().also { collisions -> checkRedeclarationConflicts(declaration, newName, collisions) renameRefactoringSupport.checkUsagesRetargeting(declaration, newName, result, collisions) } } private class FunctionWithSupersWrapper( val originalDeclaration: KtNamedFunction, val supers: List<PsiElement> ) : KtLightElement<KtNamedFunction, KtNamedFunction>, PsiNamedElement by originalDeclaration { override val kotlinOrigin: KtNamedFunction get() = originalDeclaration } private fun substituteForExpectOrActual(element: PsiElement?) = (element?.namedUnwrappedElement as? KtNamedDeclaration)?.let { el -> ActionUtil.underModalProgress(el.project, KotlinBundle.message("progress.title.searching.for.expected.actual")) { ExpectActualUtils.liftToExpected(el) } } override fun substituteElementToRename(element: PsiElement, editor: Editor?): PsiElement? { substituteForExpectOrActual(element)?.let { return it } val deepestSuperMethods = runProcessWithProgressSynchronously( KotlinBundle.message("rename.searching.for.super.declaration"), canBeCancelled = true, element.project ) { runReadAction { KotlinSearchUsagesSupport.SearchUtils.findDeepestSuperMethodsNoWrapping(element) } } val substitutedJavaElement = when { deepestSuperMethods.isEmpty() -> return element element is PsiMethod -> { javaMethodProcessorInstance.substituteElementToRename(element, editor) } else -> { val declaration = element.unwrapped as? KtNamedFunction ?: return element val chosenElements = checkSuperMethods(declaration, deepestSuperMethods) if (chosenElements.size > 1) FunctionWithSupersWrapper(declaration, chosenElements) else chosenElements.firstOrNull() ?: element } } if (substitutedJavaElement is KtLightMethod && element is KtDeclaration) { return substitutedJavaElement.kotlinOrigin as? KtNamedFunction } val canRename = try { PsiElementRenameHandler.canRename(element.project, editor, substitutedJavaElement) } catch (_: CommonRefactoringUtil.RefactoringErrorHintException) { false } return if (canRename) substitutedJavaElement else element } override fun substituteElementToRename(element: PsiElement, editor: Editor, renameCallback: Pass<in PsiElement>) { if (!PsiElementRenameHandler.canRename(element.getProject(), editor, element)) return fun preprocessAndPass(substitutedJavaElement: PsiElement) { val elementToProcess = if (substitutedJavaElement is KtLightMethod && element is KtDeclaration) { substitutedJavaElement.kotlinOrigin as? KtNamedFunction } else { substitutedJavaElement } renameCallback.accept(elementToProcess) } substituteForExpectOrActual(element)?.let { return preprocessAndPass(it) } val deepestSuperMethods = runProcessWithProgressSynchronously( KotlinBundle.message("rename.searching.for.super.declaration"), canBeCancelled = true, element.project ) { runReadAction { KotlinSearchUsagesSupport.SearchUtils.findDeepestSuperMethodsNoWrapping(element) } } when { deepestSuperMethods.isEmpty() -> preprocessAndPass(element) element is PsiMethod -> { javaMethodProcessorInstance.substituteElementToRename(element, editor, Pass.create(::preprocessAndPass)) } else -> { val declaration = element as? KtNamedFunction ?: return checkSuperMethodsWithPopup(declaration, deepestSuperMethods.toList(), editor) { chosenElements -> preprocessAndPass(if (chosenElements.size > 1) FunctionWithSupersWrapper(declaration, chosenElements) else chosenElements.firstOrNull() ?: element) } } } } override fun createRenameDialog( project: Project, element: PsiElement, nameSuggestionContext: PsiElement?, editor: Editor? ): RenameDialog { val elementForDialog = (element as? FunctionWithSupersWrapper)?.originalDeclaration ?: element return object : RenameDialog(project, elementForDialog, nameSuggestionContext, editor) { override fun createRenameProcessor(newName: String) = RenameProcessor(getProject(), element, newName, isSearchInComments, isSearchInNonJavaFiles) } } override fun prepareRenaming(element: PsiElement, newName: String, allRenames: MutableMap<PsiElement, String>, scope: SearchScope) { if (element is KtLightMethod && getJvmName(element) == null) { (element.kotlinOrigin as? KtNamedFunction)?.let { allRenames[it] = newName } } if (element is FunctionWithSupersWrapper) { allRenames.remove(element) } val namedFunction = element.unwrapped as? KtNamedFunction val originalName = namedFunction?.name ?: return val safeNewName = newName.quoteIfNeeded() for (declaration in ((element as? FunctionWithSupersWrapper)?.supers ?: listOf(element))) { val baseName = (declaration as? PsiNamedElement)?.name ?: originalName val newBaseName = if (renameRefactoringSupport.demangleInternalName(baseName) == originalName) { renameRefactoringSupport.mangleInternalName( newName, renameRefactoringSupport.getModuleNameSuffixForMangledName(baseName)!! ) } else newName prepareOverrideRenaming(declaration, baseName, newBaseName.quoteIfNeeded(), safeNewName, allRenames) } renameRefactoringSupport.prepareForeignUsagesRenaming(element, newName, allRenames, scope) } private fun prepareOverrideRenaming( declaration: PsiElement, baseName: @NlsSafe String, newBaseName: String, safeNewName: String, allRenames: MutableMap<PsiElement, String> ) { val project = declaration.project val searchHelper = PsiSearchHelper.getInstance(project) val overriders = ActionUtil.underModalProgress(project, KotlinBundle.message("rename.searching.for.all.overrides")) { val multiplatformDeclarations = if (declaration is KtNamedDeclaration) { withExpectedActuals(declaration) } else listOf(declaration) multiplatformDeclarations.forEach { allRenames[it] = safeNewName } multiplatformDeclarations.flatMap { d -> renameRefactoringSupport.findAllOverridingMethods(d, searchHelper.getUseScope(d)) } } for (originalOverrider in overriders) { // for possible Groovy wrappers val overrider = (originalOverrider as? PsiMirrorElement)?.prototype as? PsiMethod ?: originalOverrider if (overrider is SyntheticElement) continue val overriderName = (overrider as PsiNamedElement).name val newOverriderName = RefactoringUtil.suggestNewOverriderName(overriderName, baseName, newBaseName) if (newOverriderName != null) { RenameUtil.assertNonCompileElement(overrider) allRenames[overrider] = newOverriderName } } } override fun renameElement(element: PsiElement, newName: String, usages: Array<UsageInfo>, listener: RefactoringElementListener?) { val simpleUsages = ArrayList<UsageInfo>(usages.size) val ambiguousImportUsages = SmartList<UsageInfo>() val simpleImportUsages = SmartList<UsageInfo>() renameRefactoringSupport.processForeignUsages(element, newName, usages, fallbackHandler = { usage -> if (usage is LostDefaultValuesInOverridingFunctionUsageInfo) { usage.apply() return@processForeignUsages } when (usage.importState()) { ImportState.AMBIGUOUS -> ambiguousImportUsages += usage ImportState.SIMPLE -> simpleImportUsages += usage ImportState.NOT_IMPORT -> { if (!renameMangledUsageIfPossible(usage, element, newName)) { simpleUsages += usage } } } }) element.ambiguousImportUsages = ambiguousImportUsages val usagesToRename = if (simpleImportUsages.isEmpty()) simpleUsages else simpleImportUsages + simpleUsages renamePossiblyLightElement(element, newName, usagesToRename.toTypedArray(), listener) usages.forEach { (it as? KtResolvableCollisionUsageInfo)?.apply() } (element.unwrapped as? KtNamedDeclaration)?.let { renameRefactoringSupport.dropOverrideKeywordIfNecessary(it) } } override fun findReferences( element: PsiElement, searchScope: SearchScope, searchInCommentsAndStrings: Boolean ): Collection<PsiReference> { val references = super.findReferences(element, searchScope, searchInCommentsAndStrings) return processFoundReferences(element, references) } }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
13,271
intellij-community
Apache License 2.0
workshops/moscow_prefinals2020/day3/k.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package workshops.moscow_prefinals2020.day3 fun main() { val (x, y, z) = List(3) { readInts().drop(1).reversed() } var (low, high) = maxOf((x + y + z).maxOrNull()!!, 1).toLong() to Long.MAX_VALUE / 2 binarySearch@while (low + 1 < high) { val b = (low + high) / 2 val zNew = LongArray(z.size) var tooLarge = false fun add(index: Int, value: Long) { if (index >= zNew.size) tooLarge = true else zNew[index] += value } for (i in x.indices) for (j in y.indices) { add(i + j, x[i].toLong() * y[j]) for (k in i + j until zNew.size) { if (zNew[k] < b) break add(k + 1, zNew[k] / b) zNew[k] %= b } if (tooLarge) { low = b continue@binarySearch } } for (k in zNew.indices.reversed()) { if (zNew[k] == z[k].toLong()) continue if (zNew[k] > z[k]) low = b else high = b continue@binarySearch } return println(b) } println("impossible") } private fun readLn() = readLine()!! private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
bf2846347011309aace0c4a04ac5355296dfbd90
1,042
competitions
The Unlicense
projects/kotlin-project/src/org/lsp/kotlinproject/Constants.kt
Ruin0x11
121,824,068
false
null
package org.lsp.javaproject internal class Constants { private val notConstant = "notConstant" var yes = true var no = false var maybe: Boolean? = null companion object { const val INT = 42 const private val STRING = "string" val ENUM_TYPE = EnumType.FOO var sNotConstant = 12 } }
24
Kotlin
26
322
50e6726d8535b5f00ef507db19272c551a694db4
339
intellij-lsp-server
MIT License
remoting/src/main/kotlin/com/agmtopy/kocketmq/remoting/exception/impl/RemotingCommandException.kt
agmtopy
376,882,907
false
null
package com.agmtopy.kocketmq.remoting.exception.impl import com.agmtopy.kocketmq.remoting.exception.RemotingException class RemotingCommandException : RemotingException { constructor(message: String?) : super(message, null) {} constructor(message: String?, cause: Throwable?) : super(message, cause) {} companion object { private const val serialVersionUID = -6061365915274953096L } }
1
null
1
1
91e15b054ff8f1784d79b96e498894065ba025f8
411
kocketmq
Apache License 2.0
compiler/testData/psi/LocalDeclarations.kt
chashnikov
14,658,474
true
{"Java": 14526655, "Kotlin": 6831811, "JavaScript": 897073, "Groovy": 43935, "CSS": 14421, "Shell": 9248}
fun foo() { out 1 [a] abstract class foof {} abstract [a] class foof {} out val foo = 5 [a] var foo = 4 type f = T.() -> Unit }
0
Java
0
1
88a261234860ff0014e3c2dd8e64072c685d442d
159
kotlin
Apache License 2.0
features/dd-sdk-android-session-replay/src/test/kotlin/com/datadog/android/sessionreplay/forge/SystemInformationForgeryFactory.kt
DataDog
219,536,756
false
{"Kotlin": 9121111, "Java": 1179237, "C": 79303, "Shell": 63055, "C++": 32351, "Python": 5556, "CMake": 2000}
/* * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. * This product includes software developed at Datadog (https://www.datadoghq.com/). * Copyright 2016-Present Datadog, Inc. */ package com.datadog.android.sessionreplay.forge import android.content.res.Configuration import com.datadog.android.sessionreplay.internal.recorder.GlobalBounds import com.datadog.android.sessionreplay.internal.recorder.SystemInformation import fr.xgouchet.elmyr.Forge import fr.xgouchet.elmyr.ForgeryFactory internal class SystemInformationForgeryFactory : ForgeryFactory<SystemInformation> { override fun getForgery(forge: Forge): SystemInformation { return SystemInformation( screenBounds = GlobalBounds( x = 0, y = 0, width = forge.aPositiveLong(), height = forge.aPositiveLong() ), screenOrientation = forge.anElementFrom( intArrayOf( Configuration.ORIENTATION_PORTRAIT, Configuration.ORIENTATION_LANDSCAPE, Configuration.ORIENTATION_UNDEFINED ) ), screenDensity = forge.aFloat(min = 1f, max = 10f), themeColor = forge.aNullable { aStringMatching("#[0-9A-Fa-f]{6}[fF]{2}") } ) } }
61
Kotlin
60
151
d7e640cf6440ab150c2bbfbac261e09b27e258f4
1,391
dd-sdk-android
Apache License 2.0
shared/src/commonMain/kotlin/com/kaushalvasava/apps/kmp_api_handling/model/ImageModel.kt
KaushalVasava
683,397,952
false
{"Kotlin": 21384, "Swift": 342}
package com.kaushalvasava.apps.kmp_api_handling.model import kotlinx.serialization.Serializable @Serializable data class ImageModel(var urls: UrlModel)
0
Kotlin
3
9
973ab6f9a1b07cb1d123aae696ce5d78ae12d4a8
154
KMP_ApiHanding
Apache License 2.0
otpcomposable/src/main/java/com/itmagination/otpcomposable/widgets/LoadingView.kt
itmaginationdemos
554,857,435
false
null
package com.itmagination.otpcomposable.widgets import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment.Companion.CenterVertically import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.itmagination.otpcomposable.uimodel.LoadingCustomization @Composable fun LoadingView(data: LoadingCustomization) { Row(verticalAlignment = CenterVertically) { if (data.showMessage) { Text( modifier = data.modifier, text = data.loadingMessage, color = MaterialTheme.colors.onBackground, fontSize = MaterialTheme.typography.body2.fontSize, fontWeight = FontWeight.Bold ) } if (data.showProgress) { CircularProgressIndicator( modifier = Modifier.padding(start = 8.dp).size(24.dp), strokeWidth = 3.dp ) } } } @Preview @Composable private fun LoadingPreview() { LoadingView( LoadingCustomization( modifier = Modifier.padding(8.dp), loadingMessage = "Loading time!", showMessage = true, showProgress = true, ) ) }
0
Kotlin
0
2
cfed753f5430a3eac5be5f0fb2a1c6f926bd474b
1,604
OTPComposable
MIT License
service/src/test/java/be/hogent/faith/service/usecases/MakeEventFilesAvailableUseCaseTest.kt
hydrolythe
353,694,404
false
null
package be.hogent.faith.service.usecases import be.hogent.faith.domain.models.Event import be.hogent.faith.service.encryption.IEventEncryptionService import be.hogent.faith.service.repositories.IEventRepository import be.hogent.faith.service.repositories.IFileStorageRepository import be.hogent.faith.service.usecases.event.MakeEventFilesAvailableUseCase import be.hogent.faith.util.factory.EventFactory import io.mockk.every import io.mockk.mockk import io.mockk.verify import io.reactivex.rxjava3.core.Completable import io.reactivex.rxjava3.core.Scheduler import io.reactivex.rxjava3.schedulers.Schedulers import org.junit.Before import org.junit.Test import java.io.IOException class MakeEventFilesAvailableUseCaseTest { private lateinit var makeEventFilesAvailableUseCase: MakeEventFilesAvailableUseCase private val observer: Scheduler = mockk() private val fileStorageRepository: IFileStorageRepository = mockk(relaxed = true) private val eventRepository: IEventRepository = mockk(relaxed = true) private val evenEncryptionService: IEventEncryptionService = mockk(relaxed = true) private lateinit var event: Event @Before fun setUp() { makeEventFilesAvailableUseCase = MakeEventFilesAvailableUseCase( fileStorageRepository, eventRepository, evenEncryptionService, observer, Schedulers.trampoline() ) event = EventFactory.makeEvent(numberOfDetails = 0) } @Test fun getEventFilesUC_execute_getFiles() { every { fileStorageRepository.downloadEventFiles(any()) } returns Completable.complete() makeEventFilesAvailableUseCase.buildUseCaseSingle( MakeEventFilesAvailableUseCase.Params(event) ) .test() .assertNoErrors() // The image should be stored in the repo verify { fileStorageRepository.downloadEventFiles(event) } } @Test fun getEventFilesUC_execute_failsOnStorageError() { every { fileStorageRepository.downloadEventFiles(any()) } returns Completable.error( IOException() ) makeEventFilesAvailableUseCase.buildUseCaseSingle( MakeEventFilesAvailableUseCase.Params(event) ) .test() .assertError(IOException::class.java) } }
0
Kotlin
0
0
14c6aec4b3c0a42bc73a7f779964d166fffeea20
2,355
FAITHAndroid
The Unlicense
kotgres-core/src/main/kotlin/kotgres/annotations/Save.kt
mfarsikov
308,982,204
false
null
package kotgres.annotations @Target(AnnotationTarget.FUNCTION) annotation class Save
1
Kotlin
0
23
a648d4806a44598f1660c785aad6f53154f922fa
86
kotgres
Apache License 2.0
samples/simple-routing/src/main/java/com/badoo/ribs/samples/simplerouting/simple_routing_parent/builder/SimpleRoutingParentBuilder.kt
simona-anomis
335,746,355
true
{"Kotlin": 1186530}
package com.badoo.ribs.samples.simplerouting.simple_routing_parent.builder import com.badoo.ribs.builder.SimpleBuilder import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.samples.simplerouting.simple_routing_parent.SimpleRoutingParent import com.badoo.ribs.samples.simplerouting.simple_routing_parent.SimpleRoutingParentNode import com.badoo.ribs.samples.simplerouting.simple_routing_parent.SimpleRoutingParentViewImpl import com.badoo.ribs.samples.simplerouting.simple_routing_parent.routing.SimpleRoutingParentChildBuilders import com.badoo.ribs.samples.simplerouting.simple_routing_parent.routing.SimpleRoutingParentRouter class SimpleRoutingParentBuilder( private val dependency: SimpleRoutingParent.Dependency ) : SimpleBuilder<SimpleRoutingParent>() { override fun build(buildParams: BuildParams<Nothing?>): SimpleRoutingParent { val router = SimpleRoutingParentRouter( buildParams = buildParams, builders = SimpleRoutingParentChildBuilders(dependency) ) return SimpleRoutingParentNode( viewFactory = SimpleRoutingParentViewImpl.Factory().invoke(deps = null), plugins = listOf(router) ) } }
0
null
0
0
a9d5cc6dbb9e2bf8cf9240d0e835dc43aefc5cde
1,210
RIBs
Apache License 2.0
app/src/main/java/jp/kaleidot725/easycalc/compose/app/ComposeAppAction.kt
kaleidot725
727,725,457
false
{"Kotlin": 331996, "Ruby": 106}
package jp.kaleidot725.easycalc.compose.app interface ComposeAppAction
2
Kotlin
0
0
d507dd11a73cd67b1b253db0156d3f00cdcf994a
72
EasyCalc
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/deliusapi/repository/CourtReportRepository.kt
ministryofjustice
334,932,480
false
null
package uk.gov.justice.digital.hmpps.deliusapi.repository import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository import uk.gov.justice.digital.hmpps.deliusapi.entity.CourtReport @Repository interface CourtReportRepository : JpaRepository<CourtReport, Long>
2
Kotlin
1
4
371eb9040373cbc4dfefefb09ecefab47466298b
314
hmpps-delius-api
MIT License
src/main/kotlin/com/helltar/twitchviewerbot/dao/DatabaseFactory.kt
Helltar
580,061,642
false
{"Kotlin": 47287}
package com.helltar.twitchviewerbot.dao import com.helltar.twitchviewerbot.EnvConfig.databaseName import com.helltar.twitchviewerbot.EnvConfig.databasePassword import com.helltar.twitchviewerbot.EnvConfig.databaseUser import com.helltar.twitchviewerbot.EnvConfig.postgresqlHost import com.helltar.twitchviewerbot.EnvConfig.postgresqlPort import com.helltar.twitchviewerbot.dao.tables.UserChannelsTable import com.helltar.twitchviewerbot.dao.tables.UsersTable import kotlinx.coroutines.Dispatchers import org.jetbrains.exposed.sql.Database import org.jetbrains.exposed.sql.SchemaUtils import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction import org.jetbrains.exposed.sql.transactions.transaction object DatabaseFactory { val usersDAO = UsersDAO() val userChannelsDAO = UserChannelsDAO() fun init() { val driverClassName = "org.postgresql.Driver" val jdbcURL = "jdbc:postgresql://$postgresqlHost:$postgresqlPort/$databaseName" val database = Database.connect(jdbcURL, driverClassName, databaseUser, databasePassword) transaction(database) { SchemaUtils.create(UsersTable, UserChannelsTable) } } suspend fun <T> dbQuery(block: suspend () -> T): T = newSuspendedTransaction(Dispatchers.IO) { block() } }
0
Kotlin
0
5
f570adaf1ca8b5836735649b86aaad00e62204d9
1,315
twitchviewer_bot
MIT License
plugins/com.flinty.docsflow.web.core/source/com/flinty/docsflow/web/core/order/ShowOrderDifferenceEditorObjectButtonHandler.kt
flint80
413,383,841
false
{"Kotlin": 291036, "HTML": 8515, "CSS": 317}
/***************************************************************** * Gridnine AB http://www.gridnine.com * Project: coralina-docs-flow *****************************************************************/ package com.flinty.docsflow.web.core.order import com.flinty.docsflow.common.core.model.rest.CalculateOrderDifferenceRequestJS import com.flinty.docsflow.common.core.model.ui.OrderEditor import com.flinty.docsflow.common.core.model.ui.ShowOrderDifferenceDialog import com.flinty.docsflow.common.core.model.ui.SpecificationEditor import com.flinty.docsflow.web.core.DocsflowRestClient import com.gridnine.jasmine.web.core.ui.WebUiLibraryAdapter import com.gridnine.jasmine.web.standard.editor.ObjectEditor import com.gridnine.jasmine.web.standard.editor.ObjectEditorTool import com.gridnine.jasmine.web.standard.utils.StandardUiUtils class ShowOrderDifferenceEditorObjectButtonHandler: ObjectEditorTool<OrderEditor> { override suspend fun invoke(editor: ObjectEditor<OrderEditor>) { val result = DocsflowRestClient.docsflow_order_calculateDifference(CalculateOrderDifferenceRequestJS().also { it.orderUid = editor.objectUid }) if(result.vm.positions.isEmpty()){ StandardUiUtils.showMessage("Различий не найдено") return } val dialog = ShowOrderDifferenceDialog() dialog.positionsWidget.readData(result.vm.positions, null) WebUiLibraryAdapter.get().showDialog(dialog){ title = "Различия" cancelButton() } } }
0
Kotlin
0
0
d64d64bd2f539a6579ee80dc2c89b22b4c644ddc
1,549
coralina-docs-flow
MIT License
shared/src/commonMain/kotlin/presentation/widgets/PostLists.kt
prashant17d97
754,377,560
false
{"Kotlin": 326072, "Ruby": 2184, "Swift": 657, "Shell": 228}
package presentation.widgets import androidx.compose.animation.AnimatedContent import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.SizeTransform import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.slideInHorizontally import androidx.compose.animation.slideInVertically import androidx.compose.animation.slideOutHorizontally import androidx.compose.animation.slideOutVertically import androidx.compose.animation.togetherWith import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.unit.dp import clickevents.ClickEvent import clickevents.DataStoreEvent import core.ResourcePath import datamodel.model.PostModel import navigation.Screens import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.painterResource import presentation.CommonElements.cornerShape import presentation.CommonElements.elevationValue import presentation.CommonElements.globalClip import presentation.widgets.shared.LoadImage /** * Composable function for displaying a list of posts in a LazyColumn with customizable post cards. * * @param modifier The modifier to apply to the LazyColumn. * @param postCardModifier The modifier to apply to each individual post card. * @param posts The list of posts to display. * @param onClick The callback invoked when a post is clicked. * * @author <NAME> */ @OptIn(ExperimentalFoundationApi::class) @Composable fun PostLists( modifier: Modifier = Modifier, postCardModifier: Modifier = Modifier, posts: List<PostModel>, onClick: (ClickEvent) -> Unit, ) { LazyColumn( modifier = modifier, verticalArrangement = Arrangement.spacedBy( space = 10.dp, alignment = Alignment.CenterVertically, ), horizontalAlignment = Alignment.Start, ) { items(items = posts, key = { it._id }) { postModel -> Post( modifier = postCardModifier.animateItemPlacement(), post = postModel, onClick = onClick, ) } } } /** * Composable function for displaying a single post with optional disappearing animation. * * @param modifier The modifier to apply to the post. * @param post The post to display. * @param onClick The callback invoked when the post is clicked. */ @Composable fun DisappearingListPost( modifier: Modifier = Modifier, post: PostModel, onClick: (ClickEvent) -> Unit, ) { // AnimatedVisibility composable is used for entering and exiting animations AnimatedVisibility( visible = true, enter = slideInHorizontally( initialOffsetX = { it }, animationSpec = tween(durationMillis = 500, easing = LinearEasing), ), exit = slideOutHorizontally( targetOffsetX = { -it }, animationSpec = tween(durationMillis = 500, easing = LinearEasing), ), ) { Post( modifier = modifier, post = post, onClick = onClick, ) } } /** * Composable function for displaying a single post card. * * @param modifier The modifier to apply to the post card. * @param post The post to display. * @param onClick The callback invoked when the post card is clicked. * * @author <NAME> */ @OptIn(ExperimentalResourceApi::class) @Composable fun Post( modifier: Modifier = Modifier, post: PostModel, onClick: (ClickEvent) -> Unit, ) { var isSelected by remember { mutableStateOf(post.isSelected) } // Determine the bookmark icon based on the selected state val bookmarkIcon by rememberUpdatedState( if (isSelected) { ResourcePath.Drawable.BookmarkIcon } else { ResourcePath.Drawable.BookmarkBorderIcon }, ) // Post card with clickable functionality Card( shape = cornerShape, elevation = CardDefaults.cardElevation(elevationValue), modifier = modifier .fillMaxWidth() .clickable { onClick( ClickEvent.NavigateScreen( argument = post._id, screen = Screens.PostScreen, ), ) } .globalClip, ) { Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.spacedBy( space = 0.dp, alignment = Alignment.Start, ), ) { // Load post thumbnail image LoadImage( modifier = Modifier.size(120.dp), srcUrl = post.thumbnail, placeHolder = ResourcePath.Drawable.iconGallery, background = MaterialTheme.colorScheme.surfaceVariant, ) Column( modifier = Modifier.padding(10.dp), verticalArrangement = Arrangement.spacedBy( space = 5.dp, alignment = Alignment.CenterVertically, ), horizontalAlignment = Alignment.Start, ) { // Post creation date Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween, ) { Text( text = post.createdAtDate, style = MaterialTheme.typography.labelSmall.copy( fontWeight = FontWeight.ExtraLight, ), textDecoration = TextDecoration.Underline, ) // Bookmark icon with animation AnimatedContent( targetState = bookmarkIcon, transitionSpec = { if (targetState > initialState) { (slideInVertically { height -> height } + fadeIn()).togetherWith( slideOutVertically { height -> -height } + fadeOut(), ) } else { (slideInVertically { height -> -height } + fadeIn()).togetherWith( slideOutVertically { height -> height } + fadeOut(), ) }.using( SizeTransform(clip = true), ) }, label = "AnimatedContent", ) { Image( painter = painterResource(bookmarkIcon), contentDescription = "Bookmark", modifier = Modifier.size(24.dp).clickable { val (clickEvent, selected) = if (isSelected) { ClickEvent.SaveOrRemovePost( data = post, DataStoreEvent.REMOVE, ) to false } else { ClickEvent.SaveOrRemovePost( data = post, DataStoreEvent.SAVE, ) to true } onClick(clickEvent) isSelected = selected }, colorFilter = ColorFilter.tint(MaterialTheme.colorScheme.primary), ) } } // Post title and subtitle Text(text = post.title, style = MaterialTheme.typography.bodyMedium) Text( text = post.subtitle, maxLines = 1, style = MaterialTheme.typography.bodySmall, ) // Author and category view AuthorCatView(postModel = post, onClick = onClick) } } } }
1
Kotlin
0
0
d219d35d81823a049999285f57b5a8d6b1aff1bf
9,735
debug-desk
Apache License 2.0
src/main/kotlin/io/art/gradle/common/configurator/ExecutableConfigurator.kt
art-community
200,132,555
false
null
/* * ART * * Copyright 2019-2022 ART * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.art.gradle.common.configurator import io.art.gradle.common.configuration.ExecutableConfiguration import io.art.gradle.common.constants.* import org.gradle.api.Project fun Project.configureExecutable(executableConfiguration: ExecutableConfiguration) { if (executableConfiguration.jarEnabled || executableConfiguration.nativeEnabled) { val creation = JarExecutableCreationConfiguration( configuration = executableConfiguration.jar, runTask = RUN_JAR_EXECUTABLE_TASK, buildTask = BUILD_JAR_EXECUTABLE_TASK, dependencyConfiguration = EMBEDDED_CONFIGURATION_NAME, mainClass = executableConfiguration.mainClass, directory = executableConfiguration.directory, executable = executableConfiguration.executableName ) configureJar(creation) } if (executableConfiguration.nativeEnabled) { val creation = NativeExecutableCreationConfiguration( configuration = executableConfiguration.native, runTask = RUN_NATIVE_EXECUTABLE_TASK, buildTask = BUILD_NATIVE_EXECUTABLE_TASK, buildJarTask = BUILD_JAR_EXECUTABLE_TASK, runAgentTask = RUN_NATIVE_AGENT, mainClass = executableConfiguration.mainClass, executable = executableConfiguration.executableName, directory = executableConfiguration.directory ) configureNative(creation) } } fun Project.addEmbeddedConfiguration() { configurations.create(EMBEDDED_CONFIGURATION_NAME) } fun Project.configureEmbeddedConfiguration() { val embedded = configurations.getByName(EMBEDDED_CONFIGURATION_NAME) val implementation = configurations.findByName(IMPLEMENTATION_CONFIGURATION_NAME) implementation?.extendsFrom(embedded) }
0
Kotlin
1
3
2c6fa18ff4e7b8857a540d042448b2bb425dea2c
2,482
art-gradle
Apache License 2.0
app/src/main/java/com/cevlikalprn/youneedtodo/domain/useCase/SearchDatabaseUseCase.kt
cevlikalprn
633,055,594
false
{"Kotlin": 115649}
package com.cevlikalprn.youneedtodo.domain.useCase import com.cevlikalprn.youneedtodo.domain.mapper.TaskListMapper import com.cevlikalprn.youneedtodo.presentation.model.ToDoTask import com.cevlikalprn.youneedtodo.data.repository.ToDoRepository import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import javax.inject.Inject class SearchDatabaseUseCase @Inject constructor( private val toDoRepository: ToDoRepository, private val taskListMapper: TaskListMapper ) { operator fun invoke(query: String): Flow<List<ToDoTask>> { return toDoRepository .searchDatabase(query) .map { toDoTaskEntityList -> taskListMapper(toDoTaskEntityList) } } }
0
Kotlin
0
0
be41ed5c8b4197003b66f597748e441f3c53f66c
734
Compose-ToDoTasks
Apache License 2.0
app/src/main/java/br/com/alura/orgs/dao/ProdutoDAO.kt
JoaoLucasKnight
771,632,464
false
{"Kotlin": 6354}
package br.com.alura.orgs.dao import br.com.alura.orgs.model.Produto class ProdutoDAO { fun adicionar (produto: Produto){ produtos.add(produto) } fun listar(): List<Produto>{ return produtos.toList() } companion object { private val produtos = mutableListOf<Produto>() } }
0
Kotlin
0
0
4574567cbabd33a06c247a4389f36f048e959314
325
Android_Fundament
MIT License
app/src/main/java/com/dekram/trumpetabc/MainActivity.kt
vlmrkv
609,334,742
false
{"Kotlin": 10936}
package com.dekram.trumpetabc import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.TextView class MainActivity : AppCompatActivity() { private lateinit var fingerings: TextView private lateinit var tones: TextView private lateinit var notesCards: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) fingerings = findViewById(R.id.toFingerings) tones = findViewById(R.id.toTones) notesCards = findViewById(R.id.toNotesCards) fingerings.setOnClickListener { val intent = Intent(this, FingeringsActivity::class.java) startActivity(intent) } tones.setOnClickListener { val intent = Intent(this, TonesActivity::class.java) startActivity(intent) } notesCards.setOnClickListener { val intent = Intent(this, NotesCardActivity::class.java) startActivity(intent) } } }
0
Kotlin
0
0
1586867f338f0926d0752e9e4c3bb7f5b673216e
1,101
TrumpetABC
MIT License
plugins/grazie/src/main/kotlin/com/intellij/grazie/jlanguage/LangTool.kt
hieuprogrammer
284,920,751
false
null
// Copyright 2000-2019 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 com.intellij.grazie.jlanguage import com.intellij.grazie.GrazieConfig import com.intellij.grazie.ide.msg.GrazieStateLifecycle import com.intellij.grazie.jlanguage.broker.GrazieDynamicClassBroker import com.intellij.grazie.jlanguage.broker.GrazieDynamicDataBroker import org.languagetool.JLanguageTool import org.languagetool.rules.UppercaseMatchFilter import java.util.concurrent.ConcurrentHashMap object LangTool : GrazieStateLifecycle { private val langs: MutableMap<Lang, JLanguageTool> = ConcurrentHashMap() private val rulesToLanguages = HashMap<String, MutableSet<Lang>>() init { JLanguageTool.dataBroker = GrazieDynamicDataBroker JLanguageTool.classBroker = GrazieDynamicClassBroker } val allRules: Set<String> get() = rulesToLanguages.keys fun getTool(lang: Lang, state: GrazieConfig.State = GrazieConfig.get()): JLanguageTool { require(lang.jLanguage != null) { "Trying to get LangTool for not available language" } return langs.computeIfAbsent(lang) { JLanguageTool(lang.jLanguage!!, state.nativeLanguage.jLanguage).apply { addMatchFilter(UppercaseMatchFilter()) state.userDisabledRules.forEach { id -> disableRule(id) } state.userEnabledRules.forEach { id -> enableRule(id) } allRules.distinctBy { it.id }.onEach { rule -> rulesToLanguages.getOrPut(rule.id, ::HashSet).add(lang) } } } } override fun init(state: GrazieConfig.State) { // Creating LanguageTool for each language state.availableLanguages.forEach { getTool(it, state) } } override fun update(prevState: GrazieConfig.State, newState: GrazieConfig.State) { if ( prevState.availableLanguages == newState.availableLanguages && prevState.nativeLanguage == newState.nativeLanguage && prevState.userDisabledRules == newState.userDisabledRules && prevState.userEnabledRules == newState.userEnabledRules ) return langs.clear() rulesToLanguages.clear() init(newState) } fun getRuleLanguages(ruleId: String) = rulesToLanguages[ruleId] }
1
null
2
2
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
2,224
intellij-community
Apache License 2.0
xhd/src/main/java/com/architecture/light/utils/Test.kt
LingChenJie
519,031,973
false
null
package com.architecture.light.utils import com.architecture.light.helper.FeeHelper /** * Created by SuQi on 2022/8/3. * Describe: */ fun main(args: Array<String>) { // println(AmountHelper.convertAmount("1,010,000.18")) // val stringCent2Long = AmountHelper.formatAmount(AmountHelper.convertAmount("0.18")) // println(stringCent2Long) // val yuan2Fen12 = AmountHelper.yuan2Fen12(-1.100001) // println(yuan2Fen12) // val result = DoubleUtils.halfUpTwoDecimalPlaces(10.004555) // println(result) // val result = DoubleUtils.multiply(3723.0, 0.0045) // println(result) var calcFee = FeeHelper.calcFee("支付宝", 0.0) println(calcFee) calcFee = FeeHelper.calcFee("银行卡贷记卡", 0.000000) println(calcFee) calcFee = FeeHelper.calcFee("银行卡借记卡", 2290.220000) println(calcFee) }
0
Kotlin
0
0
fa0a0e3eafe01fbe6342c93d350903bd3560e9f9
819
LightArchitecture
Apache License 2.0
src/main/kotlin/no/nav/helse/flex/client/DokArkivClient.kt
navikt
451,810,928
false
{"Kotlin": 246162, "Dockerfile": 267}
package no.nav.helse.flex.client import com.fasterxml.jackson.module.kotlin.readValue import no.nav.helse.flex.domain.JournalpostRequest import no.nav.helse.flex.domain.JournalpostResponse import no.nav.helse.flex.domain.LogiskVedleggRequest import no.nav.helse.flex.domain.LogiskVedleggResponse import no.nav.helse.flex.objectMapper import org.springframework.beans.factory.annotation.Value import org.springframework.http.HttpEntity import org.springframework.http.HttpHeaders import org.springframework.http.HttpMethod import org.springframework.http.MediaType import org.springframework.retry.annotation.Backoff import org.springframework.retry.annotation.Retryable import org.springframework.stereotype.Component import org.springframework.web.client.HttpClientErrorException import org.springframework.web.client.RestTemplate @Component class DokArkivClient( @Value("\${DOKARKIV_URL}") private val dokarkivUrl: String, private val dokArkivRestTemplate: RestTemplate ) { @Retryable(backoff = Backoff(delay = 5000)) fun opprettJournalpost(pdfRequest: JournalpostRequest, id: String): JournalpostResponse { try { val url = "$dokarkivUrl/rest/journalpostapi/v1/journalpost?forsoekFerdigstill=true" val headers = HttpHeaders() headers.contentType = MediaType.APPLICATION_JSON headers["Nav-Callid"] = id val entity = HttpEntity(pdfRequest, headers) val result = dokArkivRestTemplate.exchange(url, HttpMethod.POST, entity, JournalpostResponse::class.java) if (!result.statusCode.is2xxSuccessful) { throw RuntimeException("dokarkiv feiler med HTTP-${result.statusCode} for søknad med id: $id") } return result.body ?: throw RuntimeException("dokarkiv returnerer ikke data for søknad med id: $id") } catch (e: HttpClientErrorException.Conflict) { return objectMapper.readValue(e.responseBodyAsString) } } @Retryable(backoff = Backoff(delay = 5000)) fun opprettLogiskVedlegg(logiskVedleggRequest: LogiskVedleggRequest, dokumentId: String): LogiskVedleggResponse { try { val url = "$dokarkivUrl/rest/journalpostapi/v1/dokumentInfo/$dokumentId/logiskVedlegg/" val headers = HttpHeaders() headers.contentType = MediaType.APPLICATION_JSON headers["Nav-Callid"] = dokumentId val entity = HttpEntity(logiskVedleggRequest, headers) val result = dokArkivRestTemplate.exchange(url, HttpMethod.POST, entity, LogiskVedleggResponse::class.java) if (!result.statusCode.is2xxSuccessful) { throw RuntimeException("dokarkiv feiler med HTTP-${result.statusCode} for søknad med id: $dokumentId") } return result.body ?: throw RuntimeException("dokarkiv returnerer ikke data for søknad med id: $dokumentId") } catch (e: HttpClientErrorException.Conflict) { return objectMapper.readValue(e.responseBodyAsString) } } }
4
Kotlin
0
0
897e0cb85b9c773c487d9c033ab8dbbb116b53a7
3,096
sykepengesoknad-arkivering-oppgave
MIT License
data/sqldelight/src/nonAndroidMain/kotlin/com/taetae98/codelab/data/sqldelight/SqldelightModule.kt
taetae98coding
708,459,882
false
{"Kotlin": 88745, "Swift": 1267, "HTML": 233, "Ruby": 109}
package com.taetae98.codelab.data.sqldelight import org.koin.core.annotation.Module import org.koin.core.annotation.Singleton @Module internal expect class SqldelightModule { @Singleton fun providesMemoDatabase(): MemoDatabase }
0
Kotlin
0
0
3877e6171172a1a6273461232e0252f1c4605ec8
239
CodeLab
Apache License 2.0
app/src/main/java/ilkadam/ilkmuhabbet/presentation/commoncomponents/LogOutCustomText.kt
ademkocamaz
803,881,747
false
{"Kotlin": 254039}
package ilkadam.ilkmuhabbet.presentation.commoncomponents import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.sp @Composable fun LogOutCustomText( entry: String = "Log Out", fontSize: TextUnit = 10.sp, onClick: () -> Unit = {} ) { Button( modifier = Modifier .fillMaxWidth(), onClick = { onClick() }, colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error) ) { Text( text = "Log Out", style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onError ) } // Box( // modifier = Modifier // .clip(RoundedCornerShape(percent = 50)) // .background( // MaterialTheme.colorScheme.surface // ) // .height(26.dp) // .fillMaxWidth() // .clickable { // onClick() // }) { // Text( // modifier = Modifier.align(Alignment.Center), // text = entry, // fontSize = fontSize, // color = Color.Red // ) // } }
0
Kotlin
0
0
a1024979aa2e679083c3216abd0fd3e60f3850b4
1,469
ilkMuhabbet
MIT License
BraintreeCore/src/main/java/com/braintreepayments/api/core/DeviceInspector.kt
braintree
21,631,528
false
null
package com.braintreepayments.api import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.os.Build import androidx.annotation.RestrictTo import androidx.annotation.VisibleForTesting /** * @suppress */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) class DeviceInspector @VisibleForTesting internal constructor( private val appHelper: AppHelper, private val signatureVerifier: SignatureVerifier, ) { constructor() : this( AppHelper(), SignatureVerifier(), ) internal fun getDeviceMetadata( context: Context?, configuration: Configuration?, sessionId: String?, integration: String? ): DeviceMetadata { return DeviceMetadata( appId = context?.packageName, appName = getAppName(context), clientSDKVersion = BuildConfig.VERSION_NAME, clientOs = getAPIVersion(), component = "braintreeclientsdk", deviceManufacturer = Build.MANUFACTURER, deviceModel = Build.MODEL, dropInSDKVersion = dropInVersion, environment = configuration?.environment, eventSource = "mobile-native", integrationType = integration, isSimulator = isDeviceEmulator, merchantAppVersion = getAppVersion(context), merchantId = configuration?.merchantId, platform = "Android", sessionId = sessionId ) } /** * @param context A context to access the installed packages. * @return boolean depending on if the Venmo app is installed, and has a valid signature. */ fun isVenmoAppSwitchAvailable(context: Context?): Boolean { val isVenmoIntentAvailable = appHelper.isIntentAvailable(context, venmoIntent) val isVenmoSignatureValid = signatureVerifier.isSignatureValid( context, VENMO_APP_PACKAGE, VENMO_BASE_64_ENCODED_SIGNATURE ) return isVenmoIntentAvailable && isVenmoSignatureValid } fun isPayPalInstalled(context: Context?): Boolean { return appHelper.isAppInstalled(context, PAYPAL_APP_PACKAGE) } fun isVenmoInstalled(context: Context?): Boolean { return appHelper.isAppInstalled(context, VENMO_APP_PACKAGE) } private val isDeviceEmulator: Boolean get() = "google_sdk".equals(Build.PRODUCT, ignoreCase = true) || "sdk".equals(Build.PRODUCT, ignoreCase = true) || "Genymotion".equals(Build.MANUFACTURER, ignoreCase = true) || Build.FINGERPRINT.contains("generic") private fun getAppName(context: Context?): String = getApplicationInfo(context)?.let { appInfo -> context?.packageManager?.getApplicationLabel(appInfo).toString() } ?: "ApplicationNameUnknown" @Suppress("SwallowedException") private fun getApplicationInfo(context: Context?) = try { context?.packageManager?.getApplicationInfo(context.packageName, 0) } catch (e: PackageManager.NameNotFoundException) { null } private fun getAppVersion(context: Context?): String = getPackageInfo(context) ?: "VersionUnknown" private fun getPackageInfo(context: Context?) = context?.let { try { val packageInfo = it.packageManager.getPackageInfo(it.packageName, 0) packageInfo?.versionName } catch (ignored: PackageManager.NameNotFoundException) { null } } private fun getAPIVersion(): String { val sdkInt = Build.VERSION.SDK_INT return "Android API $sdkInt" } /** * Gets the current Drop-in version or null. * * @return string representation of the current Drop-in version, or null if * Drop-in is unavailable */ private val dropInVersion get() = getDropInVersion() companion object { private const val PAYPAL_APP_PACKAGE = "com.paypal.android.p2pmobile" private const val VENMO_APP_PACKAGE = "com.venmo" private const val VENMO_APP_SWITCH_ACTIVITY = "controller.SetupMerchantActivity" @VisibleForTesting const val VENMO_BASE_64_ENCODED_SIGNATURE = "x34mMawEUcCG8l95riWCOK+kAJYejVmdt44l6tzcyUc=\n" private val venmoIntent: Intent get() = Intent().setComponent( ComponentName( VENMO_APP_PACKAGE, "$VENMO_APP_PACKAGE.$VENMO_APP_SWITCH_ACTIVITY" ) ) internal fun getDropInVersion(): String? { try { val dropInBuildConfigClass = Class.forName("com.braintreepayments.api.dropin.BuildConfig") val versionNameField = dropInBuildConfigClass.getField("VERSION_NAME") versionNameField.isAccessible = true return versionNameField[String::class] as String? } catch (ignored: ClassNotFoundException) { } catch (ignored: NoSuchFieldException) { } catch (ignored: IllegalAccessException) { } return null } } }
24
null
233
409
92dabb74f14e6203259511f6b6a51367e3247fc5
5,202
braintree_android
MIT License
src/main/kotlin/me/itstake/neisinfo/NeisParser.kt
EATSTEAK
182,555,496
false
{"HTML": 163795, "Kotlin": 31970}
package me.itstake.neisinfo import java.io.StringWriter import java.util.HashMap import kotlin.collections.ArrayList import kotlin.collections.set class NeisParser { companion object { //FOR SCHOOL INFO fun parseSchoolInfo(data: String): Info { val convertKey = hashMapOf("학교명" to "name", "우편번호" to "zipCode", "주소" to "address", "전화번호" to "callNum", "팩스번호" to "faxNum", "홈페이지주소" to "homepage", "학생수" to "stuNum", "남" to "stuNumMen", "여" to "stuNumWomen", "학년별 학급수" to "classNumByGrade", "교원정보" to "teacherNum") val table1starts = data.indexOf("<table cellspacing=\"0\" summary=\"이 표는") val table1ends = data.indexOf("</table>") + 8 val table2starts = data.indexOf("<table cellspacing=\"0\" summary=\"이 표는", table1ends) val table2ends = data.indexOf("</table>", table1ends) val table1 = infoTableToMap(data.substring(table1starts, table1ends)) as HashMap table1.putAll(infoTableToMap(data.substring(table2starts, table2ends))) val ret = HashMap<String, Any>() table1.forEach { t, u -> val ck = convertKey[t] if (convertKey.containsKey(t) && ck != null) ret.put(ck, convertInfoValue(t, u)) } return Info.fromMap(ret) } private fun convertInfoValue(t:String, u: String): Any { return when(t) { "우편번호" -> u.toLong() "학생수", "남", "여" -> u.replace("명", "").trim().toLong() "학년별 학급수" -> { val array = ArrayList<Int>() u.split(",").forEach { v -> array.add(v.split("(")[1].replace("학급)", "").toInt()) } array } "홈페이지주소" -> { u.substringAfter("이동\">").substringBefore("</a>").trim() } "교원정보" -> u.replace(" 명 재직(파견인력 포함)", "").trim().toLong() else -> u } } private fun infoTableToMap(table: String): Map<String, String> { var lastSearchedIndex = 0 var searchedIndex:Int val ret = HashMap<String, String>() while(lastSearchedIndex > -1) { val thIndex = table.indexOf("<th", lastSearchedIndex) if(thIndex <= -1) break val thEnd = table.indexOf(">", thIndex) + 1 val tdIndex = table.indexOf("<td", lastSearchedIndex) val tdEnd = table.indexOf(">", tdIndex) + 1 searchedIndex = table.indexOf(">", tdIndex) lastSearchedIndex = if(searchedIndex > -1) searchedIndex + 1 else searchedIndex ret[table.substring(thEnd, table.indexOf("</th>", thIndex)).trim()] = table.substring(tdEnd, table.indexOf("</td>", tdIndex)).trim() } return ret } //FOR SCHOOL MEALS fun parseSchoolMeals(data: String): Map<Int, Meal> { val table = data.substring(data.indexOf("<table cellspacing=\"0\" summary=\"이 표는"), data.indexOf("</table>") + 8) var lastSearchedIndex = 0 var searchedIndex:Int val ret = HashMap<Int, Meal>() while(lastSearchedIndex > -1) { val tdIndex = table.indexOf("<td", lastSearchedIndex) if(tdIndex <= -1) break val tdEnd = table.indexOf(">", tdIndex) + 1 searchedIndex = table.indexOf("</td>", tdIndex) lastSearchedIndex = if(searchedIndex > -1) searchedIndex + 1 else searchedIndex val td = table.substring(tdEnd, searchedIndex).replace("<div>", "").replace("</div>", "").trim() .split("<br />") if(td.size > 1) { val day = td[0].toInt() val breakfastIndex = td.indexOf("[조식]") val lunchIndex = td.indexOf("[중식]") val dinnerIndex = td.indexOf("[석식]") ret[day] = Meal( if (breakfastIndex > -1) toMealArray( td.subList( breakfastIndex + 1, if (lunchIndex > -1) lunchIndex else td.size ) ) else null, if (lunchIndex > -1) toMealArray( td.subList( lunchIndex + 1, if (dinnerIndex > -1) dinnerIndex else td.size ) ) else null, if (dinnerIndex > -1) toMealArray(td.subList(dinnerIndex + 1, td.size)) else null ) } } return ret } private fun toMealArray(menus: List<String>): List<MealMenu> { val ret = ArrayList<MealMenu>() menus.forEach { t -> val allergies = ArrayList<MealMenu.AllergyInfo>() var name = t for (i in 18 downTo 1) { val index = t.indexOf("$i.") if (index > -1) allergies.add(MealMenu.AllergyInfo.getByKey(i)); name = StringUtils.unescapeHtml3(name).replace("$i.", "") } ret.add(MealMenu(name.trim(), allergies)) } return ret } //FOR SCHOOL SCHEDULE fun parseSchoolSchedule(data: String, deep: Boolean, school: School?): Map<Int, Event> { val table = data.substring(data.indexOf("<table cellspacing=\"0\" summary=\"월간학사"), data.indexOf("</table>") + 8) var lastSearchedIndex = 0 var searchedIndex: Int val ret = HashMap<Int, Event>() while (lastSearchedIndex > -1) { val tdIndex = table.indexOf("<td", lastSearchedIndex) if (tdIndex <= -1) break val tdEnd = table.indexOf(">", tdIndex) + 1 searchedIndex = table.indexOf("</td>", tdIndex) lastSearchedIndex = if (searchedIndex > -1) searchedIndex + 1 else searchedIndex val td = table.substring(tdEnd, searchedIndex).replace("<div>", "").replace("</div>", "").trim() val emIndex = td.indexOf("<em") if (emIndex > -1) { val strongIndex = td.indexOf("<strong", emIndex) if (strongIndex > -1) { val emEnd = td.indexOf(">", emIndex) + 1 val strongEnd = td.indexOf(">", strongIndex) + 1 val eventCodeEnd = td.indexOf("eventCode=", emIndex) + 10 val eventDateEnd = td.indexOf("eventDate=", emIndex) + 10 val event = Event( name = td.substring(strongEnd, td.indexOf("</strong>")), code = td.substring(eventCodeEnd, eventCodeEnd + 4), date = td.substring(eventDateEnd, eventDateEnd + 8) ) if (deep && school != null) event.updateEventInfo(school) ret[td.substring(emEnd, td.indexOf("</em>")).toInt()] = event } } } return ret } fun parseEventInfo(data: String): EventInfo { val tdStart = data.indexOf("<td class=\"textL\">", data.indexOf("해당학년</th>")) val grades = ArrayList<Int>() data.substring(tdStart + 18, data.indexOf("</td>", tdStart)).split("\n").forEach { t -> if (t.contains("학년")) grades.add(t.replace("학년", "").trim().toInt()) } val textareaStart = data.indexOf("readonly\">") + 10 val textarea = data.substring(textareaStart, data.indexOf("</textarea>") + 11) return EventInfo(targetGrades = grades, details = textarea) } object StringUtils { private val ESCAPES = arrayOf( arrayOf("\"", "quot"), // " - double-quote arrayOf("&", "amp"), // & - ampersand arrayOf("<", "lt"), // < - less-than arrayOf(">", "gt"), // > - greater-than // Mapping to escape ISO-8859-1 characters to their named HTML 3.x equivalents. arrayOf("\u00A0", "nbsp"), // non-breaking space arrayOf("\u00A1", "iexcl"), // inverted exclamation mark arrayOf("\u00A2", "cent"), // cent sign arrayOf("\u00A3", "pound"), // pound sign arrayOf("\u00A4", "curren"), // currency sign arrayOf("\u00A5", "yen"), // yen sign = yuan sign arrayOf("\u00A6", "brvbar"), // broken bar = broken vertical bar arrayOf("\u00A7", "sect"), // section sign arrayOf("\u00A8", "uml"), // diaeresis = spacing diaeresis arrayOf("\u00A9", "copy"), // © - copyright sign arrayOf("\u00AA", "ordf"), // feminine ordinal indicator arrayOf("\u00AB", "laquo"), // left-pointing double angle quotation mark = left pointing guillemet arrayOf("\u00AC", "not"), // not sign arrayOf("\u00AD", "shy"), // soft hyphen = discretionary hyphen arrayOf("\u00AE", "reg"), // ® - registered trademark sign arrayOf("\u00AF", "macr"), // macron = spacing macron = overline = APL overbar arrayOf("\u00B0", "deg"), // degree sign arrayOf("\u00B1", "plusmn"), // plus-minus sign = plus-or-minus sign arrayOf("\u00B2", "sup2"), // superscript two = superscript digit two = squared arrayOf("\u00B3", "sup3"), // superscript three = superscript digit three = cubed arrayOf("\u00B4", "acute"), // acute accent = spacing acute arrayOf("\u00B5", "micro"), // micro sign arrayOf("\u00B6", "para"), // pilcrow sign = paragraph sign arrayOf("\u00B7", "middot"), // middle dot = Georgian comma = Greek middle dot arrayOf("\u00B8", "cedil"), // cedilla = spacing cedilla arrayOf("\u00B9", "sup1"), // superscript one = superscript digit one arrayOf("\u00BA", "ordm"), // masculine ordinal indicator arrayOf("\u00BB", "raquo"), // right-pointing double angle quotation mark = right pointing guillemet arrayOf("\u00BC", "frac14"), // vulgar fraction one quarter = fraction one quarter arrayOf("\u00BD", "frac12"), // vulgar fraction one half = fraction one half arrayOf("\u00BE", "frac34"), // vulgar fraction three quarters = fraction three quarters arrayOf("\u00BF", "iquest"), // inverted question mark = turned question mark arrayOf("\u00C0", "Agrave"), // А - uppercase A, grave accent arrayOf("\u00C1", "Aacute"), // Б - uppercase A, acute accent arrayOf("\u00C2", "Acirc"), // В - uppercase A, circumflex accent arrayOf("\u00C3", "Atilde"), // Г - uppercase A, tilde arrayOf("\u00C4", "Auml"), // Д - uppercase A, umlaut arrayOf("\u00C5", "Aring"), // Е - uppercase A, ring arrayOf("\u00C6", "AElig"), // Ж - uppercase AE arrayOf("\u00C7", "Ccedil"), // З - uppercase C, cedilla arrayOf("\u00C8", "Egrave"), // И - uppercase E, grave accent arrayOf("\u00C9", "Eacute"), // Й - uppercase E, acute accent arrayOf("\u00CA", "Ecirc"), // К - uppercase E, circumflex accent arrayOf("\u00CB", "Euml"), // Л - uppercase E, umlaut arrayOf("\u00CC", "Igrave"), // М - uppercase I, grave accent arrayOf("\u00CD", "Iacute"), // Н - uppercase I, acute accent arrayOf("\u00CE", "Icirc"), // О - uppercase I, circumflex accent arrayOf("\u00CF", "Iuml"), // П - uppercase I, umlaut arrayOf("\u00D0", "ETH"), // Р - uppercase Eth, Icelandic arrayOf("\u00D1", "Ntilde"), // С - uppercase N, tilde arrayOf("\u00D2", "Ograve"), // Т - uppercase O, grave accent arrayOf("\u00D3", "Oacute"), // У - uppercase O, acute accent arrayOf("\u00D4", "Ocirc"), // Ф - uppercase O, circumflex accent arrayOf("\u00D5", "Otilde"), // Х - uppercase O, tilde arrayOf("\u00D6", "Ouml"), // Ц - uppercase O, umlaut arrayOf("\u00D7", "times"), // multiplication sign arrayOf("\u00D8", "Oslash"), // Ш - uppercase O, slash arrayOf("\u00D9", "Ugrave"), // Щ - uppercase U, grave accent arrayOf("\u00DA", "Uacute"), // Ъ - uppercase U, acute accent arrayOf("\u00DB", "Ucirc"), // Ы - uppercase U, circumflex accent arrayOf("\u00DC", "Uuml"), // Ь - uppercase U, umlaut arrayOf("\u00DD", "Yacute"), // Э - uppercase Y, acute accent arrayOf("\u00DE", "THORN"), // Ю - uppercase THORN, Icelandic arrayOf("\u00DF", "szlig"), // Я - lowercase sharps, German arrayOf("\u00E0", "agrave"), // а - lowercase a, grave accent arrayOf("\u00E1", "aacute"), // б - lowercase a, acute accent arrayOf("\u00E2", "acirc"), // в - lowercase a, circumflex accent arrayOf("\u00E3", "atilde"), // г - lowercase a, tilde arrayOf("\u00E4", "auml"), // д - lowercase a, umlaut arrayOf("\u00E5", "aring"), // е - lowercase a, ring arrayOf("\u00E6", "aelig"), // ж - lowercase ae arrayOf("\u00E7", "ccedil"), // з - lowercase c, cedilla arrayOf("\u00E8", "egrave"), // и - lowercase e, grave accent arrayOf("\u00E9", "eacute"), // й - lowercase e, acute accent arrayOf("\u00EA", "ecirc"), // к - lowercase e, circumflex accent arrayOf("\u00EB", "euml"), // л - lowercase e, umlaut arrayOf("\u00EC", "igrave"), // м - lowercase i, grave accent arrayOf("\u00ED", "iacute"), // н - lowercase i, acute accent arrayOf("\u00EE", "icirc"), // о - lowercase i, circumflex accent arrayOf("\u00EF", "iuml"), // п - lowercase i, umlaut arrayOf("\u00F0", "eth"), // р - lowercase eth, Icelandic arrayOf("\u00F1", "ntilde"), // с - lowercase n, tilde arrayOf("\u00F2", "ograve"), // т - lowercase o, grave accent arrayOf("\u00F3", "oacute"), // у - lowercase o, acute accent arrayOf("\u00F4", "ocirc"), // ф - lowercase o, circumflex accent arrayOf("\u00F5", "otilde"), // х - lowercase o, tilde arrayOf("\u00F6", "ouml"), // ц - lowercase o, umlaut arrayOf("\u00F7", "divide"), // division sign arrayOf("\u00F8", "oslash"), // ш - lowercase o, slash arrayOf("\u00F9", "ugrave"), // щ - lowercase u, grave accent arrayOf("\u00FA", "uacute"), // ъ - lowercase u, acute accent arrayOf("\u00FB", "ucirc"), // ы - lowercase u, circumflex accent arrayOf("\u00FC", "uuml"), // ь - lowercase u, umlaut arrayOf("\u00FD", "yacute"), // э - lowercase y, acute accent arrayOf("\u00FE", "thorn"), // ю - lowercase thorn, Icelandic arrayOf("\u00FF", "yuml") )// я - lowercase y, umlaut private const val MIN_ESCAPE = 2 private const val MAX_ESCAPE = 6 private val lookupMap: HashMap<String, CharSequence> = HashMap() fun unescapeHtml3(input: String): String { var writer: StringWriter? = null val len = input.length var i = 1 var st = 0 while (true) { // look for '&' while (i < len && input[i - 1] != '&') i++ if (i >= len) break // found '&', look for ';' var j = i while (j < len && j < i + MAX_ESCAPE + 1 && input[j] != ';') j++ if (j == len || j < i + MIN_ESCAPE || j == i + MAX_ESCAPE + 1) { i++ continue } // found escape if (input[i] == '#') { // numeric escape var k = i + 1 var radix = 10 val firstChar = input[k] if (firstChar == 'x' || firstChar == 'X') { k++ radix = 16 } try { val entityValue = Integer.parseInt(input.substring(k, j), radix) if (writer == null) writer = StringWriter(input.length) writer.append(input.substring(st, i - 1)) if (entityValue > 0xFFFF) { val chrs = Character.toChars(entityValue) writer.write(chrs[0].toInt()) writer.write(chrs[1].toInt()) } else { writer.write(entityValue) } } catch (ex: NumberFormatException) { i++ continue } } else { // named escape val value = lookupMap[input.substring(i, j)] if (value == null) { i++ continue } if (writer == null) writer = StringWriter(input.length) writer.append(input.substring(st, i - 1)) writer.append(value) } // skip escape st = j + 1 i = st } if (writer != null) { writer.append(input.substring(st, len)) return writer.toString() } return input } init { for (seq in ESCAPES) lookupMap[seq[1]] = seq[0] } } } }
0
HTML
0
0
36859fece65460efa5eadc0b5bfc1f6bcda42723
18,976
neisinfo
Apache License 2.0
backend/src/main/kotlin/br/com/zup/bff/builder/ListViewDslScreenBuilder.kt
ZupIT
322,612,408
false
null
/* * Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA * * 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 br.com.zup.beagle.sample.builder import br.com.zup.beagle.action.alert import br.com.zup.beagle.ext.style import br.com.zup.beagle.ext.unitReal import br.com.zup.beagle.layout.container import br.com.zup.beagle.layout.navigationBarItem import br.com.zup.beagle.layout.screen import br.com.zup.beagle.layout.scrollView import br.com.zup.beagle.ui.listView import br.com.zup.beagle.ui.text import br.com.zup.beagle.widget.context.valueOf import br.com.zup.beagle.widget.core.ListDirection import br.com.zup.beagle.widget.core.ScrollAxis import br.com.zup.beagle.widget.layout.ScreenBuilder import br.com.zup.beagle.widget.ui.Text object ListViewDslScreenBuilder : ScreenBuilder { override fun build() = screen{ navigationBar { title = "Beagle ListView" showBackButton = true navigationBarItems { +navigationBarItem{ text = "" image{ mobileId = "informationImage" } action{ alert{ title = valueOf("ListView") message{ valueOf("Is a Layout component that will define a list of views natively. " + "These views could be any Server Driven Component.") } labelOk("OK") } } } } } child{ scrollView { scrollDirection = ScrollAxis.VERTICAL children{ +getStaticListView(ListDirection.VERTICAL) +getStaticListView(ListDirection.HORIZONTAL) +getDynamicListView(ListDirection.VERTICAL) +getDynamicListView(ListDirection.HORIZONTAL) } } } } private fun getStaticListView(listDirection: ListDirection) = container { children { +Text("Static $listDirection ListView").style{ margin { bottom = 10.unitReal() } } +listView { direction = listDirection children { +(1..10).map(::createText) } } } }.style { margin { bottom = 20.unitReal() } } private fun getDynamicListView(listDirection: ListDirection) = container{ children{ +text { text{valueOf("Dynamic $listDirection ListView")} }.style { margin { bottom = 10.unitReal() } } +listView { direction = listDirection children { +(0 until 20).map(::createText) } } } } private fun createText(index: Int) = text{ text = valueOf("Hello $index") } }
4
Kotlin
0
4
3339739c2f0c82cb483febfe43a782995f7f2dc0
3,701
beagle-helpers
Apache License 2.0
examples/widgets-gallery/common/src/commonMain/kotlin/org/jetbrains/compose/demo/widgets/ui/screens/Loaders.kt
JetBrains
293,498,508
false
null
package org.jetbrains.compose.demo.widgets.ui.screens import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.LinearProgressIndicator import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp @Composable internal fun Loaders() { AlignedColumn { CircularProgressIndicator() } AlignedColumn { CircularProgressIndicator(strokeWidth = 8.dp) } AlignedColumn { LinearProgressIndicator() } AlignedColumn { LinearProgressIndicator() Text(text = "Loading with text...", modifier = Modifier.padding(8.dp)) } } @Composable private fun AlignedColumn(content: @Composable () -> Unit) { Column( modifier = Modifier.fillMaxWidth().padding(16.dp) ) { content() } }
934
Kotlin
826
9,090
97266a0ac8c0d7a8ad8d19ead1c925751a00ff1c
1,120
compose-jb
Apache License 2.0