path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/steleot/jetpackcompose/playground/compose/material3/SearchBarScreen.kt
Vivecstel
338,792,534
false
{"Kotlin": 1538487}
package com.steleot.jetpackcompose.playground.compose.material3 import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Star import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.ListItem import androidx.compose.material3.MaterialTheme import androidx.compose.material3.SearchBar import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.steleot.jetpackcompose.playground.navigation.graph.Material3NavRoutes import com.steleot.jetpackcompose.playground.resources.R import com.steleot.jetpackcompose.playground.ui.base.material.DefaultScaffold private const val URL = "material3/SearchBarScreen.kt" @Composable fun SearchBarScreen() { DefaultScaffold( title = Material3NavRoutes.SearchBar, link = URL, ) { Column( modifier = Modifier .fillMaxSize() .padding(paddingValues = it), ) { SearchBarExample() } } } @OptIn(ExperimentalMaterial3Api::class) @Composable private fun ColumnScope.SearchBarExample() { var text by rememberSaveable { mutableStateOf("") } var active by rememberSaveable { mutableStateOf(false) } SearchBar( modifier = Modifier .fillMaxWidth(), query = text, onQueryChange = { text = it }, onSearch = { active = false }, active = active, onActiveChange = { active = it }, placeholder = { Text(text = stringResource(id = R.string.search_hint)) }, leadingIcon = { Icon(Icons.Default.Search, contentDescription = null) }, trailingIcon = { Icon(Icons.Default.MoreVert, contentDescription = null) }, ) { repeat(4) { idx -> val resultText = stringResource(id = R.string.search_suggestion, idx) ListItem( headlineContent = { Text(text = resultText) }, supportingContent = { Text(text = stringResource(id = R.string.search_additional_info)) }, leadingContent = { Icon(Icons.Filled.Star, contentDescription = null) }, modifier = Modifier .clickable { text = resultText active = false } .fillMaxWidth() .padding(horizontal = 16.dp, vertical = 4.dp) ) } } LazyColumn( modifier = Modifier.weight(1f), contentPadding = PaddingValues(all = 16.dp), verticalArrangement = Arrangement.spacedBy(8.dp) ) { val list = List(100) { it } items(count = list.size) { Text( text = stringResource(id = R.string.item, list[it]), modifier = Modifier .fillMaxWidth() .border(width = 1.dp, color = MaterialTheme.colorScheme.primary) .padding(horizontal = 16.dp, vertical = 8.dp) ) } } }
1
Kotlin
46
346
0161d9c7bf2eee53270ba2227a61d71ba8292ad0
3,999
Jetpack-Compose-Playground
Apache License 2.0
app/src/main/java/villalobos/diego/uni/Data/Comment.kt
DiegoVillalobosFlores
134,133,559
false
null
package villalobos.diego.uni.Data import java.io.Serializable data class Comment (var nombre:String = "", var codigo:String = "", var date:String = "", var comment:String = "") : Serializable
0
Kotlin
0
0
f325ff591b158929f21c9e257a0874e8a5d07a8e
253
Uni-Android
MIT License
wasi-emscripten-fs/src/commonMain/kotlin/op/unlink/UnlinkFile.kt
illarionov
769,429,996
false
{"Kotlin": 1838071}
/* * Copyright 2024, the wasm-sqlite-open-helper project authors and contributors. Please see the AUTHORS file * for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. * SPDX-License-Identifier: Apache-2.0 */ package ru.pixnews.wasm.sqlite.open.helper.host.filesystem.op.unlink import ru.pixnews.wasm.sqlite.open.helper.host.filesystem.error.UnlinkError import ru.pixnews.wasm.sqlite.open.helper.host.filesystem.model.BaseDirectory import ru.pixnews.wasm.sqlite.open.helper.host.filesystem.op.FileSystemOperation public data class UnlinkDirectory( public val path: String, public val baseDirectory: BaseDirectory = BaseDirectory.CurrentWorkingDirectory, ) { public companion object : FileSystemOperation<UnlinkDirectory, UnlinkError, Unit> { override val tag: String = "unlinkdir" } }
0
Kotlin
1
3
5f513e2413987ce681f12ea8e14a2aff2c56a7fd
875
wasm-sqlite-open-helper
Apache License 2.0
ktfx-listeners/tests/src/javafx/scene/media/MediaPlayerTest.kt
hendraanggrian
102,934,147
false
null
package ktfx.listeners import javafx.scene.media.MediaMarkerEvent import javafx.scene.media.MediaPlayer import com.hendraanggrian.ktfx.test.BaseMediaPlayerTest import kotlin.test.Ignore @Ignore class MediaPlayerTest : BaseMediaPlayerTest() { override fun MediaPlayer.callOnError(action: () -> Unit) = onError(action) override fun MediaPlayer.callOnMarker(action: (MediaMarkerEvent) -> Unit) = onMarker(action) override fun MediaPlayer.callOnEndOfMedia(action: () -> Unit) = onEndOfMedia(action) override fun MediaPlayer.callOnReady(action: () -> Unit) = onReady(action) override fun MediaPlayer.callOnPlaying(action: () -> Unit) = onPlaying(action) override fun MediaPlayer.callOnPaused(action: () -> Unit) = onPaused(action) override fun MediaPlayer.callOnStopped(action: () -> Unit) = onStopped(action) override fun MediaPlayer.callOnHalted(action: () -> Unit) = onHalted(action) override fun MediaPlayer.callOnRepeat(action: () -> Unit) = onRepeat(action) override fun MediaPlayer.callOnStalled(action: () -> Unit) = onStalled(action) }
1
Kotlin
2
15
ea4243fb75edb70d6710e7488fa08834084f6169
1,082
ktfx
Apache License 2.0
lib/src/main/kotlin/pro/jaitl/dynamodb/mapper/converter/collection/MapConverter.kt
jaitl
405,956,206
false
{"Kotlin": 84872}
package pro.jaitl.dynamodb.mapper.converter.collection import pro.jaitl.dynamodb.mapper.KDynamoMapperReader import pro.jaitl.dynamodb.mapper.KDynamoMapperWriter import pro.jaitl.dynamodb.mapper.UnsupportedKeyTypeException import pro.jaitl.dynamodb.mapper.attribute.mapAttribute import pro.jaitl.dynamodb.mapper.converter.TypeConverter import software.amazon.awssdk.services.dynamodb.model.AttributeValue import kotlin.reflect.KClass import kotlin.reflect.KType /** * Converts Map<String, *> to AttributeValue and vice versa. * * DynamoDb AttributeValue supports map with string key maps only. */ class MapConverter : TypeConverter<Map<*, *>> { /** * Reads DynamoDb attribute map to Map<String, *> * @throws UnsupportedKeyTypeException when map's key has type other than string type. */ override fun read(reader: KDynamoMapperReader, attr: AttributeValue, kType: KType): Map<*, *> { val keyType = kType.arguments.first().type!! val keyClazz = keyType.classifier as KClass<*> if (keyClazz != String::class) { throw UnsupportedKeyTypeException( "Map doesn't support type '$keyClazz' as key. " + "Only 'String' type supported as key" ) } val valueType = kType.arguments.last().type!! return attr.m() .mapNotNull { it.key!! to reader.readValue(it.value!!, valueType) } .toMap() } /** * Writes Map<String, *> to DynamoDb attribute map * @throws UnsupportedKeyTypeException when map's key has type other than string type. */ override fun write(writer: KDynamoMapperWriter, value: Any, kType: KType): AttributeValue { val collection = value as Map<*, *> val keyType = kType.arguments.first().type!! val keyClazz = keyType.classifier as KClass<*> if (keyClazz != String::class) { throw UnsupportedKeyTypeException( "Map doesn't support type '$keyClazz' as key. " + "Only 'String' type supported as key" ) } val valueType = kType.arguments.last().type!! val map = collection.mapKeys { it.key as String } .mapValues { writer.writeValue(it.value!!, valueType) } return mapAttribute(map) } /** * @return type of this converter */ override fun type(): KClass<Map<*, *>> = Map::class }
4
Kotlin
0
2
7ab37b2c32ba6831af0f0fb1308c23bcacf549ca
2,426
kDynamoMapper
MIT License
src/main/kotlin/day02.kt
robfletcher
724,814,488
false
{"Kotlin": 3615}
import java.io.Reader fun main() { fun parseHand(group: String) = Regex("""(\d+) (\w+)""") .findAll(group) .map(MatchResult::groupValues) .associate { (_, n, color) -> color to n.toInt() } fun part1(input: Reader) = input.useLines { lines -> val bag = mapOf("red" to 12, "green" to 13, "blue" to 14) lines.sumOf { line -> val id = checkNotNull(Regex("""Game (\d+):""").find(line)).groupValues[1].toInt() val possible = line.substringAfter(':').split(';').all { group -> parseHand(group).all { it.value <= bag.getValue(it.key) } } if (possible) id else 0 } } fun part2(input: Reader) = input.useLines { lines -> lines.fold(0) { acc, line -> line .substringAfter(':') .split(';') .fold(mapOf("red" to 0, "green" to 0, "blue" to 0)) { bag, group -> parseHand(group).let { hand -> bag.mapValues { (color, n) -> maxOf(n, hand[color] ?: 0) } } } .run { acc + values.reduce(Int::times) } } } val testInput = """ Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green""".trimIndent() assert(part1(testInput.reader()) == 8) assert(part2(testInput.reader()) == 2286) execute("day02", "Part 1", ::part1) execute("day02", "Part 2", ::part2) }
0
Kotlin
0
0
d37411ca9d19454daca1b5d4a490e826bab509e0
1,644
aoc2023
The Unlicense
app/src/main/java/io/golos/golos/screens/editor/EditorFooter.kt
bitwheeze
544,185,390
true
{"Kotlin": 1064225, "Java": 178130}
package io.golos.golos.screens.editor import android.annotation.TargetApi import android.content.Context import android.os.Build import android.text.Editable import android.text.TextWatcher import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.FrameLayout import android.widget.TextView import io.golos.golos.R import io.golos.golos.utils.StringValidator import io.golos.golos.utils.nextInt data class EditorFooterState(val showTagsEditor: Boolean = false, val tagsValidator: io.golos.golos.utils.StringValidator? = null, val tags: ArrayList<String> = ArrayList(), val tagsListener: EditorFooter.TagsListener? = null) class EditorFooter : FrameLayout { private var mTagsLayout: ViewGroup private var mAddBtn: View private var mErrorTv: TextView private var mAddTagsText: TextView private var mValidator: StringValidator = object : StringValidator { override fun validate(input: String): Pair<Boolean, String> = Pair(true, "") } @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : super(context, attrs, defStyleAttr) @TargetApi(Build.VERSION_CODES.LOLLIPOP) constructor( context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) init { LayoutInflater.from(context).inflate(R.layout.v_editor_footer, this) mTagsLayout = findViewById(R.id.tags_lo) mAddBtn = findViewById(R.id.add_btn) mErrorTv = findViewById(R.id.error_text) mAddTagsText = findViewById(R.id.add_tags_label) } var state: EditorFooterState = EditorFooterState() set(value) { if (field == value) { return } field = value value.tagsValidator?.let { mValidator = field.tagsValidator as StringValidator } if (value.showTagsEditor) { mTagsLayout.visibility = View.VISIBLE mErrorTv.visibility = View.VISIBLE } else { mTagsLayout.visibility = View.GONE mAddTagsText.visibility = View.GONE mErrorTv.visibility = View.GONE } if (value.tags.size != (mTagsLayout.childCount - 1)) { mTagsLayout.removeView(mAddBtn) if (mTagsLayout.childCount > value.tags.size) { mTagsLayout.removeViews(value.tags.size, mTagsLayout.childCount - value.tags.size) (0 until mTagsLayout.childCount).forEach { (mTagsLayout.getChildAt(it) as? EditText)?.setText(value.tags[it]) } } else { (mTagsLayout.childCount until value.tags.size).forEach { val newView = inflateNewEditText(value.tags[it]) mTagsLayout.addView(newView) } (0 until mTagsLayout.childCount).forEach { val et = (mTagsLayout.getChildAt(it) as EditText) if (et.text.toString() != value.tags[it]) { et.setText(value.tags[it]) } } } mTagsLayout.addView(mAddBtn) } if (!mAddBtn.hasOnClickListeners()) mAddBtn.setOnClickListener { if (mTagsLayout.childCount < 6) { if (mTagsLayout.childCount == 1) { mTagsLayout.removeView(mAddBtn) val newView = inflateNewEditText() mTagsLayout.addView(newView) mTagsLayout.addView(mAddBtn) newView.requestFocus() mErrorTv.text = "" } else { val prelast = mTagsLayout.getChildAt(mTagsLayout.childCount - 2) as EditText if (!prelast.text.isEmpty()) { val validatorOut = mValidator.validate(prelast.text.toString()) if (validatorOut.first) { mTagsLayout.removeView(mAddBtn) val newView = inflateNewEditText() mTagsLayout.addView(newView) mTagsLayout.addView(mAddBtn) newView.requestFocus() mErrorTv.text = "" } else { mErrorTv.text = validatorOut.second } } } } else { mErrorTv.text = resources.getString(R.string.to_much_tags) } } } private fun inflateNewEditText(startText: String? = null): EditText { val view = LayoutInflater.from(context).inflate(R.layout.v_editor_footer_tag_et, mTagsLayout, false) as EditText view.id = nextInt() if (startText != null) view.setText(startText) view.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(p0: Editable?) { if (p0 != null) onTextChanged(p0.toString()) } override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { } override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { if (p0?.length == 0 && p1 == 0 && p3 == 0) { onDeleteEt(view) } } }) view.setOnEditorActionListener({ _, _, _ -> if (view.text.isNotEmpty()) { mAddBtn.callOnClick() } true }) view.isFocusableInTouchMode = true return view } private fun onDeleteEt(et: EditText) { mTagsLayout.removeView(et) } private fun onTextChanged(text: String) { val tagsList = (0 until mTagsLayout.childCount - 1) .map { (mTagsLayout.getChildAt(it) as EditText).text.toString() } .toList() state.tagsListener?.onTagsSubmit(tagsList) } interface TagsListener { fun onTagsSubmit(tags: List<String>) } }
0
null
0
0
8203f422dc7e5d5b0b2c41dafd539c225f1a4de1
6,735
golos-android
MIT License
app/src/main/java/com/wcsm/minhastarefas/AddTaskActivity.kt
WallaceMartinsTI
737,301,198
false
{"Kotlin": 48096}
package com.wcsm.minhastarefas import android.annotation.SuppressLint import android.app.AlarmManager import android.app.DatePickerDialog import android.app.PendingIntent import android.app.TimePickerDialog import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.res.Configuration import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.DatePicker import android.widget.TimePicker import android.widget.Toast import com.google.android.material.textfield.TextInputLayout import com.wcsm.minhastarefas.database.TaskDAO import com.wcsm.minhastarefas.databinding.ActivityAddTaskBinding import com.wcsm.minhastarefas.model.DailyTask import com.wcsm.minhastarefas.model.Task import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.text.SimpleDateFormat import java.util.Calendar import java.util.Date import java.util.Locale class AddTaskActivity : AppCompatActivity(), DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener { private val binding by lazy { ActivityAddTaskBinding.inflate(layoutInflater) } private lateinit var taskToEdit: Task private lateinit var actualDate: String private var day = 0 private var month = 0 private var year = 0 private var hour = 0 private var minute = 0 private var savedDay = 0 private var savedMonth = 0 private var savedYear = 0 private var savedTime = "" private var generateWeeklyTasks = false private var isDailyTasks = false private var isLoading = false private var coroutineScope: CoroutineScope? = null private lateinit var taskDAO: TaskDAO override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) taskDAO = TaskDAO(applicationContext) val locale = Locale("pt", "BR") Locale.setDefault(locale) val config = Configuration() config.setLocale(locale) resources.updateConfiguration(config, baseContext.resources.displayMetrics) getDateTimeCalendar() actualDate = "${day}/${month + 1}/${year} - $hour:$minute" generateWeeklyTasksHandler() val bundle = intent.extras if(bundle != null) { val screenTitle = bundle.getString("screen_title") val btnText = bundle.getString("button_text") binding.tvNewTaskScreenTitle.text = screenTitle binding.btnAddOrUpdate.text = btnText if(bundle.containsKey("task")) { taskToEdit = bundle.getParcelable("task")!! } } with(binding) { btnBack.setOnClickListener { finish() } binding.tvDatetimePicked.text = actualDate pickDate() val titleField = layoutTitle val mondayField = layoutMonday cbGenerateWeeklyTasks.setOnClickListener { generateWeeklyTasks = binding.cbGenerateWeeklyTasks.isChecked generateWeeklyTasksHandler() } // Fill fields with task info when updating task if(btnAddOrUpdate.text == "ATUALIZAR") { editTextTitle.setText(taskToEdit.title) editTextDescription.setText(taskToEdit.description) cbAllowNotification.isChecked = taskToEdit.allowNotification > 0 tvDatetimePicked.text = taskToEdit.dueDate } btnAddOrUpdate.setOnClickListener { if(btnAddOrUpdate.text == "ADICIONAR") { val title = binding.editTextTitle.text.toString() val validation = validateTitle(titleField, title) val dueDate = tvDatetimePicked.text.toString() val description = binding.editTextDescription.text.toString() val allowNotification = if(binding.cbAllowNotification.isChecked) 1 else 0 if(validation) { isDailyTasks = false addTask(title, description, dueDate, allowNotification) } } else if(btnAddOrUpdate.text == "ATUALIZAR") { val title = binding.editTextTitle.text.toString() val validation = validateTitle(titleField, title) val dueDate = tvDatetimePicked.text.toString() if(validation) { updateTask(taskToEdit, title, dueDate) } } } btnGenerate.setOnClickListener { isLoading = true toggleLoading() val monday = binding.editTextMonday.text.toString() // 25 -> Actual Day: val validation = validateMonday(mondayField, monday) if(validation) { isDailyTasks = true val actualDay = "$monday/${month + 1}/$year" val dailyTasks = listOf( DailyTask("Levantar", "Hora de levantar e começar o dia!!!", "$actualDay - 06:00"), DailyTask("Hora da Caminhada", "Faça uma caminhada para energizar o dia!","$actualDay - 06:05"), DailyTask("Estudar Inglês", "Bora melhorar o Inglês, VAMO!! VAMO!!","$actualDay - 07:00"), DailyTask("Hora de Trabalhar", "Começe a trabalhar, nos vemos em breve!", "$actualDay - 08:00"), DailyTask("Tarefas de Casa", "Realizar as tarefas de casa.", "$actualDay - 17:05"), DailyTask("Começar os Estudos", "Android? Inglês? Outros? Apenas ESTUDE!", "$actualDay - 18:20"), DailyTask("Tempo Livre", "O Fim do dia chegou, faça o que quiser!!!", "$actualDay - 21:20"), ) addAllWeeklyTasks(dailyTasks) } else { isLoading = false toggleLoading() } } } } private fun toggleLoading() { if(isLoading) { with(binding) { btnGenerate.isEnabled = false cbGenerateWeeklyTasks.isEnabled = false pbLoading.visibility = View.VISIBLE tvMonday.visibility = View.INVISIBLE layoutMonday.visibility = View.INVISIBLE editTextMonday.visibility = View.INVISIBLE } } else { with(binding) { pbLoading.visibility = View.INVISIBLE btnGenerate.isEnabled = true cbGenerateWeeklyTasks.isEnabled = true tvMonday.visibility = View.VISIBLE layoutMonday.visibility = View.VISIBLE editTextMonday.visibility = View.VISIBLE } } } private fun addAllWeeklyTasks(tasks: List<DailyTask>) { coroutineScope = CoroutineScope(Dispatchers.Main) coroutineScope?.launch { tasks.forEach { addTask(it.title, it.description, it.dueDate, 1) delay(300) } Toast.makeText(applicationContext, "Tarefas Diárias criadas com sucesso!", Toast.LENGTH_SHORT).show() isLoading = false toggleLoading() finish() } } private fun addTask(title: String, description: String, dueDate: String, allowNotification: Int ) { val task = Task(-1, title, description, convertToSQLiteFormat(actualDate), convertToSQLiteFormat(actualDate), convertToSQLiteFormat(dueDate), allowNotification, 0, 0) if(taskDAO.save(task)) { if(!isDailyTasks) { Toast.makeText(applicationContext, "Tarefa registrada com sucesso!", Toast.LENGTH_SHORT).show() finish() } } } private fun updateTask(task: Task, title: String, dueDate: String) { val description = binding.editTextDescription.text.toString() val allowNotification = if(binding.cbAllowNotification.isChecked) 1 else 0 val task = Task(task.id, title, description, convertToSQLiteFormat(task.createdAt), convertToSQLiteFormat(actualDate), convertToSQLiteFormat(dueDate), allowNotification, 0, task.completed) if(taskDAO.update(task)) { Toast.makeText(applicationContext, "Tarefa atualizada com sucesso!", Toast.LENGTH_SHORT).show() finish() } } private fun validateTitle(titleField: TextInputLayout, title: String): Boolean { titleField.error = null if(title.isEmpty()) { titleField.error = "Digite o título da tarefa." return false } return true } private fun validateMonday(mondayField: TextInputLayout, mondayInputed: String?): Boolean { mondayField.error = null if(mondayInputed != null) { try { val monday = mondayInputed.toInt() if(monday <= 0 || monday > 31) { mondayField.error = "Informe um dia válido 1 à 31." return false } return true } catch (e: NumberFormatException) { e.printStackTrace() mondayField.error = "Dia inválido." return false } } else { mondayField.error = "Dia nulo." return false } } private fun generateWeeklyTasksHandler() { if(generateWeeklyTasks) { enablingAddTaskOptions("DISABLE") enablingGenerateWeeklyTasksOptions("ENABLE") } else { enablingAddTaskOptions("ENABLE") enablingGenerateWeeklyTasksOptions("DISABLE") } } private fun enablingAddTaskOptions(option: String) { if(option == "ENABLE") { with(binding) { layoutTitle.isEnabled = true layoutDescription.isEnabled = true cbAllowNotification.isEnabled = true btnDatetimePicker.isEnabled = true tvDatetimePicked.isEnabled = true btnAddOrUpdate.isEnabled = true btnGenerate.isEnabled = true } } else { with(binding) { layoutTitle.isEnabled = false layoutDescription.isEnabled = false cbAllowNotification.isEnabled = false btnDatetimePicker.isEnabled = false tvDatetimePicked.isEnabled = false btnAddOrUpdate.isEnabled = false btnGenerate.isEnabled = false } } } private fun enablingGenerateWeeklyTasksOptions(option: String) { if(option == "ENABLE") { with(binding) { tvMonday.isEnabled = true layoutMonday.isEnabled = true btnGenerate.isEnabled = true } } else { with(binding) { tvMonday.isEnabled = false layoutMonday.isEnabled = false btnGenerate.isEnabled = false } } } private fun convertToSQLiteFormat(inputDate: String): String { val inputFormat = SimpleDateFormat("dd/MM/yyyy - HH:mm", Locale.getDefault()) val outputFormat = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) val date = inputFormat.parse(inputDate) ?: Date() return outputFormat.format(date) } private fun getDateTimeCalendar() { val cal = Calendar.getInstance() day = cal.get(Calendar.DAY_OF_MONTH) month = cal.get(Calendar.MONTH) year = cal.get(Calendar.YEAR) hour = cal.get(Calendar.HOUR_OF_DAY) minute = cal.get(Calendar.MINUTE) } private fun pickDate() { binding.btnDatetimePicker.setOnClickListener { getDateTimeCalendar() val datePickerDialog = DatePickerDialog(this, this, year, month, day) datePickerDialog.datePicker.minDate = System.currentTimeMillis() - 1000 datePickerDialog.show() } } override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) { savedDay = dayOfMonth savedMonth = month savedYear = year getDateTimeCalendar() val timePickerDialog = TimePickerDialog(this, R.style.MyTimePickerStyle, this, hour, minute, true) timePickerDialog.show() } @SuppressLint("SetTextI18n") override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) { savedTime = String.format("%02d:%02d", hourOfDay, minute) //formatTime(hourOfDay, minute) binding.tvDatetimePicked.text = "$savedDay/${savedMonth + 1}/$savedYear - $savedTime" } override fun onDestroy() { coroutineScope?.cancel() super.onDestroy() } }
0
Kotlin
0
1
3aea9ce1793b6cb6c4739aa868edfc7e3165bbed
13,279
minhas-tarefas
MIT License
RxJava/src/main/kotlin/chapter05/schedulers/SingleSchedulerExample.kt
Im-Tae
260,676,018
false
null
package chapter05.schedulers import common.CommonUtils import common.Log import io.reactivex.Observable import io.reactivex.schedulers.Schedulers class SingleSchedulerExample { fun emit() { val numbers = Observable.range(100, 5) val chars = Observable.range(0, 5) .map(CommonUtils()::numberToAlphabet) numbers.subscribeOn(Schedulers.single()) .subscribe { data -> Log.it(data) } chars.subscribeOn(Schedulers.single()) .subscribe { data -> Log.it(data) } CommonUtils.sleep(500) } } fun main() { val demo = SingleSchedulerExample() demo.emit() }
0
Kotlin
12
5
819e4234069f03a822f8defa15cc2d37cc58fb25
640
Blog_Example
MIT License
src/main/kotlin/org/jetbrains/intellij/tasks/DownloadRobotServerPluginTask.kt
JetBrains
33,932,778
false
null
package org.jetbrains.intellij.tasks import org.gradle.api.GradleException import org.gradle.api.file.DirectoryProperty import org.gradle.api.internal.ConventionTask import org.gradle.api.model.ObjectFactory import org.gradle.api.provider.Property import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.OutputDirectory import org.gradle.api.tasks.TaskAction import org.jetbrains.intellij.IntelliJPluginConstants.INTELLIJ_DEPENDENCIES import org.jetbrains.intellij.IntelliJPluginConstants.VERSION_LATEST import org.jetbrains.intellij.Version import org.jetbrains.intellij.debug import org.jetbrains.intellij.logCategory import org.jetbrains.intellij.model.SpacePackagesMavenMetadata import org.jetbrains.intellij.model.XmlExtractor import org.jetbrains.intellij.utils.ArchiveUtils import java.io.File import java.net.URL import javax.inject.Inject @Suppress("UnstableApiUsage") open class DownloadRobotServerPluginTask @Inject constructor(objectFactory: ObjectFactory) : ConventionTask() { companion object { private const val METADATA_URL = "$INTELLIJ_DEPENDENCIES/com/intellij/remoterobot/robot-server-plugin/maven-metadata.xml" private const val OLD_ROBOT_SERVER_DEPENDENCY = "org.jetbrains.test:robot-server-plugin" private const val NEW_ROBOT_SERVER_DEPENDENCY = "com.intellij.remoterobot:robot-server-plugin" private const val NEW_ROBOT_SERVER_VERSION = "0.11.0" fun resolveLatestVersion(): String { debug(message = "Resolving latest Robot Server Plugin version") val url = URL(METADATA_URL) return XmlExtractor<SpacePackagesMavenMetadata>().unmarshal(url.openStream()).versioning?.latest ?: throw GradleException("Cannot resolve the latest Robot Server Plugin version") } /** * Resolves Plugin Verifier version. * If set to {@link IntelliJPluginConstants#VERSION_LATEST}, there's request to {@link #VERIFIER_METADATA_URL} * performed for the latest available verifier version. * * @return Plugin Verifier version */ fun resolveVersion(version: String?) = version?.takeIf { it != VERSION_LATEST } ?: resolveLatestVersion() fun getDependency(version: String) = when { Version.parse(version) >= Version.parse(NEW_ROBOT_SERVER_VERSION) -> NEW_ROBOT_SERVER_DEPENDENCY else -> OLD_ROBOT_SERVER_DEPENDENCY } } @Input val version: Property<String> = objectFactory.property(String::class.java) @InputFile val pluginArchive: Property<File> = objectFactory.property(File::class.java) @OutputDirectory val outputDir: DirectoryProperty = objectFactory.directoryProperty() private val archiveUtils = objectFactory.newInstance(ArchiveUtils::class.java) private val context = logCategory() @TaskAction fun downloadPlugin() { val target = outputDir.get().asFile archiveUtils.extract(pluginArchive.get(), target, context) } }
63
null
249
1,099
efe233f09e537ea62a3549612c9930cc915a0228
3,049
gradle-intellij-plugin
Apache License 2.0
app/src/main/java/it/log/tably/models/Game.kt
lorenzosimonigh
139,616,093
false
{"Kotlin": 53119}
package it.log.tably.models import it.log.tably.database.Database class Game (val reporter: Player, val date: String, val blueAttacker: Player, val redAttacker: Player, val redDefender: Player, val blueDefender: Player, val blueScore: Long = -1, val redScore: Long = -1, val key: String) { /* From FirebaseGame to Game model */ constructor (firebaseGame: FirebaseGame, key: String) : this( Database.players.getValue(firebaseGame.posterId), firebaseGame.date, Database.players.getValue(firebaseGame.bluAttack), Database.players.getValue(firebaseGame.redAttack), Database.players.getValue(firebaseGame.redDefense), Database.players.getValue(firebaseGame.bluDefense), firebaseGame.bluScore, firebaseGame.redScore, key ) val score = """$blueScore - $redScore""" /* From Firebase map to Game model */ constructor (map: MutableMap.MutableEntry<out Any, HashMap<out Any, out Any>>) : this ( Database.players.getValue(map.value["posterId"] as String), map.value["date"] as String, Database.players.getValue(map.value["bluAttack"] as String), Database.players.getValue(map.value["redAttack"] as String), Database.players.getValue(map.value["redDefense"] as String), Database.players.getValue(map.value["bluDefense"] as String), map.value["bluScore"] as Long, map.value["redScore"] as Long, map.key as String ) }
0
Kotlin
0
0
814e1960fbb5f25828d3e2e837fa2ec8dc1bf2d2
1,585
Tably
Apache License 2.0
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/bold/Notetext.kt
Tlaster
560,394,734
false
{"Kotlin": 25133302}
package moe.tlaster.icons.vuesax.vuesaxicons.bold 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.BoldGroup public val BoldGroup.Notetext: ImageVector get() { if (_notetext != null) { return _notetext!! } _notetext = Builder(name = "Notetext", 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(8.75f, 3.5f) verticalLineTo(2.0f) curveTo(8.75f, 1.59f, 8.41f, 1.25f, 8.0f, 1.25f) curveTo(7.59f, 1.25f, 7.25f, 1.59f, 7.25f, 2.0f) verticalLineTo(3.56f) curveTo(7.5f, 3.53f, 7.73f, 3.5f, 8.0f, 3.5f) horizontalLineTo(8.75f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(16.75f, 3.56f) verticalLineTo(2.0f) curveTo(16.75f, 1.59f, 16.41f, 1.25f, 16.0f, 1.25f) curveTo(15.59f, 1.25f, 15.25f, 1.59f, 15.25f, 2.0f) verticalLineTo(3.5f) horizontalLineTo(16.0f) curveTo(16.27f, 3.5f, 16.5f, 3.53f, 16.75f, 3.56f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(16.75f, 3.56f) verticalLineTo(5.0f) curveTo(16.75f, 5.41f, 16.41f, 5.75f, 16.0f, 5.75f) curveTo(15.59f, 5.75f, 15.25f, 5.41f, 15.25f, 5.0f) verticalLineTo(3.5f) horizontalLineTo(8.75f) verticalLineTo(5.0f) curveTo(8.75f, 5.41f, 8.41f, 5.75f, 8.0f, 5.75f) curveTo(7.59f, 5.75f, 7.25f, 5.41f, 7.25f, 5.0f) verticalLineTo(3.56f) curveTo(4.3f, 3.83f, 3.0f, 5.73f, 3.0f, 8.5f) verticalLineTo(17.0f) curveTo(3.0f, 20.0f, 4.5f, 22.0f, 8.0f, 22.0f) horizontalLineTo(16.0f) curveTo(19.5f, 22.0f, 21.0f, 20.0f, 21.0f, 17.0f) verticalLineTo(8.5f) curveTo(21.0f, 5.73f, 19.7f, 3.83f, 16.75f, 3.56f) close() moveTo(12.0f, 16.75f) horizontalLineTo(8.0f) curveTo(7.59f, 16.75f, 7.25f, 16.41f, 7.25f, 16.0f) curveTo(7.25f, 15.59f, 7.59f, 15.25f, 8.0f, 15.25f) horizontalLineTo(12.0f) curveTo(12.41f, 15.25f, 12.75f, 15.59f, 12.75f, 16.0f) curveTo(12.75f, 16.41f, 12.41f, 16.75f, 12.0f, 16.75f) close() moveTo(16.0f, 11.75f) horizontalLineTo(8.0f) curveTo(7.59f, 11.75f, 7.25f, 11.41f, 7.25f, 11.0f) curveTo(7.25f, 10.59f, 7.59f, 10.25f, 8.0f, 10.25f) horizontalLineTo(16.0f) curveTo(16.41f, 10.25f, 16.75f, 10.59f, 16.75f, 11.0f) curveTo(16.75f, 11.41f, 16.41f, 11.75f, 16.0f, 11.75f) close() } } .build() return _notetext!! } private var _notetext: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
4,335
VuesaxIcons
MIT License
feature/detail/src/main/kotlin/team/duckie/app/android/feature/detail/screen/DetailScreen.kt
duckie-team
503,869,663
false
null
/* * Designed and developed by Duckie Team, 2022 * * Licensed under the MIT. * Please see full license: https://github.com/duckie-team/duckie-android/blob/develop/LICENSE */ @file:OptIn(ExperimentalMaterialApi::class) package team.duckie.app.android.feature.detail.screen import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.ModalBottomSheetValue import androidx.compose.material.pullrefresh.PullRefreshIndicator import androidx.compose.material.pullrefresh.pullRefresh import androidx.compose.material.pullrefresh.rememberPullRefreshState import androidx.compose.material.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.Layout import androidx.compose.ui.layout.layoutId import androidx.compose.ui.platform.LocalContext import kotlinx.coroutines.launch import okhttp3.internal.immutableListOf import org.orbitmvi.orbit.compose.collectAsState import team.duckie.app.android.common.android.network.NetworkUtil import team.duckie.app.android.common.compose.activityViewModel import team.duckie.app.android.common.compose.ui.ErrorScreen import team.duckie.app.android.common.compose.ui.LoadingScreen import team.duckie.app.android.common.compose.ui.dialog.DuckieSelectableBottomSheetDialog import team.duckie.app.android.common.compose.ui.dialog.DuckieSelectableType import team.duckie.app.android.common.compose.ui.dialog.ReportDialog import team.duckie.app.android.domain.examInstance.model.ExamStatus import team.duckie.app.android.feature.detail.common.DetailBottomLayout import team.duckie.app.android.feature.detail.common.TopAppCustomBar import team.duckie.app.android.feature.detail.screen.exam.ExamDetailContentLayout import team.duckie.app.android.feature.detail.screen.funding.FundingDetailContentLayout import team.duckie.app.android.feature.detail.screen.quiz.QuizDetailContentLayout import team.duckie.app.android.feature.detail.viewmodel.DetailViewModel import team.duckie.app.android.feature.detail.viewmodel.state.DetailState import team.duckie.quackquack.material.QuackColor @Composable internal fun DetailScreen( modifier: Modifier, viewModel: DetailViewModel = activityViewModel(), ) { val context = LocalContext.current val state = viewModel.collectAsState().value var isNetworkAvailable: Boolean by remember { mutableStateOf(false) } isNetworkAvailable = !NetworkUtil.isNetworkAvailable(context) val bottomSheetState = rememberModalBottomSheetState(ModalBottomSheetValue.Hidden) val coroutineScope = rememberCoroutineScope() return when { isNetworkAvailable -> ErrorScreen( modifier, true, onRetryClick = viewModel::refresh, ) state is DetailState.Loading -> LoadingScreen(modifier) state is DetailState.Success -> { ReportDialog( onClick = { viewModel.updateReportDialogVisible(false) }, visible = state.reportDialogVisible, onDismissRequest = { viewModel.updateReportDialogVisible(false) }, ) DuckieSelectableBottomSheetDialog( types = immutableListOf(DuckieSelectableType.CopyLink, DuckieSelectableType.Report), bottomSheetState = bottomSheetState, closeSheet = { coroutineScope.launch { bottomSheetState.hide() } }, onReport = { viewModel.report(state.exam.id) }, onCopyLink = { viewModel.copyExamDynamicLink(state.exam.id) }, ) { ExamDetailScreen( modifier = modifier, viewModel = viewModel, openBottomSheet = { coroutineScope.launch { bottomSheetState.show() } }, state = state, ) } } else -> ErrorScreen( modifier, false, onRetryClick = viewModel::refresh, ) } } /** 데이터 성공적으로 받은[DetailState.Success] 상세 화면 */ @Composable internal fun ExamDetailScreen( viewModel: DetailViewModel, modifier: Modifier, openBottomSheet: () -> Unit, state: DetailState.Success, ) { val pullRefreshState = rememberPullRefreshState( refreshing = state.isRefreshing, onRefresh = { viewModel.pullToRefresh() }, ) Box(modifier = Modifier.pullRefresh(pullRefreshState)) { Layout( modifier = modifier.navigationBarsPadding(), content = { // 상단 탭바 Layout TopAppCustomBar( modifier = Modifier.layoutId(DetailScreenTopAppBarLayoutId), state = state, onTagClick = viewModel::goToSearch, ) when { state.examStatus == ExamStatus.Funding -> { FundingDetailContentLayout( modifier = Modifier.layoutId(DetailScreenContentLayoutId), state = state, tagItemClick = viewModel::goToSearch, moreButtonClick = openBottomSheet, followButtonClick = viewModel::followUser, profileClick = viewModel::goToProfile, ) } state.isQuiz -> { QuizDetailContentLayout( modifier = Modifier.layoutId(DetailScreenContentLayoutId), state = state, tagItemClick = viewModel::goToSearch, moreButtonClick = openBottomSheet, followButtonClick = viewModel::followUser, profileClick = viewModel::goToProfile, ) } !state.isQuiz -> { ExamDetailContentLayout( modifier = Modifier.layoutId(DetailScreenContentLayoutId), state = state, tagItemClick = viewModel::goToSearch, moreButtonClick = openBottomSheet, followButtonClick = viewModel::followUser, profileClick = viewModel::goToProfile, ) } } // 최하단 Layout DetailBottomLayout( modifier = Modifier .layoutId(DetailScreenBottomBarLayoutId) .background(color = QuackColor.White.value), state = state, onHeartClick = viewModel::heartExam, onChallengeClick = viewModel::startExam, onAddProblemClick = viewModel::goToCreateProblem, ) }, measurePolicy = screenMeasurePolicy( topLayoutId = DetailScreenTopAppBarLayoutId, contentLayoutId = DetailScreenContentLayoutId, bottomLayoutId = DetailScreenBottomBarLayoutId, ), ) PullRefreshIndicator( modifier = Modifier.align(Alignment.TopCenter), refreshing = state.isRefreshing, state = pullRefreshState, ) } }
32
null
2
8
5dbd5b7a42c621931d05a96e66431f67a3a50762
8,085
duckie-android
MIT License
src/main/kotlin/ru/scisolutions/scicmscore/engine/model/Attribute.kt
borisblack
737,700,232
false
null
package ru.scisolutions.scicmscore.model import com.fasterxml.jackson.annotation.JsonIgnore import ru.scisolutions.scicmscore.util.Json import java.time.LocalDate import java.time.OffsetDateTime import java.time.OffsetTime import java.util.Objects class Attribute( val type: FieldType, val columnName: String? = null, // optional (lowercase attribute name is used in database by default), also can be null for oneToMany and manyToMany relations val displayName: String, val description: String? = null, val enumSet: Set<String>? = null, val seqName: String? = null, val confirm: Boolean? = null, val encode: Boolean? = null, val relType: RelType? = null, val target: String? = null, val intermediate: String? = null, // intermediate item is used for manyToMany association and includes source and target attributes val mappedBy: String? = null, val inversedBy: String? = null, val required: Boolean = false, val readOnly: Boolean = false, val defaultValue: String? = null, val keyed: Boolean = false, // primary key, used only for id attribute val unique: Boolean = false, val indexed: Boolean = false, val private: Boolean = false, val pattern: String? = null, // for string type val length: Int? = null, // for string type val precision: Int? = null, // for decimal types val scale: Int? = null, // for decimal types val minRange: Long? = null, // for int, long, float, double, decimal types val maxRange: Long? = null, // for int, long, float, double, decimal types val colHidden: Boolean? = null, // hide column in UI table val colWidth: Int? = null, // column width in UI table val fieldHidden: Boolean? = null, // hide field in UI form val fieldWidth: Int? = null // field width in UI form ) { @JsonIgnore fun isRelation() = type == FieldType.relation @JsonIgnore fun isCollection() = isRelation() && (relType == RelType.oneToMany || relType == RelType.manyToMany) fun validate() { when (type) { FieldType.string -> { if (length == null || length <= 0) throw IllegalArgumentException("Invalid string length (${length})") } FieldType.enum -> { if (enumSet == null) throw IllegalArgumentException("The enumSet is required for the enum type") } FieldType.sequence -> { if (seqName == null) throw IllegalArgumentException("The seqName is required for the sequence type") } FieldType.int, FieldType.long, FieldType.float, FieldType.double -> { if (minRange != null && maxRange != null && minRange > maxRange) throw IllegalArgumentException("Invalid range ratio (minRange=${minRange} > maxRange=${maxRange})") } FieldType.decimal -> { if ((precision != null && precision <= 0) || (scale != null && scale < 0)) throw IllegalArgumentException("Invalid precision and/or scale (${precision}, ${scale})") if (minRange != null && maxRange != null && minRange > maxRange) throw IllegalArgumentException("Invalid range ratio (minRange=${minRange} > maxRange=${maxRange})") } FieldType.relation -> { if (isCollection() && required) throw IllegalArgumentException("Collection relation attribute cannot be required") } else -> {} } } fun parseDefaultValue(): Any? = if (defaultValue == null) null else when (type) { FieldType.uuid, FieldType.string, FieldType.text, FieldType.enum, FieldType.email, FieldType.sequence, FieldType.password -> defaultValue FieldType.int -> defaultValue.toInt() FieldType.long -> defaultValue.toLong() FieldType.float -> defaultValue.toFloat() FieldType.double -> defaultValue.toDouble() FieldType.decimal -> defaultValue.toBigDecimal() FieldType.date -> LocalDate.parse(defaultValue) FieldType.time -> OffsetTime.parse(defaultValue) FieldType.datetime, FieldType.timestamp -> OffsetDateTime.parse(defaultValue) FieldType.bool -> defaultValue == "1" || defaultValue == "true" FieldType.array -> Json.objectMapper.readValue(defaultValue, List::class.java) FieldType.json -> Json.objectMapper.readValue(defaultValue, Map::class.java) FieldType.media -> defaultValue FieldType.relation -> if (isCollection()) Json.objectMapper.readValue(defaultValue, List::class.java).toSet() else defaultValue } fun getColumnName(fallbackColumnName: String): String = columnName ?: fallbackColumnName.lowercase() override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Attribute return type == other.type && columnName == other.columnName && enumSet == other.enumSet && seqName == other.seqName && confirm == other.confirm && encode == other.encode && target == other.target && relType == other.relType && intermediate == other.intermediate && mappedBy == other.mappedBy && inversedBy == other.inversedBy && displayName == other.displayName && description == other.description && pattern == other.pattern && defaultValue == other.defaultValue && required == other.required && readOnly == other.readOnly && keyed == other.keyed && unique == other.unique && indexed == other.indexed && private == other.private && length == other.length && precision == other.precision && scale == other.scale && minRange == other.minRange && maxRange == other.maxRange && colHidden == other.colHidden && colWidth == other.colWidth && fieldHidden == other.fieldHidden && fieldWidth == other.fieldWidth } override fun hashCode(): Int = Objects.hash( type.name, columnName, enumSet, seqName, confirm, encode, target, relType?.name, intermediate, mappedBy, inversedBy, displayName, description, pattern, defaultValue, required, readOnly, keyed, unique, indexed, private, length, precision, scale, minRange, maxRange, colHidden, colWidth, fieldWidth, fieldHidden ) enum class RelType { oneToOne, oneToMany, manyToOne, manyToMany } }
0
null
0
4
13e2eab74403ed4166c1d58e00af43d9335ed52a
7,172
scicms-core
Apache License 2.0
app/src/main/java/com/example/androiddevchallenge/feature/home/Themes.kt
matsujun
347,087,038
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge.feature.home import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.paddingFromBaseline import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.material.Card import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.androiddevchallenge.data.Theme import com.example.androiddevchallenge.data.themes import com.example.androiddevchallenge.ui.theme.MyTheme import com.example.androiddevchallenge.ui.theme.typography import com.skydoves.landscapist.glide.GlideImage @Composable fun Themes() { LazyRow { itemsIndexed(items = themes) { index, theme -> if (index == 0) { Spacer(modifier = Modifier.width(16.dp)) } else { Spacer(modifier = Modifier.width(8.dp)) } Theme(theme) // for final item if (index == themes.size - 1) { Spacer(modifier = Modifier.width(16.dp)) } } } } @Composable fun Theme(theme: Theme) { Card( modifier = Modifier .wrapContentSize() .padding(bottom = 8.dp), elevation = 1.dp, shape = MaterialTheme.shapes.small, backgroundColor = MaterialTheme.colors.background ) { Column( modifier = Modifier.wrapContentSize() ) { GlideImage( imageModel = theme.imageUrl, modifier = Modifier .width(136.dp) .height(96.dp), alignment = Alignment.Center, contentScale = ContentScale.Crop ) Text( text = theme.name, style = typography.h2, modifier = Modifier .background(MaterialTheme.colors.background) .paddingFromBaseline(top = 24.dp, bottom = 16.dp) .padding(start = 16.dp), ) } } } @Preview @Composable fun PreviewTheme() { MyTheme { Theme(themes[0]) } }
0
Kotlin
0
1
ecc68a1ca2ef092d489084e6e4c39315555c245f
3,356
android-dev-challenge-compose_week3_1
Apache License 2.0
mesh-exam/feature/examination/src/main/java/io/flaterlab/meshexam/examination/ui/result/ResultFragment.kt
chorobaev
434,863,301
false
{"Kotlin": 467494, "Java": 1951}
package io.flaterlab.meshexam.examination.ui.result import android.os.Bundle import android.view.View import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import dagger.hilt.android.AndroidEntryPoint import io.flaterlab.meshexam.androidbase.ViewBindingFragment import io.flaterlab.meshexam.androidbase.ViewBindingProvider import io.flaterlab.meshexam.androidbase.ext.clickWithDebounce import io.flaterlab.meshexam.examination.R import io.flaterlab.meshexam.examination.databinding.FragmentResultBinding @AndroidEntryPoint internal class ResultFragment : ViewBindingFragment<FragmentResultBinding>() { private val viewModel: ResultViewModel by viewModels() override val viewBinder: ViewBindingProvider<FragmentResultBinding> get() = FragmentResultBinding::inflate override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel.attemptResult.observe(viewLifecycleOwner) { result -> with(binding) { tvExamResultName.text = result.examName tvExamResultTime.text = result.duration } } viewModel.commandGoToMain.observe(viewLifecycleOwner) { findNavController().popBackStack(R.id.nav_examination, true) } binding.btnBackToMain.clickWithDebounce(action = viewModel::onGoMainClicked) } }
0
Kotlin
0
2
364c4fcb70a461fc02d2a5ef2590ad5f8975aab5
1,430
mesh-exam
MIT License
buildSrc/src/main/java/Config.kt
MenosGrante
139,457,137
false
null
object Config { const val minimumSDKVersion = 21 const val targetSDKVersion = 32 const val compileSDKVersion = 32 const val NDKVersion = "23.1.7779620" const val versionCode = 92 const val versionName = "5.0" }
5
Kotlin
45
597
c58de293d892d88eafe700984bfa6c07ef09001e
237
Rekado
Apache License 2.0
src/main/kotlin/polkot/model/Block.kt
CrommVardek
378,463,310
false
null
package polkot.model data class Block(val height: Long) { }
0
Kotlin
0
0
5088281bd17d45c887df01f163109c0b10853806
62
Polkot-api
Apache License 2.0
app/src/main/java/com/lijukay/noteharmony/utils/interfaces/OnClickInterface.kt
Lijucay
729,290,006
false
{"Kotlin": 36894}
package com.lijukay.noteharmony.utils.interfaces interface OnClickInterface { fun onClick(position: Int) }
0
Kotlin
0
0
5f9dc3466ae2a2eb1c1becf911dd0599b3db804c
111
NoteHarmony
MIT License
yenaly_libs/src/main/java/com/yenaly/yenaly_libs/base/frame/FrameFragment.kt
YenalyLiew
524,046,895
false
{"Kotlin": 723868, "Java": 88900}
package com.yenaly.yenaly_libs.base.frame import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.ViewGroup import android.view.Window import android.widget.TextView import androidx.annotation.LayoutRes import androidx.annotation.MenuRes import androidx.appcompat.app.AlertDialog import androidx.core.view.MenuProvider import androidx.fragment.app.Fragment import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.yenaly.yenaly_libs.R import com.yenaly.yenaly_libs.utils.dp /** * @author : <NAME> * @time : 2022/04/16 016 20:25 */ abstract class FrameFragment : Fragment { constructor() : super() constructor(@LayoutRes resId: Int) : super(resId) val window: Window get() = requireActivity().window private lateinit var loadingDialog: AlertDialog @Deprecated("狗都不用") @JvmOverloads open fun showLoadingDialog( loadingText: String = getString(R.string.yenaly_loading), cancelable: Boolean = false, dialogWidth: Int = 260.dp, dialogHeight: Int = ViewGroup.LayoutParams.WRAP_CONTENT ) { val loadingDialogView = LayoutInflater.from(activity).inflate(R.layout.yenaly_dialog_loading, null) loadingDialogView.findViewById<TextView>(R.id.loading_text).text = loadingText loadingDialog = MaterialAlertDialogBuilder(requireContext()) .setCancelable(cancelable) .setView(loadingDialogView) .create() loadingDialog.show() loadingDialog.window?.setLayout(dialogWidth, dialogHeight) } @Deprecated("狗都不用") open fun hideLoadingDialog() { if (this::loadingDialog.isInitialized) { loadingDialog.hide() } } override fun onDestroy() { super.onDestroy() if (this::loadingDialog.isInitialized) { loadingDialog.dismiss() } } /** * 快捷构建 Menu * * 使用了最新 API,创建菜单更简单。 * * @param menuRes menuRes。 * @param clear 是否清除从上一界面尤其是 Activity 继承过来的 Menu Item,默认为 true。 * @param action 和 [onOptionsItemSelected] 用法一致。 */ open fun addMenu( @MenuRes menuRes: Int, clear: Boolean = true, action: (menuItem: MenuItem) -> Boolean ) { requireActivity().addMenuProvider(object : MenuProvider { override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { // (Optional) 加入 menu.clear() 的原因是,若不加入,如果 Activity 有构建过 Menu,切换到 // Fragment 会导致 Activity 的 Menu 继承到 Fragment 里,clear 一下 // 可以使得该 Fragment 能使用自己唯一的 Menu. // Fragment 之间的 Menu 问题只需要通过指定 lifecycle 就能搞定,用下面的方法。 if (clear) menu.clear() menuInflater.inflate(menuRes, menu) } override fun onMenuItemSelected(menuItem: MenuItem): Boolean { return action.invoke(menuItem) } }) } /** * 详情 [addMenu],最好使用该带 lifecycleOwner 的方法。 */ open fun addMenu( @MenuRes menuRes: Int, owner: LifecycleOwner, clear: Boolean = true, action: (menuItem: MenuItem) -> Boolean ) { requireActivity().addMenuProvider(object : MenuProvider { override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { if (clear) menu.clear() menuInflater.inflate(menuRes, menu) } override fun onMenuItemSelected(menuItem: MenuItem): Boolean { return action.invoke(menuItem) } }, owner) } /** * 详情 [addMenu] */ open fun addMenu( @MenuRes menuRes: Int, owner: LifecycleOwner, state: Lifecycle.State, clear: Boolean = true, action: (menuItem: MenuItem) -> Boolean ) { requireActivity().addMenuProvider(object : MenuProvider { override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { if (clear) menu.clear() menuInflater.inflate(menuRes, menu) } override fun onMenuItemSelected(menuItem: MenuItem): Boolean { return action.invoke(menuItem) } }, owner, state) } /** * 清除 Menu 所有元素 */ open fun clearMenu() { requireActivity().addMenuProvider(object : MenuProvider { override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { menu.clear() } override fun onMenuItemSelected(menuItem: MenuItem): Boolean { return false } }, viewLifecycleOwner) } }
37
Kotlin
78
999
b0fa1a9e50b1567e4b5a504dcb6579d5f35427fa
4,801
Han1meViewer
Apache License 2.0
core/design/src/main/kotlin/cn/wj/android/cashbook/core/design/component/SimpleLifecycleObserver.kt
WangJie0822
365,932,300
false
null
/* * Copyright 2021 The Cashbook Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("unused") package cn.wj.android.cashbook.core.design.component import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.remember import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.compose.LocalLifecycleOwner /** * 简易生命周期观察者 * * > [王杰](mailto:<EMAIL>) 创建于 2023/7/14 */ open class SimpleLifecycleObserver : DefaultLifecycleObserver { private var onCreate: ((LifecycleOwner) -> Unit)? = null fun onCreate(onCreate: (LifecycleOwner) -> Unit) { this.onCreate = onCreate } override fun onCreate(owner: LifecycleOwner) { onCreate?.invoke(owner) } private var onResume: ((LifecycleOwner) -> Unit)? = null fun onResume(onResume: (LifecycleOwner) -> Unit) { this.onResume = onResume } override fun onResume(owner: LifecycleOwner) { onResume?.invoke(owner) } private var onStart: ((LifecycleOwner) -> Unit)? = null fun onStart(onStart: (LifecycleOwner) -> Unit) { this.onStart = onStart } override fun onStart(owner: LifecycleOwner) { onStart?.invoke(owner) } private var onPause: ((LifecycleOwner) -> Unit)? = null fun onPause(onPause: (LifecycleOwner) -> Unit) { this.onPause = onPause } override fun onPause(owner: LifecycleOwner) { onPause?.invoke(owner) } private var onStop: ((LifecycleOwner) -> Unit)? = null fun onStop(onStop: (LifecycleOwner) -> Unit) { this.onStop = onStop } override fun onStop(owner: LifecycleOwner) { onStop?.invoke(owner) } private var onDestroy: ((LifecycleOwner) -> Unit)? = null fun onDestroy(onDestroy: (LifecycleOwner) -> Unit) { this.onDestroy = onDestroy } override fun onDestroy(owner: LifecycleOwner) { onDestroy?.invoke(owner) } } /** * 记录一个生命周期观察者 * - 在生命周期对象变化时移除上一个观察者并添加新的观察者 */ @Composable fun rememberLifecycleObserver(block: SimpleLifecycleObserver.() -> Unit = {}): SimpleLifecycleObserver { val owner = LocalLifecycleOwner.current val observer = SimpleLifecycleObserver().apply(block) DisposableEffect(owner) { owner.lifecycle.addObserver(observer) onDispose { owner.lifecycle.removeObserver(observer) } } return remember(owner) { observer } }
7
null
9
71
6c39b443a1e1e46cf3c4533db3ab270df1f1b9e8
3,063
Cashbook
Apache License 2.0
src/main/kotlin/no/nav/tilleggsstonader/kontrakter/felles/Saksbehandler.kt
navikt
691,013,075
false
{"Kotlin": 96011}
package no.nav.tilleggsstonader.kontrakter.felles import java.util.UUID class Saksbehandler( val azureId: UUID, val navIdent: String, val fornavn: String, val etternavn: String, val enhet: String, )
2
Kotlin
0
0
8a7b232a68960b56b444a57756dd0921bc3cebc3
221
tilleggsstonader-kontrakter
MIT License
library/core/src/main/java/com/falcon/turingx/core/utils/LifecycleUtils.kt
daniellfalcao
307,179,781
false
null
package com.falcon.turingx.core.utils import androidx.lifecycle.Lifecycle /** * Utils to get check current lifecycle state. * */ fun Lifecycle.State.isAtLeastResumed() = isAtLeast(Lifecycle.State.RESUMED) fun Lifecycle.State.isAtLeastDestroyed() = isAtLeast(Lifecycle.State.DESTROYED) fun Lifecycle.State.isAtLeastStarted() = isAtLeast(Lifecycle.State.STARTED) fun Lifecycle.State.isAtLeastInitialized() = isAtLeast(Lifecycle.State.INITIALIZED) fun Lifecycle.State.isAtLeastCreated() = isAtLeast(Lifecycle.State.CREATED)
0
Kotlin
0
0
972e7c9f2f4c4a39904eae71e56d13aa44b71db1
524
turingx
MIT License
lib/src/main/java/posidon/android/conveniencelib/Utils.kt
lposidon
351,240,649
false
null
package posidon.android.conveniencelib import android.animation.Animator import android.app.Activity import android.content.pm.PackageManager import android.os.Build import android.view.View import android.view.ViewPropertyAnimator import android.view.WindowInsets import android.view.inputmethod.InputMethodManager inline fun ViewPropertyAnimator.onEnd(crossinline onEnd: (animation: Animator?) -> Unit): ViewPropertyAnimator = setListener(object : Animator.AnimatorListener { override fun onAnimationRepeat(animation: Animator?) {} override fun onAnimationCancel(animation: Animator?) {} override fun onAnimationStart(animation: Animator?) {} override fun onAnimationEnd(animation: Animator?) = onEnd(animation) }) inline fun Animator.onEnd(crossinline onEnd: (animation: Animator?) -> Unit) = addListener(object : Animator.AnimatorListener { override fun onAnimationRepeat(animation: Animator?) {} override fun onAnimationCancel(animation: Animator?) {} override fun onAnimationStart(animation: Animator?) {} override fun onAnimationEnd(animation: Animator?) = onEnd(animation) }) inline fun PackageManager.isInstalled(packageName: String): Boolean { try { getPackageInfo(packageName, 0) } catch (e: Exception) { return false } return true }
0
Kotlin
0
1
c65a8cb120269eb3ea340036a990f8e91c084da3
1,292
android.convenienceLib
Apache License 2.0
mcrpv/src/main/kotlin/func/init_optional.kt
greenhandzdl
511,937,781
false
null
package com.greenhandzdl.func import com.greenhandzdl.MiraiConsoleReflectionPluginVersion.configFolder import com.greenhandzdl.MiraiConsoleReflectionPluginVersion.dataFolder import com.greenhandzdl.func.tools.file_check import com.greenhandzdl.func.tools.file_done import com.greenhandzdl.func.tools.json_done import com.greenhandzdl.func.tools.json_name_check import func.tools.error_break_boolean import func.tools.folder_check import func.tools.folder_done fun init_folder(pathName :String){ do{folder_done("$pathName", folder_check("$pathName"))}while(error_break_boolean(true, folder_check("$pathName"))) } fun init_file(pathName :String, fileName :String){ do{file_done("$pathName", "$fileName", file_check("$pathName", "$fileName"))}while(error_break_boolean(true, file_check("$pathName", "$fileName"))) } fun init_json(pathName :String, jsonName :String){ do{json_done("$pathName", json_name_check("$jsonName"), file_check("$pathName", json_name_check("$jsonName")))}while(error_break_boolean(true, file_check("$pathName", json_name_check("$jsonName")))) } fun init_opt_folder(){ init_folder("$configFolder/mode")//Mapping possible management options init_folder("$dataFolder/cache")//temporary storage state(Including the status of receiving and sending) init_folder("$dataFolder/cache/groupMessage") } fun init_opt_file(){ //init_file("$dataFolder","cache") } fun init_opt_json(){ init_json("$dataFolder/mode","set") } fun init_opt(){ init_opt_folder() init_opt_file() init_opt_json() }
0
Kotlin
0
0
d951ca1064c2726e526e34798c3753b23f152544
1,542
kotlin-mirai-console-reflection
MIT License
kamel-core/src/commonMain/kotlin/io/kamel/core/config/KamelConfig.kt
quanghd96
344,685,880
true
{"Kotlin": 62340}
package io.kamel.core.config import androidx.compose.ui.graphics.ImageBitmap import io.kamel.core.cache.Cache import io.kamel.core.decoder.Decoder import io.kamel.core.fetcher.Fetcher import io.kamel.core.mapper.Mapper public const val DefaultImageBitmapCacheSize: Int = 100 /** * Represents global configuration for this library. * @see KamelConfig to configure one. */ public interface KamelConfig { public val fetchers: List<Fetcher<Any>> public val decoders: List<Decoder<Any>> public val mappers: List<Mapper<Any, Any>> /** * Number of entries to cache. Default is 100. */ public val imageBitmapCache: Cache<Any, ImageBitmap> public companion object } /** * Configures [KamelConfig] using [KamelConfigBuilder]. */ public inline fun KamelConfig(block: KamelConfigBuilder.() -> Unit): KamelConfig = KamelConfigBuilder().apply(block).build()
0
null
0
0
237a526a376ac721ab264b8eba4e9869635c19e7
891
Kamel
Apache License 2.0
app/src/main/java/com/minosai/oneclick/util/RepoInterface.kt
MINOSai
140,918,008
false
null
package com.minosai.oneclick.util import androidx.lifecycle.MutableLiveData import com.minosai.oneclick.model.AccountInfo import com.minosai.oneclick.model.UserPrefs import com.minosai.oneclick.repo.OneClickRepo import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import javax.inject.Inject class RepoInterface @Inject constructor(val repo: OneClickRepo) { var activeAccount = MutableLiveData<AccountInfo>() //TODO: Change 'true' to 'false' var isAutoUpdateUsage: Boolean = false var userPrefs = UserPrefs() init { GlobalScope.launch { val account = getActiveAccount() withContext(Dispatchers.Main) { activeAccount.value = account } } isAutoUpdateUsage = repo.isAutoUpdateUsage() userPrefs = repo.getUserPrefs() } fun updateUsage(usage: String) = repo.updateUsage(usage) // fun updateAccounts() = repo.fetchAccounts() fun getActiveAccount() = repo.getActiveAccountFromDb() }
0
null
3
10
d7e9c7ede7b25bfbd5fb0dec8d281a337d6b6ed9
1,096
One-Click
Apache License 2.0
ok-blog-be-logics/src/main/kotlin/ru/otus/otuskotlin/blog/logics/chains/stubs/PostSearchStub.kt
otuskotlin
377,709,901
false
null
package ru.otus.otuskotlin.blog.logics.chains.stubs import blog.stubs.PostStub import ru.otus.otuskotlin.blog.backend.common.context.CorStatus import ru.otus.otuskotlin.blog.backend.common.context.PostContext import ru.otus.otuskotlin.blog.backend.common.exceptions.StubCaseNotFound import ru.otus.otuskotlin.blog.backend.common.models.StubCase import ru.otus.otuskotlin.blog.common.cor.handlers.ICorChainDsl import ru.otus.otuskotlin.blog.common.cor.handlers.chain import ru.otus.otuskotlin.blog.common.cor.handlers.worker internal fun ICorChainDsl<PostContext>.postSearchStub(title: String) = chain { this.title = title on { status == CorStatus.RUNNING && stubCase != StubCase.NONE } worker { this.title = "Успешный стабкейс для SEARCH" on { stubCase == StubCase.SUCCESS } handle { responsePosts = PostStub.getModels().toMutableList() status = CorStatus.FINISHING } } worker { this.title = "Обработка отсутствия подходящего стабкейса" on { status == CorStatus.RUNNING } handle { status = CorStatus.FAILING addError( e = StubCaseNotFound(stubCase.name), ) } } }
1
Kotlin
0
0
79c1d9dcac4e5cd1e5b543c4ef004e7b69bb110a
1,231
ok-202105-blog-as
MIT License
blog/api/model/src/main/kotlin/com/excref/kotblog/blog/api/model/common/ErrorResponseModel.kt
excref
93,243,887
false
null
package com.excref.kotblog.blog.api.model.common /** * @author <NAME> * @since 6/15/17 12:05 AM */ data class ErrorResponseModel(val message: String) : ResponseModel
16
Kotlin
4
5
50bc2bd840b1074eb50e9c0d0e87aac6060c7fce
169
kotblog
Apache License 2.0
07-build-custom-view-animations/starter/app/src/main/java/com/raywenderlich/android/menagerie/repository/PetRepositoryImpl.kt
raywenderlich
302,147,373
false
null
package com.raywenderlich.android.menagerie.repository import androidx.lifecycle.LiveData import androidx.lifecycle.map import com.raywenderlich.android.menagerie.data.model.Pet import com.raywenderlich.android.menagerie.database.PetDao import javax.inject.Inject class PetRepositoryImpl @Inject constructor( private val petDao: PetDao ) : PetRepository { override fun getPets(): LiveData<List<Pet>> = petDao.getPets().map { pets -> pets.sortedBy { it.name } } override suspend fun getPetData(): List<Pet> = petDao.getPetData() override fun getSleepingPets(): LiveData<List<Pet>> = petDao.getSleepingPets().map { pets -> pets.sortedBy { it.name } } override suspend fun updatePet(pet: Pet) = petDao.updatePet(pet) override suspend fun insertPets(pets: List<Pet>) = petDao.insertPets(pets) override suspend fun updatePets(pets: List<Pet>) = petDao.updatePets(pets) override fun getPetDetails(petId: String): LiveData<Pet> = petDao.getPetDetails(petId) }
0
Kotlin
12
8
893e3c135e706acf7307bdf310266b120bda2234
987
video-aa-materials
Apache License 2.0
app/src/main/java/com/kemaltalas/fakeshop/presentation/viewmodels/DetailViewModel.kt
KemalTalas
559,009,128
false
{"Kotlin": 103811}
package com.kemaltalas.fakeshop.presentation.viewmodels import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.kemaltalas.fakeshop.data.model.CartItems import com.kemaltalas.fakeshop.data.model.Product import com.kemaltalas.fakeshop.domain.usecase.FavoritesUseCase import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class DetailViewModel @Inject constructor( private val favoritesUseCase: FavoritesUseCase ) : ViewModel() { fun addFavorites(product: Product) = viewModelScope.launch(IO) { favoritesUseCase.addFavorites(product) } fun updateFavoritesItem(product: Product, isLiked : Boolean) = viewModelScope.launch { val copy = product.copy(isFavorited = isLiked) favoritesUseCase.updateFavorites(copy) } fun deleteFavorites(product: Product) = viewModelScope.launch(IO) { favoritesUseCase.deleteFavorites(product) } fun addToCart(cartItems: CartItems) = viewModelScope.launch(IO) { favoritesUseCase.addToCart(cartItems) } }
0
Kotlin
0
0
9ce5c2230b09ecc1047624e0a5a3df82ff83077d
1,132
FakeShop
Apache License 2.0
instantsearch-core/src/commonMain/kotlin/com/algolia/instantsearch/core/tree/TreePresenter.kt
algolia
55,971,521
false
{"Kotlin": 689459}
package com.algolia.instantsearch.core.tree import com.algolia.instantsearch.core.Presenter public typealias TreePresenter<I, O> = Presenter<Tree<I>, O>
15
Kotlin
32
156
cb068acebbe2cd6607a6bbeab18ddafa582dd10b
155
instantsearch-android
Apache License 2.0
sample-projects/app/site/src/jsMain/kotlin/org/example/app/components/layouts/PageLayout.kt
varabyte
745,632,890
false
null
package org.example.app.components.layouts import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import com.varabyte.kobweb.compose.dom.svg.* import com.varabyte.kobweb.compose.foundation.layout.Box import com.varabyte.kobweb.compose.foundation.layout.Column import com.varabyte.kobweb.compose.foundation.layout.ColumnScope import com.varabyte.kobweb.compose.ui.Alignment import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.modifiers.* import com.varabyte.kobweb.compose.ui.toAttrs import com.varabyte.kobweb.silk.components.style.ComponentStyle import com.varabyte.kobweb.silk.components.style.breakpoint.Breakpoint import com.varabyte.kobweb.silk.components.style.toModifier import com.varabyte.kobweb.silk.theme.colors.ColorMode import kotlinx.browser.document import org.jetbrains.compose.web.css.cssRem import org.jetbrains.compose.web.css.fr import org.jetbrains.compose.web.css.percent import org.example.app.components.sections.Footer import org.example.app.components.sections.NavHeader import org.example.app.toSitePalette val PageContentStyle by ComponentStyle { base { Modifier.fillMaxSize().padding(leftRight = 2.cssRem, top = 4.cssRem) } Breakpoint.MD { Modifier.maxWidth(60.cssRem) } } // NOTE: This is a fun little graphic that showcases what you can do with SVG. However, this probably does not make // sense in your own site, so feel free to delete it. @Composable private fun SvgCobweb(modifier: Modifier) { val color = ColorMode.current.toSitePalette().cobweb // On mobile, the SVG would cause scrolling, so clamp its max width Svg(attrs = modifier.maxWidth(100.percent).toAttrs { width(25.cssRem) height(20.cssRem) }) { val cobwebFadeOutId = SvgId("cobweb-fade-out") Defs { // Fade out the bottom right of the cobweb with a circular shape RadialGradient(cobwebFadeOutId, attrs = { cx(0) cy(0) r(120.percent) }) { Stop(50.percent, color) Stop(100.percent, color, stopOpacity = 0f) } } Path { // d { ... } is useful for type-safe, readable SVG path construction, but I got a complex path from a // designer, so using d(...) directly in this case d("M-19.5501 -131.516L37.5899-59.412C34.8649 -10.82 13.8419 26.38 -14.8001 60.62L-21.5161 58.86V78.18L-18.9591 78.852C-3.60911 123.917 -9.87111 169.679 -17.1391 217.146L-21.5151 219.193V239.823L-12.3351 235.529C-5.81911 246.236 1.32289 262.576 6.72489 276.859C10.0329 285.624 13.1183 294.472 15.9779 303.394L-21.5151 341.084V343.514H2.42689L30.9769 314.814C40.2469 314.451 72.7469 313.341 113.677 314.064C160.421 314.889 216.289 318.364 252.727 327.731L257.807 343.515H277.439L270.009 320.427C305.949 278.917 341.921 239.902 401.743 218.087L453.517 238.573V218.476L410.534 201.468C404.16 162.258 423.289 124.803 441.154 84.788L453.517 82.203V63.111L447.194 64.434L441.744 61.631C385.656 32.8 365.41 -16.36 348.444 -71.07L392.628 -131.516H369.478L330.878 -78.706C272.605 -77.452 218.403 -81.169 176.432 -116.496L174.158 -131.516H155.258L158.096 -112.766C130.96 -83.776 100.532 -64.812 53.5119 -69.41L4.29189 -131.516H-19.5521H-19.5501ZM180.367 -90.512C220.975 -64.208 268.865 -59.618 317.121 -59.882L283.981 -14.542C247.393 -14.146 214.125 -17.576 188.136 -39.18L180.367 -90.512ZM161.533 -90.072L169.823 -35.297C152.008 -16.681 132.529 -5.117 101.828 -8.443L68.7519 -50.18C107.345 -50.92 137.11 -67.324 161.532 -90.072H161.533ZM334.857 -52.48C350.393 -5.51302 371.907 40.21 419.407 70.242L367.639 81.062L366.823 80.645C329.553 61.5 316.378 29.005 304.888 -8.18501L304.172 -10.5L334.855 -52.48H334.857ZM54.1169 -38.562L88.5099 4.836C85.9869 34.419 73.1059 57.496 55.3699 79.043L4.96589 65.81C28.6799 36.036 47.6059 2.41699 54.1179 -38.563L54.1169 -38.562ZM191.965 -13.872C215.901 -0.177994 243.015 3.528 270.369 4.076L237.459 49.104C222.401 42.74 211.322 31.351 198.889 18.779L196.546 16.409L191.964 -13.871L191.965 -13.872ZM173.187 -13.062L178.779 23.893C167.603 31.393 154.343 36.043 139.733 39.385L116.831 10.488C139.541 9.093 157.926 -0.192001 173.187 -13.062ZM290.567 8.11099C300.313 37.266 313.713 66.128 341.147 86.601L285.219 98.291C272.222 87.109 265.242 73.557 258.063 58.401L256.393 54.871L290.567 8.11099ZM104.135 24.554L123.277 48.708L123.199 49.418C121.269 66.783 114.322 79.048 106.549 92.481L75.0129 84.201C88.2249 66.845 98.9529 47.373 104.133 24.554H104.135ZM181.809 43.907L187.821 83.649C184.26 84.3288 180.81 85.5 177.571 87.129L152.394 55.362C162.584 52.612 172.524 49.017 181.808 43.908L181.809 43.907ZM201.169 46.95C208.524 53.528 216.689 59.672 226.321 64.34L210.487 86.002C209.307 85.5035 208.103 85.0636 206.88 84.684L201.17 46.949L201.169 46.95ZM138.419 67.814L163.329 99.244C161.729 101.454 160.361 103.823 159.249 106.314L125.335 97.412C130.29 88.655 135.165 79.159 138.419 67.814ZM243.944 71.896C249.064 82.311 255.048 92.991 263.597 102.809L232.454 109.317C230.89 104.865 228.541 100.73 225.517 97.107L243.944 71.896ZM2.17189 84.4L51.0449 97.23C60.2719 125.445 56.8399 154.31 52.2449 184.678L3.17289 207.64C9.12289 167.493 13.4619 126.226 2.17189 84.4ZM418.314 89.562C403.381 122.197 388.2 156.295 390.881 193.692L347.141 176.385C343.541 151.369 355.917 126.94 367.866 100.107L418.316 89.563L418.314 89.562ZM71.7379 102.662L99.3519 109.91L99.9139 111.31C106.014 126.443 105.297 143.082 102.814 161.018L72.4959 175.203C75.7099 151.691 77.4719 127.39 71.7379 102.662ZM345.033 104.879C335.99 124.696 327.236 145.682 327.781 168.726L291.194 154.249C291.19 141.101 292.589 131.409 300.314 120.329L305.294 113.185L345.034 104.878L345.033 104.879ZM120.673 115.507L155.91 124.759C156.126 128.317 156.825 131.829 157.988 135.199L122.718 151.702C123.768 139.802 123.644 127.654 120.673 115.507ZM279.833 118.507C275.208 127.94 273.453 137.397 272.885 147.005L233.607 131.465C233.873 130.34 234.077 129.192 234.247 128.035L279.832 118.507H279.833ZM225.037 148.169L261.541 162.612C252.631 167.192 244.225 173.148 236.864 178.772C233.505 181.339 230.209 183.988 226.978 186.714L216.876 155.317C219.916 153.317 222.662 150.909 225.038 148.169H225.037ZM166.917 151.653L129.26 189.51C126.702 183.31 123.242 178.363 119.672 174.275L119.76 173.719L166.914 151.653H166.917ZM184.647 160.325C189.395 161.652 194.351 162.077 199.256 161.58L209.729 194.12C196.415 193.96 172.116 194.196 148.036 197.13L184.646 160.326L184.647 160.325ZM288.133 173.135L313.496 183.169C284.096 198.089 263.12 219.065 244.244 240.369L233.2 206.05C236.754 202.876 241.93 198.42 248.21 193.623C259.63 184.896 274.418 175.923 283.895 173.996L288.133 173.135ZM101.635 182.2L103.152 183.725C109 189.6 113.125 194.028 114.375 204.475L83.2319 235.783C82.8819 233.513 82.4939 231.153 82.0319 228.641C80.0219 217.691 77.5839 205.699 72.7069 195.737L101.635 182.202V182.2ZM337.563 192.693L376.781 208.211C327.358 230.711 293.866 264.895 263.331 299.681L250.896 261.034C274.999 233.196 298.569 207.418 337.564 192.694L337.563 192.693ZM55.5769 203.75C58.5789 210.587 61.7989 221.92 63.6529 232.016C65.2349 240.626 66.1529 248.096 66.6329 252.466L30.7509 288.541C28.6803 282.405 26.4966 276.307 24.2009 270.251C18.8269 256.035 12.2079 240.239 4.59089 227.611L55.5769 203.751V203.75ZM206.44 212.898C210.408 212.892 213.254 212.928 215.79 212.963L226.186 245.263C199.929 241.113 167.553 241.073 139.129 242.078C123.554 242.628 111.125 243.405 101.272 244.143L125.38 219.906L126.33 219.676C150.076 213.886 186.19 212.93 206.44 212.898ZM164.248 260.288C189.172 260.235 214.614 261.554 232.664 265.391L246.092 307.118C207.384 298.888 157.108 296.141 114.006 295.38C86.7839 294.898 64.7689 295.192 50.1359 295.553L80.9359 264.59C88.7009 263.833 111.646 261.748 139.789 260.754C147.689 260.474 155.939 260.304 164.247 260.287L164.248 260.288Z") transform { scale(0.6) } fill(cobwebFadeOutId) } } } @Composable fun PageLayout(title: String, content: @Composable ColumnScope.() -> Unit) { LaunchedEffect(title) { document.title = "Kobweb - $title" } Box( Modifier .fillMaxWidth() .minHeight(100.percent) // Create a box with two rows: the main content (fills as much space as it can) and the footer (which reserves // space at the bottom). "min-content" means the use the height of the row, which we use for the footer. // Since this box is set to *at least* 100%, the footer will always appear at least on the bottom but can be // pushed further down if the first row grows beyond the page. // Grids are powerful but have a bit of a learning curve. For more info, see: // https://css-tricks.com/snippets/css/complete-guide-grid/ .gridTemplateRows { size(1.fr); size(minContent) }, contentAlignment = Alignment.Center ) { SvgCobweb(Modifier.gridRow(1).align(Alignment.TopStart)) Column( // Isolate the content, because otherwise the absolute-positioned SVG above will render on top of it. // This is confusing but how browsers work. Read up on stacking contexts for more info. // https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_positioned_layout/Understanding_z-index/Stacking_context // Some people might have used z-index instead, but best practice is to avoid that if possible, because // as a site gets complex, Z-fighting can be a huge pain to track down. Modifier.fillMaxSize().gridRow(1), horizontalAlignment = Alignment.CenterHorizontally, ) { NavHeader() Column( PageContentStyle.toModifier(), horizontalAlignment = Alignment.CenterHorizontally ) { content() } } // Associate the footer with the row that will get pushed off the bottom of the page if it can't fit. Footer(Modifier.fillMaxWidth().gridRow(2)) } }
29
null
1
6
279e5d9a6bb16846fedc932884f8bac1c7149ee3
10,082
kobweb-intellij-plugin
Apache License 2.0
app/src/main/java/br/com/movieapp/core/data/remote/ParamsInterceptor.kt
PedroTeloeken
739,474,504
false
{"Kotlin": 177716}
package br.com.movieapp.core.data.remote import br.com.movieapp.BuildConfig import br.com.movieapp.core.util.Constants import okhttp3.Interceptor import okhttp3.Response class ParamsInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() val url = request.url.newBuilder() .addQueryParameter(Constants.LANGUAGE_PARAM , Constants.LANGUAGE_VALUE) .addQueryParameter(Constants.API_KEY_PARAM , BuildConfig.API_KEY) .build() val newRequest = request.newBuilder().url(url).build() return chain.proceed(newRequest) } }
0
Kotlin
0
1
3f4830a21290819801adf31f58edee70933092ec
657
MovieApp
MIT License
app/src/main/java/com/shid/mosquefinder/app/ui/main/views/AuthActivity.kt
theshid
275,887,919
false
null
package com.shid.mosquefinder.app.ui.main.views import android.annotation.SuppressLint import android.app.Activity import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.viewModels import androidx.lifecycle.Observer import androidx.lifecycle.lifecycleScope import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInAccount import com.google.android.gms.auth.api.signin.GoogleSignInClient import com.google.android.gms.auth.api.signin.GoogleSignInOptions import com.google.android.gms.common.api.ApiException import com.google.android.gms.maps.model.LatLng import com.google.firebase.auth.AuthCredential import com.google.firebase.auth.GoogleAuthProvider import com.shid.mosquefinder.R import com.shid.mosquefinder.app.ui.base.BaseActivity import com.shid.mosquefinder.app.ui.main.view_models.AuthViewModel import com.shid.mosquefinder.app.ui.onboardingscreen.feature.onboarding.OnBoardingActivity import com.shid.mosquefinder.app.utils.enums.Status import com.shid.mosquefinder.app.utils.extensions.showToast import com.shid.mosquefinder.app.utils.extensions.startActivity import com.shid.mosquefinder.app.utils.helper_class.FusedLocationWrapper import com.shid.mosquefinder.app.utils.helper_class.SharePref import com.shid.mosquefinder.app.utils.helper_class.singleton.Common.LOCATION_PERMISSION_REQUEST_CODE import com.shid.mosquefinder.app.utils.helper_class.singleton.Common.USER import com.shid.mosquefinder.app.utils.helper_class.singleton.Common.logErrorMessage import com.shid.mosquefinder.app.utils.helper_class.singleton.GsonParser import com.shid.mosquefinder.app.utils.helper_class.singleton.PermissionUtils import com.shid.mosquefinder.data.model.User import dagger.hilt.android.AndroidEntryPoint import kotlinx.android.synthetic.main.activity_auth.* import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.launch import timber.log.Timber import javax.inject.Inject @AndroidEntryPoint class AuthActivity : BaseActivity() { var userPosition: LatLng? = null private val authViewModel: AuthViewModel by viewModels() @Inject lateinit var googleSignInClient: GoogleSignInClient @Inject lateinit var googleSignInOptions: GoogleSignInOptions @Inject lateinit var sharePref: SharePref private var isFirstTime: Boolean? = null @OptIn(ExperimentalCoroutinesApi::class) @Inject lateinit var fusedLocationWrapper: FusedLocationWrapper override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_auth) isFirstTime = sharePref.loadFirstTime() checkIfPermissionIsActive() initSignInButton() setObservers() } @OptIn(ExperimentalCoroutinesApi::class) @SuppressLint("MissingPermission") private fun permissionCheck(fusedLocationWrapper: FusedLocationWrapper) { if (PermissionUtils.isAccessFineLocationGranted(this)) { getUserLocation(fusedLocationWrapper) } else { showToast(getString(R.string.toast_permission)) } } @OptIn(ExperimentalCoroutinesApi::class) @SuppressLint("MissingPermission") private fun getUserLocation(fusedLocationWrapper: FusedLocationWrapper) { this.lifecycleScope.launch { val location = fusedLocationWrapper.awaitLastLocation() userPosition = LatLng(location.latitude, location.longitude) userPosition?.let { sharePref.saveUserPosition(LatLng(it.latitude, it.longitude)) } } } @OptIn(ExperimentalCoroutinesApi::class) private fun checkIfPermissionIsActive() { when { PermissionUtils.isAccessFineLocationGranted(this) -> { when { PermissionUtils.isLocationEnabled(this) -> { permissionCheck(fusedLocationWrapper) } else -> { PermissionUtils.showGPSNotEnabledDialog(this) } } } else -> { PermissionUtils.requestAccessFineLocationPermission( this, LOCATION_PERMISSION_REQUEST_CODE ) } } } private fun setObservers() { authViewModel.retrieveStatusMsg().observe(this, androidx.lifecycle.Observer { when (it.status) { Status.SUCCESS -> { Toast.makeText(this, it.data, Toast.LENGTH_LONG).show() } Status.LOADING -> { } Status.ERROR -> { //Handle Error Toast.makeText(this, it.data, Toast.LENGTH_LONG).show() Timber.d(it.message.toString()) } } }) } @OptIn(ExperimentalCoroutinesApi::class) override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { LOCATION_PERMISSION_REQUEST_CODE -> { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { when { PermissionUtils.isLocationEnabled(this) -> { permissionCheck(fusedLocationWrapper) } else -> { PermissionUtils.showGPSNotEnabledDialog(this) } } } else { showToast(getString(R.string.location_permission_not_granted)) } } } } private fun initSignInButton() { google_sign_in_button.setOnClickListener { signIn() } } private fun signIn() { val signInIntent = googleSignInClient.signInIntent resultLauncher.launch(signInIntent) } private var resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if (result.resultCode == Activity.RESULT_OK) { // There are no request codes val data: Intent? = result.data val task = GoogleSignIn.getSignedInAccountFromIntent(data) try { val googleSignInAccount = task.getResult(ApiException::class.java) googleSignInAccount?.let { getGoogleAuthCredential(it) } } catch (e: ApiException) { logErrorMessage(e.message) } } } private fun getGoogleAuthCredential(googleSignInAccount: GoogleSignInAccount) { Timber.d("getGoogleAuthCredential: ") val googleTokenId = googleSignInAccount.idToken val googleAuthCredential = GoogleAuthProvider.getCredential(googleTokenId, null) signInWithGoogleAuthCredential(googleAuthCredential) } private fun signInWithGoogleAuthCredential(googleAuthCredential: AuthCredential) { Timber.d("signInWithGoogleAuthCredential: ") authViewModel.signInWithGoogle(googleAuthCredential) authViewModel.authenticatedUserLiveData?.observe(this, Observer { if (it.isNew!!) { Timber.d("new: ") createNewUser(it) } else { Timber.d("go to home: ") goToHomeActivity(it) } }) } private fun createNewUser(authenticatedUser: User) { authViewModel.createUser(authenticatedUser) authViewModel.createdUserLiveData?.observe(this, Observer { if (it.isCreated!!) { toastMessage(it.name!!) } goToOnBoardingActivity(it) }) } private fun toastMessage(name: String) { Toast.makeText( this, String.format(resources.getString(R.string.toast_auth_salutation, name)), Toast.LENGTH_LONG ).show() } private fun goToOnBoardingActivity(user: User) { startActivity<OnBoardingActivity> { putExtra(USER, user) } overridePendingTransition(R.anim.fade_in, R.anim.fade_out) finish() } private fun goToHomeActivity(user: User) { val convertUserJson = GsonParser.gsonParser?.toJson(user) convertUserJson?.let { sharePref.saveUser(convertUserJson) } if (isFirstTime == true) { startActivity<LoadingActivity>() overridePendingTransition(R.anim.fade_in, R.anim.fade_out) finish() } else { startActivity<HomeActivity> { putExtra(USER, user) } overridePendingTransition(R.anim.fade_in, R.anim.fade_out) finish() } } }
0
Kotlin
0
1
ef20551bc24f9956b4c487fb49585d736211e05b
9,241
Mosque-Finder
The Unlicense
headless/src/commonMain/kotlin/dev/fritz2/headless/validation/validation.kt
jwstegemann
230,732,344
false
null
package dev.fritz2.headless.validation import dev.fritz2.core.Inspector import dev.fritz2.validation.Validation import dev.fritz2.validation.ValidationMessage /** * Enum which specify the [Severity] of [ComponentValidationMessage]. */ enum class Severity { Info, Success, Warning, Error } /** * Special [ValidationMessage] for fritz2 headless components. * * **Important**: [path] should be generated by using the [Inspector.path] * in your [Validation]. * By default, the validation fails if one or more [ComponentValidationMessage]s have * a [severity] of [Severity.Error]. You can override the [isError] method to change this * behavior. * * @param path location of the validated field in model * @param severity used for rendering the [ValidationMessage] * @param message contains the message * @param details optional details for extending the message */ open class ComponentValidationMessage( override val path: String, val severity: Severity, val message: String, val details: String? = null, ) : ValidationMessage { override val isError: Boolean = severity > Severity.Warning override fun toString(): String = buildString { append("{ ") append("\"path\": \"$path\",") append("\"severity\": \"$severity\",") append("\"message\": \"$message\",") append("\"details\": \"${details ?: ""}\"") append(" }") } } /** * Creates [ComponentValidationMessage] with [Severity.Info]. * * @param path location of the validated field in model * @param message contains the message * @param details optional details for extending the message */ fun infoMessage(path: String, message: String, details: String? = null) = ComponentValidationMessage(path, Severity.Info, message, details) /** * Creates [ComponentValidationMessage] with [Severity.Info]. * * @param message contains the message * @param details optional details for extending the message */ fun <T> Inspector<T>.infoMessage(message: String, details: String? = null) = ComponentValidationMessage(path, Severity.Info, message, details) /** * Creates [ComponentValidationMessage] with [Severity.Info]. * * @param path location of the validated field in model * @param message contains the message * @param details optional details for extending the message */ fun successMessage(path: String, message: String, details: String? = null) = ComponentValidationMessage(path, Severity.Success, message, details) /** * Creates [ComponentValidationMessage] with [Severity.Info]. * * @param message contains the message * @param details optional details for extending the message */ fun <T> Inspector<T>.successMessage(message: String, details: String? = null) = ComponentValidationMessage(path, Severity.Success, message, details) /** * Creates [ComponentValidationMessage] with [Severity.Warning]. * * @param path location of the validated field in model * @param message contains the message * @param details optional details for extending the message */ fun warningMessage(path: String, message: String, details: String? = null) = ComponentValidationMessage(path, Severity.Warning, message, details) /** * Creates [ComponentValidationMessage] with [Severity.Warning]. * * @param message contains the message * @param details optional details for extending the message */ fun <T> Inspector<T>.warningMessage(message: String, details: String? = null) = ComponentValidationMessage(path, Severity.Warning, message, details) /** * Creates [ComponentValidationMessage] with [Severity.Error]. * * @param path location of the validated field in model * @param message contains the message * @param details optional details for extending the message */ fun errorMessage(path: String, message: String, details: String? = null) = ComponentValidationMessage(path, Severity.Error, message, details) /** * Creates [ComponentValidationMessage] with [Severity.Error]. * * @param message contains the message * @param details optional details for extending the message */ fun <T> Inspector<T>.errorMessage(message: String, details: String? = null) = ComponentValidationMessage(path, Severity.Error, message, details)
60
null
28
657
9cfe5d0fb1aba920b0433ed3db71025be6801484
4,229
fritz2
MIT License
dataadapter/src/main/java/com/gauvain/seigneur/dataadapter/injection/adapterModule.kt
GauvainSeigneur
267,048,711
false
null
package com.gauvain.seigneur.dataadapter.injection import com.gauvain.seigneur.dataadapter.adapter.GetAlbumTracksAdapter import com.gauvain.seigneur.dataadapter.adapter.GetUserAlbumsAdapter import com.gauvain.seigneur.domain.provider.* import org.koin.dsl.module val adapterModule = module { single<GetUserAlbumsProvider> { GetUserAlbumsAdapter(get()) } single<GetAlbumTracksProvider> { GetAlbumTracksAdapter(get()) } }
0
Kotlin
0
0
5cd5d9ec1a9aefe7150ec631032467210fd18d80
454
ShinyAlbums
Apache License 2.0
isbn-stacks-common/src/test/kotlin/org/jesperancinha/spring/IsbnDtoTest.kt
jesperancinha
422,836,799
false
{"Makefile": 8200, "Kotlin": 7740, "TypeScript": 6412, "Python": 3375, "Shell": 1469, "Dockerfile": 956}
package org.jesperancinha.spring import io.kotest.matchers.collections.shouldHaveSize import io.kotest.matchers.longs.shouldBeBetween import org.junit.jupiter.api.Test internal class IsbnDtoTest { @Test fun `should fall within ISBN 13 range`() { IsbnDto.ISBNS.shouldHaveSize(500000) IsbnDto.ISBNS.forEach { it.isbn.toLong().shouldBeBetween(1000000000000, 9999999999999) } } }
0
Makefile
0
2
434d3ef15008ee8f20715127f9828edeada1e35c
426
isbn-stacks
Apache License 2.0
lib/src/main/kotlin/online/ecm/youtrack/model/EmailSettings.kt
ecmonline
429,371,464
false
null
/** * YouTrack REST API * * YouTrack issue tracking and project management system * * The version of the OpenAPI document: 2021.3 * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package online.ecm.youtrack.model import online.ecm.youtrack.model.StorageEntry import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.annotation.JsonSubTypes import com.fasterxml.jackson.annotation.JsonTypeInfo /** * Represents email settings for this YouTrack installation. * * @param isEnabled * @param host * @param port * @param mailProtocol * @param anonymous * @param login * @param sslKey * @param from * @param replyTo * @param id * @param dollarType */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "\$type", visible = true) @JsonSubTypes( ) open class EmailSettings ( @get:JsonProperty("isEnabled") val isEnabled: kotlin.Boolean? = null, @get:JsonProperty("host") val host: kotlin.String? = null, @get:JsonProperty("port") val port: kotlin.Int? = null, @get:JsonProperty("mailProtocol") val mailProtocol: MailProtocol? = null, @get:JsonProperty("anonymous") val anonymous: kotlin.Boolean? = null, @get:JsonProperty("login") val login: kotlin.String? = null, @get:JsonProperty("sslKey") val sslKey: StorageEntry? = null, @get:JsonProperty("from") val from: kotlin.String? = null, @get:JsonProperty("replyTo") val replyTo: kotlin.String? = null, @get:JsonProperty("id") val id: kotlin.String? = null, @get:JsonProperty("\$type") val dollarType: kotlin.String? = null )
0
Kotlin
2
3
ccbbeea848cddc13beecfb9c3a91195735c0f19b
1,870
youtrack-rest-api
Apache License 2.0
bgw-examples/bgw-maumau-example/src/main/kotlin/tools/aqua/bgw/examples/maumau/entity/MauMauGame.kt
tudo-aqua
377,420,862
false
null
/* * Copyright 2022-2024 The BoardGameWork Authors * SPDX-License-Identifier: Apache-2.0 * * 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 tools.aqua.bgw.examples.maumau.entity /** Class representing a game of MauMau. */ class MauMauGame(player1: String = "Player 1", player2: String = "Player 2") { /** Collection of all cards in the game. */ val mauMauCards: MutableCollection<MauMauCard> = ArrayList() /** Players. */ val players: MutableList<MauMauPlayer> = mutableListOf(MauMauPlayer(player1), MauMauPlayer(player2)) /** The draw stack. */ val drawStack: DrawStack = DrawStack() /** The game stack. */ val gameStack: GameStack = GameStack() /** Next suit to be placed. May differ from topmost game stack card due to jack selection. */ var nextSuit: CardSuit = CardSuit.HEARTS /** Shuffles cards from game stack back to draw stack. */ fun shuffleGameStackBack() { drawStack.shuffleBack(gameStack.shuffleBack()) } }
31
null
16
24
266db439e4443d10bc1ec7eb7d9032f29daf6981
1,484
bgw
Apache License 2.0
PetStep/app/src/main/java/com/example/petstep/ProfilePhotoPaseadorActivity.kt
ICM2430
842,993,377
false
{"Kotlin": 57816}
package com.example.petstep import android.content.Context import android.content.Intent import android.graphics.BitmapFactory import android.net.Uri import android.os.Bundle import androidx.activity.result.ActivityResultCallback import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.core.content.FileProvider import com.example.petstep.databinding.ActivityProfilePhotoBinding import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import java.io.File class ProfilePhotoActivity : AppCompatActivity() { private lateinit var binding: ActivityProfilePhotoBinding private lateinit var uri: Uri private lateinit var auth: FirebaseAuth private lateinit var database: FirebaseDatabase private lateinit var userRef: DatabaseReference private val galleryLauncher = registerForActivityResult( ActivityResultContracts.GetContent(), ActivityResultCallback { if (it != null) { loadImage(it) saveImageUri(it) sendImageUri(it) } } ) private val cameraLauncher = registerForActivityResult( ActivityResultContracts.TakePicture(), ActivityResultCallback { if (it) { loadImage(uri) saveImageUri(uri) sendImageUri(uri) } } ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityProfilePhotoBinding.inflate(layoutInflater) setContentView(binding.root) auth = FirebaseAuth.getInstance() database = FirebaseDatabase.getInstance() val userId = auth.currentUser?.uid binding.buttonAbrirGaleria.setOnClickListener { galleryLauncher.launch("image/*") } binding.buttonTomarFoto.setOnClickListener { val file = File(getFilesDir(), "profilePic") uri = FileProvider.getUriForFile(baseContext, baseContext.packageName + ".fileprovider", file) cameraLauncher.launch(uri) } binding.buttonConfirmar.setOnClickListener { startActivity(Intent(baseContext, IniciarSesionActivity::class.java)) } } private fun loadImage(uri: Uri) { val imageStream = contentResolver.openInputStream(uri) val bitmap = BitmapFactory.decodeStream(imageStream) binding.imageFotoperfil.setImageBitmap(bitmap) } private fun saveImageUri(uri: Uri) { val sharedPreferences = getSharedPreferences("ProfilePhotoPrefs", Context.MODE_PRIVATE) val editor = sharedPreferences.edit() editor.putString("imageUri", uri.toString()) editor.apply() } private fun sendImageUri(uri: Uri) { val intent = Intent(this, PerfilActivity::class.java) intent.putExtra("imageUri", uri.toString()) startActivity(intent) } }
0
Kotlin
0
3
53c3c7dd63d58890d1f58650237660c02708ab3e
3,062
PetStep
MIT License
core/src/main/java/jmp0/app/mock/system/System.kt
asmjmp0
466,534,924
false
null
package jmp0.app.mock.system import jmp0.app.mock.annotations.ClassReplaceTo import jmp0.util.SystemReflectUtils.findSystemClass import org.apache.log4j.Logger import java.io.InputStream import java.io.PrintStream import java.lang.System // TODO: 2022/3/11 patch reflect framework,don't permit to invoke private method in android framework //first system class I replaced, congratulation!!! @ClassReplaceTo("java.lang.System") class System { // this class load by xclassloadr // if you want to use system class or method use SystemReflectUtils to get companion object{ private val logger = Logger.getLogger(System::class.java) @JvmField val out:PrintStream = xGetSystemStd("out") as PrintStream @JvmField val `in`:InputStream = xGetSystemStd("in") as InputStream @JvmField val err:PrintStream = xGetSystemStd("err") as PrintStream @JvmStatic //the annotation is important fun loadLibrary(libName: String){ logger.info("want to load $libName...") } @JvmStatic fun currentTimeMillis(): Long = java.lang.System.currentTimeMillis() @JvmStatic fun arraycopy(any: Any,a:Int,b:Any,c:Int,d:Int){ java.lang.System.arraycopy(any, a, b, c, d) } @JvmStatic fun arraycopy(any:IntArray,a:Int,b:IntArray,c:Int,d:Int){ java.lang.System.arraycopy(any, a, b, c, d) } @JvmStatic fun arraycopy(any:ByteArray,a:Int,b:ByteArray,c:Int,d:Int){ java.lang.System.arraycopy(any, a, b, c, d) } @JvmStatic fun getProperty(property: String): String { return java.lang.System.getProperty(property)?:"" } @JvmStatic fun getProperty(a:String,b:String):String{ return java.lang.System.getProperty(a,b) } @JvmStatic fun nanoTime(): Long { return java.lang.System.nanoTime() } @JvmStatic fun lineSeparator(): String { return java.lang.System.lineSeparator() } @JvmStatic fun getenv(env:String):String?{ return when (env) { "ANDROID_ROOT" -> null "ANDROID_DATA" -> "/data" "ANDROID_STORAGE" -> "/storage" "OEM_ROOT" -> null "VENDOR_ROOT" -> null else -> { logger.warn("getenv $env just return from host") java.lang.System.getenv(env) } } } @JvmStatic fun setProperty(a:String,b:String):String{ return java.lang.System.setProperty(a,b) } private fun xGetSystemStd(std: String):Any = "java.lang.System".findSystemClass().getDeclaredField(std).get(null) } }
0
Kotlin
42
189
468a37a87e5b87a8ee3623de8853f09b732e832b
2,881
appdbg
Apache License 2.0
kotlin-antd/antd-samples/src/main/kotlin/samples/progress/Dynamic.kt
oxiadenine
206,398,615
false
null
package samples.progress import antd.MouseEventHandler import antd.button.button import antd.button.buttonGroup import antd.icon.minusOutlined import antd.icon.plusOutlined import antd.progress.progress import react.* import react.dom.div import styled.css import styled.styledDiv external interface DynamicAppState : State { var percent: Number } class DynamicApp : RComponent<Props, DynamicAppState>() { private val increase: MouseEventHandler<Any> = { var newPercent = state.percent.toInt() + 10 if (newPercent > 100) { newPercent = 100 } setState { percent = newPercent } } private val decline: MouseEventHandler<Any> = { var newPercent = state.percent.toInt() - 10 if (newPercent < 0) { newPercent = 0 } setState { percent = newPercent } } override fun DynamicAppState.init() { percent = 0 } override fun RBuilder.render() { div { progress { attrs.percent = state.percent } buttonGroup { button { attrs { onClick = decline icon = buildElement { minusOutlined {} } } } button { attrs { onClick = increase icon = buildElement { plusOutlined {} } } } } } } } fun RBuilder.dynamicApp() = child(DynamicApp::class) {} fun RBuilder.dynamic() { styledDiv { css { +ProgressStyles.dynamic } dynamicApp() } }
1
null
8
50
e0017a108b36025630c354c7663256347e867251
1,835
kotlin-js-wrappers
Apache License 2.0
src/test/kotlin/no/nav/familie/ef/sak/vedtak/uttrekk/UttrekkArbeidssøkerRepositoryTest.kt
navikt
206,805,010
false
null
package no.nav.familie.ef.sak.vedtak.uttrekk import no.nav.familie.ef.sak.OppslagSpringRunnerTest import no.nav.familie.ef.sak.behandling.BehandlingRepository import no.nav.familie.ef.sak.repository.behandling import no.nav.familie.ef.sak.repository.fagsak import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import java.time.YearMonth internal class UttrekkArbeidssøkerRepositoryTest : OppslagSpringRunnerTest() { @Autowired private lateinit var behandlingRepository: BehandlingRepository @Autowired private lateinit var repository: UttrekkArbeidssøkerRepository private val årMåned = YearMonth.of(2021, 1) @BeforeEach internal fun setUp() { val fagsak = testoppsettService.lagreFagsak(fagsak()) val behandling = behandlingRepository.insert(behandling(fagsak)) for (i in 1..10) { repository.insert( UttrekkArbeidssøkere( fagsakId = fagsak.id, vedtakId = behandling.id, årMåned = årMåned, registrertArbeidssøker = false ) ) } for (i in 1..5) { repository.insert( UttrekkArbeidssøkere( fagsakId = fagsak.id, vedtakId = behandling.id, årMåned = årMåned.plusMonths(1), kontrollert = true, registrertArbeidssøker = false ) ) } for (i in 1..2) { repository.insert( UttrekkArbeidssøkere( fagsakId = fagsak.id, vedtakId = behandling.id, årMåned = årMåned.plusMonths(1), registrertArbeidssøker = true ) ) } } @Test internal fun `skal hente uttrekk for gitt måned`() { assertThat(repository.findAllByÅrMånedAndRegistrertArbeidssøkerIsFalse(årMåned.minusMonths(1))).isEmpty() assertThat(repository.findAllByÅrMånedAndRegistrertArbeidssøkerIsFalse(årMåned)).hasSize(10) assertThat(repository.findAllByÅrMånedAndRegistrertArbeidssøkerIsFalse(årMåned.plusMonths(1))).hasSize(5) assertThat(repository.findAllByÅrMånedAndRegistrertArbeidssøkerIsFalse(årMåned.plusMonths(2))).isEmpty() } }
8
Kotlin
2
0
d5a30e3058c8ee588d1a348df395a52446bbf02b
2,475
familie-ef-sak
MIT License
app/src/main/java/com/tsundoku/ui/ProfileScreen.kt
giranezafiacre
776,261,260
false
null
package com.example.navigation.screens import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import com.example.navigation.R import com.example.navigation.ui.theme.bluephantom @Composable fun ProfileScreen() { Box( modifier = Modifier .fillMaxSize() .background(bluephantom), contentAlignment = Alignment.Center ) { Text( text = stringResource(id = R.string.screen_name1), fontSize = MaterialTheme.typography.h3.fontSize, fontWeight = FontWeight.Bold, color = Color.White ) } } @Composable @Preview fun ProfileScreenPreview() { ProfileScreen() }
0
Kotlin
0
0
3bd34218e5bc7e71099a661e800a2788b60f20b7
1,148
TsundokuAndroid
MIT License
app/src/main/java/com/example/prodman/data/Measure.kt
PabloDino
804,058,522
false
{"Kotlin": 205892}
package com.example.prodman.data import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class Measure( @PrimaryKey(autoGenerate = true) val id: Int = 0, @ColumnInfo(name = "name") val name: String, @ColumnInfo(name = "description") val description: String, @ColumnInfo(name = "last_updated") val last_updated: String? )
0
Kotlin
0
0
b1558da8b460f16f011f26d45a6b9e547e1b8361
406
s7.prodtrac
Apache License 2.0
src/main/kotlin/me/senseiwells/arucas/utils/impl/ArucasEnum.kt
senseiwells
410,678,534
false
{"Kotlin": 917073, "Java": 4960}
package me.senseiwells.arucas.utils.impl /** * A basic class containing a name and ordinal * representing an enum constant in Arucas. * * @param name the name of the enum. * @param ordinal the ordinal of the enum. */ class ArucasEnum( /** * The name of the enum. */ val name: String, /** * The ordinal of the enum. */ val ordinal: Int )
0
Kotlin
4
17
127776e596fa79f3133ef677805115fc60c4f672
379
Arucas
MIT License
src/test/kotlin/test/melcloud2mqtt/client/SetHeatFlowTemperatureZone1Test.kt
trx-base
621,752,302
false
null
package test.melcloud2mqtt.client import assertk.assertThat import assertk.assertions.isEqualTo import io.micronaut.http.HttpRequest import io.micronaut.http.client.BlockingHttpClient import io.micronaut.http.client.HttpClient import io.mockk.every import io.mockk.impl.annotations.InjectMockKs import io.mockk.impl.annotations.RelaxedMockK import io.mockk.junit5.MockKExtension import io.mockk.mockk import io.mockk.slot import melcloud2mqtt.client.MelcloudHttpClient import melcloud2mqtt.client.model.SetAtw import melcloud2mqtt.client.request.SetHeatFlowTemperatureZone1Request import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import java.util.* @ExtendWith(MockKExtension::class) class SetHeatFlowTemperatureZone1Test { @InjectMockKs lateinit var melcloudHttpClient: MelcloudHttpClient @RelaxedMockK lateinit var httpClient: HttpClient @RelaxedMockK lateinit var blockingHttpClient: BlockingHttpClient var httpRequestSlot = slot<HttpRequest<SetHeatFlowTemperatureZone1Request>>() @BeforeEach fun setUp() { every { httpClient.toBlocking() } returns blockingHttpClient every { blockingHttpClient.retrieve( capture(httpRequestSlot), SetAtw::class.java, ) } returns mockk(relaxed = true) } @Test fun shouldReturnResponse_givenInMelcloudApiResponse_isDifferent() { every { blockingHttpClient.retrieve( capture(httpRequestSlot), SetAtw::class.java, ) } returns SetAtw("99_unexpected") assertThat( melcloudHttpClient.setHeatFlowTemperatureZone1( "", "", "42", ).SetHeatFlowTemperatureZone1, ).isEqualTo("99_unexpected") } @Test fun shouldSetRequestUrlPath_givenHttpRequest() { melcloudHttpClient.setHeatFlowTemperatureZone1("", "", "") assertThat(httpRequestSlot.captured.path).isEqualTo("/Mitsubishi.Wifi.Client/Device/SetAtw") } @Test fun shouldHaveTemperatureInRequest_givenAsParameter() { melcloudHttpClient.setHeatFlowTemperatureZone1("", "", "1878") assertThat(httpRequestSlot.captured.body.get().setHeatFlowTemperatureZone1).isEqualTo("1878") } @Test fun shouldSetMitsContextKey_inHeader_givenAsParameter() { val expectedMitsContextKey = UUID.randomUUID().toString() melcloudHttpClient.setHeatFlowTemperatureZone1(expectedMitsContextKey, "", "") assertThat(httpRequestSlot.captured.headers.get("X-MitsContextKey")).isEqualTo(expectedMitsContextKey) } @Test fun shouldSetDeviceID_inBody_givenAsParameter() { val expectedDeviceID = UUID.randomUUID().toString() melcloudHttpClient.setHeatFlowTemperatureZone1("", expectedDeviceID, "") assertThat(httpRequestSlot.captured.body.get().deviceId).isEqualTo(expectedDeviceID) } @Test fun shouldEffectiveFlags_inBody_givenAsStaticValue() { melcloudHttpClient.setHeatFlowTemperatureZone1("", "", "") assertThat(httpRequestSlot.captured.body.get().effectiveFlags).isEqualTo(281474976710656) } }
0
Kotlin
0
0
74363b539808a49a89b56718320fd2910bd4f944
3,273
melcloud2mqtt
MIT License
src/main/kotlin/org/wfanet/panelmatch/client/launcher/ExchangeStepValidatorImpl.kt
world-federation-of-advertisers
357,662,978
false
null
// Copyright 2021 The Cross-Media Measurement Authors // // 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.wfanet.panelmatch.client.launcher import com.google.protobuf.InvalidProtocolBufferException import java.time.Clock import java.time.ZoneOffset import org.wfanet.measurement.api.v2alpha.ExchangeStep import org.wfanet.measurement.api.v2alpha.ExchangeStepKey import org.wfanet.measurement.api.v2alpha.ExchangeWorkflow import org.wfanet.measurement.common.toLocalDate import org.wfanet.panelmatch.client.launcher.ExchangeStepValidator.ValidatedExchangeStep import org.wfanet.panelmatch.client.launcher.InvalidExchangeStepException.FailureType.PERMANENT import org.wfanet.panelmatch.client.launcher.InvalidExchangeStepException.FailureType.TRANSIENT import org.wfanet.panelmatch.common.secrets.SecretMap /** Real implementation of [ExchangeStepValidator]. */ class ExchangeStepValidatorImpl( private val party: ExchangeWorkflow.Party, private val validExchangeWorkflows: SecretMap, private val clock: Clock ) : ExchangeStepValidator { override suspend fun validate(exchangeStep: ExchangeStep): ValidatedExchangeStep { val serializedExchangeWorkflow = exchangeStep.serializedExchangeWorkflow val recurringExchangeId = requireNotNull(ExchangeStepKey.fromName(exchangeStep.name)).recurringExchangeId val existingExchangeWorkflow = validExchangeWorkflows.get(recurringExchangeId) ?: throw InvalidExchangeStepException( TRANSIENT, "No ExchangeWorkflow known for RecurringExchange $recurringExchangeId" ) if (existingExchangeWorkflow != serializedExchangeWorkflow) { throw InvalidExchangeStepException(PERMANENT, "Serialized ExchangeWorkflow unrecognized") } val workflow = try { @Suppress("BlockingMethodInNonBlockingContext") // This is in-memory. ExchangeWorkflow.parseFrom(serializedExchangeWorkflow) } catch (e: InvalidProtocolBufferException) { throw InvalidExchangeStepException(PERMANENT, "Invalid ExchangeWorkflow") } val stepIndex = exchangeStep.stepIndex if (stepIndex !in 0 until workflow.stepsCount) { throw InvalidExchangeStepException(PERMANENT, "Invalid step_index: $stepIndex") } val step = workflow.getSteps(stepIndex) if (step.party != party) { throw InvalidExchangeStepException( PERMANENT, "Party for step '${step.stepId}' was not ${party.name}" ) } val firstExchangeDate = workflow.firstExchangeDate.toLocalDate() val exchangeDate = exchangeStep.exchangeDate.toLocalDate() if (exchangeDate < firstExchangeDate) { throw InvalidExchangeStepException( PERMANENT, "exchange_date is before ExchangeWorkflow.first_exchange_date" ) } val exchangeTime = exchangeDate.atStartOfDay(ZoneOffset.UTC).toInstant() if (exchangeTime > clock.instant()) { throw InvalidExchangeStepException(TRANSIENT, "exchange_date is in the future") } return ValidatedExchangeStep(workflow, step, exchangeDate) } }
83
null
9
4
be39f195c2f3acbfc1f30fd8c6f88aa2f47136f4
3,581
panel-exchange-client
Apache License 2.0
tests/intellij-plugin-test-project/src/main/kotlin/com/example/Main.kt
apollographql
69,469,299
false
null
@file:Suppress("UNUSED_VARIABLE", "unused") package com.example import com.apollographql.apollo3.ApolloClient import com.apollographql.apollo3.api.Optional import com.example.generated.AnimalsQuery import com.example.generated.CreatePersonMutation import com.example.generated.MyEnumQuery import com.example.generated.fragment.ComputerFields import com.example.generated.type.MyEnum import com.example.generated.type.PersonInput suspend fun main() { val apolloClient = ApolloClient.Builder() .serverUrl("https://example.com") .build() val animalsQuery = AnimalsQuery() val response = apolloClient.query(animalsQuery).execute() println(response.data!!.animals[0].name) println(response.data!!.animals[0].onDog?.fieldOnDogAndCat) val computerFields = ComputerFields( cpu = "386", screen = ComputerFields.Screen(resolution = "640x480"), releaseDate = "1992", ) val myEnum = apolloClient.query(MyEnumQuery(Optional.present(MyEnum.VALUE_C))).execute().data!!.myEnum val personInput = PersonInput( lastName = Optional.Present("Smith") ) val response2 = apolloClient.mutation( CreatePersonMutation( Optional.present( personInput ) ) ).execute() }
176
null
651
3,750
174cb227efe76672cf2beac1affc7054f6bb2892
1,253
apollo-kotlin
MIT License
server/src/main/kotlin/org/nixdork/klog/frameworks/data/ExposedPeopleRepository.kt
nixdork
584,219,630
false
null
package org.nixdork.klog.frameworks.data import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq import org.jetbrains.exposed.sql.and import org.jetbrains.exposed.sql.deleteWhere import org.jetbrains.exposed.sql.transactions.transaction import org.jetbrains.exposed.sql.update import org.nixdork.klog.adapters.data.PeopleRepository import org.nixdork.klog.adapters.model.PasswordCreateResetModel import org.nixdork.klog.adapters.model.PersonLoginModel import org.nixdork.klog.adapters.model.PersonModel import org.nixdork.klog.adapters.model.VerifyLoginModel import org.nixdork.klog.common.CRYPTO_BYTES_TO_GENERATE import org.nixdork.klog.common.generateHash import org.nixdork.klog.common.generateSalt import org.nixdork.klog.common.upsert import org.nixdork.klog.frameworks.data.dao.People import org.nixdork.klog.frameworks.data.dao.Person import org.springframework.stereotype.Component import java.time.OffsetDateTime import java.util.UUID @Component class ExposedPeopleRepository : PeopleRepository { override fun getAllPeople(): List<PersonModel> = transaction { Person.all().map { it.toModel() } } override fun getPersonByEmail(email: String): PersonModel? = transaction { Person.find(People.email eq email).singleOrNull()?.toModel() } override fun getPersonById(id: UUID): PersonModel? = transaction { Person.findById(id)?.toModel() } override fun getPasswordByEmail(email: String): VerifyLoginModel? = transaction { Person.find(People.email eq email).singleOrNull()?.toVerifyLoginModel() } override fun verifyPassword(password: PersonLoginModel): Boolean = transaction { val pwd = getPasswordByEmail(password.email)?.let { it.hash to it.salt } requireNotNull(pwd) { "Person not found!" } requireNotNull(pwd.first) { "Password missing!" } requireNotNull(pwd.second) { "Password missing!" } pwd.first!! == generateHash(password.password, pwd.second!!) } override fun updateLastLogin(personId: UUID): PersonModel? = transaction { People.update({ People.id eq personId }) { it[lastLoginAt] = OffsetDateTime.now() } Person.findById(personId)?.toModel() } override fun upsertPerson(person: PersonModel): PersonModel = transaction { People.upsert { it[id] = person.id it[email] = person.email it[name] = person.name it[role] = person.role it[uri] = person.uri it[avatar] = person.avatar }.resultedValues!! .single() .let { Person.wrapRow(it).toModel() } } override fun upsertPassword(password: PasswordCreateResetModel): PersonModel = transaction { requireNotNull(Person.findById(password.id)) { "Person with ID ${password.id} not found!" } val salt = getPasswordByEmail(password.email)?.salt ?: generateSalt(CRYPTO_BYTES_TO_GENERATE) People.update({ People.id.eq(password.id) and People.email.eq(password.email) }) { it[hash] = generateHash(password.newPassword, salt) it[People.salt] = salt it[pwat] = OffsetDateTime.now() } Person.findById(password.id)!!.toModel() } override fun deletePersonById(personId: UUID) { transaction { People.deleteWhere { People.id eq personId } } } override fun deletePersonByEmail(email: String) { transaction { People.deleteWhere { People.email eq email } } } }
4
Kotlin
0
0
dd8dfa0567e04ae6d040582ebb932747eedef2ae
3,663
klog
Apache License 2.0
tic-tac-toe-back/src/main/kotlin/com/clvr/server/common/Config.kt
spbu-math-cs
698,591,633
false
{"Kotlin": 94320, "TypeScript": 49419, "JavaScript": 8395, "Python": 8353, "CSS": 738}
package com.clvr.server.common import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable enum class ReplaceMarks { DISABLED, ENABLED } @Serializable enum class OpenMultipleQuestions { DISABLED, ENABLED } @Serializable data class Config( @SerialName("replace_marks") val replaceMarks: ReplaceMarks = ReplaceMarks.DISABLED, @SerialName("open_multiple_questions") val openMultipleQuestions: OpenMultipleQuestions = OpenMultipleQuestions.DISABLED )
17
Kotlin
0
0
d77366c5ac27726399f28fe42562630f8ea792fa
511
ig-platform
Apache License 2.0
paplj/src/main/kotlin/com/virtlink/paplj/terms/ClassMemberTerm.kt
Virtlink
90,153,785
false
{"Git Config": 1, "Diff": 1, "Markdown": 1139, "Text": 2, "Ignore List": 19, "Makefile": 3, "YAML": 3, "Gradle": 21, "INI": 6, "Kotlin": 221, "Handlebars": 1, "Shell": 1, "ANTLR": 2, "XML": 5, "Maven POM": 7, "JAR Manifest": 4, "Java": 60, "Gemfile.lock": 1, "Ruby": 1, "SCSS": 1, "JSON with Comments": 2, "JSON": 6}
package com.virtlink.paplj.terms import com.virtlink.terms.ITerm import com.virtlink.terms.StringTerm /** * The ClassMemberTerm term. */ interface ClassMemberTerm : ITerm { val name: StringTerm val type: StringTerm }
1
null
1
1
f7af2531913d9809f3429c0d8e3a82fb695d5ba4
230
aesi
Apache License 2.0
compose/ui/ui-geometry/src/commonMain/kotlin/androidx/compose/ui/geometry/Rect.kt
androidx
256,589,781
false
{"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
/* * Copyright 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 androidx.compose.ui.geometry import androidx.compose.runtime.Immutable import androidx.compose.runtime.Stable import androidx.compose.ui.util.lerp import kotlin.math.absoluteValue import kotlin.math.max import kotlin.math.min // TODO(mount): Normalize this class. There are many methods that can be extension functions. /** * An immutable, 2D, axis-aligned, floating-point rectangle whose coordinates are relative to a * given origin. */ @Immutable data class Rect( /** The offset of the left edge of this rectangle from the x axis. */ @Stable val left: Float, /** The offset of the top edge of this rectangle from the y axis. */ @Stable val top: Float, /** The offset of the right edge of this rectangle from the x axis. */ @Stable val right: Float, /** The offset of the bottom edge of this rectangle from the y axis. */ @Stable val bottom: Float ) { companion object { /** A rectangle with left, top, right, and bottom edges all at zero. */ @Stable val Zero: Rect = Rect(0.0f, 0.0f, 0.0f, 0.0f) } /** The distance between the left and right edges of this rectangle. */ @Stable val width: Float get() { return right - left } /** The distance between the top and bottom edges of this rectangle. */ @Stable val height: Float get() { return bottom - top } /** The distance between the upper-left corner and the lower-right corner of this rectangle. */ @Stable val size: Size get() = Size(width, height) /** Whether any of the coordinates of this rectangle are equal to positive infinity. */ // included for consistency with Offset and Size @Stable val isInfinite: Boolean get() = left >= Float.POSITIVE_INFINITY || top >= Float.POSITIVE_INFINITY || right >= Float.POSITIVE_INFINITY || bottom >= Float.POSITIVE_INFINITY /** Whether all coordinates of this rectangle are finite. */ @Stable val isFinite: Boolean get() = left.isFinite() && top.isFinite() && right.isFinite() && bottom.isFinite() /** Whether this rectangle encloses a non-zero area. Negative areas are considered empty. */ @Stable val isEmpty: Boolean get() = left >= right || top >= bottom /** * Returns a new rectangle translated by the given offset. * * To translate a rectangle by separate x and y components rather than by an [Offset], consider * [translate]. */ @Stable fun translate(offset: Offset): Rect { return Rect(left + offset.x, top + offset.y, right + offset.x, bottom + offset.y) } /** * Returns a new rectangle with translateX added to the x components and translateY added to the * y components. */ @Stable fun translate(translateX: Float, translateY: Float): Rect { return Rect(left + translateX, top + translateY, right + translateX, bottom + translateY) } /** Returns a new rectangle with edges moved outwards by the given delta. */ @Stable fun inflate(delta: Float): Rect { return Rect(left - delta, top - delta, right + delta, bottom + delta) } /** Returns a new rectangle with edges moved inwards by the given delta. */ @Stable fun deflate(delta: Float): Rect = inflate(-delta) /** * Returns a new rectangle that is the intersection of the given rectangle and this rectangle. * The two rectangles must overlap for this to be meaningful. If the two rectangles do not * overlap, then the resulting Rect will have a negative width or height. */ @Stable fun intersect(other: Rect): Rect { return Rect( max(left, other.left), max(top, other.top), min(right, other.right), min(bottom, other.bottom) ) } /** * Returns a new rectangle that is the intersection of the given rectangle and this rectangle. * The two rectangles must overlap for this to be meaningful. If the two rectangles do not * overlap, then the resulting Rect will have a negative width or height. */ @Stable fun intersect(otherLeft: Float, otherTop: Float, otherRight: Float, otherBottom: Float): Rect { return Rect( max(left, otherLeft), max(top, otherTop), min(right, otherRight), min(bottom, otherBottom) ) } /** Whether `other` has a nonzero area of overlap with this rectangle. */ fun overlaps(other: Rect): Boolean { if (right <= other.left || other.right <= left) return false if (bottom <= other.top || other.bottom <= top) return false return true } /** The lesser of the magnitudes of the [width] and the [height] of this rectangle. */ val minDimension: Float get() = min(width.absoluteValue, height.absoluteValue) /** The greater of the magnitudes of the [width] and the [height] of this rectangle. */ val maxDimension: Float get() = max(width.absoluteValue, height.absoluteValue) /** The offset to the intersection of the top and left edges of this rectangle. */ val topLeft: Offset get() = Offset(left, top) /** The offset to the center of the top edge of this rectangle. */ val topCenter: Offset get() = Offset(left + width / 2.0f, top) /** The offset to the intersection of the top and right edges of this rectangle. */ val topRight: Offset get() = Offset(right, top) /** The offset to the center of the left edge of this rectangle. */ val centerLeft: Offset get() = Offset(left, top + height / 2.0f) /** * The offset to the point halfway between the left and right and the top and bottom edges of * this rectangle. * * See also [Size.center]. */ val center: Offset get() = Offset(left + width / 2.0f, top + height / 2.0f) /** The offset to the center of the right edge of this rectangle. */ val centerRight: Offset get() = Offset(right, top + height / 2.0f) /** The offset to the intersection of the bottom and left edges of this rectangle. */ val bottomLeft: Offset get() = Offset(left, bottom) /** The offset to the center of the bottom edge of this rectangle. */ val bottomCenter: Offset get() { return Offset(left + width / 2.0f, bottom) } /** The offset to the intersection of the bottom and right edges of this rectangle. */ val bottomRight: Offset get() { return Offset(right, bottom) } /** * Whether the point specified by the given offset (which is assumed to be relative to the * origin) lies between the left and right and the top and bottom edges of this rectangle. * * Rectangles include their top and left edges but exclude their bottom and right edges. */ operator fun contains(offset: Offset): Boolean { return offset.x >= left && offset.x < right && offset.y >= top && offset.y < bottom } override fun toString() = "Rect.fromLTRB(" + "${left.toStringAsFixed(1)}, " + "${top.toStringAsFixed(1)}, " + "${right.toStringAsFixed(1)}, " + "${bottom.toStringAsFixed(1)})" } /** * Construct a rectangle from its left and top edges as well as its width and height. * * @param offset Offset to represent the top and left parameters of the Rect * @param size Size to determine the width and height of this [Rect]. * @return Rect with [Rect.left] and [Rect.top] configured to [Offset.x] and [Offset.y] as * [Rect.right] and [Rect.bottom] to [Offset.x] + [Size.width] and [Offset.y] + [Size.height] * respectively */ @Stable fun Rect(offset: Offset, size: Size): Rect = Rect(offset.x, offset.y, offset.x + size.width, offset.y + size.height) /** * Construct the smallest rectangle that encloses the given offsets, treating them as vectors from * the origin. * * @param topLeft Offset representing the left and top edges of the rectangle * @param bottomRight Offset representing the bottom and right edges of the rectangle */ @Stable fun Rect(topLeft: Offset, bottomRight: Offset): Rect = Rect(topLeft.x, topLeft.y, bottomRight.x, bottomRight.y) /** * Construct a rectangle that bounds the given circle * * @param center Offset that represents the center of the circle * @param radius Radius of the circle to enclose */ @Stable fun Rect(center: Offset, radius: Float): Rect = Rect(center.x - radius, center.y - radius, center.x + radius, center.y + radius) /** * Linearly interpolate between two rectangles. * * The [fraction] argument represents position on the timeline, with 0.0 meaning that the * interpolation has not started, returning [start] (or something equivalent to [start]), 1.0 * meaning that the interpolation has finished, returning [stop] (or something equivalent to * [stop]), and values in between meaning that the interpolation is at the relevant point on the * timeline between [start] and [stop]. The interpolation can be extrapolated beyond 0.0 and 1.0, so * negative values and values greater than 1.0 are valid (and can easily be generated by curves). * * Values for [fraction] are usually obtained from an [Animation<Float>], such as an * `AnimationController`. */ @Stable fun lerp(start: Rect, stop: Rect, fraction: Float): Rect { return Rect( lerp(start.left, stop.left, fraction), lerp(start.top, stop.top, fraction), lerp(start.right, stop.right, fraction), lerp(start.bottom, stop.bottom, fraction) ) }
30
Kotlin
974
5,321
98b929d303f34d569e9fd8a529f022d398d1024b
10,334
androidx
Apache License 2.0
mobile_app1/module224/src/main/java/module224packageKt0/Foo136.kt
uber-common
294,831,672
false
null
package module224packageKt0; annotation class Foo136Fancy @Foo136Fancy class Foo136 { fun foo0(){ module224packageKt0.Foo135().foo3() } fun foo1(){ foo0() } fun foo2(){ foo1() } fun foo3(){ foo2() } }
6
null
6
72
9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e
237
android-build-eval
Apache License 2.0
mobile_app1/module224/src/main/java/module224packageKt0/Foo136.kt
uber-common
294,831,672
false
null
package module224packageKt0; annotation class Foo136Fancy @Foo136Fancy class Foo136 { fun foo0(){ module224packageKt0.Foo135().foo3() } fun foo1(){ foo0() } fun foo2(){ foo1() } fun foo3(){ foo2() } }
6
null
6
72
9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e
237
android-build-eval
Apache License 2.0
sample/src/main/java/com/sha/kamel/sample/model/Message.kt
ShabanKamell
110,376,843
false
null
package com.sha.kamel.sample.model import org.parceler.Parcel import org.parceler.ParcelConstructor @Parcel data class Message @ParcelConstructor constructor(var message: String)
1
null
8
28
9416078fdec57e0759b86cfb35ee7a8dfb187aa1
181
android-navigator
Apache License 2.0
plugins/kotlin/gradle/code-insight-toml/src/org/jetbrains/kotlin/idea/gradle/versionCatalog/toml/KotlinGradleTomlVersionCatalogReferencesSearcher.kt
JetBrains
2,489,216
false
{"Text": 9788, "INI": 517, "YAML": 423, "Ant Build System": 11, "Batchfile": 34, "Dockerfile": 10, "Shell": 633, "Markdown": 750, "Ignore List": 141, "Git Revision List": 1, "Git Attributes": 11, "EditorConfig": 260, "XML": 7904, "SVG": 4537, "Kotlin": 60205, "Java": 84268, "HTML": 3803, "Java Properties": 217, "Gradle": 462, "Maven POM": 95, "JavaScript": 232, "CSS": 79, "JSON": 1436, "JFlex": 33, "Makefile": 5, "Diff": 137, "XSLT": 113, "Gradle Kotlin DSL": 735, "Groovy": 3102, "desktop": 1, "JAR Manifest": 17, "PHP": 47, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 13, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 15, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 73, "GraphQL": 127, "Nginx": 1, "HAProxy": 1, "OpenStep Property List": 47, "Python": 17095, "C": 110, "C++": 42, "Protocol Buffer": 3, "fish": 2, "PowerShell": 3, "Go": 36, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "HCL": 4, "F#": 1, "GLSL": 1, "Elixir": 2, "Ruby": 4, "XML Property List": 85, "E-mail": 18, "Roff": 289, "Roff Manpage": 40, "Swift": 3, "TOML": 196, "Checksums": 49, "Java Server Pages": 11, "Vue": 1, "Dotenv": 1, "reStructuredText": 67, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 15, "Handlebars": 1, "Rust": 20, "Go Checksums": 1, "Go Module": 1, "NSIS": 8, "PlantUML": 6, "SCSS": 2, "Thrift": 3, "Cython": 13, "Regular Expression": 3, "JSON5": 4, "OASv3-json": 3, "OASv3-yaml": 1}
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.gradle.versionCatalog.toml import com.intellij.openapi.application.QueryExecutorBase import com.intellij.openapi.application.runReadAction import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.PsiReferenceBase import com.intellij.psi.impl.source.tree.LeafPsiElement import com.intellij.psi.search.RequestResultProcessor import com.intellij.psi.search.UsageSearchContext.IN_CODE import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.psi.util.parentOfType import com.intellij.util.Processor import org.jetbrains.kotlin.idea.base.util.restrictToKotlinSources import org.jetbrains.kotlin.psi.KtDotQualifiedExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.toml.lang.psi.TomlKeySegment import org.toml.lang.psi.TomlKeyValue class KotlinGradleTomlVersionCatalogReferencesSearcher : QueryExecutorBase<PsiReference, ReferencesSearch.SearchParameters>(false) { override fun processQuery(queryParameters: ReferencesSearch.SearchParameters, consumer: Processor<in PsiReference>) { val element = queryParameters.elementToSearch if (element !is TomlKeySegment) return val (tomlKeyValue, name) = runReadAction { element.parentOfType<TomlKeyValue>() to element.name } tomlKeyValue ?: return val nameParts = name?.getVersionCatalogParts() ?: return val identifier = nameParts.joinToString(".") val searchScope = queryParameters.effectiveSearchScope.restrictToKotlinSources() queryParameters.optimizer.searchWord(identifier, searchScope, IN_CODE, true, element, MyProcessor(tomlKeyValue)) } class MyProcessor(private val declarationElement: TomlKeyValue) : RequestResultProcessor() { override fun processTextOccurrence(element: PsiElement, offsetInElement: Int, consumer: Processor<in PsiReference>): Boolean { if (element !is KtDotQualifiedExpression || element.hasWrappingVersionCatalogExpression()) { return true } val handler = KotlinGradleTomlVersionCatalogGotoDeclarationHandler() // The handler doesn't work with KtDotQualifiedExpression directly, it expects its grandchild (LeafPsiElement) val grandChild = element.lastChild?.lastChild as? LeafPsiElement ?: return true val foundTargets = handler.getGotoDeclarationTargets(grandChild, 0, null) if (foundTargets?.singleOrNull() == declarationElement) { return consumer.process(KotlinVersionCatalogReference(element, declarationElement)) } return true } } private class KotlinVersionCatalogReference( refExpr: KtDotQualifiedExpression, val searchedElement: TomlKeyValue ) : PsiReferenceBase<KtDotQualifiedExpression>(refExpr) { override fun resolve(): PsiElement { return searchedElement } override fun handleElementRename(newElementName: String): PsiElement { val newElementParts = newElementName.getVersionCatalogParts() val versionCatalogName = element.text.substringBefore(".") val newElementText = versionCatalogName + newElementParts.joinToString(".", ".") val newElement = KtPsiFactory(element.project).createExpression(newElementText) return element.replace(newElement) } } } private fun String.getVersionCatalogParts(): List<String> = split("_", "-")
1
null
1
1
0d546ea6a419c7cb168bc3633937a826d4a91b7c
3,637
intellij-community
Apache License 2.0
src/main/kotlin/org/kstore/demo/stars/gameplay/view/active/tile/CursorState.kt
minorbyte
194,674,817
false
null
package org.kstore.demo.stars.gameplay.view.active.tile enum class CursorState { FREE, JUMP, MOVE }
0
Kotlin
0
0
b91a6a00d4e60a84dc8bceba5dd02c3aa352ca88
105
kotlin-reactive-store
MIT License
app/src/main/java/com/kieronquinn/app/taptap/ui/activities/AppPickerActivity.kt
KieronQuinn
283,883,226
false
null
package com.kieronquinn.app.taptap.ui.activities import android.content.res.Configuration import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import com.kieronquinn.app.taptap.R import dev.chrisbanes.insetter.Insetter class AppPickerActivity: AppCompatActivity() { private val isLightTheme get() = resources.configuration.uiMode.and(Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Insetter.setEdgeToEdgeSystemUiFlags(window.decorView, true) if(isLightTheme){ window.decorView.systemUiVisibility = window.decorView.systemUiVisibility.or(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR).or( View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR) } setContentView(R.layout.activity_app_picker) } }
52
Kotlin
2
2,251
abec5a3e139786beeea75e2fb5677013d0719bf1
918
TapTap
Apache License 2.0
core/src/no/sandramoen/spankfury/actors/EasyEnemy.kt
Slideshow776
297,314,384
false
{"Gradle": 5, "INI": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 2, "Kotlin": 31, "Proguard": 1, "XML": 7, "Java Properties": 1, "Java": 2, "JSON": 2, "GLSL": 2, "Text": 1}
package no.sandramoen.spankfury.actors import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.g2d.Animation import com.badlogic.gdx.graphics.g2d.TextureAtlas import com.badlogic.gdx.scenes.scene2d.Stage import com.badlogic.gdx.utils.Array import no.sandramoen.spankfury.utils.BaseGame class EasyEnemy(x: Float, y: Float, s: Stage, player: Player, originalSpeed: Float, hittingDelay: Float) : BaseEnemy(x, y, s, player, originalSpeed, hittingDelay) { private val token = "<PASSWORD>" override var health = 1 init { setSize( (BaseGame.WORLD_WIDTH / 12) * BaseGame.scale, (BaseGame.WORLD_HEIGHT / 3) * BaseGame.scale ) color = Color.WHITE originalColor = Color.WHITE originalWidth = width originalHeight = height points = 10 } override fun setAnimation() { var animationImages: Array<TextureAtlas.AtlasRegion> = Array() for (i in 1..4) animationImages.add(BaseGame.textureAtlas!!.findRegion("easyEnemy-idle-01")) animationImages.add(BaseGame.textureAtlas!!.findRegion("easyEnemy-idle-02")) idleAnimation = Animation(.2f, animationImages, Animation.PlayMode.LOOP) animationImages.clear() for (i in 1..8) animationImages.add(BaseGame.textureAtlas!!.findRegion("easyEnemy-walking-0$i")) walkingAnimation = Animation(.15f, animationImages, Animation.PlayMode.LOOP) animationImages.clear() for (i in 1..2) animationImages.add(BaseGame.textureAtlas!!.findRegion("easyEnemy-hitting-01")) animationImages.add(BaseGame.textureAtlas!!.findRegion("easyEnemy-hitting-02")) animationImages.add(BaseGame.textureAtlas!!.findRegion("easyEnemy-hitting-03")) for (i in 1..4) animationImages.add(BaseGame.textureAtlas!!.findRegion("easyEnemy-hitting-04")) hittingAnimation = Animation(.05f, animationImages, Animation.PlayMode.NORMAL) animationImages.clear() animationImages.add(BaseGame.textureAtlas!!.findRegion("easyEnemy-stunned-01")) stunnedAnimation = Animation(1f, animationImages, Animation.PlayMode.NORMAL) animationImages.clear() animationImages.add(BaseGame.textureAtlas!!.findRegion("easyEnemy-dying-01")) deadAnimation = Animation(1f, animationImages, Animation.PlayMode.NORMAL) animationImages.clear() setAnimation(walkingAnimation) } }
1
null
1
1
85e05cd02a81eb785e7aba854bfee8fc84334e65
2,434
Spank-Fury
Attribution Assurance License
app/src/main/java/com/arsonist/here/Models/Place.kt
CSID-DGU
180,146,867
false
null
package com.arsonist.here.Models import com.google.android.gms.maps.model.LatLng import com.google.maps.android.clustering.ClusterItem class Place(val lat: Double, val lng: Double, var name: String? = "", var Data: String? = null) : ClusterItem { fun getmPosition(): LatLng = mPosition private val mPosition: LatLng init { mPosition = LatLng(lat, lng) } override fun getPosition(): LatLng = this.getmPosition() override fun getTitle(): String? = null override fun getSnippet(): String? = null }
1
null
5
2
f1b1e2b3045290205fa5daea0953040ddaf4ba95
539
2019-1-OSSP1-Arsonist-4
Apache License 2.0
stripe-ui-core/src/main/java/com/stripe/android/uicore/elements/Controller.kt
stripe
6,926,049
false
null
package com.stripe.android.uicore.elements import androidx.annotation.RestrictTo /** This is a generic controller */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) interface Controller
88
null
644
1,277
174b27b5a70f75a7bc66fdcce3142f1e51d809c8
184
stripe-android
MIT License
compose/compose-runtime/src/main/java/androidx/compose/CompositionLifecycleObserver.kt
FYI-Google
258,765,297
false
null
/* * Copyright 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 androidx.compose /** * Instances of classes implementing this interface are notified when they are initially * used during composition and when they are no longer being used. */ interface CompositionLifecycleObserver { /** * Called when the instance is used in composition. */ fun onEnter() /** * Called when the instance is no longer used in the composition. */ fun onLeave() } /** * Holds an instance of a CompositionLifecycleObserver and a count of how many times it is * used during composition. * * The holder can be used as a key for the identity of the instance. */ internal class CompositionLifecycleObserverHolder(val instance: CompositionLifecycleObserver) { var count: Int = 0 override fun equals(other: Any?): Boolean = other === instance || other is CompositionLifecycleObserverHolder && instance === other.instance override fun hashCode(): Int = System.identityHashCode(instance) }
8
null
0
6
b9cd83371e928380610719dfbf97c87c58e80916
1,604
platform_frameworks_support
Apache License 2.0
konf/src/main/kotlin/com/uchuhimo/konf/source/yaml/YamlProvider.kt
uchuhimo
90,075,694
false
null
package com.uchuhimo.konf.source.yaml import com.uchuhimo.konf.source.Source import com.uchuhimo.konf.source.SourceProvider import com.uchuhimo.konf.source.base.asSource import org.yaml.snakeyaml.Yaml import org.yaml.snakeyaml.constructor.SafeConstructor import java.io.InputStream import java.io.Reader object YamlProvider : SourceProvider { override fun fromReader(reader: Reader): Source { val yaml = Yaml(SafeConstructor()) return yaml.load(reader).asSource("YAML") } override fun fromInputStream(inputStream: InputStream): Source { val yaml = Yaml(SafeConstructor()) return yaml.load(inputStream).asSource("YAML") } }
0
Kotlin
0
1
cbd4b6fbdc6c9af595369a4d7389044792cd20c0
674
kotlin-playground
Apache License 2.0
app/src/main/java/com/google/android/commerce/adapters/ProductAdapter.kt
dirceudn
176,595,915
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 35, "XML": 40, "Java": 2}
package com.google.android.commerce.adapters import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding import androidx.databinding.library.baseAdapters.BR import androidx.recyclerview.widget.RecyclerView import com.google.android.commerce.R import com.google.android.commerce.data.model.Product import com.google.android.commerce.interfaces.ProductAdapterListener class ProductAdapter(listener: ProductAdapterListener) : RecyclerView.Adapter<ProductAdapter.PostViewHolder>() { private var productListener: ProductAdapterListener = listener private var products: List<Product>? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostViewHolder { val layoutInflater = LayoutInflater.from(parent.context) val binding: ViewDataBinding = DataBindingUtil.inflate(layoutInflater, R.layout.item_product, parent, false) return PostViewHolder(binding) } override fun getItemCount(): Int { return if (products != null) products!!.size else 0 } override fun onBindViewHolder(holder: PostViewHolder, position: Int) { holder.bind(products!![position], productListener) } fun setProductList(list: List<Product>?) { products = list notifyDataSetChanged() } class PostViewHolder(private val binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(data: Any, productListener: ProductAdapterListener?) { binding.setVariable(BR.data, data) binding.setVariable(BR.listener, productListener) binding.executePendingBindings() binding.root.setOnClickListener { productListener?.onProductSelected(data as Product) } } } }
0
Kotlin
0
0
dcd0251a27862dcb37f0cf4356190e6611df885b
1,890
e-commerce
MIT License
features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/intro/QrCodeIntroNode.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 * * 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.element.android.features.login.impl.screens.qrcode.intro import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import com.bumble.appyx.core.modality.BuildContext import com.bumble.appyx.core.node.Node import com.bumble.appyx.core.plugin.Plugin import com.bumble.appyx.core.plugin.plugins import dagger.assisted.Assisted import dagger.assisted.AssistedInject import io.element.android.anvilannotations.ContributesNode import io.element.android.features.login.impl.di.QrCodeLoginScope @ContributesNode(QrCodeLoginScope::class) class QrCodeIntroNode @AssistedInject constructor( @Assisted buildContext: BuildContext, @Assisted plugins: List<Plugin>, private val presenter: QrCodeIntroPresenter, ) : Node(buildContext, plugins = plugins) { interface Callback : Plugin { fun onCancelClicked() fun onContinue() } private fun onCancelClicked() { plugins<Callback>().forEach { it.onCancelClicked() } } private fun onContinue() { plugins<Callback>().forEach { it.onContinue() } } @Composable override fun View(modifier: Modifier) { val state = presenter.present() QrCodeIntroView( state = state, onBackClick = ::onCancelClicked, onContinue = ::onContinue, modifier = modifier ) } }
263
Kotlin
129
955
31d0621fa15fe153bfd36104e560c9703eabe917
1,969
element-x-android
Apache License 2.0
_pending/android-super-hero-app/features/characters/characters-ui/src/main/java/com/carlosrd/superhero/ui/characters/feature/detail/adapter/model/CharacterDetailItem.kt
luannguyen252
371,359,679
false
null
package com.carlosrd.superhero.ui.characters.feature.detail.adapter.model import androidx.annotation.DrawableRes import androidx.annotation.StringRes import com.carlosrd.superhero.ui.recyclerview.StickyHeaderItemDecorator interface CharacterDetailItem { override fun equals(other: Any?): Boolean } class CharacterDetailDescriptionItem: CharacterDetailItem { val description: String? @StringRes val descriptionRes : Int constructor(description: String){ this.description = description this.descriptionRes = -1 } constructor(@StringRes descriptionRes : Int){ this.descriptionRes = descriptionRes this.description = null } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as CharacterDetailDescriptionItem if (description != other.description) return false if (descriptionRes != other.descriptionRes) return false return true } } data class CharacterDetailTitleItem(@DrawableRes val titleIcon: Int, @StringRes val title: Int): CharacterDetailItem, StickyHeaderItemDecorator.StickyHeader data class CharacterDetailFeatureItem(val name: String, var separator: Boolean = true): CharacterDetailItem
0
Kotlin
0
1
a9b5aef8662a1808042c820c3dfac02e1efd5800
1,379
my-android-journey
MIT License
profilers/src/com/android/tools/profilers/cpu/nodemodel/CppFunctionModel.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2017 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.profilers.cpu.nodemodel /** * Represents characteristics of C/C++ functions. */ class CppFunctionModel private constructor(builder: Builder) : NativeNodeModel() { /** * Function's full class name (e.g. art::interpreter::SomeClass). For functions that don't belong to a particular class (e.g. * art::bla::Method), this field stores the full namespace (e.g. art::bla). */ val classOrNamespace = builder.classOrNamespace /** * List of the method's parameters (e.g. ["int", "float"]). */ val parameters = builder.parameters.split(", ").filter { it.isNotEmpty() } /** * Whether the function is part of user-written code. */ val isUserCode = builder.isUserCode /** * Name of the ELF file containing the instruction corresponding to the function. */ val fileName = builder.fileName /** * Virtual address of the instruction in [.myFileName]. */ val vAddress = builder.vAddress // The separator is only needed when we have a class name or namespace, otherwise we're going to end up with a leading separator. We // don't have a class name or a namespace, for instance, for global functions. private val fullName = listOf(builder.classOrNamespace, builder.name).filter { it.isNotEmpty() }.joinToString("::") // Use lazy so we don't need to worry about the initialize state of fullName and parameters, and we don't create the string every time // getId() is called. Use LazyThreadSafetyMode.NONE because we don't expect any threading issues. private val id = lazy(LazyThreadSafetyMode.NONE) { "${fullName}${parameters}" } private val tag = builder.tag init { myName = builder.name } override fun getTag(): String? { return tag } override fun getFullName(): String { return fullName } override fun getId(): String { return id.value } // TODO: Remove the set*() methods once all uses have been converted to Kotlin. class Builder(val name: String) { // All fields in the build need to have @JvmField on them to stop Kotlin from creating get/set methods for them. If it was to create // set methods, they would conflict with our chaining set methods. @JvmField var classOrNamespace = "" @JvmField var isUserCode = false /** * A comma separated lust if method parameters (e.g. "int, float"). */ @JvmField var parameters = "" @JvmField var fileName: String? = null @JvmField var vAddress: Long = 0 @JvmField var tag: String? = null fun setClassOrNamespace(value: String): Builder { classOrNamespace = value return this } fun setIsUserCode(value: Boolean): Builder { isUserCode = value return this } fun setParameters(value: String): Builder { parameters = value return this } fun setFileName(value: String?): Builder { fileName = value return this } fun setVAddress(value: Long): Builder { vAddress = value return this } fun setTag(value: String?): Builder { tag = value return this } fun build(): CppFunctionModel { return CppFunctionModel(this) } } }
5
null
227
948
10110983c7e784122d94c7467e9d243aba943bf4
3,800
android
Apache License 2.0
app/src/test/java/com/example/android/architecture/blueprints/todoapp/statistics/StatisticsUtilsTest.kt
fmcauley
235,662,304
false
null
package com.example.android.architecture.blueprints.todoapp.statistics import com.example.android.architecture.blueprints.todoapp.data.Task import org.hamcrest.CoreMatchers.`is` import org.junit.Assert.* import org.junit.Test class StatisticsUtilsTest { @Test fun getActiveAndCompleteStats_noComplete_returnHundredZero() { // Create an active task val tasks = listOf<Task>( Task("title", "desc", isCompleted = false) ) // Call your function val result = getActiveAndCompletedStats(tasks) // Check the result assertThat(result.activeTasksPercent, `is`(100f)) assertThat(result.completedTasksPercent, `is`(0f)) } @Test fun getActiveAndCompleteStats_oneComplete_returnZeroHundred() { // Create a task that is complete val tasks = listOf<Task>( Task("title", "desc", isCompleted = true)) // Call your function val result = getActiveAndCompletedStats(tasks) // Check the result assertThat(result.completedTasksPercent, `is`(100f)) assertThat(result.activeTasksPercent, `is`(0f)) } @Test fun getActiveAndCompleteStats_twoCompleteAndThreeActive_returnFortySixty() { // Create the needed tasks val tasks = listOf<Task>( Task("title", "desc", isCompleted = true), Task("title", "desc", isCompleted = true), Task("title", "desc", isCompleted = false), Task("title", "desc", isCompleted = false), Task("title", "desc", isCompleted = false) ) // Call the Code Under test val result = getActiveAndCompletedStats(tasks) // Check the result assertThat(result.completedTasksPercent, `is`(40f)) assertThat(result.activeTasksPercent, `is`(60f)) } @Test fun getActiveAndCompleteStats_noTasks_returnZero() { // Create the empty list val tasks = listOf<Task>() // Call the Code Under Test val result = getActiveAndCompletedStats(tasks) // Check the result assertThat(result.activeTasksPercent, `is`(0f)) assertThat(result.completedTasksPercent, `is`(0f)) } @Test fun getActiveAndCompleteStats_error_returnZero() { // Code Under Test val result = getActiveAndCompletedStats(null) // Check the result assertThat(result.activeTasksPercent, `is`(0f)) assertThat(result.completedTasksPercent, `is`(0f)) } }
0
Kotlin
0
0
fb9ed6ecfdf355f61ceeaafdfcc0b61efe42250c
2,551
android-testing
Apache License 2.0
lights/src/commonMain/kotlin/inkapplications/shade/lights/structures/PowerupColorState.kt
InkApplications
183,111,240
false
{"Kotlin": 301356, "Shell": 99}
package inkapplications.shade.lights.structures import inkapplications.shade.serialization.DelegateSerializer import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable /** * Color state properties for powerup. */ @Serializable(with = PowerupColorState.Serializer::class) abstract class PowerupColorState private constructor() { /** * Set a static color at powerup. */ data class Color( /** * The color that is set to the light at powerup. */ val colorValue: ColorValue, /** * Color Temperature to set on powerup. * * This property will be null when the light color is not in the * ct spectrum. */ val temperatureValue: ColorTemperatureValue? = null, ): PowerupColorState() /** * Set a static color temperature at powerup. */ data class ColorTemperature( /** * Color Temperature to set on powerup. */ val temperatureValue: ColorTemperatureValue, ): PowerupColorState() /** * Restore the previous color at powewup. */ class Previous: PowerupColorState() /** * Powerup state that is unsupported by this SDK. */ internal data class Unknown( val mode: String, ): PowerupColorState() /** * Raw color state schema sent by the api */ @Serializable internal data class PowerupColorStateSchema( val mode: String, @SerialName("color_temperature") val temperatureValue: ColorTemperatureValue? = null, @SerialName("color") val colorValue: ColorValue? = null ) internal object Serializer: DelegateSerializer<PowerupColorStateSchema, PowerupColorState>( PowerupColorStateSchema.serializer(), ) { override fun serialize(data: PowerupColorState): PowerupColorStateSchema { return when (data) { is Color -> PowerupColorStateSchema( mode = "color", temperatureValue = data.temperatureValue, colorValue = data.colorValue, ) is ColorTemperature -> PowerupColorStateSchema( mode = "color_temperature", temperatureValue = data.temperatureValue, ) is Previous -> PowerupColorStateSchema( mode = "previous", ) else -> throw IllegalArgumentException("Cannot serialize unknown color state schema: $data") } } override fun deserialize(data: PowerupColorStateSchema): PowerupColorState { return when (data.mode) { "color" -> Color( colorValue = data.colorValue!!, temperatureValue = data.temperatureValue, ) "color_temperature" -> ColorTemperature( temperatureValue = data.temperatureValue!!, ) "previous" -> Previous() else -> Unknown(mode = data.mode) } } } }
18
Kotlin
4
65
f0bb14cea4a9d4744be3c038950a6c5ce1a8bd54
3,143
Shade
MIT License
solar/src/main/java/com/chiksmedina/solar/lineduotone/essentionalui/PaperBin.kt
CMFerrer
689,442,321
false
{"Kotlin": 36591890}
package com.chiksmedina.solar.lineduotone.essentionalui import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeCap.Companion.Round 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 com.chiksmedina.solar.lineduotone.EssentionalUiGroup val EssentionalUiGroup.PaperBin: ImageVector get() { if (_paperBin != null) { return _paperBin!! } _paperBin = Builder( name = "PaperBin", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f ).apply { path( fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 1.5f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(3.0335f, 8.89f) curveTo(2.553f, 5.6865f, 2.3127f, 4.0847f, 3.2104f, 3.0423f) curveTo(4.108f, 2.0f, 5.7277f, 2.0f, 8.9671f, 2.0f) horizontalLineTo(15.0329f) curveTo(18.2723f, 2.0f, 19.892f, 2.0f, 20.7897f, 3.0423f) curveTo(21.6873f, 4.0847f, 21.4471f, 5.6865f, 20.9665f, 8.89f) lineTo(19.7665f, 16.89f) curveTo(19.4009f, 19.3276f, 19.2181f, 20.5464f, 18.3741f, 21.2732f) curveTo(17.5302f, 22.0f, 16.2978f, 22.0f, 13.8329f, 22.0f) horizontalLineTo(10.1671f) curveTo(7.7023f, 22.0f, 6.4698f, 22.0f, 5.6259f, 21.2732f) curveTo(4.782f, 20.5464f, 4.5992f, 19.3276f, 4.2335f, 16.89f) lineTo(3.0335f, 8.89f) close() } path( fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(21.0f, 6.0f) horizontalLineTo(3.0f) } path( fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), fillAlpha = 0.5f, strokeAlpha = 0.5f, strokeLineWidth = 1.5f, strokeLineCap = Butt, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(8.0f, 6.0f) lineTo(3.5f, 11.0f) lineTo(11.0f, 19.0f) moveTo(14.0f, 6.0f) lineTo(4.0f, 16.0f) moveTo(20.0f, 6.0f) lineTo(7.0f, 19.0f) moveTo(13.0f, 19.0f) lineTo(20.5f, 11.0f) lineTo(16.0f, 6.0f) moveTo(10.0f, 6.0f) lineTo(20.0f, 16.0f) moveTo(4.0f, 6.0f) lineTo(17.0f, 19.0f) } path( fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(19.0f, 19.0f) horizontalLineTo(5.0f) } } .build() return _paperBin!! } private var _paperBin: ImageVector? = null
0
Kotlin
0
0
3414a20650d644afac2581ad87a8525971222678
3,870
SolarIconSetAndroid
MIT License
app/src/main/java/dev/anand/synchronossweatherapp/data/api/QueryInerceptor.kt
ananddamodaran
500,902,348
false
{"Kotlin": 30961}
package dev.anand.synchronossweatherapp.data.api import dev.anand.synchronossweatherapp.BuildConfig import okhttp3.Interceptor import okhttp3.Response class QueryParameterAddInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val url = chain.request().url.newBuilder() .addQueryParameter("appid", BuildConfig.WEATHER_APP_ID) .build() val request = chain.request().newBuilder() .url(url) .build() return chain.proceed(request) } }
0
Kotlin
0
1
bd0ab27959be2270ea4b7e9fbedd947ec40a7b8e
551
SynchronossWeatherApp
Apache License 2.0
app/src/main/java/com/omongole/fred/yomovieapp/presentation/screens/search/SearchScreen.kt
EngFred
724,071,728
false
{"Kotlin": 244248}
package com.omongole.fred.yomovieapp.presentation.screens.search import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Text import androidx.compose.runtime.Composable 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.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.paging.LoadState import androidx.paging.compose.collectAsLazyPagingItems import androidx.paging.compose.itemContentType import coil.compose.AsyncImage import com.omongole.fred.yomovieapp.presentation.common.AnimatedLargeImageShimmerEffect import com.omongole.fred.yomovieapp.presentation.common.AnimatedTextShimmerEffect import com.omongole.fred.yomovieapp.presentation.common.NoInternetComponent import com.omongole.fred.yomovieapp.presentation.common.SearchWidget import com.omongole.fred.yomovieapp.presentation.screens.search.components.SearchScreenMovieItem import com.omongole.fred.yomovieapp.presentation.viewModel.SearchScreenEvent import com.omongole.fred.yomovieapp.presentation.viewModel.SearchScreenViewModel import com.omongole.fred.yomovieapp.util.Constants @Composable fun SearchScreen( modifier: Modifier, searchMovies: (String) -> Unit, showMovieDetail: (Int) -> Unit ) { val viewModel: SearchScreenViewModel = hiltViewModel() val trendingMovies = viewModel.trendingMovies.collectAsLazyPagingItems() when( trendingMovies.loadState.refresh ) { is LoadState.Error -> { Column( modifier = modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { NoInternetComponent(modifier = modifier, error = "You're offline!", refresh = { trendingMovies.refresh() } ) } } else -> { Column( modifier = modifier ) { SearchWidget( query = viewModel.searchQuery, placeHolder = "Search movies", onCloseClicked = { viewModel.searchQuery = "" }, onSearchClicked = { if ( viewModel.searchQuery.isNotEmpty() ) { searchMovies( viewModel.searchQuery ) } }, onValueChanged = { viewModel.onEvent( SearchScreenEvent.SearchQueryChange(it) ) } ) if ( trendingMovies.loadState.refresh == LoadState.Loading ) { Column( modifier = Modifier .wrapContentHeight() .padding(5.dp)) { Row { AnimatedLargeImageShimmerEffect() Spacer(modifier = Modifier.width(7.dp)) AnimatedLargeImageShimmerEffect() } Spacer(modifier = Modifier.size(7.dp)) Row { AnimatedLargeImageShimmerEffect() Spacer(modifier = Modifier.width(7.dp)) AnimatedLargeImageShimmerEffect() } } } else { LazyVerticalGrid( columns = GridCells.Fixed(2), contentPadding = PaddingValues(start = 15.dp) ) { items( count = trendingMovies.itemCount, //key = trendingMovies.itemKey { it.id }, contentType = trendingMovies.itemContentType{"trendingMovies" } ) { val movie = trendingMovies[it] movie?.let { SearchScreenMovieItem( showMovieDetail = showMovieDetail, movie = it ) } } } } } } } }
0
Kotlin
0
0
31d0f28329a453f07a099278428bb4c7d433245d
5,215
Cinema-app
MIT License
v2-model-enumeration/src/commonMain/kotlin/com/bselzer/gw2/v2/model/enumeration/AttunementName.kt
Woody230
388,820,096
false
{"Kotlin": 750899}
package com.bselzer.gw2.v2.model.enumeration import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable enum class AttunementName { @SerialName("Fire") FIRE, @SerialName("Water") WATER, @SerialName("Earth") EARTH, @SerialName("Air") AIR; }
2
Kotlin
0
2
32f1fd4fc4252dbe886b6fc0f4310cf34ac2ef27
313
GW2Wrapper
Apache License 2.0
bip39_wordlist_en/src/test/kotlin/org/kethereum/bip39/wordlists/MnemonicTest.kt
komputing
92,780,266
false
{"Kotlin": 776856}
package org.kethereum.bip39.wordlists import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test class MnemonicTest { @Test fun throwsOnWrongEntropySize() { assertEquals(WORDLIST_ENGLISH.size, 2048) } }
43
Kotlin
82
333
1f42cede2d31cb5d3c488bd74eeb8480ec47c919
243
KEthereum
MIT License
ksp/src/main/kotlin/mongodb/ksp/KPoetUtil.kt
richard-gibson
772,786,758
false
{"Kotlin": 13231}
package mongodb.ksp import com.google.devtools.ksp.processing.CodeGenerator import com.google.devtools.ksp.processing.Dependencies import com.google.devtools.ksp.symbol.KSClassDeclaration import com.google.devtools.ksp.symbol.KSFile import com.google.devtools.ksp.symbol.KSType import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.FileSpec import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.MemberName import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.PropertySpec import com.squareup.kotlinpoet.TypeVariableName import com.squareup.kotlinpoet.asClassName import com.squareup.kotlinpoet.ksp.toClassName import com.squareup.kotlinpoet.ksp.toTypeName import com.squareup.kotlinpoet.ksp.writeTo import org.mongokt.utils.query.QueryPath //public inline val Street.Companion.name: MongoPath<Street, String> get() = MongoPath(null, "name") fun ClassName.companionMongoPath(propertyType: KSType, propertyName: String): PropertySpec { val queryPathClass = QueryPath::class.asClassName() val companion = nestedClass("Companion") return PropertySpec.builder( propertyName, queryPathClass.parameterizedBy(this, propertyType.toTypeName()) ).receiver(companion).getter( FunSpec.getterBuilder().addModifiers(KModifier.INLINE) .addStatement("return %T(null, %S)", QueryPath::class, propertyName).build() ).build() } //public inline val <P> QueryPath<P, Street>.name: QueryPath<P, String> get() = div(Street.name) fun ClassName.propertyPath(propertyType: KSType, propertyName: String): PropertySpec { val genParam = TypeVariableName("P") val queryPathClass = QueryPath::class.asClassName() val mongoPathSelect = MemberName(queryPathClass.packageName, "div") return PropertySpec.builder( propertyName, queryPathClass.parameterizedBy(genParam, propertyType.toTypeName()) ).addTypeVariable(genParam) .receiver(queryPathClass.parameterizedBy(genParam, this)) .getter( FunSpec.getterBuilder().addModifiers(KModifier.INLINE) .addStatement("return %M(%T.%L)", mongoPathSelect, this, propertyName).build() ).build() } inline fun <reified T> arrayOfNotNull(element: T?) = listOfNotNull(element).toTypedArray() fun KSClassDeclaration.genQueryPaths(codeGenerator: CodeGenerator, classProps: List<Pair<KSType, String>>) { val fileSpec = FileSpec.builder( packageName.asSanitizedString(), "${simpleName.asSanitizedString()}__MongoPaths" ) val kpClass = asType(emptyList()).toClassName() val companionMongoPaths = classProps.map { (propertyType, propertyName) -> kpClass.companionMongoPath(propertyType, propertyName) } val propertyMongoPaths = classProps.map { (propertyType, propertyName) -> kpClass.propertyPath(propertyType, propertyName) } (companionMongoPaths + propertyMongoPaths).forEach(fileSpec::addProperty) fileSpec.build().writeTo( codeGenerator, Dependencies(true, *arrayOfNotNull(containingFile)) ) }
0
Kotlin
0
0
c95795eade8a5797ccf95477b7a774148d7ae7e7
3,031
mongodb-utils
Apache License 2.0
shared/src/androidMain/kotlin/com/grantham/showplace/Platform.android.kt
fluttertutorialin
736,861,852
false
{"Kotlin": 32570, "Swift": 9632}
package com.grantham.showplace import com.grantham.showplace.data.models.Show import com.grantham.showplace.data.models.Venue import kotlinx.datetime.Clock import kotlinx.datetime.TimeZone import kotlinx.datetime.todayIn actual val showPreview = Show( id = "5", lineup = "Metal, Fun Name, Great Band", venue = Venue( name = "Fun Venue", ageLimit = "none", accessibility = "blah", url = "", capacity = "" ), time = "9pm", date = Clock.System.todayIn(TimeZone.currentSystemDefault()).toString(), price = "Free" )
0
Kotlin
0
0
12393925ec9a7013b983872ed11fce447aacb862
581
ShowPlaceKMP
MIT License
app/src/main/java/io/github/droidkaigi/confsched2018/service/push/processor/NewPostProcessor.kt
DroidKaigi
115,203,383
false
null
package io.github.droidkaigi.confsched2018.service.push.processor import android.app.Application import android.app.Notification import android.app.NotificationManager import android.app.PendingIntent import android.content.Intent import androidx.core.app.NotificationCompat import androidx.core.content.ContextCompat import com.google.firebase.messaging.RemoteMessage import io.github.droidkaigi.confsched2018.R import io.github.droidkaigi.confsched2018.presentation.MainActivity import io.github.droidkaigi.confsched2018.presentation.common.notification.NotificationChannelType import javax.inject.Inject import javax.inject.Singleton @Singleton class NewPostProcessor @Inject constructor( private val application: Application, private val notificationManager: NotificationManager) : MessageProcessor { override fun process(message: RemoteMessage) { if (message.data.isEmpty()) return val title = message.data[KEY_TITLE] val content = message.data[KEY_CONTENT] val type = message.data[KEY_TYPE] val openPi = PendingIntent.getActivity(application, 0, Intent(application, MainActivity::class.java) .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK), // TODO open with announce fragment in front? PendingIntent.FLAG_UPDATE_CURRENT) val priority = when (type) { "notification" -> NotificationCompat.PRIORITY_HIGH "alert" -> NotificationCompat.PRIORITY_HIGH else -> NotificationCompat.PRIORITY_DEFAULT } val notification: Notification = NotificationCompat.Builder(application, NotificationChannelType.NEW_FEED_POST.id) .setStyle( NotificationCompat.BigTextStyle() .setBigContentTitle(title) .bigText(content) ) .setAutoCancel(true) .setSmallIcon(R.drawable.ic_notification) .setPriority(priority) .setDefaults(NotificationCompat.DEFAULT_ALL) .setShowWhen(true) .setWhen(System.currentTimeMillis()) .setColor(ContextCompat.getColor(application, R.color.primary)) .setCategory(NotificationCompat.CATEGORY_MESSAGE) .setContentIntent(openPi) .build() notificationManager.notify(NOTIFICATION_ID, notification) } companion object { const val FCM_FROM = "/topics/post" const val NOTIFICATION_ID = 1 const val KEY_TITLE = "title" const val KEY_CONTENT = "content" const val KEY_TYPE = "type" const val TOPIC = "post" } }
30
null
337
1,340
f19dd63f8b691d44ba7f758d92c2ca615cdad08d
2,671
conference-app-2018
Apache License 2.0
app/src/main/java/com/alexjlockwood/beesandbombs/demos/SquareTwist.kt
Thanhtho96
298,254,523
true
{"Kotlin": 79099}
package com.alexjlockwood.beesandbombs.demos import androidx.compose.animation.animatedFloat import androidx.compose.animation.core.AnimationConstants import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.repeatable import androidx.compose.animation.core.tween import androidx.compose.foundation.Canvas import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.onActive import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.graphics.drawscope.withTransform import androidx.compose.ui.unit.dp import kotlin.math.sqrt @Composable fun SquareTwist(modifier: Modifier = Modifier) { val animatedProgress = animatedFloat(0f) onActive { animatedProgress.animateTo( targetValue = 1f, anim = infiniteRepeatable( animation = tween(durationMillis = 2500, easing = LinearEasing), ), ) } val darkColor = if (isSystemInDarkTheme()) Color.White else Color.Black val lightColor = if (isSystemInDarkTheme()) Color.Black else Color.White val t = animatedProgress.value Canvas(modifier = modifier.clipToBounds()) { val n = 9 val s = size.minDimension / n val l = s * sqrt(2f) / 2f val tt = t * 2 - if (t < 0.5f) 0 else 1 val rotation = 90f * tt if (t < 0.25f || 0.75f < t) { drawRect(lightColor) for (i in 0..n) { for (j in 0..n) { withTransform({ translate(i * s, j * s) rotate(rotation, Offset(0f, 0f)) }, { drawRect( color = darkColor, topLeft = Offset(-l / 2, -l / 2), size = Size(l, l), ) }) } } } else { drawRect(darkColor) for (i in 0..n) { for (j in 0..n) { withTransform({ translate((i + 0.5f) * s, (j + 0.5f) * s) rotate(rotation, Offset(0f, 0f)) }, { drawRect( color = lightColor, topLeft = Offset(-l / 2, -l / 2), size = Size(l, l), ) }) } } } drawRect( color = darkColor, style = Stroke(16.dp.toPx()), ) } }
0
null
0
0
3fceca103010c750d1b6e97535f31ae0867dc535
2,926
bees-and-bombs-compose
MIT License
src/main/kotlin/Student.kt
ShizoCactus
666,096,274
false
null
import kotlin.math.min class Student( val name: String, val group: String, val priorities: List<String>, val averageScores: List<Double>, ): Comparable<Student>{ override fun compareTo(other: Student): Int { return compareScores(this.averageScores, other.averageScores) } override fun toString() = name private fun compareScores(arr1: List<Double>, arr2: List<Double>, index: Int = 0): Int{ if (index >= min(arr1.size, arr2.size)) return 0 if (arr1[index] > arr2[index]) return 1 if (arr1[index] < arr2[index]) return -1 return compareScores(arr1, arr2, index + 1) } }
0
Kotlin
0
0
41b6b4251998f670bc6054b17741b3419d59d959
724
uchebnaya-praktika-leti-compose
Apache License 2.0
SceytChatUiKit/src/main/java/com/sceyt/sceytchatuikit/SceytUIKitInitializer.kt
sceyt
549,073,085
false
{"Kotlin": 2037491, "Java": 130301}
package com.sceyt.sceytchatuikit import android.content.Context import android.util.Log import androidx.appcompat.app.AppCompatDelegate import androidx.core.provider.FontRequest import androidx.emoji2.text.EmojiCompat import androidx.emoji2.text.FontRequestEmojiCompatConfig import androidx.lifecycle.ProcessLifecycleOwner import androidx.lifecycle.lifecycleScope import com.sceyt.chat.ChatClient import com.sceyt.sceytchatuikit.di.SceytKoinApp import com.sceyt.sceytchatuikit.di.appModules import com.sceyt.sceytchatuikit.di.cacheModule import com.sceyt.sceytchatuikit.di.coroutineModule import com.sceyt.sceytchatuikit.di.databaseModule import com.sceyt.sceytchatuikit.di.repositoryModule import com.sceyt.sceytchatuikit.di.viewModelModule import com.sceyt.sceytchatuikit.extensions.TAG import com.sceyt.sceytchatuikit.logger.SceytLog import com.sceyt.sceytchatuikit.sceytconfigs.SceytKitConfig import com.vanniktech.emoji.EmojiManager import com.vanniktech.emoji.google.GoogleEmojiProvider import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.koin.android.ext.koin.androidContext import org.koin.core.KoinApplication import org.koin.core.context.GlobalContext import org.koin.core.context.startKoin import org.koin.dsl.koinApplication class SceytUIKitInitializer(private val context: Context) { fun initialize(clientId: String, appId: String, host: String, enableDatabase: Boolean): ChatClient { //Set static flags before calling initialize val chatClient = ChatClient.initialize(context, host, appId, clientId) initKoin(enableDatabase) initTheme() initEmojiSupport() return chatClient } private fun initTheme() { if (SceytKitConfig.isDarkMode.not()) AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) else AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) } private fun initKoin(enableDatabase: Boolean) { val koin = GlobalContext.getOrNull() if (koin == null) { SceytKoinApp.koinApp = startKoin { init(enableDatabase) } } else { SceytKoinApp.koinApp = koinApplication { // declare used modules init(enableDatabase) } } } private fun initEmojiSupport() { ProcessLifecycleOwner.get().lifecycleScope.launch(Dispatchers.IO) { val fontRequest = FontRequest( "com.google.android.gms.fonts", "com.google.android.gms", "Noto Color Emoji Compat", R.array.com_google_android_gms_fonts_certs) val config = FontRequestEmojiCompatConfig(context, fontRequest) .setReplaceAll(true) .registerInitCallback(object : EmojiCompat.InitCallback() { override fun onInitialized() { SceytLog.d(TAG, "EmojiCompat initialized") } override fun onFailed(throwable: Throwable?) { SceytLog.e(TAG, "EmojiCompat initialization failed", throwable) } }) EmojiCompat.init(config) EmojiManager.install(GoogleEmojiProvider()) } } private fun KoinApplication.init(enableDatabase: Boolean) { androidContext(context) modules(arrayListOf( appModules, databaseModule(enableDatabase), repositoryModule, cacheModule, viewModelModule, coroutineModule)) } }
0
Kotlin
1
0
168a56556f9b29d5223f0501b4b0e3856adba0e1
3,633
sceyt-chat-android-uikit
MIT License
python/huggingFace/src/com/intellij/python/community/impl/huggingFace/cache/HuggingFaceCacheFillService.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.python.community.impl.huggingFace.cache import com.intellij.openapi.components.Service import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.project.Project import com.intellij.python.community.impl.huggingFace.HuggingFaceConstants import com.intellij.python.community.impl.huggingFace.HuggingFaceEntityKind import com.intellij.python.community.impl.huggingFace.api.HuggingFaceApi import com.intellij.python.community.impl.huggingFace.service.HuggingFaceCoroutine import kotlinx.coroutines.async import kotlinx.coroutines.launch import org.jetbrains.annotations.ApiStatus import java.io.IOException import java.time.Duration @ApiStatus.Internal @Service(Service.Level.PROJECT) class HuggingFaceCacheFillService(private val project: Project) { private var wasFilled = false fun triggerCacheFillIfNeeded() = HuggingFaceCoroutine.Utils.ioScope.launch { if (wasFilled) return@launch val refreshState = project.getService(HuggingFaceLastCacheRefresh::class.java) val currentTime = System.currentTimeMillis() if (currentTime - refreshState.lastRefreshTime < Duration.ofDays(1).toMillis()) return@launch wasFilled = true try { val modelFill = async { HuggingFaceApi.fillCacheWithBasicApiData(HuggingFaceEntityKind.MODEL, HuggingFaceModelsCache, HuggingFaceConstants.MAX_MODELS_IN_CACHE) } val datasetFill = async { HuggingFaceApi.fillCacheWithBasicApiData(HuggingFaceEntityKind.DATASET, HuggingFaceDatasetsCache, HuggingFaceConstants.MAX_DATASETS_IN_CACHE) } modelFill.await() datasetFill.await() HuggingFaceCacheUpdateListener.notifyCacheUpdated() wasFilled = true } catch (e: IOException) { thisLogger().error(e) wasFilled = false } } }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
1,888
intellij-community
Apache License 2.0
krpc/krpc-core/src/commonMain/kotlin/kotlinx/rpc/krpc/internal/RPCVersion.kt
Kotlin
739,292,079
false
{"Kotlin": 501936, "Java": 1587, "JavaScript": 1134, "Shell": 1072, "Dockerfile": 69}
/* * Copyright 2023-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.rpc.internal /** * Release versions of the library */ internal enum class RPCVersion { /** * Version 0.1.0 */ V_0_1_0_BETA, }
36
Kotlin
17
733
b946964ca7838d40ba68ad98fe4056f3ed17c635
292
kotlinx-rpc
Apache License 2.0
src/jsTest/kotlin/se/sekvy/compose/markdown/ParserTest.kt
sekvy
548,365,644
false
{"Kotlin": 37104}
package se.sekvy.compose.markdown import Parser import kotlin.test.Test import kotlin.test.assertEquals class ParserTest() { @Test fun testJsParser() { val parser = Parser() val node = parser.parse("Hello *world*") val walker = node.walker() assertEquals(expected = "document", actual = walker.next().node.type) assertEquals(expected = "paragraph", actual = walker.next().node.type) assertEquals(expected = "text", actual = walker.next().node.type) assertEquals(expected = "emph", actual = walker.next().node.type) assertEquals(expected = "text", actual = walker.next().node.type) assertEquals(expected = "emph", actual = walker.next().node.type) assertEquals(expected = "paragraph", actual = walker.next().node.type) assertEquals(expected = "document", actual = walker.next().node.type) } }
0
Kotlin
0
0
1e075865776fa3290ace1dded1956e77923657c3
894
compose-markdown
MIT License
kotlin-mui-icons/src/main/generated/mui/icons/material/ControlPointDuplicateOutlined.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/ControlPointDuplicateOutlined") @file:JsNonModule package mui.icons.material @JsName("default") external val ControlPointDuplicateOutlined: SvgIconComponent
10
Kotlin
145
983
7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35
240
kotlin-wrappers
Apache License 2.0
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/ThermometerEmpty.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Outline.ThermometerEmpty: ImageVector get() { if (_thermometerEmpty != null) { return _thermometerEmpty!! } _thermometerEmpty = Builder(name = "ThermometerEmpty", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(11.5f, 14.0f) curveToRelative(-1.654f, 0.0f, -3.0f, 1.346f, -3.0f, 3.0f) reflectiveCurveToRelative(1.346f, 3.0f, 3.0f, 3.0f) reflectiveCurveToRelative(3.0f, -1.346f, 3.0f, -3.0f) reflectiveCurveToRelative(-1.346f, -3.0f, -3.0f, -3.0f) close() moveTo(11.5f, 18.0f) curveToRelative(-0.552f, 0.0f, -1.0f, -0.448f, -1.0f, -1.0f) reflectiveCurveToRelative(0.448f, -1.0f, 1.0f, -1.0f) reflectiveCurveToRelative(1.0f, 0.448f, 1.0f, 1.0f) reflectiveCurveToRelative(-0.448f, 1.0f, -1.0f, 1.0f) close() moveTo(16.5f, 12.111f) verticalLineToRelative(-7.111f) curveToRelative(0.0f, -2.757f, -2.243f, -5.0f, -5.0f, -5.0f) reflectiveCurveToRelative(-5.0f, 2.243f, -5.0f, 5.0f) verticalLineToRelative(7.111f) curveToRelative(-1.276f, 1.305f, -2.0f, 3.063f, -2.0f, 4.889f) curveToRelative(0.0f, 3.859f, 3.141f, 7.0f, 7.0f, 7.0f) reflectiveCurveToRelative(7.0f, -3.141f, 7.0f, -7.0f) curveToRelative(0.0f, -1.826f, -0.724f, -3.584f, -2.0f, -4.889f) close() moveTo(11.5f, 22.0f) curveToRelative(-2.757f, 0.0f, -5.0f, -2.243f, -5.0f, -5.0f) curveToRelative(0.0f, -1.412f, 0.608f, -2.768f, 1.668f, -3.719f) curveToRelative(0.211f, -0.19f, 0.332f, -0.46f, 0.332f, -0.745f) verticalLineToRelative(-7.537f) curveToRelative(0.0f, -1.654f, 1.346f, -3.0f, 3.0f, -3.0f) reflectiveCurveToRelative(3.0f, 1.346f, 3.0f, 3.0f) verticalLineToRelative(7.537f) curveToRelative(0.0f, 0.284f, 0.121f, 0.554f, 0.332f, 0.745f) curveToRelative(1.06f, 0.951f, 1.668f, 2.307f, 1.668f, 3.719f) curveToRelative(0.0f, 2.757f, -2.243f, 5.0f, -5.0f, 5.0f) close() } } .build() return _thermometerEmpty!! } private var _thermometerEmpty: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,340
icons
MIT License
test/multiplication/MultiplicationTest.kt
josimar-jr
311,495,075
false
null
package org.josimarjr.msmulti.multiplication import com.google.gson.Gson import io.ktor.http.* import kotlin.test.* import io.ktor.server.testing.* import org.josimarjr.msmulti.module import kotlin.test.assertEquals import org.junit.Assert class MultiplicationTest { @Test fun testMultiplicationService() { Assert.assertEquals(24.0, multiplicationService(2.0, 12.0), 0.001) } @Test fun testMultiplyWithIntegers() { withTestApplication({ module(testing = true) }) { handleRequest(HttpMethod.Get, "/multiply/12/2").apply { assertEquals(HttpStatusCode.OK, response.status()) val responseType = assertNotNull(response.headers[HttpHeaders.ContentType]) assertEquals(ContentType.Application.Json.withCharset(Charsets.UTF_8), ContentType.parse(responseType)) val map: Map<String, Double> = HashMap() val body = Gson().fromJson(response.content, map.javaClass) Assert.assertEquals(24.0, body["result"].toString().toDouble(), 0.001) } } } @Test fun testMultiplyWithDoubles() { withTestApplication({ module(testing = true) }) { handleRequest(HttpMethod.Get, "/multiply/12.3/3.1").apply { assertEquals(HttpStatusCode.OK, response.status()) val responseType = assertNotNull(response.headers[HttpHeaders.ContentType]) assertEquals(ContentType.Application.Json.withCharset(Charsets.UTF_8), ContentType.parse(responseType)) val map: Map<String, Double> = HashMap() val body = Gson().fromJson(response.content, map.javaClass) Assert.assertEquals(38.13, body["result"].toString().toDouble(), 0.001) } } } }
0
Kotlin
0
0
d59d54add8ebd6d33a7f6dcab89cdc740fd22ae6
1,810
ms_calc_multiplication
MIT License
src/main/kotlin/com/miquido/stringstranslator/parsing/spreadsheet/StringHtmlAwareEscaper.kt
miquido
185,740,724
false
null
package com.miquido.stringstranslator.parsing.spreadsheet import com.miquido.stringstranslator.extensions.escape class StringHtmlAwareEscaper( private val escapeMap: Map<String, String> ) { fun escape(text: String): String { var result = text val valuesToReplace = text.split(HTML_TAG_REGEX) valuesToReplace.forEach { result = result.replace(it, it.escape(escapeMap)) } return result } private companion object { private val HTML_TAG_REGEX = Regex("<([^<])*?>") } }
0
Kotlin
1
3
6e18752563582621928f8ef40043a7f0a27a6d08
555
2match
Apache License 2.0
plugin-bazel-event-service/src/main/kotlin/bazel/v1/handlers/InvocationAttemptStartedHandler.kt
JetBrains
143,697,750
false
{"Kotlin": 450492, "Java": 15926, "Starlark": 4160, "Gherkin": 3553, "ANTLR": 1773, "Batchfile": 968, "CSS": 636}
/* * Copyright 2000-2023 JetBrains s.r.o. * * 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 bazel.v1.handlers import bazel.HandlerPriority import bazel.events.InvocationAttemptStarted import bazel.events.OrderedBuildEvent class InvocationAttemptStartedHandler : EventHandler { override val priority: HandlerPriority = HandlerPriority.Medium override fun handle(ctx: HandlerContext): OrderedBuildEvent = if (ctx.event.hasInvocationAttemptStarted()) { InvocationAttemptStarted( ctx.streamId, ctx.sequenceNumber, ctx.eventTime, ctx.event.invocationAttemptStarted.attemptNumber) } else ctx.handlerIterator.next().handle(ctx) }
8
Kotlin
10
13
0b4f86b2e4c92843fbf15c47393a107f26ba1d2f
1,287
teamcity-bazel-plugin
Apache License 2.0
app/src/main/kotlin/com/droibit/autoggler/edit/add/AddGeofenceContract.kt
droibit
107,518,827
false
{"Gradle": 3, "YAML": 1, "Java Properties": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Text": 1, "Markdown": 1, "JSON": 1, "Proguard": 2, "Kotlin": 90, "Java": 1, "XML": 31}
package com.droibit.autoggler.edit.add import android.location.Location import android.os.Bundle import android.support.annotation.StringRes import com.droibit.autoggler.data.repository.geofence.Geofence import com.droibit.autoggler.data.repository.location.AvailableStatus import com.droibit.autoggler.data.repository.location.UnavailableLocationException import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.Marker import rx.Observable import rx.Single interface AddGeofenceContract { interface View { fun saveInstanceState(outStateWrapper: ()->Bundle, geofence: Geofence) fun hasGeofenceGeometory(): Boolean fun canDropMarker(): Boolean fun dropMarker(point: LatLng) fun showMarkerInfoWindow(marker: Marker) fun hideMarkerInfoWindow(marker: Marker) fun setMarkerInfoWindow(title: String, snippet: String?) fun isDragActionModeShown(): Boolean fun showEditDialog(target: Geofence) fun startMarkerDragMode() fun enableMyLocationButton(enabled: Boolean) fun setLocation(location: Location) fun setLocation(location: LatLng) fun setDoneButtonEnabled(enabled: Boolean) fun showDoneButton() fun hideDoneButton() fun showGeofenceCircle() fun hideGeofenceCircle() fun setGeofenceRadius(radius: Double) fun showErrorToast(@StringRes msgId: Int) fun showLocationPermissionRationaleSnackbar() } interface Navigator { fun showLocationResolutionDialog(status: AvailableStatus) fun navigationToUp() fun finish(result: Geofence) } interface RuntimePermissions { enum class Usage(val requestCode: Int) { GET_LOCATION(requestCode = 1), GEOFENCING(requestCode = 2) } fun requestLocationPermission(usage: RuntimePermissions.Usage) } interface Presenter { fun onCreate() fun subscribe() fun unsubscribe() fun onSavedInstanceState(outStateWrapper: ()->Bundle) // View fun onMapLongClicked(point: LatLng) fun onMarkerInfoWindowClicked() fun onMarkerDropped(marker: Marker) fun onMarkerClicked(marker: Marker) fun onMarkerDragStart(marker: Marker) fun onMarkerDragEnd() fun onPrepareDragMode(marker: Marker) fun onFinishedDragMode(marker: Marker) fun onGeofenceUpdated(updated: Geofence) fun onDoneButtonClicked() // Navigator fun onUpNavigationButtonClicked() fun onLocationResolutionResult(resolved: Boolean) // RuntimePermissions fun onLocationPermissionsResult(usage: RuntimePermissions.Usage, granted: Boolean) } interface GetCurrentLocationTask { sealed class GetCurrentLocationEvent { class OnSuccess(val location: Location?) : GetCurrentLocationEvent() class OnError(val exception: UnavailableLocationException) : GetCurrentLocationEvent() object Nothing : GetCurrentLocationEvent() } fun requestLocation() fun asObservable(): Observable<GetCurrentLocationEvent> } interface RegisterGeofencingTask { fun register(geofence: Geofence): Single<Boolean> } }
0
Kotlin
0
0
10981725d9d89bf90aa5a0f46ae6eb7e29a6b922
3,361
autoggler
Apache License 2.0
common/src/commonMain/kotlin/dev/johnoreilly/common/stationlist/StationListPresenter.kt
joreilly
222,286,745
false
{"Kotlin": 59073, "Jupyter Notebook": 48792, "Swift": 15287, "Ruby": 3801, "HTML": 1154}
package dev.johnoreilly.common.stationlist import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import com.slack.circuit.runtime.CircuitContext import com.slack.circuit.runtime.Navigator import com.slack.circuit.runtime.presenter.Presenter import com.slack.circuit.runtime.screen.Screen import dev.johnoreilly.common.screens.StationListScreen import dev.johnoreilly.common.repository.CityBikesRepository import me.tatarka.inject.annotations.Assisted import me.tatarka.inject.annotations.Inject @Inject class StationListPresenterFactory( private val presenterFactory: (StationListScreen, Navigator) -> StationListPresenter ) : Presenter.Factory { override fun create(screen: Screen, navigator: Navigator, context: CircuitContext): Presenter<*>? { return when (screen) { is StationListScreen -> presenterFactory(screen, navigator) else -> null } } } @Inject class StationListPresenter( @Assisted private val screen: StationListScreen, @Assisted private val navigator: Navigator, private val cityBikesRepository: CityBikesRepository ) : Presenter<StationListScreen.State> { @Composable override fun present(): StationListScreen.State { val stationList by cityBikesRepository.pollNetworkUpdates(screen.networkId).collectAsState(emptyList()) return StationListScreen.State(screen.networkId, stationList) { event -> when (event) { StationListScreen.Event.BackClicked -> navigator.pop() } } } }
13
Kotlin
49
691
66b66c5b8c606991e776016c79ec3eca8ec2e952
1,611
BikeShare
Apache License 2.0
app/src/main/java/net/mm2d/orientation/view/dialog/NightModeDialogViewModel.kt
ohmae
30,814,736
false
null
/* * Copyright (c) 2021 大前良介 (<NAME>) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.orientation.view.dialog import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import net.mm2d.orientation.util.NoStateLiveData class NightModeDialogViewModel : ViewModel() { private val liveData: MutableLiveData<Int> = NoStateLiveData() fun postMode(mode: Int) { liveData.postValue(mode) } fun modeLiveData(): LiveData<Int> = liveData }
2
Kotlin
13
27
decf6fc0d7e5978a107bee1e7fd379e989821d9e
577
orientation-faker
MIT License
Browser/src/commonMain/kotlin/io/nacular/doodle/drawing/impl/VectorRenderer.kt
Hazer
273,358,963
true
{"Kotlin": 1307880}
package io.nacular.doodle.drawing.impl import io.nacular.doodle.drawing.Brush import io.nacular.doodle.drawing.Font import io.nacular.doodle.drawing.Pen import io.nacular.doodle.drawing.Renderer import io.nacular.doodle.drawing.Shadow import io.nacular.doodle.geometry.Circle import io.nacular.doodle.geometry.Ellipse import io.nacular.doodle.geometry.Point import io.nacular.doodle.geometry.Rectangle import io.nacular.doodle.text.StyledText /** * VectorRenderers provide vector rendering implementations. */ internal interface VectorRenderer: Renderer { fun rect(rectangle: Rectangle, brush: Brush ) fun rect(rectangle: Rectangle, pen: Pen, brush: Brush? = null) fun rect(rectangle: Rectangle, radius: Double, brush: Brush) fun rect(rectangle: Rectangle, radius: Double, pen: Pen, brush: Brush? = null) fun circle(circle: Circle, brush: Brush ) fun circle(circle: Circle, pen: Pen, brush: Brush? = null) fun ellipse(ellipse: Ellipse, brush: Brush ) fun ellipse(ellipse: Ellipse, pen: Pen, brush: Brush? = null) fun text(text: String, font: Font? = null, at: Point, brush: Brush) fun text(text: StyledText, at: Point) fun wrapped( text : String, font : Font? = null, at : Point, leftMargin : Double, rightMargin: Double, brush : Brush) fun wrapped( text : StyledText, at : Point, leftMargin : Double, rightMargin: Double) // fun clip(rectangle: Rectangle, block: VectorRenderer.() -> Unit) fun add (shadow: Shadow) fun remove(shadow: Shadow) } internal typealias VectorRendererFactory = (CanvasContext) -> VectorRenderer
0
null
0
0
f878abf3163a49d515038f6699a4124f087e9885
1,818
doodle
MIT License
gradle-plugin/src/main/kotlin/dev/schlaubi/mikbot/gradle/MikBotRepositories.kt
DRSchlaubi
409,332,765
false
null
package dev.schlaubi.mikbot.gradle import org.gradle.api.Project import org.gradle.api.artifacts.dsl.DependencyHandler fun Project.addRepositories() { repositories.mavenCentral() repositories.maven { it.name = "Mikbot" it.url = uri("https://schlaubi.jfrog.io/artifactory/mikbot/") } repositories.maven { it.name = "Envconf" it.url = uri("https://schlaubi.jfrog.io/artifactory/envconf/") } repositories.maven { it.name = "Kotlin Discord" it.url = uri("https://maven.kotlindiscord.com/repository/maven-public/") } repositories.maven { it.name = "Sonatype Snapshots" it.url = uri("https://s01.oss.sonatype.org/content/repositories/snapshots") } repositories.maven { it.name = "Sonatype Snapshots" it.url = uri("https://oss.sonatype.org/content/repositories/snapshots") } } fun Project.addDependencies() { dependencies.apply { // this one is included in the bot itself add("compileOnly", "org.jetbrains.kotlin:kotlin-stdlib") add("compileOnly", mikbot("api")) if (configurations.findByName("ksp") != null) { add("ksp", mikbot("plugin-processor")) } else { logger.warn("Could not add KSP processor automatically, because KSP plugin is not installed!") } } } private fun DependencyHandler.mikbot(module: String): Any = if (MikBotPluginInfo.IS_MIKBOT) project(mapOf("path" to ":$module")) else "dev.schlaubi:mikbot-$module:${MikBotPluginInfo.VERSION}"
17
Kotlin
11
34
7adfe219c243360c4f144d0eef16f1202e0f993d
1,557
mikbot
MIT License
app/src/test/java/ch/admin/foitt/pilotwallet/feature/deeplink/HandleDeeplinkTest.kt
e-id-admin
775,912,525
false
null
package ch.admin.foitt.pilotwallet.feature.deeplink import ch.admin.foitt.openid4vc.domain.model.presentationRequest.PresentationDefinition import ch.admin.foitt.openid4vc.domain.model.presentationRequest.PresentationRequest import ch.admin.foitt.pilotwallet.feature.onboarding.navigation.OnboardingNavGraph import ch.admin.foitt.pilotwallet.platform.deeplink.domain.repository.DeepLinkIntentRepository import ch.admin.foitt.pilotwallet.platform.deeplink.domain.usecase.HandleDeeplink import ch.admin.foitt.pilotwallet.platform.deeplink.domain.usecase.implementation.HandleDeeplinkImpl import ch.admin.foitt.pilotwallet.platform.invitation.domain.model.InvitationError import ch.admin.foitt.pilotwallet.platform.invitation.domain.model.ProcessInvitationError import ch.admin.foitt.pilotwallet.platform.invitation.domain.model.ProcessInvitationResult import ch.admin.foitt.pilotwallet.platform.invitation.domain.usecase.ProcessInvitation import ch.admin.foitt.pilotwallet.platform.navArgs.domain.model.CredentialOfferNavArg import ch.admin.foitt.pilotwallet.platform.navigation.NavigationManager import ch.admin.foitt.pilotwallet.platform.scaffold.extension.navigateUpOrToRoot import ch.admin.foitt.pilotwallet.platform.ssi.domain.model.CompatibleCredential import ch.admin.foitt.pilotwalletcomposedestinations.destinations.CredentialOfferScreenDestination import ch.admin.foitt.pilotwalletcomposedestinations.destinations.HomeScreenDestination import ch.admin.foitt.pilotwalletcomposedestinations.destinations.InvalidCredentialErrorScreenDestination import ch.admin.foitt.pilotwalletcomposedestinations.destinations.InvitationFailureScreenDestination import ch.admin.foitt.pilotwalletcomposedestinations.destinations.NoInternetConnectionScreenDestination import ch.admin.foitt.pilotwalletcomposedestinations.destinations.UnknownIssuerErrorScreenDestination import com.github.michaelbull.result.Err import com.github.michaelbull.result.Ok import com.ramcosta.composedestinations.spec.Direction import io.mockk.MockKAnnotations import io.mockk.clearMocks import io.mockk.coEvery import io.mockk.coVerify import io.mockk.coVerifyOrder import io.mockk.impl.annotations.MockK import io.mockk.just import io.mockk.runs import io.mockk.unmockkAll import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Before import org.junit.Test class HandleDeeplinkTest { @MockK private lateinit var mockNavigationManager: NavigationManager @MockK private lateinit var mockDeepLinkIntentRepository: DeepLinkIntentRepository @MockK private lateinit var mockProcessInvitation: ProcessInvitation private lateinit var handleDeeplinkUseCase: HandleDeeplink @Before fun setUp() { MockKAnnotations.init(this) coEvery { mockProcessInvitation(invitationUri = any()) } returns Ok(mockCredentialOfferResult) coEvery { mockDeepLinkIntentRepository.get() } returns someDeepLink coEvery { mockNavigationManager.navigateToAndPopUpTo(any(), any()) } just runs coEvery { mockNavigationManager.navigateToAndClearCurrent(any()) } just runs coEvery { mockNavigationManager.navigateUpOrToRoot() } just runs coEvery { mockDeepLinkIntentRepository.reset() } just runs handleDeeplinkUseCase = HandleDeeplinkImpl( navManager = mockNavigationManager, deepLinkIntentRepository = mockDeepLinkIntentRepository, processInvitation = mockProcessInvitation, ) } @After fun tearDown() { unmockkAll() } @Test fun `Coming from onboarding, on no intent, navigates to home screen and pop onboarding`() = runTest { coEvery { mockDeepLinkIntentRepository.get() } returns null handleDeeplinkUseCase(true).navigate() coVerifyOrder { mockDeepLinkIntentRepository.get() mockNavigationManager.navigateToAndPopUpTo( direction = HomeScreenDestination, route = OnboardingNavGraph.NAME, ) } } @Test fun `Not being in onboarding, on no intent, navigates up or to root`() = runTest { coEvery { mockDeepLinkIntentRepository.get() } returns null handleDeeplinkUseCase(false).navigate() coVerifyOrder { mockDeepLinkIntentRepository.get() mockNavigationManager.navigateUpOrToRoot() } } @Test fun `On deeplink handling, reset the repository to null`() = runTest { handleDeeplinkUseCase(false).navigate() coVerifyOrder { mockDeepLinkIntentRepository.get() mockDeepLinkIntentRepository.reset() } } @Test fun `On deeplink handling, in onboarding, pop the onboarding stack in all success cases`() = runTest { mockSuccesses.forEach { success -> coEvery { mockProcessInvitation(someDeepLink) } returns Ok(success) handleDeeplinkUseCase(true).navigate() coVerify(exactly = 1) { mockNavigationManager.navigateToAndPopUpTo(any(), route = OnboardingNavGraph.NAME) } clearMocks(mockNavigationManager, answers = false) } } @Test fun `On deeplink handling, not in onboarding, navigate and pop current screen in all success cases`() = runTest { mockSuccesses.forEach { success -> coEvery { mockProcessInvitation(someDeepLink) } returns Ok(success) handleDeeplinkUseCase(false).navigate() coVerify(exactly = 1) { mockNavigationManager.navigateToAndClearCurrent(any()) } clearMocks(mockNavigationManager, answers = false) } } @Test fun `On deeplink handling, in onboarding, pop the onboarding stack in all failure cases`() = runTest { mockFailures.forEach { failure -> coEvery { mockProcessInvitation(someDeepLink) } returns Err(failure) handleDeeplinkUseCase(true).navigate() coVerify(exactly = 1) { mockNavigationManager.navigateToAndPopUpTo(any(), route = OnboardingNavGraph.NAME) } clearMocks(mockNavigationManager, answers = false) } } @Test fun `On deeplink handling, not in onboarding, navigate and pop current screen in all failure cases`() = runTest { mockFailures.forEach { failure -> coEvery { mockProcessInvitation(someDeepLink) } returns Err(failure) handleDeeplinkUseCase(false).navigate() coVerify(exactly = 1) { mockNavigationManager.navigateToAndClearCurrent(any()) } clearMocks(mockNavigationManager, answers = false) } } @Test fun `On credential offer, navigates to credential offer screen`() = runTest { coEvery { mockProcessInvitation(someDeepLink) } returns Ok(mockCredentialOfferResult) handleDeeplinkUseCase(false).navigate() coVerify(exactly = 1) { mockNavigationManager.navigateToAndClearCurrent(any()) mockNavigationManager.navigateToAndClearCurrent( direction = CredentialOfferScreenDestination( CredentialOfferNavArg( mockCredentialOfferResult.credentialId ) ), ) } } @Test fun `On presentation request, navigate to an error`() = runTest { coEvery { mockProcessInvitation(someDeepLink) } returns Ok(mockPresentationRequestResult) handleDeeplinkUseCase(false).navigate() coVerify(exactly = 1) { mockNavigationManager.navigateToAndClearCurrent(any()) mockNavigationManager.navigateToAndClearCurrent( direction = InvalidCredentialErrorScreenDestination, ) } } @Test fun `On presentation request with multiple credentials, navigate to an error`() = runTest { coEvery { mockProcessInvitation(someDeepLink) } returns Ok(mockPresentationRequestListResult) handleDeeplinkUseCase(false).navigate() coVerify(exactly = 1) { mockNavigationManager.navigateToAndClearCurrent(any()) mockNavigationManager.navigateToAndClearCurrent( direction = InvalidCredentialErrorScreenDestination, ) } } @Test fun `On deeplink processing failure, navigate to the defined error screen`() = runTest { val definedErrorDestinations: Map<ProcessInvitationError, Direction> = mapOf( InvitationError.EmptyWallet to InvitationFailureScreenDestination, InvitationError.InvalidCredentialInvitation to InvalidCredentialErrorScreenDestination, InvitationError.InvalidInput to InvalidCredentialErrorScreenDestination, InvitationError.NetworkError to NoInternetConnectionScreenDestination(someDeepLink), InvitationError.NoMatchingCredential to InvitationFailureScreenDestination, InvitationError.Unexpected to InvitationFailureScreenDestination, InvitationError.UnknownIssuer to UnknownIssuerErrorScreenDestination, InvitationError.UnknownVerifier to InvitationFailureScreenDestination, ) definedErrorDestinations.forEach { (error, destination) -> coEvery { mockProcessInvitation(someDeepLink) } returns Err(error) handleDeeplinkUseCase(false).navigate() coVerify(exactly = 1) { mockNavigationManager.navigateToAndClearCurrent(any()) mockNavigationManager.navigateToAndClearCurrent( direction = destination, ) } clearMocks(mockNavigationManager, answers = false) } } companion object { private const val someDeepLink = "openid-credential-offer://credential_offer=..." private val mockCredentialOfferResult = ProcessInvitationResult.CredentialOffer(0L) private val mockPresentationRequest = PresentationRequest( nonce = "iusto", presentationDefinition = PresentationDefinition( id = "diam", inputDescriptors = listOf() ), responseUri = "tincidunt", responseMode = "suscipit", state = null, clientMetaData = null ) private val mockCompatibleCredential = CompatibleCredential( credentialId = mockCredentialOfferResult.credentialId, requestedFields = listOf(), ) private val mockPresentationRequestResult = ProcessInvitationResult.PresentationRequest( mockCompatibleCredential, mockPresentationRequest, ) private val mockPresentationRequestListResult = ProcessInvitationResult.PresentationRequestCredentialList( listOf(mockCompatibleCredential), mockPresentationRequest, ) private val mockSuccesses: List<ProcessInvitationResult> = listOf( ProcessInvitationResult.CredentialOffer(0L), ProcessInvitationResult.PresentationRequest(CompatibleCredential(0L, listOf()), mockPresentationRequest), ProcessInvitationResult.PresentationRequestCredentialList(listOf(), mockPresentationRequest), ) private val mockFailures: List<ProcessInvitationError> = listOf( InvitationError.EmptyWallet, InvitationError.InvalidCredentialInvitation, InvitationError.InvalidInput, InvitationError.NetworkError, InvitationError.NoMatchingCredential, InvitationError.Unexpected, InvitationError.UnknownIssuer, InvitationError.UnknownVerifier, ) } }
1
null
1
4
6572b418ec5abc5d94b18510ffa87a1e433a5c82
11,777
eidch-pilot-android-wallet
MIT License
geary-commons/src/main/kotlin/com/mineinabyss/geary/commons/components/interaction/Attacked.kt
MineInAbyss
388,677,224
false
null
package com.mineinabyss.geary.commons.components.interaction class Attacked
5
Kotlin
3
1
179d10613b13dd1df83fe169d1333d8b994d9ec8
77
Geary-addons
MIT License
app/src/main/java/com/example/shethpath/App.kt
nervster
474,202,455
false
{"Kotlin": 24219}
package com.example.shethpath import android.app.Application import android.util.Log import com.parse.Parse import com.parse.ParseObject class App : Application() { override fun onCreate() { super.onCreate() // set up for using the post class ParseObject.registerSubclass(Post::class.java) Parse.initialize( Parse.Configuration.Builder(this) .applicationId(getString(R.string.back4app_app_id)) .clientKey(getString(R.string.back4app_client_key)) .server(getString(R.string.back4app_server_url)) .build()); // val firstObject = ParseObject("FirstClass") // firstObject.put("message","Hey ! First message from android. Parse is now connected") // firstObject.saveInBackground { // if (it != null){ // it.localizedMessage?.let { message -> Log.e("App", message) } // }else{ // Log.d("App","Object saved.") // } // } } }
2
Kotlin
0
0
4e7621b563e4c0682d3f713d6b801e1301f56326
1,025
ShethPath
Apache License 2.0
forage-android/src/test/java/com/joinforage/forage/android/core/element/state/PanElementStateManagerTest.kt
teamforage
554,343,430
false
{"Kotlin": 369140}
package com.joinforage.forage.android.core.element.state import com.joinforage.forage.android.core.element.IncompleteEbtPanError import com.joinforage.forage.android.core.element.InvalidEbtPanError import com.joinforage.forage.android.core.element.StatefulElementListener import com.joinforage.forage.android.core.element.TooLongEbtPanError import com.joinforage.forage.android.model.USState import org.assertj.core.api.Assertions.assertThat import org.junit.Test class StrictForEmptyInputTest { @Test fun `cardNumber as empty string`() { val manager = PanElementStateManager.forEmptyInput() manager.handleChangeEvent("") val state = manager.getState() assertThat(state.isValid).isTrue assertThat(state.isComplete).isFalse assertThat(state.validationError).isNull() assertThat(state.derivedCardInfo).isEqualTo(DerivedCardInfoDto()) } @Test fun `cardNumber too short to contain IIN`() { val tooShortNoIIN: String = "420" val manager = PanElementStateManager.forEmptyInput() manager.handleChangeEvent(tooShortNoIIN) val state = manager.getState() // we want to consider a card valid as long as we don't have // a definitive reason to think it is invalid. If we don't // have enough digits to know if its a valid StateIIN, then // we'll consider it valid for now. assertThat(state.isValid).isTrue assertThat(state.isComplete).isFalse assertThat(state.validationError).isEqualTo(IncompleteEbtPanError) assertThat(state.derivedCardInfo).isEqualTo(DerivedCardInfoDto()) } @Test fun `cardNumber has non-existent IIN`() { val invalidIIN: String = "420420420" val manager = PanElementStateManager.forEmptyInput() manager.handleChangeEvent(invalidIIN) val state = manager.getState() assertThat(state.isValid).isFalse assertThat(state.isComplete).isFalse assertThat(state.validationError).isEqualTo(InvalidEbtPanError) assertThat(state.derivedCardInfo).isEqualTo(DerivedCardInfoDto()) } @Test fun `cardNumber has valid state IIN but is shorter than expected length`() { val tooShortMaineNumber: String = "507703111" // Maine is 507703 val manager = PanElementStateManager.forEmptyInput() manager.handleChangeEvent(tooShortMaineNumber) val state = manager.getState() assertThat(state.isValid).isTrue assertThat(state.isComplete).isFalse assertThat(state.validationError).isEqualTo(IncompleteEbtPanError) assertThat(state.derivedCardInfo).isEqualTo(DerivedCardInfoDto(USState.MAINE)) } @Test fun `cardNumber has valid state IIN and is correct length`() { val okMaineNumber: String = "5077031111111111111" // Maine is 507703 val manager = PanElementStateManager.forEmptyInput() manager.handleChangeEvent(okMaineNumber) val state = manager.getState() assertThat(state.isValid).isTrue assertThat(state.isComplete).isTrue assertThat(state.validationError).isNull() assertThat(state.derivedCardInfo).isEqualTo(DerivedCardInfoDto(USState.MAINE)) } @Test fun `cardNumber has valid state IIN and is too long`() { // NOTE: we expect the view to enforce max length based on IIN // but for good measure we'll make sure validation knows to handle // this case val longMaineNumber: String = "50770311111111111110" // Maine is 507703 val manager = PanElementStateManager.forEmptyInput() manager.handleChangeEvent(longMaineNumber) val state = manager.getState() assertThat(state.isValid).isFalse assertThat(state.isComplete).isFalse assertThat(state.validationError).isEqualTo(TooLongEbtPanError) assertThat(state.derivedCardInfo).isEqualTo(DerivedCardInfoDto(USState.MAINE)) } } class DEV_ONLY_IntegrationTests { @Test fun `StrictEbtValidator - correctly flags valid`() { val okMaineNumber: String = "5077031111111111111" // Maine is 507703 val manager = PanElementStateManager.NON_PROD_forEmptyInput() manager.handleChangeEvent(okMaineNumber) val state = manager.getState() assertThat(state.isValid).isTrue assertThat(state.isComplete).isTrue assertThat(state.validationError).isNull() assertThat(state.derivedCardInfo).isEqualTo(DerivedCardInfoDto(USState.MAINE)) } @Test fun `PaymentCaptureErrorCard - correctly flags valid`() { val whitelistedPAN: String = "4444444444444412345" val manager = PanElementStateManager.NON_PROD_forEmptyInput() manager.handleChangeEvent(whitelistedPAN) val state = manager.getState() assertThat(state.isValid).isTrue assertThat(state.isComplete).isTrue assertThat(state.derivedCardInfo).isEqualTo(DerivedCardInfoDto()) } @Test fun `BalanceCheckErrorCard - correctly flags valid`() { val whitelistedPAN: String = "5555555555555512345" val manager = PanElementStateManager.NON_PROD_forEmptyInput() manager.handleChangeEvent(whitelistedPAN) val state = manager.getState() assertThat(state.isValid).isTrue assertThat(state.isComplete).isTrue assertThat(state.derivedCardInfo).isEqualTo(DerivedCardInfoDto()) } @Test fun `NonProdValidEbtCard - correctly flags valid`() { val whitelistedPAN: String = "9999420420420420420" val manager = PanElementStateManager.NON_PROD_forEmptyInput() manager.handleChangeEvent(whitelistedPAN) val state = manager.getState() assertThat(state.isValid).isTrue assertThat(state.isComplete).isTrue assertThat(state.derivedCardInfo).isEqualTo(DerivedCardInfoDto()) } @Test fun `EmptyEbtCashBalanceCard - correctly flags valid`() { val whitelistedPAN: String = "6543210000000000000" val manager = PanElementStateManager.NON_PROD_forEmptyInput() manager.handleChangeEvent(whitelistedPAN) val state = manager.getState() assertThat(state.isValid).isTrue assertThat(state.isComplete).isTrue assertThat(state.derivedCardInfo).isEqualTo(DerivedCardInfoDto()) } @Test fun `empty string is valid`() { val manager = PanElementStateManager.NON_PROD_forEmptyInput() manager.handleChangeEvent("") val state = manager.getState() assertThat(state.isValid).isTrue assertThat(state.isComplete).isFalse assertThat(state.validationError).isNull() assertThat(state.derivedCardInfo).isEqualTo(DerivedCardInfoDto()) } @Test fun `non-whitelisted invalid Ebt Pan should be invalid`() { val manager = PanElementStateManager.NON_PROD_forEmptyInput() manager.handleChangeEvent("4204204204204204204") val state = manager.getState() assertThat(state.isValid).isFalse assertThat(state.isComplete).isFalse assertThat(state.validationError).isEqualTo(InvalidEbtPanError) assertThat(state.derivedCardInfo).isEqualTo(DerivedCardInfoDto()) } } class TestWhitelistedCards { @Test fun `prefix can be repeated arbitrary times`() { val whitelistValidator = WhitelistedCards("hello", 2) val validStr = "hellohello" assertThat(whitelistValidator.checkIfValid(validStr)).isTrue } @Test fun `complete accepts length 16 card number`() { val whitelistValidator = WhitelistedCards("hello", 2) val completeStr = "hellohello******" assertThat(whitelistValidator.checkIfComplete(completeStr)).isTrue } @Test fun `complete accepts length 19 card number`() { val whitelistValidator = WhitelistedCards("hello", 2) val completeStr = "hellohello*********" assertThat(whitelistValidator.checkIfComplete(completeStr)).isTrue } @Test fun `complete rejects too short and too long numbers`() { val whitelistValidator = WhitelistedCards("hello", 2) val tooShort = "hellohello" assertThat(whitelistValidator.checkIfValid(tooShort)).isTrue assertThat(whitelistValidator.checkIfComplete(tooShort)).isFalse val tooLong = "hellohello****************" assertThat(whitelistValidator.checkIfValid(tooLong)).isTrue assertThat(whitelistValidator.checkIfComplete(tooLong)).isFalse } @Test fun `complete and valid require matching prefix`() { val whitelistValidator = WhitelistedCards("hello", 2) val invalidCompleteStr = "hello12345*********" assertThat(whitelistValidator.checkIfValid(invalidCompleteStr)).isFalse assertThat(whitelistValidator.checkIfComplete(invalidCompleteStr)).isFalse val completeStr = "hellohello*********" assertThat(whitelistValidator.checkIfValid(completeStr)).isTrue assertThat(whitelistValidator.checkIfComplete(completeStr)).isTrue } @Test fun `validationError is always null`() { val whitelistValidator = WhitelistedCards("hello", 2) val emptyStr = "" assertThat(whitelistValidator.checkForValidationError(emptyStr)).isNull() val shortAndDoesNotMatchPrefixStr = "hello12345" assertThat(whitelistValidator.checkForValidationError(shortAndDoesNotMatchPrefixStr)).isNull() val correctLengthAndDoesNotMatchPrefixStr = "hello12345*********" assertThat(whitelistValidator.checkForValidationError(correctLengthAndDoesNotMatchPrefixStr)).isNull() val validIncompleteStr = "hellohello" assertThat(whitelistValidator.checkForValidationError(validIncompleteStr)).isNull() val completeStr = "hellohello*********" assertThat(whitelistValidator.checkForValidationError(completeStr)).isNull() } } class PanIsEmptyTest { @Test fun `cardNumber is length 0`() { val manager = PanElementStateManager.forEmptyInput() manager.handleChangeEvent("") val state = manager.getState() assertThat(state.isEmpty).isTrue } @Test fun `cardNumber is not empty`() { val manager = PanElementStateManager.forEmptyInput() manager.handleChangeEvent("1") val state = manager.getState() assertThat(state.isEmpty).isFalse } } class PanHandleChangeEventTest { @Test fun `valid card 16-digit card number passes correct state to callback`() { val manager = PanElementStateManager.forEmptyInput() var state: PanElementState = manager.getState() val callback: StatefulElementListener<PanElementState> = { newState -> state = newState } manager.setOnChangeEventListener(callback) manager.handleChangeEvent("5076807890123456") // TODO: its not clear that we should make any assertions // about the resulting state of isFocus or isBlur. Should // handle events update the focus / blurred state?? assertThat(state.isEmpty).isFalse assertThat(state.isValid).isTrue assertThat(state.isComplete).isTrue assertThat(state.validationError).isNull() assertThat(state.derivedCardInfo).isEqualTo(DerivedCardInfoDto(USState.ALABAMA)) } @Test fun `setting multiple callbacks only invokes most recently set callback`() { val manager = PanElementStateManager.forEmptyInput() var callbackAInvoked = false var callbackBInvoked = false val callbackA: StatefulElementListener<PanElementState> = { callbackAInvoked = true } val callbackB: StatefulElementListener<PanElementState> = { callbackBInvoked = true } manager.setOnChangeEventListener(callbackA) manager.setOnChangeEventListener(callbackB) manager.handleChangeEvent("1234567890123456") // only the current callback should be invoked assertThat(callbackAInvoked).isFalse assertThat(callbackBInvoked).isTrue } @Test fun `strips all non-digit characters before processing`() { val manager = PanElementStateManager.forEmptyInput() var state: PanElementState = manager.getState() val callback: StatefulElementListener<PanElementState> = { newState -> state = newState } val validStringContaminatedByOtherChars = "!@# $%^ &*()_+<>? abcd5076807890123456" manager.setOnChangeEventListener(callback) manager.handleChangeEvent(validStringContaminatedByOtherChars) assertThat(state.isEmpty).isFalse assertThat(state.isValid).isTrue assertThat(state.isComplete).isTrue assertThat(state.validationError).isNull() assertThat(state.derivedCardInfo).isEqualTo(DerivedCardInfoDto(USState.ALABAMA)) } }
6
Kotlin
0
0
cd3a7335b3d4a5212d113a61f82407bc4c8d0eef
12,857
forage-android-sdk
MIT License
core/src/main/kotlin/net/corda/core/flows/FlowVersion.kt
sasukeh
90,589,627
true
{"Kotlin": 2569685, "Java": 151940, "Groovy": 26438, "Shell": 289, "Batchfile": 106}
package net.corda.core.flows /** * Annotation for initiating [FlowLogic]s to specify the version of their flow protocol. The version is a single integer * [value] which increments by one whenever a release is made where the flow protocol changes in any manner which is * backwards incompatible. This may be a change in the sequence of sends and receives between the client and service flows, * or it could be a change in the meaning. The version is used when a flow first initiates communication with a party to * inform them what version they are using. For this reason the annotation is not applicable for the initiated flow. * * This flow version integer is not the same as Corda's platform version, though it follows a similar semantic. * * Note: Only one version of the same flow can currently be loaded at the same time. Any session request by a client flow for * a different version will be rejected. * * Defaults to a flow version of 1 if not specified. */ // TODO Add support for multiple versions once CorDapps are loaded in separate class loaders annotation class FlowVersion(val value: Int)
4
Kotlin
0
0
0ed009dfa0c5f0d6b1c51a47900339155335760b
1,117
corda
Apache License 2.0