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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/test/kotlin/no/nav/syfo/service/InntektsmeldingArbeidsgiver.kt | navikt | 121,716,621 | false | {"Kotlin": 371409, "Dockerfile": 440} | package no.nav.syfo.syfoinntektsmelding.consumer.ws
import no.nav.syfo.domain.Periode
import java.time.format.DateTimeFormatter
import java.util.function.BinaryOperator
fun inntektsmeldingArbeidsgiver(perioder: List<Periode>, fnr: String = "fnr"): String {
return "<ns6:melding xmlns:ns6=\"http://seres.no/xsd/NAV/Inntektsmelding_M/20180924\">" +
" <ns6:Skjemainnhold>" +
" <ns6:ytelse>Sykepenger</ns6:ytelse>" +
" <ns6:aarsakTilInnsending>Ny</ns6:aarsakTilInnsending>" +
" <ns6:arbeidsgiver>" +
" <ns6:virksomhetsnummer>orgnummer</ns6:virksomhetsnummer>" +
" <ns6:kontaktinformasjon>" +
" <ns6:kontaktinformasjonNavn><NAME></ns6:kontaktinformasjonNavn>" +
" <ns6:telefonnummer>81549300</ns6:telefonnummer>" +
" </ns6:kontaktinformasjon>" +
" </ns6:arbeidsgiver>" +
" <ns6:arbeidstakerFnr>" + fnr + "</ns6:arbeidstakerFnr>" +
" <ns6:naerRelasjon>false</ns6:naerRelasjon>" +
" <ns6:arbeidsforhold>" +
" <ns6:foersteFravaersdag>2019-02-01</ns6:foersteFravaersdag>" +
" <ns6:beregnetInntekt>" +
" <ns6:beloep>2000</ns6:beloep>" +
" </ns6:beregnetInntekt>" +
" <ns6:avtaltFerieListe/>" +
" <ns6:utsettelseAvForeldrepengerListe/>" +
" <ns6:graderingIForeldrepengerListe/>" +
" </ns6:arbeidsforhold>" +
" <ns6:refusjon>" +
" <ns6:endringIRefusjonListe/>" +
" </ns6:refusjon>" +
" <ns6:sykepengerIArbeidsgiverperioden>" +
" <ns6:arbeidsgiverperiodeListe>" +
perioder.stream().map { (fom, tom) ->
"<ns6:arbeidsgiverperiode>" +
" <ns6:fom>" + DateTimeFormatter.ISO_DATE.format(fom) + "</ns6:fom>" +
" <ns6:tom>" + DateTimeFormatter.ISO_DATE.format(tom) + "</ns6:tom>" +
"</ns6:arbeidsgiverperiode>"
}.reduce("", BinaryOperator<String> { obj, str -> obj + str }) +
" </ns6:arbeidsgiverperiodeListe>" +
" <ns6:bruttoUtbetalt>2000</ns6:bruttoUtbetalt>" +
" </ns6:sykepengerIArbeidsgiverperioden>" +
" <ns6:opphoerAvNaturalytelseListe/>" +
" <ns6:gjenopptakelseNaturalytelseListe/>" +
" <ns6:avsendersystem>" +
" <ns6:systemnavn>AltinnPortal</ns6:systemnavn>" +
" <ns6:systemversjon>1.0</ns6:systemversjon>" +
" </ns6:avsendersystem>" +
" <ns6:pleiepengerPerioder/>" +
" <ns6:omsorgspenger>" +
" <ns6:fravaersPerioder/>" +
" <ns6:delvisFravaersListe/>" +
" </ns6:omsorgspenger>" +
" </ns6:Skjemainnhold>" +
"</ns6:melding>"
}
| 9 | Kotlin | 3 | 4 | d16ed2d3f7cd7e5817ae5e423372dc5227ebc53c | 3,006 | syfoinntektsmelding | MIT License |
Advent_of_Code/2022/Kotlin/src/Day_05/Day_05.kt | zubie7a | 2,922,675 | false | {"Python": 327697, "C++": 281393, "Perl": 75318, "Kotlin": 72776} | fun main() {
fun part1(input: List<String>): String {
// For simplicity, let's say the crates rows are those that have "[" somewhere.
val cratesRows = input.filter { it.contains("[") }
// For simplicity, let's say the instruction rows are those that don't have "[".
val nonCratesRows = input.filter { !it.contains("[") }.filter { it.isNotBlank() }
// The first row of the non crate rows indicates the columns index.
val indexes = nonCratesRows[0]
/*
[D]
[N] [C]
[Z] [M] [P]
1 2 3
The representation in code will be:
val graph = mutableMapOf<Int, List<Char>>()
{ 1=[Z, N], 2=[M, C, D], 3=[P] }
Key: a column id
Value: a list of crate ids in that column.
The graph is built bottom up meaning the last element on each list will be the
element at the top of the column.
*/
val graph = mutableMapOf<Int, MutableList<Char>>()
indexes.forEachIndexed { index, char ->
if (char.isDigit()) {
// A list to contain the crates ids of a row.
graph[char.digitToInt()] = mutableListOf()
cratesRows.reversed().forEach { crateRow ->
if (index < crateRow.length && crateRow[index].isLetter()) {
// Because iterating rows in reverse, last element of the column ids
// list will be the id of the crate that's at the top of column.
graph[char.digitToInt()]!!.add(crateRow[index])
}
}
}
}
// Now evaluate the instructions
nonCratesRows.subList(1, nonCratesRows.size).forEach { instructionRow ->
// We are assuming that an instruction has this format:
// "Move X from Y to Z" where X, Y, and Z are integers.
val instruction = instructionRow
.split(" ")
.mapNotNull { it.toIntOrNull() }
val amount = instruction[0]
val source = instruction[1]
val target = instruction[2]
// Start moving boxes, one by one from the one at the top, meaning repeated
// operations on same columns will move boxes in opposite order to target column.
for (op in 0 until amount) {
val sourceColumn = graph[source]!!
val targetColumn = graph[target]!!
val crateId = sourceColumn.removeLast()
targetColumn.add(crateId)
}
}
// Take the ids of the crates at the end/top of each column.
return graph.map { it.value.last() }.joinToString(separator = "")
}
fun part2(input: List<String>): String {
// For simplicity, let's say the crates rows are those that have "[" somewhere.
val cratesRows = input.filter { it.contains("[") }
// For simplicity, let's say the instruction rows are those that don't have "[".
val nonCratesRows = input.filter { !it.contains("[") }.filter { it.isNotBlank() }
// The first row of the non crate rows indicates the columns index.
val indexes = nonCratesRows[0]
/*
[D]
[N] [C]
[Z] [M] [P]
1 2 3
The representation in code will be:
val graph = mutableMapOf<Int, List<Char>>()
{ 1=[Z, N], 2=[M, C, D], 3=[P] }
Key: a column id
Value: a list of crate ids in that column.
The graph is built bottom up meaning the last element on each list will be the
element at the top of the column.
*/
val graph = mutableMapOf<Int, MutableList<Char>>()
indexes.forEachIndexed { index, char ->
if (char.isDigit()) {
// A list to contain the crates ids of a row.
graph[char.digitToInt()] = mutableListOf()
cratesRows.reversed().forEach { crateRow ->
if (index < crateRow.length && crateRow[index].isLetter()) {
// Because iterating rows in reverse, last element of the column ids
// list will be the id of the crate that's at the top of column.
graph[char.digitToInt()]!!.add(crateRow[index])
}
}
}
}
// Now evaluate the instructions
nonCratesRows.subList(1, nonCratesRows.size).forEach { instructionRow ->
// We are assuming that an instruction has this format:
// "Move X from Y to Z" where X, Y, and Z are integers.
val instruction = instructionRow
.split(" ")
.mapNotNull { it.toIntOrNull() }
val amount = instruction[0]
val source = instruction[1]
val target = instruction[2]
val sourceColumn = graph[source]!!
val targetColumn = graph[target]!!
// Start moving boxes, all together from the one at the top, meaning the boxes
// will preserve their order when moved to the new column.
val crateIds = sourceColumn.subList(sourceColumn.size - amount, sourceColumn.size)
graph[source] = sourceColumn.subList(0, sourceColumn.size - amount)
targetColumn.addAll(crateIds)
}
// Take the ids of the crates at the end/top of each column.
return graph.map { it.value.last() }.joinToString(separator = "")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day_05/test_input")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day_05/input")
println(part1(input))
println(part2(input))
}
| 0 | Python | 2 | 7 | e33d77ae3343e7ac60c0c2f59ce7bf9cea7a133f | 5,964 | Algorithms | MIT License |
app/src/main/java/com/mustafa/movieguideapp/view/ui/movies/moviedetail/MovieDetailFragment.kt | Mustafashahoud | 231,958,118 | false | null | package com.mustafa.movieguideapp.view.ui.movies.moviedetail
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.databinding.DataBindingComponent
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import com.mustafa.movieguideapp.R
import com.mustafa.movieguideapp.api.Api
import com.mustafa.movieguideapp.binding.FragmentDataBindingComponent
import com.mustafa.movieguideapp.databinding.FragmentMovieDetailBinding
import com.mustafa.movieguideapp.di.Injectable
import com.mustafa.movieguideapp.models.entity.Movie
import com.mustafa.movieguideapp.utils.autoCleared
import com.mustafa.movieguideapp.view.adapter.ReviewListAdapter
import com.mustafa.movieguideapp.view.adapter.VideoListAdapter
import javax.inject.Inject
class MovieDetailFragment : Fragment(R.layout.fragment_movie_detail),
Injectable {
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
private val viewModel by viewModels<MovieDetailViewModel> { viewModelFactory }
var dataBindingComponent: DataBindingComponent = FragmentDataBindingComponent(this)
private var binding by autoCleared<FragmentMovieDetailBinding>()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding = DataBindingUtil.bind(view, dataBindingComponent)!!
initializeUI()
val movieArg = getMovieSafeArgs()
with(binding) {
lifecycleOwner = [email protected]
movie = movieArg
detailBody.viewmodel = viewModel
}
viewModel.setMovieId(movieArg.id)
}
private fun initializeUI() {
with(binding.detailBody) {
detailBodyRecyclerViewTrailers.adapter =
VideoListAdapter(dataBindingComponent) {
val playVideoIntent =
Intent(Intent.ACTION_VIEW, Uri.parse(Api.getYoutubeVideoPath(it.key)))
startActivity(playVideoIntent)
}
detailBodyRecyclerViewReviews.adapter = ReviewListAdapter(dataBindingComponent)
}
}
private fun getMovieSafeArgs(): Movie {
val params =
MovieDetailFragmentArgs.fromBundle(
requireArguments()
)
return params.movie
}
}
| 2 | Kotlin | 10 | 98 | 5f12624e566610349ba31d1eece34a32b90aa344 | 2,448 | MoviesApp | Apache License 2.0 |
app/src/main/java/com/skydoves/githubfollows/view/adapter/DetailAdapter.kt | MaTriXy | 198,682,032 | true | {"Kotlin": 103410} | package com.skydoves.githubfollows.view.adapter
import android.view.View
import com.skydoves.baserecyclerviewadapter.BaseAdapter
import com.skydoves.baserecyclerviewadapter.SectionRow
import com.skydoves.githubfollows.R
import com.skydoves.githubfollows.models.ItemDetail
import com.skydoves.githubfollows.view.viewholder.DetailViewHolder
/**
* Developed by skydoves on 2018-01-28.
* Copyright (c) 2018 skydoves rights reserved.
*/
@Suppress("PrivatePropertyName")
class DetailAdapter : BaseAdapter() {
private val section_itemDetail = 0
fun addItemDetailList(itemDetail: List<ItemDetail>) {
clearAllSections()
addSection(ArrayList<ItemDetail>())
for (item in itemDetail) {
if (item.content.isNotEmpty()) {
addItemOnSection(section_itemDetail, item)
}
}
notifyDataSetChanged()
}
override fun layout(sectionRow: SectionRow) = R.layout.item_detail_info
override fun viewHolder(layout: Int, view: View) = DetailViewHolder(view)
}
| 0 | Kotlin | 0 | 0 | c62e12e141d1feaa4fad99158ebf511ac4f2102b | 987 | GithubFollows | MIT License |
app/src/main/java/com/myweather/app/network/model/Wind.kt | a7madwaseem | 250,847,882 | false | null | package com.myweather.app.network.model
import android.annotation.SuppressLint
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
/**
* Created by <NAME> on 28/03/2020
*/
@SuppressLint("ParcelCreator")
@Parcelize
data class Wind(
@SerializedName("speed")
val speed: Double
) : Parcelable {
fun getWindSeed(): String {
return speed.toString()
}
} | 0 | Kotlin | 0 | 0 | 0a3261bf18935f634c29610e72bf7bc88ce3a2b7 | 441 | My-weather | Apache License 2.0 |
app/src/main/java/com/shuyu/github/kotlin/di/MainActivityModule.kt | CarGuo | 156,679,291 | false | null | package com.shuyu.github.kotlin.di
import android.app.Application
import android.graphics.Color
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.mikepenz.iconics.IconicsColor
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.utils.sizeDp
import com.shuyu.github.kotlin.R
import com.shuyu.github.kotlin.common.style.GSYIconfont
import com.shuyu.github.kotlin.module.dynamic.DynamicFragment
import com.shuyu.github.kotlin.module.my.MyFragment
import com.shuyu.github.kotlin.module.trend.TrendFragment
import dagger.Module
import dagger.Provides
import devlight.io.library.ntb.NavigationTabBar
/**
* MainActivity注入需要的Module
* Created by guoshuyu
* Date: 2018-09-28
*/
@Module
class MainActivityModule {
@Provides
fun providerMainFragmentList(): List<Fragment> {
return listOf(DynamicFragment(), TrendFragment(), MyFragment())
}
@Provides
fun providerMainTabModel(application: Application): List<NavigationTabBar.Model> {
return listOf(
NavigationTabBar.Model.Builder(
IconicsDrawable(application)
.icon(GSYIconfont.Icon.GSY_MAIN_DT)
.color(IconicsColor.colorInt(R.color.subTextColor))
.sizeDp(20),
Color.parseColor("#00000000"))
.title(application.getString(R.string.tabDynamic))
.build(),
NavigationTabBar.Model.Builder(
IconicsDrawable(application)
.icon(GSYIconfont.Icon.GSY_MAIN_QS)
.color(IconicsColor.colorInt(R.color.subTextColor))
.sizeDp(20),
Color.parseColor("#00000000"))
.title(application.getString(R.string.tabRecommended))
.build(),
NavigationTabBar.Model.Builder(
IconicsDrawable(application)
.icon(GSYIconfont.Icon.GSY_MAIN_MY)
.color(IconicsColor.colorInt(R.color.subTextColor))
.sizeDp(20),
Color.parseColor("#00000000"))
.title(application.getString(R.string.tabMy))
.build()
)
}
}
| 4 | Kotlin | 232 | 1,312 | a8c0697f92dea388a3cf86aed26db12ddde640f5 | 2,447 | GSYGithubAppKotlin | Apache License 2.0 |
app/src/main/java/com/example/motostranacompose/di/ViewModelModule.kt | FunnyRider34Rus | 602,934,577 | false | null | package com.example.motostranacompose.di
import android.app.Application
import android.content.Context
import com.example.motostranacompose.R
import com.example.motostranacompose.core.Constants.SIGN_IN_REQUEST
import com.example.motostranacompose.core.Constants.SIGN_UP_REQUEST
import com.example.motostranacompose.data.repository.AuthRepositoryImpl
import com.example.motostranacompose.domain.repository.AuthRepository
import com.google.android.gms.auth.api.identity.BeginSignInRequest
import com.google.android.gms.auth.api.identity.Identity
import com.google.android.gms.auth.api.identity.SignInClient
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ViewModelComponent
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Named
@Module
@InstallIn(ViewModelComponent::class)
class ViewModelModule {
@Provides
fun provideAuthRepository(
auth: FirebaseAuth,
oneTapClient: SignInClient,
@Named(SIGN_IN_REQUEST)
signInRequest: BeginSignInRequest,
@Named(SIGN_UP_REQUEST)
signUpRequest: BeginSignInRequest,
signInClient: GoogleSignInClient,
firestore: FirebaseFirestore
): AuthRepository = AuthRepositoryImpl(
auth = auth,
oneTapClient = oneTapClient,
signInRequest = signInRequest,
signUpRequest = signUpRequest,
signInClient = signInClient,
firestore = firestore
)
@Provides
fun provideOneTapClient(
@ApplicationContext
context: Context
) = Identity.getSignInClient(context)
@Provides
@Named(SIGN_IN_REQUEST)
fun provideSignInRequest(
app: Application
) = BeginSignInRequest.builder()
.setGoogleIdTokenRequestOptions(
BeginSignInRequest.GoogleIdTokenRequestOptions.builder()
.setSupported(true)
.setServerClientId(app.getString(R.string.web_client_id))
.setFilterByAuthorizedAccounts(true)
.build()
)
.setAutoSelectEnabled(true)
.build()
@Provides
@Named(SIGN_UP_REQUEST)
fun provideSignUpRequest(
app: Application
) = BeginSignInRequest.builder()
.setGoogleIdTokenRequestOptions(
BeginSignInRequest.GoogleIdTokenRequestOptions.builder()
.setSupported(true)
.setServerClientId(app.getString(R.string.web_client_id))
.setFilterByAuthorizedAccounts(false)
.build()
)
.build()
@Provides
fun provideGoogleSignInOptions(
app: Application
) = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(app.getString(R.string.web_client_id))
.requestEmail()
.build()
@Provides
fun provideGoogleSignInClient(
app: Application,
options: GoogleSignInOptions
) = GoogleSignIn.getClient(app, options)
} | 0 | Kotlin | 0 | 0 | c9edf33abec1ff1b550543114aafa0de4e136092 | 3,279 | MotoStranaCompose | Apache License 2.0 |
app/src/main/java/com/example/motostranacompose/di/ViewModelModule.kt | FunnyRider34Rus | 602,934,577 | false | null | package com.example.motostranacompose.di
import android.app.Application
import android.content.Context
import com.example.motostranacompose.R
import com.example.motostranacompose.core.Constants.SIGN_IN_REQUEST
import com.example.motostranacompose.core.Constants.SIGN_UP_REQUEST
import com.example.motostranacompose.data.repository.AuthRepositoryImpl
import com.example.motostranacompose.domain.repository.AuthRepository
import com.google.android.gms.auth.api.identity.BeginSignInRequest
import com.google.android.gms.auth.api.identity.Identity
import com.google.android.gms.auth.api.identity.SignInClient
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ViewModelComponent
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Named
@Module
@InstallIn(ViewModelComponent::class)
class ViewModelModule {
@Provides
fun provideAuthRepository(
auth: FirebaseAuth,
oneTapClient: SignInClient,
@Named(SIGN_IN_REQUEST)
signInRequest: BeginSignInRequest,
@Named(SIGN_UP_REQUEST)
signUpRequest: BeginSignInRequest,
signInClient: GoogleSignInClient,
firestore: FirebaseFirestore
): AuthRepository = AuthRepositoryImpl(
auth = auth,
oneTapClient = oneTapClient,
signInRequest = signInRequest,
signUpRequest = signUpRequest,
signInClient = signInClient,
firestore = firestore
)
@Provides
fun provideOneTapClient(
@ApplicationContext
context: Context
) = Identity.getSignInClient(context)
@Provides
@Named(SIGN_IN_REQUEST)
fun provideSignInRequest(
app: Application
) = BeginSignInRequest.builder()
.setGoogleIdTokenRequestOptions(
BeginSignInRequest.GoogleIdTokenRequestOptions.builder()
.setSupported(true)
.setServerClientId(app.getString(R.string.web_client_id))
.setFilterByAuthorizedAccounts(true)
.build()
)
.setAutoSelectEnabled(true)
.build()
@Provides
@Named(SIGN_UP_REQUEST)
fun provideSignUpRequest(
app: Application
) = BeginSignInRequest.builder()
.setGoogleIdTokenRequestOptions(
BeginSignInRequest.GoogleIdTokenRequestOptions.builder()
.setSupported(true)
.setServerClientId(app.getString(R.string.web_client_id))
.setFilterByAuthorizedAccounts(false)
.build()
)
.build()
@Provides
fun provideGoogleSignInOptions(
app: Application
) = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(app.getString(R.string.web_client_id))
.requestEmail()
.build()
@Provides
fun provideGoogleSignInClient(
app: Application,
options: GoogleSignInOptions
) = GoogleSignIn.getClient(app, options)
} | 0 | Kotlin | 0 | 0 | c9edf33abec1ff1b550543114aafa0de4e136092 | 3,279 | MotoStranaCompose | Apache License 2.0 |
app/src/main/java/com/niceplaces/niceplaces/dao/DaoLists.kt | niceplaces | 460,602,891 | false | null | package com.niceplaces.niceplaces.dao
import android.content.Context
import android.util.Log
import android.widget.Toast
import com.android.volley.Request
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.niceplaces.niceplaces.Const
import com.niceplaces.niceplaces.R
import com.niceplaces.niceplaces.controllers.PrefsController
import com.niceplaces.niceplaces.models.Place
import com.niceplaces.niceplaces.models.PlacesList
import com.niceplaces.niceplaces.utils.AppUtils
import com.niceplaces.niceplaces.utils.MyRunnable
import org.json.JSONArray
import org.json.JSONException
import java.util.*
class DaoLists(private val mContext: Context) {
private val mDbMode: String?
private val isItalian: Boolean
fun getAll(successCallback: MyRunnable, errorCallback: Runnable) {
val queue = Volley.newRequestQueue(mContext)
val url = Const.DATA_PATH + mDbMode + "/lists"
Log.i(AppUtils.tag, "HTTP request $url")
val stringRequest = StringRequest(Request.Method.GET, url,
{ response ->
try {
val jsonArray = JSONArray(response)
Log.i(AppUtils.tag, "HTTP response array length: " + jsonArray.length())
val buffer: MutableList<PlacesList> = ArrayList()
for (i in 0 until jsonArray.length()) {
val jsonObject = jsonArray.getJSONObject(i)
var name = jsonObject.getString("name_en")
if (name == "" || isItalian) {
name = jsonObject.getString("name")
}
var description = jsonObject.getString("description_en")
if (description == "" || isItalian) {
description = jsonObject.getString("description")
}
val list = PlacesList(jsonObject.getString("id"),
name,
description,
jsonObject.getString("count"))
buffer.add(list)
}
successCallback.lists = buffer
successCallback.run()
} catch (e: JSONException) {
e.printStackTrace()
errorCallback.run()
}
}, {
errorCallback.run()
Toast.makeText(mContext, R.string.connection_error, Toast.LENGTH_LONG).show()
})
queue.add(stringRequest)
}
fun getPlacesByListId(id: String, successCallback: MyRunnable, errorCallback: Runnable) {
val queue = Volley.newRequestQueue(mContext)
val url = Const.DATA_PATH + mDbMode + "/lists/" + id
Log.i(AppUtils.tag, "HTTP request $url")
val stringRequest = StringRequest(Request.Method.GET, url,
{ response ->
try {
val jsonArray = JSONArray(response)
val buffer: MutableList<Place> = ArrayList()
for (i in 0 until jsonArray.length()) {
val jsonObject = jsonArray.getJSONObject(i)
var name = jsonObject.getString("name_en")
if (name == "" || Locale.getDefault().displayLanguage == Locale.ITALIAN.displayLanguage) {
name = jsonObject.getString("name")
}
var area = jsonObject.getString("area_en")
if (area == "" || Locale.getDefault().displayLanguage == Locale.ITALIAN.displayLanguage) {
area = jsonObject.getString("area")
}
var region = jsonObject.getString("region_en")
if (region == "" || Locale.getDefault().displayLanguage == Locale.ITALIAN.displayLanguage) {
region = jsonObject.getString("region")
}
var hasDescription = jsonObject.getBoolean("has_description_en")
if (Locale.getDefault().displayLanguage == Locale.ITALIAN.displayLanguage) {
hasDescription = jsonObject.getBoolean("has_description")
}
val place = Place(jsonObject.getString("id"),
name,
area,
region,
jsonObject.getString("image"),
hasDescription,
jsonObject.getString("author"),
jsonObject.getString("wiki_url"))
buffer.add(place)
}
successCallback.places = buffer
successCallback.run()
} catch (e: JSONException) {
e.printStackTrace()
}
}, {
errorCallback.run()
Toast.makeText(mContext, R.string.connection_error, Toast.LENGTH_LONG).show()
})
stringRequest.setShouldCache(false)
queue.add(stringRequest)
}
init {
val prefs = PrefsController(mContext)
mDbMode = prefs.databaseMode
isItalian = Locale.getDefault().displayLanguage == Locale.ITALIAN.displayLanguage
}
} | 3 | Kotlin | 2 | 3 | 71e4c002adb34ceda5145f1a3d0ee57b0190d06f | 5,463 | android-app | MIT License |
kibaan/src/main/java/kibaan/android/ios/DispatchGroup.kt | Kibaan | 160,439,455 | false | null | package kibaan.android.ios
class DispatchGroup {
var waitingCount = 0
var work: (() -> Unit)? = null
var post: ((() -> Unit) -> Unit)? = null
fun enter() {
waitingCount++
}
var isChecking = false
fun leave() {
if (waitingCount == 0) {
throw IllegalStateException("This DispatchGroup can't leave anymore.")
}
waitingCount--
postCheck()
}
fun notify(post: (() -> Unit) -> Unit, work: () -> Unit) {
this.work = work
this.post = post
postCheck()
}
private fun postCheck() {
if (waitingCount == 0 && !isChecking) {
isChecking = true
val post = post
if (post != null) {
post.invoke {
checkAndCallback()
isChecking = false
}
} else {
isChecking = false
}
}
}
private fun checkAndCallback() {
if (waitingCount == 0) {
work?.invoke()
}
}
} | 1 | Kotlin | 1 | 1 | 883d30c546a05667008fff9806371f0bf6001cfa | 1,063 | Android-Kibaan | Apache License 2.0 |
domain/src/main/java/com/bottlerocketstudios/brarchitecture/domain/models/DomainModel.kt | BottleRocketStudios | 323,985,026 | false | null | package com.bottlerocketstudios.brarchitecture.data.model
/**
* [Marker interface](https://en.wikipedia.org/wiki/Marker_interface_pattern) for all [DomainModel]s used in the app to quickly/easily find them.
*
* [DomainModel]s exist to be a primary representation of data that is used throughout the app that has already been preprocessed (deserialized) from some "dirty" model such as the network/database/etc.
* [DomainModel]s shouldn't have json serialization/deserialization logic (that should be represented by a [Dto]).
*
* > ... a business object (Domain Model) usually does nothing itself but holds a set of instance variables or properties, also known as attributes, and associations with other business objects,
* weaving a map of objects representing the business relationships.
*
* More info at:
* * https://confluence.bottlerocketapps.com/display/BKB/Common+Code+Quality+Issues#CommonCodeQualityIssues-Datamodels
* * https://en.wikipedia.org/wiki/Domain_model
* * https://www.martinfowler.com/eaaCatalog/domainModel.html
* * https://en.wikipedia.org/wiki/Business_object
*
* See [Dto] for related information.
*/
interface DomainModel
| 1 | Kotlin | 1 | 9 | e8541ccaa52782c5c2440b8a4fe861ef9178111e | 1,164 | Android-ArchitectureDemo | Apache License 2.0 |
src/main/kotlin/nl/enjarai/essentialsnt/Essentialsnt.kt | enjarai | 429,325,664 | false | null | package nl.enjarai.essentialsnt
import net.fabricmc.api.ModInitializer
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents
import net.fabricmc.loader.api.FabricLoader
import net.minecraft.server.MinecraftServer
import nl.enjarai.essentialsnt.commands.*
import nl.enjarai.essentialsnt.commands.dayvote.DayVoteCommand
import nl.enjarai.essentialsnt.config.GeneralConfig
import nl.enjarai.essentialsnt.config.MessagesConfig
import nl.enjarai.essentialsnt.config.ModConfig
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.Logger
import java.util.*
object Essentialsnt : ModInitializer {
const val MODID = "essentialsnt"
val LOGGER: Logger = LogManager.getLogger(MODID)
val CONFIG_DIR = FabricLoader.getInstance().configDir.resolve(MODID)
lateinit var GENERAL_CONFIG: GeneralConfig
lateinit var MESSAGES_CONFIG: MessagesConfig
lateinit var SERVER: MinecraftServer
override fun onInitialize() {
ServerLifecycleEvents.SERVER_STARTING.register { SERVER = it }
CONFIG_DIR.toFile().mkdir()
reloadConfig()
ManagementCommands.register()
SpawnCommands.register()
WarpCommands.register()
WildCommands.register()
MessageCommands.register()
DayVoteCommand.register()
val timer = Timer()
timer.schedule(object : TimerTask() {
override fun run() {
GENERAL_CONFIG.save()
MESSAGES_CONFIG.save()
}
}, 60000, 60000)
LOGGER.info("Essentials is bad lol, even i can do better")
}
fun reloadConfig() {
GENERAL_CONFIG = ModConfig.loadConfigFile(GeneralConfig::class.java)
MESSAGES_CONFIG = ModConfig.loadConfigFile(MessagesConfig::class.java)
}
} | 0 | Kotlin | 0 | 0 | c74a288f4f2c0fbdc60b63f2f632f37f20e9ba8b | 1,791 | essentialsnt | MIT License |
model/src/main/kotlin/zama/giacomo/simplelogo/model/utils/Utils.kt | giacomozama | 452,053,863 | false | {"Kotlin": 44277, "ANTLR": 3570} | package zama.giacomo.simplelogo.model.utils
fun euclideanMod(n: Double, mod: Int) = if (n < 0) (n % mod + mod) % mod else n % mod | 0 | Kotlin | 0 | 0 | 464f04e0eff7501d4916b1b975a427e3ed1fa341 | 130 | simplelogo | MIT License |
app/common/src/main/kotlin/me/zhanghai/android/files/features/ftpserver/FtpServerTileService.kt | overphoenix | 621,371,055 | false | null | package me.zhanghai.android.files.features.ftpserver
import android.os.Build
import android.service.quicksettings.Tile
import android.service.quicksettings.TileService
import androidx.annotation.RequiresApi
import androidx.lifecycle.Observer
@RequiresApi(Build.VERSION_CODES.N)
class FtpServerTileService : TileService() {
private val observer = Observer<FtpServerService.State> { onFtpServerStateChanged(it) }
override fun onStartListening() {
super.onStartListening()
FtpServerService.stateLiveData.observeForever(observer)
}
override fun onStopListening() {
super.onStopListening()
FtpServerService.stateLiveData.removeObserver(observer)
}
private fun onFtpServerStateChanged(state: FtpServerService.State) {
val tile = qsTile
when (state) {
FtpServerService.State.STARTING, FtpServerService.State.RUNNING ->
tile.state = Tile.STATE_ACTIVE
FtpServerService.State.STOPPING -> tile.state = Tile.STATE_UNAVAILABLE
FtpServerService.State.STOPPED -> tile.state = Tile.STATE_INACTIVE
}
tile.updateTile()
}
override fun onClick() {
super.onClick()
if (isLocked) {
unlockAndRun { toggle() }
} else {
toggle()
}
}
private fun toggle() {
FtpServerService.toggle(this)
}
}
| 0 | Kotlin | 0 | 0 | 64264f261c2138d5f1932789702661917bbfae28 | 1,399 | phoenix-android | Apache License 2.0 |
src/main/kotlin/com/khekrn/jobpull/config/FlywayConfiguration.kt | khekrn | 589,942,220 | false | null | package com.khekrn.jobpull.config
import org.flywaydb.core.Flyway
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.env.Environment
@Configuration
class FlywayConfiguration(private val env: Environment) {
@Bean(initMethod = "migrate")
fun flyway(): Flyway {
return Flyway(
Flyway.configure()
.dataSource(
env.getRequiredProperty("spring.flyway.url"),
env.getRequiredProperty("spring.flyway.user"),
env.getRequiredProperty("spring.flyway.password")
)
.schemas("jobpull").baselineOnMigrate(true)
)
}
} | 0 | Kotlin | 0 | 0 | 623be9c56a02a332d1689e7fd3c52da9effac789 | 742 | jobpull | Apache License 2.0 |
app/src/main/java/com/example/fintrack/MonyEntity.kt | alanliongar | 827,734,561 | false | {"Kotlin": 45447} | package com.example.fintrack
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
@Entity(
indices = [Index(value = ["name", "cat", "val"], unique = true)],
foreignKeys = [ForeignKey(
entity = CatEntity::class,
parentColumns = ["key"],
childColumns = ["cat"]
)]
)
data class MonyEntity(
@PrimaryKey(autoGenerate = true)
val id: Long = 0,
@ColumnInfo("name")
val name: String,
@ColumnInfo("cat")
val category: String,
@ColumnInfo("val")
val value: Double
) | 0 | Kotlin | 0 | 1 | 03605c691bef658ba502d985fc01e9e9158cbf06 | 624 | Des4_FinTrack_00 | The Unlicense |
app/src/main/java/vinova/intern/best_trip/model/User.kt | uongsyphuong | 139,782,638 | false | {"Kotlin": 85846} | package vinova.intern.best_trip.model
import android.os.Parcel
import android.os.Parcelable
class User :Parcelable {
var username: String =""
var image: String = ""
var email: String = ""
constructor(parcel: Parcel) : this() {
username = parcel.readString()
image = parcel.readString()
email = parcel.readString()
}
constructor()
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(username)
parcel.writeString(image)
parcel.writeString(email)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<User> {
override fun createFromParcel(parcel: Parcel): User {
return User(parcel)
}
override fun newArray(size: Int): Array<User?> {
return arrayOfNulls(size)
}
}
} | 0 | Kotlin | 0 | 0 | c7345d75fba1d189f660f6623171c67f3a291dd0 | 899 | Best-Trip | Apache License 2.0 |
catalog/src/main/java/net/pixiv/charcoal/android/catalog/button/ButtonDefaultMListItem.kt | pixiv | 580,258,047 | false | {"Kotlin": 120287, "JavaScript": 12005, "Java": 2332} | package net.pixiv.charcoal.android.catalog.button
import android.view.View
import com.xwray.groupie.viewbinding.BindableItem
import net.pixiv.charcoal.android.catalog.R
import net.pixiv.charcoal.android.catalog.databinding.ViewHolderButtonDefaultMBinding
class ButtonDefaultMListItem(private val buttonState: ButtonState) : BindableItem<ViewHolderButtonDefaultMBinding>() {
override fun bind(viewBinding: ViewHolderButtonDefaultMBinding, position: Int) {
viewBinding.label.text = buttonState.label
buttonState.applyState(viewBinding.button)
}
override fun getLayout(): Int = R.layout.view_holder_button_default_m
override fun initializeViewBinding(view: View): ViewHolderButtonDefaultMBinding {
return ViewHolderButtonDefaultMBinding.bind(view)
}
}
| 10 | Kotlin | 5 | 28 | cd47a135bb1101c4171d36f7098eb135f6b53ab1 | 797 | charcoal-android | Apache License 2.0 |
stcspeechkit/src/main/java/ru/speechpro/stcspeechkit/domain/models/DiarizationResponse.kt | STC-VoiceKey | 138,289,130 | false | {"Kotlin": 129142, "Java": 13363} | package ru.speechpro.stcspeechkit.domain.models
import com.fasterxml.jackson.annotation.JsonProperty
/**
* @author <NAME>
*/
data class DiarizationResponse(
@JsonProperty("speakers")
var speakers: List<SpeakersItem>?
) | 0 | Kotlin | 1 | 2 | 83eabbfe0d363226f9554ba7164d9e85a25b50d5 | 230 | stc-speechkit-android | BSD 2-Clause FreeBSD License |
app/src/commonMain/kotlin/de/moviesmpp/presentation/popularmovies/PopularMoviesPresenter.kt | Syex | 181,836,417 | false | null | package de.moviesmpp.presentation.popularmovies
import de.moviesmpp.domain.defaultDispatcher
import de.moviesmpp.domain.model.Movie
import de.moviesmpp.domain.usecase.GetPopularMovies
import de.moviesmpp.domain.usecase.UseCase
import de.moviesmpp.presentation.BasePresenter
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
class PopularMoviesPresenter(
private val getPopularMovies: GetPopularMovies,
coroutineContext: CoroutineContext = defaultDispatcher
) : BasePresenter<PopularMoviesView>(coroutineContext) {
override fun onViewAttached(view: PopularMoviesView) {
view.setLoadingVisible(true)
getPopularMovies()
}
private fun getPopularMovies() {
scope.launch {
getPopularMovies(
UseCase.None,
onSuccess = { view?.setPopularMovies(it.results) },
onFailure = { view?.showMoviesFailedToLoad() }
)
view?.setLoadingVisible(false)
}
}
}
interface PopularMoviesView {
fun setPopularMovies(movies: List<Movie>)
fun showMoviesFailedToLoad()
fun setLoadingVisible(visible: Boolean)
} | 2 | null | 22 | 153 | 973fd24023afdcc5649c727e8c98b4a2f6252ca0 | 1,164 | MoviesMPP | MIT License |
app/shared/time/fake/src/commonMain/kotlin/build/wallet/time/InstantFake.kt | proto-at-block | 761,306,853 | false | {"C": 10424094, "Kotlin": 7156393, "Rust": 2046237, "Swift": 700307, "Python": 331492, "HCL": 271992, "Shell": 111209, "TypeScript": 102700, "C++": 64770, "Meson": 64234, "JavaScript": 36227, "Just": 28071, "Ruby": 9428, "Dockerfile": 5731, "Makefile": 3839, "Open Policy Agent": 1552, "Procfile": 80} | package build.wallet.time
import kotlinx.datetime.Instant
val someInstant = Instant.fromEpochSeconds(epochSeconds = 1231006505)
| 0 | C | 10 | 98 | 1f9f2298919dac77e6791aa3f1dbfd67efe7f83c | 130 | bitkey | MIT License |
remix/src/commonMain/kotlin/com/woowla/compose/icon/collections/remix/remix/media/ImageLine.kt | walter-juan | 868,046,028 | false | {"Kotlin": 34345428} | package com.woowla.compose.icon.collections.remix.remix.media
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.remix.remix.MediaGroup
public val MediaGroup.ImageLine: ImageVector
get() {
if (_imageLine != null) {
return _imageLine!!
}
_imageLine = Builder(name = "ImageLine", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(2.992f, 21.0f)
curveTo(2.444f, 21.0f, 2.0f, 20.555f, 2.0f, 20.007f)
verticalLineTo(3.993f)
curveTo(2.0f, 3.445f, 2.455f, 3.0f, 2.992f, 3.0f)
horizontalLineTo(21.008f)
curveTo(21.556f, 3.0f, 22.0f, 3.445f, 22.0f, 3.993f)
verticalLineTo(20.007f)
curveTo(22.0f, 20.555f, 21.545f, 21.0f, 21.008f, 21.0f)
horizontalLineTo(2.992f)
close()
moveTo(20.0f, 15.0f)
verticalLineTo(5.0f)
horizontalLineTo(4.0f)
verticalLineTo(19.0f)
lineTo(14.0f, 9.0f)
lineTo(20.0f, 15.0f)
close()
moveTo(20.0f, 17.828f)
lineTo(14.0f, 11.828f)
lineTo(6.828f, 19.0f)
horizontalLineTo(20.0f)
verticalLineTo(17.828f)
close()
moveTo(8.0f, 11.0f)
curveTo(6.895f, 11.0f, 6.0f, 10.105f, 6.0f, 9.0f)
curveTo(6.0f, 7.895f, 6.895f, 7.0f, 8.0f, 7.0f)
curveTo(9.105f, 7.0f, 10.0f, 7.895f, 10.0f, 9.0f)
curveTo(10.0f, 10.105f, 9.105f, 11.0f, 8.0f, 11.0f)
close()
}
}
.build()
return _imageLine!!
}
private var _imageLine: ImageVector? = null
| 0 | Kotlin | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 2,555 | compose-icon-collections | MIT License |
app/src/main/java/com/vincent/recipe_mvvm_jetpack/presentation/BaseApplication.kt | VincentGaoHJ | 398,203,841 | false | null | package com.vincent.recipe_mvvm_jetpack.presentation
import android.app.Application
import androidx.compose.runtime.mutableStateOf
import dagger.hilt.android.HiltAndroidApp
/**
* Hilt Generates the components for you automatically and then you define modules
* and install the dependencies into those generated components
*/
@HiltAndroidApp
class BaseApplication : Application() {
val isDark = mutableStateOf(false)
fun toggleLightTheme() {
isDark.value = !isDark.value
}
} | 0 | Kotlin | 0 | 0 | a5ccee3774b5077bf715bf798ee52c8e7271d633 | 500 | Recipe-MVVM-Jetpack | MIT License |
app/src/main/java/com/zasko/boxtool/novel/view/ArticleItemDecoration.kt | Zhangsongsong | 678,715,300 | false | {"Kotlin": 65070, "Java": 642} | package com.zasko.boxtool.novel.view
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration
import com.zasko.boxtool.utils.dp
class ArticleItemDecoration : ItemDecoration() {
private var bottomOffset = 0
init {
bottomOffset = 2.dp
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
super.getItemOffsets(outRect, view, parent, state)
outRect.bottom = bottomOffset
}
} | 0 | Kotlin | 0 | 0 | 950329ac7a67711804549b19902e746f95a74bf0 | 589 | BoxTool | Apache License 2.0 |
core/src/main/kotlin/cib/interns/test/task/core/controller/SocksMapper.kt | divinenickname | 421,182,378 | true | {"Kotlin": 21509, "Java": 5862} | package cib.interns.test.task.core.controller
import cib.interns.test.task.api.SocksFindRequest
import cib.interns.test.task.api.SocksGetResponse
import cib.interns.test.task.api.SocksRequest
import cib.interns.test.task.api.SocksResponse
import cib.interns.test.task.core.service.Socks
import cib.interns.test.task.core.service.SocksFind
import org.mapstruct.Mapper
@Mapper(componentModel = "spring")
interface SocksMapper {
fun transform(obj: SocksRequest): Socks
fun transform(obj: Socks):SocksResponse
fun transform(obj: SocksFindRequest): SocksFind
} | 0 | Kotlin | 0 | 0 | 92bd48d01a9d1114fa045efb76c2c22d10327c10 | 572 | cib-interns-test-task | MIT License |
app/src/main/java/com/aman/roxy/cells/InterstitialView.kt | iamanbansal | 416,477,308 | false | null | package com.aman.roxy.cells
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.constraintlayout.widget.ConstraintLayout
import com.aman.roxy.R
import com.aman.roxy.RoxyContentView
import com.aman.roxy.RoxyModelView
import com.aman.roxy.databinding.LayoutDetailsBinding
import com.aman.roxy.databinding.LayoutInterstitialBinding
import com.aman.roxy.models.Footer
import com.aman.roxy.models.Interstitial
/**
* Created by Aman Bansal on 12/10/21.
*/
@RoxyModelView(viewType = "interstitial")
class InterstitialView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
ConstraintLayout(context, attrs), RoxyContentView<Interstitial> {
private val binding = LayoutInterstitialBinding.inflate(LayoutInflater.from(context),this)
override fun bind(item: Interstitial) {
binding.interstitial.setImageResource(item.image)
}
} | 0 | Kotlin | 0 | 0 | a9fb25f109b31fdd79f5d407d4e5674b1219473a | 968 | RoxyView | Apache License 2.0 |
quranHome/src/commonMain/kotlin/com/islamversity/quran_home/feature/juz/mapper/JuzRepoUIMapper.kt | islamversity | 282,670,969 | false | null | package com.islamversity.quran_home.feature.juz.mapper
import com.islamversity.core.Mapper
import com.islamversity.domain.model.JuzRepoModel
import com.islamversity.quran_home.feature.juz.model.JozUIModel
class JuzRepoUIMapper : Mapper<JuzRepoModel, JozUIModel> {
override fun map(item: JuzRepoModel) =
JozUIModel(
item.juz,
"${item.startingSurahName}: ${item.startingAyaOrder}",
"${item.endingSurahName}: ${item.endingAyaOrder}",
item.startingAyaOrder,
item.startingSurahId,
item.startingSurahName,
)
} | 15 | Kotlin | 7 | 21 | ab825e4951facd7779e0c3fcb0e68720d68a0fa1 | 598 | Reyan | Apache License 2.0 |
app/src/main/java/com/example/mvvm/network/NetworkService.kt | rohitpsoman | 188,019,364 | false | null | package com.example.mvvm.network
import com.example.mvvm.model.PullRequest
import com.example.mvvm.model.Repository
import kotlinx.coroutines.Deferred
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
interface NetworkService {
@GET("{owner_name}/{repo_name}")
fun getRepo(
@Path("owner_name") ownerName: String,
@Path("repo_name") repositoryName: String
): Deferred<Repository>
@GET("{owner_name}/{repo_name}/pulls")
fun getPullRequests(
@Path("owner_name") ownerName: String,
@Path("repo_name") repositoryName: String,
@Query("page") page: Int,
@Query("per_page") perPage: Int,
@Query("state") state: String
): Deferred<List<PullRequest>>
} | 0 | Kotlin | 3 | 22 | 54387ac38a50d8f9a3d1f3921f38c0f84aa702b2 | 757 | Android-Kotlin-MVVM-Navigation-Room-Coroutines-Databinding | Apache License 2.0 |
tools/testing/src/jvmMain/kotlin/org/kotlincrypto/hash/TestBCDigest.kt | KotlinCrypto | 598,183,506 | false | null | /*
* Copyright (c) 2023 Matthew Nelson
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
@file:Suppress("UnnecessaryOptInAnnotation")
package org.kotlincrypto.hash
import org.kotlincrypto.core.Digest
import org.kotlincrypto.core.InternalKotlinCryptoApi
import org.kotlincrypto.core.internal.DigestState
import java.lang.IllegalStateException
@OptIn(InternalKotlinCryptoApi::class)
class TestBCDigest<T: org.bouncycastle.crypto.ExtendedDigest>: Digest {
private val delegate: T
private val copy: T.() -> T
constructor(
digest: T,
copy: T.() -> T
): super(
digest.algorithmName,
digest.byteLength,
digest.digestSize
) {
this.delegate = digest
this.copy = copy
}
@Suppress("UNCHECKED_CAST")
private constructor(state: DigestState, digest: TestBCDigest<*>): super(state) {
this.copy = digest.copy as T.() -> T
this.delegate = digest.copy.invoke(digest.delegate as T)
}
override fun copy(state: DigestState): Digest = TestBCDigest<T>(state, this)
override fun compress(input: ByteArray, offset: Int) { throw IllegalStateException("update is overridden...") }
override fun digest(bitLength: Long, bufferOffset: Int, buffer: ByteArray): ByteArray {
val out = ByteArray(digestLength())
delegate.doFinal(out, 0)
return out
}
override fun updateDigest(input: Byte) { delegate.update(input) }
override fun updateDigest(input: ByteArray, offset: Int, len: Int) { delegate.update(input, offset, len) }
override fun resetDigest() { delegate.reset() }
}
| 5 | null | 5 | 8 | e826353257b5eb877e4f8be59cf56fa8d78d4019 | 2,133 | hash | Apache License 2.0 |
presentation/src/main/java/com/movingmaker/presentation/view/onboarding/OnboardingSignUpCodeFragment.kt | dudwls901 | 458,682,004 | false | {"Kotlin": 359176} | package com.movingmaker.presentation.view.onboarding
import android.os.Bundle
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.movingmaker.presentation.R
import com.movingmaker.presentation.base.BaseFragment
import com.movingmaker.presentation.databinding.FragmentOnboardingSignUpCodeBinding
import com.movingmaker.presentation.util.FRAGMENT_NAME
import com.movingmaker.presentation.viewmodel.onboarding.OnboardingViewModel
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class OnboardingSignUpCodeFragment :
BaseFragment<FragmentOnboardingSignUpCodeBinding>(R.layout.fragment_onboarding_sign_up_code) {
private val onboardingViewModel: OnboardingViewModel by activityViewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.vm = onboardingViewModel
initViews()
observeDatas()
}
private fun initViews() {
with(onboardingViewModel) {
setShakeView(false)
setCodeCorrect(true)
clearCode()
setCurrentFragment(FRAGMENT_NAME.SIGNUP_CODE)
}
binding.backButton.setOnClickListener {
findNavController().popBackStack()
}
}
private fun observeDatas() {
onboardingViewModel.shakeView.observe(viewLifecycleOwner) {
if (it) {
val shortShake: Animation =
AnimationUtils.loadAnimation(requireContext(), R.anim.shake_short)
binding.codeNoticeTextView.startAnimation(shortShake)
}
}
}
} | 8 | Kotlin | 0 | 2 | e50510f55241db2294f23e4902980cec59594bbf | 1,792 | CommentDiary-Android | MIT License |
src/main/kotlin/com/github/zlbovolini/keymanager/consultachavepix/ConsultaPorChave.kt | zlbovolini | 407,255,916 | true | {"Kotlin": 70568} | package com.github.zlbovolini.keymanager.consultachavepix
import io.micronaut.core.annotation.Introspected
import javax.validation.constraints.NotBlank
@Introspected
data class ConsultaPorChave(
@NotBlank
val chave: String
)
| 0 | Kotlin | 1 | 0 | 2ccb0fe61dc8eb7b565db7b21cae6ac93507ee9e | 235 | orange-talents-07-template-pix-keymanager-grpc | Apache License 2.0 |
res-ktx-runtime/src/main/java/resktx/TransitionRes.kt | jamiesanson | 256,341,648 | false | null | package resktx
import androidx.annotation.TransitionRes
inline class TransitionRes(@TransitionRes override val value: Int): AnyRes | 0 | Kotlin | 0 | 5 | 595aeb108acfbbfcade0733071fb1fcfef931435 | 132 | Res-KTX | MIT License |
app/src/main/java/tmidev/marvelheroes/framework/remote/response/DataContainerResponse.kt | tminet | 437,921,880 | false | null | package tmidev.marvelheroes.framework.remote.response
import com.google.gson.annotations.SerializedName
data class DataContainerResponse<T>(
@SerializedName("offset")
val offset: Int,
@SerializedName("total")
val total: Int,
@SerializedName("results")
val results: List<T>
) | 0 | Kotlin | 1 | 0 | 1cddbd1e69be453d5749957c397e3c849cde9f69 | 300 | MarvelHeroes | MIT License |
apiTester/src/commonMain/kotlin/com/revenuecat/purchases/kmp/apitester/OfferingsAPI.kt | RevenueCat | 758,647,648 | false | {"Kotlin": 387798, "Ruby": 17642, "Swift": 594} | package com.revenuecat.purchases.kmp.apitester
import com.revenuecat.purchases.kmp.models.Offering
import com.revenuecat.purchases.kmp.models.Offerings
@Suppress("unused", "UNUSED_VARIABLE")
private class OfferingsAPI {
fun check(offerings: Offerings) {
with(offerings) {
val current: Offering? = current
val all: Map<String, Offering> = all
val o1: Offering? = getOffering("")
val o2: Offering? = this[""]
}
}
}
| 9 | Kotlin | 2 | 81 | 29cf2c936cd75069475a05d60343b22ad390ec5e | 487 | purchases-kmp | MIT License |
src/main/kotlin/dev/crashteam/uzumanalytics/client/uzum/UzumClientException.kt | crashteamdev | 647,366,680 | false | {"Kotlin": 562071, "Dockerfile": 743} | package dev.crashteam.uzumanalytics.client.uzum
class UzumClientException(status: Int, rawResponseBody: String, message: String) : RuntimeException(message)
| 3 | Kotlin | 0 | 0 | c898cbc02f86386938d4d1fa5653af219a41edbc | 158 | uzum-analytics | Apache License 2.0 |
app/src/main/java/com/example/template/TemplateApp.kt | jaakaappi | 625,001,053 | false | null | package com.example.template
import android.app.Application
import com.facebook.flipper.BuildConfig
import com.facebook.flipper.android.AndroidFlipperClient
import com.facebook.flipper.android.utils.FlipperUtils
import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin
import com.facebook.flipper.plugins.inspector.DescriptorMapping
import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin
import com.facebook.soloader.SoLoader
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class TemplateApp : Application() {
override fun onCreate() {
super.onCreate()
SoLoader.init(this, false)
if (BuildConfig.DEBUG && FlipperUtils.shouldEnableFlipper(this)) {
val client = AndroidFlipperClient.getInstance(this)
client.addPlugin(InspectorFlipperPlugin(this, DescriptorMapping.withDefaults()))
client.addPlugin(DatabasesFlipperPlugin(this))
client.start()
}
}
} | 0 | Kotlin | 1 | 0 | 0226359787bd8178984a145db411ef97dc80f698 | 975 | jetpack-app-template | MIT License |
app/src/main/java/ru/cherryperry/instavideo/data/media/retriever/UriMediaDataRetrieverSource.kt | CherryPerry | 157,012,355 | false | {"Kotlin": 175332, "Java": 11140, "RenderScript": 2719} | package ru.cherryperry.instavideo.data.media.retriever
import android.content.Context
import android.media.MediaMetadataRetriever
import android.net.Uri
class UriMediaDataRetrieverSource(
private val uri: Uri,
private val context: Context
) : MediaMetadataRetrieverSource {
override fun setDataSource(mediaMetadataRetriever: MediaMetadataRetriever) {
mediaMetadataRetriever.setDataSource(context, uri)
}
}
| 1 | Kotlin | 7 | 47 | 54886e7b78ee09f8c834dec9d1a50f50ff7fd0c5 | 433 | VideoCrop | Do What The F*ck You Want To Public License |
math/src/commonMain/kotlin/me/y9san9/calkt/math/calculate/MathCalculateSuccess.kt | y9san9 | 842,898,431 | false | {"Kotlin": 79012} | package me.y9san9.calkt.math.calculate
import me.y9san9.calkt.annotation.CalculateSubclass
import me.y9san9.calkt.calculate.CalculateResult
import me.y9san9.calkt.number.PreciseNumber
@OptIn(CalculateSubclass::class)
public data class MathCalculateSuccess(val number: PreciseNumber) : CalculateResult.Success
| 1 | Kotlin | 1 | 21 | 06d1ecbca749ad4107d08d719916a10aa95aa6df | 311 | calkt | MIT License |
core/data/src/main/java/com/alad1nks/productsandroid/core/data/repository/UserDataRepository.kt | alad1nks | 799,492,981 | false | {"Kotlin": 62936} | package com.alad1nks.productsandroid.core.data.repository
import com.alad1nks.productsandroid.core.model.UserData
import kotlinx.coroutines.flow.Flow
interface UserDataRepository {
val userData: Flow<UserData>
suspend fun changeTheme()
}
| 0 | Kotlin | 0 | 0 | 7618e863989a481b6e3ecc11f4583e438584157a | 248 | pokemons-android | MIT License |
app/src/test/java/com/garon/gmdb/movies/MoviesPresenterTest.kt | arongeorgel | 176,168,465 | false | null | package com.garon.gmdb.movies
class MoviesPresenterTest {
} | 0 | Kotlin | 0 | 1 | b1f9d7fc1fcb852ae9cdf2c56a1af74391af76c1 | 61 | GMDb | Apache License 2.0 |
cupertino-icons-extended/src/commonMain/kotlin/io/github/alexzhirkevich/cupertino/icons/outlined/MusicNoteList.kt | alexzhirkevich | 636,411,288 | false | {"Kotlin": 5215549, "Ruby": 2329, "Swift": 2101, "HTML": 2071, "Shell": 868} | /*
* Copyright (c) 2023-2024. Compose Cupertino project and open source contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.github.alexzhirkevich.cupertino.icons.outlined
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 io.github.alexzhirkevich.cupertino.icons.CupertinoIcons
public val CupertinoIcons.Outlined.MusicNoteList: ImageVector
get() {
if (_musicNoteList != null) {
return _musicNoteList!!
}
_musicNoteList = Builder(name = "MusicNoteList", defaultWidth = 23.8945.dp, defaultHeight =
24.082.dp, viewportWidth = 23.8945f, viewportHeight = 24.082f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(23.8945f, 5.8711f)
lineTo(23.8945f, 1.4648f)
curveTo(23.8945f, 0.8438f, 23.3906f, 0.4453f, 22.793f, 0.5625f)
lineTo(16.7695f, 1.875f)
curveTo(16.0195f, 2.0391f, 15.6094f, 2.4492f, 15.6094f, 3.1055f)
lineTo(15.6328f, 16.1367f)
curveTo(15.6914f, 16.7109f, 15.4219f, 17.0859f, 14.9062f, 17.1914f)
lineTo(13.043f, 17.5781f)
curveTo(10.6992f, 18.0703f, 9.5977f, 19.2656f, 9.5977f, 21.0352f)
curveTo(9.5977f, 22.8281f, 10.9805f, 24.082f, 12.9258f, 24.082f)
curveTo(14.6484f, 24.082f, 17.2266f, 22.8164f, 17.2266f, 19.4062f)
lineTo(17.2266f, 8.6836f)
curveTo(17.2266f, 8.0625f, 17.3438f, 7.9336f, 17.8945f, 7.8164f)
lineTo(23.25f, 6.6445f)
curveTo(23.6484f, 6.5625f, 23.8945f, 6.2578f, 23.8945f, 5.8711f)
close()
}
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(0.7969f, 6.4219f)
lineTo(11.2734f, 6.4219f)
curveTo(11.707f, 6.4219f, 12.0703f, 6.0586f, 12.0703f, 5.625f)
curveTo(12.0703f, 5.1914f, 11.707f, 4.8398f, 11.2734f, 4.8398f)
lineTo(0.7969f, 4.8398f)
curveTo(0.3516f, 4.8398f, 0.0f, 5.1914f, 0.0f, 5.625f)
curveTo(0.0f, 6.0586f, 0.3516f, 6.4219f, 0.7969f, 6.4219f)
close()
moveTo(0.7969f, 10.5938f)
lineTo(11.2734f, 10.5938f)
curveTo(11.7188f, 10.5938f, 12.0703f, 10.2305f, 12.0703f, 9.7852f)
curveTo(12.0703f, 9.3516f, 11.707f, 9.0117f, 11.2734f, 9.0117f)
lineTo(0.7969f, 9.0117f)
curveTo(0.3516f, 9.0117f, 0.0f, 9.3516f, 0.0f, 9.7852f)
curveTo(0.0f, 10.2305f, 0.3398f, 10.5938f, 0.7969f, 10.5938f)
close()
moveTo(0.7969f, 14.7656f)
lineTo(11.2734f, 14.7656f)
curveTo(11.7188f, 14.7656f, 12.0703f, 14.4141f, 12.0703f, 13.9688f)
curveTo(12.0703f, 13.5352f, 11.707f, 13.1836f, 11.2734f, 13.1836f)
lineTo(0.7969f, 13.1836f)
curveTo(0.3516f, 13.1836f, 0.0f, 13.5352f, 0.0f, 13.9688f)
curveTo(0.0f, 14.4141f, 0.3398f, 14.7656f, 0.7969f, 14.7656f)
close()
}
}
.build()
return _musicNoteList!!
}
private var _musicNoteList: ImageVector? = null
| 18 | Kotlin | 31 | 848 | 54bfbb58f6b36248c5947de343567903298ee308 | 4,711 | compose-cupertino | Apache License 2.0 |
microservice/car-service/src/main/kotlin/com/car/CarApplication.kt | savasdd | 730,245,979 | false | {"Kotlin": 100664, "Java": 22624} | package com.car
import com.car.service.CityService
import org.springframework.boot.CommandLineRunner
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.cloud.client.discovery.EnableDiscoveryClient
import org.springframework.core.io.ClassPathResource
import org.springframework.kafka.annotation.EnableKafka
import org.springframework.scheduling.annotation.EnableAsync
@SpringBootApplication
@EnableDiscoveryClient
@EnableKafka
@EnableAsync
class CarApplication(
private val service: CityService
) : CommandLineRunner {
override fun run(vararg args: String?) {
saveAllCity(service)
}
}
fun main(args: Array<String>) {
runApplication<CarApplication>(*args)
}
fun saveAllCity(service: CityService) {
val resource = ClassPathResource("file/city.txt")
val inputStream = resource.inputStream
inputStream.close()
} | 0 | Kotlin | 0 | 0 | 1a25589f0aaeb30d61a616b674fa742750f69e2e | 940 | springboot-car-microservice | MIT License |
app/src/main/java/com/example/android/politicalpreparedness/MainActivity.kt | tudang88 | 615,278,817 | false | null | package com.example.android.politicalpreparedness
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.example.android.politicalpreparedness.representative.RepresentativeViewModel
import org.koin.androidx.viewmodel.ext.android.getStateViewModel
class MainActivity : AppCompatActivity() {
private lateinit var representativeViewModel: RepresentativeViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
representativeViewModel = getStateViewModel()
setContentView(R.layout.activity_main)
}
}
| 0 | Kotlin | 0 | 0 | 284cda7122972dbffb95b9d4d06ae38c2315a3fb | 604 | PoliticalPreparedness | Apache License 2.0 |
tools/src/main/java/com/jiangkang/tools/utils/IntentUtils.kt | 155zhang | 123,068,902 | true | {"Kotlin": 387549, "JavaScript": 14024, "HTML": 5095, "CMake": 3043, "CSS": 2570, "C++": 968, "Makefile": 689, "Shell": 429} | package com.jiangkang.tools.utils
import android.content.Intent
import android.provider.MediaStore
/**
* Created by jiangkang on 2018/2/17.
* description:
*/
object IntentUtils {
/*
* 拍照Intent
* */
val cameraIntent: Intent
get() {
return Intent(MediaStore.ACTION_IMAGE_CAPTURE)
}
/*
* 拍视频Intent
* */
val takeVideoIntent: Intent
get() {
return Intent(MediaStore.ACTION_VIDEO_CAPTURE)
}
} | 0 | Kotlin | 0 | 0 | 26ecade56fe1980722975a94b4aae1ad1783309f | 488 | KTools | MIT License |
src/main/kotlin/frc/chargers/hardware/subsystems/swervedrive/module/RioPIDSwerveModule.kt | frc-5160-the-chargers | 497,722,545 | false | {"Kotlin": 438322, "Java": 56704} | package frc.chargers.hardware.subsystems.swervedrive.module
import com.batterystaple.kmeasure.quantities.*
import com.batterystaple.kmeasure.units.*
import edu.wpi.first.math.kinematics.SwerveModulePosition
import edu.wpi.first.math.kinematics.SwerveModuleState
import frc.chargers.constants.drivetrain.SwerveControlData
import frc.chargers.constants.tuning.DashboardTuner
import frc.chargers.controls.FeedbackController
import frc.chargers.controls.SetpointSupplier
import frc.chargers.controls.feedforward.Feedforward
import frc.chargers.controls.pid.SuperPIDController
import frc.chargers.hardware.subsystems.swervedrive.module.lowlevel.ModuleIO
import frc.chargers.utils.math.inputModulus
import frc.chargers.utils.within
import frc.chargers.wpilibextensions.geometry.twodimensional.asRotation2d
import org.littletonrobotics.junction.Logger.recordOutput
/**
* A swerve module within a [frc.chargers.hardware.subsystems.swervedrive.EncoderHolonomicDrivetrain]
* with rio PID control.
*/
public class RioPIDSwerveModule(
lowLevel: ModuleIO,
private val controlData: SwerveControlData
): SwerveModule, ModuleIO by lowLevel{
// ModuleIO by lowLevel makes the lowLevel parameter provide implementation
// of the ModuleIO interface to the class, reducing boilerplate code
/**
* A function that standardizes all angles within the 0 to 360 degree range.
*/
private fun Angle.standardize(): Angle = this.inputModulus(0.0.degrees..360.degrees)
/**
* A function used to calculate the smallest angle delta between 2 angles.
*/
private fun angleDeltaBetween(angleOne: Angle, angleTwo: Angle): Angle{
val a1 = angleOne.standardize()
val a2 = angleTwo.standardize()
val result = abs(a1-a2)
return if (360.degrees - result < result){
360.degrees-result
}else{
result
}
}
private val tuner = DashboardTuner()
private val turnPIDConstants by tuner.pidConstants(
controlData.anglePID,
"$logTab/Turning PID Constants"
)
private val drivePIDConstants by tuner.pidConstants(
controlData.velocityPID,
"$logTab/Driving PID Constants"
)
private val velocityController by tuner.refreshWhenTuned{
SuperPIDController(
drivePIDConstants,
getInput = {speed},
target = AngularVelocity(0.0),
/**
* Here, the setpoint supplier is set to the default,
* with a feedforward that directly corresponds to the input.
*/
setpointSupplier = SetpointSupplier.Default(
feedforward = Feedforward(controlData.velocityFF)
),
outputRange = -12.volts..12.volts,
selfSustain = true
)
}
private val turnController: FeedbackController<Angle, Voltage>
by tuner.refreshWhenTuned{
SuperPIDController(
turnPIDConstants,
getInput = { direction },
target = Angle(0.0),
/**
* the [SetpointSupplier] allows the controller
* to be a regular PID controller, trapezoid profiled PID controller or
* exponential profiled PID controller, depending on user specification.
*/
setpointSupplier = controlData.angleSetpointSupplier,
outputRange = -12.volts..12.volts,
continuousInputRange = 0.degrees..360.degrees,
selfSustain = true
)
}
override fun setDirectionalPower(
power: Double,
direction: Angle
){
if (angleDeltaBetween(this.direction, direction) > 90.0.degrees){
setDirection(direction + 180.degrees)
setPower(-power * cos(turnController.error))
}else{
setDirection(direction)
setPower(power * cos(turnController.error))
}
}
override fun setDirectionalVelocity(
angularVelocity: AngularVelocity,
direction: Angle
){
if (angleDeltaBetween(this.direction, direction) > 90.0.degrees){
setDirection(direction + 180.degrees)
setVelocity(-angularVelocity * cos(turnController.error))
}else{
setDirection(direction)
setVelocity(angularVelocity * cos(turnController.error))
}
}
// Note: turnSpeed will only be set if the control scheme includes second order kinematics functionality.
override fun setDirection(direction: Angle){
turnController.target = direction.standardize()
// turnVoltage is a setter variable of ModuleIO
turnVoltage = if ( (turnController.error).within(controlData.modulePrecision) ){
0.0.volts
}else{
turnController.calculateOutput()
}
recordOutput("$logTab/target", turnController.target.siValue)
recordOutput("$logTab/controllerErrorRad", turnController.error.inUnit(radians))
recordOutput("$logTab/controllerOutputVolts", turnController.calculateOutput().inUnit(volts))
}
private fun setVelocity(velocity: AngularVelocity) {
velocityController.target = velocity
// driveVoltage is a setter variable of ModuleIO
driveVoltage = velocityController.calculateOutput()
}
private fun setPower(power: Double) {
driveVoltage = power * 12.volts
}
override fun getModuleState(wheelRadius: Length): SwerveModuleState =
SwerveModuleState(
speed.inUnit(radians / seconds) * wheelRadius.inUnit(meters),
direction.asRotation2d()
)
override fun getModulePosition(wheelRadius: Length): SwerveModulePosition =
SwerveModulePosition(
wheelTravel.inUnit(radians) * wheelRadius.inUnit(meters),
direction.asRotation2d()
)
override fun halt() {
driveVoltage = 0.0.volts
setDirection(direction)
}
} | 3 | Kotlin | 0 | 2 | ef0bca03f00901ffcc5508981089edced59f91aa | 6,011 | ChargerLib | MIT License |
data/src/main/kotlin/pl/ipebk/schibsted/data/source/RecipesDataStoreFactory.kt | bskierys | 130,554,677 | false | null | package pl.ipebk.schibsted.data.source
import pl.ipebk.schibsted.data.repository.RecipesCache
import pl.ipebk.schibsted.data.repository.RecipesDataStore
import pl.ipebk.schibsted.data.repository.RecipesRemote
import java.io.IOException
import javax.inject.Inject
/**
* Create an instance of a [RecipesDataStore]
*/
class RecipesDataStoreFactory @Inject constructor(
private val recipesCache: RecipesCache,
private val recipesCacheDataStore: RecipesCacheDataStore,
private val recipesRemote: RecipesRemote,
private val recipesRemoteDataStore: RecipesRemoteDataStore
) {
/**
* Returns a DataStore based on whether or not there is content in the cache and the cache
* has not expired
*
* @throws IllegalStateException if no source is currently available
*/
fun retrieveDataStore(): RecipesDataStore {
if (recipesRemote.isAvailable()) {
return retrieveRemoteDataStore()
}
if (recipesCache.isCached()) {
return retrieveCacheDataStore()
}
throw IOException("No data source currently available")
}
/**
* Return an instance of the Remote Data Store
*/
fun retrieveCacheDataStore(): RecipesCacheDataStore {
return recipesCacheDataStore
}
/**
* Return an instance of the Cache Data Store
*/
fun retrieveRemoteDataStore(): RecipesRemoteDataStore {
return recipesRemoteDataStore
}
} | 0 | Kotlin | 0 | 0 | 07663eb3cb2201d9ffae555645cc6b089e68a7a4 | 1,372 | Godt.no | Apache License 2.0 |
app/src/main/java/com/leti/phonedetector/api/GetContact/config.kt | kovinevmv | 286,202,226 | false | {"Kotlin": 118254, "JavaScript": 7705} | package com.leti.phonedetector.api.GetContact
const val APP_VERSION = "5.6.2"
const val BASE_URL = "https://pbssrv-centralevents.com"
const val API_VERSION = "v2.8"
const val COUNTRY = "RU"
const val HMAC_KEY = "<KEY>"
const val MOD_EXP = 900719925481
| 0 | Kotlin | 6 | 13 | c03923d6420adf763d987a27b21e1f95a2f734be | 253 | PhoneDetector | MIT License |
app/src/main/java/com/example/mygithub/adapter/UserFollowAdapter.kt | 17657777777or7777777777 | 436,386,108 | true | {"Kotlin": 35979} | package com.example.mygithub.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.example.mygithub.R
import com.example.mygithub.model.UserFollowResponse
import kotlinx.android.synthetic.main.item_followers_layout.view.*
class UserFollowAdapter :
PagingDataAdapter<UserFollowResponse.UserFollowResponseItem, UserFollowAdapter.MyViewHolder>(
FOLLOWERS_COMPARATOR
) {
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem = getItem(position)
if (currentItem != null) {
Glide.with(holder.itemView).load(currentItem.avatar_url).centerCrop()
.transition(DrawableTransitionOptions.withCrossFade()).error(
R.drawable.ic_error
).into(holder.itemView.dp)
holder.itemView.user_name.text = currentItem.login
holder.itemView.index.text = (position + 1).toString()
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_followers_layout, parent, false)
return MyViewHolder(view)
}
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {}
companion object {
private val FOLLOWERS_COMPARATOR =
object : DiffUtil.ItemCallback<UserFollowResponse.UserFollowResponseItem>() {
override fun areItemsTheSame(
oldItem: UserFollowResponse.UserFollowResponseItem,
newItem: UserFollowResponse.UserFollowResponseItem
) = oldItem.login == newItem.login
override fun areContentsTheSame(
oldItem: UserFollowResponse.UserFollowResponseItem,
newItem: UserFollowResponse.UserFollowResponseItem
) = oldItem == newItem
}
}
} | 0 | null | 0 | 0 | 20de9742f07a8b7d55303ece772b9e5d3792aebb | 2,202 | MyGithub | MIT License |
pensjon-brevbaker-api-model/src/main/kotlin/no/nav/pensjon/brev/api/model/CommonEnums.kt | navikt | 375,334,697 | false | null | @file:Suppress("unused")
package no.nav.pensjon.brev.api.model
enum class Sivilstand {
ENSLIG,
ENKE,
GIFT,
GIFT_LEVER_ADSKILT,
SEPARERT,
PARTNER,
PARTNER_LEVER_ADSKILT,
SEPARERT_PARTNER,
SAMBOER1_5,
SAMBOER3_2,
}
enum class Sakstype {
AFP,
ALDER,
UFOEREP,
BARNEP,
}
enum class Institusjon {
FENGSEL,
HELSE,
SYKEHJEM,
INGEN,
}
enum class Beregningsmetode {
AUSTRALIA,
CANADA,
CHILE,
EOS,
FOLKETRYGD,
INDIA,
ISRAEL,
NORDISK,
PRORATA,
SOR_KOREA,
SVEITS,
USA
} | 0 | Kotlin | 2 | 0 | 49e27874bf9b0f20df4c4411405b7434f49f58bc | 581 | pensjonsbrev | MIT License |
shared/src/commonMain/kotlin/ml/dev/kotlin/openotp/ui/component/LoadingAnimatedVisibility.kt | avan1235 | 688,384,879 | false | {"Kotlin": 287213, "Swift": 3709, "Shell": 228} | package ml.dev.kotlin.openotp.ui.component
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@Composable
internal fun LoadingAnimatedVisibility(
visibleContent: Boolean,
loadingVerticalArrangement: Arrangement.Vertical = Arrangement.Center,
loadingHorizontalAlignment: Alignment.Horizontal = Alignment.CenterHorizontally,
precedingContent: @Composable (ColumnScope.() -> Unit)? = null,
centerContent: @Composable (ColumnScope.() -> Unit)? = {
CircularProgressIndicator(Modifier.padding(12.dp))
},
followingContent: @Composable (ColumnScope.() -> Unit)? = null,
content: @Composable BoxScope.() -> Unit,
) {
Box(
modifier = Modifier.fillMaxSize()
) {
Box(
modifier = Modifier.fillMaxSize(),
content = content,
)
AnimatedVisibility(
modifier = Modifier.fillMaxSize(),
visible = !visibleContent,
enter = fadeIn(),
exit = fadeOut()
) {
Column(
horizontalAlignment = loadingHorizontalAlignment,
verticalArrangement = loadingVerticalArrangement,
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.background),
) {
if (precedingContent != null) {
precedingContent()
}
if (centerContent != null) {
centerContent()
}
if (followingContent != null) {
followingContent()
}
}
}
}
} | 2 | Kotlin | 3 | 71 | acae3a1e4bdebcfefe549fe5f4fff4ffeed18d51 | 2,079 | open-otp | MIT License |
Hibernate/app/src/main/java/com/pressurelabs/hibernate/ui/fragments/UpgradesFragment.kt | aquaflamingo | 144,402,708 | false | {"Java": 190719, "Kotlin": 82705} | package com.pressurelabs.hibernate.ui.fragments
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.pressurelabs.hibernate.BaseFragment
import com.pressurelabs.hibernate.R
import com.pressurelabs.hibernate.ui.presenter.IUpgradesPresenter
import com.pressurelabs.hibernate.ui.presenter.UpgradesPresenter
import com.pressurelabs.hibernate.ui.view.IUpgradesView
import com.robertlevonyan.views.chip.Chip
class UpgradesFragment : BaseFragment(), IUpgradesView {
private var presenter: IUpgradesPresenter? = null;
private var firstButton: Chip?=null
private var secondButton:Chip?=null
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val rootView = inflater!!.inflate(R.layout.fragment_upgrades, container, false)
presenter = UpgradesPresenter(this,context)
firstButton = rootView.findViewById(R.id.upgrade_1_chip) as Chip
secondButton = rootView.findViewById(R.id.upgrade_2_chip) as Chip
firstButton?.setOnClickListener (View.OnClickListener {
var intent:Intent? = presenter?.onFirstButtonClicked()
if (intent!=null)
startActivity(intent!!)
})
secondButton?.setOnClickListener (View.OnClickListener{
var intent:Intent? = presenter?.onSecondButtonClicked()
if (intent!=null)
startActivity(intent!!)
})
return rootView
}
companion object {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private val ARG_SECTION_NUMBER = "section_number"
/**
* Returns a new instance of this fragment for the given section
* number.
*/
fun newInstance(sectionNumber: Int): UpgradesFragment {
val fragment = UpgradesFragment()
val args = Bundle()
args.putInt(ARG_SECTION_NUMBER, sectionNumber)
fragment.arguments = args
return fragment
}
}
} | 1 | null | 1 | 1 | eb0bdf550ef581ec7aecc0b78d16d6b76108e587 | 2,197 | OpenAndroid | Apache License 2.0 |
play-class-default/src/main/kotlin/org/example/cd/demos/parents/JavaParentAllAOKotlinDemo2.kt | dowenliu-xyz | 808,693,582 | false | {"Gradle Kotlin DSL": 13, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 2, "Java": 399, "YAML": 4, "INI": 6, "Kotlin": 354, "Java Properties": 1} | package org.example.cd.demos.parents
import com.alibaba.csp.sentinel.annotation.SentinelResource
import org.example.cd.biz.Greeting
import org.springframework.context.annotation.Primary
import org.springframework.stereotype.Component
/**
* case: annotation on parent class, all defaultFallback method overridden
*
* Aspect takes effect, defaultFallback takes effect.
*/
@Component
class JavaParentAllAOKotlinDemo2 : JavaParentAllAOForKotlin() {
@SentinelResource(value = "demo")
fun greeting(name: String?): String {
return Greeting.doGreeting(name)
}
public override fun defaultFallback(): String {
return Greeting.doDefaultFallback()
}
public override fun defaultFallback(e: Throwable?): String {
return Greeting.doDefaultFallback(e)
}
}
| 0 | Java | 0 | 1 | 8b6df6f693a0c7efa25c3a7d634823d7b8ec4915 | 800 | sentinel-plays | Apache License 2.0 |
151004/Bashlikov/rv_task05/publisher/src/main/kotlin/services/TweetService.kt | CaptMelancholy | 771,696,610 | true | {"Markdown": 8, "Batchfile": 17, "Java": 1379, "INI": 43, "TypeScript": 59, "SQL": 4, "C#": 922, "Java Properties": 5, "HTML": 3, "JavaScript": 16, "Gradle Kotlin DSL": 16, "Shell": 5, "Dockerfile": 3, "Kotlin": 265, "HTML+Razor": 12, "CSS": 21, "Java Server Pages": 5} | package by.bashlikovvv.services
import by.bashlikovvv.api.dto.request.CreateTweetDto
import by.bashlikovvv.api.dto.request.UpdateTweetDto
import by.bashlikovvv.api.dto.response.TweetDto
interface TweetService {
suspend fun create(createTweetDto: CreateTweetDto): TweetDto?
suspend fun getAll(): List<TweetDto?>
suspend fun getById(tweetId: Long): TweetDto?
suspend fun getByEditorId(editorId: Long): TweetDto?
suspend fun update(tweetId: Long, updateTweetDto: UpdateTweetDto): TweetDto?
suspend fun delete(tweetId: Long): Boolean
} | 0 | Java | 0 | 0 | 8a76ff26d5696f76ab162b16dc1b762fd0a84d8b | 564 | DC2024-01-27 | MIT License |
151004/Bashlikov/rv_task05/publisher/src/main/kotlin/services/TweetService.kt | CaptMelancholy | 771,696,610 | true | {"Markdown": 8, "Batchfile": 17, "Java": 1379, "INI": 43, "TypeScript": 59, "SQL": 4, "C#": 922, "Java Properties": 5, "HTML": 3, "JavaScript": 16, "Gradle Kotlin DSL": 16, "Shell": 5, "Dockerfile": 3, "Kotlin": 265, "HTML+Razor": 12, "CSS": 21, "Java Server Pages": 5} | package by.bashlikovvv.services
import by.bashlikovvv.api.dto.request.CreateTweetDto
import by.bashlikovvv.api.dto.request.UpdateTweetDto
import by.bashlikovvv.api.dto.response.TweetDto
interface TweetService {
suspend fun create(createTweetDto: CreateTweetDto): TweetDto?
suspend fun getAll(): List<TweetDto?>
suspend fun getById(tweetId: Long): TweetDto?
suspend fun getByEditorId(editorId: Long): TweetDto?
suspend fun update(tweetId: Long, updateTweetDto: UpdateTweetDto): TweetDto?
suspend fun delete(tweetId: Long): Boolean
} | 0 | Java | 0 | 0 | 8a76ff26d5696f76ab162b16dc1b762fd0a84d8b | 564 | DC2024-01-27 | MIT License |
src/test/kotlin/com/empowerops/getoptk/TreeIteratorSandbox.kt | cbeust | 88,466,150 | true | {"Kotlin": 70451} | package com.empowerops.getoptk
class TreeIteratorSandbox {
// so currently I'm not building any object which is directly traversable in post order.
// in particular, to do dependency validation, I need to check that every type you've specified
// through getOpt is "reachable" from string form. The easiest way to express this
// is with a traversal of the dependencies.
// such a dependency graph would also allow me to more easily reduce the token set,
// and express errors (eg
// "failed to convert 'xyz' to 'A',
// while generating arg2 for A,
// while generating arg1:A for C.constructor(a: A, str: String) specified by ArgsThing.c = getObjectOpt<C>()
//
//
} | 0 | Kotlin | 0 | 0 | cdc2f0f0e33f5560b78867d7b94dac593cbc4cf7 | 717 | getoptk | Apache License 2.0 |
app/src/main/kotlin/no/nav/tiltakspenger/vedtak/repository/vedtak/VedtakDAO.kt | navikt | 487,246,438 | false | {"Kotlin": 876482, "Shell": 1309, "Dockerfile": 495, "HTML": 45} | package no.nav.tiltakspenger.vedtak.repository.vedtak
import kotliquery.TransactionalSession
import no.nav.tiltakspenger.saksbehandling.domene.vedtak.Vedtak
interface VedtakDAO {
fun lagreVedtak(vedtak: Vedtak, tx: TransactionalSession): Vedtak
}
| 5 | Kotlin | 0 | 1 | 9e8cbda653e20bba1837618112ce5cb2e20bc8e9 | 253 | tiltakspenger-vedtak | MIT License |
xmm/app/src/main/java/com/miaomiao/xmm/ui/SplashActivity.kt | Chaoxyc | 304,313,923 | false | null | package com.miaomiao.xmm.ui
import android.app.Activity
/**
* @Author: xyc
* @Date: 2020/10/15 8:31 PM
* @Description:
* @Last Modified by:
* @Last Modified time:
*/
class SplashActivity : Activity() {
} | 0 | Kotlin | 0 | 0 | a86d03e4609410ceb9490f3e168dd04c198e4beb | 212 | xmm | Apache License 2.0 |
kotlin-antd/antd-samples/src/main/kotlin/samples/transfer/LargeData.kt | xlj44400 | 341,311,901 | true | {"Kotlin": 1549697, "HTML": 1503} | package samples.transfer
import antd.*
import antd.transfer.*
import kotlinext.js.*
import react.*
import styled.*
import kotlin.random.*
interface LargeDataTransferItem : TransferItem {
var chosen: Boolean
}
interface LargeDataAppState : RState {
var mockData: Array<TransferItem>
var targetKeys: Array<String>
}
class LargeDataApp : RComponent<RProps, LargeDataAppState>() {
private val getMock: MouseEventHandler<Any> = {
val keys = mutableListOf<String>()
val data = mutableListOf<TransferItem>()
for (i in 0..19) {
val item = jsObject<LargeDataTransferItem> {
key = i.toString()
title = "content${i + 1}"
description = "description of content${i + 1}"
chosen = Random.nextDouble() * 2 > 1
}
if (item.chosen) {
keys.add(item.key!!)
}
data.add(item)
}
setState {
mockData = data.toTypedArray()
targetKeys = keys.toTypedArray()
}
}
private val handleChange = fun(nextTargetKeys: Array<String>, direction: String, moveKeys: Any) {
console.log(nextTargetKeys, direction, moveKeys)
setState {
targetKeys = nextTargetKeys
}
}
override fun componentDidMount() {
getMock(js {}.unsafeCast<MouseEvent<Any>>())
}
override fun LargeDataAppState.init() {
mockData = emptyArray()
targetKeys = emptyArray()
}
override fun RBuilder.render() {
transfer<TransferItem, TransferComponent<TransferItem>> {
attrs {
dataSource = state.mockData
targetKeys = state.targetKeys
onChange = handleChange
render = { item -> item.title!! }
}
}
}
}
fun RBuilder.largeDataApp() = child(LargeDataApp::class) {}
fun RBuilder.largeData() {
styledDiv {
css { +TransferStyles.largeData }
largeDataApp()
}
}
| 0 | null | 0 | 0 | ce8216c0332abdfefcc0a06cf5fbbbf24e669931 | 2,040 | kotlin-js-wrappers | Apache License 2.0 |
include-mapview/src/desktopMain/kotlin/com/map/PlatformMapView_desktop.kt | avdim | 446,871,600 | false | {"Kotlin": 127135, "HTML": 978, "Shell": 543, "CSS": 108} | package com.map
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import kotlinx.coroutines.flow.StateFlow
actual typealias DisplayModifier = Modifier
@Composable
internal actual fun PlatformMapView(
modifier: DisplayModifier,
tiles: List<DisplayTileWithImage<TileImage>>,
onZoom: (Pt?, Double) -> Unit,
onClick: (Pt) -> Unit,
onMove: (Int, Int) -> Unit,
updateSize: (width: Int, height: Int) -> Unit
) {
MapViewAndroidDesktop(
modifier = modifier,
isInTouchMode = false,
tiles = tiles,
onZoom = onZoom,
onClick = onClick,
onMove = onMove,
updateSize = updateSize
)
}
| 1 | Kotlin | 2 | 18 | 40952884ce70fa9bbb0d7acd35fba2861f353172 | 690 | compose-mapview | Apache License 2.0 |
include-mapview/src/desktopMain/kotlin/com/map/PlatformMapView_desktop.kt | avdim | 446,871,600 | false | {"Kotlin": 127135, "HTML": 978, "Shell": 543, "CSS": 108} | package com.map
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import kotlinx.coroutines.flow.StateFlow
actual typealias DisplayModifier = Modifier
@Composable
internal actual fun PlatformMapView(
modifier: DisplayModifier,
tiles: List<DisplayTileWithImage<TileImage>>,
onZoom: (Pt?, Double) -> Unit,
onClick: (Pt) -> Unit,
onMove: (Int, Int) -> Unit,
updateSize: (width: Int, height: Int) -> Unit
) {
MapViewAndroidDesktop(
modifier = modifier,
isInTouchMode = false,
tiles = tiles,
onZoom = onZoom,
onClick = onClick,
onMove = onMove,
updateSize = updateSize
)
}
| 1 | Kotlin | 2 | 18 | 40952884ce70fa9bbb0d7acd35fba2861f353172 | 690 | compose-mapview | Apache License 2.0 |
src/main/kotlin/com/theoparis/cw/entity/render/base/AnimatedEntityRenderer.kt | theoparis | 484,579,728 | false | null | package com.theoparis.cw.entity.render.base
import net.minecraft.client.render.VertexConsumer
import net.minecraft.client.render.VertexConsumerProvider
import net.minecraft.client.render.entity.EntityRendererFactory
import net.minecraft.client.util.math.MatrixStack
import net.minecraft.entity.LivingEntity
import software.bernie.geckolib3.core.IAnimatable
import software.bernie.geckolib3.model.AnimatedGeoModel
import software.bernie.geckolib3.renderers.geo.GeoEntityRenderer
open class AnimatedEntityRenderer<T>(ctx: EntityRendererFactory.Context, modelProvider: AnimatedGeoModel<T>) :
GeoEntityRenderer<T>(ctx, modelProvider) where
T : LivingEntity,
T : IAnimatable {
private val features = mutableListOf<AnimatedFeatureRenderer<T>>()
fun getFeatures() = features.toList()
fun addFeature(newFeature: AnimatedFeatureRenderer<T>): Boolean = features.add(newFeature)
override fun renderEarly(
animatable: T,
stackIn: MatrixStack?,
ticks: Float,
renderTypeBuffer: VertexConsumerProvider?,
vertexBuilder: VertexConsumer?,
packedLightIn: Int,
packedOverlayIn: Int,
red: Float,
green: Float,
blue: Float,
partialTicks: Float
) {
super.renderEarly(
animatable,
stackIn,
ticks,
renderTypeBuffer,
vertexBuilder,
packedLightIn,
packedOverlayIn,
red,
green,
blue,
partialTicks
)
features.forEach {
it.render(animatable, stackIn, partialTicks, renderTypeBuffer, packedLightIn, packedOverlayIn)
}
}
}
interface AnimatedFeatureRenderer<T> where
T : LivingEntity,
T : IAnimatable {
fun render(
entity: T,
matrices: MatrixStack?,
ticks: Float,
provider: VertexConsumerProvider?,
light: Int,
overlay: Int
)
}
| 4 | Kotlin | 0 | 0 | 7fa941855f7a99c18a361a1e3c92ab0c09cfbf94 | 1,950 | cursed-insanity-mod | MIT License |
app/src/main/java/com/leelu/shadow/manager/ShadowManagerIml.kt | lks6123 | 510,275,218 | false | {"Kotlin": 55978, "Java": 7110, "AIDL": 1560} | package com.leelu.shadow.manager
import android.os.Bundle
import com.leelu.shadow.app_lib.Callback
import com.leelu.shadow.app_lib.ShadowManager
import kotlinx.coroutines.runBlocking
/**
*
* CreateDate: 2022/7/4 10:33
* Author: 李露
* Email: <EMAIL>
* Version: 1.0
* Description:
*/
object ShadowManagerIml : ShadowManager {
override fun installPlugin(assetsName: String): String {
return runBlocking {
Shadow.instance.installPlugin(assetsName)
}
}
override fun loadPlugin(partKey: String): Boolean {
return runBlocking {
Shadow.instance.loadPlugin(partKey)
}
}
override fun callPluginApplication(partKey: String) {
runBlocking {
Shadow.instance.callPluginApplication(partKey)
}
}
override fun startActivity(
pluginName: String,
activityName: String,
bundle: Bundle?,
onSuccess: (() -> Unit)?,
onError: ((Exception) -> Unit)?
) {
Shadow.instance.startActivity(pluginName,activityName,bundle,onSuccess,onError)
}
override fun startService(
pluginName: String,
serviceName: String,
bundle: Bundle?,
onSuccess: (() -> Unit)?,
onError: ((Exception) -> Unit)?
) {
TODO("Not yet implemented")
}
override fun stopService(pluginName: String, serviceName: String) {
TODO("Not yet implemented")
}
override fun bindService(
pluginName: String,
serviceName: String,
flags: Int,
callback: Callback,
bundle: Bundle?
) {
TODO("Not yet implemented")
}
override fun unbindService(pluginName: String, serviceName: String, callback: Callback) {
TODO("Not yet implemented")
}
} | 0 | Kotlin | 0 | 1 | ca69512b698f724f86d4ee66dbf2129cd5881a97 | 1,792 | ShadowPluginDemo | Apache License 2.0 |
myddd-vertx-ioc/myddd-vertx-ioc-api/src/test/kotlin/org/myddd/vertx/ioc/TestInstanceFactory.kt | mydddOrg | 394,671,816 | false | null | package org.myddd.vertx.ioc
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import org.mockito.Mockito
import org.mockito.Mockito.mock
class TestInstanceFactory {
private val provider:InstanceProvider = mock(InstanceProvider::class.java)
@Test
fun testInstanceFactoryWithoutProvider(){
Assertions.assertThrows(RuntimeException::class.java){
InstanceFactory.getInstance(A::class.java)
}
Assertions.assertThrows(RuntimeException::class.java){
InstanceFactory.getInstance(A::class.java,"AnotherBean")
}
}
@Test
fun testInstanceFactory(){
InstanceFactory.setInstanceProvider(provider)
Assertions.assertNull(InstanceFactory.getInstance(A::class.java))
Mockito.`when`(provider.getInstance(A::class.java)).thenReturn(A())
Assertions.assertNotNull(InstanceFactory.getInstance(A::class.java))
Assertions.assertNull(InstanceFactory.getInstance(A::class.java,"AnotherBean"))
Mockito.`when`(provider.getInstance(A::class.java,"AnotherBean")).thenReturn(A())
Assertions.assertNotNull(InstanceFactory.getInstance(A::class.java,"AnotherBean"))
}
} | 0 | Kotlin | 0 | 6 | 2f03041f4a8984f6acba1f6ec31a22185f0fcb0e | 1,208 | myddd-vertx | MIT License |
pf4k-core/pf4k-api/src/main/kotlin/org/artembogomolova/pf4k/api/module/Events.kt | bogomolov-a-a | 343,152,698 | false | null | package org.artembogomolova.pf4k.api.module
import java.nio.file.Path
import org.artembogomolova.pf4k.api.module.management.IModuleManager
import org.artembogomolova.pf4k.api.module.types.LoadableModuleDescriptor
typealias MutableExceptionListType = MutableList<Exception>
typealias ExceptionListType = List<Exception>
typealias DependencyPathListType = List<Path>
/*********************
****Manager events***
********************/
/**
* Event triggered, when new module found in classpath.
*
* @property [resolvedPath] path with module jar.
* @property [dependencyPathList] list of path dependencies of module in [resolvedPath].
* @property [exceptionList] list of exceptions thrown in event method handler.
* @author bogomolov-a-a
*/
data class OnResolvedEvent(
val resolvedPath: Path,
val dependencyPathList: DependencyPathListType,
val exceptionList: MutableExceptionListType
)
/**
* Event triggered, when new module loaded in memory.
*
* @property [descriptor] loaded module descriptor.
* @property [exceptionList] list of exceptions thrown in event method handler.
* @author bogomolov-a-a
*/
data class OnLoadEvent(
val descriptor: LoadableModuleDescriptor,
val exceptionList: MutableExceptionListType
)
/**
* Event triggered, when module preparing unloaded from memory.
*
* @property [descriptor] loaded module descriptor.
* @property [exceptionList] list of exceptions thrown in event method handler.
* @author bogomolov-a-a
*/
data class OnBeforeUnloadEvent(
val descriptor: LoadableModuleDescriptor,
val exceptionList: MutableExceptionListType
)
/**
* Event triggered, when module successful unloaded from memory.
*
* @property [descriptor] loaded module descriptor.
* @property [exceptionList] list of exceptions thrown in event method handler.
* @author bogomolov-a-a
*/
data class OnAfterUnloadEvent(
val descriptor: LoadableModuleDescriptor,
val exceptionList: MutableExceptionListType
)
/**
* Event triggered, when module successful unloaded from memory.
*
* @property [descriptor] loaded module descriptor.
* @property [moduleManager] current module manager.
* @property [exceptionList] list of exceptions thrown in event method handler.
* @author bogomolov-a-a
*/
data class OnFailedEvent(
val descriptor: LoadableModuleDescriptor,
val moduleManager: IModuleManager,
val exceptionList: ExceptionListType
)
/*********************
****Module events***
********************/
/**
* Event triggered, when module try to start.
*
* @property [moduleManager] current module manager.
* @property [exceptionList] list of exceptions thrown in event method handler.
* @author bogomolov-a-a
*/
data class OnBeforeStartEvent(
val moduleManager: IModuleManager,
val exceptionList: MutableExceptionListType
)
/**
* Event triggered, when module try to validate start ability.
*
* @property [descriptor] loaded module descriptor.
* @property [moduleManager] current module manager.
* @property [exceptionList] list of exceptions thrown in event method handler.
* @author bogomolov-a-a
*/
data class OnPreconditionsValidateEvent(
val descriptor: LoadableModuleDescriptor,
val moduleManager: IModuleManager,
val exceptionList: MutableExceptionListType
)
/**
* Event triggered, when module try to get resources from another module for self initialization.
*
* @property [moduleManager] current module manager.
* @property [exceptionList] list of exceptions thrown in event method handler.
* @author bogomolov-a-a
*/
data class OnInitializedDependenciesWaitEvent(
val moduleManager: IModuleManager,
val exceptionList: MutableExceptionListType
)
/**
* Event triggered, when module try to initialize self resources.
*
* @property [descriptor] loaded module descriptor.
* @property [moduleManager] current module manager.
* @property [exceptionList] list of exceptions thrown in event method handler.
* @author bogomolov-a-a
*/
data class OnInitializeResourcesEvent(
val descriptor: LoadableModuleDescriptor,
val moduleManager: IModuleManager,
val exceptionList: MutableExceptionListType
)
/**
* Event triggered, when module successful started.
*
* @property [exceptionList] list of exceptions thrown in event method handler.
* @author bogomolov-a-a
*/
data class OnAfterStartEvent(
val exceptionList: MutableExceptionListType
)
/**
* Event triggered, when module preparing to stop.
*
* @property [descriptor] loaded module descriptor.
* @property [exceptionList] list of exceptions thrown in event method handler.
* @author bogomolov-a-a
*/
data class OnBeforeStopEvent(
val descriptor: LoadableModuleDescriptor,
val exceptionList: MutableExceptionListType
)
/**
* Event triggered, when module preparing resources release.
*
* @property [moduleManager] current module manager.
* @property [exceptionList] list of exceptions thrown in event method handler.
* @author bogomolov-a-a
*/
data class OnResourcesReleaseEvent(
val moduleManager: IModuleManager,
val exceptionList: MutableExceptionListType
)
/**
* Event triggered, when module successful stopped.
*
* @property [moduleManager] current module manager.
* @property [exceptionList] list of exceptions thrown in event method handler.
* @author bogomolov-a-a
*/
data class OnAfterStopEvent(
val moduleManager: IModuleManager,
val exceptionList: MutableExceptionListType
) | 0 | Kotlin | 0 | 0 | 5f575d877d8a35bb76fb13ea16640ebc74dbc6a0 | 5,453 | pf4k | Apache License 2.0 |
ktor-client/ktor-client-core/posix/src/io/ktor/client/engine/Loader.kt | KaraShok | 190,507,625 | true | {"Kotlin": 2763826, "Lua": 280, "HTML": 165} | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.engine
import io.ktor.util.*
@InternalAPI
@Suppress("KDocMissingDocumentation")
val engines: MutableList<HttpClientEngineFactory<HttpClientEngineConfig>> by lazy {
mutableListOf<HttpClientEngineFactory<HttpClientEngineConfig>>()
}
| 0 | Kotlin | 0 | 1 | e0525a274d2c9958778fb649df39d59c44341b2b | 388 | ktor | Apache License 2.0 |
app/src/main/java/com/bsp/basekotlin/data/remote/response/Response.kt | songuyen1816 | 398,463,895 | false | null | package com.bsp.basekotlin.data.remote.response
import com.google.gson.annotations.SerializedName
open class Response<T>(
@SerializedName("error") val error: Boolean = false,
@SerializedName("code") val code: Int? = 555,
@SerializedName("message") val message: String = "",
@SerializedName("data") val data: T
) | 0 | Kotlin | 0 | 0 | c2ae99356e1e0153a09bbe585e2989027c51377e | 329 | android-base-kotlin | MIT License |
app/src/main/java/com/example/recipesharingapp/ui/theme/screen/EditProfileScreen.kt | naimPJ | 806,704,455 | false | {"Kotlin": 80333} | package com.example.recipesharingapp.ui.theme.screen
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.example.recipesharingapp.viewModel.AppViewModelProvider
import com.example.recipesharingapp.viewModel.ProfileViewModel
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun EditProfileScreen(navController: NavController,
profileViewModel: ProfileViewModel = viewModel(factory = AppViewModelProvider.Factory),
userId: Int) {
val user by profileViewModel.user.collectAsState()
LaunchedEffect(userId){
profileViewModel.loadUser(userId)
}
var newUsername by remember { mutableStateOf("") }
var newEmail by remember { mutableStateOf( "") }
var newBio by remember { mutableStateOf("") }
var newPassword by remember { mutableStateOf("") }
LaunchedEffect(user) {
user?.let {
newUsername = it.username
newEmail = it.email
newBio = it.bio
}
}
val coroutineScope = rememberCoroutineScope()
Scaffold(
topBar = {
TopAppBar(
title = { Text("Edit Profile") },
navigationIcon = {
IconButton(onClick = { navController.popBackStack() }) {
Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "Back")
}
}
)
}
) { paddingValues ->
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues)
.padding(10.dp)
.clip(RoundedCornerShape(5.dp))
.background(Color(android.graphics.Color.parseColor("#f7f7f7"))),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top
) {
item {
TextField(
value = newUsername,
onValueChange = { newUsername = it },
label = { Text("New Username") },
singleLine = true,
modifier = Modifier
.height(50.dp)
.width(300.dp)
)
Spacer(modifier = Modifier.height(16.dp))
}
item {
TextField(
value = newEmail,
onValueChange = { newEmail = it },
label = { Text("New Email") },
singleLine = true,
modifier = Modifier
.height(50.dp)
.width(300.dp)
)
Spacer(modifier = Modifier.height(16.dp))
}
item {
TextField(
value = newBio,
onValueChange = { newBio = it },
label = { Text("Bio") },
modifier = Modifier
.height(150.dp)
.width(300.dp)
)
Spacer(modifier = Modifier.height(16.dp))
}
item {
TextField(
value = newPassword,
onValueChange = { newPassword = it },
label = { Text("New Password") },
visualTransformation = PasswordVisualTransformation(),
singleLine = true,
modifier = Modifier
.height(50.dp)
.width(300.dp)
)
Spacer(modifier = Modifier.height(16.dp))
}
item {
Button(
shape = RoundedCornerShape(5.dp),
elevation = ButtonDefaults.buttonElevation(defaultElevation = 3.dp, pressedElevation = 0.dp),
colors = ButtonDefaults.buttonColors(containerColor = Color(android.graphics.Color.parseColor("#42cc33"))),
onClick = {
coroutineScope.launch {
if (newUsername.isNotEmpty() || newEmail.isNotEmpty() || newBio.isNotEmpty() || newPassword.isNotEmpty()) {
profileViewModel.updateUser(
id = userId,
email = newEmail.takeIf { it.isNotEmpty() } ?: user?.email.orEmpty(),
username = newUsername.takeIf { it.isNotEmpty() } ?: user?.username.orEmpty(),
bio = newBio.takeIf { it.isNotEmpty() } ?: user?.bio.orEmpty(),
password = newPassword.takeIf { it.isNotEmpty() } ?: user?.password.orEmpty(),
)
}
navController.navigate("profilescr/${user?.id}") {
popUpTo("profilescr/${user?.id}") { inclusive = true }
}
}
}
) {
Text(text = "Save Changes")
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | 6feb18a859eeebff2211f4ddb4f42d9a84a68eb8 | 7,179 | Recipe-Sharing-App | MIT License |
app/src/main/kotlin/fr/simonlebras/radiofrance/ui/browser/player/MiniPlayerFragment.kt | simonlebras | 73,916,448 | false | null | package fr.simonlebras.radiofrance.ui.browser.player
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaControllerCompat
import android.support.v4.media.session.PlaybackStateCompat
import android.support.v4.media.session.PlaybackStateCompat.*
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.Unbinder
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import dagger.Lazy
import fr.simonlebras.radiofrance.R
import fr.simonlebras.radiofrance.ui.base.BaseActivity
import fr.simonlebras.radiofrance.ui.base.BaseFragment
import fr.simonlebras.radiofrance.utils.MediaMetadataUtils
import javax.inject.Inject
class MiniPlayerFragment : BaseFragment<MiniPlayerPresenter>(), MiniPlayerPresenter.View {
@Inject lateinit var presenterProvider: Lazy<MiniPlayerPresenter>
@BindView(R.id.image_radio_logo) lateinit var imageRadioLogo: ImageView
@BindView(R.id.text_radio_title) lateinit var textRadioTitle: TextView
@BindView(R.id.text_radio_description) lateinit var textRadioDescription: TextView
@BindView(R.id.button_radio_play_pause) lateinit var buttonRadioPlayPause: ImageButton
@BindView(R.id.button_radio_skip_previous) lateinit var buttonRadioSkipPrevious: ImageButton
@BindView(R.id.button_radio_skip_next) lateinit var buttonRadioSkipNext: ImageButton
private lateinit var unbinder: Unbinder
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_mini_player, container, false)
unbinder = ButterKnife.bind(this, view)
buttonRadioPlayPause.setOnClickListener {
val state = MediaControllerCompat.getMediaController(activity).playbackState.state
when (state) {
STATE_PAUSED, STATE_STOPPED, STATE_NONE -> presenter.play()
STATE_PLAYING, STATE_BUFFERING, STATE_CONNECTING -> presenter.pause()
}
}
buttonRadioSkipPrevious.setOnClickListener {
presenter.skipToPrevious()
}
buttonRadioSkipNext.setOnClickListener {
presenter.skipToNext()
}
return view
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
presenter.onAttachView(this)
}
override fun onDestroyView() {
unbinder.unbind()
super.onDestroyView()
}
override fun restorePresenter() {
val presenterManager = (activity as BaseActivity<*>).presenterManager
presenter = presenterManager[uuid] as? MiniPlayerPresenter ?: presenterProvider.get()
presenterManager[uuid] = presenter
}
fun onConnected() {
val controller = MediaControllerCompat.getMediaController(activity)
controller.metadata?.let {
onMetadataChanged(it)
}
controller.playbackState?.let {
onPlaybackStateChanged(it)
}
presenter.subscribeToPlaybackUpdates()
}
override fun onMetadataChanged(metadata: MediaMetadataCompat) {
textRadioTitle.text = metadata.description.title
textRadioDescription.text = metadata.description.description
Glide.with(this)
.from(String::class.java)
.asBitmap()
.placeholder(ContextCompat.getDrawable(context, R.drawable.ic_radio_blue_64dp))
.error(ContextCompat.getDrawable(context, R.drawable.ic_radio_blue_64dp))
.diskCacheStrategy(DiskCacheStrategy.ALL)
.load(metadata.getString(MediaMetadataUtils.METADATA_KEY_SMALL_LOGO))
.into(imageRadioLogo)
}
override fun onPlaybackStateChanged(playbackState: PlaybackStateCompat) {
if (playbackState.state != STATE_PLAYING) {
buttonRadioPlayPause.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_play_arrow_pink_36dp))
} else {
buttonRadioPlayPause.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_pause_pink_36dp))
}
}
}
| 0 | Kotlin | 0 | 2 | ed57072599ebbb233b133d63c08c75f9f56444df | 4,463 | Radio-France | MIT License |
app/src/main/java/com/feirapp/feirapp/models/groceryItem/dtos/GroceryListItemModel.kt | Thyerry | 693,316,143 | false | {"Kotlin": 41496} | package com.feirapp.feirapp.models.groceryItem.dtos
import android.os.Parcelable
import com.feirapp.feirapp.models.enums.MeasureUnitEnum
import kotlinx.parcelize.Parcelize
@Parcelize
data class GroceryListItemModel(
val name: String = "",
val price: Double = 0.0,
val measureUnit: MeasureUnitEnum?,
var brand: String?,
var altName: String?,
val quantity: Double = 0.0,
val barcode: String = "",
val ncmCode: String? = "",
val cestCode: String? = "",
val purchaseDate: String,
) : Parcelable
| 0 | Kotlin | 0 | 0 | 9b3b3f6656e92edfd01b3edc17209769406396b9 | 533 | Feirapp-Android | Apache License 2.0 |
app/src/main/java/com/droidcon/cleanrepository/presentation/pagedsource/PagedRemoteViewModel.kt | alerecchi | 172,200,451 | false | null | package com.droidcon.cleanrepository.presentation.pagedsource
import com.droidcon.cleanrepository.di.qualifier.Remote
import com.droidcon.cleanrepository.domain.repository.PagedRepository
import javax.inject.Inject
class PagedRemoteViewModel @Inject constructor(@Remote pagedRepository: PagedRepository) :
PagedViewModel(pagedRepository) | 0 | Kotlin | 1 | 9 | 9e18e5262e88c190b1cd111939fa42b6c5a5e3d0 | 343 | droidcon-clean-repository | Apache License 2.0 |
sample/kotlin/src/main/kotlin/com/datadog/android/sample/data/db/room/LogRoom.kt | DataDog | 219,536,756 | false | null | /*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2016-Present Datadog, Inc.
*/
package com.datadog.android.sample.data.db.room
import android.provider.BaseColumns
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.datadog.android.sample.data.db.DatadogDbContract
import java.util.UUID
@Entity(tableName = DatadogDbContract.Logs.TABLE_NAME)
internal data class LogRoom(
@PrimaryKey
@ColumnInfo(name = BaseColumns._ID)
val uid: String = UUID.randomUUID().toString(),
@ColumnInfo(name = DatadogDbContract.Logs.COLUMN_NAME_MESSAGE)
val message: String,
@ColumnInfo(name = DatadogDbContract.Logs.COLUMN_NAME_TIMESTAMP)
val timestamp: String,
@ColumnInfo(name = DatadogDbContract.Logs.COLUMN_NAME_TTL)
val ttl: Long
)
| 33 | null | 39 | 86 | bcf0d12fd978df4e28848b007d5fcce9cb97df1c | 974 | dd-sdk-android | Apache License 2.0 |
library/src/main/java/com/github/windsekirun/naraeimagepicker/utils/CommonEx.kt | WindSekirun | 116,440,429 | false | null | package com.github.windsekirun.naraeimagepicker.utils
import android.app.Activity
import android.database.Cursor
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.Toast
/**
* NaraeImagePicker
* Class: CommonEx
* Created by Pyxis on 1/6/18.
*
* Description:
*/
fun Cursor.getColumnString(columnName: String) = this.getString(this.getColumnIndex(columnName))
fun Cursor.getColumnInt(columnName: String) = this.getInt(this.getColumnIndex(columnName))
fun Cursor.getColumnLong(columnName: String) = this.getLong(this.getColumnIndex(columnName))
inline fun catchAll(action: () -> Unit) {
try {
action()
} catch (t: Throwable) {
Log.e("NaraeImagePicker", "Catch an exception. ${t.message}", t)
}
}
fun Activity?.toast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
fun runOnUiThread(action: () -> Unit) = Handler(Looper.getMainLooper()).post(Runnable(action))
| 2 | Kotlin | 14 | 40 | 02f2905b1c4310d268d0e0b01fb959f6711ec1a0 | 978 | NaraeImagePicker | Apache License 2.0 |
src/main/kotlin/de/menkalian/pisces/command/impl/audio/JoinCommand.kt | Menkalian | 471,663,267 | false | null | package de.menkalian.pisces.command.impl.audio
import de.menkalian.pisces.OnConfigValueCondition
import de.menkalian.pisces.RequiresKey
import de.menkalian.pisces.audio.IAudioHandler
import de.menkalian.pisces.command.CommonCommandBase
import de.menkalian.pisces.command.ICommandHandler
import de.menkalian.pisces.command.data.CommandParameter
import de.menkalian.pisces.command.data.ECommandSource
import de.menkalian.pisces.database.IDatabaseHandler
import de.menkalian.pisces.message.IMessageHandler
import de.menkalian.pisces.util.FixedVariables
import de.menkalian.pisces.util.withWarningColor
import org.springframework.context.annotation.Conditional
import org.springframework.stereotype.Component
/**
* Implementierung eines Befehls der den Bot dem aktuellen Voicechat joinen lässt
*/
@Component
@Conditional(OnConfigValueCondition::class)
@RequiresKey(["pisces.command.impl.audio.Join"])
class JoinCommand(override val databaseHandler: IDatabaseHandler, val messageHandler: IMessageHandler, val audioHandler: IAudioHandler) : CommonCommandBase() {
override fun initialize() {
innerCategory = "Audio"
aliases.add("j")
aliases.add("kommmalher")
supportedContexts.addAll(ALL_GUILD_CONTEXTS)
supportedSources.addAll(ALL_SOURCES)
super.initialize()
}
override val name: String
get() = "join"
override val description: String
get() = "Der Bot tritt deinem aktuellen Voice-Channel bei."
override fun execute(
commandHandler: ICommandHandler,
source: ECommandSource,
parameters: List<CommandParameter>,
guildId: Long,
channelId: Long,
authorId: Long,
sourceInformation: FixedVariables
) {
val controller = audioHandler.getGuildAudioController(guildId)
val targetId = controller.getUserVoiceChannelId(authorId)
if (targetId != null && controller.connect(targetId)) {
messageHandler
.createMessage(guildId, channelId)
.withTitle("Verbindung zu deinem Voice-Channel erfolgreich hergestellt.")
.build()
} else {
messageHandler
.createMessage(guildId, channelId)
.withWarningColor()
.withTitle(
if (targetId == null) {
"Du bist in keinem Voice-Channel. Der Bot kann dir also nicht beitreten."
} else {
"Die Verbindung zum Voice-Channel ist fehlgeschlagen. Möglicherweise fehlen dem Bot die nötigen Rechte."
}
)
.build()
}
}
} | 0 | Kotlin | 0 | 1 | f37a1d8ecf612818ac9eed7976c717767e5259d0 | 2,680 | pisces | Apache License 2.0 |
trustagent/tests/unit/src/com/google/android/libraries/car/trustagent/PendingCarV2OobAssociationTest.kt | cailidz | 421,459,703 | true | {"Swift": 933403, "Kotlin": 823763, "Java": 243210, "Objective-C": 9962, "Objective-C++": 8509} | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.android.libraries.car.trustagent
import android.bluetooth.BluetoothDevice
import android.content.Context
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.android.companionprotos.OperationProto.OperationType
import com.google.android.encryptionrunner.EncryptionRunner
import com.google.android.encryptionrunner.EncryptionRunnerFactory
import com.google.android.encryptionrunner.EncryptionRunnerFactory.EncryptionRunnerType
import com.google.android.encryptionrunner.HandshakeMessage.HandshakeState
import com.google.android.libraries.car.trustagent.blemessagestream.BluetoothConnectionManager
import com.google.android.libraries.car.trustagent.blemessagestream.BluetoothGattManager
import com.google.android.libraries.car.trustagent.blemessagestream.MessageStream
import com.google.android.libraries.car.trustagent.blemessagestream.StreamMessage
import com.google.android.libraries.car.trustagent.testutils.Base64CryptoHelper
import com.google.android.libraries.car.trustagent.util.uuidToBytes
import com.google.common.truth.Truth.assertThat
import com.google.common.util.concurrent.MoreExecutors.directExecutor
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.argumentCaptor
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.verifyZeroInteractions
import com.nhaarman.mockitokotlin2.whenever
import java.security.SecureRandom
import java.util.UUID
import java.util.concurrent.CopyOnWriteArrayList
import javax.crypto.KeyGenerator
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestCoroutineDispatcher
import kotlinx.coroutines.test.resetMain
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.shadow.api.Shadow
private val DEVICE_ID = UUID.randomUUID()
private val TEST_VERIFICATION_TOKEN = "testVerificationToken".toByteArray()
private const val INIT_MESSAGE_ID = 1
private const val CONT_MESSAGE_ID = 2
private const val DEVICE_AND_SECRET_KEY_MESSAGE_ID = 3
@ExperimentalCoroutinesApi
@RunWith(AndroidJUnit4::class)
class PendingCarV2OobAssociationTest {
private val context = ApplicationProvider.getApplicationContext<Context>()
private val testDispatcher = TestCoroutineDispatcher()
private val mockGattManager: BluetoothGattManager = mock()
private val mockPendingCarCallback: PendingCar.Callback = mock()
private val mockStream: MessageStream = mock()
private lateinit var pendingCar: PendingCarV2OobAssociation
private lateinit var streamCallbacks: CopyOnWriteArrayList<MessageStream.Callback>
private lateinit var gattCallbacks:
CopyOnWriteArrayList<BluetoothConnectionManager.ConnectionCallback>
private lateinit var serverRunner: EncryptionRunner
private lateinit var associatedCarManager: AssociatedCarManager
private lateinit var database: ConnectedCarDatabase
private lateinit var bluetoothDevice: BluetoothDevice
private lateinit var oobConnectionManager: OobConnectionManager
private lateinit var serverOobConnectionManager: OobConnectionManager
private lateinit var oobAuthCode: ByteArray
@Before
fun setUp() {
bluetoothDevice = Shadow.newInstanceOf(BluetoothDevice::class.java)
// Using directExecutor to ensure that all operations happen on the main thread and allows for
// tests to wait until the operations are done before continuing. Without this, operations can
// leak and interfere between tests. See b/153095973 for details.
database =
Room.inMemoryDatabaseBuilder(context, ConnectedCarDatabase::class.java)
.allowMainThreadQueries()
.setQueryExecutor(directExecutor())
.build()
associatedCarManager = AssociatedCarManager(context, database, Base64CryptoHelper())
gattCallbacks = CopyOnWriteArrayList()
whenever(
mockGattManager.registerConnectionCallback(
any<BluetoothConnectionManager.ConnectionCallback>()
)
)
.thenAnswer {
val callback = it.getArgument(0) as BluetoothConnectionManager.ConnectionCallback
gattCallbacks.add(callback)
}
whenever(
mockGattManager.unregisterConnectionCallback(
any<BluetoothConnectionManager.ConnectionCallback>()
)
)
.thenAnswer {
val callback = it.getArgument(0) as BluetoothConnectionManager.ConnectionCallback
gattCallbacks.remove(callback)
}
streamCallbacks = CopyOnWriteArrayList()
// Keep track of the stream callbacks because encryption runner also registers one.
whenever(mockStream.registerMessageEventCallback(any<MessageStream.Callback>())).thenAnswer {
val callback = it.getArgument(0) as MessageStream.Callback
streamCallbacks.add(callback)
}
whenever(mockStream.unregisterMessageEventCallback(any<MessageStream.Callback>())).thenAnswer {
val callback = it.getArgument(0) as MessageStream.Callback
streamCallbacks.remove(callback)
}
setUpMockStreamMessageId()
oobConnectionManager =
OobConnectionManager().apply {
setOobData(TEST_DECRYPTION_IV + TEST_ENCRYPTION_IV + TEST_KEY.encoded)
}
serverOobConnectionManager =
OobConnectionManager().apply {
setOobData(TEST_ENCRYPTION_IV + TEST_DECRYPTION_IV + TEST_KEY.encoded)
}
serverRunner = EncryptionRunnerFactory.newRunner(EncryptionRunnerType.OOB_UKEY2)
pendingCar = createPendingCar(oobConnectionManager)
}
@After
fun tearDown() {
database.close()
Dispatchers.resetMain()
testDispatcher.cleanupTestCoroutines()
}
@Test
fun createdBySecurityVersion() {
assertThat(
PendingCar.create(
2,
context,
isAssociating = true,
stream = mockStream,
associatedCarManager = associatedCarManager,
device = bluetoothDevice,
bluetoothManager = mockGattManager,
oobConnectionManager = oobConnectionManager
)
)
.isInstanceOf(PendingCarV2OobAssociation::class.java)
}
@Test
fun connect_onConnected() {
pendingCar.connect()
respondToInitMessage()
respondToOobContMessage()
// Message containing device Id and secret key is delivered.
streamCallbacks.forEach { it.onMessageSent(DEVICE_AND_SECRET_KEY_MESSAGE_ID) }
verify(mockPendingCarCallback).onConnected(any())
verify(mockPendingCarCallback, never()).onAuthStringAvailable(any())
}
@Test
fun testOnOobAuthTokenAvailable_sendsEncryptedAuthToken() {
pendingCar.encryptionCallback.onOobAuthTokenAvailable(TEST_VERIFICATION_TOKEN)
verify(mockPendingCarCallback, never()).onConnectionFailed(pendingCar)
argumentCaptor<StreamMessage>().apply {
verify(mockStream).sendMessage(capture())
assertThat(lastValue.operation).isEqualTo(OperationType.ENCRYPTION_HANDSHAKE)
assertThat(lastValue.isPayloadEncrypted).isFalse()
}
}
@Test
fun testHandleOobVerificationMessage_invalidAuthTokenReceived_invokesOnConnectionFailed() {
pendingCar.encryptionCallback.onOobAuthTokenAvailable(TEST_VERIFICATION_TOKEN)
streamCallbacks.forEach {
it.onMessageReceived(
createStreamMessage(
serverOobConnectionManager.encryptVerificationCode(
"invalidVerificationToken".toByteArray()
)
)
)
}
verify(mockPendingCarCallback).onConnectionFailed(pendingCar)
}
@Test
fun testEncryptedCodeReceivedBeforeSent_ignoreMessage() {
streamCallbacks.forEach {
it.onMessageReceived(
createStreamMessage(
serverOobConnectionManager.encryptVerificationCode("IgnoredMessage".toByteArray())
)
)
}
verify(mockStream, never()).sendMessage(any())
verifyZeroInteractions(mockPendingCarCallback)
}
/**
* Sets up the returned message ID.
*
* Connection flow waits for certain message delivery. These message IDs can be used to trigger
* the next state.
*/
private fun setUpMockStreamMessageId() {
whenever(mockStream.sendMessage(any()))
.thenReturn(INIT_MESSAGE_ID)
.thenReturn(CONT_MESSAGE_ID)
.thenReturn(DEVICE_AND_SECRET_KEY_MESSAGE_ID)
}
private fun respondToInitMessage() {
argumentCaptor<StreamMessage>().apply {
// First message is encryption init.
verify(mockStream).sendMessage(capture())
val message = serverRunner.respondToInitRequest(lastValue.payload)
streamCallbacks.forEach { it.onMessageReceived(createStreamMessage(message.nextMessage!!)) }
}
}
private fun respondToOobContMessage() {
argumentCaptor<StreamMessage>().apply {
// Second message is encryption cont. message. Third is the encrypted code message.
verify(mockStream, times(3)).sendMessage(capture())
val contMessage =
serverRunner.continueHandshake(secondValue.payload).also {
assertThat(it.handshakeState).isEqualTo(HandshakeState.OOB_VERIFICATION_NEEDED)
}
oobAuthCode = contMessage.fullVerificationCode!!
val encryptedToken = serverOobConnectionManager.encryptVerificationCode(oobAuthCode)
streamCallbacks.forEach { it.onMessageReceived(createStreamMessage(encryptedToken)) }
// Check the auth string is accepted as soon as it becomes available.
verify(mockStream).encryptionKey = any()
val idMessage = createStreamMessage(uuidToBytes(DEVICE_ID))
// Send IHU device ID as confirmation.
streamCallbacks.forEach { it.onMessageReceived(idMessage) }
}
}
private fun createStreamMessage(payload: ByteArray) =
StreamMessage(
payload,
operation = OperationType.ENCRYPTION_HANDSHAKE,
isPayloadEncrypted = false,
originalMessageSize = 0,
recipient = null
)
private fun createPendingCar(oobConnectionManager: OobConnectionManager) =
PendingCarV2OobAssociation(
context,
messageStream = mockStream,
associatedCarManager = associatedCarManager,
device = bluetoothDevice,
bluetoothManager = mockGattManager,
oobConnectionManager = oobConnectionManager,
coroutineScope = CoroutineScope(testDispatcher)
)
.apply { callback = mockPendingCarCallback }
companion object {
private val TEST_KEY = KeyGenerator.getInstance("AES").generateKey()
private val TEST_ENCRYPTION_IV =
ByteArray(OobConnectionManager.NONCE_LENGTH_BYTES).apply { SecureRandom().nextBytes(this) }
private val TEST_DECRYPTION_IV =
ByteArray(OobConnectionManager.NONCE_LENGTH_BYTES).apply { SecureRandom().nextBytes(this) }
}
}
| 0 | null | 0 | 0 | bfb5508c818a7682ba1bec8a0744755026e3698a | 11,462 | android-auto-companion-android | Apache License 2.0 |
common/src/commonMain/kotlin/com.chrynan.chat/model/contact/FullContact.kt | chRyNaN | 206,982,352 | false | null | package com.chrynan.chat.model.contact
import com.chrynan.chat.model.account.AccountConnection
import com.chrynan.chat.model.core.ID
import com.chrynan.chat.model.core.Node
import com.chrynan.chat.model.core.UriString
data class FullContact(
override val id: ID,
val imageUri: UriString? = null,
val isPinned: Boolean = false,
val name: PersonName,
val info: ContactInfo,
val accountConnection: AccountConnection? = null
) : Node | 0 | Kotlin | 0 | 3 | 8269e4bcecad6ba4ef10e211ca4cb52e1cdff4b8 | 455 | Chat | Apache License 2.0 |
app/src/main/java/io/github/binishmanandhar23/differentscreensize/data/BookListData.kt | binishmanandhar23 | 507,541,156 | false | {"Kotlin": 60485} | package io.github.binishmanandhar23.differentscreensize.data
data class BookListData(val title: String, val optionText: String, val bookListPreviewData: List<BookListPreviewData>)
| 0 | Kotlin | 0 | 0 | 1e2282e161750e11592cdbf5ca92367c71a45c5a | 181 | DifferentScreenSize | Apache License 2.0 |
app/src/main/java/vukan/com/apursp/ui/product_image/ProductImageFragment.kt | Vukan-Markovic | 350,144,485 | false | null | package vukan.com.apursp.ui.product_image
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.fragment.app.Fragment
import vukan.com.apursp.GlideApp
import vukan.com.apursp.R
import vukan.com.apursp.firebase.Storage
class ProductImageFragment : Fragment() {
private lateinit var slika: ImageView
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.image, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
slika = view.findViewById(R.id.slika)
val storage = Storage()
if (arguments != null)
GlideApp.with(slika.context)
.load(storage.getProductImage(ProductImageFragmentArgs.fromBundle(requireArguments()).imageUrl))
.into(slika)
}
} | 0 | Kotlin | 0 | 0 | ddc120c6be8b5e4069e49b14c4d5c9abf036a454 | 1,062 | Saleroom-converted | MIT License |
Builders/Function literals with receiver/src/Task.kt | diskostu | 554,658,487 | false | null | fun task(): List<Boolean> {
val isEven: Int.() -> Boolean = {
val isEven = this % 2 == 0
println("Is $this even? -> $isEven")
isEven
}
val isOdd: Int.() -> Boolean = {
!this.isEven()
}
return listOf(42.isOdd(), 239.isOdd(), 294823098.isEven())
}
fun main() {
println("task() = ${task()}")
}
| 0 | Kotlin | 0 | 0 | 3cad6559e1add8d202e15501165e2aca0ee82168 | 359 | Kotlin_Koans | MIT License |
src/test/kotlin/fr/o80/aoc/day14/part2/exercise.kt | olivierperez | 310,899,127 | false | null | package fr.o80.aoc.day14.part2
const val exercise_d14_p2 = "5001791" | 0 | Kotlin | 1 | 2 | a52ea4e58b273a1aec55500802ad210c24257498 | 69 | AdventOfCode-KotlinStarterKit | Apache License 2.0 |
app/src/main/java/lab/maxb/dark/presentation/extra/ItemHolder.kt | MaxBQb | 408,174,279 | false | null | package lab.maxb.dark.presentation.extra
import lab.maxb.dark.domain.operations.randomUUID
data class ItemHolder<T>(
val value: T,
val id: String = randomUUID,
)
fun <T, R> ItemHolder<T>.map(value: R)
= ItemHolder(value, id)
inline fun <T, R> ItemHolder<T>.map(block: (T) -> R)
= map(block(value))
| 0 | Kotlin | 0 | 3 | 15885b8ec13bc58d78c14a69e1c2f06f84ca4380 | 317 | TheDarkApp.Client | MIT License |
src/main/kotlin/com/wgtwo/example/Secrets.kt | working-group-two | 228,354,121 | false | null | package com.wgtwo.example
import java.lang.System.getenv
object Secrets {
val WGTWO_CLIENT_ID = getenv("WGTWO_CLIENT_ID") ?: throw IllegalStateException("Missing WGTWO_CLIENT_ID from environment")
val WGTWO_CLIENT_SECRET = getenv("WGTWO_CLIENT_SECRET") ?: throw IllegalStateException("Missing WGTWO_CLIENT_SECRET from environment")
}
| 1 | Kotlin | 0 | 0 | cc825067bdfd470e9e40f710e53fdea7b28d1cc1 | 344 | wgtwo-kotlin-code-snippets | Apache License 2.0 |
app/src/main/java/com/fozechmoblive/fluidwallpaper/livefluid/ui/component/language/LanguageStartActivity.kt | hoangvannhatanh | 763,325,226 | false | {"Kotlin": 227439, "Java": 183111, "GLSL": 66443} | package com.fozechmoblive.fluidwallpaper.livefluid.ui.component.language
import android.content.Intent
import android.content.res.Resources
import android.os.Build
import androidx.recyclerview.widget.LinearLayoutManager
import com.fozechmoblive.fluidwallpaper.livefluid.R
import com.fozechmoblive.fluidwallpaper.livefluid.app.AppConstants
import com.fozechmoblive.fluidwallpaper.livefluid.callback.CallBack
import com.fozechmoblive.fluidwallpaper.livefluid.databinding.ActivityLanguageStartBinding
import com.fozechmoblive.fluidwallpaper.livefluid.extentions.getPref
import com.fozechmoblive.fluidwallpaper.livefluid.extentions.onClick
import com.fozechmoblive.fluidwallpaper.livefluid.extentions.setPref
import com.fozechmoblive.fluidwallpaper.livefluid.ui.bases.BaseActivity
import com.fozechmoblive.fluidwallpaper.livefluid.ui.component.intro.IntroduceActivity
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class LanguageStartActivity : BaseActivity<ActivityLanguageStartBinding>() {
private var listLanguage: MutableList<Language> = ArrayList()
private lateinit var stringLanguage: String
private val languagesAdapter by lazy { LanguageAdapter() }
private var languageDefaultDevice = ""
override fun getLayoutActivity() = R.layout.activity_language_start
override fun initViews() {
super.initViews()
listLanguage.apply {
add(Language(R.drawable.iv_english, getString(R.string.english), "en"))
add(Language(R.drawable.iv_hindi, getString(R.string.hindi), "hi"))
add(Language(R.drawable.iv_spanish, getString(R.string.spanish), "es"))
add(Language(R.drawable.iv_french, getString(R.string.french), "fr"))
add(Language(R.drawable.iv_portuguese, getString(R.string.portuguese), "pt"))
}
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
languageDefaultDevice =
Resources.getSystem().configuration.locales.get(0).toString()
if (languageDefaultDevice.lowercase().contains("in_")) {
languageDefaultDevice = getString(R.string.indonesian)
} else if (languageDefaultDevice.lowercase().contains("en_")) {
languageDefaultDevice = getString(R.string.english)
} else if (languageDefaultDevice.lowercase().contains("es_")) {
languageDefaultDevice = getString(R.string.spanish)
} else if (languageDefaultDevice.lowercase().contains("fr_")) {
languageDefaultDevice = getString(R.string.french)
} else if (languageDefaultDevice.lowercase().contains("pt_")) {
languageDefaultDevice = getString(R.string.portuguese)
} else if (languageDefaultDevice.lowercase().contains("hi_")) {
languageDefaultDevice = getString(R.string.hindi)
} else if (languageDefaultDevice.lowercase().contains("de_")) {
languageDefaultDevice = getString(R.string.german)
} else {
languageDefaultDevice = getString(R.string.english)
setPref(
this@LanguageStartActivity,
AppConstants.LANGUAGE_FIRST_DEFAULT_LOCALE,
true
)
}
} else {
languageDefaultDevice = getString(R.string.english)
setPref(
this@LanguageStartActivity,
AppConstants.LANGUAGE_FIRST_DEFAULT_LOCALE,
true
)
}
} catch (_: Exception) {
languageDefaultDevice = getString(R.string.english)
setPref(
this@LanguageStartActivity,
AppConstants.LANGUAGE_FIRST_DEFAULT_LOCALE,
true
)
}
//set item first for name language app
for (i in listLanguage.indices) {
if (listLanguage[i].name == languageDefaultDevice) {
listLanguage.add(0, listLanguage[i])
listLanguage.removeAt(i + 1)
}
}
stringLanguage = getPref(
this@LanguageStartActivity,
AppConstants.PREFERENCE_SELECTED_LANGUAGE,
getString(R.string.english)
).toString()
if (stringLanguage == languageDefaultDevice) {
setPref(
this@LanguageStartActivity,
AppConstants.LANGUAGE_FIRST_DEFAULT_LOCALE,
false
)
} else {
for (i in listLanguage.indices) {
if (listLanguage[i].name == stringLanguage) {
listLanguage.add(1, listLanguage[i])
listLanguage.removeAt(i + 1)
}
}
}
initRecyclerview()
}
override fun onClickViews() {
super.onClickViews()
binding.ivTick.onClick(1000) {
setPref(
this@LanguageStartActivity,
AppConstants.PREFERENCE_SELECTED_LANGUAGE,
stringLanguage
)
setPref(
this@LanguageStartActivity,
AppConstants.LANGUAGE_FIRST_DEFAULT_LOCALE,
true
)
startActivity(
Intent(
this@LanguageStartActivity,
IntroduceActivity::class.java
)
)
finish()
}
languagesAdapter.callBackLanguage(object : CallBack.CallBackLanguage {
override fun callBackLanguage(language: String, position: Int) {
stringLanguage = language
languagesAdapter.checkSelectView(position)
}
})
}
private fun initRecyclerview() {
try {
binding.recyclerView.apply {
layoutManager = LinearLayoutManager(
this@LanguageStartActivity,
LinearLayoutManager.VERTICAL,
false
)
if (!getPref(
this@LanguageStartActivity,
AppConstants.LANGUAGE_FIRST_DEFAULT_LOCALE,
false
)
) {
languagesAdapter.addAll(listLanguage, 0)
} else {
languagesAdapter.addAll(listLanguage, 1)
}
adapter = languagesAdapter
}
} catch (_: Exception) {
}
}
} | 0 | Kotlin | 0 | 0 | c9e8296ab6640b4e9cc44fd347057bfe8c236c3d | 6,652 | fluid_wallpaper | MIT License |
app/src/main/java/com/jnj/vaccinetracker/common/data/repositories/MasterDataRepository.kt | johnsonandjohnson | 503,902,626 | false | {"Kotlin": 1690434} | package com.jnj.vaccinetracker.common.data.repositories
import com.jnj.vaccinetracker.common.data.encryption.EncryptionService
import com.jnj.vaccinetracker.common.data.helpers.AndroidFiles
import com.jnj.vaccinetracker.common.data.helpers.Md5HashGenerator
import com.jnj.vaccinetracker.common.data.models.api.response.AddressHierarchyDto
import com.jnj.vaccinetracker.common.data.models.api.response.LocalizationMapDto
import com.jnj.vaccinetracker.common.domain.entities.Configuration
import com.jnj.vaccinetracker.common.domain.entities.MasterDataFile
import com.jnj.vaccinetracker.common.domain.entities.Sites
import com.jnj.vaccinetracker.common.helpers.AppCoroutineDispatchers
import com.jnj.vaccinetracker.common.helpers.logInfo
import com.jnj.vaccinetracker.common.helpers.logWarn
import com.jnj.vaccinetracker.common.helpers.toTemp
import com.jnj.vaccinetracker.sync.data.models.SyncDate
import com.jnj.vaccinetracker.sync.data.models.VaccineSchedule
import com.jnj.vaccinetracker.sync.data.models.vaccineScheduleAdapter
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import kotlinx.coroutines.withContext
import java.io.File
import java.io.IOException
import javax.inject.Inject
class MasterDataRepository @Inject constructor(
androidFiles: AndroidFiles,
private val moshi: Moshi,
private val encryptionService: EncryptionService,
private val dispatchers: AppCoroutineDispatchers,
private val md5HashGenerator: Md5HashGenerator,
) {
companion object {
private const val masterDataFolderName = "master_data"
}
private val filesDir: File = androidFiles.externalFiles
private val configAdapter get() = moshi.adapter(Configuration::class.java)
private val sitesAdapter get() = moshi.adapter(Sites::class.java)
private val addressHierarchyAdapter get() = moshi.adapter<List<String>>(Types.newParameterizedType(List::class.java, String::class.java))
private val localizationAdapter get() = moshi.adapter(LocalizationMapDto::class.java)
private val vaccineScheduleAdapter = moshi.vaccineScheduleAdapter()
private val masterDataDir get() = File(filesDir, masterDataFolderName)
private fun masterDataFile(fileName: String): File {
val folder = masterDataDir.apply {
mkdirs()
}
return File(folder, fileName)
}
private suspend fun writeFile(masterDataFile: MasterDataFile, json: String) = withContext(dispatchers.io) {
logInfo("writeFile: $masterDataFile")
val dstFile = masterDataFile(masterDataFile.fileName)
val tmpFile = dstFile.toTemp()
tmpFile.delete()
if (masterDataFile.isEncrypted)
encryptionService.writeEncryptedFile(tmpFile, json)
else
tmpFile.writeText(json)
dstFile.delete()
if (!tmpFile.renameTo(dstFile))
throw IOException("failed to rename $tmpFile to $dstFile [masterDataFile:$masterDataFile]")
}
private suspend fun MasterDataFile.readContentDecrypted(): String? {
val masterDataFile = this
return withContext(dispatchers.io) {
val srcFile = masterDataFile(masterDataFile.fileName)
if (srcFile.canRead()) {
if (masterDataFile.isEncrypted) {
encryptionService.readEncryptedFileAsText(srcFile)
} else srcFile.readText()
} else {
logWarn("$masterDataFile not available")
null
}
}
}
@Suppress("BlockingMethodInNonBlockingContext")
private suspend fun <T> readFile(masterDataFile: MasterDataFile, adapter: JsonAdapter<T>) = withContext(dispatchers.io) {
masterDataFile.readContentDecrypted()?.let { json -> adapter.fromJson(json) }
}
fun deleteAll() {
masterDataDir.listFiles()?.forEach { it.delete() }
}
suspend fun writeConfiguration(configuration: Configuration) = withContext(dispatchers.io) {
writeFile(MasterDataFile.CONFIGURATION, configAdapter.toJson(configuration))
}
suspend fun writeSites(sites: Sites) = withContext(dispatchers.io) {
writeFile(MasterDataFile.SITES, sitesAdapter.toJson(sites))
}
suspend fun writeVaccineSchedule(vaccineSchedule: VaccineSchedule) = withContext(dispatchers.io) {
writeFile(MasterDataFile.VACCINE_SCHEDULE, vaccineScheduleAdapter.toJson(vaccineSchedule))
}
suspend fun writeAddressHierarchy(addressHierarchy: AddressHierarchyDto) = withContext(dispatchers.io) {
writeFile(MasterDataFile.ADDRESS_HIERARCHY, addressHierarchyAdapter.toJson(addressHierarchy))
}
suspend fun writeLocalizationMap(localization: LocalizationMapDto) = withContext(dispatchers.io) {
writeFile(MasterDataFile.LOCALIZATION, localizationAdapter.toJson(localization))
}
fun storeDateModifiedOrThrow(masterDataFile: MasterDataFile, dateModified: SyncDate) {
val success = storeDateModified(masterDataFile, dateModified)
if (!success)
error("Failed to set date modified for $masterDataFile")
}
private fun storeDateModified(masterDataFile: MasterDataFile, dateModified: SyncDate): Boolean {
val f = masterDataFile(masterDataFile.fileName)
if (f.canRead()) {
return f.setLastModified(dateModified.time)
} else {
logWarn("file $masterDataFile cannot be read so cannot set date modified")
}
return false
}
fun getDateModified(masterDataFile: MasterDataFile): SyncDate? {
val f = masterDataFile(masterDataFile.fileName)
if (f.canRead()) {
val lastModified = f.lastModified()
if (lastModified > 0) {
return SyncDate(lastModified)
}
}
return null
}
suspend fun readLocalizationMap(): LocalizationMapDto? = readFile(MasterDataFile.LOCALIZATION, localizationAdapter)
suspend fun readSites(): Sites? = readFile(MasterDataFile.SITES, sitesAdapter)
suspend fun readConfiguration(): Configuration? = readFile(MasterDataFile.CONFIGURATION, configAdapter)
suspend fun readAddressHierarchy(): AddressHierarchyDto? = readFile(MasterDataFile.ADDRESS_HIERARCHY, addressHierarchyAdapter)
suspend fun readVaccineSchedule(): VaccineSchedule? = readFile(MasterDataFile.VACCINE_SCHEDULE, vaccineScheduleAdapter)
suspend fun md5Hash(masterDataFile: MasterDataFile): String? {
return masterDataFile.readContentDecrypted()?.let { md5HashGenerator.md5(it) }
}
} | 2 | Kotlin | 1 | 1 | dbf657c7fb7cb1233ed5c26bc554a1032afda3e0 | 6,572 | vxnaid | Apache License 2.0 |
spigot-gui/src/main/kotlin/ru/astrainteractive/astralibs/menu/menu/InventorySlotExt.kt | Astra-Interactive | 422,588,271 | false | {"Kotlin": 110093} | @file:Suppress("TooManyFunctions")
package ru.astrainteractive.astralibs.menu.slot.util
import net.kyori.adventure.text.Component
import org.bukkit.Material
import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.meta.ItemMeta
import ru.astrainteractive.astralibs.menu.clicker.Click
import ru.astrainteractive.astralibs.menu.slot.InventorySlot
object InventorySlotBuilderExt {
/**
* Set new material for current [InventorySlot.Builder.itemStack]
*/
fun InventorySlot.Builder.setMaterial(material: Material): InventorySlot.Builder {
itemStack.type = material
return this
}
/**
* Replace current ItemStack with new
*/
fun InventorySlot.Builder.setItemStack(itemStack: ItemStack): InventorySlot.Builder {
this.itemStack = itemStack
return this
}
/**
* Set inventory index of an item
*/
fun InventorySlot.Builder.setIndex(index: Int): InventorySlot.Builder {
this.index = index
return this
}
/**
* Set click listener for an item
*/
fun InventorySlot.Builder.setOnClickListener(click: Click): InventorySlot.Builder {
this.click = click
return this
}
/**
* Edit ItemStack
*/
fun InventorySlot.Builder.editItemStack(block: ItemStack.() -> Unit): InventorySlot.Builder {
itemStack = itemStack.apply(block)
return this
}
/**
* Edit ItemMeta
*/
fun InventorySlot.Builder.editMeta(block: ItemMeta.() -> Unit): InventorySlot.Builder {
itemStack.itemMeta = itemStack.itemMeta.apply(block)
return this
}
/**
* Set amount of ItemStack
*/
fun InventorySlot.Builder.setAmount(amount: Int): InventorySlot.Builder {
itemStack.amount = amount
return this
}
/**
* Set displayName of ItemStack
*/
fun InventorySlot.Builder.setDisplayName(string: String): InventorySlot.Builder {
editMeta {
this.setDisplayName(string)
}
return this
}
/**
* Set displayName of ItemStack
*/
fun InventorySlot.Builder.setDisplayName(component: Component): InventorySlot.Builder {
editMeta {
displayName(component)
}
return this
}
/**
* Set lore of ItemStack
*/
fun InventorySlot.Builder.setLore(loreComponents: List<Component>): InventorySlot.Builder {
editMeta {
lore(loreComponents)
}
return this
}
/**
* Add lore line into ItemStack
*/
fun InventorySlot.Builder.addLore(loreComponent: Component): InventorySlot.Builder {
editMeta {
val currentLore = lore().orEmpty().toMutableList()
currentLore.add(loreComponent)
lore(currentLore)
}
return this
}
/**
* Add a predicate for computed builder action
*/
fun InventorySlot.Builder.predicate(
condition: Boolean,
block: InventorySlot.Builder.() -> Unit
): InventorySlot.Builder {
if (condition) block.invoke(this)
return this
}
}
| 1 | Kotlin | 0 | 3 | bb1b90672880705880ce68bd2bb78494b2b7e525 | 3,140 | AstraLibs | MIT License |
backend/src/main/kotlin/ru/glitchless/santa/repository/auth/vas3k/Vas3kAuthRepository.kt | glitchless | 225,166,682 | false | {"TypeScript": 92354, "Kotlin": 85133, "SCSS": 22802, "JavaScript": 12185, "HTML": 8829, "Dockerfile": 913, "Shell": 886} | package ru.glitchless.santa.repository.auth.vas3k
import com.auth0.jwt.exceptions.JWTVerificationException
import com.google.gson.GsonBuilder
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.insertAndGetId
import org.jetbrains.exposed.sql.transactions.transaction
import org.jetbrains.exposed.sql.update
import ru.glitchless.santa.model.api.auth.vas3k.Vas3kUser
import ru.glitchless.santa.model.db.User
import ru.glitchless.santa.model.db.UserDao
import ru.glitchless.santa.model.db.auth.Vas3kUserInfo
import ru.glitchless.santa.model.db.auth.Vas3kUserInfoDAO
import ru.glitchless.santa.model.exception.throwables.AuthException
import ru.glitchless.santa.model.exception.throwables.ExpiredException
import ru.glitchless.santa.utils.Config
import ru.glitchless.santa.utils.ConfigKey
import ru.glitchless.santa.utils.JWTHelper
import ru.glitchless.santa.utils.SantaDateHelper
import ru.glitchless.santa.utils.tg.LogSantaBot
private val jwtHelper = JWTHelper()
private val gson = GsonBuilder().create()
fun finishAuthVas3k(jwt: String): User {
val json = try {
jwtHelper.decodeAndValidate(jwt)
} catch (ex: JWTVerificationException) {
throw AuthException()
}
val vas3kUser = gson.fromJson(json, Vas3kUser::class.java)
return transaction {
val existUser = Vas3kUserInfo.find { Vas3kUserInfoDAO.slug eq vas3kUser.slug }
.firstOrNull()
if (existUser != null) {
Vas3kUserInfoDAO.update({ Vas3kUserInfoDAO.slug eq existUser.slug }) {
it[fullName] = existUser.fullName
it[raw] = json
}
if (existUser.santaUserName.email == null) {
UserDao.update({ UserDao.id eq existUser.santaUserName.id }) {
it[email] = vas3kUser.email
}
}
return@transaction existUser.santaUserName
}
val profileUrl = "https://vas3k.club/user/${vas3kUser.slug}/"
try {
SantaDateHelper.checkExpired()
LogSantaBot.logJoin("${vas3kUser.name}", profileUrl)
} catch (ex: ExpiredException) {
LogSantaBot.logFailedJoin("${vas3kUser.name}", profileUrl)
throw ex
}
val userId = UserDao.insertAndGetId {
it[fullName] = vas3kUser.name ?: Config.get(ConfigKey.SANTA_UNKNOWN_NAME)
it[UserDao.profileUrl] = profileUrl
it[email] = vas3kUser.email
it[deliveryName] = vas3kUser.name ?: Config.get(ConfigKey.SANTA_UNKNOWN_NAME)
}
Vas3kUserInfoDAO.insert {
it[slug] = vas3kUser.slug
it[fullName] = vas3kUser.name
it[santaUserId] = userId
it[raw] = json
}
return@transaction User[userId]
}
}
| 0 | TypeScript | 0 | 1 | a50be3d0a8f9fbbc6f2268e213bb8c92e02ba70a | 2,803 | SecretSanta | Apache License 2.0 |
app/src/main/java/com/ojhdtapp/parabox/ui/message/chat/MessageItem.kt | Parabox-App | 482,740,446 | false | {"Kotlin": 811420} | package com.ojhdtapp.parabox.ui.message.chat
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
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.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.ojhdtapp.parabox.domain.model.Message
import com.ojhdtapp.parabox.domain.model.MessageWithSender
import com.ojhdtapp.parabox.domain.model.contains
import com.ojhdtapp.parabox.ui.common.CommonAvatar
import com.ojhdtapp.parabox.ui.message.MessagePageEvent
import com.ojhdtapp.parabox.ui.message.MessagePageState
import com.ojhdtapp.paraboxdevelopmentkit.model.message.ParaboxMessageElement
@Composable
fun MessageItem(
modifier: Modifier = Modifier,
state: MessagePageState.ChatDetail,
messageWithSender: MessageWithSender,
isFirst: Boolean = true,
isLast:Boolean = true,
shouldShowUserInfo: Boolean,
onEvent: (e: MessagePageEvent) -> Unit,
) {
val context = LocalContext.current
val isSelected by remember(state.selectedMessageList) {
derivedStateOf {
state.selectedMessageList.contains(messageWithSender.message.messageId)
}
}
val topStartRadius by animateDpAsState(targetValue = if (isFirst) 24.dp else 3.dp)
val bottomStartRadius by animateDpAsState(targetValue = if (isLast) 24.dp else 3.dp)
val backgroundColor by animateColorAsState(
targetValue =
if (isSelected) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.secondaryContainer
)
val textColor by animateColorAsState(
targetValue =
if (isSelected) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSecondaryContainer
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Start
) {
Box(modifier = Modifier.size(42.dp)) {
if (shouldShowUserInfo) {
CommonAvatar(
model = messageWithSender.sender.avatar.getModel(),
name = messageWithSender.sender.name
)
}
}
Spacer(modifier = Modifier.width(8.dp))
Column(modifier = Modifier.weight(1f)) {
if (shouldShowUserInfo) {
Text(
text = messageWithSender.sender.name,
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary
)
}
Spacer(modifier = Modifier.height(2.dp))
Surface(
shape = RoundedCornerShape(
topStart = topStartRadius,
topEnd = 24.dp,
bottomStart = bottomStartRadius,
bottomEnd = 24.dp
),
border = BorderStroke(3.dp, backgroundColor),
color = backgroundColor
) {
Column {
SelectionContainer {
Box(modifier = Modifier
.fillMaxWidth()
.height(40.dp)
.background(Color.Yellow))
// messageWithSender.message.contents.toLayout()
}
LazyRow(
contentPadding = PaddingValues(horizontal = 12.dp),
horizontalArrangement = Arrangement.spacedBy(4.dp)
) {
}
}
}
Spacer(modifier = Modifier.width(96.dp))
}
}
}
fun MessageItemSelf(
modifier: Modifier = Modifier,
message: Message,
onEvent: (e: MessagePageEvent) -> Unit,
) {
}
@Composable
private fun List<ParaboxMessageElement>.toLayout() {
}
| 0 | Kotlin | 5 | 94 | d10ed0f9cec27f8f0e4a0d81bf039631a732954f | 5,024 | Parabox | MIT License |
src/main/kotlin/no/nav/pale/HttpHandler.kt | purebase | 153,675,583 | false | null | package no.nav.pale
import io.ktor.application.ApplicationCall
import io.ktor.application.call
import io.ktor.http.ContentType
import io.ktor.response.respondText
import io.ktor.response.respondWrite
import io.ktor.routing.accept
import io.ktor.routing.get
import io.ktor.routing.routing
import io.ktor.server.engine.ApplicationEngine
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.prometheus.client.CollectorRegistry
import io.prometheus.client.exporter.common.TextFormat
val collectorRegistry: CollectorRegistry = CollectorRegistry.defaultRegistry
private val prometheusContentType = ContentType.parse(TextFormat.CONTENT_TYPE_004)
data class SelftestStatus(val status: String, val applicationVersion: String)
fun createHttpServer(port: Int = 8080, applicationVersion: String): ApplicationEngine = embeddedServer(Netty, port) {
routing {
accept(ContentType.Application.Json) {
get("/is_alive") {
call.respondJson(SelftestStatus(status = "I'm alive", applicationVersion = applicationVersion))
}
get("/is_ready") {
call.respondJson(SelftestStatus(status = "I'm ready", applicationVersion = applicationVersion))
}
}
get("/is_alive") {
call.respondText("I'm alive.", ContentType.Text.Plain)
}
get("/is_ready") {
call.respondText("I'm ready.", ContentType.Text.Plain)
}
get("/prometheus") {
val names = call.request.queryParameters.getAll("name[]")?.toSet() ?: setOf()
call.respondWrite(prometheusContentType) {
TextFormat.write004(this, collectorRegistry.filteredMetricFamilySamples(names))
}
}
}
}.start()
suspend fun ApplicationCall.respondJson(json: suspend () -> Any) {
respondWrite {
objectMapper.writeValue(this, json.invoke())
}
}
suspend fun ApplicationCall.respondJson(input: Any) {
respondWrite(ContentType.Application.Json) {
objectMapper.writeValue(this, input)
}
}
| 0 | Kotlin | 0 | 0 | 8168e978017701b6016ee7d985036c6b94325d35 | 2,086 | pale | MIT License |
app/src/main/java/com/hilmihanif/kerawanangempadantsunami/MainActivity.kt | HanifHilmi | 667,231,018 | false | null | package com.hilmihanif.kerawanangempadantsunami
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material3.Surface
import androidx.navigation.compose.rememberNavController
import com.hilmihanif.kerawanangempadantsunami.ui.navGraphs.RootNavigationGraph
import com.hilmihanif.kerawanangempadantsunami.ui.theme.KerawananGempaDanTsunamiTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
KerawananGempaDanTsunamiTheme {
Surface{
RootNavigationGraph(navController = rememberNavController())
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | b6496d1681c9e008013ad0fa9f07b0313cfab7de | 794 | DiseminasiKerawananGempaAndroid | Apache License 2.0 |
app/src/main/java/es/uam/eps/tfg/menuPlanner/database/DatabaseEntities.kt | moliverac8 | 381,427,467 | false | null | package es.uam.eps.tfg.menuPlanner.database
import androidx.room.*
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
class GenderTypeConverter {
@TypeConverter
fun enumToString(gender: Gender) = gender.toString()
@TypeConverter
fun stringToEnum(gender: String) = when(gender) {
Gender.MAN.toString() -> Gender.MAN
Gender.WOMAN.toString() -> Gender.MAN
else -> Gender.NONE
}
}
class LifeStyleTypeConverter {
@TypeConverter
fun enumToString(lifeStyle: LifeStyle) = lifeStyle.toString()
@TypeConverter
fun stringToEnum(lifeStyle: String) = when(lifeStyle) {
LifeStyle.ACTIVE.toString() -> LifeStyle.ACTIVE
LifeStyle.M_ACTIVE.toString() -> LifeStyle.M_ACTIVE
LifeStyle.SEDENTARY.toString() -> LifeStyle.SEDENTARY
else -> LifeStyle.NONE
}
}
class DaysConverter {
@TypeConverter
fun listToString(id_day: List<String>): String {
return id_day.joinToString()
}
@TypeConverter
fun StringToList(days: String): List<String> {
return days.split(",")
}
}
@Entity
data class Recipe(
@PrimaryKey val id_recipe: Int, val title: String, val dishTypes: String,
val instructions: String, val sourceUrl: String, val image: String,
var isSaved: Boolean = false, val readyInMinutes: Int, val servings: Int, val cuisines: List<String> = mutableListOf(), var rating: Int = 0
) {
constructor() : this(0, "", " ", "", "", "", false, 0, 0, mutableListOf())
constructor(
id: Int,
title: String,
instructions: String,
sourceUrl: String,
image: String,
readyInMinutes: Int,
servings: Int,
cuisines: List<String>
) : this(id, title, "", instructions, sourceUrl, image, false, readyInMinutes, servings, cuisines)
}
@Entity
data class Ingredient(
@PrimaryKey val id_ingredient: String,
val name: String,
var checked: Boolean = false){
constructor(): this("", ",", false)
}
@Entity
data class User(
@PrimaryKey var id_user: String,
var username: String,
var age: Int,
var height: Int,
var weight: Int,
var gender: Gender,
var lifeStyle: LifeStyle
) {
constructor() : this(
"", "", 0, 0, 0,
Gender.NONE,
LifeStyle.NONE
)
fun toUserFromFirebase(savedRecipes: List<Int> = mutableListOf()): UserFromFirebase =
UserFromFirebase(id_user, username, age, height, weight, gender, lifeStyle, savedRecipes)
}
@Entity
data class Stats(
@PrimaryKey(autoGenerate = true) val id_stats: Int,
val id_recipe: Int,
val calories: Float,
val protein: Float,
val fat: Float,
val carbs: Float
) {
constructor(id_recipe: Int, calories: Float, protein: Float, fat: Float, carbs: Float) : this(0, id_recipe, calories, protein, fat, carbs)
}
data class UserFromFirebase(
var id_user: String,
var username: String,
var age: Int,
var height: Int,
var weight: Int,
var gender: Gender,
var lifeStyle: LifeStyle,
var savedRecipes: List<Int>
) {
constructor() : this(
"", "", 0, 0, 0,
Gender.NONE,
LifeStyle.NONE,
mutableListOf()
)
fun toUser(): User = User(
id_user, username, age, height, weight, gender, lifeStyle
)
}
@Entity(primaryKeys = ["id_recipe", "id_stats"])
data class RecipeStatsCross(
val id_recipe: Int,
val id_stats: Int
)
@Entity(primaryKeys = ["id_recipe", "id_ingredient"])
data class RecipeIngCross(
val id_recipe: Int,
val id_ingredient: String,
val amount: Float,
val unit: String
)
@Entity(primaryKeys = ["id_recipe", "id_user"])
data class RecipeUserCross(
val id_recipe: Int,
val id_user: String,
val id_day: List<String>
)
data class UserWithRecipes(
@Embedded val user: User,
@Relation(
parentColumn = "id_user",
entityColumn = "id_recipe",
associateBy = Junction(RecipeUserCross::class)
)
val recipes: List<Recipe>
)
data class RecipeWithIng(
@Embedded val recipe: Recipe,
@Relation(
parentColumn = "id_recipe",
entityColumn = "id_ingredient",
associateBy = Junction(RecipeIngCross::class)
)
val ingredients: List<Ingredient>
)
@DatabaseView("select Ingredient.id_ingredient, name, checked, amount, unit, id_day " +
"from Ingredient, RecipeIngCross, Recipe, RecipeUserCross " +
"where RecipeUserCross.id_recipe = Recipe.id_recipe and Recipe.id_recipe = RecipeIngCross.id_recipe " +
"and RecipeIngCross.id_ingredient = Ingredient.id_ingredient")
data class ShoppingList(
val id_ingredient: Int,
val name: String,
var checked: Boolean,
val amount: Float,
val unit: String,
val id_day: List<String>
)
@DatabaseView("select Ingredient.id_ingredient, name, amount, unit, Recipe.id_recipe from Ingredient, " +
"RecipeIngCross, Recipe where Recipe.id_recipe = RecipeIngCross.id_recipe" +
" and RecipeIngCross.id_ingredient = Ingredient.id_ingredient")
data class RecipeIngredients(
val id_ingredient: Int,
val name: String,
val amount: Float,
val unit: String,
val id_recipe: Int
)
data class Rating(
val breakfast: MutableMap<String, Int>,
val dinner: MutableMap<String, Int>,
val lunch: MutableMap<String, Int>
){
constructor() : this(mutableMapOf(), mutableMapOf(), mutableMapOf())
override fun toString(): String {
return "Rating(breakfast=$breakfast, dinner=$dinner, lunch=$lunch)"
}
}
enum class Gender {
WOMAN, MAN, NONE
}
enum class LifeStyle {
SEDENTARY, M_ACTIVE, ACTIVE, NONE
} | 0 | Kotlin | 0 | 0 | cd0a233af55e94512697a70e96127f1cc534d732 | 5,658 | Menu-Planner | Apache License 2.0 |
src/test/kotlin/com/example/realworld/unit/dto/ErrorResponseTest.kt | brunohenriquepj | 367,784,702 | false | null | package com.example.realworld.unit.dto
import com.example.realworld.dto.ErrorResponse
import com.example.realworld.util.ListFactory
import com.example.realworld.util.builder.common.StringBuilder
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
class ErrorResponseTest {
@Test
fun `of should set response data message`() {
// arrange
val message = StringBuilder().build()
val expected = listOf(message)
// act
val actual = ErrorResponse.of(message)
// assert
actual.errors.body.toList() shouldBe expected
}
@Test
fun `of should set response data messages`() {
// arrange
val messages = ListFactory.generate({ StringBuilder().build() })
// act
val actual = ErrorResponse.of(messages.toTypedArray())
// assert
actual.errors.body.toList() shouldBe messages
}
}
| 7 | Kotlin | 0 | 2 | a3da13258606924f185b249545955e142f783b92 | 913 | spring-boot-kotlin-realworld | MIT License |
core/common/src/Buffers.kt | Kotlin | 105,809,601 | false | null | /*
* Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE.txt file.
*/
package kotlinx.io
import kotlinx.io.bytestring.ByteString
import kotlinx.io.bytestring.buildByteString
/**
* Creates a byte string containing a copy of all the data from this buffer.
*
* This call doesn't consume data from the buffer, but instead copies it.
*/
public fun Buffer.snapshot(): ByteString {
if (size == 0L) return ByteString()
check(size <= Int.MAX_VALUE) { "Buffer is too long ($size) to be converted into a byte string." }
return buildByteString(size.toInt()) {
var curr = head
do {
check(curr != null) { "Current segment is null" }
append(curr.data, curr.pos, curr.limit)
curr = curr.next
} while (curr !== head)
}
} | 36 | Kotlin | 50 | 872 | 1ee0a1df3673e9f610cdc4fd820344b5bc6851b7 | 919 | kotlinx-io | Apache License 2.0 |
app/src/main/java/com/elementary/tasks/reminder/build/adapter/viewholder/BuilderAdapterViewType.kt | naz013 | 165,067,747 | false | {"Kotlin": 2990375, "HTML": 20925} | package com.elementary.tasks.reminder.build.adapter.viewholder
enum class BuilderAdapterViewType(val value: Int) {
ITEM(0),
NOTE(1);
}
| 0 | Kotlin | 4 | 11 | 9cf31d6ac95dbe727fd421ccaa53b570207a3a92 | 140 | reminder-kotlin | Apache License 2.0 |
app/src/main/java/com/khanappsnj/thinktank/data/model/Problem.kt | SKGitKit | 631,082,173 | false | null | package com.khanappsnj.thinktank.data.model
data class Problem(
val id: String = "",
val title: String = "",
val description: String = "",
val imageUrl: String = "",
val createdDate: Long = 0L,
val active: Boolean = false,
val solutions: List<Solution> = emptyList()
) | 0 | Kotlin | 0 | 1 | ee34e53e1828ee3b5f93c98dd8d3e89361993171 | 297 | ThinkTank | MIT License |
core/ui/src/main/kotlin/nl/q42/template/ui/compose/OnLifecycleEvent.kt | Q42 | 593,537,486 | false | {"Kotlin": 55441, "Python": 2058} | package nl.q42.template.ui.compose
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
@Composable
fun OnLifecycleResume(action: () -> Unit) {
OnLifecycleEvent { event ->
if (event == Lifecycle.Event.ON_RESUME) action()
}
}
@Composable
fun OnLifecycleStop(action: () -> Unit) {
OnLifecycleEvent { event ->
if (event == Lifecycle.Event.ON_STOP) action()
}
}
@Composable
fun OnLifecycleEvent(onEvent: (event: Lifecycle.Event) -> Unit) {
val eventHandler = rememberUpdatedState(onEvent)
val lifecycleOwner by rememberUpdatedState(LocalLifecycleOwner.current)
DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { _, event ->
eventHandler.value(event)
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose {
lifecycleOwner.lifecycle.removeObserver(observer)
}
}
} | 7 | Kotlin | 0 | 7 | 417ee4c1a99570a8c851be39f51881332b24f6e3 | 1,176 | Template.Android | MIT License |
android-ui/src/main/java/app/boletinhos/messaging/UiEvent.kt | lcszc | 256,382,727 | false | {"Kotlin": 201531} | package app.boletinhos.messaging
import androidx.annotation.StringRes
sealed class UiEvent {
data class ResourceMessage(@StringRes val messageRes: Int) : UiEvent()
}
| 2 | Kotlin | 2 | 35 | a2f02de29c4c074b5ecbda4a46349ac5b864842d | 172 | Boletinhos | MIT License |
toolkit/featureforms/src/androidTest/java/com/arcgismaps/toolkit/featureforms/SwitchFieldTests.kt | Esri | 585,717,773 | false | {"Kotlin": 1508969, "Shell": 16478} | /*
* Copyright 2024 Esri
*
* 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.arcgismaps.toolkit.featureforms
import android.content.Context
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.test.assert
import androidx.compose.ui.test.assertContentDescriptionContains
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertIsNotFocused
import androidx.compose.ui.test.assertIsOff
import androidx.compose.ui.test.assertIsOn
import androidx.compose.ui.test.assertTextEquals
import androidx.compose.ui.test.hasAnyChild
import androidx.compose.ui.test.hasContentDescription
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import com.arcgismaps.mapping.featureforms.FeatureForm
import com.arcgismaps.mapping.featureforms.FieldFormElement
import org.junit.Assert.fail
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class SwitchFieldTests : FeatureFormTestRunner(
uri = "https://www.arcgis.com/home/item.html?id=ff98f13b32b349adb55da5528d9174dc",
objectId = 1
) {
@get:Rule
val composeTestRule = createComposeRule()
private lateinit var context: Context
@Before
fun setUp() {
composeTestRule.setContent {
context = LocalContext.current
FeatureForm(featureForm = featureForm)
}
}
/**
* Test case 5.1:
* Given a SwitchField type with a pre-existing "on" value
* When the switch is tapped
* Then the switch toggles to an "off" state.
* https://devtopia.esri.com/runtime/common-toolkit/blob/main/designs/Forms/FormsTestDesign.md#test-case-51-test-switch-on
*/
@Test
fun testSwitchIsOn() {
// get the switch form element
val switchElement = featureForm.getFieldFormElementWithLabel("switch integer")
?: return fail("element not found")
// find the field with the the label
val switchField = composeTestRule.onNodeWithText(switchElement.label)
// assert it is displayed and not focused
switchField.assertIsDisplayed()
switchField.assertIsNotFocused()
// find the switch field
val switch = switchField.onChildWithContentDescription("switch", recurse = true)
switch.assertIsDisplayed()
// assert that the switch is on
switch.assertIsOn()
// assert the value displayed is the current "on" value
switchField.assertEditableTextEquals(switchElement.formattedValue)
// tap on the switch
switchField.performClick()
// assert that the switch is on
switch.assertIsOff()
// assert the value displayed is the current "off" value
switchField.assertEditableTextEquals(switchElement.formattedValue)
}
/**
* Test case 5.2:
* Given a SwitchField type with a pre-existing "off" value
* When the switch is tapped
* Then the switch toggles to an "on" state.
* https://devtopia.esri.com/runtime/common-toolkit/blob/main/designs/Forms/FormsTestDesign.md#test-case-52-test-switch-off
*/
@Test
fun testSwitchIsOff() {
// get the switch form element
val switchElement = featureForm.getFieldFormElementWithLabel("switch string")
?: return fail("element not found")
// find the field with the the label
val switchField = composeTestRule.onNodeWithText(switchElement.label)
// assert it is displayed and not focused
switchField.assertIsDisplayed()
switchField.assertIsNotFocused()
// find the switch control
val switch = switchField.onChildWithContentDescription("switch", recurse = true)
switch.assertIsDisplayed()
// assert that the switch is off
switch.assertIsOff()
// assert the value displayed is the current "off" value
switchField.assertEditableTextEquals(switchElement.formattedValue)
// tap on the switch
switchField.performClick()
// assert that the switch is on
switch.assertIsOn()
// assert the value displayed is the current "on" value
switchField.assertEditableTextEquals(switchElement.formattedValue)
}
/**
* Test case 5.3:
* Given a FieldFormElement with a SwitchFormInput type and no pre-existing value
* When the FeatureForm is displayed
* Then the FieldFormElement is displayed as a ComboBox.
* https://devtopia.esri.com/runtime/common-toolkit/blob/main/designs/Forms/FormsTestDesign.md#test-case-53-test-switch-with-no-value
*/
@Test
fun testSwitchWithNoValue() {
// get the switch form element
val switchElement = featureForm.getFieldFormElementWithLabel("switch double")
?: return fail("element not found")
// find the field with the the label
val comboBoxField = composeTestRule.onNodeWithText(switchElement.label)
// assert it is displayed and not focused
comboBoxField.assertIsDisplayed()
comboBoxField.assertIsNotFocused()
// assert that this field does not have any switch control
comboBoxField.assert(!hasAnyChild(hasContentDescription("switch")))
// assert a "no value" placeholder is visible
comboBoxField.assertTextEquals(
switchElement.label,
context.getString(R.string.no_value)
)
// validate that the options icon is visible
// since combo box fields have an icon and switch fields do not
comboBoxField.assertContentDescriptionContains("field icon").assertIsDisplayed()
}
}
/**
* Returns a [FieldFormElement] with the given [label] if it exists. Else a null is returned.
*/
internal fun FeatureForm.getFieldFormElementWithLabel(label: String): FieldFormElement? =
elements.find {
it is FieldFormElement && it.label == label
} as? FieldFormElement
| 9 | Kotlin | 4 | 14 | 0e54056a49f3b89967dcbdd7ebb69ed0ee97a5ac | 6,479 | arcgis-maps-sdk-kotlin-toolkit | Apache License 2.0 |
app/src/main/java/com/hoons/mycommonutils/MainActivity.kt | showthat | 355,445,406 | false | null | package com.hoons.mycommonutils
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import com.mobon.adfit_sdk.AdfitAdapter
import com.mobon.sdk.BannerType
import com.mobon.sdk.MobonSDK
import com.mobon.sdk.RectBannerView
import com.mobon.sdk.callback.iMobonBannerCallback
import io.github.showthat.dhstringutils.forFloat
import io.github.showthat.mycommonutils.*
import io.github.showthat.mycommonutils.BuildConfig
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d("my", "" + "".toNumber())
Log.d("my", "" + "2020-11-01".toDate())
Log.d("my", "" + "".toFloat())
Log.d("my", "" + "".toNumber())
val thumbnail = findViewById<ImageView>(R.id.imageViewThumbnail)
DHUtils.instance.updateImageView(this, thumbnail, "https://i.pinimg.com/originals/b0/d6/70/b0d670e21a8378565038c44bdd4ded7d.jpg")
MobonSDK(this, "mobon")
val banner_container = findViewById<LinearLayout>(R.id.viewForAD)
var rv = RectBannerView(this, BannerType.BANNER_320x50).setBannerUnitId("484613")
rv.setAdListener(object: iMobonBannerCallback {
override fun onLoadedAdInfo(success: Boolean, errorCode: String?) {
if (success) {
Log.d("my", "배너 광고 로딩")
//광고를 띄울 View에 추가...
banner_container.addView(rv)
}
else {
Log.d("my", "광고 실패 $errorCode")
rv.destroyAd()
rv = null
}
}
override fun onAdClicked() {
Log.d("my", "광고 클릭")
}
})
rv.loadAd()
}
} | 0 | Kotlin | 0 | 0 | d0acb1fe0d121360978509194da077073cc4a818 | 1,975 | MyCommonUtils | MIT License |
src/main/kotlin/com/tailoredapps/gradle/localize/LocalizationConfig.kt | Alfies-GmbH | 530,130,338 | true | {"Kotlin": 174166} | package com.tailoredapps.gradle.localize
import java.io.File
data class LocalizationConfig(
val productName: String,
val serviceAccountCredentialsFile: File,
val sheetId: String,
val worksheets: List<String>?,
val languageTitles: List<String>,
val baseLanguage: String,
val localizationPath: File,
val addToCheckTask: Boolean,
val addComments: Boolean,
val escapeApostrophes: Boolean
) | 0 | null | 0 | 0 | e6f02249d5999b8020bc9c23b8c1c64989383a78 | 427 | gradle-localize-plugin | Apache License 2.0 |
src/main/kotlin/ru/spbstu/kparsec/wheels/AbstractCharSequence.kt | vorpal-research | 115,148,080 | false | {"Kotlin": 145245} | package ru.spbstu.kparsec.wheels
data class CharSubSequence(val seq: CharSequence, val from: Int, val to: Int): AbstractCharSequence() {
override val length: Int
get() = to - from
override fun get(index: Int): Char = when {
index !in 0..length -> throw IndexOutOfBoundsException()
else -> seq[from + index]
}
override fun subSequence(startIndex: Int, endIndex: Int) = when {
endIndex !in 0..length -> throw IndexOutOfBoundsException()
else -> CharSubSequence(seq, from + startIndex, from + endIndex)
}
/* this is NOT redundant, as data classes override base classes' toString by default */
override fun toString() = super.toString()
}
private fun CharSequence.ethemeralSubSequence(startIndex: Int, endIndex: Int) = when(this) {
is CharSubSequence -> subSequence(startIndex, endIndex)
else -> CharSubSequence(this, startIndex, endIndex)
}
abstract class AbstractCharSequence: CharSequence {
override fun subSequence(startIndex: Int, endIndex: Int): CharSequence =
CharSubSequence(this, startIndex, endIndex)
override fun toString(): String {
val sb = StringBuilder()
for(i in 0 until length) {
sb.append(get(i))
}
return sb.toString()
}
}
data class ListAsCharSequence(val inner: List<Char>): AbstractCharSequence() {
override val length: Int = inner.size
override fun get(index: Int): Char = inner.get(index)
}
fun List<Char>.asCharSequence(): CharSequence = when(this) {
is CharSequenceAsList -> inner
else -> ListAsCharSequence(this)
}
data class CharSequenceAsList(val inner: CharSequence): AbstractList<Char>() {
override val size: Int get() = inner.length
override fun get(index: Int): Char = inner.get(index)
override fun subList(fromIndex: Int, toIndex: Int): List<Char> =
CharSequenceAsList(inner.ethemeralSubSequence(fromIndex, toIndex))
}
fun CharSequence.asCharList(): List<Char> = when(this) {
is ListAsCharSequence -> inner
else -> CharSequenceAsList(this)
}
| 0 | Kotlin | 0 | 0 | 3238c73af7bb4269176dac57b51614b1402313e5 | 2,076 | kparsec | MIT License |
app/src/main/java/com/jayabreezefsm/features/viewAllOrder/interf/GenderListOnClick.kt | DebashisINT | 674,180,669 | false | {"Kotlin": 13478860, "Java": 994064} | package com.jayabreezefsm.features.viewAllOrder.interf
import com.jayabreezefsm.app.domain.NewOrderGenderEntity
interface GenderListOnClick {
fun genderListOnClick(gender: NewOrderGenderEntity)
} | 0 | Kotlin | 0 | 0 | 0642af23a4db33e4a472cd194d09e6b81b2d369e | 201 | JayaIndustries | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.