path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/jvmMain/kotlin/data/InstructionRecord.kt | Mouwrice | 666,317,508 | false | null | package data
/**
* DTO to track a single instruction
*/
data class InstructionRecord(
/**
* The offset of the instruction
*/
val offset: Int,
/**
* String representation of the instruction
*/
val instruction: String,
/**
* Contains the final result computations from the partial evaluator regarding the variables of this instruction.
*/
val finalVariablesBefore: List<String>?,
/**
* Contains the final result computations from the partial evaluator regarding the stack of this instruction.
*/
val finalStackBefore: List<String>?,
/**
* Contains the final result computations from the partial evaluator regarding the target instructions of this instruction.
*/
val finalTargetInstructions: List<Int>?,
/**
* Contains the final result computations from the partial evaluator regarding the source instructions of this instruction.
*/
val finalOriginInstructions: List<Int>?,
)
| 3 | Kotlin | 1 | 3 | a1628bc24328eb117efe5710cdeb9c0410f33556 | 988 | proguard-core-visualizer | Apache License 2.0 |
app/src/main/java/com/codepath/stargram/LoginActivity.kt | melissa-perez | 627,669,161 | false | null | package com.codepath.stargram
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.parse.ParseUser
class LoginActivity : AppCompatActivity() {
private val tag = "LoginActivity/"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
// check if user is logged in -> go to main activity instead
if (ParseUser.getCurrentUser() != null) {
goToMainActivity()
}
findViewById<Button>(R.id.login_button).setOnClickListener {
val username: String = findViewById<EditText>(R.id.stargram_username).text.toString()
val password: String = findViewById<EditText>(R.id.stargram_password).text.toString()
loginUser(username, password)
}
findViewById<Button>(R.id.signup_button).setOnClickListener {
val username: String = findViewById<EditText>(R.id.stargram_username).text.toString()
val password: String = findViewById<EditText>(R.id.stargram_password).text.toString()
signUpUser(username, password)
}
}
private fun signUpUser(username: String, password: String) {
val user = ParseUser()
user.username = username
user.setPassword(password)
user.signUpInBackground { e ->
if (e == null) {
// Hooray! Let them use the app now.
//TODO: user to main show a toast
Log.i(tag, "Successfully signed up user")
goToMainActivity()
} else {
e.printStackTrace()
Toast.makeText(this, "Error sign up user", Toast.LENGTH_SHORT).show()
}
}
}
private fun loginUser(username: String, password: String) {
ParseUser.logInInBackground(
username, password, ({ user, e ->
if (user != null) {
Log.i(tag, "Successfully logged in user")
goToMainActivity()
} else {
e.printStackTrace()
Toast.makeText(this, "Error login in user", Toast.LENGTH_SHORT).show()
}
})
)
}
private fun goToMainActivity() {
val intent = Intent(this@LoginActivity, MainActivity::class.java)
startActivity(intent)
finish()
// need a log out button
//ParseUser.logOut()
//val currentUser = ParseUser.getCurrentUser()
}
} | 0 | Kotlin | 0 | 1 | 49719788addc686ff4879d6f758ac790b091bd2d | 2,693 | Stargram | Apache License 2.0 |
lib/src/commonMain/kotlin/xyz/mcxross/kaptos/core/crypto/Platform.kt | mcxross | 702,366,239 | false | {"Kotlin": 446366, "Shell": 5540} | /*
* Copyright 2024 McXross
*
* 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 xyz.mcxross.kaptos.core.crypto
import xyz.mcxross.kaptos.model.AnyRawTransaction
import xyz.mcxross.kaptos.model.SigningSchemeInput
expect fun generateKeypair(scheme: SigningSchemeInput): KeyPair
expect fun fromSeed(seed: ByteArray): KeyPair
expect fun sha3Hash(input: ByteArray): ByteArray
expect fun sign(message: ByteArray, privateKey: ByteArray): ByteArray
expect fun secp256k1Sign(message: ByteArray, privateKey: ByteArray): ByteArray
expect fun generateSigningMessage(transaction: AnyRawTransaction): ByteArray
expect fun generateSecp256k1PublicKey(privateKey: ByteArray) : ByteArray | 3 | Kotlin | 3 | 0 | 67eb6c08b7ab74da077f34f28eef1ff18e746b15 | 1,196 | kaptos | Apache License 2.0 |
feature/home/src/main/java/com/example/home/HomeScreen.kt | jin5578 | 859,358,191 | false | {"Kotlin": 358326} | package com.example.home
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.example.design_system.component.EmptyContent
import com.example.design_system.component.Loading
import com.example.design_system.component.SortTaskDialog
import com.example.design_system.component.TaskCard
import com.example.design_system.theme.TodoTheme
import com.example.home.component.SwipeActionBox
import com.example.home.component.TaskInfoCard
import com.example.home.model.HomeUiState
import com.example.model.Category
import com.example.model.SortTask
import com.example.model.Task
import com.example.model.Theme
import com.example.model.ThemeType
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.persistentListOf
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import java.time.LocalDate
import java.time.LocalTime
import com.example.design_system.R as DesignSystemR
@Composable
internal fun HomeRoute(
viewModel: HomeViewModel = hiltViewModel(),
navigateCalendar: () -> Unit,
navigateSetting: () -> Unit,
navigateAddTask: () -> Unit,
navigateCompletedTask: (String) -> Unit,
navigateIncompleteTask: (String) -> Unit,
navigateThisWeekTask: (String) -> Unit,
navigateAllTask: (String) -> Unit,
navigateEditTask: (Long) -> Unit,
onShowErrorSnackBar: (throwable: Throwable?) -> Unit,
onShowMessageSnackBar: (message: String) -> Unit,
) {
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
LaunchedEffect(true) {
viewModel.errorFlow.collectLatest { throwable ->
onShowErrorSnackBar(throwable)
}
}
HomeContent(
uiState = uiState,
navigateCalendar = navigateCalendar,
navigateSetting = navigateSetting,
navigateAddTask = navigateAddTask,
navigateCompletedTask = navigateCompletedTask,
navigateIncompleteTask = navigateIncompleteTask,
navigateThisWeekTask = navigateThisWeekTask,
navigateAllTask = navigateAllTask,
navigateEditTask = navigateEditTask,
onSortTaskChanged = viewModel::updateSortTask,
onTaskDelete = viewModel::deleteTask,
onTaskToggleCompletion = { taskId, isChecked ->
viewModel.toggleTaskCompletion(
taskId = taskId,
isCompleted = isChecked
)
},
onShowMessageSnackBar = onShowMessageSnackBar,
)
}
@Composable
private fun HomeContent(
uiState: HomeUiState,
navigateCalendar: () -> Unit,
navigateSetting: () -> Unit,
navigateAddTask: () -> Unit,
navigateCompletedTask: (String) -> Unit,
navigateIncompleteTask: (String) -> Unit,
navigateThisWeekTask: (String) -> Unit,
navigateAllTask: (String) -> Unit,
navigateEditTask: (Long) -> Unit,
onSortTaskChanged: (SortTask) -> Unit,
onTaskDelete: (id: Long, uuid: String) -> Unit,
onTaskToggleCompletion: (Long, Boolean) -> Unit,
onShowMessageSnackBar: (message: String) -> Unit,
) {
when (uiState) {
is HomeUiState.Loading -> {
Loading()
}
is HomeUiState.Success -> {
HomeScreen(
completedTasks = uiState.completedTasks,
incompleteTasks = uiState.incompleteTasks,
categories = uiState.categories,
sleepTime = uiState.sleepTime,
sortTask = uiState.sortTask,
theme = uiState.theme,
buildVersion = uiState.buildVersion,
navigateCalendar = navigateCalendar,
navigateSetting = navigateSetting,
navigateAddTask = navigateAddTask,
navigateCompletedTask = navigateCompletedTask,
navigateIncompleteTask = navigateIncompleteTask,
navigateThisWeekTask = navigateThisWeekTask,
navigateAllTask = navigateAllTask,
navigateEditTask = navigateEditTask,
onSortTaskChanged = onSortTaskChanged,
onTaskDelete = onTaskDelete,
onTaskToggleCompletion = onTaskToggleCompletion,
onShowMessageSnackBar = onShowMessageSnackBar,
)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun HomeScreen(
completedTasks: ImmutableList<Task>,
incompleteTasks: ImmutableList<Task>,
categories: ImmutableList<Category>,
sleepTime: LocalTime,
sortTask: SortTask,
theme: Theme,
buildVersion: String,
navigateCalendar: () -> Unit,
navigateSetting: () -> Unit,
navigateAddTask: () -> Unit,
navigateCompletedTask: (String) -> Unit,
navigateIncompleteTask: (String) -> Unit,
navigateThisWeekTask: (String) -> Unit,
navigateAllTask: (String) -> Unit,
navigateEditTask: (Long) -> Unit,
onSortTaskChanged: (SortTask) -> Unit,
onTaskDelete: (id: Long, uuid: String) -> Unit,
onTaskToggleCompletion: (Long, Boolean) -> Unit,
onShowMessageSnackBar: (message: String) -> Unit,
) {
val translateX = 600f
val leftTranslate = remember { Animatable(-translateX) }
val rightTranslate = remember { Animatable(translateX) }
LaunchedEffect(Unit) {
launch {
leftTranslate.animateTo(
0f,
tween(500)
)
}
launch {
rightTranslate.animateTo(
0f,
tween(500)
)
}
}
var isShowSortTaskDialog by remember { mutableStateOf(false) }
Scaffold(
topBar = {
TopAppBar(
colors = TopAppBarDefaults.topAppBarColors(
containerColor = Color.Transparent
),
title = {
Text(
text = stringResource(id = DesignSystemR.string.app_name),
style = TodoTheme.typography.headlineLarge,
color = MaterialTheme.colorScheme.onSurface
)
},
actions = {
IconButton(
onClick = navigateCalendar
) {
Icon(
modifier = Modifier.size(21.dp),
imageVector = ImageVector.vectorResource(DesignSystemR.drawable.svg_calendar),
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurface
)
}
IconButton(onClick = navigateSetting) {
Icon(
modifier = Modifier.size(24.dp),
imageVector = ImageVector.vectorResource(DesignSystemR.drawable.svg_setting),
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurface
)
}
}
)
},
floatingActionButton = {
FloatingActionButton(
containerColor = MaterialTheme.colorScheme.tertiary,
contentColor = MaterialTheme.colorScheme.surface,
onClick = navigateAddTask,
) {
Icon(
modifier = Modifier.size(32.dp),
imageVector = ImageVector.vectorResource(DesignSystemR.drawable.svg_plus_small),
contentDescription = null
)
}
}
) { paddingValues ->
if (isShowSortTaskDialog) {
SortTaskDialog(
initSortTask = sortTask,
onCloseClick = { isShowSortTaskDialog = false },
onSelectClick = {
onSortTaskChanged(it)
isShowSortTaskDialog = false
}
)
}
Column(
modifier = Modifier.padding(paddingValues),
) {
Row(
modifier = Modifier.fillMaxWidth()
.padding(
horizontal = 16.dp,
vertical = 8.dp
),
horizontalArrangement = Arrangement.spacedBy(16.dp),
verticalAlignment = Alignment.CenterVertically
) {
TaskInfoCard(
modifier = Modifier.weight(1f)
.graphicsLayer {
translationX = leftTranslate.value
},
title = stringResource(DesignSystemR.string.completed),
icon = DesignSystemR.drawable.svg_completed,
content = "Today ${completedTasks.size} Tasks",
backgroundColor = MaterialTheme.colorScheme.primaryContainer,
onClick = navigateCompletedTask,
)
TaskInfoCard(
modifier = Modifier.weight(1f)
.graphicsLayer {
translationX = rightTranslate.value
},
title = stringResource(DesignSystemR.string.incomplete),
icon = DesignSystemR.drawable.svg_incomplete,
content = "Today ${incompleteTasks.size} Tasks",
backgroundColor = MaterialTheme.colorScheme.primaryContainer,
onClick = navigateIncompleteTask,
)
}
Row(
modifier = Modifier.fillMaxWidth()
.padding(
horizontal = 16.dp,
vertical = 8.dp
),
horizontalArrangement = Arrangement.spacedBy(16.dp),
verticalAlignment = Alignment.CenterVertically
) {
TaskInfoCard(
modifier = Modifier.weight(1f)
.graphicsLayer {
translationX = leftTranslate.value
},
title = stringResource(DesignSystemR.string.this_week),
backgroundColor = MaterialTheme.colorScheme.primaryContainer,
onClick = navigateThisWeekTask,
)
TaskInfoCard(
modifier = Modifier.weight(1f)
.graphicsLayer {
translationX = rightTranslate.value
},
title = stringResource(DesignSystemR.string.all),
backgroundColor = MaterialTheme.colorScheme.primaryContainer,
onClick = navigateAllTask,
)
}
if (incompleteTasks.isEmpty()) {
EmptyContent(title = stringResource(DesignSystemR.string.no_tasks))
} else {
Row(
modifier = Modifier.fillMaxWidth()
.padding(horizontal = 8.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
modifier = Modifier.padding(16.dp),
text = stringResource(DesignSystemR.string.today_tasks),
style = TodoTheme.typography.headlineMedium,
color = MaterialTheme.colorScheme.onSurface,
)
IconButton(onClick = { isShowSortTaskDialog = true }) {
Icon(
modifier = Modifier.size(18.dp),
imageVector = ImageVector.vectorResource(DesignSystemR.drawable.svg_sort),
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurface
)
}
}
val sortedTasks: List<Task> = remember(incompleteTasks, sortTask) {
incompleteTasks.sortedWith(
compareBy {
when (sortTask) {
SortTask.BY_CREATE_TIME_ASCENDING -> {
it.id
}
SortTask.BY_CREATE_TIME_DESCENDING -> {
-it.id
}
SortTask.BY_PRIORITY_ASCENDING -> {
it.priority
}
SortTask.BY_PRIORITY_DESCENDING -> {
-it.priority
}
SortTask.BY_TIME_ASCENDING -> {
it.time.toSecondOfDay()
}
SortTask.BY_TIME_DESCENDING -> {
-it.time.toSecondOfDay()
}
}
}
)
}
LazyColumn(
modifier = Modifier.fillMaxSize()
.padding(
start = 16.dp,
end = 16.dp,
bottom = 10.dp,
)
) {
itemsIndexed(
items = sortedTasks,
key = { _, task ->
task.id
}
) { _, task ->
Box(
modifier = Modifier.animateItem(tween(500))
) {
SwipeActionBox(
item = task,
onDeleteAction = {
onTaskDelete(it.id, it.uuid)
onShowMessageSnackBar("Task Deleted")
}
) {
TaskCard(
task = task,
category = categories.filter { it.id == task.categoryId }
.getOrNull(0),
isAvailableSwipe = true,
onTaskEdit = { taskId -> navigateEditTask(taskId) },
onTaskToggleCompletion = { taskId, isCompleted ->
onTaskToggleCompletion(taskId, isCompleted)
},
onTaskDelete = { taskId, uuid -> onTaskDelete(taskId, uuid) },
)
}
}
Spacer(modifier = Modifier.height(10.dp))
}
}
}
}
}
}
@Preview
@Composable
fun HomeScreenPreview() {
TodoTheme {
val completedTasks = persistentListOf(
Task(
id = 7418,
uuid = "cu",
title = "purus",
isCompleted = false,
isRemind = true,
time = LocalTime.now(),
date = LocalDate.now(),
memo = "memo",
priority = 1
)
)
HomeScreen(
completedTasks = completedTasks,
incompleteTasks = persistentListOf(),
categories = persistentListOf(),
sleepTime = LocalTime.now(),
sortTask = SortTask.BY_TIME_ASCENDING,
theme = Theme(ThemeType.SUN_RISE),
buildVersion = "1.0.0",
navigateCalendar = {},
navigateSetting = {},
navigateAddTask = {},
navigateCompletedTask = {},
navigateIncompleteTask = {},
navigateThisWeekTask = {},
navigateAllTask = {},
navigateEditTask = {},
onSortTaskChanged = {},
onTaskDelete = { _, _ -> },
onTaskToggleCompletion = { _, _ -> },
onShowMessageSnackBar = {},
)
}
} | 0 | Kotlin | 0 | 0 | 01364ab1ea7b3333c16500c26c1105fe134374dd | 18,242 | Todo | Apache License 2.0 |
BetterCommandBlock/src/main/kotlin/city/newnan/bettercommandblock/config/ConfigFile.kt | NewNanCity | 467,094,551 | false | null | package city.newnan.bettercommandblock.config
import com.fasterxml.jackson.annotation.JsonProperty
data class ConfigFile(
@JsonProperty("enable")
val enable: Boolean
) | 0 | Kotlin | 0 | 5 | 64a016d822c281ab74d060606f957f93947d958a | 177 | Plugins | MIT License |
app/src/main/java/br/com/sistemadereparo/listadetarefas/presenter/AdicionarTarefaPresenter.kt | JulianoRenis | 687,245,901 | false | {"Kotlin": 19881} | package br.com.sistemadereparo.listadetarefas.presenter
import android.content.Context
import android.os.Build
import android.os.Bundle
import br.com.sistemadereparo.listadetarefas.database.TarefaDAO
import br.com.sistemadereparo.listadetarefas.model.Tarefa
import br.com.sistemadereparo.listadetarefas.view.interfaces.IAdicionarTarefa
class AdicionarTarefaPresenter(
private val view : IAdicionarTarefa,
private val context: Context
) {
private var tarefa: Tarefa?= null
private var message=""
private var cliqueSalvar: Boolean = false
fun recebeBundle(bundle:Bundle) {
var tarefaMod: String?= ""
if(bundle != null){
if (bundle.getBoolean("clique")){
cliqueSalvar = bundle.getBoolean("clique")
}else{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
tarefa = bundle.getSerializable("tarefa",Tarefa::class.java)
//cliqueSalvar = bundle.getBoolean("clique")
}else{
tarefa = bundle.getSerializable("tarefa")as Tarefa
// cliqueSalvar = bundle.getBoolean("clique")
}
tarefaMod = tarefa?.descricao
view.pegarBundle(tarefaMod!!)
}
}
}
fun pegaDados(tarefa:String):String{
if(tarefa.isNotEmpty()){
if (tarefa != null){
if(cliqueSalvar==true) {
view.salvar(tarefa)
message= "Tarefa Salva"
}
else{
view.editar(tarefa)
message= "Tarefa Salva"
}
}else{
message = "Preencha uma Tarefa"
}
}else{
message = "Preencha uma Tarefa"
}
return message
}
fun salvar(descricao: String){
val tarefa = Tarefa(-1, descricao, "default")
val tarefaDAO = TarefaDAO(context)
if (tarefaDAO.salvar(tarefa)) {
message= "Salvo com sucesso!"
view.finishActivi()
}
}
fun editar(descricao:String):String{
var tarefa= tarefa
val tarefaAtualizar = Tarefa(tarefa!!.idTarefa,descricao,"default")
val tarefaDAO = TarefaDAO(context)
if (tarefaDAO.atualizar(tarefaAtualizar)){
message = "Tarefa atualizada com sucesso"
view.finishActivi()
}
return view.message(message).toString()
}
} | 0 | Kotlin | 0 | 0 | 099484538de9da5a7bb261f1f01cf591c2ec3b67 | 2,366 | ListaDeTarefas | MIT License |
src/main/java/com/arman/kotboy/core/cpu/InstrSet.kt | coenvk | 182,844,893 | false | {"Kotlin": 327296, "Batchfile": 143} | package com.arman.kotboy.core.cpu
object InstrSet {
private val instrs: Array<Instr> = setup()
private val externalInstrs: Array<Instr> = setupExternal()
private fun setupInstr(opCode: OpCode, command: ((Cpu, IntArray) -> Unit)): Instr {
return Instr(opCode) { cpu, args ->
command(cpu, args)
opCode.cycles
}
}
private fun setupJumpInstr(opCode: OpCode, command: ((Cpu, IntArray) -> Boolean)): Instr {
return Instr(opCode) { cpu, args ->
if (!command(cpu, args)) {
opCode.cyclesNotTaken
} else {
opCode.cycles
}
}
}
private fun setup(): Array<Instr> {
return Array(0x100) {
when (val opCode = OpCode[it]) {
// opcodes
OpCode.NOP_00 -> setupInstr(opCode) { cpu, args -> cpu.nop_00(*args) }
OpCode.LD_01 -> setupInstr(opCode) { cpu, args -> cpu.ld_01(*args) }
OpCode.LD_02 -> setupInstr(opCode) { cpu, args -> cpu.ld_02(*args) }
OpCode.INC_03 -> setupInstr(opCode) { cpu, args -> cpu.inc_03(*args) }
OpCode.INC_04 -> setupInstr(opCode) { cpu, args -> cpu.inc_04(*args) }
OpCode.DEC_05 -> setupInstr(opCode) { cpu, args -> cpu.dec_05(*args) }
OpCode.LD_06 -> setupInstr(opCode) { cpu, args -> cpu.ld_06(*args) }
OpCode.RLCA_07 -> setupInstr(opCode) { cpu, args -> cpu.rlca_07(*args) }
OpCode.LD_08 -> setupInstr(opCode) { cpu, args -> cpu.ld_08(*args) }
OpCode.ADD_09 -> setupInstr(opCode) { cpu, args -> cpu.add_09(*args) }
OpCode.LD_0A -> setupInstr(opCode) { cpu, args -> cpu.ld_0a(*args) }
OpCode.DEC_0B -> setupInstr(opCode) { cpu, args -> cpu.dec_0b(*args) }
OpCode.INC_0C -> setupInstr(opCode) { cpu, args -> cpu.inc_0c(*args) }
OpCode.DEC_0D -> setupInstr(opCode) { cpu, args -> cpu.dec_0d(*args) }
OpCode.LD_0E -> setupInstr(opCode) { cpu, args -> cpu.ld_0e(*args) }
OpCode.RRCA_0F -> setupInstr(opCode) { cpu, args -> cpu.rrca_0f(*args) }
OpCode.STOP_10 -> setupInstr(opCode) { cpu, args -> cpu.stop_10(*args) }
OpCode.LD_11 -> setupInstr(opCode) { cpu, args -> cpu.ld_11(*args) }
OpCode.LD_12 -> setupInstr(opCode) { cpu, args -> cpu.ld_12(*args) }
OpCode.INC_13 -> setupInstr(opCode) { cpu, args -> cpu.inc_13(*args) }
OpCode.INC_14 -> setupInstr(opCode) { cpu, args -> cpu.inc_14(*args) }
OpCode.DEC_15 -> setupInstr(opCode) { cpu, args -> cpu.dec_15(*args) }
OpCode.LD_16 -> setupInstr(opCode) { cpu, args -> cpu.ld_16(*args) }
OpCode.RLA_17 -> setupInstr(opCode) { cpu, args -> cpu.rla_17(*args) }
OpCode.JR_18 -> setupInstr(opCode) { cpu, args -> cpu.jr_18(*args) }
OpCode.ADD_19 -> setupInstr(opCode) { cpu, args -> cpu.add_19(*args) }
OpCode.LD_1A -> setupInstr(opCode) { cpu, args -> cpu.ld_1a(*args) }
OpCode.DEC_1B -> setupInstr(opCode) { cpu, args -> cpu.dec_1b(*args) }
OpCode.INC_1C -> setupInstr(opCode) { cpu, args -> cpu.inc_1c(*args) }
OpCode.DEC_1D -> setupInstr(opCode) { cpu, args -> cpu.dec_1d(*args) }
OpCode.LD_1E -> setupInstr(opCode) { cpu, args -> cpu.ld_1e(*args) }
OpCode.RRA_1F -> setupInstr(opCode) { cpu, args -> cpu.rra_1f(*args) }
OpCode.JR_20 -> setupJumpInstr(opCode) { cpu, args -> cpu.jr_20(*args) }
OpCode.LD_21 -> setupInstr(opCode) { cpu, args -> cpu.ld_21(*args) }
OpCode.LD_22 -> setupInstr(opCode) { cpu, args -> cpu.ld_22(*args) }
OpCode.INC_23 -> setupInstr(opCode) { cpu, args -> cpu.inc_23(*args) }
OpCode.INC_24 -> setupInstr(opCode) { cpu, args -> cpu.inc_24(*args) }
OpCode.DEC_25 -> setupInstr(opCode) { cpu, args -> cpu.dec_25(*args) }
OpCode.LD_26 -> setupInstr(opCode) { cpu, args -> cpu.ld_26(*args) }
OpCode.DAA_27 -> setupInstr(opCode) { cpu, args -> cpu.daa_27(*args) }
OpCode.JR_28 -> setupJumpInstr(opCode) { cpu, args -> cpu.jr_28(*args) }
OpCode.ADD_29 -> setupInstr(opCode) { cpu, args -> cpu.add_29(*args) }
OpCode.LD_2A -> setupInstr(opCode) { cpu, args -> cpu.ld_2a(*args) }
OpCode.DEC_2B -> setupInstr(opCode) { cpu, args -> cpu.dec_2b(*args) }
OpCode.INC_2C -> setupInstr(opCode) { cpu, args -> cpu.inc_2c(*args) }
OpCode.DEC_2D -> setupInstr(opCode) { cpu, args -> cpu.dec_2d(*args) }
OpCode.LD_2E -> setupInstr(opCode) { cpu, args -> cpu.ld_2e(*args) }
OpCode.CPL_2F -> setupInstr(opCode) { cpu, args -> cpu.cpl_2f(*args) }
OpCode.JR_30 -> setupJumpInstr(opCode) { cpu, args -> cpu.jr_30(*args) }
OpCode.LD_31 -> setupInstr(opCode) { cpu, args -> cpu.ld_31(*args) }
OpCode.LD_32 -> setupInstr(opCode) { cpu, args -> cpu.ld_32(*args) }
OpCode.INC_33 -> setupInstr(opCode) { cpu, args -> cpu.inc_33(*args) }
OpCode.INC_34 -> setupInstr(opCode) { cpu, args -> cpu.inc_34(*args) }
OpCode.DEC_35 -> setupInstr(opCode) { cpu, args -> cpu.dec_35(*args) }
OpCode.LD_36 -> setupInstr(opCode) { cpu, args -> cpu.ld_36(*args) }
OpCode.SCF_37 -> setupInstr(opCode) { cpu, args -> cpu.scf_37(*args) }
OpCode.JR_38 -> setupJumpInstr(opCode) { cpu, args -> cpu.jr_38(*args) }
OpCode.ADD_39 -> setupInstr(opCode) { cpu, args -> cpu.add_39(*args) }
OpCode.LD_3A -> setupInstr(opCode) { cpu, args -> cpu.ld_3a(*args) }
OpCode.DEC_3B -> setupInstr(opCode) { cpu, args -> cpu.dec_3b(*args) }
OpCode.INC_3C -> setupInstr(opCode) { cpu, args -> cpu.inc_3c(*args) }
OpCode.DEC_3D -> setupInstr(opCode) { cpu, args -> cpu.dec_3d(*args) }
OpCode.LD_3E -> setupInstr(opCode) { cpu, args -> cpu.ld_3e(*args) }
OpCode.CCF_3F -> setupInstr(opCode) { cpu, args -> cpu.ccf_3f(*args) }
OpCode.LD_40 -> setupInstr(opCode) { cpu, args -> cpu.ld_40(*args) }
OpCode.LD_41 -> setupInstr(opCode) { cpu, args -> cpu.ld_41(*args) }
OpCode.LD_42 -> setupInstr(opCode) { cpu, args -> cpu.ld_42(*args) }
OpCode.LD_43 -> setupInstr(opCode) { cpu, args -> cpu.ld_43(*args) }
OpCode.LD_44 -> setupInstr(opCode) { cpu, args -> cpu.ld_44(*args) }
OpCode.LD_45 -> setupInstr(opCode) { cpu, args -> cpu.ld_45(*args) }
OpCode.LD_46 -> setupInstr(opCode) { cpu, args -> cpu.ld_46(*args) }
OpCode.LD_47 -> setupInstr(opCode) { cpu, args -> cpu.ld_47(*args) }
OpCode.LD_48 -> setupInstr(opCode) { cpu, args -> cpu.ld_48(*args) }
OpCode.LD_49 -> setupInstr(opCode) { cpu, args -> cpu.ld_49(*args) }
OpCode.LD_4A -> setupInstr(opCode) { cpu, args -> cpu.ld_4a(*args) }
OpCode.LD_4B -> setupInstr(opCode) { cpu, args -> cpu.ld_4b(*args) }
OpCode.LD_4C -> setupInstr(opCode) { cpu, args -> cpu.ld_4c(*args) }
OpCode.LD_4D -> setupInstr(opCode) { cpu, args -> cpu.ld_4d(*args) }
OpCode.LD_4E -> setupInstr(opCode) { cpu, args -> cpu.ld_4e(*args) }
OpCode.LD_4F -> setupInstr(opCode) { cpu, args -> cpu.ld_4f(*args) }
OpCode.LD_50 -> setupInstr(opCode) { cpu, args -> cpu.ld_50(*args) }
OpCode.LD_51 -> setupInstr(opCode) { cpu, args -> cpu.ld_51(*args) }
OpCode.LD_52 -> setupInstr(opCode) { cpu, args -> cpu.ld_52(*args) }
OpCode.LD_53 -> setupInstr(opCode) { cpu, args -> cpu.ld_53(*args) }
OpCode.LD_54 -> setupInstr(opCode) { cpu, args -> cpu.ld_54(*args) }
OpCode.LD_55 -> setupInstr(opCode) { cpu, args -> cpu.ld_55(*args) }
OpCode.LD_56 -> setupInstr(opCode) { cpu, args -> cpu.ld_56(*args) }
OpCode.LD_57 -> setupInstr(opCode) { cpu, args -> cpu.ld_57(*args) }
OpCode.LD_58 -> setupInstr(opCode) { cpu, args -> cpu.ld_58(*args) }
OpCode.LD_59 -> setupInstr(opCode) { cpu, args -> cpu.ld_59(*args) }
OpCode.LD_5A -> setupInstr(opCode) { cpu, args -> cpu.ld_5a(*args) }
OpCode.LD_5B -> setupInstr(opCode) { cpu, args -> cpu.ld_5b(*args) }
OpCode.LD_5C -> setupInstr(opCode) { cpu, args -> cpu.ld_5c(*args) }
OpCode.LD_5D -> setupInstr(opCode) { cpu, args -> cpu.ld_5d(*args) }
OpCode.LD_5E -> setupInstr(opCode) { cpu, args -> cpu.ld_5e(*args) }
OpCode.LD_5F -> setupInstr(opCode) { cpu, args -> cpu.ld_5f(*args) }
OpCode.LD_60 -> setupInstr(opCode) { cpu, args -> cpu.ld_60(*args) }
OpCode.LD_61 -> setupInstr(opCode) { cpu, args -> cpu.ld_61(*args) }
OpCode.LD_62 -> setupInstr(opCode) { cpu, args -> cpu.ld_62(*args) }
OpCode.LD_63 -> setupInstr(opCode) { cpu, args -> cpu.ld_63(*args) }
OpCode.LD_64 -> setupInstr(opCode) { cpu, args -> cpu.ld_64(*args) }
OpCode.LD_65 -> setupInstr(opCode) { cpu, args -> cpu.ld_65(*args) }
OpCode.LD_66 -> setupInstr(opCode) { cpu, args -> cpu.ld_66(*args) }
OpCode.LD_67 -> setupInstr(opCode) { cpu, args -> cpu.ld_67(*args) }
OpCode.LD_68 -> setupInstr(opCode) { cpu, args -> cpu.ld_68(*args) }
OpCode.LD_69 -> setupInstr(opCode) { cpu, args -> cpu.ld_69(*args) }
OpCode.LD_6A -> setupInstr(opCode) { cpu, args -> cpu.ld_6a(*args) }
OpCode.LD_6B -> setupInstr(opCode) { cpu, args -> cpu.ld_6b(*args) }
OpCode.LD_6C -> setupInstr(opCode) { cpu, args -> cpu.ld_6c(*args) }
OpCode.LD_6D -> setupInstr(opCode) { cpu, args -> cpu.ld_6d(*args) }
OpCode.LD_6E -> setupInstr(opCode) { cpu, args -> cpu.ld_6e(*args) }
OpCode.LD_6F -> setupInstr(opCode) { cpu, args -> cpu.ld_6f(*args) }
OpCode.LD_70 -> setupInstr(opCode) { cpu, args -> cpu.ld_70(*args) }
OpCode.LD_71 -> setupInstr(opCode) { cpu, args -> cpu.ld_71(*args) }
OpCode.LD_72 -> setupInstr(opCode) { cpu, args -> cpu.ld_72(*args) }
OpCode.LD_73 -> setupInstr(opCode) { cpu, args -> cpu.ld_73(*args) }
OpCode.LD_74 -> setupInstr(opCode) { cpu, args -> cpu.ld_74(*args) }
OpCode.LD_75 -> setupInstr(opCode) { cpu, args -> cpu.ld_75(*args) }
OpCode.HALT_76 -> setupInstr(opCode) { cpu, args -> cpu.halt_76(*args) }
OpCode.LD_77 -> setupInstr(opCode) { cpu, args -> cpu.ld_77(*args) }
OpCode.LD_78 -> setupInstr(opCode) { cpu, args -> cpu.ld_78(*args) }
OpCode.LD_79 -> setupInstr(opCode) { cpu, args -> cpu.ld_79(*args) }
OpCode.LD_7A -> setupInstr(opCode) { cpu, args -> cpu.ld_7a(*args) }
OpCode.LD_7B -> setupInstr(opCode) { cpu, args -> cpu.ld_7b(*args) }
OpCode.LD_7C -> setupInstr(opCode) { cpu, args -> cpu.ld_7c(*args) }
OpCode.LD_7D -> setupInstr(opCode) { cpu, args -> cpu.ld_7d(*args) }
OpCode.LD_7E -> setupInstr(opCode) { cpu, args -> cpu.ld_7e(*args) }
OpCode.LD_7F -> setupInstr(opCode) { cpu, args -> cpu.ld_7f(*args) }
OpCode.ADD_80 -> setupInstr(opCode) { cpu, args -> cpu.add_80(*args) }
OpCode.ADD_81 -> setupInstr(opCode) { cpu, args -> cpu.add_81(*args) }
OpCode.ADD_82 -> setupInstr(opCode) { cpu, args -> cpu.add_82(*args) }
OpCode.ADD_83 -> setupInstr(opCode) { cpu, args -> cpu.add_83(*args) }
OpCode.ADD_84 -> setupInstr(opCode) { cpu, args -> cpu.add_84(*args) }
OpCode.ADD_85 -> setupInstr(opCode) { cpu, args -> cpu.add_85(*args) }
OpCode.ADD_86 -> setupInstr(opCode) { cpu, args -> cpu.add_86(*args) }
OpCode.ADD_87 -> setupInstr(opCode) { cpu, args -> cpu.add_87(*args) }
OpCode.ADC_88 -> setupInstr(opCode) { cpu, args -> cpu.adc_88(*args) }
OpCode.ADC_89 -> setupInstr(opCode) { cpu, args -> cpu.adc_89(*args) }
OpCode.ADC_8A -> setupInstr(opCode) { cpu, args -> cpu.adc_8a(*args) }
OpCode.ADC_8B -> setupInstr(opCode) { cpu, args -> cpu.adc_8b(*args) }
OpCode.ADC_8C -> setupInstr(opCode) { cpu, args -> cpu.adc_8c(*args) }
OpCode.ADC_8D -> setupInstr(opCode) { cpu, args -> cpu.adc_8d(*args) }
OpCode.ADC_8E -> setupInstr(opCode) { cpu, args -> cpu.adc_8e(*args) }
OpCode.ADC_8F -> setupInstr(opCode) { cpu, args -> cpu.adc_8f(*args) }
OpCode.SUB_90 -> setupInstr(opCode) { cpu, args -> cpu.sub_90(*args) }
OpCode.SUB_91 -> setupInstr(opCode) { cpu, args -> cpu.sub_91(*args) }
OpCode.SUB_92 -> setupInstr(opCode) { cpu, args -> cpu.sub_92(*args) }
OpCode.SUB_93 -> setupInstr(opCode) { cpu, args -> cpu.sub_93(*args) }
OpCode.SUB_94 -> setupInstr(opCode) { cpu, args -> cpu.sub_94(*args) }
OpCode.SUB_95 -> setupInstr(opCode) { cpu, args -> cpu.sub_95(*args) }
OpCode.SUB_96 -> setupInstr(opCode) { cpu, args -> cpu.sub_96(*args) }
OpCode.SUB_97 -> setupInstr(opCode) { cpu, args -> cpu.sub_97(*args) }
OpCode.SBC_98 -> setupInstr(opCode) { cpu, args -> cpu.sbc_98(*args) }
OpCode.SBC_99 -> setupInstr(opCode) { cpu, args -> cpu.sbc_99(*args) }
OpCode.SBC_9A -> setupInstr(opCode) { cpu, args -> cpu.sbc_9a(*args) }
OpCode.SBC_9B -> setupInstr(opCode) { cpu, args -> cpu.sbc_9b(*args) }
OpCode.SBC_9C -> setupInstr(opCode) { cpu, args -> cpu.sbc_9c(*args) }
OpCode.SBC_9D -> setupInstr(opCode) { cpu, args -> cpu.sbc_9d(*args) }
OpCode.SBC_9E -> setupInstr(opCode) { cpu, args -> cpu.sbc_9e(*args) }
OpCode.SBC_9F -> setupInstr(opCode) { cpu, args -> cpu.sbc_9f(*args) }
OpCode.AND_A0 -> setupInstr(opCode) { cpu, args -> cpu.and_a0(*args) }
OpCode.AND_A1 -> setupInstr(opCode) { cpu, args -> cpu.and_a1(*args) }
OpCode.AND_A2 -> setupInstr(opCode) { cpu, args -> cpu.and_a2(*args) }
OpCode.AND_A3 -> setupInstr(opCode) { cpu, args -> cpu.and_a3(*args) }
OpCode.AND_A4 -> setupInstr(opCode) { cpu, args -> cpu.and_a4(*args) }
OpCode.AND_A5 -> setupInstr(opCode) { cpu, args -> cpu.and_a5(*args) }
OpCode.AND_A6 -> setupInstr(opCode) { cpu, args -> cpu.and_a6(*args) }
OpCode.AND_A7 -> setupInstr(opCode) { cpu, args -> cpu.and_a7(*args) }
OpCode.XOR_A8 -> setupInstr(opCode) { cpu, args -> cpu.xor_a8(*args) }
OpCode.XOR_A9 -> setupInstr(opCode) { cpu, args -> cpu.xor_a9(*args) }
OpCode.XOR_AA -> setupInstr(opCode) { cpu, args -> cpu.xor_aa(*args) }
OpCode.XOR_AB -> setupInstr(opCode) { cpu, args -> cpu.xor_ab(*args) }
OpCode.XOR_AC -> setupInstr(opCode) { cpu, args -> cpu.xor_ac(*args) }
OpCode.XOR_AD -> setupInstr(opCode) { cpu, args -> cpu.xor_ad(*args) }
OpCode.XOR_AE -> setupInstr(opCode) { cpu, args -> cpu.xor_ae(*args) }
OpCode.XOR_AF -> setupInstr(opCode) { cpu, args -> cpu.xor_af(*args) }
OpCode.OR_B0 -> setupInstr(opCode) { cpu, args -> cpu.or_b0(*args) }
OpCode.OR_B1 -> setupInstr(opCode) { cpu, args -> cpu.or_b1(*args) }
OpCode.OR_B2 -> setupInstr(opCode) { cpu, args -> cpu.or_b2(*args) }
OpCode.OR_B3 -> setupInstr(opCode) { cpu, args -> cpu.or_b3(*args) }
OpCode.OR_B4 -> setupInstr(opCode) { cpu, args -> cpu.or_b4(*args) }
OpCode.OR_B5 -> setupInstr(opCode) { cpu, args -> cpu.or_b5(*args) }
OpCode.OR_B6 -> setupInstr(opCode) { cpu, args -> cpu.or_b6(*args) }
OpCode.OR_B7 -> setupInstr(opCode) { cpu, args -> cpu.or_b7(*args) }
OpCode.CP_B8 -> setupInstr(opCode) { cpu, args -> cpu.cp_b8(*args) }
OpCode.CP_B9 -> setupInstr(opCode) { cpu, args -> cpu.cp_b9(*args) }
OpCode.CP_BA -> setupInstr(opCode) { cpu, args -> cpu.cp_ba(*args) }
OpCode.CP_BB -> setupInstr(opCode) { cpu, args -> cpu.cp_bb(*args) }
OpCode.CP_BC -> setupInstr(opCode) { cpu, args -> cpu.cp_bc(*args) }
OpCode.CP_BD -> setupInstr(opCode) { cpu, args -> cpu.cp_bd(*args) }
OpCode.CP_BE -> setupInstr(opCode) { cpu, args -> cpu.cp_be(*args) }
OpCode.CP_BF -> setupInstr(opCode) { cpu, args -> cpu.cp_bf(*args) }
OpCode.RET_C0 -> setupJumpInstr(opCode) { cpu, args -> cpu.ret_c0(*args) }
OpCode.POP_C1 -> setupInstr(opCode) { cpu, args -> cpu.pop_c1(*args) }
OpCode.JP_C2 -> setupJumpInstr(opCode) { cpu, args -> cpu.jp_c2(*args) }
OpCode.JP_C3 -> setupInstr(opCode) { cpu, args -> cpu.jp_c3(*args) } // TODO: setupJumpInstr?
OpCode.CALL_C4 -> setupJumpInstr(opCode) { cpu, args -> cpu.call_c4(*args) }
OpCode.PUSH_C5 -> setupInstr(opCode) { cpu, args -> cpu.push_c5(*args) }
OpCode.ADD_C6 -> setupInstr(opCode) { cpu, args -> cpu.add_c6(*args) }
OpCode.RST_C7 -> setupInstr(opCode) { cpu, args -> cpu.rst_c7(*args) }
OpCode.RET_C8 -> setupJumpInstr(opCode) { cpu, args -> cpu.ret_c8(*args) }
OpCode.RET_C9 -> setupInstr(opCode) { cpu, args -> cpu.ret_c9(*args) } // TODO: setupJumpInstr?
OpCode.JP_CA -> setupJumpInstr(opCode) { cpu, args -> cpu.jp_ca(*args) }
OpCode.PREFIX_CB -> setupInstr(opCode) { cpu, args -> cpu.prefix_cb(*args) }
OpCode.CALL_CC -> setupJumpInstr(opCode) { cpu, args -> cpu.call_cc(*args) }
OpCode.CALL_CD -> setupInstr(opCode) { cpu, args -> cpu.call_cd(*args) } // TODO: setupJumpInstr?
OpCode.ADC_CE -> setupInstr(opCode) { cpu, args -> cpu.adc_ce(*args) }
OpCode.RST_CF -> setupInstr(opCode) { cpu, args -> cpu.rst_cf(*args) }
OpCode.RET_D0 -> setupJumpInstr(opCode) { cpu, args -> cpu.ret_d0(*args) }
OpCode.POP_D1 -> setupInstr(opCode) { cpu, args -> cpu.pop_d1(*args) }
OpCode.JP_D2 -> setupJumpInstr(opCode) { cpu, args -> cpu.jp_d2(*args) }
OpCode.CALL_D4 -> setupJumpInstr(opCode) { cpu, args -> cpu.call_d4(*args) }
OpCode.PUSH_D5 -> setupInstr(opCode) { cpu, args -> cpu.push_d5(*args) }
OpCode.SUB_D6 -> setupInstr(opCode) { cpu, args -> cpu.sub_d6(*args) }
OpCode.RST_D7 -> setupInstr(opCode) { cpu, args -> cpu.rst_d7(*args) }
OpCode.RET_D8 -> setupJumpInstr(opCode) { cpu, args -> cpu.ret_d8(*args) }
OpCode.RETI_D9 -> setupInstr(opCode) { cpu, args -> cpu.reti_d9(*args) }
OpCode.JP_DA -> setupJumpInstr(opCode) { cpu, args -> cpu.jp_da(*args) }
OpCode.CALL_DC -> setupJumpInstr(opCode) { cpu, args -> cpu.call_dc(*args) }
OpCode.SBC_DE -> setupInstr(opCode) { cpu, args -> cpu.sbc_de(*args) }
OpCode.RST_DF -> setupInstr(opCode) { cpu, args -> cpu.rst_df(*args) }
OpCode.LDH_E0 -> setupInstr(opCode) { cpu, args -> cpu.ldh_e0(*args) }
OpCode.POP_E1 -> setupInstr(opCode) { cpu, args -> cpu.pop_e1(*args) }
OpCode.LD_E2 -> setupInstr(opCode) { cpu, args -> cpu.ld_e2(*args) }
OpCode.PUSH_E5 -> setupInstr(opCode) { cpu, args -> cpu.push_e5(*args) }
OpCode.AND_E6 -> setupInstr(opCode) { cpu, args -> cpu.and_e6(*args) }
OpCode.RST_E7 -> setupInstr(opCode) { cpu, args -> cpu.rst_e7(*args) }
OpCode.ADD_E8 -> setupInstr(opCode) { cpu, args -> cpu.add_e8(*args) }
OpCode.JP_E9 -> setupInstr(opCode) { cpu, args -> cpu.jp_e9(*args) }
OpCode.LD_EA -> setupInstr(opCode) { cpu, args -> cpu.ld_ea(*args) }
OpCode.XOR_EE -> setupInstr(opCode) { cpu, args -> cpu.xor_ee(*args) }
OpCode.RST_EF -> setupInstr(opCode) { cpu, args -> cpu.rst_ef(*args) }
OpCode.LDH_F0 -> setupInstr(opCode) { cpu, args -> cpu.ldh_f0(*args) }
OpCode.POP_F1 -> setupInstr(opCode) { cpu, args -> cpu.pop_f1(*args) }
OpCode.LD_F2 -> setupInstr(opCode) { cpu, args -> cpu.ld_f2(*args) }
OpCode.DI_F3 -> setupInstr(opCode) { cpu, args -> cpu.di_f3(*args) }
OpCode.PUSH_F5 -> setupInstr(opCode) { cpu, args -> cpu.push_f5(*args) }
OpCode.OR_F6 -> setupInstr(opCode) { cpu, args -> cpu.or_f6(*args) }
OpCode.RST_F7 -> setupInstr(opCode) { cpu, args -> cpu.rst_f7(*args) }
OpCode.LD_F8 -> setupInstr(opCode) { cpu, args -> cpu.ld_f8(*args) }
OpCode.LD_F9 -> setupInstr(opCode) { cpu, args -> cpu.ld_f9(*args) }
OpCode.LD_FA -> setupInstr(opCode) { cpu, args -> cpu.ld_fa(*args) }
OpCode.EI_FB -> setupInstr(opCode) { cpu, args -> cpu.ei_fb(*args) }
OpCode.CP_FE -> setupInstr(opCode) { cpu, args -> cpu.cp_fe(*args) }
OpCode.RST_FF -> setupInstr(opCode) { cpu, args -> cpu.rst_ff(*args) }
else -> setupInstr(opCode) { cpu, args -> cpu.nop_00(*args) }
}
}
}
private fun setupExternal(): Array<Instr> {
return Array(0x100) {
when (val opCode = OpCode[it + 0x100]) {
// external opcodes
OpCode.RLC_00 -> setupInstr(opCode) { cpu, args -> cpu.rlc_00(*args) }
OpCode.RLC_01 -> setupInstr(opCode) { cpu, args -> cpu.rlc_01(*args) }
OpCode.RLC_02 -> setupInstr(opCode) { cpu, args -> cpu.rlc_02(*args) }
OpCode.RLC_03 -> setupInstr(opCode) { cpu, args -> cpu.rlc_03(*args) }
OpCode.RLC_04 -> setupInstr(opCode) { cpu, args -> cpu.rlc_04(*args) }
OpCode.RLC_05 -> setupInstr(opCode) { cpu, args -> cpu.rlc_05(*args) }
OpCode.RLC_06 -> setupInstr(opCode) { cpu, args -> cpu.rlc_06(*args) }
OpCode.RLC_07 -> setupInstr(opCode) { cpu, args -> cpu.rlc_07(*args) }
OpCode.RRC_08 -> setupInstr(opCode) { cpu, args -> cpu.rrc_08(*args) }
OpCode.RRC_09 -> setupInstr(opCode) { cpu, args -> cpu.rrc_09(*args) }
OpCode.RRC_0A -> setupInstr(opCode) { cpu, args -> cpu.rrc_0a(*args) }
OpCode.RRC_0B -> setupInstr(opCode) { cpu, args -> cpu.rrc_0b(*args) }
OpCode.RRC_0C -> setupInstr(opCode) { cpu, args -> cpu.rrc_0c(*args) }
OpCode.RRC_0D -> setupInstr(opCode) { cpu, args -> cpu.rrc_0d(*args) }
OpCode.RRC_0E -> setupInstr(opCode) { cpu, args -> cpu.rrc_0e(*args) }
OpCode.RRC_0F -> setupInstr(opCode) { cpu, args -> cpu.rrc_0f(*args) }
OpCode.RL_10 -> setupInstr(opCode) { cpu, args -> cpu.rl_10(*args) }
OpCode.RL_11 -> setupInstr(opCode) { cpu, args -> cpu.rl_11(*args) }
OpCode.RL_12 -> setupInstr(opCode) { cpu, args -> cpu.rl_12(*args) }
OpCode.RL_13 -> setupInstr(opCode) { cpu, args -> cpu.rl_13(*args) }
OpCode.RL_14 -> setupInstr(opCode) { cpu, args -> cpu.rl_14(*args) }
OpCode.RL_15 -> setupInstr(opCode) { cpu, args -> cpu.rl_15(*args) }
OpCode.RL_16 -> setupInstr(opCode) { cpu, args -> cpu.rl_16(*args) }
OpCode.RL_17 -> setupInstr(opCode) { cpu, args -> cpu.rl_17(*args) }
OpCode.RR_18 -> setupInstr(opCode) { cpu, args -> cpu.rr_18(*args) }
OpCode.RR_19 -> setupInstr(opCode) { cpu, args -> cpu.rr_19(*args) }
OpCode.RR_1A -> setupInstr(opCode) { cpu, args -> cpu.rr_1a(*args) }
OpCode.RR_1B -> setupInstr(opCode) { cpu, args -> cpu.rr_1b(*args) }
OpCode.RR_1C -> setupInstr(opCode) { cpu, args -> cpu.rr_1c(*args) }
OpCode.RR_1D -> setupInstr(opCode) { cpu, args -> cpu.rr_1d(*args) }
OpCode.RR_1E -> setupInstr(opCode) { cpu, args -> cpu.rr_1e(*args) }
OpCode.RR_1F -> setupInstr(opCode) { cpu, args -> cpu.rr_1f(*args) }
OpCode.SLA_20 -> setupInstr(opCode) { cpu, args -> cpu.sla_20(*args) }
OpCode.SLA_21 -> setupInstr(opCode) { cpu, args -> cpu.sla_21(*args) }
OpCode.SLA_22 -> setupInstr(opCode) { cpu, args -> cpu.sla_22(*args) }
OpCode.SLA_23 -> setupInstr(opCode) { cpu, args -> cpu.sla_23(*args) }
OpCode.SLA_24 -> setupInstr(opCode) { cpu, args -> cpu.sla_24(*args) }
OpCode.SLA_25 -> setupInstr(opCode) { cpu, args -> cpu.sla_25(*args) }
OpCode.SLA_26 -> setupInstr(opCode) { cpu, args -> cpu.sla_26(*args) }
OpCode.SLA_27 -> setupInstr(opCode) { cpu, args -> cpu.sla_27(*args) }
OpCode.SRA_28 -> setupInstr(opCode) { cpu, args -> cpu.sra_28(*args) }
OpCode.SRA_29 -> setupInstr(opCode) { cpu, args -> cpu.sra_29(*args) }
OpCode.SRA_2A -> setupInstr(opCode) { cpu, args -> cpu.sra_2a(*args) }
OpCode.SRA_2B -> setupInstr(opCode) { cpu, args -> cpu.sra_2b(*args) }
OpCode.SRA_2C -> setupInstr(opCode) { cpu, args -> cpu.sra_2c(*args) }
OpCode.SRA_2D -> setupInstr(opCode) { cpu, args -> cpu.sra_2d(*args) }
OpCode.SRA_2E -> setupInstr(opCode) { cpu, args -> cpu.sra_2e(*args) }
OpCode.SRA_2F -> setupInstr(opCode) { cpu, args -> cpu.sra_2f(*args) }
OpCode.SWAP_30 -> setupInstr(opCode) { cpu, args -> cpu.swap_30(*args) }
OpCode.SWAP_31 -> setupInstr(opCode) { cpu, args -> cpu.swap_31(*args) }
OpCode.SWAP_32 -> setupInstr(opCode) { cpu, args -> cpu.swap_32(*args) }
OpCode.SWAP_33 -> setupInstr(opCode) { cpu, args -> cpu.swap_33(*args) }
OpCode.SWAP_34 -> setupInstr(opCode) { cpu, args -> cpu.swap_34(*args) }
OpCode.SWAP_35 -> setupInstr(opCode) { cpu, args -> cpu.swap_35(*args) }
OpCode.SWAP_36 -> setupInstr(opCode) { cpu, args -> cpu.swap_36(*args) }
OpCode.SWAP_37 -> setupInstr(opCode) { cpu, args -> cpu.swap_37(*args) }
OpCode.SRL_38 -> setupInstr(opCode) { cpu, args -> cpu.srl_38(*args) }
OpCode.SRL_39 -> setupInstr(opCode) { cpu, args -> cpu.srl_39(*args) }
OpCode.SRL_3A -> setupInstr(opCode) { cpu, args -> cpu.srl_3a(*args) }
OpCode.SRL_3B -> setupInstr(opCode) { cpu, args -> cpu.srl_3b(*args) }
OpCode.SRL_3C -> setupInstr(opCode) { cpu, args -> cpu.srl_3c(*args) }
OpCode.SRL_3D -> setupInstr(opCode) { cpu, args -> cpu.srl_3d(*args) }
OpCode.SRL_3E -> setupInstr(opCode) { cpu, args -> cpu.srl_3e(*args) }
OpCode.SRL_3F -> setupInstr(opCode) { cpu, args -> cpu.srl_3f(*args) }
OpCode.BIT_40 -> setupInstr(opCode) { cpu, args -> cpu.bit_40(*args) }
OpCode.BIT_41 -> setupInstr(opCode) { cpu, args -> cpu.bit_41(*args) }
OpCode.BIT_42 -> setupInstr(opCode) { cpu, args -> cpu.bit_42(*args) }
OpCode.BIT_43 -> setupInstr(opCode) { cpu, args -> cpu.bit_43(*args) }
OpCode.BIT_44 -> setupInstr(opCode) { cpu, args -> cpu.bit_44(*args) }
OpCode.BIT_45 -> setupInstr(opCode) { cpu, args -> cpu.bit_45(*args) }
OpCode.BIT_46 -> setupInstr(opCode) { cpu, args -> cpu.bit_46(*args) }
OpCode.BIT_47 -> setupInstr(opCode) { cpu, args -> cpu.bit_47(*args) }
OpCode.BIT_48 -> setupInstr(opCode) { cpu, args -> cpu.bit_48(*args) }
OpCode.BIT_49 -> setupInstr(opCode) { cpu, args -> cpu.bit_49(*args) }
OpCode.BIT_4A -> setupInstr(opCode) { cpu, args -> cpu.bit_4a(*args) }
OpCode.BIT_4B -> setupInstr(opCode) { cpu, args -> cpu.bit_4b(*args) }
OpCode.BIT_4C -> setupInstr(opCode) { cpu, args -> cpu.bit_4c(*args) }
OpCode.BIT_4D -> setupInstr(opCode) { cpu, args -> cpu.bit_4d(*args) }
OpCode.BIT_4E -> setupInstr(opCode) { cpu, args -> cpu.bit_4e(*args) }
OpCode.BIT_4F -> setupInstr(opCode) { cpu, args -> cpu.bit_4f(*args) }
OpCode.BIT_50 -> setupInstr(opCode) { cpu, args -> cpu.bit_50(*args) }
OpCode.BIT_51 -> setupInstr(opCode) { cpu, args -> cpu.bit_51(*args) }
OpCode.BIT_52 -> setupInstr(opCode) { cpu, args -> cpu.bit_52(*args) }
OpCode.BIT_53 -> setupInstr(opCode) { cpu, args -> cpu.bit_53(*args) }
OpCode.BIT_54 -> setupInstr(opCode) { cpu, args -> cpu.bit_54(*args) }
OpCode.BIT_55 -> setupInstr(opCode) { cpu, args -> cpu.bit_55(*args) }
OpCode.BIT_56 -> setupInstr(opCode) { cpu, args -> cpu.bit_56(*args) }
OpCode.BIT_57 -> setupInstr(opCode) { cpu, args -> cpu.bit_57(*args) }
OpCode.BIT_58 -> setupInstr(opCode) { cpu, args -> cpu.bit_58(*args) }
OpCode.BIT_59 -> setupInstr(opCode) { cpu, args -> cpu.bit_59(*args) }
OpCode.BIT_5A -> setupInstr(opCode) { cpu, args -> cpu.bit_5a(*args) }
OpCode.BIT_5B -> setupInstr(opCode) { cpu, args -> cpu.bit_5b(*args) }
OpCode.BIT_5C -> setupInstr(opCode) { cpu, args -> cpu.bit_5c(*args) }
OpCode.BIT_5D -> setupInstr(opCode) { cpu, args -> cpu.bit_5d(*args) }
OpCode.BIT_5E -> setupInstr(opCode) { cpu, args -> cpu.bit_5e(*args) }
OpCode.BIT_5F -> setupInstr(opCode) { cpu, args -> cpu.bit_5f(*args) }
OpCode.BIT_60 -> setupInstr(opCode) { cpu, args -> cpu.bit_60(*args) }
OpCode.BIT_61 -> setupInstr(opCode) { cpu, args -> cpu.bit_61(*args) }
OpCode.BIT_62 -> setupInstr(opCode) { cpu, args -> cpu.bit_62(*args) }
OpCode.BIT_63 -> setupInstr(opCode) { cpu, args -> cpu.bit_63(*args) }
OpCode.BIT_64 -> setupInstr(opCode) { cpu, args -> cpu.bit_64(*args) }
OpCode.BIT_65 -> setupInstr(opCode) { cpu, args -> cpu.bit_65(*args) }
OpCode.BIT_66 -> setupInstr(opCode) { cpu, args -> cpu.bit_66(*args) }
OpCode.BIT_67 -> setupInstr(opCode) { cpu, args -> cpu.bit_67(*args) }
OpCode.BIT_68 -> setupInstr(opCode) { cpu, args -> cpu.bit_68(*args) }
OpCode.BIT_69 -> setupInstr(opCode) { cpu, args -> cpu.bit_69(*args) }
OpCode.BIT_6A -> setupInstr(opCode) { cpu, args -> cpu.bit_6a(*args) }
OpCode.BIT_6B -> setupInstr(opCode) { cpu, args -> cpu.bit_6b(*args) }
OpCode.BIT_6C -> setupInstr(opCode) { cpu, args -> cpu.bit_6c(*args) }
OpCode.BIT_6D -> setupInstr(opCode) { cpu, args -> cpu.bit_6d(*args) }
OpCode.BIT_6E -> setupInstr(opCode) { cpu, args -> cpu.bit_6e(*args) }
OpCode.BIT_6F -> setupInstr(opCode) { cpu, args -> cpu.bit_6f(*args) }
OpCode.BIT_70 -> setupInstr(opCode) { cpu, args -> cpu.bit_70(*args) }
OpCode.BIT_71 -> setupInstr(opCode) { cpu, args -> cpu.bit_71(*args) }
OpCode.BIT_72 -> setupInstr(opCode) { cpu, args -> cpu.bit_72(*args) }
OpCode.BIT_73 -> setupInstr(opCode) { cpu, args -> cpu.bit_73(*args) }
OpCode.BIT_74 -> setupInstr(opCode) { cpu, args -> cpu.bit_74(*args) }
OpCode.BIT_75 -> setupInstr(opCode) { cpu, args -> cpu.bit_75(*args) }
OpCode.BIT_76 -> setupInstr(opCode) { cpu, args -> cpu.bit_76(*args) }
OpCode.BIT_77 -> setupInstr(opCode) { cpu, args -> cpu.bit_77(*args) }
OpCode.BIT_78 -> setupInstr(opCode) { cpu, args -> cpu.bit_78(*args) }
OpCode.BIT_79 -> setupInstr(opCode) { cpu, args -> cpu.bit_79(*args) }
OpCode.BIT_7A -> setupInstr(opCode) { cpu, args -> cpu.bit_7a(*args) }
OpCode.BIT_7B -> setupInstr(opCode) { cpu, args -> cpu.bit_7b(*args) }
OpCode.BIT_7C -> setupInstr(opCode) { cpu, args -> cpu.bit_7c(*args) }
OpCode.BIT_7D -> setupInstr(opCode) { cpu, args -> cpu.bit_7d(*args) }
OpCode.BIT_7E -> setupInstr(opCode) { cpu, args -> cpu.bit_7e(*args) }
OpCode.BIT_7F -> setupInstr(opCode) { cpu, args -> cpu.bit_7f(*args) }
OpCode.RES_80 -> setupInstr(opCode) { cpu, args -> cpu.res_80(*args) }
OpCode.RES_81 -> setupInstr(opCode) { cpu, args -> cpu.res_81(*args) }
OpCode.RES_82 -> setupInstr(opCode) { cpu, args -> cpu.res_82(*args) }
OpCode.RES_83 -> setupInstr(opCode) { cpu, args -> cpu.res_83(*args) }
OpCode.RES_84 -> setupInstr(opCode) { cpu, args -> cpu.res_84(*args) }
OpCode.RES_85 -> setupInstr(opCode) { cpu, args -> cpu.res_85(*args) }
OpCode.RES_86 -> setupInstr(opCode) { cpu, args -> cpu.res_86(*args) }
OpCode.RES_87 -> setupInstr(opCode) { cpu, args -> cpu.res_87(*args) }
OpCode.RES_88 -> setupInstr(opCode) { cpu, args -> cpu.res_88(*args) }
OpCode.RES_89 -> setupInstr(opCode) { cpu, args -> cpu.res_89(*args) }
OpCode.RES_8A -> setupInstr(opCode) { cpu, args -> cpu.res_8a(*args) }
OpCode.RES_8B -> setupInstr(opCode) { cpu, args -> cpu.res_8b(*args) }
OpCode.RES_8C -> setupInstr(opCode) { cpu, args -> cpu.res_8c(*args) }
OpCode.RES_8D -> setupInstr(opCode) { cpu, args -> cpu.res_8d(*args) }
OpCode.RES_8E -> setupInstr(opCode) { cpu, args -> cpu.res_8e(*args) }
OpCode.RES_8F -> setupInstr(opCode) { cpu, args -> cpu.res_8f(*args) }
OpCode.RES_90 -> setupInstr(opCode) { cpu, args -> cpu.res_90(*args) }
OpCode.RES_91 -> setupInstr(opCode) { cpu, args -> cpu.res_91(*args) }
OpCode.RES_92 -> setupInstr(opCode) { cpu, args -> cpu.res_92(*args) }
OpCode.RES_93 -> setupInstr(opCode) { cpu, args -> cpu.res_93(*args) }
OpCode.RES_94 -> setupInstr(opCode) { cpu, args -> cpu.res_94(*args) }
OpCode.RES_95 -> setupInstr(opCode) { cpu, args -> cpu.res_95(*args) }
OpCode.RES_96 -> setupInstr(opCode) { cpu, args -> cpu.res_96(*args) }
OpCode.RES_97 -> setupInstr(opCode) { cpu, args -> cpu.res_97(*args) }
OpCode.RES_98 -> setupInstr(opCode) { cpu, args -> cpu.res_98(*args) }
OpCode.RES_99 -> setupInstr(opCode) { cpu, args -> cpu.res_99(*args) }
OpCode.RES_9A -> setupInstr(opCode) { cpu, args -> cpu.res_9a(*args) }
OpCode.RES_9B -> setupInstr(opCode) { cpu, args -> cpu.res_9b(*args) }
OpCode.RES_9C -> setupInstr(opCode) { cpu, args -> cpu.res_9c(*args) }
OpCode.RES_9D -> setupInstr(opCode) { cpu, args -> cpu.res_9d(*args) }
OpCode.RES_9E -> setupInstr(opCode) { cpu, args -> cpu.res_9e(*args) }
OpCode.RES_9F -> setupInstr(opCode) { cpu, args -> cpu.res_9f(*args) }
OpCode.RES_A0 -> setupInstr(opCode) { cpu, args -> cpu.res_a0(*args) }
OpCode.RES_A1 -> setupInstr(opCode) { cpu, args -> cpu.res_a1(*args) }
OpCode.RES_A2 -> setupInstr(opCode) { cpu, args -> cpu.res_a2(*args) }
OpCode.RES_A3 -> setupInstr(opCode) { cpu, args -> cpu.res_a3(*args) }
OpCode.RES_A4 -> setupInstr(opCode) { cpu, args -> cpu.res_a4(*args) }
OpCode.RES_A5 -> setupInstr(opCode) { cpu, args -> cpu.res_a5(*args) }
OpCode.RES_A6 -> setupInstr(opCode) { cpu, args -> cpu.res_a6(*args) }
OpCode.RES_A7 -> setupInstr(opCode) { cpu, args -> cpu.res_a7(*args) }
OpCode.RES_A8 -> setupInstr(opCode) { cpu, args -> cpu.res_a8(*args) }
OpCode.RES_A9 -> setupInstr(opCode) { cpu, args -> cpu.res_a9(*args) }
OpCode.RES_AA -> setupInstr(opCode) { cpu, args -> cpu.res_aa(*args) }
OpCode.RES_AB -> setupInstr(opCode) { cpu, args -> cpu.res_ab(*args) }
OpCode.RES_AC -> setupInstr(opCode) { cpu, args -> cpu.res_ac(*args) }
OpCode.RES_AD -> setupInstr(opCode) { cpu, args -> cpu.res_ad(*args) }
OpCode.RES_AE -> setupInstr(opCode) { cpu, args -> cpu.res_ae(*args) }
OpCode.RES_AF -> setupInstr(opCode) { cpu, args -> cpu.res_af(*args) }
OpCode.RES_B0 -> setupInstr(opCode) { cpu, args -> cpu.res_b0(*args) }
OpCode.RES_B1 -> setupInstr(opCode) { cpu, args -> cpu.res_b1(*args) }
OpCode.RES_B2 -> setupInstr(opCode) { cpu, args -> cpu.res_b2(*args) }
OpCode.RES_B3 -> setupInstr(opCode) { cpu, args -> cpu.res_b3(*args) }
OpCode.RES_B4 -> setupInstr(opCode) { cpu, args -> cpu.res_b4(*args) }
OpCode.RES_B5 -> setupInstr(opCode) { cpu, args -> cpu.res_b5(*args) }
OpCode.RES_B6 -> setupInstr(opCode) { cpu, args -> cpu.res_b6(*args) }
OpCode.RES_B7 -> setupInstr(opCode) { cpu, args -> cpu.res_b7(*args) }
OpCode.RES_B8 -> setupInstr(opCode) { cpu, args -> cpu.res_b8(*args) }
OpCode.RES_B9 -> setupInstr(opCode) { cpu, args -> cpu.res_b9(*args) }
OpCode.RES_BA -> setupInstr(opCode) { cpu, args -> cpu.res_ba(*args) }
OpCode.RES_BB -> setupInstr(opCode) { cpu, args -> cpu.res_bb(*args) }
OpCode.RES_BC -> setupInstr(opCode) { cpu, args -> cpu.res_bc(*args) }
OpCode.RES_BD -> setupInstr(opCode) { cpu, args -> cpu.res_bd(*args) }
OpCode.RES_BE -> setupInstr(opCode) { cpu, args -> cpu.res_be(*args) }
OpCode.RES_BF -> setupInstr(opCode) { cpu, args -> cpu.res_bf(*args) }
OpCode.SET_C0 -> setupInstr(opCode) { cpu, args -> cpu.set_c0(*args) }
OpCode.SET_C1 -> setupInstr(opCode) { cpu, args -> cpu.set_c1(*args) }
OpCode.SET_C2 -> setupInstr(opCode) { cpu, args -> cpu.set_c2(*args) }
OpCode.SET_C3 -> setupInstr(opCode) { cpu, args -> cpu.set_c3(*args) }
OpCode.SET_C4 -> setupInstr(opCode) { cpu, args -> cpu.set_c4(*args) }
OpCode.SET_C5 -> setupInstr(opCode) { cpu, args -> cpu.set_c5(*args) }
OpCode.SET_C6 -> setupInstr(opCode) { cpu, args -> cpu.set_c6(*args) }
OpCode.SET_C7 -> setupInstr(opCode) { cpu, args -> cpu.set_c7(*args) }
OpCode.SET_C8 -> setupInstr(opCode) { cpu, args -> cpu.set_c8(*args) }
OpCode.SET_C9 -> setupInstr(opCode) { cpu, args -> cpu.set_c9(*args) }
OpCode.SET_CA -> setupInstr(opCode) { cpu, args -> cpu.set_ca(*args) }
OpCode.SET_CB -> setupInstr(opCode) { cpu, args -> cpu.set_cb(*args) }
OpCode.SET_CC -> setupInstr(opCode) { cpu, args -> cpu.set_cc(*args) }
OpCode.SET_CD -> setupInstr(opCode) { cpu, args -> cpu.set_cd(*args) }
OpCode.SET_CE -> setupInstr(opCode) { cpu, args -> cpu.set_ce(*args) }
OpCode.SET_CF -> setupInstr(opCode) { cpu, args -> cpu.set_cf(*args) }
OpCode.SET_D0 -> setupInstr(opCode) { cpu, args -> cpu.set_d0(*args) }
OpCode.SET_D1 -> setupInstr(opCode) { cpu, args -> cpu.set_d1(*args) }
OpCode.SET_D2 -> setupInstr(opCode) { cpu, args -> cpu.set_d2(*args) }
OpCode.SET_D3 -> setupInstr(opCode) { cpu, args -> cpu.set_d3(*args) }
OpCode.SET_D4 -> setupInstr(opCode) { cpu, args -> cpu.set_d4(*args) }
OpCode.SET_D5 -> setupInstr(opCode) { cpu, args -> cpu.set_d5(*args) }
OpCode.SET_D6 -> setupInstr(opCode) { cpu, args -> cpu.set_d6(*args) }
OpCode.SET_D7 -> setupInstr(opCode) { cpu, args -> cpu.set_d7(*args) }
OpCode.SET_D8 -> setupInstr(opCode) { cpu, args -> cpu.set_d8(*args) }
OpCode.SET_D9 -> setupInstr(opCode) { cpu, args -> cpu.set_d9(*args) }
OpCode.SET_DA -> setupInstr(opCode) { cpu, args -> cpu.set_da(*args) }
OpCode.SET_DB -> setupInstr(opCode) { cpu, args -> cpu.set_db(*args) }
OpCode.SET_DC -> setupInstr(opCode) { cpu, args -> cpu.set_dc(*args) }
OpCode.SET_DD -> setupInstr(opCode) { cpu, args -> cpu.set_dd(*args) }
OpCode.SET_DE -> setupInstr(opCode) { cpu, args -> cpu.set_de(*args) }
OpCode.SET_DF -> setupInstr(opCode) { cpu, args -> cpu.set_df(*args) }
OpCode.SET_E0 -> setupInstr(opCode) { cpu, args -> cpu.set_e0(*args) }
OpCode.SET_E1 -> setupInstr(opCode) { cpu, args -> cpu.set_e1(*args) }
OpCode.SET_E2 -> setupInstr(opCode) { cpu, args -> cpu.set_e2(*args) }
OpCode.SET_E3 -> setupInstr(opCode) { cpu, args -> cpu.set_e3(*args) }
OpCode.SET_E4 -> setupInstr(opCode) { cpu, args -> cpu.set_e4(*args) }
OpCode.SET_E5 -> setupInstr(opCode) { cpu, args -> cpu.set_e5(*args) }
OpCode.SET_E6 -> setupInstr(opCode) { cpu, args -> cpu.set_e6(*args) }
OpCode.SET_E7 -> setupInstr(opCode) { cpu, args -> cpu.set_e7(*args) }
OpCode.SET_E8 -> setupInstr(opCode) { cpu, args -> cpu.set_e8(*args) }
OpCode.SET_E9 -> setupInstr(opCode) { cpu, args -> cpu.set_e9(*args) }
OpCode.SET_EA -> setupInstr(opCode) { cpu, args -> cpu.set_ea(*args) }
OpCode.SET_EB -> setupInstr(opCode) { cpu, args -> cpu.set_eb(*args) }
OpCode.SET_EC -> setupInstr(opCode) { cpu, args -> cpu.set_ec(*args) }
OpCode.SET_ED -> setupInstr(opCode) { cpu, args -> cpu.set_ed(*args) }
OpCode.SET_EE -> setupInstr(opCode) { cpu, args -> cpu.set_ee(*args) }
OpCode.SET_EF -> setupInstr(opCode) { cpu, args -> cpu.set_ef(*args) }
OpCode.SET_F0 -> setupInstr(opCode) { cpu, args -> cpu.set_f0(*args) }
OpCode.SET_F1 -> setupInstr(opCode) { cpu, args -> cpu.set_f1(*args) }
OpCode.SET_F2 -> setupInstr(opCode) { cpu, args -> cpu.set_f2(*args) }
OpCode.SET_F3 -> setupInstr(opCode) { cpu, args -> cpu.set_f3(*args) }
OpCode.SET_F4 -> setupInstr(opCode) { cpu, args -> cpu.set_f4(*args) }
OpCode.SET_F5 -> setupInstr(opCode) { cpu, args -> cpu.set_f5(*args) }
OpCode.SET_F6 -> setupInstr(opCode) { cpu, args -> cpu.set_f6(*args) }
OpCode.SET_F7 -> setupInstr(opCode) { cpu, args -> cpu.set_f7(*args) }
OpCode.SET_F8 -> setupInstr(opCode) { cpu, args -> cpu.set_f8(*args) }
OpCode.SET_F9 -> setupInstr(opCode) { cpu, args -> cpu.set_f9(*args) }
OpCode.SET_FA -> setupInstr(opCode) { cpu, args -> cpu.set_fa(*args) }
OpCode.SET_FB -> setupInstr(opCode) { cpu, args -> cpu.set_fb(*args) }
OpCode.SET_FC -> setupInstr(opCode) { cpu, args -> cpu.set_fc(*args) }
OpCode.SET_FD -> setupInstr(opCode) { cpu, args -> cpu.set_fd(*args) }
OpCode.SET_FE -> setupInstr(opCode) { cpu, args -> cpu.set_fe(*args) }
OpCode.SET_FF -> setupInstr(opCode) { cpu, args -> cpu.set_ff(*args) }
else -> setupInstr(opCode) { cpu, args -> cpu.nop_00(*args) }
}
}
}
fun execute(cpu: Cpu, opcode: Int, args: IntArray): Int {
return if (opcode < 0x100) instrs[opcode].execute(cpu, *args)
else externalInstrs[opcode - 0x100].execute(cpu, *args)
}
} | 0 | Kotlin | 2 | 3 | 709efa50a0b176d7ed8aefe4db0f35f173472de2 | 44,934 | KotBoy | MIT License |
easyadapter-compiler/src/main/java/com/amrdeveloper/easyadapter/compiler/data/bind/BindExpandableData.kt | AmrDeveloper | 436,362,549 | false | {"Kotlin": 165234} | package com.amrdeveloper.easyadapter.compiler.data.bind
import com.amrdeveloper.easyadapter.compiler.data.listener.ListenerData
data class BindExpandableData (
val modelClassName: String,
val modelClassPackageName : String,
val layoutId: String,
val bindingDataList: List<BindingData>,
val listeners: Set<ListenerData>
) | 1 | Kotlin | 5 | 77 | 22a727c2a71f50c5b2274c8b3f1593cc8f11c7ce | 342 | EasyAdapter | MIT License |
app/src/main/java/com/saharw/calculator/App.kt | SaharWeissman | 130,581,486 | false | {"Kotlin": 24434} | package com.saharw.calculator
import android.app.Application
import android.util.Log
/**
* Created by saharw on 22/04/2018.
*/
class App : Application(){
private val TAG = "App"
override fun onCreate() {
Log.d(TAG, "onCreateView()")
super.onCreate()
}
} | 0 | Kotlin | 0 | 0 | c9e1d109e0157ce64836f21a790e0fc21688c970 | 287 | CalculatorApp | Apache License 2.0 |
app/src/main/java/com/example/lokalassignment/db/BookmarkedJob.kt | sayak22 | 832,285,136 | false | {"Kotlin": 29673} | package com.example.lokalassignment.db
import androidx.room.Entity
import androidx.room.PrimaryKey
/**
* Data class representing a bookmarked job entity in the database.
*
* @property id Unique identifier for the job, used as the primary key.
* @property title The title of the job, nullable.
* @property destination The location of the job, nullable.
* @property salary The salary information for the job, nullable.
* @property phoneNumber The contact number for the job, nullable.
* @property isBookmarked Indicator for bookmark status, where 1 means bookmarked.
*/
@Entity(tableName = "bookmarkedJobs")
data class BookmarkedJob(
@PrimaryKey(autoGenerate = false) // Primary key for the entity, no auto-generation
val id: Long,
val title: String?, // Job title, can be null if not provided
val destination: String?, // Job location, can be null if not provided
val salary: String?, // Salary details, can be null if not provided
val phoneNumber: String?, // Contact number, can be null if not provided
val isBookmarked: Int // Bookmark status, 1 for bookmarked, 0 for not
)
| 0 | Kotlin | 0 | 0 | bab56ecb0511436c5b63e04cb9cf8192bd2e34f0 | 1,117 | lokal-assignment | MIT License |
domain/src/main/java/com/jslee/domain/model/movie/Credits.kt | JaesungLeee | 675,525,103 | false | {"Kotlin": 289426} | package com.jslee.domain.model.movie
import com.jslee.domain.model.Gender
/**
* MooBeside
* @author jaesung
* @created 2023/10/03
*/
data class Cast(
val personId: Long,
val gender: Gender,
val originalName: String,
val profileImageUrl: String?,
val character: String,
)
data class Staff(
val personId: Long,
val gender: Gender,
val originalName: String,
val profileImageUrl: String?,
val job: String,
) {
val isDirector = job == "Director"
}
| 10 | Kotlin | 0 | 4 | fc4b2b5746f3fb323789f6f45b08317253be3039 | 494 | MooBeside | MIT License |
src/main/kotlin/io/github/sovathna/domain/Repository.kt | sovathna | 520,411,216 | false | null | package io.github.sovathna.domain
import io.github.sovathna.data.wordsdb.dao.SelectDefinition
import io.github.sovathna.model.ThemeType
import io.github.sovathna.model.WordUi
import io.github.sovathna.model.WordsType
interface Repository {
suspend fun getWords(type: WordsType, filter: String, page: Int, pageSize: Int): List<WordUi>
suspend fun getDefinition(wordId: Long): SelectDefinition
suspend fun addHistory(wordId: Long, word: String)
suspend fun isBookmark(wordId: Long): Boolean
suspend fun addOrDeleteBookmark(isBookmark: Boolean, wordId: Long, word: String): Boolean
suspend fun setThemeType(themeType: ThemeType)
suspend fun getThemeType(): ThemeType
suspend fun setFontSize(size: Float)
suspend fun getFontSize(): Float
suspend fun getDataVersion(): Int
suspend fun setDataVersion(version: Int)
suspend fun shouldDownloadData(newVersion: Int): Boolean
} | 0 | Kotlin | 0 | 1 | e61e2fb8b64344879beb20849f1dc28c275929a3 | 928 | compose-dictionary | MIT License |
shared/src/androidMain/kotlin/dev/avatsav/linkding/data/unfurl/LinkUnfurler.kt | avatsav | 576,855,763 | false | {"Kotlin": 190189, "Swift": 589} | package dev.avatsav.linkding.data.unfurl
import me.saket.unfurl.Unfurler
actual class LinkUnfurler(private val unfurler: Unfurler) {
actual suspend fun unfurl(url: String): UnfurlResult {
return try {
val result = unfurler.unfurl(url)
UnfurlResult.Data(url, result?.title, result?.description)
} catch (e: Throwable) {
UnfurlResult.Error(e.message ?: "Error getting link metadata")
}
}
}
| 2 | Kotlin | 0 | 8 | 368842a2735481380fcf57382ff565a8e521d1cb | 459 | linkding-apps | MIT License |
app/src/main/java/com/marcouberti/video/playground/ui/transformations/shapes/Pyramid.kt | marcouberti | 317,791,818 | false | null | package com.bendingspoons.opengltest1.ui.main.shapes
import android.opengl.GLES20
import kotlin.math.sqrt
class Pyramid : Shape {
// Use to access and set the view transformation
private var vPMatrixHandle: Int = 0
private val mProgram: Int
private var positionHandle: Int = 0
private var mColorHandle: Int = 0
private val COORDS_PER_VERTEX = 3
private val vertexStride: Int = COORDS_PER_VERTEX * 4 // 4 bytes per vertex
// Set color with red, green, blue and alpha (opacity) values
val fillColor = floatArrayOf(
1f, 0f, 0f, 1f,
0f, 1f, 0f, 1f,
0f, 0f, 1f, 1f,
1f, 0f, 0f, 1f,
0f, 1f, 0f, 1f,
0f, 0f, 1f, 1f,
1f, 0f, 0f, 1f,
0f, 1f, 0f, 1f,
0f, 0f, 1f, 1f,
1f, 0f, 0f, 1f,
0f, 1f, 0f, 1f,
0f, 0f, 1f, 1f,
)
private val pyramid = listOf(
0f, 1f, 0f,
-1f, -1f, 1f,
1f, -1f, 1f,
0f, 1f, 0f,
1f, -1f, 1f,
1f, -1f, -1f,
0f, 1f, 0f,
1f, -1f, -1f,
-1f, -1f, -1f,
0f, 1f, 0f,
-1f, -1f, -1f,
-1f, -1f, 1f,
)
val vertexBuffer = vertexBuffer(pyramid)
init {
val vertexShader = Shape.loadShader(GLES20.GL_VERTEX_SHADER, Shape.vertexShaderCode)
val fragmentShader = Shape.loadShader(GLES20.GL_FRAGMENT_SHADER, Shape.fragmentShaderCode)
mProgram = GLES20.glCreateProgram().also {
// add the vertex shader to program
GLES20.glAttachShader(it, vertexShader)
// add the fragment shader to program
GLES20.glAttachShader(it, fragmentShader)
// creates OpenGL ES program executables
GLES20.glLinkProgram(it)
}
}
override fun draw(mvpMatrix: FloatArray) {
// Add program to OpenGL ES environment
GLES20.glUseProgram(mProgram)
// get handle to vertex shader's vPosition member
positionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition").also {
// Enable a handle to the triangle vertices
GLES20.glEnableVertexAttribArray(it)
// Prepare the triangle coordinate data
GLES20.glVertexAttribPointer(
it,
COORDS_PER_VERTEX,
GLES20.GL_FLOAT,
false,
vertexStride,
vertexBuffer,
)
// get handle to fragment shader's vColor member
mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor").also { colorHandle ->
// Set color for drawing the triangle
GLES20.glEnableVertexAttribArray(it)
// Prepare the triangle coordinate data
GLES20.glVertexAttribPointer(
it,
COORDS_PER_VERTEX,
GLES20.GL_FLOAT,
false,
vertexStride,
vertexBuffer,
)
GLES20.glUniform4fv(colorHandle, fillColor.size/4, fillColor, 0)
}
// get handle to shape's transformation matrix
vPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix")
// Pass the projection and view transformation to the shader
GLES20.glUniformMatrix4fv(vPMatrixHandle, 1, false, mvpMatrix, 0)
// Draw the shape
GLES20.glDrawArrays(
GLES20.GL_TRIANGLE_FAN,
0,
vertexBuffer.remaining() / 3,
)
// Disable vertex array
GLES20.glDisableVertexAttribArray(it)
}
}
}
| 0 | Kotlin | 1 | 2 | 99fbdbadc60a5186e716879e7aa7b95c05730f3a | 3,277 | video-editing-playground | Apache License 2.0 |
app/src/main/java/com/marcouberti/video/playground/ui/transformations/shapes/Pyramid.kt | marcouberti | 317,791,818 | false | null | package com.bendingspoons.opengltest1.ui.main.shapes
import android.opengl.GLES20
import kotlin.math.sqrt
class Pyramid : Shape {
// Use to access and set the view transformation
private var vPMatrixHandle: Int = 0
private val mProgram: Int
private var positionHandle: Int = 0
private var mColorHandle: Int = 0
private val COORDS_PER_VERTEX = 3
private val vertexStride: Int = COORDS_PER_VERTEX * 4 // 4 bytes per vertex
// Set color with red, green, blue and alpha (opacity) values
val fillColor = floatArrayOf(
1f, 0f, 0f, 1f,
0f, 1f, 0f, 1f,
0f, 0f, 1f, 1f,
1f, 0f, 0f, 1f,
0f, 1f, 0f, 1f,
0f, 0f, 1f, 1f,
1f, 0f, 0f, 1f,
0f, 1f, 0f, 1f,
0f, 0f, 1f, 1f,
1f, 0f, 0f, 1f,
0f, 1f, 0f, 1f,
0f, 0f, 1f, 1f,
)
private val pyramid = listOf(
0f, 1f, 0f,
-1f, -1f, 1f,
1f, -1f, 1f,
0f, 1f, 0f,
1f, -1f, 1f,
1f, -1f, -1f,
0f, 1f, 0f,
1f, -1f, -1f,
-1f, -1f, -1f,
0f, 1f, 0f,
-1f, -1f, -1f,
-1f, -1f, 1f,
)
val vertexBuffer = vertexBuffer(pyramid)
init {
val vertexShader = Shape.loadShader(GLES20.GL_VERTEX_SHADER, Shape.vertexShaderCode)
val fragmentShader = Shape.loadShader(GLES20.GL_FRAGMENT_SHADER, Shape.fragmentShaderCode)
mProgram = GLES20.glCreateProgram().also {
// add the vertex shader to program
GLES20.glAttachShader(it, vertexShader)
// add the fragment shader to program
GLES20.glAttachShader(it, fragmentShader)
// creates OpenGL ES program executables
GLES20.glLinkProgram(it)
}
}
override fun draw(mvpMatrix: FloatArray) {
// Add program to OpenGL ES environment
GLES20.glUseProgram(mProgram)
// get handle to vertex shader's vPosition member
positionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition").also {
// Enable a handle to the triangle vertices
GLES20.glEnableVertexAttribArray(it)
// Prepare the triangle coordinate data
GLES20.glVertexAttribPointer(
it,
COORDS_PER_VERTEX,
GLES20.GL_FLOAT,
false,
vertexStride,
vertexBuffer,
)
// get handle to fragment shader's vColor member
mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor").also { colorHandle ->
// Set color for drawing the triangle
GLES20.glEnableVertexAttribArray(it)
// Prepare the triangle coordinate data
GLES20.glVertexAttribPointer(
it,
COORDS_PER_VERTEX,
GLES20.GL_FLOAT,
false,
vertexStride,
vertexBuffer,
)
GLES20.glUniform4fv(colorHandle, fillColor.size/4, fillColor, 0)
}
// get handle to shape's transformation matrix
vPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix")
// Pass the projection and view transformation to the shader
GLES20.glUniformMatrix4fv(vPMatrixHandle, 1, false, mvpMatrix, 0)
// Draw the shape
GLES20.glDrawArrays(
GLES20.GL_TRIANGLE_FAN,
0,
vertexBuffer.remaining() / 3,
)
// Disable vertex array
GLES20.glDisableVertexAttribArray(it)
}
}
}
| 0 | Kotlin | 1 | 2 | 99fbdbadc60a5186e716879e7aa7b95c05730f3a | 3,277 | video-editing-playground | Apache License 2.0 |
domain/src/main/java/com/example/domain/entity/StatsPlayer.kt | minjun8946 | 390,971,021 | false | null | package com.example.domain.entity
data class StatsPlayer(
val playerId : Int,
val firstName : String,
val lastName : String,
val position : String,
val teamId : String,
) | 0 | Kotlin | 0 | 1 | 5957c6f9f991138c44f0a024ea2092313f19cda9 | 191 | Stats | MIT License |
app/src/main/java/br/com/evertofabio/WatcherMask.kt | evertof | 449,493,787 | false | {"Kotlin": 7969} | package br.com.evertofabio
import android.text.Editable
import android.text.TextWatcher
import com.google.android.material.textfield.TextInputEditText
class WatcherMask(private val mask: String, private val editText: TextInputEditText): TextWatcher {
private var isUpdating = false
private var maskChars = "/-,.()"
private val maskLength = mask.length
private fun getMaskChar(pos: Int): String {
var maskChar = ""
if ((pos < maskLength) && (isMaskChar(mask[pos]))) {
maskChar = mask[pos].toString()
}
return maskChar
}
private fun isMaskChar(char: Char): Boolean {
return maskChars.contains(char)
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if (isUpdating) {
isUpdating = false
return
}
if (before==1)
return
val text = onlyNumbers(s.toString())
var newText = ""
var index = 0
text.forEach {
val maskSeparator = getMaskChar(index)
if (maskSeparator.isNotEmpty()) {
index++
newText += maskSeparator
}
newText += it
index++
}
isUpdating = true
editText.setText(newText)
editText.setSelection(newText.length)
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun afterTextChanged(s: Editable?) {
}
} | 0 | Kotlin | 0 | 0 | 8cdd3dd76b7094d8d4a576b6af257c2471ef481e | 1,524 | EditDate | Apache License 2.0 |
app/src/test/java/com/taylorsloan/jobseer/dagger/component/TestStorageComponent.kt | taylorsloan | 108,706,949 | false | null | package com.taylorsloan.jobseer.dagger.component
import com.taylorsloan.jobseer.AbstractObjectBoxTest
import com.taylorsloan.jobseer.dagger.module.TestStorageModule
import com.taylorsloan.jobseer.dagger.scope.DataScope
import dagger.Component
/**
* Created by taylorsloan on 10/28/17.
*/
@Component(modules = arrayOf(TestStorageModule::class))
@DataScope
interface TestStorageComponent : StorageComponent{
fun inject(objectBoxTest: AbstractObjectBoxTest)
} | 0 | Kotlin | 0 | 1 | d22fa1fdd85c828be6295d5db2af4ecdbc7b1307 | 464 | Job-Seer | MIT License |
app/src/main/java/com/azat/newsappmvvm/util/Constant.kt | theazat | 289,460,223 | false | null | package com.azat.newsappmvvm.util
/*************************
* Created by AZAT SAYAN *
* *
* Contact: @theazat *
* *
* 22/08/2020 - 6:31 PM *
************************/
class Constant {
companion object {
const val API_KEY = "8fc34d247dee40b5ba90295e691cf8b7"
const val BASE_URL = "https://newsapi.org"
const val NEWS_DATABASE_NAME = "news_db.db"
const val SEARCH_NEWS_TIME_DELAY = 500L
}
} | 0 | Kotlin | 2 | 8 | 6108ab4243dc16a979a175b6432d63de025da671 | 485 | NewsAppMVVM | Apache License 2.0 |
src/requests/processors/builds/Routes.kt | bsscco | 209,956,587 | false | null | package requests.processors.builds
import io.ktor.application.call
import io.ktor.routing.Route
import io.ktor.routing.get
fun Route.builds() {
get("/builds/can") { BuildAvailableProcessor(call).process() }
} | 0 | Kotlin | 0 | 0 | af1311d6e980a4b654f2d702fc6497af7c3456fc | 214 | auto-build-android | Apache License 2.0 |
assertk-jvm/src/test/kotlin/test/assertk/assertions/JavaAnyTest.kt | palbecki | 146,797,407 | true | {"Kotlin": 185243, "Java": 134} | package test.assertk.assertions
import assertk.assert
import assertk.assertions.*
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
class JavaAnyTest {
val p: String = JavaAnyTest::class.java.name
val subject = BasicObject("test")
@Test fun extracts_jClass() {
assertEquals(BasicObject::class.java, assert(subject as TestObject).jClass().actual)
}
@Test fun isInstanceOf_jclass_same_class_passes() {
assert(subject).isInstanceOf(BasicObject::class.java)
}
@Test fun isInstanceOf_jclass_parent_class_passes() {
assert(subject).isInstanceOf(TestObject::class.java)
}
@Test fun isInstanceOf_jclass_different_class_fails() {
val error = assertFails {
assert(subject).isInstanceOf(DifferentObject::class.java)
}
assertEquals(
"expected to be instance of:<$p\$DifferentObject> but had class:<$p\$BasicObject>",
error.message
)
}
@Test fun isInstanceOf_jclass_run_block_when_passes() {
val error = assertFails {
assert(subject as TestObject).isInstanceOf(BasicObject::class.java) {
it.prop("str", BasicObject::str).isEqualTo("wrong")
}
}
assertEquals("expected [str]:<\"[wrong]\"> but was:<\"[test]\"> (test)", error.message)
}
@Test fun isInstanceOf_jclass_doesnt_run_block_when_fails() {
val error = assertFails {
assert(subject as TestObject).isInstanceOf(DifferentObject::class.java) {
it.isNull()
}
}
assertEquals(
"expected to be instance of:<$p\$DifferentObject> but had class:<$p\$BasicObject>",
error.message
)
}
@Test fun isNotInstanceOf_jclass_different_class_passess() {
assert(subject).isNotInstanceOf(DifferentObject::class.java)
}
@Test fun isNotInstanceOf_jclass_same_class_fails() {
val error = assertFails {
assert(subject).isNotInstanceOf(BasicObject::class.java)
}
assertEquals("expected to not be instance of:<$p\$BasicObject>", error.message)
}
@Test fun isNotInstanceOf_jclass_parent_class_fails() {
val error = assertFails {
assert(subject).isNotInstanceOf(TestObject::class.java)
}
assertEquals("expected to not be instance of:<$p\$TestObject>", error.message)
}
@Test fun prop_callable_extract_prop_passes() {
assert(subject).prop(BasicObject::str).isEqualTo("test")
}
@Test fun prop_callable_extract_prop_includes_name_in_failure_message() {
val error = assertFails {
assert(subject).prop(BasicObject::str).isEmpty()
}
assertEquals("expected [str] to be empty but was:<\"test\"> (test)", error.message)
}
open class TestObject
class BasicObject(
val str: String,
val int: Int = 42,
val double: Double = 3.14
) : TestObject() {
override fun toString(): String = str
override fun equals(other: Any?): Boolean =
(other is BasicObject) && (str == other.str && int == other.int && double == other.double)
override fun hashCode(): Int = 42
}
class DifferentObject : TestObject()
}
| 0 | Kotlin | 0 | 0 | 67559eb59a915dba13fff348bbe77e19f9e3da34 | 3,303 | assertk | MIT License |
data/src/main/java/com/alexzh/data/repository/CafeRemoteRepository.kt | AlexZhukovich | 192,403,534 | false | null | package com.alexzh.data.repository
import com.alexzh.data.model.CafeEntity
import io.reactivex.Single
interface CafeRemoteRepository {
fun getCafes(
currentLatitude: Double,
currentLongitude: Double,
searchRadius: Int,
numberCafesOnMap: Int
): Single<List<CafeEntity>>
} | 8 | Kotlin | 1 | 7 | dab7ea97efee664dd87c201dc15ac293bf3416a5 | 312 | ImBarista-App | Apache License 2.0 |
src/test/kotlin/tech/relaycorp/relaynet/keystores/CertificateStoreTest.kt | relaycorp | 171,718,724 | false | null | package tech.relaycorp.relaynet.keystores
import java.time.ZonedDateTime
import kotlin.test.assertContains
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import tech.relaycorp.relaynet.utils.KeyPairSet
import tech.relaycorp.relaynet.utils.MockCertificateStore
import tech.relaycorp.relaynet.utils.PDACertPath
import tech.relaycorp.relaynet.wrappers.asn1.ASN1Utils
import tech.relaycorp.relaynet.wrappers.x509.Certificate
@ExperimentalCoroutinesApi
class CertificateStoreTest {
private val certificate = PDACertPath.PRIVATE_GW
private val certificateChain = listOf(PDACertPath.PUBLIC_GW, PDACertPath.PUBLIC_GW)
private val aboutToExpireCertificate = Certificate.issue(
"foo",
certificate.subjectPublicKey,
KeyPairSet.PRIVATE_GW.private,
ZonedDateTime.now().plusMinutes(1),
validityStartDate = ZonedDateTime.now().minusSeconds(2)
)
private val expiredCertificate = Certificate.issue(
"foo",
certificate.subjectPublicKey,
KeyPairSet.PRIVATE_GW.private,
ZonedDateTime.now().minusSeconds(1),
validityStartDate = ZonedDateTime.now().minusSeconds(2)
)
private val unrelatedCertificate = PDACertPath.PRIVATE_ENDPOINT
@Nested
inner class Save {
@Test
fun `Certificate should be stored`() = runBlockingTest {
val store = MockCertificateStore()
store.save(certificate)
assertTrue(store.data.containsKey(certificate.subjectPrivateAddress))
val certificationPaths = store.data[certificate.subjectPrivateAddress]!!
assertEquals(1, certificationPaths.size)
}
@Test
fun `Certification path should be stored`() = runBlockingTest {
val store = MockCertificateStore()
store.save(certificate, certificateChain)
assertTrue(store.data.containsKey(certificate.subjectPrivateAddress))
val certificationPaths = store.data[certificate.subjectPrivateAddress]!!
assertEquals(1, certificationPaths.size)
}
}
@Nested
inner class RetrieveLatest {
@Test
fun `Existing certification path should be returned`() = runBlockingTest {
val store = MockCertificateStore()
store.save(certificate, certificateChain)
val certificationPath = store.retrieveLatest(certificate.subjectPrivateAddress)!!
assertEquals(certificate, certificationPath.leafCertificate)
assertEquals(certificateChain, certificationPath.chain)
}
@Test
fun `Null should be returned if there are none`() = runBlockingTest {
val store = MockCertificateStore()
assertNull(store.retrieveLatest("non-existent"))
}
@Test
fun `Last to expire certificate should be returned`() = runBlockingTest {
val store = MockCertificateStore()
store.save(certificate, certificateChain)
store.save(aboutToExpireCertificate, certificateChain)
val certificationPath = store.retrieveLatest(certificate.subjectPrivateAddress)!!
assertEquals(certificate, certificationPath.leafCertificate)
}
}
@Nested
inner class RetrieveAll {
@Test
fun `No certification path should be returned if there are none`() = runBlockingTest {
val store = MockCertificateStore()
assertEquals(0, store.retrieveAll("non-existent").size)
}
@Test
fun `All stored non-expired certification paths should be returned`() = runBlockingTest {
val store = MockCertificateStore()
store.save(certificate, certificateChain)
store.save(aboutToExpireCertificate, certificateChain)
store.save(expiredCertificate, certificateChain)
val allCertificationPaths = store.retrieveAll(certificate.subjectPrivateAddress)
assertEquals(2, allCertificationPaths.size)
assertContains(
allCertificationPaths.map { it.leafCertificate },
certificate
)
assertContains(
allCertificationPaths.map { it.leafCertificate },
aboutToExpireCertificate
)
}
@Test
fun `Malformed certification path should throw KeyStoreBackendException`() =
runBlockingTest {
val store = MockCertificateStore()
store.data[certificate.subjectPrivateAddress] = listOf(
Pair(ZonedDateTime.now().plusDays(1), "malformed".toByteArray())
)
val exception = assertThrows<KeyStoreBackendException> {
store.retrieveAll(certificate.subjectPrivateAddress)
}
assertEquals("Malformed certification path", exception.message)
}
@Test
fun `Empty certification path should throw KeyStoreBackendException`() = runBlockingTest {
val store = MockCertificateStore()
store.data[certificate.subjectPrivateAddress] = listOf(
Pair(
ZonedDateTime.now().plusDays(1),
ASN1Utils.serializeSequence(emptyList())
)
)
val exception = assertThrows<KeyStoreBackendException> {
store.retrieveAll(certificate.subjectPrivateAddress)
}
assertEquals("Empty certification path", exception.message)
}
}
@Nested
inner class DeleteExpired {
@Test
fun `All expired certification paths are deleted`() = runBlockingTest {
val store = MockCertificateStore()
store.save(expiredCertificate, certificateChain)
store.deleteExpired()
assertTrue(store.data.isEmpty())
}
}
@Nested
inner class Delete {
@Test
fun `All certification paths of a certain address are deleted`() = runBlockingTest {
val store = MockCertificateStore()
store.save(certificate, certificateChain)
store.save(aboutToExpireCertificate, certificateChain)
store.save(unrelatedCertificate, certificateChain)
store.delete(certificate.subjectPrivateAddress)
assertNull(store.data[certificate.subjectPrivateAddress])
assertTrue(store.data[unrelatedCertificate.subjectPrivateAddress]!!.isNotEmpty())
}
}
}
| 18 | Kotlin | 0 | 1 | c9bf51aab9cca50df432bb02a14be3f3a60e93fb | 6,794 | awala-jvm | Apache License 2.0 |
wordfilter/src/main/java/com/mediamonks/wordfilter/badLanguage.kt | mediamonks | 627,914,851 | false | null | package com.mediamonks.wordfilter
val badLanguage = """
2 girls 1 cup
2g1c
4r5e
5h1t
5hit
a${'$'}${'$'}
a${'$'}${'$'}hole
a_s_s
a2m
a54
a55
a55hole
aeolus
ahole
alabama hot pocket
alaskan pipeline
anal
anal impaler
anal leakage
analannie
analprobe
analsex
anilingus
anus
apeshit
ar5e
areola
areole
arian
arrse
arse
arsehole
aryan
ass
ass fuck
ass hole
assault
assbag
assbagger
assbandit
assbang
assbanged
assbanger
assbangs
assbite
assblaster
assclown
asscock
asscracker
asses
assface
assfaces
assfuck
assfucker
ass-fucker
assfukka
assgoblin
assh0le
asshat
ass-hat
asshead
assho1e
asshole
assholes
asshopper
asshore
ass-jabber
assjacker
assjockey
asskiss
asskisser
assklown
asslick
asslicker
asslover
assman
assmaster
assmonkey
assmucus
assmunch
assmuncher
assnigger
asspacker
asspirate
ass-pirate
asspuppies
assranger
assshit
assshole
asssucker
asswad
asswhole
asswhore
asswipe
asswipes
auto erotic
autoerotic
axwound
azazel
azz
b!tch
b00bs
b17ch
b1tch
babe
babeland
babes
baby batter
baby juice
badfuck
ball gag
ball gravy
ball kicking
ball licking
ball sack
ball sucking
ballbag
balllicker
balls
ballsack
bampot
bang
bang (one's) box
bangbros
banger
banging
bareback
barely legal
barenaked
barf
barface
barfface
bastard
bastardo
bastards
bastinado
batty boy
bawdy
bazongas
bazooms
bbw
bdsm
beaner
beaners
beardedclam
beastial
beastiality
beatch
beater
beatyourmeat
beaver
beaver cleaver
beaver lips
beef curtain
beef curtains
beer
beeyotch
bellend
bender
beotch
bestial
bestiality
bi+ch
biatch
bicurious
big black
big breasts
big knockers
big tits
bigbastard
bigbutt
bigger
bigtits
bimbo
bimbos
bint
birdlock
bisexual
bi-sexual
bitch
bitch tit
bitchass
bitched
bitcher
bitchers
bitches
bitchez
bitchin
bitching
bitchtits
bitchy
black cock
blonde action
blonde on blonde action
bloodclaat
bloody
bloody hell
blow
blow job
blow me
blow mud
blow your load
blowjob
blowjobs
blue waffle
blumpkin
boang
bod
bodily
bogan
bohunk
boink
boiolas
bollick
bollock
bollocks
bollok
bollox
bomd
bondage
bone
boned
boner
boners
bong
boob
boobies
boobs
booby
booger
bookie
boong
boonga
booobs
boooobs
booooobs
booooooobs
bootee
bootie
booty
booty call
booze
boozer
boozy
bosom
bosomy
bowel
bowels
bra
brassiere
breast
breastjob
breastlover
breastman
breasts
breeder
brotherfucker
brown showers
brunette action
buceta
bugger
buggered
buggery
bukkake
bull shit
bullcrap
bulldike
bulldyke
bullet vibe
bullshit
bullshits
bullshitted
bullturds
bum
bum boy
bumblefuck
bumclat
bumfuck
bummer
bung
bung hole
bunga
bunghole
bunny fucker
bust a load
busty
butchdike
butchdyke
butt
butt fuck
butt plug
buttbang
butt-bang
buttcheeks
buttface
buttfuck
butt-fuck
buttfucka
buttfucker
butt-fucker
butthead
butthole
buttman
buttmuch
buttmunch
buttmuncher
butt-pirate
buttplug
c.0.c.k
c.o.c.k.
c.u.n.t
c0ck
c-0-c-k
c0cksucker
caca
cahone
camel toe
cameltoe
camgirl
camslut
camwhore
carpet muncher
carpetmuncher
cawk
cervix
chesticle
chi-chi man
chick with a dick
child-fucker
chin
chinc
chincs
chink
chinky
choad
choade
choc ice
chocolate rosebuds
chode
chodes
chota bags
cipa
circlejerk
cl1t
cleveland steamer
climax
clit
clit licker
clitface
clitfuck
clitoris
clitorus
clits
clitty
clitty litter
clogwog
clover clamps
clunge
clusterfuck
cnut
cocain
cocaine
cock
c-o-c-k
cock pocket
cock snot
cock sucker
cockass
cockbite
cockblock
cockburger
cockeye
cockface
cockfucker
cockhead
cockholster
cockjockey
cockknocker
cockknoker
cocklicker
cocklover
cocklump
cockmaster
cockmongler
cockmongruel
cockmonkey
cockmunch
cockmuncher
cocknose
cocknugget
cocks
cockshit
cocksmith
cocksmoke
cocksmoker
cocksniffer
cocksucer
cocksuck
cocksuck
cocksucked
cocksucker
cock-sucker
cocksuckers
cocksucking
cocksucks
cocksuka
cocksukka
cockwaffle
coffin dodger
coital
cok
cokmuncher
coksucka
commie
condom
coochie
coochy
coon
coonnass
coons
cooter
cop some wood
coprolagnia
coprophilia
corksucker
cornhole
corp whore
cox
crabs
crack
cracker
crackwhore
crack-whore
crap
crappy
creampie
cretin
crikey
cripple
crotte
cum
cum chugger
cum dumpster
cum freak
cum guzzler
cumbubble
cumdump
cumdumpster
cumguzzler
cumjockey
cummer
cummin
cumming
cums
cumshot
cumshots
cumslut
cumstain
cumtart
cunilingus
cunillingus
cunn
cunnie
cunnilingus
cunntt
cunny
cunt
c-u-n-t
cunt hair
cuntass
cuntbag
cuntface
cuntfuck
cuntfucker
cunthole
cunthunter
cuntlick
cuntlick
cuntlicker
cuntlicker
cuntlicking
cuntrag
cunts
cuntsicle
cuntslut
cunt-struck
cuntsucker
cut rope
cyalis
cyberfuc
cyberfuck
cyberfucked
cyberfucker
cyberfuckers
cyberfucking
cybersex
d0ng
d0uch3
d0uche
d1ck
d1ld0
d1ldo
dago
dagos
dammit
damn
damned
damnit
darkie
darn
date rape
daterape
dawgie-style
deep throat
deepthroat
deggo
dendrophilia
dick
dick head
dick hole
dick shy
dickbag
dickbeaters
dickbrain
dickdipper
dickface
dickflipper
dickfuck
dickfucker
dickhead
dickheads
dickhole
dickish
dick-ish
dickjuice
dickmilk
dickmonger
dickripper
dicks
dicksipper
dickslap
dick-sneeze
dicksucker
dicksucking
dicktickler
dickwad
dickweasel
dickweed
dickwhipper
dickwod
dickzipper
diddle
dike
dildo
dildos
diligaf
dillweed
dimwit
dingle
dingleberries
dingleberry
dink
dinks
dipship
dipshit
dirsa
dirty
dirty pillows
dirty sanchez
dlck
dog style
dog-fucker
doggie style
doggiestyle
doggie-style
doggin
dogging
doggy style
doggystyle
doggy-style
dolcett
domination
dominatrix
dommes
dong
donkey punch
donkeypunch
donkeyribber
doochbag
doofus
dookie
doosh
dopey
double dong
double penetration
doublelift
douch3
douche
douchebag
douchebags
douche-fag
douchewaffle
douchey
dp action
drunk
dry hump
duche
dumass
dumb ass
dumbass
dumbasses
dumbcunt
dumbfuck
dumbshit
dummy
dumshit
dvda
dyke
dykes
eat a dick
eat hair pie
eat my ass
eatpussy
ecchi
ejaculate
ejaculated
ejaculates
ejaculating
ejaculatings
ejaculation
ejakulate
enlargement
erect
erection
erotic
erotism
escort
essohbee
eunuch
extacy
extasy
f u c k
f u c k e r
f.u.c.k
f_u_c_k
f4nny
facefucker
facial
fack
fag
fagbag
fagfucker
fagg
fagged
fagging
faggit
faggitt
faggot
faggotcock
faggots
faggs
fagot
fagots
fags
fagtard
faig
faigt
fanny
fannybandit
fannyflaps
fannyfucker
fanyy
fart
fartknocker
fastfuck
fat
fatass
fatfuck
fatfucker
fcuk
fcuker
fcuking
fecal
feck
fecker
felch
felcher
felching
fellate
fellatio
feltch
feltcher
female squirting
femdom
fenian
figging
fingerbang
fingerfuck
fingerfuck
fingerfucked
fingerfucker
fingerfucker
fingerfuckers
fingerfucking
fingerfucks
fingering
fist fuck
fisted
fistfuck
fistfucked
fistfucker
fistfucker
fistfuckers
fistfucking
fistfuckings
fistfucks
fisting
fisty
flamer
flange
flaps
fleshflute
flog the log
floozy
foad
foah
fondle
foobar
fook
fooker
foot fetish
footfuck
footfucker
footjob
footlicker
foreskin
freakfuck
freakyfucker
freefuck
freex
frigg
frigga
frotting
fubar
fuc
fuck
f-u-c-k
fuck buttons
fuck hole
fuck off
fuck puppet
fuck trophy
fuck yo mama
fuck you
fucka
fuckass
fuck-ass
fuckbag
fuck-bitch
fuckboy
fuckbrain
fuckbutt
fuckbutter
fucked
fuckedup
fucker
fuckers
fuckersucker
fuckface
fuckfreak
fuckhead
fuckheads
fuckher
fuckhole
fuckin
fucking
fuckingbitch
fuckings
fuckingshitmotherfucker
fuckme
fuckme
fuckmeat
fuckmehard
fuckmonkey
fucknugget
fucknut
fucknutt
fuckoff
fucks
fuckstick
fucktard
fuck-tard
fucktards
fucktart
fucktoy
fucktwat
fuckup
fuckwad
fuckwhit
fuckwhore
fuckwit
fuckwitt
fuckyou
fudge packer
fudgepacker
fudge-packer
fuk
fuker
fukker
fukkers
fukkin
fuks
fukwhit
fukwit
fuq
futanari
fux
fux0r
fvck
fxck
gae
gai
gang bang
gangbang
gang-bang
gangbanged
gangbangs
ganja
gash
gassy ass
gay sex
gayass
gaybob
gaydo
gayfuck
gayfuckist
gaylord
gays
gaysex
gaytard
gaywad
gender bender
genitals
gey
gfy
ghay
ghey
giant cock
gigolo
ginger
gippo
girl on
girl on top
girls gone wild
git
glans
goatcx
goatse
god damn
godamn
godamnit
goddam
god-dam
goddammit
goddamn
goddamned
god-damned
goddamnit
goddamnmuthafucker
godsdamn
gokkun
golden shower
goldenshower
golliwog
gonad
gonads
gonorrehea
goo girl
gooch
goodpoop
gook
gooks
goregasm
gotohell
gringo
grope
group sex
gspot
g-spot
gtfo
guido
guro
h0m0
h0mo
ham flap
hand job
handjob
hard core
hard on
hardcore
hardcoresex
he11
headfuck
hebe
heeb
hell
hemp
hentai
heroin
herp
herpes
herpy
heshe
he-she
hitler
hiv
ho
hoar
hoare
hobag
hoe
hoer
holy shit
hom0
homey
homo
homodumbshit
homoerotic
homoey
honkey
honky
hooch
hookah
hooker
hoor
hootch
hooter
hooters
hore
horniest
horny
hot carl
hot chick
hotpussy
hotsex
how to kill
how to murdep
how to murder
huge fat
hump
humped
humping
hun
hussy
hymen
iap
iberian slap
inbred
incest
injun
intercourse
j3rk0ff
jack off
jackass
jackasses
jackhole
jackoff
jack-off
jaggi
jagoff
jail bait
jailbait
jap
japs
jelly donut
jerk
jerk off
jerk0ff
jerkass
jerked
jerkoff
jerk-off
jigaboo
jiggaboo
jiggerboo
jism
jiz
jizm
jizz
jizzed
jock
juggs
jungle bunny
junglebunny
junkie
junky
kafir
kawk
kike
kikes
kill
kinbaku
kinkster
kinky
kkk
klan
knob
knob end
knobbing
knobead
knobed
knobend
knobhead
knobjocky
knobjokey
kock
kondum
kondums
kooch
kooches
kootch
kraut
kum
kummer
kumming
kums
kunilingus
kunja
kunt
kwif
kyke
l3i+ch
l3itch
labia
lameass
lardass
leather restraint
leather straight jacket
lech
lemon party
leper
lesbian
lesbians
lesbo
lesbos
lez
lezbian
lezbians
lezbo
lezbos
lezza
lezzie
lezzies
lezzy
lmao
lmfao
loin
loins
lolita
looney
lovemaking
lube
lust
lusting
lusty
m0f0
m0fo
m45terbate
ma5terb8
ma5terbate
mafugly
make me come
male squirting
mams
masochist
massa
masterb8
masterbat
masterbat3
masterbate
master-bate
masterbating
masterbation
masterbations
masturbate
masturbating
masturbation
maxi
mcfagget
menage a trois
menses
menstruate
menstruation
meth
m-fucking
mick
middle finger
midget
milf
minge
minger
missionary position
mof0
mofo
mo-fo
molest
mong
moo moo foo foo
moolie
moron
mothafuck
mothafucka
mothafuckas
mothafuckaz
mothafucked
mothafucker
mothafuckers
mothafuckin
mothafucking
mothafuckings
mothafucks
mother fucker
motherfuck
motherfucka
motherfucked
motherfucker
motherfuckers
motherfuckin
motherfucking
motherfuckings
motherfuckka
motherfucks
mound of venus
mr hands
mtherfucker
mthrfucker
mthrfucking
muff
muff diver
muff puff
muffdiver
muffdiving
munging
munter
murder
mutha
muthafecker
muthafuckaz
muthafuckker
muther
mutherfucker
mutherfucking
muthrfucking
n1gga
n1gger
nad
nads
naked
nambla
napalm
nappy
nawashi
nazi
nazism
need the dick
negro
neonazi
nig nog
nigaboo
nigg3r
nigg4h
nigga
niggah
niggas
niggaz
nigger
niggers
niggle
niglet
nig-nog
nimphomania
nimrod
ninny
nipple
nipples
nob
nob jokey
nobhead
nobjocky
nobjokey
nonce
nooky
nsfw images
nude
nudity
numbnuts
nut butter
nut sack
nutsack
nutter
nympho
nymphomania
octopussy
old bag
omg
omorashi
one cup two girls
one guy one jar
opiate
opium
oral
orally
organ
orgasim
orgasims
orgasm
orgasmic
orgasms
orgies
orgy
ovary
ovum
ovums
p.u.s.s.y.
p0rn
paddy
paedophile
paki
panooch
pansy
pantie
panties
panty
pastie
pasty
pawn
pcp
pecker
peckerhead
pedo
pedobear
pedophile
pedophilia
pedophiliac
pee
peepee
pegging
penetrate
penetration
penial
penile
penis
penisbanger
penisfucker
penispuffer
perversion
peyote
phalli
phallic
phone sex
phonesex
phuck
phuk
phuked
phuking
phukked
phukking
phuks
phuq
piece of shit
pigfucker
pikey
pillowbiter
pimp
pimpis
pinko
piss
piss off
piss pig
pissed
pissed off
pisser
pissers
pisses
pissflaps
pissin
pissing
pissoff
piss-off
pisspig
playboy
pleasure chest
pms
polack
pole smoker
polesmoker
pollock
ponyplay
poof
poon
poonani
poonany
poontang
poop
poop chute
poopchute
poopuncher
porch monkey
porchmonkey
porn
porno
pornography
pornos
pot
potty
prick
pricks
prickteaser
prig
prince albert piercing
prod
pron
prostitute
prude
psycho
pthc
pube
pubes
pubic
pubis
punani
punanny
punany
punkass
punky
punta
puss
pusse
pussi
pussies
pussy
pussy fart
pussy palace
pussylicking
pussypounder
pussys
pust
puto
queaf
queef
queer
queerbait
queerhole
queero
queers
quicky
quim
racy
raghead
raging boner
rape
raped
raper
rapey
raping
rapist
raunch
rectal
rectum
rectus
reefer
reetard
reich
renob
retard
retarded
reverse cowgirl
revue
rimjaw
rimjob
rimming
ritard
rosy palm
rosy palm and her 5 sisters
rtard
r-tard
rubbish
rum
rump
rumprammer
ruski
rusty trombone
s hit
s&m
s.h.i.t.
s.o.b.
s_h_i_t
s0b
sadism
sadist
sambo
sand nigger
sandbar
sandler
sandnigger
sanger
santorum
sausage queen
scag
scantily
scat
schizo
schlong
scissoring
screw
screwed
screwing
scroat
scrog
scrot
scrote
scrotum
scrud
scum
seaman
seamen
seduce
seks
semen
sex
sexo
sexual
sexy
sh!+
sh!t
sh1t
s-h-1-t
shag
shagger
shaggin
shagging
shamedame
shaved beaver
shaved pussy
shemale
shi+
shibari
shirt lifter
shit
s-h-i-t
shit ass
shit fucker
shitass
shitbag
shitbagger
shitblimp
shitbrains
shitbreath
shitcanned
shitcunt
shitdick
shite
shiteater
shited
shitey
shitface
shitfaced
shitfuck
shitfull
shithead
shitheads
shithole
shithouse
shiting
shitings
shits
shitspitter
shitstain
shitt
shitted
shitter
shitters
shittier
shittiest
shitting
shittings
shitty
shiz
shiznit
shota
shrimping
sissy
skag
skank
skeet
skullfuck
slag
slanteye
slave
sleaze
sleazy
slope
slut
slut bucket
slutbag
slutdumper
slutkiss
sluts
smartass
smartasses
smeg
smegma
smut
smutty
snatch
sniper
snowballing
snuff
s-o-b
sod off
sodom
sodomize
sodomy
son of a bitch
son of a motherless goat
son of a whore
son-of-a-bitch
souse
soused
spac
spade
sperm
spic
spick
spik
spiks
splooge
splooge moose
spooge
spook
spread legs
spunk
steamy
stfu
stiffy
stoned
strap on
strapon
strappado
strip
strip club
stroke
stupid
style doggy
suck
suckass
sucked
sucking
sucks
suicide girls
sultry women
sumofabiatch
swastika
swinger
t1t
t1tt1e5
t1tties
taff
taig
tainted love
taking the piss
tampon
tard
tart
taste my
tawdry
tea bagging
teabagging
teat
teets
teez
terd
teste
testee
testes
testical
testicle
testis
threesome
throating
thrust
thug
thundercunt
tied up
tight white
tinkle
tit
tit wank
titfuck
titi
tities
tits
titt
tittie5
tittiefucker
titties
titty
tittyfuck
tittyfucker
tittywank
titwank
toke
tongue in a
toots
topless
tosser
towelhead
tramp
tranny
transsexual
trashy
tribadism
trumped
tub girl
tubgirl
turd
tush
tushy
tw4t
twat
twathead
twatlips
twats
twatty
twatwaffle
twink
twinkie
two fingers
two fingers with tongue
two girls one cup
twunt
twunter
ugly
unclefucker
undies
undressing
unwed
upskirt
urethra play
urinal
urine
urophilia
uterus
uzi
v14gra
v1gra
vag
vagina
vajayjay
va-j-j
valium
venus mound
veqtable
viagra
vibrator
violet wand
virgin
vixen
vjayjay
vodka
vomit
vorarephilia
voyeur
vulgar
vulva
w00se
wad
wang
wank
wanker
wankjob
wanky
wazoo
wedgie
weed
weenie
weewee
weiner
weirdo
wench
wet dream
wetback
wh0re
wh0reface
white power
whitey
whiz
whoar
whoralicious
whore
whorealicious
whorebag
whored
whoreface
whorehopper
whorehouse
whores
whoring
wigger
willies
willy
window licker
wiseass
wiseasses
wog
womb
woody
wop
wrapping men
wrinkled starfish
wtf
xrated
x-rated
xx
xxx
yaoi
yeasty
yellow showers
yid
yiffy
yobbo
zoophile
zoophilia
zubb
""".trimIndent() | 0 | Kotlin | 0 | 0 | 67dbfd98b8df336187fb4dd26fb45d79a13690e3 | 14,753 | AndroidWordFilter | MIT License |
beyondcalendar/src/main/java/app/climbeyond/beyondcalendar/view/MonthLayout.kt | climbeyond | 552,913,583 | false | null | package app.climbeyond.beyondcalendar.view
import android.annotation.SuppressLint
import android.content.Context
import android.view.ViewGroup
import android.widget.LinearLayout
import app.climbeyond.beyondcalendar.BeyondCalendarSettings
import app.climbeyond.beyondcalendar.accent.Accent
import java.time.ZonedDateTime
import java.util.*
@Suppress("unused")
@SuppressLint("ViewConstructor")
class MonthLayout(context: Context, settings: BeyondCalendarSettings,
private var month: ZonedDateTime,
selectedDateInit: ZonedDateTime) : LinearLayout(context) {
internal var onDateSelected: ((date: ZonedDateTime) -> Unit)? = null
private val monthLegendCellGroup = MonthLegendCellGroup(context, settings)
private val monthBodyCellGroup = MonthBodyCellGroup(context, settings, month, selectedDateInit).apply {
onDateSelected = { date -> [email protected]?.invoke(date) }
}
init {
orientation = VERTICAL
addView(monthLegendCellGroup, LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT))
addView(monthBodyCellGroup, LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT))
}
fun getSelectedDate(): Date? {
return monthBodyCellGroup.selectedDayView?.date?.toInstant()?.let { Date.from(it) }
}
fun setSelectedDate(date: ZonedDateTime) {
monthBodyCellGroup.setSelectedDay(date)
}
fun setAccents(date: ZonedDateTime, accents: Collection<Accent>) {
monthBodyCellGroup.apply {
getDayView(date)?.setAccents(accents)
}.invalidateDayViews()
}
fun setAccents(map: Map<ZonedDateTime, Collection<Accent>>) {
map.forEach {
val (date, accents) = it
monthBodyCellGroup.getDayView(date)?.setAccents(accents)
}
monthBodyCellGroup.invalidateDayViews()
}
override fun toString(): String = "MonthView($month)"
}
| 0 | Kotlin | 0 | 1 | d4d1c2d2e416c58e7bb02b9af0af664af5439db1 | 2,005 | beyondcalendar | Apache License 2.0 |
src/main/kotlin/de/eternalwings/bukkit/konversation/prompts/SimplePlayerPrompt.kt | kumpelblase2 | 413,042,405 | false | null | package de.eternalwings.bukkit.konversation.prompts
import de.eternalwings.bukkit.konversation.ChainablePrompt
import de.eternalwings.bukkit.konversation.InnerBuilderCallback
import de.eternalwings.bukkit.konversation.MessageResolver
import de.eternalwings.bukkit.konversation.PromptBuilder
import org.bukkit.conversations.ConversationContext
import org.bukkit.conversations.PlayerNamePrompt
import org.bukkit.conversations.Prompt
import org.bukkit.entity.Player
import org.bukkit.plugin.Plugin
class SimplePlayerPrompt(
private val messageResolver: MessageResolver,
plugin: Plugin,
private val callback: InnerBuilderCallback<Player>
) :
PlayerNamePrompt(plugin), ChainablePrompt {
private var next: ChainablePrompt? = null
override fun getPromptText(context: ConversationContext): String {
return messageResolver.apply(context)
}
override fun acceptValidatedInput(context: ConversationContext, input: Player): Prompt? {
val builder = PromptBuilder(this)
builder.callback(input, context)
return builder.injectChain(next)
}
override fun addNextPrompt(next: ChainablePrompt) {
this.next = next
}
}
| 0 | Kotlin | 0 | 2 | b2b0ff9cc7616cdc7e93fc7a462e09c4d4a2658d | 1,185 | konversation | MIT License |
foundation/ui/imageloader/coil/src/main/kotlin/ru/pixnews/foundation/ui/imageloader/coil/DelegatingImageLoader.kt | illarionov | 305,333,284 | false | null | /*
* Copyright (c) 2023, the Pixnews project authors and contributors. Please see the AUTHORS file for details.
* Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package ru.pixnews.foundation.ui.imageloader.coil
import coil.ComponentRegistry
import coil.ImageLoader.Builder
import coil.disk.DiskCache
import coil.memory.MemoryCache
import coil.request.DefaultRequestOptions
import coil.request.Disposable
import coil.request.ImageRequest
import coil.request.ImageResult
internal class DelegatingImageLoader(
private val rootImageLoader: coil.ImageLoader,
) : PrefetchingImageLoader, ImageLoader {
override val components: ComponentRegistry get() = rootImageLoader.components
override val defaults: DefaultRequestOptions get() = rootImageLoader.defaults
override val diskCache: DiskCache? get() = rootImageLoader.diskCache
override val memoryCache: MemoryCache? get() = rootImageLoader.memoryCache
override fun enqueue(request: ImageRequest): Disposable = rootImageLoader.enqueue(request)
override suspend fun execute(request: ImageRequest): ImageResult = rootImageLoader.execute(request)
override fun newBuilder(): Builder {
error("Creating new image loaders is supposed to be done via DI")
}
override fun shutdown() = rootImageLoader.shutdown()
}
| 4 | Kotlin | 0 | 2 | cab07bacfafb6d486cea4c5bf03cacb3dee5647f | 1,362 | Pixnews | Apache License 2.0 |
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/fragments/links/LinkActionListener.kt | feelfreelinux | 97,154,881 | false | null | package io.github.feelfreelinux.wykopmobilny.ui.fragments.links
import io.github.feelfreelinux.wykopmobilny.models.dataclass.Link
interface LinkActionListener {
fun dig(link: Link)
fun removeVote(link: Link)
} | 47 | Kotlin | 51 | 166 | ec6365b9570818a7ee00c5b512f01cedead30867 | 219 | WykopMobilny | MIT License |
inspector/src/main/kotlin/kotlinx/html/HtmlBody.kt | jakeouellette | 35,901,832 | false | null | package kotlinx.html
val <T> empty_contents: T.() -> Unit = { }
public abstract class HtmlBodyTag(containingTag: HtmlTag?, name: String, renderStyle: RenderStyle = RenderStyle.expanded, contentStyle: ContentStyle = ContentStyle.block) : HtmlTag(containingTag, name, renderStyle, contentStyle) {
public var id: String by Attributes.id
public var style: String by Attributes.style
public fun addClass(c: String) {
val old = tryGet("class")
setClass(if (old.isNotEmpty()) "$old $c" else c)
}
public fun setClass(c: String) {
attribute("class", c)
}
}
public fun <T : HtmlBodyTag> HtmlBodyTag.contentTag(tag: T, styleClass: String? = null, contents: T.() -> Unit = empty_contents) {
if (styleClass != null) tag.addClass(styleClass)
build(tag, contents)
}
public fun HtmlBodyTag.a(c: String? = null, contents: A.() -> Unit = empty_contents): Unit = contentTag(A(this), c, contents)
public open class A(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "a", contentStyle = ContentStyle.propagate) {
public var href: Link by Attributes.href
public var rel: String by Attributes.rel
public var target: String by Attributes.target
}
public fun HtmlBodyTag.button(c: String? = null, contents: BUTTON.() -> Unit = empty_contents): Unit = contentTag(BUTTON(this), c, contents)
public open class BUTTON(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "button", RenderStyle.expanded, ContentStyle.propagate) {
public var name: String by Attributes.name
public var value: String by Attributes.value
public var buttonType: String by Attributes.buttonType
public var href: Link by Attributes.href
}
public fun HTML.body(c: String? = null, contents: BODY.() -> Unit) {
val tag = BODY(this)
if (c != null) tag.addClass(c)
build(tag, contents)
}
public class BODY(containingTag: HTML) : HtmlBodyTag(containingTag, "body")
public fun HtmlBodyTag.hr(c: String? = null): Unit = contentTag(HR(this), c)
public fun HtmlBodyTag.br(c: String? = null): Unit = contentTag(BR(this), c)
public fun HtmlBodyTag.wbr(c: String? = null): Unit = contentTag(WBR(this), c)
public fun HtmlBodyTag.div(c: String? = null, contents: DIV.() -> Unit = empty_contents): Unit = contentTag(DIV(this), c, contents)
public fun HtmlBodyTag.b(c: String? = null, contents: B.() -> Unit = empty_contents): Unit = contentTag(B(this), c, contents)
public fun HtmlBodyTag.i(c: String? = null, contents: I.() -> Unit = empty_contents): Unit = contentTag(I(this), c, contents)
public fun HtmlBodyTag.p(c: String? = null, contents: P.() -> Unit = empty_contents): Unit = contentTag(P(this), c, contents)
public fun HtmlBodyTag.pre(c: String? = null, contents: PRE.() -> Unit = empty_contents): Unit = contentTag(PRE(this), c, contents)
public fun HtmlBodyTag.span(c: String? = null, contents: SPAN.() -> Unit = empty_contents): Unit = contentTag(SPAN(this), c, contents)
public fun HtmlBodyTag.sub(c: String? = null, contents: SUB.() -> Unit = empty_contents): Unit = contentTag(SUB(this), c, contents)
public fun HtmlBodyTag.sup(c: String? = null, contents: SUP.() -> Unit = empty_contents): Unit = contentTag(SUP(this), c, contents)
public fun HtmlBodyTag.ins(c: String? = null, contents: INS.() -> Unit = empty_contents): Unit = contentTag(INS(this), c, contents)
public fun HtmlBodyTag.del(c: String? = null, contents: DEL.() -> Unit = empty_contents): Unit = contentTag(DEL(this), c, contents)
public fun HtmlBodyTag.s(c: String? = null, contents: S.() -> Unit = empty_contents): Unit = contentTag(S(this), c, contents)
public fun HtmlBodyTag.u(c: String? = null, contents: U.() -> Unit = empty_contents): Unit = contentTag(U(this), c, contents)
public fun HtmlBodyTag.abbr(c: String? = null, contents: ABBR.() -> Unit = empty_contents): Unit = contentTag(ABBR(this), c, contents)
public fun HtmlBodyTag.small(c: String? = null, contents: SMALL.() -> Unit = empty_contents): Unit = contentTag(SMALL(this), c, contents)
public fun HtmlBodyTag.mark(c: String? = null, contents: MARK.() -> Unit = empty_contents): Unit = contentTag(MARK(this), c, contents)
public fun HtmlBodyTag.address(c: String? = null, contents: ADDRESS.() -> Unit = empty_contents): Unit = contentTag(ADDRESS(this), c, contents)
public fun HtmlBodyTag.time(c: String? = null, contents: TIME.() -> Unit = empty_contents): Unit = contentTag(TIME(this), c, contents)
public fun HtmlBodyTag.cite(c: String? = null, contents: CITE.() -> Unit = empty_contents): Unit = contentTag(CITE(this), c, contents)
public fun HtmlBodyTag.q(c: String? = null, contents: Q.() -> Unit = empty_contents): Unit = contentTag(Q(this), c, contents)
public fun HtmlBodyTag.blockquote(c: String? = null, contents: BLOCKQUOTE.() -> Unit = empty_contents): Unit = contentTag(BLOCKQUOTE(this), c, contents)
public open class HR(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "hr", RenderStyle.empty)
public open class BR(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "br", RenderStyle.empty)
public open class WBR(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "wbr", RenderStyle.empty)
public open class DIV(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "div")
public open class B(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "b", contentStyle = ContentStyle.propagate)
public open class I(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "i", contentStyle = ContentStyle.propagate)
public open class P(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "p")
public open class PRE(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "pre")
public open class SPAN(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "span", contentStyle = ContentStyle.propagate)
public open class SUB(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "sub", contentStyle = ContentStyle.propagate)
public open class SUP(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "sup", contentStyle = ContentStyle.propagate)
public open class INS(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "ins", contentStyle = ContentStyle.propagate)
public open class DEL(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "del", contentStyle = ContentStyle.propagate)
public open class S(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "s", contentStyle = ContentStyle.propagate)
public open class U(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "u", contentStyle = ContentStyle.propagate)
public open class ABBR(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "abbr", contentStyle = ContentStyle.propagate)
public open class SMALL(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "small", contentStyle = ContentStyle.propagate)
public open class MARK(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "mark", contentStyle = ContentStyle.propagate)
public open class TIME(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "time")
public open class ADDRESS(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "address")
public open class CITE(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "cite", contentStyle = ContentStyle.propagate)
public open class Q(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "q", contentStyle = ContentStyle.propagate)
public open class BLOCKQUOTE(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "blockquote") {
public var cite: Link by Attributes.cite
}
public fun HtmlBodyTag.em(c: String? = null, contents: EM.() -> Unit = empty_contents): Unit = contentTag(EM(this), c, contents)
public fun HtmlBodyTag.strong(c: String? = null, contents: STRONG.() -> Unit = empty_contents): Unit = contentTag(STRONG(this), c, contents)
public fun HtmlBodyTag.code(c: String? = null, contents: CODE.() -> Unit = empty_contents): Unit = contentTag(CODE(this), c, contents)
public fun HtmlBodyTag.kbd(c: String? = null, contents: KBD.() -> Unit = empty_contents): Unit = contentTag(KBD(this), c, contents)
public fun HtmlBodyTag.dfn(c: String? = null, contents: DFN.() -> Unit = empty_contents): Unit = contentTag(DFN(this), c, contents)
public fun HtmlBodyTag.samp(c: String? = null, contents: SAMP.() -> Unit = empty_contents): Unit = contentTag(SAMP(this), c, contents)
public fun HtmlBodyTag.variable(c: String? = null, contents: VARIABLE.() -> Unit = empty_contents): Unit = contentTag(VARIABLE(this), c, contents)
public open class EM(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "em", contentStyle = ContentStyle.propagate)
public open class STRONG(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "strong", contentStyle = ContentStyle.propagate)
public open class CODE(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "code")
public open class KBD(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "kbd", contentStyle = ContentStyle.propagate)
public open class DFN(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "dfn", contentStyle = ContentStyle.propagate)
public open class SAMP(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "samp", contentStyle = ContentStyle.propagate)
public open class VARIABLE(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "var", contentStyle = ContentStyle.propagate)
public fun HtmlBodyTag.progress(c: String? = null, contents: PROGRESS.() -> Unit = empty_contents): Unit = contentTag(PROGRESS(this), c, contents)
public fun HtmlBodyTag.meter(c: String? = null, contents: METER.() -> Unit = empty_contents): Unit = contentTag(METER(this), c, contents)
public open class PROGRESS(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "progress", contentStyle = ContentStyle.propagate)
public open class METER(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "meter", contentStyle = ContentStyle.propagate)
public fun HtmlBodyTag.dl(c: String? = null, contents: DL.() -> Unit = empty_contents): Unit = contentTag(DL(this), c, contents)
public fun DL.dt(c: String? = null, contents: DT.() -> Unit = empty_contents): Unit = contentTag(DT(this), c, contents)
public fun DL.dd(c: String? = null, contents: DD.() -> Unit = empty_contents): Unit = contentTag(DD(this), c, contents)
public open class DL(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "dl")
public open class DD(containingTag: DL) : HtmlBodyTag(containingTag, "dd", contentStyle = ContentStyle.propagate)
public open class DT(containingTag: DL) : HtmlBodyTag(containingTag, "dt", contentStyle = ContentStyle.propagate)
public fun HtmlBodyTag.ul(c: String? = null, contents: UL.() -> Unit = empty_contents): Unit = contentTag(UL(this), c, contents)
public fun HtmlBodyTag.ol(c: String? = null, contents: OL.() -> Unit = empty_contents): Unit = contentTag(OL(this), c, contents)
public fun ListTag.li(c: String? = null, contents: LI.() -> Unit = empty_contents): Unit = contentTag(LI(this), c, contents)
public abstract class ListTag(containingTag: HtmlBodyTag, name: String) : HtmlBodyTag(containingTag, name)
public open class OL(containingTag: HtmlBodyTag) : ListTag(containingTag, "ol")
public open class UL(containingTag: HtmlBodyTag) : ListTag(containingTag, "ul")
public open class LI(containingTag: ListTag) : HtmlBodyTag(containingTag, "li")
public fun HtmlBodyTag.h1(c: String? = null, contents: H1.() -> Unit = empty_contents): Unit = contentTag(H1(this), c, contents)
public fun HtmlBodyTag.h2(c: String? = null, contents: H2.() -> Unit = empty_contents): Unit = contentTag(H2(this), c, contents)
public fun HtmlBodyTag.h3(c: String? = null, contents: H3.() -> Unit = empty_contents): Unit = contentTag(H3(this), c, contents)
public fun HtmlBodyTag.h4(c: String? = null, contents: H4.() -> Unit = empty_contents): Unit = contentTag(H4(this), c, contents)
public fun HtmlBodyTag.h5(c: String? = null, contents: H5.() -> Unit = empty_contents): Unit = contentTag(H5(this), c, contents)
public fun HtmlBodyTag.h6(c: String? = null, contents: H6.() -> Unit = empty_contents): Unit = contentTag(H6(this), c, contents)
public open class H1(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "h1")
public open class H2(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "h2")
public open class H3(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "h3")
public open class H4(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "h4")
public open class H5(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "h5")
public open class H6(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "h6")
public fun HtmlBodyTag.img(c: String? = null, contents: IMG.() -> Unit = empty_contents): Unit = contentTag(IMG(this), c, contents)
public open class IMG(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "img", RenderStyle.empty, ContentStyle.text) {
public var width: Int by Attributes.width
public var height: Int by Attributes.height
public var src: Link by Attributes.src
public var alt: String by Attributes.alt
}
public fun HtmlBodyTag.table(c: String? = null, contents: TABLE.() -> Unit = empty_contents): Unit = contentTag(TABLE(this), c, contents)
public fun TABLE.caption(c: String? = null, contents: CAPTION.() -> Unit = empty_contents): Unit = contentTag(CAPTION(this), c, contents)
public fun TABLE.tbody(c: String? = null, contents: TBODY.() -> Unit = empty_contents): Unit = contentTag(TBODY(this), c, contents)
public fun TABLE.thead(c: String? = null, contents: THEAD.() -> Unit = empty_contents): Unit = contentTag(THEAD(this), c, contents)
public fun TABLE.colgroup(c: String? = null, contents: COLGROUP.() -> Unit = empty_contents): Unit = contentTag(COLGROUP(this), c, contents)
public fun COLGROUP.col(c: String? = null, contents: COL.() -> Unit = empty_contents): Unit = contentTag(COL(this), c, contents)
public fun TABLE.tfoot(c: String? = null, contents: TFOOT.() -> Unit = empty_contents): Unit = contentTag(TFOOT(this), c, contents)
public fun TableTag.tr(c: String? = null, contents: TR.() -> Unit = empty_contents): Unit = contentTag(TR(this), c, contents)
public fun TR.th(c: String? = null, contents: TH.() -> Unit = empty_contents): Unit = contentTag(TH(this), c, contents)
public fun TR.td(c: String? = null, contents: TD.() -> Unit = empty_contents): Unit = contentTag(TD(this), c, contents)
public abstract class TableTag(containingTag: HtmlBodyTag, name: String) : HtmlBodyTag(containingTag, name)
public open class TABLE(containingTag: HtmlBodyTag) : TableTag(containingTag, "table")
public open class CAPTION(containingTag: TABLE) : HtmlBodyTag(containingTag, "caption")
public open class COLGROUP(containingTag: TABLE) : HtmlBodyTag(containingTag, "colgroup")
public open class COL(containingTag: COLGROUP) : HtmlBodyTag(containingTag, "col")
public open class THEAD(containingTag: TABLE) : TableTag(containingTag, "thead")
public open class TFOOT(containingTag: TABLE) : TableTag(containingTag, "tfoot")
public open class TBODY(containingTag: TABLE) : TableTag(containingTag, "tbody")
public open class TR(containingTag: TableTag) : HtmlBodyTag(containingTag, "tr")
public open class TH(containingTag: TR) : HtmlBodyTag(containingTag, "th")
public open class TD(containingTag: TR) : HtmlBodyTag(containingTag, "td")
public fun HtmlBodyTag.form(c: String? = null, contents: FORM.() -> Unit = empty_contents): Unit = contentTag(FORM(this), c, contents)
public open class FORM(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "form") {
public var action: Link by Attributes.action
public var enctype: String by Attributes.enctype
public var method: String by Attributes.method
}
public fun HtmlBodyTag.select(c: String? = null, contents: SELECT.() -> Unit = empty_contents): Unit = contentTag(SELECT(this), c, contents)
public fun SelectTag.option(c: String? = null, contents: OPTION.() -> Unit = empty_contents): Unit = contentTag(OPTION(this), c, contents)
public fun SELECT.optgroup(c: String? = null, contents: OPTGROUP.() -> Unit = empty_contents): Unit = contentTag(OPTGROUP(this), c, contents)
public abstract class SelectTag(containingTag: HtmlBodyTag, name: String) : HtmlBodyTag(containingTag, name)
public open class SELECT(containingTag: HtmlBodyTag) : SelectTag(containingTag, "select") {
public var name: String by Attributes.name
public var size: Int by Attributes.size
public var multiple: Boolean by Attributes.multiple
public var disabled: Boolean by Attributes.disabled
public var required: Boolean by Attributes.required
}
public open class OPTION(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "option") {
public var value: String by Attributes.value
public var label: String by Attributes.label
public var disabled: Boolean by Attributes.disabled
public var selected: Boolean by Attributes.selected
}
public open class OPTGROUP(containingTag: HtmlBodyTag) : SelectTag(containingTag, "optgroup")
public fun HtmlBodyTag.input(c: String? = null, contents: INPUT.() -> Unit = empty_contents): Unit = contentTag(INPUT(this), c, contents)
public open class INPUT(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "input", RenderStyle.expanded, ContentStyle.propagate) {
public var alt: String by Attributes.alt
public var autocomplete: Boolean by Attributes.autocomplete
public var autofocus: Boolean by Attributes.autofocus
public var checked: Boolean by Attributes.checked
public var disabled: Boolean by Attributes.disabled
public var height: Int by Attributes.height
public var maxlength: Int by Attributes.maxlength
public var multiple: Boolean by Attributes.multiple
public var inputType: String by Attributes.inputType
public var name: String by Attributes.name
public var pattern: String by Attributes.pattern
public var placeholder: String by Attributes.placeholder
public var readonly: Boolean by Attributes.readonly
public var required: Boolean by Attributes.required
public var size: Int by Attributes.size
public var src: Link by Attributes.src
public var step: Int by Attributes.step
public var value: String by Attributes.value
public var width: Int by Attributes.width
}
public fun HtmlBodyTag.label(c: String? = null, contents: LABEL.() -> Unit = empty_contents): Unit = contentTag(LABEL(this), c, contents)
public open class LABEL(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "label") {
public var forId: String by Attributes.forId
}
public fun HtmlBodyTag.textarea(c: String? = null, contents: TEXTAREA.() -> Unit = empty_contents): Unit = contentTag(TEXTAREA(this), c, contents)
public open class TEXTAREA(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "textarea") {
public var autofocus: Boolean by Attributes.autofocus
public var cols: Int by Attributes.cols
public var disabled: Boolean by Attributes.disabled
public var maxlength: Int by Attributes.maxlength
public var name: String by Attributes.name
public var placeholder: String by Attributes.placeholder
public var readonly: Boolean by Attributes.readonly
public var required: Boolean by Attributes.required
public var rows: Int by Attributes.rows
public var wrap: String by Attributes.wrap
}
public fun HtmlBodyTag.fieldset(c: String? = null, contents: FIELDSET.() -> Unit = empty_contents): Unit = contentTag(FIELDSET(this), c, contents)
public fun FIELDSET.legend(c: String? = null, contents: LEGEND.() -> Unit = empty_contents): Unit = contentTag(LEGEND(this), c, contents)
public open class FIELDSET(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "fieldset")
public open class LEGEND(containingTag: FIELDSET) : HtmlBodyTag(containingTag, "legend")
public fun HtmlBodyTag.figure(c: String? = null, contents: FIGURE.() -> Unit = empty_contents): Unit = contentTag(FIGURE(this), c, contents)
public fun FIGURE.figcaption(c: String? = null, contents: FIGCAPTION.() -> Unit = empty_contents): Unit = contentTag(FIGCAPTION(this), c, contents)
public open class FIGURE(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "figure")
public open class FIGCAPTION(containingTag: FIGURE) : HtmlBodyTag(containingTag, "figcaption")
public fun HtmlBodyTag.canvas(c: String? = null, contents: CANVAS.() -> Unit = empty_contents): Unit = contentTag(CANVAS(this), c, contents)
public open class CANVAS(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "canvas") {
public var width: Int by Attributes.width
public var height: Int by Attributes.height
}
public fun HtmlBodyTag.nav(c: String? = null, contents: NAV.() -> Unit = empty_contents): Unit = contentTag(NAV(this), c, contents)
public fun HtmlBodyTag.article(c: String? = null, contents: ARTICLE.() -> Unit = empty_contents): Unit = contentTag(ARTICLE(this), c, contents)
public fun HtmlBodyTag.aside(c: String? = null, contents: ASIDE.() -> Unit = empty_contents): Unit = contentTag(ASIDE(this), c, contents)
public fun HtmlBodyTag.section(c: String? = null, contents: SECTION.() -> Unit = empty_contents): Unit = contentTag(SECTION(this), c, contents)
public fun HtmlBodyTag.header(c: String? = null, contents: HEADER.() -> Unit = empty_contents): Unit = contentTag(HEADER(this), c, contents)
public fun HtmlBodyTag.footer(c: String? = null, contents: FOOTER.() -> Unit = empty_contents): Unit = contentTag(FOOTER(this), c, contents)
public fun HtmlBodyTag.details(c: String? = null, contents: DETAILS.() -> Unit = empty_contents): Unit = contentTag(DETAILS(this), c, contents)
public fun DETAILS.summary(c: String? = null, contents: SUMMARY.() -> Unit = empty_contents): Unit = contentTag(SUMMARY(this), c, contents)
public open class NAV(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "nav")
public open class ARTICLE(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "article")
public open class ASIDE(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "aside")
public open class SECTION(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "section")
public open class HEADER(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "header")
public open class FOOTER(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "footer")
public open class DETAILS(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "details")
public open class SUMMARY(containingTag: DETAILS) : HtmlBodyTag(containingTag, "summary")
public fun HtmlBodyTag.audio(c: String? = null, contents: AUDIO.() -> Unit = empty_contents): Unit = contentTag(AUDIO(this), c, contents)
public fun HtmlBodyTag.video(c: String? = null, contents: VIDEO.() -> Unit = empty_contents): Unit = contentTag(VIDEO(this), c, contents)
public fun MediaTag.track(c: String? = null, contents: TRACK.() -> Unit = empty_contents): Unit = contentTag(TRACK(this), c, contents)
public fun MediaTag.source(c: String? = null, contents: SOURCE.() -> Unit = empty_contents): Unit = contentTag(SOURCE(this), c, contents)
public abstract class MediaTag(containingTag: HtmlBodyTag, name: String) : HtmlBodyTag(containingTag, name)
public open class AUDIO(containingTag: HtmlBodyTag) : MediaTag(containingTag, "audio")
public open class VIDEO(containingTag: HtmlBodyTag) : MediaTag(containingTag, "video")
public open class TRACK(containingTag: MediaTag) : HtmlBodyTag(containingTag, "track")
public open class SOURCE(containingTag: MediaTag) : HtmlBodyTag(containingTag, "source")
public fun HtmlBodyTag.embed(c: String? = null, contents: EMBED.() -> Unit = empty_contents): Unit = contentTag(EMBED(this), c, contents)
public open class EMBED(containingTag: HtmlBodyTag) : HtmlBodyTag(containingTag, "embed")
| 7 | null | 10 | 218 | 7ee81d50bdee4763ce6298a95ae589032ab4d749 | 23,550 | inspector | MIT License |
app/src/main/java/com/taitascioredev/android/xingtest/data/net/impl/GithubServiceImpl.kt | phanghos | 118,010,709 | false | null | package com.taitascioredev.android.xingtest.data.net.impl
import com.taitascioredev.android.xingtest.data.entity.RepositoryEntity
import com.taitascioredev.android.xingtest.data.net.GithubApi
import com.taitascioredev.android.xingtest.data.net.GithubService
import io.reactivex.Observable
import javax.inject.Inject
/**
* Created by rrtatasciore on 18/01/18.
*/
class GithubServiceImpl @Inject constructor(private val api: GithubApi) : GithubService {
companion object {
private val LIMIT = 10
}
override fun getXingRepos(curPage: Int): Observable<List<RepositoryEntity>> {
return api.getXingRepos(curPage, LIMIT)
}
} | 0 | Kotlin | 0 | 1 | 511de872720e6875e0e089becbbdfcdd369bc0b6 | 655 | xing-test-android | MIT License |
app/src/main/java/com/example/android/weatherapp/models/WeatherXX.kt | Czeach | 253,786,708 | false | null | package com.example.android.weatherapp.models
data class WeatherXX(
val description: String,
val icon: String,
val id: Int,
val main: String
) | 0 | Kotlin | 0 | 0 | a2178d14d774ae523e09e1d818f29df11987ce11 | 160 | WeatherApp-kotlin | Apache License 2.0 |
kotlin-rss-reader/app/src/main/java/com/abubusoft/kripton/example/rssreader/viewmodel/RssViewModel.kt | xcesco | 143,140,913 | false | null | package com.abubusoft.kripton.example.rssreader.viewmodel
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.Transformations
import android.arch.lifecycle.ViewModel
import com.abubusoft.kripton.android.Logger
import com.abubusoft.kripton.example.rssreader.service.model.Article
import com.abubusoft.kripton.example.rssreader.service.model.Channel
import com.abubusoft.kripton.example.rssreader.service.persistence.FilterType
import com.abubusoft.kripton.example.rssreader.service.repository.RssRepository
class RssViewModel : ViewModel() {
val articles: LiveData<List<Article>>
private val repository = RssRepository.instance
val channel: LiveData<Channel>
get() = repository.channel
private val filterLiveData = MutableLiveData<FilterType>()
init {
articles = Transformations.switchMap<FilterType, List<Article>>(filterLiveData) { v -> repository.getArticleList(v) }
}
fun markArticleAsRead(article: Article) {
if (!article.read) {
repository.markArticleAsRead(article)
} else {
Logger.info("Article already read")
}
}
fun downloadArticles() {
repository.downloadArticles()
}
fun updateFilter(filter: FilterType) {
filterLiveData.setValue(filter)
}
} | 0 | Kotlin | 0 | 0 | eebb71eaaacf8c6362eed5356de2f605e0c20399 | 1,354 | kripton-examples-kotlin | Apache License 2.0 |
app/src/main/java/pw/phylame/imabw/Jem.kt | phylame | 88,242,007 | false | null | package pw.phylame.imabw
import android.graphics.Bitmap
import android.support.v7.graphics.Palette
import android.util.Log
import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable
import com.bumptech.glide.load.resource.drawable.GlideDrawable
import jem.Book
import jem.epm.EpmInParam
import jem.epm.EpmManager
import jem.util.flob.Flob
import pw.phylame.support.Titled
import pw.phylame.support.showyColorFor
import rx.Observable
import java.io.File
import java.io.IOException
object Jem {
val TAG: String = Jem.javaClass.simpleName
enum class PaletteMode(val id: Int, override val titleId: Int) : Titled {
Normal(0, R.string.palette_mode_normal),
Light(1, R.string.palette_mode_light),
Dark(2, R.string.palette_mode_dark),
Fallback(3, R.string.palette_mode_fallback)
}
var isCoverPalette = false
var coverPaletteMode = PaletteMode.Normal
init {
EpmManager.loadImplementors()
val prefs = ImabwApp.sharedApp.uiSettings
prefs.registerOnSharedPreferenceChangeListener { prefs, key ->
when (key) {
"coverPalette" -> isCoverPalette = prefs.getBoolean(key, true)
"paletteMode" -> coverPaletteMode = PaletteMode.valueOf(prefs.getString(key, ""))
}
}
isCoverPalette = prefs.getBoolean("coverPalette", true)
coverPaletteMode = PaletteMode.valueOf(prefs.getString("paletteMode", PaletteMode.Normal.name))
}
fun openBook(param: EpmInParam): Observable<Book> = Observable.create<Book> {
try {
it.onNext(EpmManager.readBook(param.file, param.format, param.arguments))
it.onCompleted()
} catch (e: Exception) {
it.onError(e)
}
}
fun cache(flob: Flob, dir: File): File? {
val name = Integer.toHexString(flob.toString().hashCode())
val file = File(dir, name)
if (file.exists()) {
return file
}
try {
file.outputStream().use {
flob.writeTo(it)
}
} catch (e: IOException) {
if (!file.delete()) {
Log.e(TAG, "cannot delete cache file: $file")
}
}
return file
}
fun hintTextOf(title: String): String {
var last: Char? = null
title.reversed().forEach { ch ->
if (ch.isWhitespace() || ch in separator && last != null) {
return last.toString()
}
last = ch
}
return title.firstOrNull()?.toString() ?: ""
}
fun coverSwatch(drawable: GlideDrawable, forcing: Boolean = false, mode: PaletteMode? = null): Palette.Swatch? {
return coverSwatch((drawable as GlideBitmapDrawable).bitmap, forcing, mode)
}
fun coverSwatch(bmp: Bitmap?, forcing: Boolean = false, mode: PaletteMode? = null): Palette.Swatch? {
if (bmp == null || (!isCoverPalette && !forcing)) {
return null
}
return coverSwatch(Palette.from(bmp).generate(), mode)
}
fun coverSwatch(palette: Palette, mode: PaletteMode? = null): Palette.Swatch? = when (mode ?: coverPaletteMode) {
PaletteMode.Normal -> palette.vibrantSwatch ?: palette.mutedSwatch
PaletteMode.Light -> palette.lightVibrantSwatch ?: palette.lightMutedSwatch
PaletteMode.Dark -> palette.darkVibrantSwatch ?: palette.darkMutedSwatch
PaletteMode.Fallback -> palette.vibrantSwatch ?: palette.lightVibrantSwatch ?: palette.darkVibrantSwatch
}
fun coverTextColor(color: Int) = showyColorFor(color, 0.6F, 0.95F)
val separator = charArrayOf('\u3000', '\uff1a', '\u201C', '\u300a', '\uFF0C', ':')
}
| 0 | Kotlin | 0 | 0 | 5df4733cacbe3d402522a80bf338b92f05f31911 | 3,708 | imabw-android | Apache License 2.0 |
crypto/src/main/kotlin/org/kethereum/crypto/Signatures.kt | komputing | 92,780,266 | false | {"Kotlin": 776856} | package org.kethereum.crypto
import org.kethereum.extensions.toHexStringNoPrefix
import org.kethereum.extensions.toHexStringZeroPadded
import org.kethereum.model.SignatureData
import java.math.BigInteger
fun SignatureData.toHex() = r.to64BytePaddedHex() + s.to64BytePaddedHex() + v.toHexStringNoPrefix()
private fun BigInteger.to64BytePaddedHex() = toHexStringZeroPadded(64, false) | 43 | Kotlin | 82 | 333 | 1f42cede2d31cb5d3c488bd74eeb8480ec47c919 | 384 | KEthereum | MIT License |
app/src/test/java/com/wojdor/fourthwallrecruitmenttask/ui/details/DetailsViewModelTest.kt | wojciechkryg | 424,996,078 | false | {"Kotlin": 67275} | package com.wojdor.fourthwallrecruitmenttask.ui.details
import android.net.Uri
import com.wojdor.fourthwallrecruitmenttask.domain.model.Photo
import com.wojdor.fourthwallrecruitmenttask.domain.usecase.GetPhotoUriUseCase
import com.wojdor.fourthwallrecruitmenttask.domain.usecase.base.Result
import com.wojdor.fourthwallrecruitmenttask.relaxedMockk
import com.wojdor.fourthwallrecruitmenttask.ui.details.DetailsEffect.SharePhoto
import com.wojdor.fourthwallrecruitmenttask.ui.details.DetailsEffect.ShowError
import com.wojdor.fourthwallrecruitmenttask.ui.details.DetailsIntent.ShowPhotoDetails
import com.wojdor.fourthwallrecruitmenttask.ui.details.DetailsIntent.ShowSharePhoto
import com.wojdor.fourthwallrecruitmenttask.ui.details.DetailsState.PhotoDetails
import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.InjectMockKs
import io.mockk.impl.annotations.RelaxedMockK
import io.mockk.unmockkAll
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.setMain
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
@ExperimentalCoroutinesApi
class DetailsViewModelTest {
@RelaxedMockK
private lateinit var getPhotoUriUseCase: GetPhotoUriUseCase
@InjectMockKs
private lateinit var detailsViewModel: DetailsViewModel
@BeforeEach
fun setup() {
Dispatchers.setMain(Dispatchers.Unconfined)
MockKAnnotations.init(this)
}
@AfterEach
fun clean() {
unmockkAll()
Dispatchers.resetMain()
}
@Test
fun `Check that initial state in GalleryViewModel is PhotoDetails with empty Photo`() =
runBlockingTest {
val state = detailsViewModel.uiState.value
assertTrue(state is PhotoDetails)
assertEquals(Photo(), (state as PhotoDetails).photo)
}
@Test
fun `Check that ShowPhotoDetails intent publish PhotoDetails state`() = runBlockingTest {
val photo = relaxedMockk<Photo>()
detailsViewModel.sendIntent(ShowPhotoDetails(photo))
val state = detailsViewModel.uiState.value
assertTrue(state is PhotoDetails)
assertEquals(photo, (state as PhotoDetails).photo)
}
@Test
fun `Check that ShowSharePhoto intent send SharePhoto effect on success`() =
runBlockingTest {
val imageUrl = "http://example.com"
val uri = relaxedMockk<Uri>()
every { getPhotoUriUseCase(imageUrl) } returns flow { emit(Result.Success(uri)) }
detailsViewModel.sendIntent(ShowSharePhoto(imageUrl))
val effect = detailsViewModel.uiEffect.first()
assertTrue(effect is SharePhoto)
assertEquals(uri, (effect as SharePhoto).uri)
}
@Test
fun `Check that ShowSharePhoto intent send ShowError effect on error`() =
runBlockingTest {
val imageUrl = "http://example.com"
every { getPhotoUriUseCase(imageUrl) } returns flow {
emit(Result.Error(RuntimeException()))
}
detailsViewModel.sendIntent(ShowSharePhoto(imageUrl))
val effect = detailsViewModel.uiEffect.first()
assertTrue(effect is ShowError)
}
} | 0 | Kotlin | 0 | 0 | 7e2d9d83624f62abd934fd1327251398df9c336a | 3,577 | fourthwall-recruitment-task | Apache License 2.0 |
app/src/main/kotlin/org/cirruslabs/sq/github/api/GithubSecrets.kt | fkorotkov | 124,570,105 | false | null | package org.cirruslabs.sq.github.api
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import org.apache.commons.io.FileUtils
import org.bouncycastle.jce.provider.BouncyCastleProvider
import org.bouncycastle.util.io.pem.PemReader
import org.joda.time.DateTime
import java.io.ByteArrayInputStream
import java.io.File
import java.io.InputStreamReader
import java.nio.charset.Charset
import java.security.KeyFactory
import java.security.Security
import java.security.interfaces.RSAPrivateKey
import java.security.spec.PKCS8EncodedKeySpec
class GithubSecrets(
val clientId: String,
val clientSecret: String,
val algorithm: Algorithm,
val webhookSecret: String
) {
companion object {
fun initialize(): GithubSecrets {
Security.addProvider(BouncyCastleProvider())
val byteArrayInputStream = ByteArrayInputStream(readFileFromEnvVariable("GITHUB_PRIVATE_KEY_FILE"))
val reader = PemReader(InputStreamReader(byteArrayInputStream))
val keySpec = PKCS8EncodedKeySpec(reader.readPemObject().content)
val privateKey = KeyFactory.getInstance("RSA").generatePrivate(keySpec) as RSAPrivateKey
return GithubSecrets(
readFileFromEnvVariable("GITHUB_CLIENT_ID_FILE").toString(Charset.defaultCharset()).trim(),
readFileFromEnvVariable("GITHUB_CLIENT_SECRET_FILE").toString(Charset.defaultCharset()).trim(),
Algorithm.RSA256(null, privateKey),
readFileFromEnvVariable("GITHUB_WEBHOOK_SECRET_FILE").toString(Charset.defaultCharset()).trim()
)
}
private fun readFileFromEnvVariable(envName: String): ByteArray {
val filePath: String = System.getenv()[envName]
?: throw IllegalStateException("$envName env variable should be presented in order to run the app!")
val file = File(filePath)
if (!file.exists()) {
throw IllegalStateException(" File $filePath doesn't exist!!")
}
return FileUtils.readFileToByteArray(file)
}
}
fun signJWT(issuer: String): String {
return JWT.create()
.withIssuedAt(DateTime.now().toDate())
.withExpiresAt(DateTime.now().plusMinutes(10).toDate())
.withIssuer(issuer)
.sign(algorithm)
}
}
| 0 | Kotlin | 0 | 0 | 70437b10dbe4583ff07a7c4d439e4df58fd08924 | 2,195 | submit-queue | MIT License |
src/main/kotlin/org/wfanet/measurement/kingdom/service/system/v1alpha/ComputationParticipantsService.kt | world-federation-of-advertisers | 349,561,061 | 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.measurement.kingdom.service.system.v1alpha
import io.grpc.Status
import org.wfanet.measurement.api.v2alpha.DuchyCertificateKey
import org.wfanet.measurement.common.grpc.failGrpc
import org.wfanet.measurement.common.grpc.grpcRequire
import org.wfanet.measurement.common.grpc.grpcRequireNotNull
import org.wfanet.measurement.common.identity.DuchyIdentity
import org.wfanet.measurement.common.identity.apiIdToExternalId
import org.wfanet.measurement.common.identity.duchyIdentityFromContext
import org.wfanet.measurement.internal.kingdom.ComputationParticipant as InternalComputationParticipant
import org.wfanet.measurement.internal.kingdom.ComputationParticipantKt.honestMajorityShareShuffleDetails
import org.wfanet.measurement.internal.kingdom.ComputationParticipantKt.liquidLegionsV2Details
import org.wfanet.measurement.internal.kingdom.ComputationParticipantsGrpcKt.ComputationParticipantsCoroutineStub as InternalComputationParticipantsCoroutineStub
import org.wfanet.measurement.internal.kingdom.ConfirmComputationParticipantRequest as InternalConfirmComputationParticipantRequest
import org.wfanet.measurement.internal.kingdom.FailComputationParticipantRequest as InternalFailComputationParticipantRequest
import org.wfanet.measurement.internal.kingdom.MeasurementLogEntry
import org.wfanet.measurement.internal.kingdom.SetParticipantRequisitionParamsRequest as InternalSetParticipantRequisitionParamsRequest
import org.wfanet.measurement.internal.kingdom.setParticipantRequisitionParamsRequest as internalSetParticipantRequisitionParamsRequest
import org.wfanet.measurement.system.v1alpha.ComputationParticipant
import org.wfanet.measurement.system.v1alpha.ComputationParticipant.RequisitionParams.ProtocolCase
import org.wfanet.measurement.system.v1alpha.ComputationParticipantKey
import org.wfanet.measurement.system.v1alpha.ComputationParticipantsGrpcKt.ComputationParticipantsCoroutineImplBase
import org.wfanet.measurement.system.v1alpha.ConfirmComputationParticipantRequest
import org.wfanet.measurement.system.v1alpha.FailComputationParticipantRequest
import org.wfanet.measurement.system.v1alpha.SetParticipantRequisitionParamsRequest
class ComputationParticipantsService(
private val internalComputationParticipantsClient: InternalComputationParticipantsCoroutineStub,
private val duchyIdentityProvider: () -> DuchyIdentity = ::duchyIdentityFromContext,
) : ComputationParticipantsCoroutineImplBase() {
override suspend fun setParticipantRequisitionParams(
request: SetParticipantRequisitionParamsRequest
): ComputationParticipant {
return internalComputationParticipantsClient
.setParticipantRequisitionParams(request.toInternalRequest())
.toSystemComputationParticipant()
}
override suspend fun confirmComputationParticipant(
request: ConfirmComputationParticipantRequest
): ComputationParticipant {
return internalComputationParticipantsClient
.confirmComputationParticipant(request.toInternalRequest())
.toSystemComputationParticipant()
}
override suspend fun failComputationParticipant(
request: FailComputationParticipantRequest
): ComputationParticipant {
return internalComputationParticipantsClient
.failComputationParticipant(request.toInternalRequest())
.toSystemComputationParticipant()
}
private fun SetParticipantRequisitionParamsRequest.toInternalRequest():
InternalSetParticipantRequisitionParamsRequest {
val computationParticipantKey = getAndVerifyComputationParticipantKey(name)
val duchyCertificateKey =
grpcRequireNotNull(DuchyCertificateKey.fromName(requisitionParams.duchyCertificate)) {
"Resource name unspecified or invalid."
}
grpcRequire(computationParticipantKey.duchyId == duchyCertificateKey.duchyId) {
"The owners of the computation_participant and certificate don't match."
}
return internalSetParticipantRequisitionParamsRequest {
externalComputationId = apiIdToExternalId(computationParticipantKey.computationId)
externalDuchyId = computationParticipantKey.duchyId
externalDuchyCertificateId = apiIdToExternalId(duchyCertificateKey.certificateId)
@Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") // Proto enum fields are never null.
when (requisitionParams.protocolCase) {
ProtocolCase.LIQUID_LEGIONS_V2 -> {
liquidLegionsV2 = requisitionParams.liquidLegionsV2.toLlV2Details()
}
ProtocolCase.REACH_ONLY_LIQUID_LEGIONS_V2 -> {
reachOnlyLiquidLegionsV2 = requisitionParams.reachOnlyLiquidLegionsV2.toLlV2Details()
}
ProtocolCase.HONEST_MAJORITY_SHARE_SHUFFLE -> {
honestMajorityShareShuffle = requisitionParams.honestMajorityShareShuffle.toHmssDetails()
}
ProtocolCase.PROTOCOL_NOT_SET -> failGrpc { "protocol not set in the requisition_params." }
}
}
}
private fun ComputationParticipant.RequisitionParams.LiquidLegionsV2.toLlV2Details():
InternalComputationParticipant.LiquidLegionsV2Details {
val source = this
return liquidLegionsV2Details {
elGamalPublicKey = source.elGamalPublicKey
elGamalPublicKeySignature = source.elGamalPublicKeySignature
elGamalPublicKeySignatureAlgorithmOid = source.elGamalPublicKeySignatureAlgorithmOid
}
}
private fun ComputationParticipant.RequisitionParams.HonestMajorityShareShuffle.toHmssDetails():
InternalComputationParticipant.HonestMajorityShareShuffleDetails {
val source = this
return honestMajorityShareShuffleDetails {
tinkPublicKey = source.tinkPublicKey
tinkPublicKeySignature = source.tinkPublicKeySignature
tinkPublicKeySignatureAlgorithmOid = source.tinkPublicKeySignatureAlgorithmOid
}
}
private fun ConfirmComputationParticipantRequest.toInternalRequest():
InternalConfirmComputationParticipantRequest {
val computationParticipantKey = getAndVerifyComputationParticipantKey(name)
return InternalConfirmComputationParticipantRequest.newBuilder()
.apply {
externalComputationId = apiIdToExternalId(computationParticipantKey.computationId)
externalDuchyId = computationParticipantKey.duchyId
}
.build()
}
private fun FailComputationParticipantRequest.toInternalRequest():
InternalFailComputationParticipantRequest {
val computationParticipantKey = getAndVerifyComputationParticipantKey(name)
return InternalFailComputationParticipantRequest.newBuilder()
.apply {
externalComputationId = apiIdToExternalId(computationParticipantKey.computationId)
externalDuchyId = computationParticipantKey.duchyId
errorMessage = failure.errorMessage
duchyChildReferenceId = failure.participantChildReferenceId
if (failure.hasStageAttempt()) {
stageAttempt = failure.stageAttempt.toInternalStageAttempt()
errorDetailsBuilder.apply {
type = MeasurementLogEntry.ErrorDetails.Type.PERMANENT
errorTime = failure.errorTime
}
}
}
.build()
}
private fun getAndVerifyComputationParticipantKey(name: String): ComputationParticipantKey {
val computationParticipantKey =
grpcRequireNotNull(ComputationParticipantKey.fromName(name)) {
"Resource name unspecified or invalid."
}
if (computationParticipantKey.duchyId != duchyIdentityProvider().id) {
failGrpc(Status.PERMISSION_DENIED) { "The caller doesn't own this ComputationParticipant." }
}
return computationParticipantKey
}
}
| 87 | null | 11 | 33 | 24a8b93f7c536411e08355b766fd991fdc45aebc | 8,157 | cross-media-measurement | Apache License 2.0 |
aoc_2023/src/test/kotlin/problems/day15/Day15Test.kt | Cavitedev | 725,682,393 | false | {"Kotlin": 98324} | package problems.day15
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import problems.utils.readInput
class Day15Test {
@Test
fun part1() {
val lensHashes = LensHashes(readInput("day15/input"))
Assertions.assertEquals(498538L, lensHashes.sumHashResults())
}
@Test
fun part2() {
val lensHashes = LensHashes(readInput("day15/input"))
Assertions.assertEquals(286278L, lensHashes.focusingPower())
}
} | 0 | Kotlin | 0 | 1 | dc5f07c1e6aef3d685218d58463a01326ddb9ecb | 485 | advent-of-code-2023 | MIT License |
domain/src/test/java/com/khangle/thecocktaildbapp/domain/category/FetchCategoryListUseCaseTest.kt | khangle99 | 359,019,441 | false | null | package com.khangle.thecocktaildbapp.domain.category
import com.google.common.truth.Truth
import com.khangle.thecocktaildbapp.domain.model.Category
import com.khangle.thecocktaildbapp.domain.repository.TheCockTailDBRepository
import com.khangle.thecocktaildbapp.domain.usecase.FetchCategoryListUseCase
import com.khangle.thecocktaildbapp.domain.usecase.FetchCategoryListUseCaseImp
import com.khangle.thecocktaildbapp.domain.util.TestCoroutineRule
import io.mockk.MockKAnnotations
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.impl.annotations.MockK
import kotlinx.coroutines.ExperimentalCoroutinesApi
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
@ExperimentalCoroutinesApi
class FetchCategoryListUseCaseTest {
var objectUnderTest: FetchCategoryListUseCase? = null
@MockK
lateinit var theCockTailDBRepository: TheCockTailDBRepository
@get:Rule
val testCoroutineRule = TestCoroutineRule()
@Before
fun setup() {
MockKAnnotations.init(this)
objectUnderTest = FetchCategoryListUseCaseImp(theCockTailDBRepository)
}
@Test
fun test_fetchCategoryList_returnCategoryList() = testCoroutineRule.runBlockingTest {
//given
val category = Category("")
val categoryList = listOf(category)
coEvery { theCockTailDBRepository.fetchCategoryList() } returns categoryList
//when
val result = objectUnderTest!!.invoke()
//then
coVerify(exactly = 1) { theCockTailDBRepository.fetchCategoryList() }
Truth.assertThat(result).isSameInstanceAs(categoryList)
}
@After
fun teardown() {
objectUnderTest = null
}
} | 0 | Kotlin | 0 | 0 | 47f7ddbd2508fee21fbb593b30ec2d4d086ebf11 | 1,707 | TheCooktailDBApp | MIT License |
libs/commons-database/src/main/kotlin/gov/cdc/ocio/database/dynamo/ReportConverterProvider.kt | CDCgov | 679,761,337 | false | {"Kotlin": 606270, "Python": 14605, "TypeScript": 7647, "Java": 4266, "JavaScript": 2382} | package gov.cdc.ocio.database.dynamo
import software.amazon.awssdk.enhanced.dynamodb.*
import java.util.stream.Collectors
/**
* Attribute converter provider for Report attributes. Note, this is only used by dynamodb.
*
* @property customConverters List<AttributeConverter<*>>
* @property customConvertersMap MutableMap<EnhancedType<*>, AttributeConverter<*>>
* @property defaultProvider AttributeConverterProvider
*/
class ReportConverterProvider : AttributeConverterProvider {
private val customConverters = listOf<AttributeConverter<*>>(
AnyAttributeConverter()
)
private val customConvertersMap =
customConverters.stream().collect(
Collectors.toMap(
{ obj: AttributeConverter<*> -> obj.type() },
{ c: AttributeConverter<*> -> c }
))
private val defaultProvider = DefaultAttributeConverterProvider.create()
/**
* Converter for the enhanced type generic.
*
* @param enhancedType EnhancedType<T>
* @return AttributeConverter<T>
*/
override fun <T> converterFor(enhancedType: EnhancedType<T>): AttributeConverter<T> {
@Suppress("UNCHECKED_CAST")
return customConvertersMap.computeIfAbsent(
enhancedType
) { enhancedTypeEval: EnhancedType<*>? ->
defaultProvider.converterFor(
enhancedTypeEval
)
} as AttributeConverter<T>
}
}
| 4 | Kotlin | 0 | 2 | c8b369ba84918cd90d29a25d581d42c4d2cc346e | 1,448 | data-exchange-processing-status | Apache License 2.0 |
app/src/main/java/ninja/luke/mobi/journey2/app/screen/single2/Single2Route.kt | luke-vietnam | 497,926,585 | false | {"Kotlin": 84219} | package ninja.luke.mobi.journey2.app.screen.single2
import ninja.luke.mobi.journey2.scope.single.J2SingleRoute
interface Single2Route : J2SingleRoute {
fun onSingle2ButtonClick()
} | 0 | Kotlin | 1 | 7 | 5956213e91c72e44406a1c65ccae53ffe890bf8e | 186 | journey2-concept | MIT License |
app/src/main/java/com/merttoptas/composebase/features/component/RickAndMortyEpisodesShimmer.kt | merttoptas | 467,006,657 | false | {"Kotlin": 178792} | package com.berger.baseapp.features.component
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
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.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.valentinilk.shimmer.shimmer
/**
* Created by merttoptas on 19.03.2022
*/
@Composable
fun RickAndMortyEpisodesShimmer(
modifier: Modifier = Modifier
) {
Card(
modifier = modifier
.fillMaxWidth()
.height(100.dp),
shape = RoundedCornerShape(8.dp),
) {
Row(
modifier = Modifier
.shimmer()
.padding(vertical = 10.dp, horizontal = 10.dp),
horizontalArrangement = Arrangement.SpaceBetween
) {
Column(
modifier = Modifier
.padding(start = 10.dp, end = 24.dp)
.fillMaxSize(),
verticalArrangement = Arrangement.SpaceAround
) {
RickAndMortyText(
modifier = Modifier
.fillMaxWidth()
.background(color = Color.LightGray),
text = "",
style = MaterialTheme.typography.body2,
color = MaterialTheme.colors.secondaryVariant
)
RickAndMortyText(
modifier = Modifier
.fillMaxWidth()
.background(color = Color.LightGray),
text = "",
style = MaterialTheme.typography.body2,
color = MaterialTheme.colors.secondaryVariant,
)
RickAndMortyText(
modifier = Modifier
.fillMaxWidth()
.background(color = Color.LightGray),
text = "",
style = MaterialTheme.typography.body2,
color = MaterialTheme.colors.secondaryVariant,
)
}
Box(
contentAlignment = Alignment.CenterEnd,
modifier = Modifier
.fillMaxHeight()
.width(24.dp)
.background(color = Color.LightGray)
) {
Box(
Modifier
.fillMaxHeight()
.width(24.dp)
.background(color = Color.LightGray)
) {
}
}
}
}
}
@Preview(showBackground = true)
@Composable
private fun BodyPreview() {
RickAndMortyEpisodesShimmer(
modifier = Modifier,
)
} | 2 | Kotlin | 25 | 227 | 84ce69aaab69ca351c09712bc7213da0dcbf7639 | 3,004 | BaseApp-Jetpack-Compose-Android-Kotlin | Apache License 2.0 |
app/src/main/java/com/example/demoapp/adapter/NewsAdapter.kt | alinbabu2010 | 338,063,365 | false | null | package com.example.demoapp.adapter
import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.demoapp.R
import com.example.demoapp.models.Articles
import com.example.demoapp.ui.fragments.dashboard.NewsFragment
import com.example.demoapp.utils.Constants.Companion.DATE_FORMAT_DECODE
import com.example.demoapp.utils.Constants.Companion.DATE_FORMAT_ENCODE
import com.example.demoapp.utils.Utils.Companion.openArticle
import com.example.demoapp.utils.Utils.Companion.openDummyActivity
import com.example.demoapp.utils.Utils.Companion.shareNews
import com.example.demoapp.viewmodels.NewsViewModel
import java.text.SimpleDateFormat
import java.util.*
/**
* Adapter class for RecyclerView of [NewsFragment]
*/
class NewsAdapter(
private val news: ArrayList<Articles>?,
private val newsViewModel: NewsViewModel?,
) : RecyclerView.Adapter<NewsAdapter.NewsViewHolder>() {
/**
* A subclass for providing a reference to the views for each data item
*/
class NewsViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val newsImage: ImageView = view.findViewById(R.id.news_image)
val newsTitle: TextView = view.findViewById(R.id.news_title)
val newsDesc: TextView = view.findViewById(R.id.news_desc)
val newsSrc: TextView = view.findViewById(R.id.source_textview)
val newsAuthor: TextView = view.findViewById(R.id.author_textview)
val newsDate: TextView = view.findViewById(R.id.publish_textview)
val newsLiked: CheckBox = view.findViewById(R.id.favourites_button)
val shareNews: ImageButton = view.findViewById(R.id.share_button)
val context: Context = view.context
}
/**
* Create new views (invoked by the layout manager)
*/
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NewsViewHolder {
val adapterLayout = LayoutInflater.from(parent.context).inflate(
R.layout.news_item,
parent,
false
)
return NewsViewHolder(adapterLayout)
}
/**
* Replace the contents of a view from news ArrayList (invoked by the layout manager)
*/
@SuppressLint("NotifyDataSetChanged")
override fun onBindViewHolder(holder: NewsViewHolder, position: Int) {
val item = news?.get(position)
Glide.with(holder.context).load(item?.imageUrl).override(800).into(holder.newsImage)
holder.newsTitle.text = item?.title.toString()
holder.newsDesc.text = item?.description.toString()
val author = "Author: ${item?.author}"
holder.newsAuthor.text = author
val src = "Source: ${item?.source?.name}"
holder.newsSrc.text = src
val date = SimpleDateFormat(
DATE_FORMAT_ENCODE,
Locale.US
).parse(item?.publishedDate.toString())
val formattedDate =
date?.let { SimpleDateFormat(DATE_FORMAT_DECODE, Locale.US).format(it) }
val publishDate = "Published on $formattedDate"
holder.newsDate.text = publishDate
holder.newsLiked.isChecked = newsViewModel?.isFavouriteNews(item) == true
holder.newsLiked.setOnClickListener {
if (holder.newsLiked.isChecked) {
newsViewModel?.addToFavourites(item)
notifyDataSetChanged()
} else {
newsViewModel?.removeFromFavourites(item)
notifyDataSetChanged()
}
}
holder.newsImage.setOnClickListener {
openDummyActivity(holder.context, item)
}
holder.newsTitle.setOnClickListener {
openArticle(holder.context, item)
}
holder.shareNews.setOnClickListener {
shareNews(holder.context, item?.url)
}
}
/**
* Return the size of your data set (invoked by the layout manager)
*/
override fun getItemCount(): Int = news?.size ?: 0
} | 0 | Kotlin | 1 | 1 | 4ec87e6c5d299ef5572bde225e870d1a71f5b571 | 4,240 | BitNews | MIT License |
src/main/kotlin/com/beust/kobalt/internal/JvmCompiler.kt | cypressious | 46,854,600 | true | {"Kotlin": 351608, "Java": 14747, "HTML": 1000, "Shell": 98, "Batchfile": 64} | package com.beust.kobalt.internal
import com.beust.kobalt.KobaltException
import com.beust.kobalt.TaskResult
import com.beust.kobalt.api.KobaltContext
import com.beust.kobalt.api.Project
import com.beust.kobalt.maven.DependencyManager
import com.beust.kobalt.maven.IClasspathDependency
import com.google.inject.Inject
import java.io.File
import java.util.*
/**
* Abstract the compilation process by running an ICompilerAction parameterized by a CompilerActionInfo.
* Also validates the classpath and run all the contributors.
*/
class JvmCompiler @Inject constructor(val dependencyManager: DependencyManager) {
/**
* Take the given CompilerActionInfo and enrich it with all the applicable contributors and
* then pass it to the ICompilerAction.
*/
fun doCompile(project: Project?, context: KobaltContext?, action: ICompilerAction, info: CompilerActionInfo)
: TaskResult {
// Dependencies
val allDependencies = (info.dependencies
+ dependencyManager.calculateDependencies(project, context!!, allDependencies = info.dependencies))
.distinct()
// Plugins that add flags to the compiler
val addedFlags = ArrayList(info.compilerArgs) +
if (project != null) {
context.pluginInfo.compilerFlagContributors.flatMap {
it.flagsFor(project)
}
} else {
emptyList()
}
validateClasspath(allDependencies.map { it.jarFile.get().absolutePath })
return action.compile(info.copy(dependencies = allDependencies, compilerArgs = addedFlags))
}
private fun validateClasspath(cp: List<String>) {
cp.forEach {
if (! File(it).exists()) {
throw KobaltException("Couldn't find $it")
}
}
}
}
data class CompilerActionInfo(val directory: String?, val dependencies: List<IClasspathDependency>,
val sourceFiles: List<String>, val outputDir: File, val compilerArgs: List<String>)
interface ICompilerAction {
fun compile(info: CompilerActionInfo): TaskResult
} | 0 | Kotlin | 0 | 0 | 9e480cc69924dfea523759b93971114b174fa0fb | 2,133 | kobalt | Apache License 2.0 |
app/src/main/java/com/loftechs/sample/call/voice/VoiceCallActivity.kt | LoFTechs | 355,161,561 | false | {"Kotlin": 443779, "Java": 1512} | package com.loftechs.sample.call.voice
import android.os.Bundle
import com.loftechs.sample.R
import com.loftechs.sample.base.BaseActivity
import com.loftechs.sample.call.list.CallState
import com.loftechs.sample.common.IntentKey
class VoiceCallActivity : BaseActivity() {
private lateinit var fragment: VoiceCallFragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (savedInstanceState == null) {
fragment = VoiceCallFragment.newInstance()
val receiverID = intent.getStringExtra(IntentKey.EXTRA_RECEIVER_ID)
val callUserID = intent.getStringExtra(IntentKey.EXTRA_CALL_USER_ID)
val callState = intent.getIntExtra(IntentKey.EXTRA_CALL_STATE_TYPE, CallState.NONE.ordinal)
fragment.arguments = Bundle().apply {
putString(IntentKey.EXTRA_RECEIVER_ID, receiverID)
putString(IntentKey.EXTRA_CALL_USER_ID, callUserID)
putInt(IntentKey.EXTRA_CALL_STATE_TYPE, callState)
}
supportFragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commitNow()
}
}
} | 0 | Kotlin | 1 | 1 | 1b19f8c779e2e051b326e3c491a262c76d5df731 | 1,264 | LTSample-Android-Kotlin | MIT License |
Android/app/src/main/java/ntu/platform/cookery/ui/fragment/chat/ChatFragment.kt | chiaz91 | 393,305,839 | false | null | package ntu.platform.cookery.ui.fragment.chat
import android.os.Bundle
import android.util.Log
import android.view.*
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import ntu.platform.cookery.base.BindingFragment
import ntu.platform.cookery.databinding.FragmentChatBinding
import ntu.platform.cookery.util.setSubTitle
import ntu.platform.cookery.util.setToolBar
private const val TAG = "Cy.chat"
class ChatFragment: BindingFragment<FragmentChatBinding>() {
override val bindingInflater: (LayoutInflater) -> FragmentChatBinding
get() = FragmentChatBinding::inflate
private lateinit var _viewModel: ChatViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val args by navArgs<ChatFragmentArgs>()
Log.d(TAG, "arg.chatid=${args.chatId}")
val vmFactory = ChatViewModelFactory(args.chatId)
_viewModel = ViewModelProvider(this, vmFactory).get(ChatViewModel::class.java)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initBinding()
observeViewModel()
setHasOptionsMenu(true)
}
private fun initBinding() {
with(binding){
setToolBar(toolbarLayout.toolbar)
lifecycleOwner = viewLifecycleOwner
viewModel = _viewModel
rvMessages.adapter = _viewModel.messageAdapter
(rvMessages.layoutManager as LinearLayoutManager).stackFromEnd = true
}
}
private fun observeViewModel(){
with(_viewModel){
chatMembers.observe(viewLifecycleOwner, {
_viewModel.messageAdapter.updateMembers(it)
val chatName = it.joinToString(" and "){ user -> user.name!!}
_viewModel.chat.value?.title = chatName
setSubTitle(chatName)
})
}
}
override fun onStart() {
super.onStart()
_viewModel.messageAdapter.startListening()
}
override fun onStop() {
_viewModel.messageAdapter.stopListening()
super.onStop()
}
} | 0 | Kotlin | 0 | 0 | 51dd7bc043c58e32b7798816e4d71e78b216d654 | 2,242 | elite-chef | MIT License |
src/rider/main/kotlin/com/github/rafaelldi/diagnosticsclientplugin/services/counters/PersistentCounterSessionController.kt | rafaelldi | 487,741,199 | false | null | package com.github.rafaelldi.diagnosticsclientplugin.services.counters
import com.github.rafaelldi.diagnosticsclientplugin.dialogs.CounterFileFormat
import com.github.rafaelldi.diagnosticsclientplugin.dialogs.CounterModel
import com.github.rafaelldi.diagnosticsclientplugin.dialogs.StoppingType
import com.github.rafaelldi.diagnosticsclientplugin.dialogs.map
import com.github.rafaelldi.diagnosticsclientplugin.generated.PersistentCounterSession
import com.github.rafaelldi.diagnosticsclientplugin.generated.diagnosticsHostModel
import com.github.rafaelldi.diagnosticsclientplugin.services.common.PersistentSessionController
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.jetbrains.rider.projectView.solution
import kotlin.io.path.Path
import kotlin.io.path.pathString
@Service
class PersistentCounterSessionController(project: Project) :
PersistentSessionController<PersistentCounterSession, CounterModel>(project) {
companion object {
fun getInstance(project: Project): PersistentCounterSessionController = project.service()
private const val COUNTERS = "Counters"
}
override val artifactType = COUNTERS
override val canBeOpened = true
override val sessions = project.solution.diagnosticsHostModel.persistentCounterSessions
init {
sessions.view(serviceLifetime) { lt, pid, session ->
viewSession(pid, session, lt)
}
}
override fun createSession(model: CounterModel): PersistentCounterSession {
val filePath = calculateFilePath(model)
val metrics = model.metrics.ifEmpty { null }
val duration =
if (model.stoppingType == StoppingType.AfterPeriod) model.duration
else null
return PersistentCounterSession(
model.format.map(),
model.interval,
model.providers,
metrics,
model.maxTimeSeries,
model.maxHistograms,
duration,
filePath
)
}
private fun calculateFilePath(model: CounterModel): String {
val filename = when (model.format) {
CounterFileFormat.Csv -> {
if (model.filename.endsWith(".csv"))
model.filename
else
"${model.filename}.csv"
}
CounterFileFormat.Json -> {
if (model.filename.endsWith(".json"))
model.filename
else
"${model.filename}.json"
}
}
return Path(model.path, filename).pathString
}
} | 3 | Kotlin | 0 | 4 | 8d4cfd9f4992ad10010d80c2359158399f4846aa | 2,683 | diagnostics-client-plugin | MIT License |
app/src/main/java/com/example/youtube/base/RequestCallback.kt | HugoJordan7 | 842,923,048 | false | {"Kotlin": 27410} | package com.example.youtube.base
interface RequestCallback<T> {
fun onSuccess(data: T)
fun onFailure(message: String)
fun onComplete()
} | 0 | Kotlin | 0 | 0 | 773be9e7aa271c8e1a5504b7492c3414baa80a60 | 149 | youtube | MIT License |
core/src/main/kotlin/com/deflatedpickle/rawky/api/ImportAs.kt | DeflatedPickle | 197,672,095 | false | {"Kotlin": 641980, "Python": 2204} | package com.deflatedpickle.rawky.api
enum class ImportAs {
FRAMES,
LAYERS,
} | 7 | Kotlin | 6 | 27 | 81dafc9065f76fad8ffe0c10ad6cc9ed26c7965f | 85 | Rawky | MIT License |
app/src/main/java/com/infbyte/amuzic/ui/screens/PlayBar.kt | shuberttheI | 647,623,010 | false | {"Kotlin": 89581} | package com.infbyte.amuzic.ui.screens
import android.content.res.ColorStateList
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.tween
import androidx.compose.animation.expandVertically
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import com.infbyte.amuzic.R
import com.infbyte.amuzic.data.model.Song
import com.infbyte.amuzic.playback.PlaybackMode
@Composable
fun BoxScope.PlayBar(
isVisible: State<Boolean>,
isPlaying: State<Boolean>,
song: Song,
progress: State<Float>,
playbackMode: State<PlaybackMode>,
onPlayClick: () -> Unit,
onNextClick: () -> Unit,
onPrevClick: () -> Unit,
onTogglePlaybackMode: () -> Unit,
onSeekTo: (Float) -> Unit
) {
AnimatedVisibility(
visible = isVisible.value,
Modifier
.align(Alignment.BottomCenter),
enter = expandVertically(tween(1000), Alignment.Bottom),
exit = shrinkVertically(tween(1000), Alignment.Top)
) {
Column(
Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(topStartPercent = 20, topEndPercent = 20))
.clickable {}
.border(0.dp, Color.LightGray)
.background(
MaterialTheme.colorScheme.background,
RoundedCornerShape(topStartPercent = 20, topEndPercent = 20)
),
horizontalAlignment = Alignment.CenterHorizontally
) {
Row(
Modifier.padding(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
IconButton(
onClick = {
onTogglePlaybackMode()
},
Modifier.padding(16.dp).background(
MaterialTheme.colorScheme.background
)
) {
Icon(
when (playbackMode.value) {
PlaybackMode.REPEAT_ONE ->
painterResource(R.drawable.ic_repeat_one)
PlaybackMode.REPEAT_ALL ->
painterResource(R.drawable.ic_repeat)
PlaybackMode.SHUFFLE ->
painterResource(R.drawable.ic_shuffle)
},
"",
Modifier
.size(32.dp)
)
}
IconButton(
onClick = { onPrevClick() },
Modifier.background(Color.Gray, CircleShape)
) {
Icon(
painterResource(R.drawable.ic_skip_previous),
"",
Modifier.size(32.dp)
)
}
Box(
Modifier
.padding(start = 24.dp, end = 24.dp)
.wrapContentSize()
) {
CircularProgressIndicator(
progress.value,
Modifier.size(48.dp),
strokeWidth = 1.5.dp
)
Icon(
if (isPlaying.value) {
ImageVector.vectorResource(R.drawable.ic_pause)
} else { Icons.Filled.PlayArrow },
"",
Modifier
.clip(CircleShape)
.size(48.dp)
.clickable {
onPlayClick()
}
)
}
IconButton(
onClick = { onNextClick() },
Modifier.background(Color.Gray, CircleShape)
) {
Icon(
painterResource(R.drawable.ic_skip_next),
"",
Modifier.size(32.dp)
)
}
IconButton(
onClick = {},
Modifier.padding(16.dp).background(
MaterialTheme.colorScheme.background,
CircleShape
)
) {
Icon(
painterResource(R.drawable.ic_queue_music),
"",
Modifier.size(32.dp)
)
}
}
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
Column(
Modifier.padding(8.dp).fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
song.name,
textAlign = TextAlign.Center,
maxLines = 1
)
Slider(
value = progress.value,
onValueChange = { onSeekTo(it) },
modifier = Modifier.padding(
start = 32.dp,
end = 32.dp,
top = 8.dp,
bottom = 8.dp
).height(32.dp)
)
}
}
}
}
}
@Composable
fun SeekBar(
progress: Float,
height: Dp,
color: Color,
onSeekTo: (Float) -> Unit
) {
AndroidView(
factory = { context ->
val seekBar = SeekBar(context)
val seekListener = object : OnSeekBarChangeListener {
override fun onProgressChanged(
seekBar: SeekBar?,
position: Int,
fromUser: Boolean
) {
if (fromUser) {
onSeekTo(position.toFloat() / 1000)
}
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {}
override fun onStopTrackingTouch(seekBar: SeekBar?) {}
}
seekBar.max = 1000
seekBar.progressTintList = ColorStateList.valueOf(color.toArgb())
seekBar.thumbTintList = ColorStateList.valueOf(color.toArgb())
seekBar.setOnSeekBarChangeListener(seekListener)
seekBar
},
modifier = Modifier
.fillMaxWidth()
.height(height),
update = { seekBar ->
seekBar.progress = (progress * 1000).toInt()
}
)
}
| 0 | Kotlin | 0 | 1 | 9dfc5655628028c90755235042d42e1e1e175e95 | 8,515 | Amuzic | MIT License |
src/main/kotlin/com/dariopellegrini/kdone/privacy/model/PrivacyParagraph.kt | dariopellegrini | 228,861,697 | false | {"Kotlin": 223255} | package com.dariopellegrini.kdone.privacy.model
data class PrivacyParagraph(val title: String,
val content: String,
val key: String,
var selectable: Boolean = false, // This paragraph is selectable. Otherwise is only a readable paragraph.
var mustBeAccepted: Boolean = false, // If selectable is true paragraph must be accepted by user
var mustBeAnswered: Boolean = true) // if selectable is true paragraph needs a response, either accepted or denied
fun paragraph(title: String,
content: String,
key: String,
init: (PrivacyParagraph.() -> Unit)? = null): PrivacyParagraph {
val privacyParagraph = PrivacyParagraph(title, content, key)
if (init != null) {
privacyParagraph.init()
}
return privacyParagraph
} | 1 | Kotlin | 0 | 8 | c9db12085e17db4d205bd3c6161e17ee486f6168 | 915 | KDone | MIT License |
projects/prison-custody-status-to-delius/src/main/kotlin/uk/gov/justice/digital/hmpps/messaging/actions/UpdateStatusAction.kt | ministryofjustice | 500,855,647 | false | {"Kotlin": 3294884, "HTML": 54825, "D2": 27334, "Ruby": 24334, "Shell": 12351, "SCSS": 5980, "HCL": 2712, "Dockerfile": 2414, "JavaScript": 1288, "Python": 268} | package uk.gov.justice.digital.hmpps.messaging.actions
import org.springframework.stereotype.Component
import uk.gov.justice.digital.hmpps.exception.IgnorableMessageException
import uk.gov.justice.digital.hmpps.integrations.delius.custody.entity.*
import uk.gov.justice.digital.hmpps.integrations.delius.referencedata.ReferenceData
import uk.gov.justice.digital.hmpps.integrations.delius.referencedata.ReferenceDataRepository
import uk.gov.justice.digital.hmpps.integrations.delius.referencedata.getCustodialStatus
import uk.gov.justice.digital.hmpps.integrations.delius.referencedata.getCustodyEventType
import uk.gov.justice.digital.hmpps.integrations.delius.referencedata.wellknown.CustodialStatusCode
import uk.gov.justice.digital.hmpps.integrations.delius.referencedata.wellknown.CustodyEventTypeCode
import uk.gov.justice.digital.hmpps.integrations.delius.referencedata.wellknown.NO_CHANGE_STATUSES
import uk.gov.justice.digital.hmpps.messaging.*
@Component
class UpdateStatusAction(
private val referenceDataRepository: ReferenceDataRepository,
private val custodyRepository: CustodyRepository,
private val custodyHistoryRepository: CustodyHistoryRepository
) : PrisonerMovementAction {
override val name: String = "UpdateStatus"
override fun accept(context: PrisonerMovementContext): ActionResult =
when (context.prisonerMovement) {
is PrisonerMovement.Received -> {
inboundStatusChange(context)
}
is PrisonerMovement.Released -> {
outboundStatusChange(context)
}
}
private fun inboundStatusChange(context: PrisonerMovementContext): ActionResult {
val (prisonerMovement, custody) = context
return if (custody.status.canChange() && prisonerMovement.receivedDateValid(custody)) {
val detail = if (custody.canBeRecalled()) "Recall added in custody " else "In custody "
updateStatus(
custody,
CustodialStatusCode.IN_CUSTODY,
prisonerMovement,
detail
)
} else {
ActionResult.Ignored("PrisonerStatusCorrect", prisonerMovement.telemetryProperties())
}
}
private fun outboundStatusChange(context: PrisonerMovementContext): ActionResult {
val (prisonerMovement, custody) = context
val statusCode = when {
prisonerMovement.isHospitalRelease() || prisonerMovement.isIrcRelease() || prisonerMovement.isAbsconded() -> custody.nextStatus()
else -> if (custody.canBeReleased() && prisonerMovement.releaseDateValid(custody)) {
CustodialStatusCode.RELEASED_ON_LICENCE
} else {
throw IgnorableMessageException("PrisonerStatusCorrect")
}
}
return updateStatus(
custody,
statusCode,
prisonerMovement,
when {
prisonerMovement.isHospitalRelease() -> "Transfer to/from Hospital"
prisonerMovement.isIrcRelease() -> "Transfer to Immigration Removal Centre"
prisonerMovement.isAbsconded() -> "Recall added unlawfully at large "
else -> "Released on Licence"
}
)
}
private fun Custody.nextStatus() =
when {
canBeRecalled() -> CustodialStatusCode.RECALLED
status.canChange() -> CustodialStatusCode.IN_CUSTODY
else -> throw IgnorableMessageException("PrisonerStatusCorrect")
}
private fun updateStatus(
custody: Custody,
status: CustodialStatusCode,
prisonerMovement: PrisonerMovement,
detail: String
): ActionResult = custody.updateStatusAt(
referenceDataRepository.getCustodialStatus(status.code),
prisonerMovement.occurredAt,
detail
) {
referenceDataRepository.getCustodyEventType(CustodyEventTypeCode.STATUS_CHANGE.code)
}?.let { history ->
custodyRepository.save(custody)
custodyHistoryRepository.save(history)
return ActionResult.Success(ActionResult.Type.StatusUpdated, prisonerMovement.telemetryProperties())
} ?: ActionResult.Ignored("PrisonerStatusCorrect", prisonerMovement.telemetryProperties())
}
private fun ReferenceData.canChange() = !NO_CHANGE_STATUSES.map { it.code }.contains(code)
| 8 | Kotlin | 0 | 2 | fb5efdbdedcdc6e88c25c529af94ebaeba419c7f | 4,372 | hmpps-probation-integration-services | MIT License |
app/src/main/java/com/webianks/expensive/util/Util.kt | webianks | 186,256,631 | false | null | package com.webianks.expensive.util
import android.content.Context
import android.net.Uri
import androidx.browser.customtabs.CustomTabsIntent
object Util {
const val TAG: String = "Expensive"
const val EXPENSE_COLLECTION: String = "expenses"
private const val PRIVACY_URL: String = "https://expensive.flycricket.io/privacy.html"
fun openPrivacyTab(context: Context) {
val builder = CustomTabsIntent.Builder()
val customTabsIntent = builder.build()
customTabsIntent.launchUrl(context, Uri.parse(PRIVACY_URL))
}
} | 0 | Kotlin | 5 | 23 | 13719ed6e4ce6d91aea904f7b0deadfcae574486 | 559 | Expensive | MIT License |
src/test/kotlin/LoadMarkdownInfo.kt | MalayPrime | 379,254,123 | false | null | import java.io.File
fun main() {
val file = File("./src/main/resources/assets/decorations/textures/gui/line_style/README.md")
val content = file.readLines().map { it.replace(" ", "") }
val data = mutableListOf<WidgetDescribe>()
var currentInfo : String? = null
(3 until content.size).map {
try {
val info = content[it]
currentInfo = info
if (info.length != 8 && info.isNotEmpty()) {
val splited = info.split("|").filter { s -> s.isNotEmpty() }.dropLast(1).filter { s -> s.isNotEmpty() }
val uv = splited[1].split(",").map { s -> s.toInt() }
data.add(
WidgetDescribe(
splited[0],
uv[0], uv[1],
splited[2].toInt(), splited[3].toInt()
)
)
}
}catch (e : NumberFormatException){
e.addSuppressed(RuntimeException("failed to analyse $currentInfo"))
}
}
// println("picture size = width:${} height:")
data.forEach {
println("val ${it.partName} = WidgetDescriptor(\"${it.partName}\",${it.u},${it.v},${it.width},${it.height},this)")
}
val picInfo = content[2].split("|").filter { s->s.isNotEmpty() }.dropLast(1).filter { s -> s.isNotEmpty() }
println("pic info width:${picInfo[2]} , height:${picInfo[3]} , check this if it needs check")
}
data class WidgetDescribe(val partName: String, val u: Int, val v: Int, val width: Int, val height: Int) | 0 | Kotlin | 1 | 1 | 111cf27428c1580b91602a384bb46cd0988415cd | 1,546 | rotarism-decorations | MIT License |
innertube/src/main/kotlin/it/vfsfitvnm/innertube/models/GridRenderer.kt | Sagnik0684 | 861,208,877 | false | {"Kotlin": 713513} | package it.vfsfitvnm.innertube.models
import kotlinx.serialization.Serializable
@Serializable
data class GridRenderer(
val items: List<Item>?,
) {
@Serializable
data class Item(
val musicTwoRowItemRenderer: MusicTwoRowItemRenderer?
)
}
| 0 | Kotlin | 0 | 0 | d068ae496559b4f7cc7152e38de3483a12b0b8f0 | 262 | BuzzVibe | MIT License |
xbinder/src/main/java/com/luqinx/xbinder/ServiceProxyFactory.kt | luqinx | 450,696,816 | false | null | package com.luqinx.xbinder
import com.luqinx.interceptor.Interceptor
import com.luqinx.interceptor.OnInvoke
import com.luqinx.xbinder.annotation.InvokeType
import com.luqinx.xbinder.misc.Refined
import java.lang.reflect.Method
/**
* @author qinchao
*
* @since 2022/1/2
*/
internal object ServiceProxyFactory {
fun <T> newServiceProxy(options: NewServiceOptions<T>): T {
Refined.start()
val service = newProxy(options)
Refined.log("new proxy")
(service as ILightBinder).setInstanceId(
service.`_$newConstructor_`(options.constructorTypes, options.constructorArgs)
)
Refined.log("_\$newConstructor_")
return service
}
fun <T> newCallbackProxy(options: NewServiceOptions<T>): T {
options.isCallback = true
options.invokeType = InvokeType.REMOTE_ONLY
// callback.`_$bindCallbackProxy_`(options.instanceId)
return newProxy(options)
}
private fun <T> newProxy(options: NewServiceOptions<T>): T {
return options.run {
val interfaces =
if (!ILightBinder::class.java.isAssignableFrom(serviceClass)) {
arrayOf(ILightBinder::class.java, serviceClass, IProxyFlag::class.java)
} else {
arrayOf(serviceClass, IProxyFlag::class.java)
}
Interceptor.of(null as T?).interfaces(*interfaces)
.intercepted(true)
.invoke(object : OnInvoke<T?> {
private val objectBehaviors: ObjectBehaviors =
ObjectBehaviors(
serviceClass,
options.processName,
options.instanceId
)
private val LOCAL_BEHAVIORS: ProxyBehaviors by lazy {
ProxyBehaviors(
processName,
serviceClass,
objectBehaviors.hashCode(),
options.instanceId
)
}
override fun onInvoke(source: T?, method: Method, args: Array<Any?>?): Any? {
// Refined.start()
// logger.d(message = "onInvoke: ${method?.name}(${args?.contentDeepToString()})")
// Refined.finish("logger onInvoke ")
val remoteCaller: Any = when (method.declaringClass) {
Any::class.java -> objectBehaviors
IProxyBehaviors::class.java -> LOCAL_BEHAVIORS
else -> BinderBehaviors
}
fun localInvoker(): T? = ServiceProvider.doFind(
options.processName,
objectBehaviors.hashCode(),
options.serviceClass,
options.constructorTypes,
options.constructorArgs
) as T?
var caller: Any? = when (invokeType) {
InvokeType.LOCAL_ONLY -> localInvoker()
InvokeType.LOCAL_FIRST -> localInvoker() ?: remoteCaller
InvokeType.REMOTE_ONLY -> remoteCaller
InvokeType.REMOTE_FIRST -> remoteCaller
else -> {
throw IllegalArgumentException("unknown invoke type $invokeType")
}
} ?: options.defService
if (caller == BinderBehaviors) {
try {
return BinderBehaviors.invokeMethod(
serviceClass, //
method,
args,
options,
objectBehaviors.hashCode()
)
} catch (e: XBinderException) {
if (e.code != BinderInvoker.ERROR_CODE_REMOTE_NOT_FOUND) {
caller = localInvoker() ?: options.defService
} else {
throw e
}
}
}
if (caller == null) return null
return if (args != null) {
method.invoke(caller, *args)
} else method.invoke(caller)
}
}).newInstance()!!
}
}
} | 0 | Kotlin | 1 | 5 | 42d3327ecf36886ecb55e87679399eadb1b58ed8 | 4,815 | XBinder | Apache License 2.0 |
src/main/java/com/swordglowsblue/artifice/api/builder/data/worldgen/configured/feature/config/EmeraldOreFeatureConfigBuilder.kt | CmdrNorthpaw | 383,564,722 | true | {"Kotlin": 251370, "Java": 29899} | package com.swordglowsblue.artifice.api.builder.data.worldgen.configured.feature.config
import com.google.gson.JsonObject
import com.swordglowsblue.artifice.api.builder.data.StateDataBuilder
class EmeraldOreFeatureConfigBuilder : FeatureConfigBuilder() {
fun state(processor: StateDataBuilder.() -> Unit): EmeraldOreFeatureConfigBuilder {
with("state", { JsonObject() }) { jsonObject: JsonObject ->
StateDataBuilder().apply(processor).buildTo(jsonObject)
}
return this
}
fun target(processor: StateDataBuilder.() -> Unit): EmeraldOreFeatureConfigBuilder {
with("target", { JsonObject() }) { jsonObject: JsonObject ->
StateDataBuilder().apply(processor).buildTo(jsonObject)
}
return this
}
} | 0 | Kotlin | 0 | 1 | f86b54976c4e0f890cd3c2bb295104dba0d92478 | 781 | artifice | MIT License |
app/src/main/java/com/mrspd/letschat/ui/mainActivity/MainActivity.kt | satyamurti | 275,247,716 | false | null | package com.mrspd.letschat.ui.mainActivity
import android.content.Context
import android.os.Bundle
import android.util.Log.d
import android.util.Log.w
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProviders
import androidx.navigation.NavController
import androidx.navigation.NavOptions
import androidx.navigation.Navigation
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupWithNavController
import com.facebook.CallbackManager
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.database.*
import com.google.firebase.firestore.DocumentReference
import com.mrspd.letschat.R
import com.mrspd.letschat.databinding.ActivityMainBinding
import com.mrspd.letschat.util.AuthUtil
import com.mrspd.letschat.util.FirestoreUtil
import com.mrspd.letschat.util.eventbus_events.ConnectionChangeEvent
import com.mrspd.letschat.util.eventbus_events.KeyboardEvent
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
class MainActivity : AppCompatActivity() {
private var userDocRef: DocumentReference? = AuthUtil.getAuthId().let {
FirestoreUtil.firestoreInstance.collection("users").document(it)
}
var isActivityRecreated = false
lateinit var callbackManager: CallbackManager
private lateinit var sharedViewModel: SharedViewModel
private lateinit var binding: ActivityMainBinding
private lateinit var navController: NavController
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val db = FirestoreUtil.firestoreInstance
db.collection("users").document(AuthUtil.getAuthId()).update("status", true)
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
val database = FirebaseDatabase.getInstance()
val myConnectionsRef = database.getReference("users")
// Stores the timestamp of my last disconnect (the last time I was seen online)
val lastOnlineRef = database.getReference("/users/${AuthUtil.getAuthId()}/lastOnline")
val status = database.getReference("/users/${AuthUtil.getAuthId()}/status")
val connectedRef = database.getReference(".info/connected")
connectedRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val connected: Boolean = (snapshot.getValue() ?: false) as Boolean
if (connected) {
status.setValue("online")
// db.collection("users").document(AuthUtil.getAuthId()).update("status", true)
// When this device disconnects, remove it
// val con = myConnectionsRef.push()
//
// // When this device disconnects, remove it
// con.onDisconnect().removeValue(DatabaseReference.CompletionListener { error, ref ->
// db.collection("users").document(AuthUtil.getAuthId())
// .update("status", "offldgdfgine")
// d("gghh", "status is : offline")
// })
// When I disconnect, update the last time I was seen online
lastOnlineRef.onDisconnect().setValue(ServerValue.TIMESTAMP)
status.onDisconnect().setValue("offline")
// Add this device to my connections list
// this value could contain info about the device or a timestamp too
}
}
override fun onCancelled(error: DatabaseError) {
w("gghh", "Listener was cancelled at .info/connected")
}
})
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
sharedViewModel = ViewModelProviders.of(this).get(SharedViewModel::class.java)
setSupportActionBar(binding.toolbar)
//hide toolbar on signup,login fragments
navController = Navigation.findNavController(this, R.id.nav_host_fragment)
navController.addOnDestinationChangedListener { _, destination, _ ->
if (destination.label == "SignupFragment" || destination.label == "LoginFragment") {
binding.toolbar.visibility = View.GONE
} else {
binding.toolbar.visibility = View.VISIBLE
}
}
//register to event bus to receive callbacks
EventBus.getDefault().register(this)
//hide toolbar on signup,login fragments
navController = Navigation.findNavController(this, R.id.nav_host_fragment)
navController.addOnDestinationChangedListener { _, destination, _ ->
if (destination.label == "SignupFragment" || destination.label == "LoginFragment") {
binding.toolbar.visibility = View.GONE
} else {
binding.toolbar.visibility = View.VISIBLE
}
}
//setup toolbar with navigation
val appBarConfiguration = AppBarConfiguration(setOf(R.id.homeFragment, R.id.loginFragment))
findViewById<Toolbar>(R.id.toolbar)
.setupWithNavController(navController, appBarConfiguration)
navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
}
// Show snackbar whenever the connection state changes
@Subscribe(threadMode = ThreadMode.MAIN)
open fun onConnectionChangeEvent(event: ConnectionChangeEvent): Unit {
if (!isActivityRecreated) {//to not show toast on configuration changes
Snackbar.make(binding.coordinator, event.message, Snackbar.LENGTH_LONG).show()
}
}
override fun onDestroy() {
super.onDestroy()
EventBus.getDefault().unregister(this)
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onKeyboardEvent(event: KeyboardEvent) {
hideKeyboard()
}
private fun hideKeyboard() {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.hideSoftInputFromWindow(binding.toolbar.windowToken, 0)
}
fun isValidDestination(destination: Int): Boolean {
return destination != Navigation.findNavController(this, R.id.nav_host_fragment)
.currentDestination!!.id
}
//
// override fun onCreateOptionsMenu(menu: Menu?): Boolean {
// return super.onCreateOptionsMenu(menu)
//
// menuInflater.inflate(R.menu.main_menu,menu)
// val menuItem = menu.findItem(R.id.action_incoming_requests)
// val actionView = menuItem?.actionView
// }
//
// override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
//
// R.id.action_add_friend -> {
// Navigation.findNavController(this, R.id.nav_host_fragment).navigate(R.id.action_homeFragment_to_findUserFragment)
// true
// }
// R.id.action_edit_profile -> {
// Navigation.findNavController(this, R.id.nav_host_fragment).navigate(R.id.action_homeFragment_to_profileFragment)
// true
// }
// R.id.action_logout -> {
// logout()
// true
// }
// R.id.action_incoming_requests -> {
// Navigation.findNavController(this, R.id.nav_host_fragment).navigate(R.id.action_homeFragment_to_incomingRequestsFragment)
//
//
// true
// }
//
// else -> {
// // If we got here, the user's action was not recognized.
// // Invoke the superclass to handle it.
// super.onOptionsItemSelected(item)
// }
//
// }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private val mOnNavigationItemSelectedListener =
BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.chatFragment -> {
d("gghh", "yes group")
var navOptions = NavOptions.Builder().setPopUpTo(R.id.nav_graph, true).build()
if (isValidDestination(R.id.homeFragment)) {
Navigation.findNavController(this, R.id.nav_host_fragment)
.navigate(R.id.homeFragment, null, navOptions)
}
}
R.id.groupFragment -> {
d("gghh", "yes group")
if (isValidDestination(R.id.groupFragment)) {
Navigation.findNavController(this, R.id.nav_host_fragment)
.navigate(R.id.homeFragmentRoom)
}
}
R.id.ARselfieFragment -> {
d("gghh", "yes group")
if (isValidDestination(R.id.ARselfieFragment)) {
Navigation.findNavController(this, R.id.nav_host_fragment)
.navigate(R.id.ARSelfieFragmentHome)
}
}
R.id.searchFragment -> {
d("gghh", "yes group")
if (isValidDestination(R.id.searchFragment)) {
Navigation.findNavController(this, R.id.nav_host_fragment)
.navigate(R.id.findUserFragment)
}
}
R.id.profileFragment -> {
d("gghh", "yes group")
if (isValidDestination(R.id.profileFragment)) {
Navigation.findNavController(this, R.id.nav_host_fragment)
.navigate(R.id.profileFragment)
}
}
}
item.isChecked = true
false
}
/////////////////////////////////////////////////////////////////////////
} | 1 | Kotlin | 30 | 80 | 62f0f0ae22b38d8c48c5c27800005039f2030987 | 10,417 | LetsChat | MIT License |
meistercharts-canvas/src/commonMain/kotlin/com/meistercharts/canvas/text/TextLineCalculations.kt | Neckar-IT | 599,079,962 | false | null | /**
* Copyright 2023 Neckar IT GmbH, Mössingen, Germany
*
* 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.meistercharts.canvas.text
import com.meistercharts.canvas.BlankFallbackText
import com.meistercharts.canvas.CanvasRenderingContext
import com.meistercharts.font.FontMetrics
import it.neckar.open.collections.fastForEach
import it.neckar.open.kotlin.lang.allBlank
import it.neckar.open.provider.SizedProvider
import it.neckar.open.provider.fastForEach
import it.neckar.open.provider.isNotEmpty
import it.neckar.open.unit.other.px
/**
* Supports calculations of (multi line) texts
*/
object TextLineCalculations {
/**
* Contains the [BlankFallbackText] as list
*/
val BlankFallbackLine: List<String> = listOf(BlankFallbackText)
/**
* Returns a list that contains at least one line that is not blank
*/
fun avoidAllBlankLines(lines: List<String>): List<String> {
if (lines.isEmpty()) {
return BlankFallbackLine
}
if (lines.allBlank()) {
//TODO introduce cache(?)
List(lines.size) { BlankFallbackText }
}
return lines
}
/**
* Returns the height of a text block for the given lines
*/
fun calculateTextBlockHeight(
fontMetrics: FontMetrics, linesCount: Int,
lineSpacing: LineSpacing,
/**
* The min line height - this can be used if other factors are relevant for the line height (e.g. images)
*/
minLineHeight: @px Double = 0.0,
): @px Double {
@px val spaceBetweenLines = fontMetrics.totalHeight * lineSpacing.spacePercentage
return calculateTextBlockHeight(fontMetrics, linesCount, spaceBetweenLines, minLineHeight)
}
/**
* Returns the height of a text block
*/
fun calculateTextBlockHeight(
fontMetrics: FontMetrics, linesCount: Int, spaceBetweenLines: @px Double,
/**
* The min line height - this can be used if other factors are relevant for the line height (e.g. images)
*/
minLineHeight: @px Double = 0.0,
): @px Double {
@px val lineHeight = fontMetrics.totalHeight.coerceAtLeast(minLineHeight)
return linesCount * lineHeight + (linesCount - 1) * spaceBetweenLines
}
/**
* Returns the text width for the lines.
* Returns at most the [maxStringWidth] (if provided).
*
* Throws an exception if no lines are provided
*/
@Suppress("DuplicatedCode")
fun calculateMultilineTextWidth(
renderingContext: CanvasRenderingContext,
lines: List<String>,
/**
* The optional max width that is returned
*/
maxStringWidth: @px Double = Double.MAX_VALUE,
): @px Double {
require(lines.isNotEmpty()) { "Need at least one line" }
//the current max width for all lines
var currentMaxWidth = 0.0
lines.fastForEach { line ->
if (currentMaxWidth >= maxStringWidth) {
//Skip remaining lines, return immediately if max length has been reached
return maxStringWidth
}
currentMaxWidth = currentMaxWidth.coerceAtLeast(renderingContext.calculateTextWidth(line))
}
return currentMaxWidth.coerceAtMost(maxStringWidth)
}
/**
* Calculates the multi line text width using a sized provider
*/
@Suppress("DuplicatedCode")
fun calculateMultilineTextWidth(
renderingContext: CanvasRenderingContext,
lines: SizedProvider<String>,
/**
* The optional max width that is returned
*/
maxStringWidth: @px Double = Double.MAX_VALUE,
): @px Double {
require(lines.isNotEmpty()) { "Need at least one line" }
//the current max width for all lines
var currentMaxWidth = 0.0
lines.fastForEach { line ->
if (currentMaxWidth >= maxStringWidth) {
//Skip remaining lines, return immediately if max length has been reached
return maxStringWidth
}
currentMaxWidth = currentMaxWidth.coerceAtLeast(renderingContext.calculateTextWidth(line))
}
return currentMaxWidth.coerceAtMost(maxStringWidth)
}
}
| 3 | null | 3 | 5 | ed849503e845b9d603598e8d379f6525a7a92ee2 | 4,450 | meistercharts | Apache License 2.0 |
demo/demo-basic/src/jsMain/kotlin/main.kt | spxbhuhb | 290,390,793 | false | null | /*
* Copyright © 2020-2021, <NAME> and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("unused") // main is called by webpack
import zakadabar.core.browser.application.ZkApplication
import zakadabar.core.browser.application.application
import zakadabar.core.browser.util.io
import zakadabar.core.resource.initTheme
import zakadabar.lib.demo.frontend.Routing
import zakadabar.lib.demo.resources.strings
import zakadabar.softui.browser.theme.SuiLightTheme
fun main() {
application = ZkApplication()
application.pendingModificationsEnabled = true
zakadabar.lib.accounts.browser.install(application)
zakadabar.lib.i18n.browser.install(application)
zakadabar.softui.browser.install()
io {
with(application) {
initSession()
initTheme(SuiLightTheme())
initLocale(strings)
initRouting(Routing())
run()
}
}
} | 7 | Kotlin | 3 | 15 | a7dadd160504bc3496830a336542abd831212a29 | 971 | zakadabar-stack | Apache License 2.0 |
Bitfit3/app/src/main/java/com/example/bitfit/Food.kt | claudiaisfighting | 555,867,918 | false | {"Kotlin": 12377} | package com.example.bitfit
data class Food (
val name: String,
val calories: String,
) : java.io.Serializable | 1 | Kotlin | 0 | 0 | 5c0fb1c1fb61cabc144e27b6cf3300feacac1a4c | 118 | Bitfit2 | Apache License 2.0 |
api/src/main/kotlin/edu/wgu/osmt/collection/CollectionDoc.kt | wgu-opensource | 371,168,832 | false | {"TypeScript": 870780, "Kotlin": 663910, "HTML": 153260, "JavaScript": 87226, "Shell": 42875, "HCL": 13700, "SCSS": 9144, "Java": 8284, "Smarty": 5908, "Dockerfile": 477} | package edu.wgu.osmt.collection
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonProperty
import edu.wgu.osmt.config.INDEX_COLLECTION_DOC
import edu.wgu.osmt.db.PublishStatus
import javax.annotation.Nullable
import org.springframework.data.annotation.Id
import org.springframework.data.elasticsearch.annotations.*
import org.springframework.data.elasticsearch.annotations.FieldType.*
import java.time.LocalDateTime
/**
* Elasticsearch representation of a Collection.
* Also corresponds to `CollectionSummary` API response object
*/
@JsonInclude(value = JsonInclude.Include.NON_NULL)
@Document(indexName = INDEX_COLLECTION_DOC, createIndex = true)
@Setting(settingPath = "/elasticsearch/settings.json")
data class CollectionDoc(
@Field(name = "db_id")
@get:JsonIgnore
val id: Long,
@Id
@Field(type = Keyword)
val uuid: String,
@MultiField(
mainField = Field(type = Text, analyzer = "english_stemmer"),
otherFields = [
InnerField(suffix = "", type = Search_As_You_Type, analyzer = "english_stemmer"),
InnerField(suffix = "raw", analyzer = "whitespace_exact", type = Text),
InnerField(suffix = "keyword", type = Keyword)
]
)
val name: String,
@MultiField(
mainField = Field(type = Text, analyzer = "english_stemmer"),
otherFields = [
InnerField(suffix = "", type = Search_As_You_Type),
InnerField(suffix = "raw", analyzer = "whitespace_exact", type = Text),
InnerField(suffix = "keyword", type = Keyword),
InnerField(suffix = "sort_insensitive", type = Keyword, normalizer = "lowercase_normalizer")
]
)
val description: String?,
@Field(type = Keyword)
@get:JsonProperty("status")
val publishStatus: PublishStatus,
@Field(type = Keyword)
@Nullable
@get:JsonIgnore
val skillIds: List<String>?,
@Field(type = Integer)
@Nullable
val skillCount: Int?,
@MultiField(
mainField = Field(type = Text, analyzer = "english_stemmer"),
otherFields = [
InnerField(suffix = "", type = Search_As_You_Type),
InnerField(suffix = "raw", analyzer = "whitespace_exact", type = Text),
InnerField(suffix = "keyword", type = Keyword)
]
)
@Nullable
@get:JsonIgnore
val author: String?,
@Field(type = FieldType.Date, format = [DateFormat.date_hour_minute_second])
@get:JsonProperty("archiveDate")
val archiveDate: LocalDateTime? = null,
@Field(type = FieldType.Date, format = [DateFormat.date_hour_minute_second])
@get:JsonProperty("publishDate")
val publishDate: LocalDateTime? = null,
@Field(type = Text)
@Nullable
val workspaceOwner: String?
)
| 59 | TypeScript | 9 | 38 | 661def32d727c19c77c0f8e5a9c78cda65ab047b | 2,867 | osmt | Apache License 2.0 |
appcues/src/main/java/com/appcues/data/remote/RemoteError.kt | appcues | 413,524,565 | false | null | package com.appcues.data.remote
import com.appcues.data.remote.response.ErrorResponse
internal sealed class RemoteError {
data class HttpError(val code: Int? = null, val error: ErrorResponse? = null) : RemoteError()
data class NetworkError(val throwable: Throwable? = null) : RemoteError()
}
| 5 | Kotlin | 2 | 8 | 1d09fb83554fa7f12190e267064d8948ee7f35bb | 302 | appcues-android-sdk | MIT License |
presentation-map/src/main/java/com/jacekpietras/zoo/map/viewmodel/MapViewModel.kt | JacekPietras | 334,416,736 | false | {"Kotlin": 752140, "Java": 21319} | package com.jacekpietras.zoo.map.viewmodel
import android.content.Context
import androidx.lifecycle.ViewModel
import com.jacekpietras.geometry.PointD
import com.jacekpietras.mapview.logic.MapViewLogic
import com.jacekpietras.mapview.model.ComposablePaint
import com.jacekpietras.mapview.model.RenderItem
import com.jacekpietras.mapview.ui.LastMapUpdate.trans
import com.jacekpietras.mapview.ui.compose.ComposablePaintBaker
import com.jacekpietras.zoo.core.dispatcher.flowOnBackground
import com.jacekpietras.zoo.core.dispatcher.flowOnMain
import com.jacekpietras.zoo.core.dispatcher.launchInBackground
import com.jacekpietras.zoo.core.dispatcher.onMain
import com.jacekpietras.zoo.core.text.RichText
import com.jacekpietras.zoo.core.theme.MapColors
import com.jacekpietras.zoo.domain.feature.animal.interactor.GetAnimalUseCase
import com.jacekpietras.zoo.domain.feature.animal.model.AnimalEntity
import com.jacekpietras.zoo.domain.feature.animal.model.AnimalId
import com.jacekpietras.zoo.domain.feature.favorites.interactor.ObserveAnimalFavoritesUseCase
import com.jacekpietras.zoo.domain.feature.map.interactor.LoadMapUseCase
import com.jacekpietras.zoo.domain.feature.map.interactor.ObserveMapObjectsUseCase
import com.jacekpietras.zoo.domain.feature.pathfinder.interactor.GetShortestPathFromUserUseCase
import com.jacekpietras.zoo.domain.feature.planner.interactor.ObserveCurrentPlanPathWithOptimizationUseCase
import com.jacekpietras.zoo.domain.feature.sensors.interactor.ObserveArrivalAtRegionEventUseCase
import com.jacekpietras.zoo.domain.feature.sensors.interactor.ObserveCompassUseCase
import com.jacekpietras.zoo.domain.feature.sensors.interactor.ObserveOutsideWorldEventUseCase
import com.jacekpietras.zoo.domain.feature.sensors.interactor.ObserveUserPositionWithAccuracyUseCase
import com.jacekpietras.zoo.domain.feature.sensors.interactor.StartCompassUseCase
import com.jacekpietras.zoo.domain.feature.sensors.interactor.StartNavigationUseCase
import com.jacekpietras.zoo.domain.feature.sensors.interactor.StopCompassUseCase
import com.jacekpietras.zoo.domain.feature.sensors.interactor.UploadHistoryUseCase
import com.jacekpietras.zoo.domain.interactor.FindNearRegionWithDistanceUseCase
import com.jacekpietras.zoo.domain.interactor.GetAnimalsInRegionUseCase
import com.jacekpietras.zoo.domain.interactor.GetRegionUseCase
import com.jacekpietras.zoo.domain.interactor.GetRegionsContainingPointUseCase
import com.jacekpietras.zoo.domain.interactor.LoadVisitedRouteUseCase
import com.jacekpietras.zoo.domain.interactor.ObserveRegionsWithAnimalsInUserPositionUseCase
import com.jacekpietras.zoo.domain.interactor.ObserveSuggestedThemeTypeUseCase
import com.jacekpietras.zoo.domain.interactor.ObserveTakenRouteUseCase
import com.jacekpietras.zoo.domain.interactor.ObserveVisitedRoadsUseCase
import com.jacekpietras.zoo.domain.model.Region
import com.jacekpietras.zoo.domain.model.RegionId
import com.jacekpietras.zoo.map.BuildConfig
import com.jacekpietras.zoo.map.R
import com.jacekpietras.zoo.map.extensions.applyToMap
import com.jacekpietras.zoo.map.extensions.combine
import com.jacekpietras.zoo.map.extensions.combineWithIgnoredFlow
import com.jacekpietras.zoo.map.extensions.reduce
import com.jacekpietras.zoo.map.extensions.stateFlowOf
import com.jacekpietras.zoo.map.mapper.MapViewStateMapper
import com.jacekpietras.zoo.map.model.BitmapLibrary
import com.jacekpietras.zoo.map.model.MapAction
import com.jacekpietras.zoo.map.model.MapEffect
import com.jacekpietras.zoo.map.model.MapEffect.ShowToast
import com.jacekpietras.zoo.map.model.MapState
import com.jacekpietras.zoo.map.model.MapToolbarMode.AroundYouMapActionMode
import com.jacekpietras.zoo.map.model.MapToolbarMode.NavigableMapActionMode
import com.jacekpietras.zoo.map.model.MapToolbarMode.SelectedAnimalMode
import com.jacekpietras.zoo.map.model.MapToolbarMode.SelectedRegionMode
import com.jacekpietras.zoo.map.model.MapViewState
import com.jacekpietras.zoo.map.model.MapVolatileState
import com.jacekpietras.zoo.map.model.MapVolatileViewState
import com.jacekpietras.zoo.map.model.MapWorldViewState
import com.jacekpietras.zoo.map.model.PlanState
import com.jacekpietras.zoo.map.router.MapRouter
import com.jacekpietras.zoo.tracking.permissions.GpsPermissionRequester
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
@OptIn(FlowPreview::class)
internal class MapViewModel(
context: Context,
animalId: String?,
regionId: String?,
private val mapper: MapViewStateMapper,
observeCompassUseCase: ObserveCompassUseCase,
observeSuggestedThemeTypeUseCase: ObserveSuggestedThemeTypeUseCase,
observeCurrentPlanPathUseCase: ObserveCurrentPlanPathWithOptimizationUseCase,
private val observeUserPositionWithAccuracyUseCase: ObserveUserPositionWithAccuracyUseCase,
private val stopCompassUseCase: StopCompassUseCase,
private val startCompassUseCase: StartCompassUseCase,
private val startNavigationUseCase: StartNavigationUseCase,
observeMapObjectsUseCase: ObserveMapObjectsUseCase,
observeTakenRouteUseCase: ObserveTakenRouteUseCase,
observeVisitedRoadsUseCase: ObserveVisitedRoadsUseCase,
observeAnimalFavoritesUseCase: ObserveAnimalFavoritesUseCase,
loadMapUseCase: LoadMapUseCase,
loadVisitedRouteUseCase: LoadVisitedRouteUseCase,
observeRegionsWithAnimalsInUserPositionUseCase: ObserveRegionsWithAnimalsInUserPositionUseCase,
private val observeOutsideWorldEventUseCase: ObserveOutsideWorldEventUseCase,
private val observeArrivalAtRegionEventUseCase: ObserveArrivalAtRegionEventUseCase,
private val getAnimalsInRegionUseCase: GetAnimalsInRegionUseCase,
private val getRegionsContainingPointUseCase: GetRegionsContainingPointUseCase,
private val getAnimalUseCase: GetAnimalUseCase,
private val findNearRegionWithDistance: FindNearRegionWithDistanceUseCase,
private val getRegionUseCase: GetRegionUseCase,
private val uploadHistoryUseCase: UploadHistoryUseCase,
private val getShortestPathUseCase: GetShortestPathFromUserUseCase,
) : ViewModel() {
private val paintBaker = ComposablePaintBaker(context)
private val _effects = MutableStateFlow<List<MapEffect>>(emptyList())
val effects: Flow<Unit> = _effects
.filter(List<MapEffect>::isNotEmpty)
.map { /* Unit */ }
private val mapLogic: MapViewLogic<ComposablePaint> = makeComposableMapLogic()
val mapList = MutableStateFlow<List<RenderItem<ComposablePaint>>>(emptyList())
private val mapColors = MutableStateFlow(MapColors())
private val bitmapLibrary = stateFlowOf { BitmapLibrary(context) }
private val observeTakenRoute = if (BuildConfig.DEBUG) {
observeTakenRouteUseCase.run()
} else {
flow { /* Unit */ }
}
private val observeCurrentPlanPath = observeCurrentPlanPathUseCase.run()
.onEach { plan ->
val distance = plan.distanceToNextStage
val nextStageRegion = plan.nextStageRegion
if (plan.stages.isNotEmpty() && distance != null && nextStageRegion != null) {
launchInBackground {
state.reduce {
copy(
planState = PlanState(
distance = distance,
nextStageRegion = nextStageRegion,
),
)
}
}
} else {
state.reduce {
copy(
planState = null,
)
}
}
}
private val volatileState = MutableStateFlow(MapVolatileState())
private val volatileViewState: Flow<MapVolatileViewState> = combine(
volatileState,
mapColors,
observeCurrentPlanPath,
observeVisitedRoadsUseCase.run(),
observeTakenRoute,
observeCompassUseCase.run(),
mapper::from,
)
.debounce(50L)
.flowOnBackground()
.onEach(mapLogic::applyToMap)
.flowOnMain()
private val mapWorldViewState: Flow<MapWorldViewState> = combine(
mapColors,
bitmapLibrary.filterNotNull(),
observeMapObjectsUseCase.run(),
mapper::from,
)
.debounce(50L)
.flowOnBackground()
.onEach(mapLogic::applyToMap)
.flowOnMain()
private val state = MutableStateFlow(MapState())
val viewState: Flow<MapViewState> = combine(
state,
observeSuggestedThemeTypeUseCase.run(),
observeRegionsWithAnimalsInUserPositionUseCase.run(),
observeAnimalFavoritesUseCase.run(),
mapper::from,
)
.combineWithIgnoredFlow(userPositionObservation())
.combineWithIgnoredFlow(outsideWorldEventObservation())
.combineWithIgnoredFlow(arrivalAtRegionEventObservation())
.combineWithIgnoredFlow(volatileViewState)
.combineWithIgnoredFlow(mapWorldViewState)
.flowOnBackground()
init {
launchInBackground {
loadMapUseCase.run()
animalId.toAnimalId()?.let { animalId ->
centerAtUserPosition()
navigationToAnimal(getAnimalUseCase.run(animalId), regionId.toRegionId())
}
loadVisitedRouteUseCase.run()
}
}
override fun onCleared() {
super.onCleared()
bitmapLibrary.value?.recycle()
}
private fun String?.toAnimalId(): AnimalId? =
this?.takeIf { it.isNotBlank() }
?.takeIf { it != "null" }
?.let(::AnimalId)
private fun String?.toRegionId(): RegionId? =
this?.takeIf { it.isNotBlank() }
?.takeIf { it != "null" }
?.let(::RegionId)
private suspend fun navigationToAnimal(animal: AnimalEntity, regionId: RegionId?) {
val regionIds = if (regionId != null) {
listOf(regionId)
} else {
animal.regionInZoo
}
val (shortestPath, distance) = findNearRegionWithDistance.run { it.id in regionIds } ?: return
state.reduce {
copy(
toolbarMode = SelectedAnimalMode(
animal = animal,
distance = distance,
regionId = regionId,
),
isToolbarOpened = true,
)
}
volatileState.reduce {
copy(
snappedPoint = shortestPath.last(),
shortestPath = shortestPath,
)
}
}
private fun onUploadClicked() {
try {
uploadHistoryUseCase.run()
} catch (ignored: UploadHistoryUseCase.UploadFailed) {
sendEffect(ShowToast(RichText("Upload failed")))
}
}
private fun onStopCentering() {
stopCompassUseCase.run()
}
private fun onStartCentering() {
startCompassUseCase.run()
}
private fun onPointPlaced(point: PointD) {
volatileState.reduce { copy(snappedPoint = point) }
launchInBackground {
val regionsAndAnimalsJob = async {
getRegionsContainingPointUseCase.run(point)
.map { region -> region to getAnimalsInRegionUseCase.run(region.id) }
}
val shortestPathJob = async { getShortestPathUseCase.run(point) }
val regionsAndAnimals = regionsAndAnimalsJob.await()
if (regionsAndAnimals.isEmpty() || regionsAndAnimals.none(::canNavigateToIt)) {
closeToolbar()
} else {
val shortestPath = shortestPathJob.await()
state.reduce {
copy(
toolbarMode = SelectedRegionMode(regionsAndAnimals),
isToolbarOpened = true,
)
}
volatileState.reduce { copy(shortestPath = shortestPath) }
}
}
}
private fun closeToolbar() {
state.reduce {
copy(isToolbarOpened = false)
}
volatileState.reduce {
copy(
snappedPoint = null,
shortestPath = emptyList()
)
}
}
fun onLocationButtonClicked(permissionChecker: GpsPermissionRequester) {
permissionChecker.checkPermissions(
onDenied = { onLocationDenied() },
onGranted = {
startNavigationUseCase.run()
centerAtUserPosition()
},
)
}
private fun onLocationDenied() {
sendEffect(ShowToast(RichText(R.string.location_denied)))
}
fun onCameraButtonClicked(router: MapRouter) {
router.navigateToCamera()
}
fun onRegionClicked(router: MapRouter, permissionChecker: GpsPermissionRequester, regionId: RegionId) {
launchInBackground {
val (region, _) = getRegionUseCase.run(regionId)
if (region is Region.AnimalRegion) {
onMain {
router.navigateToAnimalList(regionId)
}
} else {
permissionChecker.checkPermissions(
onDenied = { onLocationDenied() },
onGranted = {
startNavigationUseCase.run()
startNavigationToRegion(region)
},
)
}
}
}
fun onCloseClicked() {
closeToolbar()
}
fun onBackClicked(router: MapRouter) {
if (state.value.isToolbarOpened) {
closeToolbar()
} else {
router.goBack()
}
}
fun onMapActionClicked(mapAction: MapAction) {
centerAtUserPosition()
when (mapAction) {
MapAction.AROUND_YOU -> {
state.reduce {
copy(
toolbarMode = AroundYouMapActionMode(mapAction),
isToolbarOpened = true,
)
}
}
MapAction.UPLOAD -> {
onUploadClicked()
}
else -> {
launchInBackground { startNavigationToNearestRegion(mapAction) }
}
}
}
private fun startNavigationToRegion(region: Region) {
launchInBackground {
val mapAction = when (region) {
is Region.RestaurantRegion -> MapAction.RESTAURANT
is Region.ExitRegion -> MapAction.EXIT
is Region.WcRegion -> MapAction.WC
else -> throw IllegalStateException("Don't expect navigation to $region")
}
val nearWithDistance = findNearRegionWithDistance.run { it == region }
startNavigationToActionWithPath(mapAction, nearWithDistance)
}
}
private suspend fun startNavigationToNearestRegion(mapAction: MapAction) {
val nearWithDistance = when (mapAction) {
MapAction.WC -> findNearRegionWithDistance<Region.WcRegion>()
MapAction.RESTAURANT -> findNearRegionWithDistance<Region.RestaurantRegion>()
MapAction.EXIT -> findNearRegionWithDistance<Region.ExitRegion>()
else -> throw IllegalStateException("Don't expect navigation to $mapAction")
}
startNavigationToActionWithPath(mapAction, nearWithDistance)
}
private suspend fun startNavigationToActionWithPath(
mapAction: MapAction,
nearWithDistance: Pair<List<PointD>, Double>?,
) {
onMain {
if (nearWithDistance != null) {
val (path, distance) = nearWithDistance
if (path.size > 1) {
state.reduce {
copy(
toolbarMode = NavigableMapActionMode(
mapAction = mapAction,
path = path,
distance = distance,
),
isToolbarOpened = true,
)
}
volatileState.reduce {
copy(
snappedPoint = path.last(),
shortestPath = path,
)
}
} else {
closeToolbarOnUnAccessibleMapAction(mapAction)
}
} else {
closeToolbarOnUnAccessibleMapAction(mapAction)
}
}
}
private fun closeToolbarOnUnAccessibleMapAction(mapAction: MapAction) {
state.reduce {
copy(
isToolbarOpened = false,
)
}
sendEffect(ShowToast(RichText.Res(R.string.cannot_find_near, RichText(mapAction.title))))
}
private suspend inline fun <reified T> findNearRegionWithDistance(): Pair<List<PointD>, Double>? =
findNearRegionWithDistance.run { it is T }
fun onAnimalClicked(router: MapRouter, animalId: AnimalId) {
router.navigateToAnimal(animalId)
}
fun onStopEvent() {
stopCompassUseCase.run()
}
fun consumeEffect(): MapEffect {
val removed = _effects.value.first()
_effects.value = _effects.value.drop(1)
return removed
}
private fun sendEffect(effect: MapEffect) {
_effects.value = _effects.value + effect
}
private fun userPositionObservation() =
observeUserPositionWithAccuracyUseCase.run()
.onEach {
val point = PointD(it.lon, it.lat)
volatileState.reduce { copy(userPosition = point, userPositionAccuracy = it.accuracy) }
state.reduce { copy(userPosition = point) }
with(state.value) {
if (isToolbarOpened) {
when (toolbarMode) {
is NavigableMapActionMode -> startNavigationToNearestRegion(toolbarMode.mapAction)
is SelectedAnimalMode -> navigationToAnimal(toolbarMode.animal, toolbarMode.regionId)
else -> Unit
}
}
}
}
.flowOnBackground()
private fun outsideWorldEventObservation() =
observeOutsideWorldEventUseCase.run()
.onEach {
when (state.value.toolbarMode) {
is NavigableMapActionMode,
is AroundYouMapActionMode,
is SelectedAnimalMode -> state.reduce {
copy(
toolbarMode = null,
isToolbarOpened = false,
)
}
else -> Unit
}
volatileState.reduce { copy(userPosition = PointD()) }
state.reduce { copy(userPosition = PointD()) }
sendEffect(ShowToast(RichText(R.string.outside_world_warning)))
}
private fun arrivalAtRegionEventObservation() =
observeArrivalAtRegionEventUseCase.run()
.onEach { region ->
val regionsAndAnimals = listOf(region to getAnimalsInRegionUseCase.run(region.id))
state.reduce {
copy(
toolbarMode = SelectedRegionMode(regionsAndAnimals),
isToolbarOpened = true,
)
}
}
.flowOnBackground()
fun fillColors(colors: MapColors) {
mapList.value = emptyList()
mapColors.value = colors
}
private fun makeComposableMapLogic() = MapViewLogic(
invalidate = { mapList.value = it },
paintBaker = paintBaker,
setOnPointPlacedListener = ::onPointPlaced,
onStopCentering = ::onStopCentering,
onStartCentering = ::onStartCentering,
)
private fun centerAtUserPosition() {
mapLogic.centerAtUserPosition()
}
fun onSizeChanged(width: Int, height: Int) {
mapLogic.onSizeChanged(width, height)
}
fun onClick(x: Float, y: Float) {
mapLogic.onClick(x, y)
}
fun onTransform(cX: Float, cY: Float, scale: Float, rotate: Float, vX: Float, vY: Float) {
trans = System.nanoTime()
mapLogic.onTransform(cX, cY, scale, rotate, vX, vY)
}
private fun canNavigateToIt(regionWithAnimals: Pair<Region, List<AnimalEntity>>): Boolean {
val (region, animals) = regionWithAnimals
return when (region) {
is Region.AnimalRegion -> animals.isNotEmpty()
is Region.WcRegion -> true
is Region.ExitRegion -> true
is Region.RestaurantRegion -> true
}
}
}
| 0 | Kotlin | 1 | 2 | e6a689f442cc32d19ee3f51efc49bf49f9969ca8 | 21,154 | ZOO | MIT License |
build/assets/compose/vitaminassets/payments/PaysafeCard.kt | Decathlon | 511,157,831 | false | {"Kotlin": 4443549, "HTML": 226066, "Swift": 163852, "TypeScript": 60822, "CSS": 53872, "JavaScript": 33103, "Handlebars": 771} | package com.decathlon.vitamin.compose.vitaminassets.payments
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.decathlon.vitamin.compose.vitaminassets.PaymentsGroup
public val PaymentsGroup.PaysafeCard: ImageVector
get() {
if (_paysafeCard != null) {
return _paysafeCard!!
}
_paysafeCard = Builder(name = "PaysafeCard", defaultWidth = 58.0.dp, defaultHeight =
40.0.dp, viewportWidth = 58.0f, viewportHeight = 40.0f).apply {
path(fill = SolidColor(Color(0xFFFFFFFF)), stroke = SolidColor(Color(0xFFF3F3F3)),
strokeLineWidth = 1.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(4.0f, 0.5f)
lineTo(54.0f, 0.5f)
arcTo(3.5f, 3.5f, 0.0f, false, true, 57.5f, 4.0f)
lineTo(57.5f, 36.0f)
arcTo(3.5f, 3.5f, 0.0f, false, true, 54.0f, 39.5f)
lineTo(4.0f, 39.5f)
arcTo(3.5f, 3.5f, 0.0f, false, true, 0.5f, 36.0f)
lineTo(0.5f, 4.0f)
arcTo(3.5f, 3.5f, 0.0f, false, true, 4.0f, 0.5f)
close()
}
path(fill = SolidColor(Color(0xFF008ACA)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd) {
moveTo(32.3786f, 17.7964f)
curveTo(32.3855f, 17.4888f, 32.5006f, 17.2418f, 32.7261f, 17.0565f)
curveTo(32.9448f, 16.8685f, 33.2319f, 16.7717f, 33.5871f, 16.7664f)
horizontalLineTo(34.3016f)
verticalLineTo(17.8673f)
horizontalLineTo(33.8691f)
curveTo(33.6313f, 17.8726f, 33.5097f, 17.9849f, 33.5048f, 18.2014f)
verticalLineTo(18.4428f)
horizontalLineTo(34.3016f)
verticalLineTo(19.5835f)
horizontalLineTo(33.5048f)
verticalLineTo(22.947f)
horizontalLineTo(32.3786f)
verticalLineTo(17.7964f)
close()
moveTo(12.3097f, 19.8559f)
curveTo(12.3041f, 19.6792f, 12.2196f, 19.588f, 12.0553f, 19.5821f)
horizontalLineTo(11.1791f)
curveTo(10.9714f, 19.5945f, 10.8646f, 19.7067f, 10.8593f, 19.9175f)
verticalLineTo(21.4716f)
curveTo(10.8646f, 21.6894f, 10.9828f, 21.8004f, 11.2135f, 21.8067f)
horizontalLineTo(12.0163f)
curveTo(12.0999f, 21.8067f, 12.1693f, 21.7761f, 12.2246f, 21.7138f)
curveTo(12.2823f, 21.6671f, 12.3097f, 21.6069f, 12.3097f, 21.5324f)
verticalLineTo(19.8559f)
close()
moveTo(9.7341f, 19.6352f)
curveTo(9.7398f, 19.2465f, 9.8277f, 18.951f, 9.9982f, 18.7489f)
curveTo(10.0873f, 18.6644f, 10.1992f, 18.5935f, 10.335f, 18.535f)
curveTo(10.476f, 18.4726f, 10.6127f, 18.4425f, 10.7455f, 18.4425f)
horizontalLineTo(12.3541f)
curveTo(13.0637f, 18.4485f, 13.4244f, 18.831f, 13.4359f, 19.591f)
verticalLineTo(21.9299f)
curveTo(13.4305f, 22.1997f, 13.3235f, 22.4338f, 13.116f, 22.6297f)
curveTo(12.9111f, 22.8353f, 12.6659f, 22.9401f, 12.3806f, 22.9464f)
horizontalLineTo(10.8593f)
verticalLineTo(24.6327f)
horizontalLineTo(9.7341f)
verticalLineTo(19.6352f)
close()
moveTo(15.4671f, 21.5811f)
curveTo(15.4671f, 21.6461f, 15.4973f, 21.6976f, 15.5572f, 21.7361f)
curveTo(15.61f, 21.7826f, 15.6767f, 21.8067f, 15.7611f, 21.8067f)
horizontalLineTo(16.6256f)
curveTo(16.8212f, 21.8067f, 16.9224f, 21.7321f, 16.928f, 21.5811f)
verticalLineTo(21.2629f)
curveTo(16.928f, 21.0893f, 16.8248f, 21.0017f, 16.6173f, 21.0017f)
horizontalLineTo(15.7611f)
curveTo(15.6487f, 21.0017f, 15.5708f, 21.0201f, 15.5274f, 21.055f)
curveTo(15.4874f, 21.0961f, 15.4671f, 21.1774f, 15.4671f, 21.298f)
verticalLineTo(21.5811f)
close()
moveTo(16.928f, 19.8285f)
curveTo(16.9337f, 19.658f, 16.8332f, 19.5765f, 16.6253f, 19.5821f)
horizontalLineTo(14.3587f)
verticalLineTo(18.4425f)
horizontalLineTo(16.9108f)
curveTo(17.654f, 18.4543f, 18.0313f, 18.8086f, 18.0439f, 19.5073f)
verticalLineTo(21.8911f)
curveTo(18.0377f, 22.1927f, 17.9441f, 22.4412f, 17.7624f, 22.6389f)
curveTo(17.5722f, 22.8436f, 17.3273f, 22.9464f, 17.0271f, 22.9464f)
horizontalLineTo(15.4845f)
curveTo(14.7337f, 22.9401f, 14.3532f, 22.6024f, 14.3416f, 21.9307f)
verticalLineTo(21.0109f)
curveTo(14.3473f, 20.3089f, 14.7112f, 19.9523f, 15.4312f, 19.94f)
horizontalLineTo(16.928f)
verticalLineTo(19.8285f)
close()
moveTo(21.4339f, 23.3993f)
curveTo(21.3709f, 23.4559f, 21.2941f, 23.4877f, 21.2048f, 23.493f)
horizontalLineTo(18.9584f)
verticalLineTo(24.6327f)
horizontalLineTo(21.5853f)
curveTo(21.9114f, 24.627f, 22.167f, 24.513f, 22.3544f, 24.2899f)
curveTo(22.5384f, 24.0669f, 22.6342f, 23.7728f, 22.6403f, 23.4056f)
verticalLineTo(18.4425f)
horizontalLineTo(21.5244f)
verticalLineTo(21.5249f)
curveTo(21.5244f, 21.5985f, 21.4914f, 21.6612f, 21.4248f, 21.7138f)
curveTo(21.3562f, 21.7761f, 21.2741f, 21.8067f, 21.1797f, 21.8067f)
horizontalLineTo(20.3854f)
curveTo(20.1835f, 21.8067f, 20.0838f, 21.6865f, 20.0838f, 21.4457f)
verticalLineTo(18.4425f)
horizontalLineTo(18.9584f)
verticalLineTo(21.8067f)
curveTo(18.9584f, 21.9903f, 18.9844f, 22.1431f, 19.0359f, 22.263f)
curveTo(19.0849f, 22.3942f, 19.1658f, 22.5199f, 19.2784f, 22.6399f)
curveTo(19.3969f, 22.7532f, 19.5151f, 22.833f, 19.6334f, 22.8759f)
curveTo(19.7455f, 22.9228f, 19.8957f, 22.9464f, 20.0838f, 22.9464f)
horizontalLineTo(21.5244f)
verticalLineTo(23.2171f)
curveTo(21.5244f, 23.2858f, 21.4942f, 23.3465f, 21.4339f, 23.3993f)
close()
moveTo(23.5239f, 21.8067f)
horizontalLineTo(25.5291f)
curveTo(25.7127f, 21.8004f, 25.8079f, 21.728f, 25.8136f, 21.5892f)
verticalLineTo(21.4867f)
curveTo(25.8136f, 21.4572f, 25.8045f, 21.4243f, 25.7871f, 21.3888f)
curveTo(25.7422f, 21.3028f, 25.6872f, 21.26f, 25.6218f, 21.26f)
horizontalLineTo(24.6277f)
curveTo(24.3326f, 21.2544f, 24.0808f, 21.1541f, 23.8692f, 20.9607f)
curveTo(23.6553f, 20.7822f, 23.5455f, 20.5624f, 23.5393f, 20.3045f)
verticalLineTo(19.4547f)
curveTo(23.551f, 18.7918f, 23.9163f, 18.4543f, 24.6359f, 18.4425f)
horizontalLineTo(26.9616f)
verticalLineTo(19.5821f)
horizontalLineTo(24.9914f)
curveTo(24.76f, 19.5821f, 24.6437f, 19.652f, 24.6437f, 19.7912f)
verticalLineTo(19.9017f)
curveTo(24.6437f, 20.0463f, 24.7627f, 20.1186f, 25.0f, 20.1186f)
horizontalLineTo(25.9909f)
curveTo(26.2552f, 20.1247f, 26.4801f, 20.2243f, 26.6678f, 20.4186f)
curveTo(26.8573f, 20.6144f, 26.9556f, 20.8473f, 26.9616f, 21.1176f)
verticalLineTo(21.949f)
curveTo(26.9556f, 22.1824f, 26.846f, 22.4155f, 26.6351f, 22.6479f)
curveTo(26.5323f, 22.762f, 26.4272f, 22.8406f, 26.3221f, 22.8849f)
curveTo(26.2132f, 22.9257f, 26.0655f, 22.9464f, 25.8765f, 22.9464f)
horizontalLineTo(23.5239f)
verticalLineTo(21.8067f)
close()
moveTo(28.9785f, 21.7361f)
curveTo(28.9176f, 21.6976f, 28.8874f, 21.6461f, 28.8874f, 21.5811f)
verticalLineTo(21.298f)
curveTo(28.8874f, 21.1774f, 28.9084f, 21.0961f, 28.9484f, 21.055f)
curveTo(28.9915f, 21.0201f, 29.069f, 21.0017f, 29.1813f, 21.0017f)
horizontalLineTo(30.038f)
curveTo(30.245f, 21.0017f, 30.3494f, 21.0893f, 30.3494f, 21.2629f)
verticalLineTo(21.5811f)
curveTo(30.3436f, 21.7321f, 30.2428f, 21.8067f, 30.0472f, 21.8067f)
horizontalLineTo(29.1813f)
curveTo(29.098f, 21.8067f, 29.0309f, 21.7826f, 28.9785f, 21.7361f)
close()
moveTo(30.0457f, 19.5821f)
curveTo(30.2537f, 19.5765f, 30.3543f, 19.658f, 30.3494f, 19.8285f)
verticalLineTo(19.94f)
horizontalLineTo(28.852f)
curveTo(28.1311f, 19.9523f, 27.7677f, 20.3089f, 27.7627f, 21.0109f)
verticalLineTo(21.9307f)
curveTo(27.7732f, 22.6024f, 28.1543f, 22.9401f, 28.9045f, 22.9464f)
horizontalLineTo(30.448f)
curveTo(30.7487f, 22.9464f, 30.9939f, 22.8436f, 31.1828f, 22.6389f)
curveTo(31.3635f, 22.4412f, 31.4578f, 22.1927f, 31.4638f, 21.8911f)
verticalLineTo(19.5073f)
curveTo(31.4521f, 18.8086f, 31.0748f, 18.4543f, 30.3321f, 18.4425f)
horizontalLineTo(27.7797f)
verticalLineTo(19.5821f)
horizontalLineTo(30.0457f)
close()
moveTo(37.5023f, 19.7806f)
verticalLineTo(19.8072f)
lineTo(36.091f, 20.3311f)
verticalLineTo(19.8735f)
curveTo(36.091f, 19.7883f, 36.1307f, 19.7191f, 36.2086f, 19.6665f)
curveTo(36.2713f, 19.6097f, 36.3523f, 19.5821f, 36.4529f, 19.5821f)
horizontalLineTo(37.2361f)
curveTo(37.313f, 19.5821f, 37.3772f, 19.5993f, 37.4296f, 19.6352f)
curveTo(37.4782f, 19.6723f, 37.5023f, 19.722f, 37.5023f, 19.7806f)
close()
moveTo(36.109f, 21.4889f)
verticalLineTo(21.418f)
lineTo(38.6476f, 20.4341f)
verticalLineTo(19.5331f)
curveTo(38.6363f, 18.8175f, 38.2812f, 18.4543f, 37.5804f, 18.4425f)
horizontalLineTo(36.0634f)
curveTo(35.3458f, 18.4543f, 34.9806f, 18.8051f, 34.968f, 19.4944f)
lineTo(34.9776f, 21.7752f)
curveTo(34.9776f, 21.993f, 35.0006f, 22.1679f, 35.047f, 22.2995f)
curveTo(35.0894f, 22.4259f, 35.1737f, 22.5487f, 35.2974f, 22.6695f)
curveTo(35.4032f, 22.7689f, 35.5245f, 22.8406f, 35.6594f, 22.8843f)
curveTo(35.7831f, 22.9257f, 35.9576f, 22.9464f, 36.1819f, 22.9464f)
horizontalLineTo(38.64f)
verticalLineTo(21.8067f)
horizontalLineTo(36.3283f)
curveTo(36.2649f, 21.8067f, 36.2173f, 21.7725f, 36.1819f, 21.7052f)
curveTo(36.133f, 21.6527f, 36.109f, 21.5802f, 36.109f, 21.4889f)
close()
moveTo(41.0297f, 22.9464f)
curveTo(40.8592f, 22.9464f, 40.7037f, 22.9311f, 40.5627f, 22.9027f)
curveTo(40.4148f, 22.879f, 40.2674f, 22.8113f, 40.1168f, 22.6974f)
curveTo(39.9623f, 22.5647f, 39.8557f, 22.4162f, 39.7971f, 22.2518f)
curveTo(39.7353f, 22.0904f, 39.7053f, 21.9076f, 39.7053f, 21.7017f)
verticalLineTo(19.5749f)
curveTo(39.6991f, 19.4016f, 39.7167f, 19.2492f, 39.7578f, 19.1173f)
curveTo(39.7958f, 18.9853f, 39.8752f, 18.8564f, 39.9953f, 18.73f)
curveTo(40.1323f, 18.5973f, 40.272f, 18.5091f, 40.4198f, 18.4658f)
curveTo(40.5616f, 18.4307f, 40.7216f, 18.4131f, 40.901f, 18.4131f)
horizontalLineTo(42.6255f)
verticalLineTo(18.6795f)
horizontalLineTo(40.9409f)
curveTo(40.6435f, 18.6795f, 40.4097f, 18.7398f, 40.2387f, 18.8603f)
curveTo(40.0637f, 18.9921f, 39.9748f, 19.2188f, 39.9748f, 19.5384f)
verticalLineTo(21.6666f)
curveTo(39.9748f, 21.8163f, 39.9978f, 21.9618f, 40.0441f, 22.1024f)
curveTo(40.0913f, 22.2406f, 40.1698f, 22.3617f, 40.283f, 22.4675f)
curveTo(40.4054f, 22.5593f, 40.5277f, 22.6166f, 40.6467f, 22.6399f)
curveTo(40.771f, 22.6669f, 40.9039f, 22.6796f, 41.0452f, 22.6796f)
horizontalLineTo(42.6528f)
verticalLineTo(22.9464f)
horizontalLineTo(41.0297f)
close()
moveTo(44.8004f, 20.1872f)
horizontalLineTo(47.0616f)
verticalLineTo(21.786f)
curveTo(47.0616f, 22.3763f, 46.7732f, 22.6737f, 46.2007f, 22.6796f)
horizontalLineTo(44.8307f)
curveTo(44.5943f, 22.6796f, 44.378f, 22.6007f, 44.1826f, 22.4412f)
curveTo(44.0705f, 22.3536f, 43.9995f, 22.2518f, 43.9711f, 22.1379f)
curveTo(43.9424f, 22.0295f, 43.9285f, 21.9092f, 43.9285f, 21.7776f)
verticalLineTo(21.0988f)
curveTo(43.9285f, 20.8176f, 44.0066f, 20.596f, 44.1647f, 20.4348f)
curveTo(44.3177f, 20.2759f, 44.5294f, 20.1934f, 44.8004f, 20.1872f)
close()
moveTo(47.2946f, 22.1734f)
curveTo(47.317f, 22.0413f, 47.3302f, 21.8908f, 47.3302f, 21.7197f)
verticalLineTo(19.6763f)
curveTo(47.3346f, 19.3329f, 47.2334f, 19.0284f, 47.0257f, 18.7642f)
curveTo(46.957f, 18.6739f, 46.883f, 18.605f, 46.804f, 18.5578f)
curveTo(46.729f, 18.5083f, 46.6479f, 18.4741f, 46.5585f, 18.4567f)
curveTo(46.3854f, 18.4278f, 46.1938f, 18.4131f, 45.9821f, 18.4131f)
horizontalLineTo(43.6657f)
verticalLineTo(18.6795f)
horizontalLineTo(46.109f)
curveTo(46.2649f, 18.6795f, 46.4047f, 18.6958f, 46.5293f, 18.7277f)
curveTo(46.6525f, 18.7696f, 46.7609f, 18.8502f, 46.8526f, 18.9712f)
curveTo(46.9972f, 19.1574f, 47.0697f, 19.3741f, 47.0697f, 19.621f)
verticalLineTo(19.9212f)
horizontalLineTo(44.83f)
curveTo(44.0598f, 19.9393f, 43.6688f, 20.3352f, 43.6575f, 21.109f)
verticalLineTo(21.7944f)
curveTo(43.6575f, 22.1552f, 43.771f, 22.4364f, 43.995f, 22.6389f)
curveTo(44.2144f, 22.8436f, 44.4977f, 22.9464f, 44.8468f, 22.9464f)
horizontalLineTo(46.1915f)
curveTo(46.5406f, 22.9527f, 46.8336f, 22.833f, 47.0697f, 22.5876f)
curveTo(47.1832f, 22.4559f, 47.2581f, 22.3173f, 47.2946f, 22.1734f)
close()
moveTo(49.8589f, 18.6795f)
curveTo(49.2316f, 18.6912f, 48.9226f, 19.0284f, 48.9344f, 19.6923f)
verticalLineTo(22.9464f)
horizontalLineTo(48.6649f)
verticalLineTo(19.6934f)
curveTo(48.6524f, 18.8394f, 49.0646f, 18.4131f, 49.9022f, 18.4131f)
horizontalLineTo(50.2016f)
verticalLineTo(18.6795f)
horizontalLineTo(49.8589f)
close()
moveTo(52.2824f, 18.681f)
horizontalLineTo(54.4137f)
verticalLineTo(21.6682f)
curveTo(54.4063f, 22.0356f, 54.2944f, 22.2936f, 54.0743f, 22.443f)
curveTo(53.8556f, 22.6024f, 53.5708f, 22.6813f, 53.2229f, 22.6813f)
horizontalLineTo(52.2912f)
curveTo(52.1382f, 22.6813f, 51.9998f, 22.6651f, 51.8754f, 22.6326f)
curveTo(51.7503f, 22.6031f, 51.6392f, 22.5593f, 51.5378f, 22.5009f)
curveTo(51.3323f, 22.3748f, 51.2309f, 22.1401f, 51.2309f, 21.7952f)
verticalLineTo(19.7204f)
curveTo(51.2246f, 19.5593f, 51.2423f, 19.4213f, 51.2817f, 19.3062f)
curveTo(51.3117f, 19.1921f, 51.3823f, 19.078f, 51.4947f, 18.9629f)
curveTo(51.6121f, 18.8365f, 51.7374f, 18.7589f, 51.8672f, 18.73f)
curveTo(51.9913f, 18.6979f, 52.1289f, 18.681f, 52.2824f, 18.681f)
close()
moveTo(53.2999f, 22.9483f)
curveTo(54.198f, 22.9661f, 54.659f, 22.5452f, 54.683f, 21.6865f)
verticalLineTo(16.9444f)
horizontalLineTo(54.4137f)
verticalLineTo(18.4144f)
horizontalLineTo(52.2988f)
curveTo(51.4182f, 18.4078f, 50.9726f, 18.8414f, 50.9609f, 19.7135f)
verticalLineTo(21.6497f)
curveTo(50.9545f, 21.8313f, 50.9726f, 21.9977f, 51.0138f, 22.147f)
curveTo(51.0445f, 22.2969f, 51.121f, 22.443f, 51.24f, 22.5876f)
curveTo(51.3982f, 22.7484f, 51.5627f, 22.8517f, 51.7344f, 22.8954f)
curveTo(51.901f, 22.9302f, 52.0898f, 22.9483f, 52.3008f, 22.9483f)
horizontalLineTo(53.2999f)
close()
}
path(fill = SolidColor(Color(0xFFE2001A)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd) {
moveTo(3.7482f, 18.184f)
curveTo(3.66f, 18.2029f, 3.5716f, 18.2328f, 3.4833f, 18.2712f)
curveTo(3.3441f, 18.3306f, 3.2259f, 18.4079f, 3.1224f, 18.4939f)
curveTo(3.1187f, 18.3805f, 3.1208f, 18.2723f, 3.128f, 18.1683f)
curveTo(3.1802f, 16.9637f, 4.1842f, 16.0f, 5.4176f, 16.0f)
curveTo(6.6154f, 16.0f, 7.5979f, 16.9065f, 7.7024f, 18.0616f)
curveTo(7.72f, 18.1946f, 7.7259f, 18.3361f, 7.7193f, 18.4829f)
curveTo(7.5564f, 18.3329f, 7.3473f, 18.2319f, 7.0944f, 18.1848f)
curveTo(6.9322f, 17.4204f, 6.245f, 16.8461f, 5.4211f, 16.8461f)
curveTo(4.5976f, 16.8461f, 3.9107f, 17.4197f, 3.7482f, 18.184f)
close()
moveTo(3.6011f, 18.535f)
curveTo(3.7422f, 18.4727f, 3.8792f, 18.4426f, 4.0116f, 18.4426f)
horizontalLineTo(6.7599f)
curveTo(7.4697f, 18.4486f, 7.8309f, 18.831f, 7.8422f, 19.591f)
verticalLineTo(21.7976f)
curveTo(7.8309f, 22.5564f, 7.4697f, 22.9402f, 6.7599f, 22.9464f)
horizontalLineTo(4.0116f)
curveTo(3.8792f, 22.9464f, 3.7422f, 22.9158f, 3.6011f, 22.8546f)
curveTo(3.4651f, 22.7956f, 3.3532f, 22.7249f, 3.264f, 22.6389f)
curveTo(3.0933f, 22.4378f, 3.006f, 22.1428f, 3.0f, 21.7531f)
verticalLineTo(19.6353f)
curveTo(3.006f, 19.2465f, 3.0933f, 18.951f, 3.264f, 18.7489f)
curveTo(3.3532f, 18.6644f, 3.4651f, 18.5936f, 3.6011f, 18.535f)
close()
}
}
.build()
return _paysafeCard!!
}
private var _paysafeCard: ImageVector? = null
| 25 | Kotlin | 5 | 33 | c2c9cfa43128d412b7b2841cabd76952a13db2e1 | 20,430 | vitamin-design | Apache License 2.0 |
infra/src/fanpoll/infra/auth/provider/UserRunAsAuth.kt | csieflyman | 359,559,498 | false | {"Kotlin": 737653, "JavaScript": 16441, "HTML": 5481, "PLpgSQL": 3891, "Dockerfile": 126} | /*
* Copyright (c) 2021. fanpoll All rights reserved.
*/
package fanpoll.infra.auth.provider
import fanpoll.infra.auth.AuthConst
import fanpoll.infra.auth.login.session.UserSession
import fanpoll.infra.auth.principal.PrincipalSource
import fanpoll.infra.auth.principal.UserPrincipal
import fanpoll.infra.auth.principal.UserRole
import fanpoll.infra.auth.principal.UserType
import fanpoll.infra.base.exception.RequestException
import fanpoll.infra.base.json.json
import fanpoll.infra.base.response.InfraResponseCode
import fanpoll.infra.base.tenant.TenantId
import fanpoll.infra.base.util.IdentifiableObject
import io.ktor.server.auth.*
import io.ktor.server.request.header
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.jsonObject
import java.util.*
data class UserRunAsAuthCredential(val runAsKey: String, val runAsToken: String) : Credential
data class UserRunAsToken(
val userType: UserType,
val userId: UUID,
val clientId: String? = null,
val sessionData: JsonObject? = null
) {
val value = "${userType.id}:$userId:${clientId ?: "?"}${sessionData?.let { ":${json.encodeToString(it)}" } ?: ""}"
}
data class UserRunAsAuthConfig(
val principalSource: PrincipalSource,
val runAsKey: String
)
class UserRunAsAuthProvider(config: Configuration) : AuthenticationProvider(config) {
companion object {
const val RUN_AS_TOKEN_HEADER_NAME = "runAs"
const val tokenPatternDescription = "userType:userId:clientId:sessionData(jsonObjectString)"
}
private val authConfigs: List<UserRunAsAuthConfig> = config.authConfigs
override suspend fun onAuthenticate(context: AuthenticationContext) {
val call = context.call
val apiKey = call.request.header(AuthConst.API_KEY_HEADER_NAME)
val runAsToken = call.request.header(RUN_AS_TOKEN_HEADER_NAME)
if (apiKey != null && runAsToken != null) {
val principal = (authenticationFunction)(call, UserRunAsAuthCredential(apiKey, runAsToken)) as UserPrincipal?
if (principal != null) {
context.principal(principal)
}
}
}
private val authenticationFunction: AuthenticationFunction<UserRunAsAuthCredential> = { credentials ->
var principal: UserPrincipal? = null
run loop@{
authConfigs.forEach { runAsConfig ->
if (runAsConfig.runAsKey == credentials.runAsKey) {
val token = parseRunAsToken(credentials.runAsToken)
val user = token.userType.findRunAsUserById(token.userId)
principal = UserPrincipal(
token.userType, token.userId,
user.roles, runAsConfig.principalSource,
token.clientId, user.tenantId, true
)
if (principal != null && token.sessionData != null)
principal!!.session = UserSession(principal!!, null, token.sessionData)
return@loop
}
}
}
if (principal != null) {
attributes.put(PrincipalSource.ATTRIBUTE_KEY, principal!!.source)
}
principal
}
private fun parseRunAsToken(text: String): UserRunAsToken {
return try {
val segments = text.split(":")
require(segments.size in 2..3)
val userType = UserType.lookup(segments[0])
val userId = UUID.fromString(segments[1])
val clientId = if (segments.size >= 3 && segments[2] != "?") segments[2] else null
val sessionData = if (segments.size >= 4)
json.parseToJsonElement(text.substring((0..2)
.sumOf { index -> segments[index].length } + 3)).jsonObject else null
UserRunAsToken(userType, userId, clientId, sessionData)
} catch (e: Exception) {
throw RequestException(InfraResponseCode.BAD_REQUEST_HEADER, "invalid runAs token value format => $tokenPatternDescription")
}
}
class Configuration constructor(providerName: String, val authConfigs: List<UserRunAsAuthConfig>) : Config(providerName) {
fun build() = UserRunAsAuthProvider(this)
}
}
fun AuthenticationConfig.runAs(providerName: String, authConfigs: List<UserRunAsAuthConfig>) {
val provider = UserRunAsAuthProvider.Configuration(providerName, authConfigs).build()
register(provider)
}
data class RunAsUser(
override val id: UUID,
val type: UserType,
val roles: Set<UserRole>? = null,
val tenantId: TenantId? = null
) : IdentifiableObject<UUID>() | 1 | Kotlin | 9 | 58 | 0336a40bc9a5a8501b7e8cc6aeebd2112e6b4431 | 4,677 | multi-projects-architecture-with-Ktor | MIT License |
protoc-plugin/src/main/kotlin/com/example/Main.kt | benjamin-bader | 756,684,407 | false | {"Kotlin": 1319} | package com.example
import com.google.protobuf.compiler.PluginProtos.CodeGeneratorRequest
import com.google.protobuf.compiler.PluginProtos.CodeGeneratorResponse
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.FileSpec
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.TypeSpec
fun main() {
val req = CodeGeneratorRequest.parseFrom(System.`in`)
val resp = generate(req)
resp.writeTo(System.out)
}
fun generate(req: CodeGeneratorRequest): CodeGeneratorResponse {
val resp = CodeGeneratorResponse.newBuilder()
val greetBuilder = FunSpec.builder("greet")
for (file in req.protoFileList) {
greetBuilder.addStatement("println(%S)", "Hello, ${file.name}!")
}
val typeSpec = TypeSpec.classBuilder("HelloWorld")
.addFunction(greetBuilder.build())
.build()
val fileSpec = FileSpec.builder("com.example.gen", "HelloWorld.kt")
fileSpec.addType(typeSpec)
resp.addFileBuilder()
.setName("HelloWorld.kt")
.setContent(fileSpec.build().toString())
return resp.build()
}
| 0 | Kotlin | 0 | 0 | 431578e43ad292c8df3e736dda5caeb122c97f88 | 1,214 | protoc-plugins-in-monorepo | MIT License |
compose/material3/material3/src/skikoMain/kotlin/androidx/compose/material3/l10n/Ja.kt | VexorMC | 838,305,267 | false | {"Kotlin": 104238872, "Java": 66757679, "C++": 9111230, "AIDL": 628952, "Python": 306842, "Shell": 199496, "Objective-C": 47117, "TypeScript": 38627, "HTML": 28384, "Swift": 21386, "Svelte": 20307, "ANTLR": 19860, "C": 15043, "CMake": 14435, "JavaScript": 6457, "GLSL": 3842, "CSS": 1760, "Batchfile": 295} | /*
* Copyright 2024 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.material3.l10n
import androidx.compose.material3.internal.Strings
import androidx.compose.material3.internal.Translations
@Suppress("UnusedReceiverParameter", "DuplicatedCode")
internal fun Translations.ja() = mapOf(
Strings.NavigationMenu to "ナビゲーションメニュー",
Strings.ExposedDropdownMenu to "プルダウン メニュー",
Strings.CloseDrawer to "ナビゲーションメニューを閉じる",
Strings.CloseSheet to "シートを閉じる",
Strings.DefaultErrorMessage to "入力値が無効です",
Strings.SliderRangeStart to "範囲の先頭",
Strings.SliderRangeEnd to "範囲の末尾",
Strings.Dialog to "ダイアログ",
Strings.MenuExpanded to "開いています",
Strings.MenuCollapsed to "閉じています",
Strings.ToggleDropdownMenu to "プルダウン メニューを切り替えます",
Strings.SnackbarDismiss to "閉じる",
Strings.SearchBarSearch to "検索",
Strings.SuggestionsAvailable to "検索候補は次のとおりです",
Strings.DatePickerTitle to "日付の選択",
Strings.DatePickerHeadline to "選択した日付",
Strings.DatePickerSwitchToYearSelection to "年の選択に切り替え",
Strings.DatePickerSwitchToDaySelection to "スワイプして年を選択するか、タップして日付の選択に戻ります",
Strings.DatePickerSwitchToNextMonth to "翌月に変更",
Strings.DatePickerSwitchToPreviousMonth to "前月に変更",
Strings.DatePickerNavigateToYearDescription to "年に移動 %1\$s",
Strings.DatePickerHeadlineDescription to "現在の選択: %1\$s",
Strings.DatePickerNoSelectionDescription to "なし",
Strings.DatePickerTodayDescription to "今日",
Strings.DatePickerYearPickerPaneTitle to "年の選択ツールの表示",
Strings.DateInputTitle to "日付の選択",
Strings.DateInputHeadline to "入力された日付",
Strings.DateInputLabel to "日付",
Strings.DateInputHeadlineDescription to "入力された日付: %1\$s",
Strings.DateInputNoInputDescription to "なし",
Strings.DateInputInvalidNotAllowed to "許可されない日付: %1\$s",
Strings.DateInputInvalidForPattern to "想定パターンと一致しない日付: %1\$s",
Strings.DateInputInvalidYearRange to "想定される年の範囲(%1\$s~%2\$s)から日付が外れています",
Strings.DatePickerSwitchToCalendarMode to "カレンダー入力モードに切り替え",
Strings.DatePickerSwitchToInputMode to "テキスト入力モードに切り替え",
Strings.DatePickerScrollToShowLaterYears to "これより後の年を表示するにはスクロールしてください",
Strings.DatePickerScrollToShowEarlierYears to "これより前の年を表示するにはスクロールしてください",
Strings.DateRangePickerTitle to "日付の選択",
Strings.DateRangePickerStartHeadline to "開始日",
Strings.DateRangePickerEndHeadline to "終了日",
Strings.DateRangePickerScrollToShowNextMonth to "翌月を表示するにはスクロールしてください",
Strings.DateRangePickerScrollToShowPreviousMonth to "前月を表示するにはスクロールしてください",
Strings.DateRangePickerDayInRange to "範囲内",
Strings.DateRangeInputTitle to "日付の入力",
Strings.DateRangeInputInvalidRangeInput to "入力された期間は無効です",
Strings.BottomSheetPaneTitle to "ボトムシート",
Strings.BottomSheetDragHandleDescription to "ドラッグ ハンドル",
Strings.BottomSheetPartialExpandDescription to "ボトムシートを折りたたみます",
Strings.BottomSheetDismissDescription to "ボトムシートを閉じます",
Strings.BottomSheetExpandDescription to "ボトムシートを開きます",
Strings.TooltipPaneDescription to "ツールチップ",
Strings.TooltipLongPressLabel to "ツールチップを表示",
Strings.TimePickerPM to "PM",
Strings.TimePickerAM to "AM",
Strings.TimePickerPeriodToggle to "午前または午後を選択",
Strings.TimePickerHourSelection to "時刻を選択",
Strings.TimePickerMinuteSelection to "分を選択",
Strings.TimePickerHourSuffix to "%1\$d 時",
Strings.TimePicker24HourSuffix to "%1\$d 時間",
Strings.TimePickerMinuteSuffix to "%1\$d 分",
Strings.TimePickerMinute to "分",
Strings.TimePickerHour to "時間",
Strings.TimePickerMinuteTextField to "(分単位)",
Strings.TimePickerHourTextField to "(時間単位)",
)
| 0 | Kotlin | 0 | 2 | 9730aa39ce1cafe408f28962a59b95b82c68587f | 4,177 | compose | Apache License 2.0 |
android/app/src/main/kotlin/dev/jideguru/travel/MainActivity.kt | IgnatMaldive | 451,200,095 | false | {"Dart": 26796, "CMake": 7236, "C++": 4051, "HTML": 3847, "C": 691, "Kotlin": 475, "Swift": 403, "Objective-C": 37} | package dev.jideguru.travel
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | Dart | 0 | 0 | 442ee6384d10ce8d4591f554c9b0de4381d2fb5d | 124 | Flutter-Districts-of-Barcelona | Do What The F*ck You Want To Public License |
chat-messaging-memory/src/main/kotlin/com/demo/chat/config/pubsub/memory/MemoryPubSubBeans.kt | marios-code-path | 181,180,043 | false | {"Kotlin": 924762, "Shell": 36602, "C": 3160, "HTML": 2714, "Starlark": 278} | package com.demo.chat.config.pubsub.memory
import com.demo.chat.config.PubSubServiceBeans
import com.demo.chat.domain.TypeUtil
import com.demo.chat.pubsub.memory.impl.MemoryTopicPubSubService
import com.demo.chat.service.core.TopicPubSubService
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.stereotype.Component
@Component
@ConditionalOnProperty(prefix = "app.service.core", name = ["pubsub"])
class MemoryPubSubBeans<T, V>(val typeUtil: TypeUtil<T>) : PubSubServiceBeans<T, String> {
override fun pubSubService(): TopicPubSubService<T, String> = MemoryTopicPubSubService()
} | 2 | Kotlin | 1 | 9 | 2ae59375cd44e8fb58093b0f24596fc3111fd447 | 641 | demo-chat | MIT License |
src/main/java/com/keithmackay/api/routes/EmailRouter.kt | kamackay | 204,213,721 | false | null | package com.keithmackay.api.routes
import com.google.inject.Inject
import com.google.inject.Injector
import com.google.inject.Singleton
import com.keithmackay.api.auth.RequestValidator
import com.keithmackay.api.tasks.GoodMorningTask
import com.keithmackay.api.utils.async
import io.javalin.apibuilder.ApiBuilder.path
@Singleton
class EmailRouter @Inject
internal constructor(
private val validator: RequestValidator,
private val injector: Injector
) : Router {
override fun routes() {
path("email") {
validator.securePost("/goodMorning", { ctx, doc, user ->
if (user.admin) {
async(this::sendEmail)
ctx.result("Sending Good Morning Email")
}
})
}
}
private fun sendEmail() {
injector.getInstance(GoodMorningTask::class.java).run()
}
override fun isHealthy() = true
} | 0 | Kotlin | 0 | 0 | ed48495da7f9eece9c0296276fb61bd241114678 | 850 | api | MIT License |
app/src/main/java/com/rance/chatui/record/CommonDialog.kt | whykeyzheng | 223,139,716 | false | null | package com.rance.chatui.record
import android.app.Dialog
import android.content.Context
import android.view.LayoutInflater
import android.view.Window
import android.view.WindowManager
import android.widget.TextView
import com.rance.chatui.R
/**
* author: daxiong
* created on: 2019-11-26 19:26
* -----------------------------------------------
* description:
* -----------------------------------------------
*/
class CommonDialog(context: Context, var title: String, var text: String, var block: ((action: Boolean) -> Unit)? = null) : Dialog(context, R.style.PayTypeDialogStyle) {
init {
requestWindowFeature(Window.FEATURE_NO_TITLE)
val view = LayoutInflater.from(context).inflate(R.layout.dialog_common_layout, null)
setContentView(view)
val window = window
if (window != null) {
window.decorView.setPadding(0, 0, 0, 0)
val lp = window.attributes
val d = window.windowManager.defaultDisplay // 获取屏幕宽、高度
lp.width = (d.width * 0.8).toInt()
lp.height = WindowManager.LayoutParams.WRAP_CONTENT
window.attributes = lp
}
val tvTitle = findViewById<TextView>(R.id.tv_title)
val tvContent = findViewById<TextView>(R.id.tv_content)
tvTitle.text = title
tvContent.text = text
view.findViewById<TextView>(R.id.tv_confirm).setOnClickListener {
block?.invoke(true)
dismiss()
}
view.findViewById<TextView>(R.id.tv_cancel).setOnClickListener {
block?.invoke(false)
dismiss()
}
}
} | 1 | null | 1 | 4 | e94815d3c484c9a3e1eefd0347d0e5d54682885e | 1,620 | lema_sdk_push | Apache License 2.0 |
simplified-books-core/src/main/java/org/nypl/simplified/books/core/AccountGetCachedCredentialsListenerType.kt | mattniehoff | 168,598,106 | true | {"Java": 1497763, "Kotlin": 367622, "HTML": 37450, "JavaScript": 8806, "CSS": 159} | package org.nypl.simplified.books.core
/**
* The type of listeners for receiving cached credentials.
*/
interface AccountGetCachedCredentialsListenerType {
/**
* The account is not logged in.
*/
fun onAccountIsNotLoggedIn()
/**
* The account is logged in with the given credentials.
*
* @param credentials The current credentials
*/
fun onAccountIsLoggedIn(credentials: AccountCredentials)
}
| 0 | Java | 0 | 0 | 1305a9660a1122116f301ae6edc7c25b75642970 | 427 | android | Apache License 2.0 |
app/src/main/java/top/wefor/randompicker/game/DiceActivity.kt | XunMengWinter | 66,621,019 | false | null | package top.wefor.randompicker.game
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.*
import top.wefor.randompicker.Calculator
import top.wefor.randompicker.IncrementCalculator
import top.wefor.randompicker.R
import top.wefor.randompicker.RandomPicker
/**
* 用 RandomPicker 实现各种随机机制
*/
class DiceActivity : AppCompatActivity() {
private lateinit var mRadioGroup: RadioGroup
private lateinit var mWeightLayout: ViewGroup
private lateinit var mSpinner: Spinner
private lateinit var mPercentTv: TextView
private lateinit var mBoardTv: TextView
private val mRandomPicker = RandomPicker()
private val mCriticalPos = 0
private var mTotal = 0
private var mCritical = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initView(savedInstanceState)
}
fun initView(savedInstanceState: Bundle?) {
setContentView(R.layout.activity_dice)
mRadioGroup = findViewById(R.id.candidate_layout)
mWeightLayout = findViewById(R.id.weight_layout)
mSpinner = findViewById(R.id.spinner)
mPercentTv = findViewById(R.id.percent_tv)
mBoardTv = findViewById(R.id.board_tv)
val spinnerList = arrayListOf<String>()
spinnerList.add("1. originWeight++ random") //默认随机
spinnerList.add("2. independent random") //独立随机。即"真随机"
spinnerList.add("3. Blizzard War3 critical random") //war3暴击随机
spinnerList.add("4. draw random: one by one") //翻牌随机:一次一张地翻
val adapter = ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, spinnerList)
mSpinner.adapter = adapter
mSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
run {
mRandomPicker.exitCutMode() //退出切歌模式
when (position) {
0 -> setRandomPicker(IncrementCalculator())
1 -> setRandomPicker(Calculator { position, currentWeight, originWeight -> 1 }) //实现独立随机比较简单,weight永远返回同一个常数即可。
2 -> setRandomPicker(Calculator { position, currentWeight, originWeight ->
// war3随机有个特点:有几率触发100%暴击,但是不会出现0%暴击的情况。
// 计算公式大致为,综合暴击率20%时:设定初始暴击几率5%,未触发暴击则暴击率翻倍,若触发暴击则重置为初始暴击几率。
var weight = 0
if (position == mCriticalPos) {
if (currentWeight == 0)//说明需要初始化暴击几率
weight = 5
else
weight = Math.min(currentWeight * 2, 100)
} else {
try {
weight = (100 - mRandomPicker.getWeight(mCriticalPos)) / 4
} catch (e: Exception) {
weight = (100 - 5) / 4
}
}
//这种情况,走RandomPicker有点多此一举(而且需要把特定数放在第一位),而且效率不高。不过好处在于接口统一。
weight
})
3 -> {
//随机翻牌,其实开启切歌模式即可。
mRandomPicker.enterCutMode()
setRandomPicker(Calculator { position, currentWeight, originWeight -> 1 })
}
}
}
}
override fun onNothingSelected(parent: AdapterView<*>) {
}
}
mSpinner.setSelection(0)
mBoardTv.setText("用 RandomPikcer 实现几种常见的随机机制"
+ "\n\n1.RandomPicker默认模式,被选中的权重变为0,未被选中的权重++。"
+ "\n\n2.独立随机,即游戏领域所说的'真随机',每次随机都不受之前结果影响。"
+ "\n\n3.暴雪war3暴击机制,综合暴击率20%时:设定初始暴击几率5%,未触发暴击则暴击率翻倍,若触发暴击则重置为初始暴击几率。"
+ "\n\n4.翻牌随机,一次翻一张牌。每一轮翻牌中,翻过的牌不会再出现。与音乐播放里的切歌模式一致。"
)
}
fun setRandomPicker(calculator: Calculator) {
Log.i("xyz", "setRandomPicker " + calculator.calculateNextWeight(0, 0, 1))
mRandomPicker.setCalculator(calculator)
mRandomPicker.setRepeatable(true)
mRandomPicker.resetList(mRadioGroup.childCount, 1)
mTotal = 0
mCritical = 0
showCriticalTv()
}
fun showCriticalTv() {
val percent = mCritical * 100 / Math.max(mTotal, 1)
mPercentTv.setText("暴击率: $percent% $mCritical/$mTotal")
}
fun random(view: View) {
view.isEnabled = false
val pos = mRandomPicker.next()
mRadioGroup.check(mRadioGroup.getChildAt(pos).id)
for (index in 0..mWeightLayout.childCount - 1) {
(mWeightLayout.getChildAt(index) as TextView).text =
mRandomPicker.getWeight(index).toString()
}
mTotal++
if (pos == mCriticalPos) {
mCritical++
}
showCriticalTv()
view.isEnabled = true
}
fun machine(view: View) {
startActivity(Intent(this, GameActivity::class.java))
}
fun scoreShuffle(view: View) {
startActivity(Intent(this, ScoreShuffleActivity::class.java))
}
}
| 1 | null | 8 | 28 | 7360ea08ffd21bfd1896734fc3b51f65da5e20ab | 5,441 | RandomPicker | Apache License 2.0 |
compose/snippets/src/main/java/com/example/compose/snippets/images/CustomPainterSnippets.kt | android | 138,043,025 | false | null | /*
* Copyright 2022 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.compose.snippets.images
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.paint
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.toSize
import com.example.compose.snippets.R
import kotlin.math.roundToInt
/*
* Copyright 2022 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.
*/
@Preview
@Composable
fun CustomPainterUsage() {
// [START android_compose_images_custom_painter_usage]
val rainbowImage = ImageBitmap.imageResource(id = R.drawable.rainbow)
val dogImage = ImageBitmap.imageResource(id = R.drawable.dog)
val customPainter = remember {
OverlayImagePainter(dogImage, rainbowImage)
}
Image(
painter = customPainter,
contentDescription = stringResource(id = R.string.dog_content_description),
contentScale = ContentScale.Crop,
modifier = Modifier.wrapContentSize()
)
// [END android_compose_images_custom_painter_usage]
}
// [START android_compose_images_custom_painter]
class OverlayImagePainter constructor(
private val image: ImageBitmap,
private val imageOverlay: ImageBitmap,
private val srcOffset: IntOffset = IntOffset.Zero,
private val srcSize: IntSize = IntSize(image.width, image.height),
private val overlaySize: IntSize = IntSize(imageOverlay.width, imageOverlay.height)
) : Painter() {
private val size: IntSize = validateSize(srcOffset, srcSize)
override fun DrawScope.onDraw() {
// draw the first image without any blend mode
drawImage(
image,
srcOffset,
srcSize,
dstSize = IntSize(
[email protected](),
[email protected]()
)
)
// draw the second image with an Overlay blend mode to blend the two together
drawImage(
imageOverlay,
srcOffset,
overlaySize,
dstSize = IntSize(
[email protected](),
[email protected]()
),
blendMode = BlendMode.Overlay
)
}
/**
* Return the dimension of the underlying [ImageBitmap] as it's intrinsic width and height
*/
override val intrinsicSize: Size get() = size.toSize()
private fun validateSize(srcOffset: IntOffset, srcSize: IntSize): IntSize {
require(
srcOffset.x >= 0 &&
srcOffset.y >= 0 &&
srcSize.width >= 0 &&
srcSize.height >= 0 &&
srcSize.width <= image.width &&
srcSize.height <= image.height
)
return srcSize
}
}
// [END android_compose_images_custom_painter]
@Preview
@Composable
fun CustomPainterModifier() {
// [START android_compose_custom_painter_modifier]
val rainbowImage = ImageBitmap.imageResource(id = R.drawable.rainbow)
val dogImage = ImageBitmap.imageResource(id = R.drawable.dog)
val customPainter = remember {
OverlayImagePainter(dogImage, rainbowImage)
}
Box(
modifier =
Modifier.background(color = Color.Gray)
.padding(30.dp)
.background(color = Color.Yellow)
.paint(customPainter)
) { /** intentionally empty **/ }
// [END android_compose_custom_painter_modifier]
}
| 14 | null | 169 | 666 | 514653c318c747c557f70e32aad2cc7051d44115 | 5,385 | snippets | Apache License 2.0 |
tmp/arrays/youTrackTests/7544.kt | DaniilStepanov | 228,623,440 | false | null | // Original bug: KT-27034
import java.util.function.Predicate
fun test(some: ArrayList<String>) {
some.removeIf(Predicate {
println()
println()
true
})
}
| 1 | null | 1 | 1 | 602285ec60b01eee473dcb0b08ce497b1c254983 | 189 | bbfgradle | Apache License 2.0 |
server/server-api/src/main/kotlin/projektor/server/api/MathUtil.kt | craigatk | 226,096,594 | false | null | package projektor.server.api
import java.math.BigDecimal
import java.math.MathContext
import java.math.RoundingMode
object MathUtil {
fun calculatePercentage(value: BigDecimal, total: BigDecimal): BigDecimal =
if (value > BigDecimal.ZERO && total > BigDecimal.ZERO) {
value.divide(total, MathContext(4, RoundingMode.HALF_DOWN))
.times(BigDecimal(100.00)).setScale(2, RoundingMode.HALF_DOWN)
} else {
BigDecimal.ZERO
}
}
| 14 | null | 15 | 47 | f9f61314539ba393af0a9b9b15cfeccf545f7471 | 490 | projektor | MIT License |
sample/src/main/java/com/codertainment/materialintro/sample/ToolbarMenuItemActivity.kt | shripal17 | 238,678,867 | false | null | package com.codertainment.materialintro.sample
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import com.codertainment.materialintro.sample.fragment.*
import com.codertainment.materialintro.sequence.MaterialIntroSequenceListener
import com.codertainment.materialintro.utils.materialIntroSequence
import com.google.android.material.navigation.NavigationView
import kotlinx.android.synthetic.main.activity_toolbar.*
import org.jetbrains.anko.toast
/**
* This activity demonstrates how to implement Material introView on ToolBar MenuItems with custom colors and sequence
*
*/
class ToolbarMenuItemActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener, MaterialIntroSequenceListener {
private lateinit var shareAction: View
private lateinit var helpAction: View
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_toolbar)
setSupportActionBar(toolbar)
val toggle = ActionBarDrawerToggle(this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawer_layout.setDrawerListener(toggle)
toggle.syncState()
nav_view.setNavigationItemSelectedListener(this)
}
override fun onBackPressed() {
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.main, menu)
Handler().post {
helpAction = findViewById(R.id.help)
shareAction = findViewById(R.id.share)
materialIntroSequence(500) {
addConfig {
viewId = MENU_SEARCH_ID_TAG
infoText = getString(R.string.guide_setup_profile)
infoCardBackgroundColor = Color.GREEN
helpIconColor = Color.BLUE
infoTextColor = Color.BLACK
dotIconColor = Color.RED
targetView = findViewById(R.id.search)
}
addConfig {
viewId = MENU_SHARED_ID_TAG
infoText = getString(R.string.guide_setup_profile)
infoCardBackgroundColor = Color.GREEN
helpIconColor = Color.BLUE
infoTextColor = Color.BLACK
dotIconColor = Color.RED
targetView = shareAction
}
addConfig {
viewId = MENU_ABOUT_ID_TAG
infoText = getString(R.string.guide_setup_profile)
infoCardBackgroundColor = Color.GREEN
helpIconColor = Color.BLUE
infoTextColor = Color.BLACK
dotIconColor = Color.RED
targetView = helpAction
}
}
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
return if (id == R.id.action_settings) {
true
} else super.onOptionsItemSelected(item)
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
val fragment = when (item.itemId) {
R.id.nav_demo -> MainFragment()
R.id.nav_gravity -> GravityFragment()
R.id.nav_focus -> FocusFragment()
R.id.nav_recyclerview -> RecyclerViewFragment()
R.id.nav_custom_view -> CustomInfoViewFragment()
else -> null
}
if (item.itemId == R.id.nav_toolbar) {
startActivity(Intent(applicationContext, ToolbarMenuItemActivity::class.java))
} else if (fragment != null) {
supportFragmentManager.beginTransaction().replace(R.id.container, fragment).commit()
}
drawer_layout.closeDrawer(GravityCompat.START)
return true
}
companion object {
private const val MENU_SHARED_ID_TAG = "menuSharedIdTag"
private const val MENU_ABOUT_ID_TAG = "menuAboutIdTag"
private const val MENU_SEARCH_ID_TAG = "menuSearchIdTag"
}
override fun onProgress(onUserClick: Boolean, viewId: String, current: Int, total: Int) {
when (viewId) {
MENU_SHARED_ID_TAG -> toast("Share done")
MENU_ABOUT_ID_TAG -> toast("About done")
MENU_SEARCH_ID_TAG -> toast("Search done")
}
}
override fun onCompleted() {
toast("All done")
}
} | 7 | null | 11 | 53 | 6ae490d1cd089262cd87221d0092892be301129f | 4,391 | MaterialIntroView-v2 | Apache License 2.0 |
testapps/controller/src/main/java/androidx/media3/testapp/controller/PreparePlayHelper.kt | androidx | 402,527,443 | false | {"Java": 25508260, "C++": 114369, "Kotlin": 93031, "GLSL": 76938, "AIDL": 29620, "Makefile": 11496, "Shell": 9457, "CMake": 3744} | /*
* 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
*
* 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.media3.testapp.controller
import android.app.Activity
import android.net.Uri
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Spinner
import androidx.media3.common.MediaItem
import androidx.media3.session.MediaController
/** Helper class which handles prepare and play actions. */
class PreparePlayHelper(activity: Activity, private val mediaController: MediaController) :
View.OnClickListener {
private val inputType: Spinner = activity.findViewById(R.id.input_type)
private val uriInputText: EditText = activity.findViewById(R.id.uri_id_query)
private val prepareButton: Button = activity.findViewById(R.id.action_prepare)
private val playButton: Button = activity.findViewById(R.id.action_play)
init {
prepareButton.setOnClickListener(this)
playButton.setOnClickListener(this)
}
companion object {
// Indices of the values in the "input_options" string array.
private const val INDEX_SEARCH = 0
private const val INDEX_MEDIA_ID = 1
private const val INDEX_URI = 2
}
@SuppressWarnings("FutureReturnValueIgnored")
override fun onClick(v: View) {
mediaController.apply {
setMediaItem(buildMediaItem())
playWhenReady = v.id == R.id.action_play
prepare()
}
}
private fun buildMediaItem(): MediaItem {
val value: String = uriInputText.text.toString()
val mediaItemBuilder = MediaItem.Builder()
when (inputType.selectedItemPosition) {
INDEX_MEDIA_ID -> mediaItemBuilder.setMediaId(value)
INDEX_SEARCH ->
mediaItemBuilder.setRequestMetadata(
MediaItem.RequestMetadata.Builder().setSearchQuery(value).build()
)
INDEX_URI ->
mediaItemBuilder.setRequestMetadata(
MediaItem.RequestMetadata.Builder().setMediaUri(Uri.parse(value)).build()
)
}
return mediaItemBuilder.build()
}
}
| 582 | Java | 392 | 1,656 | c35a9d62baec57118ea898e271ac66819399649b | 2,534 | media | Apache License 2.0 |
src/test/kotlin/com/leetcode/P1249Test.kt | antop-dev | 229,558,170 | false | {"Kotlin": 669152, "Java": 216308} | package com.leetcode
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.`is`
import org.hamcrest.Matchers.anyOf
import org.junit.jupiter.api.Test
class P1249Test {
val p = P1249()
@Test
fun `example 01`() {
assertThat(
p.minRemoveToMakeValid("lee(t(c)o)de)"),
anyOf(`is`("lee(t(c)o)de"), `is`("lee(t(co)de)"), `is`("lee(t(c)ode)"))
)
}
@Test
fun `example 02`() {
assertThat(p.minRemoveToMakeValid("a)b(c)d"), `is`("ab(c)d"))
}
@Test
fun `example 03`() {
assertThat(p.minRemoveToMakeValid("))(("), `is`(""))
}
@Test
fun `example 04`() {
assertThat(p.minRemoveToMakeValid("(a(b(c)d)"), `is`("a(b(c)d)"))
}
@Test
fun `example 05`() {
assertThat(p.minRemoveToMakeValid("())()((("), `is`("()()"))
}
@Test
fun `example 06`() {
assertThat(p.minRemoveToMakeValid(")))t((u)"), `is`("t(u)"))
}
}
| 2 | Kotlin | 0 | 0 | a9dd7cfa4f6cfc5186a86f6e2c8aefc489f5c028 | 974 | algorithm | MIT License |
libraries/rib-base/src/androidTest/java/com/badoo/ribs/android/lifecycle/PushTwoTest.kt | badoo | 170,855,556 | false | {"Kotlin": 934999} | package com.badoo.ribs.android.lifecycle
import com.badoo.ribs.android.lifecycle.helper.ExpectedState
import com.badoo.ribs.android.lifecycle.helper.NodeState.Companion.ON_SCREEN
import com.badoo.ribs.android.lifecycle.helper.NodeState.Companion.VIEW_DETACHED
import com.badoo.ribs.test.util.ribs.root.TestRootRouter.Configuration.Content.AttachNode1
import com.badoo.ribs.test.util.ribs.root.TestRootRouter.Configuration.Content.AttachNode2
import com.badoo.ribs.test.util.ribs.root.TestRootRouter.Configuration.Content.AttachNode3
import com.badoo.ribs.test.util.ribs.root.TestRootRouter.Configuration.Overlay.AttachNode2AsOverlay
import com.badoo.ribs.test.util.ribs.root.TestRootRouter.Configuration.Overlay.AttachNode3AsOverlay
import com.badoo.ribs.test.util.ribs.root.TestRootRouter.Configuration.Permanent.Permanent1
import com.badoo.ribs.test.util.ribs.root.TestRootRouter.Configuration.Permanent.Permanent2
import com.badoo.ribs.test.util.runOnMainSync
import org.junit.Test
class PushTwoTest : BaseNodesTest() {
private fun pushTwoConfigurations(setup: When, expectedState: ExpectedState) {
test(setup, expectedState) { router, _ ->
runOnMainSync {
router.pushIt(setup.configuration1!!)
router.pushIt(setup.configuration2!!)
}
}
}
@Test
fun noPermanent_singleInitial_pushContent_pushContent() {
pushTwoConfigurations(
When(
initialConfiguration = AttachNode1,
configuration1 = AttachNode2,
configuration2 = AttachNode3
),
ExpectedState(
node1 = VIEW_DETACHED,
node2 = VIEW_DETACHED,
node3 = ON_SCREEN
)
)
}
@Test
fun noPermanent_singleInitial_pushContent_pushOverlay() {
pushTwoConfigurations(
When(
initialConfiguration = AttachNode1,
configuration1 = AttachNode2,
configuration2 = AttachNode3AsOverlay
),
ExpectedState(
node1 = VIEW_DETACHED,
node2 = ON_SCREEN,
node3 = ON_SCREEN
)
)
}
@Test
fun noPermanent_singleInitial_pushOverlay_pushOverlay() {
pushTwoConfigurations(
When(
initialConfiguration = AttachNode1,
configuration1 = AttachNode2AsOverlay,
configuration2 = AttachNode3AsOverlay
),
ExpectedState(
node1 = ON_SCREEN,
node2 = ON_SCREEN,
node3 = ON_SCREEN
)
)
}
@Test
fun multiplePermanent_singleInitial_pushContent_pushContent() {
pushTwoConfigurations(
When(
permanentParts = listOf(Permanent1, Permanent2),
initialConfiguration = AttachNode1,
configuration1 = AttachNode2,
configuration2 = AttachNode3
),
ExpectedState(
permanentNode1 = ON_SCREEN,
permanentNode2 = ON_SCREEN,
node1 = VIEW_DETACHED,
node2 = VIEW_DETACHED,
node3 = ON_SCREEN
)
)
}
@Test
fun multiplePermanent_singleInitial_pushContent_pushOverlay() {
pushTwoConfigurations(
When(
permanentParts = listOf(Permanent1, Permanent2),
initialConfiguration = AttachNode1,
configuration1 = AttachNode2,
configuration2 = AttachNode3AsOverlay
),
ExpectedState(
permanentNode1 = ON_SCREEN,
permanentNode2 = ON_SCREEN,
node1 = VIEW_DETACHED,
node2 = ON_SCREEN,
node3 = ON_SCREEN
)
)
}
@Test
fun multiplePermanent_singleInitial_pushOverlay_pushOverlay() {
pushTwoConfigurations(
When(
permanentParts = listOf(Permanent1, Permanent2),
initialConfiguration = AttachNode1,
configuration1 = AttachNode2AsOverlay,
configuration2 = AttachNode3AsOverlay
),
ExpectedState(
permanentNode1 = ON_SCREEN,
permanentNode2 = ON_SCREEN,
node1 = ON_SCREEN,
node2 = ON_SCREEN,
node3 = ON_SCREEN
)
)
}
}
| 34 | Kotlin | 50 | 162 | cec2ca936ed17ddd7720b4b7f8fca4ce12033a89 | 4,529 | RIBs | Apache License 2.0 |
app/src/main/java/com/battlelancer/seriesguide/sync/HexagonEpisodeSyncK.kt | UweTrottmann | 1,990,682 | false | null | // Copyright 2023 <NAME>
// SPDX-License-Identifier: Apache-2.0
package com.battlelancer.seriesguide.sync
data class DownloadFlagsResult(
val success: Boolean,
val noData: Boolean,
val lastWatchedMs: Long?
) {
companion object {
@JvmField
val FAILED = DownloadFlagsResult(success = false, noData = false, lastWatchedMs = null)
@JvmField
val NO_DATA = DownloadFlagsResult(success = true, noData = true, lastWatchedMs = null)
}
}
data class ShowLastWatchedInfo(
val lastWatchedMs: Long,
val episodeSeason: Int,
val episodeNumber: Int
)
| 50 | null | 400 | 1,940 | a316fcd52846cfc8bd5acee062906db7b5028495 | 601 | SeriesGuide | Apache License 2.0 |
packages/expo-modules-core/android/src/androidTest/java/expo/modules/TestRunner.kt | expo | 65,750,241 | false | {"Gemfile.lock": 1, "YAML": 79, "Git Config": 1, "JSON with Comments": 175, "Ignore List": 236, "JSON": 713, "Markdown": 291, "JavaScript": 1979, "Text": 62, "Git Attributes": 7, "Shell": 66, "Ruby": 99, "TSX": 976, "Gradle": 106, "Java Properties": 5, "Batchfile": 4, "INI": 8, "Proguard": 10, "XML": 273, "Kotlin": 1210, "Dotenv": 7, "OpenStep Property List": 30, "Objective-C": 586, "Objective-C++": 49, "Jest Snapshot": 52, "CODEOWNERS": 1, "SVG": 57, "Java": 282, "Swift": 733, "CMake": 5, "C++": 109, "C": 7, "Gradle Kotlin DSL": 3, "JSON5": 1, "HTML": 5, "MATLAB": 1, "Checksums": 6, "Diff": 46, "MDX": 748, "robots.txt": 1, "CSS": 4, "Cloud Firestore Security Rules": 1, "GraphQL": 17, "TOML": 1} | package expo.modules
import android.app.Application
import android.content.Context
import androidx.test.runner.AndroidJUnitRunner
import com.facebook.soloader.SoLoader
import expo.modules.kotlin.jni.JSIContext
/**
* A simple test runner that ensures all needed libraries will be loaded before starting any tests.
*/
class TestRunner : AndroidJUnitRunner() {
override fun newApplication(cl: ClassLoader?, className: String?, context: Context?): Application {
// Loads libs like hermes
SoLoader.init(context, /* native exopackage */false)
// Using `JSIContext.Companion` ensures that static libs will be loaded.
JSIContext.Companion
return super.newApplication(cl, className, context)
}
}
| 668 | TypeScript | 5226 | 32,824 | e62f80228dece98d5afaa4f5c5e4fb195f3daa15 | 716 | expo | Apache License 2.0 |
feature-ledger-impl/src/main/java/io/novafoundation/nova/feature_ledger_impl/presentation/account/connect/legacy/start/di/StartImportLedgerModule.kt | novasamatech | 415,834,480 | false | {"Kotlin": 11112596, "Rust": 25308, "Java": 17664, "JavaScript": 425} | package io.novafoundation.nova.feature_ledger_impl.presentation.account.connect.legacy.start.di
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import dagger.Module
import dagger.Provides
import dagger.multibindings.IntoMap
import io.novafoundation.nova.common.data.network.AppLinksProvider
import io.novafoundation.nova.common.di.viewmodel.ViewModelKey
import io.novafoundation.nova.common.di.viewmodel.ViewModelModule
import io.novafoundation.nova.feature_ledger_core.domain.LedgerMigrationTracker
import io.novafoundation.nova.feature_ledger_impl.presentation.LedgerRouter
import io.novafoundation.nova.feature_ledger_impl.presentation.account.connect.legacy.start.StartImportLedgerViewModel
@Module(includes = [ViewModelModule::class])
class StartImportLedgerModule {
@Provides
@IntoMap
@ViewModelKey(StartImportLedgerViewModel::class)
fun provideViewModel(
router: LedgerRouter,
appLinksProvider: AppLinksProvider,
ledgerMigrationTracker: LedgerMigrationTracker,
): ViewModel {
return StartImportLedgerViewModel(router, appLinksProvider, ledgerMigrationTracker)
}
@Provides
fun provideViewModelCreator(fragment: Fragment, viewModelFactory: ViewModelProvider.Factory): StartImportLedgerViewModel {
return ViewModelProvider(fragment, viewModelFactory).get(StartImportLedgerViewModel::class.java)
}
}
| 14 | Kotlin | 30 | 50 | 166755d1c3388a7afd9b592402489ea5ca26fdb8 | 1,453 | nova-wallet-android | Apache License 2.0 |
src/main/kotlin/es/urjc/realfood/restaurants/infrastructure/api/exceptions/ApiError.kt | MasterCloudApps-Projects | 391,102,931 | false | null | package es.urjc.realfood.restaurants.infrastructure.api.exceptions
data class ApiError(
val message: String
)
| 0 | Kotlin | 0 | 1 | a727933b9dad4871fcac795f3dc7c230f19f452c | 115 | realfood-restaurants | Apache License 2.0 |
data/src/main/java/com/krakert/tracker/data/tracker/mapper/ImageMapper.kt | Krakert | 500,599,145 | false | {"Kotlin": 148090} | package com.krakert.tracker.data.tracker.mapper
import com.krakert.tracker.data.extension.requireNotNull
import com.krakert.tracker.data.tracker.entity.ImagesEntity
import com.krakert.tracker.domain.tracker.model.Images
import javax.inject.Inject
class ImageMapper @Inject constructor(
) {
fun mapApiToDomain(imagesEntity: ImagesEntity): Images {
return Images(
small = imagesEntity.small.requireNotNull(),
large = imagesEntity.large.requireNotNull(),
thumb = imagesEntity.thumb.requireNotNull(),
)
}
}
| 4 | Kotlin | 1 | 7 | 13b105a8ee6e28fa4f3930e386e2b3f62a79295d | 566 | Crypto-Tracker | MIT License |
android/photosenderstable/app/src/main/java/com/example/photo_sender_stable/MainActivity.kt | fess932 | 347,026,697 | false | null | package com.example.photo_sender_stable
import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.util.Size
import android.view.WindowManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.ImageProxy
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.get
import androidx.lifecycle.MutableLiveData
import com.example.photo_sender_stable.databinding.ActivityMainBinding
import com.example.photo_sender_stable.utils.SufaceProviderImpl
import com.example.photo_sender_stable.webrtc.WebRTCClient
import com.example.photo_sender_stable.websocket.WSClient
import com.google.mlkit.vision.barcode.Barcode
import com.google.mlkit.vision.barcode.BarcodeScannerOptions
import com.google.mlkit.vision.barcode.BarcodeScanning
import com.google.mlkit.vision.common.InputImage
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File
import java.io.IOException
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
/*
Main activity
Camera
WebSocket <-> WebRTC <- Camera.VideoStream
WebSocket.Snap -> Camera
http.photo <- Camera
*/
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
companion object {
private val optionsQR = BarcodeScannerOptions.Builder()
.setBarcodeFormats(Barcode.FORMAT_QR_CODE)
.build()
private val scanner = BarcodeScanning.getClient(optionsQR)
private var imageCapture: ImageCapture? = null
private lateinit var cameraExecutor: ExecutorService
val host = MutableLiveData("")
val client = OkHttpClient().newBuilder().writeTimeout(30, TimeUnit.SECONDS).build()
private const val TAG = "CameraXBasic"
// private const val FILENAME_FORMAT = "yyyy-MM-dd-HH-mm-ss-SSS"
private const val REQUEST_CODE_PERMISSIONS = 10
private val REQUIRED_PERMISSIONS =
arrayOf(
Manifest.permission.CAMERA,
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_NETWORK_STATE,
Manifest.permission.ACCESS_WIFI_STATE
)
private lateinit var webrtcClient: WebRTCClient
private lateinit var wsClient: WSClient
// private val sdpObserver = object : AppSdpObserver() {
// override fun onCreateSuccess(p0: SessionDescription?) {
// super.onCreateSuccess(p0)
// Log.d("sdp observer", "on create success $p0")
// // wsClient.send(p0)
// }
// }
// private fun createSignalingClientListener() = object : SignalingClientListener {
// override fun onConnectionEstablished() {
// Log.d("signaling client", "connection established")
// }
//
// override fun onOfferReceived(description: SessionDescription) {
// Log.d("signaling client", "message answer $description ::: $sdpObserver")
// webrtcClient.onRemoteSessionReceived(description)
// webrtcClient.answer(sdpObserver)
// }
//
// override fun onIceCandidateReceived(iceCandidate: IceCandidate) {
// rtcClient.addIceCandidate(iceCandidate)
// }
// }
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
cameraExecutor = Executors.newSingleThreadExecutor()
checkCameraPermission()
}
private fun checkCameraPermission() {
if (allPermissionsGranted()) {
onCameraPermissionGranted()
} else {
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS)
}
}
private fun onCameraPermissionGranted() {
wsClient = WSClient()
host.observe(this, { host ->
binding.host.text = host
wsClient.updateHost(host)
})
webrtcClient = WebRTCClient(application, wsClient)
// webrtcClient.startLocalVideoCapture(binding.viewFinder)
wsClient.updateWebRTCClient(webrtcClient)//todo: update rtc client inside rtc
// webRTCClient = WebRTCClient(applicationContext, object : WebRTCClient.IStateChangeListener{
// override fun onStateChanged(state: WebRTCClient.State) {
// Log.d("state change listener", "state changed $state")
// }
// })
startCamera()
binding.cameraCaptureButton.setOnClickListener {
takePhoto()
}
}
//// utils
private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all {
ContextCompat.checkSelfPermission(baseContext, it) == PackageManager.PERMISSION_GRANTED
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == REQUEST_CODE_PERMISSIONS) {
if (allPermissionsGranted()) {
Log.d("PERMISSIONS", "Permissions granted")
} else {
Toast.makeText(this, "Permissions not granted", Toast.LENGTH_SHORT).show()
finish()
}
}
}
@SuppressLint("UnsafeExperimentalUsageError")
private fun startCamera() {
val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
cameraProviderFuture.addListener({
val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
// val sur = binding.viewFinder.surfaceProvider as SufaceProviderImpl
val preview = Preview.Builder()
.build()
.also {
it.setSurfaceProvider(binding.viewFinder.surfaceProvider)
}
imageCapture = ImageCapture.Builder().build()
val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
val imageAnalyzer = ImageAnalysis.Builder()
.setTargetResolution(Size(1280, 720))
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.build()
imageAnalyzer.setAnalyzer(cameraExecutor, { imageProxy ->
val mediaImage = imageProxy.image
if (mediaImage != null) {
val image =
InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees)
scanner.process(image)
.addOnSuccessListener { barcodes ->
barcodes.forEach { bar ->
host.value = bar.rawValue
Log.d("BARCODE", "barcodes: ${bar.rawValue}")
}
}
.addOnFailureListener { exc -> Log.d("BARCODE_EXC", "exc: $exc") }
.addOnCompleteListener { imageProxy.close() }
}
})
try {
cameraProvider.unbindAll()
cameraProvider.bindToLifecycle(
this,
cameraSelector,
preview,
imageCapture,
imageAnalyzer,
)
} catch (exc: Exception) {
Log.e(TAG, "use case binding failed", exc)
}
}, ContextCompat.getMainExecutor(this))
}
private fun takePhoto() {
val imageCapture = imageCapture ?: return
imageCapture.takePicture(ContextCompat.getMainExecutor(this), object :
ImageCapture.OnImageCapturedCallback() {
override fun onError(exception: ImageCaptureException) {
Log.e("TAKE_PHOTO", "err take photo", exception)
}
override fun onCaptureSuccess(image: ImageProxy) {
super.onCaptureSuccess(image)
Log.d("TAKE_PHOTO", "photo taked, format: ${image.format}, ${image.imageInfo}")
val buffer = image.planes[0].buffer
val bytes = ByteArray(buffer.capacity()).also { buffer.get(it) }
Log.d("TAKE_PHOTO", "image bytes size: ${bytes.size}")
image.close()
/// sending
val mediaTypeJPG = "image/jpeg".toMediaType()
val f = File.createTempFile("file0", "file1")
f.deleteOnExit()
f.writeBytes(bytes)
val rb = MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("title", "Image from android")
.addFormDataPart("file", "photo.jpg", f.asRequestBody(mediaTypeJPG))
.build()
println(host.value)
val request = Request.Builder()
.url("${host.value}/upload")
.post(rb)
// .post(f.asRequestBody(mediaTypeJPG))
.build()
GlobalScope.launch(Dispatchers.IO) {
try {
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
println(response.body!!.string())
}
} catch (exc: IOException) {
Log.e("WIFI", "network exception, $exc", exc)
}
}
}
})
}
}
| 0 | Kotlin | 0 | 0 | 4d57d591d077558d412985d3b8d1790b72a96b27 | 10,526 | PhotoSnaper | MIT License |
dd-sdk-android/src/main/kotlin/com/datadog/android/core/internal/lifecycle/ProcessLifecycleCallback.kt | nicholas-devlin | 237,227,700 | true | {"Kotlin": 655359} | package com.datadog.android.core.internal.lifecycle
import android.content.Context
import com.datadog.android.core.internal.net.info.NetworkInfo
import com.datadog.android.core.internal.net.info.NetworkInfoProvider
import com.datadog.android.core.internal.utils.triggerUploadWorker
import java.lang.ref.WeakReference
internal class ProcessLifecycleCallback(
val networkInfoProvider: NetworkInfoProvider,
appContext: Context
) :
ProcessLifecycleMonitor.Callback {
private val contextWeakRef = WeakReference<Context>(appContext)
override fun onStarted() {
// NO - OP
}
override fun onResumed() {
// NO - OP
}
override fun onStopped() {
val isOffline = (networkInfoProvider.getLatestNetworkInfo().connectivity
== NetworkInfo.Connectivity.NETWORK_NOT_CONNECTED)
if (isOffline) {
contextWeakRef.get()?.let {
triggerUploadWorker(it)
}
}
}
override fun onPaused() {
// NO - OP
}
}
| 0 | null | 0 | 0 | 827e05b864def3e1573a1935fd59bddf22449215 | 1,033 | dd-sdk-android | Apache License 2.0 |
config/src/main/kotlin/org/wcl/mfn/config/ui/mvc/ModelConfig.kt | warnettconsultingltd | 809,363,042 | false | {"Kotlin": 57760, "HTML": 6681, "CSS": 4145} | package org.wcl.mfn.config.ui.mvc
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.*
@Configuration
@PropertySource("classpath:ui/mvc/model.properties")
open class ModelConfig {
@Value("\${common.view.attribute.page-title}")
private val pageTitle: String? = null
fun pageTitle(): String? {
return pageTitle
}
}
| 0 | Kotlin | 0 | 0 | 736f94fe30c021bd8579d09646e92b46265c8884 | 393 | wcl-mfn-manager | Apache License 2.0 |
componentlibrary/src/main/java/com/vallem/componentlibrary/util/Plurals.kt | leonardovallem | 613,461,263 | false | {"Kotlin": 308660} | package com.vallem.componentlibrary.util
fun Array<out String>.pluralize(count: Int) =
if (count > 1) joinToString(" ") { it + "s" } else joinToString(" ")
fun String.pluralize(count: Int) = if (count > 1) plus("s") else this | 0 | Kotlin | 0 | 0 | 27615ff4672845892d2150ed7069702b521115ef | 231 | sylph | MIT License |
src/main/kotlin/com/nuc/libra/vo/Params.kt | onlineevaluation | 119,769,117 | false | null | package com.nuc.libra.vo
import io.swagger.annotations.ApiModel
import java.sql.Date
import java.sql.Timestamp
import java.util.*
import kotlin.collections.ArrayList
/**
* @author 杨晓辉 2018-12-29 16:06
* 用于接收前端参数的类
* 所有的类采用data class
* 所有的后缀采用 **param**
*/
/**
* 用于接收页面的 `UserParam` 值
* @param username 用户名
* @param password 密码
*/
@ApiModel("登录接收数据")
data class UserParam(
val username: String,
val password: String
)
/**
* 考试试卷信息
* @property classId Long 班级id
* @property pageId Long 试卷id
* @constructor
*/
@ApiModel("考试试卷信息")
data class ExamParam(
val classId: Long,
val pageId: Long
)
/**
* 返回的成绩视图
*/
class StudentScoreParam {
var id: Long = 0L
var studentId: Long = 0L
var pagesId: Long = 0L
var score: Double = 0.0
var time: Timestamp? = null
var dotime: Date? = null
lateinit var classRank: String
lateinit var gradeRank: String
lateinit var pageTitle: String
override fun toString(): String {
return "StudentScoreParam(id=$id, studentId=$studentId, score=$score, time=$time, dotime=$dotime, classRank=$classRank, gradeRank=$gradeRank)"
}
}
/**
* 试卷详情
*/
class PageDetailsParam {
var id: Long = 0L
var pageId: Long = 0L
/**
* 分数
*/
var score: Double = 0.0
/**
* 试卷名称
*/
lateinit var pageTitle: String
/**
* 学科
*/
lateinit var course: String
/**
* 完成用时
*/
var doTime: String? = null
var select: ArrayList<StudentAnswerSelect> = ArrayList()
var blank: ArrayList<StudentAnswer> = ArrayList()
var ans = ArrayList<StudentAnswer>()
var algorithm = ArrayList<StudentAnswer>()
}
/**
* 学生答案
* @property id Long 答案id
* @property answer String 答案
* @property score Double 分数
* @property standardAnswer String 标准答案
* @property title String 标题
*/
open class StudentAnswer {
var id: Long = 0L
var answer: String = ""
var score: Double = 0.0
var standardAnswer = ""
lateinit var title: String
}
/**
* 选项
* @property sectionA String
* @property sectionB String
* @property sectionC String
* @property sectionD String
*/
class StudentAnswerSelect : StudentAnswer() {
var sectionA: String = ""
var sectionB: String = ""
var sectionC: String = ""
var sectionD: String = ""
}
/**
* 用户的代码提交
*/
data class Code(val id: Long, val codeString: String, val language: String)
/**
* 学生提交有异议的试题
* @param titleId 试题编号
* @param studentId 学生id
* @param content 提交内容
*/
data class WrongTitleParam(val titleId: Long, val studentId: Long, val content: String)
/**
* 试卷验证id
* @param studentId 学生id
* @param pageId 试卷id
*/
data class VerifyPageParam(val studentId: Long, val pageId: Long)
/**
* 获取前 10 名 参数
* @property teacherId Long
* @property pageId Long
* @property classId Long
* @constructor
*/
data class ClassAndPageParam(val teacherId: Long, val pageId: Long, val classId: Long)
/**
* 试卷信息
* @property courseId Long 课程编号
* @property titleType IntArray 试题类型
* @property chapterIds 章节id
* @constructor
*/
data class PaperTitleTypeParam(val courseId: Long, val titleType: IntArray, val chapterIds: IntArray) {
override fun toString(): String {
return "PaperTitleTypeParam(courseId=$courseId, titleType=${Arrays.toString(titleType)}, chapterIds=${Arrays.toString(
chapterIds
)})"
}
}
/**
* 手工组卷时收到的参数
* @property courseId Long 课程id
* @property teacherId Long 教师id
* @property paperTitle String 试卷标题
* @property titleIds LongArray 试题编号
* @property choiceScore Double 选择题单项分值
* @property blankScore Double 填空题单项分值
* @property answerScore Double 简答题单项分值
* @property codeScore Double 代码题单项分值
* @property algorithmScore Double 算法题单项分值
* @constructor
*/
data class ArtificialPaperParam(
val courseId: Long,
val teacherId: Long,
val paperTitle: String,
val titleIds: LongArray,
val choiceScore: Float,
val blankScore: Float,
val answerScore: Float,
val codeScore: Float,
val algorithmScore: Float,
val totalScore: Float
)
/**
* 试卷和班级关系
* @property classIds LongArray
* @property teacherId Long
* @property startTime Long
* @property endTime Long
* @property pageId Long
* @constructor
*/
data class PageClassParam(
val classIds: LongArray,
val teacherId: Long,
val startTime: Long,
val endTime: Long,
val pageId: Long,
val needTime: Long
)
/**
*
* @property studentId Long
* @property qq String?
* @property sex String?
* @property email String?
* @constructor
*/
data class UpdateStudentParam(
val studentId: Long,
val qq: String?,
val sex: String?,
val email: String?
) | 0 | null | 5 | 5 | f0501482689b5deca5db3bd6ef27376d5109719a | 4,661 | Libra | Apache License 2.0 |
ethereumkit/src/main/java/io/definenulls/ethereumkit/api/jsonrpc/GetTransactionCountJsonRpc.kt | toEther | 677,364,903 | false | null | package io.definenulls.ethereumkit.api.jsonrpc
import io.definenulls.ethereumkit.models.Address
import io.definenulls.ethereumkit.models.DefaultBlockParameter
class GetTransactionCountJsonRpc(
@Transient val address: Address,
@Transient val defaultBlockParameter: DefaultBlockParameter
) : LongJsonRpc(
method = "eth_getTransactionCount",
params = listOf(address, defaultBlockParameter)
)
| 0 | Kotlin | 0 | 0 | 8a5c1090e305af60b8b0e5e04e8d7853f3cad3ce | 423 | ethereum-kit-android | MIT License |
app/src/main/java/com/test/pocketaces/presentation/MovieSearchUIMapper.kt | stAyushJain | 342,903,412 | false | null | package com.test.pocketaces.presentation
import com.test.pocketaces.presentation.model.MovieResponseDomainModel
import com.test.pocketaces.ui.model.SearchItemsUIModel
import javax.inject.Inject
class MovieSearchUIMapper @Inject constructor() {
fun getMoviesSearchUIModel(item: MovieResponseDomainModel): List<SearchItemsUIModel> {
val searchedItems = mutableListOf<SearchItemsUIModel>()
item.search.forEach {
searchedItems.add(
SearchItemsUIModel(
name = it.title,
imageUrl = it.poster,
description = it.description,
releasedDate = it.year,
rating = "Ratings : ${it.rating} / 10"
)
)
}
return searchedItems
}
} | 0 | Kotlin | 0 | 0 | 010a95a97cd75d665d41144abb6780d32075a7a4 | 808 | MovieApp | Apache License 2.0 |
app/src/main/java/com/yannickpulver/countdrown/ui/CountDownTimerExtended.kt | yannickpulver | 345,668,146 | 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.yannickpulver.countdrown.ui
import android.os.CountDownTimer
abstract class CountDownTimerExtended(val millisInFuture: Long, val countDownInterval: Long) : CountDownTimer(millisInFuture, countDownInterval) {
var tickCount: Int = 0
override fun onTick(millis: Long) {
tickCount++
}
}
| 0 | Kotlin | 0 | 0 | b4f5dc7be2a3f01d37dfa1ef355024438951d05b | 935 | Countdrown | Apache License 2.0 |
z2-core/src/commonMain/kotlin/hu/simplexion/z2/schematic/SchematicCompanion.kt | spxbhuhb | 665,463,766 | false | {"Kotlin": 1381124, "CSS": 165882, "Java": 7121, "HTML": 1560, "JavaScript": 975} | package hu.simplexion.z2.schematic
import hu.simplexion.z2.schematic.schema.Schema
import hu.simplexion.z2.serialization.protobuf.ProtoDecoder
import hu.simplexion.z2.serialization.protobuf.ProtoEncoder
import hu.simplexion.z2.serialization.protobuf.ProtoMessage
interface SchematicCompanion<T : Schematic<T>> : ProtoEncoder<T>, ProtoDecoder<T> {
val schematicSchema : Schema<T>
get() = placeholder()
fun newInstance() : T = placeholder()
override fun decodeProto(message: ProtoMessage?): T = placeholder()
override fun encodeProto(value: T): ByteArray = placeholder()
operator fun invoke(builder : T.() -> Unit) : T =
newInstance().apply(builder)
fun setFieldValue(instance : T, name : String, value : Any?) : Unit = placeholder()
fun getFieldValue(instance : T, name : String) : Any? = placeholder()
} | 6 | Kotlin | 0 | 1 | 204f26074a796495a838f00adc3dbde1fb0fc9b0 | 857 | z2 | Apache License 2.0 |
basick/src/main/java/com/mozhimen/basick/utilk/org/json/UtilKJSONArrayFormat.kt | mozhimen | 353,952,154 | false | {"Kotlin": 1460326, "Java": 3916, "AIDL": 964} | package com.mozhimen.basick.utilk.org.json
import com.mozhimen.basick.utilk.android.util.e
import com.mozhimen.basick.utilk.commons.IUtilK
import org.json.JSONArray
import org.json.JSONException
/**
* @ClassName UtilKJSONFormat
* @Description TODO
* @Author Mozhimen / Kolin Zhao
* @Date 2023/10/19 1:46
* @Version 1.0
*/
fun JSONArray.jSONArray2strList(): ArrayList<String?>? =
UtilKJSONArrayFormat.jSONArray2strList(this)
////////////////////////////////////////////////
object UtilKJSONArrayFormat: IUtilK {
@JvmStatic
fun jSONArray2strList(jsonArray: JSONArray): ArrayList<String?>? {
val strs = ArrayList<String?>()
for (i in 0 until jsonArray.length()) {
try {
val obj = jsonArray[i] as? String?
strs.add(obj)
} catch (e: JSONException) {
e.printStackTrace()
e.message?.e(TAG)
return null
}
}
return strs
}
} | 1 | Kotlin | 14 | 118 | bbdd6ab9b945f04036c27add35c1cbd70c1b49f7 | 989 | SwiftKit | Apache License 2.0 |
shared/core/src/commonMain/kotlin/com/paligot/confily/core/speakers/SpeakerDao.kt | GerardPaligot | 444,230,272 | false | {"Kotlin": 1063266, "Swift": 126158, "Shell": 1148, "Dockerfile": 576, "HTML": 338, "CSS": 102} | package com.paligot.confily.core.speakers
import com.paligot.confily.models.ui.SpeakerItemUi
import com.paligot.confily.models.ui.SpeakerUi
import kotlinx.collections.immutable.ImmutableList
import kotlinx.coroutines.flow.Flow
interface SpeakerDao {
fun fetchSpeaker(eventId: String, speakerId: String): Flow<SpeakerUi>
fun fetchSpeakers(eventId: String): Flow<ImmutableList<SpeakerItemUi>>
}
| 8 | Kotlin | 6 | 142 | 7694571716b8cd67970d42f5cdd7fa8f3306ddd9 | 403 | Confily | Apache License 2.0 |
api/common/src/main/kotlin/uk/co/baconi/oauth/api/common/token/RefreshTokenTable.kt | beercan1989 | 345,334,044 | false | null | package uk.co.baconi.oauth.api.common.token
import org.jetbrains.exposed.dao.id.EntityID
import org.jetbrains.exposed.dao.id.IdTable
import org.jetbrains.exposed.sql.Column
import org.jetbrains.exposed.sql.javatime.timestamp
import uk.co.baconi.oauth.api.common.authentication.AuthenticatedUsername
import uk.co.baconi.oauth.api.common.authentication.authenticatedUsernameColumn
import uk.co.baconi.oauth.api.common.client.ClientId
import uk.co.baconi.oauth.api.common.client.clientIdColumn
import uk.co.baconi.oauth.api.common.scope.ScopeRepository
import java.time.Instant
import java.util.*
object RefreshTokenTable : IdTable<UUID>() {
/**
* [RefreshToken.value]
*/
override val id: Column<EntityID<UUID>> = uuid("id").entityId()
val username: Column<AuthenticatedUsername> = authenticatedUsernameColumn().index()
val clientId: Column<ClientId> = clientIdColumn().index()
val scopes: Column<String> = varchar(
"scopes",
ScopeRepository.maxScopeFieldLength
) // TODO - Consider true DB style, with a table of scopes and references in a list format
val issuedAt: Column<Instant> = timestamp("issued_at") // TODO - Verify Instant over LocalDateTime as Instant still seems like its persisting in local time not UTC
val expiresAt: Column<Instant> = timestamp("expires_at").index()
val notBefore: Column<Instant> = timestamp("not_before")
override val primaryKey = PrimaryKey(id)
} | 0 | Kotlin | 0 | 0 | 63d8d107b328b42bed1aa081192c5ddbf9c5e2c8 | 1,450 | oauth-api | Apache License 2.0 |
letooth/src/main/java/com/adwardstark/letooth/ble/gatt/client/callbacks/LetoothNotifyCallback.kt | adwardstark | 291,655,982 | false | null | package com.adwardstark.letooth.ble.gatt.client.callbacks
interface LetoothNotifyCallback {
fun onNotificationSuccess()
fun onNotificationFailed()
} | 0 | Kotlin | 0 | 0 | e2f499c97f8d331719fa987e56b7b15feb639d11 | 159 | letooth-for-android | Apache License 2.0 |
baselib/src/main/java/com/brins/baselib/module/DjRadio.kt | BrinsLee | 297,821,918 | false | null | package com.brins.baselib.module
/**
* Created by lipeilin
* on 2020/11/17
*/
class DjRadio : BaseData() {
var id = ""
var name = ""
var dj : UserProfile? = null
var picUrl = ""
var desc = ""
var subCount = 0
var programCount = 0
var createTime = ""
var categoryId = 0
var category = ""
var rcmdText = ""
var playCount = 0
var shareCount = 0
var commentCount = 0
override val itemType: Int
get() = ITEM_SEARCH_DJRADIO
} | 0 | Kotlin | 0 | 1 | 37cbd7448ebfc23475c00462018f6d70c74631e1 | 508 | Music | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.