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
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/ChatHelp.kt
Konyaco
574,321,009
false
null
package com.konyaco.fluent.icons.regular import androidx.compose.ui.graphics.vector.ImageVector import com.konyaco.fluent.icons.Icons import com.konyaco.fluent.icons.fluentIcon import com.konyaco.fluent.icons.fluentPath public val Icons.Regular.ChatHelp: ImageVector get() { if (_chatHelp != null) { return _chatHelp!! } _chatHelp = fluentIcon(name = "Regular.ChatHelp") { fluentPath { moveTo(12.0f, 2.0f) arcToRelative(10.0f, 10.0f, 0.0f, true, true, -4.59f, 18.89f) lineTo(3.6f, 21.96f) arcToRelative(1.25f, 1.25f, 0.0f, false, true, -1.54f, -1.54f) lineToRelative(1.06f, -3.83f) arcTo(10.0f, 10.0f, 0.0f, false, true, 12.0f, 2.0f) close() moveTo(12.0f, 3.5f) arcToRelative(8.5f, 8.5f, 0.0f, false, false, -7.43f, 12.64f) lineToRelative(0.15f, 0.27f) lineToRelative(-1.1f, 3.98f) lineToRelative(3.98f, -1.11f) lineToRelative(0.27f, 0.15f) arcTo(8.5f, 8.5f, 0.0f, true, false, 12.0f, 3.5f) close() moveTo(12.0f, 15.5f) arcToRelative(1.0f, 1.0f, 0.0f, true, true, 0.0f, 2.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.0f, -2.0f) close() moveTo(12.0f, 6.75f) arcToRelative(2.75f, 2.75f, 0.0f, false, true, 2.75f, 2.75f) curveToRelative(0.0f, 1.01f, -0.3f, 1.57f, -1.05f, 2.36f) lineToRelative(-0.17f, 0.17f) curveToRelative(-0.62f, 0.62f, -0.78f, 0.89f, -0.78f, 1.47f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, -1.5f, 0.0f) curveToRelative(0.0f, -1.01f, 0.3f, -1.57f, 1.05f, -2.36f) lineToRelative(0.17f, -0.17f) curveToRelative(0.62f, -0.62f, 0.78f, -0.89f, 0.78f, -1.47f) arcToRelative(1.25f, 1.25f, 0.0f, false, false, -2.5f, -0.13f) verticalLineToRelative(0.13f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, -1.5f, 0.0f) arcTo(2.75f, 2.75f, 0.0f, false, true, 12.0f, 6.75f) close() } } return _chatHelp!! } private var _chatHelp: ImageVector? = null
1
Kotlin
3
83
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
2,382
compose-fluent-ui
Apache License 2.0
app/src/main/java/id/arvigo/arvigobasecore/ui/feature/deepAR/DeepArActivity.kt
C23-PS191-Arvigo
636,134,744
false
null
package id.arvigo.arvigobasecore.ui.feature.deepAR import ai.deepar.ar.ARErrorType import ai.deepar.ar.AREventListener import ai.deepar.ar.CameraResolutionPreset import ai.deepar.ar.DeepAR import ai.deepar.ar.DeepARImageFormat import android.Manifest import android.content.Context import android.content.pm.ActivityInfo import android.content.pm.PackageManager import android.graphics.Bitmap import android.media.Image import android.os.Bundle import android.os.Environment import android.text.format.DateFormat import android.util.DisplayMetrics import android.util.Log import android.util.Size import android.view.LayoutInflater import android.view.Surface import android.view.SurfaceHolder import android.view.SurfaceView import android.view.View import android.widget.ImageButton import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.camera.core.CameraSelector import androidx.camera.core.ImageAnalysis import androidx.camera.lifecycle.ProcessCameraProvider import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.viewinterop.AndroidView import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.content.ContextCompat import androidx.core.content.FileProvider import androidx.lifecycle.LifecycleOwner import com.google.common.util.concurrent.ListenableFuture import id.arvigo.arvigobasecore.R import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.MainScope import kotlinx.coroutines.launch import java.io.File import java.io.FileOutputStream import java.net.HttpURLConnection import java.net.URL import java.nio.ByteBuffer import java.nio.ByteOrder import java.util.Date import java.util.concurrent.ExecutionException class MySurfaceView(context: Context) : ConstraintLayout(context) { init { LayoutInflater.from(context).inflate(R.layout.activity_camera, this, true) } } class DeepArActivity : AppCompatActivity(), SurfaceHolder.Callback, AREventListener { // Default camera lens value, change to CameraSelector.LENS_FACING_BACK to initialize with back camera private val defaultLensFacing = CameraSelector.LENS_FACING_FRONT private var surfaceProvider: ARSurfaceProvider? = null private var lensFacing = defaultLensFacing private var cameraProviderFuture: ListenableFuture<ProcessCameraProvider>? = null private lateinit var buffers: Array<ByteBuffer?> private var currentBuffer = 0 private var buffersInitialized = false private var deepAR: DeepAR? = null private var currentEffect = 0 private val screenOrientation: Int get() { val rotation = windowManager.defaultDisplay.rotation val dm = DisplayMetrics() windowManager.defaultDisplay.getMetrics(dm) width = dm.widthPixels height = dm.heightPixels // if the device's natural orientation is portrait: val orientation: Int = if ((rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) && height > width || (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) && width > height ) { when (rotation) { Surface.ROTATION_0 -> ActivityInfo.SCREEN_ORIENTATION_PORTRAIT Surface.ROTATION_90 -> ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE Surface.ROTATION_180 -> ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT Surface.ROTATION_270 -> ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE else -> ActivityInfo.SCREEN_ORIENTATION_PORTRAIT } } else { when (rotation) { Surface.ROTATION_0 -> ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE Surface.ROTATION_90 -> ActivityInfo.SCREEN_ORIENTATION_PORTRAIT Surface.ROTATION_180 -> ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE Surface.ROTATION_270 -> ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT else -> ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE } } return orientation } private var effects: ArrayList<String>? = null private var recording = false private var currentSwitchRecording = false private var width = 0 private var height = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val composeView = ComposeView(this) composeView.setContent { CameraContent() } setContentView(composeView) } private val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted -> if (isGranted) { // Permission has been granted initialize() } else { // Permission has been denied // Handle the denial case // You can show an explanation to the user or take alternative actions } } override fun onStart() { val cameraPermission = Manifest.permission.CAMERA val recordAudioPermission = Manifest.permission.RECORD_AUDIO val cameraPermissionGranted = ContextCompat.checkSelfPermission( this, cameraPermission ) == PackageManager.PERMISSION_GRANTED val recordAudioPermissionGranted = ContextCompat.checkSelfPermission( this, recordAudioPermission ) == PackageManager.PERMISSION_GRANTED if (!cameraPermissionGranted || !recordAudioPermissionGranted) { if (!cameraPermissionGranted) { requestPermissionLauncher.launch(cameraPermission) } if (!recordAudioPermissionGranted) { requestPermissionLauncher.launch(recordAudioPermission) } } else { // Permission has already been granted initialize() } super.onStart() } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray, ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == 1 && grantResults.isNotEmpty()) { for (grantResult in grantResults) { if (grantResult != PackageManager.PERMISSION_GRANTED) { return // no permission } } initialize() } } private fun initialize() { MainScope().launch { initializeDeepAR() initializeFilters() initializeViews1() } } @OptIn(DelicateCoroutinesApi::class) private fun initializeFilters() { // Get the bundle extras from the intent val extras = intent.extras val link = extras?.getString("linkAr") val linkName = link?.substringAfterLast("/")?.substringBeforeLast(".") + ".deepar" Log.d("neo-tag", "initializeFilters: $link") effects = ArrayList() effects!!.add(linkName) // Download and save the effect file from the URL GlobalScope.launch(Dispatchers.IO) { val effectFile = File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), linkName) if (!effectFile.exists()) { // Check if the file already exists val url = URL(link) val connection = url.openConnection() as HttpURLConnection connection.requestMethod = "GET" connection.connectTimeout = 10000 connection.readTimeout = 10000 connection.connect() if (connection.responseCode == HttpURLConnection.HTTP_OK) { val inputStream = connection.inputStream val outputStream = FileOutputStream(effectFile) val buffer = ByteArray(1024) var bytesRead: Int while (inputStream.read(buffer).also { bytesRead = it } != -1) { outputStream.write(buffer, 0, bytesRead) } outputStream.close() inputStream.close() // Add the local file path to the effects list Log.d("neo-kaca", "Success saved.") Log.d("neo-kaca", effectFile.absolutePath.toString()) val fileUri = FileProvider.getUriForFile( applicationContext, applicationContext.packageName.toString(), File(effectFile.absolutePath) ) fileUri.path?.let { effects!!.add(it) Log.d("neo-kaca", "Masuk let") } Log.d("neo-kaca", "${fileUri.path}") } } else { // File already exists, so you can handle this case as needed Log.d("neo-kaca", "File already exists. Skipping download.") } } } private fun initializeViews1() { /*val previousMask = findViewById<ImageButton>(R.id.previousMask) val nextMask = findViewById<ImageButton>(R.id.nextMask)*/ val arView: SurfaceView by lazy { findViewById(R.id.surface_deepar) } if (arView.isActivated) { arView.holder?.addCallback(this) } else { // Handle the case where arView has not been initialized properly } arView.holder?.addCallback(this) // Surface might already be initialized, so we force the call to onSurfaceChanged arView.visibility = View.GONE arView.visibility = View.VISIBLE //val screenshotBtn = findViewById<ImageButton>(R.id.recordButton) /*val screenshotBtn: ImageButton by lazy { findViewById<ImageButton>(R.id.recordButton).apply { setOnClickListener { deepAR!!.takeScreenshot() } } } screenshotBtn.setOnClickListener { deepAR!!.takeScreenshot() } val switchCamera: ImageButton by lazy { findViewById(R.id.switchCamera) } switchCamera.setOnClickListener { lensFacing = if (lensFacing == CameraSelector.LENS_FACING_FRONT) CameraSelector.LENS_FACING_BACK else CameraSelector.LENS_FACING_FRONT //unbind immediately to avoid mirrored frame. val cameraProvider: ProcessCameraProvider? try { cameraProvider = cameraProviderFuture!!.get() cameraProvider.unbindAll() } catch (e: ExecutionException) { e.printStackTrace() } catch (e: InterruptedException) { e.printStackTrace() } setupCamera() } previousMask.setOnClickListener { gotoPrevious() } nextMask.setOnClickListener { gotoNext() }*/ } private fun initializeDeepAR() { deepAR = DeepAR(this) deepAR!!.setLicenseKey("24d3e29837cc34a6de124277b6790d397d9b22741bc02d8162f98de1449a56df8176c1664d998f7d") deepAR!!.initialize(this, this) setupCamera() } private fun setupCamera() { Log.d("neo-kaca", "setupCamera: kameraaa JALAN") cameraProviderFuture = ProcessCameraProvider.getInstance(this) cameraProviderFuture?.addListener({ try { val cameraProvider = cameraProviderFuture?.get() if (cameraProvider != null) { bindImageAnalysis(cameraProvider) } } catch (e: ExecutionException) { e.printStackTrace() } catch (e: InterruptedException) { e.printStackTrace() } }, ContextCompat.getMainExecutor(this)) } private fun bindImageAnalysis(cameraProvider: ProcessCameraProvider) { val cameraResolutionPreset = CameraResolutionPreset.P1920x1080 val width: Int val height: Int val orientation = screenOrientation if (orientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE || orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) { width = cameraResolutionPreset.width height = cameraResolutionPreset.height } else { width = cameraResolutionPreset.height height = cameraResolutionPreset.width } val cameraResolution = Size(width, height) val cameraSelector = CameraSelector.Builder().requireLensFacing(lensFacing).build() if (useExternalCameraTexture) { val preview = androidx.camera.core.Preview.Builder() .setTargetResolution(cameraResolution) .build() cameraProvider.unbindAll() cameraProvider.bindToLifecycle((this as LifecycleOwner), cameraSelector, preview) if (surfaceProvider == null) { surfaceProvider = deepAR?.let { ARSurfaceProvider(this, it) } } preview.setSurfaceProvider(surfaceProvider) surfaceProvider!!.setMirror(lensFacing == CameraSelector.LENS_FACING_FRONT) } else { val imageAnalysis = ImageAnalysis.Builder() .setTargetResolution(cameraResolution) .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST) .build() imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(this), imageAnalyzer) buffersInitialized = false cameraProvider.unbindAll() cameraProvider.bindToLifecycle((this as LifecycleOwner), cameraSelector, imageAnalysis) } } private fun initializeBuffers(size: Int) { buffers = arrayOfNulls(NUMBER_OF_BUFFERS) for (i in 0 until NUMBER_OF_BUFFERS) { buffers[i] = ByteBuffer.allocateDirect(size) buffers[i]?.order(ByteOrder.nativeOrder()) buffers[i]?.position(0) } } private val imageAnalyzer = ImageAnalysis.Analyzer { image -> val yBuffer = image.planes[0].buffer val uBuffer = image.planes[1].buffer val vBuffer = image.planes[2].buffer val ySize = yBuffer.remaining() val uSize = uBuffer.remaining() val vSize = vBuffer.remaining() if (!buffersInitialized) { buffersInitialized = true initializeBuffers(ySize + uSize + vSize) } val byteData = ByteArray(ySize + uSize + vSize) val width = image.width val yStride = image.planes[0].rowStride val uStride = image.planes[1].rowStride val vStride = image.planes[2].rowStride var outputOffset = 0 if (width == yStride) { yBuffer[byteData, outputOffset, ySize] outputOffset += ySize } else { var inputOffset = 0 while (inputOffset < ySize) { yBuffer.position(inputOffset) yBuffer[byteData, outputOffset, yBuffer.remaining().coerceAtMost(width)] outputOffset += width inputOffset += yStride } } //U and V are swapped if (width == vStride) { vBuffer[byteData, outputOffset, vSize] outputOffset += vSize } else { var inputOffset = 0 while (inputOffset < vSize) { vBuffer.position(inputOffset) vBuffer[byteData, outputOffset, vBuffer.remaining().coerceAtMost(width)] outputOffset += width inputOffset += vStride } } if (width == uStride) { uBuffer[byteData, outputOffset, uSize] outputOffset += uSize } else { var inputOffset = 0 while (inputOffset < uSize) { uBuffer.position(inputOffset) uBuffer[byteData, outputOffset, uBuffer.remaining().coerceAtMost(width)] outputOffset += width inputOffset += uStride } } buffers[currentBuffer]!!.put(byteData) buffers[currentBuffer]!!.position(0) if (deepAR != null) { deepAR!!.receiveFrame( buffers[currentBuffer], image.width, image.height, image.imageInfo.rotationDegrees, lensFacing == CameraSelector.LENS_FACING_FRONT, DeepARImageFormat.YUV_420_888, image.planes[1].pixelStride ) } currentBuffer = (currentBuffer + 1) % NUMBER_OF_BUFFERS image.close() } private fun getFilterPath(filterName: String): String? { val file = File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), filterName).absolutePath return if (filterName == "none") { null } else file } private fun gotoNext() { currentEffect = (currentEffect + 1) % effects!!.size deepAR!!.switchEffect("effect", getFilterPath(effects!![currentEffect])) Log.d("neo-kaca", "gotoNext: ${getFilterPath(effects!![currentEffect])}") } private fun gotoPrevious() { currentEffect = (currentEffect - 1 + effects!!.size) % effects!!.size deepAR!!.switchEffect("effect", getFilterPath(effects!![currentEffect])) Log.d("neo-kaca", "gotoPrev: ${getFilterPath(effects!![currentEffect])}") } override fun onStop() { recording = false currentSwitchRecording = false val cameraProvider: ProcessCameraProvider? try { cameraProvider = cameraProviderFuture?.get() cameraProvider?.unbindAll() } catch (e: ExecutionException) { e.printStackTrace() } catch (e: InterruptedException) { e.printStackTrace() } if (surfaceProvider != null) { surfaceProvider!!.stop() surfaceProvider = null } deepAR?.release() deepAR = null super.onStop() } override fun onDestroy() { super.onDestroy() if (surfaceProvider != null) { surfaceProvider!!.stop() } if (deepAR == null) { return } deepAR!!.setAREventListener(null) deepAR!!.release() deepAR = null } override fun surfaceCreated(holder: SurfaceHolder) {} override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) { // If we are using on screen rendering we have to set surface view where DeepAR will render deepAR!!.setRenderSurface(holder.surface, width, height) } override fun surfaceDestroyed(holder: SurfaceHolder) { if (deepAR != null) { deepAR!!.setRenderSurface(null, 0, 0) } } override fun screenshotTaken(bitmap: Bitmap) { val now = DateFormat.format("yyyy_MM_dd_hh_mm_ss", Date()) try { val imageFile = File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "image_$now.jpg") val outputStream = FileOutputStream(imageFile) val quality = 100 bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream) outputStream.flush() outputStream.close() } catch (e: Throwable) { e.printStackTrace() } } override fun videoRecordingStarted() {} override fun videoRecordingFinished() {} override fun videoRecordingFailed() {} override fun videoRecordingPrepared() {} override fun shutdownFinished() {} override fun initialized() { // Restore effect state after deepar release deepAR!!.switchEffect("effect", getFilterPath(effects!![currentEffect])) } override fun faceVisibilityChanged(b: Boolean) {} override fun imageVisibilityChanged(s: String, b: Boolean) {} override fun frameAvailable(image: Image) {} override fun error(arErrorType: ARErrorType, s: String) {} override fun effectSwitched(s: String) {} companion object { private const val NUMBER_OF_BUFFERS = 2 private const val useExternalCameraTexture = true } } @Composable fun CameraContent() { Box(modifier = Modifier.fillMaxSize()) { AndroidView( modifier = Modifier.fillMaxSize(), factory = { context -> MySurfaceView(context) }, ) // Rest of the UI components } }
1
Kotlin
0
0
7c2cd60a0c8088235784cfab292990dc0f431c1f
21,048
arvigo-mobile-app
MIT License
app/src/main/java/id/arvigo/arvigobasecore/ui/feature/deepAR/DeepArActivity.kt
C23-PS191-Arvigo
636,134,744
false
null
package id.arvigo.arvigobasecore.ui.feature.deepAR import ai.deepar.ar.ARErrorType import ai.deepar.ar.AREventListener import ai.deepar.ar.CameraResolutionPreset import ai.deepar.ar.DeepAR import ai.deepar.ar.DeepARImageFormat import android.Manifest import android.content.Context import android.content.pm.ActivityInfo import android.content.pm.PackageManager import android.graphics.Bitmap import android.media.Image import android.os.Bundle import android.os.Environment import android.text.format.DateFormat import android.util.DisplayMetrics import android.util.Log import android.util.Size import android.view.LayoutInflater import android.view.Surface import android.view.SurfaceHolder import android.view.SurfaceView import android.view.View import android.widget.ImageButton import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.camera.core.CameraSelector import androidx.camera.core.ImageAnalysis import androidx.camera.lifecycle.ProcessCameraProvider import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.viewinterop.AndroidView import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.content.ContextCompat import androidx.core.content.FileProvider import androidx.lifecycle.LifecycleOwner import com.google.common.util.concurrent.ListenableFuture import id.arvigo.arvigobasecore.R import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.MainScope import kotlinx.coroutines.launch import java.io.File import java.io.FileOutputStream import java.net.HttpURLConnection import java.net.URL import java.nio.ByteBuffer import java.nio.ByteOrder import java.util.Date import java.util.concurrent.ExecutionException class MySurfaceView(context: Context) : ConstraintLayout(context) { init { LayoutInflater.from(context).inflate(R.layout.activity_camera, this, true) } } class DeepArActivity : AppCompatActivity(), SurfaceHolder.Callback, AREventListener { // Default camera lens value, change to CameraSelector.LENS_FACING_BACK to initialize with back camera private val defaultLensFacing = CameraSelector.LENS_FACING_FRONT private var surfaceProvider: ARSurfaceProvider? = null private var lensFacing = defaultLensFacing private var cameraProviderFuture: ListenableFuture<ProcessCameraProvider>? = null private lateinit var buffers: Array<ByteBuffer?> private var currentBuffer = 0 private var buffersInitialized = false private var deepAR: DeepAR? = null private var currentEffect = 0 private val screenOrientation: Int get() { val rotation = windowManager.defaultDisplay.rotation val dm = DisplayMetrics() windowManager.defaultDisplay.getMetrics(dm) width = dm.widthPixels height = dm.heightPixels // if the device's natural orientation is portrait: val orientation: Int = if ((rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) && height > width || (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) && width > height ) { when (rotation) { Surface.ROTATION_0 -> ActivityInfo.SCREEN_ORIENTATION_PORTRAIT Surface.ROTATION_90 -> ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE Surface.ROTATION_180 -> ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT Surface.ROTATION_270 -> ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE else -> ActivityInfo.SCREEN_ORIENTATION_PORTRAIT } } else { when (rotation) { Surface.ROTATION_0 -> ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE Surface.ROTATION_90 -> ActivityInfo.SCREEN_ORIENTATION_PORTRAIT Surface.ROTATION_180 -> ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE Surface.ROTATION_270 -> ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT else -> ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE } } return orientation } private var effects: ArrayList<String>? = null private var recording = false private var currentSwitchRecording = false private var width = 0 private var height = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val composeView = ComposeView(this) composeView.setContent { CameraContent() } setContentView(composeView) } private val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted -> if (isGranted) { // Permission has been granted initialize() } else { // Permission has been denied // Handle the denial case // You can show an explanation to the user or take alternative actions } } override fun onStart() { val cameraPermission = Manifest.permission.CAMERA val recordAudioPermission = Manifest.permission.RECORD_AUDIO val cameraPermissionGranted = ContextCompat.checkSelfPermission( this, cameraPermission ) == PackageManager.PERMISSION_GRANTED val recordAudioPermissionGranted = ContextCompat.checkSelfPermission( this, recordAudioPermission ) == PackageManager.PERMISSION_GRANTED if (!cameraPermissionGranted || !recordAudioPermissionGranted) { if (!cameraPermissionGranted) { requestPermissionLauncher.launch(cameraPermission) } if (!recordAudioPermissionGranted) { requestPermissionLauncher.launch(recordAudioPermission) } } else { // Permission has already been granted initialize() } super.onStart() } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray, ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == 1 && grantResults.isNotEmpty()) { for (grantResult in grantResults) { if (grantResult != PackageManager.PERMISSION_GRANTED) { return // no permission } } initialize() } } private fun initialize() { MainScope().launch { initializeDeepAR() initializeFilters() initializeViews1() } } @OptIn(DelicateCoroutinesApi::class) private fun initializeFilters() { // Get the bundle extras from the intent val extras = intent.extras val link = extras?.getString("linkAr") val linkName = link?.substringAfterLast("/")?.substringBeforeLast(".") + ".deepar" Log.d("neo-tag", "initializeFilters: $link") effects = ArrayList() effects!!.add(linkName) // Download and save the effect file from the URL GlobalScope.launch(Dispatchers.IO) { val effectFile = File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), linkName) if (!effectFile.exists()) { // Check if the file already exists val url = URL(link) val connection = url.openConnection() as HttpURLConnection connection.requestMethod = "GET" connection.connectTimeout = 10000 connection.readTimeout = 10000 connection.connect() if (connection.responseCode == HttpURLConnection.HTTP_OK) { val inputStream = connection.inputStream val outputStream = FileOutputStream(effectFile) val buffer = ByteArray(1024) var bytesRead: Int while (inputStream.read(buffer).also { bytesRead = it } != -1) { outputStream.write(buffer, 0, bytesRead) } outputStream.close() inputStream.close() // Add the local file path to the effects list Log.d("neo-kaca", "Success saved.") Log.d("neo-kaca", effectFile.absolutePath.toString()) val fileUri = FileProvider.getUriForFile( applicationContext, applicationContext.packageName.toString(), File(effectFile.absolutePath) ) fileUri.path?.let { effects!!.add(it) Log.d("neo-kaca", "Masuk let") } Log.d("neo-kaca", "${fileUri.path}") } } else { // File already exists, so you can handle this case as needed Log.d("neo-kaca", "File already exists. Skipping download.") } } } private fun initializeViews1() { /*val previousMask = findViewById<ImageButton>(R.id.previousMask) val nextMask = findViewById<ImageButton>(R.id.nextMask)*/ val arView: SurfaceView by lazy { findViewById(R.id.surface_deepar) } if (arView.isActivated) { arView.holder?.addCallback(this) } else { // Handle the case where arView has not been initialized properly } arView.holder?.addCallback(this) // Surface might already be initialized, so we force the call to onSurfaceChanged arView.visibility = View.GONE arView.visibility = View.VISIBLE //val screenshotBtn = findViewById<ImageButton>(R.id.recordButton) /*val screenshotBtn: ImageButton by lazy { findViewById<ImageButton>(R.id.recordButton).apply { setOnClickListener { deepAR!!.takeScreenshot() } } } screenshotBtn.setOnClickListener { deepAR!!.takeScreenshot() } val switchCamera: ImageButton by lazy { findViewById(R.id.switchCamera) } switchCamera.setOnClickListener { lensFacing = if (lensFacing == CameraSelector.LENS_FACING_FRONT) CameraSelector.LENS_FACING_BACK else CameraSelector.LENS_FACING_FRONT //unbind immediately to avoid mirrored frame. val cameraProvider: ProcessCameraProvider? try { cameraProvider = cameraProviderFuture!!.get() cameraProvider.unbindAll() } catch (e: ExecutionException) { e.printStackTrace() } catch (e: InterruptedException) { e.printStackTrace() } setupCamera() } previousMask.setOnClickListener { gotoPrevious() } nextMask.setOnClickListener { gotoNext() }*/ } private fun initializeDeepAR() { deepAR = DeepAR(this) deepAR!!.setLicenseKey("24d3e29837cc34a6de124277b6790d397d9b22741bc02d8162f98de1449a56df8176c1664d998f7d") deepAR!!.initialize(this, this) setupCamera() } private fun setupCamera() { Log.d("neo-kaca", "setupCamera: kameraaa JALAN") cameraProviderFuture = ProcessCameraProvider.getInstance(this) cameraProviderFuture?.addListener({ try { val cameraProvider = cameraProviderFuture?.get() if (cameraProvider != null) { bindImageAnalysis(cameraProvider) } } catch (e: ExecutionException) { e.printStackTrace() } catch (e: InterruptedException) { e.printStackTrace() } }, ContextCompat.getMainExecutor(this)) } private fun bindImageAnalysis(cameraProvider: ProcessCameraProvider) { val cameraResolutionPreset = CameraResolutionPreset.P1920x1080 val width: Int val height: Int val orientation = screenOrientation if (orientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE || orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) { width = cameraResolutionPreset.width height = cameraResolutionPreset.height } else { width = cameraResolutionPreset.height height = cameraResolutionPreset.width } val cameraResolution = Size(width, height) val cameraSelector = CameraSelector.Builder().requireLensFacing(lensFacing).build() if (useExternalCameraTexture) { val preview = androidx.camera.core.Preview.Builder() .setTargetResolution(cameraResolution) .build() cameraProvider.unbindAll() cameraProvider.bindToLifecycle((this as LifecycleOwner), cameraSelector, preview) if (surfaceProvider == null) { surfaceProvider = deepAR?.let { ARSurfaceProvider(this, it) } } preview.setSurfaceProvider(surfaceProvider) surfaceProvider!!.setMirror(lensFacing == CameraSelector.LENS_FACING_FRONT) } else { val imageAnalysis = ImageAnalysis.Builder() .setTargetResolution(cameraResolution) .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST) .build() imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(this), imageAnalyzer) buffersInitialized = false cameraProvider.unbindAll() cameraProvider.bindToLifecycle((this as LifecycleOwner), cameraSelector, imageAnalysis) } } private fun initializeBuffers(size: Int) { buffers = arrayOfNulls(NUMBER_OF_BUFFERS) for (i in 0 until NUMBER_OF_BUFFERS) { buffers[i] = ByteBuffer.allocateDirect(size) buffers[i]?.order(ByteOrder.nativeOrder()) buffers[i]?.position(0) } } private val imageAnalyzer = ImageAnalysis.Analyzer { image -> val yBuffer = image.planes[0].buffer val uBuffer = image.planes[1].buffer val vBuffer = image.planes[2].buffer val ySize = yBuffer.remaining() val uSize = uBuffer.remaining() val vSize = vBuffer.remaining() if (!buffersInitialized) { buffersInitialized = true initializeBuffers(ySize + uSize + vSize) } val byteData = ByteArray(ySize + uSize + vSize) val width = image.width val yStride = image.planes[0].rowStride val uStride = image.planes[1].rowStride val vStride = image.planes[2].rowStride var outputOffset = 0 if (width == yStride) { yBuffer[byteData, outputOffset, ySize] outputOffset += ySize } else { var inputOffset = 0 while (inputOffset < ySize) { yBuffer.position(inputOffset) yBuffer[byteData, outputOffset, yBuffer.remaining().coerceAtMost(width)] outputOffset += width inputOffset += yStride } } //U and V are swapped if (width == vStride) { vBuffer[byteData, outputOffset, vSize] outputOffset += vSize } else { var inputOffset = 0 while (inputOffset < vSize) { vBuffer.position(inputOffset) vBuffer[byteData, outputOffset, vBuffer.remaining().coerceAtMost(width)] outputOffset += width inputOffset += vStride } } if (width == uStride) { uBuffer[byteData, outputOffset, uSize] outputOffset += uSize } else { var inputOffset = 0 while (inputOffset < uSize) { uBuffer.position(inputOffset) uBuffer[byteData, outputOffset, uBuffer.remaining().coerceAtMost(width)] outputOffset += width inputOffset += uStride } } buffers[currentBuffer]!!.put(byteData) buffers[currentBuffer]!!.position(0) if (deepAR != null) { deepAR!!.receiveFrame( buffers[currentBuffer], image.width, image.height, image.imageInfo.rotationDegrees, lensFacing == CameraSelector.LENS_FACING_FRONT, DeepARImageFormat.YUV_420_888, image.planes[1].pixelStride ) } currentBuffer = (currentBuffer + 1) % NUMBER_OF_BUFFERS image.close() } private fun getFilterPath(filterName: String): String? { val file = File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), filterName).absolutePath return if (filterName == "none") { null } else file } private fun gotoNext() { currentEffect = (currentEffect + 1) % effects!!.size deepAR!!.switchEffect("effect", getFilterPath(effects!![currentEffect])) Log.d("neo-kaca", "gotoNext: ${getFilterPath(effects!![currentEffect])}") } private fun gotoPrevious() { currentEffect = (currentEffect - 1 + effects!!.size) % effects!!.size deepAR!!.switchEffect("effect", getFilterPath(effects!![currentEffect])) Log.d("neo-kaca", "gotoPrev: ${getFilterPath(effects!![currentEffect])}") } override fun onStop() { recording = false currentSwitchRecording = false val cameraProvider: ProcessCameraProvider? try { cameraProvider = cameraProviderFuture?.get() cameraProvider?.unbindAll() } catch (e: ExecutionException) { e.printStackTrace() } catch (e: InterruptedException) { e.printStackTrace() } if (surfaceProvider != null) { surfaceProvider!!.stop() surfaceProvider = null } deepAR?.release() deepAR = null super.onStop() } override fun onDestroy() { super.onDestroy() if (surfaceProvider != null) { surfaceProvider!!.stop() } if (deepAR == null) { return } deepAR!!.setAREventListener(null) deepAR!!.release() deepAR = null } override fun surfaceCreated(holder: SurfaceHolder) {} override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) { // If we are using on screen rendering we have to set surface view where DeepAR will render deepAR!!.setRenderSurface(holder.surface, width, height) } override fun surfaceDestroyed(holder: SurfaceHolder) { if (deepAR != null) { deepAR!!.setRenderSurface(null, 0, 0) } } override fun screenshotTaken(bitmap: Bitmap) { val now = DateFormat.format("yyyy_MM_dd_hh_mm_ss", Date()) try { val imageFile = File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "image_$now.jpg") val outputStream = FileOutputStream(imageFile) val quality = 100 bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream) outputStream.flush() outputStream.close() } catch (e: Throwable) { e.printStackTrace() } } override fun videoRecordingStarted() {} override fun videoRecordingFinished() {} override fun videoRecordingFailed() {} override fun videoRecordingPrepared() {} override fun shutdownFinished() {} override fun initialized() { // Restore effect state after deepar release deepAR!!.switchEffect("effect", getFilterPath(effects!![currentEffect])) } override fun faceVisibilityChanged(b: Boolean) {} override fun imageVisibilityChanged(s: String, b: Boolean) {} override fun frameAvailable(image: Image) {} override fun error(arErrorType: ARErrorType, s: String) {} override fun effectSwitched(s: String) {} companion object { private const val NUMBER_OF_BUFFERS = 2 private const val useExternalCameraTexture = true } } @Composable fun CameraContent() { Box(modifier = Modifier.fillMaxSize()) { AndroidView( modifier = Modifier.fillMaxSize(), factory = { context -> MySurfaceView(context) }, ) // Rest of the UI components } }
1
Kotlin
0
0
7c2cd60a0c8088235784cfab292990dc0f431c1f
21,048
arvigo-mobile-app
MIT License
src/main/kotlin/org/opensearch/indexmanagement/indexstatemanagement/step/rollup/AttemptCreateRollupJobStep.kt
opensearch-project
354,094,562
false
null
/* * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. * * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ /* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package org.opensearch.indexmanagement.indexstatemanagement.step.rollup import org.apache.logging.log4j.LogManager import org.opensearch.ExceptionsHelper import org.opensearch.action.support.WriteRequest import org.opensearch.action.support.master.AcknowledgedResponse import org.opensearch.client.Client import org.opensearch.cluster.service.ClusterService import org.opensearch.index.engine.VersionConflictEngineException import org.opensearch.indexmanagement.indexstatemanagement.model.ManagedIndexMetaData import org.opensearch.indexmanagement.indexstatemanagement.model.managedindexmetadata.ActionProperties import org.opensearch.indexmanagement.indexstatemanagement.model.managedindexmetadata.StepMetaData import org.opensearch.indexmanagement.indexstatemanagement.step.Step import org.opensearch.indexmanagement.opensearchapi.suspendUntil import org.opensearch.indexmanagement.rollup.action.index.IndexRollupAction import org.opensearch.indexmanagement.rollup.action.index.IndexRollupRequest import org.opensearch.indexmanagement.rollup.action.index.IndexRollupResponse import org.opensearch.indexmanagement.rollup.action.start.StartRollupAction import org.opensearch.indexmanagement.rollup.action.start.StartRollupRequest import org.opensearch.indexmanagement.rollup.model.ISMRollup import org.opensearch.transport.RemoteTransportException import java.lang.Exception class AttemptCreateRollupJobStep( val clusterService: ClusterService, val client: Client, val ismRollup: ISMRollup, managedIndexMetaData: ManagedIndexMetaData ) : Step(name, managedIndexMetaData) { private val logger = LogManager.getLogger(javaClass) private var stepStatus = StepStatus.STARTING private var info: Map<String, Any>? = null private var rollupId: String? = null private var previousRunRollupId: String? = null private var hasPreviousRollupAttemptFailed: Boolean? = null override fun isIdempotent() = true override suspend fun execute(): Step { previousRunRollupId = managedIndexMetaData.actionMetaData?.actionProperties?.rollupId hasPreviousRollupAttemptFailed = managedIndexMetaData.actionMetaData?.actionProperties?.hasRollupFailed // Creating a rollup job val rollup = ismRollup.toRollup(indexName) rollupId = rollup.id logger.info("Attempting to create a rollup job $rollupId for index $indexName") val indexRollupRequest = IndexRollupRequest(rollup, WriteRequest.RefreshPolicy.IMMEDIATE) try { val response: IndexRollupResponse = client.suspendUntil { execute(IndexRollupAction.INSTANCE, indexRollupRequest, it) } logger.info("Received status ${response.status.status} on trying to create rollup job $rollupId") stepStatus = StepStatus.COMPLETED info = mapOf("message" to getSuccessMessage(rollup.id, indexName)) } catch (e: VersionConflictEngineException) { val message = getFailedJobExistsMessage(rollup.id, indexName) logger.info(message) if (rollupId == previousRunRollupId && hasPreviousRollupAttemptFailed == true) { startRollupJob(rollup.id) } else { stepStatus = StepStatus.COMPLETED info = mapOf("info" to message) } } catch (e: RemoteTransportException) { processFailure(rollup.id, ExceptionsHelper.unwrapCause(e) as Exception) } catch (e: RemoteTransportException) { processFailure(rollup.id, e) } return this } override fun getUpdatedManagedIndexMetaData(currentMetaData: ManagedIndexMetaData): ManagedIndexMetaData { val currentActionMetaData = currentMetaData.actionMetaData return currentMetaData.copy( actionMetaData = currentActionMetaData?.copy(actionProperties = ActionProperties(rollupId = rollupId)), stepMetaData = StepMetaData(name, getStepStartTime().toEpochMilli(), stepStatus), transitionTo = null, info = info ) } fun processFailure(rollupId: String, e: Exception) { val message = getFailedMessage(rollupId, indexName) logger.error(message, e) stepStatus = StepStatus.FAILED info = mapOf("message" to message, "cause" to "${e.message}") } private suspend fun startRollupJob(rollupId: String) { logger.info("Attempting to re-start the job $rollupId") try { val startRollupRequest = StartRollupRequest(rollupId) val response: AcknowledgedResponse = client.suspendUntil { execute(StartRollupAction.INSTANCE, startRollupRequest, it) } stepStatus = StepStatus.COMPLETED info = mapOf("message" to getSuccessRestartMessage(rollupId, indexName)) } catch (e: Exception) { val message = getFailedToStartMessage(rollupId, indexName) logger.error(message, e) stepStatus = StepStatus.FAILED info = mapOf("message" to message) } } companion object { const val name = "attempt_create_rollup" fun getFailedMessage(rollupId: String, index: String) = "Failed to create the rollup job [$rollupId] [index=$index]" fun getFailedJobExistsMessage(rollupId: String, index: String) = "Rollup job [$rollupId] already exists, skipping creation [index=$index]" fun getFailedToStartMessage(rollupId: String, index: String) = "Failed to start the rollup job [$rollupId] [index=$index]" fun getSuccessMessage(rollupId: String, index: String) = "Successfully created the rollup job [$rollupId] [index=$index]" fun getSuccessRestartMessage(rollupId: String, index: String) = "Successfully restarted the rollup job [$rollupId] [index=$index]" } }
73
null
46
17
c5d1739f1a6df255f75171f2b88e51fcde7b7aba
6,682
index-management
Apache License 2.0
src/main/kotlin/ajdepaul/taggedmusic/songlibraries/SongLibrary.kt
ajdepaul
273,658,128
false
null
/* * Copyright © 2021 <NAME> * Licensed under the MIT License https://ajdepaul.mit-license.org/ */ package ajdepaul.taggedmusic.songlibraries import ajdepaul.taggedmusic.Song import ajdepaul.taggedmusic.Tag import ajdepaul.taggedmusic.TagType import ajdepaul.taggedmusic.librarysources.LibrarySource import kotlinx.collections.immutable.PersistentMap import kotlinx.collections.immutable.PersistentSet import kotlinx.collections.immutable.persistentHashSetOf /** * [SongLibrary]s are represented as three separate maps. * 1. Songs | key: file name of the [Song] in its * [AudioFileProvider][ajdepaul.taggedmusic.audiofileproviders.AudioFileProvider], value: the * [Song] data object * 2. Tags | key: the [Tag] name, value: the [Tag] data object * 3. Tag Types | key: the [TagType] name, value: the [TagType] data object * * There is an additional data map that stores [String] values using [String] keys that doesn't * affect the functionality of the [SongLibrary]. It can be used to conveniently store any * additional information relevant to your application into the [LibrarySource]. * * You can read or write to these maps using the various put, remove, and get functions. * @param librarySource [LibrarySource] used to retrieve data about a user's [SongLibrary] */ abstract class SongLibrary( /** [LibrarySource] used to retrieve data about a user's [SongLibrary]. */ val librarySource: LibrarySource ) { companion object { /** Indicates what specification this Tagged Music library expects. */ const val VERSION = "1.0" } init { // check the version of librarySource val libSrcVer = librarySource.getVersion() if (libSrcVer != VERSION) println( "The library source version ($libSrcVer) does not match this Tagged Music " + "version ($VERSION). Unexpected behavior is likely to occur." ) } /** Sets the [TagType] to use when a [Tag] has no [TagType]. */ abstract fun setDefaultTagType(tagType: TagType) /** Retrieves the [TagType] to use when a [Tag] has no [TagType]. */ abstract fun getDefaultTagType(): TagType /* -------------------------------------------- Songs ------------------------------------------- */ /** * Adds or updates [song] to the [Song] map and adds any new [Tag]s in [song]'s [Tag]s to the * [Tag] map. * @param fileName if blank, no change is made */ fun putSong(fileName: String, song: Song) { if (fileName.isBlank()) return _putSong(fileName, song) } /** * Implementation for [putSong]. * @param fileName will never be blank */ protected abstract fun _putSong(fileName: String, song: Song) /** * Removes a [Song] from the [Song] map using the key [fileName]. * @param fileName if blank, no change is made */ fun removeSong(fileName: String) { if (fileName.isBlank()) return _removeSong(fileName) } /** * Implementation for [removeSong]. * @param fileName will never be blank */ protected abstract fun _removeSong(fileName: String) /** * Checks if [fileName] is a key used in the [Song] map. * @param fileName if blank, returns false */ fun hasSong(fileName: String): Boolean { if (fileName.isBlank()) return false return _hasSong(fileName) } /** * Implementation for [hasSong]. * @param fileName will never be blank */ protected abstract fun _hasSong(fileName: String): Boolean /** * Retrieves the [Song] that corresponds to the key [fileName]. * @param fileName if blank, returns null * @return null if the key does not exist */ fun getSong(fileName: String): Song? { if (fileName.isBlank()) return null return _getSong(fileName) } /** * Implementation for [getSong]. * @param fileName will never be blank */ protected abstract fun _getSong(fileName: String): Song? /** Returns a map of all of the [Song]s in the [SongLibrary]. */ abstract fun getAllSongs(): PersistentMap<String, Song> /** * Retrieves a map of songs according to the provided filters. * @param includeTags songs must have all of these tags (if empty, includes all tags) * @param excludeTags songs cannot have any of these tags (if empty, excludes no tags) */ abstract fun getSongsByTags( includeTags: PersistentSet<String> = persistentHashSetOf(), excludeTags: PersistentSet<String> = persistentHashSetOf() ): PersistentMap<String, Song> /* -------------------------------------------- Tags -------------------------------------------- */ /** * Adds [tag] to the [Tag] map. If the [tag]'s [TagType] is new, it is added to the [TagType] * map. * @param tagName if blank, no change is made */ fun putTag(tagName: String, tag: Tag) { if (tagName.isBlank()) return _putTag(tagName, tag) } /** * Implementation for [putTag]. * @param tagName will never be blank */ protected abstract fun _putTag(tagName: String, tag: Tag) /** * Removes a [Tag] from the [Tag] map using the key [tagName]. Any [Song]s in the [Song] map * that have [tagName] will have [tagName] removed. [Song]s with the [Tag] removed, do not have * their [Song.modifyDate] time updated. * @param tagName if blank, no change is made */ fun removeTag(tagName: String) { if (tagName.isBlank()) return _removeTag(tagName) } /** * Implementation for [removeTag]. * @param tagName will never be blank */ protected abstract fun _removeTag(tagName: String) /** * Checks if [tagName] is a key used in the [Tag] map. * @param tagName if blank, returns false */ fun hasTag(tagName: String): Boolean { if (tagName.isBlank()) return false return _hasTag(tagName) } /** * Implementation for [hasTag]. * @param tagName will never be blank */ protected abstract fun _hasTag(tagName: String): Boolean /** * Retrieves the [Tag] that corresponds to the key [tagName]. * @param tagName if blank, returns null * @return null if the key does not exist */ fun getTag(tagName: String): Tag? { if (tagName.isBlank()) return null return _getTag(tagName) } /** * Implementation for [getTag]. * @param tagName will never be blank */ protected abstract fun _getTag(tagName: String): Tag? /** Retrieves a map of all the [Tag]s in the [SongLibrary]. */ abstract fun getAllTags(): PersistentMap<String, Tag> /* ------------------------------------------ Tag Types ----------------------------------------- */ /** * Adds [tagType] to the [TagType] map. * @param tagTypeName if blank, no change is made */ fun putTagType(tagTypeName: String, tagType: TagType) { if (tagTypeName.isBlank()) return _putTagType(tagTypeName, tagType) } /** * Implementation for [putTagType]. * @param tagTypeName will never be blank */ protected abstract fun _putTagType(tagTypeName: String, tagType: TagType) /** * Removes a [TagType] from the [TagType] map using the key [tagTypeName]. Any [Tag]s in the * [Tag] map that have [tagTypeName] will have their type set to null. * @param tagTypeName if blank, no change is made */ fun removeTagType(tagTypeName: String) { if (tagTypeName.isBlank()) return _removeTagType(tagTypeName) } /** * Implementation for [removeTagType]. * @param tagTypeName will never be blank */ protected abstract fun _removeTagType(tagTypeName: String) /** * Checks if [tagTypeName] is a key used in the [TagType] map. * @param tagTypeName if blank, returns false */ fun hasTagType(tagTypeName: String): Boolean { if (tagTypeName.isBlank()) return false return _hasTagType(tagTypeName) } /** * Implementation for [hasTagType]. * @param tagTypeName will never be blank */ protected abstract fun _hasTagType(tagTypeName: String): Boolean /** * Retrieves the [TagType] that corresponds to the key [tagTypeName]. * @param tagTypeName if blank, returns null * @return null if the key does not exist */ fun getTagType(tagTypeName: String): TagType? { if (tagTypeName.isBlank()) return null return _getTagType(tagTypeName) } /** * Implementation for [getTagType]. * @param tagTypeName will never be blank */ protected abstract fun _getTagType(tagTypeName: String): TagType? /** Retrieves a map of all the [TagType]s in the [SongLibrary]. */ abstract fun getAllTagTypes(): PersistentMap<String, TagType> /* -------------------------------------------- Data -------------------------------------------- */ /** * Adds [value] to the data map. * @param key if blank, no change is made */ fun putData(key: String, value: String) { if (key.isBlank()) return _putData(key, value) } /** * Implementation for [putData]. * @param key will never be blank */ protected abstract fun _putData(key: String, value: String) /** * Removes an entry from the data map using [key]. * @param key if blank, no change is made */ fun removeData(key: String) { if (key.isBlank()) return _removeData(key) } /** * Implementation for [removeData]. * @param key will never be blank */ protected abstract fun _removeData(key: String) /** * Checks if [key] is a key used in the data map. * @param key if blank, returns false */ fun hasData(key: String): Boolean { if (key.isBlank()) return false return _hasData(key) } /** * Implementation for [hasData]. * @param key will never be blank */ abstract fun _hasData(key: String): Boolean /** * Retrieves the [String] from the data map that corresponds to [key]. * @param key if blank, returns null * @return null if the key does not exist */ fun getData(key: String): String? { if (key.isBlank()) return null return _getData(key) } /** * Implementation for [getData]. * @param key will never be blank */ abstract fun _getData(key: String): String? /** Retrieves a map of all the data [String]s in the [SongLibrary]. */ abstract fun getAllData(): PersistentMap<String, String> }
0
Kotlin
0
1
32cfd709c76734b690ce2999e87f95c92e4cfb08
10,712
TaggedMusic
MIT License
android/src/main/kotlin/me/yohom/amapbase/search/SearchModels.kt
CaiJingLong
160,487,654
false
null
package me.yohom.amapbase.search import android.content.Context import com.amap.api.services.core.PoiItem import com.amap.api.services.core.SuggestionCity import com.amap.api.services.geocoder.GeocodeAddress import com.amap.api.services.geocoder.GeocodeQuery import com.amap.api.services.geocoder.GeocodeResult import com.amap.api.services.poisearch.* import com.amap.api.services.route.* import com.amap.api.services.routepoisearch.RoutePOIItem import com.amap.api.services.routepoisearch.RoutePOISearch import com.amap.api.services.routepoisearch.RoutePOISearchQuery import com.amap.api.services.routepoisearch.RoutePOISearchResult class LatLng( val latitude: Double, val longitude: Double ) class RoutePlanParam( /// 起点 val from: LatLng, /// 终点 val to: LatLng, /// 计算路径的模式,可选,默认为速度优先=0 val mode: Int, /// 途经点,可选 val passedByPoints: List<LatLng>?, /// 避让区域,可选,支持32个避让区域,每个区域最多可有16个顶点。如果是四边形则有4个坐标点,如果是五边形则有5个坐标点 val avoidPolygons: List<List<LatLng>>?, /// 避让道路,只支持一条避让道路,避让区域和避让道路同时设置,只有避让道路生效 val avoidRoad: String? ) { override fun toString(): String { return "RoutePlanParam(from=$from, to=$to, mode=$mode, passedByPoints=$passedByPoints, avoidPolygons=$avoidPolygons, avoidRoad='$avoidRoad')" } } //region UnifiedDriveRouteResult internal class UnifiedDriveRouteResult(driveRouteResult: DriveRouteResult) { /// 起始 val startPos: LatLng = driveRouteResult.startPos.toLatLng() /// 终点 val targetPos: LatLng = driveRouteResult.targetPos.toLatLng() /// 打的费用 val taxiCost: Double = driveRouteResult.taxiCost.toDouble() /// 路段 val paths: List<UnifiedDrivePath> = driveRouteResult.paths.map { UnifiedDrivePath(it) } } class UnifiedDrivePath(drivePath: DrivePath) { val strategy: String = drivePath.strategy val tolls: Double = drivePath.tolls.toDouble() val tollDistance: Double = drivePath.tollDistance.toDouble() val totalTrafficlights: Int = drivePath.totalTrafficlights val steps: List<UnifiedDriveStep> = drivePath.steps.map { UnifiedDriveStep(it) } val restriction: Int = drivePath.restriction } class UnifiedDriveStep(driveStep: DriveStep) { val instruction: String = driveStep.instruction val orientation: String = driveStep.orientation val road: String = driveStep.road val distance: Double = driveStep.distance.toDouble() val tolls: Double = driveStep.tolls.toDouble() val tollDistance: Double = driveStep.tollDistance.toDouble() val tollRoad: String = driveStep.tollRoad val duration: Double = driveStep.duration.toDouble() val polyline: List<LatLng> = driveStep.polyline.map { it.toLatLng() } val action: String = driveStep.action val assistantAction: String = driveStep.assistantAction val routeSearchCityList: List<UnifiedRouteSearchCity> = driveStep.routeSearchCityList.map { UnifiedRouteSearchCity(it) } val TMCs: List<UnifiedTMC> = driveStep.tmCs.map { UnifiedTMC(it) } } class UnifiedRouteSearchCity(routeSearchCity: RouteSearchCity) { val districts: List<UnifiedDistrict> = routeSearchCity.districts.map { UnifiedDistrict(it) } } class UnifiedTMC(tmc: TMC) { val distance: Int = tmc.distance val status: String = tmc.status val polyline: List<LatLng> = tmc.polyline.map { it.toLatLng() } } class UnifiedDistrict(district: District) { val districtName: String = district.districtName val districtAdcode: String = district.districtAdcode } //endregion //region UnifiedGeocodeResult class UnifiedGeocodeResult(geocodeResult: GeocodeResult) { val geocodeQuery: UnifiedGeocodeQuery = UnifiedGeocodeQuery(geocodeResult.geocodeQuery) val geocodeAddressList: List<UnifiedGeocodeAddress> = geocodeResult.geocodeAddressList.map { UnifiedGeocodeAddress(it) } } class UnifiedGeocodeAddress(geocodeAddress: GeocodeAddress) { val formatAddress: String = geocodeAddress.formatAddress val province: String = geocodeAddress.province val city: String = geocodeAddress.city val district: String = geocodeAddress.district val township: String = geocodeAddress.township val neighborhood: String = geocodeAddress.neighborhood val building: String = geocodeAddress.building val adcode: String = geocodeAddress.adcode val latLng: LatLng = geocodeAddress.latLonPoint.toLatLng() val level: String = geocodeAddress.level } class UnifiedGeocodeQuery(geocodeQuery: GeocodeQuery) { val locationName: String = geocodeQuery.locationName val city: String = geocodeQuery.city } //endregion //region UnifiedPoiItem class UnifiedPoiItem(poiItem: PoiItem) { val businessArea: String? = poiItem.businessArea val adName: String? = poiItem.adName val cityName: String? = poiItem.cityName val provinceName: String? = poiItem.provinceName val typeDes: String? = poiItem.typeDes val tel: String? = poiItem.tel val adCode: String? = poiItem.adCode val poiId: String? = poiItem.poiId val distance: Int? = poiItem.distance val title: String? = poiItem.title val snippet: String? = poiItem.snippet val latLonPoint: LatLng? = poiItem.latLonPoint?.toLatLng() val cityCode: String? = poiItem.cityCode val enter: LatLng? = poiItem.enter?.toLatLng() val exit: LatLng? = poiItem.exit?.toLatLng() val website: String? = poiItem.website val postcode: String? = poiItem.postcode val email: String? = poiItem.email val direction: String? = poiItem.direction val isIndoorMap: Boolean? = poiItem.isIndoorMap val provinceCode: String? = poiItem.provinceCode val parkingType: String? = poiItem.parkingType val subPois: List<UnifiedSubPoiItem> = poiItem.subPois?.map { UnifiedSubPoiItem(it) } ?: listOf() val indoorData: UnifiedIndoorData? = if (poiItem.indoorData != null) UnifiedIndoorData(poiItem.indoorData) else null val photos: List<UnifiedPhoto> = poiItem.photos?.map { UnifiedPhoto(it) } ?: listOf() val poiExtension: UnifiedPoiItemExtension? = if (poiItem.poiExtension != null) UnifiedPoiItemExtension(poiItem.poiExtension) else null val typeCode: String? = poiItem.typeCode val shopID: String? = poiItem.shopID } class UnifiedPoiResult(poiResult: PoiResult) { val pageCount: Int? = poiResult.pageCount /** * 暂未支持 */ val query: PoiSearch.Query = poiResult.query private val bound: UnifiedSearchBound? = if (poiResult.bound != null) UnifiedSearchBound(poiResult.bound) else null private val pois: List<UnifiedPoiItem> = poiResult.pois?.map { UnifiedPoiItem(it) } ?: listOf() private val searchSuggestionKeywords: List<String> = poiResult.searchSuggestionKeywords ?: listOf() private val searchSuggestionCitys: List<UnifiedSuggestionCity> = poiResult.searchSuggestionCitys?.map { UnifiedSuggestionCity(it) } ?: listOf() } class UnifiedSubPoiItem(subPoiItem: SubPoiItem) { val poiId: String? = subPoiItem.poiId val title: String? = subPoiItem.title val subName: String? = subPoiItem.subName val distance: Int? = subPoiItem.distance val latLonPoint: LatLng? = subPoiItem.latLonPoint?.toLatLng() val snippet: String? = subPoiItem.snippet val subTypeDes: String? = subPoiItem.subTypeDes } class UnifiedIndoorData(indoorData: IndoorData) { val poiId: String? = indoorData.poiId val floor: Int? = indoorData.floor val floorName: String? = indoorData.floorName } class UnifiedPhoto(photo: Photo) { val title: String? = photo.title val url: String? = photo.url } class UnifiedPoiItemExtension(poiItemExtension: PoiItemExtension) { val opentime: String? = poiItemExtension.opentime val rating: String? = poiItemExtension.getmRating() } class UnifiedSuggestionCity(suggestionCity: SuggestionCity) { val cityName: String? = suggestionCity.cityName val cityCode: String? = suggestionCity.cityCode val adCode: String? = suggestionCity.adCode val suggestionNum: Int? = suggestionCity.suggestionNum } //endregion //region UnifiedPoiSearchQuery class UnifiedPoiSearchQuery( /// 查询字符串,多个关键字用“|”分割 private val query: String, /// 待查询建筑物的标识 private val building: String?, /// 待查分类组合 private val category: String?, /// 待查城市(地区)的电话区号 private val city: String, /// 设置查询的是第几页,从0开始 private val pageNum: Int, /// 设置的查询页面的结果数目 private val pageSize: Int, /// 是否严格按照设定城市搜索 private val cityLimit: Boolean, /// 是否按照父子关系展示POI private val requireSubPois: Boolean, /// 是否按照距离排序 private val distanceSort: Boolean, /// 设置的经纬度 private val location: LatLng?, /// 搜索边界, 周边检索使用 private val searchBound: UnifiedSearchBound? ) { /** * 关键字搜索 */ fun toPoiSearch(context: Context): PoiSearch { return PoiSearch(context, PoiSearch.Query(query, category, city).apply { building = [email protected] pageNum = [email protected] pageSize = [email protected] cityLimit = [email protected] requireSubPois(requireSubPois) isDistanceSort = [email protected] location = [email protected]?.toLatLonPoint() }) } /** * 周边检索 */ fun toPoiSearchBound(context: Context): PoiSearch { return PoiSearch(context, PoiSearch.Query(query, category, city).apply { building = [email protected] pageNum = [email protected] pageSize = [email protected] cityLimit = [email protected] requireSubPois(requireSubPois) isDistanceSort = [email protected] location = [email protected]?.toLatLonPoint() }).apply { bound = searchBound?.toSearchBoundCenterRange() } } /** * 多边形内检索 */ fun toPoiSearchPolygon(context: Context): PoiSearch { return PoiSearch(context, PoiSearch.Query(query, category, city).apply { building = [email protected] pageNum = [email protected] pageSize = [email protected] cityLimit = [email protected] requireSubPois(requireSubPois) isDistanceSort = [email protected] location = [email protected]?.toLatLonPoint() }).apply { bound = searchBound?.toSearchBoundPolygon() } } } //endregion //region UnifiedRoutePoiSearchQuery class UnifiedRoutePoiSearchQuery( private val from: LatLng, private val to: LatLng, private val mode: Int, private val searchType: Int, private val range: Int, private val polylines: List<LatLng> ) { fun toRoutePoiSearchLine(context: Context): RoutePOISearch { return RoutePOISearch( context, RoutePOISearchQuery( from.toLatLonPoint(), to.toLatLonPoint(), mode, when (searchType) { 0 -> RoutePOISearch.RoutePOISearchType.TypeGasStation 1 -> RoutePOISearch.RoutePOISearchType.TypeMaintenanceStation 2 -> RoutePOISearch.RoutePOISearchType.TypeATM 3 -> RoutePOISearch.RoutePOISearchType.TypeToilet 4 -> RoutePOISearch.RoutePOISearchType.TypeFillingStation 5 -> RoutePOISearch.RoutePOISearchType.TypeServiceArea else -> throw IllegalArgumentException() }, range ) ) } fun toRoutePoiSearchPolygon(context: Context): RoutePOISearch { return RoutePOISearch( context, RoutePOISearchQuery( polylines.map { it.toLatLonPoint() }, when (searchType) { 0 -> RoutePOISearch.RoutePOISearchType.TypeGasStation 1 -> RoutePOISearch.RoutePOISearchType.TypeMaintenanceStation 2 -> RoutePOISearch.RoutePOISearchType.TypeATM 3 -> RoutePOISearch.RoutePOISearchType.TypeToilet 4 -> RoutePOISearch.RoutePOISearchType.TypeFillingStation 5 -> RoutePOISearch.RoutePOISearchType.TypeServiceArea else -> throw IllegalArgumentException() }, range ) ) } } //endregion //region UnifiedRoutePoiSearchResult class UnifiedRoutePoiSearchResult(routePOISearchResult: RoutePOISearchResult) { private val routePoiList: List<UnifiedRoutePOIItem> = routePOISearchResult.routePois?.map { UnifiedRoutePOIItem(it) } ?: listOf() private val query: RoutePOISearchQuery = routePOISearchResult.query } private class UnifiedRoutePOIItem(poiItem: RoutePOIItem) { val id: String = poiItem.id val title: String = poiItem.title val point: LatLng? = poiItem.point?.toLatLng() val distance: Float = poiItem.distance val duration: Float = poiItem.duration } //endregion class UnifiedSearchBound(searchBound: PoiSearch.SearchBound) { val lowerLeft: LatLng? = searchBound.lowerLeft?.toLatLng() val upperRight: LatLng? = searchBound.upperRight?.toLatLng() private val center: LatLng? = searchBound.center?.toLatLng() private val range: Int? = searchBound.range val shape: String? = searchBound.shape val isDistanceSort: Boolean? = searchBound.isDistanceSort private val polyGonList: List<LatLng> = searchBound.polyGonList?.map { it.toLatLng() } ?: listOf() /** * 中心点 + 半径范围 */ fun toSearchBoundCenterRange(): PoiSearch.SearchBound { return PoiSearch.SearchBound(center?.toLatLonPoint(), range!!) } /** * 多边形搜索 */ fun toSearchBoundPolygon(): PoiSearch.SearchBound { return PoiSearch.SearchBound(polyGonList.map { it.toLatLonPoint() }) } }
1
null
2
3
1197e04035d6b004e7f41f659200c2bc1427b079
14,448
amap_base_flutter
Apache License 2.0
app/src/main/java/com/bilal/finalproject/SplashScreenActivity.kt
muhBilal
559,548,444
false
null
package com.bilal.finalproject import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler class SplashScreenActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash_screen) supportActionBar?.hide() val handler = Handler() handler.postDelayed({ val intent = Intent(this, MainActivity::class.java) startActivity(intent) finish() },1000) } }
0
Kotlin
0
0
5593ea8cd74190c45d05fc3aa05cceefa2589fda
609
movie
MIT License
JetpackMvvm/src/main/java/me/hgj/jetpackmvvm/exception/ApiException.kt
aii1991
521,137,839
false
{"Kotlin": 508643, "Java": 46216}
package me.hgj.jetpackmvvm.exception /** * @author zjh * 2022/6/20 */ sealed class ApiException { class NotLoginException(val code: Int = 1001,val msg: String = "please login"): Exception(msg) class ReqErrException(val code:Int = 1002, val msg: String) : Exception(msg) }
0
Kotlin
0
0
49d8c85b5ed3fb4fe067c2cce589242324bd15d0
285
kt-wanandroid
MIT License
verify/src/main/java/org/who/ddccverifier/verify/divoc/jsonldcrypto/RsaPS256BouncyCastlePublicKeyVerifier.kt
WorldHealthOrganization
430,942,275
false
{"Kotlin": 240670, "HTML": 6961, "CSS": 3544, "Procfile": 68}
package org.who.ddccverifier.verify.divoc.jsonldcrypto import com.danubetech.keyformats.crypto.PublicKeyVerifier import com.danubetech.keyformats.jose.JWSAlgorithm import com.nimbusds.jose.crypto.bc.BouncyCastleProviderSingleton import java.security.PublicKey import java.security.Signature import java.security.spec.MGF1ParameterSpec import java.security.spec.PSSParameterSpec /** * Override com.danubetech.keyformats.crypto.impl.RSA_PS256_PublicKeyVerifier to force * the use of BouncyCastle's provider */ class RsaPS256BouncyCastlePublicKeyVerifier(publicKey: PublicKey) : PublicKeyVerifier<PublicKey>(publicKey, JWSAlgorithm.PS256) { public override fun verify(content: ByteArray, signature: ByteArray): Boolean { val pssParameterSpec = PSSParameterSpec("SHA256", "MGF1", MGF1ParameterSpec.SHA256, 32, 1) val jcaSignature = Signature.getInstance("SHA256withRSAandMGF1", BouncyCastleProviderSingleton.getInstance()) jcaSignature.setParameter(pssParameterSpec) jcaSignature.initVerify(publicKey) jcaSignature.update(content) return jcaSignature.verify(signature) } }
0
Kotlin
3
9
0dc9d8b67da73ce6b93a62ee406f98ac7e2af9ce
1,134
ddcc-validator
Apache License 2.0
idea/testData/fir/multiModule/basic/m1_java/base.kt
android
263,405,600
true
null
package hello class Hello(val msg: String) class Test(val set: java.util.Set<*>)
0
Kotlin
37
316
74126637a097f5e6b099a7b7a4263468ecfda144
82
kotlin
Apache License 2.0
app/src/main/java/com/marsapi/overview/OverviewFragment.kt
zuzannakuzniar
721,152,070
false
null
package com.example.android.marsphotos.overview import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import com.example.android.marsphotos.databinding.FragmentOverviewBinding class OverviewFragment : Fragment() { private val viewModel: OverviewViewModel by viewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val binding = FragmentOverviewBinding.inflate(inflater) binding.lifecycleOwner = this binding.viewModel = viewModel binding.photosGrid.adapter = PhotoGridAdapter() return binding.root } }
0
Kotlin
0
0
f96680794cd32c4bf3b969dc4b0c4dcc157e6163
792
marsapi
Apache License 2.0
app/src/main/java/info/dvkr/screenstream/ui/tabs/settings/app/settings/general/NightMode.kt
dkrivoruchko
63,582,643
false
null
package info.dvkr.screenstream.ui.tabs.settings.app.settings.general import android.content.res.Resources import android.os.Build import androidx.annotation.ArrayRes import androidx.appcompat.app.AppCompatDelegate import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.materialIcon import androidx.compose.material.icons.materialPath import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.RadioButton import androidx.compose.material3.Text import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.runtime.Composable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.stringArrayResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.compose.collectAsStateWithLifecycle import info.dvkr.screenstream.R import info.dvkr.screenstream.common.ModuleSettings import info.dvkr.screenstream.common.settings.AppSettings import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import org.koin.compose.koinInject internal object NightMode : ModuleSettings.Item { override val id: String = AppSettings.Key.NIGHT_MODE.name override val position: Int = 1 override val available: Boolean = true override fun has(resources: Resources, text: String): Boolean = with(resources) { getString(R.string.app_pref_night_mode).contains(text, ignoreCase = true) || getStringArray(nightModeOptionsRes).any { it.contains(text, ignoreCase = true) } } @Composable override fun ItemUI(horizontalPadding: Dp, coroutineScope: CoroutineScope, onDetailShow: () -> Unit) = NightModeUI(horizontalPadding, onDetailShow) @Composable override fun DetailUI(headerContent: @Composable (String) -> Unit) = NightModeDetailUI(headerContent) @ArrayRes internal val nightModeOptionsRes = if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) R.array.app_pref_night_mode_options_api21_28 else R.array.app_pref_night_mode_options_api29 internal fun getNightModeIndex(@AppCompatDelegate.NightMode nightMode: Int): Int = nightModesCompat.firstOrNull { it.mode == nightMode }?.index ?: nightModesCompat[1].index @AppCompatDelegate.NightMode internal fun getNightModeByIndex(index: Int): Int = nightModesCompat[index].mode private data class NightMode(val index: Int, @AppCompatDelegate.NightMode val mode: Int) private val nightModesCompat = if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) listOf( NightMode(0, AppCompatDelegate.MODE_NIGHT_YES), NightMode(1, AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY), NightMode(2, AppCompatDelegate.MODE_NIGHT_NO), ) else listOf( NightMode(0, AppCompatDelegate.MODE_NIGHT_YES), NightMode(1, AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM), NightMode(2, AppCompatDelegate.MODE_NIGHT_NO) ) } @Composable private fun NightModeUI( horizontalPadding: Dp, onDetailShow: () -> Unit, appSettings: AppSettings = koinInject() ) { val appSettingsState = appSettings.data.collectAsStateWithLifecycle() val nightModeOptions = stringArrayResource(id = NightMode.nightModeOptionsRes) val nightModeSummary = remember { derivedStateOf { nightModeOptions[NightMode.getNightModeIndex(appSettingsState.value.nightMode)] } } Row( modifier = Modifier .clickable(role = Role.Button) { onDetailShow.invoke() } .padding(horizontal = horizontalPadding + 16.dp), verticalAlignment = Alignment.CenterVertically ) { Icon( imageVector = Icon_ThemeLightDark, contentDescription = stringResource(id = R.string.app_pref_night_mode), modifier = Modifier.padding(end = 16.dp) ) Column(modifier = Modifier.weight(1F)) { Text( text = stringResource(id = R.string.app_pref_night_mode), modifier = Modifier.padding(top = 8.dp, bottom = 2.dp), fontSize = 18.sp, style = MaterialTheme.typography.bodyLarge ) Text( text = nightModeSummary.value, modifier = Modifier.padding(top = 2.dp, bottom = 8.dp), style = MaterialTheme.typography.bodyMedium ) } } } @Composable private fun NightModeDetailUI( headerContent: @Composable (String) -> Unit, scope: CoroutineScope = rememberCoroutineScope(), appSettings: AppSettings = koinInject() ) { val appSettingsState = appSettings.data.collectAsStateWithLifecycle() val nightModeOptions = stringArrayResource(id = NightMode.nightModeOptionsRes) val nightModeIndex = remember { derivedStateOf { NightMode.getNightModeIndex(appSettingsState.value.nightMode) } } Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally ) { headerContent.invoke(stringResource(id = R.string.app_pref_night_mode)) Column( modifier = Modifier .widthIn(max = 480.dp) .padding(vertical = 8.dp) .selectableGroup() .verticalScroll(rememberScrollState()) ) { nightModeOptions.forEachIndexed { index, text -> Row( modifier = Modifier .selectable( selected = nightModeIndex.value == index, onClick = { if (nightModeIndex.value != index) { scope.launch { appSettings.updateData { copy(nightMode = NightMode.getNightModeByIndex(index)) } } } }, role = Role.RadioButton ) .fillMaxWidth() .padding(horizontal = 24.dp) .defaultMinSize(minHeight = 48.dp) .minimumInteractiveComponentSize(), verticalAlignment = Alignment.CenterVertically ) { RadioButton(selected = nightModeIndex.value == index, onClick = null) Text(text = text, modifier = Modifier.padding(start = 16.dp)) } } } } } private val Icon_ThemeLightDark: ImageVector = materialIcon(name = "ThemeLightDark") { materialPath { verticalLineToRelative(0.0F) moveTo(7.5F, 2.0F) curveTo(5.71F, 3.15F, 4.5F, 5.18F, 4.5F, 7.5F) curveTo(4.5F, 9.82F, 5.71F, 11.85F, 7.53F, 13.0F) curveTo(4.46F, 13.0F, 2.0F, 10.54F, 2.0F, 7.5F) arcTo(5.5F, 5.5F, 0.0F, false, true, 7.5F, 2.0F) moveTo(19.07F, 3.5F) lineTo(20.5F, 4.93F) lineTo(4.93F, 20.5F) lineTo(3.5F, 19.07F) lineTo(19.07F, 3.5F) moveTo(12.89F, 5.93F) lineTo(11.41F, 5.0F) lineTo(9.97F, 6.0F) lineTo(10.39F, 4.3F) lineTo(9.0F, 3.24F) lineTo(10.75F, 3.12F) lineTo(11.33F, 1.47F) lineTo(12.0F, 3.1F) lineTo(13.73F, 3.13F) lineTo(12.38F, 4.26F) lineTo(12.89F, 5.93F) moveTo(9.59F, 9.54F) lineTo(8.43F, 8.81F) lineTo(7.31F, 9.59F) lineTo(7.65F, 8.27F) lineTo(6.56F, 7.44F) lineTo(7.92F, 7.35F) lineTo(8.37F, 6.06F) lineTo(8.88F, 7.33F) lineTo(10.24F, 7.36F) lineTo(9.19F, 8.23F) lineTo(9.59F, 9.54F) moveTo(19.0F, 13.5F) arcTo(5.5F, 5.5F, 0.0F, false, true, 13.5F, 19.0F) curveTo(12.28F, 19.0F, 11.15F, 18.6F, 10.24F, 17.93F) lineTo(17.93F, 10.24F) curveTo(18.6F, 11.15F, 19.0F, 12.28F, 19.0F, 13.5F) moveTo(14.6F, 20.08F) lineTo(17.37F, 18.93F) lineTo(17.13F, 22.28F) lineTo(14.6F, 20.08F) moveTo(18.93F, 17.38F) lineTo(20.08F, 14.61F) lineTo(22.28F, 17.15F) lineTo(18.93F, 17.38F) moveTo(20.08F, 12.42F) lineTo(18.94F, 9.64F) lineTo(22.28F, 9.88F) lineTo(20.08F, 12.42F) moveTo(9.63F, 18.93F) lineTo(12.4F, 20.08F) lineTo(9.87F, 22.27F) lineTo(9.63F, 18.93F) close() } }
17
null
310
1,482
d8a1f5eec5b212f15e2270710d05888993c18156
9,401
ScreenStream
MIT License
app/src/main/java/cc/colorcat/viewmodel/sample/AActivity.kt
ccolorcat
639,976,271
false
null
package cc.colorcat.viewmodel.sample import androidx.appcompat.app.AppCompatActivity /** * Author: ccolorcat * Date: 2023-05-14 * GitHub: https://github.com/ccolorcat */ class AActivity : BaseActivity() { override val nextActivity: Class<out AppCompatActivity>? get() = BActivity::class.java }
0
Kotlin
0
0
4ca4cff2929bf31089702bc53ec3ae47961feaf0
311
cached-view-model
Apache License 2.0
app/src/main/java/me/banes/chris/tivi/ui/epoxymodels/HeaderModel.kt
takahirom
115,065,306
true
{"Kotlin": 277296, "Shell": 387}
/* * Copyright 2017 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.banes.chris.tivi.ui.epoxymodels import android.support.annotation.StringRes import android.view.View import com.airbnb.epoxy.EpoxyAttribute import com.airbnb.epoxy.EpoxyModelClass import com.airbnb.epoxy.EpoxyModelWithHolder import kotlinx.android.synthetic.main.view_holder_header.* import me.banes.chris.tivi.R @EpoxyModelClass(layout = R.layout.view_holder_header) abstract class HeaderModel : EpoxyModelWithHolder<TiviEpoxyHolder>() { @EpoxyAttribute @StringRes var title = 0 @EpoxyAttribute(EpoxyAttribute.Option.DoNotHash) var clickListener: View.OnClickListener? = null override fun bind(holder: TiviEpoxyHolder) { holder.header_title.setText(title) holder.header_more.setOnClickListener(clickListener) } override fun getSpanSize(totalSpanCount: Int, position: Int, itemCount: Int) = totalSpanCount }
0
Kotlin
0
0
240cf0115ef533d6aef9e7b44d522c4067687f5a
1,455
tivi
Apache License 2.0
Rejestrator/app/src/main/java/com/example/rejestrator/view/viewmodel/Admin/AdminLogsListViewModel.kt
rafgasinski
356,974,392
false
null
package com.example.rejestrator.view.viewmodel.Admin import android.app.Application import android.util.Log import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.example.rejestrator.view.model.entities.EmployeeListData import com.example.rejestrator.view.model.entities.LoginData import com.example.rejestrator.view.model.repositories.ApiRepository import kotlinx.coroutines.launch import retrofit2.Call import retrofit2.Callback import retrofit2.Response class AdminLogsListViewModel(application: Application): AndroidViewModel(application) { private val _allLogs: MutableLiveData<ArrayList<LoginData>> = MutableLiveData() val allLogs: LiveData<ArrayList<LoginData>> get()=_allLogs private val _filteredAllLogs: MutableLiveData<ArrayList<LoginData>> = MutableLiveData() val filteredAllLogs: LiveData<ArrayList<LoginData>> get()=_filteredAllLogs var employeeList1: ArrayList<EmployeeListData> = arrayListOf() var employeeList2: java.util.ArrayList<String> = arrayListOf() fun getAllLogs() { viewModelScope.launch { _allLogs.value = ApiRepository.getAllLogs() _filteredAllLogs.value = ApiRepository.getAllLogs() } } fun getAllEmployeesForTaskAdding() { ApiRepository.getAllEmployees().enqueue(object : Callback<ArrayList<EmployeeListData>>{ override fun onFailure(call: Call<ArrayList<EmployeeListData>>, t: Throwable) { } override fun onResponse(call: Call<ArrayList<EmployeeListData>>, response: Response<ArrayList<EmployeeListData>>) { employeeList1 = response.body()!! employeeList2.clear() employeeList1.forEach(){ employeeList2.add(it.toString()) } } }) } fun insertEmployee(id : String, pin : String, name : String, surname : String, shift : String) { viewModelScope.launch { ApiRepository.insertEmployee(id, pin, name, surname, shift) } } fun insertAdmin(id : String, username: String, password: String, name : String, surname : String) { viewModelScope.launch { ApiRepository.insertAdmin(id, username, password, name, surname) } } }
0
null
0
0
6972cb8658324a9c032554298a2b9f2014e924fa
2,404
rejestrator-app
MIT License
app/src/sharedTest/java/org/oppia/app/story/StoryFragmentTest.kt
netomarin
235,442,298
true
{"Kotlin": 1351971}
package org.oppia.app.story import android.content.Context import android.content.Intent import android.content.res.Resources import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import androidx.test.core.app.ActivityScenario.launch import androidx.test.core.app.ApplicationProvider import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.contrib.RecyclerViewActions.scrollToPosition import androidx.test.espresso.intent.Intents import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withParent import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.runners.AndroidJUnit4 import org.hamcrest.CoreMatchers.allOf import org.hamcrest.CoreMatchers.instanceOf import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.oppia.app.R import org.oppia.app.recyclerview.RecyclerViewMatcher.Companion.atPositionOnView import org.oppia.app.recyclerview.RecyclerViewMatcher.Companion.hasItemCount import org.oppia.app.story.testing.StoryFragmentTestActivity import org.oppia.domain.topic.TEST_STORY_ID_1 /** Tests for [StoryFragment]. */ @RunWith(AndroidJUnit4::class) class StoryFragmentTest { @Before fun setUp() { Intents.init() } @After fun tearDown() { Intents.release() } @Test fun testStoryFragment_clickOnToolbarNavigationButton_closeActivity() { launch<StoryFragmentTestActivity>(createTestActivityIntent(TEST_STORY_ID_1)).use { onView(withId(R.id.story_toolbar)).perform(click()) } } @Test fun testStoryFragment_toolbarTitle_isDisplayedSuccessfully() { launch<StoryFragmentTestActivity>(createTestActivityIntent(TEST_STORY_ID_1)).use { onView( allOf( instanceOf(TextView::class.java), withParent(withId(R.id.story_toolbar)) ) ).check(matches(withText("Second Story"))) } } @Test fun testStoryFragment_correctStoryCountLoadedInHeader() { launch<StoryFragmentTestActivity>(createTestActivityIntent(TEST_STORY_ID_1)).use { val headerString: String = getResources().getQuantityString(R.plurals.story_total_chapters, 3, 1, 3) onView(withId(R.id.story_chapter_list)).perform(scrollToPosition<RecyclerView.ViewHolder>(0)) onView(atPositionOnView(R.id.story_chapter_list, 0, R.id.story_progress_chapter_completed_text)).check( matches( withText(headerString) ) ) } } @Test fun testStoryFragment_correctNumberOfStoriesLoadedInRecyclerView() { launch<StoryFragmentTestActivity>(createTestActivityIntent(TEST_STORY_ID_1)).use { onView(withId(R.id.story_chapter_list)).check(hasItemCount(4)) } } private fun createTestActivityIntent(storyId: String): Intent { return StoryFragmentTestActivity.createTestActivityIntent(ApplicationProvider.getApplicationContext(), storyId) } private fun getResources(): Resources { return ApplicationProvider.getApplicationContext<Context>().resources } }
0
null
0
0
8ebd05b1d195d6d072339fa897bd400db28917c4
3,192
oppia-android
Apache License 2.0
safeToRunCore/src/main/kotlin/io/github/dllewellyn/safetorun/features/oscheck/OsCheckConstants.kt
Safetorun
274,838,056
false
null
package com.safetorun.features.oscheck /** * Constants file for OS Check providing static strings that are used * when doing OS Checks - primarily these are checks for emulator detection */ object OsCheckConstants { /** Type of board used on emulators */ const val AVD_EMULATOR_BOARD = "goldfish_x86" /** Unknown can be used for bootloaders, boards etc on emulators */ const val UNKNOWN = "unknown" /** Type of device for AVD emulator */ const val AVD_DEVICE_TYPE = "generic_x86_arm" /** Type of device for genymotion */ const val GENYMOTION_MANUFACTURER = "Genymotion" /** If the manufacturer is Xiaomi */ const val XIAOMI = "Xiaomi" }
9
Kotlin
1
8
501a06497485cb40c2b54f4d2a885fc34bcc1898
685
safe_to_run
Apache License 2.0
app/src/androidTest/java/com/brainasaservice/reviewbrowser/util/WaitInstruction.kt
damian-burke
145,307,980
false
null
package com.brainasaservice.reviewbrowser.util import com.azimolabs.conditionwatcher.Instruction class WaitInstruction(ms: Long = DEFAULT_WAIT_TIME) : Instruction() { private val endTime = System.currentTimeMillis() + ms override fun getDescription(): String = "Wait a certain amount of milliseconds." override fun checkCondition(): Boolean = endTime < System.currentTimeMillis() companion object { const val DEFAULT_WAIT_TIME = 1000L } }
0
Kotlin
0
1
ad079c64dfd2d68a4769b63cc017f22f9441f793
472
review-browser
Apache License 2.0
feature/share/src/main/java/com/xinh/share/widget/inputlayout/StartInputComponent.kt
HuynhXinh
209,346,576
false
null
package com.xinh.share.widget.inputlayout import com.xinh.share.widget.common.ViewComponent interface StartInputComponent : ViewComponent
1
Kotlin
5
19
6a704f65592b2bfbb2363697885b871209775b96
139
mvvm-clean-architecture
The Unlicense
app/src/main/java/net/yslibrary/monotweety/login/LoginController.kt
yshrsmz
69,078,478
false
null
package net.yslibrary.monotweety.login import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.bluelinelabs.conductor.ControllerChangeHandler import com.bluelinelabs.conductor.ControllerChangeType import com.bluelinelabs.conductor.RouterTransaction import com.bluelinelabs.conductor.changehandler.SimpleSwapChangeHandler import com.twitter.sdk.android.core.Callback import com.twitter.sdk.android.core.Result import com.twitter.sdk.android.core.TwitterException import com.twitter.sdk.android.core.TwitterSession import com.twitter.sdk.android.core.identity.TwitterLoginButton import io.reactivex.android.schedulers.AndroidSchedulers import net.yslibrary.monotweety.R import net.yslibrary.monotweety.analytics.Analytics import net.yslibrary.monotweety.base.ActionBarController import net.yslibrary.monotweety.base.HasComponent import net.yslibrary.monotweety.base.ObjectWatcherDelegate import net.yslibrary.monotweety.base.findById import net.yslibrary.monotweety.event.ActivityResult import net.yslibrary.monotweety.setting.SettingController import timber.log.Timber import javax.inject.Inject import kotlin.properties.Delegates class LoginController : ActionBarController(), HasComponent<LoginComponent> { override val shouldShowActionBar: Boolean = false lateinit var bindings: Bindings @set:[Inject] var viewModel by Delegates.notNull<LoginViewModel>() @set:[Inject] var objectWatcherDelegate by Delegates.notNull<ObjectWatcherDelegate>() override val component: LoginComponent by lazy { Timber.i("create LoginComponent") getComponentProvider<LoginComponent.ComponentProvider>(activity!!) .loginComponent(LoginViewModule()) } override fun onContextAvailable(context: Context) { super.onContextAvailable(context) Timber.i("onContextAvailable - LoginController") component.inject(this) analytics.viewEvent(Analytics.VIEW_LOGIN) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle? ): View { val view = inflater.inflate(R.layout.controller_login, container, false) bindings = Bindings(view) setEvents() return view } fun setEvents() { Timber.i("setEvents - LoginController") activityBus.on(ActivityResult::class) .observeOn(AndroidSchedulers.mainThread()) .bindToLifecycle() .subscribe { Timber.i("onActivityResult - LoginController, requestCode: ${it.requestCode}, resultCode: ${it.resultCode}, data: ${it.data}, extra: ${it.data?.extras}") bindings.loginButton.onActivityResult(it.requestCode, it.resultCode, it.data) } viewModel.loginCompleted .observeOn(AndroidSchedulers.mainThread()) .bindToLifecycle() .doOnNext { toast(getString(R.string.message_login_succeeded, it.userName))?.show() } .subscribe { analytics.loginCompleted() router.setRoot( RouterTransaction.with(SettingController()) .popChangeHandler(SimpleSwapChangeHandler()) .pushChangeHandler(SimpleSwapChangeHandler()) ) } viewModel.loginFailed .observeOn(AndroidSchedulers.mainThread()) .bindToLifecycle() .subscribe { showSnackBar(getString(R.string.error_login_failed)) } bindings.loginButton.callback = object : Callback<TwitterSession>() { override fun success(result: Result<TwitterSession>) { Timber.d("login success: $result") viewModel.onLoginCompleted(result.data) } override fun failure(exception: TwitterException) { Timber.e(exception, exception.message) viewModel.onLoginFailed(exception) } } } override fun onChangeEnded( changeHandler: ControllerChangeHandler, changeType: ControllerChangeType ) { super.onChangeEnded(changeHandler, changeType) objectWatcherDelegate.handleOnChangeEnded(isDestroyed, changeType) } override fun onDestroy() { super.onDestroy() objectWatcherDelegate.handleOnDestroy() } inner class Bindings(view: View) { val loginButton = view.findById<TwitterLoginButton>(R.id.login) } }
10
null
25
113
7b5b5fe9e0b1dd4667a024d5e22947132b01c426
4,570
monotweety
Apache License 2.0
common/src/main/java/cn/lvsong/lib/library/utils/ClickUtil.kt
Jooyer
243,921,264
false
null
package cn.lvsong.lib.library.utils import android.view.View /** * * @ProjectName: android * @ClassName: Click * @Description: 各种点击拓展 * @Author: Jooyer * @CreateDate: 2020/6/2 13:52 * @UpdateUser: * @UpdateDate: * @UpdateRemark: * @Version: 1.0 * https://www.jianshu.com/p/7118226ecba9 */ /* 基本用法 View.withTrigger().click { // 礼物弹框 } */ /*** * 设置延迟时间的View扩展 , 此方法不合适放在列表中使用, 推荐使用 clickWithTrigger * @param delay Long 延迟时间,默认600毫秒 * @return T */ fun <T : View> T.withTrigger(delay: Long = 600): T { triggerDelay = delay return this } /*** * 点击事件的View扩展, 此方法不合适放在列表中使用, 推荐使用 clickWithTrigger * @param block: (T) -> Unit 函数 * @return Unit */ fun <T : View> T.click(block: (View) -> Unit) = setOnClickListener { setOnClickListener { if (clickEnable()) { block(it as View) } } } /*** * 带延迟过滤的点击事件View扩展 * @param delay Long 延迟时间,默认600毫秒 * @param block: (T) -> Unit 函数 * @return Unit */ fun <T : View> T.clickWithTrigger(time: Long = 600, block: (View) -> Unit) { triggerDelay = time setOnClickListener { if (clickEnable()) { block(it as View) } } } private var <T : View> T.triggerLastTime: Long get() = if (getTag(1123460103) != null) getTag(1123460103) as Long else -601 set(value) { setTag(1123460103, value) } private var <T : View> T.triggerDelay: Long get() = if (getTag(1123461123) != null) getTag(1123461123) as Long else 600 set(value) { setTag(1123461123, value) } private fun <T : View> T.clickEnable(): Boolean { var flag = false val currentClickTime = System.currentTimeMillis() if (currentClickTime - triggerLastTime >= triggerDelay) { flag = true } triggerLastTime = currentClickTime return flag } /*** * 带延迟过滤的点击事件监听,见[View.OnClickListener] * 延迟时间根据triggerDelay获取:600毫秒,不能动态设置 */ interface OnLazyClickListener : View.OnClickListener { override fun onClick(view: View) { if (view.clickEnable()) { onTriggerClick(view) } } fun onTriggerClick(view: View) }
0
null
3
9
caf3c82d2e2525334e98c59607683f656c1b599b
2,154
Basics
Apache License 2.0
src/jvmTest/kotlin/software/momento/kotlin/sdk/TopicClientTest.kt
momentohq
724,323,089
false
{"Kotlin": 265819}
package software.momento.kotlin.sdk import kotlinx.coroutines.delay import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.merge import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.take import kotlinx.coroutines.flow.takeWhile import kotlinx.coroutines.flow.toCollection import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.runTest import org.junit.AfterClass import org.junit.BeforeClass import org.junit.Test import software.momento.kotlin.sdk.auth.CredentialProvider import software.momento.kotlin.sdk.config.TopicConfigurations import software.momento.kotlin.sdk.exceptions.InvalidArgumentException import software.momento.kotlin.sdk.responses.topic.TopicMessage import software.momento.kotlin.sdk.responses.topic.TopicPublishResponse import software.momento.kotlin.sdk.responses.topic.TopicSubscribeResponse import java.util.concurrent.atomic.AtomicInteger import kotlin.test.assertContentEquals import kotlin.test.assertNotNull class TopicClientTest : BaseJvmTestClass() { companion object { private lateinit var topicClient: TopicClient @JvmStatic @BeforeClass fun setUp() { topicClient = TopicClient( credentialProvider = CredentialProvider.fromEnvVar("TEST_API_KEY"), configuration = TopicConfigurations.Laptop.latest ) } @JvmStatic @AfterClass fun tearDown() { topicClient.close() } } @Test fun publishFailsWithInvalidCacheName_String() = runTest { val response = topicClient.publish("", "topic", "value") assert((response as TopicPublishResponse.Error).cause is InvalidArgumentException) } @Test fun publishFailsWithInvalidCacheName_ByteArray() = runTest { val response = topicClient.publish("", "topic", "value".encodeToByteArray()) assert((response as TopicPublishResponse.Error).cause is InvalidArgumentException) } @Test fun subscribeFailsWithInvalidCacheName_String() = runTest { val response = topicClient.subscribe("", "topic") assert((response as TopicSubscribeResponse.Error).cause is InvalidArgumentException) } @Test(timeout = 20_000) fun publishSubscribeHappyPath_String() = runBlocking { val topicName = "happyPathString" val valuesToSend = listOf("one", "two", "three", "four", "five") val messageFlow = topicClient.subscribe(cacheName, topicName) assert(messageFlow is TopicSubscribeResponse.Subscription) launch { delay(2000) for (value in valuesToSend) { val publishResponse = topicClient.publish(cacheName, topicName, value) assert(publishResponse is TopicPublishResponse.Success) delay(100) } } val receivedStrings = (messageFlow as TopicSubscribeResponse.Subscription) .take(valuesToSend.size) .toCollection(mutableListOf()) .map { it as TopicMessage.Text } .map { it.value } assertNotNull(receivedStrings) assertContentEquals(valuesToSend, receivedStrings) } @Test(timeout = 20_000) fun publishSubscribeHappyPath_Bytes() = runBlocking { val topicName = "happyPathBytes" val valuesToSend = listOf( "one".encodeToByteArray(), "two".encodeToByteArray(), "three".encodeToByteArray(), "four".encodeToByteArray(), "five".encodeToByteArray() ) val messageFlow = topicClient.subscribe(cacheName, topicName) assert(messageFlow is TopicSubscribeResponse.Subscription) launch { delay(2000) for (value in valuesToSend) { val publishResponse = topicClient.publish(cacheName, topicName, value) assert(publishResponse is TopicPublishResponse.Success) delay(100) } } val receivedByteArrays = (messageFlow as TopicSubscribeResponse.Subscription) .take(valuesToSend.size) .toCollection(mutableListOf()) .map { it as TopicMessage.Binary } .map { it.value } assertNotNull(receivedByteArrays) for (i in valuesToSend.indices) { assertContentEquals(valuesToSend[i], receivedByteArrays[i]) } } @Test(timeout = 20_000) fun publishMultipleSubscriptionsHappyPath() = runBlocking { val numTopics = 10 val messagesToPublish = 25 val topicPrefix = "multiSubscription" val subscriptionResponses = (1..numTopics).map { i -> topicClient.subscribe(cacheName, "$topicPrefix$i") }.map { response -> when (response) { is TopicSubscribeResponse.Subscription -> { response } is TopicSubscribeResponse.Error -> { throw Exception("Got an unexpected subscription response: $response") } } } launch { delay(2000) for (i in 0 until messagesToPublish) { val randomTopic = (0 until numTopics).random() + 1 val messageId = "message$i" val topic = "$topicPrefix$randomTopic" val publishResponse = topicClient.publish(cacheName, topic, messageId) assert(publishResponse is TopicPublishResponse.Success) delay(100) } for (i in 0..numTopics) { val topic = "$topicPrefix$i" val publishResponse = topicClient.publish(cacheName, topic, "done") assert(publishResponse is TopicPublishResponse.Success) delay(100) } } val receivedCount = AtomicInteger(0) val subscriptionFlows = subscriptionResponses.map { subscription -> flow { subscription.onEach { emit(it) } .takeWhile { it is TopicMessage.Text && it.value != "done" } .onEach { receivedCount.incrementAndGet() } .collect() } } val mergedFlow = merge(*subscriptionFlows.toTypedArray()) mergedFlow.collect() assert(receivedCount.get() == messagesToPublish) { "Expected $messagesToPublish messages, got $receivedCount" } } }
8
Kotlin
1
0
b722c7a0037b79aecdcd2183baa8f721be167aab
6,537
client-sdk-kotlin
Apache License 2.0
app/src/main/kotlin/com/melih/rocketscience/App.kt
MohamedGElsharkawy
217,748,879
true
{"Kotlin": 83542, "Ruby": 5912}
package com.melih.rocketscience import com.melih.core.di.DaggerCoreComponent import com.melih.rocketscience.di.DaggerAppComponent import dagger.android.AndroidInjector import dagger.android.DaggerApplication import timber.log.Timber class App : DaggerApplication() { override fun applicationInjector(): AndroidInjector<out DaggerApplication> = DaggerAppComponent.factory() .create( DaggerCoreComponent.factory() .create(this) ) override fun onCreate() { super.onCreate() Timber.plant(Timber.DebugTree()) } }
0
null
0
1
83e39400a97efdcbdfaf3fbe9607027e3fea04ff
609
Android-Kotlin-Modulerized-CleanArchitecture
Apache License 2.0
basic-auth/src/main/kotlin/ru/tinkoff/testops/droidherd/auth/BasicAuthServiceConfiguration.kt
tinkoff-mobile-tech
521,161,700
false
{"Kotlin": 106190, "Java": 54476, "Shell": 3105, "Mustache": 426}
package ru.tinkoff.testops.droidherd.auth import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import com.fasterxml.jackson.module.kotlin.registerKotlinModule import org.springframework.boot.autoconfigure.AutoConfigureOrder import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.core.Ordered import java.io.File import java.nio.file.Files import java.nio.file.Path @Configuration @AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE) @ConditionalOnMissingBean(value = [AuthService::class]) open class BasicAuthServiceConfiguration { companion object { val CREDS_PATH = "BASIC_AUTH_CREDENTIALS_PATH" val NOT_EXIST_PATH = "#not-exist#" } @Bean open fun basicAuthClients(): Map<String, BasicAuthClient> { val credentialsPath = System.getenv(CREDS_PATH) ?: NOT_EXIST_PATH if (credentialsPath == NOT_EXIST_PATH || !Files.isRegularFile(Path.of(credentialsPath))) { throw RuntimeException("No $CREDS_PATH env var specified or file not exist: $credentialsPath") } return ObjectMapper() .registerKotlinModule() .readValue<List<BasicAuthClient>>(File(credentialsPath)) .associateBy { it.client } } @Bean open fun basicAuthService(basicAuthClients: Map<String, BasicAuthClient>): AuthService { return BasicAuthService(basicAuthClients) } }
2
Kotlin
2
31
095fe2998808fc92eba1a2cf07c71787be6a735b
1,577
droidherd
Apache License 2.0
kotlin/kr/owens/ka/KoreanAsm.kt
owen151128
401,262,507
false
null
package kr.owens.ka /** * @author <EMAIL> * * Created by owen151128 on 2021/08/30 18:04 * * Providing features related to KoreanAsm class */ object KoreanAsm { private const val KOR_BASE_CODE = 44032 private const val CHO_SUNG_BASE = 588 private const val CHO_SUNG_BASE_2 = 21 private const val JUNG_SUNG_BASE = 28 // 초성 리스트. 0 ~ 18 private val CHO_SUNG_LIST = listOf( "ㄱ", "ㄲ", "ㄴ", "ㄷ", "ㄸ", "ㄹ", "ㅁ", "ㅂ", "ㅃ", "ㅅ", "ㅆ", "ㅇ", "ㅈ", "ㅉ", "ㅊ", "ㅋ", "ㅌ", "ㅍ", "ㅎ" ) // 중성 리스트. 0 ~ 20 private val JUNG_SUNG_LIST = listOf( "ㅏ", "ㅐ", "ㅑ", "ㅒ", "ㅓ", "ㅔ", "ㅕ", "ㅖ", "ㅗ", "ㅘ", "ㅙ", "ㅚ", "ㅛ", "ㅜ", "ㅝ", "ㅞ", "ㅟ", "ㅠ", "ㅡ", "ㅢ", "ㅣ" ) // 종성 리스트. 0 ~ 27 private val JONG_SUNG_LIST = listOf( " ", "ㄱ", "ㄲ", "ㄳ", "ㄴ", "ㄵ", "ㄶ", "ㄷ", "ㄹ", "ㄺ", "ㄻ", "ㄼ", "ㄽ", "ㄾ", "ㄿ", "ㅀ", "ㅁ", "ㅂ", "ㅄ", "ㅅ", "ㅆ", "ㅇ", "ㅈ", "ㅊ", "ㅋ", "ㅌ", "ㅍ", "ㅎ" ) fun disAsm(text: String): List<String> { val result = mutableListOf<String>() for (s in text) { val code = s.code - KOR_BASE_CODE val choSungIndex = code / CHO_SUNG_BASE val jungSungIndex = (code - CHO_SUNG_BASE * choSungIndex) / JUNG_SUNG_BASE val jongSungIndex = (code - CHO_SUNG_BASE * choSungIndex - JUNG_SUNG_BASE * jungSungIndex) result.add(CHO_SUNG_LIST[choSungIndex]) result.add(JUNG_SUNG_LIST[jungSungIndex]) result.add(JONG_SUNG_LIST[jongSungIndex]) } return result } fun asm(korList: List<String>): String { var result = "" var unicode = 0 for (i in korList.indices) { when (i % 3) { 0 -> unicode = CHO_SUNG_LIST.indexOf(korList[i]) * CHO_SUNG_BASE_2 1 -> unicode = (unicode + JUNG_SUNG_LIST.indexOf(korList[i])) * JUNG_SUNG_BASE 2 -> { unicode += JONG_SUNG_LIST.indexOf(korList[i]) + KOR_BASE_CODE result += unicode.toChar().toString() } } } return result } }
1
null
1
1
2f5ab06995e9e57db79350d34032385b40ff796e
2,625
korean_asm
MIT License
jext-datadog-apm/jext-datadog-apm-ktor/src/main/kotlin/kr/jadekim/jext/apm/datadog/ktor/adapter/HeadersBuilderTextMapAdapter.kt
jdekim43
421,788,472
false
null
package kr.jadekim.jext.apm.datadog.ktor.adapter import io.ktor.http.* import io.opentracing.propagation.TextMap internal class HeadersBuilderTextMapAdapter(private val headers: HeadersBuilder) : TextMap { override fun put(key: String, value: String) { headers.append(key, value) } override fun iterator(): MutableIterator<MutableMap.MutableEntry<String, String>> { return headers.entries() .filter { (_, values) -> values.isNotEmpty() } .associate { (key, values) -> key to values.first() } .toMutableMap() //This is only due to opentracing api using mutable map Iterator .iterator() } } fun HeadersBuilder.asTextMap(): TextMap = HeadersBuilderTextMapAdapter(this)
0
Kotlin
1
0
f821862ee1b4b2d6857af12714ff03a7ef3544a7
753
jext
Apache License 2.0
app/src/main/java/com/example/moviesdataapp/di/modules/MainActivityModule.kt
raja-arumugam
646,155,341
false
null
package com.example.moviesdataapp.di.modules import com.example.moviesdataapp.ui.activity.MainActivity import dagger.Module import dagger.android.ContributesAndroidInjector @Module abstract class MainActivityModule { @ContributesAndroidInjector(modules = [FragmentBuildersModule::class]) abstract fun contributeMainActivity(): MainActivity }
0
Kotlin
0
0
024ddf6a5939eea49018c529f594cadf31c729f9
351
Flimsify
Apache License 2.0
src/test/kotlin/com/github/kerubistan/kerub/services/impl/HostServiceImplTest.kt
kerubistan
19,528,622
false
null
package com.github.kerubistan.kerub.services.impl import com.github.kerubistan.kerub.data.HostDao import com.github.kerubistan.kerub.getTestKey import com.github.kerubistan.kerub.host.HostManager import com.github.kerubistan.kerub.host.SshClientService import com.github.kerubistan.kerub.model.Host import com.github.kerubistan.kerub.model.lom.PowerManagementInfo import com.github.kerubistan.kerub.services.HostAndPassword import com.github.kerubistan.kerub.services.HostJoinDetails import com.github.kerubistan.kerub.testHost import com.nhaarman.mockito_kotlin.eq import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.whenever import org.hamcrest.CoreMatchers import org.junit.Assert import org.junit.Before import org.junit.Test import org.mockito.ArgumentMatchers.anyString import org.mockito.Mockito import java.security.PublicKey import java.util.UUID import kotlin.test.assertEquals class HostServiceImplTest { val dao: HostDao = mock() val manager: HostManager = mock() val sshClientService: SshClientService = mock() var pubKey: PublicKey = getTestKey().public var service: HostServiceImpl? = null @Before fun setup() { service = HostServiceImpl(dao, manager, sshClientService) } @Test fun join() { val hostAndPwd = HostAndPassword( password = "<PASSWORD>", host = Host( id = UUID.randomUUID(), address = "127.0.0.1", publicKey = "TEST", dedicated = true, capabilities = null ) ) service!!.join(hostAndPwd) verify(manager).join(eq(hostAndPwd.host), eq(hostAndPwd.password), eq(listOf())) } @Test fun getByAddress() { whenever(dao.byAddress(eq("test.example.com") ?: "")).thenReturn(listOf(testHost)) val byAddress = service!!.getByAddress("test.example.com") assertEquals(listOf(testHost), byAddress) verify(dao).byAddress(eq("test.example.com")) } @Test fun joinWithoutPassword() { val host = Host( id = UUID.randomUUID(), address = "127.0.0.1", publicKey = "TEST", dedicated = true, capabilities = null ) service!!.joinWithoutPassword(HostJoinDetails(host = host) ) verify(manager).join(eq(host), eq(listOf<PowerManagementInfo>())) } @Test fun getHostPubkey() { Mockito.`when`(manager.getHostPublicKey(anyString())).thenReturn(pubKey) val hostPubKey = service!!.getHostPubkey("127.0.0l.1") Assert.assertThat(hostPubKey.algorithm, CoreMatchers.`is`(pubKey.algorithm)) Assert.assertThat(hostPubKey.format, CoreMatchers.`is`(pubKey.format)) Assert.assertThat(hostPubKey.fingerprint, CoreMatchers.`is`("f6:aa:fa:c7:1d:98:cd:8b:0c:5b:c6:63:bb:3a:73:f6")) } @Test fun getPubKey() { Mockito.`when`(sshClientService.getPublicKey()).thenReturn("TEST-KEY") Assert.assertThat(service!!.getPubkey(), CoreMatchers.`is`("TEST-KEY")) Mockito.verify(sshClientService)!!.getPublicKey() } }
109
null
4
14
99cb43c962da46df7a0beb75f2e0c839c6c50bda
2,886
kerub
Apache License 2.0
project-system-gradle/testSrc/com/android/tools/idea/gradle/project/sync/jdk/integration/GradleSyncJdkIntegrationTest.kt
JetBrains
60,701,247
false
{"Kotlin": 43855938, "Java": 36698280, "HTML": 1216565, "Starlark": 735324, "C++": 216476, "Python": 101594, "C": 71515, "Lex": 66026, "NSIS": 58516, "AIDL": 32502, "Shell": 28591, "CMake": 21034, "JavaScript": 18437, "Batchfile": 7774, "Smali": 7580, "RenderScript": 4411, "Makefile": 2298, "IDL": 269, "QMake": 18}
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.gradle.project.sync.jdk.integration import com.android.testutils.junit4.OldAgpTest import com.android.testutils.junit4.SeparateOldAgpTestsRule import com.android.tools.idea.gradle.project.sync.constants.JDK_11 import com.android.tools.idea.gradle.project.sync.constants.JDK_11_PATH import com.android.tools.idea.gradle.project.sync.constants.JDK_17 import com.android.tools.idea.gradle.project.sync.constants.JDK_17_PATH import com.android.tools.idea.gradle.project.sync.constants.JDK_INVALID_PATH import com.android.tools.idea.gradle.project.sync.snapshots.JdkIntegrationTest import com.android.tools.idea.gradle.project.sync.snapshots.JdkIntegrationTest.TestEnvironment import com.android.tools.idea.gradle.project.sync.snapshots.JdkTestProject.SimpleApplication import com.android.tools.idea.gradle.project.sync.utils.JdkTableUtils.Jdk import com.android.tools.idea.sdk.IdeSdks.JDK_LOCATION_ENV_VARIABLE_NAME import com.android.tools.idea.testing.AgpVersionSoftwareEnvironmentDescriptor.AGP_74 import com.android.tools.idea.testing.AndroidProjectRule import com.android.tools.idea.testing.IntegrationTestEnvironmentRule import com.google.common.truth.Expect import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkException import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkUtil.JAVA_HOME import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkUtil.USE_JAVA_HOME import com.intellij.testFramework.RunsInEdt import org.jetbrains.plugins.gradle.util.USE_GRADLE_JAVA_HOME import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder @RunsInEdt @Suppress("UnstableApiUsage") class GradleSyncJdkIntegrationTest { @get:Rule val separateOldAgpTestsRule = SeparateOldAgpTestsRule() @get:Rule val projectRule: IntegrationTestEnvironmentRule = AndroidProjectRule.withIntegrationTestEnvironment() @get:Rule val expect: Expect = Expect.createAndEnableStackTrace() @get:Rule val temporaryFolder = TemporaryFolder() private val jdkIntegrationTest = JdkIntegrationTest(projectRule, temporaryFolder, expect) @Test(expected = ExternalSystemJdkException::class) fun `Given invalid userHomeGradlePropertiesJdkPath When import project Then throw exception`() = jdkIntegrationTest.run( project = SimpleApplication( ideaGradleJdk = USE_GRADLE_JAVA_HOME ), environment = TestEnvironment( userHomeGradlePropertiesJdkPath = "/invalid/jdk/path" ) ) { sync() } @Test(expected = ExternalSystemJdkException::class) fun `Given invalid gradlePropertiesJdkPath When import project Then throw exception`() = jdkIntegrationTest.run( project = SimpleApplication( ideaGradleJdk = USE_GRADLE_JAVA_HOME, gradlePropertiesJdkPath = "/invalid/jdk/path" ) ) { sync() } @Test fun `Given invalid STUDIO_GRADLE_JDK env variable When import project Then sync ignored it and use the project jdk configuration`() { val invalidJdkPath = temporaryFolder.newFolder(JDK_INVALID_PATH) jdkIntegrationTest.run( project = SimpleApplication( ideaGradleJdk = JDK_17, ), environment = TestEnvironment( jdkTable = listOf(Jdk(JDK_17, JDK_17_PATH)), environmentVariables = mapOf(JDK_LOCATION_ENV_VARIABLE_NAME to invalidJdkPath.path) ) ) { syncWithAssertion( expectedGradleJdkName = JDK_17, expectedProjectJdkName = JDK_17, expectedJdkPath = JDK_17_PATH ) } } @Test @OldAgpTest(agpVersions = ["7.4.0"], gradleVersions = ["7.5"]) fun `Given valid STUDIO_GRADLE_JDK env variable When import project Then sync used its path and the gradle jdk configuration doesn't change`() = jdkIntegrationTest.run( project = SimpleApplication( ideaGradleJdk = JDK_17, agpVersion = AGP_74, // Later versions of AGP (8.0 and beyond) require JDK17 ), environment = TestEnvironment( jdkTable = listOf(Jdk(JDK_17, JDK_17_PATH)), environmentVariables = mapOf(JDK_LOCATION_ENV_VARIABLE_NAME to JDK_11_PATH) ) ) { syncWithAssertion( expectedGradleJdkName = JDK_17, expectedProjectJdkName = JDK_11, expectedJdkPath = JDK_11_PATH ) } @Test fun `Given USE_JAVA_HOME gradleJdk macro When import project Then sync used JAVA_HOME`() = jdkIntegrationTest.run( project = SimpleApplication( ideaGradleJdk = USE_JAVA_HOME, ideaProjectJdk = JDK_17 ), environment = TestEnvironment( jdkTable = listOf(Jdk(JDK_11, JDK_11_PATH), Jdk(JDK_17, JDK_17_PATH)), environmentVariables = mapOf(JAVA_HOME to JDK_17_PATH) ) ) { syncWithAssertion( expectedGradleJdkName = USE_JAVA_HOME, expectedProjectJdkName = JDK_17, expectedJdkPath = JDK_17_PATH ) } @Test(expected = ExternalSystemJdkException::class) fun `Given USE_GRADLE_JAVA_HOME gradleJdk macro without jdkPath defined When import project Then throw exception`() = jdkIntegrationTest.run( project = SimpleApplication( ideaGradleJdk = USE_GRADLE_JAVA_HOME ), environment = TestEnvironment( jdkTable = listOf(Jdk(JDK_17, JDK_17_PATH)) ) ) { sync() } @Test(expected = ExternalSystemJdkException::class) fun `Given project with gradleJdk not present in jdkTable When import project Then throw exception`() = jdkIntegrationTest.run( project = SimpleApplication( ideaGradleJdk = "invalid" ), environment = TestEnvironment( jdkTable = listOf(Jdk(JDK_17, JDK_17_PATH)) ) ) { sync() } @Test(expected = ExternalSystemJdkException::class) fun `Given project with gradleJdk present in jdkTable but invalid path When import project Then throw exception`() = jdkIntegrationTest.run( project = SimpleApplication( ideaGradleJdk = JDK_17, ideaProjectJdk = "any" ), environment = TestEnvironment( jdkTable = listOf(Jdk(JDK_17, JDK_INVALID_PATH)) ) ) { sync() } }
2
Kotlin
230
876
9c0a89784cca3c01ab99cf251b71a26cdb87cc47
6,802
android
Apache License 2.0
db-common/src/main/kotlin/CommonErrors.kt
crowdproj
543,982,440
false
null
package com.gitlab.sszuev.flashcards.common import com.gitlab.sszuev.flashcards.model.common.AppAuthId import com.gitlab.sszuev.flashcards.model.common.AppError import com.gitlab.sszuev.flashcards.model.domain.CardId import com.gitlab.sszuev.flashcards.model.domain.DictionaryId fun wrongDictionaryLanguageFamilies( operation: String, dictionaryIds: Collection<DictionaryId>, ) = dbError( operation = operation, fieldName = dictionaryIds.joinToString { it.asString() }, details = """specified dictionaries belong to different language families, ids="${dictionaryIds.map { it.asString() }}"""" ) fun noDictionaryFoundDbError( operation: String, id: DictionaryId, ) = dbError( operation = operation, fieldName = id.asString(), details = """dictionary with id="${id.asString()}" not found""" ) fun noCardFoundDbError( operation: String, id: CardId, ) = dbError(operation = operation, fieldName = id.asString(), details = """card with id="${id.asString()}" not found""") fun noUserFoundDbError( operation: String, uid: AppAuthId, ) = dbError( operation = operation, fieldName = uid.asString(), details = """user with uid="${uid.asString()}" not found""" ) fun wrongUserUUIDDbError( operation: String, uid: AppAuthId, ) = dbError( operation = operation, fieldName = uid.asString(), details = """wrong uuid="${uid.asString()}"""", ) fun wrongResourceDbError(exception: Throwable) = dbError( operation = "uploadDictionary", details = """can't parse dictionary from byte-array""", exception = exception, ) fun dbError( operation: String, fieldName: String = "", details: String = "", exception: Throwable? = null, ) = AppError( code = "database::$operation", field = fieldName, group = "database", message = if (details.isBlank()) "Error while $operation" else "Error while $operation: $details", exception = exception )
7
Kotlin
0
0
db6f77fdb9f3b2940aa19e6cb19da079dacf5f7f
1,956
opentutor
Apache License 2.0
app/src/main/java/com/bos/oculess/DevAdminReceiver.kt
basti564
330,003,646
false
null
package com.bos.oculess import android.app.admin.DeviceAdminReceiver import android.content.Context import android.content.Intent import android.util.Log import android.widget.Toast class DevAdminReceiver : DeviceAdminReceiver() { private val TAG = "DeviceAdminReceiver" override fun onEnabled(context: Context, intent: Intent) { super.onEnabled(context, intent) Log.d(TAG, "Device Owner Enabled") Toast.makeText(context, "Device Owner Enabled", Toast.LENGTH_LONG).show() } }
4
null
79
990
405758356f40b417f2c8a7a02f03bf22dc8979d5
513
Oculess
The Unlicense
app/src/main/java/io/redgreen/benchpress/github/GitHubViewRenderer.kt
Aryan210
346,594,002
false
{"Gradle": 3, "Java Properties": 1, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "INI": 1, "Proguard": 1, "Kotlin": 119, "XML": 22, "Java": 6}
package io.redgreen.benchpress.github import io.redgreen.benchpress.architecture.AsyncOp import io.redgreen.benchpress.github.domain.User class GitHubViewRenderer(private val view: GitHubView) { fun render(model: GitHubModel) { if (model.fetchFollowersAsyncOp == AsyncOp.SUCCEEDED && model.usernamePresence == GitHubModel.UsernamePresence.NOT_FOUND) { showUserNotFound() } else if (model.fetchFollowersAsyncOp == AsyncOp.FAILED) { showUnknownError() } else if (model.fetchFollowersAsyncOp == AsyncOp.SUCCEEDED && model.hasFollowers) { showFollowers(model.followers) } else if (model.fetchFollowersAsyncOp == AsyncOp.SUCCEEDED && !model.hasFollowers) { showNoFollowersFound() } else if (model.fetchFollowersAsyncOp == AsyncOp.IN_FLIGHT) { showLoading() } else if (model.canSearch && model.fetchFollowersAsyncOp == AsyncOp.IDLE) { showReadyToFetchFollowers() } else if (!model.canSearch && model.fetchFollowersAsyncOp == AsyncOp.IDLE) { showEmpty() } } private fun showEmpty() { with(view) { disableSearchButton() hideFollowers() enableUsernameTextView() hideNoFollowersMessage() hideRetryMessage() hideUsernameNotFoundMessage() showWelcomeMessage() } } private fun showReadyToFetchFollowers() { with(view) { enableSearchButton() showWelcomeMessage() hideProgress() hideRetryMessage() hideFollowers() hideUsernameNotFoundMessage() hideNoFollowersMessage() } } private fun showLoading() { with(view) { disableSearchButton() disableUsernameTextView() showProgress() hideRetryMessage() hideWelcomeMessage() } } private fun showFollowers( followers: List<User> ) { with(view) { enableUsernameTextView() hideProgress() showFollowers(followers) enableSearchButton() } } private fun showUserNotFound() { with(view) { enableSearchButton() enableUsernameTextView() hideProgress() showUsernameNotFoundMessage() } } private fun showNoFollowersFound() { with(view) { enableUsernameTextView() enableSearchButton() hideProgress() showNoFollowersMessage() } } private fun showUnknownError() { with(view) { enableUsernameTextView() enableSearchButton() hideProgress() showRetryMessage() } } }
1
null
1
1
51335bba348794403cca58d0aa9bcea224daeb8b
2,840
bench-mark
Apache License 2.0
modules/wasm-binary/src/commonMain/kotlin/WasmSource.kt
wasmium
761,480,110
false
{"Kotlin": 352107, "JavaScript": 200}
@file:OptIn(ExperimentalUnsignedTypes::class) package org.wasmium.wasm.binary import kotlinx.io.EOFException import kotlinx.io.Source import kotlinx.io.readTo import org.wasmium.wasm.binary.tree.ExternalKind import org.wasmium.wasm.binary.tree.LimitFlags import org.wasmium.wasm.binary.tree.LinkingKind import org.wasmium.wasm.binary.tree.LinkingSymbolType import org.wasmium.wasm.binary.tree.NameKind import org.wasmium.wasm.binary.tree.Opcode import org.wasmium.wasm.binary.tree.RelocationKind import org.wasmium.wasm.binary.tree.ResizableLimits import org.wasmium.wasm.binary.tree.SectionKind import org.wasmium.wasm.binary.tree.V128Value import org.wasmium.wasm.binary.tree.WasmType import kotlin.experimental.and public class WasmSource( protected val source: Source ) { /** Current position in the source */ public var position: UInt = 0u private set private fun consume(byteCount: UInt): Unit { position += byteCount } public fun skip(byteCount: UInt): Unit = source.skip(byteCount.toLong()).also { consume(byteCount) } public fun close(): Unit = source.close() public fun readTo(bytes: ByteArray, startIndex: UInt, endIndex: UInt): UInt { source.readTo(bytes, startIndex.toInt(), endIndex.toInt()) return (endIndex - startIndex).also { consume(it) } } public fun require(byteCount: UInt): Boolean = try { source.require(byteCount.toLong()) true } catch (e: EOFException) { false } private fun Int.toUnsignedLong(): Long = toLong() and 0xFFFFFFFFL public fun exhausted(): Boolean = source.exhausted() public fun readUInt8(): UInt = (source.readByte().toInt() and 0xFF).toUInt().also { consume(1u) } public fun readUInt32(): UInt { var result = 0.toUInt() for (i in 0..3) { result = result or ((source.readByte().toInt() and 0xFF) shl (8 * i)).toUInt() } return result.also { consume(4u) } } public fun readUInt64(): ULong { var result = 0.toULong() for (i in 0..7) { result = result or ((source.readByte().toInt() and 0xFF) shl (8 * i)).toULong() } return result.also { consume(8u) } } public fun readVarUInt1(): UInt = (source.readByte() and 0b1).toUInt().also { consume(1u) } public fun readVarUInt7(): UInt = (source.readByte() and 0x7F).toUInt().also { consume(1u) } public fun readVarInt7(): Int = readVarInt32() public fun readVarUInt32(maxCount: Int = 5): UInt { var result = 0u var current: Int var count = 0 do { current = source.readByte().toInt() and 0xff result = result or ((current and 0x7f).toLong() shl (count * 7)).toUInt() count++ } while (current and 0x80 == 0x80 && count <= maxCount) if (current and 0x80 == 0x80) { throw ParserException("Overflow: Number too large") } if (current != 0 && count > (count * 8) / 7) { throw ParserException("Underflow: Too many bytes for value") } return result.also { consume(count.toUInt()) } } public fun readVarInt32(maxCount: Int = 10): Int { var result = 0L var current: Int var count = 0 do { current = source.readByte().toInt() and 0xff result = result or ((current and 0x7f).toLong() shl (count * 7)) count++ } while (current and 0x80 == 0x80 && count <= maxCount) if (current and 0x80 == 0x80) { throw Exception("Overflow: Number too large") } if (current != 0 && count > (count * 8) / 7) { throw Exception("Underflow: Too many bytes for value") } // sign extend if appropriate if ((current and 0x40) != 0) { result = result or (-(1 shl (count * 7))).toUnsignedLong() } return result.toInt().also { consume(count.toUInt()) } } public fun readVarInt64(maxCount: Int = 10): Long { var result = 0L var current: Int var count = 0 do { current = source.readByte().toInt() and 0xff result = result or ((current and 0x7f).toLong() shl (count * 7)) count++ } while (current and 0x80 == 0x80 && count <= maxCount) if (current and 0x80 == 0x80) { throw Exception("Overflow: Number too large") } if (current != 0 && count > (count * 8) / 7) { throw Exception("Underflow: Too many bytes for value") } // sign extend if appropriate val size = 64 if (count * 7 < size && (current and 0x40) != 0) { result = result or (-(1 shl (count * 7))).toUnsignedLong() } return result.also { consume(count.toUInt()) } } public fun readSectionKind(): SectionKind { val sectionKindId = readVarUInt7() val sectionKind = SectionKind.fromSectionKindId(sectionKindId) return sectionKind ?: throw ParserException("Invalid section kind $sectionKindId") } public fun readExternalKind(): ExternalKind { val externalKindId = readVarUInt7() val externalKind = ExternalKind.fromExternalKindId(externalKindId) return externalKind ?: throw ParserException("Invalid external kind $externalKindId") } public fun readRelocationKind(): RelocationKind { val relocationKindId = readVarUInt7() val relocationKind = RelocationKind.fromRelocationKind(relocationKindId) return relocationKind ?: throw ParserException("Invalid relocation kind $relocationKindId") } public fun readType(): WasmType { val wasmTypeId = readVarUInt7() val wasmType = WasmType.fromWasmTypeId(wasmTypeId) return wasmType ?: throw ParserException("Invalid wasm type 0x${wasmTypeId.toHexString()}") } public fun readIndex(): UInt = readVarUInt32() public fun readResizableLimits(): ResizableLimits { val flags = readVarUInt32() val hasMaximum = (flags and LimitFlags.HAS_MAX.flags) != 0u val initialPages = readVarUInt32() return if (hasMaximum) { val maximum = readVarUInt32() ResizableLimits(initial = initialPages, maximum = maximum, flags = flags) } else { ResizableLimits(initial = initialPages, flags = flags) } } public fun readOpcode(): Opcode { val value = readUInt8() return if (Opcode.isPrefix(value)) { val code = readVarUInt32() val opcode = Opcode.fromPrefix(value, code) opcode ?: throw ParserException("Invalid opcode prefix $value") } else { val opcode = Opcode.fromCode(value) opcode ?: throw ParserException("Invalid opcode 0x${value.toHexString()}") } } public fun readString(): String { val length = readVarUInt32() if (length > WasmBinary.MAX_STRING_SIZE) { throw ParserException("Size of string $length exceed the maximum of ${WasmBinary.MAX_STRING_SIZE}") } val buffer = ByteArray(length.toInt()) source.readTo(buffer, 0, length.toInt()) val result = buffer.decodeToString() return result.also { consume(length) } } public fun readNameKind(): NameKind { val nameKindId = readVarUInt7() val nameKind = NameKind.fromNameKindId(nameKindId) return nameKind ?: throw ParserException("Invalid name kind $nameKindId") } public fun readLinkingKind(): LinkingKind { val linkingKindId = readVarUInt7() val linkingKind = LinkingKind.fromLinkingKindId(linkingKindId) return linkingKind ?: throw ParserException("Invalid linking kind $linkingKindId") } public fun readLinkingSymbolType(): LinkingSymbolType { val linkingSymbolTypeId = readVarUInt7() val linkingSymbolType = LinkingSymbolType.fromLinkingSymbolTypeId(linkingSymbolTypeId) return linkingSymbolType ?: throw ParserException("Invalid linking symbol type $linkingSymbolTypeId") } public fun readFloat32(): Float { val bits = readUInt32().toInt() return Float.fromBits(bits) } public fun readFloat64(): Double { val bits = readUInt64().toLong() return Double.fromBits(bits) } public fun readV128(): V128Value { val value: UIntArray = uintArrayOf(0u, 0u, 0u, 0u) for (i in 0..3) { value[i] = readUInt32() } return V128Value(value) } }
0
Kotlin
0
1
f7ddef76630278616d221e7c8251adf0f11b9587
8,617
wasmium-wasm-binary
Apache License 2.0
kground/src/commonMain/kotlin/Utils.cmn.kt
mareklangiewicz
676,002,318
false
null
package pl.mareklangiewicz.kground import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.onEach import kotlin.time.TimeMark import kotlin.time.TimeSource import pl.mareklangiewicz.ulog.hack.ulog import pl.mareklangiewicz.ulog.i infix fun <T : Any> List<T>.plusIfNN(element: T?) = if (element == null) this else this + element infix fun <T : Any> List<T>.prependIfNN(element: T?) = if (element == null) this else listOf(element) + this fun Any.classSimpleWords() = this::class.simpleName!! .split(Regex("(?<=\\w)(?=\\p{Upper})")).map { it.lowercase() } inline fun <T> Iterator<T>.logEach(logln: (T) -> Unit = { ulog.i(it) }) = forEach(logln) // TODO: move timemarks saving support to [UHackySharedFlowLog] and remove all ...WithMillis extensions here fun Iterator<*>.logEachWithMillis( mark: TimeMark = TimeSource.Monotonic.markNow(), logln: (String) -> Unit = { ulog.i(it) }, ) = logEach { logln(it.toStringWithMillis(mark)) } inline fun <T> Iterable<T>.logEach(logln: (T) -> Unit = { ulog.i(it) }) = iterator().logEach(logln) inline fun <T> Sequence<T>.logEach(logln: (T) -> Unit = { ulog.i(it) }) = iterator().logEach(logln) inline fun <K, V> Map<K, V>.logEachEntry(logln: (Map.Entry<K, V>) -> Unit = { ulog.i(it) }) = iterator().logEach(logln) fun Iterable<*>.logEachWithMillis( mark: TimeMark = TimeSource.Monotonic.markNow(), logln: (String) -> Unit = { ulog.i(it) }, ) = iterator().logEachWithMillis(mark, logln) fun Sequence<*>.logEachWithMillis( mark: TimeMark = TimeSource.Monotonic.markNow(), logln: (String) -> Unit = { ulog.i(it) }, ) = iterator().logEachWithMillis(mark, logln) fun <T> Flow<T>.onEachLog(logln: (T) -> Unit = { ulog.i(it) }) = onEach(logln) suspend fun <T> Flow<T>.logEach(logln: (T) -> Unit = { ulog.i(it) }) = onEachLog(logln).collect() private fun Any?.toStringWithMillis(from: TimeMark, separator: String = " ") = "${from.elapsedNow().inWholeMilliseconds}$separator$this" suspend fun <T> Flow<T>.onEachLogWithMillis( mark: TimeMark = TimeSource.Monotonic.markNow(), logln: (String) -> Unit = { ulog.i(it) }, ) = onEachLog { logln(it.toStringWithMillis(mark)) } suspend fun <T> Flow<T>.logEachWithMillis( mark: TimeMark = TimeSource.Monotonic.markNow(), logln: (String) -> Unit = { ulog.i(it) }, ) = onEachLogWithMillis(mark, logln).collect()
0
Kotlin
0
0
ebd3cc9574e40d1d77f38311f4b0192490ac3502
2,370
KGround
Apache License 2.0
nebulosa-sbd/src/test/kotlin/SmallBodyIdentificationServiceTest.kt
tiagohm
568,578,345
false
{"Kotlin": 2467740, "TypeScript": 451309, "HTML": 225848, "SCSS": 13625, "Python": 2817, "JavaScript": 1198, "Makefile": 160}
import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.booleans.shouldBeTrue import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.ints.shouldBeExactly import io.kotest.matchers.ints.shouldBeGreaterThanOrEqual import io.kotest.matchers.nulls.shouldNotBeNull import nebulosa.math.deg import nebulosa.math.hours import nebulosa.math.km import nebulosa.sbd.SmallBodyDatabaseService import java.time.LocalDateTime class SmallBodyIdentificationServiceTest : StringSpec() { init { val service = SmallBodyDatabaseService() "search around Ceres" { val data = service.identify( LocalDateTime.of(2023, 8, 21, 0, 0, 0, 0), // Observatorio do Pico dos Dias, Itajuba (observatory) [code: 874] (-22.5354318).deg, (-45.5827).deg, 1.81754.km, "13 21 16.50".hours, "-01 57 06.5".deg, 1.0.deg, ).execute().body() data.shouldNotBeNull() data.count shouldBeGreaterThanOrEqual 1 data.data.any { "Ceres" in it[0] }.shouldBeTrue() } "no matching records" { val data = service.identify( LocalDateTime.of(2023, 1, 15, 1, 38, 15, 0), // Observatorio do Pico dos Dias, Itajuba (observatory) [code: 874] (-22.5354318).deg, (-45.5827).deg, 1.81754.km, "10 44 02".hours, "-59 36 04".deg, 1.0.deg, ).execute().body() data.shouldNotBeNull() data.count shouldBeExactly 0 data.data.shouldBeEmpty() } } }
4
Kotlin
2
4
bc81dd82c3c7dce1cf55bd03d0a69a8a1818f9ce
1,610
nebulosa
MIT License
cpg-core/src/main/kotlin/de/fraunhofer/aisec/cpg/TranslationManager.kt
Fraunhofer-AISEC
225,386,107
false
null
/* * Copyright (c) 2021, Fraunhofer AISEC. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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 de.fraunhofer.aisec.cpg import de.fraunhofer.aisec.cpg.frontends.Language import de.fraunhofer.aisec.cpg.frontends.LanguageFrontend import de.fraunhofer.aisec.cpg.frontends.SupportsParallelParsing import de.fraunhofer.aisec.cpg.frontends.TranslationException import de.fraunhofer.aisec.cpg.frontends.cpp.CXXLanguageFrontend import de.fraunhofer.aisec.cpg.graph.Component import de.fraunhofer.aisec.cpg.graph.Name import de.fraunhofer.aisec.cpg.graph.TypeManager import de.fraunhofer.aisec.cpg.helpers.Benchmark import de.fraunhofer.aisec.cpg.helpers.Util import de.fraunhofer.aisec.cpg.passes.* import java.io.File import java.io.PrintWriter import java.lang.reflect.InvocationTargetException import java.nio.file.Files import java.nio.file.Path import java.nio.file.attribute.BasicFileAttributes import java.util.* import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletionException import java.util.concurrent.ExecutionException import java.util.concurrent.atomic.AtomicBoolean import java.util.stream.Collectors import kotlin.reflect.full.findAnnotation import org.slf4j.LoggerFactory /** Main entry point for all source code translation for all language front-ends. */ class TranslationManager private constructor( /** * Returns the current (immutable) configuration of this TranslationManager. * * @return the configuration */ val config: TranslationConfiguration ) { private val isCancelled = AtomicBoolean(false) /** * Kicks off the analysis. * * This method orchestrates all passes that will do the main work. * * @return a [CompletableFuture] with the [TranslationResult]. */ fun analyze(): CompletableFuture<TranslationResult> { val result = TranslationResult(this, ScopeManager()) // We wrap the analysis in a CompletableFuture, i.e. in an async task. return CompletableFuture.supplyAsync { analyze2(result) } } fun analyze2(result: TranslationResult): TranslationResult { val outerBench = Benchmark(TranslationManager::class.java, "Translation into full graph", false, result) var executedFrontends = setOf<LanguageFrontend>() try { // Parse Java/C/CPP files var bench = Benchmark(this.javaClass, "Executing Language Frontend", false, result) executedFrontends = runFrontends(result, config) bench.addMeasurement() // Apply passes for (pass in config.registeredPasses) { bench = Benchmark(pass.java, "Executing Pass", false, result) executePassSequential(pass, result, executedFrontends) bench.addMeasurement() if (result.isCancelled) { log.warn("Analysis interrupted, stopping Pass evaluation") } } } catch (ex: TranslationException) { throw CompletionException(ex) } finally { outerBench.addMeasurement() if (!config.disableCleanup) { log.debug("Cleaning up {} Frontends", executedFrontends.size) executedFrontends.forEach { it.cleanup() } TypeManager.getInstance().cleanup() } } return result } fun isCancelled(): Boolean { return isCancelled.get() } /** * Parses all language files using the respective [LanguageFrontend] and creates the initial set * of AST nodes. * * @param result the translation result that is being mutated * @param config the translation configuration * @throws TranslationException if the language front-end runs into an error and * [TranslationConfiguration.failOnError] * * is `true`. */ @Throws(TranslationException::class) private fun runFrontends( result: TranslationResult, config: TranslationConfiguration, ): Set<LanguageFrontend> { val usedFrontends = mutableSetOf<LanguageFrontend>() for (sc in this.config.softwareComponents.keys) { val component = Component() component.name = Name(sc) result.addComponent(component) var sourceLocations: List<File> = this.config.softwareComponents[sc] ?: listOf() var useParallelFrontends = config.useParallelFrontends val list = sourceLocations.flatMap { file -> if (file.isDirectory) { Files.find( file.toPath(), 999, { _: Path?, fileAttr: BasicFileAttributes -> fileAttr.isRegularFile } ) .map { it.toFile() } .collect(Collectors.toList()) } else { val frontendClass = file.language?.frontend val supportsParallelParsing = file.language ?.frontend ?.findAnnotation<SupportsParallelParsing>() ?.supported ?: true // By default, the frontends support parallel parsing. But the // SupportsParallelParsing annotation can be set to false and force // to disable it. if (useParallelFrontends && !supportsParallelParsing) { log.warn( "Parallel frontends are not yet supported for the language frontend ${frontendClass?.simpleName}" ) useParallelFrontends = false } listOf(file) } } if (config.useUnityBuild) { val tmpFile = Files.createTempFile("compile", ".cpp").toFile() tmpFile.deleteOnExit() PrintWriter(tmpFile).use { writer -> list.forEach { if (CXXLanguageFrontend.CXX_EXTENSIONS.contains(Util.getExtension(it))) { if (config.topLevel != null) { val topLevel = config.topLevel.toPath() writer.write( """ #include "${topLevel.relativize(it.toPath())}" """ .trimIndent() ) } else { writer.write( """ #include "${it.absolutePath}" """ .trimIndent() ) } } } } sourceLocations = listOf(tmpFile) if (config.compilationDatabase != null) { // merge include paths from all translation units config.compilationDatabase.addIncludePath( tmpFile, config.compilationDatabase.allIncludePaths ) } } else { sourceLocations = list } TypeManager.setTypeSystemActive(config.typeSystemActiveInFrontend) usedFrontends.addAll( if (useParallelFrontends) { parseParallel(component, result, sourceLocations) } else { parseSequentially(component, result, sourceLocations) } ) if (!config.typeSystemActiveInFrontend) { TypeManager.setTypeSystemActive(true) result.components.forEach { s -> s.translationUnits.forEach { val bench = Benchmark(this.javaClass, "Activating types for ${it.name}", true) result.scopeManager.activateTypes(it) bench.stop() } } } } return usedFrontends } private fun parseParallel( component: Component, result: TranslationResult, sourceLocations: Collection<File> ): Set<LanguageFrontend> { val usedFrontends = mutableSetOf<LanguageFrontend>() log.info("Parallel parsing started") val futures = mutableListOf<CompletableFuture<Optional<LanguageFrontend>>>() val parallelScopeManagers = mutableListOf<ScopeManager>() val futureToFile: MutableMap<CompletableFuture<Optional<LanguageFrontend>>, File> = IdentityHashMap() for (sourceLocation in sourceLocations) { val scopeManager = ScopeManager() parallelScopeManagers.add(scopeManager) val future = CompletableFuture.supplyAsync { try { return@supplyAsync parse(component, scopeManager, sourceLocation) } catch (e: TranslationException) { throw RuntimeException("Error parsing $sourceLocation", e) } } futures.add(future) futureToFile[future] = sourceLocation } for (future in futures) { try { future.get().ifPresent { f: LanguageFrontend -> handleCompletion(result, usedFrontends, futureToFile[future], f) } } catch (e: InterruptedException) { log.error("Error parsing ${futureToFile[future]}", e) Thread.currentThread().interrupt() } catch (e: ExecutionException) { log.error("Error parsing ${futureToFile[future]}", e) Thread.currentThread().interrupt() } } // We want to merge everything into the final scope manager of the result result.scopeManager.mergeFrom(parallelScopeManagers) log.info("Parallel parsing completed") return usedFrontends } @Throws(TranslationException::class) private fun parseSequentially( component: Component, result: TranslationResult, sourceLocations: Collection<File> ): Set<LanguageFrontend> { val usedFrontends = mutableSetOf<LanguageFrontend>() for (sourceLocation in sourceLocations) { log.info("Parsing {}", sourceLocation.absolutePath) parse(component, result.scopeManager, sourceLocation).ifPresent { f: LanguageFrontend -> handleCompletion(result, usedFrontends, sourceLocation, f) } } return usedFrontends } private fun handleCompletion( result: TranslationResult, usedFrontends: MutableSet<LanguageFrontend>, sourceLocation: File?, f: LanguageFrontend ) { usedFrontends.add(f) // remember which frontend parsed each file val sfToFe = result.scratch.computeIfAbsent(TranslationResult.SOURCE_LOCATIONS_TO_FRONTEND) { mutableMapOf<String, String>() } as MutableMap<String, String> sourceLocation?.name?.let { sfToFe[it] = f.javaClass.simpleName } } @Throws(TranslationException::class) private fun parse( component: Component, scopeManager: ScopeManager, sourceLocation: File ): Optional<LanguageFrontend> { var frontend: LanguageFrontend? = null try { frontend = getFrontend(sourceLocation, scopeManager) if (frontend == null) { log.error("Found no parser frontend for ${sourceLocation.name}") if (config.failOnError) { throw TranslationException( "Found no parser frontend for ${sourceLocation.name}" ) } return Optional.empty() } component.translationUnits.add(frontend.parse(sourceLocation)) } catch (ex: TranslationException) { log.error("An error occurred during parsing of ${sourceLocation.name}: ${ex.message}") if (config.failOnError) { throw ex } } return Optional.ofNullable(frontend) } private fun getFrontend( file: File, scopeManager: ScopeManager, ): LanguageFrontend? { val language = file.language return if (language != null) { try { // Make sure, that our simple types are also known to the type manager language.builtInTypes.values.forEach { TypeManager.getInstance().registerType(it) } // Return a new language frontend language.newFrontend(config, scopeManager) } catch (e: Exception) { when (e) { is InstantiationException, is IllegalAccessException, is InvocationTargetException, is NoSuchMethodException -> { log.error( "Could not instantiate language frontend {}", language.frontend.simpleName, e ) null } else -> throw e } } } else null } private val File.language: Language<*>? get() { return config.languages.firstOrNull { it.handlesFile(this) } } class Builder { private var config: TranslationConfiguration = TranslationConfiguration.builder().build() fun config(config: TranslationConfiguration): Builder { this.config = config return this } fun build(): TranslationManager { return TranslationManager(config) } } companion object { private val log = LoggerFactory.getLogger(TranslationManager::class.java) @JvmStatic fun builder(): Builder { return Builder() } } }
81
null
50
161
99dfacfcf32281261920f8051521db8980f88716
15,473
cpg
Apache License 2.0
app/src/main/java/org/fossasia/openevent/general/attendees/ListAttendeeIdConverter.kt
Kapil706
172,433,206
true
{"Kotlin": 282142, "Java": 3853, "Shell": 3765}
package org.fossasia.openevent.general.attendees import androidx.room.TypeConverter import com.fasterxml.jackson.core.type.TypeReference import com.fasterxml.jackson.databind.ObjectMapper class ListAttendeeIdConverter { @TypeConverter fun fromListAttendeeId(attendeeIdList: List<AttendeeId>): String { val objectMapper = ObjectMapper() return objectMapper.writeValueAsString(attendeeIdList) } @TypeConverter fun toListAttendeeId(attendeeList: String): List<AttendeeId> { val objectMapper = ObjectMapper() val mapType = object : TypeReference<List<AttendeeId>>() {} return objectMapper.readValue(attendeeList, mapType) } }
0
Kotlin
0
1
e3bf6da900f3715759cd5a4d172ed198a4dd207d
690
open-event-android
Apache License 2.0
Lab3/app/src/main/java/com/example/lab3/NoScrollExpandableListView.kt
KPI-Labs-NChernikov
544,145,881
false
null
package com.example.lab3 import android.content.Context import android.util.AttributeSet import android.widget.ExpandableListView class NoScrollExpandableListView : ExpandableListView { constructor(context: Context?) : super(context) constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : super( context, attrs, defStyle ) override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val customHeightMeasureSpec = MeasureSpec.makeMeasureSpec( Int.MAX_VALUE shr 2, MeasureSpec.AT_MOST ) super.onMeasure(widthMeasureSpec, customHeightMeasureSpec) val params = layoutParams params.height = measuredHeight } }
0
Kotlin
0
0
1ce1d21c929edc23aba92fd359e68093488b1f63
815
Android-Labs
MIT License
snowplow-tracker/src/androidTest/java/com/snowplowanalytics/snowplow/internal/utils/UtilTest.kt
snowplow
20,056,757
false
{"Kotlin": 1227237, "Java": 38410, "Shell": 78}
/* * Copyright (c) 2015-2023 Snowplow Analytics Ltd. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package com.snowplowanalytics.snowplow.internal.utils import androidx.test.ext.junit.runners.AndroidJUnit4 import com.snowplowanalytics.core.utils.Util.addToMap import com.snowplowanalytics.core.utils.Util.base64Encode import com.snowplowanalytics.core.utils.Util.deserializer import com.snowplowanalytics.core.utils.Util.getDateTimeFromTimestamp import com.snowplowanalytics.core.utils.Util.getUTF8Length import com.snowplowanalytics.core.utils.Util.joinLongList import com.snowplowanalytics.core.utils.Util.mapHasKeys import com.snowplowanalytics.core.utils.Util.serialize import com.snowplowanalytics.core.utils.Util.timestamp import com.snowplowanalytics.core.utils.Util.uUIDString import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import java.util.* @RunWith(AndroidJUnit4::class) class UtilTest { @Test fun testGetTimestamp() { Assert.assertEquals(13, timestamp().length.toLong()) } @Test fun testGetDateTimeFromTimestamp() { val timestamp = 1653923456266L Assert.assertEquals("2022-05-30T15:10:56.266Z", getDateTimeFromTimestamp(timestamp)) } @Test fun testDateTimeProducesExpectedNumerals() { val timestamp = 1660643130123L val defaultLocale = Locale.getDefault() // set locale to one where different numerals are used (Egypt - arabic) Locale.setDefault(Locale("ar", "EG")) Assert.assertEquals("2022-08-16T09:45:30.123Z", getDateTimeFromTimestamp(timestamp)) // restore original locale Locale.setDefault(defaultLocale) } @Test fun testBase64Encode() { Assert.assertEquals("Zm9v", base64Encode("foo")) } @Test fun testGetEventId() { val eid = uUIDString() Assert.assertNotNull(eid) Assert.assertTrue(eid.matches(Regex("^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$"))) } @Test fun testGetUTF8Length() { Assert.assertEquals(19, getUTF8Length("foo€♥£\uD800\uDF48\uD83C\uDF44")) } @Test fun testJoinLongList() { val list: MutableList<Long?> = ArrayList() list.add(1L) Assert.assertEquals("1", joinLongList(list)) list.add(2L) list.add(3L) Assert.assertEquals("1,2,3", joinLongList(list)) list.add(null) Assert.assertEquals("1,2,3", joinLongList(list)) list.add(5L) Assert.assertEquals("1,2,3,5", joinLongList(list)) } @Test fun testDeserialize() { val testMap: MutableMap<String, String> = HashMap() testMap["foo"] = "bar" val testMapBytes = serialize(testMap) Assert.assertNotNull(testMapBytes) val testMap2 = deserializer( testMapBytes!! ) Assert.assertNotNull(testMap2) Assert.assertEquals("bar", testMap2!!["foo"]) } @Test fun testMapHasKeys() { val map: MutableMap<String, Any> = HashMap() map["key"] = "value" Assert.assertTrue(mapHasKeys(map, "key")) Assert.assertFalse(mapHasKeys(map, "key2")) Assert.assertFalse(mapHasKeys(map, "key", "key2")) } @Test fun testAddToMap() { val map: MutableMap<String, Any> = HashMap() addToMap(null, null, map) Assert.assertEquals(0, map.size.toLong()) addToMap("hello", null, map) Assert.assertEquals(0, map.size.toLong()) addToMap("", "", map) Assert.assertEquals(0, map.size.toLong()) addToMap("hello", "world", map) Assert.assertEquals(1, map.size.toLong()) Assert.assertEquals("world", map["hello"]) } }
20
Kotlin
62
102
c6ad42b49faf979f3f8c13cc8b91304c423872bd
4,349
snowplow-android-tracker
Apache License 2.0
app/src/main/java/com/hypertrack/android/api/ApiClient.kt
hypertrack
241,723,736
false
{"Kotlin": 1523302, "Java": 7006, "Just": 616}
package com.hypertrack.android.api import android.graphics.Bitmap import android.util.Log import com.google.android.gms.maps.model.LatLng import com.hypertrack.android.api.models.RemoteError import com.hypertrack.android.api.models.RemoteGeofence import com.hypertrack.android.api.models.RemoteOrder import com.hypertrack.android.api.models.RemoteTrip import com.hypertrack.android.models.GeofenceMetadata import com.hypertrack.android.models.Integration import com.hypertrack.android.models.Metadata import com.hypertrack.android.models.local.DeviceId import com.hypertrack.android.models.local.OrderStatus import com.hypertrack.android.utils.AbstractFailure import com.hypertrack.android.utils.AbstractResult import com.hypertrack.android.utils.AbstractSuccess import com.hypertrack.android.utils.JustFailure import com.hypertrack.android.utils.JustSuccess import com.hypertrack.android.utils.SimpleResult import com.squareup.moshi.Moshi import com.squareup.moshi.Types import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import retrofit2.HttpException import retrofit2.Response import java.util.* class ApiClient( private val api: ApiInterface, private val deviceId: DeviceId, private val moshi: Moshi, ) { private val geofenceListAdapter = moshi.adapter<List<RemoteGeofence>>( Types.newParameterizedType(List::class.java, RemoteGeofence::class.javaObjectType) ) suspend fun getGeofences( paginationToken: String?, geoHash: String? = null ): GeofenceResponse { try { val response = api.getDeviceGeofences( paginationToken = paginationToken, deviceId = deviceId.value, geohash = geoHash ) if (response.isSuccessful) { return response.body()!! } else { throw HttpException(response) } } catch (e: Exception) { throw e } } suspend fun getGeofence(geofenceId: String): RemoteGeofence { try { // todo handle EOFException: End of input if there is no such geofence val metadataResponse = api.getGeofenceMetadata(geofenceId).apply { if (!isSuccessful) throw HttpException(this) } val visitsResponse = api.getGeofenceVisits(geofenceId).apply { if (!isSuccessful) throw HttpException(this) } val visitsBody = visitsResponse.body()!! return metadataResponse.body()!!.copy( marker = GeofenceMarkersResponse( visitsBody.visits, visitsBody.paginationToken, ) ) } catch (e: Exception) { throw e } } suspend fun createGeofence( latitude: Double, longitude: Double, radius: Int, metadata: GeofenceMetadata ): AbstractResult<List<RemoteGeofence>, RemoteError> { return api.createGeofences( deviceId = deviceId.value, GeofenceParams( setOf( GeofenceProperties( Point(latitude = latitude, longitude = longitude), metadata.toMap(moshi), radius ) ), deviceId = deviceId.value ) ).let { res -> val errorBody = res.errorBody()?.string() val body = res.body()?.string() when { res.isSuccessful -> { // assuming that the success is JSON array if (body == null) { throw NullPointerException("body") } val result = geofenceListAdapter.fromJson(body) ?: throw Exception("Failed to parse body") AbstractSuccess(result) } res.code() == 400 && errorBody != null -> { // assuming that the response is JSON object AbstractFailure(RemoteError(errorBody)) } else -> { throw HttpException(res) } } } } suspend fun getTrips(page: String = ""): List<RemoteTrip> { return try { val response = api.getTrips( deviceId = deviceId.value, paginationToken = page ) if (response.isSuccessful) { response.body()?.trips?.filterNot { it.id.isNullOrEmpty() } ?: emptyList() } else { throw HttpException(response) } } catch (e: Exception) { throw e } } suspend fun updateOrderMetadata( orderId: String, tripId: String, metadata: Metadata ): Response<RemoteTrip> { try { return api.updateOrder( orderId = orderId, tripId = tripId, order = OrderBody(metadata = metadata.toMap()) ) } catch (e: Exception) { throw e } } suspend fun uploadImage(filename: String, image: Bitmap) { try { val response = api.persistImage( deviceId = deviceId.value, EncodedImage(filename, image) ) if (response.isSuccessful) { // Log.v(TAG, "Got post image response ${response.body()}") } else { throw HttpException(response) } } catch (e: Throwable) { Log.w(TAG, "Got exception $e uploading image") throw e } } suspend fun createTrip(latLng: LatLng, address: String?): RemoteTrip { try { val res = api.createTrip( TripParams( deviceId = deviceId.value, orders = listOf( OrderParams( orderId = UUID.randomUUID().toString(), destination = TripDestination( geometry = Point( latitude = latLng.latitude, longitude = latLng.longitude, ), address = address, radius = null ) ) ) ) ) if (res.isSuccessful) { val trip = res.body()!! return trip } else { throw HttpException(res) } } catch (e: Throwable) { throw e } } suspend fun addOrderToTrip( tripId: String, orderCreationParams: OrderCreationParams ): RemoteTrip { try { with( api.addOrderToTrip( tripId, AddOrderBody( deviceId = deviceId.value, orderCreationParams = listOf(orderCreationParams) ) ) ) { if (isSuccessful) { return body()!! } else { throw HttpException(this) } } } catch (e: Exception) { throw e } } suspend fun completeTrip(tripId: String): SimpleResult { return try { with(api.completeTrip(tripId)) { if (isSuccessful) JustSuccess else JustFailure(HttpException(this)) } } catch (e: Exception) { JustFailure(e) } } suspend fun completeOrder(orderId: String, tripId: String): OrderCompletionResponse { try { val res = api.completeOrder(tripId = tripId, orderId = orderId) if (res.isSuccessful) { return OrderCompletionSuccess } else { if (res.code() == 409) { @Suppress("BlockingMethodInNonBlockingContext") val order = withContext(Dispatchers.IO) { moshi.adapter(RemoteOrder::class.java) .fromJson(res.errorBody()!!.string()) } when (order!!.status) { OrderStatus.COMPLETED -> return OrderCompletionCompleted OrderStatus.CANCELED -> return OrderCompletionCanceled else -> return OrderCompletionFailure(HttpException(res)) } } else { return OrderCompletionFailure(HttpException(res)) } } } catch (e: Exception) { return OrderCompletionFailure(e) } } suspend fun cancelOrder(orderId: String, tripId: String): OrderCompletionResponse { try { val res = api.cancelOrder(tripId = tripId, orderId = orderId) if (res.isSuccessful) { return OrderCompletionSuccess } else { if (res.code() == 409) { @Suppress("BlockingMethodInNonBlockingContext") val order = withContext(Dispatchers.IO) { moshi.adapter(RemoteOrder::class.java) .fromJson(res.errorBody()!!.string()) } when (order!!.status) { OrderStatus.COMPLETED -> return OrderCompletionCompleted OrderStatus.CANCELED -> return OrderCompletionCanceled else -> return OrderCompletionFailure(HttpException(res)) } } else { return OrderCompletionFailure(HttpException(res)) } } } catch (e: Exception) { return OrderCompletionFailure(e) } } suspend fun snoozeOrder(orderId: String, tripId: String): SimpleResult { return try { val res = api.snoozeOrder(tripId = tripId, orderId = orderId) if (res.isSuccessful) { JustSuccess } else { JustFailure(HttpException(res)) } } catch (e: Exception) { JustFailure(e) } } suspend fun unsnoozeOrder(orderId: String, tripId: String): SimpleResult { return try { val res = api.unsnoozeOrder(tripId = tripId, orderId = orderId) if (res.isSuccessful) { JustSuccess } else { JustFailure(HttpException(res)) } } catch (e: Exception) { JustFailure(e) } } suspend fun getIntegrations(query: String? = null, limit: Int? = null): List<Integration> { val res = api.getIntegrations(query, limit) if (res.isSuccessful) { return res.body()!!.data } else { throw HttpException(res) } } suspend fun getImageBase64(imageId: String): String? { try { val res = api.getImage(deviceId = deviceId.value, imageId = imageId) if (res.isSuccessful) { return res.body()?.data } else { throw HttpException(res) } } catch (e: Exception) { //todo handle return null } } companion object { const val TAG = "ApiClient" } }
1
Kotlin
17
30
816c9735bf8cab508eebcd966341500aa33fecea
11,695
visits-android
MIT License
app/src/main/java/org/simple/clinic/overdue/Appointment.kt
simpledotorg
132,515,649
false
null
package org.simple.clinic.overdue import android.arch.persistence.room.Dao import android.arch.persistence.room.Entity import android.arch.persistence.room.Insert import android.arch.persistence.room.OnConflictStrategy import android.arch.persistence.room.PrimaryKey import android.arch.persistence.room.Query import com.squareup.moshi.Json import io.reactivex.Flowable import org.simple.clinic.patient.SyncStatus import org.simple.clinic.util.RoomEnumTypeConverter import org.threeten.bp.Instant import org.threeten.bp.LocalDate import java.util.UUID @Entity(tableName = "Appointment") data class Appointment( @PrimaryKey val uuid: UUID, val patientUuid: UUID, val facilityUuid: UUID, val scheduledDate: LocalDate, val status: Status, val cancelReason: AppointmentCancelReason?, val remindOn: LocalDate?, val agreedToVisit: Boolean?, val syncStatus: SyncStatus, val createdAt: Instant, val updatedAt: Instant, val deletedAt: Instant? ) { enum class Status { @Json(name = "scheduled") SCHEDULED, @Json(name = "cancelled") CANCELLED, @Json(name = "visited") VISITED; class RoomTypeConverter : RoomEnumTypeConverter<Status>(Status::class.java) } @Dao interface RoomDao { @Query("SELECT * FROM Appointment WHERE syncStatus = :status") fun recordsWithSyncStatus(status: SyncStatus): Flowable<List<Appointment>> @Query("UPDATE Appointment SET syncStatus = :to WHERE syncStatus = :from") fun updateSyncStatus(from: SyncStatus, to: SyncStatus) @Query("UPDATE Appointment SET syncStatus = :to WHERE uuid IN (:ids)") fun updateSyncStatus(ids: List<UUID>, to: SyncStatus) @Query("SELECT * FROM Appointment WHERE uuid = :id LIMIT 1") fun getOne(id: UUID): Appointment? @Insert(onConflict = OnConflictStrategy.REPLACE) fun save(appointments: List<Appointment>) @Query(""" SELECT * FROM Appointment WHERE patientUuid = :patientUuid ORDER BY createdAt DESC LIMIT 1 """) fun lastCreatedAppointmentForPatient(patientUuid: UUID): Flowable<List<Appointment>> @Query("SELECT COUNT(uuid) FROM Appointment") fun count(): Flowable<Int> @Query(""" UPDATE Appointment SET status = :updatedStatus, syncStatus = :newSyncStatus, updatedAt = :newUpdatedAt WHERE patientUuid = :patientUuid AND status = :scheduledStatus """) fun markOlderAppointmentsAsVisited( patientUuid: UUID, updatedStatus: Status, scheduledStatus: Status, newSyncStatus: SyncStatus, newUpdatedAt: Instant ) @Query(""" UPDATE Appointment SET remindOn = :reminderDate, syncStatus = :newSyncStatus, updatedAt = :newUpdatedAt WHERE uuid = :appointmentUUID """) fun saveRemindDate( appointmentUUID: UUID, reminderDate: LocalDate, newSyncStatus: SyncStatus, newUpdatedAt: Instant ) @Query(""" UPDATE Appointment SET remindOn = :reminderDate, agreedToVisit = :agreed, syncStatus = :newSyncStatus, updatedAt = :newUpdatedAt WHERE uuid = :appointmentUUID """) fun markAsAgreedToVisit( appointmentUUID: UUID, reminderDate: LocalDate, agreed: Boolean = true, newSyncStatus: SyncStatus, newUpdatedAt: Instant ) @Query(""" UPDATE Appointment SET status = :newStatus, syncStatus = :newSyncStatus, updatedAt = :newUpdatedAt WHERE uuid = :appointmentUuid """) fun markAsVisited( appointmentUuid: UUID, newStatus: Status, newSyncStatus: SyncStatus, newUpdatedAt: Instant ) @Query(""" UPDATE Appointment SET cancelReason = :cancelReason, status = :newStatus, syncStatus = :newSyncStatus, updatedAt = :newUpdatedAt WHERE uuid = :appointmentUuid """) fun cancelWithReason( appointmentUuid: UUID, cancelReason: AppointmentCancelReason, newStatus: Status, newSyncStatus: SyncStatus, newUpdatedAt: Instant ) @Query("DELETE FROM Appointment") fun clear() } }
7
null
73
236
ff699800fbe1bea2ed0492df484777e583c53714
4,133
simple-android
MIT License
cosec-jwt/src/test/kotlin/me/ahoo/cosec/jwt/JwtTokenConverterTest.kt
Ahoo-Wang
567,999,401
false
{"Kotlin": 588793, "Dockerfile": 594}
/* * Copyright [2021-present] [<NAME> <<EMAIL>> (https://github.com/Ahoo-Wang)]. * 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 me.ahoo.cosec.jwt import me.ahoo.cosec.api.token.CompositeToken import me.ahoo.cosec.api.token.TokenPrincipal import me.ahoo.cosec.principal.SimplePrincipal import me.ahoo.cosec.principal.SimpleTenantPrincipal import me.ahoo.cosid.test.MockIdGenerator import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.equalTo import org.hamcrest.Matchers.notNullValue import org.junit.jupiter.api.Test /** * @author <NAME> */ internal class JwtTokenConverterTest { var jwtTokenConverter = JwtTokenConverter(MockIdGenerator.INSTANCE, JwtFixture.ALGORITHM) private val jwtTokenVerifier = JwtTokenVerifier(JwtFixture.ALGORITHM) @Test fun anonymousAsToken() { val token: CompositeToken = jwtTokenConverter.asToken(SimpleTenantPrincipal.ANONYMOUS) assertThat(token, notNullValue()) } @Test fun asToken() { val principal = SimplePrincipal( "id", setOf("policyId"), setOf("roleId"), mapOf( "attr_string" to "attr_string_value" ), ) val token: CompositeToken = jwtTokenConverter.asToken(principal) assertThat(token, notNullValue()) val verified = jwtTokenVerifier.verify<TokenPrincipal>(token) assertThat(verified.id, equalTo(principal.id)) assertThat(verified.attributes["attr_string"], equalTo("attr_string_value")) val token2 = jwtTokenConverter.asToken(verified) assertThat(token2, notNullValue()) } }
1
Kotlin
4
32
b0edd6e0b096a76d17363778b1aec8dd2c19c9b3
2,192
CoSec
Apache License 2.0
app/src/main/java/fr/coppernic/tools/transparent/terminal/TerminalFragment.kt
Coppernic
171,477,196
false
null
package fr.coppernic.tools.transparent.terminal import android.annotation.SuppressLint import android.os.Bundle import androidx.fragment.app.Fragment import androidx.recyclerview.widget.RecyclerView import android.view.* import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import com.google.android.material.snackbar.Snackbar import fr.coppernic.sdk.serial.SerialCom import fr.coppernic.sdk.serial.SerialFactory import fr.coppernic.sdk.utils.io.InstanceListener import fr.coppernic.tools.transparent.R import fr.coppernic.tools.transparent.home.LogAdapter import kotlinx.android.synthetic.main.fragment_terminal.* import javax.inject.Inject /** * A simple [Fragment] subclass. * */ class TerminalFragment @Inject constructor() : Fragment(), TerminalView { @Inject lateinit var presenter: TerminalPresenter private lateinit var viewAdapter: RecyclerView.Adapter<*> private lateinit var viewManager: RecyclerView.LayoutManager private var logs = ArrayList<String>() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_terminal, container, false) } @SuppressLint("CheckResult") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) enableSwOpen(false) initializeRecyclerView() initializeSerialPort() presenter.setUp(this).subscribe { if (it) { enableSwOpen(true) } } swOpen.setOnCheckedChangeListener { _, checked -> when(checked) { false -> presenter.closePort() true -> presenter.openPort(spPortName.selectedItem.toString(), spPortBaudrate.selectedItem.toString().toInt()) } } fabSend.setOnClickListener { presenter.send(etDataToSend.text.toString()) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { activity.let { it?.menuInflater?.inflate(R.menu.menu_main, menu) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId when (id) { R.id.action_clear_logs -> { logs.clear() viewAdapter.notifyDataSetChanged() tvEmptyLogs.visibility = View.VISIBLE } } return true } private fun initializeRecyclerView() { viewManager = LinearLayoutManager(activity) viewAdapter = LogAdapter(logs) rvLogs.apply { setHasFixedSize(true) layoutManager = viewManager addItemDecoration(DividerItemDecoration([email protected], LinearLayoutManager.VERTICAL)) adapter = viewAdapter } } private fun initializeSerialPort() { // In port instantiation context?.let { SerialFactory.getDirectInstance(it, object : InstanceListener<SerialCom> { override fun onDisposed(p0: SerialCom) { } override fun onCreated(p0: SerialCom) { presenter.setPort(p0) } }) } } private fun enableSwOpen(enable:Boolean) { swOpen.isEnabled = enable } override fun addLog(log: String) { activity.let{ it?.runOnUiThread { logs.add(0, log) viewAdapter.notifyDataSetChanged() tvEmptyLogs.visibility = View.INVISIBLE } } } override fun showError(error: TerminalView.Error) { val message = when(error) { TerminalView.Error.OPEN_ERROR -> R.string.error_open TerminalView.Error.INCORRECT_DATA_TO_SEND -> R.string.error_incorrect_data_to_send TerminalView.Error.PORT_NOT_OPENED -> R.string.error_port_not_opened else -> { R.string.error_ok } } Snackbar.make(fabSend, message, Snackbar.LENGTH_SHORT).show() } }
1
Kotlin
0
1
ec441f5251b5bc46b45420da79e3828ce730adfa
4,419
Serial
Apache License 2.0
data/src/main/java/com/keelim/cnubus/di/CacheInterceptor.kt
keelim
202,127,420
false
null
/* * Designed and developed by 2021 keelim (<NAME>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.keelim.cnubus.di import okhttp3.Interceptor import okhttp3.Response import javax.inject.Inject class CacheInterceptor @Inject constructor() : Interceptor { private val HEADER_CACHE_CONTROL = "Cache-Control" private val HEADER_CACHE_MAX_AGE = "public, max-age=${3 * 60}" // 3분 private val HEADER_USE_CACHE_PREFIX = "Use-Cache" private val HEADER_USE_CACHE = "$HEADER_USE_CACHE_PREFIX: " override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() val useCache = request.header(HEADER_USE_CACHE_PREFIX) != null return chain.proceed(request).apply { if (useCache) { newBuilder() .header(HEADER_CACHE_CONTROL, HEADER_CACHE_MAX_AGE) .removeHeader(HEADER_USE_CACHE_PREFIX) .build() } } } }
6
Kotlin
0
1
836c7fca6793ed74249f9430c798466b1a7aaa27
1,497
project_cnuBus
Apache License 2.0
login_framework/src/main/java/com/vmenon/mpo/login/framework/MpoApiUserRegistry.kt
hitoshura25
91,402,384
false
null
package com.vmenon.mpo.login.framework import com.vmenon.mpo.api.model.RegisterUserRequest import com.vmenon.mpo.api.model.UserDetails import com.vmenon.mpo.common.framework.retrofit.MediaPlayerOmegaRetrofitService import com.vmenon.mpo.login.data.GetUserException import com.vmenon.mpo.login.data.UserRegistry import com.vmenon.mpo.login.domain.User import retrofit2.HttpException import java.lang.RuntimeException class MpoApiUserRegistry( private val api: MediaPlayerOmegaRetrofitService ) : UserRegistry { override suspend fun registerUser( firstName: String, lastName: String, email: String, password: String ): User { val response = api.registerUser( RegisterUserRequest( firstName = firstName, lastName = lastName, email = email, password = <PASSWORD> ) ).blockingGet() return response.userDetails.run { User( firstName = firstName, lastName = lastName, email = email ) } } override suspend fun getCurrentUser(): User { try { val userFromApi: UserDetails = api.getCurrentUser().blockingGet() return User( firstName = userFromApi.firstName, lastName = userFromApi.lastName, email = userFromApi.email ) } catch (httpException: HttpException) { throw GetUserException(httpException) } catch (exception: RuntimeException) { throw exception.cause ?: exception } } }
15
Kotlin
0
1
d37ca42046c00bbe3c414482fac67e041c734ecf
1,658
Media-Player-Omega-Android
Apache License 2.0
core/data/src/main/java/com/t8rin/imagetoolboxlite/core/data/image/AndroidImageTransformer.kt
T8RIN
767,600,774
false
null
/* * ImageToolbox is an image editor for android * Copyright (c) 2024 T8RIN (<NAME>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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. * * You should have received a copy of the Apache License * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package ru.tech.imageresizershrinker.core.data.image import android.content.Context import android.graphics.Bitmap import android.graphics.Matrix import coil.ImageLoader import coil.request.ImageRequest import coil.size.Size import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.withContext import ru.tech.imageresizershrinker.core.data.utils.toBitmap import ru.tech.imageresizershrinker.core.data.utils.toCoil import ru.tech.imageresizershrinker.core.di.DefaultDispatcher import ru.tech.imageresizershrinker.core.domain.image.ImageTransformer import ru.tech.imageresizershrinker.core.domain.image.model.ImageFormat import ru.tech.imageresizershrinker.core.domain.image.model.ImageInfo import ru.tech.imageresizershrinker.core.domain.image.model.Preset import ru.tech.imageresizershrinker.core.domain.image.model.Quality import ru.tech.imageresizershrinker.core.domain.image.model.ResizeType import ru.tech.imageresizershrinker.core.domain.model.IntegerSize import ru.tech.imageresizershrinker.core.domain.model.sizeTo import ru.tech.imageresizershrinker.core.domain.transformation.Transformation import javax.inject.Inject import kotlin.math.abs internal class AndroidImageTransformer @Inject constructor( @ApplicationContext private val context: Context, private val imageLoader: ImageLoader, @DefaultDispatcher private val dispatcher: CoroutineDispatcher, ) : ImageTransformer<Bitmap> { override suspend fun transform( image: Bitmap, transformations: List<Transformation<Bitmap>>, originalSize: Boolean ): Bitmap? = withContext(dispatcher) { val request = ImageRequest .Builder(context) .data(image) .transformations( transformations.map { it.toCoil() } ) .apply { if (originalSize) size(Size.ORIGINAL) } .build() return@withContext imageLoader.execute(request).drawable?.toBitmap() } override suspend fun transform( image: Bitmap, transformations: List<Transformation<Bitmap>>, size: IntegerSize ): Bitmap? = withContext(dispatcher) { val request = ImageRequest .Builder(context) .data(image) .transformations( transformations.map { it.toCoil() } ) .size(size.width, size.height) .build() return@withContext imageLoader.execute(request).drawable?.toBitmap() } override suspend fun applyPresetBy( image: Bitmap?, preset: Preset, currentInfo: ImageInfo ): ImageInfo = withContext(dispatcher) { if (image == null) return@withContext currentInfo val size = currentInfo.originalUri?.let { imageLoader.execute( ImageRequest.Builder(context) .data(it) .size(Size.ORIGINAL) .build() ).drawable?.run { intrinsicWidth sizeTo intrinsicHeight } } ?: IntegerSize(image.width, image.height) val rotated = abs(currentInfo.rotationDegrees) % 180 != 0f fun calcWidth() = if (rotated) size.height else size.width fun calcHeight() = if (rotated) size.width else size.height fun Int.calc(cnt: Int): Int = (this * (cnt / 100f)).toInt() when (preset) { is Preset.Telegram -> { currentInfo.copy( width = 512, height = 512, imageFormat = ImageFormat.Png.Lossless, resizeType = ResizeType.Flexible, quality = Quality.Base(100) ) } is Preset.Numeric -> currentInfo.copy( quality = when (val quality = currentInfo.quality) { is Quality.Base -> quality.copy(qualityValue = preset.value) is Quality.Jxl -> quality.copy(qualityValue = preset.value) else -> quality }, width = calcWidth().calc(preset.value), height = calcHeight().calc(preset.value), ) is Preset.None -> currentInfo } } override suspend fun flip( image: Bitmap, isFlipped: Boolean ): Bitmap = withContext(dispatcher) { if (isFlipped) { val matrix = Matrix().apply { postScale(-1f, 1f, image.width / 2f, image.height / 2f) } Bitmap.createBitmap(image, 0, 0, image.width, image.height, matrix, true) } else image } override suspend fun rotate( image: Bitmap, degrees: Float ): Bitmap = withContext(dispatcher) { if (degrees % 90 == 0f) { val matrix = Matrix().apply { postRotate(degrees) } Bitmap.createBitmap(image, 0, 0, image.width, image.height, matrix, true) } else { val matrix = Matrix().apply { setRotate(degrees, image.width.toFloat() / 2, image.height.toFloat() / 2) } Bitmap.createBitmap(image, 0, 0, image.width, image.height, matrix, true) } } }
5
null
95
8
f8fe322c2bde32544e207b49a01cfeac92c187ce
6,000
ImageToolboxLite
Apache License 2.0
tasks/src/main/java/app/tivi/tasks/SyncAllFollowedShows.kt
SagarKisanAvhad
146,028,545
false
null
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.tasks import androidx.work.Worker import app.tivi.interactors.SyncFollowedShows import app.tivi.interactors.launchInteractor import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.runBlocking import javax.inject.Inject class SyncAllFollowedShows : Worker() { companion object { const val TAG = "sync-all-followed-shows" const val NIGHTLY_SYNC_TAG = "night-sync-all-followed-shows" } @Inject lateinit var syncFollowedShows: SyncFollowedShows override fun doWork(): Result { AndroidWorkerInjector.inject(this) runBlocking { GlobalScope.launchInteractor(syncFollowedShows, SyncFollowedShows.ExecuteParams(true)).join() } return Result.SUCCESS } }
0
null
1
1
687191398bd42fc87d4f50c89f21228e89c3a523
1,349
tivi-master
Apache License 2.0
filesystem/src/main/java/com/tinkerlog/plip/filesystem/FileSystemPersistence.kt
tinkerlog
514,838,516
false
null
package com.tinkerlog.plip.filesystem import java.io.BufferedReader import java.io.BufferedWriter import java.io.File import java.io.FileReader import java.io.FileWriter import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json interface FileSystemPersistence { fun load(): Folder fun store(root: Folder) } private const val FS_NAME = "fs.json" private const val NEW_FS_NAME = "new_fs.json" open class SingleFilePersistence( private val rootDir: File ) : FileSystemPersistence { internal var rootFolder: FolderImpl? = null protected fun reset() { rootFolder = null } override fun store(root: Folder) { val content = Json.encodeToString((root as FolderImpl).toJson()) writeToFile(content) } override fun load(): Folder { if (rootFolder == null) { val f = File(getStorageDirectory(), FS_NAME) rootFolder = if (f.canRead()) { loadFromFile(f) } else { FolderImpl(null, "") } } return rootFolder!! } private fun loadFromFile(file: File): FolderImpl { BufferedReader(FileReader(file)).use { val json = it.readText() return FolderImpl.toFolder(null, Json.parseToJsonElement(json)) } } fun writeToFile(content: String) { val tmpFile = File(getStorageDirectory(), NEW_FS_NAME) val bw = BufferedWriter(FileWriter(tmpFile)) bw.use { it.write(content) } val oldFile = File(getStorageDirectory(), FS_NAME) if (oldFile.exists() && !oldFile.delete()) { throw IllegalStateException("writeToFile failed, can not delete old fs") } val newFile = File(getStorageDirectory(), FS_NAME) if (!tmpFile.renameTo(newFile)) { throw IllegalStateException("writeToFile failed, can not rename fs") } } private fun getStorageDirectory(): File { val dir = rootDir if (!dir.exists()) { if (!dir.mkdirs()) { throw IllegalStateException("Directory '$dir' not created") } } return dir } }
0
Kotlin
0
3
03eb4d04d8a6fe43de60d3172c49647ec67e5b4b
2,187
plip_android
MIT License
src/main/kotlin/br/com/ecommerce/livros/service/LivrosService.kt
njguilhem2
281,196,756
false
{"Kotlin": 14987}
package br.com.ecommerce.livros.service import LivrosResponse import br.com.ecommerce.livros.model.Livros interface LivrosService { fun listAll(): LivrosResponse fun saveLivros(livros: Livros): Livros fun updateLivros(livros: Livros, id: Long): Livros fun deleteLivros(id: Long) fun findById(id: Long): Livros? }
0
Kotlin
0
1
3d6a75f0e243e6b2134e7c6a596c7afd138c7ea2
334
ecommerce-ngbook
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsalertsapi/resource/Headers.kt
ministryofjustice
750,461,021
false
{"Kotlin": 603075, "Mermaid": 3411, "Shell": 1799, "Dockerfile": 1387}
package uk.gov.justice.digital.hmpps.hmppsalertsapi.resource const val USERNAME = "Username" const val SOURCE = "Source"
4
Kotlin
0
0
ddb93fe023bed27dea7fab448b8d69dcb2003ef3
122
hmpps-alerts-api
MIT License
tachikoma-grpc/src/main/kotlin/com/sourceforgery/tachikoma/identifiers/MessageIdFactoryImpl.kt
SourceForgery
112,076,342
false
null
package com.sourceforgery.tachikoma.identifiers import org.kodein.di.DI import org.kodein.di.DIAware import java.util.UUID class MessageIdFactoryImpl(override val di: DI) : MessageIdFactory, DIAware { override fun createMessageId(domain: MailDomain) = MessageId("${UUID.randomUUID()}@$domain") }
8
null
3
5
12d8d0e0ccafaa8506b98d6269cae4f1bb228bf4
310
tachikoma
Apache License 2.0
app/src/main/java/com/geekymusketeers/uncrack/presentation/auth/login/LoginScreens.kt
uncrack-vault
569,328,395
false
{"Kotlin": 304649}
package com.geekymusketeers.uncrack.presentation.auth.login import android.app.Activity import android.content.Intent import android.os.Bundle import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.SystemBarStyle import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge 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.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.livedata.observeAsState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import com.geekymusketeers.uncrack.R import com.geekymusketeers.uncrack.components.NoInternetScreen import com.geekymusketeers.uncrack.components.ProgressDialog import com.geekymusketeers.uncrack.components.UCButton import com.geekymusketeers.uncrack.components.UCTextField import com.geekymusketeers.uncrack.presentation.auth.AuthViewModel import com.geekymusketeers.uncrack.presentation.auth.forgotPassword.ForgotPasswordScreen import com.geekymusketeers.uncrack.presentation.auth.signup.SignupScreen import com.geekymusketeers.uncrack.presentation.masterKey.createMasterKey.CreateMasterKeyScreen import com.geekymusketeers.uncrack.ui.theme.DMSansFontFamily import com.geekymusketeers.uncrack.ui.theme.OnPrimaryContainerLight import com.geekymusketeers.uncrack.ui.theme.PrimaryLight import com.geekymusketeers.uncrack.ui.theme.UnCrackTheme import com.geekymusketeers.uncrack.ui.theme.medium16 import com.geekymusketeers.uncrack.util.ConnectivityObserver import com.geekymusketeers.uncrack.util.NetworkConnectivityObserver import com.geekymusketeers.uncrack.util.UtilsKt.findActivity import com.geekymusketeers.uncrack.util.Validator.Companion.isValidEmail import com.geekymusketeers.uncrack.util.Validator.Companion.isValidPassword import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collectLatest @AndroidEntryPoint class LoginScreens : ComponentActivity() { private lateinit var userAuthViewModel: AuthViewModel private lateinit var connectivityObserver: ConnectivityObserver override fun onCreate(savedInstanceState: Bundle?) { enableEdgeToEdge( statusBarStyle = SystemBarStyle.light( Color.White.toArgb(), Color.White.toArgb() ), navigationBarStyle = SystemBarStyle.light( Color.White.toArgb(), Color.White.toArgb() ) ) super.onCreate(savedInstanceState) connectivityObserver = NetworkConnectivityObserver(applicationContext) setContent { UnCrackTheme { var networkStatus by remember { mutableStateOf(ConnectivityObserver.Status.Unavailable) } LaunchedEffect(key1 = true) { connectivityObserver.observe().collectLatest { status -> networkStatus = status } } userAuthViewModel = hiltViewModel() when (networkStatus) { ConnectivityObserver.Status.Available -> { LoginContent(this@LoginScreens, userAuthViewModel) } else -> { NoInternetScreen() } } } } } } @Composable fun LoginContent( activity: Activity, viewModel: AuthViewModel, modifier: Modifier = Modifier ) { val context = LocalContext.current var email by remember { mutableStateOf("") } var password by remember { mutableStateOf("") } var passwordVisibility by remember { mutableStateOf(false) } val isSignInButtonEnable by remember { derivedStateOf { email.isValidEmail() && password.isValidPassword() } } val errorLiveData by viewModel.errorLiveData.observeAsState() val loginSuccess by viewModel.loginSuccess.observeAsState() var isLoading by remember { mutableStateOf(false) } LaunchedEffect(errorLiveData) { errorLiveData?.let { error -> isLoading = false Toast.makeText(context, error, Toast.LENGTH_SHORT).show() } } LaunchedEffect(loginSuccess) { loginSuccess?.let { success -> isLoading = false if (success) { context.findActivity()?.apply { startActivity(Intent(activity, CreateMasterKeyScreen::class.java)) finish() // Optional: close the login activity } } } } Scaffold( modifier = modifier.fillMaxSize() ) { paddingValues -> Column( modifier = Modifier .fillMaxSize() .padding(paddingValues) .padding(16.dp) ) { Text( text = stringResource(R.string.log_in), fontSize = 40.sp, fontWeight = FontWeight.Bold, fontFamily = DMSansFontFamily, color = Color.Black ) Spacer(modifier = Modifier.height(60.dp)) UCTextField( modifier = Modifier.fillMaxWidth(), headerText = stringResource(R.string.email_header), hintText = stringResource(R.string.email_hint), maxLines = 1, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email, imeAction = ImeAction.Next), value = email, onValueChange = { email = it } ) Spacer(modifier = Modifier.height(30.dp)) UCTextField( modifier = Modifier.fillMaxWidth(), headerText = stringResource(R.string.password_header), hintText = stringResource(R.string.password_hint), maxLines = 1, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Done), value = password, onValueChange = { password = it }, visualTransformation = if (passwordVisibility) VisualTransformation.None else PasswordVisualTransformation(), trailingIcon = { val image = if (passwordVisibility) painterResource(id = R.drawable.visibility_off) else painterResource(id = R.drawable.visibility_on) val imageDescription = if (passwordVisibility) stringResource(R.string.show_password) else stringResource(R.string.hide_password) IconButton(onClick = { passwordVisibility = !passwordVisibility }) { Icon( modifier = Modifier.size(24.dp), painter = image, contentDescription = imageDescription ) } } ) Spacer(modifier = Modifier.height(12.dp)) Text( text = stringResource(R.string.forgot_password), modifier = Modifier .align(Alignment.End) .clickable { context.findActivity()?.let { it.startActivity(Intent(it, ForgotPasswordScreen::class.java)) } }, color = MaterialTheme.colorScheme.primary ) Spacer(modifier = Modifier.weight(1f)) UCButton( modifier = Modifier.fillMaxWidth(), text = stringResource(R.string.login), onClick = { isLoading = true viewModel.logIn(email, password) }, enabled = isSignInButtonEnable ) Spacer(modifier = Modifier.height(15.dp)) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center ) { Text( text = stringResource(R.string.don_t_have_an_account), style = medium16.copy(color = OnPrimaryContainerLight) ) Spacer(modifier = Modifier.width(8.dp)) Text( modifier = Modifier.clickable { context.findActivity()?.apply { startActivity(Intent(activity, SignupScreen::class.java)) } }, text = stringResource(R.string.create), style = medium16.copy(color = PrimaryLight) ) } } } if (isLoading) { ProgressDialog {} } }
13
Kotlin
3
28
e44b61c21e67ccce684882a54be87e0977f207c8
10,440
android
MIT License
lib/src/main/java/net/imoya/android/media/audio/AudioDecoder.kt
IceImo-P
452,667,694
false
null
/* * Copyright (C) 2022 IceImo-P * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.imoya.android.media.audio import android.content.Context import android.media.AudioFormat import android.media.AudioTrack import android.media.MediaCodec import android.media.MediaExtractor import android.media.MediaFormat import net.imoya.android.media.MediaLog import java.io.ByteArrayOutputStream import java.io.FileDescriptor import java.io.IOException import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.FloatBuffer import java.nio.ShortBuffer /** * 任意のオーディオファイルを、 [AudioTrack] へ設定可能な音声データへ変換します。 * * Android の [MediaCodec] を使用して任意のオーディオファイルをデコードし、 * [AudioTrack] へ設定可能な音声データを出力します。 * * 入力ファイルは実行環境がデコード可能な任意の形式(MP3, AAC, Ogg Vorbis 等)を利用可能ですが、 * Ogg Vorbis のみ動作確認済みです。 */ class AudioDecoder { /** * コールバック */ interface AudioDecoderCallback { /** * 変換完了時コールバック * * @param decoder 呼び出し元の [AudioDecoder] * @param data 変換の出力(16-bit linear PCM) * @param format [data] のオーディオ形式 */ fun onEnd(decoder: AudioDecoder, data: ByteArray, format: MediaFormat) /** * エラー発生時コールバック * * @param decoder 呼び出し元の [AudioDecoder] * @param e エラー内容 */ fun onError(decoder: AudioDecoder, e: Exception) } /** * 変換コンテキスト */ private class ConversionContext( val decoder: AudioDecoder, val callback: AudioDecoderCallback ) /** * 入力ファイルの読み取りに使用する [MediaExtractor] */ private var extractor: MediaExtractor = MediaExtractor() /** * 入力ファイルのトラック番号 */ private var track = -1 /** * [MediaCodec] の出力フォーマット */ private lateinit var outputFormat: MediaFormat /** * 出力の PCM エンコーディング */ private var pcmEncoding: Int = AudioFormat.ENCODING_PCM_16BIT /** * リソースIDを使用して入力ファイルを設定する * * @param context [Context] * @param resourceId リソースID */ @Throws(IOException::class) fun setSource(context: Context, resourceId: Int) { val fd = context.resources.openRawResourceFd(resourceId) extractor.setDataSource(fd.fileDescriptor, fd.startOffset, fd.length) this.checkFormat() } /** * [FileDescriptor] を使用して入力ファイルを設定する * * @param source [FileDescriptor] */ @Suppress("unused") @Throws(IOException::class) fun setSource(source: FileDescriptor) { extractor.setDataSource(source) this.checkFormat() } /** * 入力ファイルの形式をチェックする * * @throws IllegalArgumentException 入力ファイルは Android がサポートするオーディオ形式ではありません。 */ private fun checkFormat() { track = -1 run loop@{ (0 until extractor.trackCount).forEach { val format = extractor.getTrackFormat(it) val mimeType = format.getString(MediaFormat.KEY_MIME) // MediaLog.v(TAG) { "checkFormat: MIME type for track $it is: $mimeType" } if (mimeType != null && mimeType.startsWith("audio/")) { track = it // MediaLog.v(TAG) { "checkFormat: Audio track found: $it" } return@loop } } } // MediaLog.v(TAG) { "checkFormat: Audio track is: $track" } require(track >= 0) { "Illegal media type: No audio track at source" } extractor.selectTrack(track) } /** * 変換を実行します。 */ fun convert(callback: AudioDecoderCallback) { try { // MediaLog.v(TAG, "convert: start") val format = extractor.getTrackFormat(track) val mimeType = format.getString(MediaFormat.KEY_MIME) val decoder = MediaCodec.createDecoderByType(mimeType!!) decoder.setCallback(CodecCallback(ConversionContext(this, callback))) decoder.configure(format, null, null, 0) outputFormat = decoder.outputFormat pcmEncoding = AudioUtility.getAudioEncoding(outputFormat) // MediaLog.v(TAG) { "convert: Output = $outputFormat" } decoder.start() // MediaLog.v(TAG, "convert: end") } catch (e: Exception) { callback.onError(this, e) } } /** * [MediaCodec.Callback] の実装 */ private inner class CodecCallback(val context: ConversionContext) : MediaCodec.Callback() { /** * デコード済みオーディオデータの一時保存バッファ */ val destination = ByteArrayOutputStream() override fun onInputBufferAvailable(codec: MediaCodec, index: Int) { try { // 入力ファイルよりオーディオデータを読み取り入力バッファーへ設定する // MediaLog.v(TAG) { "onInputBufferAvailable: start. index = $index" } val buffer = codec.getInputBuffer(index) if (buffer != null) { val read = extractor.readSampleData(buffer, 0) if (read < 0) { // ファイル終端へ達した場合は終端フラグをセットする // MediaLog.v(TAG, "Input EOF") codec.queueInputBuffer(index, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM) } else { // MediaLog.v(TAG) { "Input length = $read" } val sampleTime = extractor.sampleTime if (extractor.advance()) { codec.queueInputBuffer(index, 0, read, sampleTime, 0) } else { // MediaLog.v(TAG, "Input EOF (with data)") codec.queueInputBuffer( index, 0, read, sampleTime, MediaCodec.BUFFER_FLAG_END_OF_STREAM ) } } } else { MediaLog.w( TAG, "onInputBufferAvailable: No buffer available(MediaCodec returned null)" ) } } catch (e: Exception) { errorProcess(codec, e) } } override fun onOutputBufferAvailable( codec: MediaCodec, index: Int, info: MediaCodec.BufferInfo ) { // MediaLog.v(TAG) { "onOutputBufferAvailable: start. index = $index" } try { val buffer = codec.getOutputBuffer(index) if (buffer != null) { when (pcmEncoding) { AudioFormat.ENCODING_PCM_8BIT -> output8bit(buffer) AudioFormat.ENCODING_PCM_16BIT -> output16bit(buffer) AudioFormat.ENCODING_PCM_FLOAT -> outputFloat(buffer) else -> throw IllegalArgumentException("Unexpected PCM encoding: $pcmEncoding") } codec.releaseOutputBuffer(index, false) } else { MediaLog.w( TAG, "onOutputBufferAvailable: No buffer available(MediaCodec returned null)" ) } // 終端か? if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) { // 終端である場合 // MediaLog.v(TAG, "Output EOF") destination.close() codec.stop() codec.release() extractor.release() // 変換完了時コールバックをコール context.callback.onEnd(context.decoder, destination.toByteArray(), outputFormat) } } catch (e: Exception) { errorProcess(codec, e) } } override fun onError(codec: MediaCodec, e: MediaCodec.CodecException) { errorProcess(codec, e) } override fun onOutputFormatChanged(codec: MediaCodec, format: MediaFormat) { // MediaLog.w(TAG, "Changing media format function is not supported.") } /** * 8-bit PCM を出力バッファへコピーします。 */ private fun output8bit(buffer: ByteBuffer) { destination.write(buffer.array()) } /** * 16-bit PCM を出力バッファへコピーします。 */ private fun output16bit(buffer: ByteBuffer) { val samples: ShortBuffer = buffer.order(ByteOrder.nativeOrder()).asShortBuffer() val writableBuffer = ByteBuffer.allocate(samples.remaining() * 2) val convertedSamples: ShortBuffer = writableBuffer.order(ByteOrder.nativeOrder()).asShortBuffer() while (samples.remaining() > 0) { convertedSamples.put(samples.get()) } destination.write(writableBuffer.array()) } /** * Float PCM を出力バッファへコピーします。 */ private fun outputFloat(buffer: ByteBuffer) { val samples: FloatBuffer = buffer.order(ByteOrder.nativeOrder()).asFloatBuffer() val writableBuffer = ByteBuffer.allocate(samples.remaining() * 2) val convertedSamples: FloatBuffer = writableBuffer.order(ByteOrder.nativeOrder()).asFloatBuffer() while (samples.remaining() > 0) { convertedSamples.put(samples.get()) } destination.write(writableBuffer.array()) } /** * エラー発生時の処理 */ private fun errorProcess(codec: MediaCodec, e: Exception) { MediaLog.i(TAG) { "Error: $e" } try { destination.close() codec.stop() codec.release() extractor.release() } catch (e: Exception) { } // エラー発生時コールバックをコール context.callback.onError(context.decoder, e) } } companion object { /** * Tag for log */ private const val TAG = "ImoMediaLib.AudioDecoder" } }
0
Kotlin
0
0
3ed3fa7799024ca3535e849e98d4975be96a2188
10,669
ImoyaAndroidMediaLib
Apache License 2.0
buildSrc/src/main/java/DaggerHilt.kt
tahaak67
508,754,612
false
null
object DaggerHilt { const val version = "2.44.2" const val hiltAndroid = "com.google.dagger:hilt-android:$version" const val hiltCompiler = "com.google.dagger:hilt-android-compiler:$version" }
8
null
4
96
f7efae3a6d3b0ba52b3cdf082727f6beb8eb74d9
206
Farhan
Apache License 2.0
app/src/main/java/com/yinlei/sunnyweather/logic/model/RealtimeResponse.kt
yinleiCoder
257,759,475
false
null
package com.sunnyweather.android.logic.model import com.google.gson.annotations.SerializedName //{ // "status": "ok", // "result": { // "realtime": { // "temperature": 23.16, // "skycon": "WIND", // "air_quality": { // "aqi": { "chn": 17.0 } // } // } // } //} data class RealtimeResponse(val status: String, val result: Result) { data class Result(val realtime: Realtime) data class Realtime(val skycon: String, val temperature: Float, @SerializedName("air_quality") val airQuality: AirQuality) data class AirQuality(val aqi: AQI) data class AQI(val chn: Float) }
0
null
0
3
e560b250f72d52fa5d0a7af604d1fd93ea5277f6
729
SunnyWeather
Apache License 2.0
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/apprunner/CfnObservabilityConfigurationPropsDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package io.cloudshiftdev.awscdkdsl.services.apprunner import io.cloudshiftdev.awscdkdsl.CfnTagDsl import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker import kotlin.String import kotlin.Unit import kotlin.collections.Collection import kotlin.collections.MutableList import software.amazon.awscdk.CfnTag import software.amazon.awscdk.IResolvable import software.amazon.awscdk.services.apprunner.CfnObservabilityConfiguration import software.amazon.awscdk.services.apprunner.CfnObservabilityConfigurationProps /** * Properties for defining a `CfnObservabilityConfiguration`. * * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.apprunner.*; * CfnObservabilityConfigurationProps cfnObservabilityConfigurationProps = * CfnObservabilityConfigurationProps.builder() * .observabilityConfigurationName("observabilityConfigurationName") * .tags(List.of(CfnTag.builder() * .key("key") * .value("value") * .build())) * .traceConfiguration(TraceConfigurationProperty.builder() * .vendor("vendor") * .build()) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apprunner-observabilityconfiguration.html) */ @CdkDslMarker public class CfnObservabilityConfigurationPropsDsl { private val cdkBuilder: CfnObservabilityConfigurationProps.Builder = CfnObservabilityConfigurationProps.builder() private val _tags: MutableList<CfnTag> = mutableListOf() /** * @param observabilityConfigurationName A name for the observability configuration. When you * use it for the first time in an AWS Region , App Runner creates revision number `1` of this * name. When you use the same name in subsequent calls, App Runner creates incremental * revisions of the configuration. * * The name `DefaultConfiguration` is reserved. You can't use it to create a new observability * configuration, and you can't create a revision of it. * * When you want to use your own observability configuration for your App Runner service, * *create a configuration with a different name* , and then provide it when you create or * update your service. * * If you don't specify a name, AWS CloudFormation generates a name for your observability * configuration. */ public fun observabilityConfigurationName(observabilityConfigurationName: String) { cdkBuilder.observabilityConfigurationName(observabilityConfigurationName) } /** * @param tags A list of metadata items that you can associate with your observability * configuration resource. A tag is a key-value pair. */ public fun tags(tags: CfnTagDsl.() -> Unit) { _tags.add(CfnTagDsl().apply(tags).build()) } /** * @param tags A list of metadata items that you can associate with your observability * configuration resource. A tag is a key-value pair. */ public fun tags(tags: Collection<CfnTag>) { _tags.addAll(tags) } /** * @param traceConfiguration The configuration of the tracing feature within this observability * configuration. If you don't specify it, App Runner doesn't enable tracing. */ public fun traceConfiguration(traceConfiguration: IResolvable) { cdkBuilder.traceConfiguration(traceConfiguration) } /** * @param traceConfiguration The configuration of the tracing feature within this observability * configuration. If you don't specify it, App Runner doesn't enable tracing. */ public fun traceConfiguration( traceConfiguration: CfnObservabilityConfiguration.TraceConfigurationProperty ) { cdkBuilder.traceConfiguration(traceConfiguration) } public fun build(): CfnObservabilityConfigurationProps { if (_tags.isNotEmpty()) cdkBuilder.tags(_tags) return cdkBuilder.build() } }
4
null
0
3
256ad92aebe2bcf9a4160089a02c76809dbbedba
4,235
awscdk-dsl-kotlin
Apache License 2.0
app/src/main/java/com/teobaranga/monica/contacts/detail/ContactDetailScreen.kt
teobaranga
686,113,276
false
{"Kotlin": 183003}
package com.teobaranga.monica.contacts.detail import ContactsNavGraph import androidx.compose.animation.Crossfade import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.ramcosta.composedestinations.annotation.Destination import com.ramcosta.composedestinations.navigation.DestinationsNavigator import com.teobaranga.monica.contacts.detail.ui.ContactInfoContactSection import com.teobaranga.monica.contacts.detail.ui.ContactInfoPersonalSection import com.teobaranga.monica.contacts.detail.ui.ContactInfoRelationshipsSection import com.teobaranga.monica.contacts.detail.ui.ContactInfoWorkSection import com.teobaranga.monica.contacts.detail.ui.fullNameItem import com.teobaranga.monica.contacts.detail.ui.infoSectionTabs import com.teobaranga.monica.contacts.detail.ui.userAvatarItem import com.teobaranga.monica.ui.PreviewPixel4 import com.teobaranga.monica.ui.avatar.UserAvatar import com.teobaranga.monica.ui.theme.MonicaTheme import com.teobaranga.monica.util.compose.nestedScrollParentFirst @ContactsNavGraph @Destination @Composable fun ContactDetail( navigator: DestinationsNavigator, contactId: Int, ) { val viewModel = hiltViewModel<ContactDetailViewModel, ContactDetailViewModel.Factory>( creationCallback = { factory: ContactDetailViewModel.Factory -> factory.create(contactId) }, ) val contactDetail by viewModel.contact.collectAsStateWithLifecycle() Crossfade( targetState = contactDetail, label = "ContactDetailScreen", ) { contactDetail -> when (contactDetail) { null -> { // TODO Loading } else -> { ContactDetailScreen( contactDetail = contactDetail, onBack = navigator::popBackStack, ) } } } } @OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class) @Composable private fun ContactDetailScreen( contactDetail: ContactDetail, onBack: () -> Unit, ) { Scaffold( topBar = { TopAppBar( title = { }, navigationIcon = { IconButton( onClick = onBack, ) { Icon( imageVector = Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "", ) } }, ) }, ) { contentPadding -> val pagerState = rememberPagerState( pageCount = { contactDetail.infoSections.size }, ) //noinspection UnusedBoxWithConstraintsScope - actually used through multiple context receivers BoxWithConstraints( modifier = Modifier .background(MaterialTheme.colorScheme.background) .fillMaxSize() .padding(contentPadding) ) { val state = rememberLazyListState() LazyColumn( modifier = Modifier .background(MaterialTheme.colorScheme.background) .fillMaxSize() .nestedScrollParentFirst(state), horizontalAlignment = Alignment.CenterHorizontally, state = state, ) { userAvatarItem(contactDetail.userAvatar) fullNameItem(contactDetail.fullName) infoSectionTabs( pagerState = pagerState, infoSections = contactDetail.infoSections, ) } } } } @Composable @PreviewPixel4 private fun PreviewContactDetailScreen() { MonicaTheme { ContactDetailScreen( contactDetail = ContactDetail( fullName = "<NAME> (Johnny)", userAvatar = UserAvatar( contactId = -1, initials = "JD", color = "#709512", avatarUrl = null, ), infoSections = listOf( ContactInfoPersonalSection(birthday = null), ContactInfoContactSection, ContactInfoWorkSection, ContactInfoRelationshipsSection, ), ), onBack = { }, ) } }
3
Kotlin
0
6
ee45fbea6028a57f73d10154e60a671e80d59fc4
5,442
monica
Apache License 2.0
app/src/test/java/com/femi/e_class/domain/use_case/ValidateEmailTest.kt
Vader-Femi
569,005,599
false
null
package com.femi.e_class.domain.use_case import com.google.common.truth.Truth.assertThat import org.junit.Test class ValidateEmailTest { @Test fun `email is blank fails`(){ val result = ValidateEmail().execute("") assertThat(result).isEqualTo( ValidationResult( false, "Email can't be black" ) ) } @Test fun `email contains uppercase characters fails`(){ val result = ValidateEmail().execute("<EMAIL>") assertThat(result).isEqualTo( ValidationResult( false, "Email must not contain upper-case letters" ) ) } @Test fun `email is invalid fails`(){ val result = ValidateEmail().execute("<EMAIL>") assertThat(result).isEqualTo( ValidationResult( false, "That's not a valid email" ) ) } @Test fun `email is acceptable succeeds`(){ val result = ValidateEmail().execute("<EMAIL>") assertThat(result).isEqualTo( ValidationResult( true ) ) } }
0
Kotlin
0
1
d334fafbac93322715e647827dc830e4221264b9
1,194
ClassKonnect
Apache License 2.0
DaggerSingleModuleApp/app/src/main/java/com/github/yamamotoj/daggersinglemoduleapp/package15/Foo01585.kt
yamamotoj
163,851,411
false
{"Text": 1, "Ignore List": 30, "Markdown": 1, "Gradle": 34, "Java Properties": 11, "Shell": 6, "Batchfile": 6, "Proguard": 22, "Kotlin": 36021, "XML": 93, "INI": 1, "Java": 32, "Python": 2}
package com.github.yamamotoj.module4.package15 import javax.inject.Inject class Foo01585 @Inject constructor(){ fun method0() { Foo01584().method5() } fun method1() { method0() } fun method2() { method1() } fun method3() { method2() } fun method4() { method3() } fun method5() { method4() } }
0
Kotlin
0
9
2a771697dfebca9201f6df5ef8441578b5102641
317
android_multi_module_experiment
Apache License 2.0
src/test/kotlin/com/forgerock/sapi/gateway/ob/uk/tests/functional/account/statements/junit/v3_1_9/GetStatementsTest.kt
SecureApiGateway
330,627,234
false
{"Kotlin": 3153129, "Dockerfile": 478, "Makefile": 215}
package com.forgerock.sapi.gateway.ob.uk.tests.functional.account.statements.junit.v3_1_9 import com.forgerock.sapi.gateway.framework.extensions.junit.CreateTppCallback import com.forgerock.sapi.gateway.framework.extensions.junit.EnabledIfVersion import com.forgerock.sapi.gateway.uk.common.shared.api.meta.obie.OBVersion import com.forgerock.sapi.gateway.ob.uk.tests.functional.account.statements.api.v3_1_8.GetStatements import org.junit.jupiter.api.Test class GetStatementsTest(val tppResource: CreateTppCallback.TppResource) { @EnabledIfVersion( type = "accounts", apiVersion = "v3.1.9", operations = ["CreateAccountAccessConsent", "GetAccounts", "GetStatements"], apis = ["statements"] ) @Test fun shouldGetStatements_v3_1_9() { GetStatements(OBVersion.v3_1_9, tppResource).shouldGetStatementsTest() } }
7
Kotlin
0
5
cda628f0823fe1f21939dd4affc78588206c1ab2
870
secure-api-gateway-ob-uk-functional-tests
Apache License 2.0
app/src/main/java/com/personal/tmdb/settings/presentation/appearance/components/Corners.kt
Avvami
755,489,313
false
{"Kotlin": 656155}
package com.personal.tmdb.settings.presentation.appearance.components import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Slider import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.State import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import com.personal.tmdb.R import com.personal.tmdb.UiEvent import com.personal.tmdb.core.presentation.PreferencesState @Composable fun Corners( preferencesState: State<PreferencesState>, uiEvent: (UiEvent) -> Unit ) { Column( modifier = Modifier .background(MaterialTheme.colorScheme.surfaceContainerLow) .padding(horizontal = 16.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(4.dp) ) { Text( text = stringResource(id = R.string.corners), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.primary ) Row( horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically ) { Slider( modifier = Modifier.weight(1f), value = preferencesState.value.corners.toFloat(), onValueChange = { uiEvent(UiEvent.SetCorners(it.toInt())) }, valueRange = 6f..24f ) Text( modifier = Modifier.weight(.15f), text = preferencesState.value.corners.toString(), color = MaterialTheme.colorScheme.primary, textAlign = TextAlign.Center ) } } }
0
Kotlin
0
2
d5b4d2ee9eb9616ab0e217f8d6fff45723bf5e58
2,064
TMDB
MIT License
app/src/main/java/com/anubhav_auth/bento/authentication/OTPVerificationPage.kt
anubhav-auth
850,108,148
false
{"Kotlin": 125228}
package com.anubhav_auth.bento.authentication import android.os.CountDownTimer import android.util.Log import android.widget.Toast import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.imePadding 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.foundation.text.BasicText import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import com.anubhav_auth.bento.ui.theme.MyFonts @Composable fun OTPVerificationPage( otpLength: Int = 6, navController: NavController, phoneNumber:String = "0000000000", authViewModel: AuthViewModel ) { val context = LocalContext.current val otpValues = remember { mutableStateListOf("", "", "", "", "", "") } val focusRequesters = List(otpLength) { FocusRequester() } val authState by authViewModel.authState.collectAsState() LaunchedEffect(authState) { when (authState) { is AuthState.Authenticated -> navController.navigate("locationAccessPage") is AuthState.Error -> Toast.makeText( context, (authState as AuthState.Error).message, Toast.LENGTH_SHORT ).show() else -> Unit } } val onContinue:() -> Unit = { if (otpValues.joinToString("").length < 6 || otpValues.joinToString("").length > 6){ Toast.makeText(context, "Enter the OTP correctly", Toast.LENGTH_SHORT).show() }else{ authViewModel.verifyCode(otpValues.joinToString("")) } } Box(modifier = Modifier.padding(12.dp)) { Column( modifier = Modifier .fillMaxSize() ) { Icon( imageVector = Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "", modifier = Modifier .size(27.dp) .clickable { navController.navigateUp() } ) Spacer(modifier = Modifier.height(12.dp)) Text( text = "Verify your details", fontSize = 30.sp, fontFamily = MyFonts.montserrat_semi_bold, fontWeight = FontWeight.Bold ) Spacer(modifier = Modifier.height(6.dp)) Text( text = "Enter OTP sent to +91 $phoneNumber via sms", fontSize = 15.sp, fontFamily = FontFamily.Default ) Spacer(modifier = Modifier.height(48.dp)) Text( text = "Enter OTP", fontSize = 18.sp, fontFamily = MyFonts.lato_regular, fontWeight = FontWeight.W600 ) Spacer(modifier = Modifier.height(12.dp)) Row( modifier = Modifier .fillMaxWidth(), ) { otpValues.forEachIndexed { index, otpValue -> OutlinedTextField( value = otpValue, onValueChange = { if (it.length <= 1) { otpValues[index] = it if (it.isNotEmpty() && index < otpLength - 1) { focusRequesters[index + 1].requestFocus() } else if (it.isEmpty() && index > 0) { focusRequesters[index - 1].requestFocus() } } }, modifier = Modifier .size(60.dp) .focusRequester(focusRequesters[index]) .padding(4.dp), textStyle = TextStyle( textAlign = TextAlign.Center, fontSize = 20.sp, fontWeight = FontWeight.Bold ), singleLine = true, maxLines = 1, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), shape = RoundedCornerShape(8.dp) ) LaunchedEffect(Unit) { if (index == 0) focusRequesters[index].requestFocus() } } } Spacer(modifier = Modifier.height(12.dp)) Row { Text( text = "Didn't receive OTP?", fontSize = 12.sp, fontFamily = MyFonts.lato_regular, fontWeight = FontWeight.W600 ) Spacer(modifier = Modifier.width(9.dp)) Text( text = "Resend", fontSize = 12.sp, modifier = Modifier .clickable { }, color = Color(0xFF49CA3E) ) Spacer(modifier = Modifier.width(50.dp)) Timer() } } Column(modifier = Modifier .align(Alignment.BottomCenter) .imePadding()) { Button( modifier = Modifier .fillMaxWidth() .height(45.dp) , onClick = { onContinue() }, shape = RoundedCornerShape(9.dp), colors = ButtonDefaults.buttonColors( containerColor = Color.Black ) ) { Text(text = "Continue", fontSize = 18.sp) } Spacer(modifier = Modifier.height(12.dp)) } } } @Composable fun Timer() { // Define a state to hold the remaining time val timerState = remember { mutableStateOf("60") } // Create a CountDownTimer LaunchedEffect(Unit) { object : CountDownTimer(60000, 1000) { override fun onTick(millisUntilFinished: Long) { val seconds = (millisUntilFinished / 1000).toInt() timerState.value = String.format("%02d", seconds) } override fun onFinish() { timerState.value = "00" } }.start() } // Display the timer Text( text = "00:${timerState.value}", fontSize = 12.sp, ) }
0
Kotlin
0
0
b27c5a1f750ffe58efe2d3b72b9cd35d8c1b9b67
8,352
Bento
MIT License
markdown/src/main/java/com/bohregard/markdown/extensions/superscript/util/Superscript.kt
bohregard
284,123,182
false
{"Kotlin": 177825}
package com.bohregard.markdown.extensions.superscript.util import org.commonmark.node.CustomNode class Superscript : CustomNode()
0
Kotlin
0
0
de7011b118bbd97ec9d5a7acd9bb66e0c02519cc
131
Compose-Companion
MIT License
plugins/ide-startup/importSettings/src/com/intellij/ide/startup/importSettings/transfer/backend/providers/vscode/parsers/Json.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.startup.importSettings.transfer.backend.providers.vscode.parsers import com.fasterxml.jackson.core.json.JsonReadFeature import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.json.JsonMapper internal val vsCodeJsonMapper: ObjectMapper get() = JsonMapper.builder() .enable(JsonReadFeature.ALLOW_JAVA_COMMENTS, JsonReadFeature.ALLOW_TRAILING_COMMA) .build()
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
548
intellij-community
Apache License 2.0
year2021/day07/part1/src/main/kotlin/com/curtislb/adventofcode/year2021/day07/part1/Year2021Day07Part1.kt
curtislb
226,797,689
false
null
/* --- Day 7: The Treachery of Whales --- A giant whale has decided your submarine is its next meal, and it's much faster than you are. There's nowhere to run! Suddenly, a swarm of crabs (each in its own tiny submarine - it's too deep for them otherwise) zooms in to rescue you! They seem to be preparing to blast a hole in the ocean floor; sensors indicate a massive underground cave system just beyond where they're aiming! The crab submarines all need to be aligned before they'll have enough power to blast a large enough hole for your submarine to get through. However, it doesn't look like they'll be aligned before the whale catches you! Maybe you can help? There's one major catch - crab submarines can only move horizontally. You quickly make a list of the horizontal position of each crab (your puzzle input). Crab submarines have limited fuel, so you need to find a way to make all of their horizontal positions match while requiring them to spend as little fuel as possible. For example, consider the following horizontal positions: ``` 16,1,2,0,4,2,7,1,2,14 ``` This means there's a crab with horizontal position 16, a crab with horizontal position 1, and so on. Each change of 1 step in horizontal position of a single crab costs 1 fuel. You could choose any horizontal position to align them all on, but the one that costs the least fuel is horizontal position 2: - Move from 16 to 2: 14 fuel - Move from 1 to 2: 1 fuel - Move from 2 to 2: 0 fuel - Move from 0 to 2: 2 fuel - Move from 4 to 2: 2 fuel - Move from 2 to 2: 0 fuel - Move from 7 to 2: 5 fuel - Move from 1 to 2: 1 fuel - Move from 2 to 2: 0 fuel - Move from 14 to 2: 12 fuel This costs a total of 37 fuel. This is the cheapest possible outcome; more expensive outcomes include aligning at position 1 (41 fuel), position 3 (39 fuel), or position 10 (71 fuel). Determine the horizontal position that the crabs can align to using the least fuel possible. How much fuel must they spend to align to that position? */ package com.curtislb.adventofcode.year2021.day07.part1 import com.curtislb.adventofcode.common.io.readInts import com.curtislb.adventofcode.common.math.medianOrNull import java.nio.file.Path import java.nio.file.Paths import kotlin.math.abs /** * Returns the solution to the puzzle for 2021, day 7, part 1. * * @param inputPath The path to the input file for this puzzle. */ fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Int { val positions = inputPath.toFile().readInts() val bestPosition = positions.medianOrNull() ?: 0 return positions.sumOf { abs(it - bestPosition) } } fun main() { println(solve()) }
0
Kotlin
1
1
e9ef1f42e245d730edeb0ebec57de515992d84e5
2,654
AdventOfCode
MIT License
app/src/main/java/com/example/housify/propertyInfoActivity.kt
amanahmed97
738,706,281
false
{"Kotlin": 271621}
package com.example.housify import android.content.Intent import android.content.pm.PackageManager import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.os.Bundle import android.Manifest import android.annotation.SuppressLint import android.content.ClipDescription import android.util.Base64 import android.util.Log import android.widget.Button import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FieldValue import com.google.firebase.firestore.FirebaseFirestore import com.tomtom.sdk.common.SystemClock import com.tomtom.sdk.location.GeoLocation import com.tomtom.sdk.location.GeoPoint import com.tomtom.sdk.map.display.MapOptions import com.tomtom.sdk.map.display.TomTomMap import com.tomtom.sdk.map.display.camera.CameraOptions import com.tomtom.sdk.map.display.camera.CameraTrackingMode import com.tomtom.sdk.map.display.gesture.GestureType import com.tomtom.sdk.map.display.image.ImageFactory import com.tomtom.sdk.map.display.location.LocationAccuracyPolicy import com.tomtom.sdk.map.display.location.LocationMarkerOptions import com.tomtom.sdk.map.display.marker.Marker import com.tomtom.sdk.map.display.marker.MarkerOptions import com.tomtom.sdk.map.display.style.StyleMode import com.tomtom.sdk.map.display.ui.MapFragment import com.tomtom.sdk.search.Search import com.tomtom.sdk.search.SearchCallback import com.tomtom.sdk.search.SearchOptions import com.tomtom.sdk.search.SearchResponse import com.tomtom.sdk.search.common.error.SearchFailure import com.tomtom.sdk.search.online.OnlineSearch import kotlin.properties.Delegates import kotlin.time.Duration.Companion.nanoseconds import kotlin.time.Duration.Companion.seconds // Property view information activity class propertyInfoActivity : AppCompatActivity() { private lateinit var propertyLocation: TextView private lateinit var propertyTitle: TextView private lateinit var propertyDescription: TextView private lateinit var propertyBedrooms: TextView private lateinit var propertyBaths: TextView private lateinit var propertyType: TextView private lateinit var propertyYear: TextView private lateinit var propertyRent: TextView private lateinit var propertyAmenities: TextView private lateinit var propertyRoommates: TextView private lateinit var propertyArea: TextView private lateinit var propertyImages: ImageView private lateinit var propertyUid: TextView private lateinit var addUserToCurrentUserCollection: ImageView private lateinit var propUid: String private lateinit var phoneNumber: String private lateinit var tomTomMap: TomTomMap private lateinit var userName : TextView private lateinit var callToUser : ImageView private lateinit var zoomIn : ImageView private var sentFirstName: String = "" private var sentLastName: String = "" private var sentNumber: String = "" private var sentUserImage: String = "" private var sentUserUid: String = "" private var propertyLongitude:Double = 0.0 private var propertyLatitude:Double = 0.0 private var propertyLocationAddressPinned: String="" private lateinit var zoomOut : ImageView private lateinit var phoneNumbeListedWithUser : TextView @SuppressLint("Range") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_property_info) propertyTitle = findViewById(R.id.propertyTitle) propertyDescription = findViewById(R.id.propertyDescription) propertyLocation = findViewById(R.id.propertyLocation) propertyBedrooms = findViewById(R.id.propertyBedrooms) propertyBaths = findViewById(R.id.propertyBaths) propertyType = findViewById(R.id.propertyType) propertyYear = findViewById(R.id.propertyYear) propertyArea = findViewById(R.id.propertyArea) propertyAmenities = findViewById(R.id.propertyAmenities) propertyRent = findViewById(R.id.propertyRent) propertyRoommates = findViewById(R.id.propertyTotalRoommates) propertyImages = findViewById<ImageView>(R.id.propertyImages) propertyUid = findViewById(R.id.propertyUidInfo) addUserToCurrentUserCollection = findViewById(R.id.chatUserNow) userName = findViewById(R.id.usernameInfoPage) callToUser = findViewById(R.id.phoneUser) phoneNumbeListedWithUser = findViewById(R.id.propertyUserListedPhoneNumber) val searchApi = OnlineSearch.create(this, "eXRlAZJos3TBi0kr7fSrXrp8Kl7Nt1e8") val extras = intent.extras if (extras != null) { val propName = extras.getString("propertyName") val propLocation = extras.getString("propertyLocation") propUid = extras.getString("propertyUid").toString() val propUserUid = extras.getString("userUid").toString() propertyTitle.text = propName propertyBedrooms.text = "3" propertyLocation.text = propLocation propertyUid.text = propUid Toast.makeText(this,"$propUserUid",Toast.LENGTH_LONG).show() phoneNumber= getUserNameFromUid(propUserUid) Toast.makeText(this,"$phoneNumber",Toast.LENGTH_LONG).show() callToUser.setOnClickListener{ if (phoneNumbeListedWithUser.text.isNotEmpty()) { if (ContextCompat.checkSelfPermission( this, Manifest.permission.CALL_PHONE ) == PackageManager.PERMISSION_GRANTED ) { val intent = Intent(Intent.ACTION_CALL) intent.data = Uri.parse("tel:$phoneNumber") startActivity(intent) } else { ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.CALL_PHONE), 100 ) } } else { Toast.makeText(this, "Phone number is empty", Toast.LENGTH_SHORT).show() } } val propertyLocation = propLocation val options = propertyLocation?.let { SearchOptions(query = it, limit = 1) } if (options != null) { val search = searchApi.search(options, object : SearchCallback { override fun onSuccess(result: SearchResponse) { if (result.results.isNotEmpty()) { val firstResult = result.results.first() val place = firstResult.place if (place != null && place.coordinate != null) { val latitude = place.coordinate.latitude val longitude = place.coordinate.longitude propertyLatitude=latitude propertyLongitude =longitude propertyLocationAddressPinned = propLocation setupMap() Log.d("TomTom", "Latitude: $latitude, Longitude: $longitude") } // val location = firstResult.position // val latitude = location.latitude // val longitude = location.longitude // Log.d("TomTom", "Latitude: $latitude, Longitude: $longitude") } else { } } override fun onFailure(failure: SearchFailure) { } }) } propUid?.let { propertyUid -> FirebaseFirestore.getInstance().collection("Properties").document(propUid).get() .addOnSuccessListener { document -> if (document != null) { var userImageBase64 = document.getString("userPropertyImages") if (!userImageBase64.isNullOrBlank()) { var decodedImage = decodeBase64ToBitmap(userImageBase64) propertyImages.setImageBitmap(decodedImage) } } else { Log.d("Property View Info", "Property details not found") } // Property Details propertyBaths.text = document.getString("propertyBathrooms") propertyBedrooms.text = document.getString("propertyBedrooms") propertyArea.text = document.getString("propertyArea") propertyRent.text = document.getString("propertyPrice") propertyYear.text = document.getString("propertyYear") propertyType.text = document.getString("propertyType") propertyRoommates.text = document.getString("propertyTotalRoommatesNeeded") propertyDescription.text = document.getString("propertyDescription") // var amenities = (document.get("propertyFacilities") as? ArrayList<Map<String, Any>> var amenities = (document.get("propertyFacilities") as? ArrayList<String>).toString() amenities = amenities.substring(1, amenities.length - 1); propertyAmenities.text = amenities }.addOnFailureListener { exception -> Log.e("Property View Info", "Error getting property details", exception) } } addUserToCurrentUserCollection.setOnClickListener { sentNumber = getUserNameFromUid(propUserUid) val intent = Intent(this, chatUserActivity::class.java) intent.putExtra("sentFirstName", sentFirstName) intent.putExtra("sentLastName", sentLastName) intent.putExtra("sentNumber", sentNumber) intent.putExtra("sentUserImage", sentUserImage) intent.putExtra("sentUserUid", sentUserUid) startActivity(intent) } } } private fun setupMap() { val mapOptions = MapOptions(mapKey = "<KEY>") val mapFragment = MapFragment.newInstance(mapOptions) supportFragmentManager.beginTransaction() .replace(R.id.map_fragment, mapFragment) .commit() val amsterdam = GeoPoint(propertyLatitude, propertyLongitude) val markerOptions = MarkerOptions( coordinate = amsterdam, pinImage = ImageFactory.fromResource(R.drawable.ic_location_marker) ) mapFragment.getMapAsync{ tomtomMap -> [email protected] = tomtomMap tomTomMap.setFrameRate(24) tomTomMap.setStyleMode(StyleMode.DARK) val layers = tomTomMap.layers tomTomMap.showHillShading() val mapLocationProvider = tomTomMap.getLocationProvider() val isLocationInVisibleArea = tomTomMap.isCurrentLocationInMapBoundingBox val currentLocation: GeoLocation? = tomTomMap.currentLocation val locationMarkerOptions = LocationMarkerOptions( type = LocationMarkerOptions.Type.Chevron ) tomTomMap.enableLocationMarker(locationMarkerOptions) tomTomMap.locationAccuracyPolicy = LocationAccuracyPolicy { location: GeoLocation -> val isAccurate = (location.accuracy?.inMeters() ?: 0.0) < 100.0 val isFresh = location.elapsedRealtimeNanos.nanoseconds > (SystemClock.elapsedRealtimeNanos().nanoseconds - 60.seconds) isAccurate && isFresh } tomtomMap.addMapClickListener { coordinate: GeoPoint -> val newCameraOptions = CameraOptions( position = amsterdam, zoom = 15.0, ) tomTomMap.moveCamera(newCameraOptions) return@addMapClickListener true } tomtomMap.addMapDoubleClickListener { coordinate: GeoPoint -> val newCameraOptions = CameraOptions( position = amsterdam, zoom = 20.0, ) tomTomMap.moveCamera(newCameraOptions) return@addMapDoubleClickListener true } tomtomMap.addMapLongClickListener { coordinate: GeoPoint -> val newCameraOptions = CameraOptions( position = amsterdam, zoom = 10.0, ) tomTomMap.moveCamera(newCameraOptions) return@addMapLongClickListener true } tomtomMap.changeGestureExclusions(GestureType.Move, setOf(GestureType.Scale)) tomtomMap.changeGestureExclusions(GestureType.Move, setOf()) val cameraPosition = tomTomMap.cameraPosition val markerOptions = MarkerOptions( coordinate = amsterdam, pinImage = ImageFactory.fromResource(R.drawable.ic_location_marker), balloonText = "$propertyLocationAddressPinned" ) this.tomTomMap.addMarker(markerOptions) tomTomMap.addMarkerClickListener { marker: Marker -> if (!marker.isSelected()) { marker.select() }} val amsterdam = GeoPoint(propertyLatitude, propertyLongitude) val newCameraOptions = CameraOptions( position = amsterdam, zoom = 5.0, ) tomTomMap.moveCamera(newCameraOptions) } } private fun createChatDocument(currentUserUid: String, selectedUserUid: String) { var chatCollection = FirebaseFirestore.getInstance().collection("ChatsCollection") var chatData = hashMapOf( "UserParticipants" to arrayListOf(currentUserUid, selectedUserUid), "messageUserUid" to getUniqueMessageUserUid(currentUserUid, selectedUserUid), "timestamp" to FieldValue.serverTimestamp() ) // chatCollection.add(chatData).addOnSuccessListener { // document-> Log.d("propertyInfoActivity","Chat Document created") // chatCollection.document(document.id).update("UserParticipants",FieldValue.arrayUnion(selectedUserUid)) // .addOnSuccessListener { Log.d("propertyInfoActivity","User added to chat successfully") // chatCollection.document(document.id).update("UserParticipants",FieldValue.arrayUnion(currentUserUid)). // addOnSuccessListener { Log.d("propertInfoActivity","User added to chat") } // .addOnFailureListener{ // exception -> // Log.e("propertyInfoActivity","User add failure",exception)}} // .addOnFailureListener{ // exception -> // Log.e("propertyInfoActivity","User add failure",exception) // } // // }.addOnFailureListener{exception -> // Log.e("propertyInfoActivity","User add failure",exception)} chatCollection.whereArrayContains("UserParticipants", currentUserUid) .whereArrayContains("UserParticipants", selectedUserUid) .get() .addOnSuccessListener { documents -> if (documents.isEmpty) { chatCollection.add(chatData) .addOnSuccessListener { document -> Log.d("propertyInfoActivity", "Chat Document Created") val messageUserUid = chatData["messageUserUid"].toString() chatCollection.document(document.id) .update( "UserParticipants", FieldValue.arrayUnion(selectedUserUid, currentUserUid) ) .addOnSuccessListener { Log.d( "propertyInfoActivity", "User added to chat successfully" ) } .addOnFailureListener { exception -> Log.e("propertyInfoActivity", "User add failure", exception) } } } else { Log.d("propertyInfoActivity", "Chat Document Already Exists") } }.addOnFailureListener { exception -> Log.e("propertyInfoActivity", "Error checking chat document") } } private fun getUniqueMessageUserUid( currentUserUid: String, selectedUserUid: String ): String { return "${currentUserUid}_${selectedUserUid}_${System.currentTimeMillis()}" } private fun getUserNameFromUid(uid: String):String { val firestore = FirebaseFirestore.getInstance() val usersCollection = firestore.collection("User") var userPhoneNumber = "" if (uid != null) { usersCollection.document(uid).get().addOnSuccessListener { documentSnapshot -> if (documentSnapshot.exists()) { Toast.makeText(this,"It Enters.",Toast.LENGTH_LONG).show() val userFirstName = documentSnapshot.getString("firstName") val userLastName = documentSnapshot.getString("lastName") sentFirstName = userFirstName.toString() sentLastName = userLastName.toString() sentNumber = documentSnapshot.getString("number").toString() sentUserImage = documentSnapshot.getString("userImage").toString() sentUserUid = documentSnapshot.getString("uid").toString() userPhoneNumber= documentSnapshot.getString("number").toString() phoneNumbeListedWithUser.text = userPhoneNumber userName.text = userFirstName + " "+ userLastName Toast.makeText(this,"User Name: $userFirstName, userPhoneNumber: $userPhoneNumber ",Toast.LENGTH_LONG).show() propertyUid.text = userFirstName } } return userPhoneNumber } return userPhoneNumber } private fun addToChatCluster(currentUserUid: String, selectedUserUid: String) { var chatUserClusterCollection = FirebaseFirestore.getInstance().collection("ChatUserCluster") chatUserClusterCollection.document(currentUserUid) .update("connectedUsers", FieldValue.arrayUnion(selectedUserUid)) .addOnSuccessListener { Log.d( "propertyInfoActivity", "User $selectedUserUid added to the following $currentUserUid cluster successfully." ) chatUserClusterCollection.document(selectedUserUid) .update("connectedUsers", FieldValue.arrayUnion(currentUserUid)) .addOnSuccessListener { Log.d( "propertyInfoActivity", "User $currentUserUid added to the following $selectedUserUid cluster successfully." ) }.addOnFailureListener { exception -> Log.e( "propertyInfoActivity", "Errorr in adding user to the chat cluster", exception ) } } .addOnFailureListener { exception -> Log.e("propertyInfoActivity", "Error in adding user to the chat cluster", exception) } } private fun decodeBase64ToBitmap(base64:String): Bitmap { var decodeByteArray = Base64.decode(base64, Base64.DEFAULT) return BitmapFactory.decodeByteArray(decodeByteArray,0,decodeByteArray.size) } }
0
Kotlin
0
0
34a9bbd04d47ce69990a232f19d2c3d969ca25e1
21,093
Housify-android-app
MIT License
mlkit-smartreply/app/src/main/java/com/google/firebase/samples/apps/mlkit/smartreply/kotlin/chat/MessageListAdapter.kt
SagarBChauhan
216,040,454
false
null
package xyz.enterkey.mlkitdemo.smartreply.chat import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import xyz.enterkey.mlkitdemo.smartreply.model.Message import de.hdodenhof.circleimageview.CircleImageView import xyz.enterkey.mlkitdemo.smartreply.R import java.util.ArrayList internal class MessageListAdapter : RecyclerView.Adapter<MessageListAdapter.MessageViewHolder>() { private val messagesList = ArrayList<Message>() var emulatingRemoteUser = false set(emulatingRemoteUser) { field = emulatingRemoteUser notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MessageViewHolder { val v = LayoutInflater.from(parent.context).inflate(viewType, parent, false) as ViewGroup return MessageViewHolder(v) } override fun onBindViewHolder(holder: MessageViewHolder, position: Int) { val message = messagesList[position] holder.bind(message) } override fun getItemViewType(position: Int): Int { return if ( messagesList[position].isLocalUser && !emulatingRemoteUser || !messagesList[position].isLocalUser && emulatingRemoteUser) { R.layout.item_message_local } else { R.layout.item_message_remote } } override fun getItemCount(): Int { return messagesList.size } fun setMessages(messages: List<Message>) { messagesList.clear() messagesList.addAll(messages) notifyDataSetChanged() } inner class MessageViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val icon: CircleImageView private val text: TextView init { icon = itemView.findViewById(R.id.messageAuthor) text = itemView.findViewById(R.id.messageText) } fun bind(message: Message) { icon.setImageDrawable(message.getIcon(icon.context)) text.text = message.text } } }
5
null
0
5
d886d348a681f41f02e78d720cb74fb8c162e339
2,136
quickstart-android
Creative Commons Attribution 4.0 International
src/main/kotlin/eom/demo/ejh_board/exception/NotFoundException.kt
stephano-tri
634,144,135
false
null
package eom.demo.ejh_board.exception class NotFoundException: RuntimeException { constructor(message: String): super(message) constructor(message: String, cause: Throwable): super(message, cause) constructor(cause: Throwable): super(cause) }
3
Kotlin
0
0
97b6d2ebc844af1a4c6de0fd229a6ed1afc140c0
255
find_similarity_board
Apache License 2.0
client/data/src/main/java/com/healthc/data/service/RecipeService.kt
Team-HealthC
601,915,784
false
{"Kotlin": 189898, "Java": 9369}
package com.healthc.data.service import com.healthc.data.BuildConfig import com.healthc.data.model.remote.recipe.IngredientResultResponse import com.healthc.data.model.remote.recipe.RecipeResponse import retrofit2.http.GET import retrofit2.http.Query interface RecipeService { @GET("/recipes/findByIngredients") suspend fun getRecipes( @Query("apiKey") apiKey: String = BuildConfig.SPOON_API_KEY, @Query("ingredients") ingredients : String, @Query("number") number : Int = 10 ) : List<RecipeResponse> // 해당 메뉴에 재료 찾기 @GET("/recipes/complexSearch") suspend fun getIngredients( @Query("apiKey") apiKey : String = BuildConfig.SPOON_API_KEY, @Query("query") query : String, @Query("number") number : Int = 1, @Query("fillIngredients") fillIngredients : Boolean = true, @Query("ignorePantry") ignorePantry : Boolean = false ) : IngredientResultResponse }
17
Kotlin
1
2
93c660eb97636a6d8c3e007d8509589c2ac99386
945
HealthC_Android
MIT License
simplified-tests/src/test/java/org/nypl/simplified/tests/lcp/LCPContentProtectionProviderTest.kt
ThePalaceProject
367,082,997
false
{"Kotlin": 3231877, "JavaScript": 853788, "Java": 400160, "CSS": 65407, "HTML": 49220, "Shell": 5017, "Ruby": 178}
package org.nypl.simplified.tests.lcp import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.nypl.simplified.lcp.LCPContentProtectionProvider import java.lang.IllegalStateException class LCPContentProtectionProviderTest { @Test fun passphrase_returnsUnencodedValue_whenHashedPassphraseIsUnencoded() { val provider = LCPContentProtectionProvider().apply { passphrase = "4a3c996c8b7fc2c353e58437dfec747e9ee9e0d9711b74bc9ff6080a924cebcf" } Assertions.assertEquals( "4a3c996c8b7fc2c353e58437dfec747e9ee9e0d9711b74bc9ff6080a924cebcf", provider.passphrase() ) } @Test fun passphrase_returnsUnencodedValue_whenHashedPassphraseIsEncoded() { val provider = LCPContentProtectionProvider().apply { passphrase = "<PASSWORD> } Assertions.assertEquals( "4a3c996c8b7fc2c353e58437dfec747e9ee9e0d9711b74bc9ff6080a924cebcf", provider.passphrase() ) } @Test fun passphrase_throws_whenHashedPassphraseIsNull() { val provider = LCPContentProtectionProvider().apply { passphrase = null } Assertions.assertThrows(IllegalStateException::class.java) { provider.passphrase() } } }
1
Kotlin
4
8
3f267cda9985bd8dc0351893e2aee021056c334f
1,207
android-core
Apache License 2.0
oneadapter/src/main/java/com/idanatz/oneadapter/external/holders/OneInternalHolderModels.kt
meruiden
232,577,694
true
{"Gradle": 7, "Markdown": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Proguard": 2, "XML": 29, "JSON": 1, "Kotlin": 107, "Java": 7, "INI": 1}
package com.idanatz.oneadapter.external.holders import com.idanatz.oneadapter.external.interfaces.Diffable import java.util.* sealed class OneInternalHolderModel : Diffable { private val uniqueId = UUID.randomUUID().mostSignificantBits override fun getUniqueIdentifier() = uniqueId override fun areContentTheSame(other: Any) = true } object LoadingIndicator : OneInternalHolderModel() object EmptyIndicator : OneInternalHolderModel()
0
Kotlin
0
0
5eaf19734939f9956d60ceb4a982320921724124
450
OneAdapter
MIT License
app/src/main/java/com/bonifes/viewbinding/sample/base/nonreflection/BaseBindingQuickAdapter.kt
panicDev
368,471,018
false
{"Gradle": 7, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 6, "Batchfile": 1, "Markdown": 1, "INI": 3, "Proguard": 7, "Kotlin": 57, "XML": 39}
package com.bonifes.viewbinding.sample.base.nonreflection import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.viewbinding.ViewBinding import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.viewholder.BaseViewHolder abstract class BaseBindingQuickAdapter<T, VB : ViewBinding>( private val inflate: (LayoutInflater, ViewGroup, Boolean) -> VB, layoutResId: Int = -1 ) : BaseQuickAdapter<T, BaseBindingQuickAdapter.BaseBindingHolder>(layoutResId) { override fun onCreateDefViewHolder(parent: ViewGroup, viewType: Int) = BaseBindingHolder(inflate(LayoutInflater.from(parent.context), parent, false)) class BaseBindingHolder(private val binding: ViewBinding) : BaseViewHolder(binding.root) { constructor(itemView: View) : this(ViewBinding { itemView }) @Suppress("UNCHECKED_CAST") fun <VB : ViewBinding> getViewBinding() = binding as VB } }
1
null
1
1
226fa5c07442aa929b0b4f8bec272ff82cfe135d
986
bvbl
Apache License 2.0
picturepicker/src/main/java/com/silwek/tools/picturepicker/PermissionRationaleDialog.kt
silwek
296,909,578
false
{"Gradle": 11, "Java Properties": 1, "YAML": 1, "Shell": 1, "Text": 1, "Ignore List": 10, "Batchfile": 1, "Markdown": 3, "INI": 9, "Proguard": 9, "XML": 20, "Kotlin": 27, "Java": 3}
package com.silwek.tools.location import android.content.Context import android.content.Intent import android.net.Uri import android.provider.Settings import androidx.appcompat.app.AlertDialog interface PermissionRationaleDialog { fun getSourceContext(): Context? fun showRationaleDialog( titleRes: Int, messageRes: Int, permission: String, requestCode: Int ) { val ctx = getSourceContext() ?: return val pkg = ctx.packageName val builder: AlertDialog.Builder = AlertDialog.Builder(ctx) builder.setTitle(titleRes) .setMessage(messageRes) .setPositiveButton(android.R.string.ok) { _, _ -> val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) val uri: Uri = Uri.fromParts("package", pkg, null) intent.data = uri startSettingActivity(intent) } .setNegativeButton(android.R.string.cancel) { dialog, _ -> dialog.cancel() } builder.create().show() } fun startSettingActivity(intent: Intent) }
1
null
1
1
1ca818cbc6fbfeaf9f87e48dc4af391c3ddbd46e
1,135
silwek-tools
Apache License 2.0
app/src/main/java/com/petrulak/cleankotlin/di/module/InteractorModule.kt
Petrulak
104,648,833
false
null
package com.petrulak.cleankotlin.di.module import com.petrulak.cleankotlin.domain.executor.SchedulerProvider import com.petrulak.cleankotlin.domain.interactor.GetWeatherLocallyUseCaseImpl import com.petrulak.cleankotlin.domain.interactor.GetWeatherRemotelyUseCaseImpl import com.petrulak.cleankotlin.domain.interactor.GetWeatherUseCaseImpl import com.petrulak.cleankotlin.domain.interactor.definition.GetWeatherLocallyUseCase import com.petrulak.cleankotlin.domain.interactor.definition.GetWeatherRemotelyUseCase import com.petrulak.cleankotlin.domain.interactor.definition.GetWeatherUseCase import com.petrulak.cleankotlin.domain.repository.WeatherRepository import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class InteractorModule { @Singleton @Provides internal fun getWeatherRemotelyUseCase(schedulerProvider: SchedulerProvider, repository: WeatherRepository): GetWeatherRemotelyUseCase { return GetWeatherRemotelyUseCaseImpl(schedulerProvider, repository) } @Singleton @Provides internal fun getWeatherLocallyUseCase(schedulerProvider: SchedulerProvider, repository: WeatherRepository): GetWeatherLocallyUseCase { return GetWeatherLocallyUseCaseImpl(schedulerProvider, repository) } @Singleton @Provides internal fun getWeatherUseCase(schedulerProvider: SchedulerProvider, repository: WeatherRepository): GetWeatherUseCase { return GetWeatherUseCaseImpl(schedulerProvider, repository) } }
0
Kotlin
10
111
51033f30ecdb9573000454f1b8890d20c2438002
1,504
android-kotlin-mvp-clean-architecture
MIT License
app/src/main/java/com/example/kotlincodingtest/programmers/Lv2/호텔_대실/Solution.kt
ichanguk
788,416,368
false
{"Kotlin": 299419}
package com.example.kotlincodingtest.programmers.Lv2.호텔_대실 class Solution { fun solution(book_time: Array<Array<String>>): Int { var answer: Int = 0 book_time.sortBy{it[0]} val N = book_time.size val isVisit = MutableList(N) { false } var cnt = 0 var startIdx = 0 var endTime = "" while (cnt < N) { answer++ for (i in book_time.indices) { if (!isVisit[i]) { isVisit[i] = true cnt++ endTime = book_time[i][1] startIdx = i + 1 break } } for (i in startIdx until N) { if (!isVisit[i] && calDiff(endTime, book_time[i][0]) >= 10) { isVisit[i] = true cnt++ endTime = book_time[i][1] } } } return answer } } fun calDiff(endTime: String, startTime:String):Int { val endT = endTime.split(':') val startT = startTime.split(':') return startT[0].toInt() * 60 + startT[1].toInt() - (endT[0].toInt() * 60 + endT[1].toInt()) }
0
Kotlin
0
0
298b0b06aebf98a4745fde773a671307f40c6886
1,214
KotlinCodingTest
MIT License
features/main/src/main/java/com/maximapps/main/ui/MainFragment.kt
merklol
442,158,957
false
{"Kotlin": 198978}
/* * Copyright (c) 2021 Maxim Smolyakov * 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 NONINFINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.maximapps.main.ui import android.os.Bundle import android.view.View import androidx.appcompat.content.res.AppCompatResources import androidx.fragment.app.Fragment import by.kirich1409.viewbindingdelegate.viewBinding import com.google.android.material.tabs.TabLayoutMediator import com.maximapps.core.utils.navigation.GlobalDirections import com.maximapps.core.utils.navigation.GlobalNavHost import com.maximapps.main.R import com.maximapps.main.databinding.FragmentMainBinding import com.maximapps.main.ui.history.HistoryFragment import com.maximapps.main.ui.pager.ViewPagerAdapter import com.maximapps.main.ui.settings.SettingsFragment import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class MainFragment @Inject constructor( private val directions: GlobalDirections, private val host: GlobalNavHost, private val versionName: String ) : Fragment(R.layout.fragment_main) { private val binding: FragmentMainBinding by viewBinding() private val tabIcons = arrayOf( R.drawable.ic_baseline_bar_chart_24, R.drawable.ic_baseline_settings_24 ) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setViewPagerAdapter(listOf(HistoryFragment(directions, host), SettingsFragment(versionName))) setupTabLayoutWithViewPager() } private fun setViewPagerAdapter(fragments: List<Fragment>) { binding.viewPager.adapter = ViewPagerAdapter(childFragmentManager, lifecycle, fragments) } private fun setupTabLayoutWithViewPager() { TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, position -> tab.icon = AppCompatResources.getDrawable(requireContext(), tabIcons[position]) }.attach() } }
0
Kotlin
0
5
2306729e92dd9f3c4fed63b7a7afe96d91982aac
2,933
Workout-Journal
MIT License
simplecloud-dependency-loader/src/main/kotlin/eu/thesimplecloud/loader/dependency/DependencyLoader.kt
theSimpleCloud
270,085,977
false
null
/* * MIT License * * Copyright (C) 2020-2022 The SimpleCloud authors * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package eu.thesimplecloud.loader.dependency import eu.thesimplecloud.jsonlib.JsonLib import eu.thesimplecloud.runner.dependency.AdvancedCloudDependency import java.io.File import java.util.concurrent.CopyOnWriteArraySet /** * Created by IntelliJ IDEA. * Date: 04.09.2020 * Time: 17:49 * @author <NAME> */ class DependencyLoader { companion object { val INSTANCE = DependencyLoader() } private val resolvedDependencies = CopyOnWriteArraySet<AdvancedCloudDependency>() private val installedDependencies = CopyOnWriteArraySet<AdvancedCloudDependency>() private var loggerEnabled: Boolean = true fun disableLogger() { this.loggerEnabled = false } fun reset() { resolvedDependencies.clear() } fun loadDependencies(repositories: List<String>, dependencies: List<AdvancedCloudDependency>): Set<File> { if (dependencies.isEmpty()) return emptySet() val dependenciesString = dependencies.joinToString { it.getName() } loggerMessage("Loading dependencies: $dependenciesString") val allDependencies = dependencies.map { collectSubDependencies(it, repositories) }.flatten() val dependenciesByArtifactId = allDependencies.groupBy { it.artifactId }.values val newestVersions = dependenciesByArtifactId.map { it.reduce { acc, dependency -> dependency.getDependencyWithNewerVersion(acc) } } val dependencyFiles = newestVersions.map { it.getDownloadedFile() } val installedDependenciesString = newestVersions.joinToString { it.getName() } loggerMessage("Installed dependencies: $installedDependenciesString") installedDependencies.addAll(newestVersions) return dependencyFiles.toSet() } private fun collectSubDependencies( dependency: AdvancedCloudDependency, repositories: List<String>, list: MutableList<AdvancedCloudDependency> = ArrayList() ): List<AdvancedCloudDependency> { if (this.resolvedDependencies.contains(dependency)) return list this.resolvedDependencies.add(dependency) list.add(dependency) resolveDependencyFilesIfNotExist(dependency, repositories) loggerMessage("Loading dependency ${dependency.getName()}") val subDependencies = getSubDependenciesOfDependency(dependency) subDependencies.forEach { collectSubDependencies(it, repositories, list) } return list } private fun resolveDependencyFilesIfNotExist(dependency: AdvancedCloudDependency, repositories: List<String>) { if (!dependency.getDownloadedInfoFile().exists()) { AdvancedDependencyDownloader(repositories).downloadFiles(dependency) } } private fun getSubDependenciesOfDependency(dependency: AdvancedCloudDependency): List<AdvancedCloudDependency> { val infoFile = dependency.getDownloadedInfoFile() val subDependencies = JsonLib.fromJsonFile(infoFile)!! .getObject(Array<AdvancedCloudDependency>::class.java) return subDependencies.asList() } private fun loggerMessage(message: String) { if (loggerEnabled) { println(message) } } fun getInstalledDependencies(): Collection<AdvancedCloudDependency> { return this.installedDependencies } }
8
null
43
98
8f10768e2be523e9b2e7c170965ca4f52a99bf09
4,477
SimpleCloud
MIT License
client-kotlin/src/test/kotlin/com/influxdb/client/kotlin/ITInfluxDBClientKotlin.kt
influxdata
151,233,646
false
null
/* * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.influxdb.client.kotlin import com.influxdb.LogLevel import com.influxdb.client.domain.HealthCheck import com.influxdb.exceptions.InfluxException import org.assertj.core.api.Assertions import org.junit.jupiter.api.Test import org.junit.platform.runner.JUnitPlatform import org.junit.runner.RunWith /** * @author Jakub Bednar (bednar@github) (30/10/2018 09:19) */ @RunWith(JUnitPlatform::class) internal class ITInfluxDBClientKotlin : AbstractITInfluxDBClientKotlin() { @Test fun queryClient() { Assertions.assertThat(influxDBClient.getQueryKotlinApi()).isNotNull } @Test fun health() { val health = influxDBClient.health() Assertions.assertThat(health).isNotNull Assertions.assertThat(health.status).isEqualTo(HealthCheck.StatusEnum.PASS) Assertions.assertThat(health.message).isEqualTo("ready for queries and writes") } @Test @Throws(Exception::class) fun healthNotRunningInstance() { val clientNotRunning = InfluxDBClientKotlinFactory.create("http://localhost:8099") val health = clientNotRunning.health() Assertions.assertThat(health).isNotNull Assertions.assertThat(health.status).isEqualTo(HealthCheck.StatusEnum.FAIL) Assertions.assertThat(health.message).startsWith("Failed to connect to") clientNotRunning.close() } @Test fun ping() { Assertions.assertThat(influxDBClient.ping()).isTrue } @Test fun pingNotRunningInstance() { val clientNotRunning = InfluxDBClientKotlinFactory.create("http://localhost:8099") Assertions.assertThat(clientNotRunning.ping()).isFalse clientNotRunning.close() } @Test fun version() { Assertions.assertThat(influxDBClient.version()).isNotBlank } @Test fun versionNotRunningInstance() { val clientNotRunning = InfluxDBClientKotlinFactory.create("http://localhost:8099") Assertions.assertThatThrownBy { clientNotRunning.version() } .isInstanceOf(InfluxException::class.java) clientNotRunning.close() } @Test fun logLevel() { // default NONE Assertions.assertThat(influxDBClient.getLogLevel()).isEqualTo(LogLevel.NONE) // set HEADERS val influxDBClient = influxDBClient.setLogLevel(LogLevel.HEADERS) Assertions.assertThat(influxDBClient).isEqualTo(this.influxDBClient) Assertions.assertThat(this.influxDBClient.getLogLevel()).isEqualTo(LogLevel.HEADERS) } @Test fun gzip() { Assertions.assertThat(influxDBClient.isGzipEnabled()).isFalse() // Enable GZIP var influxDBClient = influxDBClient.enableGzip() Assertions.assertThat(influxDBClient).isEqualTo(this.influxDBClient) Assertions.assertThat(this.influxDBClient.isGzipEnabled()).isTrue() // Disable GZIP influxDBClient = this.influxDBClient.disableGzip() Assertions.assertThat(influxDBClient).isEqualTo(this.influxDBClient) Assertions.assertThat(this.influxDBClient.isGzipEnabled()).isFalse() } }
9
null
75
434
94285a18c59beafb89bb3ac516f183722d7c202c
4,216
influxdb-client-java
MIT License
simple-icons/src/commonMain/kotlin/compose/icons/simpleicons/Asciidoctor.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36756847}
package compose.icons.simpleicons import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Butt import androidx.compose.ui.graphics.StrokeJoin.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.SimpleIcons public val SimpleIcons.Asciidoctor: ImageVector get() { if (_asciidoctor != null) { return _asciidoctor!! } _asciidoctor = Builder(name = "Asciidoctor", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(18.0685f, 0.0f) lineTo(5.9318f, 0.0f) curveTo(2.6579f, 0.0f, 0.0f, 2.6578f, 0.0f, 5.9316f) verticalLineToRelative(12.1367f) curveTo(0.0f, 21.3421f, 2.658f, 24.0f, 5.9318f, 24.0f) horizontalLineToRelative(12.1367f) curveTo(21.3423f, 24.0f, 24.0f, 21.3421f, 24.0f, 18.0683f) lineTo(24.0f, 5.9316f) curveTo(24.0f, 2.6578f, 21.3423f, 0.0f, 18.0685f, 0.0f) close() moveTo(10.708f, 15.4038f) lineTo(8.8102f, 15.4038f) curveToRelative(-0.0018f, 0.0045f, -0.0031f, 0.009f, -0.005f, 0.0135f) lineTo(7.1986f, 19.282f) arcToRelative(0.5058f, 0.5058f, 0.0f, true, true, -0.934f, -0.3883f) lineToRelative(1.4507f, -3.49f) lineTo(4.8677f, 15.4037f) arcToRelative(0.5058f, 0.5058f, 0.0f, true, true, 0.0f, -1.0113f) horizontalLineToRelative(5.8403f) arcToRelative(0.5058f, 0.5058f, 0.0f, true, true, 0.0f, 1.0113f) close() moveTo(18.6269f, 19.5685f) arcToRelative(0.5058f, 0.5058f, 0.0f, false, true, -0.6545f, -0.2886f) lineTo(12.6206f, 6.2306f) lineToRelative(-2.395f, 5.761f) horizontalLineToRelative(1.551f) arcToRelative(0.5058f, 0.5058f, 0.0f, true, true, 0.0f, 1.0113f) lineTo(5.9369f, 13.0029f) arcToRelative(0.5058f, 0.5058f, 0.0f, true, true, 0.0f, -1.0113f) horizontalLineToRelative(3.194f) curveToRelative(0.0015f, -0.0038f, 0.0026f, -0.0075f, 0.0042f, -0.0112f) lineToRelative(3.0223f, -7.2693f) arcToRelative(0.5058f, 0.5058f, 0.0f, false, true, 0.457f, -0.3112f) arcToRelative(0.5058f, 0.5058f, 0.0f, false, true, 0.4774f, 0.3137f) lineTo(18.908f, 18.896f) arcToRelative(0.5058f, 0.5058f, 0.0f, false, true, -0.2812f, 0.6725f) close() } } .build() return _asciidoctor!! } private var _asciidoctor: ImageVector? = null
15
Kotlin
20
460
651badc4ace0137c5541f859f61ffa91e5242b83
3,321
compose-icons
MIT License
sentry-kotlin-multiplatform/src/commonMain/kotlin/io/sentry/kotlin/multiplatform/protocol/Breadcrumb.kt
getsentry
285,502,515
false
null
package io.sentry.kotlin.multiplatform.protocol import io.sentry.kotlin.multiplatform.SentryLevel public data class Breadcrumb constructor( /** The breadcrumb's level */ var level: SentryLevel? = null, /** The breadcrumb's type */ var type: String? = null, /** The breadcrumb's message */ var message: String? = null, /** The breadcrumb's category */ var category: String? = null, private var data: MutableMap<String, Any>? = null ) { public companion object { public fun user(category: String, message: String): Breadcrumb { return Breadcrumb().apply { this.category = category this.message = message this.type = "user" } } public fun http(url: String, method: String): Breadcrumb { return Breadcrumb().apply { this.type = "http" this.category = "http" this.setData("url", url) this.setData("method", method.uppercase()) } } public fun http(url: String, method: String, code: Int?): Breadcrumb { return http(url, method).apply { code?.let { this.setData("status_code", code) } } } public fun navigation(from: String, to: String): Breadcrumb { return Breadcrumb().apply { this.category = "navigation" this.type = "navigation" this.setData("from", from) this.setData("to", to) } } public fun transaction(message: String): Breadcrumb { return Breadcrumb().apply { this.type = "default" this.category = "sentry.transaction" this.message = message } } public fun debug(message: String): Breadcrumb { val breadcrumb = Breadcrumb().apply { this.type = "debug" this.message = message this.level = SentryLevel.DEBUG } return breadcrumb } public fun error(message: String): Breadcrumb { return Breadcrumb().apply { this.type = "error" this.message = message this.level = SentryLevel.ERROR } } public fun info(message: String): Breadcrumb { return Breadcrumb().apply { this.type = "info" this.message = message this.level = SentryLevel.INFO } } public fun query(message: String): Breadcrumb { return Breadcrumb().apply { this.type = "query" this.message = message } } public fun ui(category: String, message: String): Breadcrumb { return Breadcrumb().apply { this.type = "default" this.category = "ui.$category" this.message = message } } public fun userInteraction( subCategory: String, viewId: String?, viewClass: String?, additionalData: Map<String?, Any?> ): Breadcrumb { return Breadcrumb().apply { this.type = "user" this.category = "ui.$subCategory" this.level = SentryLevel.INFO viewId?.let { this.setData("view.id", it) } viewClass?.let { this.setData("view.class", viewClass) } for ((key, value) in additionalData) { if (key != null && value != null) { this.setData(key, value) } } } } public fun userInteraction( subCategory: String, viewId: String?, viewClass: String? ): Breadcrumb { return userInteraction(subCategory, viewId, viewClass, emptyMap<String?, Any>()) } } /** * Set's the breadcrumb's data with key, value * * @param key The key * @param value The value */ public fun setData(key: String, value: Any) { if (data == null) data = mutableMapOf() data?.put(key, value) } /** * Set's the breadcrumb's data with a map * * @param map The map */ public fun setData(map: MutableMap<String, Any>) { data = map } /** Returns the breadcrumb's data */ public fun getData(): MutableMap<String, Any>? { return data } /** Clears the breadcrumb and returns it to the default state */ public fun clear() { data = null level = null category = null type = null message = null } }
7
null
9
97
a42d02cb266274fa4417a29363d8eaa59701f290
4,827
sentry-kotlin-multiplatform
MIT License
sentry-kotlin-multiplatform/src/commonMain/kotlin/io/sentry/kotlin/multiplatform/protocol/Breadcrumb.kt
getsentry
285,502,515
false
null
package io.sentry.kotlin.multiplatform.protocol import io.sentry.kotlin.multiplatform.SentryLevel public data class Breadcrumb constructor( /** The breadcrumb's level */ var level: SentryLevel? = null, /** The breadcrumb's type */ var type: String? = null, /** The breadcrumb's message */ var message: String? = null, /** The breadcrumb's category */ var category: String? = null, private var data: MutableMap<String, Any>? = null ) { public companion object { public fun user(category: String, message: String): Breadcrumb { return Breadcrumb().apply { this.category = category this.message = message this.type = "user" } } public fun http(url: String, method: String): Breadcrumb { return Breadcrumb().apply { this.type = "http" this.category = "http" this.setData("url", url) this.setData("method", method.uppercase()) } } public fun http(url: String, method: String, code: Int?): Breadcrumb { return http(url, method).apply { code?.let { this.setData("status_code", code) } } } public fun navigation(from: String, to: String): Breadcrumb { return Breadcrumb().apply { this.category = "navigation" this.type = "navigation" this.setData("from", from) this.setData("to", to) } } public fun transaction(message: String): Breadcrumb { return Breadcrumb().apply { this.type = "default" this.category = "sentry.transaction" this.message = message } } public fun debug(message: String): Breadcrumb { val breadcrumb = Breadcrumb().apply { this.type = "debug" this.message = message this.level = SentryLevel.DEBUG } return breadcrumb } public fun error(message: String): Breadcrumb { return Breadcrumb().apply { this.type = "error" this.message = message this.level = SentryLevel.ERROR } } public fun info(message: String): Breadcrumb { return Breadcrumb().apply { this.type = "info" this.message = message this.level = SentryLevel.INFO } } public fun query(message: String): Breadcrumb { return Breadcrumb().apply { this.type = "query" this.message = message } } public fun ui(category: String, message: String): Breadcrumb { return Breadcrumb().apply { this.type = "default" this.category = "ui.$category" this.message = message } } public fun userInteraction( subCategory: String, viewId: String?, viewClass: String?, additionalData: Map<String?, Any?> ): Breadcrumb { return Breadcrumb().apply { this.type = "user" this.category = "ui.$subCategory" this.level = SentryLevel.INFO viewId?.let { this.setData("view.id", it) } viewClass?.let { this.setData("view.class", viewClass) } for ((key, value) in additionalData) { if (key != null && value != null) { this.setData(key, value) } } } } public fun userInteraction( subCategory: String, viewId: String?, viewClass: String? ): Breadcrumb { return userInteraction(subCategory, viewId, viewClass, emptyMap<String?, Any>()) } } /** * Set's the breadcrumb's data with key, value * * @param key The key * @param value The value */ public fun setData(key: String, value: Any) { if (data == null) data = mutableMapOf() data?.put(key, value) } /** * Set's the breadcrumb's data with a map * * @param map The map */ public fun setData(map: MutableMap<String, Any>) { data = map } /** Returns the breadcrumb's data */ public fun getData(): MutableMap<String, Any>? { return data } /** Clears the breadcrumb and returns it to the default state */ public fun clear() { data = null level = null category = null type = null message = null } }
7
null
9
97
a42d02cb266274fa4417a29363d8eaa59701f290
4,827
sentry-kotlin-multiplatform
MIT License
app/src/main/java/com/fch/android_demo/dispatch/DispatchActivity.kt
fangood
237,617,057
false
null
package com.fch.android_demo.dispatch import android.os.Bundle import android.util.Log import android.view.MotionEvent import androidx.appcompat.app.AppCompatActivity import com.fch.android_demo.R class DispatchActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_dispatch) } override fun dispatchTouchEvent(ev: MotionEvent?): Boolean { Log.v("DispatchActivity", "dispatchTouchEvent") // return super.dispatchTouchEvent(ev) return false } override fun onTouchEvent(event: MotionEvent?): Boolean { Log.v("DispatchActivity", "onTouchEvent") return super.onTouchEvent(event) } }
0
Kotlin
0
0
60decbe723fd58613972207c627f9d52e2fe3332
762
android_kotlin_demo
Apache License 2.0
aws-storage-s3/src/main/java/com/amplifyframework/storage/s3/transfer/worker/PartUploadTransferWorker.kt
aws-amplify
177,009,933
false
null
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amplifyframework.storage.s3.transfer.worker import android.content.Context import androidx.work.WorkerParameters import aws.sdk.kotlin.services.s3.S3Client import aws.sdk.kotlin.services.s3.uploadPart import aws.sdk.kotlin.services.s3.withConfig import aws.smithy.kotlin.runtime.content.asByteStream import com.amplifyframework.storage.TransferState import com.amplifyframework.storage.s3.transfer.PartUploadProgressListener import com.amplifyframework.storage.s3.transfer.TransferDB import com.amplifyframework.storage.s3.transfer.TransferStatusUpdater import com.amplifyframework.storage.s3.transfer.UploadProgressListenerInterceptor import java.io.File /** * Worker to upload a part for multipart upload **/ internal class PartUploadTransferWorker( private val s3: S3Client, private val transferDB: TransferDB, private val transferStatusUpdater: TransferStatusUpdater, context: Context, workerParameters: WorkerParameters ) : BaseTransferWorker(transferStatusUpdater, transferDB, context, workerParameters) { private lateinit var multiPartUploadId: String private lateinit var partUploadProgressListener: PartUploadProgressListener override var maxRetryCount = 3 override suspend fun performWork(): Result { if (isStopped) { return Result.retry() } transferStatusUpdater.updateTransferState(transferRecord.mainUploadId, TransferState.IN_PROGRESS) multiPartUploadId = inputData.keyValueMap[MULTI_PART_UPLOAD_ID] as String partUploadProgressListener = PartUploadProgressListener(transferRecord, transferStatusUpdater) return s3.withConfig { interceptors += UploadProgressListenerInterceptor(partUploadProgressListener) enableAccelerate = transferRecord.useAccelerateEndpoint == 1 }.uploadPart { bucket = transferRecord.bucketName key = transferRecord.key uploadId = multiPartUploadId body = File(transferRecord.file).asByteStream( start = transferRecord.fileOffset, transferRecord.fileOffset + transferRecord.bytesTotal - 1 ) partNumber = transferRecord.partNumber }.let { response -> response.eTag?.let { tag -> transferDB.updateETag(transferRecord.id, tag) transferDB.updateState(transferRecord.id, TransferState.PART_COMPLETED) updateProgress() Result.success(outputData) } ?: run { throw IllegalStateException("Etag is empty") } } } private fun updateProgress() { transferStatusUpdater.updateProgress( transferRecord.id, transferRecord.bytesTotal, transferRecord.bytesTotal, false ) } }
99
null
115
245
14c71f38f052a964b96d7abaff6e157bd21a64d8
3,431
amplify-android
Apache License 2.0
clearnetandroid/src/test/java/clearnet/android/NotNullKotlinFieldsValidatorTest.kt
xelevra
176,962,795
true
{"Gradle": 6, "Markdown": 3, "Java Properties": 1, "Shell": 1, "Ignore List": 5, "Batchfile": 1, "Kotlin": 51, "Java": 35, "Proguard": 1, "XML": 2, "INI": 1}
package clearnet.android import clearnet.android.help.JavaModel import clearnet.error.ValidationException import com.google.gson.Gson import com.google.gson.reflect.TypeToken import org.junit.Assert.* import org.junit.Before import org.junit.Test class NotNullKotlinFieldsValidatorTest { private lateinit var validator: NotNullFieldsValidator private val gson = Gson() @Before fun setUp() { validator = NotNullFieldsValidator(true) } @Test fun testDeserialize() { var item = convert("right", Item::class.java) assertNotNull(item.getPrivateRequired()) assertNotNull(item.optional) item = convert("required", Item::class.java) assertNotNull(item.getPrivateRequired()) val list: ArrayList<Item> = convert("arrayRight", ItemsArrayList::class.java) assertEquals(list.size.toLong(), 1) val array: Array<Item> = convert("arrayRight", object : TypeToken<Array<Item>>() {}.rawType as Class<Array<Item>>) assertEquals(array.size.toLong(), 1) val map: Map<String, Item> = convert("mapRight", StringToItemMap::class.java) assertNull(map["one"]) item = map["two"] assertNotNull(item!!.getPrivateRequired()) assertNotNull(item.optional) item = map["three"] assertNotNull(item!!.getPrivateRequired()) var extended = convert("wrong", Included::class.java) assertNull(extended.item) extended = convert("includedRight", Included::class.java) assertNotNull(extended.item) assertNotNull(extended.item!!.getPrivateRequired()) try { convert("wrong", Item::class.java) fail() } catch (e: ValidationException) { } try { convert("arrayWrong", ItemsArrayList::class.java) fail() } catch (e: ValidationException) { } try { convert("arrayWrong", object : TypeToken<Array<Item>>() {}.rawType as Class<Array<Item>>) fail() } catch (e: ValidationException) { } try { convert("mapWrong", StringToItemMap::class.java) fail() } catch (e: ValidationException) { } try { convert("includedWrong", Included::class.java) fail() } catch (e: ValidationException) { } try { convert("wrong", ItemExtended::class.java) fail() } catch (e: ValidationException) { } } @Test fun testPackages() { validator = NotNullFieldsValidator(true, "another.package") try { convert("wrong", Item::class.java, validator) } catch (e: ValidationException) { fail() } validator = NotNullFieldsValidator(true, Item::class.java.`package`.name) try { convert("wrong", Item::class.java, validator) fail() } catch (e: ValidationException) { } } @Test fun ignoreJavaClasses() { try { convert("wrong", JavaModel::class.java) } catch (e: ValidationException){ fail() } } @Throws(ValidationException::class) private fun <T> convert(request: String, type: Class<T>, validator: NotNullFieldsValidator = this.validator) = gson.fromJson(getStringForResponse(request), type).apply { validator.validate(this) } private fun getStringForResponse(request: String) = when (request) { "right" -> "{\"required\":\"yes\", \"optional\":\"no\"}" "required" -> "{\"required\":\"yes\"}" "arrayRight" -> "[{\"required\":\"yes\"}]" "arrayWrong" -> "[{}]" "includedRight" -> "{\"item\":{\"required\":\"yes\"}}" "includedWrong" -> "{\"item\":{}}" "mapRight" -> "{\"one\":null,\"two\":{\"required\":\"yes\", \"optional\":\"no\"},\"three\":{\"required\":\"yes\"}}" "mapWrong" -> "{\"one\":null,\"two\":{\"optional\":\"no\"},\"three\":{\"required\":\"yes\"}}" else -> "{}" } open class Item( private val required: String, var optional: String?, var requiredPrimitive: Int = 0 // must ignore annotation ) { fun getPrivateRequired() = required } class ItemExtended( one: String, two: String?, three: Int, private val rr: String? ) : Item(one, two, three) class Included { var item: Item? = null } class ItemsArrayList : ArrayList<Item>() class StringToItemMap : HashMap<String, Item>() }
0
Kotlin
0
0
e9a6e5658b358110d90d0cd7129a9d77ff18af49
4,624
clearnet
Apache License 2.0
app/src/main/java/com/skeleton/mvp/fragment/VideoCallInvitationBottomSheetFragment.kt
jungleworks
387,698,917
false
null
package com.skeleton.mvp.fragment import android.app.Dialog import android.content.Context import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.FrameLayout import android.widget.LinearLayout import androidx.appcompat.widget.AppCompatCheckBox import androidx.coordinatorlayout.widget.CoordinatorLayout import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.bottomsheet.BottomSheetDialog import com.google.android.material.bottomsheet.BottomSheetDialogFragment import com.skeleton.mvp.BuildConfig import com.skeleton.mvp.R import com.skeleton.mvp.activity.ChatActivity import com.skeleton.mvp.adapter.VideoCallInvitationAdapter import com.skeleton.mvp.constant.FuguAppConstant.CHANNEL_ID import com.skeleton.mvp.constant.FuguAppConstant.EN_USER_ID import com.skeleton.mvp.data.db.CommonData import com.skeleton.mvp.data.network.ApiError import com.skeleton.mvp.model.Member import com.skeleton.mvp.model.userSearch.User import com.skeleton.mvp.model.userSearch.UserSearch import com.skeleton.mvp.ui.AppConstants.SEARCH_TEXT import com.skeleton.mvp.util.KeyboardUtil import com.skeleton.mvp.util.Log class VideoCallInvitationBottomSheetFragment(private val isHangoutsMeet: Boolean = false) : BottomSheetDialogFragment() { private var mContext: Context? = null private var rvMembers: androidx.recyclerview.widget.RecyclerView? = null private var membersList = ArrayList<Member>() private var userIds = ArrayList<Long>() private var videoCallInvitationAdapter: VideoCallInvitationAdapter? = null private var etSearch: EditText? = null private var clMain: CoordinatorLayout? = null private var behavior: BottomSheetBehavior<FrameLayout>? = null private var llClose: LinearLayout? = null private var keyboardVisibility = false private var channelId = 1L private var multiMemberAddGroupMap = java.util.LinkedHashMap<Long, Member>() var cbSelectAll: AppCompatCheckBox? = null private val keyboardListener = KeyboardUtil.SoftKeyboardToggleListener { isVisible -> keyboardVisibility = isVisible if (isVisible) { behavior?.isHideable = false behavior?.peekHeight = 3000 behavior?.state = BottomSheetBehavior.STATE_EXPANDED rvMembers?.minimumHeight = 3000 llClose?.visibility = View.VISIBLE } } companion object { fun newInstance(arg: Int, context: Context, membersList: ArrayList<Member>, channelId: Long, isHangoutsMeet: Boolean = false): VideoCallInvitationBottomSheetFragment { val frag = VideoCallInvitationBottomSheetFragment(isHangoutsMeet) val args = Bundle() frag.arguments = args frag.setContext(context) frag.setMembersList(membersList) frag.setChannelId(channelId) return frag } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.video_call_invitation_fragment, container) rvMembers = view?.findViewById(R.id.rvMembers) etSearch = view.findViewById(R.id.etSearch) clMain = view.findViewById(R.id.clMain) llClose = view.findViewById(R.id.llClose) videoCallInvitationAdapter = VideoCallInvitationAdapter(membersList, mContext!!, userIds, multiMemberAddGroupMap, isHangoutsMeet) rvMembers?.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(mContext) rvMembers?.itemAnimator = null rvMembers?.adapter = videoCallInvitationAdapter cbSelectAll = view.findViewById(R.id.cbSelectAll) if (CommonData.getCommonResponse().data.workspacesInfo[CommonData.getCurrentSignedInPosition()].config.max_conference_participants >= membersList.size) { cbSelectAll?.visibility = View.VISIBLE } llClose?.setOnClickListener { llClose?.visibility = View.GONE behavior?.isHideable = true behavior?.state = BottomSheetBehavior.STATE_HALF_EXPANDED rvMembers?.minimumHeight = 1300 behavior?.peekHeight = 1300 if (keyboardVisibility) { KeyboardUtil.toggleKeyboardVisibility(context as ChatActivity) } } KeyboardUtil.addKeyboardToggleListener(context as ChatActivity, keyboardListener) etSearch?.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { val filteredList = ArrayList<Member>() if (s!!.isNotEmpty() && s.length <= 2) { filteredList.add(membersList[0]) for (member in membersList) { if (member.name.toLowerCase().contains(s.toString().toLowerCase())) { filteredList.add(member) } } videoCallInvitationAdapter?.updateList(filteredList, userIds, multiMemberAddGroupMap) videoCallInvitationAdapter?.notifyDataSetChanged() } else if (s.isNotEmpty() && s.length > 2) { apiUserSearch(s.toString()) } else { videoCallInvitationAdapter?.updateList(membersList, userIds, multiMemberAddGroupMap) videoCallInvitationAdapter?.notifyDataSetChanged() } } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } }) cbSelectAll?.setOnCheckedChangeListener { _, isChecked -> if (multiMemberAddGroupMap.isEmpty() && !isChecked){ return@setOnCheckedChangeListener } for (member in membersList) { (mContext as ChatActivity).setRecyclerViewAddedMembers(member) } (mContext as ChatActivity).setRecyclerViewAddedMembers(membersList[0]) } return view } private fun apiUserSearch(text: String) { val workspaceInfo = CommonData.getCommonResponse().data.workspacesInfo[CommonData.getCurrentSignedInPosition()] val commonParams = com.skeleton.mvp.retrofit.CommonParams.Builder() .add(EN_USER_ID, workspaceInfo.enUserId) .add(SEARCH_TEXT, text) .add(CHANNEL_ID, channelId) com.skeleton.mvp.data.network.RestClient.getApiInterface(true).userSearch(CommonData.getCommonResponse().getData().getUserInfo().getAccessToken(), workspaceInfo.fuguSecretKey, 1, BuildConfig.VERSION_CODE, commonParams.build().map) .enqueue(object : com.skeleton.mvp.data.network.ResponseResolver<UserSearch>() { override fun onSuccess(userSearch: UserSearch?) { val filteredSearchedMemberArrayList = ArrayList<Member>() filteredSearchedMemberArrayList.clear() filteredSearchedMemberArrayList.add(membersList[0]) for (i: Int in userSearch?.data?.users!!.indices) { val user: User = userSearch.data.users[i] filteredSearchedMemberArrayList.add(Member(user.fullName, user.userId, "", user.userThumbnailImage, user.email, user.userType, user.status, user.leaveType)) } videoCallInvitationAdapter?.updateList(filteredSearchedMemberArrayList, userIds, multiMemberAddGroupMap) videoCallInvitationAdapter?.notifyDataSetChanged() } override fun onError(error: ApiError?) { } override fun onFailure(throwable: Throwable?) { } }) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val bottomSheetDialog = super.onCreateDialog(savedInstanceState) as BottomSheetDialog bottomSheetDialog.setOnShowListener { dialog -> val bottomSheet = bottomSheetDialog.findViewById<FrameLayout>(com.google.android.material.R.id.design_bottom_sheet) if (null != bottomSheet) { behavior = BottomSheetBehavior.from(bottomSheet) behavior?.isHideable = true behavior?.peekHeight = 1300 rvMembers?.minimumHeight = 1300 behavior?.setBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() { override fun onSlide(p0: View, p1: Float) { } override fun onStateChanged(p0: View, state: Int) { Log.e("State --->", state.toString()) if (state == BottomSheetBehavior.STATE_EXPANDED && behavior?.peekHeight!! <= 3000) { behavior?.isHideable = false behavior?.peekHeight = 3000 behavior?.state = BottomSheetBehavior.STATE_EXPANDED rvMembers?.minimumHeight = 3000 llClose?.visibility = View.VISIBLE } else if (state == BottomSheetBehavior.STATE_HIDDEN) { dismiss() } } }) } } return bottomSheetDialog } override fun onDestroyView() { super.onDestroyView() KeyboardUtil.removeKeyboardToggleListener(keyboardListener) } private fun setChannelId(channelId: Long) { this.channelId = channelId } private fun setMembersList(membersList: ArrayList<Member>) { this.membersList = membersList userIds = ArrayList() } fun updateBottomSheet(membersList: ArrayList<Member>, userIds: ArrayList<Long>, multiMemberAddGroupMap: java.util.LinkedHashMap<Long, Member>, delay: Boolean) { etSearch?.setText("") this.membersList = membersList this.userIds = userIds this.multiMemberAddGroupMap = multiMemberAddGroupMap videoCallInvitationAdapter?.updateList(membersList, userIds, multiMemberAddGroupMap) videoCallInvitationAdapter?.notifyDataSetChanged() cbSelectAll?.setOnCheckedChangeListener(null) if (userIds.size == membersList.size-1) { cbSelectAll?.isChecked = true } cbSelectAll?.setOnCheckedChangeListener { _, isChecked -> for (member in membersList) { (mContext as ChatActivity).setRecyclerViewAddedMembers(member) } (mContext as ChatActivity).setRecyclerViewAddedMembers(membersList[0]) } } private fun setContext(context: Context) { this.mContext = context } }
0
null
5
3
44f1bdd5af887302448b0fad00ab180b0fe98526
11,136
fugu-android
Apache License 2.0
ui-app/src/commonMain/kotlin/com/alexvanyo/composelife/ui/app/action/settings/FullscreenSettingsScreen.kt
alexvanyo
375,146,193
false
null
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("MatchingDeclarationName") package com.alexvanyo.composelife.ui.app.action.settings import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.animateDpAsState import androidx.compose.animation.core.exponentialDecay import androidx.compose.animation.core.spring import androidx.compose.foundation.Canvas import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.ScrollState import androidx.compose.foundation.gestures.AnchoredDraggableState import androidx.compose.foundation.gestures.DraggableAnchors import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.anchoredDraggable import androidx.compose.foundation.hoverable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.collectIsDraggedAsState import androidx.compose.foundation.interaction.collectIsHoveredAsState import androidx.compose.foundation.interaction.collectIsPressedAsState import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.WindowInsetsSides import androidx.compose.foundation.layout.consumeWindowInsets import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.only import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawing import androidx.compose.foundation.layout.safeDrawingPadding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.sizeIn import androidx.compose.foundation.layout.windowInsetsBottomHeight import androidx.compose.foundation.layout.windowInsetsEndWidth import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.foundation.layout.windowInsetsStartWidth import androidx.compose.foundation.layout.windowInsetsTopHeight import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.filled.Analytics import androidx.compose.material.icons.filled.Flag import androidx.compose.material.icons.filled.Palette import androidx.compose.material.icons.outlined.Analytics import androidx.compose.material.icons.outlined.Flag import androidx.compose.material.icons.outlined.Palette import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi import androidx.compose.material3.windowsizeclass.WindowSizeClass 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.key import androidx.compose.runtime.movableContentOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState 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.geometry.CornerRadius import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.input.pointer.PointerIcon import androidx.compose.ui.input.pointer.pointerHoverIcon import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.layout.boundsInParent import androidx.compose.ui.layout.layoutId import androidx.compose.ui.layout.onPlaced import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.selected import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.dp import com.alexvanyo.composelife.ui.app.ComposeLifeNavigation import com.alexvanyo.composelife.ui.app.R import com.alexvanyo.composelife.ui.app.component.PlainTooltipBox import com.alexvanyo.composelife.ui.app.entrypoints.WithPreviewDependencies import com.alexvanyo.composelife.ui.app.theme.ComposeLifeTheme import com.alexvanyo.composelife.ui.util.AnimatedContent import com.alexvanyo.composelife.ui.util.Crossfade import com.alexvanyo.composelife.ui.util.Layout import com.alexvanyo.composelife.ui.util.MobileDevicePreviews import com.alexvanyo.composelife.ui.util.RepeatablePredictiveBackHandler import com.alexvanyo.composelife.ui.util.RepeatablePredictiveBackState import com.alexvanyo.composelife.ui.util.TargetState import com.alexvanyo.composelife.ui.util.rememberRepeatablePredictiveBackStateHolder import com.livefront.sealedenum.GenSealedEnum import kotlin.math.roundToInt interface FullscreenSettingsScreenInjectEntryPoint : SettingUiInjectEntryPoint interface FullscreenSettingsScreenLocalEntryPoint : SettingUiLocalEntryPoint context(FullscreenSettingsScreenInjectEntryPoint, FullscreenSettingsScreenLocalEntryPoint) @OptIn(ExperimentalFoundationApi::class) @Suppress("LongMethod", "CyclomaticComplexMethod") @Composable fun FullscreenSettingsScreen( windowSizeClass: WindowSizeClass, navEntryValue: ComposeLifeNavigation.FullscreenSettings, onBackButtonPressed: () -> Unit, modifier: Modifier = Modifier, ) { val currentWindowSizeClass by rememberUpdatedState(windowSizeClass) val listScrollState = rememberScrollState() val detailScrollStates = SettingsCategory.values.associateWith { key(it) { rememberScrollState() } } fun showList() = when (currentWindowSizeClass.widthSizeClass) { WindowWidthSizeClass.Compact -> !navEntryValue.showDetails else -> true } fun showDetail() = when (currentWindowSizeClass.widthSizeClass) { WindowWidthSizeClass.Compact -> navEntryValue.showDetails else -> true } fun showListAndDetail() = showList() && showDetail() val predictiveBackStateHolder = rememberRepeatablePredictiveBackStateHolder() RepeatablePredictiveBackHandler( repeatablePredictiveBackStateHolder = predictiveBackStateHolder, enabled = showDetail() && !showList(), ) { navEntryValue.showDetails = false } val listContent = remember(navEntryValue) { movableContentOf { SettingsCategoryList( currentSettingsCategory = navEntryValue.settingsCategory, showSelectedSettingsCategory = showListAndDetail(), listScrollState = listScrollState, setSettingsCategory = { navEntryValue.settingsCategory = it navEntryValue.showDetails = true }, showFloatingAppBar = showListAndDetail(), onBackButtonPressed = onBackButtonPressed, modifier = Modifier.fillMaxSize(), ) } } val detailContent = remember(navEntryValue) { movableContentOf { settingsCategory: SettingsCategory -> val detailScrollState = detailScrollStates.getValue(settingsCategory) SettingsCategoryDetail( settingsCategory = settingsCategory, detailScrollState = detailScrollState, showAppBar = !showListAndDetail(), onBackButtonPressed = { navEntryValue.showDetails = false }, settingToScrollTo = navEntryValue.settingToScrollTo, onFinishedScrollingToSetting = { navEntryValue.onFinishedScrollingToSetting() }, modifier = Modifier.fillMaxSize(), ) } } val density = LocalDensity.current val anchoredDraggableState = rememberSaveable( saver = AnchoredDraggableState.Saver( positionalThreshold = { totalDistance -> totalDistance * 0.5f }, velocityThreshold = { with(density) { 200.dp.toPx() } }, snapAnimationSpec = spring(), decayAnimationSpec = exponentialDecay(), ), ) { AnchoredDraggableState( initialValue = 0.5f, positionalThreshold = { totalDistance -> totalDistance * 0.5f }, velocityThreshold = { with(density) { 200.dp.toPx() } }, snapAnimationSpec = spring(), decayAnimationSpec = exponentialDecay(), ) } val minPaneWidth = 200.dp if (showListAndDetail()) { Layout( layoutIdTypes = ListAndDetailLayoutTypes.sealedEnum, modifier = modifier, content = { Spacer( modifier = Modifier .layoutId(ListAndDetailLayoutTypes.StartInsets) .windowInsetsStartWidth(WindowInsets.safeDrawing), ) Spacer( modifier = Modifier .layoutId(ListAndDetailLayoutTypes.EndInsets) .windowInsetsEndWidth(WindowInsets.safeDrawing), ) Box( modifier = Modifier .layoutId(ListAndDetailLayoutTypes.List) .consumeWindowInsets(WindowInsets.safeDrawing.only(WindowInsetsSides.End)), ) { listContent() } Column( Modifier .layoutId(ListAndDetailLayoutTypes.Detail) .consumeWindowInsets(WindowInsets.safeDrawing.only(WindowInsetsSides.Start)) .windowInsetsPadding(WindowInsets.safeDrawing.only(WindowInsetsSides.Horizontal)) .padding( top = 4.dp, start = 8.dp, end = 8.dp, bottom = 16.dp, ), ) { Spacer(Modifier.windowInsetsTopHeight(WindowInsets.safeDrawing)) Surface( color = MaterialTheme.colorScheme.secondaryContainer, shape = RoundedCornerShape(16.dp), modifier = Modifier .weight(1f) .consumeWindowInsets(WindowInsets.safeDrawing.only(WindowInsetsSides.Vertical)), ) { Crossfade( targetState = TargetState.Single(navEntryValue.settingsCategory), ) { settingsCategory -> detailContent(settingsCategory) } } Spacer(Modifier.windowInsetsBottomHeight(WindowInsets.safeDrawing)) } Box( modifier = Modifier .layoutId(ListAndDetailLayoutTypes.Divider) .fillMaxHeight() .windowInsetsPadding(WindowInsets.safeDrawing.only(WindowInsetsSides.Vertical)), contentAlignment = Alignment.Center, ) { val handleInteractionSource = remember { MutableInteractionSource() } Box( modifier = Modifier .size(64.dp) .hoverable( interactionSource = handleInteractionSource, ) .anchoredDraggable( state = anchoredDraggableState, orientation = Orientation.Horizontal, interactionSource = handleInteractionSource, ) .pointerHoverIcon(PointerIcon.Hand), contentAlignment = Alignment.Center, ) { val isHandleDragged by handleInteractionSource.collectIsDraggedAsState() val isHandleHovered by handleInteractionSource.collectIsHoveredAsState() val isHandlePressed by handleInteractionSource.collectIsPressedAsState() val isHandleActive = isHandleDragged || isHandleHovered || isHandlePressed val handleWidth by animateDpAsState( targetValue = if (isHandleActive) 12.dp else 4.dp, label = "handleWidth", ) val handleColor by animateColorAsState( targetValue = if (isHandleActive) { MaterialTheme.colorScheme.onSurface } else { MaterialTheme.colorScheme.outline }, label = "handleColor", ) Canvas( modifier = Modifier.fillMaxSize(), ) { val handleSize = DpSize(handleWidth, 48.dp).toSize() val handleOffset = Offset( (size.width - handleSize.width) / 2f, (size.height - handleSize.height) / 2f, ) drawRoundRect( color = handleColor, topLeft = handleOffset, size = handleSize, cornerRadius = CornerRadius(handleSize.width / 2), ) } } } }, measurePolicy = { measurables, constraints -> val startInsetsPlaceable = measurables .getValue(ListAndDetailLayoutTypes.StartInsets) .measure(constraints.copy(minWidth = 0)) val endInsetsPlaceable = measurables .getValue(ListAndDetailLayoutTypes.EndInsets) .measure(constraints.copy(minWidth = 0)) val minPaneWidthPx = minPaneWidth.toPx() val freeSpace = constraints.maxWidth - startInsetsPlaceable.width - endInsetsPlaceable.width - minPaneWidthPx * 2 layout(constraints.maxWidth, constraints.maxHeight) { val minAnchoredDraggablePosition = 0f val maxAnchoredDraggablePosition = freeSpace.coerceAtLeast(0f) anchoredDraggableState.updateAnchors( newAnchors = ContinuousDraggableAnchors( minAnchoredDraggablePosition = minAnchoredDraggablePosition, maxAnchoredDraggablePosition = maxAnchoredDraggablePosition, ), newTarget = anchoredDraggableState.targetValue, ) val currentFraction = checkNotNull( anchoredDraggableState.anchors.closestAnchor( anchoredDraggableState.requireOffset(), ), ) val listPaneExtraSpace = freeSpace * currentFraction val listPaneWidth = (startInsetsPlaceable.width + minPaneWidthPx + listPaneExtraSpace).roundToInt() val detailPaneWidth = constraints.maxWidth - listPaneWidth val listPanePlaceable = measurables .getValue(ListAndDetailLayoutTypes.List) .measure(constraints.copy(minWidth = listPaneWidth, maxWidth = listPaneWidth)) val detailPanePlaceable = measurables .getValue(ListAndDetailLayoutTypes.Detail) .measure(constraints.copy(minWidth = detailPaneWidth, maxWidth = detailPaneWidth)) listPanePlaceable.placeRelative(0, 0) detailPanePlaceable.placeRelative(listPaneWidth, 0) val dividerPlaceable = measurables .getValue(ListAndDetailLayoutTypes.Divider) .measure(constraints) dividerPlaceable.placeRelative(listPaneWidth - dividerPlaceable.width / 2, 0) } }, ) } else { AnimatedContent( targetState = when (val predictiveBackState = predictiveBackStateHolder.value) { RepeatablePredictiveBackState.NotRunning -> TargetState.Single(showList()) is RepeatablePredictiveBackState.Running -> TargetState.InProgress( current = false, provisional = true, progress = predictiveBackState.progress, ) }, modifier = modifier, ) { showList -> if (showList) { listContent() } else { detailContent(navEntryValue.settingsCategory) } } } } @OptIn(ExperimentalFoundationApi::class) data class ContinuousDraggableAnchors( private val minAnchoredDraggablePosition: Float, private val maxAnchoredDraggablePosition: Float, ) : DraggableAnchors<Float> { override val size: Int = 1 override fun closestAnchor(position: Float): Float = ( position.coerceIn(minAnchoredDraggablePosition, maxAnchoredDraggablePosition) - minAnchoredDraggablePosition ) / (maxAnchoredDraggablePosition - minAnchoredDraggablePosition) override fun closestAnchor(position: Float, searchUpwards: Boolean): Float? = if (searchUpwards) { if (position <= maxAnchoredDraggablePosition) { ( position.coerceIn(minAnchoredDraggablePosition, maxAnchoredDraggablePosition) - minAnchoredDraggablePosition ) / (maxAnchoredDraggablePosition - minAnchoredDraggablePosition) } else { null } } else { if (position >= minAnchoredDraggablePosition) { ( position.coerceIn(minAnchoredDraggablePosition, maxAnchoredDraggablePosition) - minAnchoredDraggablePosition ) / (maxAnchoredDraggablePosition - minAnchoredDraggablePosition) } else { null } } override fun maxAnchor(): Float = maxAnchoredDraggablePosition override fun minAnchor(): Float = minAnchoredDraggablePosition override fun positionOf(value: Float): Float = value * (maxAnchoredDraggablePosition - minAnchoredDraggablePosition) + minAnchoredDraggablePosition override fun hasAnchorFor(value: Float): Boolean = value in minAnchoredDraggablePosition..maxAnchoredDraggablePosition } sealed interface ListAndDetailLayoutTypes { data object StartInsets : ListAndDetailLayoutTypes data object EndInsets : ListAndDetailLayoutTypes data object List : ListAndDetailLayoutTypes data object Detail : ListAndDetailLayoutTypes data object Divider : ListAndDetailLayoutTypes @GenSealedEnum companion object } @OptIn(ExperimentalMaterial3Api::class) @Suppress("LongMethod", "LongParameterList") @Composable private fun SettingsCategoryList( currentSettingsCategory: SettingsCategory, showSelectedSettingsCategory: Boolean, listScrollState: ScrollState, setSettingsCategory: (SettingsCategory) -> Unit, showFloatingAppBar: Boolean, onBackButtonPressed: () -> Unit, modifier: Modifier = Modifier, ) { Scaffold( topBar = { val isElevated = listScrollState.canScrollBackward val elevation by animateDpAsState(targetValue = if (isElevated) 3.dp else 0.dp) Surface( tonalElevation = elevation, shape = RoundedCornerShape(if (showFloatingAppBar) 16.dp else 0.dp), modifier = Modifier .then( if (showFloatingAppBar) { Modifier .windowInsetsPadding( WindowInsets.safeDrawing.only( WindowInsetsSides.Horizontal + WindowInsetsSides.Top, ), ) .padding(4.dp) } else { Modifier }, ), ) { Box( modifier = Modifier .fillMaxWidth() .then( if (showFloatingAppBar) { Modifier } else { Modifier.windowInsetsPadding( WindowInsets.safeDrawing.only( WindowInsetsSides.Horizontal + WindowInsetsSides.Top, ), ) }, ) .height(64.dp), ) { Box( modifier = Modifier.align(Alignment.CenterStart), ) { PlainTooltipBox( tooltip = { Text(stringResource(id = R.string.back)) }, ) { IconButton( onClick = onBackButtonPressed, modifier = Modifier.tooltipAnchor(), ) { Icon( Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(id = R.string.back), ) } } } Text( stringResource(id = R.string.settings), modifier = Modifier.align(Alignment.Center), style = MaterialTheme.typography.titleLarge, ) } } }, modifier = modifier, ) { innerPadding -> Column( modifier = Modifier .fillMaxSize() .verticalScroll(listScrollState) .padding(innerPadding) .consumeWindowInsets(innerPadding) .padding(horizontal = 8.dp) .safeDrawingPadding(), verticalArrangement = Arrangement.spacedBy(16.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { SettingsCategory.values.forEach { settingsCategory -> SettingsCategoryButton( settingsCategory = settingsCategory, showSelectedSettingsCategory = showSelectedSettingsCategory, isCurrentSettingsCategory = settingsCategory == currentSettingsCategory, onClick = { setSettingsCategory(settingsCategory) }, ) } } } } @Composable private fun SettingsCategoryButton( settingsCategory: SettingsCategory, showSelectedSettingsCategory: Boolean, isCurrentSettingsCategory: Boolean, onClick: () -> Unit, ) { val title = settingsCategory.title val outlinedIcon = settingsCategory.outlinedIcon val filledIcon = settingsCategory.filledIcon val isVisuallySelected = showSelectedSettingsCategory && isCurrentSettingsCategory val icon = if (isVisuallySelected) filledIcon else outlinedIcon Card( colors = CardDefaults.cardColors( containerColor = if (isVisuallySelected) { MaterialTheme.colorScheme.surfaceVariant } else { MaterialTheme.colorScheme.surface }, ), onClick = onClick, modifier = Modifier.semantics { if (showSelectedSettingsCategory) { selected = isCurrentSettingsCategory } }, ) { Row( modifier = Modifier .sizeIn(minHeight = 64.dp) .padding(16.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(16.dp), ) { Icon(icon, contentDescription = null) Text( text = title, modifier = Modifier.weight(1f), style = MaterialTheme.typography.titleMedium, ) } } } context(SettingUiInjectEntryPoint, SettingUiLocalEntryPoint) @OptIn(ExperimentalMaterial3Api::class) @Suppress("LongMethod", "LongParameterList") @Composable private fun SettingsCategoryDetail( settingsCategory: SettingsCategory, detailScrollState: ScrollState, showAppBar: Boolean, onBackButtonPressed: () -> Unit, settingToScrollTo: Setting?, onFinishedScrollingToSetting: () -> Unit, modifier: Modifier = Modifier, ) { Column( modifier = modifier, ) { if (showAppBar) { val isElevated = detailScrollState.canScrollBackward val elevation by animateDpAsState(targetValue = if (isElevated) 3.dp else 0.dp) Surface( tonalElevation = elevation, ) { Box( modifier = Modifier .fillMaxWidth() .windowInsetsPadding( WindowInsets.safeDrawing.only( WindowInsetsSides.Horizontal + WindowInsetsSides.Top, ), ) .height(64.dp), ) { Box( modifier = Modifier.align(Alignment.CenterStart), ) { PlainTooltipBox( tooltip = { Text(stringResource(id = R.string.back)) }, ) { IconButton( onClick = onBackButtonPressed, modifier = Modifier.tooltipAnchor(), ) { Icon( Icons.AutoMirrored.Default.ArrowBack, contentDescription = stringResource(id = R.string.back), ) } } } Text( text = settingsCategory.title, modifier = Modifier.align(Alignment.Center), style = MaterialTheme.typography.titleLarge, ) } } } Column( verticalArrangement = Arrangement.spacedBy(16.dp), modifier = Modifier .then( if (showAppBar) { Modifier.consumeWindowInsets( WindowInsets.safeDrawing.only( WindowInsetsSides.Horizontal + WindowInsetsSides.Top, ), ) } else { Modifier }, ) .safeDrawingPadding() .verticalScroll(detailScrollState) .padding(vertical = 16.dp), ) { settingsCategory.settings.forEach { setting -> var layoutCoordinates: LayoutCoordinates? by remember { mutableStateOf(null) } SettingUi( setting = setting, modifier = Modifier .padding(horizontal = 16.dp) .onPlaced { layoutCoordinates = it }, ) val currentOnFinishedScrollingToSetting by rememberUpdatedState(onFinishedScrollingToSetting) LaunchedEffect(settingToScrollTo, layoutCoordinates) { val currentLayoutCoordinates = layoutCoordinates if (currentLayoutCoordinates != null && settingToScrollTo == setting) { detailScrollState.animateScrollTo(currentLayoutCoordinates.boundsInParent().top.roundToInt()) currentOnFinishedScrollingToSetting() } } } } } } private val SettingsCategory.title: String @Composable get() = when (this) { SettingsCategory.Algorithm -> stringResource(id = R.string.algorithm) SettingsCategory.FeatureFlags -> stringResource(id = R.string.feature_flags) SettingsCategory.Visual -> stringResource(id = R.string.visual) } private val SettingsCategory.filledIcon: ImageVector @Composable get() = when (this) { SettingsCategory.Algorithm -> Icons.Filled.Analytics SettingsCategory.FeatureFlags -> Icons.Filled.Flag SettingsCategory.Visual -> Icons.Filled.Palette } private val SettingsCategory.outlinedIcon: ImageVector @Composable get() = when (this) { SettingsCategory.Algorithm -> Icons.Outlined.Analytics SettingsCategory.FeatureFlags -> Icons.Outlined.Flag SettingsCategory.Visual -> Icons.Outlined.Palette } @OptIn(ExperimentalMaterial3WindowSizeClassApi::class) @MobileDevicePreviews @Composable fun FullscreenSettingsScreenListPreview() { WithPreviewDependencies { ComposeLifeTheme { BoxWithConstraints { val size = DpSize(maxWidth, maxHeight) Surface { FullscreenSettingsScreen( windowSizeClass = WindowSizeClass.calculateFromSize(size), navEntryValue = ComposeLifeNavigation.FullscreenSettings( initialSettingsCategory = SettingsCategory.Algorithm, initialShowDetails = false, initialSettingToScrollTo = null, ), onBackButtonPressed = {}, modifier = Modifier.fillMaxSize(), ) } } } } } @OptIn(ExperimentalMaterial3WindowSizeClassApi::class) @MobileDevicePreviews @Composable fun FullscreenSettingsScreenAlgorithmPreview() { WithPreviewDependencies { ComposeLifeTheme { BoxWithConstraints { val size = DpSize(maxWidth, maxHeight) Surface { FullscreenSettingsScreen( windowSizeClass = WindowSizeClass.calculateFromSize(size), navEntryValue = ComposeLifeNavigation.FullscreenSettings( initialSettingsCategory = SettingsCategory.Algorithm, initialShowDetails = true, initialSettingToScrollTo = null, ), onBackButtonPressed = {}, modifier = Modifier.fillMaxSize(), ) } } } } } @OptIn(ExperimentalMaterial3WindowSizeClassApi::class) @MobileDevicePreviews @Composable fun FullscreenSettingsScreenVisualPreview() { WithPreviewDependencies { ComposeLifeTheme { BoxWithConstraints { val size = DpSize(maxWidth, maxHeight) Surface { FullscreenSettingsScreen( windowSizeClass = WindowSizeClass.calculateFromSize(size), navEntryValue = ComposeLifeNavigation.FullscreenSettings( initialSettingsCategory = SettingsCategory.Visual, initialShowDetails = true, initialSettingToScrollTo = null, ), onBackButtonPressed = {}, modifier = Modifier.fillMaxSize(), ) } } } } } @OptIn(ExperimentalMaterial3WindowSizeClassApi::class) @MobileDevicePreviews @Composable fun FullscreenSettingsScreenFeatureFlagsPreview() { WithPreviewDependencies { ComposeLifeTheme { BoxWithConstraints { val size = DpSize(maxWidth, maxHeight) Surface { FullscreenSettingsScreen( windowSizeClass = WindowSizeClass.calculateFromSize(size), navEntryValue = ComposeLifeNavigation.FullscreenSettings( initialSettingsCategory = SettingsCategory.FeatureFlags, initialShowDetails = true, initialSettingToScrollTo = null, ), onBackButtonPressed = {}, modifier = Modifier.fillMaxSize(), ) } } } } }
37
null
9
99
3b697abef92c235eb92dfe3364c3176110a73132
35,309
composelife
Apache License 2.0
kt/godot-library/src/main/kotlin/godot/gen/godot/VisualShaderNodeTransformCompose.kt
utopia-rise
289,462,532
false
null
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY! @file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier", "UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST", "RemoveRedundantQualifierName", "NOTHING_TO_INLINE") package godot import godot.`annotation`.GodotBaseType import kotlin.Suppress import kotlin.Unit /** * Composes a [godot.core.Transform] from four [godot.core.Vector3]s within the visual shader graph. * * Creates a 4x4 transform matrix using four vectors of type `vec3`. Each vector is one row in the matrix and the last column is a `vec4(0, 0, 0, 1)`. */ @GodotBaseType public open class VisualShaderNodeTransformCompose : VisualShaderNode() { public override fun __new(): Unit { callConstructor(ENGINECLASS_VISUALSHADERNODETRANSFORMCOMPOSE) } }
47
Kotlin
25
301
0d33ac361b354b26c31bb36c7f434e6455583738
838
godot-kotlin-jvm
MIT License
services/csm.cloud.project.api.timeseries/src/main/kotlin/com/bosch/pt/csm/cloud/projectmanagement/translation/facade/rest/TranslationRestController.kt
boschglobal
805,348,245
false
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
/* * ************************************************************************ * * Copyright: <NAME> Power Tools GmbH, 2018 - 2023 * * ************************************************************************ */ package com.bosch.pt.csm.cloud.projectmanagement.translation.facade.rest import com.bosch.pt.csm.cloud.common.facade.rest.ApiVersion import com.bosch.pt.csm.cloud.projectmanagement.translation.facade.rest.resource.response.TranslationListResource import com.bosch.pt.csm.cloud.projectmanagement.translation.facade.rest.resource.response.assembler.TranslationListResourceAssembler import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RestController @RestController @ApiVersion class TranslationRestController( private val translationListResourceAssembler: TranslationListResourceAssembler ) { @GetMapping("/translations") fun getTranslations(): TranslationListResource = translationListResourceAssembler.assemble() }
0
Kotlin
3
9
9f3e7c4b53821bdfc876531727e21961d2a4513d
1,003
bosch-pt-refinemysite-backend
Apache License 2.0
mui-icons-kotlin/src/jsMain/kotlin/mui/icons/material/RecyclingTwoTone.kt
karakum-team
387,062,541
false
{"Kotlin": 3079611, "TypeScript": 2249, "HTML": 724, "CSS": 86}
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/RecyclingTwoTone") package mui.icons.material @JsName("default") external val RecyclingTwoTone: SvgIconComponent
0
Kotlin
5
35
60404a8933357df15ecfd8caf6e83258962ca909
196
mui-kotlin
Apache License 2.0
kt/godot-library/src/main/kotlin/godot/gen/godot/PlaneMesh.kt
ShalokShalom
343,354,086
true
{"Kotlin": 516486, "GDScript": 294955, "C++": 262753, "C#": 11670, "CMake": 2060, "Shell": 1628, "C": 959, "Python": 75}
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY! @file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier", "UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST", "RemoveRedundantQualifierName") package godot import godot.annotation.GodotBaseType import godot.core.TransferContext import godot.core.VariantType.LONG import godot.core.VariantType.NIL import godot.core.VariantType.VECTOR2 import godot.core.Vector2 import godot.util.VoidPtr import kotlin.Long import kotlin.Suppress import kotlin.Unit @GodotBaseType open class PlaneMesh : PrimitiveMesh() { open var size: Vector2 get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_PLANEMESH_GET_SIZE, VECTOR2) return TransferContext.readReturnValue(VECTOR2, false) as Vector2 } set(value) { TransferContext.writeArguments(VECTOR2 to value) TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_PLANEMESH_SET_SIZE, NIL) } open var subdivideDepth: Long get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_PLANEMESH_GET_SUBDIVIDE_DEPTH, LONG) return TransferContext.readReturnValue(LONG, false) as Long } set(value) { TransferContext.writeArguments(LONG to value) TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_PLANEMESH_SET_SUBDIVIDE_DEPTH, NIL) } open var subdivideWidth: Long get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_PLANEMESH_GET_SUBDIVIDE_WIDTH, LONG) return TransferContext.readReturnValue(LONG, false) as Long } set(value) { TransferContext.writeArguments(LONG to value) TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_PLANEMESH_SET_SUBDIVIDE_WIDTH, NIL) } override fun __new(): VoidPtr = TransferContext.invokeConstructor(ENGINECLASS_PLANEMESH) open fun size(schedule: Vector2.() -> Unit): Vector2 = size.apply{ schedule(this) size = this } }
0
null
0
1
7b9b195de5be4a0b88b9831c3a02f9ca06aa399c
2,159
godot-jvm
MIT License
ugc-detail-component/src/main/java/com/kotlin/android/ugc/detail/component/binder/UgcBannerImageBinder.kt
R-Gang-H
538,443,254
false
null
package com.kotlin.android.ugc.detail.component.binder import com.kotlin.android.ugc.detail.component.R import com.kotlin.android.ugc.detail.component.bean.UgcImageViewBean import com.kotlin.android.ugc.detail.component.databinding.ItemUgcDetailBannerImageBinding import com.kotlin.android.widget.adapter.multitype.adapter.binder.MultiTypeBinder /** * create by lushan on 2020/8/7 * description: 图集样式ugc 上方banner */ open class UgcBannerImageBinder(var list: MutableList<UgcImageViewBean> = mutableListOf(),var title:String = "") : MultiTypeBinder<ItemUgcDetailBannerImageBinding>() { override fun layoutId(): Int = R.layout.item_ugc_detail_banner_image override fun areContentsTheSame(other: MultiTypeBinder<*>): Boolean { return other is UgcBannerImageBinder && other.list.hashCode() != list.hashCode() } }
0
Kotlin
0
1
e63b1f9a28c476c1ce4db8d2570d43a99c0cdb28
833
Mtime
Apache License 2.0
src/com/aedans/plugins/scheme/config/SchemeConfigurationType.kt
aedans
97,307,821
false
{"XML": 5, "Text": 1, "Ignore List": 1, "Markdown": 1, "Java": 71, "Kotlin": 18, "JFlex": 1}
package com.aedans.plugins.scheme.config import com.intellij.execution.configurations.ConfigurationFactory import com.intellij.execution.configurations.ConfigurationType import com.intellij.execution.configurations.RunConfiguration import com.intellij.openapi.project.Project import icons.SchemePluginIcons import javax.swing.Icon /** * Created by Aedan Smith. */ class SchemeConfigurationType : ConfigurationType { private val configurationFactory = object : ConfigurationFactory(this) { override fun createTemplateConfiguration(project: Project): RunConfiguration { return SchemeRunConfiguration(project, this) } } override fun getDisplayName(): String { return "Scheme Runtime" } override fun getConfigurationTypeDescription(): String { return "Scheme runtime configuration" } override fun getIcon(): Icon { return SchemePluginIcons.SCHEME_ICON } override fun getId(): String { return "com.ackdevelopment.plugins.scheme.config.SchemeConfigurationType" } override fun getConfigurationFactories(): Array<ConfigurationFactory> { return arrayOf(configurationFactory) } }
0
Kotlin
0
1
0590203aa8796c91ce043aeb97f12e2207abf1ea
1,196
Scheme-Support
MIT License
src/main/kotlin/com/helltar/aibot/dao/FilesDAO.kt
Helltar
591,327,331
false
null
package com.helltar.aibot.dao import com.helltar.aibot.dao.DatabaseFactory.dbQuery import org.jetbrains.exposed.sql.insertIgnore import org.jetbrains.exposed.sql.select import com.helltar.aibot.dao.tables.FilesIdsTable as FilesIdsTable class FilesIds { fun add(name: String, fileId: String) = dbQuery { FilesIdsTable.insertIgnore { it[this.name] = name it[this.fileId] = fileId } .insertedCount > 0 } fun getFileId(name: String) = dbQuery { FilesIdsTable.select { FilesIdsTable.name eq name }.singleOrNull()?.get(FilesIdsTable.fileId) } }
0
null
3
21
1a446727f4206d26c786a2958b3a275b1593eefb
618
artific_intellig_bot
MIT License
android_sdk/src/main/java/com/swirepay/android_sdk/retrofit/ApiInterface.kt
swirepay
344,241,532
false
{"Kotlin": 269211, "Java": 70043}
package com.swirepay.android_sdk.retrofit import com.swirepay.android_sdk.checkout.model.* import com.swirepay.android_sdk.model.* import com.swirepay.android_sdk.model.OrderInfo import com.swirepay.android_sdk.model.pusher.AppConfig import com.swirepay.android_sdk.model.pusher.Request import com.swirepay.android_sdk.ui.payment_method.SetupSession import com.swirepay.android_sdk.ui.subscription_button.model.Plan import com.swirepay.android_sdk.ui.subscription_button.model.PlanRequest import com.swirepay.android_sdk.ui.subscription_button.model.SubscriptionButton import com.swirepay.android_sdk.ui.subscription_button.model.SubscriptionButtonRequest import retrofit2.Call import retrofit2.http.* interface ApiInterface { @POST("v1/payment-link") fun fetchPaymentLink( @Body body: PaymentRequest, @Header("x-api-key") api_key: String ): Call<SuccessResponse<PaymentLink>> @GET("v1/payment-link/{paymentLinkGid}") fun checkStatus(@Path("paymentLinkGid") paymentLinkGid: String): Call<SuccessResponse<PaymentLink>> @POST("v1/plan") fun createPlan( @Body planRequest: PlanRequest, @Header("x-api-key") api_key: String ): Call<SuccessResponse<Plan>> @POST("v1/subscription-button") fun createSubscriptionButton( @Body subscriptionButtonRequest: SubscriptionButtonRequest, @Header("x-api-key") api_key: String ): Call<SuccessResponse<SubscriptionButton>> @GET("v1/subscription-button/{subscriptionButtonId}") fun getSubscriptionButton( @Path("subscriptionButtonId") subscriptionButtonId: String, @Header("x-api-key") api_key: String ): Call<SuccessResponse<SubscriptionButton>> @GET("v1/setup-session/{setupSessionId}") fun getSetupSession( @Path("setupSessionId") setupSessionId: String, @Header("x-api-key") api_key: String ): Call<SuccessResponse<SetupSession>> @POST("v1/payment-button") fun createPaymentButtonRequest( @Body paymentButtonRequest: PaymentButtonRequest, @Header("x-api-key") api_key: String ): Call<SuccessResponse<PaymentButton>> @GET("v1/payment-button/{paymentButtonId}") fun getPaymentButton( @Path("paymentButtonId") paymentButtonId: String, @Header("x-api-key") apiKey: String ): Call<SuccessResponse<PaymentButton>> @GET("v1/invoice-link/{invoiceLinkGid}") fun checkInvoiceStatus(@Path("invoiceLinkGid") invoiceLinkGid: String): Call<SuccessResponse<InvoiceResponse>> @GET("/v1/terminal/streams/config") fun GetTerminalConfigData(): Call<AppConfig> @POST("/v1/terminal/streams") fun sendPaymentRequest(@Body request: Request): Call<SuccessResponse<String>> @Headers("Content-Type:application/json") @POST("/v1/payment-method") fun createPaymentMethod( @Body paymentMethod: PaymentMethodCard?, @Header("x-api-key") api_key: String ): Call<SuccessResponse<PaymentMethodResponse>> @Headers("Content-Type:application/json") @POST("/v1/payment-method") fun createPaymentMethodUPI( @Body paymentMethod: PaymentMethodUpi?, @Header("x-api-key") api_key: String ): Call<SuccessResponse<PaymentMethodResponse>> @Headers("Content-Type:application/json") @POST("/v1/payment-method") fun createPaymentMethodNetBanking( @Body paymentMethod: PaymentMethodNetBank?, @Header("x-api-key") api_key: String ): Call<SuccessResponse<PaymentMethodResponse>> @POST("/v1/payment-session") fun createPaymentSession( @Body orderInfo: OrderInfo?, @Header("x-api-key") api_key: String ): Call<SuccessResponse<PaymentSessionResponse>> @GET("/v1/payment-session/{paymentSession}") fun getPaymentSession( @Path("paymentSession") paymentSession: String?, @Query("sp") sp: String?, @Query("secret") secret: String?, @Header("x-api-key") api_key: String ): Call<SuccessResponse<PaymentSessionResponse>> @GET("/v1/profile") fun getProfile( @Header("x-api-key") api_key: String? ): Call<SuccessResponse<ProfileResponse>> @GET("/v1/account/{accountGid}") fun getAccount( @Path("accountGid") accountGid: String, @Header("x-api-key") api_key: String? ): Call<SuccessResponse<AccountResponse>> @PATCH("/v1/card/{cardGid}") fun updateCVV( @Path("cardGid") cardGid: String?, @Body cardInfo: CardInfo, @Header("x-api-key") api_key: String? ): Call<SuccessResponse<CardResponse>> @POST("/v1/customer") fun createCustomer( @Body customer: SPCustomer?, @Header("x-api-key") api_key: String? ): Call<SuccessResponse<CustomerResponse>> @GET("v1/cashfree-bank") fun getAllBanks( @Query("isTest") isTest: Boolean ): Call<SuccessResponse<List<Banks>>> @GET("v1/customer") fun getCustomer( @Query(value = "name.EQ", encoded = true) name: String, @Query(value = "email.EQ", encoded = true) email: String, @Query(value = "phoneNumber.EQ", encoded = true) phoneNumber: String, @Header("x-api-key") api_key: String? ): Call<SuccessResponse<CustomerContent>> @GET("v1/payment-method") fun getPaymentMethod( @Query("customer.gid.EQ", encoded = true) customerGid: String, @Query("isSaved.EQ") isSaved: Boolean, @Header("x-api-key") api_key: String? ): Call<SuccessResponse<PaymentMethodContent>> }
1
Kotlin
3
1
a7f2b6bcae57f471ac6520f667e7c86ea9af64ca
5,498
swirepay-android
MIT License
compiler/testData/diagnostics/testsWithJsStdLib/dynamicTypes/comparisonToNull.kt
JakeWharton
99,388,807
false
null
// FIR_IDENTICAL // !DIAGNOSTICS: -UNUSED_VARIABLE fun test(d: dynamic) { d == null d != null d["foo"] == null d["foo"] != null d.foo == null d.foo != null }
181
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
182
kotlin
Apache License 2.0
src/main/kotlin/App.kt
Daniel0110000
702,220,698
false
{"Kotlin": 259455}
import com.dr10.database.domain.repositories.AutocompleteSettingsRepository import com.dr10.editor.ui.viewModels.EditorViewModel import com.dr10.editor.ui.viewModels.TabsViewModel import com.dr10.settings.ui.viewModels.AutocompleteSettingsViewModel import com.dr10.settings.ui.viewModels.SettingsViewModel import com.dr10.settings.ui.viewModels.SyntaxHighlightSettingsViewModel import org.koin.core.component.KoinComponent import org.koin.core.component.inject import ui.viewModels.CodeEditorViewModel import ui.viewModels.FileTreeViewModel /** * A [KoinComponent] class for provided the dependency injection */ class App: KoinComponent { // Inject [AutocompleteSettingsRepository] val autocompleteSettingsRepository: AutocompleteSettingsRepository by inject() // Inject [SyntaxHighlightSettingsViewModel] val syntaxHighlightSettingsViewModel: SyntaxHighlightSettingsViewModel by inject() // Inject [AutocompleteSettingsViewModel val autocompleteSettingsViewModel: AutocompleteSettingsViewModel by inject() // Inject [SettingsViewModel] val settingsViewModel: SettingsViewModel by inject() // Inject [CodeEditorViewModel] val codeEditorViewModel: CodeEditorViewModel by inject() // Inject [FileTreeViewModel] val fileTreeViewModel: FileTreeViewModel by inject() // Inject [TabsViewModel] val tabsViewModel: TabsViewModel by inject() // Inject [EditorViewModel] val editorViewModel: EditorViewModel by inject() }
1
Kotlin
3
29
9d75ecc560d86e12de14ff3153bcac79b0f0c02d
1,486
DeepCodeStudio
Apache License 2.0
src/test/kotlin/no/nav/familie/ba/sak/kjerne/eøs/EøsPeriodeTest.kt
navikt
224,639,942
false
null
package no.nav.familie.ba.sak.kjerne.eøs // ktlint-disable no-wildcard-imports import no.nav.familie.ba.sak.kjerne.autovedtak.fødselshendelse.Resultat import no.nav.familie.ba.sak.kjerne.eøs.TestUtil.jan import no.nav.familie.ba.sak.kjerne.eøs.kompetanse.domene.MAX_MÅNED import no.nav.familie.ba.sak.kjerne.eøs.kompetanse.domene.MIN_MÅNED import no.nav.familie.ba.sak.kjerne.eøs.kompetanse.domene.RegelverkMåned import no.nav.familie.ba.sak.kjerne.eøs.kompetanse.domene.VilkårResultatMåned import no.nav.familie.ba.sak.kjerne.vilkårsvurdering.domene.Regelverk import no.nav.familie.ba.sak.kjerne.vilkårsvurdering.domene.Vilkår import no.nav.familie.ba.sak.kjerne.vilkårsvurdering.domene.Vilkår.BOR_MED_SØKER import no.nav.familie.ba.sak.kjerne.vilkårsvurdering.domene.Vilkår.BOSATT_I_RIKET import no.nav.familie.ba.sak.kjerne.vilkårsvurdering.domene.Vilkår.GIFT_PARTNERSKAP import no.nav.familie.ba.sak.kjerne.vilkårsvurdering.domene.Vilkår.LOVLIG_OPPHOLD import no.nav.familie.ba.sak.kjerne.vilkårsvurdering.domene.Vilkår.UNDER_18_ÅR import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import java.time.YearMonth internal class EøsPeriodeTest { @Test fun skalFinneEøsPerioderKomplisertCase() { VilkårsvurderingTester(jan(2021)) .medVilkår("---------------- ", UNDER_18_ÅR) .medVilkår(" EEE NNNN EEEE--- ", BOSATT_I_RIKET) .medVilkår(" EEENNEEEEEEEEE ", LOVLIG_OPPHOLD) .medVilkår("NNNNNNNNNNEEEEEEEEEEE", BOR_MED_SØKER) .medVilkår("---------------------", GIFT_PARTNERSKAP) .harUtfall(" ? ?NN? EE ") } @Test fun skalFinneEøsPerioderÅpentCase() { VilkårsvurderingTester(jan(2021)) .medVilkår("--------->", UNDER_18_ÅR) .medVilkår(" EEEE--EE>", BOSATT_I_RIKET) .medVilkår("EEEEEEEEE>", LOVLIG_OPPHOLD) .medVilkår("EEEENNEEE>", BOR_MED_SØKER) .medVilkår("--------->", GIFT_PARTNERSKAP) .harUtfall(" EE??? E>") } @Test fun skalFinneEøsPerioderÅpentToveisCase() { VilkårsvurderingTester(jan(2021)) .medVilkår("---------->", UNDER_18_ÅR) .medVilkår("EEEEE--EE> ", BOSATT_I_RIKET) .medVilkår(" E> ", LOVLIG_OPPHOLD) .medVilkår("EE> ", BOR_MED_SØKER) .medVilkår("---------->", GIFT_PARTNERSKAP) .harUtfall(" EEE?? EE>") } } internal class VilkårsvurderingTester( val startMåned: YearMonth, val vilkårsresultater: List<VilkårResultatMåned> = emptyList() ) { fun medVilkår(v: String, vilkår: Vilkår): VilkårsvurderingTester { return VilkårsvurderingTester( startMåned = this.startMåned, vilkårsresultater = this.vilkårsresultater + parseVilkår(v, vilkår) ) } fun harUtfall(u: String) { val forventedeRegelverkMåneder = parseUtfall(u) val faktiskeRegelverkMåneder = EøsUtil.utledMånederMedRegelverk(this.vilkårsresultater) assertThat(faktiskeRegelverkMåneder).isEqualTo(forventedeRegelverkMåneder) } private fun parseUtfall(u: String): Collection<RegelverkMåned> { return u.mapIndexed { index, tegn -> if (erPeriode(tegn)) lagRegelverkMåned(startMåned.plusMonths(index.toLong()), tegn) else if (tegn == '>') { lagRegelverkMåned(MAX_MÅNED, u[index - 1]) } else if (tegn == '<') { lagRegelverkMåned(MIN_MÅNED, u[index + 1]) } else null }.filterNotNull() } private fun parseVilkår(periodeString: String, vilkår: Vilkår): Collection<VilkårResultatMåned> { return periodeString .mapIndexed { index, tegn -> if (erPeriode(tegn)) { lagVilkårResultatMåned(vilkår, tegn, startMåned.plusMonths(index.toLong())) } else if (tegn == '>') { lagVilkårResultatMåned(vilkår, periodeString[index - 1], MAX_MÅNED) } else if (tegn == '<') { lagVilkårResultatMåned(vilkår, periodeString[index + 1], MIN_MÅNED) } else null } .filterNotNull() } private fun lagRegelverkMåned( måned: YearMonth, tegn: Char ): RegelverkMåned? = if (erPeriode(tegn)) RegelverkMåned(måned = måned, vurderesEtter = finnRegelverk(tegn)) else null private fun lagVilkårResultatMåned( vilkår: Vilkår, tegn: Char, måned: YearMonth ): VilkårResultatMåned? = if (erPeriode(tegn)) VilkårResultatMåned( vilkårType = vilkår, resultat = finnResultat(tegn), måned = måned, vurderesEtter = finnRegelverk(tegn) ) else null private fun erPeriode(c: Char) = when (c) { '?', 'E', 'N', '-' -> true else -> false } private fun finnRegelverk(gjeldendeTegn: Char?): Regelverk? = when (gjeldendeTegn) { 'E' -> Regelverk.EØS_FORORDNINGEN 'N' -> Regelverk.NASJONALE_REGLER else -> null } private fun finnResultat(gjeldendeTegn: Char?) = when (gjeldendeTegn) { ' ' -> Resultat.IKKE_VURDERT '?' -> null else -> Resultat.OPPFYLT } }
3
Kotlin
0
7
a33ee2c537dbe9d78dbbf79deb3e932898fed2f4
5,430
familie-ba-sak
MIT License
app/src/main/java/local/example/jetlike/StartFragment.kt
paolomococci
176,811,727
false
null
/** * * Copyright 2019 <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 local.example.jetlike import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.navigation.Navigation import local.example.jetlike.R.layout class StartFragment : Fragment() { companion object { fun newInstance() = StartFragment() } private lateinit var viewModel: StartViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(layout.start_fragment, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = ViewModelProviders.of(this).get(StartViewModel::class.java) viewModel.data.observe(this, Observer { data -> view?.findViewById<TextView>(R.id.start_fragment_text_view)?.text = data }) view?.findViewById<Button>(R.id.navigate_button)?.setOnClickListener { view?.let { Navigation.findNavController(it).navigate(R.id.end_action) } } } }
0
Kotlin
0
0
b40d9d81463b41aca4c321ee26ae6b05b5192281
1,941
jetlike
Apache License 2.0
app/src/main/java/org/bmsk/beomtube/data/VideoList.kt
AndroidStudy-bmsk
639,497,085
false
null
package org.bmsk.beomtube.data import com.google.gson.annotations.SerializedName data class VideoList( @SerializedName("videos") val videos: List<VideoEntity> ) data class VideoEntity( @SerializedName("id") val id: String, @SerializedName("title") val title: String, @SerializedName("sources") val sources: List<String>, @SerializedName("subtitle") val channelName: String, @SerializedName("thumb") val videoThumb: String, @SerializedName("channelThumb") val channelThumb: String, @SerializedName("viewCount") val viewCount: Long, @SerializedName("date") val date: String, )
0
Kotlin
0
0
cb9b0ae2e5716642dbf0b5b57b78dff9a01e5afb
650
BeomTube
MIT License
core/src/cz/veleto/aoc/core/PosUtils.kt
haluzpav
573,073,312
false
{"Kotlin": 164348}
package cz.veleto.aoc.core import kotlin.math.abs typealias Pos = Pair<Int, Int> typealias Pos3 = Triple<Int, Int, Int> operator fun List<String>.get(pos: Pos): Char = this[pos.first][pos.second] operator fun Pos.plus(other: Pos): Pos = first + other.first to second + other.second operator fun Pos.minus(other: Pos): Pos = first - other.first to second - other.second fun Pos.manhattanTo(other: Pos): Int = abs(first - other.first) + abs(second - other.second) fun Pos3.manhattanTo(other: Pos3): Int = abs(first - other.first) + abs(second - other.second) + abs(third - other.third) operator fun Pair<IntRange, IntRange>.contains(pos: Pos): Boolean { val (xRange, yRange) = this val (x, y) = pos return x in xRange && y in yRange }
0
Kotlin
0
1
f42a04376bbaaa8d9a450ca378d21e9aea2cb3ec
761
advent-of-pavel
Apache License 2.0