path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/example/abschlussprojekt_husewok/ui/theme/composables/statics/HouseworkImage.kt
|
Phenkel
| 732,028,288
| false
|
{"Kotlin": 273774}
|
package com.example.abschlussprojekt_husewok.ui.theme.composables.statics
import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.material3.ShapeDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import com.example.abschlussprojekt_husewok.ui.theme.Orange80
import com.example.abschlussprojekt_husewok.ui.theme.Purple80
import com.example.abschlussprojekt_husewok.utils.CalcSizes
import com.example.abschlussprojekt_husewok.utils.CalcSizes.calcDp
/**
* A composable function that displays a housework image.
*
* @param image The resource ID of the image to display.
*/
@Composable
fun HouseworkImage(image: Int) {
Image(
painter = painterResource(id = image),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier
.width(calcDp(percentage = 0.8f, dimension = CalcSizes.Dimension.Width))
.height(calcDp(percentage = 0.333f, dimension = CalcSizes.Dimension.Height))
.border(
width = calcDp(percentage = 0.8f, dimension = CalcSizes.Dimension.Width) / 100,
brush = Brush.horizontalGradient(
colors = listOf(Orange80, Color.White, Purple80)
),
shape = ShapeDefaults.ExtraSmall
)
)
}
| 0
|
Kotlin
|
0
| 0
|
156528573a66c4023495e6e9d86410b22abd06af
| 1,645
|
Abschlussprojekt_Kotlin_Husewok
|
Apache License 2.0
|
shared/src/commonMain/kotlin/ch/dreipol/multiplatform/reduxsample/shared/redux/middleware/StoreRatingMiddleware.kt
|
terrakok
| 334,467,384
| true
|
{"Kotlin": 145354, "Swift": 99066, "Ruby": 16325, "Shell": 483}
|
package ch.dreipol.multiplatform.reduxsample.shared.redux.middleware
import ch.dreipol.multiplatform.reduxsample.shared.redux.AppState
import ch.dreipol.multiplatform.reduxsample.shared.redux.actions.OpenedWithReminderNotification
import ch.dreipol.multiplatform.reduxsample.shared.utils.SettingsHelper
import ch.dreipol.multiplatform.reduxsample.shared.utils.getAppConfiguration
import org.reduxkotlin.middleware
fun storeRatingMiddleware() = middleware<AppState> { _, next, action ->
when (action) {
is OpenedWithReminderNotification -> {
if (SettingsHelper.hasRatingShown().not()) {
showRating()
}
Unit
}
else -> next(action)
}
}
private fun showRating() {
getAppConfiguration().platformFeatures.showRatingDialog()
SettingsHelper.setRatingShowed(true)
}
| 0
|
Kotlin
|
0
| 1
|
d35f0034f3fa870c00dd783d692dc586c8785614
| 852
|
multiplatform-redux-sample
|
MIT License
|
clients/android/app/src/main/java/app/lockbook/model/DetailScreenLoaderViewModel.kt
|
lockbook
| 231,677,385
| false
|
{"Rust": 2021419, "Swift": 403831, "Kotlin": 384034, "HTML": 20335, "Shell": 9717, "Makefile": 5918, "CSS": 5835, "JavaScript": 3707, "C": 65}
|
package app.lockbook.model
import android.app.Application
import android.graphics.BitmapFactory
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.viewModelScope
import app.lockbook.util.*
import com.github.michaelbull.result.Err
import com.github.michaelbull.result.Ok
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
class DetailScreenLoaderViewModel(application: Application, val loadingInfo: DetailScreen.Loading) :
AndroidViewModel(application) {
private val _updateDetailScreenLoaderUI = SingleMutableLiveData<UpdateDetailScreenLoaderUI>()
val updateDetailScreenLoaderUI: LiveData<UpdateDetailScreenLoaderUI>
get() = _updateDetailScreenLoaderUI
init {
viewModelScope.launch(Dispatchers.IO) {
loadContent(loadingInfo)
}
}
private fun loadContent(loadingInfo: DetailScreen.Loading) {
val extensionHelper = ExtensionHelper(loadingInfo.file.name)
val updateUI = when {
extensionHelper.isDrawing -> {
when (val getDrawingResult = CoreModel.getDrawing(loadingInfo.file.id)) {
is Ok -> {
UpdateDetailScreenLoaderUI.NotifyFinished(
DetailScreen.Drawing(
loadingInfo.file,
getDrawingResult.value
)
)
}
is Err ->
return _updateDetailScreenLoaderUI.postValue(
UpdateDetailScreenLoaderUI.NotifyError(
getDrawingResult.error.toLbError(getRes())
)
)
}
}
extensionHelper.isImage -> {
val bytes = CoreModel.readDocumentBytes(loadingInfo.file.id)
if (bytes == null) {
UpdateDetailScreenLoaderUI.NotifyError(LbError.basicError(getRes()))
} else {
UpdateDetailScreenLoaderUI.NotifyFinished(
DetailScreen.ImageViewer(
loadingInfo.file,
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
)
)
}
}
extensionHelper.isPdf -> {
val child = File(getContext().cacheDir, OPENED_FILE_FOLDER)
child.deleteRecursively()
child.mkdir()
when (val exportFileResult = CoreModel.exportFile(loadingInfo.file.id, child.toString(), true)) {
is Ok -> UpdateDetailScreenLoaderUI.NotifyFinished(DetailScreen.PdfViewer(loadingInfo.file, child))
is Err -> {
UpdateDetailScreenLoaderUI.NotifyError(exportFileResult.error.toLbError(getRes()))
}
}
}
else -> {
val text = when (val readDocumentResult = CoreModel.readDocument(loadingInfo.file.id)) {
is Ok -> readDocumentResult.value
is Err ->
return _updateDetailScreenLoaderUI.postValue(
UpdateDetailScreenLoaderUI.NotifyError(
readDocumentResult.error.toLbError(getRes())
)
)
}
UpdateDetailScreenLoaderUI.NotifyFinished(
DetailScreen.TextEditor(loadingInfo.file, text)
)
}
}
_updateDetailScreenLoaderUI.postValue(updateUI)
}
}
sealed class UpdateDetailScreenLoaderUI {
data class NotifyFinished(val newScreen: DetailScreen) : UpdateDetailScreenLoaderUI()
data class NotifyError(val error: LbError) : UpdateDetailScreenLoaderUI()
}
class ExtensionHelper(fileName: String) {
val extension = File(fileName).extension
val isImage: Boolean
get() = extension in setOf(
"jpeg",
"jpg",
"png"
)
val isDrawing: Boolean get() = extension == "draw"
val isPdf: Boolean get() = extension == "pdf"
}
const val OPENED_FILE_FOLDER = "opened-files/"
| 197
|
Rust
|
4
| 82
|
6e1f6da58db203feac86de76b3490b20f12b8168
| 4,369
|
lockbook
|
The Unlicense
|
app/src/main/java/com/example/belindas_closet/screen/SignUp.kt
|
SeattleColleges
| 656,918,420
| false
|
{"Kotlin": 93917}
|
package com.example.belindas_closet.screen
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.isSystemInDarkTheme
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import com.example.belindas_closet.R
import com.example.belindas_closet.Routes
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SignUpPage( navController: NavHostController) {
var firstName by remember { mutableStateOf("") }
var lastName by remember { mutableStateOf("") }
var email by remember { mutableStateOf("") }
var password by remember { mutableStateOf("") }
var confirmPassword by remember { mutableStateOf("") }
var isEmailValid by remember { mutableStateOf(true) }
var isPasswordValid by remember { mutableStateOf(true) }
var doPasswordsMatch by remember { mutableStateOf(true) }
var isPasswordVisible by remember { mutableStateOf(false) }
var isConfirmPasswordVisible by remember { mutableStateOf(false) }
/* Back arrow that navigates back to login page */
TopAppBar(
title = { Text("Login") },
navigationIcon = {
IconButton(
onClick = {
navController.navigate(Routes.Login.route)
}
) {
Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "Back")
}
}
)
Column (
modifier = Modifier
.fillMaxSize()
.wrapContentSize(Alignment.Center),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Image(
painter = painterResource(id = R.drawable.packaging),
contentDescription = stringResource(id = R.string.signup_logo_description),
modifier = Modifier
.size(50.dp)
)
Text(
text = stringResource(id = R.string.signup_title),
style = TextStyle(
fontSize = 30.sp,
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Light,
color = if (isSystemInDarkTheme()) Color.White else Color.Black
),
modifier = Modifier
.wrapContentSize()
)
Box(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
contentAlignment = Alignment.Center
) {
Column(
modifier = Modifier
.fillMaxWidth()
.background(
color = MaterialTheme.colorScheme.surfaceVariant,
shape = MaterialTheme.shapes.small
),
) {
// First name field
TextField(
value = firstName,
onValueChange = {
firstName = it
},
label = { Text(text = stringResource(id = R.string.signup_first_name)) },
singleLine = true,
modifier = Modifier
.fillMaxWidth()
.padding(start = 30.dp, top = 30.dp, end = 30.dp, bottom = 16.dp)
)
// Last name field
TextField(
value = lastName,
onValueChange = {
lastName = it
},
label = { Text(text = stringResource(id = R.string.signup_last_name)) },
singleLine = true,
modifier = Modifier
.fillMaxWidth()
.padding(start = 30.dp, end = 30.dp, bottom = 16.dp)
)
// Email field
TextField(
value = email,
onValueChange = {
email = it
isEmailValid = validateEmail(it)
},
isError = !isEmailValid,
label = { Text(text = stringResource(id = R.string.signup_email)) },
singleLine = true,
modifier = Modifier
.fillMaxWidth()
.padding(start = 30.dp, end = 30.dp, bottom = 16.dp)
)
// Email display error
if (!isEmailValid) {
ErrorDisplay(text = stringResource(id = R.string.signup_email_error))
}
// Password field and toggle button
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
// Password field
TextField(
value = password,
onValueChange = {
password = it
isPasswordValid = validatePassword(it)
doPasswordsMatch = validateConfirmPassword(password, confirmPassword)
},
isError = !isPasswordValid,
label = { Text(text = stringResource(id = R.string.signup_password)) },
singleLine = true,
visualTransformation = if (isPasswordVisible) VisualTransformation.None else PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
modifier = Modifier
.weight(1f)
.padding(start = 30.dp, end = 8.dp, bottom = 16.dp),
)
// Toggle button to show/hide password
IconButton(
onClick = {
isPasswordVisible = !isPasswordVisible
}
) {
Icon(
painter = if (isPasswordVisible) painterResource(R.drawable.baseline_visibility_24) else painterResource(R.drawable.baseline_visibility_off_24),
contentDescription = if (isPasswordVisible) "Hide Password" else "Show Password",
modifier = Modifier
.padding(top = 15.dp),
)
}
}
// Password display error
if (!isPasswordValid) {
ErrorDisplay(text = stringResource(id = R.string.signup_password_error))
}
// Confirm password field and toggle button
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
// Confirm password field
TextField(
value = confirmPassword,
onValueChange = {
confirmPassword = it
doPasswordsMatch = validateConfirmPassword(password, it)
},
isError = !doPasswordsMatch,
label = { Text(text = stringResource(id = R.string.signup_confirm_password)) },
singleLine = true,
visualTransformation = if (isConfirmPasswordVisible) VisualTransformation.None else PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
modifier = Modifier
.weight(1f)
.padding(start = 30.dp, end = 8.dp, bottom = 16.dp),
)
// Toggle button to show/hide confirm password
IconButton(
onClick = {
isConfirmPasswordVisible = !isConfirmPasswordVisible
}
) {
Icon(
painter = if (isConfirmPasswordVisible) painterResource(R.drawable.baseline_visibility_24) else painterResource(R.drawable.baseline_visibility_off_24),
contentDescription = if (isConfirmPasswordVisible) "Hide Confirm Password" else "Show Confirm Password",
modifier = Modifier
.padding(top = 15.dp),
)
}
}
// Confirm password display error
if (!doPasswordsMatch) {
ErrorDisplay(text = stringResource(id = R.string.signup_confirm_password_error))
}
// SignUp button
Button(
onClick = {
try {
// TODO: Add sign up functionality
} catch (e: Exception) {
// TODO: Add error handling
}
},
modifier = Modifier
.padding(16.dp)
.width(225.dp)
.align(Alignment.CenterHorizontally),
) {
Text(
text = stringResource(id = R.string.signup_button_text).uppercase(),
style = TextStyle(
fontSize = 14.sp,
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Bold,
)
)
}
}
}
}
}
fun validateConfirmPassword(password: String, confirmPassword: String): Boolean {
return password.isNotEmpty() && password.isNotBlank() && password == confirmPassword
}
| 23
|
Kotlin
|
4
| 5
|
1dd5a3c4ae39a23027d03630bdeca10b22cd5b2b
| 11,829
|
belindas-closet-android
|
MIT License
|
src/main/kotlin/org/wfanet/measurement/storage/testing/InMemoryStorageClient.kt
|
world-federation-of-advertisers
| 375,798,604
| 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.storage.testing
import com.google.protobuf.ByteString
import java.util.concurrent.ConcurrentHashMap
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.wfanet.measurement.common.BYTES_PER_MIB
import org.wfanet.measurement.common.asBufferedFlow
import org.wfanet.measurement.common.flatten
import org.wfanet.measurement.storage.StorageClient
/**
* The default byte buffer size. Chosen as it is a commonly used default buffer size in an attempt
* to keep the tests as close to actual usage as possible.
*/
private const val BYTE_BUFFER_SIZE = BYTES_PER_MIB * 1
/** In-memory [StorageClient]. */
class InMemoryStorageClient : StorageClient {
private val storageMap = ConcurrentHashMap<String, StorageClient.Blob>()
/** Exposes all the blobs in the [StorageClient]. */
val contents: Map<String, StorageClient.Blob>
get() = storageMap
private fun deleteKey(path: String) {
storageMap.remove(path)
}
override val defaultBufferSizeBytes: Int
get() = BYTE_BUFFER_SIZE
override suspend fun createBlob(blobKey: String, content: Flow<ByteString>): StorageClient.Blob {
return withContext(Dispatchers.IO) {
var created = false
val blob =
storageMap.getOrPut(blobKey) {
created = true
Blob(blobKey, runBlocking { content.flatten() })
}
require(created) { "Blob with key $blobKey already exists" }
blob
}
}
override fun getBlob(blobKey: String): StorageClient.Blob? {
return storageMap[blobKey]
}
private inner class Blob(private val blobKey: String, private val content: ByteString) :
StorageClient.Blob {
override val size: Long
get() = content.size().toLong()
override val storageClient: InMemoryStorageClient
get() = this@InMemoryStorageClient
override fun read(bufferSizeBytes: Int): Flow<ByteString> =
content.asBufferedFlow(bufferSizeBytes)
override fun delete() = storageClient.deleteKey(blobKey)
}
}
| 3
|
Kotlin
|
0
| 1
|
38773d0dfe5661a9affb72ef27bd56424dd0fedd
| 2,711
|
common-jvm
|
Apache License 2.0
|
core/src/main/java/com/ramitsuri/notificationjournal/core/utils/Constants.kt
|
ramitsuri
| 667,037,607
| false
|
{"Kotlin": 274675, "Shell": 8329, "Python": 3405, "HTML": 1499, "JavaScript": 1016}
|
package com.ramitsuri.notificationjournal.core.utils
object Constants {
const val REMOTE_INPUT_JOURNAL_KEY = "remote_input_journal_text"
const val ACTION_JOURNAL = "action_journal"
const val ACTION_UPLOAD = "action_upload"
const val PREF_FILE = "com.ramitsuri.notificationjournal.prefs"
const val PREF_KEY_API_URL = "api_url"
const val PREF_KEY_SORT_ORDER = "sort_order"
const val DEFAULT_API_URL = "http://test.com"
object DataSharing {
const val JOURNAL_ENTRY_ROUTE = "/journal"
const val JOURNAL_ENTRY_VALUE = "journal_entry_value"
const val JOURNAL_ENTRY_TIME = "journal_entry_time"
const val JOURNAL_ENTRY_TIME_ZONE = "journal_entry_time_zone"
const val JOURNAL_ENTRY_TAG = "journal_entry_tag"
const val REQUEST_UPLOAD_ROUTE = "/upload"
const val TEMPLATE_ROUTE = "/template"
const val TEMPLATE_ID = "template_id"
const val TEMPLATE_VALUE = "template_value"
const val TEMPLATE_TAG = "template_tag"
}
}
| 0
|
Kotlin
|
0
| 0
|
f669ff08cfa0bc8a725ea34887c7fc2e7177747c
| 1,026
|
notification-journal
|
MIT License
|
app/src/main/java/com/hasbihal/ui/register/RegisterViewModel.kt
|
hasbihal
| 148,445,846
| false
| null |
package com.hasbihal.ui.register
import androidx.lifecycle.ViewModel
import com.google.firebase.auth.FirebaseAuth
import com.hasbihal.data.model.User
import timber.log.Timber
class RegisterViewModel: ViewModel() {
val fireBaseAuth = FirebaseAuth.getInstance()
// TODO : Covert the arguments to user model object
fun register(mail: String, password: String) {
fireBaseAuth.createUserWithEmailAndPassword(mail, password)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Timber.d("The task is successfully completed")
} else {
Timber.d("There is an error : "+task.exception)
}
}
}
}
| 0
|
Kotlin
|
0
| 3
|
adb30f036ccaa337f4160bebecbc844f61d3871a
| 755
|
android
|
MIT License
|
app/src/main/java/com/kudesta/bettergeeks/screens/ask_question/AskQuestionFragment.kt
|
vylhart
| 644,937,601
| false
| null |
package com.kudesta.bettergeeks.screens.ask_question
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.kudesta.bettergeeks.R
import com.kudesta.bettergeeks.data.model.local.TopicData
import com.kudesta.bettergeeks.databinding.FragmentAskQuestionBinding
import com.kudesta.bettergeeks.screens.add_topic.AddTopicFragment
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class AskQuestionFragment : Fragment() {
private lateinit var binding: FragmentAskQuestionBinding
private val viewModel: AskQuestionViewModel by viewModels()
private var menuList: Menu? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = FragmentAskQuestionBinding.inflate(inflater, container, false)
setObservers()
setHasOptionsMenu(true)
return binding.root
}
private fun setObservers() {
binding.editTextQuestion.setOnEditorActionListener { _, _, _ ->
val question = binding.editTextQuestion.text.toString().trim()
viewModel.generateAnswer(question)
true
}
viewModel.list.observe(viewLifecycleOwner) {
binding.spinner.adapter = ArrayAdapter(
requireContext(),
R.layout.spinner_item,
it.map { topicData -> topicData.topicName })
binding.spinner.onItemSelectedListener = getSpinnerListener(it)
}
viewModel.textResponse.observe(viewLifecycleOwner) {
when (it) {
is ResponseData.Success -> {
binding.responseLayout.apply {
if (it.data.answer != null && it.data.question != null) {
setText(it.data.answer)
setQuestion(it.data.question)
//setClickListener { viewModel.save(it.data) }
}
}
menuList?.findItem(R.id.nav_save)?.isVisible = true
}
is ResponseData.Error -> {
showToast(it.message)
}
}
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
this.menuList = menu
inflater.inflate(R.menu.ask_menu, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId){
R.id.nav_save -> {
viewModel.save()
}
R.id.nav_add_topic -> {
AddTopicFragment().show(parentFragmentManager, "AddTopicFragment")
}
}
return super.onOptionsItemSelected(item)
}
private fun showToast(message: String) {
Toast.makeText(requireActivity(), message, Toast.LENGTH_SHORT).show()
}
private fun getSpinnerListener(topicData: List<TopicData>): AdapterView.OnItemSelectedListener {
return object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
val selectedTopic = parent?.getItemAtPosition(position) as String
viewModel.selectedTopic = topicData.find { it.topicName == selectedTopic }
}
override fun onNothingSelected(parent: AdapterView<*>?) {
viewModel.selectedTopic = null
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
d7fae7a4a7d8bd3ba0e09414030bc1b157a1fe3a
| 3,910
|
BetterGeeks
|
Apache License 2.0
|
app/src/main/java/com/example/slore/MainActivity.kt
|
knightafter
| 802,131,272
| false
|
{"Kotlin": 197766}
|
package com.example.slore
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.slore.ui.theme.SloreTheme
import com.google.firebase.FirebaseApp
class MainActivity : ComponentActivity() {
private lateinit var activityResultLauncher: ActivityResultLauncher<Intent>
private val PERMISSION_REQUEST_CODE = 1001
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
FirebaseApp.initializeApp(this) // Initialize Firebase
enableEdgeToEdge()
//code from here to before the set content is a process to send the notification to the user when the download is successfully completed
NotificationHelper.createNotificationChannel(this)
// Request notification permission if needed
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.POST_NOTIFICATIONS), 1)
}
}
setContent {
SloreTheme {
NavGraph()
}
}
// Initialize the ActivityResultLauncher
activityResultLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
// Handle the result of the activity
}
checkAndRequestPermissions()
}
private fun checkAndRequestPermissions() {
val permissions = arrayOf(
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
val permissionsToRequest = permissions.filter {
ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
}
if (permissionsToRequest.isNotEmpty()) {
ActivityCompat.requestPermissions(
this,
permissionsToRequest.toTypedArray(),
PERMISSION_REQUEST_CODE
)
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == PERMISSION_REQUEST_CODE) {
if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
// Permission granted, proceed with your functionality
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show()
}
}
}
}
| 0
|
Kotlin
|
0
| 2
|
943ea1b22ea44650460ff8f07946df7f41928b43
| 3,181
|
Slore--A-Password-and-Notes-Manager-App.
|
Apache License 2.0
|
android/engine/src/test/java/org/smartregister/fhircore/engine/rulesengine/RulesFactoryTest.kt
|
opensrp
| 339,242,809
| false
| null |
/*
* Copyright 2021-2023 Ona Systems, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.smartregister.fhircore.engine.rulesengine
import androidx.test.core.app.ApplicationProvider
import com.google.android.fhir.logicalId
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.runs
import io.mockk.slot
import io.mockk.spyk
import io.mockk.verify
import java.util.Date
import javax.inject.Inject
import org.apache.commons.jexl3.JexlException
import org.hl7.fhir.r4.model.Address
import org.hl7.fhir.r4.model.CarePlan
import org.hl7.fhir.r4.model.CodeableConcept
import org.hl7.fhir.r4.model.Coding
import org.hl7.fhir.r4.model.Condition
import org.hl7.fhir.r4.model.ContactPoint
import org.hl7.fhir.r4.model.Enumerations
import org.hl7.fhir.r4.model.HumanName
import org.hl7.fhir.r4.model.Identifier
import org.hl7.fhir.r4.model.Meta
import org.hl7.fhir.r4.model.Patient
import org.hl7.fhir.r4.model.Reference
import org.hl7.fhir.r4.model.Resource
import org.hl7.fhir.r4.model.ResourceType
import org.hl7.fhir.r4.model.StringType
import org.hl7.fhir.r4.model.Task
import org.hl7.fhir.r4.model.Task.TaskStatus
import org.jeasy.rules.api.Facts
import org.jeasy.rules.api.Rules
import org.jeasy.rules.core.DefaultRulesEngine
import org.joda.time.LocalDate
import org.joda.time.Period
import org.joda.time.format.DateTimeFormat
import org.joda.time.format.DateTimeFormatter
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.robolectric.util.ReflectionHelpers
import org.smartregister.fhircore.engine.app.fakes.Faker
import org.smartregister.fhircore.engine.configuration.ConfigurationRegistry
import org.smartregister.fhircore.engine.domain.model.RuleConfig
import org.smartregister.fhircore.engine.robolectric.RobolectricTest
import org.smartregister.fhircore.engine.util.fhirpath.FhirPathDataExtractor
@HiltAndroidTest
class RulesFactoryTest : RobolectricTest() {
@get:Rule(order = 0) val hiltAndroidRule = HiltAndroidRule(this)
@Inject lateinit var fhirPathDataExtractor: FhirPathDataExtractor
private val rulesEngine = mockk<DefaultRulesEngine>()
private val configurationRegistry: ConfigurationRegistry = Faker.buildTestConfigurationRegistry()
private lateinit var rulesFactory: RulesFactory
private lateinit var rulesEngineService: RulesFactory.RulesEngineService
@Before
fun setUp() {
hiltAndroidRule.inject()
rulesFactory =
spyk(
RulesFactory(
ApplicationProvider.getApplicationContext(),
configurationRegistry,
fhirPathDataExtractor
)
)
rulesEngineService = rulesFactory.RulesEngineService()
}
@Test
fun initClearsExistingFacts() {
val facts = ReflectionHelpers.getField<Facts>(rulesFactory, "facts")
Assert.assertEquals(0, facts.asMap().size)
}
@Test
fun beforeEvaluateReturnsTrue() {
Assert.assertTrue(rulesFactory.beforeEvaluate(mockk(), mockk()))
}
@Test
fun fireRuleCallsRulesEngineFireWithCorrectRulesAndFacts() {
val baseResource = populateTestPatient()
val relatedResourcesMap: Map<String, List<Resource>> = emptyMap()
val ruleConfig =
RuleConfig(
name = "patientName",
description = "Retrieve patient name",
actions = listOf("data.put('familyName', fhirPath.extractValue(Group, 'Group.name'))")
)
val ruleConfigs = listOf(ruleConfig)
ReflectionHelpers.setField(rulesFactory, "rulesEngine", rulesEngine)
every { rulesEngine.fire(any(), any()) } just runs
rulesFactory.fireRule(
ruleConfigs = ruleConfigs,
baseResource = baseResource,
relatedResourcesMap = relatedResourcesMap
)
val factsSlot = slot<Facts>()
val rulesSlot = slot<Rules>()
verify { rulesEngine.fire(capture(rulesSlot), capture(factsSlot)) }
val capturedBaseResource = factsSlot.captured.get<Patient>(baseResource.resourceType.name)
Assert.assertEquals(baseResource.logicalId, capturedBaseResource.logicalId)
Assert.assertTrue(capturedBaseResource.active)
Assert.assertEquals(baseResource.birthDate, capturedBaseResource.birthDate)
Assert.assertEquals(baseResource.name[0].given, capturedBaseResource.name[0].given)
Assert.assertEquals(
baseResource.address[0].city,
capturedBaseResource.address[0].city,
)
val capturedRule = rulesSlot.captured.first()
Assert.assertEquals(ruleConfig.name, capturedRule.name)
Assert.assertEquals(ruleConfig.description, capturedRule.description)
}
@Test
fun retrieveRelatedResourcesReturnsCorrectResource() {
populateFactsWithResources()
val result =
rulesEngineService.retrieveRelatedResources(
resource = populateTestPatient(),
relatedResourceType = ResourceType.CarePlan,
fhirPathExpression = "CarePlan.subject.reference"
)
Assert.assertEquals(1, result.size)
Assert.assertEquals("CarePlan", result[0].resourceType.name)
Assert.assertEquals("careplan-1", result[0].logicalId)
}
@Test
fun retrieveParentResourcesReturnsCorrectResource() {
populateFactsWithResources()
val result =
rulesEngineService.retrieveParentResource(
childResource = populateCarePlan(),
parentResourceType = "Patient",
fhirPathExpression = "CarePlan.subject.reference"
)
Assert.assertEquals("Patient", result!!.resourceType.name)
Assert.assertEquals("patient-1", result.logicalId)
}
@Test
fun extractGenderReturnsCorrectGender() {
Assert.assertEquals(
"Male",
rulesEngineService.extractGender(Patient().setGender(Enumerations.AdministrativeGender.MALE))
)
Assert.assertEquals(
"Female",
rulesEngineService.extractGender(
Patient().setGender(Enumerations.AdministrativeGender.FEMALE)
)
)
Assert.assertEquals(
"Other",
rulesEngineService.extractGender(Patient().setGender(Enumerations.AdministrativeGender.OTHER))
)
Assert.assertEquals(
"Unknown",
rulesEngineService.extractGender(
Patient().setGender(Enumerations.AdministrativeGender.UNKNOWN)
)
)
Assert.assertEquals("", rulesEngineService.extractGender(Patient()))
}
@Test
fun extractDOBReturnsCorrectDate() {
Assert.assertEquals(
"03/10/2015",
rulesEngineService.extractDOB(
Patient().setBirthDate(LocalDate.parse("2015-10-03").toDate()),
"dd/MM/YYYY"
)
)
}
@Test
fun shouldFormatDateWithExpectedFormat() {
val inputDate = Date("2021/10/10")
val expectedFormat = "dd-MM-yyyy"
Assert.assertEquals("10-10-2021", rulesEngineService.formatDate(inputDate, expectedFormat))
val expectedFormat2 = "dd yyyy"
Assert.assertEquals("10 2021", rulesEngineService.formatDate(inputDate, expectedFormat2))
Assert.assertEquals("Sun, Oct 10 2021", rulesEngineService.formatDate(inputDate))
}
@Test
fun shouldInputDateStringWithExpectedFormat() {
val inputDateString = "2021-10-10"
val inputDateFormat = "yyyy-MM-dd"
val expectedFormat = "dd-MM-yyyy"
Assert.assertEquals(
"10-10-2021",
rulesEngineService.formatDate(inputDateString, inputDateFormat, expectedFormat)
)
val expectedFormat2 = "dd yyyy"
Assert.assertEquals(
"10 2021",
rulesEngineService.formatDate(inputDateString, inputDateFormat, expectedFormat2)
)
Assert.assertEquals(
"Sun, Oct 10 2021",
rulesEngineService.formatDate(inputDateString, inputDateFormat)
)
}
@Test
fun shouldInputDateTimeStringWithExpectedFormat() {
val inputDateString = "2023-09-01T00:00:00.00Z"
val inputDateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
val expectedFormat = "dd-MM-yyyy"
Assert.assertEquals(
"01-09-2023",
rulesEngineService.formatDate(inputDateString, inputDateFormat, expectedFormat)
)
}
@Test
fun mapResourcesToLabeledCSVReturnsCorrectLabels() {
val fhirPathExpression = "Patient.active and (Patient.birthDate >= today() - 5 'years')"
val resources =
listOf(
Patient().setBirthDate(LocalDate.parse("2015-10-03").toDate()),
Patient().setActive(true).setBirthDate(LocalDate.parse("2019-10-03").toDate()),
Patient().setActive(true).setBirthDate(LocalDate.parse("2020-10-03").toDate())
)
val result = rulesEngineService.mapResourcesToLabeledCSV(resources, fhirPathExpression, "CHILD")
Assert.assertEquals("CHILD,CHILD", result)
}
@Test
fun mapResourceToLabeledCSVReturnsCorrectLabels() {
val fhirPathExpression = "Patient.active and (Patient.birthDate >= today() - 5 'years')"
val resource = Patient().setActive(true).setBirthDate(LocalDate.parse("2019-10-03").toDate())
val result = rulesEngineService.mapResourceToLabeledCSV(resource, fhirPathExpression, "CHILD")
Assert.assertEquals("CHILD", result)
}
@Test
fun filterResourceList() {
val fhirPathExpression =
"Task.status = 'ready' or Task.status = 'cancelled' or Task.status = 'failed'"
val resources =
listOf(
Task().apply { status = TaskStatus.COMPLETED },
Task().apply { status = TaskStatus.READY },
Task().apply { status = TaskStatus.CANCELLED }
)
Assert.assertTrue(
rulesEngineService.filterResources(
resources = resources,
fhirPathExpression = fhirPathExpression
)
.size == 2
)
}
@Test
fun fetchDescriptionFromReadyTasks() {
val fhirPathExpression = "Task.status = 'ready'"
val resources =
listOf(
Task().apply {
status = TaskStatus.COMPLETED
description = "minus"
},
Task().apply {
status = TaskStatus.READY
description = "plus"
},
Task().apply {
status = TaskStatus.CANCELLED
description = "multiply"
},
Task().apply {
status = TaskStatus.COMPLETED
description = "minus five"
},
)
val filteredTask = rulesEngineService.filterResources(resources, fhirPathExpression)
val descriptionList =
rulesEngineService.mapResourcesToExtractedValues(filteredTask, "Task.description")
Assert.assertTrue(descriptionList.first() == "plus")
}
@Test
fun filterResourceListWithWrongExpression() {
val fhirPathExpression = "Task.status = 'not ready'"
val resources =
listOf(
Task().apply { status = TaskStatus.COMPLETED },
Task().apply { status = TaskStatus.REQUESTED },
Task().apply { status = TaskStatus.CANCELLED }
)
val results = rulesEngineService.filterResources(resources, fhirPathExpression)
Assert.assertTrue(results.isEmpty())
}
@Test
fun pickNamesOfPatientFromCertainAge() {
val fhirPathExpression =
"(Patient.birthDate <= today() - 2 'years') and (Patient.birthDate >= today() - 4 'years')"
val resources =
listOf(
Patient().apply {
birthDate = LocalDate.parse("2015-10-03").toDate()
addName().apply { family = "alpha" }
},
Patient().apply {
birthDate = LocalDate.parse("2017-10-03").toDate()
addName().apply { family = "beta" }
},
Patient().apply {
birthDate = LocalDate.parse("2018-10-03").toDate()
addName().apply { family = "gamma" }
},
Patient().apply {
birthDate = LocalDate.parse("2019-10-03").toDate()
addName().apply { family = "rays" }
},
Patient().apply {
birthDate = LocalDate.parse("2021-10-03").toDate()
addName().apply { family = "light" }
},
)
val patientsList = rulesEngineService.filterResources(resources, fhirPathExpression)
val names =
rulesEngineService.mapResourcesToExtractedValues(patientsList, "Patient.name.family")
Assert.assertTrue(names.isNotEmpty())
}
@Test
fun pickCodesFromCertainConditions() {
val resources =
listOf(
Condition().apply {
id = "001"
clinicalStatus = CodeableConcept(Coding("", "0001", "Pregnant"))
},
Condition().apply {
id = "002"
clinicalStatus = CodeableConcept(Coding("", "0002", "Family Planning"))
}
)
val conditions =
rulesEngineService.filterResources(
resources,
"Condition.clinicalStatus.coding.display = 'Pregnant'"
)
val conditionIds = rulesEngineService.mapResourcesToExtractedValues(conditions, "Condition.id")
Assert.assertTrue(conditionIds.first() == "001")
}
@Test
fun evaluateToBooleanReturnsCorrectValueWhenMatchAllIsTrue() {
val fhirPathExpression = "Patient.active"
val patients =
mutableListOf(Patient().setActive(true), Patient().setActive(true), Patient().setActive(true))
Assert.assertTrue(rulesEngineService.evaluateToBoolean(patients, fhirPathExpression, true))
patients.add(Patient().setActive(false))
Assert.assertFalse(rulesEngineService.evaluateToBoolean(patients, fhirPathExpression, true))
}
@Test
fun evaluateToBooleanReturnsCorrectValueWhenMatchAllIsFalse() {
val fhirPathExpression = "Patient.active"
val patients =
mutableListOf(Patient().setActive(true), Patient().setActive(true), Patient().setActive(true))
Assert.assertTrue(rulesEngineService.evaluateToBoolean(patients, fhirPathExpression, false))
patients.add(Patient().setActive(false))
Assert.assertTrue(rulesEngineService.evaluateToBoolean(patients, fhirPathExpression, false))
}
@Test
fun onFailureLogsWarningForJexlException_Variable() {
val exception = mockk<JexlException.Variable>()
every { exception.localizedMessage } returns "jexl exception"
every { exception.variable } returns "var"
rulesFactory.onFailure(mockk(relaxed = true), mockk(relaxed = true), exception)
verify {
rulesFactory.log(
exception,
"jexl exception, consider checking for null before usage: e.g var != null"
)
}
}
@Test
fun onFailureLogsErrorForException() {
val exception = mockk<Exception>()
every { exception.localizedMessage } returns "jexl exception"
rulesFactory.onFailure(mockk(relaxed = true), mockk(relaxed = true), exception)
verify { rulesFactory.log(exception) }
}
@Test
fun onEvaluationErrorLogsError() {
val exception = mockk<Exception>()
every { exception.localizedMessage } returns "jexl exception"
rulesFactory.onEvaluationError(mockk(relaxed = true), mockk(relaxed = true), exception)
verify { rulesFactory.log(exception, "Evaluation error") }
}
@Test
fun testGenerateRandomNumberOfLengthSix() {
val generatedNumber = rulesEngineService.generateRandomSixDigitInt()
Assert.assertEquals(generatedNumber.toString().length, 6)
}
@Test
fun testFilterListShouldReturnMatchingResource() {
val resources =
listOf(
Condition().apply {
id = "1"
clinicalStatus = CodeableConcept(Coding("", "0001", "pregnant"))
},
Condition().apply {
id = "2"
clinicalStatus = CodeableConcept(Coding("", "0002", "family-planning"))
}
)
val result = rulesEngineService.filterResources(resources, "Condition.id = 2")
Assert.assertTrue(result.size == 1)
with(result.first() as Condition) {
Assert.assertEquals("2", id)
Assert.assertEquals("0002", clinicalStatus.codingFirstRep.code)
Assert.assertEquals("family-planning", clinicalStatus.codingFirstRep.display)
}
}
@Test
fun testFilterListShouldReturnEmptyListWhenFieldNotFound() {
val listOfResources =
listOf(
Condition().apply {
id = "1"
clinicalStatus = CodeableConcept(Coding("", "0001", "pregnant"))
}
)
val result = rulesEngineService.filterResources(listOfResources, "unknown_field")
Assert.assertTrue(result.isEmpty())
}
private fun populateFactsWithResources() {
val carePlanRelatedResource = mutableListOf(populateCarePlan())
val patientRelatedResource = mutableListOf(populateTestPatient())
val facts = ReflectionHelpers.getField<Facts>(rulesFactory, "facts")
facts.apply {
put(carePlanRelatedResource[0].resourceType.name, carePlanRelatedResource)
put(patientRelatedResource[0].resourceType.name, patientRelatedResource)
}
ReflectionHelpers.setField(rulesFactory, "facts", facts)
}
private fun populateTestPatient(): Patient {
val patientId = "patient-1"
val patient: Patient =
Patient().apply {
id = patientId
active = true
birthDate = LocalDate.parse("1999-10-03").toDate()
gender = Enumerations.AdministrativeGender.MALE
address =
listOf(
Address().apply {
city = "Nairobi"
country = "Kenya"
}
)
name =
listOf(
HumanName().apply {
given = mutableListOf(StringType("Kiptoo"))
family = "Maina"
}
)
telecom = listOf(ContactPoint().apply { value = "12345" })
meta = Meta().apply { lastUpdated = Date() }
}
return patient
}
private fun populateCarePlan(): CarePlan {
val carePlan: CarePlan =
CarePlan().apply {
id = "careplan-1"
identifier =
mutableListOf(
Identifier().apply {
use = Identifier.IdentifierUse.OFFICIAL
value = "value-1"
}
)
subject = Reference().apply { reference = "Patient/patient-1" }
}
return carePlan
}
@Test
fun testPrettifyDateReturnXDaysAgo() {
val weeksAgo = 2
val inputDateString = LocalDate.now().minusWeeks(weeksAgo).toString()
val expected = rulesFactory.RulesEngineService().prettifyDate(inputDateString)
Assert.assertEquals("$weeksAgo weeks ago", expected)
}
@Test
fun testPrettifyDateWithDateAsInput() {
val inputDate = Date()
val expected = rulesFactory.RulesEngineService().prettifyDate(inputDate)
Assert.assertEquals("", expected)
}
@Test
fun extractAge() {
val dateFormatter: DateTimeFormatter? = DateTimeFormat.forPattern("yyyy-MM-dd")
val period =
Period(
LocalDate.parse("2005-01-01", dateFormatter),
LocalDate.parse(LocalDate.now().toString(), dateFormatter)
)
Assert.assertEquals(
period.years.toString() + "y",
rulesEngineService.extractAge(Patient().setBirthDate(LocalDate.parse("2005-01-01").toDate()))
)
}
}
| 140
|
Kotlin
|
12
| 24
|
70489e14827789efe8096196e452b8a206a03996
| 19,196
|
fhircore
|
Apache License 2.0
|
src/main/kotlin/ca.jrvs.trading/controller/QuoteController.kt
|
syumet
| 307,445,286
| false
| null |
package ca.jrvs.trading.controller
import ca.jrvs.trading.domain.Quote
import ca.jrvs.trading.domain.iex.IexQuoteDto
import ca.jrvs.trading.service.QuoteService
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.*
@Api(value = "quote", produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
@RequestMapping("/quote")
class QuoteController(val quoteService: QuoteService) {
@ApiOperation(value = "Show the dailyList", notes = "Show dailyList for this trading system.")
@GetMapping(path = ["/dailyList"])
@ResponseStatus(HttpStatus.OK)
fun getDailyList(): List<Quote> {
return quoteService.findAllQuotes()
}
@ApiOperation(value = "Show IexQuote", notes = "Show IexQuote for a given ticker/symbol")
@GetMapping(path = ["/iex/ticker/{ticker}"])
@ResponseStatus(HttpStatus.OK)
fun getIexQuote(@PathVariable ticker: String): IexQuoteDto? {
return quoteService.findIexQuoteByTicker("RY")
}
@ApiOperation(value = "Update quote table using IEX data", notes = "Update all quotes in the quote table. Use IEX trading API as market data source.")
@PutMapping(path = ["/updateAll"])
@ResponseStatus(HttpStatus.OK)
fun updateMarketData(): List<Quote> {
return quoteService.updateMarketData()
}
@ApiOperation(value = "Update a given quote in the quote table", notes = "Manually update a quote in the quote table using IEX market data.")
@PutMapping(path = ["/update"])
@ResponseStatus(HttpStatus.OK)
fun putQuote(@RequestBody quote: Quote): Quote {
return quoteService.saveQuote(quote)
}
@ApiOperation(value = "Add a new ticker to the dailyList (quote table)", notes = "Add a new ticker/symbol to the quote table, so trader can trade this security.")
@PostMapping(path = ["/tickerId/{tickerId}"])
@ResponseStatus(HttpStatus.CREATED)
fun addQuoteByTicker(tickerId: String): Quote? {
return quoteService.saveQuote(tickerId)
}
}
| 0
|
Kotlin
|
0
| 0
|
7fa7363d96ce41951df2f46ad6ed37162c0cd0c3
| 2,120
|
trading-kotlin
|
MIT License
|
backend/src/test/kotlin/org/dontstw/eventfactory/config/SecurityConfigTest.kt
|
hahava
| 258,443,979
| true
|
{"Kotlin": 8410, "JavaScript": 2370, "TypeScript": 608, "TSQL": 470, "HTML": 335}
|
package org.dontstw.eventfactory.config
import org.junit.jupiter.api.Assertions.assertSame
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
@SpringBootTest
class SecurityConfigTest {
@Test
fun `bcrypt_encoding_test`() {
val bCryptPasswordEncoder = BCryptPasswordEncoder()
val password = "<PASSWORD>"
val encodedPassword = <PASSWORD>"
assertSame(bCryptPasswordEncoder.matches(password, encodedPassword), true)
}
}
| 0
|
Kotlin
|
0
| 0
|
376fd4bc8e192217bbe97ab7917f19500abcb4b7
| 584
|
event-factory
|
MIT License
|
moralis-lib/src/main/java/com/moralis/web3/MoralisApplication.kt
|
mobilekosmos
| 411,831,799
| false
|
{"Kotlin": 81386, "Java": 1868, "Batchfile": 601}
|
package com.moralis.web3
import android.app.Application
import android.content.Context
import com.moralis.web3.walletconnect.server.BridgeServer
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import okhttp3.OkHttpClient
import org.komputing.khex.extensions.toNoPrefixHexString
import org.walletconnect.Session
import org.walletconnect.impls.*
import org.walletconnect.nullOnThrow
import java.io.File
import java.util.*
open class MoralisApplication : Application() {
override fun onCreate() {
super.onCreate()
mInstance = this
init()
}
private fun init() {
initMoshi()
initClient()
initBridge()
initSessionStorage()
appName = getApplicationName()
appPackage = applicationInfo.packageName
}
private fun getApplicationName(): String {
val stringId: Int = applicationInfo.labelRes
return if (stringId == 0) applicationInfo.nonLocalizedLabel.toString() else getString(stringId)
}
private fun initClient() {
client = OkHttpClient.Builder().build()
}
private fun initMoshi() {
moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
}
private fun initBridge() {
bridge = BridgeServer(moshi)
bridge.start()
}
private fun initSessionStorage() {
storage = FileWCSessionStore(File(cacheDir, "session_store.json").apply { createNewFile() }, moshi)
}
companion object {
lateinit var mInstance: MoralisApplication
private lateinit var client: OkHttpClient
private lateinit var moshi: Moshi
private lateinit var bridge: BridgeServer
private lateinit var storage: WCSessionStore
private lateinit var appName: String
private lateinit var appPackage : String
// TODO For now walletConnect only supports URL, maybe in a future version we can pass here raw data.
// private lateinit var appIconURL : String
lateinit var config: Session.FullyQualifiedConfig
lateinit var session: Session
fun resetSession(chainId: Long? = null) {
nullOnThrow { session }?.clearCallbacks()
val key = ByteArray(32).also { Random().nextBytes(it) }.toNoPrefixHexString()
config = Session.FullyQualifiedConfig(
UUID.randomUUID().toString(),
"http://localhost:${BridgeServer.PORT}",
key
)
// The walletConnect app freezes/crashes if "icons" in passed PeerMeta is not filled, so pass at least an empty list.
session = WCSession(
config,
MoshiPayloadAdapter(moshi),
storage,
OkHttpTransport.Builder(client, moshi),
Session.PeerMeta(
url = appPackage,
name = appName,
description = appName,
icons = listOf()
),
_chainId = chainId
)
session.offer()
}
fun getContext(): Context {
return mInstance.applicationContext
}
}
}
| 2
|
Kotlin
|
1
| 5
|
5cef71a0beea81e826c023d13e2189e9b8c22cad
| 3,204
|
moralis-sdk-android
|
Apache License 2.0
|
app/src/main/java/com/twobbble/biz/impl/BaseBiz.kt
|
550609334
| 82,531,843
| false
| null |
package com.twobbble.biz.impl
import com.twobbble.biz.assist.NetService
import com.twobbble.biz.assist.RetrofitFactory
/**
* Created by liuzipeng on 2017/3/1.
*/
open class BaseBiz {
fun getNetService(): NetService = RetrofitFactory.instance().getService()
}
| 1
| null |
62
| 398
|
e91797a3d4a0fa7737f983a8914eaa109a452054
| 266
|
Twobbble
|
Apache License 2.0
|
app/src/main/java/com/one/kumaran/restpokemon/ui/main/MainView.kt
|
bellank
| 145,264,830
| false
| null |
package com.one.kumaran.restpokemon.ui.main
import com.one.kumaran.restpokemon.repository.model.Pokemon
import com.one.kumaran.restpokemon.repository.state.MainState
import com.one.kumaran.restpokemon.ui.View
interface MainView: View {
fun populateData(mainState: MainState, pokemon: Pokemon)
fun showLoading(mainState: MainState)
fun errorOccured(error: Throwable, mainState: MainState)
fun dataLoadCompleted(mainState: MainState)
}
| 0
|
Kotlin
|
0
| 0
|
37254090da661e4cd897e5cb0c4de77295e46e0e
| 451
|
restpokemon
|
Apache License 2.0
|
src/main/kotlin/br/upf/sistemadevoos/exceptions/InvalidParametersException.kt
|
gcerbaro
| 702,686,292
| false
|
{"Kotlin": 38457}
|
package br.upf.sistemadevoos.exceptions
import java.lang.RuntimeException
class InvalidParametersException(override val message: String) : RuntimeException()
| 0
|
Kotlin
|
0
| 0
|
88b4ee9c53f5b1c59b06b16bc94a0ee169bf3ab4
| 160
|
SistemaVoosKotlin
|
MIT License
|
damzel-parsers-ksp/src/main/kotlin/com/sokoobo/damzel/parsers/ksp/Utils.kt
|
sokoobo
| 869,785,019
| false
|
{"Kotlin": 163808, "HTML": 4051}
|
package com.sokoobo.damzel.parsers.ksp
import java.util.*
fun String.toTitleCase(locale: Locale?): String {
return replaceFirstChar { x -> x.uppercase(locale ?: Locale.ROOT) }
}
| 0
|
Kotlin
|
0
| 0
|
535e638059205ac87e77615cdc436b2500574f7d
| 181
|
damzel-parsers
|
MIT License
|
src/main/java/com/store/model/InventoryRecord.kt
|
znsio
| 690,364,752
| false
|
{"Kotlin": 16597, "Java": 890}
|
package com.store.model
data class InventoryRecord(val productid: Int = 0, val quantity: Int = 0)
| 11
|
Kotlin
|
0
| 1
|
9c2a6b463555ae015240832e391c698c98459089
| 99
|
specmatic-order-api-java-with-oauth
|
MIT License
|
src/main/kotlin/ai/serenade/intellij/MainToolWindow.kt
|
serenadeai
| 279,932,207
| false
| null |
package ai.serenade.intellij
import ai.serenade.intellij.services.ToolWindowService
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowFactory
import io.ktor.util.KtorExperimentalAPI
class MainToolWindow : ToolWindowFactory {
@KtorExperimentalAPI
override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
ToolWindowService(project).setContent(false)
}
}
| 0
|
Kotlin
|
2
| 7
|
5c14fc7dc9d37fab64e6be52f56c61ff60cd7c5f
| 475
|
intellij
|
MIT License
|
src/main/kotlin/gui/entity/EntityModifier.kt
|
nea89o
| 637,563,904
| false
|
{"Kotlin": 600801, "Java": 131606, "Nix": 1217}
|
package moe.nea.firmament.gui.entity
import com.google.gson.JsonObject
import net.minecraft.entity.LivingEntity
fun interface EntityModifier {
fun apply(entity: LivingEntity, info: JsonObject): LivingEntity
}
| 25
|
Kotlin
|
6
| 37
|
9cdc30e024fac9fe04eeeccb15dfd46f4aa648cb
| 216
|
Firmament
|
Apache License 2.0
|
src/test/kotlin/io/github/dca/OptimizeRouterTest.kt
|
laguiar
| 476,662,074
| false
|
{"Kotlin": 41736}
|
package io.github.dca
import io.ktor.client.call.body
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.http.ContentType
import io.ktor.http.ContentType.Application.Json
import io.ktor.http.HttpStatusCode
import io.ktor.http.contentType
import io.ktor.serialization.kotlinx.json.json
import io.ktor.server.testing.testApplication
import org.junit.jupiter.api.Test
import strikt.api.expectThat
import strikt.assertions.hasEntry
import strikt.assertions.hasSize
import strikt.assertions.isEqualTo
class OptimizeRouterTest {
@Test
fun testOptimizeRouter() = testApplication {
val client = createClient {
install(ContentNegotiation) {
json()
}
}
val response = client.post("/api/optimize") {
contentType(Json)
this.setBody("""
{
"amount": "1000.00",
"assets": [
{
"ticker": "BTC",
"weight": "50.0",
"target": "70.0"
}
]
}
""".trimIndent()
)
}
expectThat(response.status).isEqualTo(HttpStatusCode.OK)
expectThat(response.contentType()).isEqualTo(Json.withParameter("charset", "UTF-8"))
expectThat(response.body<DcaResponse>().distribution).hasSize(1)
expectThat(response.body<DcaResponse>().distribution).hasEntry("BTC", BigDecimalNumber("1000.00"))
}
}
| 0
|
Kotlin
|
1
| 0
|
261c6b36b5f482f7ed793bfd091a0d3871133506
| 1,648
|
dca-optimizer
|
MIT License
|
airbyte-cdk/java/airbyte-cdk/dependencies/src/main/kotlin/io/airbyte/configoss/AirbyteConfigValidator.kt
|
tim-werner
| 511,419,970
| false
|
{"Java Properties": 8, "Shell": 57, "Markdown": 1170, "Batchfile": 1, "Makefile": 3, "JavaScript": 31, "CSS": 9, "Python": 4183, "Kotlin": 845, "Java": 723, "INI": 10, "Dockerfile": 27, "HTML": 7, "SQL": 527, "PLpgSQL": 8, "TSQL": 1, "PLSQL": 2}
|
/*
* Copyright (c) 2023 Airbyte, Inc., all rights reserved.
*/
package io.airbyte.configoss
import io.airbyte.validation.json.AbstractSchemaValidator
import java.nio.file.Path
class AirbyteConfigValidator : AbstractSchemaValidator<ConfigSchema>() {
override fun getSchemaPath(configType: ConfigSchema): Path {
return configType.configSchemaFile.toPath()
}
companion object {
val AIRBYTE_CONFIG_VALIDATOR: AirbyteConfigValidator = AirbyteConfigValidator()
}
}
| 1
| null |
1
| 1
|
b2e7895ed3e1ca7c1600ae1c23578dd1024f20ff
| 496
|
airbyte
|
MIT License
|
year2023/day05/almanac/src/main/kotlin/com/curtislb/adventofcode/year2023/day05/almanac/Almanac.kt
|
curtislb
| 226,797,689
| false
|
{"Kotlin": 2014224}
|
package com.curtislb.adventofcode.year2023.day05.almanac
import com.curtislb.adventofcode.common.io.forEachSection
import com.curtislb.adventofcode.common.parse.parseLongs
import java.io.File
/**
* A copy of the Island Island Almanac, which contains [CategoryMap]s for converting integer values
* between various categories.
*
* @property categoryMaps A map from each category in the almanac to a [CategoryMap] that converts
* values of that category to new values of a different category.
*
* @constructor Creates a new [Almanac] instance with the given [categoryMaps].
*/
class Almanac(private val categoryMaps: Map<String, CategoryMap>) {
/**
* Returns the list of values that result from converting the given input [values] from the
* specified [sourceCategory] to [targetCategory].
*
* @throws IllegalArgumentException If [sourceCategory] can't be converted to [targetCategory].
*/
fun convertValues(
values: List<Long>,
sourceCategory: String,
targetCategory: String
): List<Long> {
return foldOverCategoryMaps(values, sourceCategory, targetCategory) { result, categoryMap ->
categoryMap.convertValues(result)
}
}
/**
* Returns a list of value ranges that result from converting the given input [ranges] from the
* specified [sourceCategory] to [targetCategory].
*
* @throws IllegalArgumentException If [sourceCategory] can't be converted to [targetCategory].
*/
fun convertRanges(
ranges: Set<LongRange>,
sourceCategory: String,
targetCategory: String
): Set<LongRange> {
return foldOverCategoryMaps(ranges, sourceCategory, targetCategory) { result, categoryMap ->
categoryMap.convertRanges(result)
}
}
/**
* Returns the result of applying the specified [operation] to an [initial] value and subsequent
* result values for each category map in the almanac that can be used (in order) to map values
* from [sourceCategory] to [targetCategory].
*
* @throws IllegalArgumentException If [sourceCategory] can't be converted to [targetCategory].
*/
private inline fun <T> foldOverCategoryMaps(
initial: T,
sourceCategory: String,
targetCategory: String,
operation: (result: T, categoryMap: CategoryMap) -> T
): T {
var result = initial
var category = sourceCategory
while (category != targetCategory) {
val categoryMap = categoryMaps[category]
require(categoryMap != null) { "No map for category: $category" }
result = operation(result, categoryMap)
category = categoryMap.targetCategory
}
return result
}
companion object {
/**
* Returns a list of initial values and an [Almanac] read from the given input [file].
*
* The [file] must have the following format:
*
* ```
* $label: $value1 $value2 ... $valueN
*
* $categoryMap1
*
* $categoryMap2
*
* ...
*
* $categoryMapM
* ```
*
* See [CategoryMap.fromLines] for how each `categoryMap` section is formatted.
*
* @throws IllegalArgumentException If [file] is not formatted correctly.
*/
fun parseFile(file: File): Pair<List<Long>, Almanac> {
var values: List<Long> = emptyList()
val categoryMaps = mutableMapOf<String, CategoryMap>()
file.forEachSection { lines ->
if (values.isEmpty()) {
// Read initial values from the first line
values = lines[0].parseLongs()
} else {
// Read category maps from subsequent sections
val categoryMap = CategoryMap.fromLines(lines)
categoryMaps[categoryMap.sourceCategory] = categoryMap
}
}
return Pair(values, Almanac(categoryMaps))
}
}
}
| 0
|
Kotlin
|
1
| 1
|
a55341d18b4a44f05efbc9b0b9583e11d9528285
| 4,109
|
AdventOfCode
|
MIT License
|
services/csm.cloud.user.user/src/main/kotlin/com/bosch/pt/csm/cloud/usermanagement/pat/pat/command/handler/DeletePatCommandHandler.kt
|
boschglobal
| 805,348,245
| false
|
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
|
/*
* ************************************************************************
*
* Copyright: <NAME> Power Tools GmbH, 2018 - 2023
*
* ************************************************************************
*/
package com.bosch.pt.csm.cloud.usermanagement.pat.pat.command.handler
import com.bosch.pt.csm.cloud.common.command.handler.CommandHandler
import com.bosch.pt.csm.cloud.usermanagement.common.translation.Key.PAT_VALIDATION_ERROR_USER_MISMATCH
import com.bosch.pt.csm.cloud.usermanagement.pat.eventstore.PatLocalEventBus
import com.bosch.pt.csm.cloud.usermanagement.pat.pat.command.api.DeletePatCommand
import com.bosch.pt.csm.cloud.usermanagement.pat.pat.command.mapper.PatTombstoneAvroSnapshotMapper
import com.bosch.pt.csm.cloud.usermanagement.pat.pat.command.snapshotstore.PatSnapshotStore
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.stereotype.Component
import org.springframework.transaction.annotation.Transactional
@Component
class DeletePatCommandHandler(
private val snapshotStore: PatSnapshotStore,
private val eventBus: PatLocalEventBus,
private val patTombstoneAvroSnapshotMapper: PatTombstoneAvroSnapshotMapper
) {
@Suppress("SpringElInspection")
@PreAuthorize("#command.impersonatedUser == principal.identifier")
@Transactional
fun handle(command: DeletePatCommand) =
CommandHandler.of(
snapshotStore.findOrFail(command.patId),
patTombstoneAvroSnapshotMapper,
)
.assertVersionMatches(command.version)
.checkAuthorization { command.impersonatedUser == it.impersonatedUser }
.onFailureThrow(PAT_VALIDATION_ERROR_USER_MISMATCH)
.emitTombstone()
.to(eventBus)
.andReturnSnapshot()
.identifier
}
| 0
|
Kotlin
|
3
| 9
|
9f3e7c4b53821bdfc876531727e21961d2a4513d
| 1,811
|
bosch-pt-refinemysite-backend
|
Apache License 2.0
|
documents_feature/src/main/java/com/flyview/documents_feature/ui/scan/product_list/toolbar/ProductListToolbarComponent.kt
|
DmiMukh
| 676,402,705
| false
|
{"Kotlin": 288475, "Java": 130379}
|
package com.flyview.documents_feature.ui.scan.product_list.toolbar
interface ProductListToolbarComponent {
fun onBackClick()
fun onSaveClick()
}
| 0
|
Kotlin
|
0
| 0
|
5c184121116c08abe217946ba7da27804c232edb
| 154
|
PharmMobile
|
MIT License
|
src/main/kotlin/no/nav/pensjon/opptjening/omsorgsopptjening/bestem/pensjonsopptjening/omsorgsarbeid/model/Landstilknyttning.kt
|
navikt
| 593,529,397
| false
| null |
package no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.omsorgsarbeid.model
enum class Landstilknytning {
EOS,
NASJONAL
}
| 0
|
Kotlin
|
0
| 0
|
279242c5ca79bb34dd136c29dfd5a1b5a5e60651
| 152
|
omsorgsopptjening-bestem-pensjonsopptjening
|
MIT License
|
app/src/main/java/by/lebedev/nanopoolmonitoring/data/dto/workers/WorkersResponse.kt
|
PaladinVCT
| 536,445,483
| false
| null |
package by.lebedev.nanopoolmonitoring.data.dto.workers
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class WorkersResponse(
@Json(name = "data")
val `data`: List<WorkerResponse>? = null,
@Json(name = "status")
val status: Boolean? = null
) {
@JsonClass(generateAdapter = true)
data class WorkerResponse(
@Json(name = "hashrate")
val hashrate: Double? = null,
@Json(name = "id")
val id: String? = null,
@Json(name = "lastShare")
val lastShare: Long? = null,
@Json(name = "rating")
val rating: Long? = null,
@Json(name = "uid")
val uid: Int? = null
)
}
| 0
|
Kotlin
|
0
| 0
|
07d57e5a42b5794dfc644c08750b1241f6e35f54
| 722
|
Nanopool
|
Apache License 2.0
|
redwood-protocol-host/src/commonMain/kotlin/app/cash/redwood/protocol/widget/ProtocolMismatchHandler.kt
|
cashapp
| 305,409,146
| false
|
{"Kotlin": 1637648, "Swift": 14358, "Java": 1583, "Objective-C": 1499, "HTML": 235, "C": 43}
|
/*
* Copyright (C) 2022 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.redwood.protocol.widget
import app.cash.redwood.protocol.ChildrenTag
import app.cash.redwood.protocol.ModifierTag
import app.cash.redwood.protocol.PropertyTag
import app.cash.redwood.protocol.WidgetTag
import kotlin.jvm.JvmField
import kotlin.native.ObjCName
/**
* Handler invoked when the protocol sent from Compose to the widget display encounters unknown
* entities. This usually occurs when either the Compose-side or the widget-side was generated from
* a newer schema than the other, or if their schemas were changed in an incompatible way.
*/
@ObjCName("ProtocolMismatchHandler", exact = true)
public interface ProtocolMismatchHandler {
/** Handle a request to create an unknown widget [tag]. */
public fun onUnknownWidget(tag: WidgetTag)
/** Handle a request to create an unknown layout modifier [tag]. */
public fun onUnknownModifier(tag: ModifierTag)
/** Handle a request to manipulate unknown children [tag] for the specified [widgetTag]. */
public fun onUnknownChildren(widgetTag: WidgetTag, tag: ChildrenTag)
/** Handle a request to set an unknown property [tag] for the specified [widgetTag]. */
public fun onUnknownProperty(widgetTag: WidgetTag, tag: PropertyTag)
public companion object {
/** A [ProtocolMismatchHandler] which throws [IllegalArgumentException] for all callbacks. */
@JvmField
public val Throwing: ProtocolMismatchHandler = object : ProtocolMismatchHandler {
override fun onUnknownWidget(tag: WidgetTag) {
throw IllegalArgumentException("Unknown widget tag ${tag.value}")
}
override fun onUnknownModifier(tag: ModifierTag) {
throw IllegalArgumentException("Unknown layout modifier tag ${tag.value}")
}
override fun onUnknownChildren(widgetTag: WidgetTag, tag: ChildrenTag) {
throw IllegalArgumentException(
"Unknown children tag ${tag.value} for widget tag ${widgetTag.value}",
)
}
override fun onUnknownProperty(widgetTag: WidgetTag, tag: PropertyTag) {
throw IllegalArgumentException(
"Unknown property tag ${tag.value} for widget tag ${widgetTag.value}",
)
}
}
}
}
| 101
|
Kotlin
|
52
| 1,296
|
ecddfc7fab869b935b9593ee979758dd5df97c26
| 2,783
|
redwood
|
Apache License 2.0
|
shared/src/commonMain/kotlin/AppColors.kt
|
AhmMhd
| 631,529,012
| false
| null |
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.ui.graphics.Color
val appBlack: Color = Color(0xff25242b)
val appYellow: Color = Color(0xffffb400)
val appWhite: Color = Color(0xffffffff)
val LightThemeColors = lightColors(
primary = appYellow,
primaryVariant = appYellow,
background = appWhite,
secondary = appBlack
)
val DarkThemeColors = darkColors(
primary = appYellow,
primaryVariant = appYellow,
background = appBlack,
secondary = appWhite
)
| 0
|
Kotlin
|
0
| 24
|
50f93b813a382f24df972d75d00979cf415103eb
| 546
|
Portfolio-App
|
Apache License 2.0
|
app/src/main/java/com/example/mini_projet/views/home/HomeFragment.kt
|
zahracarthage
| 429,762,274
| false
|
{"Kotlin": 225057}
|
package com.example.mini_projet.views.home
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.SearchView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.mini_projet.adapters.CategoriesAdapter
import com.example.mini_projet.adapters.RestaurantAdapter
import com.example.mini_projet.databinding.FragmentHomeBinding
import com.example.mini_projet.models.Restaurant
import com.example.mini_projet.models.RestaurantList
class HomeFragment : Fragment(), CategoriesAdapter.CustomListeners,
RestaurantAdapter.CustomListeners {
private lateinit var binding: FragmentHomeBinding
private lateinit var searchView: SearchView
private lateinit var filterRecyclerView: RecyclerView
private lateinit var restaurantRecyclerView: RecyclerView
private lateinit var restaurantAdapter: RestaurantAdapter
private lateinit var categoriesAdapter: CategoriesAdapter
private val viewModel: HomeViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentHomeBinding.inflate(inflater, container, false)
searchView = binding.search
filterRecyclerView = binding.filters
restaurantRecyclerView = binding.restaurantslist
filterRecyclerView.layoutManager =
GridLayoutManager(requireContext(), 2, GridLayoutManager.HORIZONTAL, false)
restaurantRecyclerView.layoutManager = LinearLayoutManager(requireContext())
categoriesAdapter = CategoriesAdapter(this)
restaurantAdapter = RestaurantAdapter(this, requireContext())
filterRecyclerView.adapter = categoriesAdapter
restaurantRecyclerView.adapter = restaurantAdapter
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(p0: String?): Boolean {
if (p0 != null && viewModel.resturantsStable != null) {
requireView().findNavController().navigate(
HomeFragmentDirections.actionMenuHomeToSearchFragment(
RestaurantList(viewModel.resturantsStable!!),
p0
)
)
}
return false
}
override fun onQueryTextChange(p0: String?): Boolean {
println("query change ")
searchView.queryHint = null
return false
}
})
return binding.root
}
override fun onStart() {
super.onStart()
viewModel.getCategories()
viewModel.getResturants()
viewModel.resturants.observe(viewLifecycleOwner, {
restaurantAdapter.submitList(it ?: listOf())
})
viewModel.categories.observe(viewLifecycleOwner, {
println("categories ${it}")
categoriesAdapter.submitList(it ?: listOf())
})
}
override fun onItemSelected(item: String) {
viewModel.handleSelection(item)
}
override fun onItemSelected(restaurant: Restaurant) {
requireView().findNavController()
.navigate(HomeFragmentDirections.actionHomeFragmentToShowOneFragment(restaurant))
}
}
| 0
|
Kotlin
|
0
| 0
|
6f062c59b32bb5f4a7595ffa69e47d1eaa195126
| 3,643
|
mini-projet-android
|
MIT License
|
eudi-wallet-oidc-android/src/main/java/com/ewc/eudi_wallet_oidc_android/services/codeVerifier/CodeVerifierServiceInterface.kt
|
EWC-consortium
| 749,764,479
| false
|
{"Kotlin": 155109}
|
package com.ewc.eudi_wallet_oidc_android.services.codeVerifier
interface CodeVerifierServiceInterface {
/**
* To generate the code verifier for issuance
* high-entropy cryptographic random STRING using the
* unreserved characters [A-Z] / [a-z] / [0-9] / "-" / "." / "_" / "~"
* with a minimum length of 43 characters
* and a maximum length of 128 characters.
* Refer - https://datatracker.ietf.org/doc/html/rfc7636#section-4.1
* @return code_verifier
*/
fun generateCodeVerifier(): String?
/**
* To generate the code challenge from the code verifier
* Refer - https://datatracker.ietf.org/doc/html/rfc7636#section-4.2
* @param codeVerifier
* @return code_challenge
*/
fun generateCodeChallenge(codeVerifier: String): String?
}
| 0
|
Kotlin
|
1
| 0
|
6090a2f177590f354fc80b4b5d11a49af4d48e4a
| 822
|
eudi-wallet-oid4vc-android
|
Apache License 2.0
|
app/src/main/java/com/thirty/nikeapp/MyApplication.kt
|
anurenjatgithub4u
| 668,812,274
| false
| null |
package com.thirty.nikeapp
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class MyApplication :Application(){
}
| 0
|
Kotlin
|
0
| 0
|
eb5b8a51851fb088f5447c931adaff51e9b08677
| 156
|
Sneakers
|
MIT License
|
zircon.core/common/src/main/kotlin/org/hexworks/zircon/internal/component/renderer/DefaultContainerRenderer.kt
|
smomen
| 159,274,471
| true
|
{"Kotlin": 1062940, "Java": 16867, "CSS": 1525}
|
package org.hexworks.zircon.internal.component.renderer
import org.hexworks.zircon.api.component.renderer.ComponentRenderContext
import org.hexworks.zircon.api.component.renderer.ComponentRenderer
import org.hexworks.zircon.api.graphics.impl.SubTileGraphics
import org.hexworks.zircon.internal.component.impl.DefaultContainer
class DefaultContainerRenderer : ComponentRenderer<DefaultContainer> {
override fun render(tileGraphics: SubTileGraphics, context: ComponentRenderContext<DefaultContainer>) {
val style = context.componentStyle.currentStyle()
tileGraphics.applyStyle(style)
}
}
| 0
|
Kotlin
|
0
| 0
|
bb1f993f8eca72660cd44da736f1643a351bcb68
| 613
|
zircon
|
MIT License
|
composeApp/src/commonMain/kotlin/domain/model/Movie.kt
|
alirezaeiii
| 835,875,495
| false
|
{"Kotlin": 52210, "Swift": 621}
|
package domain.model
import kotlinx.serialization.Serializable
@Serializable
data class Movie(
val id: Int,
val overview: String,
val releaseDate: String?,
val backdropPath: String?,
val name: String,
val voteAverage: Double,
val voteCount: Int
)
| 0
|
Kotlin
|
0
| 2
|
38a5f028c897af18c5ff510b342d248d08025db1
| 276
|
TMDb-CMP-Playground
|
The Unlicense
|
app/src/main/java/foss/cnugteren/nlweer/ui/fragments/BuienradarPluimFragment.kt
|
CNugteren
| 218,386,512
| false
| null |
package foss.cnugteren.nlweer.ui.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.fragment.app.Fragment
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import foss.cnugteren.nlweer.MainActivity
import foss.cnugteren.nlweer.R
class WebClientBuienradarPluim : WebViewClient() {
// From https://stackoverflow.com/questions/14423981/android-webview-display-only-some-part-of-website
override fun shouldOverrideUrlLoading(
view: WebView,
url: String
): Boolean {
view.loadUrl(url)
return true
}
override fun onPageFinished(view: WebView, url: String) {
view.loadUrl("javascript:(function() {" +
"document.getElementById('header').style.display='none';" +
"document.getElementById('footer').style.display='none';" +
"document.getElementById('adholderContainerFooterSmall').style.display='none';" +
"document.getElementsByClassName('control-block')[0].style.display='none';" +
"document.getElementsByClassName('side-content')[0].style.display='none';" +
"}\n)()")
}
}
class BuienradarPluimFragment : Fragment() {
private lateinit var webView: WebView
private lateinit var root: View
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
root = inflater.inflate(R.layout.fragment_knmi_pluim, container, false)
// Pull down to refresh the page
val pullToRefresh = root.findViewById<SwipeRefreshLayout>(R.id.pullToRefresh)
pullToRefresh.setOnRefreshListener(SwipeRefreshLayout.OnRefreshListener {
refreshPage()
pullToRefresh.isRefreshing = false
})
// Do display floating navigation buttons
val activity = this.activity as MainActivity
activity.toggleNavigationButtons(true)
// The web-viewer for the content
webView = root.findViewById(R.id.web_view) as WebView
val webViewClientModified = WebClientBuienradarPluim()
webView.settings.javaScriptEnabled = true
webView.webViewClient = webViewClientModified
loadPage()
return root
}
private fun getURL(): String {
return "https://www.buienradar.nl/nederland/verwachtingen/de-pluim"
}
private fun refreshPage() {
webView.clearCache(false)
loadPage()
}
private fun loadPage() {
webView.loadUrl(getURL())
}
}
| 8
|
Kotlin
|
4
| 16
|
6ab1edc64ef9ddd9b04f095dee48d2b61eef95bf
| 2,695
|
NLWeer
|
MIT License
|
src/main/kotlin/function.kt
|
BangShinChul
| 380,409,082
| false
| null |
/**
* 함수 예제입니다.
* */
fun functionExamples() {
functionCallExample() // 함수 호출 예제
지명_함수_인자_예제()
// shouldReturnAString()
`**~prolly not a good idea!~**`()
`사용자가 로그아웃을 클릭하면 로그아웃되어야 합니다`()
}
/**
* 함수의 리턴 예제입니다.
* */
private fun formatHealthStatus1(healthPoints: Int, isBlessed: Boolean): String {
val healthStatus = when (healthPoints) {
100 -> "최상의 상태임!"
in 90..99 -> "약간의 찰과상만 있음."
in 75..89 -> if (isBlessed) {
"경미한 상처가 있지만 빨리 치유되고 있음!"
} else {
"경미한 상처만 있음."
}
in 15..74 -> "많이 다친 것 같음."
else -> "최악의 상태임!"
}
return healthStatus
}
/**
* 함수의 기본 인자 예제입니다.
* */
private fun castFireball1(numFireballs: Int = 2) {
println("한 덩어리의 파이어볼이 나타난다. (x$numFireballs)")
}
/**
* 함수 호출 예제입니다.
* */
fun functionCallExample() {
val name = "마드리갈"
var healthPoints = 89
var isBlessed = true
val healthStatus = formatHealthStatus1(healthPoints, isBlessed)
println(healthStatus)
castFireball1(5) // 인자값 5를 전달. "한 덩어리의 파이어볼이 나타난다. (x5)" 출력
castFireball1() // 인자값 전달하지 않음. 기본 인자값 사용. "한 덩어리의 파이어볼이 나타난다. (x2)" 출력
}
/**
* 단일 표현식 예제입니다. 1
* */
private fun formatHealthStatus2(healthPoints: Int, isBlessed: Boolean) =
when (healthPoints) {
100 -> "최상의 상태임!"
in 90..99 -> "약간의 찰과상만 있음."
in 75..89 -> if (isBlessed) {
"경미한 상처가 있지만 빨리 치유되고 있음!"
} else {
"경미한 상처만 있음."
}
in 15..74 -> "많이 다친 것 같음."
else -> "최악의 상태임!"
}
/**
* 단일 표현식 예제입니다. 2
* */
private fun castFireball(numFireballs: Int = 2) =
println("한 덩어리의 파이어볼이 나타난다. (x$numFireballs)")
private fun printPlayerStatus(
auraColor: String,
isBlessed: Boolean,
name: String,
healthStatus: String
) {
println(
"(Aura: $auraColor) " +
"(Blessed: ${if (isBlessed) "YES" else "NO"})"
)
println("$name $healthStatus")
}
/**
* 지명 함수 인자 예제입니다.
* */
fun 지명_함수_인자_예제() {
val status = formatHealthStatus1(89, true)
printPlayerStatus(auraColor = "NONE", isBlessed = true, name = "마드리갈", healthStatus = status)
}
/**
* Nothing 타입 예제입니다.
* */
//fun shouldReturnAString(): String {
// TODO("문자열을 반환하는 코드를 여기에 구현해야 함")
// println("절대 실행할 수 없는 코드")
//}
/**
* 백틱 함수 예제입니다.
* */
fun `**~prolly not a good idea!~**`() {
println("prolly not a good idea!")
}
fun `사용자가 로그아웃을 클릭하면 로그아웃되어야 합니다`() {
println("테스트 코드를 작성합니다.")
}
| 0
|
Kotlin
|
0
| 0
|
155ecb353fd0cdabf3fd1035a903b612be9604eb
| 2,462
|
kotlin-study
|
MIT License
|
app/src/main/java/com/uxstate/launchpad/presentation/screens/home/components/tabs/TabsContent.kt
|
Tonnie-Dev
| 564,375,014
| false
|
{"Kotlin": 159012}
|
package com.uxstate.launchpad.presentation.screens.home.components.tabs
import android.content.res.Configuration.UI_MODE_NIGHT_NO
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PageSize
import androidx.compose.foundation.pager.PagerState
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
@Composable
fun TabsContent(tabs: List<TabItem>, pagerState: PagerState) {
HorizontalPager(state = pagerState, pageSize = PageSize.Fill) {
page ->
tabs[page].composeFunction()
}
}
@Preview(uiMode = UI_MODE_NIGHT_NO, showBackground = true)
@Composable
fun TabsContentPreviewLight() {
/* val tabs = listOf(TabItem.Upcoming, TabItem.Previous)
val pagerState = rememberPagerState()
LaunchPadTheme() {
TabsContent(tabs = tabs, pagerState = pagerState)
}*/
}
@Preview(uiMode = UI_MODE_NIGHT_YES, showBackground = true)
@Composable
fun TabsContentPreviewDark() {
/* val tabs = listOf(TabItem.Upcoming, TabItem.Previous)
val pagerState = rememberPagerState()
LaunchPadTheme() {
TabsContent(tabs = tabs, pagerState = pagerState)
}*/
}
| 0
|
Kotlin
|
1
| 8
|
ce1fe7b336c874220c7c8ef4d824664e39d57166
| 1,247
|
LaunchPad
|
MIT License
|
app/src/main/java/com/uxstate/launchpad/presentation/screens/home/components/tabs/TabsContent.kt
|
Tonnie-Dev
| 564,375,014
| false
|
{"Kotlin": 159012}
|
package com.uxstate.launchpad.presentation.screens.home.components.tabs
import android.content.res.Configuration.UI_MODE_NIGHT_NO
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PageSize
import androidx.compose.foundation.pager.PagerState
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
@Composable
fun TabsContent(tabs: List<TabItem>, pagerState: PagerState) {
HorizontalPager(state = pagerState, pageSize = PageSize.Fill) {
page ->
tabs[page].composeFunction()
}
}
@Preview(uiMode = UI_MODE_NIGHT_NO, showBackground = true)
@Composable
fun TabsContentPreviewLight() {
/* val tabs = listOf(TabItem.Upcoming, TabItem.Previous)
val pagerState = rememberPagerState()
LaunchPadTheme() {
TabsContent(tabs = tabs, pagerState = pagerState)
}*/
}
@Preview(uiMode = UI_MODE_NIGHT_YES, showBackground = true)
@Composable
fun TabsContentPreviewDark() {
/* val tabs = listOf(TabItem.Upcoming, TabItem.Previous)
val pagerState = rememberPagerState()
LaunchPadTheme() {
TabsContent(tabs = tabs, pagerState = pagerState)
}*/
}
| 0
|
Kotlin
|
1
| 8
|
ce1fe7b336c874220c7c8ef4d824664e39d57166
| 1,247
|
LaunchPad
|
MIT License
|
app/src/main/java/com/erkindilekci/chatwave/presentation/ui/theme/Color.kt
|
erkindilekci
| 654,943,054
| false
| null |
package com.erkindilekci.chatwave.presentation.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
val DarkSlateGrey = Color(0xFF27474e)
val DarkSlateGreyLight = Color(0xFF36626B)
val Plum = Color(0xFF7d387d)
val OldRose = Color(0xFFcd8b76)
val Vanilla = Color(0xFFe1d89f)
val LightPrimary = Color(0xFF825500)
val LightOnPrimary = Color(0xFFFFFFFF)
val LightPrimaryContainer = Color(0xFFFFDDAE)
val LightOnPrimaryContainer = Color(0xFF2A1800)
val LightSecondary = Color(0xFF6F5B40)
val LightOnSecondary = Color(0xFFFFFFFF)
val LightSecondaryContainer = Color(0xFFFADEBC)
val LightOnSecondaryContainer = Color(0xFF271904)
val LightTertiary = Color(0xFF516440)
val LightOnTertiary = Color(0xFFFFFFFF)
val LightTertiaryContainer = Color(0xFFD3EABC)
val LightOnTertiaryContainer = Color(0xFF102004)
val LightError = Color(0xFFBA1B1B)
val LightErrorContainer = Color(0xFFFFDAD4)
val LightOnError = Color(0xFFFFFFFF)
val LightOnErrorContainer = Color(0xFF410001)
val LightBackground = Color(0xFFFCFCFC)
val LightOnBackground = Color(0xFF1F1B16)
val LightSurface = Color(0xFFFCFCFC)
val LightOnSurface = Color(0xFF1F1B16)
val LightSurfaceVariant = Color(0xFFF0E0CF)
val LightOnSurfaceVariant = Color(0xFF4F4539)
val LightOutline = Color(0xFF817567)
val LightInverseOnSurface = Color(0xFFF9EFE6)
val LightInverseSurface = Color(0xFF34302A)
val LightPrimaryInverse = Color(0xFFFFB945)
val DarkPrimary = Color(0xFFFFB945)
val DarkOnPrimary = Color(0xFF452B00)
val DarkPrimaryContainer = Color(0xFF624000)
val DarkOnPrimaryContainer = Color(0xFFFFDDAE)
val DarkSecondary = Color(0xFFDDC3A2)
val DarkOnSecondary = Color(0xFF3E2E16)
val DarkSecondaryContainer = Color(0xFF56442B)
val DarkOnSecondaryContainer = Color(0xFFFADEBC)
val DarkTertiary = Color(0xFFB8CEA2)
val DarkOnTertiary = Color(0xFF243516)
val DarkTertiaryContainer = Color(0xFF3A4C2B)
val DarkOnTertiaryContainer = Color(0xFFD3EABC)
val DarkError = Color(0xFFFFB4A9)
val DarkErrorContainer = Color(0xFF930006)
val DarkOnError = Color(0xFF680003)
val DarkOnErrorContainer = Color(0xFFFFDAD4)
val DarkBackground = Color(0xFF1F1B16)
val DarkOnBackground = Color(0xFFEAE1D9)
val DarkSurface = Color(0xFF1F1B16)
val DarkOnSurface = Color(0xFFEAE1D9)
val DarkSurfaceVariant = Color(0xFF4F4539)
val DarkOnSurfaceVariant = Color(0xFFD3C4B4)
val DarkOutline = Color(0xFF9C8F80)
val DarkInverseOnSurface = Color(0xFF1F1B16)
val DarkInverseSurface = Color(0xFFEAE1D9)
val DarkPrimaryInverse = Color(0xFF825500)
| 0
|
Kotlin
|
0
| 0
|
00078200915fdd9596950cdf4c17382cc47e9917
| 2,659
|
ChatWave
|
Apache License 2.0
|
src/jsMain/kotlin/app/softwork/routingcompose/NavLink.kt
|
rbro112
| 377,354,971
| true
|
{"Kotlin": 27864, "HTML": 290}
|
package app.softwork.routingcompose
import androidx.compose.runtime.*
import org.jetbrains.compose.web.attributes.*
import org.jetbrains.compose.web.dom.*
import org.w3c.dom.*
@Composable
public fun NavLink(
to: String,
attrs: AttrsBuilder<HTMLAnchorElement>.() -> Unit = {},
content: @Composable () -> Unit
) {
A(attrs = {
attrs()
onClick {
HashRouter.navigate(to)
}
}) { content() }
}
| 0
| null |
0
| 0
|
83cea2e816f50cee5273bff6faf6921ba3aafb3a
| 444
|
routing-compose
|
Apache License 2.0
|
src/test/kotlin/org/domaindrivenarchitecture/provs/syspec/infrastructure/SyspecConfigRepoKtTest.kt
|
DomainDrivenArchitecture
| 671,424,521
| false
|
{"Kotlin": 401907, "Shell": 38541, "Python": 3745, "Vim Script": 457, "Dockerfile": 374}
|
package org.domaindrivenarchitecture.provs.syspec.infrastructure
import org.domaindrivenarchitecture.provs.configuration.domain.ConfigFileName
import org.domaindrivenarchitecture.provs.syspec.domain.CommandSpec
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
internal class SyspecConfigRepoKtTest {
@Test
fun findSpecConfigFromFile_use_default_config_if_default_config_file_is_not_found() {
// when
val res = findSpecConfigFromFile(ConfigFileName("syspec-config.yaml"))
// then
assertEquals(
"SyspecConfig(command=null, file=null, folder=null, host=null, package=[PackageSpec(name=firefox, installed=true), PackageSpec(name=thunderbird, installed=true), PackageSpec(name=ssh, installed=true), PackageSpec(name=git, installed=true)], netcat=null, socket=null, certificate=null, s3=null)",
res.getOrNull().toString())
}
@Test
fun findSpecConfigFromResource_success() {
// when
val res = findSpecConfigFromResource("syspec-config.yaml")
// then
assertEquals(listOf(CommandSpec("echo just_for_test", "just_for_test")), res.getOrNull()?.command)
}
@Test
fun findSpecConfigFromFile_null() {
// when
val res = findSpecConfigFromFile(ConfigFileName("dontexist"))
// then
assertNull(res.getOrNull())
}
@Test
fun findSpecConfigFromResource_null() {
// when
val res = findSpecConfigFromResource("dontexist")
// then
assertNull(res.getOrNull())
}
}
| 0
|
Kotlin
|
0
| 1
|
277302d0eed5043e27ad6706c85d7febb1315550
| 1,574
|
provs
|
Apache License 2.0
|
app/src/main/java/com/africablue/awsapp/util/StringUtils.kt
|
AfricaBlue72
| 259,641,836
| false
| null |
package com.africablue.awsapp.util
object StringUtils {
fun obscureEmail(email: String): String?{
val at = email.indexOf('@')
val dot = email.lastIndexOf('.')
if(at == -1 || dot == -1)
return null
return email.
replaceRange(1,email.indexOf('@'), "****").
replaceRange((at+1), dot, "****")
}
}
| 0
|
Kotlin
|
0
| 0
|
f5aea4b4e08e69c79f76cd7384308f657d61e21f
| 371
|
AwsApp
|
MIT License
|
app/src/main/java/jet/pack/compose/masterdetails/ui/components/PokemonTypeBullet.kt
|
damienlo
| 353,440,081
| false
| null |
package jet.pack.compose.masterdetails.ui.components
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import jet.pack.compose.masterdetails.ui.model.PokemonTypeUiModel
import jet.pack.compose.masterdetails.ui.theme.MasterDetailsTheme
@Composable
fun PokemonTypeBullet(type: PokemonTypeUiModel, modifier: Modifier = Modifier) {
Card(
shape = RoundedCornerShape(percent = 50),
elevation = 0.dp,
backgroundColor = if (isSystemInDarkTheme()) type.darkColor else type.lightColor,
modifier = modifier
) {
Text(
text = stringResource(type.nameResId),
textAlign = TextAlign.Center,
style = MaterialTheme.typography.caption,
color = MaterialTheme.colors.onSurface,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
}
@Preview("Bullet Light Theme")
@Composable
fun PokemonTypeBulletLightPreview() {
MasterDetailsTheme {
PokemonTypeBullet(PokemonTypeUiModel.GRASS)
}
}
@Preview("Bullet Dark Theme")
@Composable
fun PokemonTypeBulletErrorDarkPreview() {
MasterDetailsTheme(darkTheme = true) {
PokemonTypeBullet(PokemonTypeUiModel.GRASS)
}
}
| 0
|
Kotlin
|
0
| 3
|
5694b9dca530339b300e578923d8980771096f81
| 1,828
|
Compose-Pokemon-List-Details
|
Beerware License
|
app/src/main/java/jet/pack/compose/masterdetails/ui/components/PokemonTypeBullet.kt
|
damienlo
| 353,440,081
| false
| null |
package jet.pack.compose.masterdetails.ui.components
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import jet.pack.compose.masterdetails.ui.model.PokemonTypeUiModel
import jet.pack.compose.masterdetails.ui.theme.MasterDetailsTheme
@Composable
fun PokemonTypeBullet(type: PokemonTypeUiModel, modifier: Modifier = Modifier) {
Card(
shape = RoundedCornerShape(percent = 50),
elevation = 0.dp,
backgroundColor = if (isSystemInDarkTheme()) type.darkColor else type.lightColor,
modifier = modifier
) {
Text(
text = stringResource(type.nameResId),
textAlign = TextAlign.Center,
style = MaterialTheme.typography.caption,
color = MaterialTheme.colors.onSurface,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
}
@Preview("Bullet Light Theme")
@Composable
fun PokemonTypeBulletLightPreview() {
MasterDetailsTheme {
PokemonTypeBullet(PokemonTypeUiModel.GRASS)
}
}
@Preview("Bullet Dark Theme")
@Composable
fun PokemonTypeBulletErrorDarkPreview() {
MasterDetailsTheme(darkTheme = true) {
PokemonTypeBullet(PokemonTypeUiModel.GRASS)
}
}
| 0
|
Kotlin
|
0
| 3
|
5694b9dca530339b300e578923d8980771096f81
| 1,828
|
Compose-Pokemon-List-Details
|
Beerware License
|
library/src/main/java/renetik/android/store/extensions/CSStore+NullProperty.kt
|
renetik
| 506,380,036
| false
|
{"Kotlin": 85653}
|
package renetik.android.store.extensions
import renetik.android.core.lang.ArgFunc
import renetik.android.event.common.CSHasDestruct
import renetik.android.event.common.parent
import renetik.android.store.CSStore
import renetik.android.store.property.CSStoreProperty
import renetik.android.store.property.listenStore
import renetik.android.store.property.nullable.CSBooleanNullableStoreProperty
import renetik.android.store.property.nullable.CSFloatNullableStoreProperty
import renetik.android.store.property.nullable.CSIntNullableStoreProperty
import renetik.android.store.property.nullable.CSStringNullableStoreProperty
fun CSStore.nullStringProperty(
key: String, default: String? = null,
onChange: ArgFunc<String?>? = null,
) = CSStringNullableStoreProperty(this, key, default, onChange)
fun CSStore.dataNullStringProperty(
key: String, default: String? = null,
onChange: ArgFunc<String?>? = null,
) = nullStringProperty(key, default, onChange).listenStore()
fun CSStore.nullStringProperty(
parent: CSHasDestruct,
key: String, default: String? = null,
onChange: ArgFunc<String?>? = null,
) = CSStringNullableStoreProperty(this, key, default, onChange)
.parent(parent).listenStore()
fun CSStore.nullBoolProperty(
key: String, default: Boolean? = null,
onChange: ArgFunc<Boolean?>? = null,
): CSStoreProperty<Boolean?> =
CSBooleanNullableStoreProperty(this, key, default, onChange)
fun CSStore.dataNullBoolProperty(
key: String, default: Boolean? = null,
onChange: ArgFunc<Boolean?>? = null,
): CSStoreProperty<Boolean?> =
nullBoolProperty(key, default, onChange).listenStore()
fun CSStore.nullIntProperty(
key: String, default: Int? = null,
onChange: ArgFunc<Int?>? = null,
): CSStoreProperty<Int?> =
CSIntNullableStoreProperty(this, key, default, onChange)
fun CSStore.dataNullIntProperty(
key: String, default: Int? = null,
onChange: ArgFunc<Int?>? = null,
): CSStoreProperty<Int?> =
nullIntProperty(key, default, onChange).listenStore()
fun CSStore.nullIntProperty(
parent: CSHasDestruct,
key: String, default: Int? = null,
onChange: ArgFunc<Int?>? = null,
): CSStoreProperty<Int?> =
CSIntNullableStoreProperty(this, key, default, onChange)
.parent(parent).listenStore()
fun CSStore.nullFloatProperty(
key: String, default: Float? = null,
onChange: ArgFunc<Float?>? = null,
): CSStoreProperty<Float?> =
CSFloatNullableStoreProperty(this, key, default, onChange)
fun CSStore.nullFloatProperty(
parent: CSHasDestruct,
key: String, default: Float? = null,
onChange: ArgFunc<Float?>? = null,
): CSStoreProperty<Float?> =
CSFloatNullableStoreProperty(this, key, default, onChange)
.parent(parent).listenStore()
| 0
|
Kotlin
|
0
| 1
|
8a6c01e7f91e8fcb1b4c15c5e9290fd0966ad92d
| 2,761
|
renetik-android-store
|
MIT License
|
db-objekts-core/src/test/kotlin/com/dbobjekts/metadata/SubClauseTest.kt
|
jaspersprengers
| 576,889,038
| false
|
{"Kotlin": 1251411, "PLpgSQL": 45872, "Dockerfile": 2463}
|
package com.dbobjekts.metadata
import com.dbobjekts.statement.SQLOptions
import com.dbobjekts.statement.whereclause.SubClause
import com.dbobjekts.testdb.acme.CatalogDefinition
import com.dbobjekts.testdb.acme.core.Employee
import com.dbobjekts.testdb.acme.hr.Hobby
import org.assertj.core.api.Assertions
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
class SubClauseTest {
val c = CatalogDefinition
@Test
fun `create sub clause with column`(){
val clause = Employee.name.eq(Hobby.name)
assertThat(SubClause.toSQL(clause, SQLOptions(true))).isEqualTo("em.NAME = ho.NAME")
}
}
| 0
|
Kotlin
|
2
| 4
|
f4e92c78539909110cf0ab9da1713c20a9b4888b
| 650
|
db-objekts
|
Apache License 2.0
|
ocgena-domain/src/main/kotlin/ru/misterpotz/ocgena/simulation_v2/algorithm/simulation/StepExecutor.kt
|
MisterPotz
| 605,293,662
| false
|
{"Kotlin": 749008, "TypeScript": 495751, "JavaScript": 36713, "CSS": 14489, "Python": 8026, "HTML": 3173, "Ruby": 285, "EJS": 274, "Java": 140}
|
package ru.misterpotz.ocgena.simulation_v2.algorithm.simulation
import ru.misterpotz.SimulationStepLog
import ru.misterpotz.ocgena.simulation_v2.algorithm.solution_search.FullSolution
import ru.misterpotz.ocgena.simulation_v2.algorithm.solution_search.Shuffler
import ru.misterpotz.ocgena.simulation_v2.entities.TokenWrapper
import ru.misterpotz.ocgena.simulation_v2.entities.TransitionWrapper
import ru.misterpotz.ocgena.simulation_v2.entities.Transitions
import ru.misterpotz.ocgena.simulation_v2.entities.wrap
import ru.misterpotz.ocgena.simulation_v2.entities_selection.ModelAccessor
import ru.misterpotz.ocgena.simulation_v2.entities_storage.TokenStore
import ru.misterpotz.ocgena.simulation_v2.utils.sstep
interface ShiftTimeSelector {
suspend fun get(timeRange: LongRange): Long
}
interface TransitionSelector {
suspend fun get(transitions: Transitions): TransitionWrapper
}
interface TransitionSolutionSelector {
suspend fun get(solutionMeta: Meta): Int
data class Meta(val solutionsAmount: Int)
}
class StepExecutor(
private val transitions: Transitions,
private val shiftTimeSelector: ShiftTimeSelector,
private val transitionSelector: TransitionSelector,
private val tokenStore: TokenStore,
private val model: ModelAccessor,
private val shuffler: Shuffler
) {
companion object {
private const val DEBUG = false
}
enum class EnabledMode {
DISABLED_BY_MARKING,
ENABLED_BY_MARKING,
CAN_FIRE,
}
private fun collectTransitions(
filter: EnabledMode,
sourceTransitions: Transitions? = null
): Transitions {
return (sourceTransitions ?: transitions).filter {
when (filter) {
EnabledMode.CAN_FIRE -> {
it.timer.canFireNow() && it.checkEnabledByTokensCache()
}
EnabledMode.DISABLED_BY_MARKING -> {
!it.checkEnabledByTokensCache()
}
EnabledMode.ENABLED_BY_MARKING -> {
it.checkEnabledByTokensCache()
}
}
}.wrap()
}
// index transitions
private fun reindexTransitionSolutions() {
for (transition in transitions) {
if (transition.needCheckCache()) {
val solutionIterator = transition.inputArcsSolutions(
tokenStore,
shuffler = shuffler,
tokenGenerator = tokenStore,
existenceConfirmationMode = true
).iterator()
val hasSolution = solutionIterator.hasNext()
if (hasSolution) {
val solution = solutionIterator.next()
// need to create additional logics to only calculate availability, where additional tokens are not generated...
when (solution) {
is FullSolution.Exists -> {
// ok
}
else -> throw IllegalStateException()
}
}
transition.setEnabledByMarkingCache(hasSolution)
}
}
}
var logBuilder: LogBuilder = LogBuilder()
private var stepNumber: Long = 0
suspend fun execute(): SimulationStepLog? {
logBuilder = LogBuilder()
logBuilder.recordStartMarking(tokenStore)
logBuilder.recordStepNumber(stepNumber)
sstep("Need to reindex transitions that are not indexed") {
reindexTransitionSolutions()
}
val simulationFinish = sstep("try finding shift time and increment clocks") {
// определяем какие transition enabled
val enabledByMarkign = collectTransitions(EnabledMode.ENABLED_BY_MARKING)
val shiftTimes = determineShiftTimes(enabledByMarkign) ?: return@sstep true
val shiftTime = selectShiftTime(shiftTimes)
enabledByMarkign.forEach { t -> t.timer.incrementCounter(shiftTime) }
logBuilder.recordClockIncrement(shiftTime)
false
}
if (simulationFinish) return null
sstep("execute transition if possible") {
val fireableTransitions = collectTransitions(EnabledMode.CAN_FIRE)
val selectedTransition = selectTransitionToFire(fireableTransitions)
fireTransition(selectedTransition)
logBuilder.recordMarking(tokenStore)
selectedTransition.setNeedCheckCache()
for (transition in selectedTransition.dependentTransitions) {
transition.setNeedCheckCache()
}
}
sstep("reindex preliminary solutions of disabled transitions") {
reindexTransitionSolutions()
}
sstep("reset clocks of transitions that became disabled") {
collectTransitions(EnabledMode.DISABLED_BY_MARKING).forEach { t ->
t.timer.resetCounter()
}
}
sstep("clean tokens whose participation is finished") {
garbageTokensAtEndPlace()
}
stepNumber++
return logBuilder.build()
}
private fun cleanTokenTransitionVisits(tokens: Collection<TokenWrapper>) {
for (token in tokens) {
for (visitedTransition in token.visitedTransitions) {
visitedTransition.removeTokenVisit(token)
}
}
}
private fun fireTransition(transition: TransitionWrapper) {
logBuilder.recordFiredTransition(transition)
val solution = transition.inputArcsSolutions(tokenStore, shuffler, tokenGenerator = tokenStore)
.iterator().also {
require(it.hasNext()) {
"during transition fire there must already exist solution that was checked before"
}
}
.next()
val generatedAtInputSolution = (solution as? FullSolution.Tokens)?.generatedTokens ?: emptyList()
val minusTokens = solution.toTokenSlice()
val (plusTokens, consumed, generatedAtOutput) = transition.outputArcsSolutions(
minusTokens,
shuffler,
tokenGenerator = tokenStore
)
tokenStore.minus(minusTokens)
tokenStore.plus(plusTokens)
if (DEBUG) {
println("minusTokens ${minusTokens.makeBeautifulString()}")
println("plusTokens ${plusTokens.makeBeautifulString()}")
println("removed tokens $consumed")
println("generated tokens ${generatedAtInputSolution + generatedAtOutput}")
}
logBuilder.recordTokens(
minusTokens,
plusTokens,
generatedAtInputSolution + generatedAtOutput
)
transition.logTokensOnFireIfSynchronized(plusTokens)
transition.transitionsWithSharedPreplaces.forEach { t ->
t.timer.resetCounter()
}
garbageTokens(consumed)
}
private fun garbageTokens(tokens: List<TokenWrapper>) {
cleanTokenTransitionVisits(tokens)
tokenStore.removeTokens(tokens)
}
private fun garbageTokensAtEndPlace() {
model.outPlaces.forEach { endPlace ->
cleanTokenTransitionVisits(tokenStore.tokensAt(endPlace))
tokenStore.modifyTokensAt(endPlace) { tokens ->
tokenStore.removeTokens(tokens)
tokens.clear()
}
}
}
private fun determineShiftTimes(enabledByMarking: Transitions): LongRange? {
if (enabledByMarking.isEmpty()) return null
// find time until min lft
val minTimeUntilLftTrans = enabledByMarking.minByOrNull {
it.timer.timeUntilLFT()
}!!.timer.timeUntilLFT()
// find time until min eft
val minTimeUntilEftTrans = enabledByMarking.minByOrNull {
it.timer.timeUntilEFT()
}!!.timer.timeUntilEFT()
return minTimeUntilEftTrans..minTimeUntilLftTrans
}
private suspend fun selectShiftTime(shiftTimes: LongRange): Long {
return shiftTimeSelector.get(shiftTimes)
}
private suspend fun selectTransitionToFire(transitions: Transitions): TransitionWrapper {
return transitionSelector.get(transitions)
}
}
| 0
|
Kotlin
|
0
| 1
|
32a25441882c4780ed6b964a24430ef086222b76
| 8,288
|
ocgena
|
MIT License
|
src/main/kotlin/dev/neire/mc/youdonthavetheright/datagen/BrewingRecipesProvider.kt
|
neirenoir
| 808,780,850
| false
|
{"Kotlin": 56063, "Java": 33248}
|
package dev.neire.mc.youdonthavetheright.datagen
import dev.neire.mc.youdonthavetheright.logic.crafter.BrewingLogic
import dev.neire.mc.youdonthavetheright.mixins.crafter.PotionBrewingAccessor
import dev.neire.mc.youdonthavetheright.recipebook.BrewingBookCategory
import dev.neire.mc.youdonthavetheright.recipebook.RecipeBrewingRecipe
import net.minecraft.data.PackOutput
import net.minecraft.data.recipes.FinishedRecipe
import net.minecraft.data.recipes.RecipeProvider
import net.minecraft.resources.ResourceLocation
import net.minecraft.world.item.ItemStack
import net.minecraft.world.item.Items
import net.minecraft.world.item.alchemy.Potion
import net.minecraft.world.item.alchemy.PotionUtils
import net.minecraft.world.item.alchemy.Potions
import net.minecraftforge.data.event.GatherDataEvent
import net.minecraftforge.registries.ForgeRegistries
import java.util.function.Consumer
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.Logger
class BrewingRecipesProvider(packOutput: PackOutput) : RecipeProvider(packOutput) {
// Initialize a logger for debugging purposes
private val logger: Logger = LogManager.getLogger()
override fun buildRecipes(consumer: Consumer<FinishedRecipe>) {
val potionTypes = arrayOf(
Pair(Items.POTION, BrewingBookCategory.POTION),
Pair(Items.SPLASH_POTION, BrewingBookCategory.SPLASHING),
Pair(Items.LINGERING_POTION, BrewingBookCategory.LINGERING)
)
// Iterate over each potion type and its category
for ((potionItem, category) in potionTypes) {
PotionBrewingAccessor.getPotionMixes().forEach { mix ->
val inputPotion: Potion = mix.from.get()
val outputPotion: Potion = mix.to.get()
logger.debug(
"Processing brewing mix: {} -> {} with ingredient: {}",
inputPotion,
outputPotion,
mix.ingredient
)
val ingredientRL: ResourceLocation? =
ForgeRegistries.ITEMS.getKey(mix.ingredient.items[0].item)
val inputRL: ResourceLocation? =
ForgeRegistries.POTIONS.getKey(inputPotion)
val outputRL: ResourceLocation? =
ForgeRegistries.POTIONS.getKey(outputPotion)
val potionItemRL: ResourceLocation? =
ForgeRegistries.ITEMS.getKey(potionItem)
if (ingredientRL == null) {
logger.warn("Ingredient item not registered: ${mix.ingredient.items[0]
.item}")
return@forEach
}
if (inputRL == null) {
logger.warn("Input potion not registered: $inputPotion")
return@forEach
}
if (outputRL == null) {
logger.warn("Output potion not registered: $outputPotion")
return@forEach
}
// Validate that the ingredient has at least one item
if (mix.ingredient.items.isEmpty()) {
logger.warn("Ingredient has no items: $mix.ingredient")
return@forEach
}
// Create ItemStacks for input and output potions
val basePotionStack =
PotionUtils.setPotion(ItemStack(potionItem), inputPotion)
val resultPotionStack =
PotionUtils.setPotion(ItemStack(potionItem), outputPotion)
val recipeId = BrewingLogic.buildRecipeId(
potionItemRL!!, inputRL, ingredientRL, outputRL
)
// Build and save the brewing recipe using the custom BrewingRecipeBuilder
BrewingRecipeBuilder
.brewing(
listOf(
mix.ingredient.items.first(),
basePotionStack
),
resultPotionStack,
BrewingBookCategory.POTION,
RecipeBrewingRecipe.Serializer
)
.unlockedBy("has_potion", has(potionItem))
.group(category.toString())
.save(consumer, recipeId)
}
}
PotionBrewingAccessor.getContainerMixes().forEach { mix ->
try {
val input = PotionUtils.setPotion(ItemStack(Items.POTION), Potions.WATER)
val output = PotionUtils.setPotion(ItemStack(mix.to.get()), Potions.WATER)
val ingredient = ItemStack(mix.ingredient.items.first().item, 1)
BrewingRecipeBuilder
.brewing(
listOf(ingredient, input),
output,
BrewingBookCategory.POTION,
RecipeBrewingRecipe.Serializer
)
.unlockedBy("has_potion", has(input.item))
.save(consumer)
} catch (e: Exception) {
// Catch and log any unexpected exceptions during recipe processing
logger.error("Error processing brewing mix: ${mix.from.get()} -> ${mix.to.get()} with ingredient: ${mix.ingredient}", e)
}
}
}
}
object BrewingRecipesEventListener {
fun onGatherData(ev: GatherDataEvent) {
ev.generator.addProvider(
ev.includeServer(),
BrewingRecipesProvider(ev.generator.packOutput)
)
}
}
| 0
|
Kotlin
|
0
| 0
|
fc3744489e0a7a9aee2ade7ca7d2dcc87980c981
| 5,658
|
you-dont-have-the-right
|
MIT License
|
app/src/main/java/com/example/dropy/ui/components/commons/LoadImage.kt
|
dropyProd
| 705,360,878
| false
|
{"Kotlin": 3916897, "Java": 20617}
|
package com.example.dropy.ui.components.commons
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.example.dropy.R
@Composable
fun LoadImage(
imageUrl:String? = null,
imageDescription:String = "image",
modifier: Modifier = Modifier,
contentScale: ContentScale = ContentScale.Crop
){
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(imageUrl)
.crossfade(true)
.build(),
placeholder = painterResource(R.drawable.imageplaceholder),
error = painterResource(R.drawable.imageplaceholder),
contentDescription = imageDescription,
contentScale = contentScale,
modifier = modifier
.fillMaxSize()
)
}
| 0
|
Kotlin
|
0
| 0
|
6d994c9c61207bac28c49717b6c250656fe4ae6b
| 1,032
|
DropyLateNights
|
Apache License 2.0
|
app/src/main/java/com/moataz/mox/ui/ux/viewmodel/UXViewModel.kt
|
MoatazBadawy
| 526,809,224
| false
|
{"Kotlin": 33050}
|
package com.moataz.mox.ui.ux.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.moataz.mox.data.model.ArticleResponse
import com.moataz.mox.data.repository.UXRepository
import com.moataz.mox.utils.status.Recourses
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
class UXViewModel : ViewModel() {
private val disposables = CompositeDisposable()
private val articlesRepository = UXRepository()
private val _mediumObjectsList = MutableLiveData<Recourses<ArticleResponse>>()
val mediumObjectsList: LiveData<Recourses<ArticleResponse>> get() = _mediumObjectsList
private fun makeApiCallUx() {
disposables.add(articlesRepository.getUXList()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ result: ArticleResponse ->
_mediumObjectsList.postValue(
Recourses.Success(
result
)
)
},
{ error -> _mediumObjectsList.postValue(Recourses.Failure(error.message.toString())) }
))
}
init {
makeApiCallUx()
}
override fun onCleared() {
disposables.clear()
}
}
| 0
|
Kotlin
|
0
| 0
|
5a7f4970fd37bd91c4535e211e5694cfb9f7f0ed
| 1,448
|
MOX_Articles
|
Apache License 2.0
|
src/me/anno/gpu/buffer/StaticBuffer.kt
|
AntonioNoack
| 456,513,348
| false
| null |
package me.anno.gpu.buffer
import me.anno.gpu.GFX
import me.anno.gpu.shader.Shader
import me.anno.image.svg.SVGMesh
import me.anno.utils.pooling.ByteBufferPool
import org.lwjgl.opengl.GL31C.*
open class StaticBuffer(attributes: List<Attribute>, var vertexCount: Int, usage: Int = GL_STATIC_DRAW) :
Buffer(attributes, usage) {
constructor(points: List<List<Float>>, attributes: List<Attribute>, vertices: IntArray) :
this(attributes, vertices.size) {
for (v in vertices) {
for (p in points[v]) {
put(p)
}
}
}
constructor(points: FloatArray, vertices: IntArray, attributes: List<Attribute>) :
this(attributes, vertices.size) {
val dimPerPoint = attributes.sumOf { it.components }
for (v in vertices) {
val baseIndex = v * dimPerPoint
for (dOffset in 0 until dimPerPoint) {
put(points[baseIndex + dOffset])
}
}
}
constructor(floats: FloatArray, attributes: List<Attribute>) :
this(attributes, floats.size / attributes.sumOf { it.components }) {
put(floats)
}
init {
createNioBuffer()
}
// data for SVGs, might be removed in the future
var minX = 0f
var maxX = 0f
var minY = 0f
var maxY = 0f
/**
* copies all information over
* */
fun put(s: StaticBuffer) {
val dst = nioBuffer!!
val src = s.nioBuffer!!
val length = src.position()
for (i in 0 until length) {
dst.put(src[i])
}
}
fun setBounds(svg: SVGMesh) {
minX = svg.minX
maxX = svg.maxX
minY = svg.minY
maxY = svg.maxY
}
open fun clear() {
val buffer = nioBuffer!!
buffer.position(0)
buffer.limit(buffer.capacity())
isUpToDate = false
drawLength = 0
}
final override fun createNioBuffer() {
val byteSize = vertexCount * attributes.sumOf { it.byteSize }
nioBuffer = ByteBufferPool.allocateDirect(byteSize)
}
companion object {
private val nullBuffer = StaticBuffer(
listOf(Attribute("nothing0", AttributeType.UINT8_NORM, 4)),
4
).apply {
putInt(0)
putInt(1)
putInt(2)
putInt(3)
}
fun drawArraysNull(shader: Shader, mode: Int, length: Int) {
// we need a null array, or bind bogus data, because drivers don't like this
// https://stackoverflow.com/questions/8039929/opengl-drawarrays-without-binding-vbo
nullBuffer.drawMode = mode
nullBuffer.ensureBuffer()
nullBuffer.apply {
val baseLength = when (mode) {
GL_LINE, GL_LINES -> 2
GL_TRIANGLES -> 3
GL_QUADS -> 4
else -> throw RuntimeException("DrawMode ${GFX.getName(mode)} is not supported")
}
bind(shader)
glDrawArraysInstanced(mode, 0, baseLength, length)
unbind(shader)
}
}
fun join(buffers: List<StaticBuffer>): StaticBuffer? {
if (buffers.isEmpty()) return null
val vertexCount = buffers.sumOf { it.vertexCount }
val sample = buffers.first()
val joint = StaticBuffer(sample.attributes, vertexCount)
for (buffer in buffers) joint.put(buffer)
return joint
}
}
}
| 0
|
Kotlin
|
1
| 9
|
566e183d43bff96ee3006fecf0142e6d20828857
| 3,546
|
RemsEngine
|
Apache License 2.0
|
app/src/main/java/android/thortechasia/popularmovie/utils/Ext.kt
|
riefist
| 160,018,829
| false
| null |
package android.thortechasia.popularmovie.utils
import android.content.Context
import android.view.View
import android.widget.ImageView
import com.bumptech.glide.Glide
fun ImageView.loadImage(context: Context, url: String){
Glide.with(context)
.load(url)
.into(this)
}
fun View.visible(){
visibility = View.VISIBLE
}
fun View.gone(){
visibility = View.GONE
}
| 0
|
Kotlin
|
2
| 1
|
6ec35276828745ba7e4857c1a586f707e780f981
| 390
|
PopularMovie
|
MIT License
|
Core/src/main/kotlin/collections/refcell/RefCell.kt
|
Froze-N-Milk
| 723,515,808
| false
|
{"Kotlin": 102332, "Java": 43672}
|
package collections.refcell
import datacarton.annotations.Data
import datacarton.annotations.Flatten
import java.util.function.Consumer
import java.util.function.Supplier
open class RefCell<T>(private var ref: T) : Supplier<T>, Consumer<T> {
override fun get(): T {
return ref
}
override fun accept(p0: T) {
this.ref = p0;
}
}
| 0
|
Kotlin
|
2
| 1
|
2f3cfc190869e40629c43c098dc969e0260fe146
| 361
|
Dairy
|
BSD 3-Clause Clear License
|
app/src/main/java/com/martinszuc/templateapp/ui/component/menu/MenuScreen.kt
|
martinszuc
| 849,894,555
| false
|
{"Kotlin": 75233}
|
package com.martinszuc.templateapp.ui.component.menu
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.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.List
import androidx.compose.material.icons.filled.List
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.martinszuc.templateapp.R
import com.martinszuc.templateapp.ui.component.common.AppBarWithoutActions
import com.martinszuc.templateapp.ui.component.common.SquareButtonWithIcon
import com.martinszuc.templateapp.ui.navigation.Screen
@Composable
fun MenuScreen(navController: NavHostController) {
Scaffold(
topBar = {
AppBarWithoutActions(
title = stringResource(R.string.label_menu)
)
}
) { innerPadding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(innerPadding)
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
// Define the buttons with labels, routes, and icons
val buttons = listOf(
Triple(
"Screen Three",
Screen.ScreenThree.route,
Icons.Filled.Search // Change icon as needed
),
Triple(
"Screen Four",
Screen.ScreenFour.route,
Icons.AutoMirrored.Filled.List // Change icon as needed
)
// Add more buttons here with appropriate labels, routes, and icons
)
// Display buttons in rows of 2
buttons.chunked(2).forEach { rowButtons ->
Row(
horizontalArrangement = Arrangement.spacedBy(16.dp),
modifier = Modifier.fillMaxWidth()
) {
rowButtons.forEach { (label, route, icon) ->
Box(
modifier = Modifier
.weight(1f)
.padding(8.dp),
contentAlignment = Alignment.Center
) {
SquareButtonWithIcon(
label = label,
route = route,
icon = icon,
navController = navController
)
}
}
// Add a Spacer to fill the row if there's an odd number of buttons
if (rowButtons.size == 1) {
Spacer(
modifier = Modifier
.weight(1f)
.padding(8.dp)
)
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
e29d358f30147c13e53bc0a99db4d22ae8b1ed18
| 3,638
|
template-compose-navigation
|
MIT License
|
app/src/main/java/com/example/palto/ui/menu/MenuFragment.kt
|
Faraphel
| 706,555,802
| false
|
{"Kotlin": 37739}
|
package com.example.palto.ui.menu
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.navGraphViewModels
import com.example.palto.R
import com.example.palto.databinding.FragmentMenuListBinding
import com.example.palto.domain.Session
import com.example.palto.ui.login.LoginViewModel
/**
* A fragment representing a list of Sessions.
*/
class MenuFragment : Fragment() {
private val menuViewModel: MenuViewModel by
navGraphViewModels(R.id.nav_graph) { MenuViewModel.Factory }
private val loginViewModel: LoginViewModel by
activityViewModels() { LoginViewModel.Factory }
// This property is only valid between onCreateView and onDestroyView
private lateinit var binding: FragmentMenuListBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentMenuListBinding.inflate(inflater, container, false)
val navController = findNavController()
// Connect the user.
loginViewModel.user.observe(viewLifecycleOwner) {
if (it != null) {
// Get sessions of the user from remote.
} else {
navController.navigate(R.id.loginFragment)
}
}
// Display the list of sessions.
// Create a new MenuAdapter (list) with the given function when clicking an item.
val adapter = MenuAdapter { adapterOnClick(it) }
binding.menuList.adapter = adapter
// Link the adapter with the session list in the menuViewMode.
menuViewModel.sessions.observe(viewLifecycleOwner) {
adapter.submitList(it)
}
// Bind the add button.
binding.createSession.setOnClickListener {
navController.navigate(R.id.action_menuFragment_to_newSessionFragment)
}
return binding.root
}
private fun adapterOnClick(session: Session) {
val bundle = bundleOf("session" to session.id)
findNavController().navigate(R.id.action_menuFragment_to_sessionFragment, bundle)
}
}
| 0
|
Kotlin
|
0
| 0
|
af46937c9d5e4a4b1c1045d4ac8361dc31a32aae
| 2,374
|
Palto-Client
|
Apache License 2.0
|
src/main/kotlin/ru/dronelektron/microlisp/parser/SemanticException.kt
|
dronelektron
| 215,286,625
| false
| null |
package ru.dronelektron.microlisp.parser
import ru.dronelektron.grammarparser.lrone.lexer.token.Token
class SemanticException(
message: String,
val token: Token,
cause: Throwable? = null
) : Exception(message, cause)
| 0
|
Kotlin
|
0
| 0
|
203172eb252263a5927aa6103b725cc804c88798
| 222
|
micro-lisp
|
MIT License
|
app/src/main/java/com/starwarscharacter/app/features/planet/domain/entity/Planets.kt
|
mirmahfuz99
| 719,903,588
| false
|
{"Kotlin": 75841}
|
package com.starwarscharacter.app.features.planet.domain.entity
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "planets")
data class Planets(
@PrimaryKey
var id: String = "",
var name: String?,
val rotationPeriod: String?,
val orbitalPeriod: String?,
val diameter: String?,
val climate: String?,
val gravity: String?,
val terrain: String?,
val surfaceWater: String?,
val population: String?,
)
| 0
|
Kotlin
|
0
| 0
|
674b3e619004980e2ee8bdb99ab90242971ae328
| 472
|
StarWarsCharacter
|
Apache License 2.0
|
app/src/main/java/smk/adzikro/moviezone/ui/main/MainActivity.kt
|
al-qorut
| 683,978,951
| false
|
{"Kotlin": 97687}
|
package smk.adzikro.moviezone.ui.main
import android.animation.ObjectAnimator
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.ViewTreeObserver
import android.view.WindowManager
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.animation.doOnEnd
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import dagger.hilt.android.AndroidEntryPoint
import smk.adzikro.moviezone.R
import smk.adzikro.moviezone.databinding.ActivityMainBinding
import smk.adzikro.moviezone.ui.MainViewModel
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private var _binding: ActivityMainBinding ? = null
private val binding get() = _binding
private lateinit var content: View
private val viewModel by viewModels<MainViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
_binding = ActivityMainBinding.inflate(layoutInflater)
window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)
setContentView(binding?.root)
splashScreen()
setupView()
val navHostFragment = supportFragmentManager.findFragmentById(R.id.main_nav_host) as NavHostFragment
val nav = navHostFragment.navController
binding?.apply {
bottomNav.setupWithNavController(nav)
btnSearchMovie.setOnClickListener {
showSearch("")
}
}
}
private fun splashScreen(){
content = findViewById(android.R.id.content)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
content.viewTreeObserver.addOnPreDrawListener(object :
ViewTreeObserver.OnPreDrawListener {
override fun onPreDraw(): Boolean =
when {
viewModel.mockDataLoading() -> {
content.viewTreeObserver.removeOnPreDrawListener(this)
true
}
else -> false
}
})
splashScreen.setOnExitAnimationListener { splashScreenView ->
ObjectAnimator.ofFloat(
splashScreenView,
View.TRANSLATION_X,
0f,
splashScreenView.width.toFloat()
).apply {
duration = 1000
doOnEnd {
splashScreenView.remove()
}
}.also {
it.start()
}
}
}
}
private fun setupView() {
binding?.apply {
menuMain.getToolbar().inflateMenu(R.menu.home_menu)
menuMain.toggleHideOnScroll(false)
menuMain.setupMenu()
menuMain.onSearchClosedListener = {
//getAllFragments().forEach {
// it?.searchQueryChanged("")
// }
}
menuMain.onSearchTextChangedListener = { text ->
if (text.length >= 3) {
showSearch(text)
}
}
menuMain.getToolbar().setOnMenuItemClickListener { menuItem ->
when (menuItem.itemId) {
R.id.action_setting -> showSetting()
R.id.action_logout -> finish()
else -> return@setOnMenuItemClickListener false
}
return@setOnMenuItemClickListener true
}
}
}
private fun showSetting(){
val navController = findNavController(R.id.main_nav_host)
navController.navigateUp()
navController.navigate(R.id.settingsFragment)
}
override fun onDestroy() {
super.onDestroy()
_binding = null
}
private fun showSearch(query:String){
val uri = Uri.parse("movieapp://search")
val intent = Intent(Intent.ACTION_VIEW, uri)
intent.putExtra("search",query)
startActivity(intent)
}
}
| 0
|
Kotlin
|
0
| 0
|
1057c8c290ff078d2d69a1e33317c07eea368348
| 4,288
|
MovieZone
|
Apache License 2.0
|
app/src/main/kotlin/jp/co/yumemi/android/code_check/view/activity/TopActivity.kt
|
yuchan2215
| 532,719,899
| false
| null |
/*
* Copyright © 2021 YUMEMI Inc. All rights reserved.
*/
package jp.co.yumemi.android.code_check.view.activity
import androidx.appcompat.app.AppCompatActivity
import java.util.*
import jp.co.yumemi.android.code_check.R
class TopActivity : AppCompatActivity(R.layout.activity_top) {
companion object {
/**GitHubリポジトリを最後に検索した日時*/
var lastSearchDate: Date? = null
}
}
| 1
|
Kotlin
|
0
| 0
|
23820fe5a75abf4759e7973363a20ca64725be36
| 395
|
android-engineer-codecheck
|
Apache License 2.0
|
neumorph/effect/src/commonMain/kotlin/com/adwi/neumorph/neumorph/shape/MorphShape.kt
|
charlee-dev
| 463,862,958
| false
|
{"Kotlin": 104402}
|
package com.adwi.neumorph.neumorph.shape
import androidx.compose.ui.graphics.drawscope.ContentDrawScope
import com.adwi.neumorph.neumorph.model.MorphStyle
abstract class MorphShape(open val cornerShape: CornerShape) {
abstract fun draw(drawScope: ContentDrawScope, style: MorphStyle)
}
| 8
|
Kotlin
|
5
| 88
|
a645509e241778e1ea29ebb48b8bd6b46a374f58
| 292
|
neumorph-ui
|
The Unlicense
|
core/src/commonMain/kotlin/work/socialhub/kmisskey/entity/GalleryPost.kt
|
uakihir0
| 756,689,268
| false
|
{"Kotlin": 223847, "Shell": 2146, "Makefile": 315}
|
package work.socialhub.kmisskey.entity
import kotlinx.serialization.Serializable
import work.socialhub.kmisskey.entity.user.User
@Serializable
open class GalleryPost {
var id: String? = null
var createdAt: String? = null
var updatedAt: String? = null
var title: String? = null
var description: String? = null
var userId: String? = null
var user: User? = null
var fileIds: List<String>? = null
var files: List<File>? = null
var tags: List<String>? = null
var sensitive: Boolean? = null
var liked: Boolean? = null
var likedCount: Int? = null
}
| 1
|
Kotlin
|
1
| 3
|
744f62ce20e8038edc7b80ce705c8de4fe24a379
| 601
|
kmisskey
|
MIT License
|
src/test/kotlin/org/amshove/kluent/tests/backtickassertions/ShouldBeTrueTests.kt
|
charles-achilefu
| 113,007,100
| true
|
{"Kotlin": 374684}
|
package org.amshove.kluent.tests.backtickassertions
import org.amshove.kluent.`should be true`
import org.jetbrains.spek.api.Spek
import kotlin.test.assertFails
class ShouldBeTrueTests : Spek({
given("the `should be true` method") {
on("passing true") {
it("should pass") {
true.`should be true`()
}
}
on("passing false") {
it("should fail") {
assertFails({ false.`should be true`() })
}
}
}
})
| 0
|
Kotlin
|
0
| 0
|
e15459f09557a40c1d21de1f002fc43a8e9bf9a7
| 517
|
Kluent
|
MIT License
|
src/test/kotlin/org/amshove/kluent/tests/backtickassertions/ShouldBeTrueTests.kt
|
charles-achilefu
| 113,007,100
| true
|
{"Kotlin": 374684}
|
package org.amshove.kluent.tests.backtickassertions
import org.amshove.kluent.`should be true`
import org.jetbrains.spek.api.Spek
import kotlin.test.assertFails
class ShouldBeTrueTests : Spek({
given("the `should be true` method") {
on("passing true") {
it("should pass") {
true.`should be true`()
}
}
on("passing false") {
it("should fail") {
assertFails({ false.`should be true`() })
}
}
}
})
| 0
|
Kotlin
|
0
| 0
|
e15459f09557a40c1d21de1f002fc43a8e9bf9a7
| 517
|
Kluent
|
MIT License
|
src/en/mangamo/src/eu/kanade/tachiyomi/extension/en/mangamo/dto/MangamoLoginDto.kt
|
komikku-app
| 720,497,299
| false
|
{"Kotlin": 6775539, "JavaScript": 2160}
|
package eu.kanade.tachiyomi.extension.en.mangamo.dto
import kotlinx.serialization.Serializable
@Serializable
class MangamoLoginDto(
val accessToken: String,
)
| 22
|
Kotlin
|
8
| 97
|
7fc1d11ee314376fe0daa87755a7590a03bc11c0
| 165
|
komikku-extensions
|
Apache License 2.0
|
services/csm.cloud.project.notifications/src/main/kotlin/com/bosch/pt/csm/cloud/projectmanagement/company/facade/listener/strategies/state/UpdateStateFromEmployeeEvent.kt
|
boschglobal
| 805,348,245
| false
|
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
|
/*
* *************************************************************************
*
* Copyright: Robert Bosch Power Tools GmbH, 2019
*
* *************************************************************************
*/
package com.bosch.pt.csm.cloud.projectmanagement.company.facade.listener.strategies.state
import com.bosch.pt.csm.cloud.common.businesstransaction.boundary.EventRecord
import com.bosch.pt.csm.cloud.common.model.key.EventMessageKey
import com.bosch.pt.csm.cloud.companymanagement.employee.messages.EmployeeEventAvro
import com.bosch.pt.csm.cloud.companymanagement.employee.messages.EmployeeEventEnumAvro
import com.bosch.pt.csm.cloud.companymanagement.employee.messages.buildAggregateIdentifier
import com.bosch.pt.csm.cloud.companymanagement.employee.messages.getCompanyIdentifier
import com.bosch.pt.csm.cloud.companymanagement.employee.messages.getUserIdentifier
import com.bosch.pt.csm.cloud.projectmanagement.company.boundary.EmployeeService
import com.bosch.pt.csm.cloud.projectmanagement.company.model.Employee
import com.bosch.pt.csm.cloud.projectmanagement.notification.facade.listener.strategies.state.AbstractStateStrategy
import com.bosch.pt.csm.cloud.projectmanagement.notification.facade.listener.strategies.state.UpdateStateStrategy
import datadog.trace.api.Trace
import org.springframework.stereotype.Component
@Component
class UpdateStateFromEmployeeEvent(private val employeeService: EmployeeService) :
AbstractStateStrategy<EmployeeEventAvro>(), UpdateStateStrategy {
override fun handles(record: EventRecord) = record.value is EmployeeEventAvro
@Trace
override fun updateState(messageKey: EventMessageKey, event: EmployeeEventAvro): Unit =
event.aggregate.run {
employeeService.save(
Employee(
identifier = buildAggregateIdentifier(),
companyIdentifier = getCompanyIdentifier(),
userIdentifier = getUserIdentifier(),
deleted = event.name == EmployeeEventEnumAvro.DELETED))
}
}
| 0
|
Kotlin
|
3
| 9
|
9f3e7c4b53821bdfc876531727e21961d2a4513d
| 2,030
|
bosch-pt-refinemysite-backend
|
Apache License 2.0
|
yandex-mapkit-kmp/src/commonMain/kotlin/ru/sulgik/mapkit/MapKit.kt
|
SuLG-ik
| 813,953,018
| false
|
{"Kotlin": 210084}
|
package ru.sulgik.mapkit
import ru.sulgik.mapkit.location.LocationManager
import ru.sulgik.mapkit.map.MapWindow
import ru.sulgik.mapkit.user_location.UserLocationLayer
import ru.sulgik.runtime.sensors.LocationActivityType
expect class MapKit {
/**
* Returns the version of the MapKit bundle.
*/
val version: String
/**
* Resets the global location manager to a default one, that is a location manager that is created by createLocationManager() call.
*/
fun resetLocationManagerToDefault()
/**
* Notifies MapKit when the application resumes the foreground state.
*/
fun onStart()
/**
* Notifies MapKit when the application pauses and goes to the background.
*/
fun onStop()
/**
* Sets single global location manager that is used by every module in MapKit by default.
*/
fun setLocationManager(locationManager: LocationManager)
/**
* Creates a manager that allows to listen for device location updates.
*/
fun createLocationManager(): LocationManager
/**
* Creates a manager that allows to listen for device location updates, uses activityType as a hint.
*/
fun createLocationManager(activityType: LocationActivityType): LocationManager
/**
* Create layer with the user location icon.
*/
fun createUserLocationLayer(mapWindow: MapWindow): UserLocationLayer
companion object {
fun setLocale(locale: String?)
fun setApiKey(apiKey: String)
fun setUserId(userId: String)
fun getInstance(): MapKit
}
}
| 1
|
Kotlin
|
1
| 10
|
c7923c349864cbb38d90fff888d455a96524cbfb
| 1,596
|
yandex-mapkit-kmp
|
Apache License 2.0
|
src/test/kotlin/no/skatteetaten/aurora/sprocket/service/ImageChangeEventServiceTest.kt
|
Skatteetaten
| 179,026,051
| false
| null |
package no.skatteetaten.aurora.sprocket.service
import assertk.assertThat
import assertk.assertions.isEqualTo
import assertk.assertions.isNull
import no.skatteetaten.aurora.sprocket.jsonMapper
import no.skatteetaten.aurora.sprocket.utils.ResourceLoader
import org.junit.jupiter.api.Test
class ImageChangeEventServiceTest : ResourceLoader() {
val service = ImageChangeEventService()
@Test
fun `should parse global event`() {
val event = service.fromGlobalNexus(loadJsonResource("globalNexus.json", "events"))
assertThat(event?.name).isEqualTo("no_skatteetaten_aurora/test")
assertThat(event?.tag).isEqualTo("1")
}
@Test
fun `should parse global snapshot event`() {
val event = service.fromGlobalNexus(loadJsonResource("globalNexusSnapshot.json", "events"))
assertThat(event?.name).isEqualTo("no_skatteetaten_aurora/test")
assertThat(event?.tag).isEqualTo("nexus-SNAPSHOT")
}
@Test
fun `should parse global asset event with version present`() {
val event = service.fromGlobalNexus(loadJsonResource("globalNexusNew.json", "events"))
assertThat(event?.name).isEqualTo("sprocket-test/alpine-test2")
assertThat(event?.tag).isEqualTo("0.2")
}
@Test
fun `should ignore component events`() {
val event = service.fromGlobalNexus(loadJsonResource("globalNexusComponent.json", "events"))
assertThat(event).isNull()
}
@Test
fun `should ignore json that is not valid nexus payload`() {
val event = service.fromGlobalNexus(
jsonMapper.readTree(
"""
{
"audit": {
"domain": "repository.asset"
},
"foo" : "bar"
}
"""
)
)
assertThat(event).isNull()
}
}
| 0
|
Kotlin
|
0
| 1
|
a733671a90585acd47c003cfcd4e81d371855d3a
| 1,849
|
sprocket
|
Apache License 2.0
|
src/test/kotlin/uk/gov/justice/digital/hmpps/oauth2server/integration/ClientConfigSpecification.kt
|
uk-gov-mirror
| 356,783,105
| true
|
{"Kotlin": 1669768, "HTML": 158306, "CSS": 9895, "Shell": 8311, "Mustache": 7004, "PLSQL": 6379, "TSQL": 1100, "Dockerfile": 1015, "Groovy": 780, "JavaScript": 439}
|
package uk.gov.justice.digital.hmpps.oauth2server.integration
import org.assertj.core.api.Assertions.assertThat
import org.fluentlenium.core.annotation.Page
import org.fluentlenium.core.annotation.PageUrl
import org.fluentlenium.core.domain.FluentList
import org.fluentlenium.core.domain.FluentWebElement
import org.junit.jupiter.api.Test
import org.openqa.selenium.support.FindBy
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
class ClientConfigSpecification : AbstractAuthSpecification() {
@Page
private lateinit var clientSummaryPage: ClientSummaryPage
@Page
private lateinit var clientMaintenancePage: ClientMaintenancePage
@Page
private lateinit var clientMaintenanceAddPage: ClientMaintenanceAddPage
@Page
private lateinit var clientCreatedSuccessPage: ClientCreatedSuccessPage
@Page
private lateinit var clientUpdatedSuccessPage: ClientUpdatedSuccessPage
@Page
private lateinit var clientGenerateNewSecret: ClientGenerateNewSecret
@Page
private lateinit var duplicateClientSuccessPage: DuplicateClientSuccessPage
@Page
private lateinit var clientMaintenancePageWithError: ClientMaintenancePageWithError
@Test
fun `View Client Dashboard once logged in`() {
goTo("/ui")
loginPage.isAtPage().submitLogin("ITAG_USER_ADM", "<PASSWORD>")
clientSummaryPage.isAtPage()
.checkClientSummary()
}
@Test
fun `I can edit a client credential`() {
goTo(loginPage).loginAs("ITAG_USER_ADM", "<PASSWORD>")
goTo(clientSummaryPage).editClient()
clientMaintenancePage.isAtPage().checkDetails().save()
clientSummaryPage.isAtPage()
}
@Test
fun `I can edit a client credential with extra jwt field`() {
goTo(loginPage).loginAs("ITAG_USER_ADM", "<PASSWORD>")
goTo(clientSummaryPage).editClient("elite2apiclient")
clientMaintenancePage.isAtPage()
assertThat(el("#jwtFields").value()).isEqualTo("-name")
}
@Test
fun `I can edit a client credential with legacy username field`() {
goTo(loginPage).loginAs("ITAG_USER_ADM", "<PASSWORD>")
goTo(clientSummaryPage).editClient("prison-to-probation-update-api-client")
clientMaintenancePage.isAtPage()
assertThat(el("#databaseUsernameField").value()).isEqualTo("DSS_USER")
}
@Test
fun `I can edit a client credential with an mfa field`() {
goTo(loginPage).loginAs("ITAG_USER_ADM", "<PASSWORD>")
goTo(clientSummaryPage).editClient("deliusnewtech")
clientMaintenancePage.isAtPage()
assertThat(el("#mfa-2").selected()).isTrue
}
@Test
fun `I can edit a client credential and set an mfa field`() {
goTo(loginPage).loginAs("ITAG_USER_ADM", "<PASSWORD>")
goTo(clientSummaryPage).editClient("v1-client")
clientMaintenancePage.isAtPage()
assertThat(el("#mfa-3").selected()).isFalse
clientMaintenancePage.selectCheckboxOption("mfa-3").save()
clientSummaryPage.isAtPage().editClient("v1-client")
assertThat(el("#mfa-3").selected()).isTrue
clientMaintenancePage.selectCheckboxOption("mfa-1").save()
}
@Test
fun `I can edit a client credential as an auth user`() {
goTo(loginPage).loginAs("AUTH_ADM", "<PASSWORD>")
goTo(clientSummaryPage).editClient()
clientMaintenancePage.isAtPage().checkDetails().save()
clientSummaryPage.isAtPage()
}
@Test
fun `I can edit a client and new details are copied over to the duplicate`() {
goTo(loginPage).loginAs("AUTH_ADM", "<PASSWORD>")
goTo(clientSummaryPage).editClient("rotation-test-client")
clientMaintenancePage.isAtPage()
.edit("registeredRedirectUri", "http://a_url:3003")
.edit("accessTokenValiditySeconds", "1234")
.edit("scopes", "read,bob")
.save()
clientSummaryPage.isAtPage()
goTo(clientSummaryPage).editClient("rotation-test-client")
with(clientMaintenancePage) {
isAtPage()
assertThat(el("#registeredRedirectUri").value()).isEqualTo("http://a_url:3003")
assertThat(el("#accessTokenValiditySeconds").value()).isEqualTo("1234")
assertThat(el("#scopes").value()).isEqualTo("read,bob")
}
goTo("/ui/clients/form?client=rotation-test-client-2")
with(clientMaintenancePage) {
assertThat(el("#registeredRedirectUri").value()).isEqualTo("http://a_url:3003")
assertThat(el("#accessTokenValiditySeconds").value()).isEqualTo("1234")
assertThat(el("#scopes").value()).isEqualTo("read,bob")
}
}
@Test
fun `I can edit a client duplicate and new details are copied over to the original`() {
goTo(loginPage).loginAs("AUTH_ADM", "<PASSWORD>")
goTo("/ui/clients/form?client=rotation-test-client-2")
clientMaintenancePage.isAtPage()
.edit("resourceIds", "some_resource")
.edit("refreshTokenValiditySeconds", "2345")
.edit("authorities", "ROLE_BOB,ROLE_JOE")
.save()
clientSummaryPage.isAtPage()
goTo(clientSummaryPage).editClient("rotation-test-client")
with(clientMaintenancePage) {
isAtPage()
assertThat(el("#resourceIds").value()).isEqualTo("some_resource")
assertThat(el("#refreshTokenValiditySeconds").value()).isEqualTo("2345")
assertThat(el("#authorities").value()).isEqualTo("ROLE_BOB,ROLE_JOE")
}
goTo("/ui/clients/form?client=rotation-test-client-2")
with(clientMaintenancePage) {
assertThat(el("#resourceIds").value()).isEqualTo("some_resource")
assertThat(el("#refreshTokenValiditySeconds").value()).isEqualTo("2345")
assertThat(el("#authorities").value()).isEqualTo("ROLE_BOB,ROLE_JOE")
}
}
@Test
fun `I can generate a new client secret for client`() {
goTo(loginPage).loginAs("AUTH_ADM", "<PASSWORD>")
goTo(clientSummaryPage).editClient("rotation-test-client")
clientMaintenancePage.isAtPage()
.generateClientSecret("rotation-test-client")
clientGenerateNewSecret.cancelToClientMaintenancePage()
clientMaintenancePage.isAtPage()
.generateClientSecret("rotation-test-client")
clientGenerateNewSecret.continueToGenerateClientSecret()
clientUpdatedSuccessPage.isAtPage()
.checkClientSuccessDetails()
.continueToClientUiPage()
}
@Test
fun `I can generate a new client secret for each duplicate client`() {
goTo(loginPage).loginAs("AUTH_ADM", "<PASSWORD>")
goTo(clientSummaryPage).editClient("rotation-test-client")
clientMaintenancePage.isAtPage()
.generateClientSecret("rotation-test-client")
clientGenerateNewSecret.continueToGenerateClientSecret()
clientUpdatedSuccessPage.isAtPage()
.continueToClientUiPage()
goTo(clientSummaryPage).editClient("rotation-test-client")
clientMaintenancePage.isAtPage()
.generateClientSecret("rotation-test-client-2")
clientGenerateNewSecret.continueToGenerateClientSecret()
clientUpdatedSuccessPage.isAtPage()
.continueToClientUiPage()
goTo(clientSummaryPage).editClient("rotation-test-client")
clientMaintenancePage.isAtPage()
.duplicate()
goTo(clientSummaryPage).editClient("rotation-test-client")
clientMaintenancePage.isAtPage()
.generateClientSecret("rotation-test-client-3")
clientGenerateNewSecret.continueToGenerateClientSecret()
clientUpdatedSuccessPage.isAtPage()
.continueToClientUiPage()
goTo(clientSummaryPage).editClient("rotation-test-client")
with(clientMaintenancePage) {
isAtPage()
assertThat(el("#rotation-test-client-last-accessed").text()).isEqualTo("28-01-2013 13:23")
val secretDateTime = LocalDateTime.parse(el("#rotation-test-client-secret-updated").text(), DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm"))
assertThat(secretDateTime).isAfter(LocalDateTime.now().minusMinutes(2))
assertThat(el("#rotation-test-client-created").text()).isEqualTo("26-01-2013 13:23")
assertThat(el("#rotation-test-client-2-last-accessed").text()).isEqualTo("25-12-2018 01:03")
val secretDateTime2 = LocalDateTime.parse(el("#rotation-test-client-2-secret-updated").text(), DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm"))
assertThat(secretDateTime2).isAfter(LocalDateTime.now().minusMinutes(2))
assertThat(el("#rotation-test-client-2-last-accessed").text()).isEqualTo("25-12-2018 01:03")
val accessedDateTime3 = LocalDateTime.parse(el("#rotation-test-client-3-last-accessed").text(), DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm"))
assertThat(accessedDateTime3).isAfter(LocalDateTime.now().minusMinutes(2))
val secretDateTime3 = LocalDateTime.parse(el("#rotation-test-client-3-secret-updated").text(), DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm"))
assertThat(secretDateTime3).isAfter(LocalDateTime.now().minusMinutes(2))
val createdDateTime3 = LocalDateTime.parse(el("#rotation-test-client-3-created").text(), DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm"))
assertThat(createdDateTime3).isAfter(LocalDateTime.now().minusMinutes(2))
}
goTo("/ui/clients/rotation-test-client-3/delete")
clientSummaryPage.isAtPage()
.checkClientDoesntExist("rotation-test-client-3")
}
@Test
fun `I can create and remove client credential`() {
goTo(loginPage).loginAs("ITAG_USER_ADM", "<PASSWORD>")
goTo(clientSummaryPage).editClient(client = "client")
clientMaintenanceAddPage.isAtPage()
.edit("clientId", "new-client")
.edit("registeredRedirectUri", "http://a_url:3003")
.edit("accessTokenValiditySeconds", "1200")
.edit("scopes", "read")
.edit("authorities", "ROLE_BOB,ROLE_FRED")
.selectCheckboxOption("client_credentials")
.edit("jwtFields", "-name")
.selectCheckboxOption("mfa-3")
.save()
clientCreatedSuccessPage.isAtPage()
.checkClientSuccessDetails()
.continueToClientUiPage()
clientSummaryPage.isAtPage()
.checkClientSummary(
client = "new-client",
text =
"""
new-client
[read]
[client_credentials]
[ROLE_BOB, ROLE_FRED]
1200
MFA ALL
"""
)
// now remove so test is re-runnable
goTo("/ui/clients/new-client/delete")
clientSummaryPage.isAtPage()
.checkClientDoesntExist("new-client")
}
@Test
fun `I can duplicate a client`() {
goTo(loginPage).loginAs("AUTH_ADM", "<PASSWORD>")
goTo(clientSummaryPage).editClient("rotation-test-client")
clientMaintenancePage.isAtPage()
.duplicate()
duplicateClientSuccessPage.isAtPage()
.checkClientSuccessDetails()
.continueToClientUiPage()
// now remove so test is re-runnable
goTo("/ui/clients/rotation-test-client-3/delete")
clientSummaryPage.isAtPage()
.checkClientDoesntExist("rotation-test-client-3")
}
@Test
fun `Display last accessed, created and secret updated`() {
goTo(loginPage).loginAs("AUTH_ADM", "<PASSWORD>")
goTo(clientSummaryPage).editClient("rotation-test-client")
with(clientMaintenancePage) {
isAtPage()
assertThat(el("#rotation-test-client-last-accessed").text()).isEqualTo("28-01-2013 13:23")
val secretDateTime = LocalDateTime.parse(el("#rotation-test-client-secret-updated").text(), DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm"))
assertThat(secretDateTime).isAfter(LocalDateTime.now().minusDays(1))
assertThat(el("#rotation-test-client-created").text()).isEqualTo("26-01-2013 13:23")
assertThat(el("#rotation-test-client-2-last-accessed").text()).isEqualTo("25-12-2018 01:03")
val secretDateTime2 = LocalDateTime.parse(el("#rotation-test-client-secret-updated").text(), DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm"))
assertThat(secretDateTime2).isAfter(LocalDateTime.now().minusDays(1))
assertThat(el("#rotation-test-client-2-created").text()).isEqualTo("25-12-2018 01:03")
}
}
@Test
fun `I receive error if I try to have more than 3 of a client`() {
goTo(loginPage).loginAs("AUTH_ADM", "<PASSWORD>")
goTo(clientSummaryPage).editClient("rotation-test-client")
clientMaintenancePage.isAtPage()
.duplicate()
duplicateClientSuccessPage.isAtPage()
.continueToClientUiPage()
goTo(clientSummaryPage).editClient("rotation-test-client")
clientMaintenancePage.isAtPage()
.duplicate()
clientMaintenancePageWithError
.checkError("You are only allowed 3 versions of this client at one time. You will need to delete one to be able to duplicate it again.")
// now remove so test is re-runnable
goTo("/ui/clients/rotation-test-client-3/delete")
clientSummaryPage.isAtPage()
.checkClientDoesntExist("rotation-test-client-3")
}
}
@PageUrl("/ui")
class ClientSummaryPage : AuthPage<ClientSummaryPage>(
"HMPPS Digital Services - Administration Dashboard",
"OAuth server administration dashboard"
) {
@FindBy(css = "table tbody tr")
private lateinit var rows: FluentList<FluentWebElement>
@Suppress("UsePropertyAccessSyntax")
fun checkClientSummary(
client: String = "apireporting",
text: String =
"""
apireporting
[reporting]
[client_credentials]
[ROLE_REPORTING]
3600""",
): ClientSummaryPage {
assertThat(rows).hasSizeGreaterThan(10)
assertThat(el("tr[data-qa='$client']").text()).isEqualTo(text.replaceIndent().replace("\n", ""))
return this
}
fun checkClientDoesntExist(client: String) {
assertThat(el("tr[data-qa='$client']").displayed()).isFalse()
}
fun editClient(client: String = "apireporting") {
el("#edit-$client").click()
}
}
@PageUrl("/ui/clients/form")
open class ClientMaintenancePage(heading: String = "Edit client", headingStartsWith: Boolean = true) :
AuthPage<ClientMaintenancePage>(
"HMPPS Digital Services - Maintain Client Configuration",
heading,
headingStartsWith
) {
@FindBy(name = "client-submit")
private lateinit var save: FluentWebElement
@FindBy(name = "duplicate-client")
private lateinit var duplicate: FluentWebElement
fun checkDetails(): ClientMaintenancePage {
assertThat(el("#clientId").value()).isEqualTo("apireporting")
assertThat(el("#clientSecret").value()).isBlank()
assertThat(el("#accessTokenValiditySeconds").value()).isEqualTo("3600")
assertThat(el("#authorities").value()).isEqualTo("ROLE_REPORTING")
assertThat(el("#jwtFields").value()).isBlank()
assertThat(el("#databaseUsernameField").value()).isBlank()
return this
}
fun editClient(client: String = "apireporting"): ClientMaintenancePage {
el("#edit-$client").click()
return this
}
fun edit(field: String, text: String): ClientMaintenancePage {
el("#$field").click().fill().with(text)
return this
}
fun selectCheckboxOption(type: String): ClientMaintenancePage {
el("#$type").click()
return this
}
fun save() {
save.click()
}
fun duplicate(): ClientMaintenancePage {
duplicate.click()
return this
}
fun generateClientSecret(client: String) {
el("#generate-secret-$client").click()
}
}
@PageUrl("/ui/clients/form")
class ClientMaintenanceAddPage : ClientMaintenancePage("Add client", false)
@PageUrl("/ui/clients/form")
class ClientMaintenancePageWithError : ClientMaintenancePage("Edit client 'rotation-test-client'", false)
@PageUrl("/ui/clients/generate")
open class ClientGenerateNewSecret : AuthPage<ClientGenerateNewSecret>(
"HMPPS Digital Services - Client Configuration",
"Generate new client secret"
) {
@FindBy(css = "#submit")
private lateinit var continueButton: FluentWebElement
@FindBy(css = "#cancel")
private lateinit var cancelButton: FluentWebElement
fun continueToGenerateClientSecret(): ClientGenerateNewSecret {
continueButton.click()
return this
}
fun cancelToClientMaintenancePage(): ClientGenerateNewSecret {
assertThat(cancelButton.text()).isEqualTo("Cancel")
cancelButton.click()
return this
}
}
@PageUrl("ui/clients/client-success")
open class ClientCreatedSuccessPage : AuthPage<ClientCreatedSuccessPage>(
"HMPPS Digital Services - Client Configuration",
"Client has been created"
) {
@FindBy(css = "#continue")
private lateinit var continueButton: FluentWebElement
fun checkClientSuccessDetails(): ClientCreatedSuccessPage {
assertThat(el("[data-qa='clientId']").text()).isEqualTo("new-client")
assertThat(el("[data-qa='clientSecret']").text()).isNotBlank
assertThat(el("[data-qa='base64ClientId']").text()).isEqualTo("bmV3LWNsaWVudA==")
assertThat(el("[data-qa='base64ClientSecret']").text()).isNotBlank
return this
}
fun continueToClientUiPage(): ClientCreatedSuccessPage {
assertThat(continueButton.text()).isEqualTo("Continue")
continueButton.click()
return this
}
}
@PageUrl("ui/clients/client-success")
open class ClientUpdatedSuccessPage : AuthPage<ClientUpdatedSuccessPage>(
"HMPPS Digital Services - Client Configuration",
"Client secret has been updated"
) {
@FindBy(css = "#continue")
private lateinit var continueButton: FluentWebElement
fun checkClientSuccessDetails(): ClientUpdatedSuccessPage {
assertThat(el("[data-qa='clientId']").text()).isEqualTo("rotation-test-client")
assertThat(el("[data-qa='clientSecret']").text()).isNotBlank
assertThat(el("[data-qa='base64ClientId']").text()).isEqualTo("cm90YXRpb24tdGVzdC1jbGllbnQ=")
assertThat(el("[data-qa='base64ClientSecret']").text()).isNotBlank
return this
}
fun continueToClientUiPage(): ClientUpdatedSuccessPage {
assertThat(continueButton.text()).isEqualTo("Continue")
continueButton.click()
return this
}
}
@PageUrl("ui/clients/duplicate-client-success")
open class DuplicateClientSuccessPage : AuthPage<DuplicateClientSuccessPage>(
"HMPPS Digital Services - Duplicate Client Configuration",
"Client has been duplicated"
) {
@FindBy(css = "#continue")
private lateinit var continueButton: FluentWebElement
fun checkClientSuccessDetails(): DuplicateClientSuccessPage {
assertThat(el("[data-qa='clientId']").text()).isEqualTo("rotation-test-client-3")
assertThat(el("[data-qa='clientSecret']").text()).isNotBlank
assertThat(el("[data-qa='base64ClientId']").text()).isEqualTo("cm90YXRpb24tdGVzdC1jbGllbnQtMw==")
assertThat(el("[data-qa='base64ClientSecret']").text()).isNotBlank
return this
}
fun continueToClientUiPage(): DuplicateClientSuccessPage {
assertThat(continueButton.text()).isEqualTo("Continue")
continueButton.click()
return this
}
}
| 0
|
Kotlin
|
0
| 0
|
f5a2a2f4eecc76459e206e7c84fde15d2c781758
| 18,419
|
ministryofjustice.hmpps-auth
|
MIT License
|
app/src/main/java/com/example/android/politicalpreparedness/election/VoterInfoViewModel.kt
|
sindyoke
| 731,385,322
| false
|
{"Kotlin": 50620}
|
package com.example.android.politicalpreparedness.election
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.android.politicalpreparedness.Repository
import com.example.android.politicalpreparedness.network.models.AdministrationBody
import com.example.android.politicalpreparedness.network.models.Division
import com.example.android.politicalpreparedness.network.models.Election
import com.example.android.politicalpreparedness.network.models.VoterInfoResponse
import kotlinx.coroutines.launch
import timber.log.Timber
class VoterInfoViewModel(private val repository: Repository, private val electionId: Int, private val division: Division) : ViewModel() {
private val _voterInfoResponse = MutableLiveData<VoterInfoResponse>()
val voterInfoResponse: LiveData<VoterInfoResponse>
get() = _voterInfoResponse
private val _election = MutableLiveData<Election>()
val election: LiveData<Election>
get() = _election
private val _stateElectionAdministrationBody = MutableLiveData<AdministrationBody>()
val stateElectionAdministrationBody: LiveData<AdministrationBody>
get() = _stateElectionAdministrationBody
private val _electionIsSaved = MutableLiveData<Boolean>()
val electionIsSaved: LiveData<Boolean>
get() = _electionIsSaved
private fun getAddress(): String {
if(division.state.isNotEmpty()) {
return "${division.country},${division.state}"
}
return "USA,CA"
}
init {
checkIfElectionSaved()
getVoterInfo()
}
fun getVoterInfo() = viewModelScope.launch {
_electionIsSaved.value = repository.checkIfElectionIsSaved(electionId).value
try {
_voterInfoResponse.value = repository.getVoterInfo(getAddress(), electionId)
_election.value = voterInfoResponse.value?.election
_stateElectionAdministrationBody.value = voterInfoResponse.value?.state?.first()?.electionAdministrationBody
Timber.d("address: ${getAddress()}, electionId: $electionId")
Timber.d("voterInfoResponse is: ${voterInfoResponse.value.toString()}")
Timber.d("election: ${voterInfoResponse.value?.election.toString()}")
Timber.d("locationUrl: ${stateElectionAdministrationBody.value?.votingLocationFinderUrl.toString()}")
Timber.d("ballotUrl: ${stateElectionAdministrationBody.value?.ballotInfoUrl.toString()}")
Timber.d("correspondenceAddress: ${stateElectionAdministrationBody.value?.correspondenceAddress.toString()}")
} catch (exception: java.lang.Exception) {
Timber.e(exception)
}
}
fun checkIfElectionSaved() {
viewModelScope.launch {
val electionFromDatabase: Election? = repository.getElectionByIdFromDb(electionId)
if(electionFromDatabase == null) {
Timber.d("election from database is null")
_electionIsSaved.value = false
} else {
Timber.d("electionId from database is ${electionFromDatabase.id}")
_electionIsSaved.value = true
}
}
}
fun onButtonClick() = viewModelScope.launch {
if(electionIsSaved.value == true) {
election.value?.let { repository.deleteElection(it.id) }
_electionIsSaved.value = false
} else {
repository.insertElection(election.value!!)
_electionIsSaved.value = true
}
}
}
| 0
|
Kotlin
|
0
| 0
|
c6a9790c9d8e414f4743d4c62ee22818a9f81e7a
| 3,602
|
PoliticalPreparedness
|
Apache License 2.0
|
app/src/main/java/com/example/wishlist/MainActivity.kt
|
IwattsX
| 853,517,715
| false
|
{"Kotlin": 5884}
|
package com.example.wishlist
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class MainActivity : AppCompatActivity() {
lateinit var WLItems: MutableList<WLItem>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
// Initialize the WLItems list
WLItems = mutableListOf(
//WLItem("Item 1", "$10", "http://example.com/1"),
//WLItem("Item 2", "$20", "http://example.com/2")
// Add more items as needed
)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
val itemsRv = findViewById<RecyclerView>(R.id.wishlist_items)
// Create and set the adapter with the initialized WLItems list
val adapter = WishListAdapter(WLItems)
itemsRv.adapter = adapter
itemsRv.layoutManager = LinearLayoutManager(this)
val summitBtn = findViewById<Button>(R.id.button)
val itemName = findViewById<EditText>(R.id.obTitle)
val itemCost = findViewById<EditText>(R.id.cost)
val itemURL = findViewById<EditText>(R.id.url)
summitBtn.setOnClickListener{
val itemsNameStr = itemName.text.toString()
val itemCostStr = itemCost.text.toString()
val itemURIStr = itemURL.text.toString()
if(itemsNameStr == "" || itemCostStr == "" || itemURIStr == ""){
Toast.makeText(it.context, "You need to enter in all fields", Toast.LENGTH_SHORT).show()
}
else {
//Toast.makeText(it.context, "You entered everything", Toast.LENGTH_SHORT).show()
val newItem = WLItem(itemsNameStr, itemCostStr, itemURIStr)
WLItems.add(newItem)
adapter.notifyItemInserted(adapter.itemCount - 1)
// Clear the text from the EditText
itemName.text.clear()
itemCost.text.clear()
itemURL.text.clear()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
559aaa96db853448788ab199a221a93f298ff679
| 2,649
|
wishlist_android
|
Apache License 2.0
|
BasicToCompose/app/src/androidTest/java/com/example/android/basictocompose/MyComposeFragmentTest.kt
|
daijinload
| 506,486,888
| false
|
{"Kotlin": 32821}
|
package com.example.android.basictocompose
import android.graphics.Bitmap
import android.os.Environment
import android.util.Log
import androidx.compose.ui.graphics.asAndroidBitmap
import androidx.compose.ui.test.captureToImage
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onRoot
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.io.FileOutputStream
@RunWith(AndroidJUnit4::class)
class MyComposeFragmentTest {
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun helloWorldScreenshot() {
composeTestRule.setContent {
MyApp{}
}
val bitmap = composeTestRule.onRoot().captureToImage().asAndroidBitmap()
saveScreenshot("hello-world", bitmap)
}
}
// TODO スクリーンショットは保存されるが、エミュレータの中に保存されるため、どうにかして取り出したい。。。
// [View] > [Tool Windows] > [Device File Explorer] で中身は見れる。パスは下記
// /data/data/com.example.android.basictocompose/files/hello-world.png
// /sdcard/Download/dog-best-friend-1.png
private fun saveScreenshot(filename: String, bmp: Bitmap) {
val path = Environment.getExternalStorageDirectory().path
val myPngPath = "$path/Download/dog-best-friend-1.png"
val canonicalPath = InstrumentationRegistry.getInstrumentation().targetContext.filesDir.canonicalPath
Log.d("TestScreenShot", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: $canonicalPath/$filename.png");
Log.d("TestScreenShot", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa2: $myPngPath");
// FileOutputStream("$path/$filename.png").use { out ->
FileOutputStream(myPngPath).use { out ->
bmp.compress(Bitmap.CompressFormat.PNG, 100, out)
}
println("Saved screenshot to $path/$filename.png")
}
| 0
|
Kotlin
|
0
| 0
|
27332f540842104450f270b91d3c80a8a12470e9
| 1,846
|
android-naitive
|
MIT License
|
shared/src/commonMain/kotlin/ui/ScrollableDigitField.kt
|
alexmaryin
| 419,989,861
| false
|
{"Kotlin": 169549}
|
package ui
import androidx.compose.animation.*
import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.rememberScrollableState
import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.material.TextField
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlin.math.roundToInt
@Composable
fun ScrollableDigitField(
value: Int,
range: IntRange,
speed: Float = 1f,
fontSize: TextUnit = 24.sp,
fontWeight: FontWeight = FontWeight.Bold,
onChange: (Int) -> Unit
) {
var isUp by remember { mutableStateOf(false) }
var isEditable by remember { mutableStateOf(false) }
var tempValue by remember { mutableStateOf("$value") }
val density = LocalDensity.current.density * 2
Row(verticalAlignment = Alignment.CenterVertically) {
TextButton(
onClick = { onChange((value - 1).coerceIn(range)); isUp = false },
enabled = value > range.first,
modifier = Modifier.testTag("decrease button")
) { Text(text = "-", fontWeight = fontWeight, fontSize = fontSize) }
AnimatedContent(
targetState = value,
transitionSpec = {
if (isUp) {
(slideInVertically { height -> height } + fadeIn())
.togetherWith(slideOutVertically { height -> -height } + fadeOut())
} else {
(slideInVertically { height -> -height } + fadeIn())
.togetherWith(slideOutVertically { height -> height } + fadeOut())
}.using(
SizeTransform(clip = false)
)
}
) {
if (isEditable) {
TextField(
value = tempValue,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Done
),
onValueChange = { new -> tempValue = "${new.toIntOrNull() ?: ""}" },
singleLine = true,
keyboardActions = KeyboardActions(onDone = {
isEditable = false
onChange(tempValue.toInt().coerceIn(range))
})
)
} else {
Text(
text = "$value",
fontWeight = fontWeight,
fontSize = fontSize,
modifier = Modifier
.padding(horizontal = 6.dp)
.scrollable(orientation = Orientation.Vertical, reverseDirection = true,
state = rememberScrollableState { delta ->
isUp = delta > 0
val newValue = ((delta / density * speed).roundToInt() + value).coerceIn(range)
onChange(newValue)
delta
})
.clickable { isEditable = true }
)
}
}
TextButton(
onClick = { onChange((value + 1).coerceIn(range)); isUp = true },
enabled = value < range.last,
modifier = Modifier.testTag("increase button")
) { Text(text = "+", fontWeight = fontWeight, fontSize = fontSize) }
}
}
| 2
|
Kotlin
|
1
| 5
|
8a2fe1ee7b5d4b6dc4af0973a24c189b3fd4e8c2
| 4,306
|
sims_checklist
|
Apache License 2.0
|
modules/jogl/kotlin/com/huskerdev/openglfx/jogl/events/JOGLRenderEvent.kt
|
husker-dev
| 393,363,130
| false
| null |
package com.huskerdev.openglfx.jogl.events
import com.huskerdev.openglfx.canvas.events.GLRenderEvent
import com.jogamp.opengl.GL3
import javafx.beans.NamedArg
import javafx.event.EventType
class JOGLRenderEvent(
override val gl: GL3,
@NamedArg("eventType") eventType: EventType<GLRenderEvent>,
fps: Int,
delta: Double,
width: Int,
height: Int,
fbo: Int
): GLRenderEvent(eventType, fps, delta, width, height, fbo), JOGLEvent
| 7
| null |
7
| 84
|
ac22d5435915f16fa731b9e3564533c2507f2dc0
| 453
|
openglfx
|
Apache License 2.0
|
app/src/main/java/com/example/mymovie/presentation/components/Loading.kt
|
didikk
| 829,815,819
| false
|
{"Kotlin": 86255}
|
package com.example.mymovie.presentation.components
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@Composable
fun Loading(modifier: Modifier = Modifier) {
Box(
modifier = modifier
.padding(24.dp)
.fillMaxWidth()
) {
CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
}
}
| 0
|
Kotlin
|
0
| 0
|
a7a72e500525fb73e6ad19e192913fa333eb143a
| 660
|
compose-movie-app
|
MIT License
|
app/src/main/java/com/shicheeng/copymanga/fm/view/PersonalFragment.kt
|
shizheng233
| 475,870,275
| false
| null |
package com.shicheeng.copymanga.fm.view
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.graphics.Insets
import androidx.core.view.updatePadding
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.RecyclerView
import com.shicheeng.copymanga.MyApp
import com.shicheeng.copymanga.R
import com.shicheeng.copymanga.adapter.PersonalAdapter
import com.shicheeng.copymanga.app.BaseFragment
import com.shicheeng.copymanga.databinding.FragmentPersonalBinding
import com.shicheeng.copymanga.util.FileUtil
import com.shicheeng.copymanga.viewmodel.PersonalViewModel
import com.shicheeng.copymanga.viewmodel.PersonalViewModelFactory
class PersonalFragment : BaseFragment<FragmentPersonalBinding>() {
private val model: PersonalViewModel by viewModels {
PersonalViewModelFactory(
FileUtil(requireContext(), viewLifecycleOwner.lifecycleScope),
(requireActivity().application as MyApp).repo
)
}
override fun onViewBindingIn(
inflater: LayoutInflater,
container: ViewGroup?,
): FragmentPersonalBinding = FragmentPersonalBinding
.inflate(inflater, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val pool = RecyclerView.RecycledViewPool()
val adapter = PersonalAdapter(pool)
model.combineOfList.observe(viewLifecycleOwner) {
adapter.items = it
}
binding.personalRecyclerView.adapter = adapter
adapter.setOnHeaderViewOnClickListener {
when (it) {
R.string.history -> {
val action = PersonalFragmentDirections
.actionPersonalFragmentToHistoryFragment()
findNavController().navigate(action)
}
R.string.download_manga -> {
val action = PersonalFragmentDirections
.actionPersonalFragmentToDownloadFragment()
findNavController().navigate(action)
}
}
}
}
override fun onResume() {
super.onResume()
model.updateDownloadList()
}
override fun onFragmentInsets(systemBarInsets: Insets?, view: View) {
binding.personalRecyclerView.updatePadding(bottom = systemBarInsets?.bottom ?: 0)
}
}
| 5
|
Kotlin
|
0
| 58
|
0ac29592bde2b108b4da2f189db9f7b81f542b4b
| 2,578
|
CopyMangaJava
|
MIT License
|
HelperCheckDate/src/main/kotlin/com/checkdate/helper/automatichelper/logger/LoggerUtil.kt
|
hhvvkk
| 488,906,137
| false
| null |
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
import kotlin.reflect.full.companionObject
fun getLogger(forClass: Class<*>): Logger = LoggerFactory.getLogger(forClass)
fun <T : Any> getClassForLogging(javaClass: Class<T>): Class<*> {
return javaClass.enclosingClass?.takeIf {
it.kotlin.companionObject?.java == javaClass
} ?: javaClass
}
class LoggerDelegate<in R : Any> : ReadOnlyProperty<R, Logger> {
override fun getValue(thisRef: R, property: KProperty<*>) =
getLogger(getClassForLogging(thisRef.javaClass))
}
| 0
|
Kotlin
|
0
| 0
|
48ad7753ba8a58d69a5e16c5031260ae47d6210e
| 628
|
ToolsAndUtilities
|
MIT License
|
arrow-libs/core/arrow-core/src/jvmTest/kotlin/examples/example-either-27.kt
|
lukaszkalnik
| 427,116,886
| true
|
{"Kotlin": 1928099, "SCSS": 99659, "JavaScript": 83153, "HTML": 25306, "Java": 7691, "Ruby": 917, "Shell": 98}
|
// This file was automatically generated from Either.kt by Knit tool. Do not edit.
package arrow.core.examples.exampleEither27
import arrow.core.Either.Right
import arrow.core.leftIfNull
fun main() {
val value =
//sampleStart
Right(12).leftIfNull({ -1 })
//sampleEnd
println(value)
}
| 0
|
Kotlin
|
0
| 1
|
73fa3847df1f04e634a02bba527917389b59d7df
| 298
|
arrow
|
Apache License 2.0
|
src/main/kotlin/endredeak/aoc2022/Day04.kt
|
edeak
| 571,891,076
| false
|
{"Kotlin": 44975}
|
package endredeak.aoc2022
fun main() {
solve("Camp Cleanup") {
infix fun Pair<Int, Int>.fullyContains(other: Pair<Int, Int>) =
(this.first <= other.first && other.second <= this.second) ||
other.first <= this.first && this.second <= other.second
infix fun Pair<Int, Int>.overlaps(other: Pair<Int, Int>) =
(this.first <= other.first && other.first <= this.second) ||
(other.first <= this.first && this.first <= other.second)
val input = lines
.map { it.split(",", "-") }
.map { it.map(String::toInt) }
.map { (a, b, c, d) -> (a to b) to (c to d) }
part1(471) { input.count { (l, r) -> l fullyContains r } }
part2(888) { input.count { (l, r) -> l overlaps r } }
}
}
| 0
|
Kotlin
|
0
| 0
|
e0b95e35c98b15d2b479b28f8548d8c8ac457e3a
| 816
|
AdventOfCode2022
|
Do What The F*ck You Want To Public License
|
app/src/main/java/com/jorgedguezm/elections/presentation/common/Constants.kt
|
Narsuf
| 52,900,182
| false
| null |
package com.jorgedguezm.elections.presentation.common
object Constants {
const val KEY_ELECTION = "election"
const val KEY_CONGRESS_ELECTION = "congress.election"
const val KEY_SENATE_ELECTION = "senate.election"
const val KEY_CONGRESS = "Congreso"
const val KEY_SENATE = "Senado"
}
| 0
|
Kotlin
|
0
| 1
|
4373973217dc8a5f75cc07bf5a48fd781e4820fc
| 305
|
Elections
|
Apache License 2.0
|
sampleapp/src/main/java/com/kirkbushman/sampleapp/models/TicketModel.kt
|
KirkBushman
| 200,888,940
| false
| null |
package com.kirkbushman.sampleapp.models
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import com.airbnb.epoxy.EpoxyAttribute
import com.airbnb.epoxy.EpoxyModelClass
import com.airbnb.epoxy.EpoxyModelWithHolder
import com.kirkbushman.sampleapp.R
import com.kirkbushman.sampleapp.models.base.KotlinHolder
import com.kirkbushman.zammad.models.Ticket
@EpoxyModelClass
abstract class TicketModel : EpoxyModelWithHolder<TicketHolder>() {
@EpoxyAttribute
lateinit var ticket: Ticket
@EpoxyAttribute(EpoxyAttribute.Option.DoNotHash)
lateinit var clickListener: View.OnClickListener
@EpoxyAttribute(EpoxyAttribute.Option.DoNotHash)
lateinit var articleListener: View.OnClickListener
@EpoxyAttribute(EpoxyAttribute.Option.DoNotHash)
lateinit var updateListener: View.OnClickListener
@EpoxyAttribute(EpoxyAttribute.Option.DoNotHash)
lateinit var deleteListener: View.OnClickListener
override fun getDefaultLayout(): Int {
return R.layout.item_ticket
}
override fun bind(holder: TicketHolder) {
holder.ticketTitle.text = ticket.title
holder.ticketId.text = ticket.id.toString()
holder.ticketCreated.text = ticket.createdAt
holder.ticketArticle.text = ticket.articleCount.toString().plus(" articles")
holder.container.setOnClickListener(clickListener)
holder.ticketArticle.setOnClickListener(articleListener)
holder.ticketUpdate.setOnClickListener(updateListener)
holder.ticketDelete.setOnClickListener(deleteListener)
}
override fun unbind(holder: TicketHolder) {
holder.container.setOnClickListener(null)
holder.ticketArticle.setOnClickListener(null)
holder.ticketUpdate.setOnClickListener(null)
holder.ticketDelete.setOnClickListener(null)
}
}
class TicketHolder : KotlinHolder() {
val container by bind<LinearLayout>(R.id.container)
val ticketTitle by bind<TextView>(R.id.ticket_title)
val ticketId by bind<TextView>(R.id.ticket_id)
val ticketCreated by bind<TextView>(R.id.ticket_created)
val ticketArticle by bind<Button>(R.id.ticket_articles)
val ticketUpdate by bind<Button>(R.id.ticket_update)
val ticketDelete by bind<Button>(R.id.ticket_delete)
}
| 2
|
Kotlin
|
5
| 34
|
92e27d4e920083da95dfaadae3963a2f211c392b
| 2,328
|
zammad-android
|
MIT License
|
thelema-studio/src/commonMain/kotlin/app/thelema/studio/tool/NameDialog.kt
|
zeganstyl
| 275,550,896
| false
| null |
package app.thelema.studio
import app.thelema.input.KEY
import app.thelema.ui.*
class NameWindow: Window("Name") {
val nameText = TextField().apply {
hintText = "Name..."
}
var nameSetter: (name: String) -> Unit = {}
val acceptButton = TextButton("Accept") {
onClick {
applyNameAndHide()
}
}
init {
content.add(nameText).growX().newRow()
content.add(acceptButton)
isResizable = true
nameText.addListener(object : InputListener {
override fun keyDown(event: InputEvent, keycode: Int): Boolean {
when (keycode) {
KEY.ENTER -> applyNameAndHide()
}
return super.keyDown(event, keycode)
}
})
closeButton.onClick {
nameSetter = {}
hide()
}
pack()
}
private fun applyNameAndHide() {
nameSetter(nameText.text)
nameSetter = {}
hide()
}
fun show(name: String? = null, block: (name: String) -> Unit) {
nameText.text = name ?: ""
nameSetter = block
show(Studio.hud)
}
}
| 3
|
Kotlin
|
5
| 61
|
8e2943b6d2de3376ce338025b58ff31c14097caf
| 1,177
|
thelema-engine
|
Apache License 2.0
|
app/src/main/java/com/elhady/movies/core/domain/usecase/tvdetails/GetTvShowsByPersonUseCase.kt
|
islamelhady
| 301,591,032
| false
|
{"Kotlin": 584524}
|
package com.elhady.movies.core.domain.usecase.tvdetails
import com.elhady.movies.core.domain.entities.TvShowEntity
import com.elhady.movies.core.domain.repository.MovieRepository
import javax.inject.Inject
class GetTvShowsByPersonUseCase @Inject constructor(
private val movieRepository: MovieRepository,
) {
suspend operator fun invoke(personId:Int): List<TvShowEntity> {
return movieRepository.getTvShowsByPerson(personId)
}
}
| 1
|
Kotlin
|
0
| 0
|
d9b6c3f241b5de6c334fa2dcc9f2653de3c04762
| 450
|
movie-night-v2
|
Apache License 2.0
|
src/main/kotlin/com/freshtuna/tunarest/util/queryBuilder/QueryBuilder.kt
|
FRESH-TUNA
| 704,869,969
| false
|
{"Kotlin": 13897}
|
package com.freshtuna.tunarest.util.queryBuilder
import com.freshtuna.tunarest.domain.Variables
class QueryBuilder private constructor() {
companion object {
fun builder(): QueryBuilder {
return QueryBuilder()
}
}
private var variables = Variables()
fun addQuery(name: String, value: String): QueryBuilder {
this.variables.add(name, value)
return this
}
fun build(): String {
val parseResult = StringBuilder("?")
for (name in variables.findAllNames()) {
for(token in variables.findAllValuesBy(name))
parseResult.append("$name=$token&")
}
parseResult.deleteCharAt(parseResult.length-1)
return parseResult.toString()
}
}
| 0
|
Kotlin
|
0
| 0
|
c464fc8951825aed32755deb8a0becdad8b1a76a
| 766
|
restool
|
MIT License
|
generateKeyboard.kt
|
zeitlinger
| 615,489,554
| false
|
{"Kotlin": 18243, "C": 176}
|
import org.hjson.JsonValue
import java.io.File
import java.io.FileReader
fun main() {
val config = File("/home/gregor/source/keyboard/README.md")
val layoutTemplate = File("/home/gregor/source/keyboard/layout.h")
val comboFile = File("/home/gregor/source/mini-ryoku/qmk/combos.def")
val layoutFile = File("/home/gregor/source/mini-ryoku/qmk/layout.h")
val features = setOf<Feature>()
run(config, comboFile, layoutFile, layoutTemplate, features)
}
const val mainLayerTemplate =
"\t[%d] = LAYOUT_split_3x5_2(" +
"%s, %s, %s, %s, KC_NO, KC_NO, %s, %s, %s, %s, " +
"%s, %s, %s, %s, KC_NO, KC_NO, %s, %s, %s, %s, " +
"%s, %s, %s, %s, KC_NO, KC_NO, %s, %s, %s, %s, " +
"%s, %s, %s, %s),"
const val keyboardRows = 3
const val thumbRows = 1
enum class Feature {
ModCombo
}
class QmkTranslator(val symbols: Symbols, private val layerNames: Map<String, Int>) {
private val map: Map<String, String>
init {
val files = mapOf(
"/home/gregor/qmk_firmware/data/constants/keycodes/keycodes_0.0.1_basic.hjson" to "keycodes",
"/home/gregor/qmk_firmware/data/constants/keycodes/extras/keycodes_us_0.0.1.hjson" to "aliases",
)
map = files.flatMap { file ->
val aliases = JsonValue.readHjson(FileReader(file.key))
.asObject().get(file.value).asObject()
aliases.mapNotNull {
val o = it.value.asObject()
val key = o.get("key").asString()
key.takeUnless { it.contains("KP_") || it.contains("NONUS_") }?.let { o.get("label").asString() to it }
}
}.toMap()
}
fun toQmk(key: String): String = key
.let { symbols.replace(it) }
.let { translatedKey -> map.getOrDefault(translatedKey.replaceFirstChar { it.titlecase() }, translatedKey) }
.let {
when {
getSubstitutionCombo(it) != null -> it
else -> assertQmk(it)
}
}
fun mustTranslateLayer(key: String): Int = layerNames.getValue(key)
}
data class Hand(
val name: String,
val columns: Int,
val baseLayerRowSkip: Int,
val skip: Int,
val translateComboIndex: (Int) -> Int
) {
fun applies(rows: Rows): Boolean {
if (this.columns != rows[0].size) {
return false
}
val half = this.columns / 2
val halves = listOf(0, half).map { drop ->
rows.map { it.drop(drop).take(half) }.flatten()
}
val isFull = halves
.any {
val comboTriggers = it.filter { it == comboTrigger }.size
val used = it.filter { it != blocked }.size
used > 0 && comboTriggers == 0
}
return this.isFull == isFull
}
val isRight = this.name.startsWith("right")
val isThumb = this.name.contains("thumb")
private val isFull = this.name.contains("both")
val comboColumns = if (isFull) this.columns else this.columns / 2
}
val hands = listOf(
Hand("left", 8, 0, 0) { i -> i + 3 },
Hand("right", 8, 0, 4) { i -> 8 - i },
Hand("both", 8, 0, 0) { i -> i },
Hand("left thumb", 4, 3, 0) { i -> i + 1 },
Hand("right thumb", 4, 3, 2) { i -> 4 - i },
Hand("both thumbs", 4, 3, 0) { i -> i },
)
enum class Modifier {
Alt, Shift, Ctrl
}
data class ModTrigger(val mods: List<Modifier>, val triggers: List<Int>, val command: String, val name: String?)
private const val qmkNo = "KC_NO"
typealias Rows = List<List<String>>
data class Layer(
val name: String,
val baseRows: Rows,
val combos: List<Rows>,
val number: Int,
val comboTrigger: String?,
)
val qmkPrefixes = setOf(
"KC_",
"LT(",
"MO(",
"LCTL(",
"RCS(",
"RALT(",
"LALT(",
"LSFT(",
"LALT_T(",
"LCTL_T(",
"RCTL_T(",
"RALT_T(",
"LSFT_T(",
"RSFT_T(",
)
fun assertQmk(key: String): String {
return when {
key == blocked || key == comboTrigger || qmkPrefixes.any { key.startsWith(it) } -> key
else -> throw IllegalStateException("key not translated $key")
}
}
val specialLayers = listOf("FnMou", "Sym", "Media", "Alt", "Ctrl")
data class Generator(
val layers: List<Layer>,
) {
fun generateBase(): String {
return layers.mapIndexed { index, layer ->
val def = layer.baseRows.flatten()
val qmk = def
.map { if (it == blocked) qmkNo else it }
mainLayerTemplate.format(*listOf(index).plus<Any>(qmk).toTypedArray())
}.joinToString("\n")
}
}
private fun run(config: File, comboFile: File, layoutFile: File, layoutTemplate: File, features: Set<Feature>) {
val tables = readTables(config)
val symbols = Symbols(tables.getMappingTable("Symbol"))
val thumbs = tables.get("Thumb").drop(1) // Header
.groupBy { it[0] }
.toMap()
val layerContent = tables.get("Layer")
val layerNames = layerContent.drop(1).map { it[0] }.toSet().mapIndexed { index, s -> s to index }.toMap()
val modifierTypes = tables.get("Modifiers")
.drop(1)
.associateBy { it[0] }
.mapValues { it.value.drop(1) }
val translator = QmkTranslator(symbols, layerNames)
val layers = readLayers(layerContent, thumbs, translator, modifierTypes)
val layerNumbers = layers.joinToString("\n") { "#define _${it.name.uppercase()} ${it.number}" }
// printMissingAndUnexpected(translator, layers, symbols)
val generator = Generator(layers)
val combos = generateCombos(generator.layers, features).map { combo ->
combo.type.template.format(
combo.name.padEnd(20),
combo.result.padEnd(50),
combo.triggers
.joinToString(", ")
)
}.sorted()
val generationNote =
"file is generated from ${config.name} using https://github.com/zeitlinger/keyboard/blob/main/generateKeyboard.kt"
val base = layoutTemplate.readText()
.replace("\${generationNote}", generationNote)
.replace("\${layers}", generator.generateBase())
.replace("\${layerNumbers}", layerNumbers)
layoutFile.writeText(base)
comboFile.writeText((listOf("// $generationNote") + combos).joinToString("\n"))
}
//
//private fun printMissingAndUnexpected(
// translator: QmkTranslator,
// layers: List<Layer>,
// symbols: Symbols
//) {
// val gotKeys = thumbs.map { translator.toQmk(it.baseKey) } +
// layers.map { it.baseRows.flatten() + it.combos.flatten().flatten() }.flatten()
// .filterNot { it == blocked || it == comboTrigger }
//
// val want =
// symbols.mapping.values +
// (CharRange('!', '~')
// .map { it.toString() }
// .filter { it.lowercase() == it }
// .map { translator.toQmk(it) }) +
// (1..12).map { "KC_F$it" }
// .toSet()
//
// val missing = (want - gotKeys.toSet()).map { translator.toLabel(it) }
// val unexpected = (gotKeys.toSet() - want.toSet()).map { translator.toLabel(it) }
// println("expected: ${want.size}")
// println("missing: $missing")
// println("unexpected: $unexpected")
// val dups = gotKeys.filter { k -> gotKeys.filter { k == it }.size > 1 }
// .map { translator.toLabel(it) }.distinct()
// println("duplicates: $dups")
//}
fun readLayers(
layerContent: Table,
thumbs: Map<String, List<List<String>>>,
translator: QmkTranslator,
modifierTypes: Map<String, List<String>>
): List<Layer> {
val comboLayerTrigger = mutableMapOf<Int, String>()
val layerByName = layerContent.drop(1) // Header
.groupBy { it[0] }
.toMap()
return layerByName.entries.mapIndexed { layerNumber, (layerName, content) ->
val data = translateTable(content, translator, comboLayerTrigger)
val base = data.take(keyboardRows)
.mapIndexed { row, def ->
if (row == 1) {
addModTab(def, modifierTypes.getValue(layerName))
} else {
def
}
}
val combos = data.drop(keyboardRows).chunked(keyboardRows)
val thumbData = translateTable(thumbs[layerName] ?: listOf(List(5) { " " }), translator, comboLayerTrigger)
// val baseThumb = listOf(thumbData.getOrElse(0) { _ -> listOf(" ").repeat(4) })
val baseThumb = listOf(thumbData[0])
val comboThumb = thumbData.drop(thumbRows).chunked(thumbRows)
val baseRows = (base + baseThumb)
Layer(
layerName, baseRows,
combos + comboThumb,
layerNumber,
comboLayerTrigger[layerNumber]
)
}
}
private fun translateCommand(
command: String,
comboLayerTrigger: MutableMap<Int, String>,
translator: QmkTranslator
): String = when {
translator.symbols.mapping.containsKey(command) -> {
command // is translated later
}
command.startsWith("ComboLayer:") -> {
val parts = command.split(" ")
val trigger = translator.mustTranslateLayer(parts[0].split(":")[1])
val key = translateCommand(parts[1], comboLayerTrigger, translator)
comboLayerTrigger[trigger] = key
key
}
command.contains("+") && command.length > 1 -> {
val parts = command.split("+")
"LT(${translator.mustTranslateLayer(parts[1])},${translator.toQmk(parts[0])})"
}
command.contains("-") && command.length > 1 -> {
val parts = command.split("-")
val modifier = parts[0]
val key = translator.toQmk(parts[1])
when (modifier) {
"A" -> "LALT(${key})"
"C" -> "LCTL(${key})"
"S" -> "LSFT(${key})"
"CS" -> "RCS(${key})"
else -> throw IllegalStateException("unknown modifier $modifier")
}
}
command.isNotBlank() && command[0].isUpperCase() -> {
"MO(${translator.mustTranslateLayer(command)})"
}
else -> {
command
}
}
fun addModTab(row: List<String>, modifierTypes: List<String>): List<String> {
val left = modifierTypes[0] == "HomeRow"
val right = modifierTypes[1] == "HomeRow"
return row.mapIndexed { index, key ->
when {
"(" in key -> {
key
}
index < 4 && left -> {
if (key == blocked) {
when (index) {
1 -> "KC_LALT"
2 -> "KC_LCTL"
3 -> "KC_LSFT"
else -> key
}
} else {
when (index) {
1 -> "LALT_T($key)"
2 -> "LCTL_T($key)"
3 -> "LSFT_T($key)"
else -> key
}
}
}
index >= 4 && right -> {
if (key == blocked) {
when (index) {
4 -> "KC_RSFT"
5 -> "KC_RCTL"
6 -> "KC_RALT"
else -> key
}
} else {
when (index) {
4 -> "RSFT_T($key)"
5 -> "RCTL_T($key)"
6 -> "LALT_T($key)"
else -> key
}
}
}
else -> key
}
}
}
private fun translateTable(
content: List<List<String>>,
translator: QmkTranslator,
comboLayerTrigger: MutableMap<Int, String>
) = content.map { it.drop(1) }
.map { row ->
row
.map { translateCommand(it, comboLayerTrigger, translator) }
.map { translator.toQmk(it) }
}
| 0
|
Kotlin
|
0
| 1
|
f8f6968bb4689eedbee9953e6e2070b174cc4daf
| 11,901
|
keyboard
|
MIT License
|
src/main/java/space/gtimpact/virtual_world/addon/visual_prospecting/cache/CacheModels.kt
|
GT-IMPACT
| 600,141,768
| false
|
{"Kotlin": 151783, "Java": 3883}
|
package space.gtimpact.virtual_world.addon.visual_prospecting.cache
import space.gtimpact.virtual_world.api.VirtualOreVein
data class CacheOreVeinList(
val layer: Int, //byte (0..1)
val veins: List<CacheOreVein>
)
data class CacheOreVein(
val veinId: Int, //short
val x: Int,
val z: Int,
val chunks: List<CacheOreVeinChunk>,
) {
var dimension: Int = 0
var vein: VirtualOreVein? = null
}
data class CacheOreVeinChunk(
val x: Int,
val z: Int,
val size: Int, //byte (percent 0..100)
)
| 0
|
Kotlin
|
0
| 0
|
fe0e517c6ab87b6dacfe8b744e45978b09863df9
| 530
|
VirtualWorld
|
MIT License
|
app/src/main/java/com/ojhdtapp/action/logic/dao/ActionDao.kt
|
ojhdt
| 425,239,290
| false
|
{"Kotlin": 414237}
|
package com.ojhdtapp.action.logic.dao
import android.hardware.lights.LightState
import androidx.lifecycle.LiveData
import androidx.room.*
import com.ojhdtapp.action.logic.model.Action
@Dao
interface ActionDao {
@Insert
fun insertAction(action: Action): Long
@Delete
fun deleteAction(action: Action)
@Update
fun updateAction(newAction: Action)
@Query("DELETE FROM action_table")
fun deleteAll()
@Query("SELECT * FROM `action_table`")
fun loadAllAction(): List<Action>
@Query("SELECT * FROM `action_table` WHERE history IS NOT NULL AND history != ''")
fun loadActivatedAction(): List<Action>
@Query("SELECT * FROM `action_table` WHERE isActivating = 1")
fun loadAllActivatingAction(): List<Action>
@Query("SELECT * FROM `action_table`")
fun loadAllActionLive(): LiveData<List<Action>>
@Query("SELECT * FROM `action_table` WHERE history IS NOT NULL AND history != ''")
fun loadActivatedActionLive(): LiveData<List<Action>>
@Query("SELECT * FROM `action_table` WHERE isActivating = 1")
fun loadAllActivatingActionLive(): LiveData<List<Action>>
@Query("DELETE FROM `action_table` WHERE id = :id")
fun deleteActionById(id: Long): Int
@Query("SELECT * FROM action_table WHERE isActivating = 0 AND (:currentTime - lastTriggered) >= 43200000 AND activityStateTrigger = :activityStateTrigger AND lightStateTrigger = :lightStateTrigger AND locationStateTrigger =:locationStateTrigger AND timeStateTrigger = :timeStateTrigger AND weatherStateTrigger = :weatherStateTrigger ORDER BY weight DESC")
fun loadAvailableActionByConditions(
activityStateTrigger: Int = -1,
lightStateTrigger: Int = -1,
locationStateTrigger: Int = -1,
timeStateTrigger: Int = -1,
weatherStateTrigger: Int = -1,
currentTime: Long = System.currentTimeMillis()
): List<Action>
@Query("SELECT 1 FROM action_table WHERE objectId = :objectId LIMIT 1")
fun isStored(objectId: String): Boolean
}
| 0
|
Kotlin
|
1
| 1
|
4fad043c6e30bf3392f5a7df75c02515db9f712d
| 2,021
|
Action
|
MIT License
|
bz/bz_xc/src/main/java/com/atmk/xc/XCApplication.kt
|
YangJian007
| 527,470,200
| false
|
{"Kotlin": 650668, "Java": 293068}
|
package com.atmk.xc
import com.atmk.base.BzBaseModuleInit
import com.hjq.base.application.ApplicationProvider
import com.hjq.base.application.ModuleInitDelegate
/**
* @author 杨剑
* @fileName
* @date 2022-08-24
* @describe
* @changeUser
* @changTime
*/
class XCApplication : ApplicationProvider() {
init {
ModuleInitDelegate.register(BzBaseModuleInit())
}
}
| 1
|
Kotlin
|
3
| 8
|
19e65fd5d22ebc1f5faded3d182fad25c9aa8627
| 382
|
AtmkArch
|
Apache License 2.0
|
modules/model/model/src/main/java/com/project/model/Sponsorship.kt
|
dev-darck
| 499,210,154
| false
| null |
package com.project.model
import com.google.gson.annotations.SerializedName
data class Sponsorship(
@SerializedName("impression_urls")
val impressionUrls: List<String>,
@SerializedName("sponsor")
val sponsor: Sponsor,
@SerializedName("tagline")
val tagline: String,
@SerializedName("tagline_url")
val taglineUrl: String
)
| 1
|
Kotlin
|
0
| 0
|
d6b0e8f79a8b229f7cec3907547bd05b01af606d
| 356
|
PicPicker
|
Apache License 2.0
|
Application-Challenge/项目11-160215-HandyInstruction/AndroidApp/app/src/main/java/com/qingkouwei/handyinstruction/av/ui/widget/MixedCallVideoLayout.kt
|
qingkouwei
| 520,060,307
| false
|
{"Markdown": 4, "Git Attributes": 1, "Text": 2, "Ignore List": 5, "XML": 260, "Java Properties": 2, "Gradle": 3, "Shell": 1, "Batchfile": 1, "Proguard": 1, "Java": 299, "Kotlin": 11, "Makefile": 2, "JSON": 1}
|
package com.qingkouwei.handyinstruction.av.ui.widget
import android.app.Activity
import android.graphics.Bitmap
import android.opengl.GLSurfaceView
import android.os.Handler
import android.util.AttributeSet
import android.util.Log
import android.view.SurfaceView
import android.view.View
import android.widget.FrameLayout
import android.widget.Toast
import com.hyphenate.chat.EMClient
import com.hyphenate.easecallkit.EaseCallKit
import com.hyphenate.easecallkit.EaseCallKit.EaseCallError.RTC_ERROR
import com.hyphenate.easecallkit.base.EaseCallEndReason.EaseCallEndReasonHangup
import com.hyphenate.easecallkit.base.EaseCallFloatWindow
import com.hyphenate.easecallkit.base.EaseCallKitTokenCallback
import com.hyphenate.easecallkit.base.EaseCallType
import com.hyphenate.easecallkit.base.EaseCallType.SINGLE_VIDEO_CALL
import com.hyphenate.easecallkit.base.EaseCallType.SINGLE_VOICE_CALL
import com.hyphenate.easecallkit.base.EaseUserAccount
import com.hyphenate.util.EMLog
import com.qingkouwei.handyinstruction.R
import com.qingkouwei.handyinstruction.R.layout
import com.qingkouwei.handyinstruction.av.bean.Size
import com.qingkouwei.handyinstruction.av.util.AndroidUtils
import com.qingkouwei.handyinstruction.av.util.Resource.Companion.getString
import com.qingkouwei.handyinstruction.av.video.DrawVideoSource
import com.qingkouwei.handyinstruction.av.video.MixVideoHelper
import com.qingkouwei.handyinstruction.av.video.VideoSourceMgr
import com.qingkouwei.handyinstruction.common.utils.DemoLog
import com.qingkouwei.handyinstruction.common.utils.ToastUtils
import com.wonxing.adapter.holder.ColorPickerHoder.ColorPickerListener
import io.agora.rtc.Constants
import io.agora.rtc.IRtcEngineEventHandler
import io.agora.rtc.RtcEngine
import io.agora.rtc.gl.EglBase14.Context
import io.agora.rtc.gl.RendererCommon
import io.agora.rtc.mediaio.IVideoSource
import io.agora.rtc.mediaio.MediaIO
import io.agora.rtc.models.UserInfo
import io.agora.rtc.video.VideoCanvas
import io.agora.rtc.video.VideoEncoderConfiguration
import io.agora.rtc.video.VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_15
import io.agora.rtc.video.VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_ADAPTIVE
import kotlinx.android.synthetic.main.mixed_call_layout.view.drawView
import kotlinx.android.synthetic.main.mixed_call_layout.view.lscFinish
import kotlinx.android.synthetic.main.mixed_call_layout.view.lslTime
import kotlinx.android.synthetic.main.mixed_call_layout.view.menu
import kotlinx.android.synthetic.main.mixed_call_layout.view.pickColorLayout
import java.util.HashMap
class MixedCallVideoLayout : FrameLayout {
protected val TAG = javaClass.simpleName + "Log"
private val uIdMap: MutableMap<Int, EaseUserAccount> = HashMap()
private var mRootView: View? =null
private var mChannelName: String? = null
private var mPeerUserId: String? = null
private var mVideoSource: IVideoSource? = null
private var isMicEnable: Boolean = true
private var isFlashlightOpen: Boolean = false
private var mGLSurfaceView: GLSurfaceView? = null
private var mMixVideoHelper: MixVideoHelper? = null
private var mRemoteRender: MixVideoHelper.YuvImageRenderer? = null
private var mRender: MixVideoHelper.YuvImageRenderer? = null
private var mHandler: Handler? = null
private var mDrawVideoSource: DrawVideoSource? = null
private var drawingViewWidth: Int = 0
private var drawingViewHeight: Int = 0
private var mRtcEngine: RtcEngine? = null
private var agoraAppId: String? = null
var listener = EaseCallKit.getInstance().callListener
private var isCameraFront: Boolean = false;
private var remoteUId = 0
protected var mCallType: EaseCallType? = null
private var mCallback: Callback? = null
private var mActivity: Activity? = null
private val mRtcEventHandler: IRtcEngineEventHandler = object : IRtcEngineEventHandler() {
override fun onError(err: Int) {
super.onError(err)
DemoLog.d(
TAG,
"IRtcEngineEventHandler onError:$err"
)
if (listener != null) {
listener.onCallError(RTC_ERROR, err, "rtc error")
}
}
override fun onJoinChannelSuccess(channel: String, uid: Int, elapsed: Int) {
DemoLog.d(TAG, "onJoinChannelSuccess channel:$channel uid$uid")
mActivity?.runOnUiThread(Runnable {
DemoLog.i(TAG, "onJoinChannelSuccess callback = " + mCallback)
mCallback?.onJoinChannelSuccess(channel, uid, elapsed)
})
}
override fun onRejoinChannelSuccess(channel: String, uid: Int, elapsed: Int) {
super.onRejoinChannelSuccess(channel, uid, elapsed)
}
override fun onLeaveChannel(stats: RtcStats) {
super.onLeaveChannel(stats)
}
override fun onLocalUserRegistered(uid: Int, userAccount: String) {
super.onLocalUserRegistered(uid, userAccount)
}
override fun onUserInfoUpdated(uid: Int, userInfo: UserInfo) {
super.onUserInfoUpdated(uid, userInfo)
}
override fun onUserJoined(uid: Int, elapsed: Int) {
super.onUserJoined(uid, elapsed)
mActivity?.runOnUiThread(Runnable { //检测到对方进来
mCallback?.makeOngoingStatus()
mCallback?.setUserJoinChannelInfo(null, uid)
})
}
override fun onUserOffline(uid: Int, reason: Int) {
mActivity?.runOnUiThread(Runnable {
//检测到对方退出 自己退出
mCallback?.exitChannel()
if (uIdMap != null) {
uIdMap.remove(uid)
}
if (listener != null) {
//对方挂断
val time: Long = mCallback?.getChronometerSeconds()!!
listener.onEndCallWithReason(mCallType, mChannelName, EaseCallEndReasonHangup, time * 1000)
}
})
}
override fun onFirstRemoteVideoDecoded(uid: Int, width: Int, height: Int, elapsed: Int) {
mActivity?.runOnUiThread(Runnable {
remoteUId = uid
addNewUser(uid, width, height)
})
}
@Deprecated("") override fun onFirstRemoteAudioFrame(uid: Int, elapsed: Int) {
mActivity?.runOnUiThread(Runnable {
remoteUId = uid
mCallback?.onFirstRemoteAudioFrame(uid, elapsed)
})
}
override fun onRemoteVideoStateChanged(uid: Int, state: Int, reason: Int, elapsed: Int) {
mActivity?.runOnUiThread(Runnable {
//对端停止视频
if (uid == remoteUId) {
//远端转换为视频流
if (state == Constants.REMOTE_VIDEO_STATE_STOPPED || state == Constants.REMOTE_VIDEO_STATE_REASON_REMOTE_MUTED) {
mCallType = SINGLE_VOICE_CALL
EaseCallKit.getInstance().callType = SINGLE_VOICE_CALL
EaseCallFloatWindow.getInstance(mActivity?.getApplicationContext()).callType =
mCallType
mCallback?.onRemoteVideoStateChanged(uid, state, reason, elapsed)
if (mRtcEngine != null) {
mRtcEngine!!.muteLocalVideoStream(true)
mRtcEngine!!.enableVideo()
}
}
}
})
}
}
constructor(context: android.content.Context) : super(context) {
init(context)
}
constructor(context: android.content.Context, attributeSet: AttributeSet) : super(
context,
attributeSet
) {
init(context)
}
constructor(context: android.content.Context, attributeSet: AttributeSet, defStyleAttr: Int) : super(
context,
attributeSet,
defStyleAttr
) {
init(context)
}
constructor(
context: android.content.Context,
attributeSet: AttributeSet,
defStyleAttr: Int,
defStyleRes: Int
) : super(context, attributeSet, defStyleAttr, defStyleRes) {
init(context)
}
private fun init(context: android.content.Context){
initView(context)
}
fun setupRtcEngine(channelName: String, peerUserId: String, callType: EaseCallType) {
DemoLog.i(TAG, "setupRtcEngine")
mCallType = callType
mChannelName = channelName
mPeerUserId = peerUserId
initializeEngine()
mHandler = Handler()
if(callType == SINGLE_VIDEO_CALL){
mMixVideoHelper = MixVideoHelper.setView(this.mGLSurfaceView, Runnable {
mHandler!!.post {
VideoSourceMgr.getInstance().initEGLContext(
mMixVideoHelper!!.eglBaseContext as Context?, Size(
VideoEncoderConfiguration.VD_1280x720.width,
VideoEncoderConfiguration.VD_1280x720.height
), Size(AndroidUtils.getScreenHeight(context), AndroidUtils.getScreenWidth(context))
)
mVideoSource = VideoSourceMgr.getInstance().mainVideoSource
mRender = mMixVideoHelper!!.createGuiRenderer(
0, 0, 100, 100,
RendererCommon.ScalingType.SCALE_ASPECT_FILL, false
)
mRender!!.setBufferType(MediaIO.BufferType.TEXTURE)
mRender!!.setPixelFormat(MediaIO.PixelFormat.TEXTURE_OES)
mRtcEngine!!.setVideoSource(mVideoSource)
mRtcEngine!!.setLocalVideoRenderer(mRender)
preview(true, null, 0)
setupVideoConfig(Constants.CLIENT_ROLE_BROADCASTER)
joinChannel(mChannelName!!, 0)
}
})
mGLSurfaceView!!.visibility = View.VISIBLE
}else{
joinChannel(mChannelName!!, 0)
}
}
fun updateUI(){
DemoLog.i(TAG, "updateUI")
if(mCallType == SINGLE_VIDEO_CALL){
menu.visibility = View.VISIBLE
lscFinish.visibility = View.VISIBLE
lslTime.visibility = View.VISIBLE
lslTime.start()
}
}
private fun preview(start: Boolean, view: SurfaceView?, uid: Int) {
if (start) {
mRtcEngine!!.setupLocalVideo(VideoCanvas(view, VideoCanvas.RENDER_MODE_HIDDEN, uid))
mRtcEngine!!.startPreview()
} else {
mRtcEngine!!.stopPreview()
}
}
private fun initView(context: android.content.Context) {
mActivity = context as Activity;
mRootView = inflate(context, layout.mixed_call_layout, this)
mGLSurfaceView = mRootView?.findViewById<View>(R.id.glSurfaceView) as GLSurfaceView
var w = VideoEncoderConfiguration.VD_1280x720.height.toFloat()
var h = VideoEncoderConfiguration.VD_1280x720.width.toFloat()
val ratio = w / h
val screenWidth = AndroidUtils.getScreenWidth(context)
var screenHeight = AndroidUtils.getScreenHeight(context)
val screenRatio = screenWidth / screenHeight;
DemoLog.e(TAG, "ratio = " + ratio + ";screenRatio = " + screenRatio)
if (ratio < screenRatio) {
var width = (screenHeight * ratio).toInt()
DemoLog.e(TAG, "width = " + width)
drawView.layoutParams.width = width
mGLSurfaceView!!.layoutParams.width = width
} else {
var height = (AndroidUtils.getScreenWidth(getContext()).toFloat() / ratio).toInt()
DemoLog.e(TAG, "height = " + height)
drawView.layoutParams.height = height
mGLSurfaceView!!.layoutParams.height = height
}
lscFinish.setOnClickListener {
tryQuit()
}
pickColorLayout.setColorPickerListener(object : ColorPickerListener {
override fun onSelected(color: Int) {
if (!mMixVideoHelper!!.isBlend) {
showToast(R.string.toast_not_support)
return
}
drawView.color = color
pickColorLayout.visibility = View.GONE
}
})
menu.setOnDrawOpenClickListener {
if (!mMixVideoHelper!!.isBlend) {
showToast(R.string.toast_not_support)
return@setOnDrawOpenClickListener
}
menu.openDrawMenu()
drawView.visibility = View.VISIBLE
if (drawingViewWidth != 0 && drawingViewHeight != 0) {
VideoSourceMgr.getInstance().addDrawing(drawingViewWidth, drawingViewHeight);
}
}
menu.setOnDrawCloseClickListener {
if (!mMixVideoHelper!!.isBlend) {
showToast(R.string.toast_not_support)
return@setOnDrawCloseClickListener
}
pickColorLayout.visibility = View.GONE
drawView.visibility = View.GONE
VideoSourceMgr.getInstance().delDrawing()
}
menu.setOnDrawClearClickListener() {
if (!mMixVideoHelper!!.isBlend) {
showToast(R.string.toast_not_support)
return@setOnDrawClearClickListener
}
drawView.clear()
}
menu.setOnDrawEraserClickListener { v ->
if (!mMixVideoHelper!!.isBlend) {
showToast(R.string.toast_not_support)
return@setOnDrawEraserClickListener
}
if (v.isSelected) {
drawView.setEsaserMode(true)
} else {
drawView.setEsaserMode(false)
}
}
menu.setOnDrawColorClickListener {
if (!mMixVideoHelper!!.isBlend) {
showToast(R.string.toast_not_support)
return@setOnDrawColorClickListener
}
if (pickColorLayout.visibility == View.GONE) {
pickColorLayout.visibility = View.VISIBLE
} else {
pickColorLayout.visibility = View.GONE
}
}
menu.setOnFrameModeListener {
menu.changeFrameMode(mMixVideoHelper!!.isBlend )
mMixVideoHelper!!.isBlend = !mMixVideoHelper!!.isBlend
}
drawView.setmOnDrawCallback(
object : DrawView.OnDrawCallback {
override fun updatePix(bitmap: Bitmap?) {
if (VideoSourceMgr.getInstance().drawVideoSource != null && VideoSourceMgr.getInstance().drawVideoSource.isRunning) {
if (mDrawVideoSource != null) {
mDrawVideoSource?.onVideoFrameBitmap(bitmap)
} else {
mDrawVideoSource = VideoSourceMgr.getInstance().drawVideoSource
mDrawVideoSource?.onVideoFrameBitmap(bitmap)
}
}
}
}
)
drawView.setViewSizeChangeCallback { width, height ->
if (width == 0 || height == 0) {
return@setViewSizeChangeCallback
}
DemoLog.i(TAG, "setViewSizeChangeCallback:" + width + "*" + height);
drawingViewWidth = width
drawingViewHeight = height
VideoSourceMgr.getInstance().addDrawing(width, height)
}
menu.setOnMikeModeListener {
if (isMicEnable) {
mRtcEngine!!.disableAudio()
menu.setMikeStateText(R.string._text_livestudio_menu_mike_open_state)
isMicEnable = false
} else {
mRtcEngine!!.enableAudio()
menu.setMikeStateText(R.string._text_livestudio_menu_mike_close_state)
isMicEnable = true
}
}
menu.setOnCameraModeListener {
VideoSourceMgr.getInstance().cameraVideoSource.switchCamera()
}
menu.setOnFlashlightListener {
if (!mMixVideoHelper!!.isBlend) {
showToast(R.string.toast_not_support)
return@setOnFlashlightListener
}
if (VideoSourceMgr.getInstance().cameraVideoSource.isFacingMode) {
Toast.makeText(getContext(), "前置摄像头无法开启", Toast.LENGTH_SHORT).show()
} else {
if (isFlashlightOpen) {
if (VideoSourceMgr.getInstance().cameraVideoSource.switchFlashlight(false)) {
isFlashlightOpen = false
}
} else {
if (VideoSourceMgr.getInstance().cameraVideoSource.switchFlashlight(true)) {
isFlashlightOpen = true
}
}
}
}
menu.visibility = View.GONE
drawView.visibility = View.GONE
lscFinish.visibility = View.GONE
lslTime.visibility = View.GONE
}
private fun initializeEngine() {
try {
val config = EaseCallKit.getInstance().callKitConfig
if (config != null) {
agoraAppId = config.agoraAppId
}
mRtcEngine = RtcEngine.create(context, agoraAppId, mRtcEventHandler)
//因为有小程序 设置为直播模式 角色设置为主播
mRtcEngine!!.setChannelProfile(Constants.CHANNEL_PROFILE_LIVE_BROADCASTING)
mRtcEngine!!.setClientRole(Constants.CLIENT_ROLE_BROADCASTER)
EaseCallFloatWindow.getInstance().setRtcEngine(
context.applicationContext,
mRtcEngine
)
} catch (e: Exception) {
DemoLog.e(TAG, Log.getStackTraceString(e))
throw RuntimeException(
"""
NEED TO check rtc sdk init fatal error
${Log.getStackTraceString(e)}
""".trimIndent()
)
}
}
private fun setupVideoConfig(cRole: Int) {
if (EaseCallKit.getInstance().callType == SINGLE_VIDEO_CALL) {
mRtcEngine!!.enableVideo()
val videoEncoderConfiguration = VideoEncoderConfiguration(
VideoEncoderConfiguration.VD_840x480,
FRAME_RATE_FPS_15, 610,
ORIENTATION_MODE_ADAPTIVE
)
mRtcEngine!!.setVideoEncoderConfiguration(videoEncoderConfiguration)
mRtcEngine!!.setClientRole(cRole)
isCameraFront = false
} else {
mRtcEngine!!.disableVideo()
}
}
/**
* 加入频道
*/
private fun joinChannel(channelName: String, uuid: Int) {
DemoLog.i(TAG,"joinChannel:" + channelName)
val callKitConfig = EaseCallKit.getInstance().callKitConfig
if (listener != null && callKitConfig != null && callKitConfig.isEnableRTCToken) {
listener.onGenerateToken(
EMClient.getInstance().currentUser,
channelName,
EMClient.getInstance().options.appKey,
object : EaseCallKitTokenCallback {
override fun onSetToken(token: String, uId: Int) {
DemoLog.d(
TAG,
"onSetToken token:$token uid: $uId"
)
//获取到Token uid加入频道
mRtcEngine!!.joinChannel(token, channelName, null, uId)
//自己信息加入uIdMap
uIdMap.put(uId, EaseUserAccount(uId, EMClient.getInstance().currentUser))
}
override fun onGetTokenError(error: Int, errorMsg: String) {
EMLog.e(
TAG,
"onGenerateToken error :$error errorMsg:$errorMsg"
)
//获取Token失败,退出呼叫
mCallback?.exitChannel()
}
})
}
}
private fun addNewUser(uid: Int, width: Int, height: Int) {
DemoLog.e(TAG, "addNewUser")
mRemoteRender = mMixVideoHelper!!.createGuiRenderer(
75,
0,
25,
25,
RendererCommon.ScalingType.SCALE_ASPECT_FILL,
false
)
mRemoteRender!!.setBufferType(MediaIO.BufferType.BYTE_ARRAY)
mRemoteRender!!.setPixelFormat(MediaIO.PixelFormat.I420)
mRtcEngine!!.setRemoteVideoRenderer(uid, mRemoteRender)
}
/**
* 离开频道
*/
fun leaveChannel() {
// 离开当前频道。
if (mRtcEngine != null) {
mRtcEngine!!.leaveChannel()
}
}
private fun tryQuit() {
mCallback!!.exitChannelDisplay()
}
fun isCameraFront(): Boolean {
return isCameraFront
}
fun getRtcEngine(): RtcEngine{
return mRtcEngine!!;
}
protected fun showToast(resId: Int) {
showToast(getString(resId))
}
protected fun showToast(msg: String) {
if (!mActivity!!.isFinishing) {
ToastUtils.showToast(msg, 1000)
}
}
fun release(){
VideoSourceMgr.getInstance().destroy()
}
fun setCallback(callback: Callback){
this.mCallback = callback
}
interface Callback{
fun exitChannel()
fun onJoinChannelSuccess(channel: String, uid: Int, elapsed: Int)
fun makeOngoingStatus()
fun setUserJoinChannelInfo(userName: String?, uId: Int)
fun onFirstRemoteAudioFrame(uid: Int, elapsed: Int)
fun onRemoteVideoStateChanged(uid: Int, state: Int, reason: Int, elapsed: Int)
fun getChronometerSeconds(): Long
fun exitChannelDisplay()
}
}
| 1
| null |
1
| 1
|
e2d691e137999a2b2f5d3ceaab409b76d8431266
| 19,104
|
RTE-2022-Innovation-Challenge
|
MIT License
|
library/src/main/java/com/herry/libs/nodeview/model/NodePosition.kt
|
HerryPark
| 273,154,769
| false
|
{"Kotlin": 1362527, "Java": 602}
|
package com.herry.libs.nodeview.model
@Suppress("unused")
class NodePosition(internal val positions: IntArray) {
companion object {
const val NO_POSITION = -1
/**
* Creates the NodePosition with relative position
*/
internal fun compose(position: Int, relative: NodePosition?): NodePosition {
if (relative != null) {
val relativePosition = IntArray(relative.positions.size + 1)
relativePosition[0] = position
for (index in 1..relative.positions.size) {
relativePosition[index] = relative.positions[index - 1]
}
return NodePosition(relativePosition)
}
return NodePosition(intArrayOf(position))
}
}
fun getViewPosition(): Int {
return positions.sum()
}
fun getPosition(): Int {
if (positions.isNotEmpty()) {
return positions[positions.size - 1]
}
return NO_POSITION
}
fun getParentPosition(): NodePosition? {
if (positions.size > 1) {
val parentPositions = IntArray(positions.size - 1)
for (parentPosition in parentPositions.indices) {
parentPositions[parentPosition] = positions[parentPosition]
}
return NodePosition(parentPositions)
}
return null
}
override fun toString(): String {
val sb = StringBuilder()
for (position in positions) {
sb.append("[$position]")
}
return sb.toString()
}
}
| 0
|
Kotlin
|
0
| 0
|
a0fdf428ef056565aa829597ee02d3c4a26608c9
| 1,598
|
HerryApiDemo
|
Apache License 2.0
|
src/main/kotlin/com/financesbox/usermgmt/app/user/query/getuser/model/UserQueryModel.kt
|
FinancesBox
| 839,818,989
| false
|
{"Kotlin": 76010, "Dockerfile": 247}
|
package com.financesbox.usermgmt.app.user.query.getuser.model
import com.financesbox.shared.application.cqs.query.QueryModel
import io.micronaut.serde.annotation.Serdeable
import java.time.Instant
import java.util.*
@Serdeable
class UserQueryModel(
val id: UUID, val name: String, val email: String, val roles: List<String>, val createdAt: Instant,
) : QueryModel()
| 0
|
Kotlin
|
0
| 0
|
9496b4dabb13b163a161d7e0843649f592f7a4ad
| 371
|
core-api
|
MIT License
|
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/SiteAlt.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.straight.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Filled.SiteAlt: ImageVector
get() {
if (_siteAlt != null) {
return _siteAlt!!
}
_siteAlt = Builder(name = "SiteAlt", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(12.126f, 21.68f)
curveToRelative(-0.052f, -0.042f, -0.095f, -0.07f, -0.15f, -0.116f)
curveToRelative(-0.678f, -0.718f, -1.752f, -1.977f, -2.688f, -3.586f)
horizontalLineToRelative(1.571f)
lineToRelative(-0.684f, -2.0f)
horizontalLineToRelative(-1.873f)
curveToRelative(-0.493f, -1.234f, -0.825f, -2.587f, -0.825f, -4.0f)
reflectiveCurveToRelative(0.334f, -2.765f, 0.829f, -4.0f)
horizontalLineToRelative(7.334f)
curveToRelative(0.294f, 0.736f, 0.54f, 1.508f, 0.683f, 2.317f)
lineToRelative(2.103f, 0.72f)
curveToRelative(-0.091f, -1.062f, -0.329f, -2.078f, -0.653f, -3.036f)
horizontalLineToRelative(3.363f)
curveToRelative(0.491f, 1.119f, 0.775f, 2.345f, 0.822f, 3.632f)
curveToRelative(0.005f, 0.123f, 0.008f, 0.532f, 0.006f, 0.615f)
lineToRelative(1.966f, 0.673f)
curveToRelative(0.023f, -0.305f, 0.047f, -0.609f, 0.047f, -0.919f)
horizontalLineToRelative(0.0f)
curveTo(23.978f, 5.361f, 18.594f, -0.022f, 11.978f, -0.022f)
reflectiveCurveTo(-0.022f, 5.361f, -0.022f, 11.978f)
reflectiveCurveToRelative(5.383f, 12.0f, 12.0f, 12.0f)
horizontalLineToRelative(0.0f)
curveToRelative(0.31f, 0.0f, 0.616f, -0.016f, 0.921f, -0.039f)
lineToRelative(-0.773f, -2.259f)
close()
moveTo(9.288f, 5.978f)
curveToRelative(0.933f, -1.603f, 2.013f, -2.868f, 2.69f, -3.586f)
curveToRelative(0.676f, 0.716f, 1.75f, 1.985f, 2.681f, 3.586f)
horizontalLineToRelative(-5.371f)
close()
moveTo(19.958f, 5.978f)
horizontalLineToRelative(-3.019f)
curveToRelative(-0.723f, -1.451f, -1.591f, -2.689f, -2.36f, -3.645f)
curveToRelative(2.177f, 0.588f, 4.057f, 1.891f, 5.379f, 3.645f)
close()
moveTo(9.365f, 2.336f)
curveToRelative(-0.768f, 0.953f, -1.631f, 2.198f, -2.353f, 3.642f)
horizontalLineToRelative(-3.017f)
curveToRelative(1.32f, -1.751f, 3.197f, -3.053f, 5.369f, -3.642f)
close()
moveTo(2.818f, 7.978f)
horizontalLineToRelative(3.36f)
curveToRelative(-0.422f, 1.245f, -0.7f, 2.587f, -0.7f, 4.0f)
reflectiveCurveToRelative(0.278f, 2.755f, 0.7f, 4.0f)
horizontalLineToRelative(-3.36f)
curveToRelative(-0.538f, -1.226f, -0.841f, -2.578f, -0.841f, -4.0f)
reflectiveCurveToRelative(0.303f, -2.774f, 0.841f, -4.0f)
close()
moveTo(3.996f, 17.978f)
horizontalLineToRelative(3.017f)
curveToRelative(0.728f, 1.457f, 1.599f, 2.689f, 2.371f, 3.647f)
curveToRelative(-2.181f, -0.587f, -4.064f, -1.891f, -5.388f, -3.647f)
close()
moveTo(24.022f, 15.043f)
lineToRelative(-6.108f, 2.874f)
lineToRelative(-2.874f, 6.106f)
lineToRelative(-4.67f, -13.651f)
lineToRelative(13.652f, 4.671f)
close()
}
}
.build()
return _siteAlt!!
}
private var _siteAlt: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 4,618
|
icons
|
MIT License
|
rumascot-api-v2-kmp/src/commonMain/kotlin/requests/UpdateRequestStrategy.kt
|
mathemator
| 586,045,497
| false
| null |
package ru.otus.otuskotlin.marketplace.api.v2.requests
import kotlinx.serialization.KSerializer
import ru.otus.otuskotlin.marketplace.api.v2.models.AdUpdateRequest
import ru.otus.otuskotlin.marketplace.api.v2.models.IRequest
import kotlin.reflect.KClass
object UpdateRequestStrategy: IRequestStrategy {
override val discriminator: String = "update"
override val clazz: KClass<out IRequest> = AdUpdateRequest::class
override val serializer: KSerializer<out IRequest> = AdUpdateRequest.serializer()
override fun <T : IRequest> fillDiscriminator(req: T): T {
require(req is AdUpdateRequest)
@Suppress("UNCHECKED_CAST")
return req.copy(requestType = discriminator) as T
}
}
| 2
|
Kotlin
|
0
| 0
|
633640f3c74b3d5a352052bbce9fd6358881953a
| 716
|
goppeav-kotlin-2022-12
|
Apache License 2.0
|
src/test/kotlin/multiple/SetTest.kt
|
sya-ri
| 557,209,174
| false
|
{"Kotlin": 206299}
|
package multiple
import dev.s7a.ktconfig.ktConfigString
import dev.s7a.ktconfig.saveKtConfigString
import io.kotest.core.spec.style.FunSpec
import io.kotest.datatest.withData
import io.kotest.matchers.shouldBe
import java.math.BigDecimal
import java.math.BigInteger
import java.util.Calendar
import java.util.Date
import java.util.TimeZone
import java.util.UUID
@Suppress("unused")
class SetTest :
FunSpec({
data class Config(
val string: Set<String>,
val int: Set<Int>,
val uint: Set<UInt>,
val boolean: Set<Boolean>,
val double: Set<Double>,
val float: Set<Float>,
val long: Set<Long>,
val ulong: Set<ULong>,
val byte: Set<Byte>,
val ubyte: Set<UByte>,
val char: Set<Char>,
val short: Set<Short>,
val ushort: Set<UShort>,
val bigInteger: Set<BigInteger>,
val bigDecimal: Set<BigDecimal>,
val date: Set<Date>,
val calendar: Set<Calendar>,
val uuid: Set<UUID>,
)
test("should get single values as set") {
ktConfigString<Config>(
"""
string: config string
int: 123
uint: 123
boolean: true
double: 123.45
float: 123.45
long: 1234567890123456789
ulong: 1234567890123456789
byte: 127
ubyte: 255
char: c
short: 12345
ushort: 12345
bigInteger: 1234567890123456789012345678901234567890
bigDecimal: '12345.67890'
date: 2020-12-03T10:35:30Z
calendar: 2020-12-03T10:35:30Z
uuid: 123e4567-e89b-12d3-a456-426655440000
""".trimIndent(),
) shouldBe
Config(
string = setOf("config string"),
int = setOf(123),
uint = setOf(123u),
boolean = setOf(true),
double = setOf(123.45),
float = setOf(123.45f),
long = setOf(1234567890123456789L),
ulong = setOf(1234567890123456789uL),
byte = setOf(127),
ubyte = setOf(255u),
char = setOf('c'),
short = setOf(12345),
ushort = setOf(12345u),
bigInteger =
setOf(
BigInteger("1234567890123456789012345678901234567890"),
),
bigDecimal =
setOf(
BigDecimal("12345.67890"),
),
date =
setOf(
Date(1606991730000L),
),
calendar =
setOf(
Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply { time = Date(1606991730000L) },
),
uuid =
setOf(
UUID.fromString("123e4567-e89b-12d3-a456-426655440000"),
),
)
}
context("should get all list values from config") {
withData(
"""
string: [config string, another string]
int: [123, 456]
uint: [123, 456]
boolean: [true, false]
double: [123.45, 678.90]
float: [123.45, 678.90]
long: [1234567890123456789, -1234567890123456789]
ulong: [1234567890123456789, 9876543210]
byte: [127, 126]
ubyte: [255, 254]
char: [c, d]
short: [12345, 23456]
ushort: [12345, 23456]
bigInteger: [1234567890123456789012345678901234567890, 9876543210123456789012345678901234567890]
bigDecimal: ['12345.67890', '67890.12345']
date: [2020-12-03T10:35:30Z, 2021-01-01T00:00:00Z]
calendar: [2020-12-03T10:35:30Z, 2021-01-01T00:00:00Z]
uuid: [123e4567-e89b-12d3-a456-426655440000, 123e4567-e89b-12d3-a456-426655440001]
""".trimIndent(),
"""
string:
- config string
- another string
int:
- 123
- 456
uint:
- 123
- 456
boolean:
- true
- false
double:
- 123.45
- 678.9
float:
- 123.45
- 678.9
long:
- 1234567890123456789
- -1234567890123456789
ulong:
- 1234567890123456789
- 9876543210
byte:
- 127
- 126
ubyte:
- 255
- 254
char:
- c
- d
short:
- 12345
- 23456
ushort:
- 12345
- 23456
bigInteger:
- 1234567890123456789012345678901234567890
- 9876543210123456789012345678901234567890
bigDecimal:
- '12345.67890'
- '67890.12345'
date:
- 2020-12-03T10:35:30Z
- 2021-01-01T00:00:00Z
calendar:
- 2020-12-03T10:35:30Z
- 2021-01-01T00:00:00Z
uuid:
- 123e4567-e89b-12d3-a456-426655440000
- 123e4567-e89b-12d3-a456-426655440001
""".trimIndent(),
) { yaml ->
ktConfigString<Config>(
yaml,
) shouldBe
Config(
string = setOf("config string", "another string"),
int = setOf(123, 456),
uint = setOf(123u, 456u),
boolean = setOf(true, false),
double = setOf(123.45, 678.90),
float = setOf(123.45f, 678.90f),
long = setOf(1234567890123456789L, -1234567890123456789L),
ulong = setOf(1234567890123456789uL, 9876543210uL),
byte = setOf(127, 126),
ubyte = setOf(255u, 254u),
char = setOf('c', 'd'),
short = setOf(12345, 23456),
ushort = setOf(12345u, 23456u),
bigInteger =
setOf(
BigInteger("1234567890123456789012345678901234567890"),
BigInteger("9876543210123456789012345678901234567890"),
),
bigDecimal =
setOf(
BigDecimal("12345.67890"),
BigDecimal("67890.12345"),
),
date =
setOf(
Date(1606991730000L),
Date(1609459200000L),
),
calendar =
setOf(
Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply { time = Date(1606991730000L) },
Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply { time = Date(1609459200000L) },
),
uuid =
setOf(
UUID.fromString("123e4567-e89b-12d3-a456-426655440000"),
UUID.fromString("123e4567-e89b-12d3-a456-426655440001"),
),
)
}
}
test("should save all list values to config") {
saveKtConfigString(
Config(
string = setOf("config string", "another string"),
int = setOf(123, 456),
uint = setOf(123u, 456u),
boolean = setOf(true, false),
double = setOf(123.45, 678.90),
float = setOf(123.45f, 678.90f),
long = setOf(1234567890123456789L, -1234567890123456789L),
ulong = setOf(1234567890123456789uL, 9876543210uL),
byte = setOf(127, 126),
ubyte = setOf(255u, 254u),
char = setOf('c', 'd'),
short = setOf(12345, 23456),
ushort = setOf(12345u, 23456u),
bigInteger =
setOf(
BigInteger("1234567890123456789012345678901234567890"),
BigInteger("9876543210123456789012345678901234567890"),
),
bigDecimal =
setOf(
BigDecimal("12345.67890"),
BigDecimal("67890.12345"),
),
date =
setOf(
Date(1606991730000L),
Date(1609459200000L),
),
calendar =
setOf(
Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply { time = Date(1606991730000L) },
Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply { time = Date(1609459200000L) },
),
uuid =
setOf(
UUID.fromString("123e4567-e89b-12d3-a456-426655440000"),
UUID.fromString("123e4567-e89b-12d3-a456-426655440001"),
),
),
) shouldBe
"""
string:
- config string
- another string
int:
- 123
- 456
uint:
- 123
- 456
boolean:
- true
- false
double:
- 123.45
- 678.9
float:
- 123.45
- 678.9
long:
- 1234567890123456789
- -1234567890123456789
ulong:
- 1234567890123456789
- 9876543210
byte:
- 127
- 126
ubyte:
- 255
- 254
char:
- c
- d
short:
- 12345
- 23456
ushort:
- 12345
- 23456
bigInteger:
- 1234567890123456789012345678901234567890
- 9876543210123456789012345678901234567890
bigDecimal:
- '12345.67890'
- '67890.12345'
date:
- 2020-12-03T10:35:30Z
- 2021-01-01T00:00:00Z
calendar:
- 2020-12-03T10:35:30Z
- 2021-01-01T00:00:00Z
uuid:
- 123e4567-e89b-12d3-a456-426655440000
- 123e4567-e89b-12d3-a456-426655440001
""".trimIndent()
}
test("should get all duplicate list values from config") {
val yaml =
"""
string: [duplicate string, duplicate string]
int: [123, 123]
uint: [123, 123]
boolean: [true, true]
double: [123.45, 123.45]
float: [123.45, 123.45]
long: [1234567890123456789, 1234567890123456789]
ulong: [1234567890123456789, 1234567890123456789]
byte: [127, 127]
ubyte: [255, 255]
char: [c, c]
short: [12345, 12345]
ushort: [12345, 12345]
bigInteger: [1234567890123456789012345678901234567890, 1234567890123456789012345678901234567890]
bigDecimal: ['12345.67890', '12345.67890']
date: [2020-12-03T10:35:30Z, 2020-12-03T10:35:30Z]
calendar: [2020-12-03T10:35:30Z, 2020-12-03T10:35:30Z]
uuid: [123e4567-e89b-12d3-a456-426655440000, 123e4567-e89b-12d3-a456-426655440000]
""".trimIndent()
ktConfigString<Config>(yaml) shouldBe
Config(
string = setOf("duplicate string"),
int = setOf(123),
uint = setOf(123u),
boolean = setOf(true),
double = setOf(123.45),
float = setOf(123.45f),
long = setOf(1234567890123456789L),
ulong = setOf(1234567890123456789uL),
byte = setOf(127),
ubyte = setOf(255u),
char = setOf('c'),
short = setOf(12345),
ushort = setOf(12345u),
bigInteger =
setOf(
BigInteger("1234567890123456789012345678901234567890"),
),
bigDecimal =
setOf(
BigDecimal("12345.67890"),
),
date =
setOf(
Date(1606991730000L),
),
calendar =
setOf(
Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply { time = Date(1606991730000L) },
),
uuid =
setOf(
UUID.fromString("123e4567-e89b-12d3-a456-426655440000"),
),
)
}
test("should save all duplicate list values to config") {
val config =
Config(
string = setOf("duplicate string", "duplicate string"),
int = setOf(123, 123),
uint = setOf(123u, 123u),
boolean = setOf(true, true),
double = setOf(123.45, 123.45),
float = setOf(123.45f, 123.45f),
long = setOf(1234567890123456789L, 1234567890123456789L),
ulong = setOf(1234567890123456789uL, 1234567890123456789uL),
byte = setOf(127, 127),
ubyte = setOf(255u, 255u),
char = setOf('c', 'c'),
short = setOf(12345, 12345),
ushort = setOf(12345u, 12345u),
bigInteger =
setOf(
BigInteger("1234567890123456789012345678901234567890"),
BigInteger("1234567890123456789012345678901234567890"),
),
bigDecimal =
setOf(
BigDecimal("12345.67890"),
BigDecimal("12345.67890"),
),
date =
setOf(
Date(1606991730000L),
Date(1606991730000L),
),
calendar =
setOf(
Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply { time = Date(1606991730000L) },
Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply { time = Date(1606991730000L) },
),
uuid =
setOf(
UUID.fromString("123e4567-e89b-12d3-a456-426655440000"),
UUID.fromString("123e4567-e89b-12d3-a456-426655440000"),
),
)
saveKtConfigString(config) shouldBe
"""
string:
- duplicate string
int:
- 123
uint:
- 123
boolean:
- true
double:
- 123.45
float:
- 123.45
long:
- 1234567890123456789
ulong:
- 1234567890123456789
byte:
- 127
ubyte:
- 255
char:
- c
short:
- 12345
ushort:
- 12345
bigInteger:
- 1234567890123456789012345678901234567890
bigDecimal:
- '12345.67890'
date:
- 2020-12-03T10:35:30Z
calendar:
- 2020-12-03T10:35:30Z
uuid:
- 123e4567-e89b-12d3-a456-426655440000
""".trimIndent()
}
})
| 5
|
Kotlin
|
1
| 10
|
47066550bec14392147d10c179b298f5c181d906
| 17,846
|
ktConfig
|
MIT License
|
ok/src/main/kotlin/com/github/jmfayard/okandroid/MainActivity.kt
|
jmfayard
| 113,597,045
| false
| null |
package com.github.jmfayard.okandroid
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.github.jmfayard.screens.HomeScreen
import com.github.jmfayard.screens.TagsScreen
import com.github.jmfayard.utils.See
import com.wealthfront.magellan.Navigator
import com.wealthfront.magellan.Screen
import com.wealthfront.magellan.ScreenLifecycleListener
import com.wealthfront.magellan.support.SingleActivity
import com.wealthfront.magellan.transitions.DefaultTransition
import timber.log.Timber
@See(layout = R.layout.all_activity)
class MainActivity : SingleActivity() {
companion object {
val REQUEST_ENABLE_BT = 101
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(this as AppCompatActivity).setContentView(R.layout.all_activity)
handleShortcutIntents()
}
fun handleShortcutIntents() {
// Overwriting root screen with magellan https://github.com/wealthfront/magellan/issues/41
val screen = intent?.extras?.getString("screen") ?: "main"
if (screen == "tags") {
getNavigator().resetWithRoot(this, TagsScreen())
}
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
android.R.id.home -> getNavigator().replace(HomeScreen())
else -> return super.onOptionsItemSelected(item)
}
return true
}
override fun createNavigator(): Navigator {
val navigator = Navigator.withRoot(HomeScreen())
.transition(DefaultTransition())
.loggingEnabled(true)
.build()
navigator.addLifecycleListener(LifeCycle)
return navigator
}
val LifeCycle = object : ScreenLifecycleListener {
override fun onShow(screen: Screen<*>) {
val title = screen.getTitle(applicationContext)
Log.i("Navigator", "onShow(screen = '$title')")
with(supportActionBar!!) {
val firstScreen = screen is HomeScreen
setDisplayUseLogoEnabled(firstScreen)
setDisplayHomeAsUpEnabled(!firstScreen)
}
}
override fun onHide(screen: Screen<*>) {
val title = screen.getTitle(applicationContext)
Log.i("Navigator", "onHide(screen = '$title')")
}
}
public override fun onNewIntent(intent: Intent) {
// onResume gets called after this to handle the intent
setIntent(intent)
}
public override fun onResume() {
super.onResume()
// Check to see that the Activity started due to an Android Beam
when {
intent == null -> return
intent.hasCategory(Intent.CATEGORY_LAUNCHER) -> return
else -> Toast.makeText(this, intent.description(), Toast.LENGTH_LONG).show()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val result = when (resultCode) {
Activity.RESULT_CANCELED -> "RESULT_CANCELED"
Activity.RESULT_OK -> "RESULT_OK"
else -> "ResultCode:$resultCode"
}
val request = when (requestCode) {
REQUEST_ENABLE_BT -> "REQUEST_ENABLE_BT"
else -> "Code $requestCode"
}
val message = "OnActivityResult for $request : $result data=${data?.description()}"
Timber.w(message)
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}
}
| 0
|
Kotlin
|
0
| 0
|
7d0e82038e457dc015bb31a77fa16787f6368166
| 3,734
|
okAndroid
|
The Unlicense
|
app/src/test/java/com/hivian/compose_mvvm/presentation/HomeViewModelTest.kt
|
hivian
| 558,800,190
| false
| null |
package com.hivian.compose_mvvm.presentation
import com.hivian.compose_mvvm.InstantExecutorExtension
import com.hivian.compose_mvvm.MainCoroutineExtension
import com.hivian.compose_mvvm.core.base.ViewModelVisualState
import com.hivian.compose_mvvm.core.data.ServiceResult
import com.hivian.compose_mvvm.core.data.network.ErrorType
import com.hivian.compose_mvvm.core.services.localization.ILocalizationService
import com.hivian.compose_mvvm.core.services.userinteraction.IUserInteractionService
import com.hivian.compose_mvvm.domain.mappers.ImageSize
import com.hivian.compose_mvvm.domain.mappers.mapToRandomUsers
import com.hivian.compose_mvvm.data.models.Location
import com.hivian.compose_mvvm.data.models.Name
import com.hivian.compose_mvvm.data.models.Picture
import com.hivian.compose_mvvm.data.models.RandomUserDTO
import com.hivian.compose_mvvm.domain.services.application.IRandomUsersService
import com.hivian.compose_mvvm.presentation.home.HomeViewModel
import com.hivian.compose_mvvm.ui.services.navigation.INavigationService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertAll
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.kotlin.doSuspendableAnswer
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
@ExperimentalCoroutinesApi
@ExtendWith(InstantExecutorExtension::class, MainCoroutineExtension::class)
class HomeViewModelTest {
private val localizationService = mock<ILocalizationService>()
private val navigationService = mock<INavigationService>()
private val randomUsersService = mock<IRandomUsersService>()
private val userInteractionService = mock<IUserInteractionService>()
private lateinit var viewModel: HomeViewModel
@BeforeEach
fun setUp() {
viewModel = HomeViewModel(localizationService, navigationService, randomUsersService, userInteractionService)
}
@Test
fun `ViewModel is initialized`() {
viewModel.initialize()
assertEquals(true, viewModel.isInitialized.value)
}
@Test
fun `ViewModel is not initialized`() {
assertEquals(false, viewModel.isInitialized.value)
}
@Test
fun `Success state works`() = runTest {
whenever(
randomUsersService.fetchRandomUsers(HomeViewModel.PAGINATOR_INITIAL_KEY, HomeViewModel.RESULT_COUNT)
).thenReturn(
ServiceResult.Success(emptyList())
)
viewModel.initialize()
advanceUntilIdle()
assertEquals(ViewModelVisualState.Success, viewModel.viewModelVisualState.value)
}
@Test
fun `Failure state works`() = runTest {
whenever(
randomUsersService.fetchRandomUsers(HomeViewModel.PAGINATOR_INITIAL_KEY, HomeViewModel.RESULT_COUNT)
).thenReturn(
ServiceResult.Error(ErrorType.UNKNOWN, emptyList())
)
viewModel.initialize()
advanceUntilIdle()
assertEquals(ViewModelVisualState.Error(ErrorType.UNKNOWN), viewModel.viewModelVisualState.value)
}
@Test
fun `Initial Loading state works`() = runTest {
whenever(
randomUsersService.fetchRandomUsers(HomeViewModel.PAGINATOR_INITIAL_KEY, HomeViewModel.RESULT_COUNT)
).doSuspendableAnswer {
withContext(Dispatchers.IO) { delay(1000) }
ServiceResult.Success(emptyList())
}
viewModel.initialize()
advanceUntilIdle()
assertAll("Initial loader is loading",
{ assertEquals(ViewModelVisualState.Loading, viewModel.viewModelVisualState.value) },
{ assertEquals(false, viewModel.showLoadMoreLoader.value) }
)
}
@Test
fun `Load more Loading state works`() = runTest {
whenever(
randomUsersService.fetchRandomUsers(HomeViewModel.PAGINATOR_INITIAL_KEY, HomeViewModel.RESULT_COUNT)
).thenReturn(
ServiceResult.Success(emptyList())
)
whenever(
randomUsersService.fetchRandomUsers(HomeViewModel.PAGINATOR_INITIAL_KEY + 1, HomeViewModel.RESULT_COUNT)
).doSuspendableAnswer {
withContext(Dispatchers.IO) { delay(1000) }
ServiceResult.Success(emptyList())
}
viewModel.initialize()
viewModel.loadNextItem()
advanceUntilIdle()
assertAll("Load more loader is loading",
{ assertEquals(ViewModelVisualState.Success, viewModel.viewModelVisualState.value) },
{ assertEquals(true, viewModel.showLoadMoreLoader.value) }
)
}
@Test
fun `Items are initialized with correct data`() = runTest {
val id = 0
val gender = "male"
val title = "Mr"
val firstName = "Toto"
val lastName = "Tutu"
val email = "<EMAIL>"
val cell = "0606060606"
val phone = "0101010101"
val picture = Picture.EMPTY
val location = Location.EMPTY
val usersDTO = listOf(
RandomUserDTO(
localId = id,
gender = gender,
name = Name(title = title, first = firstName, last = lastName),
email = email,
cell = cell,
phone = phone,
picture = picture,
location = location
)
)
val usersDomain = usersDTO.mapToRandomUsers(ImageSize.MEDIUM)
whenever(
randomUsersService.fetchRandomUsers(HomeViewModel.PAGINATOR_INITIAL_KEY, HomeViewModel.RESULT_COUNT)
).thenReturn(
ServiceResult.Success(usersDTO)
)
viewModel.initialize()
advanceUntilIdle()
assertEquals(usersDomain, viewModel.items.toList())
}
@Test
fun `Items are updated with correct data`() = runTest {
val id = 0
val gender = "male"
val title = "Mr"
val firstName = "Toto"
val lastName = "Tutu"
val email = "<EMAIL>"
val cell = "0606060606"
val phone = "0101010101"
val picture = Picture.EMPTY
val location = Location.EMPTY
val usersDTO = ArrayList<RandomUserDTO>()
repeat(2) { index ->
usersDTO.addAll(listOf(
RandomUserDTO(
localId = id + index,
gender = gender,
name = Name(title = title, first = firstName, last = lastName),
email = email,
cell = cell,
phone = phone,
picture = picture,
location = location
)
))
}
repeat(2) { index ->
whenever(
randomUsersService.fetchRandomUsers(HomeViewModel.PAGINATOR_INITIAL_KEY + index, HomeViewModel.RESULT_COUNT)
).thenReturn(
ServiceResult.Success(listOf(usersDTO[index]))
)
}
val usersDomain = usersDTO.mapToRandomUsers(ImageSize.MEDIUM)
viewModel.initialize()
viewModel.loadNextItem()
advanceUntilIdle()
assertEquals(usersDomain, viewModel.items.toList())
}
}
| 0
|
Kotlin
|
0
| 0
|
5ca1bced1ce4c766f8b85f672cb0a8e324b17d81
| 7,464
|
Android-Compose-MVVM
|
MIT License
|
core-mvi/src/main/java/ru/surfstudio/android/core/mvi/ui/middleware/RxMiddleware.kt
|
eltray
| 200,101,552
| true
|
{"Kotlin": 1787549, "Java": 826942, "FreeMarker": 54338, "Groovy": 8823, "C++": 1542, "CMake": 285}
|
package ru.surfstudio.android.core.mvi.ui.middleware
import io.reactivex.Observable
import ru.surfstudio.android.core.mvi.event.Event
import ru.surfstudio.android.core.mvi.event.LoadableEvent
import ru.surfstudio.android.core.mvi.ui.relation.StateEmitter
import ru.surfstudio.android.core.mvp.binding.rx.loadable.type.mapToLoadType
/**
* [Middleware] с реализацией в Rx.
*
* Кроме типизации по [Observable], содержит некоторые вспомогательные функции для работы с потоком.
*/
interface RxMiddleware<T : Event> : Middleware<T, Observable<T>, Observable<out T>>, StateEmitter {
fun <T, E : LoadableEvent<T>> Observable<T>.mapToLoadable(event: E): Observable<out E> = this
.mapToLoadType()
.map { event.apply { type = it } }
fun <T> skip() = Observable.empty<T>()
fun <T> doAndSkip(action: () -> Unit): Observable<T> {
action()
return Observable.empty<T>()
}
fun Observable<T>.ignoreError() = onErrorResumeNext { _: Throwable -> Observable.empty() }
fun merge(vararg observables: Observable<out T>): Observable<out T> = Observable.merge(observables.toList())
}
| 0
|
Kotlin
|
0
| 0
|
69d435621d90954102af7424b4b309213d9bc95d
| 1,132
|
SurfAndroidStandard
|
Apache License 2.0
|
ledger/src/main/kotlin/org/knowledger/ledger/serial/internal/HashEncodeForDisplay.kt
|
fakecoinbase
| 282,563,487
| false
| null |
package org.knowledger.ledger.serial.internal
import kotlinx.serialization.CompositeDecoder
import kotlinx.serialization.CompositeEncoder
import kotlinx.serialization.SerialDescriptor
import org.knowledger.ledger.crypto.Hash
import org.knowledger.ledger.serial.display.HashDisplaySerializer
internal interface HashEncodeForDisplay : HashEncode {
override val hashDescriptor: SerialDescriptor
get() = HashDisplaySerializer.descriptor
override fun CompositeEncoder.encodeHash(
index: Int, hash: Hash
) {
encodeSerializableElement(descriptor, index, HashDisplaySerializer, hash)
}
override fun CompositeDecoder.decodeHash(index: Int): Hash =
decodeSerializableElement(descriptor, index, HashDisplaySerializer)
}
| 0
|
Kotlin
|
0
| 0
|
8bc64987e1ab4d26663064da06393de6befc30ae
| 764
|
SeriyinslashKnowLedger
|
MIT License
|
src/DcircleChainP-Node/foundation/src/main/java/com/base/foundation/db/DIDArticleStat.kt
|
wanxiang-blockchain
| 683,936,032
| false
|
{"Kotlin": 564771, "Java": 393645, "TypeScript": 313064, "Go": 182715, "SCSS": 72564, "CSS": 6411, "Solidity": 4012, "JavaScript": 2433, "HTML": 2352}
|
package com.base.foundation.db
import com.base.foundation.getUs
import com.base.foundation.nc.NcEvent
import com.blankj.utilcode.util.LogUtils
import com.github.xpwu.ktdbtable.eq
import com.github.xpwu.ktdbtable.invoke
import com.github.xpwu.ktdbtable.where.and
import com.github.xpwu.ktdbtble.annotation.*
import com.github.xpwu.ktdbtble.annotation.Table
import com.tencent.wcdb.database.SQLiteDatabase
private val table = DIDArticleStat.Companion
@Table("DIDArticleStat")
class DIDArticleStat {
class ChangedEvent(var address: String="") : NcEvent<String>(listOf(address)) {
override fun getName(): String {
return super.getName() + address
}
}
@Column("statId", primaryKey = PrimaryKey.ONLY_ONE)
var statId: String = ""
@Column("dataUpdateTime")
var DataUpdateTime: Long = 0
@Index(true, name = "id_role_ymd", sequence = 0)
@Column("roleId")
var RoleId:String = ""
@Index(true, name = "id_role_ymd", sequence = 1)
@Column("roleStatType")
var RoleStatType: String = ""
@Index(true, name = "id_role_ymd", sequence = 2)
@Column("ymd")
var ymd:String = ""
@Column("contentNums")
var ContentNums: Int = 0
@Column("circulationNums")
var CirculationNums: Int = 0
@Column("consumerNums")
var ConsumerNums: Int = 0
@Column("consumptionTimes")
var ConsumptionTimes: Int = 0
@Column("reachNums")
var ReachNums: Int = 0
@Column("groupNums")
var GroupNums: Int = 0
@Column("potentialCirculationNums")
var PotentialCirculationNums: Int = 0
@Column("potentialConsumerNums")
var PotentialConsumerNums: Int = 0
@Column("sgNums")
var sgNums: Int = 0
@Column("tTimes")
var tTimes: Int = 0
@Column("exposureGroupNums")
var exposureGroupNums: Int = 0
@Column("exposurePeopleNums")
var exposurePeopleNums: Int = 0
@Column("revenueNums")
var revenueNums: Int = 0
@Column("joinTimes")
var JoinTimes: Int = 0
@Column("joinUserCount")
var JoinUserCount: Int = 0
@Column("shareGroupCount")
var ShareGroupCount: Int = 0
/**
Content Nums (内容总数)
CirculationNums (流通量)
ConsumerNums (消费人数)
ConsumptionTimes (消费次数)
ReachNums (传播人数)
tTimes(传播次数)
GroupNums (传播群数)
PotentialCirculationNums (潜力流通量)
PotentialConsumerNums (潜力消费数)
sgNums 来源群数
exposureGroupNums 曝光群数
exposurePeopleNums 曝光人数
revenueNums 个人收入
* */
companion object;
enum class StatRoleType(val value: String) {
ArticleStat("ArticleStat"),
CreatorStat("CreatorStat"),
TransferStat("TransferStat"),
GroupStat("GroupStat"),
SingleGroupStat("SingleGroupStat"), // 单个群聊,id则为chatId
ConsumerStat("ConsumerStat"),
InviteJoinGroupStat("InviteJoinGroupStat");//用户邀请进群信息
companion object {
fun fromValue(value: String) = StatRoleType.values().first { it.value == value }
}
}
}
suspend fun Array<DIDArticleStat>.update(): Array<String> {
val failed: MutableList<String> = mutableListOf()
for (item in this) {
if (item.update() != null) {
failed.add(item.statId)
}
}
return failed.toTypedArray()
}
suspend fun DIDArticleStat.update(): Error? {
return getUs().shareDB.invoke {
val columns = listOf(
DIDArticleStat.ContentNums,
DIDArticleStat.CirculationNums,
DIDArticleStat.ConsumerNums,
DIDArticleStat.ConsumptionTimes,
DIDArticleStat.ReachNums,
DIDArticleStat.GroupNums,
DIDArticleStat.PotentialCirculationNums,
DIDArticleStat.PotentialConsumerNums,
DIDArticleStat.exposureGroupNums,
DIDArticleStat.revenueNums,
DIDArticleStat.sgNums,
DIDArticleStat.tTimes,
DIDArticleStat.exposurePeopleNums,
DIDArticleStat.RoleStatType,
DIDArticleStat.ymd,
DIDArticleStat.DataUpdateTime,
DIDArticleStat.RoleId,
DIDArticleStat.JoinTimes,
DIDArticleStat.JoinUserCount,
DIDArticleStat.ShareGroupCount,
)
val where = DIDArticleStat.statId.eq(this.statId)
val name = table.TableNameIn(it)
try {
val colNum = it.UnderlyingDB.updateWithOnConflict(
name,
this.ToContentValues(columns),
where.ArgSQL,
where.BindArgs,
SQLiteDatabase.CONFLICT_IGNORE
)
if (colNum <= 0) {
return@invoke Error("not found")
}
return@invoke null
} catch (e: Exception) {
LogUtils.e("DIDArticle.Update err", e)
return@invoke Error(e)
}
}
}
suspend fun DIDArticleStat.insert(): Error? {
return getUs().shareDB.invoke {
val values = this.ToContentValues()
val name = table.TableNameIn(it)
try {
it.UnderlyingDB.insertOrThrow(name, null, values)
return@invoke null
} catch (e: Exception) {
return@invoke Error(e)
}
}
}
suspend fun Array<DIDArticleStat>.insert(): Array<String> {
return getUs().shareDB.invoke {
val failedList: MutableList<String> = mutableListOf()
val name = table.TableNameIn(it)
it.UnderlyingDB.beginTransaction()
try {
for (data in this) {
try {
it.UnderlyingDB.insertOrThrow(name, null, data.ToContentValues())
} catch (e: Exception) {
failedList.add(data.statId)
}
}
it.UnderlyingDB.setTransactionSuccessful()
} finally {
it.UnderlyingDB.endTransaction()
}
return@invoke failedList.toTypedArray()
}
}
suspend fun DIDArticleStat.Companion.FindLatestByRole(userid:String , userRoles: Array<DIDArticleStat.StatRoleType> ): Array<DIDArticleStat> {
return getUs().shareDB {
val result = mutableListOf<DIDArticleStat>()
for (role in userRoles) {
val doc = findLatestByRole(userid,role)
if (doc != null) {
result.add(doc)
}
}
return@shareDB result.toTypedArray()
}
}
suspend fun DIDArticleStat.Companion.FindLatestByArticle(didArticleAddress:String): DIDArticleStat? {
return getUs().shareDB {
return@shareDB findLatestByRole(didArticleAddress,DIDArticleStat.StatRoleType.ArticleStat)
}
}
suspend fun DIDArticleStat.Companion.findByRoleWithDate(address :String , role: DIDArticleStat.StatRoleType,date: String): DIDArticleStat ? {
return getUs().shareDB { it ->
val where = DIDArticleStat.RoleId.eq(address) and DIDArticleStat.RoleStatType.eq(role.value) and
DIDArticleStat.ymd.eq(date)
val cursor =
it.UnderlyingDB.query(
table.TableNameIn(it),
DIDArticleStat.AllColumns().map { it.name }.toTypedArray(),
where.ArgSQL,
where.BindArgs,
null,
null,
"${DIDArticleStat.ymd.name} DESC"
)
if (!cursor.moveToFirst()) {
cursor.close()
return@shareDB null
}
val doc = DIDArticleStat()
cursor.ToDIDArticleStat(doc)
cursor.close()
return@shareDB doc
}
}
suspend fun DIDArticleStat.Companion.findLatestByRole(address :String , role: DIDArticleStat.StatRoleType): DIDArticleStat ? {
return getUs().shareDB { it ->
val where = DIDArticleStat.RoleId.eq(address) and DIDArticleStat.RoleStatType.eq(role.value)
val cursor =
it.UnderlyingDB.query(
table.TableNameIn(it),
DIDArticleStat.AllColumns().map { it.name }.toTypedArray(),
where.ArgSQL,
where.BindArgs,
null,
null,
"${DIDArticleStat.ymd.name} DESC"
)
if (!cursor.moveToFirst()) {
cursor.close()
return@shareDB null
}
val doc = DIDArticleStat()
cursor.ToDIDArticleStat(doc)
cursor.close()
return@shareDB doc
}
}
| 0
|
Kotlin
|
8
| 29
|
d3a91f9fb7b0a5b29806bcd2968e4dc8d894581b
| 8,335
|
2023WXH-DcircleChain
|
MIT License
|
src/jvmMain/kotlin/com/sdercolin/vlabeler/ui/editor/labeler/CanvasParams.kt
|
sdercolin
| 503,365,242
| false
| null |
package com.sdercolin.vlabeler.ui.editor.labeler
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import androidx.compose.ui.unit.Density
import com.sdercolin.vlabeler.model.AppConf
@Stable
data class CanvasParams(
val dataLength: Int,
val resolution: Int,
val density: Density,
) {
val lengthInPixel = dataLength.toFloat() / resolution
val canvasWidthInDp = with(density) { lengthInPixel.toDp() }
@Immutable
class ResolutionRange(
private val conf: AppConf.CanvasResolution,
) {
fun canIncrease(resolution: Int) = resolution < conf.max
fun canDecrease(resolution: Int) = resolution > conf.min
fun increaseFrom(resolution: Int) = resolution.plus(conf.step).coerceAtMost(conf.max)
fun decreaseFrom(resolution: Int) = resolution.minus(conf.step).coerceAtLeast(conf.min)
}
}
| 2
|
Kotlin
|
12
| 85
|
4941e4ffce9d1d398f7f6baa3a392476244e7f88
| 884
|
vlabeler
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.