path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/no/kasperi/Listeners/ForslagsElementClickListener.kt
Keezpaa
538,821,448
false
null
package no.kasperi.Listeners import no.kasperi.Models.ForslagsElement import no.kasperi.Models.HjemKategoriElement interface ForslagsElementClickListener { fun onKategoriClick(kategori : ForslagsElement) fun onHjemKategoriClick(kategori : HjemKategoriElement) }
0
Kotlin
0
0
1d60fafdef8f99d040a7dcae8ca76df4e6db5bf7
272
Food4U
MIT License
app/src/main/java/com/example/tvmazeapp/data/model/Links.kt
luiz-matias
219,049,110
false
null
package com.example.tvmazeapp.data.model data class Links( val previousepisode: Previousepisode, val self: Self )
0
Kotlin
0
0
b756eeebf78a71ce7379e8b7c1179a8ec90e5018
122
tvmaze-app
MIT License
domain/src/main/java/com/allysonjeronimo/toshop/domain/entity/Category.kt
allysonjeronimo
329,934,342
false
null
package com.allysonjeronimo.toshop.domain.entity data class Category( val id:Long, val resourceIconName:String, val name:String )
0
Kotlin
0
3
0c5ffd6aaa3d31ac6ac6738abc5caafb000f0b19
142
ToShop
MIT License
app/src/main/java/com/example/assignment_8/activities/PlantListActivity.kt
Eaindrae
222,049,972
false
null
package com.example.assignment_8.activities import android.animation.ObjectAnimator import android.content.Intent import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.transition.Fade import android.transition.Slide import android.transition.Transition import android.transition.TransitionListenerAdapter import android.view.* import android.view.animation.AccelerateDecelerateInterpolator import android.view.inputmethod.EditorInfo import android.widget.ImageView import android.widget.TextView import androidx.core.app.ActivityOptionsCompat import androidx.core.util.Pair import androidx.recyclerview.widget.LinearLayoutManager import com.example.assignment_8.R import com.example.assignment_8.adapters.PlantItemAdapter import com.example.assignment_8.data.vos.PlantVO import com.example.assignment_8.mvp.presenters.PlantListPresenter import com.example.assignment_8.mvp.views.PlantListView import kotlinx.android.synthetic.main.activity_plant_list.* class PlantListActivity: BaseActivity(), PlantListView { override fun displayPlantList(plantList: List<PlantVO>) { plantItemAdapter.setNewData(plantList as MutableList<PlantVO>) } override fun displayErrorMessage(message: String) { showSnackBar(message) } override fun navigateToPlantDetail(plant_id: String, plantImageView: ImageView) { val pair = Pair.create(plantImageView as View, "plantTransition") val options = ActivityOptionsCompat.makeSceneTransitionAnimation(this,pair) startActivity(DetailActivity.newIntent(this,plant_id),options.toBundle()) } private lateinit var plantListPresenter: PlantListPresenter private lateinit var plantItemAdapter: PlantItemAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //setUpFadeTransition() setContentView(R.layout.activity_plant_list) setUpPresenter() setUpRecycler() setUpListener() setUpEditableText() plantListPresenter.onUIReady(this) setUpSlideTransition() } private fun setUpFadeTransition(){ with(window){ requestFeature(Window.FEATURE_ACTIVITY_TRANSITIONS) val fadeTransition = Fade() fadeTransition.interpolator = AccelerateDecelerateInterpolator() fadeTransition.duration = 2000 enterTransition = fadeTransition exitTransition = fadeTransition fadeTransition.addListener(object: TransitionListenerAdapter(){ override fun onTransitionEnd(transition: Transition?) { setUpSlideTransition() } }) } } private fun setUpSlideTransition(){ recyclerView.visibility = View.VISIBLE val animator = ObjectAnimator.ofFloat(recyclerView, View.TRANSLATION_X, 800f, recyclerView.width.toFloat()) animator.interpolator = AccelerateDecelerateInterpolator() animator.duration = 3000 animator.start() } private fun setUpPresenter(){ plantListPresenter = PlantListPresenter() plantListPresenter.initPresenter(this) } private fun setUpRecycler(){ with(recyclerView) { setHasFixedSize(true) layoutManager = LinearLayoutManager(this@PlantListActivity) plantItemAdapter = PlantItemAdapter(plantListPresenter) adapter = plantItemAdapter } } private fun setUpListener(){ profile_iv.setOnClickListener { startActivity(Intent(this, ProfileActivity::class.java)) } navigation.setOnClickListener { startActivity(Intent(this, FavouritePlantActivity::class.java)) } } private fun setUpEditableText(){ search_et.setOnEditorActionListener(TextView.OnEditorActionListener { v, actionId, event -> if (actionId == EditorInfo.IME_ACTION_SEARCH) { val search_keyword = search_et.text.toString() return@OnEditorActionListener true } false }) search_et.setOnKeyListener { v, keyCode, event -> if (keyCode == KeyEvent.KEYCODE_DEL) { plantListPresenter.onUIReady(this) } false } search_et.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { } override fun afterTextChanged(s: Editable) { searchByKeyword(s.toString()) } }) } private fun searchByKeyword(keyword: String){ plantItemAdapter.setNewData(plantModel.getPlantsByName(keyword) as MutableList<PlantVO>) recyclerView.adapter = plantItemAdapter } }
0
Kotlin
0
0
d603d455ddca3b49fc6cd4abb730dcfa2cdfda28
4,980
MyPlantAnimation
Apache License 2.0
app/src/main/java/com/example/eyesup_application/MainActivity.kt
marckbarrion
824,524,586
false
{"Kotlin": 28031}
// MainActivity.kt package com.example.eyesup_application import android.Manifest import android.content.pm.PackageManager import android.graphics.Bitmap import android.graphics.Color import android.graphics.Matrix import android.media.MediaPlayer import android.os.Bundle import android.util.Log import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.camera.core.AspectRatio import androidx.camera.core.Camera import androidx.camera.core.CameraSelector import androidx.camera.core.ImageAnalysis import androidx.camera.core.Preview import androidx.camera.lifecycle.ProcessCameraProvider import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.example.eyesup_application.Constants.LABELS_PATH import com.example.eyesup_application.Constants.MODEL_PATH import com.example.eyesup_application.databinding.ActivityMainBinding import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import android.view.WindowManager class MainActivity : AppCompatActivity(), Detector.DetectorListener { private lateinit var binding: ActivityMainBinding // Initialize view binding private val isFrontCamera = false // Set the default camera to back private var preview: Preview? = null // Camera preview use case private var imageAnalyzer: ImageAnalysis? = null // Image analysis use case private var camera: Camera? = null // Camera instance private var cameraProvider: ProcessCameraProvider? = null // Camera provider instance private lateinit var detector: Detector // Object detection instance private lateinit var cameraExecutor: ExecutorService // Executor for camera operations private lateinit var mediaPlayer: MediaPlayer // Media player for detection audio private lateinit var thankYouMediaPlayer: MediaPlayer // Media player for end detection audio private var isDetectionActive = false // Flag to track detection state override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) // Inflate the layout setContentView(binding.root) // Set the content view to the inflated layout window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) // Keep the screen on detector = Detector(baseContext, MODEL_PATH, LABELS_PATH, this) // Initialize detector with model and labels detector.setup() // Setup the detector mediaPlayer = MediaPlayer.create(this, R.raw.eyes_up_walk_safely_tone) // Initialize detection audio player thankYouMediaPlayer = MediaPlayer.create(this, R.raw.thank_you_for_walk_safely_tone) // Initialize end detection audio player if (allPermissionsGranted()) { startCamera() // Start the camera if permissions are granted } else { ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS) // Request necessary permissions } cameraExecutor = Executors.newSingleThreadExecutor() // Initialize the camera executor } private fun startCamera() { val cameraProviderFuture = ProcessCameraProvider.getInstance(this) // Get camera provider instance cameraProviderFuture.addListener({ cameraProvider = cameraProviderFuture.get() // Assign the camera provider bindCameraUseCases() // Bind camera use cases }, ContextCompat.getMainExecutor(this)) } private fun bindCameraUseCases() { val cameraProvider = cameraProvider ?: throw IllegalStateException("Camera initialization failed.") // Check for camera provider val rotation = binding.viewFinder.display.rotation // Get display rotation val cameraSelector = CameraSelector .Builder() .requireLensFacing(CameraSelector.LENS_FACING_BACK) // Select back camera .build() preview = Preview.Builder() .setTargetAspectRatio(AspectRatio.RATIO_4_3) // Set aspect ratio for preview .setTargetRotation(rotation) // Set target rotation .build() imageAnalyzer = ImageAnalysis.Builder() .setTargetAspectRatio(AspectRatio.RATIO_4_3) // Set aspect ratio for image analysis .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST) // Set backpressure strategy .setTargetRotation(binding.viewFinder.display.rotation) // Set target rotation .setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_RGBA_8888) // Set output image format .build() imageAnalyzer?.setAnalyzer(cameraExecutor) { imageProxy -> // Set analyzer for image analysis val bitmapBuffer = Bitmap.createBitmap( imageProxy.width, imageProxy.height, Bitmap.Config.ARGB_8888 ) imageProxy.use { bitmapBuffer.copyPixelsFromBuffer(imageProxy.planes[0].buffer) } // Copy pixels to bitmap buffer imageProxy.close() val matrix = Matrix().apply { postRotate(imageProxy.imageInfo.rotationDegrees.toFloat()) // Rotate image according to rotation degrees if (isFrontCamera) { postScale( -1f, 1f, imageProxy.width.toFloat(), imageProxy.height.toFloat() ) // Flip image for front camera } } val rotatedBitmap = Bitmap.createBitmap( bitmapBuffer, 0, 0, bitmapBuffer.width, bitmapBuffer.height, matrix, true ) detector.detect(rotatedBitmap) // Perform object detection on the rotated bitmap } cameraProvider.unbindAll() // Unbind previous use cases try { camera = cameraProvider.bindToLifecycle( this, cameraSelector, preview, imageAnalyzer ) // Bind preview and image analysis to lifecycle preview?.setSurfaceProvider(binding.viewFinder.surfaceProvider) // Set the surface provider for preview } catch(exc: Exception) { Log.e(TAG, "Use case binding failed", exc) // Log error if binding fails } } private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all { ContextCompat.checkSelfPermission(baseContext, it) == PackageManager.PERMISSION_GRANTED // Check if all permissions are granted } private val requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions()) { if (it[Manifest.permission.CAMERA] == true) { startCamera() } // Start camera if permission is granted } override fun onDestroy() { super.onDestroy() detector.clear() // Clear detector resources cameraExecutor.shutdown() // Shutdown camera executor mediaPlayer.release() // Release media player resources thankYouMediaPlayer.release() // Release thank you media player resources } override fun onResume() { super.onResume() if (allPermissionsGranted()){ startCamera() // Restart camera on resume if permissions are granted } else { requestPermissionLauncher.launch(REQUIRED_PERMISSIONS) // Request permissions if not granted } } companion object { private const val TAG = "Camera" // Tag for logging private const val REQUEST_CODE_PERMISSIONS = 10 // Request code for permissions private val REQUIRED_PERMISSIONS = mutableListOf ( Manifest.permission.CAMERA ).toTypedArray() // Array of required permissions } override fun onEmptyDetect() { binding.overlay.invalidate() // Invalidate overlay on empty detection // Check if a detection was previously active and now it's not if (isDetectionActive) { isDetectionActive = false // Reset detection flag if (!thankYouMediaPlayer.isPlaying) { thankYouMediaPlayer.start() // Play end detection audio } } } override fun onDetect(boundingBoxes: List<BoundingBox>, inferenceTime: Long) { runOnUiThread { binding.inferenceTime.text = "${inferenceTime}ms" // Display inference time // Create a Sort instance to use the update and checkProximity methods val sort = Sort() // Update tracked boxes val trackedBoxes = sort.update(boundingBoxes.map { Sort.Detection(it.x1, it.y1, it.x2, it.y2, it.cnf, it.cls) }) // Convert tracked boxes to BoundingBox objects val boundingBoxList = trackedBoxes.map { track -> BoundingBox( track.x1, track.y1, track.x2, track.y2, (track.x1 + track.x2) / 2, (track.y1 + track.y2) / 2, track.x2 - track.x1, track.y2 - track.y1, track.score, track.cls, when (track.cls) { 0 -> "person" 1 -> "head" 2 -> "cellphone" // 0 -> "person" // 1 -> "cellphone" // 2 -> "head-up" // 3 -> "head-down" // 4 -> "arm-bend" // 5 -> "arm-up" else -> "unknown" }, track.id // Use the track ID for the bounding box ) } // Check proximity and update colors val resultBoxes = sort.checkProximity(boundingBoxList) // Check if any bounding box is red, indicating a cellphone near a head val isPhoneDetectedNearHead = resultBoxes.any { it.color == Color.RED } // Play audio if a phone is detected near a head if (isPhoneDetectedNearHead) { if (!mediaPlayer.isPlaying) { mediaPlayer.start() // Play detection audio } isDetectionActive = true // Set detection flag } binding.overlay.apply { setResults(resultBoxes) // Set detection results invalidate() // Invalidate overlay to trigger redraw } } } }
0
Kotlin
0
0
503d52e3ef9c694bdc08242d4f34ab7842b07d2f
10,606
EyesUp_Application
MIT License
app/src/main/java/me/otomir23/partyverse/ui/map/MapWrapper.kt
kotekote-co
595,217,132
false
null
package me.otomir23.partyverse.ui.map import android.Manifest import androidx.compose.foundation.layout.* import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.viewinterop.AndroidView import androidx.constraintlayout.compose.ConstraintLayout import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.isGranted import com.google.accompanist.permissions.rememberPermissionState import com.mapbox.geojson.Point import com.mapbox.maps.CameraOptions import com.mapbox.maps.MapView import com.mapbox.maps.plugin.annotation.annotations import com.mapbox.maps.plugin.annotation.generated.PointAnnotationOptions import com.mapbox.maps.plugin.annotation.generated.createPointAnnotationManager import com.mapbox.maps.plugin.locationcomponent.location import me.otomir23.partyverse.R @OptIn(ExperimentalPermissionsApi::class) @Composable fun MapWrapper( providedMapView: MapView? = null, showLocation: Boolean = false, onMove: (Point) -> Unit = {}, ) { ConstraintLayout(modifier = Modifier.fillMaxSize()) { val context = LocalContext.current val mapboxMap = createRef() val canShowLocation = rememberPermissionState( permission = Manifest.permission.ACCESS_FINE_LOCATION ).status.isGranted val mapView = providedMapView ?: rememberMapView() val annotationManager = remember { mapView.annotations.createPointAnnotationManager().apply { create( PointAnnotationOptions() .withPoint(Point.fromLngLat(37.458313, 55.660513)) .withIconImage("marker") .withTextField("здесь были убиты пять человек тринадцатого марта") .withTextColor(context.getColor(R.color.white)) .withTextSize(12.0) ) } } LaunchedEffect(canShowLocation, showLocation) { if (canShowLocation && showLocation) { mapView.location.updateSettings { enabled = true pulsingEnabled = true pulsingColor = context.getColor(R.color.purple_500) } var locationUpdated = false mapView.location.addOnIndicatorPositionChangedListener { onMove(it) if (locationUpdated) return@addOnIndicatorPositionChangedListener mapView.getMapboxMap().setCamera( CameraOptions.Builder() .center(it) .zoom(15.0) .build() ) locationUpdated = true } } else { mapView.location.updateSettings { enabled = false } } } AndroidView( factory = {mapView}, modifier = Modifier.constrainAs(mapboxMap) { top.linkTo(parent.top) bottom.linkTo(parent.bottom) start.linkTo(parent.start) end.linkTo(parent.end) } ) } } @Preview @Composable fun MapWrapperPreview() { MapWrapper() }
0
Kotlin
0
1
20ed11329528cc32cf45c7ff0310be854287464a
3,439
partyverse-android
MIT License
core/ui/src/androidTest/java/ytemplate/android/ui/templates/TestLoadingIndicator.kt
codeandtheory
612,178,341
false
{"Kotlin": 185287, "Shell": 2179}
package ytemplate.android.ui.templates import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import org.junit.Rule import org.junit.Test import ytemplate.android.core.ui.templates.AppLoadingIndicator import ytemplate.android.core.ui.theme.YTemplateTheme class TestLoadingIndicator { @get:Rule val composeTestRule = createComposeRule() @Test fun testLoadingIndicator() { // Start the app composeTestRule.setContent { YTemplateTheme { AppLoadingIndicator() } } composeTestRule.onNodeWithTag("loadingIndicator").assertIsDisplayed() } }
11
Kotlin
3
22
8c7ebb298c16f9a72d6538b8ec0fb241a9fc7454
729
ytemplate-android
Apache License 2.0
app/src/main/java/com/leandro/darksoulsapp/SignUpActivity.kt
lennardscript
681,910,132
false
{"Kotlin": 24976}
package com.leandro.darksoulsapp import android.content.Intent import android.content.res.ColorStateList import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button import android.widget.EditText import android.widget.TextView import android.widget.Toast import androidx.core.content.ContextCompat import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.UserProfileChangeRequest import com.google.firebase.database.FirebaseDatabase import com.leandro.darksoulsapp.databinding.ActivitySignUpBinding class SignUpActivity : AppCompatActivity() { private lateinit var binding:ActivitySignUpBinding private lateinit var firebaseAuth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySignUpBinding.inflate(layoutInflater) setContentView(binding.root) firebaseAuth = FirebaseAuth.getInstance() binding.btnSignUp.setOnClickListener { val email = binding.txtEmail.text.toString() val password = binding.txtPassword.text.toString() if (email.isNotEmpty() && password.isNotEmpty()) { firebaseAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener{ if (it.isSuccessful) { val intent = Intent(this, HomeFragment::class.java) startActivity(intent) } else { Toast.makeText(this, it.exception.toString(), Toast.LENGTH_SHORT).show() } } } else { Toast.makeText(this, "Debe completar los campos solicitados", Toast.LENGTH_SHORT).show() } } val textvLogin = findViewById<TextView>(R.id.textvLogin) textvLogin.setOnClickListener { onButtonClick(it) } } fun onButtonClick(view: View) { val intent = Intent(this, SignInActivity::class.java) startActivity(intent) } /* val btnRegister = findViewById<Button>(R.id.btnSignUp) btnRegister.setOnClickListener { onButtonClickSignUp(it) } fun onButtonClickSignUp(view: View) { val intent = Intent(this, HomeActivity::class.java) startActivity(intent) } * */ }
0
Kotlin
0
0
3107df12ab717b9bab308dddd191c319e1e2ee0e
2,364
DarkSoulsApp
MIT License
src/test/kotlin/example/ExampleTest.kt
mfalcier
95,121,055
false
null
package example import org.junit.Assert import org.junit.Rule import org.junit.Test import org.neo4j.driver.v1.Config import org.neo4j.driver.v1.GraphDatabase import org.neo4j.harness.junit.Neo4jRule class ExampleTest { // This rule starts a Neo4j instance @Rule @JvmField var neo4j = Neo4jRule() // This is the function we want to test .withFunction(Example::class.java) .withProcedure(Example::class.java) @Test @Throws(Throwable::class) fun shouldConcatStringsCorrectly() { // In a try-block, to make sure we close the driver and session after the test GraphDatabase.driver(neo4j.boltURI(), Config.build().withoutEncryption().toConfig()).use({ driver -> driver.session().use({ session -> // Given // When val result = session.run("RETURN example.concat(['name','surname'], ';') as result") // Then Assert.assertEquals("name;surname;", result.single().get("result").asString()) }) }) } @Test @Throws(Throwable::class) fun shouldConnectNodesCorrectly() { // In a try-block, to make sure we close the driver and session after the test GraphDatabase.driver(neo4j.boltURI(), Config.build().withoutEncryption().toConfig()).use({ driver -> driver.session().use({ session -> // Given session.run("CREATE (p:From)") session.run("CREATE (p:To)") // When session.run("MATCH (f:From), (t:To) WITH f, t CALL example.connect(f, 'KNOWS', t) RETURN *") // Then val result = session.run("MATCH p=(f:From)-[:KNOWS]->(t:To) return p") Assert.assertEquals(1, result.single().size()) }) }) } }
0
Kotlin
3
5
1549d0e57da0835a08d3e3d7ea6129eb88c53872
1,872
neo4j-kotlin-procedure-example
Apache License 2.0
google-cloud-datastore/src/main/kotlin/NamingHelpers.kt
Khan
170,153,651
false
null
/** * Helpers for translating between kotlin and datastore property names. */ package org.khanacademy.datastore import org.khanacademy.metadata.Meta import kotlin.reflect.KAnnotatedElement import kotlin.reflect.KClass import kotlin.reflect.KParameter import kotlin.reflect.full.findAnnotation import kotlin.reflect.full.memberProperties import kotlin.reflect.full.valueParameters /** * Read the name out of a @Meta annotation, if present. */ internal fun metaAnnotationName(element: KAnnotatedElement): String? { val annotName = element.findAnnotation<Meta>()?.name return if (annotName != null && annotName != "") { annotName } else { null } } /** * Find the name for the given parameter in the datastore. * * Prefer a `@Meta(name = ...)` annotation if present; otherwise, fallback on * the name in code. */ internal fun datastoreName(kParameter: KParameter): String? = metaAnnotationName(kParameter) ?: kParameter.name /** * Get the datastore name for a property by name. * * Prefer a `@Meta(name = ...)` annotation if present; otherwise, fall back on * the provided name. * * Note that because annotations for all properties except computed properties * go on constructor parameters, we need to check both the constructor * parameters and properties to cover both cases. */ internal fun kotlinNameToDatastoreName( cls: KClass<*>, kotlinName: String ): String { val parameter = assertedPrimaryConstructor(cls) .valueParameters.firstOrNull { it.name == kotlinName } val property = cls.memberProperties.firstOrNull { it.name == kotlinName } return parameter?.let { metaAnnotationName(it) } ?: property?.let { metaAnnotationName(it) } ?: kotlinName }
10
Kotlin
2
7
245420984c7362f922f5b22bb34b973ab4a8a9cc
1,778
kotlin-datastore
MIT License
src/main/kotlin/net/hanekawa/papika/toslack/PapikaToSlack.kt
kennydo
98,774,461
false
null
package net.hanekawa.papika.toslack import com.timgroup.statsd.NonBlockingStatsDClient import net.hanekawa.papika.common.getLogger import net.hanekawa.papika.common.slack.SlackClient import org.apache.kafka.clients.consumer.KafkaConsumer import java.util.* class PapikaToSlackBridge(val config: Config) { companion object { val LOG = getLogger(this::class.java) } fun run() { LOG.info("Starting the bridge from Kafka to Slack") val statsd = NonBlockingStatsDClient("papika.toslack", config.statsDHost, config.statsDPort) val slackClient = SlackClient(statsd, config.slackApiToken) LOG.info("Connecting to Kafka servers {} with consumer group {}", config.kafkaBootstrapServers, config.consumerGroup) val kafkaConsumer = createKafkaConsumer(config.kafkaBootstrapServers, config.consumerGroup) LOG.info("Subscribing to topic: {}", config.toSlackTopic) kafkaConsumer.subscribe(arrayListOf(config.toSlackTopic)) val kafkaHandler = KafkaRecordHandler(statsd, slackClient) while (true) { val records = kafkaConsumer.poll(500) records.forEach { try { kafkaHandler.onKafkaRecord(it) } catch (e: Exception) { LOG.error("Failed to handle Kafka record {}: {}", it, e) } } } } private fun createKafkaConsumer(bootstrapServers: String, consumerGroup: String): KafkaConsumer<String, String> { val props = Properties() props.put("bootstrap.servers", bootstrapServers) props.put("group.id", consumerGroup) props.put("enable.auto.commit", "true") props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer") props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer") return KafkaConsumer(props) } } fun main(args: Array<String>) { val config = Config.load() val bridge = PapikaToSlackBridge(config) bridge.run() }
0
Kotlin
0
0
fab4f5813ba74eb32162954274790989199d7d96
2,073
papika2
MIT License
app/src/main/java/com/vitorpamplona/amethyst/model/Channel.kt
vitorpamplona
587,850,619
false
null
package com.vitorpamplona.amethyst.model import androidx.lifecycle.LiveData import com.vitorpamplona.amethyst.service.NostrSingleChannelDataSource import com.vitorpamplona.amethyst.service.model.ChannelCreateEvent import com.vitorpamplona.amethyst.ui.note.toShortenHex import fr.acinq.secp256k1.Hex import java.util.concurrent.ConcurrentHashMap class Channel(val idHex: String) { var creator: User? = null var info = ChannelCreateEvent.ChannelData(null, null, null) var updatedMetadataAt: Long = 0 val notes = ConcurrentHashMap<HexKey, Note>() fun id() = Hex.decode(idHex) fun idNote() = id().toNote() fun idDisplayNote() = idNote().toShortenHex() fun toBestDisplayName(): String { return info.name ?: idDisplayNote() } fun addNote(note: Note) { notes[note.idHex] = note } fun updateChannelInfo(creator: User, channelInfo: ChannelCreateEvent.ChannelData, updatedAt: Long) { this.creator = creator this.info = channelInfo this.updatedMetadataAt = updatedAt live.refresh() } fun profilePicture(): String? { if (info.picture.isNullOrBlank()) info.picture = null return info.picture } fun anyNameStartsWith(prefix: String): Boolean { return listOfNotNull(info.name, info.about) .filter { it.startsWith(prefix, true) }.isNotEmpty() } // Observers line up here. val live: ChannelLiveData = ChannelLiveData(this) fun pruneOldAndHiddenMessages(account: Account): Set<Note> { val important = notes.values .filter { it.author?.let { it1 -> account.isHidden(it1) } == false } .sortedBy { it.createdAt() } .reversed() .take(1000) .toSet() val toBeRemoved = notes.values.filter { it !in important }.toSet() toBeRemoved.forEach { notes.remove(it.idHex) } return toBeRemoved } } class ChannelLiveData(val channel: Channel) : LiveData<ChannelState>(ChannelState(channel)) { fun refresh() { postValue(ChannelState(channel)) } override fun onActive() { super.onActive() NostrSingleChannelDataSource.add(channel.idHex) } override fun onInactive() { super.onInactive() NostrSingleChannelDataSource.remove(channel.idHex) } } class ChannelState(val channel: Channel)
102
Kotlin
70
604
a2d04c99081daa00cbd8ef6ef002c4e97bf94478
2,409
amethyst
MIT License
android/app/src/main/kotlin/com/example/shitshow/MainActivity.kt
Devlonoah
414,564,334
false
{"Dart": 27085, "HTML": 3695, "Swift": 404, "Kotlin": 125, "Objective-C": 38}
package com.example.shitshow import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
3789f8f255139a06691112accb98b4c7ec9beb3e
125
Bank_app-UI-
MIT License
app/src/main/java/vip/qsos/select/SelectHolder.kt
hslooooooool
239,998,824
false
{"Kotlin": 23141}
package vip.qsos.select import android.view.View import androidx.recyclerview.widget.RecyclerView import kotlinx.android.synthetic.main.item_time_picker.view.* /** * @author : 华清松 * * 选择器案例列表项 */ class SelectHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun setData(data: String) { itemView.item_select_name.text = data } }
0
Kotlin
0
2
d66207f709cfa4097abfff1aa1a16cc6a85d4d32
361
widgets-select
Apache License 2.0
src/main/kotlin/daniel/mybank/model/Client.kt
DanFonseca
602,188,054
false
null
package daniel.mybank.model import com.fasterxml.jackson.annotation.JsonIgnore import org.jetbrains.annotations.NotNull import javax.persistence.Entity import javax.persistence.Id import javax.persistence.OneToOne import javax.persistence.Table @Entity @Table(name = "client") class Client ( @Id var cpf: String, @NotNull var name: String, @OneToOne(mappedBy = "client") @JsonIgnore val account: Account? = null ) { }
0
Kotlin
0
0
b327cd4e8d7735b269708580d02bf865904109b8
485
mybank
MIT License
app/src/main/java/ro/alexmamo/firebase/data/User.kt
alexmamo
373,479,949
false
null
package ro.alexmamo.firebase.data import java.util.* data class User( var name: String? = null, var email: String? = null, var photoUrl: String? = null, var createdAt: Date? = null )
0
Kotlin
10
47
c83e9deb3db13dda297fb508bd4908f69454c26f
200
FireApp
Apache License 2.0
platf-skia-awt/src/main/kotlin/org/jetbrains/letsPlot/skia/awt/view/SvgSkikoViewAwt.kt
JetBrains
571,767,875
false
{"Kotlin": 183331}
/* * Copyright (c) 2023 JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package org.jetbrains.letsPlot.skia.awt.view import org.jetbrains.letsPlot.awt.util.AwtEventUtil import org.jetbrains.letsPlot.commons.event.MouseEventSpec import org.jetbrains.letsPlot.skia.view.SvgSkikoView import org.jetbrains.skiko.SkiaLayer import java.awt.Dimension import java.awt.event.MouseEvent import java.awt.event.MouseListener import java.awt.event.MouseMotionListener typealias LetsPlotMouseEvent = org.jetbrains.letsPlot.commons.event.MouseEvent internal class SvgSkikoViewAwt : SvgSkikoView() { override fun updateSkiaLayerSize(width: Int, height: Int) { skiaLayer.preferredSize = Dimension(width, height) } override fun createSkiaLayer(view: SvgSkikoView): SkiaLayer { return SkiaLayer().also { it.renderDelegate = view it.addMouseListener(object : MouseListener { override fun mouseClicked(e: MouseEvent) { view.eventDispatcher?.dispatchMouseEvent(MouseEventSpec.MOUSE_CLICKED, AwtEventUtil.translate(e)) } override fun mousePressed(e: MouseEvent) { view.eventDispatcher?.dispatchMouseEvent(MouseEventSpec.MOUSE_PRESSED, AwtEventUtil.translate(e)) } override fun mouseReleased(e: MouseEvent) { view.eventDispatcher?.dispatchMouseEvent(MouseEventSpec.MOUSE_RELEASED, AwtEventUtil.translate(e)) } override fun mouseEntered(e: MouseEvent) { view.eventDispatcher?.dispatchMouseEvent(MouseEventSpec.MOUSE_ENTERED, AwtEventUtil.translate(e)) } override fun mouseExited(e: MouseEvent) { view.eventDispatcher?.dispatchMouseEvent(MouseEventSpec.MOUSE_LEFT, AwtEventUtil.translate(e)) } }) it.addMouseMotionListener(object : MouseMotionListener { override fun mouseDragged(e: MouseEvent) { view.eventDispatcher?.dispatchMouseEvent(MouseEventSpec.MOUSE_DRAGGED, AwtEventUtil.translate(e)) } override fun mouseMoved(e: MouseEvent) { view.eventDispatcher?.dispatchMouseEvent(MouseEventSpec.MOUSE_MOVED, AwtEventUtil.translate(e)) } }) } } }
5
Kotlin
2
131
765f5eaf2814ceb24f958af7de50e0c8a24a4307
2,465
lets-plot-skia
MIT License
app/src/main/java/com/mikimn/recordio/model/RegisteredCall.kt
mikimn
400,547,041
false
null
package com.mikimn.recordio.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import androidx.room.TypeConverters import com.mikimn.recordio.db.Converters import java.time.Duration enum class CallType { INCOMING, OUTGOING, MISSED } @Entity(tableName = "registered_calls") @TypeConverters(Converters.CallTypeConverter::class, Converters.DurationConverter::class) data class RegisteredCall( @PrimaryKey(autoGenerate = true) val id: Int, @ColumnInfo(name = "source") val source: String, @ColumnInfo(name = "call_type") val callType: CallType, @ColumnInfo(name = "duration") val duration: Duration, )
0
Kotlin
0
0
cb00af440699414acaa7411c13231cde29893572
681
recordio
The Unlicense
src/jsMain/kotlin/io.rippledown.caseview/CaseTableHeader.kt
TimLavers
513,037,911
false
null
package io.rippledown.caseview import emotion.react.css import mui.material.TableCell import mui.material.TableHead import mui.material.TableRow import mui.system.sx import px4 import px8 import react.FC import react.Props import react.dom.html.ReactHTML import react.dom.html.ReactHTML.th import react.dom.html.ReactHTML.thead import react.dom.html.ReactHTML.tr external interface HeaderHandler: Props { var dates: List<Long> } val CaseTableHeader = FC<HeaderHandler> { TableHead { TableRow { TableCell { +"Attribute" sx { padding = px4 } id = "case_table_header_attribute" } it.dates.forEachIndexed { i, d -> EpisodeDateCell { index = i date = d } } TableCell { +"Reference Range" sx { padding = px4 } id = "case_table_header_reference_range" } } } }
0
Kotlin
0
0
870ceee75825a93920839a37a770f159664881a0
1,095
OpenRDR
MIT License
cva-common/src/main/kotlin/com/_2horizon/cva/common/confluence/dto/content/Storage.kt
esowc
264,099,974
false
null
package com._2horizon.cva.common.confluence.dto.content import com.fasterxml.jackson.annotation.JsonProperty data class Storage( @JsonProperty("representation") val representation: String, @JsonProperty("value") val value: String )
3
Kotlin
1
1
e3cf8d9b5f8c76c8c0138b47d24ee91eb3043f82
251
ECMWF-Conversational-Virtual-Assistant
MIT License
feature/calendar/public/src/test/kotlin/fixture/UpcomingReleaseDateFixtures.kt
illarionov
305,333,284
false
{"Kotlin": 2008969, "FreeMarker": 2782, "Shell": 855, "Fluent": 72}
/* * Copyright (c) 2023, the Pixnews project authors and contributors. Please see the AUTHORS file for details. * Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package ru.pixnews.feature.calendar.fixture import kotlinx.datetime.LocalDateTime import kotlinx.datetime.TimeZone import kotlinx.datetime.toInstant import ru.pixnews.domain.model.datetime.Date.Year import ru.pixnews.domain.model.datetime.Date.YearMonth import ru.pixnews.domain.model.datetime.Date.YearMonthDay import ru.pixnews.domain.model.datetime.Date.YearQuarter import java.time.Month.APRIL import java.time.Month.AUGUST import java.time.Month.JULY import java.time.Month.JUNE import java.time.Month.MARCH import java.time.Month.MAY import java.time.Month.OCTOBER object UpcomingReleaseDateFixtures { val currentTimeZone = TimeZone.of("UTC+3") val currentDateTimestamp = LocalDateTime(2023, 4, 19, 23, 10, 0).toInstant(currentTimeZone) object LastMonth { val exactDate25 = YearMonthDay(2023, MARCH, 5) val approxDate = YearMonth(2023, MARCH) } object CurrentMonth { val exactDateStartOfWeek = YearMonthDay(2023, APRIL, 17) val exactDateYesterday = YearMonthDay(2023, APRIL, 18) val exactDateToday = YearMonthDay(2023, APRIL, 19) val exactDateTomorrow = YearMonthDay(2023, APRIL, 20) val exactDateLater25 = YearMonthDay(2023, APRIL, 25) val exactDateLater26 = YearMonthDay(2023, APRIL, 26) val approxDate = YearMonth(2023, APRIL) } object NextMonth { val exactDate10 = YearMonthDay(2023, MAY, 10) val exactDate15 = YearMonthDay(2023, MAY, 15) val approxDate = YearMonth(2023, MAY) } object CurrentQuarter { val exactDate = YearMonthDay(2023, JUNE, 11) val approxDateMonth = YearMonth(2023, JUNE) val approxDateQuarter = YearQuarter(2023, 2) } object NextQuarter { val exactDate = YearMonthDay(2023, JULY, 2) val approxDateMonth = YearMonth(2023, AUGUST) val approxDate3Quarter = YearQuarter(2023, 3) } object CurrentYear { val exactDate2Oct = YearMonthDay(2023, OCTOBER, 2) val approxDateOctober = YearMonth(2023, OCTOBER) val approxDate4Quarter = YearQuarter(2023, 4) val approxDateYear = Year(2023) } object NextYear { val exactDate1jun = YearMonthDay(2024, JUNE, 1) val approxDateApril = YearMonth(2024, APRIL) val approxDateQuarter = YearQuarter(2024, 1) val approxDateYear = Year(2024) } }
0
Kotlin
0
2
0ecc9582728c1cb3c408f94185ce079b289bcf42
2,604
Pixnews
Apache License 2.0
data/RF02414/rnartist.kts
fjossinet
449,239,232
false
{"Kotlin": 8214424}
import io.github.fjossinet.rnartist.core.* rnartist { ss { rfam { id = "RF02414" name = "consensus" use alignment numbering } } theme { details { value = 3 } color { location { 25 to 27 245 to 247 } value = "#fb1827" } color { location { 51 to 60 228 to 237 } value = "#0c3233" } color { location { 63 to 66 167 to 170 } value = "#428675" } color { location { 71 to 78 146 to 153 } value = "#54ca8a" } color { location { 80 to 81 143 to 144 } value = "#cf782d" } color { location { 174 to 178 218 to 222 } value = "#e0d926" } color { location { 184 to 185 210 to 211 } value = "#0fc2c7" } color { location { 186 to 192 202 to 208 } value = "#014e43" } color { location { 28 to 50 238 to 244 } value = "#65b2f6" } color { location { 61 to 62 171 to 173 223 to 227 } value = "#c6a583" } color { location { 67 to 70 154 to 166 } value = "#065621" } color { location { 79 to 79 145 to 145 } value = "#3e97ad" } color { location { 82 to 142 } value = "#381434" } color { location { 179 to 183 212 to 217 } value = "#14b926" } color { location { 186 to 185 209 to 209 } value = "#98b831" } color { location { 193 to 201 } value = "#c06f44" } color { location { 1 to 24 } value = "#37f1e3" } color { location { 248 to 248 } value = "#0a0efd" } } }
0
Kotlin
0
0
3016050675602d506a0e308f07d071abf1524b67
2,858
Rfam-for-RNArtist
MIT License
src/main/kotlin/hu/netcode/slog/data/document/Post.kt
mobal
282,811,538
false
null
package hu.netcode.slog.data.document import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.databind.annotation.JsonSerialize import hu.netcode.slog.serializer.ZonedDateTimeSerializer import org.springframework.data.annotation.Id import org.springframework.data.mongodb.core.mapping.Document import java.time.ZonedDateTime import javax.validation.Valid import javax.validation.constraints.NotEmpty @Document(collection = "posts") data class Post( @Id @JsonIgnore val id: String? = null, @NotEmpty var author: String, var body: String, @NotEmpty @Valid val meta: Meta, @NotEmpty var title: String, @JsonIgnore @NotEmpty var tagList: List<String>, @JsonIgnore val visible: Boolean = true, @JsonIgnore val createdAt: ZonedDateTime? = ZonedDateTime.now(), @JsonIgnore val deletedAt: ZonedDateTime? = null, @JsonSerialize(using = ZonedDateTimeSerializer::class) val publishedAt: ZonedDateTime? = null, @JsonSerialize(using = ZonedDateTimeSerializer::class) var updatedAt: ZonedDateTime = ZonedDateTime.now() ) { @JsonIgnore fun isDeleted(): Boolean { return deletedAt != null } @JsonIgnore fun isPublished(): Boolean { return publishedAt != null } }
0
Kotlin
0
0
2666ecb0a98ea0e156d92aedc546ba63213fe403
1,310
slog
Apache License 2.0
rounded/src/commonMain/kotlin/me/localx/icons/rounded/filled/ChartPieSimpleCircleCurrency.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.filled import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Filled.ChartPieSimpleCircleCurrency: ImageVector get() { if (_chartPieSimpleCircleCurrency != null) { return _chartPieSimpleCircleCurrency!! } _chartPieSimpleCircleCurrency = Builder(name = "ChartPieSimpleCircleCurrency", 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(19.4f, 18.0f) curveToRelative(0.0f, 0.772f, -0.628f, 1.4f, -1.4f, 1.4f) reflectiveCurveToRelative(-1.4f, -0.628f, -1.4f, -1.4f) reflectiveCurveToRelative(0.628f, -1.4f, 1.4f, -1.4f) reflectiveCurveToRelative(1.4f, 0.628f, 1.4f, 1.4f) close() moveTo(18.0f, 12.0f) curveToRelative(-3.314f, 0.0f, -6.0f, 2.686f, -6.0f, 6.0f) reflectiveCurveToRelative(2.686f, 6.0f, 6.0f, 6.0f) reflectiveCurveToRelative(6.0f, -2.686f, 6.0f, -6.0f) reflectiveCurveToRelative(-2.686f, -6.0f, -6.0f, -6.0f) close() moveTo(21.0f, 18.0f) curveToRelative(0.0f, 0.536f, -0.153f, 1.033f, -0.4f, 1.469f) lineToRelative(0.65f, 0.65f) curveToRelative(0.312f, 0.312f, 0.312f, 0.819f, 0.0f, 1.132f) curveToRelative(-0.312f, 0.312f, -0.819f, 0.312f, -1.131f, 0.0f) lineToRelative(-0.65f, -0.65f) curveToRelative(-0.436f, 0.247f, -0.932f, 0.4f, -1.469f, 0.4f) reflectiveCurveToRelative(-1.033f, -0.153f, -1.469f, -0.4f) lineToRelative(-0.65f, 0.65f) curveToRelative(-0.312f, 0.312f, -0.819f, 0.312f, -1.131f, 0.0f) curveToRelative(-0.313f, -0.312f, -0.313f, -0.819f, 0.0f, -1.132f) lineToRelative(0.65f, -0.65f) curveToRelative(-0.247f, -0.436f, -0.4f, -0.932f, -0.4f, -1.469f) reflectiveCurveToRelative(0.153f, -1.033f, 0.4f, -1.469f) lineToRelative(-0.65f, -0.65f) curveToRelative(-0.312f, -0.312f, -0.312f, -0.819f, 0.0f, -1.132f) curveToRelative(0.312f, -0.312f, 0.819f, -0.312f, 1.131f, 0.0f) lineToRelative(0.65f, 0.65f) curveToRelative(0.436f, -0.247f, 0.932f, -0.4f, 1.469f, -0.4f) reflectiveCurveToRelative(1.033f, 0.153f, 1.469f, 0.4f) lineToRelative(0.65f, -0.65f) curveToRelative(0.312f, -0.312f, 0.819f, -0.312f, 1.131f, 0.0f) curveToRelative(0.313f, 0.312f, 0.313f, 0.819f, 0.0f, 1.132f) lineToRelative(-0.65f, 0.65f) curveToRelative(0.247f, 0.436f, 0.4f, 0.932f, 0.4f, 1.469f) close() moveTo(17.112f, 10.0f) horizontalLineToRelative(4.847f) curveToRelative(0.643f, 0.002f, 1.248f, -0.303f, 1.629f, -0.822f) curveToRelative(0.282f, -0.38f, 0.426f, -0.843f, 0.411f, -1.316f) curveToRelative(-0.008f, -0.164f, -0.035f, -0.327f, -0.08f, -0.486f) curveToRelative(-0.234f, -0.872f, -0.584f, -1.708f, -1.038f, -2.487f) curveTo(21.512f, 2.543f, 19.278f, 0.827f, 16.658f, 0.112f) curveToRelative(-0.173f, -0.047f, -0.559f, -0.074f, -0.559f, -0.074f) curveToRelative(-0.138f, 0.0f, -0.732f, 0.0f, -1.203f, 0.381f) curveToRelative(-0.691f, 0.544f, -0.8f, 1.163f, -0.81f, 1.211f) curveToRelative(-0.036f, 0.151f, -0.055f, 0.307f, -0.055f, 0.462f) lineTo(14.031f, 6.919f) curveToRelative(0.0f, 1.702f, 1.379f, 3.081f, 3.081f, 3.081f) close() moveTo(10.0f, 18.0f) curveToRelative(0.0f, -2.531f, 1.178f, -4.783f, 3.012f, -6.249f) curveToRelative(-0.608f, -0.344f, -1.023f, -0.988f, -1.023f, -1.736f) lineTo(11.989f, 5.283f) curveToRelative(0.003f, -0.933f, -0.429f, -1.815f, -1.167f, -2.386f) curveToRelative(-0.7f, -0.554f, -1.618f, -0.752f, -2.484f, -0.535f) curveTo(2.452f, 3.824f, -1.135f, 9.781f, 0.326f, 15.667f) curveToRelative(1.029f, 4.147f, 4.371f, 7.321f, 8.566f, 8.135f) curveToRelative(1.251f, 0.239f, 2.494f, 0.25f, 3.689f, 0.071f) curveToRelative(-1.583f, -1.462f, -2.581f, -3.548f, -2.581f, -5.873f) close() } } .build() return _chartPieSimpleCircleCurrency!! } private var _chartPieSimpleCircleCurrency: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
5,466
icons
MIT License
{{ cookiecutter.repo_name }}/core/src/main/java/{{ cookiecutter.core_package_dir }}/utils/injection/NavigationModule.kt
dawidfiruzek
139,716,709
false
{"Kotlin": 25345}
package {{ cookiecutter.core_package_name }}.utils.injection import dagger.Binds import dagger.Module import {{ cookiecutter.core_package_name }}.navigation.Navigator import {{ cookiecutter.core_package_name }}.navigation.NavigatorImpl @Module abstract class NavigationModule { @Binds abstract fun navigation(navigator: NavigatorImpl): Navigator }
0
Kotlin
1
1
84e73608198a3c1dc6fab439aa9f7d74142e7e38
358
android-kotlin-template
Apache License 2.0
app/src/main/java/com/siliconstack/framework/cleanarch/data/source/local/AppDatabase.kt
sushantinfo4u
304,494,423
false
null
package com.siliconstack.rxkotlinassignment.data.room.appdatabase import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.siliconstack.framework.cleanarch.data.model.User import com.siliconstack.framework.cleanarch.data.source.local.USerDao @Database(entities = arrayOf(User::class),version = 1) abstract class AppDatabase:RoomDatabase() { abstract fun movieDao():USerDao companion object { var INSTANCE: AppDatabase? = null fun getAppDataBase(context: Context): AppDatabase? { if (INSTANCE == null){ synchronized(AppDatabase::class){ INSTANCE = Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, "myDB").build() } } return INSTANCE } fun destroyDataBase(){ INSTANCE = null } } }
0
Kotlin
0
0
eec510f3de4ec29303efdf8c167672418610c099
935
FinalRxAssignment
Apache License 2.0
Aula19Quiz/app/src/main/java/eduardo/gladzik/aula19quiz/activities/Activity18.kt
EduardoGladzik
289,071,387
false
null
package eduardo.gladzik.aula19quiz.activities import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.RadioButton import eduardo.gladzik.aula19quiz.R import eduardo.gladzik.aula19quiz.extension.toast import eduardo.gladzik.aula19quiz.extension.vibrate import eduardo.gladzik.aula19quiz.model.Quiz import kotlinx.android.synthetic.main.activity_18.* import kotlinx.android.synthetic.main.activity_7.* class Activity18 : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_18) activity18ButtonNext.visibility = View.INVISIBLE Quiz.shuffleQuestions() val question = Quiz.questionsArray.get(0) getScore() activity18TextViewQuestion.text = question.questionDescription activity18RadioButtonA.text = question.option1 activity18RadioButtonB.text = question.option2 activity18RadioButtonC.text = question.option3 activity18RadioButtonD.text = question.option4 activity18ButtonConfirm.setOnClickListener { activity18ButtonNext.visibility = View.VISIBLE activity18ButtonConfirm.visibility = View.INVISIBLE val id = activity18RadioGroup.checkedRadioButtonId val radio: RadioButton = findViewById(id) if (Quiz.verifyTheCorrectAnswer(radio.text.toString())) { toast(R.string.toast_thats_correct) } else { toast(R.string.toast_thats_incorrect) } } activity18ButtonNext.setOnClickListener { vibrate() startActivity(Intent(this@Activity18, Activity19::class.java)) finish() } } fun getScore() { activity18TextViewScore.text = Quiz.score().toString() } }
0
Kotlin
0
0
7854c98a604dc4b436583ae0143e86c96ced739f
1,929
kotlin-android
MIT License
korge-core/src/korlibs/image/format/ImageFormats.kt
korlibs
80,095,683
false
{"WebAssembly": 14293935, "Kotlin": 9728800, "C": 77092, "C++": 20878, "TypeScript": 12397, "HTML": 6043, "Python": 4296, "Swift": 1371, "JavaScript": 328, "Shell": 254, "CMake": 202, "CSS": 66, "Batchfile": 41}
package korlibs.image.format import korlibs.encoding.* import korlibs.image.bitmap.* import korlibs.io.concurrent.atomic.* import korlibs.io.file.* import korlibs.io.lang.* import korlibs.io.lang.ASCII import korlibs.io.stream.* import kotlin.coroutines.cancellation.* open class ImageFormats(formats: Iterable<ImageFormat>) : ImageFormat("") { constructor(vararg formats: ImageFormat) : this(formats.toList()) @PublishedApi internal var _formats: Set<ImageFormat> by KorAtomicRef(formats.listFormats() - this) val formats: Set<ImageFormat> get() = _formats fun formatByExtOrNull(ext: String): ImageFormat? = formats.firstOrNull { ext in it.extensions } fun formatByExt(ext: String): ImageFormat { return formatByExtOrNull(ext) ?: throw UnsupportedOperationException("Don't know how to generate file for extension '$ext' (supported extensions ${formats.flatMap { it.extensions }})") } override fun toString(): String = "ImageFormats(${formats.size})$formats" override suspend fun decodeHeaderSuspend(s: AsyncStream, props: ImageDecodingProps): ImageInfo? { for (format in formats) return try { format.decodeHeaderSuspend(s.sliceStart(), props) ?: continue } catch (e: Throwable) { imageLoadingLogger.info { e } if (e is CancellationException) throw e continue } return null } override fun decodeHeader(s: SyncStream, props: ImageDecodingProps): ImageInfo? { if (formats.isEmpty()) return null //println("ImageFormats.decodeHeader:" + formats.size + ": " + formats) for (format in formats) return try { format.decodeHeader(s.sliceStart(), props) ?: continue } catch (e: Throwable) { //e.printStackTrace() if (e is CancellationException) throw e continue } return null } private inline fun <T> readImageTyped(s: SyncStream, props: ImageDecodingProps, block: (format: ImageFormat, s: SyncStream, props: ImageDecodingProps) -> T): T { //val format = formats.firstOrNull { it.check(s.sliceStart(), props) } //println("--------------") //println("FORMATS: $formats, props=$props") for (format in formats) { if (format.check(s.sliceStart(), props)) { //println("FORMAT CHECK: $format") return block(format, s.sliceStart(), props) } } //if (format != null) return format.readImage(s.sliceStart(), props) throw UnsupportedOperationException( "No suitable image format : MAGIC:" + s.sliceStart().readString(4, ASCII) + "(" + s.sliceStart().readBytes(4).hex + ") (" + s.sliceStart().readBytes(4).toString(ASCII) + ")" ) } override fun readImage(s: SyncStream, props: ImageDecodingProps): ImageData { return readImageTyped(s, props) { format, s, props -> format.readImage(s.sliceStart(), props) } } override fun writeImage(image: ImageData, s: SyncStream, props: ImageEncodingProps) { //println("filename: $filename") formatByExt(PathInfo(props.filename).extensionLC).writeImage(image, s, props) } override suspend fun encodeSuspend(image: ImageDataContainer, props: ImageEncodingProps): ByteArray { return formatByExt(props.filename.pathInfo.extensionLC).encodeSuspend(image, props) } override fun readImageContainer(s: SyncStream, props: ImageDecodingProps): ImageDataContainer { return readImageTyped(s, props) { format, s, props -> format.readImageContainer(s.sliceStart(), props) } } override suspend fun decodeSuspend(data: ByteArray, props: ImageDecodingProps): Bitmap { return readImageTyped(data.openSync(), props) { format, s, props -> format.decodeSuspend(data, props) } } override suspend fun decode(file: VfsFile, props: ImageDecodingProps): Bitmap { return formatByExt(file.extensionLC).decode(file, props) } } fun Array<out ImageFormat>.listFormats(): Set<ImageFormat> = this.toList().listFormats() fun Iterable<ImageFormat>.listFormats(): Set<ImageFormat> = flatMap { it.listFormats() }.toMutableSet() fun ImageFormat.listFormats(): Set<ImageFormat> = when (this) { is ImageFormats -> this.formats else -> setOf(this) } operator fun ImageFormat.plus(format: ImageFormat): ImageFormat { if (this == format) return this if (format is ImageFormats && format.formats.isEmpty()) return this if (this is ImageFormats && this.formats.isEmpty()) return format return ImageFormats((this.listFormats() + format.listFormats()).distinct()) } operator fun ImageFormat.plus(formats: List<ImageFormat>): ImageFormat { if (formats.isEmpty()) return this if (formats.size == 1) return this + formats.first() return this + ImageFormats(formats.listFormats()) } @Suppress("unused") suspend fun Bitmap.writeTo( file: VfsFile, formats: ImageFormat = RegisteredImageFormats, props: ImageEncodingProps = ImageEncodingProps() ) = file.writeBytes(formats.encode(this, props.withFile(file))) @Suppress("unused") suspend fun BmpSlice.writeTo( file: VfsFile, formats: ImageFormat = RegisteredImageFormats, props: ImageEncodingProps = ImageEncodingProps() ) = this.extract().writeTo(file, formats, props) suspend fun Bitmap.encode(formats: ImageFormat = RegisteredImageFormats, props: ImageEncodingProps = ImageEncodingProps()) = formats.encode(this, props)
444
WebAssembly
121
2,207
dc3d2080c6b956d4c06f4bfa90a6c831dbaa983a
5,518
korge
Apache License 2.0
wrapper/godot-library/src/main/kotlin/godot/generated/StreamTexture.kt
payload
189,718,948
true
{"Kotlin": 3888394, "C": 6051, "Batchfile": 714, "Shell": 574}
@file:Suppress("unused", "ClassName", "EnumEntryName", "FunctionName", "SpellCheckingInspection", "PARAMETER_NAME_CHANGED_ON_OVERRIDE", "UnusedImport", "PackageDirectoryMismatch") package godot import godot.gdnative.* import godot.core.* import godot.utils.* import godot.icalls.* import kotlinx.cinterop.* // NOTE: THIS FILE IS AUTO GENERATED FROM JSON API CONFIG open class StreamTexture : Texture { constructor() : super("StreamTexture") constructor(variant: Variant) : super(variant) internal constructor(mem: COpaquePointer) : super(mem) internal constructor(name: String) : super(name) // Enums // Signals class Signal { companion object { } } companion object { infix fun from(other: Texture): StreamTexture = StreamTexture("").apply { setRawMemory(other.rawMemory) } infix fun from(other: Resource): StreamTexture = StreamTexture("").apply { setRawMemory(other.rawMemory) } infix fun from(other: Reference): StreamTexture = StreamTexture("").apply { setRawMemory(other.rawMemory) } infix fun from(other: Object): StreamTexture = StreamTexture("").apply { setRawMemory(other.rawMemory) } infix fun from(other: Variant): StreamTexture = fromVariant(StreamTexture(""), other) // Constants } // Properties open val loadPath: String get() = _icall_String(getLoadPathMethodBind, this.rawMemory) // Methods private val loadMethodBind: CPointer<godot_method_bind> by lazy { getMB("StreamTexture", "load") } open fun load(path: String): GodotError { return GodotError.fromInt(_icall_Long_String(loadMethodBind, this.rawMemory, path)) } private val getLoadPathMethodBind: CPointer<godot_method_bind> by lazy { getMB("StreamTexture", "get_load_path") } open fun getLoadPath(): String { return _icall_String(getLoadPathMethodBind, this.rawMemory) } }
0
Kotlin
1
2
70473f9b9a0de08d82222b735e7f9b07bbe91700
1,938
kotlin-godot-wrapper
Apache License 2.0
RickandMorty/core/src/main/java/com/renatoramos/rickandmorty/data/store/local/paperdb/provider/episodes/EpisodesProvider.kt
renatoramos7
208,802,459
false
null
package com.renatoramos.rickandmorty.data.store.local.paperdb.provider.episodes import com.renatoramos.rickandmorty.data.store.dto.episodes.EpisodeDTO import io.paperdb.Paper import io.reactivex.Observable class EpisodesProvider { fun add(repos: List<EpisodeDTO>, page: Int, tagKey: String): Observable<List<EpisodeDTO>> { val tagPage = tagKey+page return Observable.create<List<EpisodeDTO>> { e -> try { Paper.book().delete(tagPage) Paper.book().write(tagPage, repos) e.onNext(repos) e.onComplete() } catch (exception: Exception) { e.onError(exception) } } } fun getAll(page: Int, tagKey: String): Observable<List<EpisodeDTO>> { val repoList = Paper.book().read<List<EpisodeDTO>>(tagKey+page) return if (repoList != null) { Observable.just<List<EpisodeDTO>>(repoList) } else { val episodeDTOList: List<EpisodeDTO> = listOf() Observable.just(episodeDTOList) } } fun getById(id: Int?, page: Int, tagKey: String): Observable<EpisodeDTO> { val repoList = Paper.book().read<List<EpisodeDTO>>(tagKey+page) return if (repoList != null) { Observable.fromIterable(repoList).filter { repo -> repo.id == id }.map{ customer -> customer } } else { val episodeDTOList: EpisodeDTO? = null Observable.just<EpisodeDTO>(episodeDTOList) } } fun delete(page: Int, tagKey: String): Observable<Void> { return Observable.create { e -> try { Paper.book().delete(tagKey+page) e.onComplete() } catch (exception: Exception) { e.onError(exception) } } } }
0
Kotlin
1
1
d953085a36b1daae251107cd4c18ac5b50eebb44
1,869
Rick-And-Morty-Android
MIT License
core/src/main/kotlin/io/github/iromul/home/media/movies/kox/copy/CommandFileExecutor.kt
iRomul
739,488,993
false
{"Kotlin": 2124}
package io.github.iromul.home.media.movies.kox.copy import io.github.iromul.home.media.io.filesystem.FilesystemOperations import io.github.iromul.home.media.movies.kox.model.CommandFile class CommandFileExecutor( private val filesystemOperations: FilesystemOperations ) { fun exec(commandFile: CommandFile) { commandFile.targets?.forEach { filesystemOperations.requireOrCreateDirectory(it.path!!) } } }
0
Kotlin
0
0
13182af6cd0c0c4130ccf83a4c95f0f558ac4a37
445
home-media-movies-kox
MIT License
app/src/main/java/de/j4velin/babyphone/Recorder.kt
j4velin
266,587,635
false
null
package de.j4velin.babyphone import android.content.Context import android.media.MediaRecorder import android.util.Log import java.io.File import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger /** * An object, which can be stopped */ interface Stoppable { /** * Stops this Stoppable */ fun stop() } /** * Continuously gets the max amplitude between two measurements * * @param delayMs the delay between to measurements * @param context the Android context * @param action the action to invoke when a value was measured * @return a stoppable to stop the measurements */ fun getAmplitude(delayMs: Long, context: Context, action: (Int) -> Unit): Stoppable { val keepRunning = AtomicBoolean(true) getAmplitudeWhile({ keepRunning.get() }, delayMs, context, action) return object : Stoppable { override fun stop() { keepRunning.set(false) } } } private val recorder: MediaRecorder by lazy { MediaRecorder() } private val listener = AtomicInteger(0) /** * Continuously gets the max amplitude between two measurements as long as the condition is fulfilled * * @param condition the amplitude is measured until this condition produces false * @param delayMs the delay between to measurements * @param context the Android context * @param action the action to invoke when a value was measured */ fun getAmplitudeWhile( condition: () -> Boolean, delayMs: Long, context: Context, action: (Int) -> Unit ) { if (listener.getAndIncrement() == 0) { // first listener? then start recoding recorder.setAudioSource(MediaRecorder.AudioSource.MIC) recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP) recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB) recorder.setOutputFile(File(context.externalCacheDir, "babyphone")) recorder.prepare() try { recorder.start() } catch (e: Exception) { Log.e(TAG, "Can not start recorder", e) listener.getAndDecrement() return } recorder.maxAmplitude // ignore first value Log.i(TAG, "recoding started") } Thread { while (condition.invoke()) { action.invoke(recorder.maxAmplitude) Thread.sleep(delayMs) } if (listener.decrementAndGet() == 0) { // no component needs amplitude updates any more -> stop recording recorder.stop() Log.i(TAG, "all listener expired -> recoding stopped") } else { Log.i(TAG, "listener expired but recording still active") } }.start() }
0
Kotlin
0
1
013c1a526e80f21717a82b18d4673d4693f86743
2,701
Babyphone
Apache License 2.0
st_predicted_maintenance/src/main/java/com/st/predicted_maintenance/composable/PredictedMaintenanceAxeElementView.kt
STMicroelectronics
81,465,478
false
{"Kotlin": 2828028, "Java": 25368, "Shell": 13927, "HTML": 3291, "GLSL": 1461}
package com.st.predicted_maintenance.composable import androidx.annotation.DrawableRes import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import com.st.blue_sdk.features.extended.predictive.Status import com.st.predicted_maintenance.R import com.st.predicted_maintenance.utilities.Point import com.st.ui.theme.LocalDimensions import java.util.Locale @Composable fun PredictedMaintenanceAxeElementView( modifier: Modifier = Modifier, axeName: String, statusValue: Status?, point: Point?, format: String = "Peak: %.2f" ) { Row( modifier = modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(LocalDimensions.current.paddingNormal) ) { statusValue?.let { status -> Icon( modifier = Modifier .size(size = LocalDimensions.current.iconNormal), painter = painterResource( getStatusImage(status) ), tint = Color.Unspecified, contentDescription = null ) } Column( modifier .weight(2f) .padding(start = LocalDimensions.current.paddingNormal), horizontalAlignment = Alignment.Start, verticalArrangement = Arrangement.spacedBy(LocalDimensions.current.paddingNormal) ) { statusValue?.let { status -> Text( style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.primary, text = "$axeName: ${getStatusString(status)}" ) } point?.let { point -> point.freq?.let { freq -> if(!freq.isNaN()) { Text( style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.primary, text = String.format( Locale.getDefault(), "Frequency (Hz): %.2f", freq ) ) } } point.value?.let { value -> if(!value.isNaN()) { Text( style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.primary, text = String.format(Locale.getDefault(), format, value) ) } } } } } } private fun getStatusString(s: Status): String { return when (s) { Status.GOOD -> "Good" Status.WARNING -> "Warning" Status.BAD -> "Alarm" else -> "Unknown" } } @DrawableRes private fun getStatusImage(s: Status): Int { return when (s) { Status.GOOD -> R.drawable.predictive_status_good Status.WARNING -> R.drawable.predictive_status_warnings Status.BAD -> R.drawable.predictive_status_bad else -> R.drawable.predictive_status_unknown } }
12
Kotlin
58
114
cd556743faffbf1e759543f639659ae3a40b789a
3,836
STBLESensor_Android
The Unlicense
app/src/main/java/com/mizukikk/mltd/room/dao/IdolDao.kt
mizukikk
268,541,057
false
null
package com.mizukikk.mltd.room.dao import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.mizukikk.mltd.data.source.local.preferences.PreferencesHelper import com.mizukikk.mltd.room.entity.* import com.mizukikk.mltd.room.query.IdolItem @Dao interface IdolDao { @Query("SELECT * FROM idol WHERE idol.lang = :lang AND idol.cardId < 8000 ORDER BY idol.cardId DESC LIMIT 1") fun checkDBData(lang: String = PreferencesHelper.apiLanguage): List<IdolEntity> @Query("SELECT * FROM idol WHERE idol.cardId = :id") fun searchById(id: Int): List<IdolEntity> @Query("SELECT * FROM idol WHERE idol.lang = :lang ORDER BY idol.cardId DESC ") fun getFirstIdolList(lang: String): List<IdolItem> @Query("SELECT * FROM idol WHERE idol.cardId <= :currentId AND idol.lang = :lang ORDER BY idol.cardId DESC LIMIT 20") fun getIdolList(currentId: Int, lang: String): List<IdolItem> @Query("SELECT * FROM idol WHERE idol.lang = :lang ORDER BY idol.cardId DESC") fun getAllIdolList(lang: String): List<IdolItem> @Query("SELECT * FROM idol WHERE idol.lang = 'ja' AND idol.rarity = 4 AND idol.idolId = :idolId ORDER BY idol.cardId DESC LIMIT 1 ") fun getAnivIdolIconData(idolId: Int): List<IdolItem> @Query("SELECT * FROM idol WHERE idol.lang = 'ja' AND idol.rarity = 4 AND category != 'event3' GROUP BY idol.idolId ORDER BY idolId ASC") fun getAnivEventIdolList(): List<IdolItem> @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertIdol(idolEntity: IdolEntity) @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertCenterEffect(centerEffectEntity: CenterEffectEntity) @Insert(onConflict = OnConflictStrategy.IGNORE) fun insertCostume(costumeEntity: CostumeEntity) @Insert(onConflict = OnConflictStrategy.IGNORE) fun insertBonusCostume(bonusCostumeEntity: BonusCostumeEntity) @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertRank5Costume(rank5CostumeEntity: Rank5CostumeEntity) @Insert(onConflict = OnConflictStrategy.IGNORE) fun insertSkill(skillEntity: SkillEntity) }
0
Kotlin
0
0
10e765109df9d0aa68557e78720851eae51622f1
2,158
MLTD
MIT License
src/main/kotlin/names/MoorishNames.kt
Jaboo36
748,020,581
false
{"Kotlin": 55361}
package names object MoorishNames { fun generateName(isFemale: Boolean): String { val firstName = if (isFemale) femaleNames.random() else maleNames.random() val lastName = maleNames.random() val prefix = if (isFemale) prefix.first() else prefix.last() return "$firstName $prefix$lastName" } private val femaleNames = setOf( "Aisha", "Amena", "Baya", "Hadada", "Illi", "Kahina", "Kella", "Lella", "Lemta", "Lundja", "Markunda", "Muli", "Rayshabu", "Safiyya", "Sekkura", "Tanelhir", "Tanloubouh", "Thula", "Tinfsut", "tioueyin", "Tufifawt", "Tufent", "Wertenezzu", "Zegiga", "Zahara" ) private val maleNames = setOf( "Ahmedu", "Amergiw", "Antal", "Asmil", "Azawakh", "Aziouel", "Baragsen", "Beddis", "Bekketa", "Brahim", "Dassin", "Ehenkouen", "Ehenu", "Idir", "Ilou", "Izil", "Khyar", "Lamine", "Masgaba", "Massena", "Munatas", "Sidi", "Sufian", "Tariq", "Udad", "Wagguten", "Yabdas", "Yuba", "Yugerten", "Ziri" ) private val prefix = setOf( "ult-", "ag-" ) }
0
Kotlin
0
0
93dd227878face46b19273d16c802594126c0a93
1,484
hyperborea-name-generator
Creative Commons Zero v1.0 Universal
bash-cli/src/main/kotlin/ru/hse/spb/cli/commands/PwdCommand.kt
trilis
237,592,057
false
null
package ru.hse.spb.cli.commands import java.io.File /** * This command simulates behaviour of 'pwd' bash command, printing current directory. */ class PwdCommand : Command { /** * Executes this command. * @param input is ignored. * @return absolute path of current directory. */ override fun run(input: List<String>): List<String> = listOf(File("").absolutePath) }
1
Kotlin
1
0
dbeac5651ec14145245665ee5ae155550e6e77c6
405
software-design-course
Apache License 2.0
phoenix-shared/src/commonMain/kotlin/fr.acinq.phoenix/utils/NetworkMonitor.kt
wiz
359,536,747
true
{"Kotlin": 436559, "Swift": 345238, "HTML": 2524, "CSS": 959}
package fr.acinq.phoenix.utils import fr.acinq.lightning.utils.Connection import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.flow.StateFlow import org.kodein.log.LoggerFactory enum class NetworkState { Available, NotAvailable } @OptIn(ExperimentalCoroutinesApi::class) expect class NetworkMonitor(loggerFactory: LoggerFactory, ctx: PlatformContext) { val networkState: StateFlow<NetworkState> fun start() fun stop() }
0
null
0
1
99782bafc218365ddcd4b504812df15337ca6103
518
phoenix-kmm
Apache License 2.0
app/src/main/java/com/fberg/newsapp/feature/presentation/search/components/CountrySearchSelection.kt
FabioFehlberg
567,386,268
false
{"Kotlin": 62671}
package com.fberg.newsapp.feature.presentation.search.components import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.fberg.newsapp.feature.presentation.search.CountryForSearch @Composable fun CountrySearchSelection( onCountrySelected: (CountryForSearch) -> Unit ) { val scrollState = rememberScrollState() var countrySelected by remember { mutableStateOf(CountryForSearch.GERMANY) } Row( modifier = Modifier .fillMaxWidth() .horizontalScroll(scrollState) .padding(end = 16.dp) ) { RadioButtonIcon( icon = CountryForSearch.NONE.icon, selected = countrySelected == CountryForSearch.NONE, onSelect = { countrySelected = CountryForSearch.NONE onCountrySelected(CountryForSearch.NONE) } ) Spacer(modifier = Modifier.width(8.dp)) RadioButtonIcon( icon = CountryForSearch.GERMANY.icon, selected = countrySelected == CountryForSearch.GERMANY, onSelect = { countrySelected = CountryForSearch.GERMANY onCountrySelected(CountryForSearch.GERMANY) } ) Spacer(modifier = Modifier.width(8.dp)) RadioButtonIcon( icon = CountryForSearch.UNITED_STATES.icon, selected = countrySelected == CountryForSearch.UNITED_STATES, onSelect = { countrySelected = CountryForSearch.UNITED_STATES onCountrySelected(CountryForSearch.UNITED_STATES) } ) Spacer(modifier = Modifier.width(8.dp)) RadioButtonIcon( icon = CountryForSearch.BRAZIL.icon, selected = countrySelected == CountryForSearch.BRAZIL, onSelect = { countrySelected = CountryForSearch.BRAZIL onCountrySelected(CountryForSearch.BRAZIL) } ) Spacer(modifier = Modifier.width(8.dp)) RadioButtonIcon( icon = CountryForSearch.AUSTRALIA.icon, selected = countrySelected == CountryForSearch.AUSTRALIA, onSelect = { countrySelected = CountryForSearch.AUSTRALIA onCountrySelected(CountryForSearch.AUSTRALIA) } ) Spacer(modifier = Modifier.width(8.dp)) RadioButtonIcon( icon = CountryForSearch.RUSSIA.icon, selected = countrySelected == CountryForSearch.RUSSIA, onSelect = { countrySelected = CountryForSearch.RUSSIA onCountrySelected(CountryForSearch.RUSSIA) } ) } }
0
Kotlin
0
0
b0bc34f5f1e836795b77d1ff3982f9c7d9e2804d
3,272
NewsAppCompose
MIT License
src/main/kotlin/no/nav/NarePrometheus.kt
navikt
170,293,591
false
null
package no.nav import io.prometheus.client.CollectorRegistry import io.prometheus.client.Counter import no.nav.nare.core.evaluations.Evaluering class NarePrometheus(registry: CollectorRegistry) { val idLabel = "identifikator" val evaluationLabel = "evaluation" private val telleverk: Counter = Counter .build("nare_result", "for storing the results of nare evaluations") .labelNames(idLabel, evaluationLabel) .register(registry) fun tellEvaluering(function: () -> Evaluering): Evaluering { val evaluering: Evaluering = function() evaluering.tell() return evaluering } private fun Evaluering.tell() { telleverk .labels(this.identifikator, this.resultat.name) .inc() this.children.forEach { it.tell() } } }
1
Kotlin
0
0
0b41ab472f0034ae3b05eafd786dd55e1c6d5aed
848
nare-prometheus
MIT License
app/src/main/java/com/pablo/desafio/shared/di/ActivityBuilderModule.kt
digounet
134,750,176
true
{"Kotlin": 35004}
package com.pablo.desafio.shared.di import com.pablo.desafio.features.detail.MovieDetailActivity import com.pablo.desafio.features.main.MainActivity import dagger.Module import dagger.Provides import dagger.android.ContributesAndroidInjector @Module interface ActivityBuilderModule { @ContributesAndroidInjector(modules = [(FragmentBuilderModule::class)]) fun mainActivity(): MainActivity @ContributesAndroidInjector(modules = [(FragmentBuilderModule::class)]) fun detailActivity(): MovieDetailActivity }
0
Kotlin
0
0
7887077f81caf400e7faf101c48de726520f85cc
523
desafio-android
The Unlicense
platform/experiment/src/com/intellij/platform/experiment/ab/impl/experiment/ABExperiment.kt
sprigogin
285,457,947
false
{"Text": 9376, "INI": 516, "YAML": 419, "Ant Build System": 11, "Batchfile": 33, "Dockerfile": 10, "Shell": 633, "Markdown": 744, "Ignore List": 143, "Git Revision List": 1, "Git Attributes": 11, "EditorConfig": 260, "XML": 7826, "SVG": 4416, "Kotlin": 58363, "Java": 83686, "HTML": 3782, "Java Properties": 220, "Gradle": 447, "Maven POM": 95, "JavaScript": 229, "CSS": 79, "JSON": 1419, "JFlex": 33, "Makefile": 5, "Diff": 137, "XSLT": 113, "Gradle Kotlin DSL": 713, "Groovy": 3131, "desktop": 1, "JAR Manifest": 17, "PHP": 47, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 13, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 26, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 72, "GraphQL": 125, "Nginx": 1, "HAProxy": 1, "OpenStep Property List": 47, "Python": 17005, "C": 111, "C++": 42, "Protocol Buffer": 3, "fish": 2, "PowerShell": 3, "Go": 36, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "HCL": 4, "Elixir": 2, "Ruby": 4, "XML Property List": 84, "E-mail": 18, "Roff": 283, "Roff Manpage": 40, "Swift": 3, "TOML": 196, "Checksums": 49, "Java Server Pages": 11, "Vue": 1, "Dotenv": 1, "reStructuredText": 67, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 17, "Handlebars": 1, "Rust": 17, "Go Checksums": 1, "Go Module": 1, "NSIS": 8, "PlantUML": 6, "SCSS": 2, "Thrift": 3, "Cython": 13, "Regular Expression": 3, "JSON5": 4, "OASv3-json": 3, "OASv3-yaml": 1}
// 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.platform.experiment.ab.impl.experiment import com.intellij.internal.statistic.eventLog.fus.MachineIdManager import com.intellij.internal.statistic.utils.getPluginInfoByDescriptor import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.platform.experiment.ab.impl.option.ABExperimentControlOption import com.intellij.util.MathUtil import com.intellij.util.PlatformUtils fun getABExperimentInstance(): ABExperiment { return ApplicationManager.getApplication().service<ABExperiment>() } /** * This is a multi-optional A/B experiment for all IDEs and JetBrains plugins, * which affects IDE metrics like user retention in IDE. * * Each feature is represented as an option. * An option defines the number of user groups which will be associated with this option. * There is a control option for default behavior. * You need to implement `ABExperimentOption` extension point to implement an option for your feature. * * The number of A/B experimental groups is limited. * It is necessary to keep a group audience sufficient to make statistically significant conclusions. * So it is crucial to choose group size judiciously. * If group capacity is exhausted for a specific IDE, there will be an error. * In such a case, you need to communicate with related people to handle such a case and rearrange option groups accordingly. * * A/B experiment supports the implemented options from JetBrains plugins. * Plugins can be installed/uninstalled or enabled/disabled. * Accordingly, the options defined in plugins may appear when the plugin is enabled or installed, * or disappear when the plugin is disabled or uninstalled. * The experiment uses special storage to be able to work with such conditions correctly. * * @see com.intellij.platform.experiment.ab.impl.option.ABExperimentControlOption * @see com.intellij.platform.experiment.ab.impl.experiment.ABExperimentGroupStorageService */ @Service class ABExperiment { companion object { private val AB_EXPERIMENTAL_OPTION_EP = ExtensionPointName<ABExperimentOption>("com.intellij.experiment.abExperimentOption") private val LOG = logger<ABExperiment>() private const val DEVICE_ID_PURPOSE = "A/B Experiment" private const val DEVICE_ID_SALT = "ab experiment salt" private const val TOTAL_NUMBER_OF_BUCKETS = 1024 internal val TOTAL_NUMBER_OF_GROUPS = if (isPopularIDE()) 16 else 8 internal val OPTION_ID_FREE_GROUP = ABExperimentOptionId("free.option") internal fun getJbABExperimentOptionList(): List<ABExperimentOption> { return AB_EXPERIMENTAL_OPTION_EP.extensionList.filter { val pluginDescriptor = it.getPluginDescriptor() val pluginInfo = getPluginInfoByDescriptor(pluginDescriptor) pluginInfo.isDevelopedByJetBrains() } } internal fun isPopularIDE() = PlatformUtils.isIdeaUltimate() || PlatformUtils.isPyCharmPro() } fun isControlExperimentOptionEnabled(): Boolean { return isExperimentOptionEnabled(ABExperimentControlOption::class.java) } fun isExperimentOptionEnabled(experimentOptionClass: Class<out ABExperimentOption>): Boolean { return experimentOptionClass.isInstance(getUserExperimentOption()) } internal fun getUserExperimentOption(): ABExperimentOption? { val userOptionId = getUserExperimentOptionId() return getJbABExperimentOptionList().find { it.id.value == userOptionId.value } } internal fun getUserExperimentOptionId(): ABExperimentOptionId { val manualOptionIdText = System.getProperty("platform.experiment.ab.manual.option", "") if (manualOptionIdText.isNotBlank()) { LOG.debug { "Use manual option id from Registry. Registry key value is: $manualOptionIdText" } val manualOption = getJbABExperimentOptionList().find { it.id.value == manualOptionIdText } if (manualOption != null) { LOG.debug { "Found manual option is: $manualOption" } return manualOption.id } else if (manualOptionIdText == OPTION_ID_FREE_GROUP.value) { LOG.debug { "Found manual option is: $manualOptionIdText" } return ABExperimentOptionId(manualOptionIdText) } else { LOG.debug { "Manual option with id $manualOptionIdText not found." } return OPTION_ID_FREE_GROUP } } val userGroupNumber = getUserGroupNumber() ?: return OPTION_ID_FREE_GROUP val userOptionId = ABExperimentGroupStorageService.getUserExperimentOptionId(userGroupNumber) LOG.debug { "User option id is: ${userOptionId.value}." } return userOptionId } internal fun getUserGroupNumber(): Int? { val bucket = getUserBucket() if (TOTAL_NUMBER_OF_BUCKETS < TOTAL_NUMBER_OF_GROUPS) { LOG.error("Number of buckets is less than number of groups. " + "Please revise related experiment constants and adjust them accordingly.") return null } val experimentGroup = bucket % TOTAL_NUMBER_OF_GROUPS LOG.debug { "User group number is: $experimentGroup." } return experimentGroup } internal fun getUserBucket(): Int { val deviceId = LOG.runAndLogException { MachineIdManager.getAnonymizedMachineId(DEVICE_ID_PURPOSE, DEVICE_ID_SALT) } val bucketNumber = MathUtil.nonNegativeAbs(deviceId.hashCode()) % TOTAL_NUMBER_OF_BUCKETS LOG.debug { "User bucket number is: $bucketNumber." } return bucketNumber } }
1
null
1
1
f1b733c79fd134e6646f28d1dc99af144c942785
5,824
intellij-community
Apache License 2.0
src/main/java/miyucomics/hexical/prestidigitation/NoteblockEffect.kt
miyucomics
757,094,041
false
{"Kotlin": 328883, "Java": 28621, "GLSL": 1075, "Shell": 45}
package miyucomics.hexical.prestidigitation import miyucomics.hexical.interfaces.PrestidigitationEffect import net.minecraft.block.Blocks import net.minecraft.block.NoteBlock import net.minecraft.entity.Entity import net.minecraft.server.network.ServerPlayerEntity import net.minecraft.util.math.BlockPos import net.minecraft.world.event.GameEvent class NoteblockEffect : PrestidigitationEffect { override fun effectBlock(caster: ServerPlayerEntity, position: BlockPos) { val state = caster.world.getBlockState(position) if (state.block is NoteBlock) { caster.world.addSyncedBlockEvent(position, Blocks.NOTE_BLOCK, 0, 0) caster.world.emitGameEvent(null, GameEvent.NOTE_BLOCK_PLAY, position) } } override fun effectEntity(caster: ServerPlayerEntity, entity: Entity) {} }
0
Kotlin
3
1
be79a0319f88e0cbff2b9afe1f7246b4632e79fe
787
hexical
MIT License
app/src/main/java/com/kuss/krude/shizuku/FileExplorerServiceManager.kt
KusStar
294,712,671
false
{"Kotlin": 434644, "HTML": 47585, "Java": 5923, "Shell": 539, "AIDL": 476}
package com.kuss.krude.shizuku import android.content.ComponentName import android.content.ServiceConnection import android.os.IBinder import com.kuss.krude.BuildConfig import com.kuss.krude.ui.components.internal.files.FileHelper import com.kuss.krude.utils.ActivityHelper import rikka.shizuku.Shizuku import rikka.shizuku.Shizuku.UserServiceArgs import timber.log.Timber object FileExplorerServiceManager { var isBind = false private val USER_SERVICE_ARGS: UserServiceArgs = UserServiceArgs( ComponentName( ActivityHelper.getActivity()?.packageName ?: "com.kuss.krude", FileExplorerService::class.java.name ) ).daemon(false).debuggable(BuildConfig.DEBUG).processNameSuffix("file_explorer_service") .version(1) private val SERVICE_CONNECTION: ServiceConnection = object : ServiceConnection { override fun onServiceConnected(name: ComponentName, service: IBinder) { Timber.d("onServiceConnected: ") isBind = true FileHelper.setIFileExplorerService(IFileExplorerService.Stub.asInterface(service)) } override fun onServiceDisconnected(name: ComponentName) { Timber.d("onServiceDisconnected: ") isBind = false FileHelper.setIFileExplorerService(null) } } fun bindService() { Timber.d("bindService: isBind = $isBind") if (!isBind) { Shizuku.bindUserService(USER_SERVICE_ARGS, SERVICE_CONNECTION) } } }
0
Kotlin
1
22
3576afa9b98eb44913d12dfe87cf0de389e1bcb1
1,519
krude
MIT License
app/src/main/java/dev/mangione/andrea/androidhc12carcontroller/util/Point3d.kt
MangioneAndrea
345,679,178
false
null
package dev.mangione.andrea.androidhc12carcontroller.util class Point3d(var x: Int, var y: Int, var z: Int) { fun set(x: Int, y: Int, z: Int) { this.x = x; this.y = y; this.z = z; } override fun toString(): String { return "X: $x | Y:$y | Z:$z"; } }
0
Kotlin
0
0
f8576d6fd91a2b70ade0d5a8b1a1fe8cdf6341ed
299
AndroidHC12CarController
MIT License
app/src/main/java/com/skapps/YksStudyApp/view/NicknameAdd/AddNickNameViewModel.kt
sahinkaradeniz
539,663,028
false
{"Kotlin": 86204}
package com.skapps.YksStudyApp.view.NicknameAdd import android.annotation.SuppressLint import android.app.Application import android.content.ContentValues import android.content.Context import android.util.Log import android.widget.Toast import androidx.core.content.ContextCompat import androidx.lifecycle.MutableLiveData import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.ktx.auth import com.google.firebase.auth.ktx.userProfileChangeRequest import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase import com.skapps.YksStudyApp.Base.BaseViewModel import com.skapps.YksStudyApp.Model.UserProfile import com.skapps.YksStudyApp.R import com.skapps.YksStudyApp.database.LocalDatabase import com.skapps.YksStudyApp.databinding.FragmentAddNickNameBinding import com.skapps.YksStudyApp.util.succesToast import kotlinx.coroutines.launch import java.lang.Exception class AddNickNameViewModel(application: Application) :BaseViewModel(application) { private var auth: FirebaseAuth = Firebase.auth private val db= Firebase.firestore private var useruid=auth.currentUser?.uid private val localDatabase=LocalDatabase() private val dbFirestore = Firebase.firestore private val nicklist=ArrayList<String>() var clickEnabled=MutableLiveData<Boolean>() var nicknamelist=MutableLiveData<ArrayList<String>>() init { useruid= localDatabase.getSharedPreference(application.applicationContext,"useruid",useruid) getAllNickname() } fun getAllNickname(){ dbFirestore.collection("users").addSnapshotListener { value, error -> Log.e("re","we") if(value !=null){ val documents = value.documents try { for(document in documents){ val nick=document.get("nickname") as String nicknamelist.value?.add(nick) nicklist.add(nick) Log.e("re",nick) } }catch (e:Exception) { Log.e("getallnick",e.toString()) } } } } @SuppressLint("SetTextI18n") fun duplicate(nick:String, binding:FragmentAddNickNameBinding,context: Context){ var cout=0 if (nick.isNotEmpty()){ for (i in nicklist){ if (i==nick){ cout+=1 } } if (cout>0){ clickEnabled.value=false binding.textExplanation.text="Bu kullanıcı adı kullanılmaktadır." binding.textExplanation.setTextColor(ContextCompat.getColor(context,R.color.darkred)) }else{ clickEnabled.value=true binding.textExplanation.text="Kullanılabilir" binding.textExplanation.setTextColor(ContextCompat.getColor(context,R.color.black)) } }else{ clickEnabled.value=false binding.textExplanation.text="Kullanıcı adı boş olamaz" binding.textExplanation.setTextColor(ContextCompat.getColor(context,R.color.darkred)) } } fun profileUpdates(nick: String,context: Context){ launch { val user=Firebase.auth.currentUser val profileUpdates= userProfileChangeRequest { displayName=nick } user!!.updateProfile(profileUpdates).addOnCompleteListener { task -> if (task.isSuccessful){ context.succesToast("Profil oluşturuldu") } } } } }
0
Kotlin
1
3
900a82be997421aa7ff0676805df759538790ebe
3,747
PomodoroApp
MIT License
Live-Page-Counter-Server/src/main/kotlin/com/poc/ktor/plugins/Sockets.kt
gsttarun
552,278,377
false
null
package com.poc.ktor.plugins import MessageType import WSMessage import com.google.gson.Gson import com.poc.ktor.LivePageCount import com.poc.ktor.globalLogger import io.ktor.server.application.* import io.ktor.server.routing.* import io.ktor.server.websocket.* import io.ktor.websocket.* import java.time.Duration fun Application.configureSockets() { install(WebSockets) { pingPeriod = Duration.ofSeconds(15) timeout = Duration.ofSeconds(15) maxFrameSize = Long.MAX_VALUE masking = false } routing { webSocket("/ws") { // websocketSession for (frame in incoming) { if (frame is Frame.Text) { val message = Gson().fromJson(frame.readText(), WSMessage::class.java) // val text = frame.readText() // outgoing.send(Frame.Text("YOU SAID: $text")) when (message.type) { MessageType.PAGE_VISIT -> { LivePageCount.incrementCount() updateCountToClients() } MessageType.PAGE_EXIT -> { LivePageCount.decrementCount() updateCountToClients() } MessageType.BYE -> { close(CloseReason(CloseReason.Codes.NORMAL, "Client said BYE")) globalLogger.info("Client normal closure - Client said BYE") } } } } } } } private suspend fun DefaultWebSocketServerSession.updateCountToClients() { globalLogger.info("Page Count -> ${LivePageCount.getLiveCount()}") outgoing.send(Frame.Text("Count-${LivePageCount.getLiveCount()}")) }
0
Kotlin
0
0
9cb4e7f3dff6fa483df379d1118b7e98bb44a4d2
1,848
Live-Page-Counter-Server-And-Client
The Unlicense
app/src/main/java/com/example/journey/adapter/StoryAdapter.kt
Raideeen
721,742,785
false
{"Kotlin": 10282}
package com.example.journey.adapter import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import coil.load import com.example.journey.R import com.example.journey.model.Story class StoryAdapter( private val context: Context, private val storyList: List<Story> ) : RecyclerView.Adapter<StoryAdapter.StoryViewHolder>() { /* * Adapter for the [RecyclerView] in [MainActivity]. Displays [Story] data object. */ class StoryViewHolder(private val view: View) : RecyclerView.ViewHolder(view) { val storyTitle = view.findViewById<TextView>(R.id.title) val storySubTitle = view.findViewById<TextView>(R.id.subTitle) val storyDescription = view.findViewById<TextView>(R.id.description) val storyImage = view.findViewById<ImageView>(R.id.travelImage) } /* * * Create new view (invoked by the layout manager) ? Note: we inflate `notebook_list_item.xml` here, which is the layout for each item in the list. * */ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StoryViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.notebook_list_item, parent, false) return StoryViewHolder(view) } /* * * Replace the contents of a view (invoked by the layout manager) * */ override fun onBindViewHolder(holder: StoryViewHolder, position: Int) { val story = storyList[position] holder.storyTitle.text = context.resources.getString(story.titleResourceId) holder.storySubTitle.text = context.resources.getString(story.subTitleResourceId) holder.storyDescription.text = context.resources.getString(story.storyDetails) holder.storyImage.load(story.imageResourceId) } /* * * Return the size of your dataset (invoked by the layout manager) * */ override fun getItemCount() = storyList.size }
0
Kotlin
0
1
fdd23f955881effd047718baa42cef5e05ca3f24
2,080
journey-app
MIT License
crowth_app/android/app/src/main/kotlin/com/example/crowth_app/MainActivity.kt
shonorio
413,147,360
false
{"Dart": 30275, "HTML": 3855, "Swift": 404, "Kotlin": 127, "Objective-C": 38}
package com.example.crowth_app import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
88e28713cc0a5294ea846b8dcb51b8b7830840b0
127
flutter_crowth
MIT License
library/src/main/kotlin/ru/dimsuz/vanilla/Bind.kt
dimsuz
284,305,456
false
null
package ru.dimsuz.vanilla import com.github.michaelbull.result.Err import com.github.michaelbull.result.Ok import com.github.michaelbull.result.get import com.github.michaelbull.result.onFailure import ru.dimsuz.vanilla.validator.just /** * Applies multiple validators to the value and then uses [bindFn] function to produce a final result if they * all return success. * * ``` * val v = bind( * Validator { input -> Ok(input + 4) }, * Validator { input -> Ok(input + 9) }, * { a, b -> a + b } * ) * * v.validate(1) // produces Ok(15), i.e (1 + 4) + (1 + 9) * ``` * * If some validators fail then all their errors will be accumulated in the final [Err] list: * * ``` * val v = bind( * Validator { input -> Ok(input + 4) }, * Validator { input -> Err(listOf("v2 failed1", "v2 failed2")) }, * Validator { input -> Err(listOf("v3 failed1")) }, * { a, b -> a + b } * ) * v.validate(1) // produces Err(listOf("v2 failed1", "v2 failed2", "v3 failed")) * ``` */ fun <VI, VE, VO, A, B> Validator.Companion.bind( validatorA: Validator<VI, A, VE>, validatorB: Validator<VI, B, VE>, bindFn: (A, B) -> VO ): Validator<VI, VO, VE> { val unitValidator = Validator.just<VI, Unit, VE>(Unit) return Validator.bindN( validatorA, validatorB, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator ) { a, b, _, _, _, _, _, _, _, _, _, _, _, _ -> bindFn(a, b) } } /** * Applies multiple validators to the value and then uses [bindFn] function to produce a final result if they * all return success. * * ``` * val v = bind( * Validator { input -> Ok(input + 4) }, * Validator { input -> Ok(input + 9) }, * { a, b -> a + b } * ) * * v.validate(1) // produces Ok(15), i.e (1 + 4) + (1 + 9) * ``` * * If some validators fail then all their errors will be accumulated in the final [Err] list: * * ``` * val v = bind( * Validator { input -> Ok(input + 4) }, * Validator { input -> Err(listOf("v2 failed1", "v2 failed2")) }, * Validator { input -> Err(listOf("v3 failed1")) }, * { a, b -> a + b } * ) * v.validate(1) // produces Err(listOf("v2 failed1", "v2 failed2", "v3 failed")) * ``` */ fun <VI, VE, VO, A, B, C> Validator.Companion.bind( validatorA: Validator<VI, A, VE>, validatorB: Validator<VI, B, VE>, validatorC: Validator<VI, C, VE>, bindFn: (A, B, C) -> VO ): Validator<VI, VO, VE> { val unitValidator = Validator.just<VI, Unit, VE>(Unit) return Validator.bindN( validatorA, validatorB, validatorC, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator ) { a, b, c, _, _, _, _, _, _, _, _, _, _, _ -> bindFn(a, b, c) } } /** * Applies multiple validators to the value and then uses [bindFn] function to produce a final result if they * all return success. * * ``` * val v = bind( * Validator { input -> Ok(input + 4) }, * Validator { input -> Ok(input + 9) }, * { a, b -> a + b } * ) * * v.validate(1) // produces Ok(15), i.e (1 + 4) + (1 + 9) * ``` * * If some validators fail then all their errors will be accumulated in the final [Err] list: * * ``` * val v = bind( * Validator { input -> Ok(input + 4) }, * Validator { input -> Err(listOf("v2 failed1", "v2 failed2")) }, * Validator { input -> Err(listOf("v3 failed1")) }, * { a, b -> a + b } * ) * v.validate(1) // produces Err(listOf("v2 failed1", "v2 failed2", "v3 failed")) * ``` */ fun <VI, VE, VO, A, B, C, D> Validator.Companion.bind( validatorA: Validator<VI, A, VE>, validatorB: Validator<VI, B, VE>, validatorC: Validator<VI, C, VE>, validatorD: Validator<VI, D, VE>, bindFn: (A, B, C, D) -> VO ): Validator<VI, VO, VE> { val unitValidator = Validator.just<VI, Unit, VE>(Unit) return Validator.bindN( validatorA, validatorB, validatorC, validatorD, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator ) { a, b, c, d, _, _, _, _, _, _, _, _, _, _ -> bindFn(a, b, c, d) } } /** * Applies multiple validators to the value and then uses [bindFn] function to produce a final result if they * all return success. * * ``` * val v = bind( * Validator { input -> Ok(input + 4) }, * Validator { input -> Ok(input + 9) }, * { a, b -> a + b } * ) * * v.validate(1) // produces Ok(15), i.e (1 + 4) + (1 + 9) * ``` * * If some validators fail then all their errors will be accumulated in the final [Err] list: * * ``` * val v = bind( * Validator { input -> Ok(input + 4) }, * Validator { input -> Err(listOf("v2 failed1", "v2 failed2")) }, * Validator { input -> Err(listOf("v3 failed1")) }, * { a, b -> a + b } * ) * v.validate(1) // produces Err(listOf("v2 failed1", "v2 failed2", "v3 failed")) * ``` */ fun <VI, VE, VO, A, B, C, D, E> Validator.Companion.bind( validatorA: Validator<VI, A, VE>, validatorB: Validator<VI, B, VE>, validatorC: Validator<VI, C, VE>, validatorD: Validator<VI, D, VE>, validatorE: Validator<VI, E, VE>, bindFn: (A, B, C, D, E) -> VO ): Validator<VI, VO, VE> { val unitValidator = Validator.just<VI, Unit, VE>(Unit) return Validator.bindN( validatorA, validatorB, validatorC, validatorD, validatorE, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator ) { a, b, c, d, e, _, _, _, _, _, _, _, _, _ -> bindFn(a, b, c, d, e) } } /** * Applies multiple validators to the value and then uses [bindFn] function to produce a final result if they * all return success. * * ``` * val v = bind( * Validator { input -> Ok(input + 4) }, * Validator { input -> Ok(input + 9) }, * { a, b -> a + b } * ) * * v.validate(1) // produces Ok(15), i.e (1 + 4) + (1 + 9) * ``` * * If some validators fail then all their errors will be accumulated in the final [Err] list: * * ``` * val v = bind( * Validator { input -> Ok(input + 4) }, * Validator { input -> Err(listOf("v2 failed1", "v2 failed2")) }, * Validator { input -> Err(listOf("v3 failed1")) }, * { a, b -> a + b } * ) * v.validate(1) // produces Err(listOf("v2 failed1", "v2 failed2", "v3 failed")) * ``` */ fun <VI, VE, VO, A, B, C, D, E, F> Validator.Companion.bind( validatorA: Validator<VI, A, VE>, validatorB: Validator<VI, B, VE>, validatorC: Validator<VI, C, VE>, validatorD: Validator<VI, D, VE>, validatorE: Validator<VI, E, VE>, validatorF: Validator<VI, F, VE>, bindFn: (A, B, C, D, E, F) -> VO ): Validator<VI, VO, VE> { val unitValidator = Validator.just<VI, Unit, VE>(Unit) return Validator.bindN( validatorA, validatorB, validatorC, validatorD, validatorE, validatorF, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator ) { a, b, c, d, e, f, _, _, _, _, _, _, _, _ -> bindFn(a, b, c, d, e, f) } } /** * Applies multiple validators to the value and then uses [bindFn] function to produce a final result if they * all return success. * * ``` * val v = bind( * Validator { input -> Ok(input + 4) }, * Validator { input -> Ok(input + 9) }, * { a, b -> a + b } * ) * * v.validate(1) // produces Ok(15), i.e (1 + 4) + (1 + 9) * ``` * * If some validators fail then all their errors will be accumulated in the final [Err] list: * * ``` * val v = bind( * Validator { input -> Ok(input + 4) }, * Validator { input -> Err(listOf("v2 failed1", "v2 failed2")) }, * Validator { input -> Err(listOf("v3 failed1")) }, * { a, b -> a + b } * ) * v.validate(1) // produces Err(listOf("v2 failed1", "v2 failed2", "v3 failed")) * ``` */ fun <VI, VE, VO, A, B, C, D, E, F, G> Validator.Companion.bind( validatorA: Validator<VI, A, VE>, validatorB: Validator<VI, B, VE>, validatorC: Validator<VI, C, VE>, validatorD: Validator<VI, D, VE>, validatorE: Validator<VI, E, VE>, validatorF: Validator<VI, F, VE>, validatorG: Validator<VI, G, VE>, bindFn: (A, B, C, D, E, F, G) -> VO ): Validator<VI, VO, VE> { val unitValidator = Validator.just<VI, Unit, VE>(Unit) return Validator.bindN( validatorA, validatorB, validatorC, validatorD, validatorE, validatorF, validatorG, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator ) { a, b, c, d, e, f, g, _, _, _, _, _, _, _ -> bindFn(a, b, c, d, e, f, g) } } /** * Applies multiple validators to the value and then uses [bindFn] function to produce a final result if they * all return success. * * ``` * val v = bind( * Validator { input -> Ok(input + 4) }, * Validator { input -> Ok(input + 9) }, * { a, b -> a + b } * ) * * v.validate(1) // produces Ok(15), i.e (1 + 4) + (1 + 9) * ``` * * If some validators fail then all their errors will be accumulated in the final [Err] list: * * ``` * val v = bind( * Validator { input -> Ok(input + 4) }, * Validator { input -> Err(listOf("v2 failed1", "v2 failed2")) }, * Validator { input -> Err(listOf("v3 failed1")) }, * { a, b -> a + b } * ) * v.validate(1) // produces Err(listOf("v2 failed1", "v2 failed2", "v3 failed")) * ``` */ fun <VI, VE, VO, A, B, C, D, E, F, G, H> Validator.Companion.bind( validatorA: Validator<VI, A, VE>, validatorB: Validator<VI, B, VE>, validatorC: Validator<VI, C, VE>, validatorD: Validator<VI, D, VE>, validatorE: Validator<VI, E, VE>, validatorF: Validator<VI, F, VE>, validatorG: Validator<VI, G, VE>, validatorH: Validator<VI, H, VE>, bindFn: (A, B, C, D, E, F, G, H) -> VO ): Validator<VI, VO, VE> { val unitValidator = Validator.just<VI, Unit, VE>(Unit) return Validator.bindN( validatorA, validatorB, validatorC, validatorD, validatorE, validatorF, validatorG, validatorH, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator ) { a, b, c, d, e, f, g, h, _, _, _, _, _, _ -> bindFn(a, b, c, d, e, f, g, h) } } /** * Applies multiple validators to the value and then uses [bindFn] function to produce a final result if they * all return success. * * ``` * val v = bind( * Validator { input -> Ok(input + 4) }, * Validator { input -> Ok(input + 9) }, * { a, b -> a + b } * ) * * v.validate(1) // produces Ok(15), i.e (1 + 4) + (1 + 9) * ``` * * If some validators fail then all their errors will be accumulated in the final [Err] list: * * ``` * val v = bind( * Validator { input -> Ok(input + 4) }, * Validator { input -> Err(listOf("v2 failed1", "v2 failed2")) }, * Validator { input -> Err(listOf("v3 failed1")) }, * { a, b -> a + b } * ) * v.validate(1) // produces Err(listOf("v2 failed1", "v2 failed2", "v3 failed")) * ``` */ fun <VI, VE, VO, A, B, C, D, E, F, G, H, I> Validator.Companion.bind( validatorA: Validator<VI, A, VE>, validatorB: Validator<VI, B, VE>, validatorC: Validator<VI, C, VE>, validatorD: Validator<VI, D, VE>, validatorE: Validator<VI, E, VE>, validatorF: Validator<VI, F, VE>, validatorG: Validator<VI, G, VE>, validatorH: Validator<VI, H, VE>, validatorI: Validator<VI, I, VE>, bindFn: (A, B, C, D, E, F, G, H, I) -> VO ): Validator<VI, VO, VE> { val unitValidator = Validator.just<VI, Unit, VE>(Unit) return Validator.bindN( validatorA, validatorB, validatorC, validatorD, validatorE, validatorF, validatorG, validatorH, validatorI, unitValidator, unitValidator, unitValidator, unitValidator, unitValidator ) { a, b, c, d, e, f, g, h, i, _, _, _, _, _ -> bindFn(a, b, c, d, e, f, g, h, i) } } /** * Applies multiple validators to the value and then uses [bindFn] function to produce a final result if they * all return success. * * ``` * val v = bind( * Validator { input -> Ok(input + 4) }, * Validator { input -> Ok(input + 9) }, * { a, b -> a + b } * ) * * v.validate(1) // produces Ok(15), i.e (1 + 4) + (1 + 9) * ``` * * If some validators fail then all their errors will be accumulated in the final [Err] list: * * ``` * val v = bind( * Validator { input -> Ok(input + 4) }, * Validator { input -> Err(listOf("v2 failed1", "v2 failed2")) }, * Validator { input -> Err(listOf("v3 failed1")) }, * { a, b -> a + b } * ) * v.validate(1) // produces Err(listOf("v2 failed1", "v2 failed2", "v3 failed")) * ``` */ fun <VI, VE, VO, A, B, C, D, E, F, G, H, I, J> Validator.Companion.bind( validatorA: Validator<VI, A, VE>, validatorB: Validator<VI, B, VE>, validatorC: Validator<VI, C, VE>, validatorD: Validator<VI, D, VE>, validatorE: Validator<VI, E, VE>, validatorF: Validator<VI, F, VE>, validatorG: Validator<VI, G, VE>, validatorH: Validator<VI, H, VE>, validatorI: Validator<VI, I, VE>, validatorJ: Validator<VI, J, VE>, bindFn: (A, B, C, D, E, F, G, H, I, J) -> VO ): Validator<VI, VO, VE> { val unitValidator = Validator.just<VI, Unit, VE>(Unit) return Validator.bindN( validatorA, validatorB, validatorC, validatorD, validatorE, validatorF, validatorG, validatorH, validatorI, validatorJ, unitValidator, unitValidator, unitValidator, unitValidator ) { a, b, c, d, e, f, g, h, i, j, _, _, _, _ -> bindFn(a, b, c, d, e, f, g, h, i, j) } } /** * Applies multiple validators to the value and then uses [bindFn] function to produce a final result if they * all return success. * * ``` * val v = bind( * Validator { input -> Ok(input + 4) }, * Validator { input -> Ok(input + 9) }, * { a, b -> a + b } * ) * * v.validate(1) // produces Ok(15), i.e (1 + 4) + (1 + 9) * ``` * * If some validators fail then all their errors will be accumulated in the final [Err] list: * * ``` * val v = bind( * Validator { input -> Ok(input + 4) }, * Validator { input -> Err(listOf("v2 failed1", "v2 failed2")) }, * Validator { input -> Err(listOf("v3 failed1")) }, * { a, b -> a + b } * ) * v.validate(1) // produces Err(listOf("v2 failed1", "v2 failed2", "v3 failed")) * ``` */ fun <VI, VE, VO, A, B, C, D, E, F, G, H, I, J, K> Validator.Companion.bind( validatorA: Validator<VI, A, VE>, validatorB: Validator<VI, B, VE>, validatorC: Validator<VI, C, VE>, validatorD: Validator<VI, D, VE>, validatorE: Validator<VI, E, VE>, validatorF: Validator<VI, F, VE>, validatorG: Validator<VI, G, VE>, validatorH: Validator<VI, H, VE>, validatorI: Validator<VI, I, VE>, validatorJ: Validator<VI, J, VE>, validatorK: Validator<VI, K, VE>, bindFn: (A, B, C, D, E, F, G, H, I, J, K) -> VO ): Validator<VI, VO, VE> { val unitValidator = Validator.just<VI, Unit, VE>(Unit) return Validator.bindN( validatorA, validatorB, validatorC, validatorD, validatorE, validatorF, validatorG, validatorH, validatorI, validatorJ, validatorK, unitValidator, unitValidator, unitValidator ) { a, b, c, d, e, f, g, h, i, j, k, _, _, _ -> bindFn(a, b, c, d, e, f, g, h, i, j, k) } } /** * Applies multiple validators to the value and then uses [bindFn] function to produce a final result if they * all return success. * * ``` * val v = bind( * Validator { input -> Ok(input + 4) }, * Validator { input -> Ok(input + 9) }, * { a, b -> a + b } * ) * * v.validate(1) // produces Ok(15), i.e (1 + 4) + (1 + 9) * ``` * * If some validators fail then all their errors will be accumulated in the final [Err] list: * * ``` * val v = bind( * Validator { input -> Ok(input + 4) }, * Validator { input -> Err(listOf("v2 failed1", "v2 failed2")) }, * Validator { input -> Err(listOf("v3 failed1")) }, * { a, b -> a + b } * ) * v.validate(1) // produces Err(listOf("v2 failed1", "v2 failed2", "v3 failed")) * ``` */ fun <VI, VE, VO, A, B, C, D, E, F, G, H, I, J, K, L> Validator.Companion.bind( validatorA: Validator<VI, A, VE>, validatorB: Validator<VI, B, VE>, validatorC: Validator<VI, C, VE>, validatorD: Validator<VI, D, VE>, validatorE: Validator<VI, E, VE>, validatorF: Validator<VI, F, VE>, validatorG: Validator<VI, G, VE>, validatorH: Validator<VI, H, VE>, validatorI: Validator<VI, I, VE>, validatorJ: Validator<VI, J, VE>, validatorK: Validator<VI, K, VE>, validatorL: Validator<VI, L, VE>, bindFn: (A, B, C, D, E, F, G, H, I, J, K, L) -> VO ): Validator<VI, VO, VE> { val unitValidator = Validator.just<VI, Unit, VE>(Unit) return Validator.bindN( validatorA, validatorB, validatorC, validatorD, validatorE, validatorF, validatorG, validatorH, validatorI, validatorJ, validatorK, validatorL, unitValidator, unitValidator ) { a, b, c, d, e, f, g, h, i, j, k, l, _, _ -> bindFn(a, b, c, d, e, f, g, h, i, j, k, l) } } /** * Applies multiple validators to the value and then uses [bindFn] function to produce a final result if they * all return success. * * ``` * val v = bind( * Validator { input -> Ok(input + 4) }, * Validator { input -> Ok(input + 9) }, * { a, b -> a + b } * ) * * v.validate(1) // produces Ok(15), i.e (1 + 4) + (1 + 9) * ``` * * If some validators fail then all their errors will be accumulated in the final [Err] list: * * ``` * val v = bind( * Validator { input -> Ok(input + 4) }, * Validator { input -> Err(listOf("v2 failed1", "v2 failed2")) }, * Validator { input -> Err(listOf("v3 failed1")) }, * { a, b -> a + b } * ) * v.validate(1) // produces Err(listOf("v2 failed1", "v2 failed2", "v3 failed")) * ``` */ fun <VI, VE, VO, A, B, C, D, E, F, G, H, I, J, K, L, M> Validator.Companion.bind( validatorA: Validator<VI, A, VE>, validatorB: Validator<VI, B, VE>, validatorC: Validator<VI, C, VE>, validatorD: Validator<VI, D, VE>, validatorE: Validator<VI, E, VE>, validatorF: Validator<VI, F, VE>, validatorG: Validator<VI, G, VE>, validatorH: Validator<VI, H, VE>, validatorI: Validator<VI, I, VE>, validatorJ: Validator<VI, J, VE>, validatorK: Validator<VI, K, VE>, validatorL: Validator<VI, L, VE>, validatorM: Validator<VI, M, VE>, bindFn: (A, B, C, D, E, F, G, H, I, J, K, L, M) -> VO ): Validator<VI, VO, VE> { val unitValidator = Validator.just<VI, Unit, VE>(Unit) return Validator.bindN( validatorA, validatorB, validatorC, validatorD, validatorE, validatorF, validatorG, validatorH, validatorI, validatorJ, validatorK, validatorL, validatorM, unitValidator ) { a, b, c, d, e, f, g, h, i, j, k, l, m, _ -> bindFn(a, b, c, d, e, f, g, h, i, j, k, l, m) } } /** * Applies multiple validators to the value and then uses [bindFn] function to produce a final result if they * all return success. * * ``` * val v = bind( * Validator { input -> Ok(input + 4) }, * Validator { input -> Ok(input + 9) }, * { a, b -> a + b } * ) * * v.validate(1) // produces Ok(15), i.e (1 + 4) + (1 + 9) * ``` * * If some validators fail then all their errors will be accumulated in the final [Err] list: * * ``` * val v = bind( * Validator { input -> Ok(input + 4) }, * Validator { input -> Err(listOf("v2 failed1", "v2 failed2")) }, * Validator { input -> Err(listOf("v3 failed1")) }, * { a, b -> a + b } * ) * v.validate(1) // produces Err(listOf("v2 failed1", "v2 failed2", "v3 failed")) * ``` */ fun <VI, VE, VO, A, B, C, D, E, F, G, H, I, J, K, L, M, N> Validator.Companion.bind( validatorA: Validator<VI, A, VE>, validatorB: Validator<VI, B, VE>, validatorC: Validator<VI, C, VE>, validatorD: Validator<VI, D, VE>, validatorE: Validator<VI, E, VE>, validatorF: Validator<VI, F, VE>, validatorG: Validator<VI, G, VE>, validatorH: Validator<VI, H, VE>, validatorI: Validator<VI, I, VE>, validatorJ: Validator<VI, J, VE>, validatorK: Validator<VI, K, VE>, validatorL: Validator<VI, L, VE>, validatorM: Validator<VI, M, VE>, validatorN: Validator<VI, N, VE>, bindFn: (A, B, C, D, E, F, G, H, I, J, K, L, M, N) -> VO ): Validator<VI, VO, VE> { return Validator.bindN( validatorA, validatorB, validatorC, validatorD, validatorE, validatorF, validatorG, validatorH, validatorI, validatorJ, validatorK, validatorL, validatorM, validatorN, bindFn ) } private fun <VI, VE, VO, A, B, C, D, E, F, G, H, I, J, K, L, M, N> Validator.Companion.bindN( validatorA: Validator<VI, A, VE>, validatorB: Validator<VI, B, VE>, validatorC: Validator<VI, C, VE>, validatorD: Validator<VI, D, VE>, validatorE: Validator<VI, E, VE>, validatorF: Validator<VI, F, VE>, validatorG: Validator<VI, G, VE>, validatorH: Validator<VI, H, VE>, validatorI: Validator<VI, I, VE>, validatorJ: Validator<VI, J, VE>, validatorK: Validator<VI, K, VE>, validatorL: Validator<VI, L, VE>, validatorM: Validator<VI, M, VE>, validatorN: Validator<VI, N, VE>, bindFn: (A, B, C, D, E, F, G, H, I, J, K, L, M, N) -> VO ): Validator<VI, VO, VE> { return Validator { input -> val errors = mutableListOf<VE>() val a = validatorA.validate(input).onFailure { errors.addAll(it) }.get() val b = validatorB.validate(input).onFailure { errors.addAll(it) }.get() val c = validatorC.validate(input).onFailure { errors.addAll(it) }.get() val d = validatorD.validate(input).onFailure { errors.addAll(it) }.get() val e = validatorE.validate(input).onFailure { errors.addAll(it) }.get() val f = validatorF.validate(input).onFailure { errors.addAll(it) }.get() val g = validatorG.validate(input).onFailure { errors.addAll(it) }.get() val h = validatorH.validate(input).onFailure { errors.addAll(it) }.get() val i = validatorI.validate(input).onFailure { errors.addAll(it) }.get() val j = validatorJ.validate(input).onFailure { errors.addAll(it) }.get() val k = validatorK.validate(input).onFailure { errors.addAll(it) }.get() val l = validatorL.validate(input).onFailure { errors.addAll(it) }.get() val m = validatorM.validate(input).onFailure { errors.addAll(it) }.get() val n = validatorN.validate(input).onFailure { errors.addAll(it) }.get() if (errors.isEmpty()) { Ok(bindFn(a!!, b!!, c!!, d!!, e!!, f!!, g!!, h!!, i!!, j!!, k!!, l!!, m!!, n!!)) } else { Err(errors) } } }
3
Kotlin
0
31
ea42f6fb6c8b40b0e8ed94cf45958c4ac4de59f9
22,850
vanilla
MIT License
src/main/kotlin/no/nav/personbruker/dittnav/eventaggregator/done/DoneEventService.kt
navikt
189,239,389
false
null
package no.nav.personbruker.dittnav.eventaggregator.done import no.nav.brukernotifikasjon.schemas.Done import no.nav.brukernotifikasjon.schemas.Nokkel import no.nav.brukernotifikasjon.schemas.builders.exception.FieldValidationException import no.nav.personbruker.dittnav.eventaggregator.common.EventBatchProcessorService import no.nav.personbruker.dittnav.eventaggregator.common.database.ListPersistActionResult import no.nav.personbruker.dittnav.eventaggregator.common.exceptions.NokkelNullException import no.nav.personbruker.dittnav.eventaggregator.common.exceptions.UntransformableRecordException import no.nav.personbruker.dittnav.eventaggregator.common.kafka.serializer.getNonNullKey import no.nav.personbruker.dittnav.eventaggregator.config.EventType.DONE import no.nav.personbruker.dittnav.eventaggregator.metrics.EventMetricsProbe import no.nav.personbruker.dittnav.eventaggregator.metrics.EventMetricsSession import org.apache.kafka.clients.consumer.ConsumerRecord import org.apache.kafka.clients.consumer.ConsumerRecords import org.slf4j.Logger import org.slf4j.LoggerFactory class DoneEventService( private val donePersistingService: DonePersistingService, private val eventMetricsProbe: EventMetricsProbe ) : EventBatchProcessorService<Done> { private val log: Logger = LoggerFactory.getLogger(DoneEventService::class.java) override suspend fun processEvents(events: ConsumerRecords<Nokkel, Done>) { val successfullyTransformedEvents = mutableListOf<no.nav.personbruker.dittnav.eventaggregator.done.Done>() val problematicEvents = mutableListOf<ConsumerRecord<Nokkel, Done>>() eventMetricsProbe.runWithMetrics(eventType = DONE) { events.forEach { event -> try { val internalEventKey = event.getNonNullKey() val internalEventValue = DoneTransformer.toInternal(internalEventKey, event.value()) successfullyTransformedEvents.add(internalEventValue) countSuccessfulEventForProducer(internalEventKey.getSystembruker()) } catch (e: NokkelNullException) { countFailedEventForProducer("NoProducerSpecified") log.warn("Eventet manglet nøkkel. Topic: ${event.topic()}, Partition: ${event.partition()}, Offset: ${event.offset()}", e) } catch (fve: FieldValidationException) { countFailedEventForProducer(event.systembruker ?: "NoProducerSpecified") val msg = "Eventet kan ikke brukes fordi det inneholder valideringsfeil, eventet vil bli forkastet. EventId: ${event.eventId}, systembruker: ${event.systembruker}, $fve" log.warn(msg, fve) } catch (cce: ClassCastException) { countFailedEventForProducer(event.systembruker ?: "NoProducerSpecified") val funnetType = event.javaClass.name val eventId = event.eventId val systembruker = event.systembruker log.warn("Feil eventtype funnet på done-topic. Fant et event av typen $funnetType. Eventet blir forkastet. EventId: $eventId, systembruker: $systembruker, $cce", cce) } catch (e: Exception) { countFailedEventForProducer(event.systembruker ?: "NoProducerSpecified") problematicEvents.add(event) log.warn("Transformasjon av done-event fra Kafka feilet.", e) } } val groupedDoneEvents = groupDoneEventsByAssociatedEventType(successfullyTransformedEvents) donePersistingService.writeDoneEventsForBeskjedToCache(groupedDoneEvents.foundBeskjed) donePersistingService.writeDoneEventsForOppgaveToCache(groupedDoneEvents.foundOppgave) donePersistingService.writeDoneEventsForInnboksToCache(groupedDoneEvents.foundInnboks) val writeEventsToCacheResult = donePersistingService.writeEventsToCache(groupedDoneEvents.notFoundEvents) countDuplicateKeyEvents(writeEventsToCacheResult) } kastExceptionHvisMislykkedeTransformasjoner(problematicEvents) } private suspend fun groupDoneEventsByAssociatedEventType(successfullyTransformedEvents: List<no.nav.personbruker.dittnav.eventaggregator.done.Done>): DoneBatchProcessor { val eventIds = successfullyTransformedEvents.map { it.eventId }.distinct() val aktiveBrukernotifikasjoner = donePersistingService.fetchBrukernotifikasjonerFromViewForEventIds(eventIds) val batch = DoneBatchProcessor(aktiveBrukernotifikasjoner) batch.process(successfullyTransformedEvents) return batch } private fun EventMetricsSession.countDuplicateKeyEvents(result: ListPersistActionResult<no.nav.personbruker.dittnav.eventaggregator.done.Done>) { if (result.foundConflictingKeys()) { val constraintErrors = result.getConflictingEntities().size val totalEntities = result.getAllEntities().size result.getConflictingEntities() .groupingBy { done -> done.systembruker } .eachCount() .forEach { (systembruker, duplicates) -> countDuplicateEventKeysByProducer(systembruker, duplicates) } val msg = """Traff $constraintErrors feil på duplikate eventId-er ved behandling av $totalEntities done-eventer. | Feilene ble produsert av: ${getNumberDuplicateKeysByProducer()}""".trimMargin() logAsWarningForAllProducersExceptForFpinfoHistorikk(msg) } } private fun kastExceptionHvisMislykkedeTransformasjoner(problematicEvents: MutableList<ConsumerRecord<Nokkel, Done>>) { if (problematicEvents.isNotEmpty()) { val message = "En eller flere eventer kunne ikke transformeres" val exception = UntransformableRecordException(message) exception.addContext("antallMislykkedeTransformasjoner", problematicEvents.size) throw exception } } }
0
Kotlin
0
1
4c88ee694a12250707423a2ef80d09efb81ba724
6,133
dittnav-event-aggregator
MIT License
indexer-core/src/main/kotlin/io/github/saneea/fileindexer/core/filewatcher/DirWatcher.kt
saneea
355,091,573
false
null
package io.github.saneea.fileindexer.core.filewatcher import io.github.saneea.fileindexer.core.common.FSEventKind import io.github.saneea.fileindexer.core.common.FSEventKind.* import io.github.saneea.fileindexer.core.utils.UsageRegistry import java.nio.file.* class DirWatcher(val listener: (FSEventKind, Path) -> Unit) : AutoCloseable { data class Registration( private val watchKeyRegistry: UsageRegistry<WatchKey>, private val watchKey: WatchKey ) { init { watchKeyRegistry.inUse(watchKey) } fun cancel() = watchKeyRegistry.free(watchKey, WatchKey::cancel) } private val watchService = FileSystems.getDefault().newWatchService() private val backgroundThread = Thread(this::handleWatchKeys, "FSWatcher") private val watchKeyRegistry = UsageRegistry<WatchKey>() init { backgroundThread.isDaemon = true backgroundThread.start() } fun register(dirPath: Path) = Registration( watchKeyRegistry, dirPath.register( watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY ) ) private fun handleWatchKeys() { try { while (true) { val watchKey = watchService.take() if (watchKey != null) { handleWatchEvents(watchKey) } watchKey.reset() } } catch (e: InterruptedException) { //it is normal ending of background thread } } private fun handleWatchEvents(watchKey: WatchKey) { val parentDirPath = watchKey.watchable() if (parentDirPath is Path) { for (watchEvent in watchKey.pollEvents()) { val childPath = watchEvent.context() if (childPath is Path) { val eventKind = watchEvent.kind().toDirWatcherEventKind() val resolvedFilePath = parentDirPath.resolve(childPath) try { listener(eventKind, resolvedFilePath) } catch (e: Exception) { //TODO log this exception e.printStackTrace() } } } } } override fun close() { backgroundThread.interrupt() backgroundThread.join() watchService.close() } } private fun <T> WatchEvent.Kind<T>.toDirWatcherEventKind() = when (this) { StandardWatchEventKinds.ENTRY_CREATE -> CREATE StandardWatchEventKinds.ENTRY_DELETE -> DELETE StandardWatchEventKinds.ENTRY_MODIFY -> MODIFY else -> throw IllegalArgumentException("Unknown WatchEvent.Kind: $this") }
0
Kotlin
0
0
942996dea4fbe17cbc00b6483be8c35b503485f9
2,878
file-indexer
MIT License
src/main/java/dev/tang/tool/XlsFileReader.kt
tangbomao
215,714,503
false
{"Kotlin": 19661}
package dev.tang.tool import dev.tang.tool.export.DataExport import dev.tang.tool.logger.Logger import jxl.Cell import jxl.Workbook import jxl.WorkbookSettings import java.io.File import java.io.IOException import java.util.* /** * Excel文件处理器 * * @param outputDir 输出文件夹名称 * @param clientHidden 支持客户端隐藏数据,默认false * * @author TangYing */ class XlsFileReader(private val filePath: String, private val outputDir: String, private val clientHidden: Boolean = false) { companion object { private val LOG = Logger(XlsFileReader::class.java) } /** * 数据类型 */ private val typeMap = LinkedHashMap<String, String>() /** * 注释 */ private val commentMap = LinkedHashMap<String, String>() /** * 数据 */ private val datas = LinkedList<Map<String, Any>>() /** * 导出文件 */ fun read() { var errorRow = 0 var errorCell = 0 val fileName = filePath.substring(0, filePath.lastIndexOf(".")) val file = File("$fileName.xls") val workbookSettings = WorkbookSettings() workbookSettings.encoding = "ISO-8859-1" val wwb: Workbook try { // 获取内容 wwb = Workbook.getWorkbook(file, workbookSettings) // 获取分页第一页 val sheet = wwb.getSheet(0) // =========================== // Start to generate // =========================== // Get first row cells val firstRows = sheet.getRow(0) // Get all comments for (j in firstRows.indices) { errorCell = j val cell = firstRows[j] if (cell != null) { val key = firstRows[j].contents val comment = "" commentMap[key] = comment } } // Get second row cells val secondRows = sheet.getRow(1) errorRow = 1 for (j in secondRows.indices) { errorCell = j val cell = secondRows[j] if (cell != null) { val key = firstRows[j].contents val type = cell.contents typeMap[key] = type } } // Get all data val totalRowNum = sheet.rows // For each cell, except first and second row for (i in 2 until totalRowNum) { // Row map data val map = LinkedHashMap<String, Any>() // Get row val rowCells = sheet.getRow(i) for (j in firstRows.indices) { errorRow = i errorCell = j val key = firstRows[j].contents val cell = if (rowCells.size > j) rowCells[j] else null // Default object value var obj: Any? = "" // Check cell null if (cell != null && cell.contents != "") { obj = handleStringCell(key, cell) } else { obj = handleBlankCell(key) } if (obj != null) { // value map map[key] = obj } } // Add data map datas.add(map) } // JSON val dataExport = DataExport(fileName, datas, outputDir) dataExport.export() wwb.close() } catch (ioe: IOException) { LOG.error("{0}, 第{1}行, 第{2}列, IOException. {3}", fileName, errorRow + 1, errorCell + 1, ioe.toString()) } catch (e: Exception) { e.printStackTrace() LOG.error("{0}, 第{1}行, 第{2}列, Exception. {3}", fileName, errorRow + 1, errorCell + 1, e.toString()) } } /** * 空数据处理,填补有效默认数据 * * @return */ private fun handleBlankCell(key: String): Any? { val typeCellContent = typeMap[key]?.toLowerCase() ?: "" // 隐藏数据 val typeHidden = typeCellContent.contains("hidden") if (clientHidden && typeHidden) { return null } // 获取数据类型 val type = typeCellContent.split("\\|".toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()[0] return when (type) { "int[]" -> intArrayOf() "double[]" -> doubleArrayOf() "string[]" -> arrayOf<String>() "boolean[]" -> arrayOf<Boolean>() "int" -> 0 "double" -> 0.0 "boolean" -> false "string" -> "" "empty" -> null else -> null } } /** * 正常数据数据,根据数据类型转化数据 * * @param cell * @return */ private fun handleStringCell(key: String, cell: Cell): Any? { val typeCellContent = typeMap[key]?.toLowerCase() ?: "" // 隐藏部分数据 val typeHidden = typeCellContent.contains("hidden") if (clientHidden && typeHidden) { return null } // 获取原始数据 val str = cell.contents // 获取数据类型 val type = typeCellContent.split("\\|".toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()[0] return when (type) { "int[]" -> str.split("\\|").map { it.toInt() } "double[]" -> str.split("\\|").map { it.toDouble() } "string[]" -> str.split("\\|") "boolean[]" -> str.split("\\|").map { it.toBoolean() } "int" -> str.toInt() "double" -> str.toDouble() "boolean" -> str.toBoolean() "string" -> str "empty" -> null else -> null } } }
1
Kotlin
0
2
bc611b8255d662d561d1b2808eb1daa20dce885f
5,801
excel2json
Apache License 2.0
src/main/kotlin/org/cikit/modules/hotspot/HotspotCollector.kt
b8b
111,886,239
false
null
package org.cikit.modules.hotspot import io.prometheus.client.CollectorRegistry import io.prometheus.client.hotspot.DefaultExports import org.cikit.core.Collector import org.cikit.core.MetricType import org.cikit.core.MetricValue import org.cikit.core.MetricWriter class HotspotCollector(val labels: Map<String, String>) : Collector { override val instance: String get() = "local" init { DefaultExports.initialize() } override suspend fun export(writer: MetricWriter) { val samples = CollectorRegistry.defaultRegistry.metricFamilySamples() val metricValues = samples.asSequence().flatMap { metric -> metric.samples.asSequence().map { sample -> MetricValue( metric.name, sample.value, when (metric.type) { io.prometheus.client.Collector.Type.COUNTER -> MetricType.Counter io.prometheus.client.Collector.Type.GAUGE -> MetricType.Gauge io.prometheus.client.Collector.Type.HISTOGRAM -> MetricType.Histogram io.prometheus.client.Collector.Type.SUMMARY -> MetricType.Summary else -> MetricType.Gauge }, metric.help, fields = labels.map { (k, v) -> k to v } + sample.labelNames .mapIndexed { i, k -> k to sample.labelValues[i] }) } }.toList() metricValues.forEach { writer.metricValue(it) } } }
1
Kotlin
0
1
29f967ae0a13b14653cc28a707aae1fdb355216d
1,637
universal_exporter
Apache License 2.0
IdentityVerification/IdentityVerificationKotlinExample/app/src/main/java/com/transmitsecurity/idvsdkdemoapp/fragments/RequiredCameraPermissionsFragment.kt
TransmitSecurity
665,969,421
false
null
package com.transmitsecurity.idvsdkdemoapp.fragments import android.graphics.Typeface import androidx.core.app.ActivityCompat import com.transmitsecurity.idvsdkdemoapp.R class RequiredCameraPermissionsFragment: FirstFragment() { private val CAMERACODE = 100; override val title: String get() = getString(R.string.camera_permissions_title) override val visibleBtn: Boolean get() = true override val subtitle: String get() = getString(R.string.camera_permissions_sub_title) override val btnTxt: String get() = getString(R.string.camera_permissions_btn) override val titleWeight: Typeface get() = Typeface.create(Typeface.DEFAULT, Typeface.BOLD) override val subTitleWeight: Typeface get() = Typeface.create(Typeface.DEFAULT, Typeface.NORMAL) override val drawing: Int get() = R.drawable.camera_permissions override val visibleDrawing: Boolean get() = true override val visibleProgressBar: Boolean get() = false override fun myClickListener() { ActivityCompat.requestPermissions( requireActivity(),arrayOf(android.Manifest.permission.CAMERA), CAMERACODE) } }
0
Kotlin
0
0
fb4ad7d3978b3c91ec2a05fbe8211b2829fc9f38
1,191
transmit-android-samples
MIT License
android/app/src/main/java/com/converse/dev/PushNotificationsService.kt
ephemeraHQ
573,386,822
false
{"TypeScript": 1199056, "Kotlin": 78440, "Swift": 66779, "JavaScript": 28731, "Ruby": 4019, "Objective-C++": 2703, "Shell": 401, "Objective-C": 327, "CSS": 34}
package com.converse.dev import android.Manifest import android.app.ActivityManager import android.content.ComponentName import android.content.Intent import android.content.pm.PackageManager import android.graphics.Bitmap import android.net.Uri import android.os.Build import android.os.Parcelable import android.util.Log import androidx.annotation.RequiresApi import androidx.core.app.ActivityCompat import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.app.Person import androidx.core.content.pm.ShortcutInfoCompat import androidx.core.content.pm.ShortcutManagerCompat import androidx.core.graphics.drawable.IconCompat import com.beust.klaxon.Klaxon import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import com.converse.dev.xmtp.NotificationDataResult import com.converse.dev.xmtp.getNewConversationFromEnvelope import com.converse.dev.xmtp.getNewGroup import com.converse.dev.xmtp.getXmtpClient import com.converse.dev.xmtp.handleGroupMessage import com.converse.dev.xmtp.handleGroupWelcome import com.converse.dev.xmtp.handleNewConversationFirstMessage import com.converse.dev.xmtp.handleOngoingConversationMessage import com.converse.dev.xmtp.initCodecs import com.facebook.react.bridge.ReactApplicationContext import com.google.crypto.tink.subtle.Base64 import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage import com.reactnativecommunity.asyncstorage.AsyncStorageModule import expo.modules.core.ModuleRegistry import expo.modules.core.interfaces.InternalModule import expo.modules.core.interfaces.SingletonModule import expo.modules.kotlin.AppContext import expo.modules.kotlin.ModulesProvider import expo.modules.kotlin.modules.Module import expo.modules.notifications.notifications.JSONNotificationContentBuilder import expo.modules.notifications.notifications.model.Notification import expo.modules.notifications.notifications.model.NotificationAction import expo.modules.notifications.notifications.model.NotificationContent import expo.modules.notifications.notifications.model.NotificationRequest import expo.modules.notifications.notifications.model.NotificationResponse import expo.modules.notifications.notifications.model.triggers.FirebaseNotificationTrigger import expo.modules.notifications.notifications.presentation.builders.CategoryAwareNotificationBuilder import expo.modules.notifications.notifications.presentation.builders.ExpoNotificationBuilder import expo.modules.notifications.service.NotificationsService.Companion.EVENT_TYPE_KEY import expo.modules.notifications.service.NotificationsService.Companion.NOTIFICATION_ACTION_KEY import expo.modules.notifications.service.NotificationsService.Companion.NOTIFICATION_EVENT_ACTION import expo.modules.notifications.service.NotificationsService.Companion.NOTIFICATION_KEY import expo.modules.notifications.service.NotificationsService.Companion.findDesignatedBroadcastReceiver import expo.modules.notifications.service.delegates.SharedPreferencesNotificationCategoriesStore import expo.modules.securestore.AuthenticationHelper import expo.modules.securestore.SecureStoreModule import expo.modules.securestore.encryptors.AESEncryptor import expo.modules.securestore.encryptors.HybridAESEncryptor import kotlinx.coroutines.* import org.json.JSONObject import org.xmtp.android.library.messages.EnvelopeBuilder import java.lang.ref.WeakReference import java.security.KeyStore import java.util.* import kotlin.reflect.full.declaredMemberProperties import kotlin.reflect.jvm.isAccessible import kotlin.reflect.jvm.javaField class PushNotificationsService : FirebaseMessagingService() { companion object { const val TAG = "PushNotificationsService" lateinit var secureStoreModule: SecureStoreModule lateinit var asyncStorageModule: AsyncStorageModule lateinit var reactAppContext: ReactApplicationContext } override fun onCreate() { super.onCreate() initSecureStore() initAsyncStorage() initSentry(this) } // Define a CoroutineScope for the service private val serviceJob = SupervisorJob() private val serviceScope = CoroutineScope(Dispatchers.IO + serviceJob) override fun onMessageReceived(remoteMessage: RemoteMessage) { Log.d(TAG, "Received a notification") // Check if message contains a data payload. if (remoteMessage.data.isEmpty()) return val envelopeJSON = remoteMessage.data["body"] ?: return Log.d(TAG, "Message data payload: $envelopeJSON") val notificationData = Klaxon().parse<NotificationData>(envelopeJSON) ?: return Log.d(TAG, "Decoded notification data: account is ${notificationData.account} - topic is ${notificationData.contentTopic}") initCodecs() // Equivalent to initSentry() val accounts = getAccounts(this) if (!accounts.contains(notificationData.account)) { Log.d(TAG, "Account ${notificationData.account} is not in store") return } Log.d(TAG, "INSTANTIATED XMTP CLIENT FOR ${notificationData.contentTopic}") val encryptedMessageData = Base64.decode(notificationData.message, Base64.NO_WRAP) val envelope = EnvelopeBuilder.buildFromString(notificationData.contentTopic, Date(notificationData.timestampNs.toLong() / 1000000), encryptedMessageData) var shouldShowNotification = false var result = NotificationDataResult() var context = this // Using IO dispatcher for background work, not blocking the main thread and UI serviceScope.launch { try { val xmtpClient = getXmtpClient(context, notificationData.account) ?: run { Log.d(TAG, "NO XMTP CLIENT FOUND FOR TOPIC ${notificationData.contentTopic}") return@launch } if (isInviteTopic(notificationData.contentTopic)) { Log.d(TAG, "Handling a new conversation notification") val conversation = getNewConversationFromEnvelope(applicationContext, xmtpClient, envelope) if (conversation != null) { result = handleNewConversationFirstMessage( applicationContext, xmtpClient, conversation, remoteMessage ) if (result != NotificationDataResult()) { shouldShowNotification = result.shouldShowNotification } // Replace invite-topic with the topic in the notification content val newNotificationData = NotificationData( notificationData.message, notificationData.timestampNs, conversation.topic, notificationData.account, ) val newNotificationDataJson = Klaxon().toJsonString(newNotificationData) remoteMessage.data["body"] = newNotificationDataJson } } else if (isGroupWelcomeTopic(notificationData.contentTopic)) { val group = getNewGroup(xmtpClient, notificationData.contentTopic) if (group != null) { result = handleGroupWelcome(applicationContext, xmtpClient, group, remoteMessage) if (result != NotificationDataResult()) { shouldShowNotification = result.shouldShowNotification } } } else if (isGroupMessageTopic(notificationData.contentTopic)) { Log.d(TAG, "Handling an ongoing group message notification") result = handleGroupMessage(applicationContext, xmtpClient, envelope, remoteMessage) if (result != NotificationDataResult()) { shouldShowNotification = result.shouldShowNotification } } else { Log.d(TAG, "Handling an ongoing conversation message notification") result = handleOngoingConversationMessage(applicationContext, xmtpClient, envelope, remoteMessage) if (result != NotificationDataResult()) { shouldShowNotification = result.shouldShowNotification } } val notificationAlreadyShown = notificationAlreadyShown(applicationContext, result.messageId) if (shouldShowNotification && !notificationAlreadyShown) { incrementBadge(applicationContext) result.remoteMessage?.let { showNotification(result, it) } } } catch (e: Exception) { // Handle any exceptions Log.e(TAG, "Error on IO Dispatcher coroutine", e) } } } private fun getNotificationIdentifier(remoteMessage: RemoteMessage): String { return remoteMessage.data?.get("tag") ?: remoteMessage.messageId ?: UUID.randomUUID().toString() } private fun createNotificationRequest( identifier: String, content: NotificationContent, notificationTrigger: FirebaseNotificationTrigger ): NotificationRequest { return NotificationRequest(identifier, content, notificationTrigger) } private fun createNotificationFromRemoteMessage(title: String, subtitle:String?, message: String, remoteMessage: RemoteMessage): Notification { val identifier = getNotificationIdentifier(remoteMessage) var data = remoteMessage.data as MutableMap<Any, Any> data["title"] = title if (subtitle !== null) { data["subtitle"] = subtitle } data["message"] = message Log.d(TAG, "SHOWING NOTIFICATION WITH DATA $data") val payload = JSONObject(data as Map<*, *>) val content = JSONNotificationContentBuilder(this).setPayload(payload).build() val request = createNotificationRequest(identifier, content, FirebaseNotificationTrigger(remoteMessage)) return Notification(request, Date(remoteMessage.sentTime)) } private suspend fun showNotification(result: NotificationDataResult, remoteMessage: RemoteMessage) { val context = this // Hooking into Expo's android notification system to get the native NotificationCompat builder and customize it // while still enablig Expo's React Native notification interaction handling val expoNotification = createNotificationFromRemoteMessage(result.title, result.subtitle, result.body, remoteMessage); val expoBuilder = CategoryAwareNotificationBuilder(this, SharedPreferencesNotificationCategoriesStore(this)).also { it.setNotification(expoNotification) } as ExpoNotificationBuilder if (ActivityCompat.checkSelfPermission( this, Manifest.permission.POST_NOTIFICATIONS ) != PackageManager.PERMISSION_GRANTED ) { return } val createBuilder = ExpoNotificationBuilder::class.java.getDeclaredMethod("createBuilder") createBuilder.isAccessible = true val builder = createBuilder.invoke(expoBuilder) as NotificationCompat.Builder customizeMessageNotification(this, builder, expoNotification, result) NotificationManagerCompat.from(this).notify( expoNotification.notificationRequest.identifier, 0, builder.build() ) } private fun initSecureStore() { // Basically hooking inside React / Expo modules internals // to access the Expo SecureStore module from Kotlin val internalModules: Collection<InternalModule> = listOf() val singletonModules: Collection<SingletonModule> = listOf() val moduleRegistry = ModuleRegistry(internalModules, singletonModules) reactAppContext = ReactApplicationContext(this) val weakRef = WeakReference(reactAppContext) val appContext = AppContext(object : ModulesProvider { override fun getModulesList() = listOf( SecureStoreModule::class.java, ) }, moduleRegistry, weakRef) secureStoreModule = SecureStoreModule() val appC = Module::class.declaredMemberProperties.find { it.name == "_appContext" } appC?.isAccessible = true appC?.javaField?.set(secureStoreModule, appContext) val authenticationHelper = SecureStoreModule::class.declaredMemberProperties.find { it.name == "authenticationHelper" } val hybridAESEncryptor = SecureStoreModule::class.declaredMemberProperties.find { it.name == "hybridAESEncryptor" } val keyStore = SecureStoreModule::class.declaredMemberProperties.find { it.name == "keyStore" } authenticationHelper?.isAccessible = true; hybridAESEncryptor?.isAccessible = true; keyStore?.isAccessible = true; authenticationHelper?.javaField?.set(secureStoreModule, AuthenticationHelper(reactAppContext, appContext.legacyModuleRegistry)) hybridAESEncryptor?.javaField?.set(secureStoreModule, HybridAESEncryptor(reactAppContext, AESEncryptor())) val ks = KeyStore.getInstance("AndroidKeyStore") ks.load(null) keyStore?.javaField?.set(secureStoreModule, ks) } private fun initAsyncStorage() { val reactContext = ReactApplicationContext(this) asyncStorageModule = AsyncStorageModule(reactContext) } override fun onDestroy() { super.onDestroy() // Cancel the serviceScope when the service is destroyed serviceScope.cancel() } }
102
TypeScript
3
34
e3600a048ec7391cba1f1a511ff0849070d5ac72
13,985
converse-app
MIT License
notion-toggler-core/src/main/kotlin/io/yahorbarkouski/notion/toggler/core/FeatureFlag.kt
yahorbarkouski
576,698,464
false
null
package io.yahorbarkouski.notion.toggler.core import io.yahorbarkouski.notion.toggler.core.annotation.Documented import io.yahorbarkouski.notion.toggler.core.util.camelToWords import kotlin.reflect.full.memberProperties import kotlin.reflect.jvm.javaField /** * Base open class for feature flags, * that represents a feature flag with a name, an enabled state, and an optional description. */ open class FeatureFlag( open var name: String = "", @Documented open var description: String? = "", open var created: String? = "" ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is FeatureFlag) return false if (name != other.name) return false if (created != other.created) return false if (description != other.description) return false return true } override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + (created?.hashCode() ?: 0) result = 31 * result + (description?.hashCode() ?: 0) return result } override fun toString(): String { return "FeatureFlag(name='$name', description=$description, created=$created)" } fun achieveDocumentedFields(): Map<String, String> { return this::class.memberProperties .associate { it.name.camelToWords() to it.getter.call(this) as String } .filterKeys { this::class.memberProperties .find { field -> field.name.camelToWords() == it }!!.javaField!! .annotations .any { it is Documented } } } }
4
Kotlin
0
2
5d77a4dfd9725069f14b89dd5a09ed2f864ecf0a
1,665
notion-toggler
Apache License 2.0
app/src/main/java/com/khanappsnj/procoreinterviewapp/CardAdapter.kt
SKGitKit
631,069,664
false
null
package com.khanappsnj.procoreinterviewapp import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.khanappsnj.procoreinterviewapp.databinding.CardItemBinding import com.khanappsnj.procoreinterviewapp.Constants.NAME import com.khanappsnj.procoreinterviewapp.Constants.TYPE import com.khanappsnj.procoreinterviewapp.Constants.HP class CardAdapter(var cards : List<Data>, val onRowClick : (Data) -> Unit) : RecyclerView.Adapter<CardHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardHolder { val inflater = LayoutInflater.from(parent.context) return CardHolder(CardItemBinding.inflate(inflater,parent,false)) } override fun getItemCount(): Int = cards.size ?: 0 override fun onBindViewHolder(holder: CardHolder, position: Int) { holder.bind(cards[position], onRowClick) } fun sortData (option : String){ when(option) { NAME -> cards = cards.sortedBy { it.name } TYPE -> cards = cards.sortedBy { it.types.first() } HP -> cards = cards.sortedBy { it.hp } } notifyDataSetChanged() } }
0
Kotlin
0
0
a36b3b6fb2549b559f1ab3e3768254f4d0ce6a81
1,198
Pokemon-TCG-app
MIT License
src/main/kotlin/no/nav/pensjon/selvbetjening/fssgw/journalforing/JournalforingController.kt
navikt
348,062,453
false
null
package no.nav.pensjon.selvbetjening.fssgw.journalforing import no.nav.pensjon.selvbetjening.fssgw.common.ControllerBase import no.nav.pensjon.selvbetjening.fssgw.common.ServiceClient import no.nav.pensjon.selvbetjening.fssgw.tech.jwt.JwsValidator import no.nav.pensjon.selvbetjening.fssgw.tech.sts.ServiceTokenGetter import org.springframework.beans.factory.annotation.Value import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import javax.servlet.http.HttpServletRequest @RestController @RequestMapping("rest/journalpostapi") class JournalforingController( jwsValidator: JwsValidator, egressTokenGetter: ServiceTokenGetter, serviceClient: ServiceClient, @Value("\${journalforing.url}") egressEndpoint: String) : ControllerBase(jwsValidator, serviceClient, egressTokenGetter, egressEndpoint) { @PostMapping("v1/journalpost") fun handlePostRequest(@RequestBody body: String, request: HttpServletRequest): ResponseEntity<String> { return super.doPost(request, body) } override fun egressAuthWaived(): Boolean { return false } override fun consumerTokenRequired(): Boolean { return false } }
1
Kotlin
0
0
e1126ba64bb8778cad6a549d30f59b9d8e3544ea
1,404
pensjon-selvbetjening-fss-gateway
MIT License
libs/common/src/main/kotlin/gyldigSoeknad/VurdertGyldighet.kt
navikt
417,041,535
false
null
package no.nav.etterlatte.libs.common.gyldigSoeknad import java.time.LocalDateTime data class VurdertGyldighet( val navn: GyldighetsTyper, val resultat: VurderingsResultat, val basertPaaOpplysninger: Any? ) data class GyldighetsResultat( val resultat: VurderingsResultat?, val vurderinger: List<VurdertGyldighet>, val vurdertDato: LocalDateTime ) enum class VurderingsResultat(val prioritet: Int) { OPPFYLT(1), KAN_IKKE_VURDERE_PGA_MANGLENDE_OPPLYSNING(2), IKKE_OPPFYLT(3) }
6
Kotlin
0
3
8d41d2e006b5df41eacef84a670bc162ed72233c
514
pensjon-etterlatte-saksbehandling
MIT License
idea-plugin/examples/simple-preview-example/mpp-jvm/src/commonMain/kotlin/App.kt
JetBrains
293,498,508
false
null
import androidx.compose.material.Button import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.* @Composable fun App() { MaterialTheme { Button(onClick = {}) { Text("Hello, ${getPlatformName()}!") } } } expect fun getPlatformName(): String
668
Kotlin
645
9,090
97266a0ac8c0d7a8ad8d19ead1c925751a00ff1c
339
compose-jb
Apache License 2.0
src/main/kotlin/me/rhysxia/explore/server/graphql/scalar/TimestampScalar.kt
RhysXia
362,829,891
false
null
package me.rhysxia.explore.server.graphql.scalar import graphql.language.IntValue import graphql.schema.Coercing import graphql.schema.CoercingParseLiteralException import graphql.schema.CoercingParseValueException import graphql.schema.CoercingSerializeException import me.rhysxia.explore.server.configuration.graphql.annotation.GraphqlScalar import java.time.Instant @GraphqlScalar("Timestamp") class TimestampScalar : Coercing<Instant, Long> { override fun serialize(dataFetcherResult: Any): Long { return if (dataFetcherResult is Instant) { dataFetcherResult.toEpochMilli() } else { throw CoercingSerializeException("Not a valid Timestamp") } } override fun parseValue(input: Any): Instant { if (input is Long) { return Instant.ofEpochMilli(input) } else if (input is Int) { return Instant.ofEpochMilli(input.toLong()) } throw CoercingParseValueException("Expected a 'number' but was '${input.javaClass.name}'.") } override fun parseLiteral(input: Any): Instant { if ((input is IntValue)) { return Instant.ofEpochMilli(input.value.toLong()) } throw CoercingParseLiteralException("Expected AST type 'IntValue' but was ''${input.javaClass.name}'.") } }
6
Kotlin
0
0
8896c3c2916493ceb45b8cad488fd007446a65c9
1,240
explore-server
MIT License
livemap/src/commonMain/kotlin/jetbrains/livemap/mapobjects/MapPoint.kt
tchigher
229,856,588
true
{"Kotlin": 4345032, "Python": 257583, "CSS": 1842, "C": 1638, "Shell": 1590, "JavaScript": 1584}
/* * Copyright (c) 2019. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package jetbrains.livemap.mapobjects import jetbrains.datalore.base.spatial.LonLat import jetbrains.datalore.base.typedGeometry.Vec import jetbrains.datalore.base.values.Color class MapPoint( index: Int, mapId: String?, regionId: String?, override var point: Vec<LonLat>, val label: String, val animation: Int, val shape: Int, val radius: Double, val fillColor: Color, val strokeColor: Color, val strokeWidth: Double ) : MapObject(index, mapId, regionId), MapPointGeometry
0
null
0
0
f6fd07e9f44c789206a720dcf213d0202392976f
667
lets-plot
MIT License
nexa-plugins/adventure/src/main/kotlin/pixel/nexa/plugin/adventure/entity/item/ItemStack.kt
PixelVoyagers
812,454,511
false
{"Kotlin": 155472, "HTML": 14726}
package pixel.nexa.plugin.adventure.entity.item import pixel.auxframework.component.annotation.Autowired import pixel.auxframework.component.annotation.Component import pixel.nexa.core.data.component.DataComponentMap import pixel.nexa.core.data.component.IDataComponentType import pixel.nexa.core.data.tag.CompoundTag import pixel.nexa.core.data.tag.compoundTagOf import pixel.nexa.network.message.MessageFragments import pixel.nexa.network.message.TextFragment import pixel.nexa.plugin.adventure.AdventurePlugin import pixel.nexa.plugin.adventure.entity.AdventureRegistries @Component class ItemStackDataType(private val registry: AdventureRegistries) : IDataComponentType<ItemStack, CompoundTag> { @Autowired private lateinit var items: Items override fun deserialize(tag: CompoundTag): ItemStack { val count = tag.getLong("count") ?: 1 val item = registry.items.get(tag.getString("item")?.let(AdventurePlugin::id) ?: items.airItem.getLocation()) ?: items.airItem.get() val data = tag.getCompound("data") ?: CompoundTag() val stack = ItemStack(item, count) stack.getDataComponents().load(data) return stack } override fun serialize(element: ItemStack): CompoundTag { val tag = CompoundTag() tag.putString("item", registry.items.get(element.getItem())!!.toString()) tag.putNumber("count", element.getCount()) tag.putCompound("data", element.getDataComponents().read()) return tag } } class ItemStack(private val item: Item, private var count: Long = 1, private val dataComponentMap: DataComponentMap = DataComponentMap()) : ItemLike, ItemStackLike { fun getDataComponents() = dataComponentMap fun getItem() = item fun getCount() = count fun isEmpty() = count == 0L || item is AirItem override fun asItem() = getItem() override fun asItemStack() = this fun setCount(to: Long) = apply { count = to } init { dataComponentMap.schema.putAll(getItem().getDataComponentSchema()) } fun getName(): TextFragment { return getDataComponents().getTyped(ItemDataComponentTypes.CUSTOM_NAME.second)?.getOrNull() ?: getItem().getName(this) } fun getTooltip(): MutableList<TextFragment> { val tooltip = mutableListOf<TextFragment>() if (Item.Properties.copy(getItem()).showDefaultTooltip()) tooltip += MessageFragments.translatable(getItem().getRegistry().get(getItem())!!.format { namespace, path -> "item.$namespace.$path.tooltip" }) tooltip += getDataComponents().getTyped(ItemDataComponentTypes.CUSTOM_TOOLTIP.second)?.getOrNull() ?: emptyList() getItem().appendTooltip(this, tooltip) return tooltip } fun getNameWithCount(): TextFragment { return MessageFragments.multiple(getName(), MessageFragments.text(" * "), MessageFragments.text(getCount().toString())) } fun copy() = ItemStack(item, count).also { it.dataComponentMap.load(compoundTagOf(dataComponentMap.read().copy().read())) } }
0
Kotlin
0
1
30aafb4f35fca79786a83a25a6fc0b3c445e8f69
3,081
Nexa
Apache License 2.0
src/main/kotlin/io/github/sgtsilvio/gradle/oci/platform/Platform.kt
SgtSilvio
522,265,898
false
{"Kotlin": 356020}
package io.github.sgtsilvio.gradle.oci.platform import io.github.sgtsilvio.gradle.oci.internal.compareTo import java.io.Serializable import java.util.* /** * @author <NAME> */ sealed interface Platform : Comparable<Platform>, Serializable { val os: String val architecture: String val variant: String val osVersion: String val osFeatures: SortedSet<String> } internal fun Platform( os: String, architecture: String, variant: String, osVersion: String, osFeatures: SortedSet<String>, ): Platform = PlatformImpl(os, architecture, variant.ifEmpty { defaultVariant(architecture) }, osVersion, osFeatures) private data class PlatformImpl( override val os: String, override val architecture: String, override val variant: String, override val osVersion: String, override val osFeatures: SortedSet<String>, ) : Platform { override fun toString(): String { val s = "@$os,$architecture" return when { osFeatures.isNotEmpty() -> "$s,$variant,$osVersion," + osFeatures.joinToString(",") osVersion.isNotEmpty() -> "$s,$variant,$osVersion" variant.isNotEmpty() -> "$s,$variant" else -> s } } override fun compareTo(other: Platform): Int { os.compareTo(other.os).also { if (it != 0) return it } architecture.compareTo(other.architecture).also { if (it != 0) return it } variant.compareTo(other.variant).also { if (it != 0) return it } osVersion.compareTo(other.osVersion).also { if (it != 0) return it } return osFeatures.compareTo(other.osFeatures) } } private fun defaultVariant(architecture: String) = when (architecture) { "arm64" -> "v8" "arm" -> "v7" else -> "" }
1
Kotlin
0
27
ed359b94fd52ab47e7fc17fccc8db47694a3d767
1,765
gradle-oci
Apache License 2.0
arrow-core/src/main/kotlin/arrow/core/Id.kt
benfleis
119,547,943
true
{"Kotlin": 1371767, "CSS": 115818, "HTML": 9227, "JavaScript": 7275, "Java": 4423, "Shell": 3057}
package arrow.core import arrow.higherkind fun <A> IdKind<A>.value(): A = this.ev().value @higherkind data class Id<out A>(val value: A) : IdKind<A> { inline fun <B> map(f: (A) -> B): Id<B> = Id(f(value)) inline fun <B> flatMap(f: (A) -> IdKind<B>): Id<B> = f(value).ev() fun <B> foldLeft(b: B, f: (B, A) -> B): B = f(b, this.ev().value) fun <B> foldRight(lb: Eval<B>, f: (A, Eval<B>) -> Eval<B>): Eval<B> = f(this.ev().value, lb) fun <B> coflatMap(f: (IdKind<A>) -> B): Id<B> = this.ev().map({ f(this) }) fun extract(): A = this.ev().value fun <B> ap(ff: IdKind<(A) -> B>): Id<B> = ff.ev().flatMap { f -> map(f) }.ev() companion object { tailrec fun <A, B> tailRecM(a: A, f: (A) -> IdKind<Either<A, B>>): Id<B> { val x: Either<A, B> = f(a).ev().value return when (x) { is Either.Left<A, B> -> tailRecM(x.a, f) is Either.Right<A, B> -> Id(x.b) } } fun <A> pure(a: A): Id<A> = Id(a) } }
0
Kotlin
0
0
0f63726be8d9c662156f3a1705cc86cd51101967
1,030
arrow
Apache License 2.0
app/src/main/kotlin/com/gnoemes/shimori/appinitializers/ThreeTenBpInitializer.kt
gnoemes
213,210,354
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 com.gnoemes.shimori.appinitializers import android.app.Application import com.gnoemes.shimori.base.appinitializers.AppInitializer import com.gnoemes.shimori.base.utils.AppCoroutineDispatchers import com.jakewharton.threetenabp.AndroidThreeTen import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import org.threeten.bp.zone.ZoneRulesProvider import javax.inject.Inject class ThreeTenBpInitializer @Inject constructor( private val dispatchers: AppCoroutineDispatchers ) : AppInitializer { override fun init(app: Application) { AndroidThreeTen.init(app) // Query the ZoneRulesProvider so that it is loaded on a background coroutine @OptIn(DelicateCoroutinesApi::class) GlobalScope.launch(dispatchers.io) { ZoneRulesProvider.getAvailableZoneIds() } } }
0
Kotlin
0
9
7a8373881e2abc29be51a2030ddfd329d9928d80
1,486
Shimori
Apache License 2.0
app/src/main/java/com/tazkrtak/staff/models/Ticket.kt
tazkrtak
212,135,611
false
null
package com.tazkrtak.staff.models import android.util.Base64 import com.tazkrtak.staff.BuildConfig import com.tazkrtak.staff.util.Mode import javax.crypto.Cipher import javax.crypto.spec.IvParameterSpec import javax.crypto.spec.SecretKeySpec class Ticket { var userNationalId: String? = null var totp: String? = null var quantity: Int? = null var fees: Double? = null var isValid: Boolean = false val totalFees: Double get() = fees!! * quantity!! constructor(encryptedData: String) { val data = try { decrypt(encryptedData) } catch (e: Exception) { return } if (validate(data)) { isValid = true populate(data) } } private fun decrypt(encryptedText: String): String { val algorithm = "AES" val transformation = "AES/CBC/PKCS5Padding" val cipher = Cipher.getInstance(transformation) val key = "<KEY>" val secretKeySpec = SecretKeySpec(key.toByteArray(), algorithm) val iv = ByteArray(16) val charArray = key.toCharArray() (charArray.indices).forEach { iv[it] = charArray[it].toByte() } val ivParameterSpec = IvParameterSpec(iv) cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec) val decryptedByteValue = cipher.doFinal(Base64.decode(encryptedText, Base64.NO_PADDING)) return String(decryptedByteValue) } private fun populate(qrData: String) { val data = qrData.split(";") userNationalId = data[0] totp = data[1] quantity = data[2].toInt() fees = data[3].toDouble() } private fun validate(qrData: String): Boolean { val regex = if (BuildConfig.Mode == Mode.TEST) { Regex("^\\d{3};\\d{6};([1-9]|[1-4][0-9]|50);([3-9]|10).[0-9]\$") } else { Regex("^\\d{14};\\d{6};([1-9]|[1-4][0-9]|50);([3-9]|10).[0-9]\$") } return qrData.matches(regex) } }
0
Kotlin
1
0
00db96ab69807237bf0d276413fcc43e889420fe
2,005
alpha-staff
Apache License 2.0
app/src/main/java/com/byy/mvvm_interviewtest/data/remote/ApiService.kt
bbyhao
132,335,526
false
null
package com.byy.mvvm_interviewtest.data.remote import com.byy.mvvm_interviewtest.data.RateEntry import io.reactivex.Observable import retrofit2.http.GET /** * @author Created by fq on 2018/4/28. */ interface ApiService { @GET("latest") fun getRate(): Observable<RateEntry> }
0
Kotlin
0
6
efaac1eb91e32cf87b51b99e143982cce7628ebb
286
mvvm_interview
Apache License 2.0
src/main/kotlin/us/timinc/mc/cobblemon/unimplementeditems/items/PostBattleItem.kt
timinc-cobble
669,249,509
false
{"Kotlin": 20737, "Java": 1329}
package us.timinc.mc.cobblemon.unimplementeditems.items import com.cobblemon.mod.common.api.events.battles.BattleVictoryEvent import com.cobblemon.mod.common.pokemon.Pokemon import net.minecraft.item.ItemStack interface PostBattleItem { fun doPostBattle(itemStack: ItemStack, pokemon: Pokemon, event: BattleVictoryEvent) }
8
Kotlin
0
1
18678b071c7620589d6527d5a2cbb0974add939e
328
cobblemon-unimplemented-items-1.4-fabric
MIT License
asm-debuglog-plugin/src/main/java/it/sephiroth/android/library/asm/plugin/debuglog/DebugArguments.kt
sephiroth74
429,513,067
false
null
package it.sephiroth.android.library.asm.plugin.debuglog import java.io.Serializable enum class DebugArguments(val value: Int) : Serializable { None(0), Short(1), Full(2) }
0
Kotlin
0
0
e8ec660baec7d813a42581c1974b5c1c33ba3bbc
179
AndroidDebugLog
MIT License
src/test/kotlin/no/edgeworks/kotlinbeer/wallet/WalletControllerTest.kt
vehagn
364,834,062
false
null
package no.edgeworks.kotlinbeer.wallet import io.mockk.every import io.mockk.mockk import no.edgeworks.kotlinbeer.user.UserDAO import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest import org.springframework.boot.test.context.TestConfiguration import org.springframework.context.annotation.Bean import org.springframework.test.context.ActiveProfiles import org.springframework.test.context.junit.jupiter.SpringExtension import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.post import java.time.ZonedDateTime import java.util.* @ActiveProfiles("test") @ExtendWith(SpringExtension::class) @WebMvcTest(WalletController::class) internal class WalletControllerTest { private val testUserA = UserDAO( id = 1, cardId = 10, firstName = "<NAME>", lastName = "Testusen", email = "<EMAIL>", birthday = ZonedDateTime.now().minusYears(20), userGroup = "BFY", isMember = true, userProperties = Collections.emptySet(), createdBy = "Test" ) private val walletA = WalletDAO( id = 1, user = testUserA, cashBalance = 0, totalSpent = 0, ) @TestConfiguration class ControllerTestConfig { @Bean fun mockWalletService() = mockk<WalletService>() } @Autowired private lateinit var mockMvc: MockMvc @Autowired private lateinit var mockWalletService: WalletService @Test fun purchase() { every { mockWalletService.purchase(any(), any()) } returns UserWallet(testUserA, walletA) mockMvc.post("/users/123/wallet/buy?value=100") .andExpect { status { isOk() } } } }
0
Kotlin
0
0
09e221542a2bd1bd3fb6e4b3a072a255cd7130b6
1,892
kotlinBeer
MIT License
plugin/src/main/java/com/jacobibanez/plugin/android/godotplaygameservices/signin/SignInProxy.kt
Iakobs
729,152,304
false
{"Kotlin": 99074, "GDScript": 85564}
package com.jacobibanez.plugin.android.godotplaygameservices.signin import android.util.Log import com.google.android.gms.games.GamesSignInClient import com.google.android.gms.games.PlayGames import com.jacobibanez.plugin.android.godotplaygameservices.BuildConfig import com.jacobibanez.plugin.android.godotplaygameservices.signals.SignInSignals.serverSideAccessRequested import com.jacobibanez.plugin.android.godotplaygameservices.signals.SignInSignals.userAuthenticated import org.godotengine.godot.Godot import org.godotengine.godot.plugin.GodotPlugin.emitSignal class SignInProxy( private val godot: Godot, private val gamesSignInClient: GamesSignInClient = PlayGames.getGamesSignInClient(godot.getActivity()!!) ) { private val tag: String = SignInProxy::class.java.simpleName fun isAuthenticated() { Log.d(tag, "Checking if user is authenticated") gamesSignInClient.isAuthenticated.addOnCompleteListener { task -> if (task.isSuccessful) { Log.d(tag, "User authenticated: ${task.result.isAuthenticated}") emitSignal( godot, BuildConfig.GODOT_PLUGIN_NAME, userAuthenticated, task.result.isAuthenticated ) } else { Log.e(tag, "User not authenticated. Cause: ${task.exception}", task.exception) emitSignal( godot, BuildConfig.GODOT_PLUGIN_NAME, userAuthenticated, false ) } } } fun signIn() { Log.d(tag, "Signing in") gamesSignInClient.signIn().addOnCompleteListener { task -> if (task.isSuccessful) { Log.d(tag, "User signed in: ${task.result.isAuthenticated}") emitSignal( godot, BuildConfig.GODOT_PLUGIN_NAME, userAuthenticated, task.result.isAuthenticated ) } else { Log.e(tag, "User not signed in. Cause: ${task.exception}", task.exception) emitSignal(godot, BuildConfig.GODOT_PLUGIN_NAME, userAuthenticated, false) } } } fun signInRequestServerSideAccess(serverClientId: String, forceRefreshToken: Boolean) { Log.d( tag, "Requesting server side access for client id $serverClientId with refresh token $forceRefreshToken" ) gamesSignInClient.requestServerSideAccess(serverClientId, forceRefreshToken) .addOnCompleteListener { task -> if (task.isSuccessful) { Log.d(tag, "Access granted to server side for user: $serverClientId") emitSignal( godot, BuildConfig.GODOT_PLUGIN_NAME, serverSideAccessRequested, task.result ) } else { Log.e( tag, "Failed to request server side access. Cause: ${task.exception}", task.exception ) } } } }
1
Kotlin
4
57
2fe3975082df827cc4bb9ee1b7e61703017ba8b8
3,303
godot-play-game-services
MIT License
app/src/main/java/com/ricknout/rugbyranker/di/AppModule.kt
victorvicari
203,642,375
true
{"Kotlin": 224788}
package com.ricknout.rugbyranker.di import android.content.Context import android.content.SharedPreferences import androidx.room.Room import androidx.work.WorkManager import com.ricknout.rugbyranker.RugbyRankerApplication import com.ricknout.rugbyranker.core.api.WorldRugbyService import com.ricknout.rugbyranker.db.RugbyRankerDb import com.ricknout.rugbyranker.db.RugbyRankerMigrations import com.ricknout.rugbyranker.matches.db.WorldRugbyMatchDao import com.ricknout.rugbyranker.matches.repository.MatchesRepository import com.ricknout.rugbyranker.matches.work.MatchesWorkManager import com.ricknout.rugbyranker.rankings.db.WorldRugbyRankingDao import com.ricknout.rugbyranker.rankings.prefs.RankingsSharedPreferences import com.ricknout.rugbyranker.rankings.repository.RankingsRepository import com.ricknout.rugbyranker.rankings.work.RankingsWorkManager import com.ricknout.rugbyranker.teams.db.WorldRugbyTeamDao import com.ricknout.rugbyranker.teams.repository.TeamsRepository import com.ricknout.rugbyranker.teams.work.TeamsWorkManager import com.ricknout.rugbyranker.theme.prefs.ThemeSharedPreferences import com.ricknout.rugbyranker.theme.repository.ThemeRepository import dagger.Module import dagger.Provides import javax.inject.Singleton import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.create @Module(includes = [ViewModelModule::class, WorkerModule::class]) class AppModule { @Provides @Singleton fun provideContext(application: RugbyRankerApplication): Context { return application.applicationContext } @Provides @Singleton fun provideRetrofit(): Retrofit { return Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .baseUrl(WorldRugbyService.BASE_URL) .build() } @Provides @Singleton fun provideWorldRugbyService(retrofit: Retrofit): WorldRugbyService { return retrofit.create() } @Provides @Singleton fun provideDatabase(context: Context): RugbyRankerDb { return Room.databaseBuilder(context, RugbyRankerDb::class.java, RugbyRankerDb.DATABASE_NAME) .addMigrations(RugbyRankerMigrations.MIGRATION_1_2, RugbyRankerMigrations.MIGRATION_2_3) .build() } @Provides @Singleton fun provideWorldRugbyRankingDao(database: RugbyRankerDb): WorldRugbyRankingDao { return database.worldRugbyRankingDao() } @Provides @Singleton fun provideWorldRugbyMatchDao(database: RugbyRankerDb): WorldRugbyMatchDao { return database.worldRugbyMatchDao() } @Provides @Singleton fun provideWorldRugbyTeamDao(database: RugbyRankerDb): WorldRugbyTeamDao { return database.worldRugbyTeamDao() } @Provides @Singleton fun provideSharedPreferences(context: Context): SharedPreferences { return context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE) } @Provides @Singleton fun provideRankingsSharedPreferences(sharedPreferences: SharedPreferences): RankingsSharedPreferences { return RankingsSharedPreferences(sharedPreferences) } @Provides @Singleton fun provideThemeSharedPreferences(sharedPreferences: SharedPreferences): ThemeSharedPreferences { return ThemeSharedPreferences(sharedPreferences) } @Provides @Singleton fun provideRankingsRepository( worldRugbyService: WorldRugbyService, worldRugbyRankingDao: WorldRugbyRankingDao, rankingsSharedPreferences: RankingsSharedPreferences ): RankingsRepository { return RankingsRepository(worldRugbyService, worldRugbyRankingDao, rankingsSharedPreferences) } @Provides @Singleton fun provideMatchesRepository( worldRugbyService: WorldRugbyService, worldRugbyMatchDao: WorldRugbyMatchDao ): MatchesRepository { return MatchesRepository(worldRugbyService, worldRugbyMatchDao) } @Provides @Singleton fun provideThemeRepository(themeSharedPreferences: ThemeSharedPreferences): ThemeRepository { return ThemeRepository(themeSharedPreferences) } @Provides @Singleton fun provideTeamsRepository( worldRugbyService: WorldRugbyService, worldRugbyTeamDao: WorldRugbyTeamDao ): TeamsRepository { return TeamsRepository(worldRugbyService, worldRugbyTeamDao) } @Provides @Singleton fun provideWorkManager(context: Context): WorkManager { return WorkManager.getInstance(context) } @Provides @Singleton fun provideRankingsWorkManager(workManager: WorkManager): RankingsWorkManager { return RankingsWorkManager(workManager) } @Provides @Singleton fun provideMatchesWorkManager(workManager: WorkManager): MatchesWorkManager { return MatchesWorkManager(workManager) } @Provides @Singleton fun provideTeamsWorkManager(workManager: WorkManager): TeamsWorkManager { return TeamsWorkManager(workManager) } companion object { private const val SHARED_PREFERENCES_NAME = "rugby_ranker_shared_preferences" } }
0
Kotlin
0
0
eb89f49d829278ec08c6b60eb0f184c63f25d6c9
5,217
rugby-ranker
Apache License 2.0
web/src/main/kotlin/com/github/niuhf0452/exile/web/MediaType.kt
niuhf0452
240,633,641
false
null
package com.github.niuhf0452.exile.web import com.github.niuhf0452.exile.common.PublicApi import java.nio.charset.Charset import java.nio.charset.UnsupportedCharsetException @PublicApi data class MediaType( val text: String, val type: String, val subtype: String, val tree: String? = null, val suffix: String? = null, val charset: Charset = Charsets.UTF_8 ) { fun isAcceptable(m: MediaType): Boolean { return (type == "*" || type == m.type) && (subtype == "*" || subtype == m.subtype) && (subtype == "*" || tree == m.tree) && (subtype == "*" || suffix == m.suffix) } override fun toString(): String { return text } companion object { private val TYPE = "([\\w\\-]+|\\*)/(?:(\\w+)\\.)?([\\w\\-]+|\\*)(?:\\+([\\w\\-]+))?".toPattern() private val CHARSET = ";\\s*charset\\s*=\\s*([\\w\\-]+)".toRegex() val ALL = parse0("*/*") val APPLICATION_JSON = parse0("application/json") val APPLICATION_XML = parse0("application/xml") val APPLICATION_X_YAML = parse0("application/x-yaml") val TEXT_PLAIN = parse0("text/plain") val TEXT_HTML = parse0("text/html") val TEXT_YAML = parse0("text/yaml") private val cached = listOf( APPLICATION_JSON, APPLICATION_XML, APPLICATION_X_YAML, TEXT_PLAIN, TEXT_HTML, TEXT_YAML ) /** * Cache for speed. */ private val cacheMap = cached.map { m -> "${m.type}/${m.subtype}" to m }.toMap() fun parse(value: String): MediaType { return cacheMap[value] ?: parse0(value) } private fun parse0(value: String): MediaType { if (value.isEmpty()) { throw IllegalArgumentException() } val m = TYPE.matcher(value) if (!m.lookingAt()) { throw IllegalArgumentException("Invalid media type: $value") } val type = m.group(1) val tree = m.group(2) val subtype = m.group(3) val suffix = m.group(4) val charset = getCharset(value, m.end()) return MediaType(value, type, subtype, tree, suffix, charset) } private fun getCharset(value: String, start: Int): Charset { val m = CHARSET.find(value, start) ?: return Charsets.UTF_8 try { return Charset.forName(m.groupValues[1]) } catch (ex: UnsupportedCharsetException) { throw IllegalArgumentException("Invalid media type, unsupported charset: $value") } } } }
0
Kotlin
1
2
8020cb1ab799f7b1e75c73f762a9ee1ed493a003
2,836
exile
Apache License 2.0
app/src/main/java/app/accrescent/client/ui/AppIcon.kt
accrescent
438,517,305
false
null
package app.accrescent.client.ui import androidx.compose.foundation.shape.CircleShape import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import app.accrescent.client.data.REPOSITORY_URL import coil.compose.AsyncImage @Composable fun AppIcon(appId: String, modifier: Modifier = Modifier) { AsyncImage( "$REPOSITORY_URL/apps/$appId/icon.png", "App icon", modifier.clip(CircleShape), ) }
21
Kotlin
9
250
0114324cd1a7d4dc700a47935f9553df7deb1426
484
accrescent
ISC License
shared/src/commonMain/kotlin/com/seyedjafariy/shared/model/dto/CompanyInfoDTO.kt
seyedjafariy
520,298,973
false
{"Kotlin": 101839}
package com.seyedjafariy.shared.model.dto import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class CompanyInfoDTO( @SerialName("id") val id: String, @SerialName("name") val name: String, @SerialName("founder") val founder: String, @SerialName("founded") val founded: Int, @SerialName("employees") val employees: Int, @SerialName("launch_sites") val launchSites: Int, @SerialName("valuation") val valuation: Long, )
0
Kotlin
0
7
65a91dbc992368e0552fde97c7975cdd5bed3b92
523
Shuttle
Apache License 2.0
app/src/main/java/com/autosec/pie/screens/InstallNewPackage.kt
cryptrr
850,497,911
false
{"Kotlin": 355163, "Shell": 1942}
package com.autosec.pie.screens import android.app.Activity import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer 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.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.SheetState import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3Api::class) @Composable fun InstallNewPackageBottomSheet( state: SheetState, open : MutableState<Boolean>, onHide: () -> Unit = {}, onExpand: () -> Unit = {} ) { val scope = rememberCoroutineScope() val activity = (LocalContext.current as? Activity) @Composable fun bottomSheetContent() { Box( modifier = Modifier .fillMaxWidth() //.height(700.dp) .fillMaxHeight(0.75F) , contentAlignment = Alignment.TopStart ) { Column( Modifier .fillMaxSize() .padding(horizontal = 15.dp)){ InstallNewPackageScreen() } } } ModalBottomSheet( sheetState = state, content = { bottomSheetContent() }, shape = RoundedCornerShape(topStart = 15.dp, topEnd = 15.dp), containerColor = MaterialTheme.colorScheme.secondaryContainer, onDismissRequest = { scope.launch { open.value = false } } ) } @Composable fun InstallNewPackageScreen( ) { Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center){ Column(horizontalAlignment = Alignment.CenterHorizontally){ Text("Install new package from Repository") Spacer(modifier = Modifier.height(7.dp)) Text("Work In Progress") } } }
2
Kotlin
0
4
bbad9def664e896635a22d186c783c2c7a9eb026
2,612
AutoPie
Apache License 2.0
app/src/main/java/de/jepfa/yapm/util/Constants.kt
jenspfahl
378,141,282
false
null
package de.jepfa.yapm.util import android.net.Uri import java.text.DateFormat import java.text.DecimalFormat import java.text.NumberFormat import java.text.SimpleDateFormat import java.util.* object Constants { val HOMEPAGE = Uri.parse("https://anotherpass.jepfa.de") val FOSS_SITE = "https://github.com/jenspfahl/anotherpass" val BUG_REPORT_SITE = FOSS_SITE + "/issues/new?title=%s&body=%s" val MIN_PIN_LENGTH = 6 val MAX_LABELS_PER_CREDENTIAL = 5 val MAX_CREDENTIAL_PASSWD_LENGTH = 50 val MASTER_KEY_BYTE_SIZE = 128 val SDF_DT_MEDIUM = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.MEDIUM, SimpleDateFormat.MEDIUM) val SDF_D_INTERNATIONAL: DateFormat = SimpleDateFormat("yyyy-MM-dd") // Note: This is actually not a vault version rather than a Masterkey interpretation. So new vault versions should be handled differently ! const val INITIAL_VAULT_VERSION = 1 const val FAST_KEYGEN_VAULT_VERSION = 2 const val CURRENT_VERSION = FAST_KEYGEN_VAULT_VERSION }
0
Kotlin
0
6
6e3735dfd5aebecb3fdb283e444cdab0247e511a
1,032
ANOTHERpass
MIT License
core/src/main/java/pn/android/core/base/StatusViewModel.kt
purenative
577,193,628
false
null
package pn.android.core.base import android.annotation.SuppressLint import android.content.Context import org.orbitmvi.orbit.syntax.simple.SimpleSyntax import org.orbitmvi.orbit.syntax.simple.intent import timber.log.Timber @SuppressLint("StaticFieldLeak") abstract class StatusViewModel<STATE : Statusable, SIDE_EFFECT : Any>( private val context: Context ) : BaseViewModel<STATE, SIDE_EFFECT>() { abstract suspend fun SimpleSyntax<STATE, SIDE_EFFECT>.onLoading() abstract suspend fun SimpleSyntax<STATE, SIDE_EFFECT>.onError(status: Status) fun statusIntent( transformer: suspend SimpleSyntax<STATE, SIDE_EFFECT>.() -> Unit ) { intent { try { onLoading() transformer() } catch (e: Exception) { Timber.e(e) onError(Status.UnknownError) } } } }
5
Kotlin
0
9
97493e520eaa0c950447859477b5da136fb0adaf
900
pn-android
MIT License
app/src/main/java/com/github/spacepilothannah/spongiform/ui/LoginActivity.kt
spacepilothannah
175,169,331
false
null
package com.github.spacepilothannah.spongiform.ui import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.annotation.TargetApi import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Build import android.os.Bundle import android.util.Log import android.view.KeyEvent import android.view.View import android.view.inputmethod.EditorInfo import android.widget.Button import android.widget.EditText import android.widget.TextView import android.widget.Toast import com.github.spacepilothannah.spongiform.R import com.github.spacepilothannah.spongiform.data.DataManager import com.github.spacepilothannah.spongiform.data.DataManagerFactory import com.github.spacepilothannah.spongiform.data.api.Credentials /** * A login screen that offers login via email/password. */ class LoginActivity : AppCompatActivity() { var dataManagerFactory: DataManagerFactory = DataManagerFactory.Companion val dataManager: DataManager get() { return dataManagerFactory.createDataManager(this) } // UI references. private val mUriView: EditText by lazy { findViewById<View>(R.id.uri) as EditText } private val mUserView: EditText by lazy { findViewById<View>(R.id.user) as EditText } private val mPassView: EditText by lazy { findViewById<View>(R.id.password) as EditText } private val mProgressView: View by lazy { findViewById<View>(R.id.login_progress) } private val mLoginFormView: View by lazy { findViewById<View>(R.id.login_form) } protected override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d("SQUID", "LoginActivity onCreate") // if I weren't using HTTP Basic auth like a prune I'd have: // val token = dataManager.getToken() // if(token != "") { // attemptLoginWithToken() // } setSupportActionBar(findViewById(R.id.login_activity_action_bar)) val credentials = dataManager.getCredentials() if(credentials.isValid()) { attemptLogin() } setContentView(R.layout.login_activity) mPassView.text.replace(0, mPassView.text.length, credentials.password) mUserView.text.replace(0, mUserView.text.length, credentials.username) mUriView.text.replace(0, mUriView.text.length, credentials.url) mPassView.setOnEditorActionListener { _: TextView, id: Int, keyEvent: KeyEvent -> var done = false if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) { if(setCredentials()) { done = true attemptLogin() } } done } val signInButton = findViewById<View>(R.id.sign_in_button) as Button signInButton.setOnClickListener { setCredentials() attemptLogin() } } private fun launchMainActivity() { Log.d("SQUID", "launching MainActivity") val intent = Intent(this, MainActivity::class.java).apply { // extra data goes here (there is none?) } startActivity(intent) } private fun attemptLogin() { showProgress(true) Log.d("SQUID", "attempting login with credentials " + dataManager.getCredentials().toString()) dataManager.tryLogin() { success -> Log.d("SQUID","logged in? $success") if(success) { launchMainActivity() } else { Toast.makeText(this, "Couldn't log in for some reason :-C", Toast.LENGTH_LONG).show() } showProgress(false) } } private fun setCredentials() : Boolean { // Reset errors. mUriView.error = null mPassView.error = null var cancel = false var focusView: View? = null for(view in arrayListOf(mPassView, mUserView, mUriView)) { if(view.text.isEmpty()) { view.error = "This field is required" focusView = view cancel = true } } focusView?.requestFocus() if (cancel) { return false } val uri = mUriView.text.toString() val user = mUserView.text.toString() val password = mPassView.text.toString() val creds = Credentials( username = user, password = <PASSWORD>, url = uri ) Log.d("SQUID", "setting credentials to " + creds.toString()) dataManager.setCredentials(creds) return true } private fun isUserValid(email: String): Boolean { return !email.contains(" ") } private fun isPasswordValid(password: String): Boolean { return password.length > 4 } /** * Shows the progress UI and hides the login form. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) private fun showProgress(show: Boolean) { // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow // for very easy animations. If available, use these APIs to fade-in // the progress spinner. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { val shortAnimTime = resources.getInteger(android.R.integer.config_shortAnimTime) mLoginFormView?.visibility = if (show) View.GONE else View.VISIBLE mLoginFormView?.animate()?.setDuration(shortAnimTime.toLong())?.alpha( (if (show) 0 else 1).toFloat())?.setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { mLoginFormView?.visibility = if (show) View.GONE else View.VISIBLE } }) mProgressView?.visibility = if (show) View.VISIBLE else View.GONE mProgressView?.animate()?.setDuration(shortAnimTime.toLong())?.alpha( (if (show) 1 else 0).toFloat())?.setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { mProgressView?.visibility = if (show) View.VISIBLE else View.GONE } }) } else { // The ViewPropertyAnimator APIs are not available, so simply show // and hide the relevant UI components. mProgressView?.visibility = if (show) View.VISIBLE else View.GONE mLoginFormView?.visibility = if (show) View.GONE else View.VISIBLE } } }
0
Kotlin
0
0
3e0b4bf1d1966024cf1a2a410f215d5e78ba5447
6,608
spongiform-app
MIT License
telegram-bot/src/main/kotlin/eu/vendeli/tgbot/api/chat/GetChatAdministrators.kt
vendelieu
496,567,172
false
null
@file:Suppress("MatchingDeclarationName") package eu.vendeli.tgbot.api.chat import eu.vendeli.tgbot.interfaces.Action import eu.vendeli.tgbot.interfaces.WrappedTypeOf import eu.vendeli.tgbot.interfaces.getInnerType import eu.vendeli.tgbot.types.ChatMember import eu.vendeli.tgbot.types.internal.TgMethod class GetChatAdministratorsAction : Action<List<ChatMember>>, WrappedTypeOf<ChatMember> { override val method: TgMethod = TgMethod("getChatAdministrators") override val parameters: MutableMap<String, Any?> = mutableMapOf() override val wrappedDataType = getInnerType() } fun getChatAdministrators() = GetChatAdministratorsAction()
0
Kotlin
2
65
4ed11db0d9b7aba66dfbcaf5511cd5d1970ecc26
652
telegram-bot
Apache License 2.0
core/data/src/androidMain/kotlin/io/github/droidkaigi/confsched/data/contributors/ContributorsRepositoryModule.kt
DroidKaigi
776,354,672
false
{"Kotlin": 1119401, "Swift": 211686, "Shell": 2954, "Makefile": 1314, "Ruby": 386}
package io.github.droidkaigi.confsched.data.contributors import dagger.Binds import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import dagger.multibindings.ClassKey import dagger.multibindings.IntoMap import io.github.droidkaigi.confsched.data.di.RepositoryQualifier import io.github.droidkaigi.confsched.model.ContributorsRepository import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) public abstract class ContributorsRepositoryModule { @Binds @RepositoryQualifier @IntoMap @ClassKey(ContributorsRepository::class) public abstract fun bind(repository: ContributorsRepository): Any public companion object { @Provides @Singleton public fun provideContributorsRepository( contributorsApi: ContributorsApiClient, ): ContributorsRepository { return DefaultContributorsRepository( contributorsApi = contributorsApi, ) } } }
49
Kotlin
201
438
57c38a76beb5b75edc9220833162e1257f40ac06
1,039
conference-app-2024
Apache License 2.0
app/src/main/kotlin/com/tans/tfiletranserdesktop/ui/resources/Strings.kt
Tans5
341,413,863
false
{"Kotlin": 387306}
package com.tans.tfiletranserdesktop.ui.resources const val stringAppName = "tFileTransfer" // Broadcast const val stringLocalConnectionTitle = "Connect Remote Device via LocalNetwork" const val stringLocalConnectionTips = "If two devices in the same local network, you can use this way create connection. \n Use QR code scan or UDP broadcast." const val stringLocalConnectionLocalDevice = "Local Device:" const val stringLocalConnectionLocalAddress = "Local IP Address:" const val stringLocalConnectionShowQRCode = "Show QR Code" const val stringLocalConnectionAsReceiver = "Search Servers" const val stringLocalConnectionAsSender = "As Server" // Broadcast Sender Dialog const val stringBroadcastSenderDialogTitle = "Waiting connect..." const val stringBroadcastSenderDialogCancel = "CANCEL" // Broadcast Request Connect Dialog const val stringBroadcastRequestDialogTitle = "Request Connect" const val stringBroadcastRequestDialogAccept = "ACCEPT" const val stringBroadcastRequestDialogDeny = "DENY" // Broadcast Receiver Dialog const val stringBroadcastReceiverDialogTitle = "Searching..." const val stringBroadcastReceiverDialogCancel = "CANCEL" // Handshake Error const val stringHandshakeErrorTitle = "Handshake Error" // Connection Error const val stringConnectionErrorTitle = "Connection Error"
1
Kotlin
2
35
0478156da948e4ea9816444d5ba1a10ce83ea1c7
1,310
tFileTransfer_desktop
Apache License 2.0
src/main/kotlin/com/dannybierek/tools/hmc/model/Subsets.kt
dbierek
630,756,451
false
null
package com.dannybierek.tools.hmc.model data class Subsets( val AudioEmitters: List<String> = listOf(), val Replicable: List<String> = listOf() )
0
Kotlin
0
0
415c0501028f80f340b56d620e3adb700e2f19d3
154
HitmanModCreator
Apache License 2.0
app/src/main/java/com/gwj/sem4_anime_app/ui/register/RegisterFragment.kt
GWJian
730,619,677
false
{"Kotlin": 141201}
package com.gwj.sem4_anime_app.ui.register import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import com.gwj.sem4_anime_app.ui.base.BaseFragment import com.gwj.sem4_anime_app.databinding.FragmentRegisterBinding import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch @AndroidEntryPoint class RegisterFragment : BaseFragment<FragmentRegisterBinding>() { override val viewModel: RegisterViewModel by viewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentRegisterBinding.inflate(inflater, container, false) return binding.root } override fun setupUIComponents() { super.setupUIComponents() binding.run { registerBtn.setOnClickListener { viewModel.signUp( registerUsername.text.toString(), registerEmail.text.toString(), registerPass.text.toString(), confirmPass.text.toString() ) } // registerToLogin.setOnClickListener { // navController.popBackStack() // } } binding.registerToLogin.setOnClickListener { val action = RegisterFragmentDirections.registerToLogin() navController.navigate(action) } } override fun setupViewModelObserver() { super.setupViewModelObserver() lifecycleScope.launch { viewModel.success.collect { val action = RegisterFragmentDirections.registerToLogin() navController.navigate(action) } } } }
0
Kotlin
0
0
bc0e0d52caadcacf33c0b01e6dd3acc6f9f546d7
1,870
sem4_anime_app
MIT License
app/src/main/java/com/getstream/navigation/BottomNavigation.kt
6879756e
619,553,559
false
null
package com.getstream.navigation import androidx.compose.material3.Icon import androidx.compose.material3.NavigationBar import androidx.compose.material3.NavigationBarItem import androidx.compose.material3.Text import androidx.compose.runtime.Composable @Composable fun GetStreamPerusalBottomNavigation( currentDestination: Destination, onItemClicked: (Destination) -> Unit, ) { NavigationBar { Destination.allDestinations.forEach { NavigationBarItem( selected = it == currentDestination, onClick = { onItemClicked(it) }, icon = { Icon( imageVector = if (it == currentDestination) it.imageVectorFilled else it.imageVectorOutlined, contentDescription = "Decorative icon for ${it.label}" ) }, label = { Text(text = it.label) } ) } } }
0
Kotlin
0
0
91b19b587d734baf961b652d23ca5327f7311f42
958
GetStreamPerusal
MIT License
app/src/main/java/com/arjanvlek/oxygenupdater/activities/FAQActivity.kt
iGotYourBackMr
254,597,651
true
{"Kotlin": 640563, "Java": 101703}
package com.arjanvlek.oxygenupdater.activities import android.annotation.SuppressLint import android.graphics.Color import android.os.Bundle import android.view.MenuItem import androidx.core.view.isVisible import com.arjanvlek.oxygenupdater.BuildConfig import com.arjanvlek.oxygenupdater.OxygenUpdater import com.arjanvlek.oxygenupdater.R import com.arjanvlek.oxygenupdater.internal.WebViewClient import com.arjanvlek.oxygenupdater.internal.WebViewError import com.arjanvlek.oxygenupdater.utils.ThemeUtils import kotlinx.android.synthetic.main.activity_faq.* import kotlinx.android.synthetic.main.layout_error.* class FAQActivity : SupportActionBarActivity() { override fun onCreate( savedInstanceState: Bundle? ) = super.onCreate(savedInstanceState).also { setContentView(R.layout.activity_faq) swipeRefreshLayout.apply { setOnRefreshListener { loadFaqPage() } setColorSchemeResources(R.color.colorPrimary) // needs to be done as a workaround to WebView not being able to scroll up if it's not a direct child of a SwipeRefreshLayout setOnChildScrollUpCallback { _, _ -> // allow scrolling up (and thus, disable the swipe-to-refresh gesture) only if: // 1. currently displayed view is a WebView, // 2. and this WebView is not at the topmost Y position webView.isVisible && webView.scrollY != 0 } } loadFaqPage() } override fun onBackPressed() = finish() /** * Respond to the action bar's Up/Home button. * Delegate to [onBackPressed] if [android.R.id.home] is clicked, otherwise call `super` */ override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { android.R.id.home -> onBackPressed().let { true } else -> super.onOptionsItemSelected(item) } /** * Loads the FAQ page, or displays a No Network connection screen if there is no network connection */ @SuppressLint("SetJavaScriptEnabled") // JavaScript is required to toggle the FAQ Item boxes. private fun loadFaqPage() { webView.apply { // must be done to avoid the white background in dark themes setBackgroundColor(Color.TRANSPARENT) // since we can't edit CSS in WebViews, // append 'Light' or 'Dark' to faqServerUrl to get the corresponding themed version // backend handles CSS according to material spec val faqServerUrl = BuildConfig.FAQ_SERVER_URL + "/" + if (ThemeUtils.isNightModeActive(context)) "Dark" else "Light" settings.javaScriptEnabled = true settings.userAgentString = OxygenUpdater.APP_USER_AGENT clearCache(true) loadUrl(faqServerUrl).also { swipeRefreshLayout.isRefreshing = true } // disable loading state once page is completely loaded webViewClient = WebViewClient(context) { error -> if (isFinishing) { return@WebViewClient } // hide progress bar since the page has been loaded swipeRefreshLayout.isRefreshing = false if (error == null) { // Show WebView webView.isVisible = true hideErrorStateIfInflated() } else { // Hide WebView webView.isVisible = false inflateAndShowErrorState(error) } } } } private fun inflateAndShowErrorState(error: WebViewError) { // Show error layout errorLayoutStub?.inflate() errorLayout.isVisible = true errorTitle.text = error.errorCodeString errorText.text = getString(R.string.faq_no_network_text) errorActionButton.setOnClickListener { loadFaqPage() } } private fun hideErrorStateIfInflated() { // Stub is null only after it has been inflated, and // we need to hide the error state only if it has been inflated if (errorLayoutStub == null) { errorLayout.isVisible = false errorActionButton.setOnClickListener { } } } }
0
null
0
0
884766371e62969831f2933ba790bbec4c2c1613
4,261
oxygen-updater
MIT License
sample/src/main/java/com/androidchekhov/pagingrecyclerview/presentation/CommentsPagingAdapter.kt
AndroidChekhov
162,025,190
false
null
package com.androidchekhov.pagingrecyclerview.presentation import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.androidchekhov.pagination.PagingAdapter import com.androidchekhov.pagingrecyclerview.R import com.androidchekhov.pagingrecyclerview.repository.Comment import kotlinx.android.synthetic.main.item_comment.view.* class CommentsPagingAdapter: PagingAdapter<Comment, RecyclerView.ViewHolder>(CommentsDiffCallback()) { override fun getViewType(pos: Int): Int = 1 override fun onCreatePagingViewHolder(parent: ViewGroup): RecyclerView.ViewHolder { val view = inflate(parent, R.layout.item_loading) return PagingViewHolder(view) } override fun onCreateDataViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val view = inflate(parent, R.layout.item_comment) return CommentViewHolder(view) } override fun onBindDataViewHolder(holder: RecyclerView.ViewHolder, pos: Int) { getItem(pos)?.let { with(holder.itemView) { username.text = it.username displayDate.text = it.displayDate commentText.text = it.comment } } } private fun inflate(parent: ViewGroup, layoutRes: Int): View { val inflater = LayoutInflater.from(parent.context) return inflater.inflate(layoutRes, parent, false) } /** * A [RecyclerView.ViewHolder] for a comment view. */ class CommentViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) /** * A [RecyclerView.ViewHolder] for a progress indicator. */ class PagingViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) }
0
Kotlin
0
0
b56e1b0fe92c143e27a75f9a00ef82b81e741270
1,819
paging-indicator-list
Apache License 2.0
dashboard/src/main/java/com/ekenya/rnd/dashboard/di/injectables/RoomModule.kt
JMDev2
691,496,412
false
{"Kotlin": 63475, "Java": 14180}
package com.ekenya.rnd.dashboard.di.injectables import android.content.Context import com.ekenya.rnd.baseapp.di.ModuleScope import com.ekenya.rnd.common.model.ShipData import com.ekenya.rnd.dashboard.database.ShipDao import com.ekenya.rnd.dashboard.database.ShipDatabase import dagger.Module import dagger.Provides @Module class RoomModule(private val context: Context) { @Provides @ModuleScope fun provideContext(): Context{ return context } @Provides @ModuleScope fun provideAppDatabase(context: Context): ShipDatabase{ return ShipDatabase.getInstance(context) } @Provides @ModuleScope fun provideShipDao(database: ShipDatabase): ShipDao { return database.shipDao() } }
0
Kotlin
1
0
6831467c3fecb9713926b9a520310d5e47b99e38
748
ShipX
MIT License
src/main/kotlin/com/github/theapache64/ambientide/data/repo/RulesRepo.kt
theapache64
598,237,118
false
null
package com.github.theapache64.ambientide.data.repo import com.github.theapache64.ambientide.model.IDE import com.github.theapache64.ambientide.model.Rule import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import java.io.File import javax.inject.Inject import kotlin.time.ExperimentalTime import kotlin.time.measureTimedValue interface RulesRepo { fun parseRules(ide: IDE): List<Rule> } class RulesRepoImpl @Inject constructor( private val json: Json ) : RulesRepo { @OptIn(ExperimentalTime::class) override fun parseRules(ide: IDE): List<Rule> { val (value, duration) = measureTimedValue<List<Rule>> { val configFile = getToolHome().resolve(ide.configName) if (!configFile.exists()) { // val configStream = javaClass.getResourceAsStream(ide.defaultConfig) ?: error("Couldn't read ${ide.defaultConfig}") Thread.currentThread().contextClassLoader = RulesRepoImpl::class.java.classLoader val configStream = Thread.currentThread().contextClassLoader.getResourceAsStream(ide.defaultConfig) ?: error("Couldn't read ${ide.defaultConfig}") val text = configStream.bufferedReader().readText() println("Writing default config...") configFile.writeText(text) } json.decodeFromString(configFile.readText()) } println("Time took to parse rules : ${duration.inWholeMilliseconds}ms") return value } private fun getToolHome(): File { val toolHome = System.getProperty("user.home") + File.separator + ".config" + File.separator + "ambient-IDE" return File(toolHome).also { if (!it.exists()) { it.mkdirs() } } } }
0
Kotlin
0
3
55063b0be8b3152905f4e108ce5dff700892fb16
1,827
ambient-IDE
Apache License 2.0
kine/src/main/java/com/kine/client/KineClient.kt
TrendingTechnology
292,750,353
true
{"Kotlin": 186420}
package com.kine.client import com.kine.request.Request import com.kine.response.KineResponse /** * kineClient for making the actual HTTP request to server. */ abstract class KineClient constructor(){ abstract fun canHandleRequest(url: String, method: Int): Boolean @Throws(Throwable::class) abstract fun <T> execute(request: Request, clazz: Class<T>): KineResponse<T> abstract fun cancelAllRequests(tag: String?=null) }
0
null
0
0
e496ea19a7949b846147343016ee2d6bb08a1613
444
Kine
Apache License 2.0
app/src/main/kotlin/com/whereismymotivation/ui/content/ContentViewModel.kt
unusualcodeorg
730,655,456
false
{"Kotlin": 472092}
package com.whereismymotivation.ui.content import androidx.lifecycle.SavedStateHandle import com.whereismymotivation.data.repository.ContentRepository import com.whereismymotivation.ui.base.BaseViewModel import com.whereismymotivation.ui.common.browser.ContentBrowser import com.whereismymotivation.ui.common.progress.Loader import com.whereismymotivation.ui.common.snackbar.Messenger import com.whereismymotivation.ui.navigation.Destination import com.whereismymotivation.ui.navigation.Navigator import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class ContentViewModel @Inject constructor( loader: Loader, messenger: Messenger, savedStateHandle: SavedStateHandle, private val navigator: Navigator, private val contentRepository: ContentRepository, private val contentBrowser: ContentBrowser ) : BaseViewModel(loader, messenger, navigator) { companion object { const val TAG = "ContentViewModel" } val contentId = savedStateHandle.get<String>(Destination.YouTube.routeArgName) fun checkRedirection() { if (contentId == null) return navigator.navigateTo(Destination.Home.route) launchNetwork(error = { navigator.navigateTo(Destination.Home.route) }) { contentRepository.fetchContentDetails(contentId) .collect { contentBrowser.show(it, true) } } } }
0
Kotlin
4
38
5b77e6a6b14ae9ad21e8edd55e8c9b3cc2066f75
1,401
wimm-android-app
Apache License 2.0
couchbase-lite/src/commonMain/kotlin/kotbase/ReplicatorActivityLevel.kt
jeffdgr8
518,984,559
false
{"Kotlin": 2266831, "Python": 294}
/* * Copyright 2022-2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kotbase /** * Activity level of a replicator. */ public expect enum class ReplicatorActivityLevel { /** * The replication is finished or hit a fatal error. */ STOPPED, /** * The replicator is offline because the remote host is unreachable. */ OFFLINE, /** * The replicator is connecting to the remote host. */ CONNECTING, /** * The replication is inactive; either waiting for changes or offline * as the remote host is unreachable. */ IDLE, /** * The replication is actively transferring data. */ BUSY }
0
Kotlin
0
7
ec8fbeb0d3e6c487ec8fb48ba2ba5388c71a29b1
1,210
kotbase
Apache License 2.0
common/kotlinx-coroutines-core-common/src/Annotations.kt
qwertyfinger
153,363,619
true
{"Kotlin": 1832146, "CSS": 8215, "JavaScript": 2505, "Shell": 2222, "Ruby": 1927, "HTML": 1675, "Java": 356}
/* * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.experimental /** * Marks declarations that are still **experimental** in coroutines API, which means that the design of the * corresponding declarations has open issues which may (or may not) lead to their changes in the future. * Roughly speaking, there is a chance that those declarations will be deprecated in the near future or * the semantics of their behavior may change in some way that may break some code. */ @MustBeDocumented @Retention(value = AnnotationRetention.SOURCE) // todo: Experimental WARNING public annotation class ExperimentalCoroutinesApi /** * Marks declarations that are **obsolete** in coroutines API, which means that the design of the corresponding * declarations has serious known flaws and they will be redesigned in the future. * Roughly speaking, these declarations will be deprecated in the future but there is no replacement for them yet, * so they cannot be deprecated right away. */ @MustBeDocumented @Retention(value = AnnotationRetention.SOURCE) // todo: Experimental WARNING public annotation class ObsoleteCoroutinesApi /** * Marks declarations that are **internal** in coroutines API, which means that should not be used outside of * `kotlinx.coroutines`, because their signatures and semantics will be changing between release without any * warnings and without providing any migration aids. * * @suppress **This an internal API and should not be used from general code.** */ @Retention(value = AnnotationRetention.SOURCE) // todo: Experimental ERROR public annotation class InternalCoroutinesApi
0
Kotlin
0
0
4c76c6f4c47a34aa81a33c8c0c8bbaf942b83c68
1,697
kotlinx.coroutines
Apache License 2.0
app/src/main/java/romansytnyk/spacex/ui/capsules/adapter/CapsulesAdapter.kt
RomanSytnyk
124,294,424
false
null
package romansytnyk.spacex.ui.capsules.adapter import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.StringRes import kotlinx.android.synthetic.main.item_capsules.view.* import romansytnyk.spacex.R import romansytnyk.spacex.data.db.entity.CapsuleEntity /** * Created by Roman on 02.03.2018 */ class CapsulesAdapter(private var capsules: List<CapsuleEntity>) : androidx.recyclerview.widget.RecyclerView.Adapter<CapsulesAdapter.RocketViewHolder>() { init { capsules = capsules.reversed() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RocketViewHolder { val v = LayoutInflater.from(parent.context).inflate(R.layout.item_capsules, parent, false) return RocketViewHolder(v) } override fun onBindViewHolder(holder: RocketViewHolder, position: Int) { holder.fillWith(capsules[position]) } override fun getItemCount(): Int = capsules.size inner class RocketViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView) { @SuppressLint("SetTextI18n") fun fillWith(item: CapsuleEntity) { itemView.name.text = item.name itemView.crew.text = String.format(getString(R.string.capsule_crew), item.crewCapacity) // Orbit Duration itemView.orbitDurationYears.text = String.format(getString(R.string.capsule_orbit_duration), item.orbitDurationYr?.toInt()) // Material itemView.material.text = String.format(getString(R.string.capsule_material), item.heatShield?.material, item.heatShield?.sizeMeters, item.heatShield?.tempDegrees?.toInt()) // Sidewall Angle itemView.sidewallAngle.text = String.format(getString(R.string.capsule_sidewall_angle), item.sidewallAngleDeg) // Playload itemView.launchPayloadMass.text = String.format(getString(R.string.capsule_launch_payload), item.launchPayloadMass?.kg?.toInt(), item.launchPayloadMass?.lb?.toInt(), item.launchPayloadVol?.cubicMeters?.toInt()) // Active item.active?.let { if (it) { itemView.status.text = String.format( getString(R.string.status), getString(R.string.active)) } else { itemView.status.text = String.format( getString(R.string.status), getString(R.string.inactive)) } } } private fun getString(@StringRes id: Int): String = itemView.context.getString(id) } }
0
Kotlin
1
10
ae9caa0a36799b275d38c6aa0a9d40fb9dbdb8f4
2,897
SpaceX-App-unofficial
Apache License 2.0
app/src/main/java/com/example/wordsapp/LetterListFragment.kt
MobyLab-Android-Workshop-2023
673,795,554
false
null
package com.example.wordsapp import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.wordsapp.databinding.FragmentLetterListBinding class LetterListFragment : Fragment() { private var isLinearLayoutManager = true private lateinit var recyclerView: RecyclerView private var _binding: FragmentLetterListBinding? = null val binding: FragmentLetterListBinding get() = _binding!! override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentLetterListBinding.inflate(inflater, container, false) val view = binding.root return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { recyclerView = _binding!!.recyclerView chooseLayout() } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.layout_menu, menu) val layoutButton = menu.findItem(R.id.action_switch_layout) setIcon(layoutButton) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return if (item.itemId == R.id.action_switch_layout) { isLinearLayoutManager = !isLinearLayoutManager chooseLayout() setIcon(item) true } else super.onOptionsItemSelected(item) } private fun chooseLayout() { recyclerView.layoutManager = if (isLinearLayoutManager) LinearLayoutManager(context) else GridLayoutManager(context, 4) recyclerView.adapter = LetterAdapter() } private fun setIcon(menuItem: MenuItem?) { if (menuItem == null) return menuItem.icon = if (isLinearLayoutManager) ContextCompat.getDrawable(requireContext(), R.drawable.ic_grid_layout) else ContextCompat.getDrawable(requireContext(), R.drawable.ic_linear_layout) } }
0
Kotlin
0
0
c39edbcddbcd71be6aeb1f7eeb621c0b061ed295
2,579
Words
Apache License 2.0
domain/learningandworkprogress/src/main/kotlin/uk/gov/justice/digital/hmpps/domain/learningandworkprogress/education/PreviousQualifications.kt
ministryofjustice
653,598,082
false
{"Kotlin": 1309284, "Mustache": 2705, "Dockerfile": 1375}
package uk.gov.justice.digital.hmpps.domain.learningandworkprogress.education import uk.gov.justice.digital.hmpps.domain.learningandworkprogress.induction.KeyAwareDomain import java.time.Instant import java.util.UUID /** * Holds details about a Prisoner's educational qualifications, including where relevant, the grades achieved in each * subject. * * Note that the list of `qualifications` can be empty, but `educationLevel` is mandatory (but only if the Prisoner has * been asked about their education). */ data class PreviousQualifications( val reference: UUID, val prisonNumber: String, val educationLevel: EducationLevel?, val qualifications: List<Qualification>, val createdBy: String?, val createdByDisplayName: String?, val createdAt: Instant?, val createdAtPrison: String, val lastUpdatedBy: String?, val lastUpdatedByDisplayName: String?, val lastUpdatedAt: Instant?, val lastUpdatedAtPrison: String, ) data class Qualification( val reference: UUID?, val subject: String, val level: QualificationLevel, val grade: String, val createdBy: String?, val createdAt: Instant?, val lastUpdatedBy: String?, val lastUpdatedAt: Instant?, ) : KeyAwareDomain { override fun key(): String = "${subject.trim()},$level".uppercase() }
5
Kotlin
0
2
2342be2e0b94c24f8a25bb58b5e0c5964b3af9cd
1,281
hmpps-education-and-work-plan-api
MIT License
app/src/main/java/com/qhy040404/libraryonetap/utils/migration/BaseMigration.kt
qhy040404
484,416,715
false
null
package com.qhy040404.libraryonetap.utils.migration import jonathanfinerty.once.Once abstract class BaseMigration(private val commit: String) { protected abstract val reason: String protected abstract fun migrate() fun doMigration() { if (Once.beenDone(commit)) return migrate() Once.markDone(commit) } }
1
Kotlin
0
9
db5d2cf858f05a03273c5fe1e06944a713842c71
328
Library-One-Tap-Android
Apache License 2.0
app/src/main/java/com/qhy040404/libraryonetap/utils/migration/BaseMigration.kt
qhy040404
484,416,715
false
null
package com.qhy040404.libraryonetap.utils.migration import jonathanfinerty.once.Once abstract class BaseMigration(private val commit: String) { protected abstract val reason: String protected abstract fun migrate() fun doMigration() { if (Once.beenDone(commit)) return migrate() Once.markDone(commit) } }
1
Kotlin
0
9
db5d2cf858f05a03273c5fe1e06944a713842c71
328
Library-One-Tap-Android
Apache License 2.0
app/src/main/java/com/apx6/chipmunk/app/ui/viewholder/AttachViewHolder.kt
volt772
506,075,620
false
{"Kotlin": 305901}
package com.apx6.chipmunk.app.ui.viewholder import androidx.recyclerview.widget.RecyclerView import com.apx6.chipmunk.app.ext.setOnSingleClickListener import com.apx6.chipmunk.databinding.ItemAttachBinding import com.apx6.domain.dto.CmdAttachment class AttachViewHolder( private val binding: ItemAttachBinding, private val deleteAttach: (CmdAttachment) -> Unit ) : RecyclerView.ViewHolder(binding.root) { fun bind(attachment: CmdAttachment) { binding.apply { tvAttachName.text = attachment.name tvAttachSize.text = attachment.size.toString() ivDelete.setOnSingleClickListener { deleteAttach.invoke(attachment) } } } }
0
Kotlin
0
0
c3d4a20422090153b40f9542bbc51a3368750034
723
chipmunk
Apache License 2.0