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
plugins/kotlin/code-insight/postfix-templates/test/org/jetbrains/kotlin/idea/k2/codeInsight/postfix/test/AbstractKotlinPostfixTemplateTest.kt
mdaniel
196,571,905
false
{"Text": 9369, "INI": 518, "YAML": 419, "Ant Build System": 11, "Batchfile": 34, "Dockerfile": 9, "Shell": 633, "Markdown": 741, "Ignore List": 143, "Git Revision List": 1, "Git Attributes": 11, "EditorConfig": 260, "XML": 7809, "SVG": 4412, "Kotlin": 58074, "Java": 83551, "HTML": 3783, "Java Properties": 215, "Gradle": 449, "Maven POM": 95, "JavaScript": 228, "CSS": 79, "JSON": 1472, "JFlex": 33, "Makefile": 5, "Diff": 137, "XSLT": 113, "Gradle Kotlin DSL": 676, "Groovy": 3156, "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": 48, "Python": 17005, "C": 110, "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": 192, "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": 16, "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-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.k2.codeInsight.postfix.test import org.jetbrains.kotlin.idea.base.plugin.KotlinPluginMode import org.jetbrains.kotlin.idea.codeInsight.postfix.AbstractKotlinPostfixTemplateTestBase abstract class AbstractK2PostfixTemplateTest : AbstractKotlinPostfixTemplateTestBase() { override val pluginMode: KotlinPluginMode get() = KotlinPluginMode.K2 }
1
null
1
1
da982277a1db650154baf710b44f43a4b167413c
511
intellij-community
Apache License 2.0
app/src/main/java/com/example/bancodigital/data/repository/transaction/TransactionDataSourceImpl.kt
DEV-GUS-AGO
836,022,574
false
{"Kotlin": 141785}
package com.example.bancodigital.data.repository.transaction import com.example.bancodigital.data.model.Transaction import com.example.bancodigital.util.FirebaseHelper import com.google.firebase.database.* import javax.inject.Inject import kotlin.coroutines.suspendCoroutine class TransactionDataSourceImpl @Inject constructor( database: FirebaseDatabase ) : TransactionDataSource { private val transactionReference = database.reference .child("transaction") .child(FirebaseHelper.getUserId()) override suspend fun saveTransaction(transaction: Transaction) { return suspendCoroutine { continuation -> transactionReference .child(transaction.id) .setValue(transaction).addOnCompleteListener { task -> if (task.isSuccessful) { val dateReference = transactionReference .child(transaction.id) .child("date") dateReference.setValue(ServerValue.TIMESTAMP) continuation.resumeWith(Result.success(Unit)) } else { task.exception?.let { continuation.resumeWith(Result.failure(it)) } } } } } override suspend fun getTransactions(): List<Transaction> { return suspendCoroutine { continuation -> transactionReference.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { val transactions = mutableListOf<Transaction>() for (ds in snapshot.children) { val transaction = ds.getValue(Transaction::class.java) transaction?.let { transactions.add(it) } } continuation.resumeWith(Result.success(transactions)) } override fun onCancelled(error: DatabaseError) { error.toException().let { continuation.resumeWith(Result.failure(it)) } } }) } } }
0
Kotlin
0
0
cd8ee534b2152035a81579a019d5f567916775ee
2,268
Banco-Digital
The Unlicense
app/src/main/java/com/canwar/rawgvideogames/viewmodel/ViewModelFactory.kt
azisanw19
615,401,824
false
null
package com.canwar.rawgvideogames.viewmodel import android.content.Context import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.canwar.rawgvideogames.di.Injection class ViewModelFactory(private val context: Context) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(HomeViewModel::class.java)) { @Suppress("UNCHECKED_CAST") return HomeViewModel(Injection.provideRepository(context)) as T } else if (modelClass.isAssignableFrom(DetailViewModel::class.java)) { @Suppress("UNCHECKED_CAST") return DetailViewModel(Injection.provideRepository(context)) as T } else if (modelClass.isAssignableFrom(FavoriteViewModel::class.java)) { @Suppress("UNCHECKED_CAST") return FavoriteViewModel(Injection.provideRepository(context)) as T } throw IllegalArgumentException("Unknown ViewModel Class") } }
0
Kotlin
0
0
8000116eef443de053172361c5c24bbf64af76d3
1,023
RAWG-Video-Games
MIT License
libs/console/src/commonMain/kotlin/com/attafitamim/seer/libs/console/PlatformLogger.kt
tamimattafi
281,893,883
false
{"Kotlin": 9301, "Ruby": 3216}
package com.attafitamim.seer.libs.console import com.attafitamim.seer.libs.core.model.LogLevel expect fun log(level: LogLevel, tag: String, message: String)
1
Kotlin
0
1
b60d8b9b6a78fb1a4fd2bb8dc6b2a8913ab178fe
159
seer
Apache License 2.0
app/src/main/java/com/tejpratapsingh/recyclercalendaractivity/MainActivity.kt
tejpratap46
232,281,186
false
null
package com.tejpratapsingh.recyclercalendaractivity import android.content.Intent import android.os.Bundle import android.widget.LinearLayout import androidx.appcompat.app.AppCompatActivity import com.tejpratapsingh.recyclercalendaractivity.horizontal.HorizontalCalendarActivity import com.tejpratapsingh.recyclercalendaractivity.simple.InfiniteRecyclerCalendarActivity import com.tejpratapsingh.recyclercalendaractivity.simple.SimpleRecyclerCalendarActivity import com.tejpratapsingh.recyclercalendaractivity.vertical.VerticalCalendarActivity import com.tejpratapsingh.recyclercalendaractivity.viewpager.ViewPagerCalendarActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val layoutWeekCalendar: LinearLayout = findViewById(R.id.layoutWeekCalendarActivity); layoutWeekCalendar.setOnClickListener { val intent: Intent = Intent(this@MainActivity, HorizontalCalendarActivity::class.java) startActivity(intent) } val layoutMonthCalendar: LinearLayout = findViewById(R.id.layoutMonthCalendarActivity); layoutMonthCalendar.setOnClickListener { val intent: Intent = Intent(this@MainActivity, VerticalCalendarActivity::class.java) startActivity(intent) } val layoutPageCalendar: LinearLayout = findViewById(R.id.layoutPageCalendarActivity); layoutPageCalendar.setOnClickListener { val intent: Intent = Intent(this@MainActivity, ViewPagerCalendarActivity::class.java) startActivity(intent) } val layoutSimpleCalendar: LinearLayout = findViewById(R.id.layoutSimpleCalendarActivity); layoutSimpleCalendar.setOnClickListener { val intent: Intent = Intent(this@MainActivity, SimpleRecyclerCalendarActivity::class.java) startActivity(intent) } val layoutInfiniteCalendar: LinearLayout = findViewById(R.id.layoutInfiniteCalendarActivity); layoutInfiniteCalendar.setOnClickListener { val intent: Intent = Intent(this@MainActivity, InfiniteRecyclerCalendarActivity::class.java) startActivity(intent) } } }
0
Kotlin
10
98
e35596e321244fa92bd4b1d61aff07c044d3fa17
2,334
RecyclerCalendarAndroid
MIT License
app/src/main/java/com/example/finalproject/RestaurantTopFragment.kt
jadamcda
733,744,991
false
{"Kotlin": 55324}
package com.example.finalproject import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.StaggeredGridLayoutManager class RestaurantTopFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val view = inflater.inflate(R.layout.fragment_restaraunt_top, container, false) val rViewModel = ViewModelProvider(this).get(RestaurantViewModel::class.java) val imagesRecycler = view.findViewById<RecyclerView>(R.id.imagesRecycler) imagesRecycler.setHasFixedSize(true) val layout = StaggeredGridLayoutManager(1, LinearLayoutManager.HORIZONTAL) imagesRecycler.layoutManager = layout // val imagesList : ArrayList<String> = rViewModel.thisRestaurant.images // // val imagesAdapter = ImagesAdapter(imagesList) // imagesRecycler.adapter = imagesAdapter return view } }
0
Kotlin
0
0
d2e4dedbc6ffd697b05435be21a9513281869566
1,281
FinalProject
Apache License 2.0
lib/src/test/kotlin/stack/LockFreeStackTests.kt
therain7
771,223,970
false
{"Kotlin": 8333}
package stack import org.jetbrains.kotlinx.lincheck.annotations.Operation import org.jetbrains.kotlinx.lincheck.check import org.jetbrains.kotlinx.lincheck.strategy.managed.modelchecking.ModelCheckingOptions import org.junit.jupiter.api.Test class SequentialIntStack : Stack<Int> { private val stack = ArrayDeque<Int>() override fun top() = stack.firstOrNull() override fun pop() = stack.removeFirstOrNull() override fun push(value: Int) = stack.addFirst(value) } class LockFreeStackTest { private val stack = LockFreeStack<Int>() @Operation fun top() = stack.top() @Operation fun push(value: Int) = stack.push(value) @Operation fun pop() = stack.pop() @Test fun test() = ModelCheckingOptions() .sequentialSpecification(SequentialIntStack::class.java) .checkObstructionFreedom(true) .check(this::class) }
0
Kotlin
0
0
319625671023508d92b3ae83b5e881d63b6300bd
909
lockfree-stack
MIT License
app/src/main/java/org/xtimms/ridebus/ui/routes/details/stop/base/BaseStopItem.kt
ridebus-by
379,109,231
false
null
package org.xtimms.ridebus.ui.routes.details.stop.base import eu.davidea.flexibleadapter.items.AbstractHeaderItem import eu.davidea.flexibleadapter.items.AbstractSectionableItem import org.xtimms.ridebus.data.database.entity.Stop abstract class BaseStopItem<T : BaseStopHolder, H : AbstractHeaderItem<*>>( val stop: Stop, header: H? = null ) : AbstractSectionableItem<T, H?>(header) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other is BaseStopItem<*, *>) { return stop.stopId!! == other.stop.stopId!! } return false } override fun hashCode(): Int { return stop.stopId!!.hashCode() } }
0
null
0
7
086da0d23cdbb238c35622053568361802ebd2bc
708
ridebus
Apache License 2.0
Oxygen/bukkit/src/main/kotlin/cc/fyre/stark/engine/command/data/parameter/impl/offlineplayer/OfflinePlayerWrapperParameterType.kt
AndyReckt
364,514,997
false
{"Java": 12055418, "Kotlin": 766337, "Shell": 5518}
/* * Copyright (c) 2020. * Created by YoloSanta * Created On 10/22/20, 1:23 AM */ package cc.fyre.stark.engine.command.data.parameter.impl.offlineplayer import cc.fyre.stark.Stark import cc.fyre.stark.engine.command.data.parameter.ParameterType import org.bukkit.Bukkit import org.bukkit.command.CommandSender import org.bukkit.entity.Player import java.util.* class OfflinePlayerWrapperParameterType : ParameterType<OfflinePlayerWrapper> { override fun transform(sender: CommandSender, source: String): OfflinePlayerWrapper { return OfflinePlayerWrapper(source) } override fun tabComplete(sender: Player, flags: Set<String>, source: String): List<String> { val completions = ArrayList<String>() for (player in Bukkit.getOnlinePlayers()) { if (!Stark.instance.visibilityEngine.treatAsOnline(player, sender)) { continue } completions.add(player.name) } return completions } }
1
null
1
1
200501c7eb4aaf5709b4adceb053fee6707173fa
992
Old-Code
Apache License 2.0
woodroid/src/main/java/me/gilo/woodroid/data/api/ProductAttributeTermAPI.kt
syedtehrimabbas
526,100,544
false
null
package me.gilo.woodroid.data.api import me.gilo.woodroid.models.AttributeTerm import retrofit2.Call import retrofit2.http.* interface ProductAttributeTermAPI { @Headers("Content-Type: application/json") @POST("products/attributes/{id}/terms") fun create(@Path("id") attribute_id: Int, @Body body: AttributeTerm): Call<AttributeTerm> @GET("products/attributes/{id}/terms/[term_id]") fun view(@Path("id") attribute_id: Int, @Path("term_id") term_id: Int): Call<AttributeTerm> @GET("products/attributes/{id}/terms") fun list(@Path("id") attribute_id: Int): Call<List<AttributeTerm>> @Headers("Content-Type: application/json") @PUT("products/attributes/{id}/terms/[term_id]") fun update(@Path("id") attribute_id: Int, @Path("term_id") term_id: Int, @Body body: AttributeTerm): Call<AttributeTerm> @DELETE("products/attributes/{id}/terms/[term_id]") fun delete(@Path("id") attribute_id: Int, @Path("term_id") term_id: Int): Call<AttributeTerm> @DELETE("products/attributes/{id}/terms/[term_id]") fun delete(@Path("id") attribute_id: Int, @Path("term_id") term_id: Int, @Query("force") force: Boolean): Call<AttributeTerm> @POST("products/attributes/batch") fun batch(@Body body: AttributeTerm): Call<String> @GET("products/attributes/{id}/terms") fun filter(@Path("id") attribute_id: Int, @QueryMap filter: Map<String, String>): Call<List<AttributeTerm>> }
0
Kotlin
0
0
d3ffe8ce0e11abfde577a4bf4082e60c65d78309
1,436
dida-procop-android
MIT License
app/src/main/java/com/concordium/wallet/ui/bakerdelegation/baker/ChangeBakerStatusBottomSheet.kt
Concordium
750,205,274
false
{"Kotlin": 1615856, "Java": 247867, "HTML": 31416, "CSS": 256}
package com.concordium.wallet.ui.bakerdelegation.baker import android.os.Bundle import android.view.View import android.widget.Button import androidx.annotation.IdRes import androidx.core.view.forEach import androidx.fragment.app.setFragmentResult import com.concordium.wallet.R import com.concordium.wallet.databinding.FragmentChangeBakingStatusBottomSheetBinding import com.google.android.material.bottomsheet.BottomSheetDialogFragment class ChangeBakerStatusBottomSheet : BottomSheetDialogFragment( R.layout.fragment_change_baking_status_bottom_sheet ) { override fun getTheme() = R.style.AppBottomSheetDialogTheme override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val binding = FragmentChangeBakingStatusBottomSheetBinding.bind(view) // Set the click listener for all the buttons. val resultClickListener = View.OnClickListener { clickedView -> setResultAndDismiss(clickedView.id) } binding.root.forEach { childView -> (childView as? Button)?.setOnClickListener(resultClickListener) } binding.stopButton.isEnabled = arguments?.getBoolean(IS_STOP_ENABLED_EXTRA) == true } private fun setResultAndDismiss(@IdRes clickedButtonId: Int) { setFragmentResult(REQUEST_KEY, getResultBundle(clickedButtonId)) dismiss() } companion object { private const val CLICKED_BUTTON_ID_EXTRA = "clicked_button" private const val IS_STOP_ENABLED_EXTRA = "is_stop_enabled" const val REQUEST_KEY = "change_baker_status" private fun getResultBundle(@IdRes clickedButtonId: Int) = Bundle().apply { putInt(CLICKED_BUTTON_ID_EXTRA, clickedButtonId) } /** * @return clicked button ID or null if nothing is clicked. */ @IdRes fun getResult(bundle: Bundle): Int? = bundle .getInt(CLICKED_BUTTON_ID_EXTRA, 0) .takeIf { it != 0 } fun newInstance( isStopEnabled: Boolean, ) = ChangeBakerStatusBottomSheet().apply { arguments = Bundle().apply { putBoolean(IS_STOP_ENABLED_EXTRA, isStopEnabled) } } } }
8
Kotlin
0
1
0539d0282f76ba815046c0f75a2ef32f5aad2bc3
2,300
cryptox-android
Apache License 2.0
app/src/main/java/com/example/findmyrepresentatives/MainActivity.kt
OrenScheer
281,565,226
false
null
package com.example.findmyrepresentatives import android.Manifest import android.content.Intent import android.location.Location import android.os.Bundle import android.os.Looper import android.util.Log import android.view.View import android.view.inputmethod.EditorInfo import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.google.android.gms.common.api.ResolvableApiException import com.google.android.gms.location.* import com.google.android.gms.tasks.Task import com.livinglifetechway.quickpermissions_kotlin.runWithPermissions import kotlinx.android.synthetic.main.activity_main.* import java.util.* import java.util.concurrent.TimeUnit /** * The main activity of the app. * This screen gives users a search box where they can search for their representatives by postal code. * @author <NAME> */ class MainActivity : AppCompatActivity() { private lateinit var fusedLocationProviderClient: FusedLocationProviderClient private lateinit var locationRequest: LocationRequest private lateinit var locationCallback: LocationCallback private var currentLocation: Location? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this) search_box.setOnEditorActionListener{ _, actionId, _ -> when(actionId) { EditorInfo.IME_ACTION_SEND -> { button.performClick() true } else -> false } } } /** * The function called when the search button is pressed by a postal code. * @param view the source of the click */ fun enterPostalCode(view: View) { var postalCode = search_box.text.toString().trim() val errorMessage = findViewById<TextView>(R.id.postal_code_error) if (!Utils.isValidPostalCode(postalCode)) { postal_code_error.text = getString(R.string.postal_code_error, postalCode) postal_code_error.visibility = View.VISIBLE } else { errorMessage.visibility = View.INVISIBLE postalCode = postalCode.replace(" ", "") postalCode = "postcodes/" + postalCode.toUpperCase(Locale.CANADA) val intent = Intent(this, ResultsActivity::class.java).apply { putExtra("query", postalCode) } startActivity(intent) } } /** * The function called when the find location button is pressed. * @param view the source of the click */ fun useLocation(view: View) = runWithPermissions(Manifest.permission.ACCESS_FINE_LOCATION) { try { val locationRequest = LocationRequest().apply { // We will only be requesting the location once interval = TimeUnit.SECONDS.toMillis(60) fastestInterval = TimeUnit.SECONDS.toMillis(30) maxWaitTime = TimeUnit.SECONDS.toMillis(2) priority = LocationRequest.PRIORITY_HIGH_ACCURACY } val builder = LocationSettingsRequest.Builder().addLocationRequest(locationRequest) val client: SettingsClient = LocationServices.getSettingsClient(this) val task: Task<LocationSettingsResponse> = client.checkLocationSettings(builder.build()) // Check if settings allow for access to location task.addOnFailureListener() { exception -> if (exception is ResolvableApiException){ location_error.visibility = View.VISIBLE // Location is probably turned off fusedLocationProviderClient.removeLocationUpdates(locationCallback) // We need to wait for the user to press the button again once location is turned on } } locationCallback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult?) { super.onLocationResult(locationResult) if (locationResult?.lastLocation != null) { currentLocation = locationResult.lastLocation Log.d("current lat", currentLocation!!.latitude.toString()) val intent = Intent(applicationContext, ResultsActivity::class.java).apply { putExtra("query", "representatives/") // URL to use for the API call putExtra("latlong", currentLocation!!.latitude.toString() + ',' + currentLocation!!.longitude.toString()) // Followed by the latitude and longitude as a "point" option } fusedLocationProviderClient.removeLocationUpdates(locationCallback) startActivity(intent) } else { location_error.visibility = View.VISIBLE } } } fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper()) } catch (e: SecurityException) { location_error.visibility = View.VISIBLE // Permission wasn't granted, shouldn't happen using QuickPermissions } } override fun onResume() { super.onResume() currentLocation = null location_error.visibility = View.INVISIBLE postal_code_error.visibility = View.INVISIBLE search_box.setText("") main_layout.requestFocus() } override fun onStop() { super.onStop() if (currentLocation != null) { fusedLocationProviderClient.removeLocationUpdates(locationCallback) // Stop updates just in case they are still active } } override fun onPause() { super.onPause() if (currentLocation != null) { fusedLocationProviderClient.removeLocationUpdates(locationCallback) // Stop updates just in case they are still active } } }
0
Kotlin
0
0
8aa1a42809d47fd1310233b08f216a510cd18b51
6,115
Find-My-Representatives
MIT License
presentation/src/main/java/com/bikcodeh/mubi/presentation/screens/home/HomeScreen.kt
Bikcodeh
553,763,395
false
{"Kotlin": 253338}
package com.bikcodeh.mubi.presentation.screens.home import androidx.compose.foundation.background import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Modifier import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.paging.LoadState import androidx.paging.compose.LazyPagingItems import androidx.paging.compose.collectAsLazyPagingItems import com.bikcodeh.mubi.domain.common.toError import com.bikcodeh.mubi.domain.model.TVShow import com.bikcodeh.mubi.domain.model.TvShowType import com.bikcodeh.mubi.domain.model.getTvShowType import com.bikcodeh.mubi.presentation.components.ErrorScreen import com.bikcodeh.mubi.presentation.components.handleError import com.bikcodeh.mubi.presentation.screens.home.components.HomeTopBar import com.bikcodeh.mubi.presentation.theme.backgroundColor import com.bikcodeh.mubi.presentation.util.ErrorLoadState @ExperimentalLifecycleComposeApi @OptIn(ExperimentalMaterial3Api::class) @Composable fun HomeScreen( homeViewModel: HomeViewModel = hiltViewModel(), onClickItem: (tvShow: TVShow) -> Unit, navigateToProfile: () -> Unit, navigateToSearch: () -> Unit ) { val selectedCTvShowType = rememberSaveable { mutableStateOf<TvShowType>(TvShowType.POPULAR) } LaunchedEffect(key1 = selectedCTvShowType.value) { homeViewModel.searchTvShows(tvShowType = selectedCTvShowType.value) } val tvShows = homeViewModel.tvShows.collectAsStateWithLifecycle().value.collectAsLazyPagingItems() val result = handlePagingResult(tvShows = tvShows) Scaffold( topBar = { HomeTopBar(onSearchClick = navigateToSearch, onProfileClick = navigateToProfile) } ) { paddingValues -> if (result.isRefresh) { result.error?.let { ErrorScreen( messageId = handleError(error = it), modifier = Modifier.fillMaxSize(), onTryAgain = { tvShows.retry() }, displayTryButton = true ) } } else { HomeContent( modifier = Modifier .fillMaxSize() .padding(top = paddingValues.calculateTopPadding()) .background(MaterialTheme.colorScheme.backgroundColor), tvShows = tvShows, onClickItem = onClickItem, errorState = result, isLoading = tvShows.loadState.refresh is LoadState.Loading, selectedCTvShowType = selectedCTvShowType.value, onSelectionChange = { tvShowTypeName -> getTvShowType(tvShowTypeName)?.let { tvShowType -> selectedCTvShowType.value = tvShowType } } ) } } } @Composable fun handlePagingResult( tvShows: LazyPagingItems<TVShow> ): ErrorLoadState { val errorLoadState = ErrorLoadState() tvShows.apply { val stateError = when { loadState.refresh is LoadState.Error -> { errorLoadState.isRefresh = true loadState.refresh as LoadState.Error } loadState.prepend is LoadState.Error -> loadState.prepend as LoadState.Error loadState.append is LoadState.Error -> { errorLoadState.isAppend = true loadState.append as LoadState.Error } else -> null } val error = stateError?.error?.toError() errorLoadState.error = error return errorLoadState } }
0
Kotlin
0
1
25929e402744a1070357ff1af9b05eb7d8bd345c
4,127
Mubi
MIT License
ontrack-kdsl-acceptance/src/test/java/net/nemerosa/ontrack/kdsl/acceptance/tests/jenkins/ACCJenkinsAutoVersioningPostProcessing.kt
nemerosa
19,351,480
false
{"Kotlin": 9640276, "JavaScript": 3232252, "Java": 1029918, "HTML": 507415, "Groovy": 372843, "CSS": 137546, "Less": 35335, "Dockerfile": 6298, "Shell": 5086}
package net.nemerosa.ontrack.kdsl.acceptance.tests.jenkins import net.nemerosa.ontrack.json.asJson import net.nemerosa.ontrack.kdsl.acceptance.tests.av.AbstractACCAutoVersioningTestSupport import net.nemerosa.ontrack.kdsl.acceptance.tests.scm.withMockScmRepository import net.nemerosa.ontrack.kdsl.acceptance.tests.support.uid import net.nemerosa.ontrack.kdsl.spec.configurations.configurations import net.nemerosa.ontrack.kdsl.spec.extension.av.AutoVersioningSourceConfig import net.nemerosa.ontrack.kdsl.spec.extension.av.setAutoVersioningConfig import net.nemerosa.ontrack.kdsl.spec.extension.jenkins.JenkinsConfiguration import net.nemerosa.ontrack.kdsl.spec.extension.jenkins.JenkinsPostProcessingSettings import net.nemerosa.ontrack.kdsl.spec.extension.jenkins.jenkins import net.nemerosa.ontrack.kdsl.spec.extension.jenkins.jenkinsPostProcessing import net.nemerosa.ontrack.kdsl.spec.extension.jenkins.mock.mock import net.nemerosa.ontrack.kdsl.spec.settings.settings import org.junit.jupiter.api.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertTrue class ACCJenkinsAutoVersioningPostProcessing : AbstractACCAutoVersioningTestSupport() { @Test fun `Extra parameters and specific job`() { withMockScmRepository(ontrack) { withAutoVersioning { repositoryFile("gradle.properties") { "some-version = 1.0.0" } // Jenkins config val jenkinsConfigName = uid("j-") ontrack.configurations.jenkins.create( JenkinsConfiguration( name = jenkinsConfigName, url = "http://jenkins", ) ) // Jenkins AV config ontrack.settings.jenkinsPostProcessing.set( JenkinsPostProcessingSettings( config = jenkinsConfigName, job = "/default/pipeline", ) ) // Dependency val depBranch = branchWithPromotion(promotion = "RELEASE") // Sample project to automatically upgrade & post-process using a custom Jenkins job project { branch { configuredForMockRepository() setAutoVersioningConfig( listOf( AutoVersioningSourceConfig( sourceProject = depBranch.project.name, sourceBranch = depBranch.name, sourcePromotion = "RELEASE", targetPath = "gradle.properties", targetProperty = "some-version", postProcessing = "jenkins", postProcessingConfig = mapOf( "dockerImage" to "sample/docker", "dockerCommand" to "sample command", "job" to "/custom/pipeline", "parameters" to listOf( mapOf( "name" to "EXTRA", "value" to "some-value", ) ) ).asJson(), ) ) ) // Creates a new promoted version of the dependency depBranch.apply { build(name = "2.0.0") { promote("RELEASE") } } waitForAutoVersioningCompletion() assertThatMockScmRepository { fileContains("gradle.properties") { "some-version = 2.0.0" } // Checks the Jenkins execution val jenkinsJob = ontrack.jenkins.mock.job(jenkinsConfigName, "/custom/pipeline").jenkinsJob assertNotNull(jenkinsJob, "Custom pipeline found") { job -> assertTrue(job.wasCalled, "Custom pipeline was called") assertEquals("some-value", job.lastBuild.parameters["EXTRA"]) } } } } } } } }
49
Kotlin
25
96
53c2b0df210aec3a2f57ca778d65393a7a95e719
4,809
ontrack
MIT License
internalServer/src/main/java/ru/rpuxa/internalserver/stream/TwoWayMessageStream.kt
rpuxa
162,908,097
false
null
package ru.rpuxa.internalserver.stream import java.io.* import java.util.* import java.util.concurrent.ConcurrentHashMap import kotlin.concurrent.thread typealias MessageListener = (Int, Any?) -> Any? class TwoWayMessageStream(input: InputStream, output: OutputStream) { private var oos: ObjectOutputStream? = null private var ois: ObjectInputStream? = null private val promises: MutableMap<Long, PromiseImpl<*>> = ConcurrentHashMap() private var timeToCheck = TIMEOUT private lateinit var listener: MessageListener var isClosed = false init { try { oos = ObjectOutputStream(output) ois = ObjectInputStream(input) } catch (e: IOException) { e.printStackTrace() close() } } fun open() { if (isClosed) return thread { try { while (!isClosed) { val msg = ois!!.readObject() as Message if (msg != CHECK_MESSAGE) { println("in $msg") val promise = promises.remove(msg.id) if (promise == null) { if (msg.command != ANSWER) thread { val ans = listener(msg.command, msg.data) send(Message(msg.id, ANSWER, ans)) } } else { promise.message(msg.data) } } } } catch (e: Exception) { e.printStackTrace() close() } } thread { try { while (true) { while (!isClosed && timeToCheck > 0) { Thread.sleep(10) timeToCheck -= 10 } if (isClosed) return@thread send(CHECK_MESSAGE) } } catch (e: Exception) { e.printStackTrace() close() } } } fun <T> sendMessage(command: Int, data: Any? = null): Promise<T> { val promise = PromiseImpl<T>() val msg = Message(random.nextLong(), command, data) thread { Thread.sleep(5000) val p = promises.remove(msg.id) ?: return@thread p.timeout() } promises[msg.id] = promise send(msg) return promise } fun onMessage(listener: MessageListener) { this.listener = listener } @Synchronized private fun send(msg: Message) { if (msg != CHECK_MESSAGE) println("out $msg") timeToCheck = 2 * TIMEOUT try { oos!!.writeObject(msg) oos!!.flush() } catch (e: IOException) { e.printStackTrace() close() } timeToCheck = 2 * TIMEOUT } fun close() { isClosed = true try { ois?.close() } catch (e: IOException) { } try { oos?.close() } catch (e: IOException) { } } interface Promise<T> { fun onMessage(callback: (T) -> Unit): Promise<T> fun onTimeout(callback: () -> Unit): Promise<T> } private class PromiseImpl<T> : Promise<T> { var messageCallback: ((T) -> Unit)? = null var timeoutCallback: (() -> Unit)? = null override fun onMessage(callback: (T) -> Unit): Promise<T> { messageCallback = callback return this } override fun onTimeout(callback: () -> Unit): Promise<T> { timeoutCallback = callback return this } fun message(msg: Any?) { @Suppress("UNCHECKED_CAST") messageCallback?.invoke(msg as T) } fun timeout() { timeoutCallback?.invoke() } } private data class Message(val id: Long, val command: Int, val data: Any?) : Serializable companion object { private const val TIMEOUT = 300 private val random = Random() private val CHECK_MESSAGE = Message(-1488228, -1, null) private const val ANSWER = -1 } } object NothingReturn : Serializable
0
Kotlin
2
8
26074194e3df70e673f4595bdbc7090f2ba07593
4,427
SuperWirelessAdb
Apache License 2.0
adil-android/adil/app/src/main/java/com/path_studio/adil/ui/categoryResult/CategoryResultActivity.kt
nadhifikbarw
372,546,196
false
{"Jupyter Notebook": 1105192, "Kotlin": 114743, "Python": 27172, "JavaScript": 14999}
package com.path_studio.adil.ui.categoryResult import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import com.path_studio.adil.databinding.ActivityCategoryResultBinding import com.path_studio.adil.ui.searchResult.SearchResultActivity import com.path_studio.adil.viewModel.ViewModelFactory import java.lang.Integer.parseInt class CategoryResultActivity : AppCompatActivity() { private lateinit var binding: ActivityCategoryResultBinding companion object { const val EXTRA_CATEGORY = "extra_category" } @SuppressLint("NotifyDataSetChanged") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityCategoryResultBinding.inflate(layoutInflater) setContentView(binding.root) val extras = intent.extras if (extras != null) { val categoryName = extras.getString(EXTRA_CATEGORY) //Get Data From Firestore val resultAdapter = CategoriesResultAdapter(this) val factory = ViewModelFactory.getInstance(this) val viewModel = ViewModelProvider(this, factory)[CategoryResultViewModel::class.java] binding.skeletonLayout.showSkeleton() //check if filter by category or year var isYear = true try { val num = parseInt(categoryName.toString()) } catch (e: NumberFormatException) { isYear = false } if(categoryName.toString().length == 4 && isYear){ //show year result viewModel.getLegislationResultByYear(parseInt(categoryName.toString())).observe(this, { legislation -> binding.skeletonLayout.showOriginal() binding.searchLegis.setQuery(categoryName,false) binding.categoryName.text = "Semua peraturan pada tahun ${categoryName.toString()}" val jumlahPeraturan = "${legislation.size} jumlah peraturan" binding.totalCategoryResult.text = jumlahPeraturan resultAdapter.setLegislation(legislation) resultAdapter.notifyDataSetChanged() }) }else if(!isYear){ viewModel.getLegislationResult(categoryName.toString()).observe(this, { legislation -> binding.skeletonLayout.showOriginal() binding.searchLegis.setQuery(categoryName,false) binding.categoryName.text = categoryName.toString() val jumlahPeraturan = "${legislation.size} jumlah peraturan" binding.totalCategoryResult.text = jumlahPeraturan resultAdapter.setLegislation(legislation) resultAdapter.notifyDataSetChanged() }) } with(binding.rvListCategoryResult){ layoutManager = LinearLayoutManager(context) setHasFixedSize(true) adapter = resultAdapter } } binding.searchLegis.setOnQueryTextListener(object : androidx.appcompat.widget.SearchView.OnQueryTextListener{ override fun onQueryTextSubmit(query: String): Boolean { val intent = Intent(this@CategoryResultActivity, SearchResultActivity::class.java) intent.putExtra(SearchResultActivity.EXTRA_QUERY, query) startActivity(intent) return true } override fun onQueryTextChange(newText: String?): Boolean { return true } }) //set back button listener binding.backButton.setOnClickListener { super.onBackPressed() } } }
0
Jupyter Notebook
4
1
4976e6cc97f75fa641af001b05b72f97da2293b0
3,957
adil-monorepo
MIT License
app/src/main/java/com/example/root/mvpdemo_kotlin/entity/Book.kt
jiwenjie
154,255,046
false
{"Gradle": 3, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "INI": 1, "Proguard": 1, "Kotlin": 11, "XML": 15, "Java": 1}
package com.example.root.mvpdemo_kotlin.entity /** * author:Jiwenjie * email:Jiwenjie97@gmail.com * time:2018/10/20 * desc: * version:1.0 */ data class Book(var count: Int, var start: Int, var total: Int, var books: List<BooksBean>) { data class BooksBean(var rating: RatingBean, var subtitle: String, var pubdate: String, var origin_title: String, var image: String, var binding: String, var catalog: String, var images: ImagesBean, var alt: String, var id: String, var publisher: String, var isbn10: String, var isbn13: String, var title: String, var url: String, var alt_title: String, var author_intro: String, var summary: String, var price: String, var author: List<String>, var tags: List<TagsBean>, var translator: List<String>) { data class RatingBean(var max: Int, var numRaters: Int, var average: String, var min: Int) data class ImagesBean(var small: String, var large: String, var medium: String) data class TagsBean(var count: Int, var name: String, var title: String) } }
0
Kotlin
0
1
d937c133fc31338c949b96ba091262b8150c9331
1,292
MVPDemo_Kotlin
Apache License 2.0
lib/src/test/kotlin/com/grappenmaker/mappings/Common.kt
770grappenmaker
705,037,045
false
{"Kotlin": 187067}
package com.grappenmaker.mappings private val testsClassLoader = (object {}).javaClass.classLoader fun String.getResource() = testsClassLoader.getResourceAsStream(this)?.use { it.readBytes() }?.decodeToString() ?: error("Could not find resource $this")
0
Kotlin
2
8
053b931959490da59eebf9705db9f290ac5a3012
257
mappings-util
MIT License
kotlin-mui-icons/src/main/generated/mui/icons/material/RequestPageRounded.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/RequestPageRounded") @file:JsNonModule package mui.icons.material @JsName("default") external val RequestPageRounded: SvgIconComponent
10
Kotlin
145
983
7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35
218
kotlin-wrappers
Apache License 2.0
app/src/main/java/com/mindvalley/mindvalleyapp/common/Constants.kt
ishtian-revee
828,630,879
false
{"Kotlin": 105571}
package com.mindvalley.mindvalleyapp.common object Constants { const val BASE_URL = "https://pastebin.com/raw/" const val DATABASE_NAME = "mindvalley.db" const val MAX_ITEM_PER_ROW = 6 const val MAX_CATEGORY_COLUMN_COUNT = 2 }
0
Kotlin
0
0
554b3791541c11f394523e269be7cebe978cf058
243
mindvalley-coding-challenge
MIT License
telegram-bot-bumblebee-core/src/main/kotlin/com/github/bumblebee/security/PrivilegedCommandBeanPostProcessor.kt
denzelby
46,003,534
false
null
package com.github.bumblebee.security import com.github.bumblebee.bot.consumer.UpdateHandler import com.github.bumblebee.security.exception.UnprivilegedExecutionException import com.github.bumblebee.security.roles.service.UserRolesService import com.github.bumblebee.util.logger import com.github.telegram.domain.Update import org.springframework.aop.MethodBeforeAdvice import org.springframework.aop.framework.ProxyFactory import org.springframework.beans.BeansException import org.springframework.beans.factory.config.BeanPostProcessor import org.springframework.stereotype.Component import java.lang.reflect.Method import java.util.* @Component class PrivilegedCommandBeanPostProcessor(private val rolesService: UserRolesService) : BeanPostProcessor { private val beans = HashMap<String, Class<*>>() private val updateHandlerMethod: Method = UpdateHandler::class.java.methods.first() @Throws(BeansException::class) override fun postProcessBeforeInitialization(bean: Any, beanName: String): Any { val clazz = bean.javaClass if (clazz.isAnnotationPresent(PrivilegedCommand::class.java)) { if (!UpdateHandler::class.java.isAssignableFrom(clazz)) { throw IllegalStateException(clazz.name + "is not an UpdateHandler") } beans[beanName] = clazz } return bean } @Throws(BeansException::class) override fun postProcessAfterInitialization(bean: Any, beanName: String): Any { val clazz = beans[beanName] ?: return bean log.info("Instantiating proxy for {}", clazz) return with(ProxyFactory(bean)) { addAdvice(MethodBeforeAdvice { method, args, target -> if (updateHandlerMethod == method) { val update = args[0] as Update val role = (clazz.getAnnotation(PrivilegedCommand::class.java) as PrivilegedCommand).role ensurePrivilege(target, update, role) } }) proxy } } private fun ensurePrivilege(bean: Any?, update: Update, role: UserRole) { val userId = update.message?.from?.id log.info("Executing privileged from: {}", userId) if (userId == null || !rolesService.hasPrivilege(userId, role)) { (bean as? UnauthorizedRequestAware)?.onUnauthorizedRequest(update) throw UnprivilegedExecutionException("Role '$role' required. User id: $userId") } } companion object { private val log = logger<PrivilegedCommandBeanPostProcessor>() } }
1
Kotlin
6
2
5a89784f5d042839bf6ce4cf3562d2cf14bbae2a
2,590
telegram-bot-bumblebee
MIT License
app/src/main/java/com/goda/marvel/domain/characterList/CharacterListInteractor.kt
gehadfatah
228,142,732
false
null
package com.goda.marvel.domain.characterList import com.goda.marvel.common.mapNetworkErrors import com.goda.marvel.model.Character import com.goda.marvel.model.CharacterRepository import com.goda.marvel.model.charactersRepositoryDep import io.reactivex.Single const val LIMIT_Character_LIST = 10 const val API_KEY = "<KEY>" class CharacterListInteractor(private val characterRepository: CharacterRepository = charactersRepositoryDep) : CharacterListUseCases { override fun getCharactersListBy(page: Int): Single<List<Character>> { return characterRepository.getCharacterList(page, LIMIT_Character_LIST, API_KEY) .mapNetworkErrors() .map { response -> response.data.characters} } }
0
Kotlin
0
0
b4a9593a5ec3dd100c815657c52a34b044ca3358
735
MarvelGodaApp
Apache License 2.0
plugins/kotlin/idea/tests/testData/inspectionsLocal/convertTwoComparisonsToRangeCheck/gtDouble.kt
ingokegel
72,937,917
true
null
// PROBLEM: none // WITH_STDLIB fun foo(bar: Int) { bar > 0.0 && 10.0 >= bar<caret> }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
89
intellij-community
Apache License 2.0
projects/workforce-allocations-to-delius/src/integrationTest/kotlin/uk/gov/justice/digital/hmpps/ProbationRecordIntegrationTest.kt
ministryofjustice
500,855,647
false
{"Kotlin": 3111491, "HTML": 50736, "D2": 27334, "Ruby": 22747, "Shell": 12351, "SCSS": 5590, "JavaScript": 2998, "HCL": 2712, "Dockerfile": 2103}
package uk.gov.justice.digital.hmpps import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.equalTo import org.hamcrest.Matchers.hasItems import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status import uk.gov.justice.digital.hmpps.api.model.* import uk.gov.justice.digital.hmpps.data.generator.PersonGenerator import uk.gov.justice.digital.hmpps.data.generator.StaffGenerator import uk.gov.justice.digital.hmpps.test.MockMvcExtensions.contentAsJson import uk.gov.justice.digital.hmpps.test.MockMvcExtensions.withToken import java.time.LocalDate @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @AutoConfigureMockMvc class ProbationRecordIntegrationTest { @Autowired lateinit var mockMvc: MockMvc @Test fun `get probation record unauthorised`() { mockMvc.perform(get("/allocation-demand/N452321/1/probation-record")) .andExpect(status().isUnauthorized) } @Test fun `get probation record no results`() { mockMvc.perform(get("/allocation-demand/N452321/1/probation-record").withToken()) .andExpect(status().isNotFound) } @Test fun `get probation record successful retrieval of active and inactive events`() { val person = PersonGenerator.DEFAULT val eventNumber = "2" val staff = StaffGenerator.STAFF_FOR_INACTIVE_EVENT val pr = mockMvc.perform(get("/allocation-demand/${person.crn}/$eventNumber/probation-record").withToken()) .andExpect(status().is2xxSuccessful) .andReturn().response.contentAsJson<ProbationRecord>() assertNotNull(pr) assertThat(pr.crn, equalTo(person.crn)) assertThat(pr.name, equalTo(person.name())) assertThat(pr.event.number, equalTo(eventNumber)) val sentence = PrSentence("Sentenced - In Custody", "12 Months", LocalDate.now().minusDays(2), null) val offences = listOf( PrOffence("A main offence", true), PrOffence("An additional offence", false) ) val event = PrEvent(sentence, offences) assertThat(pr.activeEvents, hasItems(event)) assertThat( pr.inactiveEvents, hasItems(event.copy(manager = StaffMember(staff.code, staff.name(), grade = staff.grade()))) ) } }
3
Kotlin
0
2
d0c94f043b3b9d21aa3015e5f76b2462c473e76b
2,767
hmpps-probation-integration-services
MIT License
app/src/main/java/eput/android/ui/widgets/ArrayPreference.kt
ni9l
495,534,282
false
null
package eput.android.ui.widgets import android.content.Context import android.util.AttributeSet import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.LinearLayout import android.widget.Spinner import androidx.appcompat.content.res.AppCompatResources import androidx.appcompat.widget.LinearLayoutCompat import androidx.core.view.children import androidx.fragment.app.FragmentManager import com.google.android.material.shape.MaterialShapeDrawable import com.google.android.material.shape.ShapeAppearanceModel import com.google.android.material.textview.MaterialTextView import eput.android.R import eput.android.db.CustomizedPreference import eput.android.instantiatePreference import eput.android.setPreferenceProperty import eput.protocol.BaseItem import eput.protocol.properties.ArrayProperty class ArrayPreference : LinearLayoutCompat, Preference { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) private val itemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected( parent: AdapterView<*>, view: View, position: Int, id: Long ) { setSelected(position) container.children.forEach { if (it is Preference) it.onSetUpComplete() } } override fun onNothingSelected(parent: AdapterView<*>) { // Ignore } } private lateinit var fragmentManager: FragmentManager private lateinit var title: MaterialTextView private lateinit var spinner: Spinner private lateinit var container: LinearLayout private var selectedProfile = 0 private var property: ArrayProperty? = null private var displayLanguage: String? = null private var uiConfig: List<CustomizedPreference> = listOf() private var hideOnDisable: Boolean = false private fun setUp( titleView: MaterialTextView, spinnerView: Spinner, containerView: LinearLayout, fragmentManager: FragmentManager, hideOnDisable: Boolean ) { this.hideOnDisable = hideOnDisable this.fragmentManager = fragmentManager title = titleView spinner = spinnerView container = containerView val typedValue = TypedValue() val theme = context.theme theme.resolveAttribute(R.attr.backgroundColor, typedValue, true) val backgroundColor = AppCompatResources.getColorStateList(context, typedValue.resourceId) theme.resolveAttribute(R.attr.colorOnBackground, typedValue, true) val borderColor = AppCompatResources.getColorStateList(context, typedValue.resourceId) val model = ShapeAppearanceModel.builder( context, R.style.ShapeAppearance_MaterialComponents_MediumComponent, 0) .build() val drawable = MaterialShapeDrawable(model) drawable.fillColor = backgroundColor drawable.setStrokeTint(borderColor) drawable.strokeWidth = context.resources.getDimension(R.dimen.border_width) background = drawable } override fun setProperty(property: BaseItem, displayLanguage: String?) { isEnabled = true visibility = VISIBLE val prop = property as ArrayProperty this.property = prop this.displayLanguage = displayLanguage title.text = prop.getDisplayName(displayLanguage) if (prop.profileCount > 0) { for (p in prop.getProfile(0)) { instantiatePreference( p, uiConfig, container, displayLanguage, hideOnDisable, fragmentManager ) { } } } val items = (0 until prop.profileCount).map { context.getString(R.string.profile_name, it + 1) } val adapter = ArrayAdapter(context, R.layout.entry_text_list, items) spinner.adapter = adapter spinner.onItemSelectedListener = itemSelectedListener } override fun clearProperty() { property = null title.text = "" spinner.onItemSelectedListener = null spinner.adapter = null container.children.forEach { if (it is Preference) it.clearProperty() } container.removeAllViews() } override fun setEnabled(enabled: Boolean) { super.setEnabled(enabled) title.isEnabled = enabled spinner.isEnabled = enabled container.children.forEach { it.isEnabled = enabled } if (enabled) { container.children.forEach { if (it is Preference) it.onSetUpComplete() } } } override fun setEnabled(enabled: Boolean, ids: List<String>) { if (property?.id in ids) { isEnabled = enabled if (hideOnDisable) { visibility = if (enabled) VISIBLE else GONE } } } override fun onSetUpComplete() { container.children.forEach { if (it is Preference) it.onSetUpComplete() } } fun setUiConfig(uiConfig: List<CustomizedPreference>) { this.uiConfig = uiConfig } private fun setSelected(index: Int) { if (!isEnabled) return property?.let { if (-1 < index && index < it.profileCount) { selectedProfile = index container.children.forEachIndexed { viewIndex, view -> if (view is Preference) { view.clearProperty() val prop = it.getProfile(index)[viewIndex] setPreferenceProperty(view, prop, uiConfig, displayLanguage) } } } } } companion object { fun get( parent: ViewGroup, property: BaseItem, displayLanguage: String?, hideOnDisable: Boolean, fragmentManager: FragmentManager, uiConfig: List<CustomizedPreference>, ): ArrayPreference { val layout = LayoutInflater.from(parent.context).inflate( R.layout.input_array, parent, false ) as ArrayPreference val title = layout.findViewById<MaterialTextView>(R.id.title) val spinner = layout.findViewById<Spinner>(R.id.spinner) val container = layout.findViewById<LinearLayout>(R.id.container) layout.setUp(title, spinner, container, fragmentManager, hideOnDisable) layout.setUiConfig(uiConfig) layout.setProperty(property, displayLanguage) return layout } } }
0
Kotlin
0
0
8b47fc09309dccbde9dd1ca968223b6c671f31c2
7,024
eput-android
MIT License
app/src/main/kotlin/dev/aaa1115910/bv/viewmodel/search/SearchInputViewModel.kt
aaa1115910
571,702,700
false
null
package dev.aaa1115910.bv.viewmodel.search import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dev.aaa1115910.biliapi.BiliApi import dev.aaa1115910.biliapi.entity.search.Hotword import dev.aaa1115910.biliapi.entity.search.KeywordSuggest import dev.aaa1115910.bv.BVApp import dev.aaa1115910.bv.dao.AppDatabase import dev.aaa1115910.bv.entity.db.SearchHistoryDB import dev.aaa1115910.bv.util.fInfo import dev.aaa1115910.bv.util.toast import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import mu.KotlinLogging import java.util.Date class SearchInputViewModel( private val db: AppDatabase = BVApp.getAppDatabase() ) : ViewModel() { private val logger = KotlinLogging.logger { } var keyword by mutableStateOf("") val hotwords = mutableStateListOf<Hotword>() val suggests = mutableStateListOf<KeywordSuggest.Result.Tag>() val searchHistories = mutableStateListOf<SearchHistoryDB>() init { updateHotwords() loadSearchHistories() } private fun updateHotwords() { logger.fInfo { "Update hotwords" } viewModelScope.launch(Dispatchers.Default) { runCatching { val hotwordData = BiliApi.getHotwords( limit = 50 ).getResponseData() logger.debug { "Find hotwords: ${hotwordData.trending.list}" } hotwords.addAll(hotwordData.trending.list) }.onFailure { withContext(Dispatchers.Main) { "bilibili 热搜加载失败".toast(BVApp.context) } } } } fun updateSuggests() { logger.fInfo { "Update search suggests with '$keyword'" } viewModelScope.launch(Dispatchers.Default) { runCatching { val keywordSuggest = BiliApi.getKeywordSuggest(keyword) logger.debug { "Find suggests: ${keywordSuggest.result}" } suggests.clear() suggests.addAll(keywordSuggest.suggests) }.onFailure { withContext(Dispatchers.Main) { "bilibili 搜索建议加载失败".toast(BVApp.context) } } } } private fun loadSearchHistories() { logger.fInfo { "Load search histories" } viewModelScope.launch(Dispatchers.Default) { //当第一次调用时,可能会出现异常 IllegalStateException: Reading a state that was created after the snapshot was taken or in a snapshot that has not yet been applied runCatching { searchHistories.clear() } runCatching { searchHistories.addAll(db.searchHistoryDao().getHistories(20)) logger.fInfo { "Load search histories finish, size: ${searchHistories.size}" } } } } fun addSearchHistory(keyword: String) { logger.fInfo { "Add search history: $keyword" } viewModelScope.launch(Dispatchers.Default) { db.searchHistoryDao().findHistory(keyword)?.let { history -> logger.fInfo { "Search history $keyword already exist" } history.searchDate = Date() db.searchHistoryDao().update(history) } ?: let { logger.fInfo { "Insert new search history $keyword" } val history = SearchHistoryDB(keyword = keyword) db.searchHistoryDao().insert(history) } loadSearchHistories() } } }
21
Kotlin
95
812
f4bdfb9f59f265c2d9e8c9ad99a58b1050885582
3,700
bv
MIT License
app/src/main/java/app/coinverse/feed/models/FeedViewEffects.kt
kumarsubramanir
243,884,635
true
{"Kotlin": 268176}
package app.coinverse.feed.models import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import app.coinverse.feed.models.FeedViewEffectType.* import app.coinverse.utils.FeedType import app.coinverse.utils.UserActionType /** View state effects for content feeds */ class _FeedViewEffects( val _signIn: MutableLiveData<SignInEffect> = MutableLiveData(), val _notifyItemChanged: MutableLiveData<NotifyItemChangedEffect> = MutableLiveData(), val _contentLoadingIds: HashSet<String> = hashSetOf(), val _enableSwipeToRefresh: MutableLiveData<EnableSwipeToRefreshEffect> = MutableLiveData(), val _swipeToRefresh: MutableLiveData<SwipeToRefreshEffect> = MutableLiveData(), val _contentSwiped: MutableLiveData<ContentSwipedEffect> = MutableLiveData(), val _snackBar: MutableLiveData<SnackBarEffect> = MutableLiveData(), val _shareContentIntent: MutableLiveData<ShareContentIntentEffect> = MutableLiveData(), val _openContentSourceIntent: MutableLiveData<OpenContentSourceIntentEffect> = MutableLiveData(), val _screenEmpty: MutableLiveData<ScreenEmptyEffect> = MutableLiveData(), val _updateAds: MutableLiveData<UpdateAdsEffect> = MutableLiveData()) class FeedViewEffects(_effects: _FeedViewEffects) { val signIn: LiveData<SignInEffect> = _effects._signIn val notifyItemChanged: LiveData<NotifyItemChangedEffect> = _effects._notifyItemChanged val contentLoadingIds: HashSet<String> = _effects._contentLoadingIds val enableSwipeToRefresh: LiveData<EnableSwipeToRefreshEffect> = _effects._enableSwipeToRefresh val swipeToRefresh: LiveData<SwipeToRefreshEffect> = _effects._swipeToRefresh val contentSwiped: LiveData<ContentSwipedEffect> = _effects._contentSwiped val snackBar: LiveData<SnackBarEffect> = _effects._snackBar val shareContentIntent: LiveData<ShareContentIntentEffect> = _effects._shareContentIntent val openContentSourceIntent: LiveData<OpenContentSourceIntentEffect> = _effects._openContentSourceIntent val screenEmpty: LiveData<ScreenEmptyEffect> = _effects._screenEmpty val updateAds: LiveData<UpdateAdsEffect> = _effects._updateAds } sealed class FeedViewEffectType { data class SignInEffect(val toSignIn: Boolean) : FeedViewEffectType() data class NotifyItemChangedEffect(val position: Int) : FeedViewEffectType() data class EnableSwipeToRefreshEffect(val isEnabled: Boolean) : FeedViewEffectType() data class SwipeToRefreshEffect(val isEnabled: Boolean) : FeedViewEffectType() data class ContentSwipedEffect(val feedType: FeedType, val actionType: UserActionType, val position: Int) : FeedViewEffectType() data class SnackBarEffect(val text: String) : FeedViewEffectType() data class ShareContentIntentEffect( val contentRequest: LiveData<Content> = MutableLiveData()) : FeedViewEffectType() data class OpenContentSourceIntentEffect(val url: String) : FeedViewEffectType() data class ScreenEmptyEffect(val isEmpty: Boolean) : FeedViewEffectType() class UpdateAdsEffect : FeedViewEffectType() }
0
null
0
0
870b22ed48676bc01201f975419988ca58760b91
3,152
Coinverse
Apache License 2.0
src/main/kotlin/com/lucaguiss/haikyuuapi/facade/PersonFacade.kt
lucasguiss
378,271,807
false
null
package com.lucaguiss.haikyuuapi.facade import com.lucaguiss.haikyuuapi.api.dto.CreatePersonDTO import com.lucaguiss.haikyuuapi.model.PersonModel import com.lucaguiss.haikyuuapi.service.PersonService import com.lucaguiss.haikyuuapi.service.SchoolService import org.springframework.stereotype.Service @Service class PersonFacade( private val personService: PersonService, private val schoolService: SchoolService ) { fun createPerson(dto: CreatePersonDTO): PersonModel { val school = schoolService.findById(dto.school) if (school !== null) { return personService.createPerson(dto) } throw Exception("No school found by the informed id!") } }
0
Kotlin
0
1
39c52932fc6758e8456537eec42de36029f97994
703
haikyuu-api
MIT License
app/src/main/kotlin/com/example/octodroid/views/components/ViewPagerAdapter.kt
rejasupotaro
29,092,522
false
null
package com.example.octodroid.views.components import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentStatePagerAdapter import java.util.ArrayList class ViewPagerAdapter(fragmentManager: FragmentManager) : FragmentStatePagerAdapter(fragmentManager) { private val fragments = ArrayList<Fragment>() private val titles = ArrayList<String>() fun addFragment(fragment: Fragment, title: String) { fragments.add(fragment) titles.add(title) } override fun getItem(position: Int): Fragment { return fragments[position] } override fun getCount(): Int { return fragments.size } override fun getPageTitle(position: Int): CharSequence { return titles[position] } }
6
null
14
92
e4af7cb485bd2335f55633fabcb822e8dee6a52d
810
octodroid
MIT License
expandinglayout/src/main/java/io/github/grakhell/expandinglayout/ExpandState.kt
grakhell
421,805,586
false
{"Kotlin": 37208}
package io.github.grakhell.expandinglayout /* Copyright 2022 <NAME>. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import androidx.annotation.IntDef @Retention(AnnotationRetention.SOURCE) @IntDef(EXPANDED, EXPANDING, COLLAPSING, COLLAPSED, FIXED_SIZE) annotation class ExpandState const val EXPANDED = 0 const val EXPANDING = 1 const val COLLAPSING = 2 const val COLLAPSED = 3 const val FIXED_SIZE = 4
0
Kotlin
0
0
a9591e1f2de9638f79e13139f5f0bcba87079198
885
ExpandingLayout
Apache License 2.0
src/main/kotlin/ar/edu/utn/frba/tacs/tp/api/herocardsgame/mapper/CharacterMapper.kt
tacs-2021-1c-tp-hero-cards
358,787,857
false
null
package ar.edu.utn.frba.tacs.tp.api.herocardsgame.mapper import ar.edu.utn.frba.tacs.tp.api.herocardsgame.integration.client.api.* import ar.edu.utn.frba.tacs.tp.api.herocardsgame.models.game.character.* import org.springframework.stereotype.Component @Component class CharacterMapper { fun map(characterApi: CharacterApi) = Character( characterApi.id!!, characterApi.name!!, mapPowerstats(characterApi.powerstats!!), mapBiography(characterApi.biography!!), mapAppearance(characterApi.appearance!!), mapWork(characterApi.work!!), mapConnections(characterApi.connections!!) ) private fun mapPowerstats(powerstatsApi: PowerstatsApi) = Powerstats( powerstatsApi.intelligence, powerstatsApi.strength, powerstatsApi.speed, powerstatsApi.durability, powerstatsApi.power, powerstatsApi.combat ) private fun mapBiography(biographyApi: BiographyApi) = Biography( biographyApi.fullName, biographyApi.alterEgos, biographyApi.aliases, biographyApi.placeOfBirth, biographyApi.firstAppearance, biographyApi.publisher, biographyApi.alignment ) private fun mapAppearance(appearanceApi: AppearanceApi) = Appearance( appearanceApi.gender, appearanceApi.race, appearanceApi.height, appearanceApi.weight, appearanceApi.eyeColor, appearanceApi.hairColor ) private fun mapWork(workApi: WorkApi) = Work(workApi.occupation, workApi.base) private fun mapConnections(connectionsApi: ConnectionsApi) = Connections( connectionsApi.groupAffiliation, connectionsApi.relatives, ) }
20
null
1
1
5ddb882bfdef41c04eaca7a68afacbb2999457bb
1,898
hero-cards-game
MIT License
examples/listOfCounters/src/main/kotlin/com/brianegan/bansa/listOfCounters/BansaAdapter.kt
brianegan
47,591,925
false
null
package com.brianegan.bansa.listOfCounters import trikita.anvil.RenderableAdapter class BansaAdapter<M, VM>(var models: List<M>, val mapModelToViewModel: (M) -> VM, val r: RenderableAdapter.Item<VM>) : RenderableAdapter() { override fun getCount(): Int { return models.size } override fun getItem(position: Int): VM { return mapModelToViewModel(models[position]) } override fun view(pos: Int) { r.view(pos, this.getItem(pos)); } fun update(newModels: List<M>): BansaAdapter<M, VM> { if (models.equals(newModels).not()) { this.models = newModels; notifyDataSetChanged() } return this } }
4
Kotlin
29
442
ffb606ad2aefa58cac08e9daee26b6767b03186b
697
bansa
MIT License
quizview/src/main/java/com/chaturaloka/quizview/QuizView.kt
subbramanil
186,014,079
false
null
package com.chaturaloka.quizview import android.content.Context import android.util.AttributeSet import android.util.Log import android.view.Gravity import android.view.LayoutInflater import android.widget.LinearLayout import android.widget.RadioButton import android.widget.RadioGroup import androidx.appcompat.widget.AppCompatTextView import androidx.core.content.ContextCompat import androidx.core.view.iterator class QuizView(context: Context, attrs: AttributeSet) : LinearLayout(context, attrs) { private lateinit var mAnswerWeightsArray: Array<out CharSequence> private var mChosenAnswerIndex: Int = 0 private lateinit var mAnswerWeights: MutableList<Int> private var mEqualWeight: Boolean private var mRevealAnswer: Boolean private var mCorrectAnswerIndex: Int private val TAG: String = QuizView::javaClass.name private var mAnswersSet: Array<out CharSequence>? = null private var mQuizQuestion: String? = null private var mNumAnswers: Int = 0 var callback: QuizCallback? = null init { orientation = VERTICAL gravity = Gravity.CENTER context.theme.obtainStyledAttributes( attrs, R.styleable.QuizView, 0, 0 ).apply { try { mNumAnswers = getInteger(R.styleable.QuizView_numAnswers, 0) mCorrectAnswerIndex = getInteger(R.styleable.QuizView_correctAnswer, 0) mQuizQuestion = getString(R.styleable.QuizView_quizQuestion) mAnswersSet = getTextArray(R.styleable.QuizView_answerSet) mRevealAnswer = getBoolean(R.styleable.QuizView_revealAnswer, false) mEqualWeight = getBoolean(R.styleable.QuizView_equalWeight, false) if (!mEqualWeight) { mAnswerWeightsArray = getTextArray(R.styleable.QuizView_answerWeights) } } finally { recycle() } if (!mEqualWeight) { Log.d(TAG, "List of Weights: ${mAnswerWeightsArray.asList()}") mAnswerWeights = mutableListOf() for (answerText in mAnswerWeightsArray.asList()) { Log.d(TAG, "Adding: $answerText") mAnswerWeights.add(answerText.toString().toInt()) } Log.d(TAG, "List of Weights: $mAnswerWeights") } } addQuestion() addAnswers() } private fun addQuestion() { val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater val quizQuestionView = inflater .inflate(R.layout.quiz_ques_view_layout, this, false) as AppCompatTextView quizQuestionView.text = mQuizQuestion addView(quizQuestionView) } private fun addAnswers() { val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater val ansGroupView = inflater .inflate(R.layout.quiz_ans_group_view_layout, this, false) as RadioGroup var ansIndex = 1 do { Log.d("QuizView", "Adding Radio button: $ansIndex") val ansView = inflater .inflate(R.layout.quiz_ans_view_layout, this, false) as RadioButton ansView.text = mAnswersSet?.get(ansIndex - 1) ansView.id = ansIndex ansGroupView.addView(ansView) } while (ansIndex++ < mNumAnswers) ansGroupView.setOnCheckedChangeListener { group, checkedId -> run { Log.d(TAG, "Checked Radio Button: $checkedId") if (mRevealAnswer) { mChosenAnswerIndex = checkedId if (mCorrectAnswerIndex == checkedId) { val chosenAnswer = group.findViewById<RadioButton>(mCorrectAnswerIndex) chosenAnswer.setBackgroundColor(ContextCompat.getColor(context, R.color.accent)) } else { clearBackgrounds(group) } callback?.onAnswerChanged(this@QuizView) } } } addView(ansGroupView) } private fun clearBackgrounds(group: RadioGroup?) { group?.iterator()?.forEach { radioButton -> radioButton.setBackgroundColor(ContextCompat.getColor(context, R.color.white)) } } fun getQuestionWeight(): Int { return if (mEqualWeight) { if (isAnsweredCorrectly()) 1 else 0 } else { mAnswerWeights[mChosenAnswerIndex - 1] } } fun isAnsweredCorrectly(): Boolean { return mChosenAnswerIndex == mCorrectAnswerIndex } interface QuizCallback { fun onAnswerChanged(view: QuizView) } }
0
Kotlin
0
0
27c3731b1eb3534add451ae8e21edb075f6446f2
4,803
pop-quiz-view
Apache License 2.0
app/src/main/java/com/currency/currencyconvertermm/CurrencyApp.kt
oianmol
508,191,089
false
null
package com.currency.currencyconvertermm import android.app.Application import androidx.hilt.work.HiltWorkerFactory import androidx.work.* import com.currency.currencyconvertermm.features.currencyconverter.defferable.PeriodicFetchLatestRates import com.currency.domain.CurrencyConverter import dagger.hilt.android.HiltAndroidApp import java.util.concurrent.TimeUnit import javax.inject.Inject @HiltAndroidApp class CurrencyApp : Application(), Configuration.Provider { @Inject lateinit var workerFactory: HiltWorkerFactory override fun getWorkManagerConfiguration() = Configuration.Builder() .setWorkerFactory(workerFactory) .build() override fun onCreate() { super.onCreate() scheduleWork() } private fun scheduleWork() { val constraints = Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .setRequiresBatteryNotLow(true) .setRequiresStorageNotLow(true) .build() PeriodicWorkRequestBuilder<PeriodicFetchLatestRates>( 30, TimeUnit.MINUTES, ).setConstraints(constraints) .build().apply { WorkManager.getInstance(this@CurrencyApp) .enqueueUniquePeriodicWork( CurrencyConverter.KEY_LATEST_PRICES, ExistingPeriodicWorkPolicy.KEEP, this ) } } }
1
Kotlin
1
4
8a152bfe52ea57fb4954f7a27e7d4d3513a42d42
1,488
CurrencyConverter
Apache License 2.0
app/src/main/java/com/example/lumatutorium2/MainActivity.kt
ChristianFigge
874,697,341
false
{"Kotlin": 19433}
package com.example.lumatutorium2 import android.annotation.SuppressLint import android.content.Context import android.content.pm.PackageManager import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import android.location.Location import android.location.LocationListener import android.location.LocationManager import android.os.Bundle import android.os.Handler import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.dp import androidx.core.app.ActivityCompat import com.example.lumatutorium2.ui.theme.LumaTutorium2Theme import java.util.Locale import kotlin.math.pow import kotlin.math.sqrt class MainActivity : ComponentActivity() { private var str_accelData = mutableStateOf("\nNO DATA YET\n") private var str_gyrosData = mutableStateOf("\nNO DATA YET\n") private var str_lightData = mutableStateOf("\nNO DATA YET\n") private var str_magnetData = mutableStateOf("\nNO DATA YET\n") private val SENSOR_TYPES = listOf( Sensor.TYPE_ACCELEROMETER, Sensor.TYPE_GYROSCOPE, Sensor.TYPE_LIGHT, Sensor.TYPE_MAGNETIC_FIELD ) private lateinit var sensorManager : SensorManager private var sensorListeners = mutableListOf<SensorEventListener>() private lateinit var locationManager : LocationManager private val locationProviders = listOf(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER) private var locationListenersAndData = mutableMapOf<String, Pair<LocationListener, MutableState<String>>>() private val locationPermissions = arrayOf( android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION ) private lateinit var locationPermissionRequest : ActivityResultLauncher<Array<String>> private var locationPermissionsGranted : Boolean = true // delayed loop stuff (nur für den "1 per sec" knopf aus der übung): private var handler = Handler() // deprecated af private var runDelayedSensorLoop : Boolean = true private var runnable : Runnable? = null @Composable private fun PrintSensorData(label: String, dataString: MutableState<String>?, modifier: Modifier = Modifier) { Text( text = buildAnnotatedString { withStyle( style = SpanStyle( textDecoration = TextDecoration.Underline ) ) { append("$label:\n") } append("${dataString?.value}") }, textAlign = TextAlign.Center, modifier = modifier.padding(horizontal = 20.dp, vertical = 10.dp) ) } private fun getMagnitude(values : FloatArray): Float { var result : Float = 0.0f values.forEach { result += it.pow(2) } return sqrt(result) } private fun radToDeg(rad : Float): Double { return rad * 180 / Math.PI } private fun createListeners() { // Sensor Listeners anlegen (wichtig: 1 für jeden sensor_type, sonst unregelmäßige readouts) SENSOR_TYPES.forEach { _ -> sensorListeners.add( object : SensorEventListener { override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) { // kann leer sein, muss aber implementiert werden } override fun onSensorChanged(event: SensorEvent?) { when (event?.sensor?.type) { Sensor.TYPE_GYROSCOPE -> { str_gyrosData.value = "X: %.2f deg/s\nY: %.2f deg/s\nZ: %.2f deg/s\nMag: %.2f deg/s".format( radToDeg(event.values[0]), radToDeg(event.values[1]), radToDeg(event.values[2]), radToDeg(getMagnitude(event.values)) ) } Sensor.TYPE_ACCELEROMETER -> { str_accelData.value = "X: %.2f m/s²\nY: %.2f m/s²\nZ: %.2f m/s²\nMag: %.2f m/s²".format( event.values[0], event.values[1], event.values[2], getMagnitude(event.values) ) } Sensor.TYPE_LIGHT -> { str_lightData.value = "\n${event.values[0].toInt()} lx" } Sensor.TYPE_MAGNETIC_FIELD -> { str_magnetData.value = "X: %.2f uT\nY: %.2f uT\nZ: %.2f uT".format( event.values[0], event.values[1], event.values[2] ) } } if(runDelayedSensorLoop) { // unregister nach 1 readout: sensorManager.unregisterListener(this) } } } ) } // Location Listeners & Data als dictionary mit ["provider"] = Pair<Listener, str_Data> locationProviders.forEach { val str_locData = mutableStateOf("NO DATA YET\n") locationListenersAndData[it] = Pair<LocationListener, MutableState<String>>( object : LocationListener { override fun onLocationChanged(location: Location) { //Log.d("Location", "Position:\nLatitude: ${location.latitude}\nLongitude: ${location.longitude}") str_locData.value = "Lat: ${location.latitude}\nLong: ${location.longitude}" } }, str_locData) } } private fun registerSensorListeners(samplingPeriodUs : Int = SensorManager.SENSOR_DELAY_UI) { SENSOR_TYPES.forEachIndexed { idx, type -> sensorManager.registerListener( sensorListeners[idx], sensorManager.getDefaultSensor(type), samplingPeriodUs ) } } private fun unregisterSensorListeners() { sensorListeners.forEach { sensorManager.unregisterListener(it) } } // Nur für Tutorium Aufgabe, in jeder echten App überflüssig: // .registerListener(.., samplingPeriodUs) wird für Werte >200ms scheinbar ignoriert // und das selbe postDelayed skript im Listener.onSensorChanged läuft auch nicht :( // Also workaround mit delayed register & unregister (im Listener) nach dem ersten readout: private fun startDelayedSensorLoop(delayMillis : Long = 1000L) { runnable = object : Runnable { override fun run() { registerSensorListeners() handler.postDelayed(this, delayMillis) // registriere 1 mal pro sekunde neu } } handler.post(runnable as Runnable) } private fun stopDelayedSensorLoop() { runnable?.let { handler.removeCallbacks(it) } } private fun checkLocationPermissions(): Int { locationPermissions.forEach { if (ActivityCompat.checkSelfPermission(this, it) == PackageManager.PERMISSION_DENIED) { return PackageManager.PERMISSION_DENIED } } return PackageManager.PERMISSION_GRANTED } @SuppressLint("MissingPermission") // wird geregelt, Android studio kackt unnötig rum private fun registerLocationListeners(minTimeMs : Long = 1000L) { if(locationPermissionsGranted) { // registriere location listener für GPS & NETWORK: locationListenersAndData.forEach { (provider, listenerAndData) -> listenerAndData.second.value = "Waiting 4 signal ...\n" locationManager.requestLocationUpdates( provider, minTimeMs, 0f, listenerAndData.first ) } } } private fun unregisterLocationListeners() { locationListenersAndData.forEach { (_, listenerAndData) -> locationManager.removeUpdates(listenerAndData.first) } } private fun stopAllReadouts() { stopDelayedSensorLoop() unregisterSensorListeners() unregisterLocationListeners() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Request Launcher definieren: locationPermissionRequest = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions() ) { isGranted: Map<String, @JvmSuppressWildcards Boolean> -> if (isGranted.containsValue(true)) { // Mindestens eine location permission erteilt (coarse oder fine) locationPermissionsGranted = true Log.i("LocPermissions", "Request: Location Permissions granted: $isGranted") } else { // Keine permission erteilt locationPermissionsGranted = false locationListenersAndData.forEach { (_, listenerAndData) -> listenerAndData.second.value = "Standortzugriff verweigert\n(Änderbar in Einstellungen)" } Log.i("LocPermissions", "Request: Location Permissions denied.") } } // TODO shouldShowRequestPermissionRationale(permission) abfragen // s. https://developer.android.com/training/permissions/requesting#allow-system-manage-request-code if(checkLocationPermissions() == PackageManager.PERMISSION_DENIED) { Log.i("LocPermissions", "Check: Location Permissions denied.") locationPermissionRequest.launch(locationPermissions) } else { Log.i("LocPermissions", "Check: Location Permissions granted.") } sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager this.createListeners() enableEdgeToEdge() setContent { LumaTutorium2Theme { Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding -> Column( modifier = Modifier.padding(innerPadding).fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { // SENSOREN Row() { PrintSensorData("Accelerometer", str_accelData) PrintSensorData("Gyroskop", str_gyrosData) } Row() { PrintSensorData("Beleuchtung", str_lightData) PrintSensorData("Magnetfeld", str_magnetData) } // LOCATIONS locationListenersAndData.forEach { (provider, listenerAndData) -> Row() { PrintSensorData( "Position (${provider.uppercase(Locale.ROOT)})", listenerAndData.second ) } } // BUTTONS Row(Modifier.padding(top = 30.dp)) { Button( content = { Text("Fast AF") }, modifier = Modifier.padding(horizontal = 20.dp), onClick = { stopAllReadouts() runDelayedSensorLoop = false registerSensorListeners() registerLocationListeners(0L) } ) Button( content = { Text("1 per Sec") }, modifier = Modifier.padding(horizontal = 20.dp), onClick = { stopAllReadouts() runDelayedSensorLoop = true startDelayedSensorLoop(1000L) registerLocationListeners(1000L) } ) } Row() { Button( content = { Text("HALT STOP") }, modifier = Modifier.padding(vertical = 20.dp), onClick = { stopAllReadouts() str_accelData.value = "\nSTOPPED\n" str_gyrosData.value = "\nSTOPPED\n" str_lightData.value = "\nSTOPPED\n" str_magnetData.value = "\nSTOPPED\n" if(locationPermissionsGranted) { locationListenersAndData.forEach { (_, listenerAndData) -> listenerAndData.second.value = "STOPPED\n" } } } ) } } } } } } }
0
Kotlin
0
0
d4bcbc0e019366d97f11e7cd49546fb55b0d7ead
15,401
LumaTutorium2
The Unlicense
src/main/kotlin/com/github/xetra11/ck3workbench/app/view/CurrentMainView.kt
cybernetics
324,037,223
true
{"Kotlin": 91034}
package com.github.xetra11.ck3workbench.module.character.view import androidx.compose.runtime.Composable import com.github.xetra11.ck3workbench.app.ViewManager import com.github.xetra11.ck3workbench.app.view.EntryView @Composable fun CurrentMainView() { when (ViewManager.currentMainView()) { ViewManager.View.ENTRY_VIEW -> EntryView() ViewManager.View.DYNASTY_VIEW -> DynastieModuleView() ViewManager.View.CHARACTER_VIEW -> CharacterModuleView() ViewManager.View.CHARACTER_CREATE_VIEW -> CharacterCreateView() } }
0
null
0
0
dbc23838e09f435878ac5ca5a8f6249a34d3ed45
557
CK3-Workbench
MIT License
src/main/kotlin/com/github/xetra11/ck3workbench/app/view/CurrentMainView.kt
cybernetics
324,037,223
true
{"Kotlin": 91034}
package com.github.xetra11.ck3workbench.module.character.view import androidx.compose.runtime.Composable import com.github.xetra11.ck3workbench.app.ViewManager import com.github.xetra11.ck3workbench.app.view.EntryView @Composable fun CurrentMainView() { when (ViewManager.currentMainView()) { ViewManager.View.ENTRY_VIEW -> EntryView() ViewManager.View.DYNASTY_VIEW -> DynastieModuleView() ViewManager.View.CHARACTER_VIEW -> CharacterModuleView() ViewManager.View.CHARACTER_CREATE_VIEW -> CharacterCreateView() } }
0
null
0
0
dbc23838e09f435878ac5ca5a8f6249a34d3ed45
557
CK3-Workbench
MIT License
app/src/main/java/com/samset/workmanager/MainActivity.kt
SamsetDev
153,939,847
false
null
package com.samset.workmanager import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.View import androidx.work.* import java.util.concurrent.TimeUnit import androidx.work.PeriodicWorkRequest import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity(), View.OnClickListener { private var TAG: String = MainActivity::class.java.simpleName private lateinit var workManager: WorkManager private lateinit var timeWorkRequest: OneTimeWorkRequest private lateinit var periodicWorkRequest: PeriodicWorkRequest private var PERIODIC_REQUEST_TAG: String = "periodic_request" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) workManager = WorkManager.getInstance()!! btnstart.setOnClickListener(this) btnstop.setOnClickListener(this) } private fun setupOneTimeWorker() { timeWorkRequest = OneTimeWorkRequest.Builder(MyWorker::class.java)?.build() workManager.enqueue(timeWorkRequest) } private fun setupPeriodicWorker() { val work = PeriodicWorkRequest.Builder(MyWorker::class.java, PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS, TimeUnit.MINUTES, PeriodicWorkRequest.MIN_PERIODIC_FLEX_MILLIS, TimeUnit.MINUTES) periodicWorkRequest = work.build() workManager.enqueue(periodicWorkRequest) } private fun isScheduleWork(tag: String): Boolean { val statuses = workManager.getWorkInfosByTag(tag) if (statuses.get().isEmpty()) return false var running = false for (state in statuses.get()) { running = state.state == WorkInfo.State.RUNNING || state.state == WorkInfo.State.ENQUEUED } return running } override fun onClick(view: View?) { if (view == btnstart) { setupOneTimeWorker() } else if (view == btnstop) { !isScheduleWork(PERIODIC_REQUEST_TAG) setupPeriodicWorker() } } }
0
Kotlin
2
1
06d8120bcd0fe1005ba684a132cdf6c180227eec
2,125
WorkManager-jetpack
Apache License 2.0
server/src/main/kotlin/de/westermann/robots/server/service/ThreadedService.kt
pixix4
130,015,411
false
null
package de.westermann.robots.server.service import de.westermann.robots.server.util.ServiceAlreadyStartedException import de.westermann.robots.datamodel.util.toDashCase import mu.KLogger import kotlin.concurrent.thread import kotlin.jvm.Volatile /** * @author lars */ abstract class ThreadedService( private val daemon:Boolean = true ): Service { abstract val logger: KLogger; val name: String get() = this::class.simpleName?.toDashCase() ?: "robot-service" @Volatile override var running: Boolean = false abstract fun run() private var serviceThread: Thread? = null override fun start() { if (serviceThread != null) { throw ServiceAlreadyStartedException("Cannot start $name twice") } running = true serviceThread = thread(isDaemon = daemon, name = name) { while (running) try { run() } catch (e: Exception) { logger.warn("Unexpected error in thread loop", e) } } } override fun stop() { running = false serviceThread?.interrupt() } }
0
Kotlin
0
0
383475939c2ba1bf95b458edf762e123b10e8509
1,138
Robots
Apache License 2.0
src/main/kotlin/com/cultureshock/madeleine/rest/controller/SignInController.kt
DDD-Community
401,593,410
false
null
package com.cultureshock.madeleine.rest.controller import com.cultureshock.madeleine.rest.RestSupport import com.cultureshock.madeleine.rest.dto.request.SignInRequest import com.cultureshock.madeleine.rest.dto.request.SignOutRequest import com.cultureshock.madeleine.service.user.KakaoAuthService import io.swagger.annotations.Api import io.swagger.annotations.ApiOperation import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Value import org.springframework.http.HttpHeaders import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* import java.net.URI import javax.servlet.http.HttpServletRequest @Api(tags = ["권한"]) @RestController @RequestMapping("/api/v1/auth") class SignInController( @Value("\${kakao.client_id}") private val clientId: String, private val kakaoAuthService: KakaoAuthService ): RestSupport() { companion object { private val log: Logger = LoggerFactory.getLogger(SignInController::class.java) } @PostMapping("/login") @ApiOperation(value="카카오 로그인.POST", notes="[POST]카카오 로그인") fun kakaoSignIn( @RequestBody request: SignInRequest ): ResponseEntity<Any> { return response(kakaoAuthService.kakaoSignIn(request)) } @GetMapping("/kakao/signin") @ApiOperation(value="카카오 로그인.GET", notes="[GET]카카오 로그인 시도 => 회원이 아니면 회원가입까지 진행 => callback") fun kakaoBackendSignPage( ): ResponseEntity<*> { val redirectUrl = "https://kauth.kakao.com/oauth/authorize?client_id=${clientId}&redirect_uri=http://localhost:8080/api/v1/auth/kakao/signin/callback&response_type=code" val uri = URI(redirectUrl) val headers = HttpHeaders() headers.location = uri return ResponseEntity<Any>(headers, HttpStatus.SEE_OTHER) } /* @PostMapping("/signout") @ApiOperation(value="카카오 인증 토큰 해제", notes="") fun kakaoSignOut(@RequestBody request: SignOutRequest): ResponseEntity<Any>{ return response(kakaoAuthService.kakaoSignOut(request)) } */ /* @PostMapping("/kakao/signin") @ApiOperation(value="카카오 로그인.POST", notes="[POST]카카오 로그인") fun kakaoSignIn(@RequestBody request: SignInRequest): ResponseEntity<Any> { return response(kakaoAuthService.kakaoSignIn(request)) } */ /* @GetMapping("/kakao/signin/callback") @ApiOperation(value="카카오 로그인.GET CallBack", notes="[GET]카카오 로그인 callback") fun kakaoBackendSigninCallback(request: HttpServletRequest, @RequestParam("code") code: String): ResponseEntity<*> { return response(kakaoAuthService.kakaoSignIn(SignInRequest(code = code, redirectUri = "http://localhost:8080/api/v1/auth/kakao/signin/callback", agreementMarketingRecv = true))) } */ }
2
Kotlin
1
4
fc07b03adafd42f7c9c11c8e135c197f24182df8
2,832
CultureShock-Server
MIT License
app/src/main/java/com/car2go/endpoint2mock/MainActivity.kt
sharenowTech
93,642,073
false
null
package com.car2go.endpoint2mock import android.os.Bundle import android.support.v7.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* import retrofit.RestAdapter import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers class MainActivity : AppCompatActivity() { private lateinit var githubApi: GithubApi private var subscription: Subscription? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) githubApi = RestAdapter.Builder() .setClient( MockableClient.build("http://${BuildConfig.BUILD_HOST_ADDRESS}") // Assuming that you have something running at this URL .mockWhen { mockToggle.isChecked } .build() ) .setEndpoint("https://api.github.com") .build() .create(GithubApi::class.java) requestButton.setOnClickListener { subscription?.unsubscribe() subscription = githubApi.getRepositories("car2go") .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { repositories -> result.text = repositories.toString() }, { result.text = it.toString() } ) } } override fun onPause() { super.onPause() subscription?.unsubscribe() } }
1
null
1
16
ac1dd5196a20372462ab2f2e0b3aa9f199d3c3c2
1,691
Endpoint2mock
The Unlicense
src/main/kotlin/org/ocpp/client/event/server/request/AuthorizeRequestEvent.kt
NLCProject
494,622,679
false
{"Kotlin": 45823}
package org.ocpp.client.event.server.request import eu.chargetime.ocpp.model.core.AuthorizeRequest import org.springframework.context.ApplicationEvent import java.util.* /** * Event is fired by an incoming authorize request. * * @param sessionIndex . * @param request . * @param source Class where the event has been fired. */ class AuthorizeRequestEvent(source: Any, val sessionIndex: UUID, val request: AuthorizeRequest) : ApplicationEvent(source)
0
Kotlin
0
0
26e0d5608de1daa723ef0f03ffc20e083e497d39
462
OcppClient
ISC License
src/commonTest/kotlin/ru/spbstu/wheels/ExpandoTest.kt
vorpal-research
185,828,983
false
{"Kotlin": 245655}
package ru.spbstu.wheels import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith data class Foo(val i: Int): Expando() { override fun toString(): String { return "{i=$i, $expansion}" } } val Foo.s: String by Expando.lazy { "" } var Foo.ss: String by Expando var Foo.sss: String by Expando class ExpandoTest { @Test fun testSimple() { val foo = Foo(2) assertEquals("", foo.s) foo.ss = "Hello" assertEquals("Hello", foo.ss) assertFailsWith<IllegalStateException> { foo.sss } foo.sss = "World" assertEquals("World", foo.sss) } @Test fun testToString() { val foo = Foo(2) assertEquals("{i=2, }", "$foo") foo.ss = "a" foo.s assertEquals("{i=2, ss=a, s=}", "$foo") } }
0
Kotlin
2
1
389f9c290d496aae3d4f5eaa2a0d4f4863f281c2
862
kotlin-wheels
MIT License
app/src/main/java/com/cyberfanta/talentviewer/presenters/JobActivityPresenter.kt
cyberfanta
389,012,773
false
null
package com.cyberfanta.talentviewer.presenters import com.cyberfanta.talentviewer.models.Jobs interface JobActivityPresenter { //View fun showJob(job: Jobs) fun errorLoadingJob() //Interactor fun getJob(id: String): Jobs? }
0
Kotlin
0
0
fe27f89b97cd3f18306957286eba01a8e9ab8d18
246
TalentViewer
Apache License 2.0
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/bulk/Documentcloud.kt
Tlaster
560,394,734
false
{"Kotlin": 25133302}
package moe.tlaster.icons.vuesax.vuesaxicons.bulk import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import moe.tlaster.icons.vuesax.vuesaxicons.BulkGroup public val BulkGroup.Documentcloud: ImageVector get() { if (_documentcloud != null) { return _documentcloud!! } _documentcloud = Builder(name = "Documentcloud", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF292D32)), stroke = null, fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(20.5f, 10.19f) horizontalLineTo(17.61f) curveTo(15.24f, 10.19f, 13.31f, 8.26f, 13.31f, 5.89f) verticalLineTo(3.0f) curveTo(13.31f, 2.45f, 12.86f, 2.0f, 12.31f, 2.0f) horizontalLineTo(8.07f) curveTo(4.99f, 2.0f, 2.5f, 4.0f, 2.5f, 7.57f) verticalLineTo(16.43f) curveTo(2.5f, 20.0f, 4.99f, 22.0f, 8.07f, 22.0f) horizontalLineTo(15.93f) curveTo(19.01f, 22.0f, 21.5f, 20.0f, 21.5f, 16.43f) verticalLineTo(11.19f) curveTo(21.5f, 10.64f, 21.05f, 10.19f, 20.5f, 10.19f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(15.7997f, 2.21f) curveTo(15.3897f, 1.8f, 14.6797f, 2.08f, 14.6797f, 2.65f) verticalLineTo(6.14f) curveTo(14.6797f, 7.6f, 15.9197f, 8.81f, 17.4297f, 8.81f) curveTo(18.3797f, 8.82f, 19.6997f, 8.82f, 20.8297f, 8.82f) curveTo(21.3997f, 8.82f, 21.6997f, 8.15f, 21.2997f, 7.75f) curveTo(19.8597f, 6.3f, 17.2797f, 3.69f, 15.7997f, 2.21f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(14.7605f, 19.2598f) curveTo(12.4105f, 19.4298f, 12.4105f, 22.8298f, 14.7605f, 22.9998f) horizontalLineTo(20.3205f) curveTo(20.9905f, 22.9998f, 21.6505f, 22.7498f, 22.1405f, 22.2998f) curveTo(23.7905f, 20.8598f, 22.9105f, 17.9798f, 20.7405f, 17.7098f) curveTo(19.9605f, 13.0198f, 13.1805f, 14.7998f, 14.7805f, 19.2698f) } } .build() return _documentcloud!! } private var _documentcloud: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
3,531
VuesaxIcons
MIT License
app/src/main/java/com/ganhuo/app/adpter/brvah/more/NavigationTwoAdapter.kt
robertchar
250,484,237
false
null
package com.ganhuo.app.adpter.brvah.more import android.annotation.SuppressLint import android.view.ViewGroup import android.widget.TextView import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.viewholder.BaseViewHolder import com.ganhuo.app.R import com.ganhuo.app.bean.HotTagBean import com.ganhuo.app.bean.NavigationBean import com.google.android.flexbox.AlignSelf import com.google.android.flexbox.FlexboxLayoutManager class NavigationTwoAdapter(data: MutableList<NavigationBean.Data.Article>?) : BaseQuickAdapter<NavigationBean.Data.Article, BaseViewHolder>(R.layout.item_hot_two, data) { @SuppressLint("WrongConstant") override fun convert(helper: BaseViewHolder, item: NavigationBean.Data.Article) { @Suppress("DEPRECATION") helper.setText(R.id.tv_option, item.title) val textView = helper.getView<TextView>(R.id.tv_option) val lp: ViewGroup.LayoutParams = textView.layoutParams if (lp is FlexboxLayoutManager.LayoutParams) { val fireboxLp = lp as FlexboxLayoutManager.LayoutParams fireboxLp.flexGrow = 1.0f fireboxLp.alignSelf=AlignSelf.FLEX_END } } }
0
Kotlin
0
1
3ce1dedf35d203a5f878fc4b2353d4e112cac8f2
1,200
KotlinGanhuo
Apache License 2.0
app/src/main/java/com/example/project_auction/util/fcm/MyJobService.kt
4538cgy
376,812,255
false
null
package com.example.project_auction.util.fcm import com.firebase.jobdispatcher.JobParameters import com.firebase.jobdispatcher.JobService class MyJobService : JobService() { override fun onStartJob(jobParameters: JobParameters): Boolean { //작업이 실행되기 시작했음을 나타 내기 위해 호출됩니다. // TODO(developer): add long running task here. return false } override fun onStopJob(jobParameters: JobParameters): Boolean { return false //이 메서드는 호출 기회가 있기 전에도 작업 실행을 중지해야한다고 시스템에서 결정한 경우 호출 jobFinished(JobParameters, boolean)됩니다. } companion object { private const val TAG = "MyJobService" } }
1
Kotlin
1
0
ca8352892909aa1516098fbd859705a11630dcdc
646
ProjectAuction
Apache License 2.0
common/src/main/kotlin/org/jetbrains/research/deepbugs/common/ide/quickfixes/FlipFunctionArgumentsQuickFix.kt
JetBrains-Research
146,897,119
false
{"Kotlin": 87528, "JavaScript": 1529, "HTML": 806, "Python": 199}
package org.jetbrains.research.deepbugs.common.ide.quickfixes import com.intellij.codeInsight.intention.PriorityAction import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.research.deepbugs.common.CommonResourceBundle import org.jetbrains.research.deepbugs.common.ide.fus.collectors.counter.DeepBugsCounterCollector abstract class FlipFunctionArgumentsQuickFix<T : PsiElement> : LocalQuickFix, PriorityAction { override fun getName(): String = CommonResourceBundle.message("deepbugs.flip.arguments.quickfix") override fun getPriority(): PriorityAction.Priority = PriorityAction.Priority.HIGH protected abstract fun T.toArguments(): Pair<PsiElement, PsiElement> @Suppress("UNCHECKED_CAST") override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement as? T ?: return val (arg0, arg1) = element.toArguments() arg0.replace(arg1) arg1.replace(arg0) DeepBugsCounterCollector.quickFixApplied(project, "flip.arguments", cancelled = false) } }
7
Kotlin
1
6
8e9b2c0b070baef9bdcbf9159c0fec0ef357b7a7
1,205
DeepBugsPlugin
MIT License
app/src/main/java/com/example/rostermanagementandroidsystem/database/AppDatabase.kt
Lelekhoa1812
837,902,175
false
{"Kotlin": 62774, "JavaScript": 13112}
package com.example.rostermanagementandroidsystem.database import AccountDao import AccountEntity import AppDatabaseCallback import RoleDao import RoleEntity import ShiftDao import ShiftEntity import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase @Database(entities = [RoleEntity::class, AccountEntity::class, ShiftEntity::class], version = 1) abstract class AppDatabase : RoomDatabase() { abstract fun roleDao(): RoleDao abstract fun accountDao(): AccountDao abstract fun shiftDao(): ShiftDao companion object { @Volatile private var INSTANCE: AppDatabase? = null fun getDatabase(context: Context): AppDatabase { return INSTANCE ?: synchronized(this) { val instance = Room.databaseBuilder( context.applicationContext, AppDatabase::class.java, "roster_management_database" ) .addCallback(AppDatabaseCallback()) // Add the callback here .build() INSTANCE = instance instance } } } }
0
Kotlin
0
0
721c4ad4f35c2f50a428660f6632801d839e62fd
1,186
RosterManagement
MIT License
src/main/kotlin/com/youdozi/demo/config/bcrypt/BcryptConfig.kt
youdozi
237,245,042
false
null
package com.youdozi.demo.config.bcrypt import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder import org.springframework.security.crypto.password.PasswordEncoder /** * PasswordEncoder 설정 */ @Configuration class BcryptConfig { @Bean fun passwordEncoder(): PasswordEncoder? { return BCryptPasswordEncoder() } }
0
Kotlin
0
0
d9a1a9f93264bd017c118bb4f29ae8945421d30d
461
spring-boot-rest-kotlin
MIT License
src/main/kotlin/com/zqlite/android/diycode/device/view/notification/NotificationContract.kt
ZhangQinglian
100,032,799
false
null
/* * Copyright 2017 zhangqinglian * * 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.zqlite.android.diycode.device.view.notification import com.zqlite.android.dclib.entiry.Notification import com.zqlite.android.diycode.device.view.imvp.IPresenter import com.zqlite.android.diycode.device.view.imvp.IView /** * Created by scott on 2017/8/21. */ interface NotificationContract { interface Presenter : IPresenter{ fun loadNotification() fun readNotification(notificationId:Int) } interface View: IView<NotificationContract.Presenter>{ fun updateNotification(datas:List<Notification>) } }
0
Kotlin
0
4
1341b52acdf005e5ecdba94c8ded6d31b05f41be
1,183
dcapp
Apache License 2.0
compiler/testData/debug/stepping/lambdaStepInline.kt
prasenjitghose36
258,198,392
true
{"Kotlin": 46593414, "Java": 7626725, "JavaScript": 200386, "HTML": 77284, "Lex": 23805, "TypeScript": 21756, "Groovy": 11196, "CSS": 9270, "Swift": 8589, "Shell": 7220, "Batchfile": 5727, "Ruby": 1300, "Objective-C": 404, "Scala": 80}
// FILE: test.kt inline fun foo(stringMaker: () -> String): String { return stringMaker() } fun box(): String { foo { "OK "} foo { "OK" // Comment } return "OK" } // LINENUMBERS // test.kt:8 // test.kt:4 // test.kt:8 // test.kt:9 // test.kt:4 // test.kt:10 // test.kt:13
1
null
1
2
acced52384c00df5616231fa5ff7e78834871e64
309
kotlin
Apache License 2.0
src/sorting/ShellSorter.kt
chechulnikov
108,676,828
false
null
package sorting class ShellSorter : Sorter { override fun <T : Comparable<T>> ascendingSort(list: MutableList<T>): List<T> { return sort(list, { element, selectedElement -> element.compareTo(selectedElement) > 0 }) } override fun <T : Comparable<T>> descendingSort(list: MutableList<T>): List<T> { return sort(list, { element, selectedElement -> element.compareTo(selectedElement) < 0 }) } private fun <T> sort(list: MutableList<T>, compareFunction: (T, T) -> Boolean): List<T> { var step = list.count() / 2; while (step > 0) { var i: Int = step var j: Int while (i < list.count()) { var selectedElement = list[i] j = i - step while ((j >= 0) && (compareFunction(list[j], selectedElement))) { list[j + step] = list[j] j -= step } list[j + step] = selectedElement; i += 1 } step /= 2; } return list } }
0
Kotlin
0
0
5746dbad19d54f3aa800236a6698031396b5554d
1,108
kotlin-workshop
MIT License
app/src/main/java/com/example/proyectodam/RegistroOperacionActivity.kt
mabmab159
495,255,881
false
null
package com.example.proyectodam import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class RegistroOperacionActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_registro_operacion) } }
0
Kotlin
0
0
7d79f34e4b3782a7967d753f60e263e00a2fb609
331
ProyectoDAM
MIT License
guide/example/example-readme-09.kt
vmishenev
429,008,741
true
{"Kotlin": 61064}
// This file was automatically generated from README.md by Knit tool. Do not edit. package example.exampleReadme09 import arrow.* import arrow.core.* import arrow.fx.coroutines.* import kotlinx.coroutines.* import io.kotest.matchers.collections.* import io.kotest.assertions.* import io.kotest.matchers.* import io.kotest.matchers.types.* import kotlin.coroutines.cancellation.CancellationException import io.kotest.property.* import io.kotest.property.arbitrary.* import arrow.core.test.generators.* import java.io.* @JvmInline value class Content(val body: List<String>) sealed interface FileError @JvmInline value class SecurityError(val msg: String?) : FileError @JvmInline value class FileNotFound(val path: String) : FileError object EmptyPath : FileError { override fun toString() = "EmptyPath" } fun readFile(path: String?): Cont<FileError, Content> = cont { ensureNotNull(path) { EmptyPath } ensure(path.isNotEmpty()) { EmptyPath } try { val lines = File(path).readLines() Content(lines) } catch (e: FileNotFoundException) { shift(FileNotFound(path)) } catch (e: SecurityException) { shift(SecurityError(e.message)) } } fun <A: Job> A.onCancel(f: (CancellationException) -> Unit): A = also { invokeOnCompletion { error -> if (error is CancellationException) f(error) else Unit } } suspend fun test() { val exit = CompletableDeferred<CancellationException>() cont<FileError, Int> { withContext(Dispatchers.IO) { val job = launch { delay(1_000_000) }.onCancel { ce -> require(exit.complete(ce)) } val content = readFile("failure").bind() job.join() content.body.size } }.fold({ e -> e shouldBe FileNotFound("failure") }, { fail("Int can never be the result") }) exit.await().shouldBeInstanceOf<CancellationException>() }
0
null
0
0
8c58a0d677a5fd1fac5a9c8ef6628d9ca30155c2
1,813
Continuation
Apache License 2.0
4436/solution.kt
daily-boj
253,815,781
false
null
fun main(args: Array<out String>) { System.`in`.bufferedReader().lineSequence().joinToString("\n") { val n = it.toLong() val notAppeared = "0123456789".toCharArray().toMutableSet() var curr = n var k = 0 while (notAppeared.isNotEmpty()) { k += 1 for (c in curr.toString()) { notAppeared -= c } curr += n } k.toString() }.let(::println) }
0
Rust
0
12
74294a4628e96a64def885fdcdd9c1444224802c
466
RanolP
The Unlicense
src/main/java/de/vkay/api/tmdb/IncludeLanguages.kt
vkay94
352,665,975
false
null
/* * Copyright 2014 <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 de.vkay.api.tmdb import java.util.* class IncludeLanguages(private vararg val languageCodes: String) { override fun toString(): String = languageCodes.joinToString(separator = ",") { it.lowercase(Locale.ROOT) } companion object { private val DEFAULT = arrayOf("null", "en") val defaults = IncludeLanguages(*DEFAULT) } }
1
Kotlin
1
7
f0aad85f253ab2f8ffa1dd1515ddd98d814480c2
960
TMDb-Kotlin
Apache License 2.0
idea/testData/codeInsight/outOfBlock/FunNoBody.kt
JakeWharton
99,388,807
false
null
// TRUE fun some() = <caret>12
0
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
30
kotlin
Apache License 2.0
plugins/textmate/src/org/jetbrains/plugins/textmate/editor/TextMateEnterHandler.kt
JetBrains
2,489,216
false
null
//package org.jetbrains.plugins.textmate.editor // //import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegate //import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegateAdapter //import com.intellij.openapi.actionSystem.DataContext //import com.intellij.openapi.editor.Editor //import com.intellij.openapi.editor.ex.EditorEx //import com.intellij.psi.PsiDocumentManager //import com.intellij.psi.PsiFile //import org.jetbrains.plugins.textmate.TextMateService //import org.jetbrains.plugins.textmate.language.preferences.IndentAction //import org.jetbrains.plugins.textmate.language.preferences.OnEnterRule //import org.jetbrains.plugins.textmate.psi.TextMateFile // //// todo: consider using this for onEnterRules, instead of TextMateLineIndentProvider //class TextMateEnterHandler : EnterHandlerDelegateAdapter() { // override fun postProcessEnter(file: PsiFile, editor: Editor, dataContext: DataContext): EnterHandlerDelegate.Result { // if (file !is TextMateFile) return super.postProcessEnter(file, editor, dataContext) // // val caretOffset = editor.caretModel.offset // val manager = PsiDocumentManager.getInstance(editor.project!!) // manager.commitDocument(editor.document) // manager.getPsiFile(editor.document) // // val actualScope = TextMateEditorUtils.getCurrentScopeSelector((editor as EditorEx)) ?: return super.postProcessEnter(file, editor, // dataContext) // // val registry = TextMateService.getInstance().preferenceRegistry // val preferencesList = registry.getPreferences(actualScope) // val onEnterRules = preferencesList.mapNotNull { it.onEnterRules }.flatten() // // indent(editor, caretOffset, onEnterRules) // // return super.postProcessEnter(file, editor, dataContext) // } // // private fun indent(editor: Editor, // caretOffset: Int, // onEnterRules: List<OnEnterRule>) { // val document = editor.document // val text = document.text // val lines = text.lines() // val lineNumber = document.getLineNumber(caretOffset) // if (lineNumber <= 0L) return // val lineOffset = document.getLineStartOffset(lineNumber) // if (lineOffset <= 0L) return // val prevLineText = lines[lineNumber - 1] // // for (onEnterRule in onEnterRules){ // val beforeTextPatter = onEnterRule.beforeText.text // if (prevLineText.contains(Regex(beforeTextPatter))) { // when (onEnterRule.action.indent) { // // todo: use com.intellij.openapi.editor.actions.EditorActionUtil.indentLine(com.intellij.openapi.project.Project, com.intellij.openapi.editor.Editor, int, int, int) // IndentAction.INDENT -> editor.document.replaceString(lineOffset, lineOffset, " ") // else -> {} // } // } // } // } //}
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
2,914
intellij-community
Apache License 2.0
app/src/main/java/com/example/reply/data/MailboxType.kt
S-H-U-R-A
751,377,074
false
{"Kotlin": 63041}
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.reply.data /** * Una clase de enumeración para definir diferentes tipos de carpetas o categorías de correo electrónico. */ enum class MailboxType { Inbox, //Bandeja de entrada Drafts, //Borradores Sent, //Enviados Spam, //Correo no deseado }
0
Kotlin
0
0
e0e84a8db6fa1c6e0b52a5b7e00febf6911f06ef
906
Codelab-Adaptive-Desing
Apache License 2.0
app/src/main/java/com/rkbapps/neetflix/SplashActivity.kt
Rajkumarbhakta
603,033,367
false
null
package com.rkbapps.neetflix import android.content.Intent import android.os.Bundle import android.os.Handler import android.os.Looper import androidx.appcompat.app.AppCompatActivity import com.rkbapps.neetflix.activityes.MainActivity class SplashActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) Handler(Looper.getMainLooper()).postDelayed({ val i = Intent(this@SplashActivity, MainActivity::class.java) startActivity(i) finish() }, 3000) } }
0
Kotlin
0
0
9238d6a950cee413962191f6576180fe15c38666
633
Neetflix
Apache License 2.0
css-gg/src/commonMain/kotlin/compose/icons/cssggicons/FormatColor.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36719092}
package compose.icons.cssggicons import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.CssGgIcons public val CssGgIcons.FormatColor: ImageVector get() { if (_formatColor != null) { return _formatColor!! } _formatColor = Builder(name = "FormatColor", 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 = EvenOdd) { moveTo(12.948f, 3.209f) curveTo(12.772f, 2.832f, 12.391f, 2.616f, 12.0f, 2.633f) curveTo(11.609f, 2.617f, 11.228f, 2.833f, 11.052f, 3.209f) lineTo(5.135f, 15.898f) curveTo(4.902f, 16.398f, 5.119f, 16.993f, 5.619f, 17.227f) curveTo(6.12f, 17.46f, 6.715f, 17.244f, 6.948f, 16.743f) lineTo(8.399f, 13.632f) horizontalLineTo(15.601f) lineTo(17.052f, 16.743f) curveTo(17.285f, 17.243f, 17.88f, 17.46f, 18.381f, 17.227f) curveTo(18.881f, 16.993f, 19.098f, 16.398f, 18.865f, 15.898f) lineTo(12.948f, 3.209f) close() moveTo(14.669f, 11.632f) lineTo(12.0f, 5.909f) lineTo(9.331f, 11.632f) horizontalLineTo(14.669f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(6.0f, 19.368f) curveTo(5.448f, 19.368f, 5.0f, 19.816f, 5.0f, 20.368f) curveTo(5.0f, 20.92f, 5.448f, 21.368f, 6.0f, 21.368f) horizontalLineTo(18.0f) curveTo(18.552f, 21.368f, 19.0f, 20.92f, 19.0f, 20.368f) curveTo(19.0f, 19.816f, 18.552f, 19.368f, 18.0f, 19.368f) horizontalLineTo(6.0f) close() } } .build() return _formatColor!! } private var _formatColor: ImageVector? = null
17
Kotlin
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
2,949
compose-icons
MIT License
lib/src/commonMain/kotlin/com/prateekgrover/lib/common.kt
kerry
215,108,844
false
{"Ruby": 3466, "Kotlin": 1956, "Swift": 333}
package com.prateekgrover.lib class Greeting() { fun start() { KNDispatchQueue.sharedInstance.performWorkAsync() } } expect class KNDispatchQueue() { companion object Singleton { val sharedInstance: KNDispatchQueue } fun performWorkAsync() }
2
Ruby
0
0
a024e53f4710fe408df42f0d0ddaf1f4fa093b26
281
CoreKN
Apache License 2.0
src/test/kotlin/io/toolisticon/lib/avro/declaration/SchemaDeclarationTest.kt
toolisticon
493,962,736
false
{"Kotlin": 48684}
package io.toolisticon.lib.avro.declaration import io.toolisticon.lib.avro.AvroKotlinLib import io.toolisticon.lib.avro.TestFixtures import io.toolisticon.lib.avro.TestFixtures.simpleStringValueSchema import io.toolisticon.lib.avro.ext.SchemaExt.writeToDirectory import io.toolisticon.lib.avro.fqn.AvroDeclarationMismatchException import io.toolisticon.lib.avro.fqn.SchemaFqn import org.apache.avro.Schema import org.apache.avro.SchemaBuilder import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatThrownBy import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir import java.io.File import java.nio.file.Files internal class SchemaDeclarationTest { @TempDir private lateinit var tmp: File @Test fun `create contentFqn from fqn and content`() { val namespace = "com.acme.test" val name = "Foo" val fqn = SchemaFqn(namespace, name) val schema = simpleStringValueSchema(namespace, name) val declaration = SchemaDeclaration(fqn, schema) assertThat(declaration.contentFqn).isEqualTo(fqn) assertThat(declaration.verifyPackageConvention()).isTrue assertThat(declaration.name).isEqualTo(name) assertThat(declaration.namespace).isEqualTo(namespace) assertThat(declaration.canonicalName).isEqualTo("$namespace.$name") } @Test fun `create contentFqn from schema`() { val namespace = "com.acme.test" val name = "Foo" val schema = simpleStringValueSchema(namespace, name) val declaration = SchemaDeclaration(schema) assertThat(declaration.contentFqn).isEqualTo(SchemaFqn(namespace,name)) assertThat(declaration.verifyPackageConvention()).isTrue assertThat(declaration.name).isEqualTo(name) assertThat(declaration.namespace).isEqualTo(namespace) assertThat(declaration.canonicalName).isEqualTo("$namespace.$name") } @Test fun `violating package convention`() { val namespace = "com.acme.test" val name = "Foo" val differentLocation = SchemaFqn("foo", "Bar") val schema = simpleStringValueSchema(namespace, name) val declaration = SchemaDeclaration(differentLocation, schema) assertThatThrownBy { declaration.verifyPackageConvention() } .isInstanceOf(AvroDeclarationMismatchException::class.java) } @Test fun `package convention mismatch`() { val namespace = "com.acme.test" val name = "Foo" val fqn = SchemaFqn(namespace+".foo", name) val schema = simpleStringValueSchema(namespace, name) val declaration = SchemaDeclaration(fqn, schema) assertThat(declaration.contentFqn.namespace).isEqualTo(namespace) assertThat(declaration.contentFqn.name).isEqualTo(name) assertThat(declaration.contentFqn.fileExtension).isEqualTo(AvroKotlinLib.EXTENSION_SCHEMA) assertThatThrownBy { declaration.verifyPackageConvention(true) } .isInstanceOf(AvroDeclarationMismatchException::class.java) } @Test fun `load from file`() { val schemaFoo = TestFixtures.schemaFoo val schemaBar = TestFixtures.schemaBar schemaFoo.writeToDirectory(tmp) schemaBar.writeToDirectory(tmp) Files.walk(tmp.toPath()) .forEach { println(it) } } }
1
Kotlin
0
2
49276914d5e89b8875703f6caef7c19f98162366
3,187
avro-kotlin
Apache License 2.0
app/src/main/java/com/dreamsoftware/tvnexa/ui/components/ChannelLogo.kt
sergio11
328,373,511
false
{"Kotlin": 586066}
package com.dreamsoftware.tvnexa.ui.components import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.tv.material3.Border import androidx.tv.material3.ExperimentalTvMaterial3Api import androidx.tv.material3.MaterialTheme @OptIn(ExperimentalTvMaterial3Api::class) @Composable fun ChannelLogo( modifier: Modifier = Modifier, size: Dp, logo: String?, borderColor: Color? = null ) { with(MaterialTheme.colorScheme) { CommonAsyncImage( modifier = modifier .size(size) .clip(CircleShape) .background(onPrimaryContainer) .border(2.dp, borderColor ?: onPrimaryContainer, CircleShape), context = LocalContext.current, contentScale = ContentScale.Fit, imageUrl = logo ) } }
0
Kotlin
0
1
30fb84765276b1afcadc27b0ce8ffc15155decc4
1,290
tvnexa_androidtv
Apache License 2.0
android/app/src/main/kotlin/com/example/studio/MainActivity.kt
TerminalStudio
285,940,840
false
null
package com.example.studio import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
10
53
c9d36e04e8a96bf21f941eb1336f60a632903d5b
123
studio
Apache License 2.0
kotlin/src/main/kotlin/com/laioffer/Kotlin基础/pkg18_解构/HiKotlin10.kt
yuanuscfighton
632,030,844
false
{"Kotlin": 1005102, "Java": 675082}
package Kotlin基础.pkg18_解构 fun main() { // 只读类型是协变的,因为它只用于从集合中获取数据,而不会修改集合中的数据 val s = listOf("a", "b") val s2: List<Any> = s }
0
Kotlin
0
0
b03a297acdf094f56c5d43f99eb29afa35146109
135
SiberianHusky
Apache License 2.0
app/src/main/java/com/jarvis/weatherj/data/local/entity/CurrentConditionEntity.kt
johanforce
569,695,306
false
{"Kotlin": 212462, "Java": 10587}
package com.jarvis.weatherj.data.local.entity import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "current") data class CurrentConditionEntity( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") val id: Int = 0, @ColumnInfo(name = "feels_like_c") val feelsLikeC: String? = null, @ColumnInfo(name = "feels_like_f") val feelsLikeF: String? = null, @ColumnInfo(name = "cloudcover") val cloudcover: String? = null, @ColumnInfo(name = "humidity") val humidity: String? = null, @ColumnInfo(name = "local_obs_date_time") val localObsDateTime: String? = null, @ColumnInfo(name = "observation_time") val observationTime: String? = null, @ColumnInfo(name = "precip_inches") val precipInches: String? = null, @ColumnInfo(name = "precip_mm") val precipMM: String? = null, @ColumnInfo(name = "pressure") val pressure: String? = null, @ColumnInfo(name = "pressure_inches") val pressureInches: String? = null, @ColumnInfo(name = "temp_c") val tempC: String? = null, @ColumnInfo(name = "temp_f") val tempF: String? = null, @ColumnInfo(name = "uv_index") val uvIndex: String? = null, @ColumnInfo(name = "visibility") val visibility: String? = null, @ColumnInfo(name = "visibility_miles") val visibilityMiles: String? = null, @ColumnInfo(name = "weather_code") val weatherCode: String? = null, @ColumnInfo(name = "winddir_16_point") val winddir16Point: String? = null, @ColumnInfo(name = "winddir_degree") val winddirDegree: String? = null, @ColumnInfo(name = "windspeed_kmph") val windspeedKmph: String? = null, @ColumnInfo(name = "windspeed_miles") val windspeedMiles: String? = null )
0
Kotlin
0
1
e4aea6a097f3085305574c79985385919b343c90
1,811
aether
MIT License
app/src/main/java/com/saranomy/nolauncher/AppItem.kt
sakkke
577,204,035
false
null
package com.saranomy.nolauncher import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.Image import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.interaction.MutableInteractionSource 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.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp data class AppItem( val name: String, val packageName: String ) : Comparable<AppItem> { override fun compareTo(other: AppItem): Int { return name.compareTo(other.name, true) } @OptIn(ExperimentalFoundationApi::class) @Composable fun Display(onClick: () -> Unit, onLongClick: () -> Unit) { Row( modifier = Modifier .fillMaxWidth() .combinedClickable( interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = onClick, onLongClick = onLongClick ) .padding(16.dp), verticalAlignment = Alignment.CenterVertically ) { MainActivity.icons[packageName]?.let { Image( bitmap = it, contentDescription = null, modifier = Modifier.size(32.dp) ) } Text( text = name, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(horizontal = 12.dp) ) } } }
0
Kotlin
0
2
dc8fc9977bd3144c57ceb7469a86874bb9dd1d3e
1,967
AmoledLauncher
Apache License 2.0
datalogger/src/main/java/org/obd/graphs/bl/query/DragRacingQueryStrategy.kt
tzebrowski
326,375,780
false
{"Kotlin": 594209}
/** * Copyright 2019-2023, <NAME> * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package org.obd.graphs.bl.query import org.obd.graphs.bl.drag.dragRacingResultRegistry internal class DragRacingQueryStrategy : QueryStrategy( mutableSetOf( dragRacingResultRegistry.getEngineRpmPID(), dragRacingResultRegistry.getVehicleSpeedPID() ) )
1
Kotlin
0
4
45d1dcdf40c0f83ad5309c7bae055ba25ae5bcfa
1,114
ObdGraphs
Apache License 2.0
src/main/kotlin/ru/krindra/vknorthtypes/groups/GroupsLongPollSettings.kt
kravandir
745,597,090
false
{"Kotlin": 633233}
package ru.krindra.vknorthtypes.groups import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class GroupsLongPollSettings ( @SerialName("events") val events: GroupsLongPollEvents, @SerialName("is_enabled") val isEnabled: Boolean, @SerialName("api_version") val apiVersion: String? = null, )
0
Kotlin
0
0
508d2d1d59c4606a99af60b924c6509cfec6ef6c
352
VkNorthTypes
MIT License
Mobile Development/app/src/main/java/com/bangkit/skinskan/data/source/remote/response/ResultResponse.kt
emnopal
373,780,058
true
{"Jupyter Notebook": 13020201, "Kotlin": 46548, "Python": 2961, "Dockerfile": 805}
package com.bangkit.skinskan.data.source.remote.response import com.google.gson.annotations.SerializedName data class ResultResponse( @field:SerializedName("prediction") val predictionResult: Int? = null, )
0
Jupyter Notebook
0
1
b0642cb64d916a01101e35844fbf244bafdea4a2
217
bangkit-final-project
MIT License
mui-kotlin/src/jsMain/kotlin/mui/material/OutlinedInput.mui.kt
karakum-team
387,062,541
false
{"Kotlin": 3060426, "TypeScript": 2249, "HTML": 724, "CSS": 86}
// Automatically generated - do not modify! @file:Suppress( "NESTED_CLASS_IN_EXTERNAL_INTERFACE", ) package mui.material import seskar.js.JsValue import seskar.js.JsVirtual import web.cssom.ClassName @JsVirtual sealed external interface MuiOutlinedInput { companion object { @JsValue("MuiOutlinedInput-root") val root: ClassName @JsValue("MuiOutlinedInput-colorSecondary") val colorSecondary: ClassName @JsValue("MuiOutlinedInput-adornedStart") val adornedStart: ClassName @JsValue("MuiOutlinedInput-adornedEnd") val adornedEnd: ClassName @JsValue("MuiOutlinedInput-sizeSmall") val sizeSmall: ClassName @JsValue("MuiOutlinedInput-multiline") val multiline: ClassName @JsValue("MuiOutlinedInput-notchedOutline") val notchedOutline: ClassName @JsValue("MuiOutlinedInput-input") val input: ClassName @JsValue("MuiOutlinedInput-inputSizeSmall") val inputSizeSmall: ClassName @JsValue("MuiOutlinedInput-inputMultiline") val inputMultiline: ClassName @JsValue("MuiOutlinedInput-inputAdornedStart") val inputAdornedStart: ClassName @JsValue("MuiOutlinedInput-inputAdornedEnd") val inputAdornedEnd: ClassName @JsValue("MuiOutlinedInput-inputTypeSearch") val inputTypeSearch: ClassName } }
0
Kotlin
5
35
83952a79ffff62f5409461a2928102d0ff95d86b
1,417
mui-kotlin
Apache License 2.0
src/main/kotlin/moe/irony/simplepc/parser/Combinator.kt
kokoro-aya
398,263,839
false
null
package moe.irony.simplepc.parser import moe.irony.simplepc.instances.Either import moe.irony.simplepc.instances.Option import moe.irony.simplepc.instances.Result import moe.irony.simplepc.parser.Parser.Companion.`*≻` import moe.irony.simplepc.parser.Parser.Companion.`≺$≻` import moe.irony.simplepc.parser.Parser.Companion.`≺*` import moe.irony.simplepc.parser.Parser.Companion.`≺*≻` import moe.irony.simplepc.parser.Parser.Companion.`≺|≻` import moe.irony.simplepc.parser.Parser.Companion.`≻≻=` import moe.irony.simplepc.parser.Parser.Companion.`≻≻` import moe.irony.simplepc.parser.Parser.Companion.attempt import moe.irony.simplepc.parser.Parser.Companion.combine import moe.irony.simplepc.parser.Parser.Companion.pure import moe.irony.simplepc.types.HKT import moe.irony.simplepc.types.Tuple0 import moe.irony.simplepc.utils.* // Basic Parsers fun identity(): Parser<Char> = Parser { Trampoline.done( if (it.hasNext()) Result.Success(Context(it.next(), true, it.peek())) else Result.Failure(FailContext(it, consumed = false, halted = false))) } fun eof(): Parser<Char> = TODO("Not yet implemented") fun satisfy(pred: (Char) -> Boolean): Parser<Char> = Parser.narrow( identity() `≻≻=` { if (pred.invoke(it)) Parser.pure(it) else Parser.empty() } ) // Text Parsers fun anyChar(): Parser<Char> = satisfy { true } fun isDigit(): Parser<Char> = satisfy { it.isDigit() } fun isLetter(): Parser<Char> = satisfy { it.isLetter() } fun matchChar(c: Char): Parser<Char> = satisfy { it == c } fun space(): Parser<Char> = satisfy { it.isWhitespace() } fun matchString(str: String): HKT<Parser<*>, String> = if (str.isEmpty()) Parser.pure(str) // 这里不能用Parser.empty()否则会出现None导致整个调用栈被污染 else matchChar(str.first()) `≻≻=` { c -> matchString(str.drop(1)) `≻≻=` { cs -> Parser.pure(c + cs) } } fun matchStringStrict(str: String): HKT<Parser<*>, String> = // 如果我想要匹配一个字符串但不需要用到它的值 if (str.isEmpty()) Parser.empty() else matchChar(str.first()) `≻≻=` { c -> matchString(str.drop(1)) `≻≻=` { cs -> Parser.pure(c + cs) } } fun anyString(): HKT<Parser<*>, String> = (List<Char>::constructString) `≺$≻` many1(isLetter()) fun asterisk(p: HKT<Parser<*>, String>): HKT<Parser<*>, String> = tryParse(p) `≺|≻` pure("") // Combinators @Deprecated("Use asterisk() instead") fun <A, B, C> tryAndThen(p: HKT<Parser<*>, A>, q: HKT<Parser<*>, B>, f: (A, B) -> C, or: (B) -> C): HKT<Parser<*>, C> = (p `≻≻=` { x -> q `≻≻=` { y -> pure(f(x, y)) }}) `≺|≻` (q `≻≻=` { pure(or(it)) }) fun <A> tryParse(p: HKT<Parser<*>, A>): HKT<Parser<*>, A> = attempt(p) // FIXED fun <A> choice(desc: String, ps: List<HKT<Parser<*>, A>>): HKT<Parser<*>, A> = ps.reduce(Parser.Companion::alt) fun <A, B, C> between(open: HKT<Parser<*>, B>, p: HKT<Parser<*>, A>, close: HKT<Parser<*>, C>): HKT<Parser<*>, A> = open `*≻` p `≺*` close fun <A> orElse(p: HKT<Parser<*>, A>, opt: A): HKT<Parser<*>, A> = p `≺|≻` pure(opt) fun <A> optional(p: HKT<Parser<*>, A>): HKT<Parser<*>, Option<A>> = TODO("no idea how to implement") // orElse(empty(), Option.narrow(Option.liftM1(Option.Some(p)))) fun <A> tryDiscard(p: HKT<Parser<*>, A>): HKT<Parser<*>, Tuple0> = p `≻≻=` { _ -> pure(Tuple0) } `≺|≻` pure(Tuple0) fun <A> replicate(n: Int, p: HKT<Parser<*>, A>): HKT<Parser<*>, List<A>> = if (n <= 0) Parser.pure(listOf<A>()) else Parser.narrow(p) `≻≻=` { a -> recur { replicate(n - 1, p) } `≻≻=` { ax -> Parser.pure(cons<A>()(a)(ax)) } } fun <A, B> runLoop(a: A, f: (A) -> HKT<Parser<*>, Either<B, A>>): HKT<Parser<*>, B> = f.invoke(a) `≻≻=` { ei -> when (ei) { is Either.Left -> pure(ei.a) is Either.Right -> recur { runLoop(ei.b, f) } } } fun <A> many(p: HKT<Parser<*>, A>): HKT<Parser<*>, List<A>> = recur { many1(p) } `≺|≻` Parser.pure(listOf()) fun <A> many1(p: HKT<Parser<*>, A>): HKT<Parser<*>, List<A>> = cons<A>() `≺$≻` p `≺*≻` recur { many(p) } infix fun <A, S> (HKT<Parser<*>, A>).sepBy(s: HKT<Parser<*>, S>): HKT<Parser<*>, List<A>> = recur { this sepBy1 s } `≺|≻` Parser.pure(listOf()) infix fun <A, S> (HKT<Parser<*>, A>).sepBy1(s: HKT<Parser<*>, S>): HKT<Parser<*>, List<A>> = this `≻≻=` { a -> recur { many(s `≻≻` this) `≻≻=` { xs -> pure(cons<A>()(a)(xs)) } } } fun <A> skipMany(p: HKT<Parser<*>, A>): HKT<Parser<*>, Tuple0> = Parser.pure(Tuple0) `≺*` recur { many(p) } fun <A> skipMany1(p: HKT<Parser<*>, A>): HKT<Parser<*>, Tuple0> = p `*≻` recur { skipMany(p) } infix fun <A, B> (HKT<Parser<*>, A>).endBy(sep: HKT<Parser<*>, B>): HKT<Parser<*>, List<A>> = recur { many(this `≻≻=` { a -> sep `≻≻=` { _ -> pure(a) } }) } infix fun <A, B> (HKT<Parser<*>, A>).endBy1(sep: HKT<Parser<*>, B>): HKT<Parser<*>, List<A>> = recur { many1(this `≻≻=` { a -> sep `≻≻=` { _ -> pure(a) } }) } infix fun <A, B> (HKT<Parser<*>, A>).endByOptional(sep: HKT<Parser<*>, B>): HKT<Parser<*>, List<A>> = recur { this endByOptional1 sep } `≺|≻` pure(listOf<A>()) infix fun <A, B> (HKT<Parser<*>, A>).endByOptional1(sep: HKT<Parser<*>, B>): HKT<Parser<*>, List<A>> = this `≻≻=` { x -> sep `≻≻=` { _ -> recur { this endByOptional sep } `≻≻=` { xs -> pure(cons<A>()(x)(xs)) } } `≺|≻` pure(listOf(x)) } fun <A> chainl(p: HKT<Parser<*>, A>, op: HKT<Parser<*>, (A, A) -> A>, x: A): HKT<Parser<*>, A> = chainl1(p, op) `≺|≻` pure(x) fun <A> chainl1(p: HKT<Parser<*>, A>, op: HKT<Parser<*>, (A, A) -> A>): HKT<Parser<*>, A> = p `≻≻=` { x -> yCombinator<A, HKT<Parser<*>, A>> { recur -> { x -> (op `≻≻=` { f -> p `≻≻=` { y -> recur(f(x, y)) } }) `≺|≻` Parser.pure(x) } }(x) } fun <A> notFollowedBy(p: HKT<Parser<*>, A>): HKT<Parser<*>, Tuple0> = TODO("Not yet implemented") fun <A, B> manyTill(p: HKT<Parser<*>, A>, end: HKT<Parser<*>, B>): HKT<Parser<*>, List<A>> = TODO("Not yet implemented") fun <A> lookAhead(p: HKT<Parser<*>, A>): HKT<Parser<*>, A> = Parser { ps -> Parser.narrow(p).runParser(ps) `≻≻=` { res -> when (res) { is Result.Success -> Trampoline.done(Result.Success(Context(ps, false, res.value.result))); is Result.Failure -> Trampoline.done(Result.Failure(res.failure)) } } } // Applications fun skipSpaces(): HKT<Parser<*>, Tuple0> = skipMany(space()) fun symbol(str: String): HKT<Parser<*>, String> = skipSpaces() `*≻` matchString(str) `≺*` skipSpaces() fun natural(): HKT<Parser<*>, Int> = skipSpaces() `*≻` ((List<Char>::constructInt) `≺$≻` many1(isDigit())) `≺*` skipSpaces() fun real(): HKT<Parser<*>, Double> = skipSpaces() `*≻` natural().combine({ ll: List<Char> -> ll.foldRight(0.0 to 0.1) { i, (x, y) -> x + y * (i - '0').toDouble() to y * 0.1 }.first } `≺$≻` (matchChar('.') `*≻` many1(isDigit())) `≺*` skipSpaces(), Int::plus) `≺|≻` ((Int::toDouble) `≺$≻` natural())
0
Kotlin
0
0
3fc718f6c525b79ecd07b5f86264e5a18d5ee20d
7,207
NekoBinator
MIT License
lib_common/src/main/java/com/frame/mvp/common/base/BaseApplication.kt
jisx
166,322,898
false
{"Gradle": 8, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 6, "Batchfile": 1, "Markdown": 1, "Proguard": 4, "Java": 6, "XML": 40, "Kotlin": 45, "INI": 1}
package com.frame.mvp.common.base import android.app.Application import android.content.Context import androidx.annotation.Keep import androidx.multidex.MultiDex @Keep open class BaseApplication : Application() { override fun attachBaseContext(base: Context) { super.attachBaseContext(base) MultiDex.install(this) } }
1
null
1
1
8e159bf09602d30717e373a7d44d3b9d65574706
346
frame-mvp
Apache License 2.0
plugin_example/src/main/java/id/psw/floatstat/plugin_example/providers/PluginDataProvider.kt
EmiyaSyahriel
500,192,208
false
{"Kotlin": 85933}
package id.psw.floatstat.plugin_example.providers import id.psw.floatstat.plugin_example.SamplePluginService import id.psw.floatstat.plugins.PluginData open class PluginDataProvider(val ctx: SamplePluginService) { open fun getData() : PluginData = SamplePluginService.blankPluginData }
0
Kotlin
0
1
acd72e9ed19683f96eed5159ddc8df6dc1d57a74
291
floatstat
Apache License 2.0
subprojects/core/src/main/kotlin/com/handtruth/mc/mcsman/server/service/ServicesFunctionality.kt
handtruth
417,843,728
false
null
package com.handtruth.mc.mcsman.server.service import com.handtruth.mc.mcsman.AlreadyExistsMCSManException import com.handtruth.mc.mcsman.NotExistsMCSManException import com.handtruth.mc.mcsman.event.ManageServiceEvent import com.handtruth.mc.mcsman.event.SendCommand2ServiceEvent import com.handtruth.mc.mcsman.event.ServiceCreationEvent import com.handtruth.mc.mcsman.event.ServiceLifeEvent import com.handtruth.mc.mcsman.server.ReactorContext import com.handtruth.mc.mcsman.server.event.Events import com.handtruth.mc.mcsman.server.model.ServiceTable import com.handtruth.mc.mcsman.server.util.suspendTransaction import org.jetbrains.exposed.sql.Database import org.jetbrains.exposed.sql.insertAndGetId import org.jetbrains.exposed.sql.select import org.jetbrains.exposed.sql.statements.api.ExposedBlob import org.koin.core.KoinComponent import org.koin.core.get internal class ServicesFunctionality : KoinComponent { private val events: Events = get() private val db: Database = get() private val services: Services = get() private fun notExists(name: String): Nothing = throw NotExistsMCSManException("service $name does not exists") private fun alreadyExists(name: String): Nothing { throw AlreadyExistsMCSManException("service $name already exists") } fun initialize() { events.correct<ServiceCreationEvent> { event -> if (!event.direction) { val table = ServiceTable val service = suspendTransaction(db) { table.select { table.name eq event.service }.firstOrNull() } ?: notExists(event.service) event.copy(state = service[table.state].bytes, className = service[table.className]) } else { event } } @OptIn(ReactorContext::class) events.react<ServiceCreationEvent> { event -> val table = ServiceTable if (event.direction) { val notExists = suspendTransaction(db) { table.select { table.name eq event.service }.empty() } if (!notExists) throw alreadyExists(event.service) val id = suspendTransaction(db) { table.insertAndGetId { it[table.name] = event.service it[table.className] = event.className it[table.state] = ExposedBlob(event.state) }.value } services.get(id).invokeOnCreate() } else { val notExists = suspendTransaction(db) { table.select { table.name eq event.service }.empty() } if (notExists) notExists(event.service) services.get(event.service).delete() } } events.react<ManageServiceEvent> { event -> services.get(event.service).invokeManage(event.action) } events.react<SendCommand2ServiceEvent> { event -> services.get(event.service).internalSend.send(event.command) } events.register<ServiceLifeEvent>() } }
0
Kotlin
0
0
58b2d4bd0413522dbf1cbabc1c8bab78e1b1edfe
3,228
mcsman
Apache License 2.0
Android/app/src/main/java/com/versilistyson/searchflix/presentation/ui/common/fragment/BindedFragment.kt
vdtyson
255,445,964
false
null
package com.versilistyson.searchflix.presentation.ui.common.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding import androidx.fragment.app.Fragment abstract class BindedFragment<Binding: ViewDataBinding>: Fragment() { protected lateinit var binding: Binding abstract val layoutId: Int override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = DataBindingUtil.inflate(inflater, layoutId, container, false) binding.lifecycleOwner = viewLifecycleOwner return binding.root } }
0
Kotlin
0
1
895bb09903d38952a4373bbe7dd413301771e6c9
772
SearchFlix
MIT License
buildSrc/src/main/kotlin/dev/jonaz/vured/util/gradle/Versions.kt
vured
367,025,536
false
null
package dev.jonaz.vured.util.gradle object Versions { const val KOTLIN = "1.5.0" const val LAVA_PLAYER = "1.3.75" const val JDA = "4.2.1_253" const val LOGBACK = "1.2.3" const val HOPLITE = "1.4.0" const val KOIN = "3.0.1" }
0
Kotlin
0
0
e981064194ffe34590b7a3192528c24d495f0d86
250
vured-util
Apache License 2.0
org.librarysimplified.drm.core/src/main/java/org/nypl/drm/core/AxisNowFileAsset.kt
NYPL-Simplified
42,663,893
false
null
package org.nypl.drm.core import org.readium.r2.shared.publication.asset.FileAsset import org.readium.r2.shared.publication.asset.PublicationAsset import java.io.File /** * A Readium2 AxisNow-protected asset. */ class AxisNowFileAsset( /** * The actual EPUB file. */ val fileAsset: FileAsset, /** * The Axis license file, assuming there is one. */ val axisLicense: File?, /** * The Axis user key file, assuming there is one. */ val axisUserKey: File?, ) : PublicationAsset by fileAsset
3
null
1
1
d0fd9aed6167682c4575c565a790551d91e3e1ff
552
DRM-Android-Core
Apache License 2.0
app/src/main/java/com/masterwok/demoffmpegglidevideodecoder/glide/GlideModule.kt
masterwok
144,424,265
false
null
package com.masterwok.demoffmpegglidevideodecoder.glide import android.content.Context import android.graphics.Bitmap import android.net.Uri import com.bumptech.glide.Glide import com.bumptech.glide.Registry import com.bumptech.glide.annotation.GlideModule import com.bumptech.glide.module.AppGlideModule import com.masterwok.ffmpegglidevideodecoder.FFmpegVideoDecoder @GlideModule() class GlideModule : AppGlideModule() { override fun registerComponents(context: Context, glide: Glide, registry: Registry) { registry.prepend( Registry.BUCKET_BITMAP , Uri::class.java , Bitmap::class.java , FFmpegVideoDecoder(glide.bitmapPool) ) super.registerComponents(context, glide, registry) } }
0
Kotlin
6
29
c90a6c438e8f6b9292f6874c1d3ee5b440b2c4e8
789
ffmpeg-glide-video-decoder
MIT License
src/main/kotlin/com/cuupa/opengarden/persistence/field/FieldEntity.kt
Cuupa
478,063,266
false
null
package com.cuupa.opengarden.persistence.field import com.cuupa.opengarden.persistence.user.UserEntity import javax.persistence.* @Entity @Table(name = "field") open class FieldEntity { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", updatable = false, nullable = false) open var id: Long? = null open var name = "" /** * UserId of the associated field */ @OneToOne(fetch = FetchType.LAZY) open var user: UserEntity? = null @OneToMany(fetch = FetchType.LAZY) open var plantPosition = mutableListOf<PlantPositionEntity>() @Enumerated(EnumType.ORDINAL) open var fieldType: FieldTypeEntity = FieldTypeEntity.UNDEFINED }
14
Kotlin
0
0
c71b87dbdb4e97afb42a3dc7546a17cd8e8c8b5e
707
open-garden
MIT License
app/src/main/java/com/gigamole/quatrogradesample/AnimationExampleActivity.kt
GIGAMOLE
381,280,794
false
{"Kotlin": 25056}
package com.gigamole.quatrogradesample import android.animation.Animator import android.animation.ArgbEvaluator import android.animation.ValueAnimator import android.os.Bundle import android.view.animation.LinearInterpolator import androidx.appcompat.app.AppCompatActivity import codes.side.andcolorpicker.converter.setFromColorInt import codes.side.andcolorpicker.converter.toColorInt import codes.side.andcolorpicker.model.IntegerHSLColor import com.gigamole.quatrograde.GradeModel import com.gigamole.quatrogradesample.databinding.ActivityAnimationBinding import kotlin.random.Random class AnimationExampleActivity : AppCompatActivity() { private lateinit var binding: ActivityAnimationBinding private val topGrades = listOf( GradeModel(randomColor(true), 0.0F), GradeModel(randomColor(true), 0.33F), GradeModel(randomColor(true), 1.0F) ) private val bottomGrades = listOf( GradeModel(randomColor(true), 0.0F), GradeModel(randomColor(true), 0.66F), GradeModel(randomColor(true), 1.0F) ) private val argbEvaluator = ArgbEvaluator() private val animatorTop0 = ValueAnimator() private val animatorTop1 = ValueAnimator() private val animatorTop2 = ValueAnimator() private val animatorBottom0 = ValueAnimator() private val animatorBottom1 = ValueAnimator() private val animatorBottom2 = ValueAnimator() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityAnimationBinding.inflate(layoutInflater) setContentView(binding.root) setupUi() } private fun setupUi() { topGrades[1].color = getRandomMidColor(topGrades[0].color) bottomGrades[1].color = getRandomMidColor(bottomGrades[2].color) binding.animationQuatroGradeView.setGrades(topGrades, bottomGrades) setupAnimator(animatorTop0, binding.animationQuatroGradeView.getTopGrades()[0]) setupAnimator( animatorTop1, binding.animationQuatroGradeView.getTopGrades()[1], forMidColorGradeModel = binding.animationQuatroGradeView.getTopGrades()[0] ) setupAnimator(animatorTop2, binding.animationQuatroGradeView.getTopGrades()[2]) setupAnimator(animatorBottom0, binding.animationQuatroGradeView.getBottomGrades()[0]) setupAnimator( animatorBottom1, binding.animationQuatroGradeView.getBottomGrades()[1], forMidColorGradeModel = binding.animationQuatroGradeView.getBottomGrades()[2] ) setupAnimator(animatorBottom2, binding.animationQuatroGradeView.getBottomGrades()[2]) animatorBottom1.addUpdateListener { binding.animationQuatroGradeView.refresh() } } private fun setupAnimator( animator: ValueAnimator, gradeModel: GradeModel, forMidColorGradeModel: GradeModel? = null ) { randomizeAnimator(forMidColorGradeModel, animator, gradeModel) animator.interpolator = LinearInterpolator() animator.setEvaluator(argbEvaluator) animator.addListener( object : Animator.AnimatorListener { override fun onAnimationStart(animation: Animator?) = Unit override fun onAnimationEnd(animation: Animator?) { randomizeAnimator(forMidColorGradeModel, animator, gradeModel) animator.start() } override fun onAnimationCancel(animation: Animator?) = Unit override fun onAnimationRepeat(animation: Animator?) = Unit } ) animator.addUpdateListener { gradeModel.color = it.animatedValue as Int } animator.start() } internal fun randomizeAnimator( forMidColorGradeModel: GradeModel?, animator: ValueAnimator, gradeModel: GradeModel ) { if (forMidColorGradeModel != null) { animator.setIntValues(gradeModel.color, getRandomMidColor(forMidColorGradeModel.color)) } else { animator.setIntValues(gradeModel.color, randomColor(true)) } animator.duration = getRandomDuration() } internal fun getRandomMidColor(fromColor: Int) = IntegerHSLColor().apply { setFromColorInt(fromColor) intH += Random.nextInt(-36, 36) }.toColorInt() internal fun getRandomDuration() = (4000 + Random.nextInt(1000)).toLong() }
0
Kotlin
7
35
19fe5225143794f585b2c19a67a2da2d450bbd3c
3,963
QuatroGrade
MIT License
app/src/main/java/com/iambedant/mvistarter/mvibase/MviIntent.kt
iamBedant
134,553,457
false
null
package com.iambedant.mvistarter.mvibase /** * Immutable object which represent an view's intent. */ interface MviIntent
0
Kotlin
5
19
c8dd34cce44967535de3498757f5f50157d7418e
124
Android-Mvi-Starter
MIT License
app/src/main/java/com/katana/koin/ui/MainNavigator.kt
cybernetics
211,757,315
false
null
package com.katana.koin.ui /** * Created by Kaz on 10:15 2018-12-19 */ interface MainNavigator { }
0
Kotlin
0
0
8f33d409174293f63e0a680d35eee9106065fdd7
101
mvvm-koin
Apache License 2.0
ui/src/main/java/ru/tinkoff/acquiring/sdk/smartfield/BaubleClearOrScanButton.kt
itlogic
293,802,517
true
{"Kotlin": 1162428, "Java": 29422}
package ru.tinkoff.acquiring.sdk.smartfield import android.content.res.ColorStateList import android.util.Log import android.view.ViewGroup import android.widget.ImageView import androidx.core.content.res.ResourcesCompat import androidx.core.view.isVisible import ru.tinkoff.acquiring.sdk.R import ru.tinkoff.acquiring.sdk.cardscanners.CardScanner import ru.tinkoff.acquiring.sdk.cardscanners.delegate.CardScannerWrapper import ru.tinkoff.acquiring.sdk.cardscanners.delegate.isEnabled import ru.tinkoff.acquiring.sdk.utils.SimpleTextWatcher import ru.tinkoff.acquiring.sdk.utils.dpToPx internal class BaubleClearOrScanButton { private lateinit var textFieldView: AcqTextFieldView private lateinit var clear: ImageView private lateinit var scan: ImageView private var cardScanner: CardScannerWrapper? = null fun attach(textFieldView: AcqTextFieldView, scanner: CardScannerWrapper?) { this.textFieldView = textFieldView this.cardScanner = scanner val context = textFieldView.context clear = ImageView(context).apply { setImageResource(R.drawable.acq_ic_clear) imageTintList = ColorStateList.valueOf(ResourcesCompat.getColor( context.resources, R.color.acq_colorTextTertiary, context.theme)) layoutParams = ViewGroup.LayoutParams(context.dpToPx(16), context.dpToPx(16)) } clear.setOnClickListener { textFieldView.text = "" } textFieldView.addRightBauble(clear) scan = ImageView(context).apply { setImageResource(R.drawable.acq_ic_card_frame) layoutParams = ViewGroup.LayoutParams(context.dpToPx(16), context.dpToPx(16)) } scan.setOnClickListener { scanner?.start() } textFieldView.addRightBauble(scan) textFieldView.addViewFocusChangeListener { update() } textFieldView.editText.addTextChangedListener(SimpleTextWatcher.after { update() }) update() } private fun update() { clear.isVisible = textFieldView.isEnabled && textFieldView.text.isNullOrBlank().not() && textFieldView.isViewFocused() scan.isVisible = textFieldView.isEnabled && cardScanner.isEnabled() && textFieldView.text.isNullOrBlank() } }
0
Kotlin
0
0
8de009c2ae6ca40843c74799429346fcfa74820c
2,309
AcquiringSdkAndroid
Apache License 2.0
app/src/main/java/com/tzion/jetpackmovies/domain/entities/Language.kt
4mr0m3r0
156,536,164
false
{"Kotlin": 151737}
package com.tzion.jetpackmovies.domain.entities class Language { }
4
Kotlin
4
15
11b983e57bc1508a6ec5ca738af70c4f9a8ea9aa
68
movies-jetpack-sample
MIT License
baselib/src/main/java/com/wan/baselib/rxbus/RxBus.kt
qinghuaAndroid
252,683,218
false
{"Kotlin": 278208, "Java": 73348}
package com.wan.baselib.rxbus import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.processors.FlowableProcessor import io.reactivex.rxjava3.processors.PublishProcessor import io.reactivex.rxjava3.subscribers.SerializedSubscriber enum class RxBus { INSTANCE; private val bus: FlowableProcessor<Any> = PublishProcessor.create<Any>().toSerialized() // 发送一个新的事件 fun post(o: Any) { SerializedSubscriber(bus).onNext(o) } // 根据传递的 eventType 类型返回特定类型(eventType)的 被观察者 fun <T : Any> toFlowable(eventType: Class<T>): Flowable<T> { return bus.ofType(eventType) } fun hasSubscribers(): Boolean { return bus.hasSubscribers() } }
1
Kotlin
3
3
35e86bbc06a3ef306d3355432b8dc6cdb7217c1e
703
WanAndroid-MVVM
Apache License 2.0
app/src/main/java/com/ms/quokkaism/db/QuoteDao.kt
mshohrat
548,821,104
false
null
package com.ms.quokkaism.db import androidx.paging.DataSource import androidx.room.* import com.ms.quokkaism.db.model.Quote @Dao interface QuoteDao { @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insertQuote(quote: Quote) @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insertQuotes(quotesList: List<Quote>) @Update(onConflict = OnConflictStrategy.REPLACE) suspend fun updateQuotes(quotesList: List<Quote>) @Transaction suspend fun upsert(quotes: List<Quote>) { insertQuotes(quotes) quotes.forEach { it.id?.let { id -> updateQuote(id,it.text,it.author,it.isFavorite,it.isRead) } } } @Query("UPDATE quotes SET text = :text,author = :author,is_favorite = :isFavorite,is_read = :isRead WHERE id = :id") suspend fun updateQuote(id: Long, text: String,author: String?, isFavorite: Int,isRead: Int) @Query("UPDATE quotes SET is_favorite = :isFavorite WHERE id = :id") suspend fun updateQuoteIsfavorite(id: Long, isFavorite: Int) @Query("UPDATE quotes SET is_read = :isRead,modified_at=:time WHERE id = :id") suspend fun updateQuoteIsRead(id: Long, isRead: Int,time: Long = System.currentTimeMillis()) @Query("SELECT * FROM quotes WHERE is_favorite == 1 ORDER BY modified_at ASC") fun getLikedQuotes(): DataSource.Factory<Int, Quote?> @Query("SELECT * FROM quotes WHERE is_read == 1 ORDER BY modified_at DESC") fun getLastReadQuotes(): DataSource.Factory<Int,Quote?> @Query("SELECT * FROM quotes WHERE is_read == 0 LIMIT 1") suspend fun getFirstUnreadQuote(): Quote? @Query("SELECT * FROM quotes WHERE is_read == 0 LIMIT 10") suspend fun getFirstUnreadQuotes(): List<Quote?>? @Query("SELECT * FROM quotes WHERE is_read == 1 AND text LIKE :query ORDER BY modified_at ASC") fun searchQuotes(query: String?): DataSource.Factory<Int,Quote?> }
0
Kotlin
0
0
49e02903018d4a444428d3a8bba06b58e41193b1
1,936
PositiveQuotes
MIT License
app/src/main/java/cucerdariancatalin/sms_messenger/receivers/MmsSentReceiver.kt
cucerdariancatalin
586,080,344
false
null
package cucerdariancatalin.sms_messenger.receivers import android.app.Activity import android.content.Context import android.content.Intent import cucerdariancatalin.sms_messenger.helpers.refreshMessages class MmsSentReceiver : com.klinker.android.send_message.MmsSentReceiver() { override fun onMessageStatusUpdated(context: Context?, intent: Intent?, resultCode: Int) { super.onMessageStatusUpdated(context, intent, resultCode) if (resultCode == Activity.RESULT_OK) { refreshMessages() } } }
0
Kotlin
0
2
bde8d17dfc800c3a291a96d3b4ee653f335019bb
540
SMSMessenger
MIT License
app/src/main/java/com/example/budget/trx/TrxActivity.kt
okumaru
725,161,333
false
{"Kotlin": 258088}
package com.example.budget.trx import android.content.Intent import android.widget.Toast import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row 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.material.icons.Icons import androidx.compose.material.icons.filled.FilterAlt import androidx.compose.material.icons.outlined.Clear import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import com.example.budget.AddActivity import com.example.budget.BudgetApp import com.example.budget.R import com.example.budget.account.AccountViewModel import com.example.budget.data.Account import com.example.budget.data.CategoryWithTypeBudget import com.example.budget.data.TrxWithAccountBudget import com.example.budget.home.HomeActivity import com.example.budget.libs.HeadActivity import com.example.budget.libs.composables.account.AccountsDropdownMenu import com.example.budget.libs.composables.trx.GridTrxSummary import com.example.budget.libs.composables.trx_cat.CatsDropMenu import com.example.budget.setting.SettingActivity import com.example.budget.trx_cat.TrxCatActivity import com.example.budget.trx_cat.TrxCatViewModel class TrxActivity: BudgetApp() { override val navName = R.string.nav_trx private var accountid: Int? by mutableStateOf(null) private var categoryid: Int? by mutableStateOf(null) private var accountsList: List<Account>? by mutableStateOf(null) private var catsList: List<CategoryWithTypeBudget>? by mutableStateOf(null) @Composable override fun Content() { if (super.apiConfig === null || !super.readyToUse) change(R.string.nav_setting_config) val trxVM = TrxViewModel(super.apiConfig!!) val accountVM = AccountViewModel(super.apiConfig!!) val catVM = TrxCatViewModel(super.apiConfig!!) var trxsList by remember { mutableStateOf<List<TrxWithAccountBudget>?>(value = null) } LaunchedEffect(Unit, block = { //get data from intent val intent = intent accountid = intent.getIntExtra("accountid", 0) categoryid = intent.getIntExtra("categoryid", 0) accountsList = accountVM.getAccounts() catsList = catVM.getCategories(null) trxsList = trxVM.getTrxs(accountid, categoryid) }) if (trxVM.errorMessage.isNotEmpty()) { Toast.makeText(this, trxVM.errorMessage,Toast.LENGTH_SHORT).show() } if (accountVM.errorMessage.isNotEmpty()) { Toast.makeText(this, accountVM.errorMessage,Toast.LENGTH_SHORT).show() } Column(modifier = Modifier .fillMaxSize(1F) .padding(bottom = 64.dp)){ HeadActivity( title = R.string.trx_head_title, addSection = { PopupWindowDialog() } ) GridTrxSummary( trxs = trxsList, onClick = { detail(it) } ) } } @Composable fun PopupWindowDialog() { val openAlertDialog = remember { mutableStateOf(false) } IconButton(onClick = { openAlertDialog.value = !openAlertDialog.value }) { Icon(imageVector = Icons.Default.FilterAlt, contentDescription = null) } if (openAlertDialog.value) { AlertDialogExample( onDismissRequest = { openAlertDialog.value = false }, ) } } @Composable fun AlertDialogExample( onDismissRequest: () -> Unit, ) { Dialog(onDismissRequest = { }) { // Draw a rectangle shape with rounded corners inside the dialog Card( modifier = Modifier .fillMaxWidth() .height(288.dp), shape = MaterialTheme.shapes.medium, colors = CardDefaults.cardColors( containerColor = MaterialTheme.colorScheme.background, ) ) { Column( modifier = Modifier .fillMaxSize() .padding(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { Row( horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth(), ) { Text( text = "Filter data transaction." ) IconButton(onClick = { onDismissRequest() }) { Icon(imageVector = Icons.Outlined.Clear, contentDescription = null) } } if (accountsList !== null) { AccountsDropdownMenu( label = "Account", accounts = accountsList!!, initItem = true, changeAccountId = { accountid = it }, ) } if (catsList !== null) { CatsDropMenu( label = "Categories", catsList = catsList, initItem = true, changeCategoryId = { categoryid = it }, ) } Row( horizontalArrangement = Arrangement.spacedBy(16.dp), ) { Button(onClick = { filter(0, 0) }) { Text(text = "Reset Filter") } Button(onClick = { filter(accountid, categoryid) }) { Text(text = "Filter") } } } } } } private fun filter(accountId: Int?, categoryId: Int?) { val intent = intent intent.putExtra("accountid", accountId) intent.putExtra("categoryid", categoryId) startActivity(intent) } private fun detail(trx: TrxWithAccountBudget) { val intent = Intent(this, DetailTrxActivity::class.java) intent.putExtra("trxid", trx.id) startActivity(intent) } override fun change(activity: Int) { when(activity) { R.string.nav_home -> { val intent = Intent(this, HomeActivity::class.java) startActivity(intent) } R.string.nav_trx -> { val intent = Intent(this, TrxActivity::class.java) startActivity(intent) } R.string.nav_add -> { val intent = Intent(this, AddActivity::class.java) startActivity(intent) } R.string.nav_trx_cat -> { val intent = Intent(this, TrxCatActivity::class.java) startActivity(intent) } R.string.nav_setting -> { val intent = Intent(this, SettingActivity::class.java) startActivity(intent) } } } }
0
Kotlin
0
0
59627b9d50538fbbc5512f2622a3608ced425577
8,192
mobile-app-budget
MIT License
android/Library/Owner/app/src/main/java/com/pradyotprakash/libraryowner/app/pages/splash/viewmodel/SplashViewModel.kt
pradyotprksh
385,586,594
false
{"Kotlin": 1895342, "Dart": 1052279, "Python": 311069, "Swift": 145439, "C++": 90451, "CMake": 74709, "Go": 45704, "HTML": 19243, "Ruby": 12424, "C": 5700, "Shell": 817, "JavaScript": 781, "CSS": 588, "Objective-C": 342, "Makefile": 318, "Dockerfile": 32}
package com.pradyotprakash.libraryowner.app.pages.splash.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.pradyotprakash.libraryowner.app.routes.Routes import com.pradyotprakash.libraryowner.app.routes.path import com.pradyotprakash.libraryowner.app.utils.BuildDetails import com.pradyotprakash.libraryowner.core.navigation.Navigator import com.pradyotprakash.libraryowner.core.response.OwnerResponse import com.pradyotprakash.libraryowner.domain.usecases.AuthenticationUseCase import com.pradyotprakash.libraryowner.domain.usecases.UnsplashUseCase import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.delay import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class SplashViewModel @Inject constructor( private val unsplashUseCase: UnsplashUseCase, private val authenticationUseCase: AuthenticationUseCase, private val navigator: Navigator, ) : ViewModel() { private val _backgroundImageUrls = MutableLiveData(emptyList<String>()) val backgroundImageUrls: LiveData<List<String>> get() = _backgroundImageUrls fun getBackgroundImage() { if (!BuildDetails.IS_DEBUG) { viewModelScope.launch { unsplashUseCase.getLibraryPortraitImage(count = 50).collect { response -> when (response) { is OwnerResponse.Success -> { val backgroundImages = response.data.results.mapNotNull { it.urls?.full }.shuffled() if (backgroundImages.size > 9) { _backgroundImageUrls.value = backgroundImages.subList(fromIndex = 0, toIndex = 9) } } else -> {} } goToNextScreen() } } } else { goToNextScreen() } } private fun goToNextScreen() { viewModelScope.launch { delay(2500) if (authenticationUseCase.isUserLoggedIn()) { } else { navigator.navigate { it.navigate(Routes.Welcome.path()) } } } } }
0
Kotlin
9
15
f2bef232d7b45c68f94985a0ac2542f3bb2d8f19
2,378
development_learning
MIT License
SKIE/compiler/kotlin-plugin/src/kgp_common/kotlin/co/touchlab/skie/phases/swift/CompileSwiftPhase.kt
touchlab
685,579,240
false
{"Kotlin": 1041703, "Swift": 24501, "Shell": 183}
package co.touchlab.skie.phases.swift import co.touchlab.skie.configuration.SkieConfigurationFlag import co.touchlab.skie.phases.SirPhase import co.touchlab.skie.util.Command import org.jetbrains.kotlin.backend.konan.BitcodeEmbedding import org.jetbrains.kotlin.backend.konan.KonanConfigKeys import org.jetbrains.kotlin.konan.target.platformName import org.jetbrains.kotlin.konan.target.withOSVersion import java.io.File class CompileSwiftPhase( context: SirPhase.Context, ) : SirPhase { private val framework = context.framework private val cacheableKotlinFramework = context.cacheableKotlinFramework private val konanConfig = context.konanConfig private val swiftCompilerConfiguration = context.swiftCompilerConfiguration private val skieConfiguration = context.skieConfiguration private val configurables = context.configurables private val skieBuildDirectory = context.skieBuildDirectory private val targetTriple = context.configurables.targetTriple private val swiftFrameworkHeader = context.skieBuildDirectory.swiftCompiler.moduleHeader(framework.moduleName) context(SirPhase.Context) override fun execute() { val sourceFiles = skieBuildDirectory.swift.allSwiftFiles if (sourceFiles.isEmpty()) { return } callSwiftCompiler(sourceFiles) deleteOldObjectFiles(sourceFiles) copySwiftModuleFiles() addSwiftSubmoduleToModuleMap() addSwiftSpecificLinkerArgs() } private fun callSwiftCompiler(sourceFiles: List<File>) { Command("${configurables.absoluteTargetToolchain}/usr/bin/swiftc").apply { +listOf("-module-name", framework.moduleName) +"-import-underlying-module" +"-F" +cacheableKotlinFramework.parentDir.absolutePath +"-F" +skieBuildDirectory.swiftCompiler.fakeObjCFrameworks.directory.absolutePath +"-emit-module" +"-emit-module-path" +swiftFrameworkHeader.swiftModule +"-emit-module-interface-path" +swiftFrameworkHeader.swiftInterface +"-emit-private-module-interface-path" +swiftFrameworkHeader.privateSwiftInterface +"-emit-objc-header" +"-emit-objc-header-path" +swiftFrameworkHeader.swiftHeader getSwiftcBitcodeArg()?.let { +it } +getSwiftcBuildTypeArgs() +"-emit-object" +"-parse-as-library" +"-g" +"-module-cache-path" +skieBuildDirectory.cache.swiftModules.directory.absolutePath +"-swift-version" +swiftCompilerConfiguration.swiftVersion +parallelizationArgument +"-sdk" +configurables.absoluteTargetSysRoot +"-target" +configurables.targetTriple.withOSVersion(configurables.osVersionMin).toString() +sourceFiles.map { it.absolutePath } workingDirectory = skieBuildDirectory.swiftCompiler.objectFiles.directory execute(logFile = skieBuildDirectory.debug.logs.swiftc) } } private fun deleteOldObjectFiles(sourceFiles: List<File>) { if (konanConfig.debug) { val sourceFilesNames = sourceFiles.map { it.nameWithoutExtension }.toSet() skieBuildDirectory.swiftCompiler.objectFiles.all .filterNot { it.nameWithoutExtension in sourceFilesNames } .forEach { objectFile -> objectFile.delete() } } else { skieBuildDirectory.swiftCompiler.objectFiles.all .filter { it.nameWithoutExtension != framework.moduleName } .forEach { objectFile -> objectFile.delete() } } } private fun getSwiftcBitcodeArg() = when (konanConfig.configuration.get(KonanConfigKeys.BITCODE_EMBEDDING_MODE)) { BitcodeEmbedding.Mode.NONE, null -> null BitcodeEmbedding.Mode.FULL -> "-embed-bitcode" BitcodeEmbedding.Mode.MARKER -> "-embed-bitcode-marker" } private fun getSwiftcBuildTypeArgs() = if (konanConfig.debug) { emptyList() } else { listOf("-O", "-whole-module-optimization") } private fun copySwiftModuleFiles() { val copyFiles = mapOf( swiftFrameworkHeader.swiftModule to framework.swiftModule(targetTriple), swiftFrameworkHeader.swiftInterface to framework.swiftInterface(targetTriple), swiftFrameworkHeader.privateSwiftInterface to framework.privateSwiftInterface(targetTriple), swiftFrameworkHeader.swiftDoc to framework.swiftDoc(targetTriple), swiftFrameworkHeader.abiJson to framework.abiJson(targetTriple), swiftFrameworkHeader.swiftSourceInfo to framework.swiftSourceInfo(targetTriple), swiftFrameworkHeader.swiftHeader to framework.swiftHeader, ) copyFiles.forEach { (source, target) -> source.copyTo(target, overwrite = true) } } private fun addSwiftSubmoduleToModuleMap() { framework.modulemapFile.appendText( """ module ${framework.moduleName}.Swift { header "${framework.swiftHeader.name}" requires objc } """.trimIndent(), ) } private fun addSwiftSpecificLinkerArgs() { val swiftLibSearchPaths = listOf( File(configurables.absoluteTargetToolchain, "usr/lib/swift/${configurables.platformName().lowercase()}"), File(configurables.absoluteTargetSysRoot, "usr/lib/swift"), ).flatMap { listOf("-L", it.absolutePath) } val otherLinkerFlags = listOf( "-rpath", "/usr/lib/swift", "-dead_strip", ) konanConfig.configuration.addAll(KonanConfigKeys.LINKER_ARGS, swiftLibSearchPaths) konanConfig.configuration.addAll(KonanConfigKeys.LINKER_ARGS, otherLinkerFlags) } private val parallelizationArgument: String get() = if (SkieConfigurationFlag.Build_ParallelSwiftCompilation in skieConfiguration.enabledConfigurationFlags) { "-j${Runtime.getRuntime().availableProcessors()}" } else { "-j1" } }
9
Kotlin
4
358
febe2f6f7448d4874f934a1ade10787eb02a86cc
6,352
SKIE
Apache License 2.0
project/jimmer-sql-kotlin/src/main/kotlin/org/babyfish/jimmer/sql/kt/filter/impl/JavaFilter.kt
meiMingle
554,763,123
true
{"Markdown": 18, "Batchfile": 8, "Shell": 10, "Java": 537, "Kotlin": 292, "SQL": 9, "INI": 11, "Gradle Kotlin DSL": 14, "JavaScript": 4, "CSS": 3}
package org.babyfish.jimmer.sql.kt.filter.impl import org.apache.commons.lang3.reflect.TypeUtils import org.babyfish.jimmer.meta.ImmutableType import org.babyfish.jimmer.sql.ast.impl.table.TableImplementor import org.babyfish.jimmer.sql.ast.table.Props import org.babyfish.jimmer.sql.filter.Filter import org.babyfish.jimmer.sql.filter.FilterArgs import org.babyfish.jimmer.sql.filter.impl.AbstractFilterArgsImpl import org.babyfish.jimmer.sql.filter.impl.TypeAwareFilter import org.babyfish.jimmer.sql.kt.filter.KFilter internal open class JavaFilter constructor( protected val ktFilter: KFilter<*> ) : TypeAwareFilter { private val immutableType: ImmutableType = TypeUtils .getTypeArguments(ktFilter::class.java, KFilter::class.java) .values .first() .let { if (it !is Class<*>) { throw IllegalArgumentException( "\"${ktFilter::class.qualifiedName}\" is illegal, " + "the type argument of \"${KFilter::class.qualifiedName}\" " + "is not specified" ) } ImmutableType.get(it) } @Suppress("UNCHECKED_CAST") override fun filter(args: FilterArgs<Props>?) { val javaQuery = (args as AbstractFilterArgsImpl<*>).unwrap() (ktFilter as KFilter<Any>).filter( KFilterArgsImpl( javaQuery, args.getTable() as TableImplementor<Any> ) ) } override fun getImmutableType(): ImmutableType = immutableType override fun getFilterType(): Class<*> = ktFilter::class.java override fun hashCode(): Int = ktFilter.hashCode() override fun equals(other: Any?): Boolean { if (this === other) { return true } if (other !is JavaFilter) { return false } return ktFilter == other.ktFilter } override fun toString(): String = ktFilter.toString() }
0
null
0
0
d3850dbb2b22ffa6b277914c0fafc03fa5b673de
2,020
jimmer
MIT License
Extra/app/src/main/java/com/example/extra/MainActivity.kt
CHcrocs
863,499,039
false
{"Kotlin": 23790}
package com.example.extra import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextField 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.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.extra.ui.theme.ExtraTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MunchkinMain() } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun MunchkinMain() { //Jogador 1 var nome by remember { mutableStateOf("") } var level by remember { mutableStateOf(1) } var equipBonus by remember { mutableStateOf(0) } var modificador by remember { mutableStateOf(0) } //Jogador 2 var nome2 by remember { mutableStateOf("") } var level2 by remember { mutableStateOf(1) } var equipBonus2 by remember { mutableStateOf(0) } var modificador2 by remember { mutableStateOf(0) } //Jogador 3 var nome3 by remember { mutableStateOf("") } var level3 by remember { mutableStateOf(1) } var equipBonus3 by remember { mutableStateOf(0) } var modificador3 by remember { mutableStateOf(0) } //Jogador 4 var nome4 by remember { mutableStateOf("") } var level4 by remember { mutableStateOf(1) } var equipBonus4 by remember { mutableStateOf(0) } var modificador4 by remember { mutableStateOf(0) } //Jogador 5 var nome5 by remember { mutableStateOf("") } var level5 by remember { mutableStateOf(1) } var equipBonus5 by remember { mutableStateOf(0) } var modificador5 by remember { mutableStateOf(0) } //Jogador 6 var nome6 by remember { mutableStateOf("") } var level6 by remember { mutableStateOf(1) } var equipBonus6 by remember { mutableStateOf(0) } var modificador6 by remember { mutableStateOf(0) } LazyColumn { //Jogador 1 item { Column( Modifier .fillMaxSize() .padding(10.dp) ) { TextField( value = nome, onValueChange = { nome = it }, label = { Text(text = "Nome") }) Text( text = "Poder: ${level + equipBonus + modificador}", fontSize = 20.sp ) Row { Button(onClick = { if (level <= 0) { //Eliminado } else { level-- } }) { Text(text = "-") } Text(text = "Level: $level", fontSize = 20.sp) Button(onClick = { if (level >= 10) { //level maximo } else { level++ } }) { Text(text = "+") } } Row { Button(onClick = { if (equipBonus <= 0) { //Limite minimo } else { equipBonus-- } }) { Text(text = "-") } Text(text = "Equipamento: $equipBonus", fontSize = 20.sp) Button(onClick = { if (equipBonus >= 40) { //Limite maximo } else { equipBonus++ } }) { Text(text = "+") } } Row { Button(onClick = { if (modificador <= -5) { //Limite minimo } else { modificador-- } }) { Text(text = "-") } Text(text = "Modificador: $modificador", fontSize = 20.sp) Button(onClick = { if (modificador >= 10) { //Limite maximo } else { modificador++ } }) { Text(text = "+") } } } } //Jogador 2 item { Column( Modifier .fillMaxSize() .padding(10.dp) ) { TextField( value = nome2, onValueChange = { nome2 = it }, label = { Text(text = "Nome") }) Text( text = "Poder: ${level2 + equipBonus2 + modificador2}", fontSize = 20.sp ) Row { Button(onClick = { if (level2 <= 0) { //Eliminado } else { level2-- } }) { Text(text = "-") } Text(text = "Level: $level2", fontSize = 20.sp) Button(onClick = { if (level2 >= 10) { //level maximo } else { level2++ } }) { Text(text = "+") } } Row { Button(onClick = { if (equipBonus2 <= 0) { //Limite minimo } else { equipBonus2-- } }) { Text(text = "-") } Text(text = "Equipamento: $equipBonus2", fontSize = 20.sp) Button(onClick = { if (equipBonus2 >= 40) { //Limite maximo } else { equipBonus2++ } }) { Text(text = "+") } } Row { Button(onClick = { if (modificador2 <= -5) { //Limite minimo } else { modificador2-- } }) { Text(text = "-") } Text(text = "Modificador: $modificador2", fontSize = 20.sp) Button(onClick = { if (modificador2 >= 10) { //Limite maximo } else { modificador2++ } }) { Text(text = "+") } } } } //Jogador 3 item { Column( Modifier .fillMaxSize() .padding(10.dp) ) { TextField( value = nome3, onValueChange = { nome3 = it }, label = { Text(text = "Nome") }) Text( text = "Poder: ${level3 + equipBonus3 + modificador3}", fontSize = 20.sp ) Row { Button(onClick = { if (level3 <= 0) { //Eliminado } else { level3-- } }) { Text(text = "-") } Text(text = "Level: $level3", fontSize = 20.sp) Button(onClick = { if (level3 >= 10) { //level maximo } else { level3++ } }) { Text(text = "+") } } Row { Button(onClick = { if (equipBonus3 <= 0) { //Limite minimo } else { equipBonus3-- } }) { Text(text = "-") } Text(text = "Equipamento: $equipBonus3", fontSize = 20.sp) Button(onClick = { if (equipBonus3 >= 40) { //Limite maximo } else { equipBonus3++ } }) { Text(text = "+") } } Row { Button(onClick = { if (modificador3 <= -5) { //Limite minimo } else { modificador3-- } }) { Text(text = "-") } Text(text = "Modificador: $modificador3", fontSize = 20.sp) Button(onClick = { if (modificador3 >= 10) { //Limite maximo } else { modificador3++ } }) { Text(text = "+") } } } } //Jogador 4 item { Column( Modifier .fillMaxSize() .padding(10.dp) ) { TextField( value = nome4, onValueChange = { nome4 = it }, label = { Text(text = "Nome") }) Text( text = "Poder: ${level4 + equipBonus4 + modificador4}", fontSize = 20.sp ) Row { Button(onClick = { if (level4 <= 0) { //Eliminado } else { level4-- } }) { Text(text = "-") } Text(text = "Level: $level4", fontSize = 20.sp) Button(onClick = { if (level4 >= 10) { //level maximo } else { level4++ } }) { Text(text = "+") } } Row { Button(onClick = { if (equipBonus4 <= 0) { //Limite minimo } else { equipBonus4-- } }) { Text(text = "-") } Text(text = "Equipamento: $equipBonus4", fontSize = 20.sp) Button(onClick = { if (equipBonus4 >= 40) { //Limite maximo } else { equipBonus4++ } }) { Text(text = "+") } } Row { Button(onClick = { if (modificador4 <= -5) { //Limite minimo } else { modificador4-- } }) { Text(text = "-") } Text(text = "Modificador: $modificador4", fontSize = 20.sp) Button(onClick = { if (modificador4 >= 10) { //Limite maximo } else { modificador4++ } }) { Text(text = "+") } } } } //Jogador 5 item { Column( Modifier .fillMaxSize() .padding(10.dp) ) { TextField( value = nome5, onValueChange = { nome5 = it }, label = { Text(text = "Nome") }) Text( text = "Poder: ${level5 + equipBonus5 + modificador5}", fontSize = 20.sp ) Row { Button(onClick = { if (level5 <= 0) { //Eliminado } else { level5-- } }) { Text(text = "-") } Text(text = "Level: $level5", fontSize = 20.sp) Button(onClick = { if (level5 >= 10) { //level maximo } else { level5++ } }) { Text(text = "+") } } Row { Button(onClick = { if (equipBonus5 <= 0) { //Limite minimo } else { equipBonus5-- } }) { Text(text = "-") } Text(text = "Equipamento: $equipBonus5", fontSize = 20.sp) Button(onClick = { if (equipBonus5 >= 40) { //Limite maximo } else { equipBonus5++ } }) { Text(text = "+") } } Row { Button(onClick = { if (modificador5 <= -5) { //Limite minimo } else { modificador5-- } }) { Text(text = "-") } Text(text = "Modificador: $modificador5", fontSize = 20.sp) Button(onClick = { if (modificador5 >= 10) { //Limite maximo } else { modificador5++ } }) { Text(text = "+") } } } } //Jogador 6 item { Column( Modifier .fillMaxSize() .padding(10.dp) ) { TextField( value = nome6, onValueChange = { nome6 = it }, label = { Text(text = "Nome") }) Text( text = "Poder: ${level6 + equipBonus6 + modificador6}", fontSize = 20.sp ) Row { Button(onClick = { if (level6 <= 0) { //Eliminado } else { level6-- } }) { Text(text = "-") } Text(text = "Level: $level6", fontSize = 20.sp) Button(onClick = { if (level6 >= 10) { //level maximo } else { level6++ } }) { Text(text = "+") } } Row { Button(onClick = { if (equipBonus6 <= 0) { //Limite minimo } else { equipBonus6-- } }) { Text(text = "-") } Text(text = "Equipamento: $equipBonus6", fontSize = 20.sp) Button(onClick = { if (equipBonus6 >= 40) { //Limite maximo } else { equipBonus6++ } }) { Text(text = "+") } } Row { Button(onClick = { if (modificador6 <= -5) { //Limite minimo } else { modificador6-- } }) { Text(text = "-") } Text(text = "Modificador: $modificador6", fontSize = 20.sp) Button(onClick = { if (modificador6 >= 10) { //Limite maximo } else { modificador6++ } }) { Text(text = "+") } } } } } }
0
Kotlin
0
0
bc7b56e5eceb73bdc7bce29d7c47e9d0f2d6a405
19,337
AtividadeExtra
MIT License
src/main/kotlin/io/github/gaming32/mckt/commands/commands/SaveCommand.kt
mckt-Minecraft
532,076,162
false
null
package io.github.gaming32.mckt.commands.commands import com.mojang.brigadier.builder.LiteralArgumentBuilder.literal import io.github.gaming32.mckt.commands.CommandSource import io.github.gaming32.mckt.commands.executesSuspend import net.kyori.adventure.text.Component object SaveCommand : BuiltinCommand { override val helpText = Component.text("Saves the world") override fun buildTree() = literal<CommandSource>("save") .requires { it.hasPermission(4) } .executesSuspend { source.server.world.saveAndLog(source) 0 }!! }
0
Kotlin
0
2
98e88af4f54a12faeea2543c4bbdc950dd744092
582
mckt
MIT License
src/main/kotlin/dev/argraur/aosp/builder/cli/command/Command.kt
argraur
459,604,174
false
null
/* * SPDX-FileCopyrightText: 2022 Arseniy Graur <me@argraur.dev> * SPDX-License-Identifier: MIT */ package dev.argraur.aosp.builder.cli.command import dev.argraur.aosp.builder.utils.Logger interface Command { private val TAG: String get() = this.javaClass.simpleName private val logger: Logger get() = Logger.getInstance() fun start(args: String) fun help(): String }
0
Kotlin
0
2
f0ebc53f318f81065b10a07b635bba66e2228f19
405
aosp-builder
MIT License
app/src/main/java/com/joe/transactionsapp/framework/presentation/detail/TransactionDetailFragment.kt
jizhe7550
389,596,293
false
null
package com.joe.transactionsapp.framework.presentation.detail import android.view.View import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import androidx.navigation.navGraphViewModels import com.joe.transactionsapp.R import com.joe.transactionsapp.business.domain.state.StateMessageCallback import com.joe.transactionsapp.databinding.FragmentTransactionDetailBinding import com.joe.transactionsapp.framework.presentation.base.BaseFragment import com.joe.transactionsapp.framework.presentation.detail.state.TransactionStateEvent.* import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview @FlowPreview @ExperimentalCoroutinesApi @AndroidEntryPoint class TransactionDetailFragment : BaseFragment<TransactionDetailViewModel, FragmentTransactionDetailBinding>(R.layout.fragment_transaction_detail) { override val viewModel: TransactionDetailViewModel by viewModels() override fun setupChannel() { viewModel.setupChannel() } override fun subscribeObservers() { viewModel.viewState.observe(viewLifecycleOwner, { viewState -> viewState?.apply { transaction?.let { transactionModel -> binding.tvSummary.text = transactionModel.summary binding.tvCredit.text = transactionModel.credit.toString() binding.tvDebit.text = transactionModel.debit.toString() binding.tvDate.text = transactionModel.transactionDate } } }) viewModel.shouldDisplayProgressBar.observe(viewLifecycleOwner, { uiController.displayProgressBar(it) }) viewModel.stateMessage.observe(viewLifecycleOwner, { stateMessage -> stateMessage?.let { uiController.onResponseReceived( response = stateMessage.response, stateMessageCallback = object : StateMessageCallback { override fun removeMessageFromStack() { viewModel.clearStateMessage() } } ) } }) } override fun initBinding(view: View): FragmentTransactionDetailBinding = FragmentTransactionDetailBinding.bind(view) override fun init() { setupEvent() } private fun setupEvent() { viewModel.searchTransactionByIdInCache() } }
0
Kotlin
1
3
6b0c238fba80dd040765b90c108145869dae15b2
2,522
TransactionsApp
MIT License
src/main/kotlin/com/lightbend/akka/sample/Printer.kt
harry-uglow
136,621,983
true
{"Kotlin": 65158, "Shell": 11857, "Batchfile": 1373, "Scala": 276}
package com.lightbend.akka.sample import akka.actor.AbstractActor import akka.actor.Props import akka.event.Logging class Printer : AbstractActor() { private val log = Logging.getLogger(context.system, this) class Greeting(val message: String) override fun createReceive(): AbstractActor.Receive { return receiveBuilder() .match(Greeting::class.java) { greeting -> log.info(greeting.message) } .build() } companion object { fun props(): Props { return Props.create(Printer::class.java) { Printer() } } } }
0
Kotlin
1
1
218c91f6c1cb2f37c2669d1abe64e5afdc39da58
558
akka-quickstart-kotlin
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/lightbend/akka/sample/Printer.kt
harry-uglow
136,621,983
true
{"Kotlin": 65158, "Shell": 11857, "Batchfile": 1373, "Scala": 276}
package com.lightbend.akka.sample import akka.actor.AbstractActor import akka.actor.Props import akka.event.Logging class Printer : AbstractActor() { private val log = Logging.getLogger(context.system, this) class Greeting(val message: String) override fun createReceive(): AbstractActor.Receive { return receiveBuilder() .match(Greeting::class.java) { greeting -> log.info(greeting.message) } .build() } companion object { fun props(): Props { return Props.create(Printer::class.java) { Printer() } } } }
0
Kotlin
1
1
218c91f6c1cb2f37c2669d1abe64e5afdc39da58
558
akka-quickstart-kotlin
Creative Commons Zero v1.0 Universal