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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
core/src/test/kotlin/net/kotlinx/core/calculator/BatchChunkTest.kt | mypojo | 565,799,715 | false | {"Kotlin": 979801, "Jupyter Notebook": 2068} | package net.kotlinx.core.calculator
import net.kotlinx.core.gson.GsonData
import net.kotlinx.core.gson.GsonSet
import net.kotlinx.test.TestRoot
import org.junit.jupiter.api.Test
class BatchChunkTest : TestRoot() {
data class Qq(
val name: String,
) {
lateinit var aa: String
}
@Test
fun poo() {
//val qq = Qq("aa").apply { aa = "123" }
val qq = Qq("aa")
println(qq)
val json = GsonSet.GSON.toJson(qq)
println(json)
val q2 = GsonData.parse(json).fromJson<Qq>()
println(q2)
println(q2.aa)
}
@Test
fun getPageCnt() {
// BatchChunk(999, 500).also { it.maxPageNo shouldBe 2 }
// BatchChunk(1000, 500).also { it.maxPageNo shouldBe 2 }
// BatchChunk(1001, 500).also { it.maxPageNo shouldBe 3 }
//
// BatchChunk(105, 33).also {
// it.maxPageNo shouldBe 4
// it.range(1) shouldBe (1L to 33L)
// it.range(3) shouldBe (67L to 99L)
// it.range(4) shouldBe (100L to 105L)
// }
}
} | 0 | Kotlin | 0 | 1 | 2f3340f3da3aa7241c602d6472dead8d9bf49d84 | 1,075 | kx_kotlin_support | MIT License |
spring-boot/API cliente/src/main/kotlin/sptech/projetojpa1/controller/RespostaController.kt | kronos-agendamento | 758,290,087 | false | {"Kotlin": 60498, "HTML": 41970, "CSS": 27041, "JavaScript": 5498} | package sptech.projetojpa1.controller
import jakarta.validation.Valid
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import sptech.projetojpa1.dominio.Resposta
import sptech.projetojpa1.repository.RespostaRepository
@RestController
@RequestMapping("/ficha-resposta")
class RespostaController(
val respostaRepository: RespostaRepository
) {
// Cadastro de Nova Resposta
@PostMapping("/cadastro-resposta")
fun cadastrarResposta(@RequestBody @Valid novaResposta: Resposta): ResponseEntity<Any> {
val respostaSalva = respostaRepository.save(novaResposta)
return ResponseEntity.status(201).body("Resposta ${respostaSalva.resposta} cadastrada com sucesso")
}
// Listar Todas as Respostas
@GetMapping("/lista-todas-respostas")
fun listarTodasRespostas(): ResponseEntity<Any> {
val respostas = respostaRepository.findAll()
if (respostas.isEmpty()) {
return ResponseEntity.status(204).body("Nenhuma resposta foi cadastrada.")
}
return ResponseEntity.status(200).body(respostas)
}
// Filtrar Respostas por CPF do Usuário
@GetMapping("/filtro-por-cpf/{cpf}")
fun filtrarPorCpf(@Valid @PathVariable cpf: String): ResponseEntity<Any> {
val respostas = respostaRepository.findByUsuarioCpf(cpf)
return if (respostas.isEmpty()) {
ResponseEntity.status(204).body("Nenhuma resposta foi cadastrada para esse cliente.")
} else {
// Mapeando as respostas para um formato específico antes de retornar
val respostasComUsuario = respostas.map { resposta ->
mapOf(
"resposta" to resposta.resposta,
"nomeUsuario" to resposta.usuario.nome,
"cpfUsuario" to resposta.usuario.cpf,
"dataPreenchimentoFicha" to resposta.ficha.dataPreenchimento
)
}
ResponseEntity.status(200).body(respostasComUsuario)
}
}
// Filtrar Respostas por Descrição da Pergunta
@GetMapping("/filtro-por-pergunta/{nome}")
fun filtrarPorPergunta(@Valid @PathVariable nome: String): ResponseEntity<Any> {
val respostas = respostaRepository.findByPerguntaDescricao(nome)
return if (respostas.isEmpty()) {
ResponseEntity.status(204).body("Nenhuma pergunta foi encontrada vinculada à essa pergunta.")
} else {
// Mapeando as respostas para um formato específico antes de retornar
val respostasComPergunta = respostas.map { resposta ->
mapOf(
"resposta" to resposta.resposta,
"descricaoPergunta" to resposta.pergunta.descricao,
"tipoPergunta" to resposta.pergunta.tipo,
"nomeUsuario" to resposta.usuario.nome,
"cpfUsuario" to resposta.usuario.cpf,
"dataPreenchimentoFicha" to resposta.ficha.dataPreenchimento
)
}
ResponseEntity.status(200).body(respostasComPergunta)
}
}
// Excluir Resposta por ID
@DeleteMapping("/exclusao-resposta/{id}")
fun excluirResposta(@PathVariable id: Int): ResponseEntity<String> {
val respostaOptional = respostaRepository.findById(id)
return if (respostaOptional.isPresent) {
respostaRepository.deleteById(id)
ResponseEntity.status(200).body("Resposta excluída com sucesso.")
} else {
ResponseEntity.status(404).body("Resposta não encontrada para o ID fornecido.")
}
}
}
| 0 | Kotlin | 0 | 2 | e40021c99e8b7e25a60d4222dddd1797f0919727 | 3,653 | projeto-teste | MIT License |
loginLibrary/src/main/java/com/github/mohamedwael/login/verificationcodelogin/verification/VerificationLoginViewModel.kt | MohamedWael | 270,424,052 | false | null | package com.github.mohamedwael.login.verificationcodelogin.verification
import android.os.Handler
import android.widget.Button
import androidx.databinding.BindingAdapter
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableInt
import androidx.lifecycle.MutableLiveData
import com.alimuzaffar.lib.pin.PinEntryEditText
import com.github.mohamedwael.login.R
import com.github.mohamedwael.login.base.BaseLoginViewModel
import com.github.mohamedwael.login.config.InputValidationProvider
import kotlin.math.absoluteValue
const val TIMER_TICK_DOWN_INTERVAL = 1000L
const val KEY_USER_NAME = "validated_username"
const val KEY_VERIFICATION_ID = "validated_verificationId"
class VerificationLoginViewModel(
private val verificationConfig: VerificationConfig,
inputValidationProvider: InputValidationProvider
) : BaseLoginViewModel(inputValidationProvider) {
var username: String? = null
private var timerHandler: Handler? = null
val resendButtonVisibility = ObservableBoolean(verificationConfig.isSendFirst)
val isTimerClickable = ObservableBoolean(verificationConfig.onTimerClick != null)
val pinCodeMaxLength = ObservableInt(verificationConfig.pinCodeMaxLength)
val verificationTitle = ObservableInt(R.string.verification_title)
val verificationDescription = ObservableInt(R.string.verification_description)
var remainingTime = verificationConfig.countDownTimeSecond.absoluteValue
val verificationCounterText = MutableLiveData("0")
val pinCodeListener = PinEntryEditText.OnPinEnteredListener {
hideKeyboard()
verificationConfig.onPinCodeChangeListener(username, it.toString())
}
var onSendClick: (() -> Unit)? = {
username?.also {
resendButtonVisibility.set(false)
verificationConfig.onSendClick?.invoke(it)
startTimer()
}
}
var onTimerClick: (() -> Unit)? = verificationConfig.onTimerClick
fun startTimer() {
if (timerHandler == null && !resendButtonVisibility.get()) {
timerHandler = Handler()
verificationConfig.onTimerStarted?.invoke()
}
timerHandler?.postDelayed(::onTimerTickDown, TIMER_TICK_DOWN_INTERVAL)
}
private fun onTimerTickDown() {
resendButtonVisibility.set(remainingTime <= 0)
if (remainingTime > 0) {
remainingTime -= 1
verificationCounterText.value = remainingTime.toString()
startTimer()
} else {
remainingTime = verificationConfig.countDownTimeSecond
verificationConfig.onTimerTickDownFinish?.invoke()
clearHandler()
}
}
private fun clearHandler() {
timerHandler?.removeCallbacks(::onTimerTickDown)
timerHandler = null
}
override fun onCleared() {
super.onCleared()
clearHandler()
onSendClick = null
onTimerClick = null
username = null
}
}
object VerificationBindingAdapter {
@JvmStatic
@BindingAdapter("app:updateTimer")
fun updateTimer(btn: Button, time: MutableLiveData<String>) {
btn.text = try {
val timer = time.value?.toInt() ?: 0
if (timer < 10)
"${btn.context.getString(R.string.remaining_time)}${"0" + time.value}"
else "${btn.context.getString(R.string.remaining_time)}${time.value}"
} catch (e: Exception) {
"${btn.context.getString(R.string.remaining_time)}${time.value}"
}
}
} | 0 | Kotlin | 0 | 1 | ed50417bf60692efd15cebd29e6171a912580843 | 3,518 | Login-library | MIT License |
loginLibrary/src/main/java/com/github/mohamedwael/login/verificationcodelogin/verification/VerificationLoginViewModel.kt | MohamedWael | 270,424,052 | false | null | package com.github.mohamedwael.login.verificationcodelogin.verification
import android.os.Handler
import android.widget.Button
import androidx.databinding.BindingAdapter
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableInt
import androidx.lifecycle.MutableLiveData
import com.alimuzaffar.lib.pin.PinEntryEditText
import com.github.mohamedwael.login.R
import com.github.mohamedwael.login.base.BaseLoginViewModel
import com.github.mohamedwael.login.config.InputValidationProvider
import kotlin.math.absoluteValue
const val TIMER_TICK_DOWN_INTERVAL = 1000L
const val KEY_USER_NAME = "validated_username"
const val KEY_VERIFICATION_ID = "validated_verificationId"
class VerificationLoginViewModel(
private val verificationConfig: VerificationConfig,
inputValidationProvider: InputValidationProvider
) : BaseLoginViewModel(inputValidationProvider) {
var username: String? = null
private var timerHandler: Handler? = null
val resendButtonVisibility = ObservableBoolean(verificationConfig.isSendFirst)
val isTimerClickable = ObservableBoolean(verificationConfig.onTimerClick != null)
val pinCodeMaxLength = ObservableInt(verificationConfig.pinCodeMaxLength)
val verificationTitle = ObservableInt(R.string.verification_title)
val verificationDescription = ObservableInt(R.string.verification_description)
var remainingTime = verificationConfig.countDownTimeSecond.absoluteValue
val verificationCounterText = MutableLiveData("0")
val pinCodeListener = PinEntryEditText.OnPinEnteredListener {
hideKeyboard()
verificationConfig.onPinCodeChangeListener(username, it.toString())
}
var onSendClick: (() -> Unit)? = {
username?.also {
resendButtonVisibility.set(false)
verificationConfig.onSendClick?.invoke(it)
startTimer()
}
}
var onTimerClick: (() -> Unit)? = verificationConfig.onTimerClick
fun startTimer() {
if (timerHandler == null && !resendButtonVisibility.get()) {
timerHandler = Handler()
verificationConfig.onTimerStarted?.invoke()
}
timerHandler?.postDelayed(::onTimerTickDown, TIMER_TICK_DOWN_INTERVAL)
}
private fun onTimerTickDown() {
resendButtonVisibility.set(remainingTime <= 0)
if (remainingTime > 0) {
remainingTime -= 1
verificationCounterText.value = remainingTime.toString()
startTimer()
} else {
remainingTime = verificationConfig.countDownTimeSecond
verificationConfig.onTimerTickDownFinish?.invoke()
clearHandler()
}
}
private fun clearHandler() {
timerHandler?.removeCallbacks(::onTimerTickDown)
timerHandler = null
}
override fun onCleared() {
super.onCleared()
clearHandler()
onSendClick = null
onTimerClick = null
username = null
}
}
object VerificationBindingAdapter {
@JvmStatic
@BindingAdapter("app:updateTimer")
fun updateTimer(btn: Button, time: MutableLiveData<String>) {
btn.text = try {
val timer = time.value?.toInt() ?: 0
if (timer < 10)
"${btn.context.getString(R.string.remaining_time)}${"0" + time.value}"
else "${btn.context.getString(R.string.remaining_time)}${time.value}"
} catch (e: Exception) {
"${btn.context.getString(R.string.remaining_time)}${time.value}"
}
}
} | 0 | Kotlin | 0 | 1 | ed50417bf60692efd15cebd29e6171a912580843 | 3,518 | Login-library | MIT License |
app/src/main/java/com/dlutrix/themoviewikicompose/ui/discover/UpcomingMovies.kt | DLutrix | 404,992,763 | false | null | package com.dlutrix.themoviewikicompose.ui.discover
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import androidx.paging.ExperimentalPagingApi
import androidx.paging.LoadState
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.items
import coil.annotation.ExperimentalCoilApi
import coil.compose.rememberImagePainter
import com.dlutrix.themoviewikicompose.R
import com.dlutrix.themoviewikicompose.data.entity.Movie
import com.dlutrix.themoviewikicompose.ui.theme.WhiteSmoke
import kotlinx.coroutines.launch
@ExperimentalPagingApi
@ExperimentalCoilApi
@ExperimentalMaterialApi
@Composable
fun UpcomingMovies(
movies: LazyPagingItems<Movie>,
isExpanded: Boolean,
bottomSheetScaffoldState: BottomSheetScaffoldState,
refreshDiscoverMovies: () -> Unit,
navController: NavController,
contentPadding: PaddingValues
) {
var paddingState by remember {
mutableStateOf(32.dp)
}
val paddingSize by animateDpAsState(
targetValue = paddingState,
spring(Spring.DampingRatioHighBouncy)
)
val scope = rememberCoroutineScope()
SideEffect {
paddingState = if (isExpanded) {
contentPadding.calculateTopPadding() + 64.dp
} else {
32.dp
}
}
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
LazyColumn(
contentPadding = PaddingValues(top = paddingSize, bottom = 16.dp)
) {
items(movies) { movie ->
UpcomingMoviesItem(movie = movie, navController = navController)
}
movies.apply {
when {
loadState.refresh is LoadState.Loading -> {
scope.launch {
bottomSheetScaffoldState.snackbarHostState.currentSnackbarData?.dismiss()
}
item { LoadingView(modifier = Modifier.fillParentMaxSize()) }
}
loadState.append is LoadState.Loading -> {
item { LoadingItem() }
}
loadState.refresh is LoadState.Error -> {
val e = movies.loadState.refresh as LoadState.Error
scope.launch {
val snackBarResult = bottomSheetScaffoldState.snackbarHostState
.showSnackbar(
e.error.localizedMessage!!,
actionLabel = "Retry",
duration = SnackbarDuration.Indefinite
)
when (snackBarResult) {
SnackbarResult.Dismissed -> {
}
SnackbarResult.ActionPerformed -> {
movies.refresh()
refreshDiscoverMovies()
bottomSheetScaffoldState.snackbarHostState.currentSnackbarData?.dismiss()
}
}
}
}
loadState.append is LoadState.Error -> {
val e = movies.loadState.append as LoadState.Error
item {
ErrorItem(
message = e.error.localizedMessage!!,
onClickRetry = {
movies.retry()
}
)
}
}
}
}
}
}
}
@ExperimentalCoilApi
@Composable
fun UpcomingMoviesItem(
movie: Movie?,
navController: NavController
) {
Box(
modifier = Modifier
.padding(
bottom = 16.dp,
end = 16.dp,
start = 16.dp
)
.height(200.dp)
.clickable {
navController.navigate(
"movie_detail_screen/${movie?.id}/${movie?.title}"
)
},
contentAlignment = Alignment.BottomStart
) {
Box(
contentAlignment = Alignment.BottomEnd
) {
Card(
modifier = Modifier.height(180.dp),
elevation = 8.dp,
shape = RoundedCornerShape(16.dp)
) {
Row(
modifier = Modifier.padding(top = 8.dp, end = 16.dp, start = 16.dp)
) {
Box(modifier = Modifier.weight(1f))
Column(
verticalArrangement = Arrangement.SpaceAround,
modifier = Modifier
.padding(start = 16.dp)
.fillMaxSize()
.weight(2f),
) {
Text(
text = movie?.title ?: "",
fontWeight = FontWeight.W600,
fontFamily = FontFamily(Font(R.font.nunito_bold)),
maxLines = 2,
overflow = TextOverflow.Ellipsis,
modifier = Modifier
.weight(1f)
.padding(end = 36.dp)
)
Text(
text = movie?.overview ?: "",
fontWeight = FontWeight.W400,
maxLines = 4,
overflow = TextOverflow.Ellipsis,
fontSize = 14.sp,
modifier = Modifier.weight(2f)
)
}
}
Box(
contentAlignment = Alignment.TopEnd,
modifier = Modifier.fillMaxWidth()
) {
Box(
modifier = Modifier
.clip(
RoundedCornerShape(
topEnd = 16.dp,
bottomStart = 16.dp
)
)
.fillMaxWidth(0.13f)
.background(MaterialTheme.colors.secondary),
contentAlignment = Alignment.Center
) {
Text(
text = movie?.voteAverage.toString(),
modifier = Modifier.padding(8.dp),
color = WhiteSmoke,
textAlign = TextAlign.Center,
fontWeight = FontWeight.W600
)
}
}
}
}
Box(
modifier = Modifier.fillMaxWidth(0.33f),
contentAlignment = Alignment.TopStart
) {
Card(
shape = RoundedCornerShape(16.dp),
elevation = 8.dp,
modifier = Modifier.padding(start = 8.dp, bottom = 16.dp)
) {
Image(
painter = rememberImagePainter(
"https://image.tmdb.org/t/p/w500/${movie?.posterPath}",
builder = {
crossfade(true)
}
),
contentDescription = "${movie?.title} image",
contentScale = ContentScale.Crop,
modifier = Modifier
.height(200.dp)
)
}
}
}
}
@Composable
fun LoadingView(
modifier: Modifier = Modifier
) {
Column(
modifier = modifier,
verticalArrangement = Arrangement.Top,
horizontalAlignment = Alignment.CenterHorizontally
) {
CircularProgressIndicator()
}
}
@Composable
fun LoadingItem() {
CircularProgressIndicator(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.wrapContentWidth(Alignment.CenterHorizontally)
)
}
@Composable
fun ErrorItem(
message: String,
modifier: Modifier = Modifier,
onClickRetry: () -> Unit
) {
Card(
elevation = 8.dp,
modifier = modifier.padding(
top = 16.dp,
start = 16.dp,
end = 16.dp,
bottom = 64.dp
)
) {
Row(
modifier.padding(
start = 16.dp,
end = 16.dp,
top = 8.dp,
bottom = 8.dp
),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = message,
maxLines = 1,
modifier = Modifier.weight(1f),
)
OutlinedButton(onClick = onClickRetry) {
Text(text = "Try again")
}
}
}
} | 0 | Kotlin | 0 | 2 | 8def6b0ed2b38305cce578fcd9d8afdb42b759ee | 10,246 | The-Movie-Wiki-Compose | MIT License |
ui/common/src/test/java/ly/david/ui/common/relation/RelationListItemTest.kt | lydavid | 458,021,427 | false | null | package ly.david.ui.common.relation
import com.google.testing.junit.testparameterinjector.TestParameterInjector
import ly.david.ui.common.PaparazziScreenshotTest
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(TestParameterInjector::class)
class RelationListItemTest : PaparazziScreenshotTest() {
@Test
fun artist() {
snapshot {
PreviewArtistRelationListItem()
}
}
@Test
fun recording() {
snapshot {
PreviewRecordingRelationListItem()
}
}
@Test
fun relation() {
snapshot {
PreviewUrlRelationListItem()
}
}
}
| 54 | Kotlin | 0 | 4 | 052613fefaeb5a687ee36d0f3889d9a120224994 | 648 | MusicSearch | Apache License 2.0 |
app/src/main/java/com/bayraktar/shop/model/Category.kt | ebayraktar | 382,096,078 | false | null | package com.bayraktar.shop.model
import android.os.Parcelable
import com.bayraktar.shop.model.base.BaseList
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
@Parcelize
data class Category(
@SerializedName("id")
@Expose val id: Int?,
@SerializedName("name")
@Expose val name: String?,
@SerializedName("parent_id")
@Expose val parentId: Int?,
@SerializedName("order")
@Expose val order: Int?,
@SerializedName("parent_category")
@Expose val parentCategory: ParentCategory?,
@SerializedName("logo")
@Expose val logo: Logo?,
@SerializedName("cover")
@Expose val cover: Cover?,
) : Parcelable, BaseList | 0 | Kotlin | 0 | 0 | e25800a7f574091f5b95c921df0bd373adae56cb | 743 | Shop | MIT License |
Kotlin/UploadLocal.kts | roboflow | 350,815,750 | false | null | import java.io.*
import java.net.HttpURLConnection
import java.net.URL
import java.nio.charset.StandardCharsets
import java.util.*
fun main() {
// Get Image Path
val filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "YOUR_IMAGE.jpg"
val file = File(filePath)
// Base 64 Encode
val encodedFile: String
val fileInputStreamReader = FileInputStream(file)
val bytes = ByteArray(file.length().toInt())
fileInputStreamReader.read(bytes)
encodedFile = String(Base64.getEncoder().encode(bytes), StandardCharsets.US_ASCII)
val API_KEY = "" // Your API Key
val MODEL_ENDPOINT = "dataset/v" // Set model endpoint (Found in Dataset URL)
// Construct the URL
val uploadURL ="https://detect.roboflow.com/" + MODEL_ENDPOINT + "?api_key=" + API_KEY + "&name=YOUR_IMAGE.jpg";
// Http Request
var connection: HttpURLConnection? = null
try {
// Configure connection to URL
val url = URL(uploadURL)
connection = url.openConnection() as HttpURLConnection
connection.requestMethod = "POST"
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded")
connection.setRequestProperty("Content-Length",
Integer.toString(encodedFile.toByteArray().size))
connection.setRequestProperty("Content-Language", "en-US")
connection.useCaches = false
connection.doOutput = true
//Send request
val wr = DataOutputStream(
connection.outputStream)
wr.writeBytes(encodedFile)
wr.close()
// Get Response
val stream = connection.inputStream
val reader = BufferedReader(InputStreamReader(stream))
var line: String?
while (reader.readLine().also { line = it } != null) {
println(line)
}
reader.close()
} catch (e: Exception) {
e.printStackTrace()
} finally {
connection?.disconnect()
}
}
main() | 3 | Python | 13 | 14 | 50bed6096ace5a82b59f72bb3f816b5748d05746 | 2,022 | roboflow-api-snippets | Apache License 2.0 |
app/src/main/java/com/example/coolwheather/service/AutoUpdateService.kt | nicejk | 292,979,024 | false | null | package com.example.coolwheather.service
import android.app.AlarmManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
import android.os.SystemClock
import android.preference.PreferenceManager
import com.example.coolwheather.WeatherActivity.Companion.SP_BINGPIC
import com.example.coolwheather.WeatherActivity.Companion.SP_WEATHER
import com.example.coolwheather.util.HttpUtil
import com.example.coolwheather.util.Utility
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.io.IOException
/**
* @Description:
* @author: haishan
* @Date: 2020/9/7
*/
class AutoUpdateService : Service() {
override fun onBind(intent: Intent?): IBinder? {
return null
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
updateWeather()
updateBiyingPic()
val manager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val anHour = 8 * 60 * 60 * 1000
val triggerAtTime = SystemClock.elapsedRealtime() + anHour
val i = Intent(this, AutoUpdateService::class.java)
val pi = PendingIntent.getService(this, 0, i, 0)
manager.cancel(pi)
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi)
return super.onStartCommand(intent, flags, startId)
}
private fun updateBiyingPic() {
val requestBiyingPic = "http://guolin.tech/api/bing_pic"
HttpUtil.sendOkHttpRequest(requestBiyingPic, object : Callback{
override fun onResponse(call: Call, response: Response) {
val biyingPic = response.body?.string()
val editor = PreferenceManager.getDefaultSharedPreferences(applicationContext).edit()
editor.putString(SP_BINGPIC, biyingPic)
editor.apply()
}
override fun onFailure(call: Call, e: IOException) {
}
})
}
private fun updateWeather() {
val prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext)
val weatherString = prefs.getString(SP_WEATHER, null)
if (!weatherString.isNullOrEmpty()) {
val weather = Utility.handleWeatherResponse(weatherString)
val weatherId = weather?.basic?.weatherId
val weatherUrl = "http://guolin.tech./api/weather?cityid=${weatherId}&key=d3d303b7ab314add897857be7f3300e7"
HttpUtil.sendOkHttpRequest(weatherUrl, object : Callback{
override fun onResponse(call: Call, response: Response) {
val responseText = response.body?.string()
val weatherResp = Utility.handleWeatherResponse(responseText)
if (weatherResp != null && "ok" == weatherResp.status) {
val editor = PreferenceManager.getDefaultSharedPreferences(applicationContext).edit()
editor.putString(SP_WEATHER, responseText)
editor.apply()
}
}
override fun onFailure(call: Call, e: IOException) {
}
})
}
}
} | 0 | Kotlin | 0 | 0 | d21ad2da32040ec3c74806f5be76bd8bee7d4b42 | 3,224 | coolweather | Apache License 2.0 |
plugin/src/main/kotlin/io/papermc/hangarpublishplugin/internal/model/ProjectPageContainerImpl.kt | HangarMC | 592,451,816 | false | null | /*
* Hangar Publish Plugin Gradle Plugin
* Copyright (c) 2023 HangarMC 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.papermc.hangarpublishplugin.internal.model
import io.papermc.hangarpublishplugin.model.ProjectPage
import io.papermc.hangarpublishplugin.model.ProjectPageContainer
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.NamedDomainObjectProvider
import org.gradle.api.provider.Provider
import javax.inject.Inject
abstract class ProjectPageContainerImpl @Inject constructor(
override val backingContainer: NamedDomainObjectContainer<ProjectPage>
) : ProjectPageContainer,
NamedDomainObjectContainer<ProjectPage> by backingContainer {
companion object {
const val RESOURCE_PAGE_ID = "MainResourcePage"
}
override fun resourcePage(content: String): NamedDomainObjectProvider<ProjectPage> = register(RESOURCE_PAGE_ID) {
this.content.set(content)
}
override fun resourcePage(content: Provider<String>): NamedDomainObjectProvider<ProjectPage> = register(RESOURCE_PAGE_ID) {
this.content.set(content)
}
override fun resourcePage(): NamedDomainObjectProvider<ProjectPage> = named(RESOURCE_PAGE_ID)
}
| 3 | Kotlin | 1 | 9 | cb4148e39c26dac9e6edbf84e0e3ac15b246cedc | 1,731 | hangar-publish-plugin | Apache License 2.0 |
Lint/LintChecks/src/main/java/com/lkl/android/lint/checks/detector/xml/ApplicationAttrDetector.kt | lkl22 | 447,592,588 | false | {"Kotlin": 97345, "Java": 11617} | package com.lkl.android.lint.checks.detector.xml
import com.android.SdkConstants
import com.android.tools.lint.detector.api.*
import com.android.xml.AndroidManifest
import com.google.gson.JsonObject
import com.lkl.android.lint.checks.bean.AttrItem
import com.lkl.android.lint.checks.detector.base.BaseConfigDetector
import com.lkl.android.lint.checks.utils.DetectorUtils
import com.lkl.android.lint.checks.utils.GsonUtils
import org.w3c.dom.Element
/**
* 检查Application Attr相关配置
*
* @author lkl
* @since 2022/02/21
*/
@Suppress("UnstableApiUsage")
class ApplicationAttrDetector : BaseConfigDetector(), XmlScanner {
companion object {
private const val REPORT_MESSAGE = "some attribute better to set correct value."
/**
* Issue describing the problem and pointing to the detector
* implementation.
*/
@JvmField
val ISSUE: Issue = Issue.create(
id = "ApplicationAttribute",
briefDescription = REPORT_MESSAGE,
explanation = REPORT_MESSAGE,
category = Category.SECURITY,
priority = 6,
severity = Severity.ERROR,
implementation = Implementation(
ApplicationAttrDetector::class.java, Scope.MANIFEST_SCOPE
)
)
}
private var attrs: List<AttrItem>? = null
override fun beforeCheckRootProject(context: Context) {
super.beforeCheckRootProject(context)
attrs = GsonUtils.parseJson2List(getJsonStringConfig("attrs"), AttrItem::class.java)
}
override fun getUsageConfig(): JsonObject? {
return getUsageConfig("application-attr")
}
override fun getApplicableElements(): Collection<String> {
return listOf(AndroidManifest.NODE_APPLICATION)
}
override fun visitElement(context: XmlContext, element: Element) {
attrs?.forEach {
if (!DetectorUtils.isBuildVariant(context, it.buildVariant)) {
return@forEach
}
if (!it.attrName.isNullOrBlank() && !it.attrValue.isNullOrBlank()) {
val ns = it.namespace ?: SdkConstants.ANDROID_URI
val attr = element.getAttributeNodeNS(ns, it.attrName)
if (attr == null || attr.value != it.attrValue) {
val scope = attr ?: element
context.report(
ISSUE,
scope,
context.getLocation(scope),
"${it.attrName} attribute better to set to ${it.attrValue}.",
fix().set(
ns, it.attrName, it.attrValue
).build()
)
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | 6d05c47f154b661090087fbc874f143b12b8cd58 | 2,770 | AndroidLint | Apache License 2.0 |
cameraViewEx/src/main/base/com/priyankvasa/android/cameraviewex/SizeMap.kt | kibotu | 171,441,617 | true | {"Kotlin": 261635, "Java": 6115, "RenderScript": 1028} | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.priyankvasa.android.cameraviewex
import android.support.v4.util.ArrayMap
import java.util.SortedSet
import java.util.TreeSet
/**
* A collection class that automatically groups [Size]s by their [AspectRatio]s.
*/
internal class SizeMap {
private val ratios = ArrayMap<AspectRatio, SortedSet<Size>>()
val isEmpty: Boolean get() = ratios.isEmpty
/**
* Add a new [Size] to this collection.
*
* @param size The size to add.
* @return `true` if it is added, `false` if it already exists and is not added.
*/
fun add(size: Size): Boolean {
ratios.keys.forEach { ratio ->
if (ratio.matches(size)) {
return if (ratios[ratio]?.contains(size) == true) false
else {
ratios[ratio]?.add(size)
true
}
}
}
// None of the existing ratio matches the provided size; add a new key
ratios[AspectRatio.of(size.width, size.height)] = TreeSet<Size>().apply { add(size) }
return true
}
/**
* Removes the specified aspect ratio and all sizes associated with it.
*
* @param ratio The aspect ratio to be removed.
* Note: [ratio] is nullable because for some reason, on older devices,
* looping through previewSizes in [Camera2.collectCameraInfo] has null elements. Seems like a ghost bug.
*/
fun remove(ratio: AspectRatio?) {
ratios.remove(ratio)
}
fun ratios(): Set<AspectRatio> = ratios.keys
/**
* Note: [ratio] is nullable because for some reason, on older devices,
* looping through previewSizes in [Camera1.supportedAspectRatios] has null elements. Seems like a ghost bug.
*/
fun sizes(ratio: AspectRatio?): SortedSet<Size> = ratios[ratio] ?: sortedSetOf()
fun clear() = ratios.clear()
} | 0 | Kotlin | 0 | 0 | 866e69bd092cefbc22de36a4fcf62a5cb5da79c1 | 2,488 | cameraview-ex | Apache License 2.0 |
src/main/kotlin/hash/HashListMode.kt | Fritz-Xu | 757,929,889 | false | {"Kotlin": 346637} | package hash
/**
* LettCode 981. 基于时间的键值存储(middle)
* https://leetcode.cn/problems/time-based-key-value-store
*/
class HashListMode {
data class Node(val timeStamp: Int, val value: String)
private val map = mutableMapOf<String, ArrayList<Node>>()
fun set(key: String, value: String, timestamp: Int) {
if (map[key] == null) {
map[key] = ArrayList()
}
map[key]?.add(Node(timestamp, value))
}
fun get(key: String, timestamp: Int): String {
map[key]?.let { list ->
if (list.size == 1) {
return if (list[0].timeStamp > timestamp) "" else list[0].value
}
var start = 0
var end = list.size - 1
while (start < end) {
val mid = (end + start + 1) shr 1
if (list[mid].timeStamp > timestamp) {
end = mid - 1
} else {
start = mid
}
}
return if(list[end].timeStamp > timestamp) "" else list[end].value
}
return ""
}
} | 0 | Kotlin | 0 | 0 | 39850bcd5f2ea9c2e051597064c8566189901726 | 1,101 | leetCodeStudy | MIT License |
app/src/main/java/com/example/missingseven/Screen/TaskScreen.kt | csc301-fall-2022 | 539,005,226 | false | null | package com.example.missingseven.Screen
import androidx.compose.runtime.Composable
import com.example.missingseven.Component.*
import com.example.missingseven.Model.TaskUiState
import com.example.missingseven.ViewModel.TaskViewModel
/***
* composable function for task screen
*/
@Composable
fun TaskScreen(
viewModel: TaskViewModel
){
TaskTemplate(
content = {
when (viewModel.getCurrentTask()){
is TaskUiState.ReadingTask -> {
ReadingTaskBody(
task = viewModel.getCurrentTask() as TaskUiState.ReadingTask,
skipHandler = viewModel::navigateBack
)
}
is TaskUiState.MultipleChoiceTask -> {
MultipleChoiceTaskBody({index->viewModel.updateChooseHandler(index)},
viewModel.getCurrentTask() as TaskUiState.MultipleChoiceTask)
}
is TaskUiState.SlidingScaleTask -> {
SlidingScaleTaskBody({curr -> viewModel.slidingScaleTaskChangeHandler(curr)},
viewModel.getCurrentTask() as TaskUiState.SlidingScaleTask)
}
is TaskUiState.ShortAnswerTask -> {
ShortAnswerTaskBody({viewModel.shortAnswerSaveHandler()},
viewModel.getCurrentTask() as TaskUiState.ShortAnswerTask,
{value -> viewModel.shortAnswerTaskValueChangeHandler(value)},
submitHandler = {context -> viewModel.submitAnswerHandler(context) }
)
}
is TaskUiState.WelcomeTask -> {
WelcomeTaskBody(viewModel = viewModel)
}
is TaskUiState.LiteracyRateTask -> {
LiteracyRateTaskBody(
task = viewModel.getCurrentTask() as TaskUiState.LiteracyRateTask)
}
is TaskUiState.GlobalLiteracyRateTask -> {
GlobalLiteracyRateBody(
task = viewModel.getCurrentTask() as TaskUiState.GlobalLiteracyRateTask)
}
else -> {}
}
},
nextHandler = {viewModel.onNextClicked()},
backHandler = {viewModel.onBackClicked()},
finishHandler = { viewModel.navigateBack()},
taskUiState = viewModel.getCurrentTask()!!,
shouldShowFirst = !viewModel.isFirstTask(),
shouldShowLast = !viewModel.isLastTask()
)
} | 0 | Kotlin | 1 | 0 | 866c02d651645fa2cee25f7b85a85af9797e566c | 2,550 | team-project-4-engineers-without-boarders-canada-t | MIT License |
dispatching-center/src/main/kotlin/com/qingzhu/dispatcher/service/AssignmentService.kt | nedphae | 322,789,778 | false | {"Kotlin": 744301, "ANTLR": 281490, "Java": 48298, "Dockerfile": 375} | package com.qingzhu.dispatcher.service
import com.qingzhu.common.domain.shared.msg.constant.CreatorType
import com.qingzhu.dispatcher.component.AssignmentComponent
import com.qingzhu.dispatcher.component.MessageService
import com.qingzhu.dispatcher.customer.domain.constant.PreventStrategy
import com.qingzhu.dispatcher.customer.domain.entity.Blacklist
import com.qingzhu.dispatcher.customer.service.BlacklistService
import com.qingzhu.dispatcher.domain.constant.CloseReason
import com.qingzhu.dispatcher.domain.constant.RelatedType
import com.qingzhu.dispatcher.domain.constant.TransferType
import com.qingzhu.dispatcher.domain.dto.*
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import reactor.kotlin.core.publisher.switchIfEmpty
import reactor.kotlin.core.publisher.toMono
import java.time.Duration
import java.time.Instant
@Service
class AssignmentService(
private val assignmentComponent: AssignmentComponent,
private val messageService: MessageService,
private val blacklistService: BlacklistService,
) {
/**
* 根据 机构id[organizationId] 和 用户id[userId] 自动分配客服,并返回会话信息
* TODO: 获取设置的用户信息里的客服ID 和 分组 配置
*/
fun assignmentAuto(organizationId: Int, userId: Long): Mono<ConversationViewDto> {
val customerDispatcherDto = assignmentComponent.getCustomerDispatcherWithCache(organizationId, userId)
// 检查黑名单
val blacklist = customerDispatcherDto.flatMap { cdd ->
val queryList = listOf(Blacklist(PreventStrategy.UID, cdd.uid), Blacklist(PreventStrategy.IP, cdd.ip))
.onEach { it.organizationId = cdd.organizationId }
blacklistService.getBlacklistBy(queryList.first())
.switchIfEmpty(blacklistService.getBlacklistBy(queryList.last()))
}.cache()
// 添加 10 分钟内自动转接人工
val mono = assignmentComponent
.getLastConversationWithCache(organizationId, userId)
.filterWhen {
// 检查是否在黑名单里
blacklist.map { _ -> it.interaction == 0 }.switchIfEmpty(Mono.just(true))
}
return mono
.transform { assignmentCustomerAndSendEvent(it) }
// 分配失败就分配新客服
.assignmentNewOnError(customerDispatcherDto)
// 不存在历史会话 或者 重新分配客服失败 就转到机器人客服
.switchIfEmpty(
assignmentComponent.getBot(customerDispatcherDto)
.switchIfEmpty {
// 没有机器人在线就分配到人工
customerDispatcherDto
.filterWhen {
// 检查是否在黑名单里
blacklist.map { false }.switchIfEmpty(Mono.just(true))
}
.flatMap { assignmentComponent.getStaff(it.toMono()) }
}
)
// 保存会话状态
.transform { assignmentComponent.saveConversation(it) }
.map {
ConversationStatusAndViewMapper.mapper.map2View(it)
}
.flatMap {
if (it.interaction == 0) {
val blockOnStaff = it.toMono().doOnNext { cvd -> cvd.blockOnStaff = 1 }
// 检查是否可以转人工
blacklist.flatMap {
// 在黑名单里不提供转人工
blockOnStaff
}.switchIfEmpty {
// 无人工客服在线也不可以转人工
messageService.findIdleStaff(it.organizationId, it.shuntId)
.next()
.map { _ -> it }
.switchIfEmpty {
blockOnStaff
}
}
} else {
it.toMono()
}
}
}
/**
* 用户主动点击转人工
* 根据 机构id[organizationId] 用户id[userId] 分配人工客服 / 或者进行排队
*/
fun assignmentStaff(organizationId: Int, userId: Long, fromQueue: Boolean = false): Mono<ConversationViewDto> {
val customerDispatcherDto = assignmentComponent.getCustomerDispatcherWithCache(organizationId, userId)
val mono = Mono
// 获取历史会话的人工座席信息
.defer { messageService.findLatestStaffConvByUserId(organizationId, userId) }
.cache()
return mono
.transform {
customerDispatcherDto
.flatMap { cd ->
assignmentNewConversation(it, cd)
}
}
.onErrorResume {
// 分配失败就重新分配到其他客服
assignmentComponent.getStaff(customerDispatcherDto)
.doOnNext { cs -> cs.transferType = TransferType.INITIATIVE }
}
.switchIfEmpty {
// 不存在历史座席就分配到新客服
assignmentComponent.getStaff(customerDispatcherDto)
.doOnNext { cs -> cs.transferType = TransferType.INITIATIVE }
}
.flatMap {
// 与机器人会话 进行双向关联
val endDto = assignmentComponent
.getLastConversationWithCache(organizationId, userId)
.doOnNext { lc ->
lc.closeReason = CloseReason.BOT_TO_STAFF
lc.isValid = 1
lc.terminator = CreatorType.CUSTOMER
lc.endTime = Instant.now()
}
.map { lc ->
it.relatedId = lc.id
it.relatedType = RelatedType.FROM_BOT
it.visitRange = Duration.between(it.startTime, lc.endTime).toMillis()
lc
}
Mono.zip(it.toMono(), endDto)
}
.flatMap { zip ->
// null 的时候丢失了类型信息
assignmentComponent.saveConversation(zip.t1.toMono())
.transform { cv ->
cv
.map {
zip.t2.relatedType = RelatedType.FROM_BOT
zip.t2.relatedId = it.id
zip.t2
}
.transform {
// 更新机器人会话
assignmentComponent.endConversation(it).transform { cv }
}
}
}
.map {
ConversationStatusAndViewMapper.mapper.map2View(it)
}
.switchIfEmpty {
if (!fromQueue) {
// getStaff 方法获取客服为空时 进行排队
assignmentComponent.pushIntoQueue(customerDispatcherDto)
} else {
// 分配失败 返回空
Mono.empty()
}
}
}
/**
* 根据 会话状态[ConversationStatusDto] 更新客服状态
* 然后更新会话信息
*/
private fun assignmentCustomerAndSendEvent(mono: Mono<ConversationStatusDto>): Mono<ConversationStatusDto> {
return mono
.map { StaffChangeStatusDto(it.organizationId, it.staffId, it.userId) }
.transform {
assignmentComponent
// 尝试分配到历史客服
.assignmentCustomer(it)
// 更新会话信息
.then(mono)
}
}
/**
* 根据 会话状态[ConversationStatusDto] 更新客服状态
* 然后更新会话信息
*/
private fun assignmentNewConversation(
mono: Mono<ConversationStatusDto>,
customerDispatcherDto: CustomerDispatcherDto
): Mono<ConversationStatusDto> {
return mono
.map { StaffChangeStatusDto(it.organizationId, it.staffId, it.userId) }
.transform {
assignmentComponent
// 尝试分配到历史客服
.assignmentCustomer(it)
// 更新会话信息
.then(it
.flatMap { sc ->
assignmentComponent.createConversation(customerDispatcherDto, sc.staffId)
})
}
}
/**
* 分配历史座席失败时,就根据历史信息分配到新客服
* 会新建一个会话,并与缓存的会话进行关联
*/
private fun Mono<ConversationStatusDto>.assignmentNewOnError(customerDispatcherDto: Mono<CustomerDispatcherDto>): Mono<ConversationStatusDto> {
return this
.onErrorResume {
this
.flatMap {
if (it.interaction == 1) {
// 客服会话
assignmentComponent
.getStaff(customerDispatcherDto)
.doOnNext { cs ->
// 设置为主动转人工
cs.transferType = TransferType.INITIATIVE
}
} else {
// 机器人会话
assignmentComponent.getBot(customerDispatcherDto)
}
}
.flatMap {
// 进行会话关联
// 历史会话不进行双向关联
this
.map { cv ->
it.relatedId = cv.id
it.relatedType = RelatedType.FROM_HISTORY
it.visitRange = Duration.between(it.startTime, cv.endTime).toMillis()
it
}
}
// 如果分配到新客服也失败了,就返回空对象,后续直接分配到机器人
.onErrorResume { Mono.empty() }
}
}
} | 1 | Kotlin | 18 | 42 | 217b4658508763133e1a5b6a96763a14e9f6f4ad | 9,669 | contact-center | Apache License 2.0 |
app/src/main/java/edu/arimanius/letsqueeze/ui/setting/SettingViewModelFactory.kt | arimanius | 581,500,511 | false | {"Kotlin": 95551} | package edu.arimanius.letsqueeze.ui.setting
import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import edu.arimanius.letsqueeze.data.LetsQueezeDatabase
import edu.arimanius.letsqueeze.data.repository.SettingRepository
/**
* ViewModel provider factory to instantiate LoginViewModel.
* Required given LoginViewModel has a non-empty constructor
*/
class SettingViewModelFactory(private val context: Context) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(SettingViewModel::class.java)) {
return SettingViewModel(
settingRepository = SettingRepository(
LetsQueezeDatabase.getInstance(context).settingDao(),
LetsQueezeDatabase.getInstance(context).categoryDao(),
)
) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
| 0 | Kotlin | 0 | 0 | 392c48c1e2feb497fc3f33921be4c6affb93a67c | 1,034 | letsqueeze | MIT License |
app/src/main/java/br/com/mauker/githubapp/ghrepositories/service/GhRepositoriesService.kt | Mauker1 | 601,832,597 | false | null | package br.com.mauker.githubapp.ghrepositories.service
import br.com.mauker.githubapp.ACCEPT_JSON_GH_V3
import br.com.mauker.githubapp.DEFAULT_ITEMS_PER_PAGE
import br.com.mauker.githubapp.HEADER_ACCEPT
import br.com.mauker.githubapp.STARTING_PAGE_INDEX
import br.com.mauker.githubapp.ghrepositories.domain.entity.GhRepoResponse
import retrofit2.http.GET
import retrofit2.http.Header
import retrofit2.http.Query
interface GhRepositoriesService {
@GET(PATH_REPOSITORIES)
suspend fun getRepositories(
@Header(HEADER_ACCEPT) accept: String = ACCEPT_JSON_GH_V3,
@Query(PARAM_QUERY) query: String,
@Query(PARAM_PAGE) page: Int = STARTING_PAGE_INDEX,
@Query(PARAM_PER_PAGE) perPage: Int = DEFAULT_ITEMS_PER_PAGE,
): GhRepoResponse
companion object {
private const val PATH_REPOSITORIES = "search/repositories"
private const val PARAM_QUERY = "q"
private const val PARAM_PER_PAGE = "per_page"
private const val PARAM_PAGE = "page"
}
} | 0 | Kotlin | 0 | 0 | 2705433ec5de89681ef3715bbbbf4361b9de160b | 1,015 | GithubRepoApp | MIT License |
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/DisableFormatting.kt | Danilo-Araujo-Silva | 271,904,885 | false | null | package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/**
*````
*
* Name: DisableFormatting
*
* Full name: System`DisableFormatting
*
* Usage: DisableFormatting[expr] is a form that disables the formatting of expr when it appears inside held expressions, but gives expr as soon as evaluation occurs.
*
* Options: None
*
* Protected
* Attributes: ReadProtected
*
* local: paclet:ref/DisableFormatting
* Documentation: web: http://reference.wolfram.com/language/ref/DisableFormatting.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun disableFormatting(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("DisableFormatting", arguments.toMutableList(), options)
}
| 2 | Kotlin | 0 | 3 | 4fcf68af14f55b8634132d34f61dae8bb2ee2942 | 1,116 | mathemagika | Apache License 2.0 |
src/main/kotlin/com/kuvaszuptime/kuvasz/services/SMTPMailer.kt | kuvasz-uptime | 280,438,796 | false | null | package com.kuvaszuptime.kuvasz.services
import com.kuvaszuptime.kuvasz.config.SMTPMailerConfig
import jakarta.inject.Singleton
import org.simplejavamail.api.email.Email
import org.simplejavamail.mailer.MailerBuilder
import org.slf4j.LoggerFactory
import java.util.concurrent.CompletableFuture
@Singleton
class SMTPMailer(smtpMailerConfig: SMTPMailerConfig) {
companion object {
private val logger = LoggerFactory.getLogger(SMTPMailer::class.java)
}
private val mailerClient =
MailerBuilder
.withTransportStrategy(smtpMailerConfig.transportStrategy.toJavaMailerTransportStrategy())
.withSMTPServerHost(smtpMailerConfig.host)
.withSMTPServerPort(smtpMailerConfig.port)
.async()
.apply {
if (!smtpMailerConfig.username.isNullOrBlank() && !smtpMailerConfig.password.isNullOrBlank()) {
withSMTPServerUsername(smtpMailerConfig.username)
.withSMTPServerPassword(smtpMailerConfig.password)
}
}.buildMailer()
init {
@Suppress("TooGenericExceptionCaught")
try {
mailerClient.testConnection()
logger.info("SMTP connection to ${smtpMailerConfig.host} has been set up successfully")
} catch (e: Throwable) {
logger.error("Connection to ${smtpMailerConfig.host} cannot be set up")
throw e
}
}
fun sendAsync(email: Email): CompletableFuture<Void> = mailerClient.sendMail(email, true)
}
| 5 | null | 9 | 40 | 6c3164110c25d2ead36199617541c1cfba79b402 | 1,546 | kuvasz | Apache License 2.0 |
src/main/kotlin/ua/kurinnyi/jaxrs/auto/mock/MockNotFoundException.kt | Kurinnyi | 153,566,842 | false | null | package ua.kurinnyi.jaxrs.auto.mock
import java.lang.RuntimeException
class MockNotFoundException(override val message:String) : RuntimeException() | 0 | Kotlin | 1 | 5 | a100b58f2092fc2dd57a474e644706d24681c11f | 149 | Jax-Rs-Auto-Mock | MIT License |
idea/testData/quickfix/typeOfAnnotationMember/star.kt | NickyXiao | 94,400,084 | true | {"Java": 23451398, "Kotlin": 23101223, "JavaScript": 137649, "Protocol Buffer": 57064, "HTML": 51139, "Lex": 18174, "Groovy": 14228, "ANTLR": 9797, "IDL": 8057, "Shell": 5883, "CSS": 4679, "Batchfile": 4437} | // "Replace array of boxed with array of primitive" "false"
// ERROR: Invalid type of annotation member
annotation class SuperAnnotation(
val foo: <caret>Array<*>,
val str: Array<String>
) | 0 | Java | 0 | 1 | a2427c64a10e4229c06fef1b4446fa8d6bd5f2cf | 204 | kotlin | Apache License 2.0 |
XDPapp/src/main/java/com/spread/xdpartner/network/legacy/Jsouper.kt | SpreadZhao | 715,187,997 | false | {"Kotlin": 43616} | package com.spread.xdpartner.network.legacy
import com.spread.xdpartner.network.NetworkConstant
import com.spread.xdpartner.network.NetworkConstant.PERMANENT_TOKEN
import org.jsoup.Connection
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import java.lang.StringBuilder
object Jsouper {
fun login(stuId: String, password: String): String {
val doc = Jsoup.connect("${NetworkConstant.BASE_URL}wz/user/login?stuId=${stuId}&password=${password}&vcode=")
.defaultPost()
return doc.body().toString()
}
fun getLatestThread(current: Int): String {
val doc = Jsoup.connect("${NetworkConstant.BASE_URL}wz/blog/queryNewestBlog")
.data("current", current.toString())
.header("token", PERMANENT_TOKEN)
.defaultGet()
return doc.body().toString()
}
fun getHotestThread(current: Int): String {
val doc = Jsoup.connect("${NetworkConstant.BASE_URL}wz/blog/queryHottestBlog")
.data("current", current.toString())
.header("token", PERMANENT_TOKEN)
.defaultGet()
return doc.body().toString()
}
fun queryThreadById(id: Int): String {
val doc = Jsoup.connect("${NetworkConstant.BASE_URL}wz/blog/query/${id}")
.header("token", PERMANENT_TOKEN)
.defaultGet()
return doc.body().toString()
}
private fun Document.parse() = StringBuilder().run {
toString()
}
private fun Connection.addDefaultHeader() = apply {
this.header("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
}
private fun Connection.defaultSettings() = apply {
this.ignoreContentType(true)
this.ignoreHttpErrors(true)
}
private fun Connection.defaultPost() = let {
it.addDefaultHeader().defaultSettings().post()
}
private fun Connection.defaultGet() = let {
it.addDefaultHeader().defaultSettings().get()
}
} | 1 | Kotlin | 0 | 1 | 8c04e25fd34dfd9b254504ee8cb27b0b29cb5131 | 1,813 | XDPartner | Apache License 2.0 |
src/main/kotlin/org/mvnsearch/plugins/wit/ide/icons/WitIcons.kt | linux-china | 602,892,689 | false | null | package org.mvnsearch.plugins.wit.ide.icons
import com.intellij.openapi.util.IconLoader
object WitIcons {
val WASM = IconLoader.findIcon("/icons/wasm.svg", WitIcons::class.java.classLoader)!!
} | 1 | Kotlin | 0 | 4 | 748538c795cba8a382b47597dd5000ed1ee12ea5 | 199 | wit-jetbrains-plugin | Apache License 2.0 |
pool-log-tracer/src/main/kotlin/io/github/shinglem/easyvertx/logtracer/Util.kt | Shinglem | 407,472,712 | false | null | package io.github.shinglem.easyvertx.logtracer
import io.vertx.sqlclient.Tuple
fun Tuple.logString(): String {
val sb = StringBuilder()
sb.append("[")
val size = size()
for (i in 0 until size) {
sb.append(getValue(i)?.let {
val str = it.toString()
if (str.length > 20) {
str.substring(0..19)+" ... "
}else{
str
}
})
if (i + 1 < size) sb.append(",")
}
sb.append("]")
return sb.toString()
}
| 0 | Kotlin | 0 | 0 | 4b12f560ff30c1f141e295077ab326cea3a52eac | 523 | easy-vertx-project | MIT License |
plugins/kotlin/idea/tests/testData/multiModuleQuickFix/actualAnnotationsNotMatchExpect/copyToActualPrimaryConstructor/jvm/jvm.kt | JetBrains | 2,489,216 | false | null | // "Copy mismatched annotation 'Ann' from expect to actual declaration (may change semantics)" "true"
// DISABLE-ERRORS
// FIR_COMPARISON
actual class Foo actual constructor<caret>()
| 249 | null | 5023 | 15,928 | 9ba394021dc73a3926f13d6d6cdf434f9ee7046d | 184 | intellij-community | Apache License 2.0 |
ui/ui-test/src/androidMain/kotlin/androidx/ui/test/AndroidComposeTestRule.kt | flyfire | 292,134,455 | false | null | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.ui.test
import androidx.activity.ComponentActivity
import androidx.ui.test.android.AndroidOwnerRegistry
import androidx.ui.test.android.FirstDrawRegistry
import androidx.ui.test.android.registerComposeWithEspresso
import androidx.ui.test.android.unregisterComposeFromEspresso
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Recomposer
import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.compose.animation.transitionsEnabled
import androidx.compose.ui.platform.setContent
import androidx.compose.foundation.InternalFoundationApi
import androidx.compose.foundation.blinkingCursorEnabled
import androidx.compose.ui.text.input.textInputServiceFactory
import androidx.compose.ui.unit.Density
import org.junit.runner.Description
import org.junit.runners.model.Statement
import androidx.compose.ui.unit.IntSize
import androidx.ui.test.android.createAndroidComposeRule
actual fun createComposeRule(
disableTransitions: Boolean,
disableBlinkingCursor: Boolean
): ComposeTestRule =
createAndroidComposeRule<ComponentActivity>(
disableTransitions,
disableBlinkingCursor
)
/**
* Android specific implementation of [ComposeTestRule].
*/
class AndroidComposeTestRule<T : ComponentActivity>(
// TODO(b/153623653): Remove activityRule from arguments when AndroidComposeTestRule can
// work with any kind of Activity launcher.
val activityRule: ActivityScenarioRule<T>,
private val disableTransitions: Boolean = false,
private val disableBlinkingCursor: Boolean = true
) : ComposeTestRule {
private fun getActivity(): T {
var activity: T? = null
if (activity == null) {
activityRule.scenario.onActivity { activity = it }
if (activity == null) {
throw IllegalStateException("Activity was not set in the ActivityScenarioRule!")
}
}
return activity!!
}
override val clockTestRule: AnimationClockTestRule = AndroidAnimationClockTestRule()
internal var disposeContentHook: (() -> Unit)? = null
override val density: Density get() =
Density(getActivity().resources.displayMetrics.density)
override val displaySize by lazy {
getActivity().resources.displayMetrics.let {
IntSize(it.widthPixels, it.heightPixels)
}
}
override fun apply(base: Statement, description: Description?): Statement {
val activityTestRuleStatement = activityRule.apply(base, description)
val composeTestRuleStatement = AndroidComposeStatement(activityTestRuleStatement)
return clockTestRule.apply(composeTestRuleStatement, description)
}
/**
* @throws IllegalStateException if called more than once per test.
*/
@SuppressWarnings("SyntheticAccessor")
override fun setContent(composable: @Composable () -> Unit) {
check(disposeContentHook == null) {
"Cannot call setContent twice per test!"
}
lateinit var activity: T
activityRule.scenario.onActivity { activity = it }
runOnUiThread {
val composition = activity.setContent(
Recomposer.current(),
composable
)
disposeContentHook = {
composition.dispose()
}
}
if (!isOnUiThread()) {
// Only wait for idleness if not on the UI thread. If we are on the UI thread, the
// caller clearly wants to keep tight control over execution order, so don't go
// executing future tasks on the main thread.
waitForIdle()
}
}
inner class AndroidComposeStatement(
private val base: Statement
) : Statement() {
override fun evaluate() {
val oldTextInputFactory = @Suppress("DEPRECATION_ERROR")(textInputServiceFactory)
beforeEvaluate()
try {
base.evaluate()
} finally {
afterEvaluate()
@Suppress("DEPRECATION_ERROR")
textInputServiceFactory = oldTextInputFactory
}
}
@OptIn(InternalFoundationApi::class)
private fun beforeEvaluate() {
transitionsEnabled = !disableTransitions
blinkingCursorEnabled = !disableBlinkingCursor
AndroidOwnerRegistry.setupRegistry()
FirstDrawRegistry.setupRegistry()
registerComposeWithEspresso()
@Suppress("DEPRECATION_ERROR")
textInputServiceFactory = {
TextInputServiceForTests(it)
}
}
@OptIn(InternalFoundationApi::class)
private fun afterEvaluate() {
transitionsEnabled = true
blinkingCursorEnabled = true
AndroidOwnerRegistry.tearDownRegistry()
FirstDrawRegistry.tearDownRegistry()
unregisterComposeFromEspresso()
// Dispose the content
if (disposeContentHook != null) {
runOnUiThread {
// NOTE: currently, calling dispose after an exception that happened during
// composition is not a safe call. Compose runtime should fix this, and then
// this call will be okay. At the moment, however, calling this could
// itself produce an exception which will then obscure the original
// exception. To fix this, we will just wrap this call in a try/catch of
// its own
try {
disposeContentHook!!()
} catch (e: Exception) {
// ignore
}
disposeContentHook = null
}
}
}
}
} | 1 | null | 1 | 1 | 03689fc69b6b352354ef5723e18e326922322f19 | 6,450 | androidx | Apache License 2.0 |
dino-third-party-integrations/dino-serialization-kotlinx/src/test/kotlin/org/ufoss/dino/serialization/kotlinx/JsonTestBase.kt | ufoss-org | 264,428,446 | false | null | /*
* Copyright 2023 UFOSS, Org. Use of this source code is governed by the Apache 2.0 license.
*
* Forked from kotlinx.serialization : json-okio module
* (https://github.com/Kotlin/kotlinx.serialization/tree/master/formats/json-okio), original copyright is below
*
* Copyright 2017-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package org.ufoss.dino.serialization.kotlinx
import kotlinx.serialization.*
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.internal.*
import kotlinx.serialization.modules.EmptySerializersModule
import kotlinx.serialization.modules.SerializersModule
import org.assertj.core.api.Assertions.assertThat
import org.ufoss.dino.buffer
@OptIn(ExperimentalSerializationApi::class)
abstract class JsonTestBase {
protected val default = Json { encodeDefaults = true }
internal inline fun <reified T : Any> Json.encodeToStringWithDino(value: T): String {
val serializer = serializersModule.serializer<T>()
return encodeToStringWithDino(serializer, value)
}
internal fun <T> Json.encodeToStringWithDino(
serializer: SerializationStrategy<T>,
value: T
): String {
val buffer = buffer()
encodeToBufferedSink(serializer, value, buffer)
return buffer.readUtf8()
}
internal inline fun <reified T : Any> Json.decodeFromStringWithDino(source: String): T {
val deserializer = serializersModule.serializer<T>()
return decodeFromStringWithDino(deserializer, source)
}
internal fun <T> Json.decodeFromStringWithDino(
deserializer: DeserializationStrategy<T>,
source: String,
): T {
val buffer = buffer()
buffer.writeUtf8(source)
return decodeFromBufferedSource(deserializer, buffer)
}
protected open fun parametrizedTest(test: () -> Unit) {
processResults(buildList {
add(runCatching { test() })
})
}
private inner class SwitchableJson(
val json: Json,
override val serializersModule: SerializersModule = EmptySerializersModule()
) : StringFormat {
override fun <T> encodeToString(serializer: SerializationStrategy<T>, value: T): String {
return json.encodeToStringWithDino(serializer, value)
}
override fun <T> decodeFromString(deserializer: DeserializationStrategy<T>, string: String): T {
return json.decodeFromStringWithDino(deserializer, string)
}
}
protected fun parametrizedTest(json: Json, test: StringFormat.() -> Unit) {
val dinoResult = runCatching { SwitchableJson(json).test() }
processResults(listOf(dinoResult))
}
protected fun processResults(results: List<Result<*>>) {
results.forEach { result ->
result.onFailure {
println("Failed test for Dino")
throw it
}
}
for (i in results.indices) {
for (j in results.indices) {
if (i == j) continue
assertThat(results[i].getOrNull()!!).isEqualTo(results[j].getOrNull())
}
}
}
/**
* Same as [assertStringFormAndRestored], but tests both json converters (streaming and tree)
* via [parametrizedTest]
*/
internal fun <T> assertJsonFormAndRestored(
serializer: KSerializer<T>,
data: T,
expected: String,
json: Json = default
) {
parametrizedTest {
val serialized = json.encodeToStringWithDino(serializer, data)
assertThat(serialized).isEqualTo(expected)
val deserialized: T = json.decodeFromStringWithDino(serializer, serialized)
assertThat(deserialized).isEqualTo(data)
}
}
/**
* Same as [assertStringFormAndRestored], but tests both json converters (streaming and tree)
* via [parametrizedTest]. Use custom checker for deserialized value.
*/
internal fun <T> assertJsonFormAndRestoredCustom(
serializer: KSerializer<T>,
data: T,
expected: String,
check: (T, T) -> Boolean
) {
parametrizedTest {
val serialized = Json.encodeToStringWithDino(serializer, data)
assertThat(serialized).isEqualTo(expected)
val deserialized: T = Json.decodeFromStringWithDino(serializer, serialized)
assertThat(
check(
data,
deserialized
)
).isTrue
}
}
}
| 14 | null | 1 | 9 | 3bf047f5b049ee75d49224363b8f45806d1228a2 | 4,574 | dino | Apache License 2.0 |
challenge/flutter/all_samples/widgets_interactiveviewer_builder_1/android/app/src/main/kotlin/com/example/widgets_interactiveviewer_builder_1/MainActivity.kt | davidzou | 5,868,257 | false | null | package com.example.widgets_interactiveviewer_builder_1
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 1 | null | 1 | 4 | 1060f6501c432510e164578d4af60a49cd5ed681 | 152 | WonderingWall | Apache License 2.0 |
android/app/src/main/java/com/epimorphics/android/myrivers/renderers/WIMSPointRenderer.kt | alessio-b-zak | 71,778,738 | false | null | package com.epimorphics.android.myrivers.renderers
import android.content.Context
import com.epimorphics.android.myrivers.R
import com.epimorphics.android.myrivers.data.WIMSPoint
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.MarkerOptions
import com.google.maps.android.clustering.ClusterManager
import com.google.maps.android.clustering.view.DefaultClusterRenderer
/**
* A renderer class for a WIMSPoint marker
*
* @param context Application context
* @param mMap GoogleMap
* @param clusterManager ClusterManager
*
* @see WIMSPoint
*/
class WIMSPointRenderer(context: Context, val mMap: GoogleMap, clusterManager: ClusterManager<WIMSPoint>) :
DefaultClusterRenderer<WIMSPoint>(context, mMap, clusterManager) {
/**
* Sets marker icon from resource drawable
*
* @param wimsPoint a DischargePermitPoint for which a marker icon is to be set
* @param markerOptions a MarkerOptions of a given wimsPoint
*/
override fun onBeforeClusterItemRendered(wimsPoint: WIMSPoint, markerOptions: MarkerOptions) {
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_wims_marker))
}
} | 0 | Kotlin | 0 | 0 | b07943da4dd6f4fdacb1d7751f1332e4fd97eb3f | 1,251 | myRivers | MIT License |
app/src/main/java/com/william/easykt/ui/RoundImageActivity.kt | WeiLianYang | 255,907,870 | false | {"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 2, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "INI": 1, "Proguard": 2, "Kotlin": 215, "XML": 118, "Java": 4, "Protocol Buffer": 1} | /*
* Copyright WeiLianYang
*
* 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.william.easykt.ui
import com.william.base_component.activity.BaseActivity
import com.william.base_component.extension.bindingView
import com.william.easykt.R
import com.william.easykt.databinding.ActivityRoundImageBinding
/**
* author:William
* date:2022/9/4 20:04
* description:Round Image
*/
class RoundImageActivity : BaseActivity() {
override val viewBinding: ActivityRoundImageBinding by bindingView()
override fun initAction() {
}
override fun initData() {
setTitleText(R.string.test_round_image)
}
} | 0 | Kotlin | 6 | 21 | 6e33d7c32945a261117a7de8f2a388a5187637c5 | 1,150 | EasyKotlin | Apache License 2.0 |
src/main/kotlin/gl8080/lifegame/logic/Position.kt | opengl-8080 | 56,601,458 | false | {"Gradle": 1, "Text": 1, "Ignore List": 1, "Markdown": 1, "Java": 8, "HTML": 1, "XML": 3, "CSS": 2, "JavaScript": 13, "SQL": 5, "Kotlin": 41} | package gl8080.lifegame.logic
import gl8080.lifegame.logic.exception.IllegalParameterException
import javax.persistence.Column
import javax.persistence.Embeddable
/**
* 位置を表すクラス。
* <p>
* このクラスは、縦横の座標によってオブジェクトを一意に識別します。<br>
* つまり、座標が同じ場所を指していれば、異なるインスタンスであっても {@link Position#equals(Object) equals()} メソッドは
* {@code true} を返します。
* <p>
* 座標値は、 {@code 0} オリジンです。
*/
@Embeddable
data class Position(
@Column(name="VERTICAL_POSITION")
private val vertical: Int,
@Column(name="HORIZONTAL_POSITION")
private val horizontal: Int
) {
init {
if (this.vertical < 0 || this.horizontal < 0) {
throw IllegalParameterException("座標にマイナスは指定できません (${this.vertical}, ${this.horizontal})")
}
}
/**
* この位置に隣接する、周囲8つの位置をリストで取得します。
* <p>
* 隣接する座標がマイナスになる場合、その座標を指す位置はリストから除外されます。
*
* @return この位置に隣接する周囲8つの位置オブジェクト
*/
fun getNeighborPositions(): List<Position> {
val neighbors = mutableListOf<Position>()
for (v in (this.vertical - 1)..(this.vertical + 1)) {
for (h in (this.horizontal - 1)..(this.horizontal + 1)) {
if ((0 <= v && 0 <= h) && !(this.vertical==v && this.horizontal==h)) {
neighbors.add(Position(v, h))
}
}
}
return neighbors
}
@Deprecated(message = "JPA用", level = DeprecationLevel.ERROR)
private constructor(): this(Int.MAX_VALUE, Int.MAX_VALUE)
}
| 0 | JavaScript | 0 | 0 | 67e67fce82619ceab507d3288375233130441910 | 1,468 | kotlin-lifegame | MIT License |
realm/realm-library/src/androidTestObjectServer/kotlin/io/realm/entities/DummySyncObject.kt | realm | 4,084,908 | false | {"Gradle": 38, "Git Config": 1, "Markdown": 11, "Dockerfile": 2, "INI": 18, "Shell": 22, "Text": 5, "Ignore List": 4, "Batchfile": 8, "Groovy": 2, "Java Properties": 5, "XML": 146, "Proguard": 8, "HTML": 1, "Java": 676, "Kotlin": 212, "C++": 88, "CMake": 1, "YAML": 13, "JSON": 60, "Python": 1, "JavaScript": 14, "SVG": 2} | /**
* Copyright 2022 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.realm.entities
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
import org.bson.types.ObjectId
import java.util.*
open class DummySyncObject: RealmObject() {
@PrimaryKey
var _id: ObjectId? = ObjectId.get()
var string: String = UUID.randomUUID().toString()
}
| 400 | Java | 1747 | 11,450 | e564a45fbeabb4710ac5fcd231c107642dd4aa83 | 892 | realm-java | Apache License 2.0 |
compiler/light-classes/src/org/jetbrains/kotlin/asJava/classes/ultraLightClassForScript.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.asJava.classes
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiModifier
import com.intellij.psi.PsiType
import com.intellij.psi.impl.java.stubs.PsiJavaFileStub
import com.intellij.psi.impl.light.LightMethodBuilder
import com.intellij.psi.util.CachedValue
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import org.jetbrains.kotlin.analyzer.KotlinModificationTrackerService
import org.jetbrains.kotlin.asJava.builder.LightClassData
import org.jetbrains.kotlin.asJava.builder.LightClassDataHolder
import org.jetbrains.kotlin.asJava.elements.KtLightField
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtScript
class KtUltraLightClassForScript(
script: KtScript,
private val support: KtUltraLightSupport,
) : KtLightClassForScript(script) {
override val clsDelegate: PsiClass get() = invalidAccess()
override val lightClassData: LightClassData get() = invalidAccess()
override fun getLightClassDataHolder(): LightClassDataHolder.ForScript = invalidAccess()
override val javaFileStub: PsiJavaFileStub? = null
private val membersBuilder by lazyPub {
UltraLightMembersCreator(
containingClass = this,
containingClassIsNamedObject = false,
containingClassIsSealed = true,
mangleInternalFunctions = true,
support = support,
)
}
internal inner class KtUltraLightScriptMainParameter(mainMethod: KtUltraLightMethod) :
KtUltraLightParameter(
name = "args",
kotlinOrigin = null,
support = support,
ultraLightMethod = mainMethod
) {
override fun getType(): PsiType =
PsiType.getJavaLangString(manager, resolveScope).createArrayType()
override fun isVarArgs(): Boolean = false
override val qualifiedNameForNullabilityAnnotation: String? = null
}
private fun MutableList<KtLightMethod>.addScriptDefaultMethods() {
val defaultConstructor = KtUltraLightMethodForSourceDeclaration(
delegate = LightMethodBuilder(manager, language, name).setConstructor(true).addModifier(PsiModifier.PUBLIC),
declaration = script,
support = support,
containingClass = this@KtUltraLightClassForScript,
methodIndex = METHOD_INDEX_FOR_DEFAULT_CTOR,
)
add(defaultConstructor)
val methodBuilder = LightMethodBuilder(manager, language, "main").apply {
isConstructor = false
addModifiers(PsiModifier.PUBLIC, PsiModifier.STATIC, PsiModifier.FINAL)
setMethodReturnType(PsiType.VOID)
}
val mainMethod = KtUltraLightMethodForSourceDeclaration(
delegate = methodBuilder,
declaration = script,
support = support,
containingClass = this@KtUltraLightClassForScript,
methodIndex = METHOD_INDEX_FOR_SCRIPT_MAIN,
)
methodBuilder.addParameter(KtUltraLightScriptMainParameter(mainMethod))
add(mainMethod)
}
private fun ownMethods(): List<KtLightMethod> {
val result = mutableListOf<KtLightMethod>()
result.addScriptDefaultMethods()
for (declaration in script.declarations.filterNot { it.isHiddenByDeprecation(support) }) {
when (declaration) {
is KtNamedFunction -> result.addAll(membersBuilder.createMethods(declaration, forceStatic = false))
is KtProperty -> result.addAll(
membersBuilder.propertyAccessors(declaration, declaration.isVar, forceStatic = false, onlyJvmStatic = false),
)
}
}
return result
}
private val _ownMethods: CachedValue<List<KtLightMethod>> = CachedValuesManager.getManager(project).createCachedValue(
{
CachedValueProvider.Result.create(
ownMethods(),
KotlinModificationTrackerService.getInstance(project).outOfBlockModificationTracker,
)
},
false,
)
override fun getOwnMethods(): List<KtLightMethod> = _ownMethods.value
private val _ownFields: List<KtLightField> by lazyPub {
val result = arrayListOf<KtLightField>()
val usedNames = hashSetOf<String>()
for (property in script.declarations.filterIsInstance<KtProperty>()) {
membersBuilder
.createPropertyField(property, usedNames, forceStatic = false)
?.let(result::add)
}
result
}
override fun getOwnFields(): List<KtLightField> = _ownFields
override fun copy(): KtLightClassForScript = KtUltraLightClassForScript(script, support)
} | 132 | Kotlin | 5074 | 40,992 | 57fe6721e3afb154571eb36812fd8ef7ec9d2026 | 5,098 | kotlin | Apache License 2.0 |
tiles-layout-anko/src/androidTest/kotlin/it/czerwinski/android/view/layout/tiles/anko/AnkoTilesLayoutHVPaddingTest.kt | sczerwinski | 93,967,789 | false | null | package it.czerwinski.android.view.layout.tiles.anko
import android.app.Activity
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.matcher.ViewMatchers.*
import android.support.test.filters.LargeTest
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import it.czerwinski.android.view.layout.tiles.TilesLayout
import org.hamcrest.Matchers.*
import org.jetbrains.anko.dip
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class AnkoTilesLayoutHVPaddingTest {
@Rule
@JvmField
val testRule = ActivityTestRule<AnkoTilesHVPaddingActivity>(AnkoTilesHVPaddingActivity::class.java)
private val activity: Activity
get() = testRule.activity
private val horizontalPadding: Int
get() = activity.dip(8)
private val verticalPadding: Int
get() = activity.dip(16)
@Test
@Throws(Exception::class)
fun layoutShouldBeProperlyInitialized() {
onView(withClassName(containsString(TilesLayout::class.java.simpleName)))
.check { view, _ ->
val layout = view as TilesLayout
assertThat("layout left padding", layout.paddingLeft, equalTo(horizontalPadding))
assertThat("layout right padding", layout.paddingRight, equalTo(horizontalPadding))
assertThat("layout top padding", layout.paddingTop, equalTo(verticalPadding))
assertThat("layout bottom padding", layout.paddingBottom, equalTo(verticalPadding))
assertThat("layout inner horizontal padding", layout.innerHorizontalPadding, equalTo(horizontalPadding))
assertThat("layout inner vertical padding", layout.innerVerticalPadding, equalTo(verticalPadding))
}
}
}
| 1 | Kotlin | 1 | 1 | 55045746820be812da884f4c029efda0d9a686f3 | 1,711 | android-tiles-layout | Apache License 2.0 |
user-management/keycloak-gateway/src/main/kotlin/co/nilin/opex/auth/gateway/extension/UserProfileResourceFactory.kt | opexdev | 370,411,517 | false | {"Kotlin": 1303016, "HTML": 43145, "Shell": 8309, "Java": 8001, "PLpgSQL": 3351, "Dockerfile": 3334, "HCL": 823} | package co.nilin.opex.auth.gateway.extension
import org.keycloak.Config
import org.keycloak.models.KeycloakSession
import org.keycloak.models.KeycloakSessionFactory
import org.keycloak.services.resource.RealmResourceProvider
import org.keycloak.services.resource.RealmResourceProviderFactory
class UserProfileResourceFactory : RealmResourceProviderFactory {
override fun create(session: KeycloakSession): RealmResourceProvider {
return UserProfileResource(session)
}
override fun init(config: Config.Scope?) {
}
override fun postInit(factory: KeycloakSessionFactory?) {
}
override fun close() {
}
override fun getId(): String {
return "user-profile"
}
} | 29 | Kotlin | 22 | 51 | fedf3be46ee7fb85ca7177ae91b13dbc6f2e8a73 | 719 | core | MIT License |
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/navigation/AbstractGotoDeclarationTest.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.navigation
abstract class AbstractGotoDeclarationTest : AbstractGotoActionTest() {
override val actionName: String get() = "GotoDeclaration"
}
| 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 342 | intellij-community | Apache License 2.0 |
app/src/main/java/com/example/androidutils/fragment/lab/AudioFocusFragment.kt | ZhangXinmin528 | 117,549,346 | false | {"Java": 728866, "Kotlin": 166497} | package com.example.androidutils.fragment.lab
import android.annotation.SuppressLint
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import com.coding.zxm.annotation.Function
import com.coding.zxm.annotation.Group
import com.coding.zxm.lib_core.base.BaseFragment
import com.example.androidutils.R
import com.example.androidutils.databinding.FragmentAudioFocusBinding
import com.zxm.utils.core.audiofocus.AudioFocusHelper
import com.zxm.utils.core.audiofocus.OnAudioFocusChangedCallback
/**
* Created by zhangxinmin on 2023/12/13.
*/
@SuppressLint("NonConstantResourceId")
@Function(group = Group.Lab, funcName = "音频焦点", funcIconRes = R.mipmap.icon_audio_focus)
class AudioFocusFragment : BaseFragment(), OnClickListener, OnAudioFocusChangedCallback {
private lateinit var binding: FragmentAudioFocusBinding
private lateinit var audioFocusHelper: AudioFocusHelper
override fun setLayoutId(inflater: LayoutInflater, container: ViewGroup?): View {
binding = FragmentAudioFocusBinding.inflate(layoutInflater, container, false)
return binding.root
}
override fun initParamsAndValues() {
binding.layoutTitle.tvToolbarTitle.text = "音频焦点"
binding.layoutTitle.ivToolbarBack.setOnClickListener(this)
if (!::audioFocusHelper.isInitialized)
audioFocusHelper = mContext?.let { AudioFocusHelper(it) } ?: return
//设置回调
audioFocusHelper.setOnAudioFocusChangedCallback(this)
binding.btnRequstFocus.setOnClickListener(this)
binding.btnAbondonFocus.setOnClickListener(this)
binding.btnStartMusic.setOnClickListener(this)
binding.btnStopMusic.setOnClickListener(this)
}
override fun onClick(v: View?) {
when (v?.id) {
R.id.iv_toolbar_back -> {
popBackStack()
}
R.id.btn_requst_focus -> {
audioFocusHelper.changeAudioFocus(
true
)
}
R.id.btn_abondon_focus -> {
audioFocusHelper.changeAudioFocus(false)
}
R.id.btn_start_music -> {
}
R.id.btn_stop_music -> {
}
}
}
override fun onAudioFocusLoss() {
Log.d(sTAG, "${sTAG}..onAudioFocusLoss()~")
binding.tvAudioFocusResult.text = "音频焦点:失去"
}
override fun onAudioFocusLossTransient() {
Log.d(sTAG, "${sTAG}..onAudioFocusLossTransient()~")
binding.tvAudioFocusResult.text = "音频焦点:失去"
}
override fun onAudioFocusLossTransientCanDuck() {
Log.d(sTAG, "${sTAG}..onAudioFocusLossTransientCanDuck()~")
binding.tvAudioFocusResult.text = "音频焦点:失去"
}
override fun onAudioFocusGain() {
Log.d(sTAG, "${sTAG}..onAudioFocusGain()~")
binding.tvAudioFocusResult.text = "音频焦点:获取"
}
} | 0 | Java | 1 | 5 | 6b49ab3ada9691543aa85e0fecf091f93b910e47 | 2,966 | AndroidUtils | Apache License 2.0 |
app/src/main/java/com/dede/android_eggs/util/Views.kt | hushenghao | 306,645,388 | false | {"Java": 532422, "Kotlin": 466397, "Python": 8564, "Ruby": 2933} | package com.dede.android_eggs.util
import android.content.Context
import android.content.res.Resources
import android.util.LayoutDirection
import android.view.View
import androidx.core.view.ViewCompat
val systemIsRtl: Boolean
get() = Resources.getSystem().configuration.layoutDirection == LayoutDirection.RTL
val Context.isRtl: Boolean
get() = resources.configuration.layoutDirection == LayoutDirection.RTL
val View.isRtl: Boolean
get() = context.isRtl
// get() = ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL | 1 | Kotlin | 24 | 456 | a7bc8846e86fb8d78681b9168b05c27457951678 | 553 | AndroidEasterEggs | Apache License 2.0 |
android/beagle/src/test/java/br/com/zup/beagle/android/context/tokenizer/function/builtin/array/OperationsTest.kt | tyagi2141 | 295,206,658 | true | {"Kotlin": 1729548, "Swift": 975230, "C++": 262909, "Objective-C": 59574, "Ruby": 26910, "Java": 26583, "Shell": 6216, "Dart": 3253, "sed": 1618, "HTML": 1322, "C": 1109} | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package br.com.zup.beagle.android.context.tokenizer.function.builtin.array
import br.com.zup.beagle.android.context.tokenizer.function.builtin.comparison.*
import br.com.zup.beagle.android.context.tokenizer.function.builtin.logic.AndFunction
import br.com.zup.beagle.android.context.tokenizer.function.builtin.logic.ConditionFunction
import br.com.zup.beagle.android.context.tokenizer.function.builtin.logic.NotFunction
import br.com.zup.beagle.android.context.tokenizer.function.builtin.logic.OrFunction
import br.com.zup.beagle.android.context.tokenizer.function.builtin.number.DivideFunction
import br.com.zup.beagle.android.context.tokenizer.function.builtin.number.MultiplyFunction
import br.com.zup.beagle.android.context.tokenizer.function.builtin.number.SubtractFunction
import br.com.zup.beagle.android.context.tokenizer.function.builtin.number.SumFunction
import br.com.zup.beagle.android.context.tokenizer.function.builtin.other.IsEmptyFunction
import br.com.zup.beagle.android.context.tokenizer.function.builtin.other.LengthFunction
import br.com.zup.beagle.android.context.tokenizer.function.builtin.string.*
import org.json.JSONArray
import org.junit.Test
import org.junit.Assert.*
import kotlin.test.assertFails
class OperationsTest {
// Array
@Test
fun insert_should_insert_element() {
val insert = InsertFunction()
assertEquals(listOf(9, 1, 2, 3), insert.execute(listOf(1, 2, 3), 9, 0))
assertEquals(listOf(1, 2, 3, 9), insert.execute(listOf(1, 2, 3), 9))
assertEquals(jsonArrayOf(9, 1, 2, 3).toString(), insert.execute(jsonArrayOf(1, 2, 3), 9, 0).toString())
assertEquals(jsonArrayOf(1, 2, 3, 9).toString(), insert.execute(jsonArrayOf(1, 2, 3), 9).toString())
}
@Test
fun contains_should_check_if_contains_element() {
val contains = ContainsFunction()
assertTrue(contains.execute(listOf(1, 2, 3), 2))
assertFalse(contains.execute(listOf(1, 2, 3), 4))
assertTrue(contains.execute(jsonArrayOf(1, 2, 3), 2))
assertFalse(contains.execute(jsonArrayOf(1, 2, 3), 4))
}
@Test
fun remove_should_remove_all_elements() {
val remove = RemoveFunction()
assertEquals(listOf(1, 3), remove.execute(listOf(1, 2, 3, 2), 2))
assertEquals(jsonArrayOf(1, 3).toString(), remove.execute(jsonArrayOf(1, 2, 3, 2), 2).toString())
}
@Test
fun removeIndex_should_remove_element_at_index() {
val removeIndex = RemoveIndexFunction()
assertEquals(listOf(2, 3), removeIndex.execute(listOf(1, 2, 3), 0))
assertEquals(jsonArrayOf(2, 3).toString(), removeIndex.execute(jsonArrayOf(1, 2, 3), 0).toString())
}
// Comparison
@Test
fun eq_should_compare_two_values() {
val eq = EqFunction()
assertTrue(eq.execute(1.0, 1.0))
assertFalse(eq.execute(2.0, 1.0))
assertTrue(eq.execute(1, 1))
assertFalse(eq.execute(2, 1))
assertTrue(eq.execute("a", "a"))
assertFalse(eq.execute("a", "b"))
assertTrue(eq.execute(listOf(1), listOf(1)))
assertFails { eq.execute() }
}
@Test
fun gte_should_check_if_two_numbers_is_greater_or_equals() {
val gte = GteFunction()
assertTrue(gte.execute(1.0, 1.0))
assertFalse(gte.execute(1.0, 2.0))
assertTrue(gte.execute(2.0, 1.0))
assertTrue(gte.execute(1, 1))
assertFalse(gte.execute(1, 2))
assertTrue(gte.execute(2, 1))
assertFails { gte.execute() }
}
@Test
fun gt_should_check_if_two_numbers_is_greater_than_other() {
val gt = GtFunction()
assertFalse(gt.execute(1.0, 1.0))
assertFalse(gt.execute(1.0, 2.0))
assertTrue(gt.execute(2.0, 1.0))
assertFalse(gt.execute(1, 1))
assertFalse(gt.execute(1, 2))
assertTrue(gt.execute(2, 1))
assertFails { gt.execute() }
}
@Test
fun lte_should_check_if_two_numbers_is_less_than_or_equals_than() {
val lte = LteFunction()
assertTrue(lte.execute(1.0, 1.0))
assertTrue(lte.execute(1.0, 2.0))
assertFalse(lte.execute(2.0, 1.0))
assertTrue(lte.execute(1, 1))
assertTrue(lte.execute(1, 2))
assertFalse(lte.execute(2, 1))
assertFails { lte.execute() }
}
@Test
fun lt_should_check_if_two_numbers_is_less_than_other_number() {
val lt = LtFunction()
assertFalse(lt.execute(1.0, 1.0))
assertTrue(lt.execute(1.0, 2.0))
assertFalse(lt.execute(2.0, 1.0))
assertFalse(lt.execute(1, 1))
assertTrue(lt.execute(1, 2))
assertFalse(lt.execute(2, 1))
assertFails { lt.execute() }
}
// Logic
@Test
fun and_should_be_true_if_all_params_is_true() {
val and = AndFunction()
assertTrue(and.execute(true))
assertTrue(and.execute(true, true, true))
assertFalse(and.execute(true, false, true))
assertFails { and.execute() }
}
@Test
fun or_should_be_true_if_one_param_is_true() {
val or = OrFunction()
assertTrue(or.execute(true))
assertFalse(or.execute(false))
assertTrue(or.execute(true, true, true))
assertTrue(or.execute(false, true, false))
assertTrue(or.execute(true, false, false))
assertTrue(or.execute(false, false, true))
assertFalse(or.execute(false, false, false))
}
@Test
fun condition_should_return_true_or_false_condition() {
val conditionFunction = ConditionFunction()
assertEquals("is true", conditionFunction.execute(true, "is true", "is false"))
assertEquals("is false", conditionFunction.execute(false, "is true", "is false"))
}
@Test
fun not_should_invert_boolean_parameter() {
val not = NotFunction()
assertFalse(not.execute(true))
assertTrue(not.execute(false))
}
// Number
@Test
fun divide_should_divide_two_numbers() {
val divide = DivideFunction()
assertEquals(1.0, divide.execute(2.0, 2.0))
assertEquals(1, divide.execute(2, 2))
assertFails { divide.execute() }
}
@Test
fun multiply_should_divide_two_numbers() {
val multiply = MultiplyFunction()
assertEquals(4.0, multiply.execute(2.0, 2.0))
assertEquals(4, multiply.execute(2, 2))
assertFails { multiply.execute() }
}
@Test
fun subtract_should_divide_two_numbers() {
val subtract = SubtractFunction()
assertEquals(0.0, subtract.execute(2.0, 2.0))
assertEquals(0, subtract.execute(2, 2))
assertFails { subtract.execute() }
}
@Test
fun sum_should_divide_two_numbers() {
val sum = SumFunction()
assertEquals(4.0, sum.execute(2.0, 2.0))
assertEquals(4, sum.execute(2, 2))
assertFails { sum.execute() }
}
// Other
@Test
fun isEmpty_should_check_if_values_is_empty() {
val isEmpty = IsEmptyFunction()
assertTrue(isEmpty.execute(""))
assertFalse(isEmpty.execute(" "))
assertTrue(isEmpty.execute(emptyList<Int>()))
assertFalse(isEmpty.execute(listOf(1)))
assertTrue(isEmpty.execute(emptyMap<String, String>()))
assertFalse(isEmpty.execute(mapOf("" to "")))
assertTrue(isEmpty.execute(null))
assertFails { isEmpty.execute() }
}
@Test
fun length_should_check_return_value_length() {
val length = LengthFunction()
assertEquals(0, length.execute(""))
assertEquals(1, length.execute(" "))
assertEquals(0, length.execute(emptyList<Int>()))
assertEquals(1, length.execute(listOf(1)))
assertEquals(0, length.execute(emptyMap<String, String>()))
assertEquals(1, length.execute(mapOf("" to "")))
assertEquals(0, length.execute(null))
}
@Test
fun isNull_should_check_if_values_is_null() {
assertTrue(IsEmptyFunction().execute(null))
}
// String
@Test
fun capitalize_should_capitalize_first_character() {
val capitalize = CapitalizeFunction()
assertEquals("Aaa", capitalize.execute("aaa"))
assertEquals("AAA", capitalize.execute("AAA"))
assertEquals("AaA", capitalize.execute("aaA"))
}
@Test
fun concat_should_concatenate_all_parameters() {
val concat = ConcatFunction()
assertEquals("aabbcc", concat.execute("aa", "bb", "cc"))
assertEquals("", concat.execute("", ""))
}
@Test
fun lowercase_should_return_string_lowered() {
assertEquals("aa", LowercaseFunction().execute("AA"))
}
@Test
fun uppercase_should_return_string_upped() {
assertEquals("AA", UppercaseFunction().execute("aa"))
}
@Test
fun substr_should_return_sub_string() {
val substr = SubstrFunction()
val str = "123456789"
assertEquals("", substr.execute(str, 5, 0))
assertEquals("12345", substr.execute(str, 0, 5))
assertEquals("456", substr.execute(str, 3, 3))
assertEquals("6789", substr.execute(str, 5))
}
private fun jsonArrayOf(vararg items: Int): JSONArray {
return JSONArray().apply {
items.forEach {
put(it)
}
}
}
} | 0 | null | 0 | 1 | d64c69511dbf7c8f6198ed14cc07c1fa15bf080e | 9,921 | beagle | Apache License 2.0 |
src/org/elixir_lang/debugger/node/handle_cast/BreakpointReached.kt | KronicDeth | 22,329,177 | false | {"Kotlin": 2461440, "Elixir": 2165417, "Java": 1582388, "Euphoria": 151683, "Lex": 69822, "HTML": 22466, "Makefile": 499} | /*
* Copyright 2012-2014 <NAME>
* Copyright 2017 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.elixir_lang.debugger.node.handle_cast
import com.ericsson.otp.erlang.*
import org.elixir_lang.Clause
import org.elixir_lang.debugger.Node
import org.elixir_lang.debugger.node.ProcessSnapshot
import org.elixir_lang.debugger.node.event.Listener
class BreakpointReached(private val node : Node, private val eventListener: Listener) : Clause {
override fun match(arguments: OtpErlangList): Match? {
assert(arguments.arity() == 1)
return arguments
.elementAt(0)
.let { it as? OtpErlangTuple }
?.let { tuple ->
if (tuple.arity() == 3) {
tuple
} else {
null
}
}
?.let { tuple ->
if (tuple.elementAt(0) == BREAKPOINT_REACHED && tuple.elementAt(1) is OtpErlangPid && tuple.elementAt(2) is OtpErlangList) {
val pid = tuple.elementAt(1) as? OtpErlangPid
val otpSnapshotWithStacks = tuple.elementAt(2) as? OtpErlangList
if (pid != null && otpSnapshotWithStacks != null) {
Match(pid, otpSnapshotWithStacks)
} else {
null
}
} else {
null
}
}
}
override fun run(match: org.elixir_lang.clause.Match): OtpErlangObject {
val breakpointReachedMatch = match as Match
val pid = breakpointReachedMatch.pid
val processSnapshotList = breakpointReachedMatch.snapshotsWithStacks.toProcessSnapshotList()
node.processSuspended(pid)
eventListener.breakpointReached(pid, processSnapshotList)
return OtpErlangAtom("ok")
}
inner class Match(val pid: OtpErlangPid, val snapshotsWithStacks: OtpErlangList) : org.elixir_lang.clause.Match
}
private val BREAKPOINT_REACHED = OtpErlangAtom("breakpoint_reached")
private fun OtpErlangList.toProcessSnapshotList(): List<ProcessSnapshot> =
withIndex().mapNotNull { indexedTerm->
ProcessSnapshot.from(indexedTerm)
}
| 590 | Kotlin | 153 | 1,815 | b698fdaec0ead565023bf4461d48734de135b604 | 2,839 | intellij-elixir | Apache License 2.0 |
app/src/main/java/com/github/vase4kin/teamcityapp/buildlist/tracker/BuildListTracker.kt | vase4kin | 68,111,887 | false | {"Gradle": 29, "JSON": 2, "Java Properties": 2, "Markdown": 6, "Shell": 1, "Ignore List": 26, "Batchfile": 1, "Text": 1, "YAML": 5, "INI": 24, "Proguard": 25, "XML": 228, "Java": 33, "Kotlin": 580, "HTML": 1, "Gradle Kotlin DSL": 1} | /*
* Copyright 2019 Andrey Tolpeev
*
* 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.github.vase4kin.teamcityapp.buildlist.tracker
import com.github.vase4kin.teamcityapp.base.tracker.ViewTracker
/**
* Tracking for build list
*/
interface BuildListTracker : ViewTracker {
/**
* Track run build button is pressed
*/
fun trackRunBuildButtonPressed()
/**
* Track user wants to see queued build details
*/
fun trackUserWantsToSeeQueuedBuildDetails()
companion object {
/**
* Build list screen name
*/
const val SCREEN_NAME_BUILD_LIST = "screen_build_list"
/**
* Snapshot dependencies
*/
const val SCREEN_NAME_SNAPSHOT_DEPENDECIES = "screen_snapshot_dependencies"
/**
* Event for run build button pressed
*/
const val EVENT_RUN_BUILD_BUTTON_PRESSED = "run_build_fab_click"
/**
* Event for show queued build details
*/
const val EVENT_SHOW_QUEUED_BUILD_DETAILS = "build_list_show_queued_details"
}
}
| 0 | Kotlin | 11 | 52 | 9abb1ed56c127d64679124c38d30b0014ec024de | 1,609 | TeamCityApp | Apache License 2.0 |
app/src/main/java/arcus/app/device/settings/fragment/NetworkSettingsFragment.kt | arcus-smart-home | 168,191,380 | false | null | /*
* Copyright 2019 Arcus Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package arcus.app.device.settings.fragment
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import arcus.app.R
import arcus.app.activities.PermissionsActivity
import arcus.app.common.fragments.BaseFragment
import arcus.app.common.image.IntentRequestCode
import arcus.app.common.popups.ScleraPopup
import arcus.app.device.more.ConnectedToWiFiSnackBar
import arcus.app.pairing.device.steps.bledevice.BlePairingStepsActivity
import arcus.presentation.device.settings.wifi.NetworkSettingsPresenterImpl
import arcus.presentation.device.settings.wifi.NetworkSettingsView
import arcus.presentation.device.settings.wifi.WiFiNetwork
class NetworkSettingsFragment : BaseFragment(), NetworkSettingsView {
private lateinit var networkName : TextView
private lateinit var signalStrength : ImageView
private val presenter = NetworkSettingsPresenterImpl()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
networkName = view.findViewById(R.id.network_name)
signalStrength = view.findViewById(R.id.signal_strength)
}
override fun onResume() {
super.onResume()
presenter.setView(this)
presenter.loadFromDeviceAddress(arguments?.getString(CAMERA_ADDRESS) ?: "")
setTitle()
}
override fun onPause() {
super.onPause()
presenter.clearView()
}
override fun getTitle(): String? {
return getString(R.string.setting_camera_net_and_wifi)
}
override fun getLayoutId(): Int? {
return R.layout.fragment_ble_camera_network
}
override fun onLoaded(network: WiFiNetwork) {
networkName.text = network.networkName
signalStrength.setImageResource(when (network.signalStrength) {
1 -> R.drawable.wifi_white_2_24x20
2 -> R.drawable.wifi_white_3_24x20
3 -> R.drawable.wifi_white_4_24x20
4 -> R.drawable.wifi_white_5_24x20
else -> R.drawable.wifi_white_1_24x20 // 0 or unknown
})
view?.findViewById<View>(R.id.update_wifi_button)?.setOnClickListener { clickedView ->
startActivityForResult(
BlePairingStepsActivity.createIntentForReconnect(clickedView.context, network.productAddress),
IntentRequestCode.HUB_WIFI_PAIRING_REQUEST.requestCode
)
activity?.overridePendingTransition(R.anim.slide_in_from_bottom, R.anim.fade_out)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
val requestCodeMatches = requestCode == IntentRequestCode.HUB_WIFI_PAIRING_REQUEST.requestCode
val successfulResult = resultCode == Activity.RESULT_OK
var justSetupWiFi = requestCodeMatches && successfulResult
if (justSetupWiFi) {
activity.run {
if (data == null || this !is PermissionsActivity) {
return // Can't show snackbar!
}
val network = data.getStringExtra(Intent.EXTRA_TEXT)
justSetupWiFi = data.getBooleanExtra(Intent.EXTRA_RETURN_RESULT, true)
val networkName = network ?: ""
this.showSnackbar { layout -> ConnectedToWiFiSnackBar.make(layout).setNetworkName(networkName, justSetupWiFi) }
}
} else if (resultCode == Activity.RESULT_FIRST_USER) {
ScleraPopup.newInstance(
R.string.device_is_offline,
R.string.device_is_offline_sub_text,
R.string.ok,
-1,
true,
true
).show(fragmentManager)
}
}
companion object {
private const val CAMERA_ADDRESS = "CAMERA_ADDRESS"
@JvmStatic
fun newInstance(cameraAddress: String) = NetworkSettingsFragment().also {
val bundle = Bundle()
bundle.putString(CAMERA_ADDRESS, cameraAddress)
it.arguments = bundle
}
}
}
| 6 | null | 27 | 27 | 845b23b6ee913c58e009914e920242e29d0b137a | 4,749 | arcusandroid | Apache License 2.0 |
android/src/com/android/tools/idea/databinding/util/LayoutBindingTypeUtil.kt | JetBrains | 60,701,247 | false | null | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.databinding.util
import com.android.SdkConstants
import com.android.resources.ResourceType
import com.android.resources.ResourceUrl
import com.android.tools.idea.databinding.index.BindingLayoutType
import com.android.tools.idea.databinding.index.BindingXmlData
import com.android.tools.idea.databinding.index.BindingXmlIndex
import com.android.tools.idea.databinding.index.ViewIdData
import com.android.tools.idea.databinding.util.DataBindingUtil.getQualifiedBindingName
import com.android.tools.idea.util.androidFacet
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementFactory
import com.intellij.psi.PsiType
import com.intellij.util.IncorrectOperationException
import org.jetbrains.android.facet.AndroidFacet
import org.jetbrains.kotlin.idea.util.projectStructure.getModule
object LayoutBindingTypeUtil {
private val VIEW_PACKAGE_ELEMENTS = listOf(
SdkConstants.VIEW, SdkConstants.VIEW_GROUP, SdkConstants.TEXTURE_VIEW, SdkConstants.SURFACE_VIEW
)
/**
* Creates a [PsiType] for the target [typeStr], returning null instead of throwing an exception if it was not possible to create it for
* some reason. [typeStr] can be a fully qualified class name, an array type or a primitive type.
*/
@JvmStatic
fun parsePsiType(typeStr: String, context: PsiElement): PsiType? {
return try {
PsiElementFactory.getInstance(context.project).createTypeFromText(typeStr, context)
}
catch (e: IncorrectOperationException) {
// Class named "text" not found.
null
}
}
/**
* Convert a view tag (e.g. <TextView... />) to its PSI type, if possible, or return `null` otherwise.
*/
@JvmStatic
fun resolveViewPsiType(xmlData: BindingXmlData, viewIdData: ViewIdData, context: PsiElement): PsiType? {
val androidFacet = context.androidFacet ?: return null
val viewClassName = getViewClassName(xmlData, viewIdData, androidFacet) ?: return null
return if (viewClassName.isNotEmpty()) PsiType.getTypeByName(viewClassName, context.project, context.resolveScope) else null
}
/**
* Convert a view name (e.g. "TextView") to its PSI type, if possible, or return `null` otherwise.
*/
@JvmStatic
fun resolveViewPsiType(xmlData: BindingXmlData, viewTag: String, context: PsiElement): PsiType? {
val androidFacet = context.androidFacet ?: return null
val viewClassName = getViewClassName(xmlData, viewTag, null, androidFacet) ?: return null
return if (viewClassName.isNotEmpty()) PsiType.getTypeByName(viewClassName, context.project, context.resolveScope) else null
}
/**
* Receives a [ViewIdData] and returns the name of the View class that is implied by it. May return null if it cannot find anything
* reasonable (e.g. it is a merge but does not have data binding)
*/
private fun getViewClassName(xmlData: BindingXmlData, viewIdData: ViewIdData, facet: AndroidFacet): String? {
return getViewClassName(xmlData, viewIdData.viewName, viewIdData.layoutName, facet)
}
private fun getViewClassName(xmlData: BindingXmlData, viewName: String, layoutName: String?, facet: AndroidFacet): String? {
return when {
SdkConstants.VIEW_MERGE == viewName -> getViewClassNameFromMergeTag(layoutName, facet)
SdkConstants.VIEW_INCLUDE == viewName -> getViewClassNameFromIncludeTag(layoutName, facet)
SdkConstants.VIEW_STUB == viewName -> {
when (xmlData.layoutType) {
BindingLayoutType.PLAIN_LAYOUT -> SdkConstants.CLASS_VIEWSTUB
BindingLayoutType.DATA_BINDING_LAYOUT ->
DataBindingUtil.getDataBindingMode(facet).viewStubProxy.takeIf { it.isNotBlank() } ?: SdkConstants.CLASS_VIEWSTUB
}
}
// <fragment> tags are ignored by data binding / view binding compiler
SdkConstants.TAG_FRAGMENT == viewName -> null
else -> getFqcn(viewName)
}
}
/**
* Return the fully qualified path to a target class name.
*
* It the name is already a fully qualified path, it will be returned directly. Otherwise, it
* will be assumed to be a view class, e.g. "ImageView" returns "android.widget.ImageView"
*/
@JvmStatic
fun getFqcn(className: String): String {
return when {
className.indexOf('.') >= 0 -> className
VIEW_PACKAGE_ELEMENTS.contains(className) -> SdkConstants.VIEW_PKG_PREFIX + className
SdkConstants.WEB_VIEW == className -> SdkConstants.ANDROID_WEBKIT_PKG + className
else -> SdkConstants.WIDGET_PKG_PREFIX + className
}
}
private fun getViewClassNameFromIncludeTag(layoutName: String?, facet: AndroidFacet): String {
val reference = getViewClassNameFromLayoutAttribute(layoutName, facet)
return reference ?: SdkConstants.CLASS_VIEW
}
private fun getViewClassNameFromMergeTag(layoutName: String?, facet: AndroidFacet): String? {
return getViewClassNameFromLayoutAttribute(layoutName, facet)
}
private fun getViewClassNameFromLayoutAttribute(layoutName: String?, facet: AndroidFacet): String? {
if (layoutName == null) {
return null
}
val resourceUrl = ResourceUrl.parse(layoutName)
if (resourceUrl == null || resourceUrl.type != ResourceType.LAYOUT) {
return null
}
val indexEntry = BindingXmlIndex.getEntriesForLayout(facet.module.project, resourceUrl.name).firstOrNull() ?: return null
// Note: The resource might exist in a different module than the one passed into this method;
// e.g. if "activity_main.xml" includes a layout from a library, `facet` will be tied to "app"
// while `resourceFacet` would be tied to the library.
val resourceFacet =
indexEntry.file.getModule(facet.module.project)?.let { AndroidFacet.getInstance(it) } ?: return null
if (indexEntry.data.layoutType == BindingLayoutType.PLAIN_LAYOUT && !resourceFacet.isViewBindingEnabled()) {
// If including a non-binding layout, we just use its root tag as the type for this tag (e.g. FrameLayout, TextView)
return getViewClassName(indexEntry.data, indexEntry.data.rootTag, null, resourceFacet)
}
return getQualifiedBindingName(resourceFacet, indexEntry)
}
} | 3 | null | 219 | 921 | dbd9aeae0dc5b8c56ce2c7d51208ba26ea0f169b | 6,751 | android | Apache License 2.0 |
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/outline/Usercirlceadd.kt | Tlaster | 560,394,734 | false | {"Kotlin": 25133302} | package moe.tlaster.icons.vuesax.vuesaxicons.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import moe.tlaster.icons.vuesax.vuesaxicons.OutlineGroup
public val OutlineGroup.Usercirlceadd: ImageVector
get() {
if (_usercirlceadd != null) {
return _usercirlceadd!!
}
_usercirlceadd = Builder(name = "Usercirlceadd", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(11.4604f, 14.4799f)
curveTo(9.5004f, 14.4799f, 7.9004f, 12.8799f, 7.9004f, 10.9199f)
curveTo(7.9004f, 8.9599f, 9.5004f, 7.3599f, 11.4604f, 7.3599f)
curveTo(13.4204f, 7.3599f, 15.0204f, 8.9599f, 15.0204f, 10.9199f)
curveTo(15.0204f, 12.8799f, 13.4204f, 14.4799f, 11.4604f, 14.4799f)
close()
moveTo(11.4604f, 8.8699f)
curveTo(10.3304f, 8.8699f, 9.4004f, 9.7899f, 9.4004f, 10.9299f)
curveTo(9.4004f, 12.0699f, 10.3204f, 12.9899f, 11.4604f, 12.9899f)
curveTo(12.6004f, 12.9899f, 13.5204f, 12.0699f, 13.5204f, 10.9299f)
curveTo(13.5204f, 9.7899f, 12.6004f, 8.8699f, 11.4604f, 8.8699f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(16.6495f, 20.95f)
curveTo(16.2395f, 20.95f, 15.8995f, 20.61f, 15.8995f, 20.2f)
curveTo(15.8995f, 18.28f, 13.9095f, 16.72f, 11.4595f, 16.72f)
curveTo(9.0095f, 16.72f, 7.0195f, 18.28f, 7.0195f, 20.2f)
curveTo(7.0195f, 20.61f, 6.6795f, 20.95f, 6.2695f, 20.95f)
curveTo(5.8595f, 20.95f, 5.5195f, 20.61f, 5.5195f, 20.2f)
curveTo(5.5195f, 17.46f, 8.1795f, 15.22f, 11.4595f, 15.22f)
curveTo(14.7395f, 15.22f, 17.3995f, 17.45f, 17.3995f, 20.2f)
curveTo(17.3995f, 20.61f, 17.0595f, 20.95f, 16.6495f, 20.95f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(11.5f, 22.75f)
curveTo(5.85f, 22.75f, 1.25f, 18.15f, 1.25f, 12.5f)
curveTo(1.25f, 6.85f, 5.85f, 2.25f, 11.5f, 2.25f)
curveTo(12.89f, 2.25f, 14.23f, 2.52f, 15.49f, 3.05f)
curveTo(15.85f, 3.2f, 16.03f, 3.6f, 15.91f, 3.97f)
curveTo(15.8f, 4.3f, 15.75f, 4.65f, 15.75f, 5.0f)
curveTo(15.75f, 5.59f, 15.91f, 6.17f, 16.22f, 6.67f)
curveTo(16.38f, 6.95f, 16.59f, 7.2f, 16.83f, 7.41f)
curveTo(17.7f, 8.2f, 18.99f, 8.45f, 20.0f, 8.09f)
curveTo(20.37f, 7.95f, 20.79f, 8.14f, 20.94f, 8.51f)
curveTo(21.48f, 9.78f, 21.75f, 11.13f, 21.75f, 12.51f)
curveTo(21.75f, 18.15f, 17.15f, 22.75f, 11.5f, 22.75f)
close()
moveTo(11.5f, 3.75f)
curveTo(6.68f, 3.75f, 2.75f, 7.67f, 2.75f, 12.5f)
curveTo(2.75f, 17.33f, 6.68f, 21.25f, 11.5f, 21.25f)
curveTo(16.32f, 21.25f, 20.25f, 17.33f, 20.25f, 12.5f)
curveTo(20.25f, 11.54f, 20.09f, 10.59f, 19.79f, 9.68f)
curveTo(18.41f, 9.92f, 16.9f, 9.49f, 15.84f, 8.52f)
curveTo(15.49f, 8.22f, 15.18f, 7.85f, 14.94f, 7.44f)
curveTo(14.5f, 6.72f, 14.26f, 5.87f, 14.26f, 5.0f)
curveTo(14.26f, 4.73f, 14.28f, 4.47f, 14.33f, 4.21f)
curveTo(13.42f, 3.9f, 12.47f, 3.75f, 11.5f, 3.75f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(19.0f, 9.75f)
curveTo(17.82f, 9.75f, 16.7f, 9.31f, 15.83f, 8.52f)
curveTo(15.48f, 8.22f, 15.17f, 7.85f, 14.93f, 7.44f)
curveTo(14.49f, 6.72f, 14.25f, 5.87f, 14.25f, 5.0f)
curveTo(14.25f, 4.49f, 14.33f, 3.99f, 14.49f, 3.51f)
curveTo(14.71f, 2.83f, 15.09f, 2.2f, 15.6f, 1.69f)
curveTo(16.5f, 0.77f, 17.71f, 0.25f, 19.01f, 0.25f)
curveTo(20.37f, 0.25f, 21.66f, 0.83f, 22.54f, 1.83f)
curveTo(23.32f, 2.7f, 23.76f, 3.82f, 23.76f, 5.0f)
curveTo(23.76f, 5.38f, 23.71f, 5.76f, 23.61f, 6.12f)
curveTo(23.51f, 6.57f, 23.32f, 7.04f, 23.06f, 7.45f)
curveTo(22.48f, 8.43f, 21.56f, 9.16f, 20.48f, 9.5f)
curveTo(20.03f, 9.67f, 19.53f, 9.75f, 19.0f, 9.75f)
close()
moveTo(19.0f, 1.75f)
curveTo(18.11f, 1.75f, 17.28f, 2.1f, 16.67f, 2.73f)
curveTo(16.32f, 3.09f, 16.07f, 3.5f, 15.92f, 3.97f)
curveTo(15.81f, 4.3f, 15.76f, 4.65f, 15.76f, 5.0f)
curveTo(15.76f, 5.59f, 15.92f, 6.17f, 16.23f, 6.67f)
curveTo(16.39f, 6.95f, 16.6f, 7.2f, 16.84f, 7.41f)
curveTo(17.71f, 8.2f, 19.0f, 8.45f, 20.01f, 8.09f)
curveTo(20.77f, 7.85f, 21.39f, 7.35f, 21.79f, 6.68f)
curveTo(21.97f, 6.39f, 22.09f, 6.08f, 22.16f, 5.77f)
curveTo(22.23f, 5.51f, 22.26f, 5.26f, 22.26f, 5.0f)
curveTo(22.26f, 4.2f, 21.96f, 3.43f, 21.42f, 2.83f)
curveTo(20.81f, 2.14f, 19.93f, 1.75f, 19.0f, 1.75f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(20.49f, 5.73f)
horizontalLineTo(17.5f)
curveTo(17.09f, 5.73f, 16.75f, 5.39f, 16.75f, 4.98f)
curveTo(16.75f, 4.57f, 17.09f, 4.23f, 17.5f, 4.23f)
horizontalLineTo(20.49f)
curveTo(20.9f, 4.23f, 21.24f, 4.57f, 21.24f, 4.98f)
curveTo(21.24f, 5.39f, 20.91f, 5.73f, 20.49f, 5.73f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(19.0f, 7.26f)
curveTo(18.59f, 7.26f, 18.25f, 6.92f, 18.25f, 6.51f)
verticalLineTo(3.52f)
curveTo(18.25f, 3.11f, 18.59f, 2.77f, 19.0f, 2.77f)
curveTo(19.41f, 2.77f, 19.75f, 3.11f, 19.75f, 3.52f)
verticalLineTo(6.51f)
curveTo(19.75f, 6.93f, 19.41f, 7.26f, 19.0f, 7.26f)
close()
}
}
.build()
return _usercirlceadd!!
}
private var _usercirlceadd: ImageVector? = null
| 0 | Kotlin | 0 | 2 | b8a8231e6637c2008f675ae76a3423b82ee53950 | 8,105 | VuesaxIcons | MIT License |
services/cache/src/main/kotlin/io/github/mkutz/greatgradlegoodies/rating/RatingService.kt | mkutz | 788,417,831 | false | {"Kotlin": 94264, "Shell": 448} | package io.github.mkutz.greatgradlegoodies.rating
import java.util.*
import org.springframework.data.repository.findByIdOrNull
import org.springframework.stereotype.Service
@Service
class RatingService(private val repository: RatingRepository) {
fun getAll() = repository.findAll().map { Rating(it) }
fun getById(id: UUID) = repository.findByIdOrNull(id)?.let { Rating(it) }
fun create(rating: Rating) = Rating(repository.save(RatingEntity(rating)))
fun getByProductId(productId: UUID) = repository.findAllByProductId(productId).map { Rating(it) }
}
| 0 | Kotlin | 0 | 0 | 25f51dd2aae46385d6f37e17aeec7340cee40d31 | 564 | great-gradle-goodies | Apache License 2.0 |
converter/src/main/java/com/zizohanto/android/currencyconverter/converter/presentation/mvi/ConverterViewState.kt | zizoh | 315,755,201 | false | null | package com.zizohanto.android.currencyconverter.converter.presentation.mvi
import com.zizohanto.android.currencyconverter.converter.presentation.models.ConverterDataModel
import com.zizohanto.android.currencyconverter.converter.presentation.models.HistoricalDataModel
import com.zizohanto.android.currencyconverter.presentation.mvi.ViewState
/**
* Created by zizoh on 26/November/2020.
*/
sealed class ConverterViewState : ViewState {
object Idle : ConverterViewState()
object GettingSymbols : ConverterViewState()
data class SymbolsLoaded(val state: ConverterDataModel) : ConverterViewState()
object GettingConversion : ConverterViewState()
data class Converted(val historicalData: HistoricalDataModel) : ConverterViewState()
sealed class Error : ConverterViewState() {
data class ErrorGettingSymbols(val message: String) : Error()
data class ErrorGettingConversion(val message: String) : Error()
data class ErrorGettingChart(val message: String) : Error()
}
object GettingChartData : ConverterViewState()
data class ChartDataLoaded(
val numberOfEntries: Int,
val historicalData: List<HistoricalDataModel>
) : ConverterViewState()
} | 0 | Kotlin | 0 | 0 | 3cc5bc91b0d3af5c8986f100fecbf06270926a4e | 1,220 | Currency-Converter | Apache License 2.0 |
buildSrc/src/main/kotlin/GooglePlayServices.kt | michaelbel | 354,625,997 | false | null | package org.michaelbel.template
/**
* Set up Google Play services
*
* https://developers.google.com/android/guides/setup
*/
object GooglePlayServices {
private const val GoogleServicesPluginVersion = "4.3.10"
private const val OssLicensesPluginVersion = "0.10.4"
private const val StrictPluginVersion = "1.2.2"
private const val GmsAds = "20.5.0"
private const val GmsAdsIdentifier = "18.0.1"
private const val GmsAdsLite = "20.5.0"
private const val GmsAfsNative = "19.0.3"
private const val GmsAnalytics = "18.0.1"
private const val GmsAppset = "16.0.2"
private const val GmsAuth = "20.0.1"
private const val GmsAuthApiPhone = "18.0.1"
private const val GmsAuthBlockstore = "16.1.0"
private const val GmsAwareness = "19.0.1"
private const val GmsBase = "18.0.1"
private const val GmsBasement = "18.0.0"
private const val GmsCast = "21.0.1"
private const val GmsCastFramework = "21.0.1"
private const val GmsCronet = "18.0.1"
private const val GmsFido = "19.0.0-beta"
private const val GmsFitness = "21.0.1"
private const val GmsGames = "22.0.1"
private const val GmsInstantapps = "18.0.1"
private const val GmsLocation = "19.0.1"
private const val GmsMaps = "18.0.2"
private const val GmsMlkitBarcodeScanning = "17.0.0"
private const val GmsMlkitFaceDetection = "16.2.1"
private const val GmsMlkitImageLabeling = "16.0.6"
private const val GmsMlkitImageLabelingCustom = "16.0.0-beta2"
private const val GmsMlkitLanguageId = "16.0.0-beta2"
private const val GmsMlkitTextRecognition = "17.0.1"
private const val GmsNearby = "18.0.2"
private const val GmsOssLicenses = "17.0.0"
private const val GmsPasswordComplexity = "18.0.1"
private const val GmsPay = "16.0.3"
private const val GmsRecaptcha = "17.0.1"
private const val GmsSafetynet = "18.0.1"
private const val GmsTagManager = "18.0.1"
private const val GmsTasks = "18.0.1"
private const val GmsVision = "20.1.3"
private const val GmsWallet = "19.1.0"
private const val GmsWearable = "17.1.0"
const val GoogleServicesPlugin = "com.google.gms:google-services:$GoogleServicesPluginVersion"
const val OssLicensesPlugin = "com.google.android.gms:oss-licenses-plugin:$OssLicensesPluginVersion"
const val StrictPlugin = "com.google.android.gms:strict-version-matcher-plugin:$StrictPluginVersion"
const val Ads = "com.google.android.gms:play-services-ads:$GmsAds"
const val AdsIdentifier = "com.google.android.gms:play-services-ads-identifier:$GmsAdsIdentifier"
const val AdsLite = "com.google.android.gms:play-services-ads-lite:$GmsAdsLite"
const val AfsNative = "com.google.android.gms:play-services-afs-native:$GmsAfsNative"
const val Analytics = "com.google.android.gms:play-services-analytics:$GmsAnalytics"
const val Appset = "com.google.android.gms:play-services-appset:$GmsAppset"
const val Auth = "com.google.android.gms:play-services-auth:$GmsAuth"
const val AuthApiPhone = "com.google.android.gms:play-services-auth-api-phone:$GmsAuthApiPhone"
const val AuthBlockstore = "com.google.android.gms:play-services-auth-blockstore:$GmsAuthBlockstore"
const val Awareness = "com.google.android.gms:play-services-awareness:$GmsAwareness"
const val Base = "com.google.android.gms:play-services-base:$GmsBase"
const val Basement = "com.google.android.gms:play-services-basement:$GmsBasement"
const val Cast = "com.google.android.gms:play-services-cast:$GmsCast"
const val CastFramework = "com.google.android.gms:play-services-cast-framework:$GmsCastFramework"
const val Cronet = "com.google.android.gms:play-services-cronet:$GmsCronet"
const val Fido = "com.google.android.gms:play-services-fido:$GmsFido"
const val Fitness = "com.google.android.gms:play-services-fitness:$GmsFitness"
const val Games = "com.google.android.gms:play-services-games:$GmsGames"
const val InstantApps = "com.google.android.gms:play-services-instantapps:$GmsInstantapps"
const val Location = "com.google.android.gms:play-services-location:$GmsLocation"
const val Maps = "com.google.android.gms:play-services-maps:$GmsMaps"
const val MlkitBarcodeScanning = "com.google.android.gms:play-services-mlkit-barcode-scanning:$GmsMlkitBarcodeScanning"
const val MlkitFaceDetection = "com.google.android.gms:play-services-mlkit-face-detection:$GmsMlkitFaceDetection"
const val MlkitImageLabelling = "com.google.android.gms:play-services-mlkit-image-labeling:$GmsMlkitImageLabeling"
const val MlkitImageLabellingCustom = "com.google.android.gms:play-services-mlkit-image-labeling-custom:$GmsMlkitImageLabelingCustom"
const val MlkitLanguageId = "com.google.android.gms:play-services-mlkit-language-id:$GmsMlkitLanguageId"
const val MlkitTextRecognition = "com.google.android.gms:play-services-mlkit-text-recognition:$GmsMlkitTextRecognition"
const val Nearby = "com.google.android.gms:play-services-nearby:$GmsNearby"
const val OssLicenses = "com.google.android.gms:play-services-oss-licenses:$GmsOssLicenses"
const val PasswordComplexity = "com.google.android.gms:play-services-password-complexity:$GmsPasswordComplexity"
const val Pay = "com.google.android.gms:play-services-pay:$GmsPay"
const val Recaptcha = "com.google.android.gms:play-services-recaptcha:$GmsRecaptcha"
const val Safetynet = "com.google.android.gms:play-services-safetynet:$GmsSafetynet"
const val Tagmanager = "com.google.android.gms:play-services-tagmanager:$GmsTagManager"
const val Tasks = "com.google.android.gms:play-services-tasks:$GmsTasks"
const val Vision = "com.google.android.gms:play-services-vision:$GmsVision"
const val Wallet = "com.google.android.gms:play-services-wallet:$GmsWallet"
const val Wearable = "com.google.android.gms:play-services-wearable:$GmsWearable"
} | 1 | Kotlin | 1 | 2 | 6b8b208326091b3a2aaa3a266fae10711a115c56 | 5,908 | android-app-template | Apache License 2.0 |
app/src/main/java/com/github/boybeak/v8x/app/WebGLActivity.kt | boybeak | 616,090,715 | false | null | package com.github.boybeak.v8x.app
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.eclipsesource.v8.NodeJS
import com.github.boybeak.adapter.AnyAdapter
import com.github.boybeak.adapter.event.OnClick
import com.github.boybeak.v8x.R
import com.github.boybeak.v8x.app.adapter.AssetsAdapter
import com.github.boybeak.v8x.app.adapter.item.AssetsJsItem
import com.github.boybeak.v8x.app.fragment.WebGLFragment
import java.io.File
class WebGLActivity : AppCompatActivity() {
private val webGLRv: RecyclerView by lazy {
findViewById(R.id.web_gl_rv)
}
private val adapter by lazy {
AssetsAdapter(this, "webgl").apply {
setOnClickFor(AssetsJsItem::class.java, object : OnClick<AssetsJsItem> {
override fun getClickableIds(): IntArray {
return intArrayOf(0)
}
override fun onClick(
view: View,
item: AssetsJsItem,
position: Int,
adapter: AnyAdapter
) {
showWebGL("${item.path}${File.separator}${item.source()}")
}
})
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_web_gl)
val utilJs = File(externalCacheDir, "webgl/util.js")
utilJs.parentFile?.mkdirs()
copyAssetsTo("util.js", utilJs)
webGLRv.adapter = adapter
}
private fun showWebGL(assetsPath: String) {
WebGLFragment(assetsPath).show(supportFragmentManager, assetsPath)
}
} | 0 | Kotlin | 0 | 1 | b60fbd170b14ddca0433a684ddedfc131d3a9737 | 1,750 | v8x | MIT License |
spine/src/main/kotlin/glass/yasan/spine/Validatable.kt | yasanglass | 455,284,796 | false | {"Kotlin": 16248} | package glass.yasan.spine
interface Validatable {
fun isValid(): Boolean
} | 0 | Kotlin | 0 | 5 | 5619bdebc6f781c095728ff8e0b1a5b88253bbcc | 80 | spine | MIT License |
app/src/main/java/com/muedsa/tvbox/demoplugin/service/MediaDetailService.kt | muedsa | 872,828,287 | false | {"Kotlin": 15543} | package com.muedsa.tvbox.demoplugin.service
import com.muedsa.tvbox.api.data.MediaDetail
import com.muedsa.tvbox.api.data.MediaEpisode
import com.muedsa.tvbox.api.data.MediaHttpSource
import com.muedsa.tvbox.api.data.MediaPlaySource
import com.muedsa.tvbox.api.data.SavedMediaCard
import com.muedsa.tvbox.api.service.IMediaDetailService
class MediaDetailService(
private val danDanPlayApiService: DanDanPlayApiService
) : IMediaDetailService {
override suspend fun getDetailData(mediaId: String, detailUrl: String): MediaDetail {
val resp = danDanPlayApiService.getAnime(mediaId.toInt())
if (resp.errorCode != 0) {
throw RuntimeException(resp.errorMessage)
}
val bangumi = resp.bangumi ?: throw RuntimeException("bangumi not found")
return MediaDetail(
id = bangumi.animeId.toString(),
title = bangumi.animeTitle,
subTitle = bangumi.typeDescription,
description = bangumi.summary,
detailUrl = bangumi.animeId.toString(),
backgroundImageUrl = bangumi.imageUrl,
playSourceList = listOf(
MediaPlaySource(
id = "bangumi",
name = "bangumi",
episodeList = bangumi.episodes.map {
MediaEpisode(
id = it.episodeId.toString(),
name = it.episodeTitle
)
}
)
),
favoritedMediaCard = SavedMediaCard(
id = bangumi.animeId.toString(),
title = bangumi.animeTitle,
detailUrl = bangumi.animeId.toString(),
coverImageUrl = bangumi.imageUrl,
cardWidth = 210 / 2,
cardHeight = 302 / 2,
)
)
}
override suspend fun getEpisodePlayInfo(
playSource: MediaPlaySource,
episode: MediaEpisode
): MediaHttpSource = MediaHttpSource(url = "https://media.w3.org/2010/05/sintel/trailer.mp4")
} | 0 | Kotlin | 0 | 0 | 9558b51660cce6557b87c8d7afa02dd0d61ed00c | 2,089 | TvBoxDemoPlugin | MIT License |
app/src/main/java/com/breezeshankar/features/login/model/productlistmodel/ProductRateListResponseModel.kt | DebashisINT | 851,529,165 | false | {"Kotlin": 15698684, "Java": 1025747} | package com.breezeshankar.features.login.model.productlistmodel
import com.breezeshankar.base.BaseResponse
import java.io.Serializable
/**
* Created by Saikat on 15-01-2020.
*/
class ProductRateListResponseModel : BaseResponse(), Serializable {
var product_rate_list: ArrayList<ProductRateDataModel>? = null
} | 0 | Kotlin | 0 | 0 | d382b7af0064e3965a2a89789c42731687d911f5 | 317 | SHANKARMG | Apache License 2.0 |
app/src/main/java/xyz/malkki/neostumbler/constants/PreferenceKeys.kt | mjaakko | 702,807,829 | false | {"Kotlin": 222388} | package xyz.malkki.neostumbler.constants
/**
* Constants for preference key values
*/
object PreferenceKeys {
const val AUTOSCAN_ENABLED = "autoscan_enabled"
const val PREFER_FUSED_LOCATION = "prefer_fused_location"
} | 13 | Kotlin | 0 | 2 | 0e41b1b37d766f2195c329bf418c74ce3ec16d30 | 228 | NeoStumbler | MIT License |
src/main/kotlin/com/bbbang/license/cmd/LoadCmd.kt | laifugroup | 749,306,751 | false | {"Kotlin": 12939} | package com.bbbang.license.cmd
import com.bbbang.parent.keymgr.LicenseManager
import global.namespace.truelicense.api.LicenseManagementException
import io.micronaut.http.HttpStatus
import picocli.CommandLine
import java.util.concurrent.Callable
@CommandLine.Command(name = "load",description=["加载证书-加载证书信息"])
class LoadCmd : Callable<Any> {
@Throws(Exception::class)
override fun call(): Any {
try {
val loadCert= LicenseManager.standard.load()
println("\n")
println("授权用户:"+loadCert.info)
println("过期时间:"+loadCert.notAfter)
println("\n")
return loadCert
}catch (e: LicenseManagementException){
val loadFailure="证书加载错误,请联系管理员"
println(loadFailure)
return loadFailure
}
}
}
| 0 | Kotlin | 0 | 0 | 844b1b3c99c377348998fb37368c1e1b4076daff | 821 | license | Blue Oak Model License 1.0.0 |
scalechain-cli/src/test/kotlin/io/scalechain/blockchain/cli/control/HelpSpec.kt | ScaleChain | 45,332,311 | false | null | package io.scalechain.blockchain.cli.control
import com.google.gson.JsonPrimitive
import io.kotlintest.KTestJUnitRunner
import io.scalechain.blockchain.api.Services
import io.scalechain.blockchain.api.command.help.Help
import io.scalechain.blockchain.api.domain.StringResult
import io.scalechain.blockchain.cli.APITestSuite
import org.junit.runner.RunWith
/**
* Created by kangmo on 11/2/15.
*/
@RunWith(KTestJUnitRunner::class)
class HelpSpec : APITestSuite() {
override fun beforeEach() {
// set-up code
//
super.beforeEach()
}
override fun afterEach() {
super.afterEach()
// tear-down code
//
}
init {
"Help" should "list commands if no argument is provided." {
val response = invoke(Help)
val result = response.right()!! as StringResult
result.value.contains("== Blockchain ==") shouldBe true
}
"Help" should "show a help for a command if the command argument is provided." {
// For each command, try to run help.
for (command in Services.serviceByCommand.keys) {
println("Testing if help for command, $command works well.")
val response = invoke(Help, listOf(JsonPrimitive(command)))
val result = response.right()!! as StringResult
result.value.contains(command) shouldBe true
}
}
}
}
| 11 | Kotlin | 67 | 234 | 702ac4d65febb05dc8283e8c165df454efa339b8 | 1,323 | scalechain | Intel Open Source License |
scalechain-cli/src/test/kotlin/io/scalechain/blockchain/cli/control/HelpSpec.kt | ScaleChain | 45,332,311 | false | null | package io.scalechain.blockchain.cli.control
import com.google.gson.JsonPrimitive
import io.kotlintest.KTestJUnitRunner
import io.scalechain.blockchain.api.Services
import io.scalechain.blockchain.api.command.help.Help
import io.scalechain.blockchain.api.domain.StringResult
import io.scalechain.blockchain.cli.APITestSuite
import org.junit.runner.RunWith
/**
* Created by kangmo on 11/2/15.
*/
@RunWith(KTestJUnitRunner::class)
class HelpSpec : APITestSuite() {
override fun beforeEach() {
// set-up code
//
super.beforeEach()
}
override fun afterEach() {
super.afterEach()
// tear-down code
//
}
init {
"Help" should "list commands if no argument is provided." {
val response = invoke(Help)
val result = response.right()!! as StringResult
result.value.contains("== Blockchain ==") shouldBe true
}
"Help" should "show a help for a command if the command argument is provided." {
// For each command, try to run help.
for (command in Services.serviceByCommand.keys) {
println("Testing if help for command, $command works well.")
val response = invoke(Help, listOf(JsonPrimitive(command)))
val result = response.right()!! as StringResult
result.value.contains(command) shouldBe true
}
}
}
}
| 11 | Kotlin | 67 | 234 | 702ac4d65febb05dc8283e8c165df454efa339b8 | 1,323 | scalechain | Intel Open Source License |
app/src/main/java/by/godevelopment/currencyappsample/data/datasources/network/CurrencyApi.kt | aleh-god | 458,777,301 | false | {"Kotlin": 61033} | package by.godevelopment.currencyappsample.data.datasources.network
import by.godevelopment.currencyappsample.data.datamodels.CurrencyApiModel
import by.godevelopment.currencyappsample.data.datamodels.RateCurrencyApiModel
import retrofit2.Call
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
interface CurrencyApi {
@GET("currencies")
suspend fun getAllCurrencies(): List<CurrencyApiModel>
@GET("rates?periodicity=0")
suspend fun getAllRatesByDate(@Query("ondate") date: String): List<RateCurrencyApiModel>
@GET("rates?periodicity=1")
suspend fun getAllRatesByMonth(@Query("ondate") date: String): List<RateCurrencyApiModel>
}
// полный перечень валют: https://www.nbrb.by/api/exrates/currencies
// Адрес запроса: https://www.nbrb.by/api/exrates/rates[/{cur_id}]
// получение официального курса белорусского рубля по отношению к иностранным валютам, устанавливаемого ежедневно, на сегодня:
// https://www.nbrb.by/api/exrates/rates?periodicity=0
// получение официального курса белорусского рубля по отношению к иностранным валютам, устанавливаемого ежедневно, на 6 июля 2016 года:
// https://www.nbrb.by/api/exrates/rates?ondate=2016-7-6&periodicity=0
// получение официального курса белорусского рубля по отношению к иностранным валютам, устанавливаемого ежемесячно, на 1 июля 2016 года:
// https://www.nbrb.by/api/exrates/rates?ondate=2016-7-1&periodicity=1
// получение официального курса белорусского рубля по отношению к 1 Доллару США на сегодня:
// https://www.nbrb.by/api/exrates/rates/431 – по внутреннему коду валюты
// https://www.nbrb.by/api/exrates/rates/840?parammode=1 – по цифровому коду валюты (ИСО 4217)
// https://www.nbrb.by/api/exrates/rates/USD?parammode=2 – по буквенному коду валюты (ИСО 4217)
// получение официального курса белорусского рубля по отношению к 100 Российским рублям на 5 июля 2016 года:
// https://www.nbrb.by/api/exrates/rates/298?ondate=2016-7-5 | 0 | Kotlin | 0 | 0 | 87790b898eecde93fb4fcfde0f5fb836c815e749 | 1,948 | currency-app | MIT License |
triggers/selector_with_timer/src/commonMain/kotlin/PackageInfo.kt | InsanusMokrassar | 526,191,498 | false | {"Kotlin": 145873, "Shell": 1793, "Dockerfile": 179} | package dev.inmo.plaguposter.triggers.selector_with_timer
| 0 | Kotlin | 1 | 5 | 63800ce19cf2d89ef94bc469c3cf0d40e3758ac8 | 58 | PlaguPoster | MIT License |
sample/src/main/java/com/rawa/recyclerswipes/sample/ui/dashboard/DashboardFragment.kt | Rawa | 250,207,704 | false | null | package com.rawa.recyclerswipes.sample.ui.dashboard
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.elevate.rxbinding3.swipes
import com.rawa.recyclerswipes.RecyclerSwipes
import com.rawa.recyclerswipes.SwipeDirection
import com.rawa.recyclerswipes.attachTo
import com.rawa.recyclerswipes.sample.R
import com.rawa.recyclerswipes.sample.ui.dashboard.adapter.DashboardAdapter
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
class DashboardFragment : Fragment() {
private val dashboardViewModel: DashboardViewModel by viewModels()
private lateinit var swipes: RecyclerSwipes
private lateinit var adapter: DashboardAdapter
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment_dashboard, container, false)
adapter = DashboardAdapter()
val recyclerView: RecyclerView = root.findViewById(R.id.rv_dashboard_items)
recyclerView.adapter = adapter
recyclerView.layoutManager = GridLayoutManager(context, 4, RecyclerView.HORIZONTAL, false)
dashboardViewModel.text.observe(viewLifecycleOwner, Observer {
adapter.update(it)
})
swipes = RecyclerSwipes(
SwipeDirection.UP to R.layout.swipe_peekabo,
SwipeDirection.DOWN to R.layout.swipe_peekabo
)
swipes.attachTo(recyclerView)
return root
}
lateinit var disposable: Disposable
override fun onResume() {
super.onResume()
disposable = swipes.swipes().observeOn(AndroidSchedulers.mainThread()).subscribe {
when (it.direction) {
SwipeDirection.UP, SwipeDirection.DOWN -> {
val item = adapter.getItem(it.viewHolder.adapterPosition)
Toast.makeText(context, "Peekabo ${item.word}!", Toast.LENGTH_SHORT).show()
dashboardViewModel.deleteWord(item.id)
}
else -> {
throw UnsupportedOperationException()
}
}
}
}
override fun onPause() {
super.onPause()
disposable.dispose()
}
}
| 0 | Kotlin | 0 | 1 | cdf4a54fc1ab8b9d6ba0030f46c2de385f2bb2e7 | 2,593 | recycler-swipes | MIT License |
app/src/main/java/net/catstack/nfcpay/domain/PaymentPatternModel.kt | GORR174 | 311,296,297 | false | null | package net.catstack.nfcpay.domain
data class PaymentPatternModel(
val imageResource: Int,
val name: String,
val sum: Int
) | 1 | Kotlin | 1 | 0 | e429ea2a561db9282d220af4ebab27af667dc9c7 | 136 | NfcPayments-android | Apache License 2.0 |
features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/MessageShieldView.kt | element-hq | 546,522,002 | false | {"Kotlin": 8692554, "Python": 57175, "Shell": 39911, "JavaScript": 20399, "Java": 9607, "HTML": 9416, "CSS": 2519, "Ruby": 44} | /*
* Copyright (c) 2024 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.element.android.features.messages.impl.timeline.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import io.element.android.compound.theme.ElementTheme
import io.element.android.compound.tokens.generated.CompoundIcons
import io.element.android.libraries.designsystem.preview.ElementPreview
import io.element.android.libraries.designsystem.preview.PreviewsDayNight
import io.element.android.libraries.designsystem.theme.components.Icon
import io.element.android.libraries.designsystem.theme.components.Text
import io.element.android.libraries.matrix.api.timeline.item.event.MessageShield
import io.element.android.libraries.matrix.api.timeline.item.event.isCritical
import io.element.android.libraries.ui.strings.CommonStrings
@Composable
internal fun MessageShieldView(
shield: MessageShield,
modifier: Modifier = Modifier
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = modifier,
) {
Icon(
imageVector = shield.toIcon(),
contentDescription = null,
modifier = Modifier.size(15.dp),
tint = shield.toIconColor(),
)
Spacer(modifier = Modifier.size(4.dp))
Text(
text = shield.toText(),
style = ElementTheme.typography.fontBodySmMedium,
color = shield.toTextColor()
)
}
}
@Composable
internal fun MessageShield.toIconColor(): Color {
return when (isCritical) {
true -> ElementTheme.colors.iconCriticalPrimary
false -> ElementTheme.colors.iconSecondary
}
}
@Composable
private fun MessageShield.toTextColor(): Color {
return when (isCritical) {
true -> ElementTheme.colors.textCriticalPrimary
false -> ElementTheme.colors.textSecondary
}
}
@Composable
internal fun MessageShield.toText(): String {
return stringResource(
id = when (this) {
is MessageShield.AuthenticityNotGuaranteed -> CommonStrings.event_shield_reason_authenticity_not_guaranteed
is MessageShield.UnknownDevice -> CommonStrings.event_shield_reason_unknown_device
is MessageShield.UnsignedDevice -> CommonStrings.event_shield_reason_unsigned_device
is MessageShield.UnverifiedIdentity -> CommonStrings.event_shield_reason_unverified_identity
is MessageShield.SentInClear -> CommonStrings.event_shield_reason_sent_in_clear
is MessageShield.PreviouslyVerified -> CommonStrings.event_shield_reason_previously_verified
}
)
}
@Composable
internal fun MessageShield.toIcon(): ImageVector {
return when (this) {
is MessageShield.AuthenticityNotGuaranteed -> CompoundIcons.Info()
is MessageShield.UnknownDevice,
is MessageShield.UnsignedDevice,
is MessageShield.UnverifiedIdentity,
is MessageShield.PreviouslyVerified -> CompoundIcons.HelpSolid()
is MessageShield.SentInClear -> CompoundIcons.LockOff()
}
}
@PreviewsDayNight
@Composable
internal fun MessageShieldViewPreview() {
ElementPreview {
Column(
modifier = Modifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
MessageShieldView(
shield = MessageShield.UnknownDevice(true)
)
MessageShieldView(
shield = MessageShield.UnverifiedIdentity(true)
)
MessageShieldView(
shield = MessageShield.AuthenticityNotGuaranteed(false)
)
MessageShieldView(
shield = MessageShield.UnsignedDevice(false)
)
MessageShieldView(
shield = MessageShield.SentInClear(false)
)
MessageShieldView(
shield = MessageShield.PreviouslyVerified(false)
)
}
}
}
| 263 | Kotlin | 129 | 955 | 31d0621fa15fe153bfd36104e560c9703eabe917 | 5,011 | element-x-android | Apache License 2.0 |
app/src/main/kotlin/com/mitch/appname/di/DatastoreModule.kt | seve-andre | 564,679,359 | false | {"Kotlin": 94005} | package com.mitch.appname.di
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.core.DataStoreFactory
import androidx.datastore.dataStoreFile
import com.mitch.appname.ProtoUserPreferences
import com.mitch.appname.data.local.datastore.user.preferences.ProtoUserPreferencesSerializer
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object DatastoreModule {
@Provides
@Singleton
fun providesUserPreferencesDatastore(
@ApplicationContext context: Context,
protoUserPreferencesSerializer: ProtoUserPreferencesSerializer,
): DataStore<ProtoUserPreferences> =
DataStoreFactory.create(
serializer = protoUserPreferencesSerializer,
scope = CoroutineScope(SupervisorJob())
) {
context.dataStoreFile("user_preferences.pb")
}
}
| 0 | Kotlin | 1 | 38 | da8e8e112810278284071bc62f4c890299070b75 | 1,146 | android-jetpack-compose-template | MIT License |
redwood-yoga/src/commonMain/kotlin/app/cash/redwood/yoga/internal/enums/YGEdge.kt | cashapp | 305,409,146 | false | {"Kotlin": 2089205, "Swift": 20649, "Objective-C": 4497, "Java": 1583, "Shell": 253, "HTML": 235, "C": 129} | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package app.cash.redwood.yoga.internal.enums
internal enum class YGEdge {
YGEdgeLeft,
YGEdgeTop,
YGEdgeRight,
YGEdgeBottom,
YGEdgeStart,
YGEdgeEnd,
YGEdgeHorizontal,
YGEdgeVertical,
YGEdgeAll;
}
| 108 | Kotlin | 73 | 1,648 | 3f14e622c2900ec7e0dfaff5bd850c95a7f29937 | 404 | redwood | Apache License 2.0 |
Bumpify/app/src/main/java/com/example/bumpify/ReportActivity.kt | Marlpzg | 362,357,794 | false | null | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package com.example.bumpify
import android.content.Intent
import android.location.Location
import android.media.Image
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.example.bumpify.model.ReportModel
import com.example.bumpify.repository.Repository
import com.google.android.material.snackbar.Snackbar
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
import com.scottyab.aescrypt.AESCrypt
import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider
import java.io.BufferedReader
import java.io.File
import java.io.FileInputStream
import java.io.InputStreamReader
class ReportActivity : AppCompatActivity() {
lateinit var ID: String
lateinit var txtDescripcion: EditText
lateinit var latitude: String
lateinit var longitude: String
lateinit var txtplaceholder: TextView
lateinit var ivplaceholder: ImageView
var imageid: Int = 0
var reportname: String = ""
private lateinit var viewModel: MainViewModel
private lateinit var repository: Repository
private lateinit var viewModelFactory: MainViewModelFactory
//Modelo donde se guardan las respuestas del servidor
data class Req(@SerializedName("data") val mensaje: String, @SerializedName("codigo") val codigo: Int)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_report)
val intent = getIntent()
txtplaceholder = findViewById<TextView>(R.id.tv_placeholder)
ivplaceholder = findViewById<ImageView>(R.id.iv_report_holder)
//Porción de código para obtener datos de un intent
ID = intent.getIntExtra("id", 1).toString()
latitude = intent.getDoubleExtra("latitude", 1.1).toString()
longitude = intent.getDoubleExtra("longitude", 1.1).toString()
reportname = intent.getStringExtra("name").toString()
imageid = intent.getIntExtra("image", 1)
var completetext = "Reportando un "+reportname
txtplaceholder.text = completetext
ivplaceholder.setImageResource(imageid)
txtDescripcion = findViewById<EditText>(R.id.txtDescripcion)
}
override fun onStart() {
super.onStart()
//Configuración para envir datos a la API
repository = Repository()
viewModelFactory = MainViewModelFactory(repository)
viewModel = ViewModelProvider(this, viewModelFactory).get(MainViewModel::class.java)
viewModel.myRespuesta.observe(this, Observer { response ->
val res: SignInActivity.Req = Gson().fromJson(response.body()?.res,SignInActivity.Req::class.java)
//Validación de la respuesta de la API
if(res.codigo == 500){
val contexto = findViewById<View>(R.id.ReportContainer)
val snack = Snackbar.make(contexto,res.mensaje, Snackbar.LENGTH_INDEFINITE);
snack.setAction("Aceptar",View.OnClickListener { snack.dismiss()})
snack.show()
}else{
var intent = Intent(this, MainActivity::class.java)
intent.putExtra("mensaje", res.mensaje)
startActivity(intent)
}
})
}
/**
* Función para enviar Datos al servidor
* */
fun enviarReporte(v: View){
var gps : Location
var descripcion = txtDescripcion.text.toString()
var lat = latitude.toDouble();
var long = longitude.toDouble();
var user = readFromFile()
var type = ID.toInt()
val myReport = ReportModel(type,descripcion,lat,long,user)
viewModel.pushReport(myReport)
}
/**
* Función para leer de un archivo
* */
fun readFromFile(): String {
try {
val dir = File(filesDir, "mydir/sesion.txt")
val gpxfile = FileInputStream(dir)
val reader = BufferedReader(InputStreamReader(gpxfile))
val linea = reader.readLine()
if(linea.isNotEmpty()){
return linea
}
} catch (ex: Exception) {
ex.printStackTrace()
}
return "error"
}
} | 0 | Kotlin | 0 | 0 | 35e4a1e06e73f1a094ac768be35746f90c183fa5 | 5,238 | Proyecto_SIG_ACA | Apache License 2.0 |
ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ExperimentalRuleSetProvider.kt | pinterest | 64,293,719 | false | null | package com.pinterest.ktlint.ruleset.experimental
import com.pinterest.ktlint.core.RuleSet
import com.pinterest.ktlint.core.RuleSetProvider
import com.pinterest.ktlint.ruleset.experimental.trailingcomma.TrailingCommaRule
public class ExperimentalRuleSetProvider : RuleSetProvider {
override fun get(): RuleSet = RuleSet(
"experimental",
AnnotationRule(),
ArgumentListWrappingRule(),
MultiLineIfElseRule(),
NoEmptyFirstLineInMethodBlockRule(),
TrailingCommaRule(),
PackageNameRule(),
EnumEntryNameCaseRule(),
SpacingAroundDoubleColonRule(),
SpacingBetweenDeclarationsWithCommentsRule(),
SpacingBetweenDeclarationsWithAnnotationsRule(),
SpacingAroundAngleBracketsRule(),
SpacingAroundUnaryOperatorRule(),
AnnotationSpacingRule(),
UnnecessaryParenthesesBeforeTrailingLambdaRule()
)
}
| 120 | null | 401 | 4,765 | e1674f8810c8bed6d6ee43c7e97737855c848975 | 912 | ktlint | MIT License |
presentation/base/src/main/java/com/bateng/jikan/api/presentation/base/viewmodel/BaseViewModel.kt | bat-eng | 516,289,173 | false | null | package com.bateng.jikan.api.presentation.base.viewmodel
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bateng.jikan.api.presentation.base.mvi.BaseUiEvent
import com.bateng.jikan.api.presentation.base.mvi.BaseUiIntent
import com.bateng.jikan.api.presentation.base.mvi.BaseUiState
import com.bateng.jikan.api.presentation.base.mvi.IntentDispatcher
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
abstract class BaseViewModel<S : BaseUiState, I : BaseUiIntent, E : BaseUiEvent> : ViewModel() {
private val initialState: S by lazy { createInitialState() }
abstract fun createInitialState(): S
private val _uiEvent = Channel<BaseUiEvent>(Channel.BUFFERED)
private val _uiIntent = MutableSharedFlow<BaseUiIntent>(extraBufferCapacity = 64)
private val _uiState = MutableStateFlow(initialState)
@Composable
operator fun component1(): S = _uiState.collectAsState().value
operator fun component2(): Flow<BaseUiEvent> = _uiEvent.receiveAsFlow()
operator fun component3(): IntentDispatcher<BaseUiIntent> = { _uiIntent.tryEmit(it) }
init {
subscribeIntent()
}
// Get Current State
val currentState: S
get() = _uiState.value
/**
* Handle UiState
*/
protected fun setState(reduce: S.() -> S) {
val newState = _uiState.value.reduce()
_uiState.value = newState
}
/**
* Handle UiEvent
*/
protected fun setEvent(builder: () -> BaseUiEvent) {
val effectValue = builder()
_uiEvent.trySend(effectValue)
}
/**
* Handle UiIntent
*/
private fun subscribeIntent() {
viewModelScope.launch {
_uiIntent.collect {
handleIntent(it)
}
}
}
abstract fun handleIntent(intent: BaseUiIntent)
}
| 0 | Kotlin | 0 | 0 | b9ca169141c605dfc0693a076abd065bceecccc3 | 2,132 | JikanApi | Apache License 2.0 |
src/Day20.kt | frozbiz | 573,457,870 | false | null | class CircularList {
class Node(
val num: Long
) {
lateinit var prev: Node
lateinit var next: Node
}
lateinit var orderList: List<Node>
lateinit var zero: Node
var countNodes = 0L
inline fun makeNode(string: String, multiplier: Long): Node {
return Node(string.trim().toLong() * multiplier)
}
fun load(input: List<String>, multiplier: Long = 1) {
val nodeList = ArrayList<Node>(input.size)
val first = makeNode(input[0], multiplier)
var last = first
nodeList.add(last)
if (last.num == 0L) {
zero = last
}
for (line in input.subList(1, input.size)) {
last.next = makeNode(line, multiplier)
last.next.prev = last
last = last.next
nodeList.add(last)
if (last.num == 0L) {
zero = last
}
}
last.next = first
first.prev = last
countNodes = input.size.toLong()
orderList = nodeList
}
fun move(node: Node) {
val num = node.num % (countNodes - 1)
when {
num > 0 -> {
node.next.prev = node.prev
node.prev.next = node.next
for (i in 0 until num) {
node.next = node.next.next
}
node.prev = node.next.prev
node.next.prev = node
node.prev.next = node
}
num < 0 -> {
node.next.prev = node.prev
node.prev.next = node.next
for (i in 0 until -num) {
node.prev = node.prev.prev
}
node.next = node.prev.next
node.next.prev = node
node.prev.next = node
}
}
}
fun print() {
print("0")
var curr = zero.next
do {
print(", ${curr.num}")
curr = curr.next
} while (curr != zero)
println()
}
fun run(passes: Int = 1): Triple<Long, Long, Long> {
repeat(passes) { orderList.forEach { move(it) } }
var curr = zero
repeat(1000) { curr = curr.next }
val one = curr.num
repeat(1000) { curr = curr.next }
val two = curr.num
repeat(1000) { curr = curr.next }
val tre = curr.num
return Triple(one, two, tre)
}
}
fun main() {
fun part1(input: List<String>): Long {
val list = CircularList()
list.load(input)
val ans = list.run()
return ans.first + ans.second + ans.third
}
fun part2(input: List<String>): Long {
val list = CircularList()
list.load(input, 811589153)
val ans = list.run(10)
return ans.first + ans.second + ans.third
}
// test if implementation meets criteria from the description, like:
val testInput = listOf(
"1\n",
"2\n",
"-3\n",
"3\n",
"-2\n",
"0\n",
"4\n",
)
check(part1(testInput) == 3L)
check(part2(testInput) == 1623178306L)
val input = readInput("day20")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4feef3fa7cd5f3cea1957bed1d1ab5d1eb2bc388 | 3,238 | 2022-aoc-kotlin | Apache License 2.0 |
app/src/main/java/com/concordium/wallet/ui/auth/login/AuthLoginActivity.kt | Concordium | 358,250,608 | false | null | package com.concordium.wallet.ui.auth.login
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.biometric.BiometricPrompt
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.concordium.wallet.R
import com.concordium.wallet.core.arch.EventObserver
import com.concordium.wallet.core.security.BiometricPromptCallback
import com.concordium.wallet.data.preferences.AuthPreferences
import com.concordium.wallet.databinding.ActivityAuthLoginBinding
import com.concordium.wallet.ui.base.BaseActivity
import com.concordium.wallet.ui.intro.introsetup.IntroSetupActivity
import com.concordium.wallet.uicore.afterTextChanged
import com.concordium.wallet.uicore.view.PasscodeView
import com.concordium.wallet.util.KeyboardUtil
import javax.crypto.Cipher
class AuthLoginActivity : BaseActivity() {
private lateinit var binding: ActivityAuthLoginBinding
private lateinit var viewModel: AuthLoginViewModel
private lateinit var biometricPrompt: BiometricPrompt
//region Lifecycle
//************************************************************
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityAuthLoginBinding.inflate(layoutInflater)
setContentView(binding.root)
setupActionBar(
binding.toolbarLayout.toolbar,
binding.toolbarLayout.toolbarTitle,
R.string.auth_login_title
)
initializeViewModel()
viewModel.initialize()
initializeViews()
if (viewModel.shouldShowBiometrics()) {
showBiometrics()
}
}
override fun onBackPressed() {
// Ignore back press
}
//endregion
//region Initialize
//************************************************************
private fun initializeViewModel() {
viewModel = ViewModelProvider(
this,
ViewModelProvider.AndroidViewModelFactory.getInstance(application)
)[AuthLoginViewModel::class.java]
viewModel.finishScreenLiveData.observe(this, object : EventObserver<Boolean>() {
override fun onUnhandledEvent(value: Boolean) {
if (value) {
KeyboardUtil.hideKeyboard(this@AuthLoginActivity)
finish()
}
}
})
viewModel.waitingLiveData.observe(this, Observer<Boolean> { waiting ->
waiting?.let {
showWaiting(waiting)
}
})
viewModel.errorLiveData.observe(this, object : EventObserver<Int>() {
override fun onUnhandledEvent(value: Int) {
showError(value)
}
})
viewModel.passwordErrorLiveData.observe(this, object : EventObserver<Int>() {
override fun onUnhandledEvent(value: Int) {
showPasswordError(value)
}
})
viewModel.errorSeedLiveData.observe(this) { error ->
if (error) {
KeyboardUtil.hideKeyboard(this)
binding.errorSeedTextview.visibility = View.VISIBLE
} else {
binding.errorSeedTextview.visibility = View.GONE
}
}
}
private fun initializeViews() {
showWaiting(false)
hideActionBarBack()
setActionBarTitle(if (viewModel.usePasscode()) R.string.auth_login_info_passcode else R.string.auth_login_info_password)
binding.confirmButton.setOnClickListener {
onConfirmClicked()
}
if (viewModel.usePasscode()) {
binding.passwordEdittext.visibility = View.GONE
binding.confirmButton.visibility = View.INVISIBLE
binding.passcodeView.passcodeListener = object : PasscodeView.PasscodeListener {
override fun onInputChanged() {
binding.errorTextview.text = ""
binding.errorSeedTextview.visibility = View.GONE
}
override fun onDone() {
onConfirmClicked()
}
}
binding.passcodeView.requestFocus()
} else {
binding.passcodeView.visibility = View.GONE
binding.passwordEdittext.setOnEditorActionListener { _, actionId, _ ->
return@setOnEditorActionListener when (actionId) {
EditorInfo.IME_ACTION_DONE -> {
onConfirmClicked()
true
}
else -> false
}
}
binding.passwordEdittext.afterTextChanged {
binding.errorTextview.text = ""
}
binding.passwordEdittext.requestFocus()
}
}
//endregion
//region Control/UI
//************************************************************
private fun showWaiting(waiting: Boolean) {
if (waiting) {
binding.includeProgress.progressLayout.visibility = View.VISIBLE
} else {
binding.includeProgress.progressLayout.visibility = View.GONE
}
}
private fun onConfirmClicked() {
if (viewModel.usePasscode()) {
viewModel.checkLogin(binding.passcodeView.getPasscode())
} else {
viewModel.checkLogin(binding.passwordEdittext.text.toString())
}
}
private fun showBiometrics() {
biometricPrompt = createBiometricPrompt()
val promptInfo = createPromptInfo()
val cipher = viewModel.getCipherForBiometrics()
if (cipher != null) {
biometricPrompt.authenticate(promptInfo, BiometricPrompt.CryptoObject(cipher))
}
}
private fun showPasswordError(stringRes: Int) {
binding.passwordEdittext.setText("")
binding.passcodeView.clearPasscode()
binding.errorTextview.setText(stringRes)
}
private fun showError(stringRes: Int) {
binding.passwordEdittext.setText("")
binding.passcodeView.clearPasscode()
KeyboardUtil.hideKeyboard(this)
popup.showSnackbar(binding.rootLayout, stringRes)
}
//endregion
//region Biometrics
//************************************************************
private fun createBiometricPrompt(): BiometricPrompt {
val executor = ContextCompat.getMainExecutor(this)
val callback = object : BiometricPromptCallback() {
override fun onAuthenticationSucceeded(cipher: Cipher) {
viewModel.checkLogin(cipher)
}
}
val biometricPrompt = BiometricPrompt(this, executor, callback)
return biometricPrompt
}
private fun createPromptInfo(): BiometricPrompt.PromptInfo {
return BiometricPrompt.PromptInfo.Builder()
.setTitle(getString(R.string.auth_login_biometrics_dialog_title))
.setSubtitle(getString(R.string.auth_login_biometrics_dialog_subtitle))
.setConfirmationRequired(false)
.setNegativeButtonText(getString(if (viewModel.usePasscode()) R.string.auth_login_biometrics_dialog_cancel_passcode else R.string.auth_login_biometrics_dialog_cancel_password))
.build()
}
override fun loggedOut() {
// do nothing as we are one of the root activities
}
override fun loggedIn() {
if (!AuthPreferences(this).hasSeedPhrase()) run {
startActivity(Intent(this, IntroSetupActivity::class.java))
}
finish()
}
//endregion
}
| 9 | null | 3 | 9 | 5a273dbcac459e6c2a94b2b9a241eccfcb229cb9 | 7,676 | concordium-reference-wallet-android | Apache License 2.0 |
common/src/commonMain/kotlin/com/artemchep/keyguard/feature/justdeleteme/directory/JustDeleteMeServiceViewScreen.kt | AChep | 669,697,660 | false | {"Kotlin": 4777375, "HTML": 44513} | package com.artemchep.keyguard.feature.justdeleteme.directory
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.AccountBox
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.Email
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.artemchep.keyguard.common.model.getOrNull
import com.artemchep.keyguard.feature.dialog.Dialog
import com.artemchep.keyguard.feature.justdeleteme.AhDifficulty
import com.artemchep.keyguard.feature.navigation.LocalNavigationController
import com.artemchep.keyguard.feature.navigation.NavigationIntent
import com.artemchep.keyguard.feature.tfa.directory.FlatLaunchBrowserItem
import com.artemchep.keyguard.res.Res
import com.artemchep.keyguard.ui.FlatItem
import com.artemchep.keyguard.ui.MediumEmphasisAlpha
import com.artemchep.keyguard.ui.icons.ChevronIcon
import com.artemchep.keyguard.ui.icons.IconBox
import com.artemchep.keyguard.ui.icons.icon
import com.artemchep.keyguard.ui.markdown.MarkdownText
import com.artemchep.keyguard.ui.poweredby.PoweredByJustDeleteMe
import com.artemchep.keyguard.ui.theme.Dimens
import com.artemchep.keyguard.ui.theme.combineAlpha
import dev.icerock.moko.resources.compose.stringResource
@Composable
fun JustDeleteMeScreen(
args: JustDeleteMeServiceViewRoute.Args,
) {
val loadableState = produceJustDeleteMeServiceViewState(
args = args,
)
Dialog(
icon = icon(Icons.Outlined.AccountBox, Icons.Outlined.Delete),
title = {
val title = args.justDeleteMe.name
Text(
text = title,
)
Text(
text = stringResource(Res.strings.justdeleteme_title),
style = MaterialTheme.typography.titleSmall,
color = LocalContentColor.current
.combineAlpha(MediumEmphasisAlpha),
)
AhDifficulty(
modifier = Modifier
.padding(top = 4.dp),
model = args.justDeleteMe,
)
},
content = {
Column {
val notes = args.justDeleteMe.notes
if (notes != null) {
MarkdownText(
modifier = Modifier
.padding(horizontal = Dimens.horizontalPadding),
markdown = notes,
)
Spacer(
modifier = Modifier
.height(16.dp),
)
}
val navigationController by rememberUpdatedState(LocalNavigationController.current)
val updatedEmail by rememberUpdatedState(args.justDeleteMe.email)
if (updatedEmail != null) {
FlatItem(
elevation = 8.dp,
leading = {
IconBox(Icons.Outlined.Email)
},
title = {
Text(
text = stringResource(Res.strings.justdeleteme_send_email_title),
)
},
trailing = {
ChevronIcon()
},
onClick = {
// Open the email, if it's available.
updatedEmail?.let {
val intent = NavigationIntent.NavigateToEmail(
it,
subject = args.justDeleteMe.emailSubject,
body = args.justDeleteMe.emailBody,
)
navigationController.queue(intent)
}
},
enabled = updatedEmail != null,
)
}
val websiteUrl = args.justDeleteMe.url
if (websiteUrl != null) {
FlatLaunchBrowserItem(
title = stringResource(Res.strings.uri_action_launch_website_title),
url = websiteUrl,
)
}
Spacer(
modifier = Modifier
.height(8.dp),
)
PoweredByJustDeleteMe(
modifier = Modifier
.padding(horizontal = Dimens.horizontalPadding)
.fillMaxWidth(),
)
}
},
contentScrollable = true,
actions = {
val updatedOnClose by rememberUpdatedState(loadableState.getOrNull()?.onClose)
TextButton(
enabled = updatedOnClose != null,
onClick = {
updatedOnClose?.invoke()
},
) {
Text(stringResource(Res.strings.close))
}
},
)
}
| 33 | Kotlin | 17 | 294 | 80318722c558e0442e41991b7b352d13cc4e4bd0 | 5,698 | keyguard-app | Linux Kernel Variant of OpenIB.org license |
kautomator/src/main/kotlin/com/kaspersky/components/kautomator/intercepting/interaction/UiDeviceInteraction.kt | aartikov | 222,651,686 | true | {"Kotlin": 488317, "Java": 10748} | package com.kaspersky.components.kautomator.intercepting.interaction
import androidx.test.uiautomator.UiDevice
import com.kaspersky.components.kautomator.intercepting.operation.UiDeviceAction
import com.kaspersky.components.kautomator.intercepting.operation.UiDeviceAssertion
/**
* Provides an interaction to work with the UiDevice
*/
class UiDeviceInteraction(
val device: UiDevice
) : UiInteraction<UiDeviceAssertion, UiDeviceAction> {
override fun check(assertion: UiDeviceAssertion) {
assertion.execute(device)
}
override fun perform(action: UiDeviceAction) {
action.execute(device)
}
override fun toString(): String {
return "UiDeviceInteraction(device=$device)"
}
} | 0 | Kotlin | 0 | 1 | a79c8ffab972f44184abe214a55b963d8af4449f | 730 | Kaspresso | Apache License 2.0 |
core/src/test/kotlin/org/eduardoleolim/organizadorpec660/municipality/application/MunicipalityCreatorTest.kt | eduardoleolim | 673,214,659 | false | {"Kotlin": 832185, "Shell": 2116} | package org.eduardoleolim.organizadorpec660.core.municipality.application
import org.eduardoleolim.organizadorpec660.core.federalEntity.domain.FederalEntity
import org.eduardoleolim.organizadorpec660.core.federalEntity.infrastructure.persistence.InMemoryFederalEntityRepository
import org.eduardoleolim.organizadorpec660.core.municipality.application.create.MunicipalityCreator
import org.eduardoleolim.organizadorpec660.core.municipality.domain.Municipality
import org.eduardoleolim.organizadorpec660.core.municipality.domain.MunicipalityAlreadyExistsError
import org.eduardoleolim.organizadorpec660.core.municipality.infrastructure.InMemoryMunicipalityRepository
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import java.util.*
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class MunicipalityCreatorTest {
private val municipalityRepository = InMemoryMunicipalityRepository()
private val federalEntityRepository = InMemoryFederalEntityRepository()
private val creator = MunicipalityCreator(municipalityRepository, federalEntityRepository)
private val aguascalientesId = "ae7434f1-a8d5-4300-971b-1ec04a701e57"
private val bajaCaliforniaId = "ae7434f1-a8d5-4300-971b-1ec04a701e58"
private val bajaCaliforniaSurId = "ae7434f1-a8d5-4300-971b-1ec04a701e59"
private val campecheId = "ae7434f1-a8d5-4300-971b-1ec04a701e60"
private val veracruzId = "ae7434f1-a8d5-4300-971b-1ec04a701e61"
@BeforeEach
fun beforeEach() {
municipalityRepository.municipalities.clear()
municipalityRepository.federalEntities.clear()
federalEntityRepository.records.clear()
listOf(
FederalEntity.from(aguascalientesId, "01", "AGUASCALIENTES", Date(), null),
FederalEntity.from(bajaCaliforniaId, "02", "BAJA CALIFORNIA", Date(), null),
FederalEntity.from(bajaCaliforniaSurId, "03", "BAJA CALIFORNIA SUR", Date(), null),
FederalEntity.from(campecheId, "04", "CAMPECHE", Date(), null),
FederalEntity.from(veracruzId, "30", "VERACRUZ", Date(), null)
).forEach {
val key = it.id().toString()
federalEntityRepository.records[key] = it
municipalityRepository.federalEntities[key] = it
}
}
@Test
fun `create a municipality`() {
val keyCode = "001"
val name = "AGUASCALIENTES"
val federalEntityId = aguascalientesId
try {
creator.create(keyCode, name, federalEntityId)
assert(municipalityRepository.municipalities.size == 1)
} catch (e: Exception) {
assert(false)
}
}
@Nested
inner class ValidationTests {
private val municipalityId = "ae7434f1-a8d5-4300-971b-1ec04a701e62"
@BeforeEach
fun beforeEach() {
Municipality.from(municipalityId, "001", "AGUASCALIENTES", aguascalientesId, Date(), null).let {
municipalityRepository.municipalities[it.id().toString()] = it
}
}
@Test
fun `fails if municipality already exists`() {
val keyCode = "001"
val name = "AGUASCALIENTES"
val federalEntityId = aguascalientesId
try {
creator.create(keyCode, name, federalEntityId)
.fold(
ifRight = {
assert(false)
},
ifLeft = {
assert(it is MunicipalityAlreadyExistsError)
}
)
} catch (e: Throwable) {
assert(false)
}
}
@Test
fun `create with same keyCode but different federal entity`() {
val keyCode = "001"
val name = "ACAJETE"
val federalEntityId = veracruzId
try {
creator.create(keyCode, name, federalEntityId)
.fold(
ifRight = {
assert(municipalityRepository.municipalities.size == 2)
},
ifLeft = {
assert(false)
}
)
} catch (e: Exception) {
assert(false)
}
}
}
}
| 0 | Kotlin | 0 | 0 | bfe0cdaa736579f86d96e77503bdb8dca57685e8 | 4,445 | organizador-pec-660 | Creative Commons Attribution 4.0 International |
rxmock/src/jvmMain/kotlin/pl/mareklangiewicz/rxmock/RxMockSingle1.kt | langara | 142,078,321 | false | null | package pl.mareklangiewicz.rxmock
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.core.SingleObserver
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.functions.Consumer
import io.reactivex.rxjava3.subjects.SingleSubject
class RxMockSingle1<A, T>(var invocationCheck: (A) -> Boolean = { true })
: SingleObserver<T>, Consumer<T>, (A) -> Single<T> {
constructor(vararg allowedArgs: A) : this({ it in allowedArgs })
val invocations = mutableListOf<A>()
var subject: SingleSubject<T>? = null
override fun invoke(arg: A): Single<T> {
if (!invocationCheck(arg)) throw RxMockException("RxMockSingle1 fail for arg: $arg")
invocations += arg
return SingleSubject.create<T>().also { subject = it }
}
override fun accept(t: T) = onSuccess(t)
override fun onSuccess(t: T) = subject?.onSuccess(t) ?: throw RxMockException()
override fun onSubscribe(d: Disposable) = subject?.onSubscribe(d) ?: throw RxMockException()
override fun onError(e: Throwable) = subject?.onError(e) ?: throw RxMockException()
}
| 0 | Kotlin | 0 | 2 | 3cb4e744da6f81d1dfe2abb16c5fcfac2198a915 | 1,111 | RxMock | Apache License 2.0 |
android/features/vacancies/vacancies-wiring/src/main/java/jobajob/feature/vacancies/wiring/VacanciesWiring.kt | Twinsen81 | 208,475,234 | false | null | package jobajob.feature.vacancies.wiring
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import jobajob.feature.vacancies.api.VacanciesBaseUrl
@Module
@InstallIn(SingletonComponent::class)
object VacanciesWiring {
@Provides
@VacanciesBaseUrl
fun getBaseUrl() = "https://jobajob81.firebaseio.com"
} | 0 | Kotlin | 0 | 1 | f0c17aa5798d5341d5e99857af6687d5cdc566f3 | 385 | JobAJob | Apache License 2.0 |
app/src/test/java/ua/com/radiokot/photoprism/GalleryMonthsSequenceTest.kt | Radiokot | 612,884,518 | false | null | package ua.com.radiokot.photoprism
import org.junit.Assert
import org.junit.Test
import ua.com.radiokot.photoprism.features.gallery.data.model.parsePhotoPrismDate
import ua.com.radiokot.photoprism.features.gallery.logic.GalleryMonthsSequence
import java.util.*
class GalleryMonthsSequenceTest {
@Test
fun generateForRange() {
val endDate = parsePhotoPrismDate("2023-04-01T00:05:10Z")!!
val startDate = parsePhotoPrismDate("2021-02-15T22:06:45Z")!!
val months = GalleryMonthsSequence(
startDate = startDate,
endDate = endDate,
).toList()
Assert.assertEquals(27, months.size)
Assert.assertEquals(1612130400000, months.first().firstDay.time)
Assert.assertEquals(1614549600000, months.first().nextDayAfter.time)
Assert.assertEquals(1646085600000, months[13].firstDay.time)
Assert.assertEquals(1648760400000, months[13].nextDayAfter.time)
Assert.assertEquals(1680296400000, months.last().firstDay.time)
Assert.assertEquals(1682888400000, months.last().nextDayAfter.time)
}
@Test
fun generateForSingleDate() {
val date = parsePhotoPrismDate("2023-04-01T00:05:10Z")!!
val months = GalleryMonthsSequence(
startDate = date,
endDate = date
).toList()
Assert.assertEquals(1, months.size)
Assert.assertEquals(1680296400000, months.first().firstDay.time)
Assert.assertEquals(1682888400000, months.first().nextDayAfter.time)
}
@Test(expected = IllegalArgumentException::class)
fun incorrectRange() {
GalleryMonthsSequence(
startDate = Date(),
endDate = Date(System.currentTimeMillis() - 360000)
)
}
} | 0 | Kotlin | 8 | 121 | 97b659c553b25b4bdc59a1e245229f61f0667db2 | 1,758 | photoprism-android-client | Apache License 2.0 |
src/main/kotlin/io/github/sgpublic/advcompose/core/window/ComposeWindow.kt | sgpublic | 395,833,511 | false | {"Kotlin": 32496} | package io.github.sgpublic.advcompose.core.window
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ExperimentalComposeApi
import androidx.compose.ui.window.Window
import io.github.sgpublic.advcompose.AdvComposeApplication
import io.github.sgpublic.advcompose.core.ComposeBase
import io.github.sgpublic.advcompose.core.component.ComponentProp
import io.github.sgpublic.advcompose.core.component.ComposeComponent
import kotlin.reflect.KClass
abstract class ComposeWindow<Prop: WindowProp>: ComposeBase<Prop>() {
private var created: Boolean = false
@Composable
private fun createWindow() {
onComponentUpdate()
prop.window.run window@{
onCloseRequest = { AdvComposeApplication.closeWindow(this@ComposeWindow::class) }
theme.run state@{
Window(
onCloseRequest, state, visible, title, icon,
undecorated, resizable, enabled, focusable,
alwaysOnTop, onPreviewKeyEvent, onKeyEvent
) {
MaterialTheme(colors, typography, shapes) {
compose()
}
}
}
}
if (created){
return
}
created = true
onComponentCreated()
}
protected fun onClosing(): Boolean {
return true
}
protected final fun close(){
if (!onClosing()){
return
}
AdvComposeApplication.closeWindow(this::class)
}
protected final fun finish(){
AdvComposeApplication.finish()
}
@Composable
protected final fun includeComponent(clazz: KClass<out ComposeComponent<out ComponentProp>>){
ComposeComponent.createComponent(clazz)
}
@ExperimentalComposeApi
@Composable
protected final fun <T: ComponentProp> includeComponent(clazz: KClass<out ComposeComponent<out T>>, prop: T){
// ComposeComponent.createComponent(clazz, prop)
}
companion object {
@JvmStatic
@Composable
internal fun createWindow(windowClass: KClass<out ComposeWindow<out WindowProp>>) {
windowClass.java.getDeclaredConstructor()
.newInstance().createWindow()
}
@JvmStatic
@Composable
@ExperimentalComposeApi
internal fun <T: WindowProp> createWindow(windowClass: KClass<out ComposeWindow<T>>, prop: T) {
windowClass.java.getDeclaredConstructor(prop.javaClass)
.newInstance(prop).createWindow()
}
}
} | 0 | Kotlin | 0 | 0 | 58edc2b40c8c72cc8c696c38dc62c3e39b32d38f | 2,632 | AdvComposeDesktop | Apache License 2.0 |
source-code/starter-project/app/src/main/java/com/droidcon/droidflix/ui/FlixDetailsScreen.kt | droidcon-academy | 788,303,674 | false | {"Kotlin": 82048} | package com.droidcon.droidflix.ui
import android.content.res.Configuration
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PagerState
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
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.graphics.graphicsLayer
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.zIndex
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import coil.compose.AsyncImage
import com.droidcon.droidflix.R
import com.droidcon.droidflix.data.model.Flix
import kotlin.math.absoluteValue
@Composable
fun FlixDetailsScreen(viewModel: FlixViewModel, id: String) {
val lifecycleOwner = LocalLifecycleOwner.current
DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_START) {
viewModel.getFlix(id)
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose {
lifecycleOwner.lifecycle.removeObserver(observer)
}
}
val flix by viewModel.flix.collectAsState()
val isLoading by viewModel.loading.collectAsState()
val configuration = LocalConfiguration.current
when (configuration.orientation) {
Configuration.ORIENTATION_LANDSCAPE -> {
FlixDetailsLandscapeLayout(flix, isLoading)
}
else -> {
FlixDetailsPortraitLayout(flix, isLoading)
}
}
}
@Composable
fun FlixDetailsPortraitLayout(flix: Flix?, isLoading: Boolean) {
ConstraintLayout(
modifier = Modifier.fillMaxSize()
) {
val (image, title, year, card, loader, info) = createRefs()
if (isLoading) {
CircularProgressIndicator(
modifier = Modifier
.zIndex(1f)
.constrainAs(loader) {
top.linkTo(parent.top)
start.linkTo(parent.start)
end.linkTo(parent.end)
bottom.linkTo(parent.bottom)
}
)
} else if (flix?.error?.isNotBlank() == true) {
Text(
text = flix.error,
textAlign = TextAlign.Center,
modifier = Modifier
.padding(8.dp)
.constrainAs(info) {
top.linkTo(parent.top)
end.linkTo(parent.end)
start.linkTo(parent.start)
bottom.linkTo(parent.bottom)
}
)
} else if (flix == null) {
Text(
text = stringResource(id = R.string.empty),
textAlign = TextAlign.Center,
modifier = Modifier
.padding(8.dp)
.constrainAs(info) {
top.linkTo(parent.top)
end.linkTo(parent.end)
start.linkTo(parent.start)
bottom.linkTo(parent.bottom)
}
)
}
flix?.let {
val texts = arrayListOf(Pair(stringResource(id = R.string.plot), flix.plot))
texts.add(Pair(stringResource(id = R.string.ratings), flix.ratings.joinToString("\n\n")))
AsyncImage(
model = flix.poster,
contentDescription = null,
modifier = Modifier
.padding(16.dp)
.constrainAs(image) {
top.linkTo(parent.top)
end.linkTo(parent.end)
start.linkTo(parent.start)
bottom.linkTo(title.top)
height = Dimension.fillToConstraints
},
)
Text(
modifier = Modifier
.padding(16.dp)
.constrainAs(title) {
top.linkTo(parent.top)
bottom.linkTo(parent.bottom)
start.linkTo(parent.start, margin = 8.dp)
end.linkTo(parent.end, margin = 8.dp)
},
textAlign = TextAlign.Center,
text = flix.title,
fontSize = 24.sp
)
Text(
modifier = Modifier.constrainAs(year) {
top.linkTo(title.bottom)
start.linkTo(parent.start, margin = 8.dp)
end.linkTo(parent.end, margin = 8.dp)
},
text = flix.year,
fontSize = 16.sp
)
CardPagerWithIndicator(modifier = Modifier
.constrainAs(card) {
top.linkTo(year.bottom, margin = 8.dp)
start.linkTo(parent.start, margin = 16.dp)
end.linkTo(parent.end, margin = 16.dp)
bottom.linkTo(parent.bottom, margin = 16.dp)
height = Dimension.fillToConstraints
width = Dimension.fillToConstraints
},
texts = texts
)
}
}
}
@Composable
fun FlixDetailsLandscapeLayout(flix: Flix?, isLoading: Boolean) {
ConstraintLayout(
modifier = Modifier.fillMaxSize()
) {
val (image, title, year, card, loader, info) = createRefs()
if (isLoading) {
CircularProgressIndicator(
modifier = Modifier.constrainAs(loader) {
top.linkTo(parent.top)
start.linkTo(parent.start)
end.linkTo(parent.end)
bottom.linkTo(parent.bottom)
}
)
} else if (flix?.error?.isNotBlank() == true) {
Text(
text = flix.error,
textAlign = TextAlign.Center,
modifier = Modifier
.padding(8.dp)
.constrainAs(info) {
top.linkTo(parent.top)
end.linkTo(parent.end)
start.linkTo(parent.start)
bottom.linkTo(parent.bottom)
}
)
} else if (flix == null) {
Text(
text = stringResource(id = R.string.empty),
textAlign = TextAlign.Center,
modifier = Modifier
.padding(8.dp)
.constrainAs(info) {
top.linkTo(parent.top)
end.linkTo(parent.end)
start.linkTo(parent.start)
bottom.linkTo(parent.bottom)
}
)
}
flix?.let {
val texts = arrayListOf(Pair(stringResource(id = R.string.plot), flix.plot))
texts.add(Pair(stringResource(id = R.string.ratings), flix.ratings.joinToString("\n\n")))
AsyncImage(
model = flix.poster,
contentDescription = null,
modifier = Modifier
.padding(16.dp)
.constrainAs(image) {
top.linkTo(parent.top)
start.linkTo(parent.start)
end.linkTo(card.start)
bottom.linkTo(parent.bottom)
height = Dimension.fillToConstraints
},
)
Text(
modifier = Modifier.constrainAs(title) {
top.linkTo(parent.top, margin = 8.dp)
bottom.linkTo(card.top, margin = 8.dp)
start.linkTo(image.end, margin = 8.dp)
end.linkTo(parent.end, margin = 8.dp)
},
text = flix.title,
fontSize = 24.sp
)
Text(
modifier = Modifier.constrainAs(year) {
top.linkTo(parent.top, margin = 8.dp)
start.linkTo(title.end, margin = 8.dp)
},
text = flix.year,
fontSize = 16.sp
)
CardPagerWithIndicator(modifier = Modifier
.constrainAs(card) {
top.linkTo(title.bottom, margin = 8.dp)
start.linkTo(image.end, margin = 16.dp)
end.linkTo(parent.end, margin = 16.dp)
bottom.linkTo(parent.bottom, margin = 16.dp)
height = Dimension.fillToConstraints
width = Dimension.fillToConstraints
},
texts = texts
)
}
}
}
@Composable
fun CardPagerWithIndicator(modifier: Modifier, texts: ArrayList<Pair<String, String>>) {
Box(modifier = modifier.fillMaxSize()) {
val pageCount = texts.size
val pagerState = rememberPagerState(pageCount = { pageCount })
HorizontalPager(
beyondViewportPageCount = 2,
state = pagerState) {
PagerItem(
title = texts[it].first,
text = texts[it].second,
modifier = Modifier
.pagerFadeTransition(it, pagerState = pagerState)
.fillMaxSize()
)
}
Row(
modifier = Modifier
.height(30.dp)
.fillMaxWidth()
.align(Alignment.BottomCenter),
horizontalArrangement = Arrangement.Center
) {
repeat(pageCount) { iteration ->
val color = if (pagerState.currentPage == iteration) Color.White else Color.White.copy(alpha = 0.5f)
Box(
modifier = Modifier
.padding(4.dp)
.clip(CircleShape)
.background(color)
.size(10.dp)
)
}
}
}
}
@Composable
fun PagerItem(modifier: Modifier, title: String, text: String) {
Card(modifier = modifier) {
Text(
text = title,
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
fontSize = 20.sp
)
Text(
text = text,
textAlign = TextAlign.Center,
maxLines = 10,
overflow = TextOverflow.Ellipsis,
modifier = Modifier
.fillMaxWidth()
.verticalScroll(rememberScrollState())
.padding(start = 16.dp, end = 16.dp)
)
}
}
fun PagerState.calculateCurrentOffsetForPage(page: Int): Float {
return (currentPage - page) + currentPageOffsetFraction
}
fun Modifier.pagerFadeTransition(page: Int, pagerState: PagerState) =
graphicsLayer {
val pageOffset = pagerState.calculateCurrentOffsetForPage(page)
translationX = pageOffset * size.width
alpha = 1- pageOffset.absoluteValue
} | 0 | Kotlin | 0 | 0 | e08a8a73841a649e7c9566e5e8ed236cf465f055 | 12,587 | android-mc-espresso-test | Apache License 2.0 |
app/src/main/java/com/dscvit/periodsapp/utils/Constants.kt | GDGVIT | 234,146,371 | false | null | package com.dscvit.femhelper.utils
object Constants {
const val BASE_URL = "https://femhelper-swe.herokuapp.com/app/"
const val WS_BASE_URL = "https://femhelper-swe.herokuapp.com/ws/chat/"
const val PREF_NAME = "periods_app_pref"
const val PREF_AUTH_KEY = "PREF_AUTH_KEY"
const val PREF_IS_LOGGED_IN = "PREF_IS_LOGGED_IN"
const val PREF_DEVICE_ID = "PREF_DEVICE_ID"
const val PREF_FCM_TOKEN = "PREF_FCM_TOKEN"
const val PREF_PHONE_NUMBER = "PREF_PHONE_NUMBER"
const val PREF_TOKEN_IS_UPDATED = "PREF_TOKEN_IS_UPDATED"
const val PREF_USER_ID = "PREF_USER_ID"
const val PREF_CURR_CHAT_ROOM = "PREF_CURR_CHAT_ROOM"
const val PREF_CURR_LAT = "PREF_CURR_LAT"
const val PREF_CURR_LON = "PREF_CURR_LON"
const val EXTRA_RECEIVER_ID = "PREF_RECEIVER_ID"
const val EXTRA_CHAT_ROOM_ID = "EXTRA_CHAT_ROOM_ID"
const val EXTRA_RECEIVER_NAME = "EXTRA_RECEIVER_NAME"
} | 0 | Kotlin | 2 | 2 | 027cfe5e05ab0953c21b6924a3ddea8b8f48c36f | 921 | PeriodAlert-App | MIT License |
app-elgoog/src/main/kotlin/dev/bogdanzurac/marp/app/elgoog/news/NewsNavigator.kt | bogdanzurac | 606,411,511 | false | null | package dev.bogdanzurac.marp.app.elgoog.news
import dev.bogdanzurac.marp.app.elgoog.core.navigation.FeatureNavigator
import org.koin.core.annotation.Single
@Single
class NewsNavigator : FeatureNavigator() {
fun navigateToNewsDetails(id: String) = navigateTo(NewsDetails(id))
}
| 0 | Kotlin | 0 | 1 | 9cc815c57d7b3948a5a20f12883dc4dbee7fc4b3 | 284 | marp-app-client-android | Apache License 2.0 |
app/src/main/java/ni/edu/uca/myuca2lavenganzadelauca/ModificarCoordinador.kt | GabrielMerinoUCA | 621,001,766 | false | null | package ni.edu.uca.myuca2lavenganzadelauca
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.navigation.Navigation
import androidx.navigation.fragment.navArgs
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import ni.edu.uca.myuca2lavenganzadelauca.Modelos.Coordinador
import ni.edu.uca.myuca2lavenganzadelauca.databinding.FragmentModificarCoordinadorBinding
import okhttp3.*
import java.io.IOException
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use M,erino [ModificarCoordinador.newInstance] factory method to
* create an instance of this fragment.
*/
class ModificarCoordinador : Fragment() {
private var param1: String? = null
private var param2: String? = null
private lateinit var fbinding: FragmentModificarCoordinadorBinding
private lateinit var coordinador: Coordinador
private val args: ModificarCoordinadorArgs by navArgs()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
@RequiresApi(Build.VERSION_CODES.O)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the Merino layout for this fragment
fbinding = FragmentModificarCoordinadorBinding.inflate(layoutInflater)
coordinador = args.coordinador
iniciar()
return fbinding.root
}
@RequiresApi(Build.VERSION_CODES.O)
private fun iniciar() {
fbinding.etNombresModificar.setText(coordinador.nombres)
fbinding.etApellidosModificar.setText(coordinador.apellidos)
fbinding.etFechaModificar.setText(coordinador.fechaNac.dayOfMonth.toString())
fbinding.etMesModificar.setText(coordinador.fechaNac.monthValue.toString())
fbinding.etYearModificar.setText(coordinador.fechaNac.year.toString())
fbinding.etTituloModificar.setText(coordinador.titulo)
fbinding.etEmailModificar.setText(coordinador.email)
fbinding.etFacultadModificar.setText(coordinador.facultad)
fbinding.btnModificarCoordinador.setOnClickListener {
modificarPUT()
}
fbinding.btnEliminarCoordinador.setOnClickListener {
eliminarDELETE()
}
}
private fun modificarPUT() {
val nombres: String = fbinding.etNombresModificar.text.toString()
val apellidos: String = fbinding.etApellidosModificar.text.toString()
val fechaNac: String =
fbinding.etYearModificar.text.toString() + "-" + fbinding.etMesModificar.text.toString() + "-" + fbinding.etFechaModificar.text.toString()
val titulo: String = fbinding.etTituloModificar.text.toString()
val email: String = fbinding.etEmailModificar.text.toString()
val facultad: String = fbinding.etFacultadModificar.text.toString()
val client = OkHttpClient.Builder()
.build()
val body = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"),
"[\"${coordinador.idC}\"," +
"\"${nombres}\"," +
"\"${apellidos}\"," +
"\"${fechaNac}\"," +
"\"${titulo}\"," +
"\"${email}\"," +
"\"${facultad}\"]")
val request = Request.Builder()
.url("http://192.168.1.14/MyUCA2/modificarCoordinador.php")
.method("PUT", body)
.build()
client.newCall(request).enqueue(object : Callback{
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
}
override fun onResponse(call: Call, response: Response) {
response.use {
try {
GlobalScope.launch(Dispatchers.Main) {
Toast.makeText(requireActivity(), "Guardado exitosamente", Toast.LENGTH_SHORT).show()
Navigation.findNavController(fbinding.root).navigate(R.id.acModificarCoordinador_Main)
}
} catch (e: Exception) {
GlobalScope.launch(Dispatchers.Main) {
Toast.makeText(requireActivity(), "Error de guardado", Toast.LENGTH_SHORT).show()
}
e.printStackTrace()
}
}
}
})
}
private fun eliminarDELETE() {
val client = OkHttpClient.Builder()
.build()
val body = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"),
"[${coordinador.idC}]")
val request = Request.Builder()
.url("http://192.168.1.14/MyUCA2/eliminarCoordinador.php")
.method("DELETE", body)
.build()
client.newCall(request).enqueue(object : Callback{
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
}
override fun onResponse(call: Call, response: Response) {
response.use {
try {
GlobalScope.launch(Dispatchers.Main) {
Toast.makeText(requireActivity(), "Eliminado exitosamente", Toast.LENGTH_SHORT).show()
Navigation.findNavController(fbinding.root).navigate(R.id.acModificarCoordinador_Main)
}
}catch (e: Exception){
GlobalScope.launch(Dispatchers.Main) {
Toast.makeText(requireActivity(), "Error al eliminar", Toast.LENGTH_SHORT).show()
}
e.printStackTrace()
}
}
}
})
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using Merino the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ModificarCoordinador.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
ModificarCoordinador().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | 0 | Kotlin | 0 | 0 | 035d2402ed9b86261c12d8e394857b04336dbb3b | 6,973 | MyUCA2 | Apache License 2.0 |
app/src/main/java/com/example/lessons_schedule/adapter/SubjectsAdapter.kt | RUD0MIR | 597,636,190 | false | {"Kotlin": 75382} | package com.example.lessons_schedule.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.lessons_schedule.R
import com.example.lessons_schedule.data.model.Subject
class SubjectsAdapter (
private val context: Context,
private val onItemLongClick: (View, Subject) -> Unit
) : ListAdapter<Subject, SubjectsAdapter.SubjectsViewHolder>(SubjectsDiffCallback) {
class SubjectsViewHolder
(
view: View,
val context: Context,
private val onItemLongClick: (View, Subject) -> Unit
) : RecyclerView.ViewHolder(view) {
private val subjectNameTv: TextView = itemView.findViewById(R.id.subject_text)
private var currentSubject: Subject? = null
init {
itemView.setOnLongClickListener{ itemView ->
currentSubject?.let { subject ->
onItemLongClick(itemView, subject)
}
return@setOnLongClickListener true
}
}
fun bind(subject: Subject) {
currentSubject = subject
subjectNameTv.text = subject.name
}
}
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): SubjectsViewHolder {
val view = LayoutInflater.from(viewGroup.context)
.inflate(R.layout.subject_list_item, viewGroup, false)
return SubjectsViewHolder(view, context, onItemLongClick)
}
override fun onBindViewHolder(viewHolder: SubjectsViewHolder, position: Int) {
val subject = getItem(position)
viewHolder.bind(subject)
}
object SubjectsDiffCallback : DiffUtil.ItemCallback<Subject>() {
override fun areItemsTheSame(oldItem: Subject, newItem: Subject): Boolean {
return oldItem == newItem
}
override fun areContentsTheSame(oldItem: Subject, newItem: Subject): Boolean {
return oldItem.id == newItem.id
}
}
} | 0 | Kotlin | 0 | 0 | b4ff2a5d4c09e0b4fef40264d5e2ff324c75c507 | 2,186 | lessons-schedule-manager-app | MIT License |
api/src/main/kotlin/net/bytemc/bytecloud/api/services/packets/DolphinSelfInfoPacket.kt | bytemcnetzwerk | 684,494,766 | false | {"Kotlin": 178268} | package net.bytemc.bytecloud.api.services.packets
import net.bytemc.bytecloud.api.CloudAPI
import net.bytemc.bytecloud.api.group.CloudGroup
import net.bytemc.bytecloud.api.network.PacketBuffer
import net.bytemc.bytecloud.api.network.packet.Packet
import net.bytemc.bytecloud.api.services.CloudService
class DolphinSelfInfoPacket(var group: CloudGroup? = null, var service: CloudService? = null) : Packet {
override fun write(out: PacketBuffer) {
out.writeGroup(group!!)
out.writeService(service!!)
}
override fun read(inBuf: PacketBuffer) {
group = CloudAPI.getInstance().getCloudGroupProvider().createInstance(inBuf)
service = CloudAPI.getInstance().getCloudServiceProvider().createInstance(inBuf)
}
override fun id(): Int {
return 3
}
} | 1 | Kotlin | 3 | 5 | 71a52f1a41d3dcd3c656090549e25e13b846539b | 807 | bytecloud | Apache License 2.0 |
tibiakt-core/src/main/kotlin/com/galarzaa/tibiakt/core/models/forums/ForumThread.kt | Galarzaa90 | 285,669,589 | false | {"Kotlin": 539836, "Dockerfile": 1451} | /*
* Copyright © 2024 Allan Galarza
*
* 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.galarzaa.tibiakt.core.models.forums
import com.galarzaa.tibiakt.core.models.PaginatedWithUrl
import com.galarzaa.tibiakt.core.utils.getForumThreadUrl
import kotlinx.serialization.Serializable
/**
* A thread in the Tibia forums.
*
* @property board The name of the board the thread is in.
* @property boardId The internal ID of the board the thread is in.
* @property section The name of the section the board is in.
* @property sectionId The internal ID of the section the board is in.
* @property previousTopicNumber The ID of the thread before this one.
* @property nextTopicNumber The ID of the thread after this one.
* @property goldenFrame Whether the post has a golden frame or not.
* @property anchoredPost The post that corresponds to the anchor in the URL if any.
*/
@Serializable
public data class ForumThread(
override val title: String,
override val threadId: Int,
val board: String,
val boardId: Int,
val section: String,
val sectionId: Int,
val previousTopicNumber: Int?,
val nextTopicNumber: Int?,
val goldenFrame: Boolean,
val anchoredPost: ForumPost? = null,
override val currentPage: Int,
override val totalPages: Int,
override val resultsCount: Int,
override val entries: List<ForumPost>,
) : BaseForumThread, PaginatedWithUrl<ForumPost> {
override val url: String get() = getForumThreadUrl(threadId, currentPage)
/**
* Get the URL to a specific page in the thread.
*/
public override fun getPageUrl(page: Int): String = getForumThreadUrl(threadId, page)
}
| 0 | Kotlin | 2 | 1 | a36cb41c5eef7b9ed54a8bf35c499e32d9bc4fc3 | 2,183 | TibiaKt | Apache License 2.0 |
app/src/main/java/com/chun/anime/ui/adapter/SearchAdapter.kt | nchungdev | 398,720,732 | false | null | package com.chun.anime.ui.adapter
import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.viewbinding.ViewBinding
import com.bumptech.glide.RequestManager
import com.chun.anime.databinding.ItemPortraitBinding
import com.chun.anime.ui.base.rv.Config
import com.chun.anime.ui.base.rv.PagingAdapter
import com.chun.anime.ui.base.rv.ViewHolder
import com.chun.anime.util.glide.SimpleRequestListener
import com.chun.anime.util.glide.loadThumbnail
import com.chun.domain.model.Otaku
class SearchAdapter(
context: Context,
private val requestManager: RequestManager,
config: Config = Config(),
onClick: (View) -> Unit = {},
onRetry: (View) -> Unit = {}
) :
PagingAdapter<Otaku>(context, config, onClick, onRetry) {
override fun provideViewBinding(parent: ViewGroup, viewType: Int): ViewBinding {
return ItemPortraitBinding.inflate(inflater, parent, false).apply {
root.layoutParams.width = config.width
root.layoutParams.height = config.height
}
}
override fun updateViewHolder(holder: ViewHolder<ViewBinding>, position: Int) {
if (holder.binding is ItemPortraitBinding) {
val otaku = getItem(position) ?: return
holder.binding.tvTitle.text = otaku.name
requestManager
.loadThumbnail(otaku.imageUrl, isLightTheme)
.listener(SimpleRequestListener(
onSuccess = { holder.binding.tvTitle.isVisible = false },
onFailure = { holder.binding.tvTitle.isVisible = true }
))
.into(holder.binding.thumbnail)
holder.itemView.tag = otaku
holder.itemView.setOnClickListener { onClick(it) }
}
}
} | 0 | Kotlin | 0 | 0 | 92a75c4304243f379f168ad4eb786de1028cc727 | 1,819 | AnimeDi | MIT License |
src/packages/cacao_driver/driver/SerializableFinder.kt | Vidbar | 271,691,094 | false | null | package packages.cacao_driver.driver
public abstract class SerializableFinder {
public abstract val finderType: String
public open fun serialize(): Map<String, String> = mapOf("finderType" to finderType)
public companion object {
public fun deserialize(json: Map<String, String>): SerializableFinder {
when (json["finderType"] as String) {
"byType" -> return ByType.deserialize(json)
else -> error("!")
}
}
}
} | 0 | Kotlin | 0 | 0 | 224c3f363c254cfce016cacec7ca100245455aae | 500 | Cacao | MIT License |
app/src/main/java/com/example/game_app/menu/LobbiesRecycleView.kt | Gotalicp | 704,093,487 | false | {"Kotlin": 19741} | package com.example.game_app.menu
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.recyclerview.widget.RecyclerView
import com.example.game_app.R
import com.example.game_app.common.itemClickListener
import com.example.game_app.data.LobbyInfo
class LobbiesRecycleView : RecyclerView.Adapter<LobbiesRecycleView.LobbiesViewHolder>() {
private var items = ArrayList<LobbyInfo>()
var itemClickListener: itemClickListener<LobbyInfo>? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LobbiesViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_menu, parent, false)
return LobbiesViewHolder(view)
}
override fun onBindViewHolder(holder: LobbiesViewHolder, position: Int) {
holder.bind(items[position])
}
override fun getItemCount(): Int {
return items.size
}
inner class LobbiesViewHolder(view: View) : RecyclerView.ViewHolder(view) {
private val button = view.findViewById<Button>(R.id.buttonJoin)
fun bind(lobby: LobbyInfo) {
button.setOnClickListener {
itemClickListener?.onItemClicked(lobby, absoluteAdapterPosition)
}
}
}
} | 0 | Kotlin | 0 | 1 | fe70ffc87fa260bf266663b0c8620e21c00dd61a | 1,302 | game-app | MIT License |
app/src/main/java/com/example/dolarcambio/utils/SwipeDelete.kt | ariel10aguero | 347,642,504 | false | {"Kotlin": 42593} | package com.example.dolarcambio.utils
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.example.dolarcambio.R
import com.example.dolarcambio.ui.RecyclerAdapter
import com.example.dolarcambio.viewmodel.MainViewModel
class SwipeDelete(val adapter: RecyclerAdapter, val context: Context, val viewModel: MainViewModel) : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
private val deleteIcon = ContextCompat.getDrawable(context, R.drawable.ic_delete)
private val intrinsicWidth = deleteIcon?.intrinsicWidth
private val intrinsicHeight = deleteIcon?.intrinsicHeight
private val background = ColorDrawable()
private val backgroundColor = Color.parseColor("#f44336")
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
return false
}
override fun getSwipeDirs(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder
): Int {
if(viewHolder is RecyclerAdapter.EmptyList) return 0
return super.getSwipeDirs(recyclerView, viewHolder)
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
viewModel.deleteTransaction(adapter.getTrans(viewHolder.adapterPosition))
adapter.transList.removeAt(viewHolder.adapterPosition)
adapter.notifyItemRemoved(viewHolder.adapterPosition)
}
override fun onChildDraw(
c: Canvas,
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
dX: Float,
dY: Float,
actionState: Int,
isCurrentlyActive: Boolean
) {
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE && isCurrentlyActive){
val itemView = viewHolder.itemView
val itemHeight = itemView.bottom - itemView.top
val isCanceled = dX == 0f && !isCurrentlyActive
// Draw the red delete background
background.color = backgroundColor
background.setBounds(itemView.right + dX.toInt(), itemView.top, itemView.right, itemView.bottom)
background.draw(c)
// Calculate position of delete icon
val deleteIconTop = itemView.top + (itemHeight - intrinsicHeight!!) / 2
val deleteIconMargin = (itemHeight - intrinsicHeight) / 2
val deleteIconLeft = itemView.right - deleteIconMargin - intrinsicWidth!!
val deleteIconRight = itemView.right - deleteIconMargin
val deleteIconBottom = deleteIconTop + intrinsicHeight
// Draw the delete icon
deleteIcon?.setBounds(deleteIconLeft, deleteIconTop, deleteIconRight, deleteIconBottom)
deleteIcon?.draw(c)
}
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
}
} | 0 | Kotlin | 0 | 2 | b8fab19d1c2c669658ccb3c8fca994b50035e05f | 3,113 | DolarCambio | MIT License |
jvm/src/functions.kt | Samoxive | 115,284,693 | false | null | // This is how functions are defined in Kotlin
// It's pretty close to Java syntax
fun sum(x: Int, y: Int): Int {
return x + y
}
// You can also use a shortcut when defining functions if it's one line long
fun sum1(x: Int, y: Int) = x + y
// Functions can also be passed to other functions
fun callFunctionWith2And3(func: (x: Int, y: Int) -> Int) = func(2, 3)
fun main(args: Array<String>) {
// Functions can be created inline, these functions are called `lambda`s.
val a = { x: Int, y: Int -> x + y }
// Will print 2 + 3 = 5
println(callFunctionWith2And3(a))
// For functions that take a function as a parameter, we can use this shortcut to define lambdas for them
val result = callFunctionWith2And3 { x, y ->
val k = 2 * x
val l = 2 * y
k + l
}
// Will print (2 * 2) + (2 * 3) = 10
println(result)
} | 0 | Kotlin | 0 | 0 | ec3f2ecd1ac8e2e3432e10649417f736b1ea206e | 869 | intro-to-kotlin | MIT License |
app/src/main/java/com/twobbble/biz/impl/UserBiz.kt | 872409 | 97,719,825 | true | {"Kotlin": 246224, "Java": 8986} | package com.twobbble.biz.impl
import com.twobbble.biz.api.IUserBiz
import com.twobbble.biz.assist.RetrofitFactory
import com.twobbble.entity.NullResponse
import com.twobbble.entity.Shot
import com.twobbble.entity.Token
import com.twobbble.entity.User
import com.twobbble.tools.NetSubscriber
import com.twobbble.tools.RxHelper
import org.jetbrains.annotations.NotNull
import retrofit2.http.Query
import rx.Subscription
/**
* Created by liuzipeng on 2017/3/5.
*/
class UserBiz : BaseBiz(), IUserBiz {
override fun checkIfFollowingUser(id: Long, access_token: String, netSubscriber: NetSubscriber<NullResponse>): Subscription {
getNetService().checkIfFollowingUser(id, access_token)
.compose(RxHelper.singleModeThread())
.subscribe(netSubscriber)
return netSubscriber
}
override fun followUser(id: Long, access_token: String, netSubscriber: NetSubscriber<NullResponse>): Subscription {
getNetService().followUser(id, access_token)
.compose(RxHelper.singleModeThread())
.subscribe(netSubscriber)
return netSubscriber
}
override fun unFollowUser(id: Long, access_token: String, netSubscriber: NetSubscriber<NullResponse>): Subscription {
getNetService().unFollowUser(id, access_token)
.compose(RxHelper.singleModeThread())
.subscribe(netSubscriber)
return netSubscriber
}
override fun getUserShot(user: String, id: String?, access_token: String, page: Int?, netSubscriber: NetSubscriber<MutableList<Shot>>): Subscription {
getNetService().getUserShot(user, id, access_token, page)
.compose(RxHelper.listModeThread())
.subscribe(netSubscriber)
return netSubscriber
}
override fun getMyInfo(@NotNull access_token: String, netSubscriber: NetSubscriber<User>): Subscription {
getNetService().getMyInfo(access_token)
.compose(RxHelper.singleModeThread())
.subscribe(netSubscriber)
return netSubscriber
}
override fun getToken(oauthCode: String, netSubscriber: NetSubscriber<Token>): Subscription {
RetrofitFactory.getInstance()
.createWebsiteRetrofit()
.getToken(oauthCode = oauthCode)
.compose(RxHelper.singleModeThread())
.subscribe(netSubscriber)
return netSubscriber
}
} | 0 | Kotlin | 0 | 0 | 63843fdb43ee1f35829fcb47173b171a6c31ea94 | 2,446 | Twobbble | Apache License 2.0 |
plugin/src/main/kotlin/io/telereso/plugin/util/TeleresoFiles.kt | telereso | 333,239,062 | false | {"Kotlin": 65665, "Dart": 21663, "TypeScript": 14169, "CSS": 12685, "HTML": 9400, "JavaScript": 4101, "Shell": 1633, "Ruby": 333} | package io.telereso.plugin.util
import com.google.gson.Gson
import com.intellij.ide.highlighter.XmlFileType
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFileFactory
import com.intellij.psi.search.FilenameIndex
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.xml.XmlFile
import java.io.File
object TeleresoFiles {
private fun createTeleresoDir(project: Project): File? {
project.projectFile?.apply {
val dir = File(parent.parent.path, ".telereso")
if (!dir.exists()) {
dir.mkdir()
parent.parent.refresh(false, false)
}
return dir
}
return null
}
private fun clearTeleresoDir(project: Project) {
project.projectFile?.apply {
val dir = File(parent.parent.path, ".telereso")
if (!dir.exists())
dir.deleteRecursively()
return
}
}
private fun createStringsFolder(project: Project): File? {
createTeleresoDir(project)?.let { dir ->
val stringsDir = File(dir, "strings")
if (!stringsDir.exists())
stringsDir.mkdir()
return stringsDir
}
return null
}
private fun createModuleFolder(currentDir: File, module: String): File {
val moduleDir = File(currentDir, module)
if (!moduleDir.exists())
moduleDir.mkdir()
return moduleDir
}
fun createStringFile(dir: File, fileName: String, txt: String): File {
val f = File(dir, fileName)
f.delete()
f.createNewFile()
f.writeText(txt)
return f
}
fun exportDocument(
project: Project,
module: String,
file: VirtualFile,
txt: String,
singleFile: Boolean = false,
keys: List<String>? = null
): File? {
val document = PsiFileFactory.getInstance(project)
.createFileFromText(file.name, XmlFileType.INSTANCE, txt) as XmlFile
val json = Converters.xmlToJson(document, keys)
if (json == "{}") return null
val local = file.parent.name.split("-").toMutableList()
local.removeAt(0)
if (local.isEmpty()) {
local.add("default")
}
var fileName = "strings_${local.joinToString("_") { it.toLowerCase() }}.json"
return if (singleFile) {
fileName = "${module}_$fileName"
createTeleresoDir(project)?.let { dir ->
createStringFile(dir, fileName, json)
}
} else {
createStringsFolder(project)?.let { dir -> createModuleFolder(dir, module) }?.let { dir ->
createStringFile(dir, fileName, json)
}
}
}
fun clearStringsFolder(project: Project): Boolean {
createTeleresoDir(project)?.let { dir ->
File(dir, "strings").deleteRecursively()
return true
}
return false
}
fun saveMergedStrings(project: Project, allFiles: List<File>) {
val gson = Gson()
val map = hashMapOf<String, HashMap<String, String>>()
allFiles.forEach {
val local = it.name.split(".")[0].split("_").toMutableList()
local.removeAt(0)
if (local.isEmpty()) {
local.add("default")
}
var localName= "strings_${local.joinToString("_") { it.toLowerCase() }}.json"
val m = map.getOrDefault(localName, hashMapOf())
m.putAll(Converters.jsonToMap(it.readText()))
map[localName] = m
}
createStringsFolder(project)?.let { dir ->
val mergedDir = File(dir, "merged")
mergedDir.deleteRecursively()
mergedDir.mkdir()
map.forEach { entry ->
val f = File(mergedDir, "strings_${entry.key}.json")
f.createNewFile()
f.writeText(gson.toJson(entry.value))
}
}
}
fun getTeleresoDir(project: Project): VirtualFile? {
project.projectFile?.apply {
val dir = File(parent.parent.path, ".telereso")
if (dir.exists())
return LocalFileSystem.getInstance().findFileByIoFile(dir)
}
return null
}
fun exportStringsAsJson(project: Project, isSingleFile: Boolean = false, keys: List<String>? = null): String? {
var message: String? = null
clearStringsFolder(project)
val allFiles = mutableListOf<File>()
FilenameIndex.getFilesByName(project, "strings.xml", GlobalSearchScope.projectScope(project)).forEach {
ModuleUtil.findModuleForFile(it.virtualFile, project)?.apply {
val modelName = if (name.contains(".")) name.split(".")[1] else name
val f = TeleresoFiles.exportDocument(project, modelName, it.virtualFile, it.text, isSingleFile, keys)
if (f == null) {
message = "Failed to export"
return@forEach
} else
allFiles.add(f)
}
}
saveMergedStrings(project, allFiles)
getTeleresoDir(project)?.refresh(false, true)
return message
}
} | 0 | Kotlin | 0 | 7 | c7090765b1f6b39423a1ccfe06eb7e837eddb164 | 5,425 | telereso | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/learn/TwoStackQueue.kt | ashtanko | 203,993,092 | false | {"Kotlin": 6608183, "Shell": 1168, "Makefile": 961} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.learn
import java.util.Stack
class TwoStackQueue<T> : Collection<T> {
private val stack1 = Stack<T>()
private val stack2 = Stack<T>()
override val size: Int
get() = stack1.size
override fun contains(element: T): Boolean {
return stack1.contains(element)
}
override fun containsAll(elements: Collection<T>): Boolean {
return stack1.containsAll(elements)
}
override fun isEmpty(): Boolean {
return stack1.isEmpty()
}
override fun iterator(): Iterator<T> {
return stack2.iterator()
}
fun peek(): T {
if (size == 0) throw NoSuchElementException()
if (stack1.isEmpty()) {
throw NoSuchElementException()
}
val item = stack1.peek()
stack1.pop()
return item
}
fun add(item: T) {
while (stack1.isNotEmpty()) {
stack2.push(stack1.pop())
}
stack1.push(item)
while (stack2.isNotEmpty()) {
stack1.push(stack2.pop())
}
}
}
| 4 | Kotlin | 0 | 19 | d7f842ebc3041ed6a407782d4f5da2e6a53c34df | 1,665 | kotlab | Apache License 2.0 |
android/src/main/kotlin/com/ekycsolutions/ekyc_id_flutter/FaceScanner/FlutterFaceScanner.kt | EKYCSolutions | 507,305,515 | false | {"Dart": 59127, "Swift": 40658, "Kotlin": 33972, "Ruby": 2309, "Objective-C": 732, "Shell": 460} | package com.ekycsolutions.ekyc_id_flutter.FaceScanner
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.view.View
import android.widget.LinearLayout
import com.ekycsolutions.ekyc_id_flutter.R
import com.ekycsolutions.ekycid.core.models.FrameStatus
import com.ekycsolutions.ekycid.facescanner.FaceScannerEventListener
import com.ekycsolutions.ekycid.facescanner.FaceScannerOptions
import com.ekycsolutions.ekycid.facescanner.FaceScannerView
import com.ekycsolutions.ekycid.facescanner.cameraview.FaceScannerCameraOptions
import com.ekycsolutions.ekycid.livenessdetection.cameraview.LivenessFace
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.platform.PlatformView
import java.io.ByteArrayOutputStream
class FlutterFaceScanner(
private var binding: FlutterPlugin.FlutterPluginBinding,
private var context: Context,
private val viewId: Int
): PlatformView, MethodChannel.MethodCallHandler, FaceScannerEventListener {
private var scanner: FaceScannerView? = null
private var scannerView: LinearLayout = LinearLayout(context)
private val methodChannel: MethodChannel =
MethodChannel(binding.binaryMessenger, "FaceScanner_MethodChannel_$viewId")
private val eventChannel: EventChannel =
EventChannel(binding.binaryMessenger, "FaceScanner_EventChannel_$viewId")
private val eventStreamHandler = FaceScannerEventStreamHandler(context)
init {
this.methodChannel.setMethodCallHandler(this)
this.eventChannel.setStreamHandler(eventStreamHandler)
}
override fun getView(): View {
return scannerView
}
override fun dispose() {
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
when (call.method) {
"start" -> {
start(call, result)
}
"nextImage" -> {
nextImage(call, result)
}
"dispose" -> {
disposeFlutter(call, result)
}
else -> {
result.notImplemented()
}
}
}
private fun start(call: MethodCall, result: MethodChannel.Result) {
try {
val args = call.arguments as HashMap<*, *>
val useFrontCamera = args["useFrontCamera"] as Boolean
val cameraOptions = args["cameraOptions"] as HashMap<String, Any>
this.scanner = FaceScannerView(context, useFrontCamera)
this.scanner!!.addListener(this)
this.scanner!!.start(
FaceScannerOptions(
FaceScannerCameraOptions(
cameraOptions["captureDurationCountDown"] as Int,
(cameraOptions["faceCropScale"] as Double).toFloat(),
(cameraOptions["roiSize"] as Double).toFloat(),
(cameraOptions["minFaceWidthPercentage"] as Double).toFloat(),
(cameraOptions["maxFaceWidthPercentage"] as Double).toFloat(),
)
)
)
this.scanner!!.layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
)
this.scannerView.addView(this.scanner)
result.success(true)
} catch (e: Exception) {
result.error(e.toString(), e.message, "")
}
}
private fun disposeFlutter(call: MethodCall, result: MethodChannel.Result) {
try {
if (this.scanner != null) {
this.scanner!!.stop()
this.scanner = null
}
result.success(true)
} catch (e: Exception) {
result.error(e.toString(), e.message, "")
}
}
private fun nextImage(call: MethodCall, result: MethodChannel.Result) {
try {
if (this.scanner != null) {
this.scanner!!.nextImage()
}
result.success(true)
} catch (e: Exception) {
result.error(e.toString(), e.message, "")
}
}
override fun onInitialized() {
this.eventStreamHandler?.sendOnInitializedEventToFlutter()
}
override fun onFaceScanned(face: LivenessFace) {
this.eventStreamHandler?.sendOnFaceScannedEventToFlutter(face)
}
override fun onFrameStatusChanged(frameStatus: FrameStatus) {
this.eventStreamHandler?.sendOnFrameStatusChangedEventToFlutter(frameStatus)
}
override fun onCaptureCountDownChanged(current: Int, max: Int) {
this.eventStreamHandler?.sendOnCaptureCountDownChangedEventToFlutter(current, max)
}
class FaceScannerEventStreamHandler(private var context: Context) : EventChannel.StreamHandler {
private var events: EventChannel.EventSink? = null
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
this.events = events
}
override fun onCancel(arguments: Any?) {
this.events = null
}
fun sendOnInitializedEventToFlutter() {
if (events != null) {
(context as Activity).runOnUiThread {
val event = HashMap<String, Any>()
event["type"] = "onInitialized"
val values = HashMap<String, Any?>()
event["values"] = values
events!!.success(event)
}
}
}
fun sendOnFrameStatusChangedEventToFlutter(frameStatus: FrameStatus) {
if (events != null) {
(context as Activity).runOnUiThread {
val event = HashMap<String, Any>()
event["type"] = "onFrameStatusChanged"
event["values"] = frameStatus.name
events!!.success(event)
}
}
}
fun sendOnFaceScannedEventToFlutter(face: LivenessFace) {
if (events != null) {
(context as Activity).runOnUiThread {
val event = HashMap<String, Any>()
event["type"] = "onFaceScanned"
event["values"] = livenessFaceToFlutterMap(face)
events!!.success(event)
}
}
}
fun sendOnCaptureCountDownChangedEventToFlutter(current: Int, max: Int) {
if (events != null) {
(context as Activity).runOnUiThread {
val event = HashMap<String, Any>()
event["type"] = "onCaptureCountDownChanged"
val values = HashMap<String, Any?>()
values["current"] = current
values["max"] = max
event["values"] = values
events!!.success(event)
}
}
}
private fun livenessFaceToFlutterMap(livenessFace: LivenessFace): HashMap<String, Any?> {
var values = HashMap<String, Any?>()
values["image"] = bitmapToFlutterByteArray(livenessFace.image!!)
values["leftEyeOpenProbability"] = livenessFace.leftEyeOpenProbability
values["rightEyeOpenProbability"] = livenessFace.rightEyeOpenProbability
values["headEulerAngleX"] = livenessFace.headEulerAngleX
values["headEulerAngleY"] = livenessFace.headEulerAngleY
values["headEulerAngleZ"] = livenessFace.headEulerAngleZ
if (livenessFace.headDirection != null) {
values["headDirection"] = livenessFace.headDirection!!.name
} else {
values["headDirection"] = null
}
if (livenessFace.eyesStatus != null) {
values["eyesStatus"] = livenessFace.eyesStatus!!.name
} else {
values["eyesStatus"] = null
}
return values
}
private fun bitmapToFlutterByteArray(image: Bitmap): ByteArray {
val stream = ByteArrayOutputStream()
image.compress(Bitmap.CompressFormat.JPEG, 90, stream)
return stream.toByteArray()
}
}
} | 0 | Dart | 4 | 18 | 17571db6ccffbed61a1c00e768c19d42c3b74405 | 8,443 | ekyc-id-flutter | Academic Free License v1.2 |
flx/src/main/java/org/fuusio/flx/core/Assignment.kt | Fuusio | 337,071,263 | false | null | /*
* Copyright (C) 2016 - 2021 <NAME>
*
* http://fuusio.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fuusio.flx.core
sealed class Assignment {
abstract fun get(): Any
}
data class SymbolAssignment(var value: Any) : Assignment() {
override fun get(): Any = value
fun set(value: Any): Any {
this.value = value
return value
}
}
data class VarAssignment(var value: Any) : Assignment() {
override fun get(): Any = value
fun set(value: Any): Any {
this.value = value
return value
}
}
data class ValAssignment(val value: Any) : Assignment() {
override fun get(): Any = value
} | 0 | Kotlin | 0 | 9 | 2c37b6c1cf3618f24e991ee764e1e28bf75c85d0 | 1,175 | flx-lisp | Apache License 2.0 |
src/main/kotlin/dev/hybridlabs/aquatic/world/biome/HybridAquaticTerrablenderAPI.kt | hybridlabs | 661,391,321 | false | {"Kotlin": 892890, "Java": 69899} | package dev.hybridlabs.aquatic.world.biome
import dev.hybridlabs.aquatic.HybridAquatic
import dev.hybridlabs.aquatic.world.biome.surface.HybridAquaticMaterialRules
import net.minecraft.util.Identifier
import terrablender.api.Regions
import terrablender.api.SurfaceRuleManager
import terrablender.api.TerraBlenderApi
class HybridAquaticTerrablenderAPI : TerraBlenderApi {
override fun onTerraBlenderInitialized() {
Regions.register(HybridAquaticOverworldRegion(Identifier(HybridAquatic.MOD_ID, "overworld"), 4))
SurfaceRuleManager.addSurfaceRules(
SurfaceRuleManager.RuleCategory.OVERWORLD,
HybridAquatic.MOD_ID,
HybridAquaticMaterialRules.makeRules())
}
} | 6 | Kotlin | 0 | 4 | 82c3b26d6697d2e5666b173101ade38505a3fe4c | 718 | hybrid-aquatic | MIT License |
app/src/test/java/com/devspacecinenow/detail/MovieDetailViewModelTest.kt | victorashino | 819,629,909 | false | {"Kotlin": 74629} | package com.devspacecinenow.detail
import androidx.lifecycle.ViewModel
import app.cash.turbine.test
import com.devspacecinenow.common.data.local.MovieCategory
import com.devspacecinenow.common.data.model.Movie
import com.devspacecinenow.common.data.remote.model.MovieDto
import com.devspacecinenow.list.presentation.ui.MovieListUiState
import com.devspacecinenow.list.presentation.ui.MovieUiData
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.stub
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestCoroutineScheduler
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Test
import retrofit2.Response
class MovieDetailViewModelTest : ViewModel() {
private val fakeService = FakeDetailService()
@OptIn(ExperimentalCoroutinesApi::class)
private val testDispatcher = UnconfinedTestDispatcher(TestCoroutineScheduler())
private val underTest by lazy {
MovieDetailViewModel(fakeService, testDispatcher)
}
@Test
fun `fetchMovieDetail returns expected movie detail`() {
runTest {
// Given
val movie = MovieDto(
id = 1,
title = "Title 1",
overview = "Overview 1",
postPath = "postPath 1"
)
underTest.fetchMovieDetail(movie.id.toString())
// When
underTest.uiMovieDetail.test {
// Then assert expected value
val expected = MovieDto(
id = movie.id,
title = "Fake Movie",
overview = "This is a fake movie for testing.",
postPath = "PostPath",
)
assertEquals(expected, awaitItem())
}
}
}
@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun `fetchMovieDetail logs error when request fails`() {
runTest {
// Given
fakeService.shouldReturnError = true
// When
underTest.fetchMovieDetail("invalid_id")
advanceUntilIdle() // Aguarda todas as corrotinas terminarem
// Then
val movieDetail = underTest.uiMovieDetail.value
assertEquals(null, movieDetail)
}
}
} | 0 | Kotlin | 0 | 0 | fa8868df4f324770ed0b1bb9ccda97a43e9b231b | 2,440 | CineNow | MIT License |
chooser-compose/src/main/java/net/mm2d/color/chooser/compose/Tab.kt | ohmae | 158,970,822 | false | {"Kotlin": 160321} | package net.mm2d.color.chooser.compose
/**
* Enum class representing the color chooser tabs.
*/
enum class Tab {
/**
* Select from palette.
*/
PALETTE,
/**
* Select by HSV.
*/
HSV,
/**
* Select by RGB.
*/
RGB,
/**
* Select from Material3 colors.
*/
M3,
;
companion object {
val DEFAULT_TABS: List<Tab> = listOf(PALETTE, HSV, RGB)
val DEFAULT_TAB: Tab = PALETTE
}
}
| 1 | Kotlin | 5 | 23 | 00a15b42ee16a2c0cc488a1a5c7d12e473a2819c | 472 | color-chooser | MIT License |
app/src/main/java/com/huanchengfly/tieba/post/adapters/base/BaseMultiTypeAdapter.kt | fly2marss | 405,560,522 | true | {"Kotlin": 840467, "Java": 801077, "JavaScript": 47843} | package com.huanchengfly.tieba.post.adapters.base
import android.content.Context
import android.view.ViewGroup
import com.huanchengfly.tieba.post.components.MyViewHolder
abstract class BaseMultiTypeAdapter<Item>(
context: Context
) : BaseAdapter<Item>(
context
) {
protected abstract fun getItemLayoutId(
itemType: Int
): Int
protected abstract fun getViewType(
position: Int,
item: Item
): Int
final override fun getItemViewType(position: Int): Int {
return getViewType(position, getItem(position))
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder =
MyViewHolder(context, getItemLayoutId(viewType))
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.setItemOnClickListener {
onItemClickListener?.onClick(holder, getItem(position), position)
}
holder.setItemOnLongClickListener {
onItemLongClickListener?.onLongClick(holder, getItem(position), position) ?: false
}
convert(holder, getItem(position), position, getItemViewType(position))
}
protected abstract fun convert(
viewHolder: MyViewHolder,
item: Item,
position: Int,
viewType: Int
)
} | 0 | Kotlin | 0 | 0 | 34c341be0e706810febda54ea68cbd38955502d8 | 1,294 | TiebaLite | Apache License 2.0 |
exposed/src/main/kotlin/com/huanshankeji/exposed/Slice.kt | huanshankeji | 407,303,262 | false | {"Kotlin": 83098} | package com.huanshankeji.exposed
import org.jetbrains.exposed.sql.ColumnSet
/**
* To simplify the SQL in some expression queries.
* For example `Dual.slice(exists(Table.emptySlice().select(op))).selectAll()` generates a SQL with no columns which is simpler.
*/
fun ColumnSet.emptySlice() =
slice(emptyList())
| 3 | Kotlin | 0 | 5 | f2bd735dc410abf8510b2cdb90510c0d422b7504 | 318 | kotlin-common | Apache License 2.0 |
app/src/main/java/com/example/myapplication/LoadClassActivity.kt | treko50 | 698,150,961 | false | {"Kotlin": 47733} | package com.example.myapplication
import android.app.*
import android.content.ContentValues
import android.content.ContentValues.TAG
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.*
import com.google.firebase.database.*
import com.google.firebase.firestore.CollectionReference
import com.google.firebase.firestore.FirebaseFirestore
import java.lang.Exception
import java.util.*
import kotlin.collections.ArrayList
class LoadClassActivity: Activity() {
private var mUniversityText: AutoCompleteTextView? = null
private var mSchoolDepartmentText: AutoCompleteTextView? = null
private var mClassNameText: EditText? = null
private var textViewData: TextView? = null
private var db : FirebaseDatabase? = FirebaseDatabase.getInstance()
private var notebookRef : DatabaseReference? = db!!.getReference("Notebooks")
internal lateinit var getClasses: MutableList<Classes>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.load_class)
mUniversityText = findViewById<View>(R.id.autocompleteUni2) as AutoCompleteTextView
mSchoolDepartmentText = findViewById<View>(R.id.autocompleteDep2) as AutoCompleteTextView
mClassNameText = findViewById<View>(R.id.title2) as EditText
getClasses = ArrayList()
val unis = resources.getStringArray(R.array.university)
val uniAdapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, unis)
mUniversityText!!.setAdapter(uniAdapter)
val depart = resources.getStringArray(R.array.departments)
val departAdapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, depart)
mSchoolDepartmentText!!.setAdapter(departAdapter)
val cancelButton = findViewById<View>(R.id.cancelButton2) as Button
cancelButton.setOnClickListener {
Log.i(ContentValues.TAG, "Entered cancelButton.OnClickListener.onClick()")
// TODO - Indicate result and finish
setResult(Activity.RESULT_CANCELED);
finish();
}
// TODO - Set up OnClickListener for the Reset Button
val resetButton = findViewById<View>(R.id.resetButton2) as Button
resetButton.setOnClickListener {
Log.i(ContentValues.TAG, "Entered resetButton.OnClickListener.onClick()")
mClassNameText!!.setText("")
mSchoolDepartmentText!!.setText("")
mUniversityText!!.setText("")
}
// Set up OnClickListener for the Submit Button
val searchButton = findViewById<View>(R.id.searchButton) as Button
searchButton.setOnClickListener {
Log.i(ContentValues.TAG, "Entered searchButton.OnClickListener.onClick()")
// TODO - gather ToDoItem data
val classString: String = mClassNameText?.text.toString()
val universityString: String = mUniversityText?.text.toString()
val departmentString: String = mSchoolDepartmentText?.text.toString()
notebookRef!!.addValueEventListener(object: ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
getClasses.clear()
var single: Classes? = null
Log.e("SLackr", dataSnapshot.toString())
for(postSnap in dataSnapshot.children)
{
try {
single = postSnap.getValue(Classes::class.java)
Log.e("SLackr", single.toString() )
var group = String()
when(single!!.groupSize)
{
Classes.GroupSize.TWO ->
{
group = 2.toString()
}
Classes.GroupSize.THREE ->
{
group = 3.toString()
}
Classes.GroupSize.FOUR ->
{
group = 4.toString()
}
Classes.GroupSize.FIVEORMORE ->
{
group = 10.toString()
}
}
if(single!!.className == classString && single!!.university == universityString && single!!.schoolDepartment == departmentString && single!!.numStudents.toInt() < group.toInt() ){
getClasses.add(single!!)
}
}
catch (e: Exception){
Log.e(TAG, e.toString())
}
}
Log.e("getC",getClasses.toString())
if(getClasses.size > 0)
{
val intent = Intent(this@LoadClassActivity, ListClassActivity::class.java)
intent.putExtra("mylist", getClasses as ArrayList<Classes>)
startActivity(intent)
}
else{
val toast = Toast.makeText(applicationContext, "There are no Study Groups that match your Criteria", Toast.LENGTH_LONG)
toast.show()
}
}
override fun onCancelled(databaseError : DatabaseError) {
Log.e("cancel", databaseError.toString())
}
})
finish()
}
}
} | 0 | Kotlin | 0 | 0 | 6fe9f0a2bdc639d1b4e5933bdf1e55b91611106e | 5,868 | slackr | MIT License |
connekted-operator/src/main/kotlin/io/github/cfraser/connekted/operator/api/v0/MessagingApplicationController.kt | c-fraser | 420,198,834 | false | null | /*
Copyright 2021 c-fraser
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package io.github.cfraser.connekted.operator.api.v0
import io.github.cfraser.connekted.common.MessagingApplicationData
import io.github.cfraser.connekted.operator.registry.MessagingApplicationRegistry
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiParam
import java.util.Optional
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.reactor.mono
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import reactor.core.publisher.Mono
/**
* [MessagingApplicationController] is a reactive [RestController] for retrieving
* [MessagingApplicationData] corresponding to running *messaging applications*.
*
* @property messagingApplicationRegistry the [MessagingApplicationRegistry] to get
* [MessagingApplicationData] from
*/
@Api
@RestController
@RequestMapping("\${connekted.v0.api.path}/messaging-application")
internal class MessagingApplicationController(
private val messagingApplicationRegistry: MessagingApplicationRegistry
) {
@ApiOperation(
value = "Get the messaging applications.", produces = MediaType.APPLICATION_JSON_VALUE)
@GetMapping("")
fun getAll(): Mono<Set<MessagingApplicationData>> {
return mono(Dispatchers.Default) { messagingApplicationRegistry.getAll() }
}
@ApiOperation(value = "Get a messaging application.", produces = MediaType.APPLICATION_JSON_VALUE)
@GetMapping("/{name}")
fun get(
@PathVariable @ApiParam("The name of the messaging application.") name: String
): Mono<ResponseEntity<MessagingApplicationData>> {
return mono(Dispatchers.Default) { messagingApplicationRegistry[name] }.map { data ->
ResponseEntity.of(Optional.ofNullable(data))
}
}
}
| 0 | Kotlin | 0 | 2 | 17affcb232a20ea4f8489d915ab915dd724333e1 | 2,548 | connekted | Apache License 2.0 |
app/src/main/java/io/github/takusan23/coneco/ui/component/MergeHlsConfigComponent.kt | takusan23 | 474,671,887 | false | {"Kotlin": 198254, "Java": 16696} | package io.github.takusan23.coneco.ui.component
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import io.github.takusan23.coneco.R
import io.github.takusan23.conecohls.data.MultiVariantPlaylist
/**
* プレイリスト(m3u8)のUrl入力欄
*
* @param modifier [Modifier]
* @param m3u8Url m3u8のプレイリストがあるURL
* @param onM3u8UrlChange URLが変わったら呼ばれる
* @param onRequestClick 画質一覧取得ボタンを押したら呼ばれる
* */
@Composable
fun MergeHlsPlaylistUrlConfigComponent(
modifier: Modifier = Modifier,
m3u8Url: String,
onM3u8UrlChange: (String) -> Unit,
onRequestClick: () -> Unit,
) {
// 開いたら速攻フォーカスをあてるための
val focusRequester = remember { FocusRequester() }
LaunchedEffect(key1 = Unit, block = {
focusRequester.requestFocus()
})
Surface(
modifier = modifier,
shape = RoundedCornerShape(20.dp),
color = MaterialTheme.colorScheme.primaryContainer,
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(10.dp)
) {
Text(
text = stringResource(id = R.string.merge_video_hls_config_url_message),
fontSize = 18.sp,
)
OutlinedTextField(
modifier = Modifier
.fillMaxWidth()
.padding(5.dp)
.focusRequester(focusRequester),
value = m3u8Url,
label = { Text(text = stringResource(id = R.string.merge_video_hls_config_url_label)) },
maxLines = 1,
singleLine = true,
onValueChange = onM3u8UrlChange
)
Button(
modifier = Modifier.align(alignment = Alignment.End),
onClick = onRequestClick
) {
Text(text = stringResource(id = R.string.merge_video_hls_config_url_button))
Spacer(modifier = Modifier.size(ButtonDefaults.IconSpacing))
Icon(painter = painterResource(id = R.drawable.ic_outline_language_24), contentDescription = null)
}
}
}
}
/**
* 画質一覧を表示する
*
* @param modifier [Modifier]
* @param list 画質一覧
* @param onClick 選んだ画質
* @param selectUrl 選択中のプレイリストURL
* */
@Composable
fun MergeHlsQualityListConfigComponent(
modifier: Modifier = Modifier,
list: List<MultiVariantPlaylist>,
selectUrl: String,
onClick: (MultiVariantPlaylist) -> Unit,
) {
Surface(
modifier = modifier,
shape = RoundedCornerShape(20.dp),
color = MaterialTheme.colorScheme.primaryContainer
) {
Column {
Row(
modifier = Modifier.padding(5.dp),
verticalAlignment = Alignment.CenterVertically
) {
Icon(
modifier = Modifier.size(30.dp),
painter = painterResource(id = R.drawable.ic_outline_language_24),
contentDescription = null
)
Text(
modifier = Modifier.weight(1f),
text = stringResource(id = R.string.merge_video_hls_config_quality_list_title),
fontSize = 18.sp,
)
}
LazyColumn {
items(list) { item ->
HlsQualityListItem(
modifier = Modifier.padding(start = 5.dp, end = 5.dp),
data = item,
onClick = onClick,
isChecked = item.url == selectUrl
)
Divider(modifier = Modifier.padding(start = 5.dp, end = 5.dp))
}
}
}
}
}
/**
* Hls画質一覧の各項目
*
* @param modifier [Modifier]
* @param data 画質情報
* @param isChecked チェックマークをつけるならtrue
* @param onClick 押したとき
* */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun HlsQualityListItem(
modifier: Modifier = Modifier,
data: MultiVariantPlaylist,
isChecked: Boolean,
onClick: (MultiVariantPlaylist) -> Unit,
) {
Surface(
modifier = modifier,
color = Color.Transparent,
onClick = { onClick(data) }
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Column(modifier = Modifier.weight(1f)) {
if (data.resolution != null) {
Text(
modifier = Modifier.padding(3.dp),
text = "${stringResource(id = R.string.merge_video_hls_config_quality_list_resolution)}:${data.resolution}",
fontSize = 20.sp
)
}
if (data.bandWidth != null) {
Text(
modifier = Modifier.padding(3.dp),
text = "${stringResource(id = R.string.merge_video_hls_config_quality_list_bitrate)}:${data.bandWidth}",
)
}
Text(
modifier = Modifier.padding(3.dp),
text = "${stringResource(id = R.string.merge_video_hls_config_quality_list_playlist)}:${data.url}",
overflow = TextOverflow.Ellipsis,
maxLines = 1,
)
}
if (isChecked) {
Icon(
modifier = Modifier.padding(10.dp),
painter = painterResource(id = R.drawable.ic_outline_check_24),
contentDescription = null
)
}
}
}
} | 0 | Kotlin | 0 | 1 | eeefb31e9f5cd8535073e78e6a7204d936949964 | 6,276 | Coneco | Apache License 2.0 |
src/main/kotlin/me/lensvol/blackconnect/config/sections/ConfigSection.kt | lensvol | 261,833,378 | false | null | package me.lensvol.blackconnect.config.sections
import com.intellij.openapi.project.Project
import me.lensvol.blackconnect.settings.BlackConnectProjectSettings
import javax.swing.JPanel
abstract class ConfigSection(project: Project) {
abstract val panel: JPanel
abstract fun loadFrom(configuration: BlackConnectProjectSettings)
abstract fun saveTo(configuration: BlackConnectProjectSettings)
abstract fun isModified(configuration: BlackConnectProjectSettings): Boolean
}
| 6 | Kotlin | 3 | 28 | 9f41da5818b7e1dac313ef4700c774094327de3b | 492 | intellij-blackconnect | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.