path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/test/matrix/Mat3Test.kt
|
comexos
| 103,531,915
| true
|
{"Kotlin": 660502, "HTML": 262}
|
package test.matrix
import spr5.matrix.Mat3
import spr5.util.assertEquals
import spr5.util.assertFalse
import spr5.util.assertTrue
import test.annotations.After
import test.annotations.Before
import test.annotations.Test
class Mat3Test {
@Before
fun setUp() {
}
@After
fun tearDown() {
}
@Test
fun create() {
val identity = Mat3.identityDoubleArray()
assertEquals(1.0, identity[0])
assertEquals(0.0, identity[1])
assertEquals(0.0, identity[2])
assertEquals(0.0, identity[3])
assertEquals(1.0, identity[4])
assertEquals(0.0, identity[5])
assertEquals(0.0, identity[6])
assertEquals(0.0, identity[7])
assertEquals(1.0, identity[8])
}
@Test
fun testEquals() {
val m1 = Mat3.fromValues(1.0, 2.0, 3.0,
4.0, 1.0, 1.0,
3.0, 4.0, 5.0)
val m2 = Mat3.fromValues(1.0, 2.0, 3.0,
4.0, 1.0, 1.0,
3.0, 4.0, 5.0)
val m3 = Mat3.fromValues(0.0, 1.0, 2.0,
3.0, 0.0, -1.0,
5.0, 2.0, 5.0)
assertTrue(Mat3.equals(m1, m2))
assertTrue(Mat3.equals(m2, m1))
assertFalse(Mat3.equals(m2, m3))
assertFalse(Mat3.equals(m3, m2))
}
@Test
fun testAddMatrix() {
val m1 = Mat3(1.0, 2.0, 3.0,
4.0, 5.0, 6.0,
7.0, 8.0, 9.0)
val m2 = Mat3(1.0, 2.0, 3.0,
4.0, 5.0, 6.0,
7.0, 8.0, 9.0)
1
val expected = Mat3(2.0, 4.0, 6.0,
8.0, 10.0, 12.0,
14.0, 16.0, 18.0);
assertTrue(Mat3.equals(expected, m1 + m2));
assertTrue(Mat3.equals(expected, m2 + m1));
assertTrue(Mat3.equals(expected, Mat3.add(m1, m2)));
assertTrue(Mat3.equals(expected, Mat3.add(m2, m1)));
assertTrue(Mat3.equals(expected, m1.add(m2)));
assertTrue(Mat3.equals(expected, m1));
}
@Test
fun testAddZero() {
val m1 = Mat3(1.0, 2.0, 3.0,
4.0, 5.0, 6.0,
7.0, 8.0, 9.0)
val m2 = Mat3(0.0, 0.0, 0.0,
0.0, 0.0, 0.0,
0.0, 0.0, 0.0)
val expected = Mat3(1.0, 2.0, 3.0,
4.0, 5.0, 6.0,
7.0, 8.0, 9.0);
assertTrue(Mat3.equals(expected, m1 + m2));
assertTrue(Mat3.equals(expected, m2 + m1));
assertTrue(Mat3.equals(expected, Mat3.add(m1, m2)));
assertTrue(Mat3.equals(expected, Mat3.add(m2, m1)));
assertTrue(Mat3.equals(expected, m1.add(m2)));
assertTrue(Mat3.equals(expected, m1));
}
@Test
fun multiplyWithIdentity() {
val identity = Mat3.identityDoubleArray()
val m = Mat3.fromValues(
1.0, 2.0, 3.0,
4.0, 1.0, 1.0,
5.0, 4.0, 2.4)
// test m * I
assertTrue(Mat3.equals(m, Mat3.multiply(m, identity)))
// test I * m
assertTrue(Mat3.equals(m, Mat3.multiply(identity, m)))
}
@Test
fun multiplyWithMatrix() {
val m1 = Mat3.fromValues(1.0, 2.0, 3.0,
4.0, 5.0, 6.0,
7.0, 8.0, 9.0)
val m2 = Mat3.fromValues(3.0, 0.0, 1.0,
2.0, 4.0, -1.0,
5.5, 3.2, 1.0)
val prod1 = Mat3.multiply(m2, m1) // computes m1 * m2
val prod2 = Mat3.multiply(m1, m2) // computes m2 * m1
assertTrue(Mat3.equals(prod1,
Mat3.fromValues(23.5, 17.6, 2.0,
55.0, 39.2, 5.0,
86.5, 60.8, 8.0)))
assertTrue(Mat3.equals(prod2,
Mat3.fromValues(10.0, 14.0, 18.0,
11.0, 16.0, 21.0,
25.3, 35.0, 44.7)))
}
}
| 0
|
Kotlin
|
0
| 0
|
2afd59e8c9ebc193db81a45a61ee4bbdb9fd9027
| 3,902
|
3d-playground
|
Apache License 2.0
|
app/src/main/java/com/blackcatz/android/hnews/mvi/android/MviAppActivity.kt
|
vinayagasundar
| 157,092,166
| false
| null |
package com.blackcatz.android.hnews.mvi.android
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.blackcatz.android.hnews.mvi.MviIntent
import com.blackcatz.android.hnews.mvi.MviView
import com.blackcatz.android.hnews.mvi.MviViewModel
import com.blackcatz.android.hnews.mvi.MviViewState
import com.blackcatz.android.hnews.mvi.rx.AsyncTransformer
import com.blackcatz.android.hnews.mvi.rx.RxLifeCycle
import com.blackcatz.android.hnews.mvi.rx.RxTransformer
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import timber.log.Timber
/**
* @author vinayagasundar
*/
abstract class MviAppActivity<I : MviIntent, S : MviViewState, out VM : MviViewModel<I, S>>
: AppCompatActivity(),
MviView<I, S>, RxLifeCycle {
private val compositeDisposable = CompositeDisposable()
private val viewModel: VM by lazy {
createViewModel()
}
abstract fun createViewModel(): VM
open fun injectDependencies() {}
override fun onCreate(savedInstanceState: Bundle?) {
injectDependencies()
super.onCreate(savedInstanceState)
}
override fun onStart() {
super.onStart()
bind()
}
override fun onStop() {
super.onStop()
unBind()
}
private fun unBind() {
compositeDisposable.clear()
}
private fun bind() {
bind {
viewModel.states()
.compose(async())
.subscribe(this::render, Timber::e)
}
viewModel.processIntents(intents())
}
final override fun bind(data: () -> Disposable) {
compositeDisposable.add(data.invoke())
}
final override fun <T> async(): RxTransformer<T> = AsyncTransformer.create()
}
| 1
|
Kotlin
|
1
| 1
|
04e68552bfc295ee18f028a8a77c13f55e842de4
| 1,774
|
hnews
|
Apache License 2.0
|
app/src/main/java/org/onaio/rxgithub/presentation/ui/main/MainFragment.kt
|
ellykits
| 167,240,122
| false
| null |
package org.onaio.rxgithub.presentation.ui.main
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import org.koin.android.ext.android.get
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.onaio.rxgithub.R
import org.onaio.rxgithub.domain.entities.GithubUser
import org.onaio.rxgithub.presentation.di.Components
class MainFragment : Fragment() {
private lateinit var usersRecyclerView: RecyclerView
private lateinit var errorText: TextView
private lateinit var errorImageView: ImageView
private lateinit var progressBar: ProgressBar
private val viewModel: MainViewModel by viewModel()
private val usersRecyclerAdapter: GithubUsersRecyclerAdapter = get()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return inflater.inflate(R.layout.main_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
usersRecyclerView = activity!!.findViewById(R.id.usersRecyclerView)
progressBar = activity!!.findViewById(R.id.progressBar)
errorImageView = activity!!.findViewById(R.id.dangerImageView)
errorText = activity!!.findViewById(R.id.errorTextView)
activity?.title = activity?.getString(R.string.who_to_follow)
initRecyclerViewAdapter()
viewModel.state.observe(this, Observer { handleViewState(it) })
viewModel.errorEvent.observe(this, Observer { handleError(it) })
viewModel.retrieveUsers()
}
private fun initRecyclerViewAdapter() {
usersRecyclerView.adapter = usersRecyclerAdapter
usersRecyclerView.layoutManager = LinearLayoutManager(activity)
usersRecyclerAdapter.setOnItemClickListener(View.OnClickListener {
val viewHolder = it.tag as RecyclerView.ViewHolder
val currentUser: GithubUser = usersRecyclerAdapter.getGithubUser(viewHolder.adapterPosition)
val userDetailsFragment = Components.detailsFragment
userDetailsFragment.arguments = bundleCurrentUser(currentUser)
userDetailsFragment.show(activity?.supportFragmentManager, userDetailsFragment.tag)
})
}
private fun bundleCurrentUser(githubUser: GithubUser): Bundle {
val bundle = Bundle()
bundle.let {
it.putString("NAME", githubUser.fullName)
it.putString("USERNAME", githubUser.username)
it.putString("BIO", githubUser.bio)
it.putString("LOCATION", githubUser.location)
it.putString("COMPANY", githubUser.company)
it.putString("REPOS", githubUser.publicRepos)
it.putString("GISTS", githubUser.imageUri)
it.putString("FOLLOWERS", githubUser.followers)
it.putString("FOLLOWING", githubUser.following)
it.putString("PROFILE", githubUser.imageUri)
}
return bundle
}
private fun handleViewState(viewState: MainActivityViewState) {
toggleVisibility()
usersRecyclerAdapter.addUser(viewState.githubUser)
when {
viewState.isLoading -> {
progressBar.visibility = View.GONE
}
else -> progressBar.visibility = View.INVISIBLE
}
}
private fun toggleVisibility() {
errorText.visibility = View.GONE
progressBar.visibility = View.GONE
errorImageView.visibility = View.GONE
}
private fun handleError(throwable: Throwable) {
progressBar.visibility = View.GONE
errorText.visibility = View.VISIBLE
errorImageView.visibility = View.VISIBLE
Toast.makeText(context, "An error occurred. Try again later ${throwable.message}", Toast.LENGTH_LONG).show()
}
fun refreshList() {
toggleVisibility()
usersRecyclerAdapter.clearList()
viewModel.retrieveUsers()
}
override fun onDestroy() {
usersRecyclerAdapter.clearList()
super.onDestroy()
}
}
| 0
|
Kotlin
|
0
| 0
|
a3755dce67ebf9554d955e245c7ee47a3dce321c
| 4,438
|
git-client
|
Apache License 2.0
|
app/src/main/java/com/example/todolist/domain/repository/TodoListRepository.kt
|
yoempanha
| 730,547,101
| false
|
{"Kotlin": 38263}
|
package com.example.todolist.domain.repository
import com.example.todolist.domain.entity.TodoListContentModel
interface TodoListRepository {
suspend fun upsertTodoListContent(todoListContentModel: TodoListContentModel)
suspend fun deleteTodoListContent(todoListContentModel: TodoListContentModel)
suspend fun getTodoList(filter: String): List<TodoListContentModel>
}
| 0
|
Kotlin
|
0
| 0
|
fb0dcd9f83ce886641f9966eb3ea112baa4bd246
| 382
|
todo-list
|
Apache License 2.0
|
mobilesdk-merchantbackend/src/main/java/com/swedbankpay/mobilesdk/merchantbackend/InvalidInstrumentException.kt
|
SwedbankPay
| 209,749,704
| false
| null |
package com.swedbankpay.mobilesdk.merchantbackend
/**
* Reported as the [com.swedbankpay.mobilesdk.PaymentViewModel.RichState.updateException]
* if the instrument was not valid for the payment order.
*/
class InvalidInstrumentException(
val instrument: String,
cause: Throwable?
) : Exception(cause)
| 13
|
Kotlin
|
2
| 5
|
9c5b21f3e622741b9b4f5ae1b256242ba26d2efb
| 312
|
swedbank-pay-sdk-android
|
Apache License 2.0
|
app/app/src/main/java/com/substandard/waiter/ui/main/MainViewModel.kt
|
sub-standard
| 217,688,634
| false
|
{"Python": 115518, "JavaScript": 10131, "Kotlin": 10114, "HTML": 1705}
|
package com.substandard.waiter.ui.main
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.substandard.waiter.Drinks
import com.substandard.waiter.MongoClient
import com.uriio.beacons.model.iBeacon
import kotlinx.coroutines.*
import kotlinx.coroutines.Dispatchers.IO
import org.bson.types.ObjectId
class MainViewModel : ViewModel() {
private val id = "abcdefghijklmnop"
private var orderDrinks: Drinks? = null
private var orderId: String? = null
private val beacon =
iBeacon(id.toByteArray(), 0, 0, "wAIter")
private val mongo = MongoClient()
private val _status = MutableLiveData("none")
val status: LiveData<String> = _status
fun startBeacon() = beacon.start()
fun stopBeacon() = beacon.stop()
fun setOrder(order: Drinks) {
orderDrinks = order
}
fun getOrder(): Drinks? {
return orderDrinks
}
fun orderDelivered() {
stopBeacon()
mongo.client.callFunction("set_delivered", listOf(orderId)).addOnCompleteListener {
_status.postValue("delivered")
}
}
// send a signal to database
fun createOrder() {
mongo.client.callFunction<String>(
"new_order"
, listOf(when(orderDrinks) {
Drinks.SOTB -> "Sex on the Beach"
Drinks.AS -> "Aperol Spritz"
Drinks.BL -> "Blue Lagoon"
Drinks.BM -> "Bloody Mary"
Drinks.MJ -> "Mojito"
Drinks.MT -> "Mai Tai"
Drinks.PR -> "Purple Rain"
Drinks.WM -> "Watermelon Margarita"
else -> null
}), String::class.java
)
.addOnCompleteListener {
orderId = it.result
viewModelScope.launch {
pollOrder()
}
}
}
fun checkOrder() {
mongo.client.callFunction<String>(
"get_order_status"
, listOf(ObjectId(orderId)), String::class.java
)
.addOnCompleteListener {
_status.postValue(it.result)
Log.d("status", it.result)
}
}
suspend fun pollOrder() = Dispatchers.IO {
while (status.value != "sending") {
delay(2000)
checkOrder()
}
}
}
| 0
|
Python
|
1
| 4
|
0ba9e25fd9a9670261a237b7a1ebd5defe79a0ff
| 2,469
|
wAIter
|
MIT License
|
src/main/kotlin/com/kenkoro/taurus/api/client/core/plugins/Routing.kt
|
kenkoro
| 752,573,952
| false
|
{"Kotlin": 62812, "Shell": 645}
|
package com.kenkoro.taurus.api.client.core.plugins
import com.kenkoro.taurus.api.client.controllers.CutOrderControllerImpl
import com.kenkoro.taurus.api.client.controllers.OrderControllerImpl
import com.kenkoro.taurus.api.client.controllers.UserControllerImpl
import io.ktor.server.application.Application
fun Application.configureRouting() {
// For testing purposes
val isUnderTest = SutService.get()
val userController = UserControllerImpl()
val orderController = OrderControllerImpl()
val cutOrderController = CutOrderControllerImpl()
configureAuthRouting(userController)
configureUserRouting(userController)
configureOrderRouting(userController, orderController)
configureCutOrderRouting(cutOrderController)
}
| 1
|
Kotlin
|
0
| 3
|
ef428e9d3306c422e6f9f1f25c24bebfe0aa4614
| 736
|
taurus-backend
|
Apache License 2.0
|
app/src/main/java/com/example/weatherlicious/data/model/currentweather/Condition.kt
|
agul1no
| 513,198,414
| false
|
{"Kotlin": 108184}
|
package com.example.weatherlicious.data.model.currentweather
data class Condition(
val text: String,
val icon: String,
val code: Int
)
| 6
|
Kotlin
|
0
| 1
|
f8cba961c67876675f29dcfb0040e2ed4522e0e9
| 147
|
Weatherlicious
|
MIT License
|
app/src/main/java/com/nullpointer/nullsiteadmin/ui/screens/home/viewModel/HomeViewModel.kt
|
Hcnc100
| 506,449,303
| false
|
{"Kotlin": 364704}
|
package com.nullpointer.nullsiteadmin.ui.screens.home.viewModel
import androidx.lifecycle.ViewModel
import com.nullpointer.nullsiteadmin.core.utils.launchSafeIO
import com.nullpointer.nullsiteadmin.domain.auth.AuthRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class HomeViewModel @Inject constructor(
private val authRepository: AuthRepository
) : ViewModel() {
init {
verifyPhoneData()
}
fun logout() = launchSafeIO {
authRepository.logout()
}
private fun verifyPhoneData() = launchSafeIO {
authRepository.verifyInfoPhoneData()
}
}
| 0
|
Kotlin
|
1
| 2
|
5fec4c0e845a008feda27826f2dfea6b731d710f
| 647
|
NullSiteApp
|
MIT License
|
app/src/main/kotlin/com/goodwy/keyboard/app/ext/ExtensionHomeScreen.kt
|
Goodwy
| 811,363,624
| false
|
{"Kotlin": 2084011, "Python": 12567, "Nix": 2785, "CMake": 1970, "Rust": 330, "C": 34, "Shell": 10}
|
package com.goodwy.keyboard.app.ext
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.Input
import androidx.compose.material.icons.filled.Keyboard
import androidx.compose.material.icons.filled.Language
import androidx.compose.material.icons.filled.Palette
import androidx.compose.material.icons.filled.Shop
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.goodwy.keyboard.BuildConfig
import com.goodwy.keyboard.R
import com.goodwy.keyboard.app.LocalNavController
import com.goodwy.keyboard.app.Routes
import com.goodwy.keyboard.extensionManager
import com.goodwy.keyboard.lib.util.launchUrl
import com.goodwy.keyboard.lib.compose.FlorisOutlinedBox
import com.goodwy.keyboard.lib.compose.FlorisScreen
import com.goodwy.keyboard.lib.compose.FlorisTextButton
import com.goodwy.keyboard.lib.compose.defaultFlorisOutlinedBox
import com.goodwy.keyboard.lib.compose.stringRes
import dev.patrickgold.jetpref.datastore.ui.Preference
import dev.patrickgold.jetpref.datastore.ui.PreferenceGroup
@Composable
fun ExtensionHomeScreen() = FlorisScreen {
title = stringRes(R.string.ext__home__title)
previewFieldVisible = false
val context = LocalContext.current
val navController = LocalNavController.current
val extensionManager by context.extensionManager()
val extensionIndex = extensionManager.combinedExtensionList()
content {
FlorisOutlinedBox(
modifier = Modifier.defaultFlorisOutlinedBox(),
) {
Text(
modifier = Modifier.padding(start = 16.dp, top = 8.dp, end = 16.dp, bottom = 4.dp),
text = stringRes(id = R.string.ext__home__info),
style = MaterialTheme.typography.bodySmall,
)
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 6.dp),
) {
FlorisTextButton(
onClick = {
context.launchUrl("https://${BuildConfig.FLADDONS_STORE_URL}/")
},
icon = Icons.Default.Shop,
text = stringRes(id = R.string.ext__home__visit_store),
)
Spacer(modifier = Modifier.weight(1f))
FlorisTextButton(
onClick = {
navController.navigate(Routes.Ext.Import(ExtensionImportScreenType.EXT_ANY, null))
},
icon = Icons.AutoMirrored.Filled.Input,
text = stringRes(R.string.action__import),
)
}
}
UpdateBox(extensionIndex = extensionIndex)
PreferenceGroup(title = stringRes(id = R.string.ext__home__visit_store)) {
Preference(
icon = Icons.Default.Palette,
title = stringRes(R.string.ext__list__ext_theme),
onClick = {
navController.navigate(Routes.Ext.List(ExtensionListScreenType.EXT_THEME,false))
},
)
Preference(
icon = Icons.Default.Keyboard,
title = stringRes(R.string.ext__list__ext_keyboard),
onClick = {
navController.navigate(Routes.Ext.List(ExtensionListScreenType.EXT_KEYBOARD,false))
},
)
Preference(
icon = Icons.Default.Language,
title = stringRes(R.string.ext__list__ext_languagepack),
onClick = {
navController.navigate(Routes.Ext.List(ExtensionListScreenType.EXT_LANGUAGEPACK,false))
},
)
}
}
}
| 1
|
Kotlin
|
1
| 7
|
472b7eb1a9efcf6e12e55474698f7cc3254c1341
| 4,129
|
Keyboard
|
Apache License 2.0
|
src/main/kotlin/org/jetbrains/plugins/rsocket/restClient/execution/RSocketRequest.kt
|
servicex-sh
| 433,655,998
| false
|
{"Kotlin": 77305, "HTML": 234}
|
package org.jetbrains.plugins.rsocket.restClient.execution
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.intellij.httpClient.execution.common.CommonClientRequest
import com.intellij.util.queryParameters
import io.rsocket.metadata.WellKnownMimeType
import java.net.URI
import java.util.*
@Suppress("UnstableApiUsage")
class RSocketRequest(override val URL: String?, override val httpMethod: String?, override val textToSend: String?, val headers: Map<String, String>) : CommonClientRequest {
val rsocketURI: URI
val dataMimeType: String
val metadataMimeType: String
val setupData: String?
val setupMetadata: String?
val metadata: String?
val acceptMimeType: String?
val authorization: String?
val userAgent: String?
val bodyText: String?
var graphqlOperationName = "request"
init {
rsocketURI = URI.create(URL!!)
this.metadataMimeType = headers["Metadata-Type"] ?: WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.string
authorization = headers["Authorization"]
userAgent = headers["User-Agent"]
acceptMimeType = headers["Accept"]
setupMetadata = headers["Setup-Metadata"]
setupData = headers["Setup-Data"]
metadata = headers["Metadata"]
// graphql convert https://github.com/spring-projects/spring-graphql/issues/339
var tempDataMimeType = headers["Content-Type"]
var tempBody = textToSend ?: ""
//GraphQL over RSocket
if (httpMethod == "GRAPHQL") {
val objectMapper = ObjectMapper()
tempDataMimeType = tempDataMimeType ?: "application/graphql"
if (tempDataMimeType == "application/graphql") {
if (tempBody.startsWith("subscription")) {
graphqlOperationName = "subscription"
}
val jsonRequest = mutableMapOf<String, Any>()
jsonRequest["query"] = tempBody
// check body + variables json
val offset1 = tempBody.lastIndexOf('{')
val offset2 = tempBody.lastIndexOf('}')
if (offset2 > offset1) {
val jsonText = tempBody.substring(offset1, offset2 + 1)
if (jsonText.contains('"')) {
try {
jsonRequest["variables"] = objectMapper.readValue(jsonText, Map::class.java)
jsonRequest["query"] = tempBody.subSequence(0, offset1)
} catch (ignore: Exception) {
}
}
}
val graphqlVariables = getHeadValue("x-graphql-variables")
if (graphqlVariables != null) {
jsonRequest["variables"] = objectMapper.readValue(graphqlVariables, Map::class.java)
}
tempBody = objectMapper.writeValueAsString(jsonRequest)
tempDataMimeType = "application/json"
} else if (tempDataMimeType.contains("json")) { // application/graphql+json is not well-known type now
tempDataMimeType = "application/json"
val document = objectMapper.readValue<Map<String, Any>>(tempBody)
if (document.contains("query")) {
if (document["query"].toString().contains("subscription")) {
graphqlOperationName = "subscription"
}
}
}
}
this.dataMimeType = tempDataMimeType ?: WellKnownMimeType.APPLICATION_JSON.string
this.bodyText = tempBody
}
fun routingMetadata(): List<String> {
var path = rsocketURI.path ?: ""
if (rsocketURI.scheme.contains("+ws")) {
val endpointPath = getWebSocketEndpointPath(rsocketURI.toString())
if (endpointPath.isNotEmpty()) {
path = path.substring(endpointPath.length)
}
}
if (path.startsWith("/")) {
path = path.substring(1)
}
val routing = mutableListOf(path);
val params = rsocketURI.queryParameters
if (params.isNotEmpty()) {
params.forEach { (key, value) -> routing.add("${key}=${value}") }
}
return routing
}
fun acceptMimeTypeHint(): String {
return acceptMimeType ?: dataMimeType
}
fun isAliBroker(): Boolean {
return this.headers.contains("X-AliBroker")
}
fun isSpringBroker(): Boolean {
return this.headers.contains("X-ServiceName")
}
fun getWebsocketRequestURI(): URI {
var connectionURL = rsocketURI.toString()
if (connectionURL.startsWith("rsocket+ws")) { //rsocket as ws path
connectionURL = connectionURL.substring(8)
// for example: ws://127.0.0.1:8080/rsocket/demo
val endpointPath = getWebSocketEndpointPath(connectionURL)
if (endpointPath.isNotEmpty()) {
connectionURL = connectionURL.substring(0, connectionURL.indexOf(endpointPath) + endpointPath.length)
}
}
return URI.create(connectionURL)
}
private fun getWebSocketEndpointPath(url: String): String {
val offset1 = if (url.startsWith("rsocket+")) {
url.indexOf('/', 15)
} else {
url.indexOf('/', 7)
}
if (offset1 > 0) {
val offset2 = url.indexOf('/', offset1 + 1)
if (offset2 < 0) {
return url.substring(offset1)
} else {
return url.substring(offset1, offset2)
}
}
return ""
}
fun body(): ByteArray {
return if (bodyText == null) {
ByteArray(0)
} else if (bodyText.startsWith("data:")) {
val base64Text = bodyText.substring(bodyText.indexOf(",") + 1).trim()
Base64.getDecoder().decode(base64Text)
} else {
if (dataMimeType.startsWith("application/json") && bodyText.startsWith("\"")) {
bodyText.trim('"').toByteArray(Charsets.UTF_8)
} else {
bodyText.toByteArray(Charsets.UTF_8)
}
}
}
fun textToBytes(text: String?): ByteArray {
return if (text == null) {
ByteArray(0)
} else if (text.startsWith("data:")) {
val base64Text = text.substring(text.indexOf(",") + 1).trim()
Base64.getDecoder().decode(base64Text);
} else {
text.toByteArray(Charsets.UTF_8)
}
}
private fun getHeadValue(name: String): String? {
for (header in headers) {
if (header.key.lowercase() == name) {
return header.value
}
}
return null
}
}
| 2
|
Kotlin
|
2
| 8
|
3da7e0343096f0d8b0b7d76b27f4d9291ee4e9b8
| 6,851
|
rsocket-jetbrains-plugin
|
Apache License 2.0
|
src/linuxX64Main/kotlin/org/guiVista/gui/widget/tool/tool_bar.kt
|
gui-vista
| 331,127,836
| false
| null |
package org.guiVista.gui.widget.tool
import glib2.FALSE
import glib2.TRUE
import gtk3.*
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.reinterpret
import org.guiVista.gui.layout.Container
import org.guiVista.gui.widget.tool.item.ToolItem
import org.guiVista.gui.widget.tool.item.ToolItemBase
public actual class ToolBar(toolBarPtr: CPointer<GtkToolbar>? = null) : Container, ToolShell {
override val gtkWidgetPtr: CPointer<GtkWidget>? = toolBarPtr?.reinterpret() ?: gtk_toolbar_new()
override val gtkToolShellPtr: CPointer<GtkToolShell>?
get() = gtkWidgetPtr?.reinterpret()
public val gtkToolBarPtr: CPointer<GtkToolbar>?
get() = gtkWidgetPtr?.reinterpret()
public actual val totalItems: Int
get() = gtk_toolbar_get_n_items(gtkToolBarPtr)
/**
* The size of the icons in a [ToolBar] is normally determined by the [iconSize] setting. When this property is set
* it overrides the setting. This should only be used for special-purpose toolbars. Normal application toolbars
* should respect the user preferences for the size of icons. Default value
* is *GtkIconSize.GTK_ICON_SIZE_LARGE_TOOLBAR*.
*/
override var iconSize: GtkIconSize
get() = gtk_toolbar_get_icon_size(gtkToolBarPtr)
set(value) = gtk_toolbar_set_icon_size(gtkToolBarPtr, value)
public actual var showArrow: Boolean
get() = gtk_toolbar_get_show_arrow(gtkToolBarPtr) == TRUE
set(value) = gtk_toolbar_set_show_arrow(gtkToolBarPtr, if (value) TRUE else FALSE)
/** How to draw the toolbar. Default value is *GtkToolbarStyle.GTK_TOOLBAR_BOTH_HORIZ*. */
public var toolBarStyle: GtkToolbarStyle
get() = gtk_toolbar_get_style(gtkToolBarPtr)
set(value) = gtk_toolbar_set_style(gtkToolBarPtr, value)
public actual fun unsetStyle() {
gtk_toolbar_unset_style(gtkToolBarPtr)
}
public actual fun insert(item: ToolItemBase, pos: Int) {
gtk_toolbar_insert(toolbar = gtkToolBarPtr, item = item.gtkToolItemPtr, pos = pos)
}
public actual fun fetchItemIndex(item: ToolItemBase): Int =
gtk_toolbar_get_item_index(gtkToolBarPtr, item.gtkToolItemPtr)
/**
* Fetches the item by [position][pos] on the [ToolBar], or *null* if the [ToolBar] doesn't contain the item.
* @param pos The position on the [ToolBar].
* @return The [item][ToolItem] on the [ToolBar], or *null* if the item doesn't exist at the [position][pos] on
* the [ToolBar].
*/
public fun fetchItemAtPosition(pos: Int): ToolItem? {
val toolItemPtr = gtk_toolbar_get_nth_item(gtkToolBarPtr, pos)
return if (toolItemPtr != null) ToolItem(toolItemPtr) else null
}
public actual fun fetchDropIndex(x: Int, y: Int): Int =
gtk_toolbar_get_drop_index(toolbar = gtkToolBarPtr, x = x, y = y)
public actual fun changeDropHighlightItem(toolItem: ToolItemBase, index: Int) {
gtk_toolbar_set_drop_highlight_item(toolbar = gtkToolBarPtr, tool_item = toolItem.gtkToolItemPtr,
index_ = index)
}
public actual fun unsetIconSize() {
gtk_toolbar_unset_icon_size(gtkToolBarPtr)
}
}
public fun toolBarWidget(toolBarPtr: CPointer<GtkToolbar>? = null, init: ToolBar.() -> Unit): ToolBar {
val toolBar = ToolBar(toolBarPtr)
toolBar.init()
return toolBar
}
| 0
|
Kotlin
|
0
| 0
|
484e1e8437a3d57faaf5667489d622402fe7be01
| 3,353
|
guivista-gui
|
Apache License 2.0
|
app/src/main/java/com/example/hrmaster/app/di/SignUpViewModel.kt
|
wildan29
| 814,681,005
| false
|
{"Kotlin": 54093}
|
package com.example.hrmaster.app.di
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.hrmaster.data.models.request.UserRegisterRequest
import com.example.hrmaster.data.models.response.UserRegisterResponse
import com.example.hrmaster.data.repo.MainRepo
import com.example.hrmaster.domain.models.Resource
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import org.json.JSONObject
import javax.inject.Inject
@HiltViewModel
class SignUpViewModel @Inject constructor(private val mainRepo: MainRepo) : ViewModel(){
private val _userSignUp =
MutableStateFlow<Resource<UserRegisterResponse>>(Resource.loading(null))
val userSignUp: StateFlow<Resource<UserRegisterResponse>>
get() = _userSignUp
// create shared flow for handling message
private val _message = MutableStateFlow("")
val message: SharedFlow<String>
get() = _message
fun add(request: UserRegisterRequest) = viewModelScope.launch {
_userSignUp.value = Resource.loading(null)
try {
mainRepo.userRegiser( request).let {
if (it.isSuccessful) {
_userSignUp.value = Resource.success(it.body())
} else {
val jsonObj =
JSONObject(it.errorBody()!!.charStream().readText()).getString("errors")
_message.value = jsonObj
_userSignUp.value = (Resource.error(it.errorBody().toString(), null))
}
}
} catch (e: Exception) {
_userSignUp.value = (Resource.error(e.message.toString(), null))
_message.value = e.message.toString()
e.printStackTrace()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
4c938902e7d842de0c49b4ac88ca11e7ea3f8b5a
| 1,949
|
HR-APP
|
MIT License
|
app/src/test/java/com/notisaver/database/AppTemplateTest.kt
|
Viet200103
| 724,431,957
| false
|
{"Kotlin": 453537}
|
package com.notisaver.database
import android.content.Context
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.notisaver.database.entities.AppMetaData
import com.notisaver.database.entities.ONotification
import com.notisaver.misc.createPackageHashcode
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import org.junit.After
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.annotation.Config
import java.io.IOException
@Config
@ExperimentalCoroutinesApi
@RunWith(AndroidJUnit4::class)
internal class AppTemplateTest {
private lateinit var repository: NotisaveRepository
private lateinit var db: NotisaveDatabase
@Before
fun setup() {
val context = ApplicationProvider.getApplicationContext<Context>()
db = Room.inMemoryDatabaseBuilder(
context, NotisaveDatabase::class.java
).build()
repository = NotisaveRepository(
context, db, UnconfinedTestDispatcher()
)
}
@Test
fun load_AppTemplate() = runTest(UnconfinedTestDispatcher()){
repository.logAppMetaData(
listOf(
AppMetaData(
packageHashcode = "com.test.template.1.hashcode",
packageName = "com.test.template.1"
),
AppMetaData(
packageHashcode = "com.test.template.2",
packageName = "com.test.template.2"
),
)
)
repository.logNotification(
ONotification(
sbnKeyHashcode = "hashcodeTest",
timePost = 1234567890,
logId = "logIdTest",
title = "Test",
contentText = "contentTest",
packageHashcode = "com.test.template.1.hashcode"
)
)
repository.logNotification(
ONotification(
sbnKeyHashcode = "hashcodeTest2",
timePost = 1234567890,
logId = "logIdTest2",
title = "Test2",
contentText = "contentTest2",
packageHashcode = "com.test.template.1.hashcode"
)
)
repository.loadAppTemplate().take(1).collect {
Assert.assertTrue(
it.size ==2
)
Assert.assertEquals(
it[0].aPackageHashcode, "com.test.template.1.hashcode"
)
Assert.assertEquals(
it[0].nCount,2
)
Assert.assertEquals(
it[1].nCount,0
)
}
}
@After
@Throws(IOException::class)
fun closeDb() {
db.close()
}
}
| 0
|
Kotlin
|
0
| 2
|
6b479442f63a0ce9314d7c8dc08870afd1787555
| 2,970
|
Notification-History-Android
|
MIT License
|
MomoPlants/src/main/kotlin/entities/PlantEntity.kt
|
Johnmorales26
| 614,629,687
| false
| null |
package entities
data class PlantEntity(
val id: Int,
val name: String,
val origin: String,
val weather: String,
val format: String,
val price: Int,
val stock: Int = 0,
var quantity: Int = 0
) {
fun totalPrice(): Int = quantity * price
}
| 0
|
Kotlin
|
0
| 0
|
91a7ffd66b34804f00a5ad9f72bd42db4d2f3e0c
| 274
|
Momo_Plants
|
W3C Software Notice and License (2002-12-31)
|
src/main/kotlin/com/xiangrui/doge/dogekt/middlewares/cors.kt
|
Xiangrui2019
| 207,785,056
| false
| null |
package com.xiangrui.doge.dogekt.middlewares
import com.xiangrui.doge.dogekt.conf.env
import io.ktor.application.Application
import io.ktor.application.install
import io.ktor.client.request.request
import io.ktor.features.CORS
import io.ktor.http.HttpMethod
import io.ktor.routing.Route
fun Route.Cors() {
install(CORS) {
method(HttpMethod.Get)
method(HttpMethod.Post)
method(HttpMethod.Put)
method(HttpMethod.Patch)
method(HttpMethod.Delete)
method(HttpMethod.Head)
if (env?.get("KTOR_MODE")!! == "debug") {
anyHost()
} else {
host(env?.get("CORS_DOMAIN")!!)
}
allowCredentials = true
allowNonSimpleContentTypes = true
}
}
| 0
|
Kotlin
|
0
| 2
|
6b71eaf2366a1fed7fa413cbfda906cd01ccec2d
| 748
|
dogekt
|
MIT License
|
demos/sandbox-appyx-navigation/common/src/commonMain/kotlin/com/bumble/appyx/demos/sandbox/navigation/Ext.kt
|
bumble-tech
| 493,334,393
| false
|
{"Kotlin": 829246, "Python": 2324, "HTML": 347, "Shell": 327, "CSS": 134}
|
package com.bumble.appyx.demos.sandbox.navigation
import com.bumble.appyx.demos.sandbox.navigation.ui.atomic_tangerine
import com.bumble.appyx.demos.sandbox.navigation.ui.manatee
import com.bumble.appyx.demos.sandbox.navigation.ui.md_amber_500
import com.bumble.appyx.demos.sandbox.navigation.ui.md_blue_500
import com.bumble.appyx.demos.sandbox.navigation.ui.md_blue_grey_500
import com.bumble.appyx.demos.sandbox.navigation.ui.md_cyan_500
import com.bumble.appyx.demos.sandbox.navigation.ui.md_grey_500
import com.bumble.appyx.demos.sandbox.navigation.ui.md_indigo_500
import com.bumble.appyx.demos.sandbox.navigation.ui.md_light_blue_500
import com.bumble.appyx.demos.sandbox.navigation.ui.md_light_green_500
import com.bumble.appyx.demos.sandbox.navigation.ui.md_lime_500
import com.bumble.appyx.demos.sandbox.navigation.ui.md_pink_500
import com.bumble.appyx.demos.sandbox.navigation.ui.md_teal_500
import com.bumble.appyx.demos.sandbox.navigation.ui.silver_sand
import com.bumble.appyx.demos.sandbox.navigation.ui.sizzling_red
val colors = listOf(
manatee,
sizzling_red,
atomic_tangerine,
silver_sand,
md_pink_500,
md_indigo_500,
md_blue_500,
md_light_blue_500,
md_cyan_500,
md_teal_500,
md_light_green_500,
md_lime_500,
md_amber_500,
md_grey_500,
md_blue_grey_500
)
| 85
|
Kotlin
|
54
| 997
|
f5cc89fbdf9a168a70f8e9f11313e6524914179a
| 1,335
|
appyx
|
Apache License 2.0
|
review-component/src/main/java/com/kotlin/android/review/component/item/adapter/ReviewShareBinder.kt
|
R-Gang-H
| 538,443,254
| false
| null |
package com.kotlin.android.review.component.item.adapter
import android.view.View
import com.kotlin.android.review.component.R
import com.kotlin.android.review.component.databinding.ItemReviewShareBinding
import com.kotlin.android.review.component.item.bean.ReviewShareItemViewBean
import com.kotlin.android.review.component.item.bean.ReviewShareItemViewBean.Companion.REVIEW_SHARE_PLATFORM_SWITCH
import com.kotlin.android.widget.adapter.multitype.adapter.binder.MultiTypeBinder
/**
* create by lushan on 2020/11/4
* description:分享的binder
*/
class ReviewShareBinder(var bean: ReviewShareItemViewBean) : MultiTypeBinder<ItemReviewShareBinding>() {
override fun layoutId(): Int {
return R.layout.item_review_share
}
override fun areContentsTheSame(other: MultiTypeBinder<*>): Boolean {
return other is ReviewShareBinder && other.bean != bean
}
override fun onClick(view: View) {
when (view.id) {
R.id.sharePlatTv -> {//如果是匿名,不需要交给上层处理
if (bean.platformId == REVIEW_SHARE_PLATFORM_SWITCH) {
bean.isOpen = !bean.isOpen
notifyAdapterSelfChanged()
}
super.onClick(view)
}
else -> {
super.onClick(view)
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
e63b1f9a28c476c1ce4db8d2570d43a99c0cdb28
| 1,320
|
Mtime
|
Apache License 2.0
|
core/jvm/main/kotlin/com/meowbase/toolkit/Any.kt
|
siylt007
| 336,180,880
| true
|
{"Kotlin": 1405824, "Java": 474434, "Dart": 14190, "HTML": 70}
|
@file:Suppress("NOTHING_TO_INLINE")
package com.meowbase.toolkit
import kotlin.reflect.KClass
/**
* 获得实例的 [KClass]
* @see javaClass
*/
inline val <T : Any> T.kotlinClass: KClass<T> get() = javaClass.kotlin
/** 获得实例的类名 */
inline val Any.className: String get() = javaClass.name
/** 判断实例的类名是否为 [comparedClassName] */
infix fun Any.typeIs(comparedClassName: String): Boolean = javaClass.name == comparedClassName
/** 判断实例的类型 [Class] 是否为 [comparedClass] */
infix fun Any.typeIs(comparedClass: Class<*>): Boolean = javaClass == comparedClass
/** 判断实例的类型 [KClass] 是否为 [comparedClass] */
infix fun Any.typeIs(comparedClass: KClass<*>): Boolean = javaClass.kotlin == comparedClass
/** 判断实例的类型是否为 [T] */
inline fun <reified T> Any.typeIs(): Boolean = javaClass.name == T::class.java.name
/** 判断实例是否为 null */
inline fun Any?.isNull(): Boolean = this == null
/** 判断实例是否不为 null */
inline fun Any?.isNotNull(): Boolean = this != null
| 0
| null |
0
| 0
|
df82f0588beb13fbd22308b3d015852c25781612
| 934
|
toolkit
|
Apache License 2.0
|
src/test/kotlin/me/peckb/aoc/_2016/calendar/day15/Day15Test.kt
|
peckb1
| 433,943,215
| false
|
{"Kotlin": 818902}
|
package me.peckb.aoc._2016.calendar.day15
import javax.inject.Inject
import me.peckb.aoc._2016.DaggerTestDayComponent
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
internal class Day15Test {
@Inject
lateinit var day15: Day15
@BeforeEach
fun setup() {
DaggerTestDayComponent.create().inject(this)
}
@Test
fun testDay15PartOne() {
assertEquals(203660, day15.partOne(DAY_15))
}
@Test
fun testDay15PartTwo() {
assertEquals(2408135, day15.partTwo(DAY_15))
}
companion object {
private const val DAY_15: String = "advent-of-code-input/2016/day15.input"
}
}
| 0
|
Kotlin
|
1
| 4
|
5507219c37a97500eed6e455520038549237b504
| 682
|
advent-of-code
|
MIT License
|
solar/src/main/java/com/chiksmedina/solar/boldduotone/school/CaseMinimalistic.kt
|
CMFerrer
| 689,442,321
| false
|
{"Kotlin": 36591890}
|
package com.chiksmedina.solar.boldduotone.school
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.chiksmedina.solar.boldduotone.SchoolGroup
val SchoolGroup.CaseMinimalistic: ImageVector
get() {
if (_caseMinimalistic != null) {
return _caseMinimalistic!!
}
_caseMinimalistic = Builder(
name = "CaseMinimalistic", 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 = EvenOdd
) {
moveTo(10.5812f, 2.25f)
lineTo(10.5608f, 2.25f)
curveTo(10.4473f, 2.25f, 10.359f, 2.25f, 10.2754f, 2.255f)
curveTo(9.2149f, 2.3193f, 8.2864f, 2.9885f, 7.8901f, 3.9743f)
curveTo(7.8587f, 4.0524f, 7.807f, 4.2076f, 7.7701f, 4.3183f)
lineTo(7.7662f, 4.3299f)
curveTo(7.6631f, 4.6098f, 7.477f, 4.8522f, 7.2614f, 5.0253f)
curveTo(7.034f, 5.0327f, 6.8167f, 5.0422f, 6.609f, 5.0545f)
curveTo(4.9651f, 5.1514f, 3.9218f, 5.4212f, 3.1714f, 6.1716f)
curveTo(2.9268f, 6.4162f, 2.7332f, 6.692f, 2.5801f, 7.0097f)
curveTo(2.6377f, 7.0293f, 2.6937f, 7.0563f, 2.7471f, 7.091f)
curveTo(4.8474f, 8.4562f, 6.167f, 9.3101f, 7.2634f, 9.8579f)
curveTo(7.3299f, 9.5117f, 7.6344f, 9.2501f, 8.0f, 9.2501f)
curveTo(8.4142f, 9.2501f, 8.75f, 9.5859f, 8.75f, 10.0001f)
verticalLineTo(10.458f)
curveTo(10.8694f, 11.0976f, 13.1305f, 11.0976f, 15.25f, 10.458f)
verticalLineTo(10.0001f)
curveTo(15.25f, 9.5859f, 15.5858f, 9.2501f, 16.0f, 9.2501f)
curveTo(16.3656f, 9.2501f, 16.6701f, 9.5117f, 16.7365f, 9.8579f)
curveTo(17.833f, 9.3102f, 19.1526f, 8.4562f, 21.253f, 7.091f)
curveTo(21.3063f, 7.0564f, 21.3623f, 7.0294f, 21.4197f, 7.0097f)
curveTo(21.2666f, 6.6921f, 21.073f, 6.4163f, 20.8283f, 6.1716f)
curveTo(20.078f, 5.4212f, 19.0347f, 5.1514f, 17.3907f, 5.0545f)
curveTo(17.1936f, 5.0428f, 16.9878f, 5.0337f, 16.7728f, 5.0265f)
curveTo(16.7593f, 5.0155f, 16.7457f, 5.0041f, 16.7321f, 4.9923f)
curveTo(16.4914f, 4.7843f, 16.3032f, 4.5101f, 16.2083f, 4.2529f)
lineTo(16.2052f, 4.2434f)
curveTo(16.1693f, 4.1358f, 16.1414f, 4.0519f, 16.1101f, 3.9743f)
curveTo(15.7139f, 2.9885f, 14.7853f, 2.3193f, 13.7248f, 2.255f)
curveTo(13.6412f, 2.25f, 13.5529f, 2.25f, 13.4394f, 2.25f)
lineTo(10.5812f, 2.25f)
close()
moveTo(14.8175f, 4.8157f)
lineTo(14.813f, 4.805f)
lineTo(14.8081f, 4.7929f)
lineTo(14.8035f, 4.7809f)
lineTo(14.7999f, 4.771f)
lineTo(14.7981f, 4.766f)
lineTo(14.7939f, 4.7537f)
lineTo(14.7901f, 4.7424f)
lineTo(14.788f, 4.7362f)
lineTo(14.7852f, 4.7278f)
lineTo(14.783f, 4.7208f)
lineTo(14.7812f, 4.7151f)
curveTo(14.7418f, 4.5971f, 14.7297f, 4.562f, 14.7184f, 4.5338f)
curveTo(14.5383f, 4.0857f, 14.1162f, 3.7815f, 13.6342f, 3.7523f)
curveTo(13.6019f, 3.7503f, 13.5623f, 3.75f, 13.419f, 3.75f)
horizontalLineTo(10.5812f)
curveTo(10.4379f, 3.75f, 10.3983f, 3.7503f, 10.3661f, 3.7523f)
curveTo(9.8841f, 3.7815f, 9.4621f, 4.0856f, 9.2819f, 4.5335f)
lineTo(9.2793f, 4.5405f)
lineTo(9.2713f, 4.5624f)
curveTo(9.2647f, 4.581f, 9.2566f, 4.6043f, 9.2473f, 4.6316f)
curveTo(9.2308f, 4.6799f, 9.2122f, 4.7355f, 9.1934f, 4.7919f)
lineTo(9.1916f, 4.7978f)
lineTo(9.1893f, 4.8048f)
lineTo(9.1866f, 4.8131f)
lineTo(9.1845f, 4.8194f)
lineTo(9.1807f, 4.8307f)
lineTo(9.1764f, 4.8429f)
lineTo(9.1747f, 4.848f)
lineTo(9.171f, 4.8579f)
lineTo(9.1664f, 4.8699f)
lineTo(9.1616f, 4.882f)
lineTo(9.1574f, 4.8919f)
lineTo(9.1567f, 4.8934f)
curveTo(9.1428f, 4.9292f, 9.1281f, 4.965f, 9.1125f, 5.0006f)
curveTo(9.3961f, 5.0f, 9.6917f, 5.0f, 9.9999f, 5.0f)
horizontalLineTo(13.9999f)
curveTo(14.3114f, 5.0f, 14.61f, 5.0f, 14.8964f, 5.0007f)
curveTo(14.8679f, 4.9396f, 14.8416f, 4.8778f, 14.8175f, 4.8157f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, fillAlpha = 0.5f, strokeAlpha
= 0.5f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(2.1621f, 8.4995f)
curveTo(2.0f, 9.6033f, 2.0f, 11.0494f, 2.0f, 12.9998f)
curveTo(2.0f, 16.7711f, 2.0f, 18.6567f, 3.1716f, 19.8283f)
curveTo(4.3432f, 20.9998f, 6.2288f, 20.9998f, 10.0f, 20.9998f)
horizontalLineTo(14.0f)
curveTo(17.7712f, 20.9998f, 19.6569f, 20.9998f, 20.8284f, 19.8283f)
curveTo(22.0f, 18.6567f, 22.0f, 16.7711f, 22.0f, 12.9998f)
curveTo(22.0f, 11.0495f, 22.0f, 9.6035f, 21.8379f, 8.4997f)
curveTo(19.5613f, 9.9795f, 18.1021f, 10.9233f, 16.7501f, 11.5045f)
verticalLineTo(11.9999f)
curveTo(16.7501f, 12.4141f, 16.4143f, 12.7499f, 16.0001f, 12.7499f)
curveTo(15.5914f, 12.7499f, 15.259f, 12.423f, 15.2503f, 12.0163f)
curveTo(13.12f, 12.5779f, 10.8802f, 12.5779f, 8.7499f, 12.0163f)
curveTo(8.7412f, 12.4229f, 8.4088f, 12.7499f, 8.0001f, 12.7499f)
curveTo(7.5859f, 12.7499f, 7.2501f, 12.4141f, 7.2501f, 11.9999f)
verticalLineTo(11.5044f)
curveTo(5.898f, 10.9232f, 4.4388f, 9.9794f, 2.1621f, 8.4995f)
close()
}
}
.build()
return _caseMinimalistic!!
}
private var _caseMinimalistic: ImageVector? = null
| 0
|
Kotlin
|
0
| 0
|
3414a20650d644afac2581ad87a8525971222678
| 7,126
|
SolarIconSetAndroid
|
MIT License
|
project/kimmer/src/main/kotlin/org/babyfish/kimmer/Creator.kt
|
babyfish-ct
| 447,936,858
| false
| null |
package org.babyfish.kimmer
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.withContext
import org.babyfish.kimmer.runtime.AsyncDraftContext
import org.babyfish.kimmer.runtime.DraftSpi
import org.babyfish.kimmer.runtime.SyncDraftContext
import java.lang.UnsupportedOperationException
import kotlin.coroutines.AbstractCoroutineContextElement
import kotlin.coroutines.CoroutineContext
import kotlin.reflect.KClass
/**
* Create new immutable data by original data and user code
*
* Example:
* ```
* fun test() {
* // 1. Create object
* val book = new(Book::class).by {
* name = "The book"
* store().name = "The store"
* authors() += new(Book::class).by {
* name = "The first author"
* }
* authors() += new(Book::class).by {
* name = "The second author"
* }
* }
*
* // 2. Create a new object based on the current object.
* // This is the core value of *kimmer*.
* val book2 = new(Book::class).by(book) {
* name += "!"
* sotre().name += "!"
* for (author in authors()) {
* author.name += "!"
* }
* }
* }
* ```
*
* @param type The immutable interface type
* @return The helper object with the API generated by *kimmer-ksp*,
* it's inline-class so that there is no unnecessary cost.
*/
inline fun<T: Immutable> new(type: KClass<T>): SyncCreator<T> =
SyncCreator(type)
/**
* Create new immutable data by original data and asynchronous user code
*
* Example:
* ```
* suspend fun testAsync() {
* // 1. Create object
* val book = newAsync(Book::class).by {
* delay(100)
* name = "The book"
* store().name = "The store"
* authors() += newAsync(Book::class).by {
* delay(100)
* name = "The first author"
* }
* authors() += newAsync(Book::class).by {
* delay(100)
* name = "The second author"
* }
* }
*
* // 2. Create a new object based on the current object.
* // This is the core value of *kimmer*.
* val book2 = newAsync(Book::class).by(book) {
* delay(100)
* name += "!"
* sotre().name += "!"
* for (author in authors()) {
* author.name += "!"
* }
* }
* }
* ```
*
* @param type The immutable interface type
* @return The helper object with the API generated by *kimmer-ksp*,
* it's inline-class so that there is no unnecessary cost.
*/
inline fun<T: Immutable> newAsync(type: KClass<T>): AsyncCreator<T> =
AsyncCreator(type)
/**
* The object of this class is return by the function[new].
*
* it's helper object with the API generated by *kimmer-ksp*,
* this class is inline so that there is no unnecessary cost.
*/
@JvmInline
value class SyncCreator<T: Immutable>(
val type: KClass<T>
)
/**
* The object of this class is return by the function[newAsync].
*
* it's helper object with the API generated by *kimmer-ksp*,
* this class is inline so that there is no unnecessary cost.
*/
@JvmInline
value class AsyncCreator<T: Immutable>(
val type: KClass<T>
)
/**
* The object of this class is return by the function[SyncDraft.new].
*
* it's helper object with the API generated by *kimmer-ksp*,
* this class is inline so that there is no unnecessary cost.
*/
@JvmInline
value class SyncDraftCreator<T: Immutable>(
val type: KClass<T>
)
/**
* The object of this class is return by the function[AsyncDraft.newAsync].
*
* it's helper object with the API generated by *kimmer-ksp*,
* this class is inline so that there is no unnecessary cost.
*/
@JvmInline
value class AsyncDraftCreator<T: Immutable>(
val type: KClass<T>
)
/**
* Create new data by old data and user code.
*
* In general, developer will not call this function directly.
* *kimmer-ksp* will generate more friendly inline functions to wrap it.
*
* @param type The immutable interface type
* @param base The original immutable data, this function creates new data based on it.
* If it's null, that means to create data from scratch.
* @param block The user code to modify the draft object.
* @return The new immutable data.
*/
fun <T: Immutable> produce(
type: KClass<T>,
base: T? = null,
block: Draft<T>.() -> Unit
): T =
draftContextLocal
.get()
?.let {
it.createDraft(type, base).apply {
block()
} as T
} ?: SyncDraftContext()
.let {
draftContextLocal.set(it)
try {
it.createDraft(type, base).let { draft ->
draft.block()
(draft as DraftSpi).`{resolve}`() as T
} as T
} finally {
draftContextLocal.remove()
}
}
/**
*
* Create new draft by old data and user code.
*
* - In general, developer will not call this function directly.
* *kimmer-ksp* will generate more friendly inline functions to wrap it.
*
* - This function can only be called in the lambda of [produce],
* otherwise, an [UnsupportedOperationException] will be raised.
*
* @param type The immutable interface type
* @param base The original immutable data, this function creates new data based on it.
* If it's null, that means to create data from scratch.
* @param block The user code to modify the draft object.
* @return The new mutable draft.
* @exception UnsupportedOperationException This function isn't called under the lambda of [produce]
*/
fun <T: Immutable, D: SyncDraft<T>> produceDraft(
type: KClass<T>,
base: T? = null,
block: D.() -> Unit
): D =
draftContextLocal
.get()
?.let {
val draft = it.createDraft(type, base) as D
draft.block()
return draft
} ?: throw UnsupportedOperationException(
"'produceDraft' can only be used in the lambda of 'produce'"
)
private val draftContextLocal = ThreadLocal<SyncDraftContext>()
/**
* Create new data by old data and asynchronous user code.
*
* In general, developer will not call this function directly.
* *kimmer-ksp* will generate more friendly inline functions to wrap it.
*
* @param type The immutable interface type
* @param base The original immutable data, this function creates new data based on it.
* If it's null, that means to create data from scratch.
* @param block The user code to modify the draft object.
* @return The new immutable data.
*/
suspend fun <T: Immutable> produceAsync(
type: KClass<T>,
base: T? = null,
block: suspend Draft<T>.() -> Unit
): T =
currentCoroutineContext()[DraftContextElement]?.ctx?.let {
it.createDraft(type, base).apply {
block()
} as T
} ?: AsyncDraftContext().let {
withContext(DraftContextElement(it)) {
it.createDraft(type, base).let { draft ->
draft.block()
(draft as DraftSpi).`{resolve}`() as T
}
}
}
/**
* Create new draft by old data and asynchronous user code.
*
* - In general, developer will not call this function directly.
* *kimmer-ksp* will generate more friendly inline functions to wrap it.
*
* - This function can only be called in the lambda of [produceAsync],
* otherwise, an [UnsupportedOperationException] will be raised.
*
* @param type The immutable interface type
* @param base The original immutable data, this function creates new data based on it.
* If it's null, that means to create data from scratch.
* @param block The user code to modify the draft object.
* @return The new mutable draft.
* @exception UnsupportedOperationException This function isn't called under the lambda of [produceAsync]
*/
suspend fun <T: Immutable, D: AsyncDraft<T>> produceDraftAsync(
type: KClass<T>,
base: T? = null,
block: suspend D.() -> Unit
): D =
currentCoroutineContext()[DraftContextElement]
?.let { it.ctx }
?.let {
val draft = it.createDraft(type, base) as D
draft.block()
return draft
} ?: throw UnsupportedOperationException(
"'produceDraftAsync' can only be used in the lambda of 'produceAsync'"
)
private data class DraftContextElement(
val ctx: AsyncDraftContext
) : AbstractCoroutineContextElement(DraftContextElement) {
companion object Key : CoroutineContext.Key<DraftContextElement>
}
| 0
|
Kotlin
|
0
| 25
|
fe1b92b7fb5c3ac27557a8de4368cbef698f3fac
| 8,521
|
kimmer
|
MIT License
|
kmprevenuecat-purchases/src/commonMain/kotlin/com/mmk/kmprevenuecat/purchases/KMPRevenueCatAnnotations.kt
|
mirzemehdi
| 760,892,738
| false
|
{"Kotlin": 33682, "Ruby": 4656, "Swift": 1016}
|
package com.mmk.kmprevenuecat.purchases
/**
* KMPRevenueCatInternalApi Annotation class that limits access for internal usage
*/
@RequiresOptIn(
message = "This is internal API for KMPRevenueCat. This shouldn't be used outside of KMPRevenueCat API",
level = RequiresOptIn.Level.ERROR
)
@Retention(AnnotationRetention.BINARY)
@Target(
AnnotationTarget.CLASS,
AnnotationTarget.FUNCTION,
AnnotationTarget.FIELD,
AnnotationTarget.PROPERTY
)
public annotation class KMPRevenueCatInternalApi
| 1
|
Kotlin
|
1
| 7
|
1b8661e58c733f94fc09e537e9bbbfc727c79257
| 512
|
KMPRevenueCat
|
Apache License 2.0
|
QuantasPessoasTemMeuNome/app/src/main/java/com/example/quantaspessoastemmeunome22101195/dadosremotos/NomesAPIService.kt
|
RafaCaire1507
| 759,526,248
| false
|
{"Kotlin": 24221, "Java": 4506}
|
package com.example.quantaspessoastemmeunome22101195.dadosremotos
import retrofit2.http.GET
import retrofit2.http.Path
interface NomesAPIService {
@GET("{nome}")
fun getFrequenciaNomePorDecada(@Path("nome") nome : String) : retrofit2.Call<List<RespostaNome>>
}
| 0
|
Kotlin
|
0
| 0
|
a99b4c635fb6bea39df00e33c28c1591ead02f2d
| 271
|
Android
|
MIT License
|
src/jvmMain/kotlin/acidicoala/koalageddon/core/ui/composable/ConfirmationDialog.kt
|
acidicoala
| 584,899,259
| false
| null |
package acidicoala.koalageddon.core.ui.composable
import acidicoala.koalageddon.core.model.OpenState
import acidicoala.koalageddon.core.ui.composition.LocalStrings
import acidicoala.koalageddon.core.ui.theme.DefaultMaxWidth
import androidx.compose.foundation.layout.width
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun ConfirmationDialog(
openState: OpenState,
title: String,
message: String,
onOk: () -> Unit,
onCancel: () -> Unit = {}
) {
if (!openState.open.value) {
return
}
val strings = LocalStrings.current
AlertDialog(
onDismissRequest = {},
title = {
Text(title)
},
text = {
Text(message)
},
confirmButton = {
Button(
onClick = {
openState.close()
onOk()
}
) {
Text(text = strings.ok)
}
},
modifier = Modifier.width(DefaultMaxWidth),
dismissButton = {
Button(
onClick = {
openState.close()
onCancel()
}
) {
Text(text = strings.cancel)
}
}
)
}
| 1
|
Kotlin
|
4
| 50
|
9ec09a7ba5cabc7b1be173a9c8e8794c93984a24
| 1,377
|
Koalageddon2
|
The Unlicense
|
src/Day25.kt
|
syncd010
| 324,790,559
| false
| null |
class Day25: Day {
private fun convert(input: List<String>) : List<Long> {
return input[0].split(",").map { it.toLong() }
}
private fun List<Long>.fromAscii() = this
.map { it.toChar() }
.joinToString("") { it.toString() }
.trim()
private fun String.toAscii(): List<Long> = this.map { it.toLong() }
override fun solvePartOne(input: List<String>): String {
val computer = Intcode(convert(input))
// Navigate and get all items
var commands: String = ("north,take tambourine,east,take astrolabe," +
"south,take shell,north,east,north,take klein bottle,north,take easter egg," +
"south,south,west,west,south,south,south,take hypercube,north,north," +
"west,take dark matter,west,north,west,take coin,south,inv,")
.replace(',', '\n')
var prompt = computer.execute(commands.toAscii()).fromAscii()
// println(prompt)
// Drop all items before checkpoint
val items = prompt.substringAfter("inventory:")
.replace("- ","").trim().split("\n").dropLast(2)
commands = items.joinToString("") { "drop $it\n" }
prompt = computer.execute(commands.toAscii()).fromAscii()
// println(prompt)
for (bitmask in 0 until 2.pow(items.size)) {
commands = items
.mapIndexedNotNull { idx, s -> if (bitmask and 2.pow(idx) != 0) "take $s\n" else null }
.joinToString("")
commands += "south\n"
prompt = computer.execute(commands.toAscii()).fromAscii()
// println(prompt)
if (!prompt.contains("lighter") && !prompt.contains("heavier")) break
commands = items
.mapIndexedNotNull { idx, s -> if (bitmask and 2.pow(idx) != 0) "drop $s\n" else null }
.joinToString("")
prompt = computer.execute(commands.toAscii()).fromAscii()
// println(prompt)
}
return prompt.substringAfter("typing ").substringBefore(" ")
// while (true) {
// commands = readLine()?.plus('\n') ?: ""
// out = computer.execute(commands.map { it.toLong() })
// println(outputToStr(out))
// }
}
override fun solvePartTwo(input: List<String>): String {
return "Done"
}
}
| 0
|
Kotlin
|
0
| 0
|
11c7c7d6ccd2488186dfc7841078d9db66beb01a
| 2,397
|
AoC2019
|
Apache License 2.0
|
src/main/kotlin/site/liangbai/lbapi/hologram/base/ClickHandler.kt
|
Liangbai2333
| 846,688,168
| false
|
{"Kotlin": 122537}
|
package site.liangbai.lbapi.hologram.base
import org.bukkit.entity.Player
import site.liangbai.lbapi.hologram.event.HologramInteractEvent
/**
* @author Arasple
* @date 2021/2/12 14:10
*/
fun interface ClickHandler {
fun eval(player: Player, type: HologramInteractEvent.Type)
}
| 0
|
Kotlin
|
0
| 0
|
d10ef178a7cd31845a99b51b25ccf222303afa52
| 287
|
LBAPI
|
Creative Commons Zero v1.0 Universal
|
plugin/src/main/kotlin/ru/astrainteractive/astratemplate/gui/di/SampleGuiDependencies.kt
|
Astra-Interactive
| 378,620,934
| false
|
{"Kotlin": 82506}
|
package ru.astrainteractive.astratemplate.gui.di
import ru.astrainteractive.astralibs.async.BukkitDispatchers
import ru.astrainteractive.astralibs.string.BukkitTranslationContext
import ru.astrainteractive.astratemplate.api.local.di.ApiLocalModule
import ru.astrainteractive.astratemplate.core.PluginTranslation
import ru.astrainteractive.astratemplate.core.di.CoreModule
import ru.astrainteractive.astratemplate.di.BukkitModule
import ru.astrainteractive.astratemplate.gui.api.ItemStackSpigotAPI
import ru.astrainteractive.astratemplate.gui.domain.GetRandomColorUseCaseImpl
import ru.astrainteractive.astratemplate.gui.domain.SetDisplayNameUseCaseImpl
import ru.astrainteractive.astratemplate.gui.sample.DefaultSampleGUIComponent
import ru.astrainteractive.klibs.kdi.Factory
import ru.astrainteractive.klibs.kdi.Module
import ru.astrainteractive.klibs.kdi.getValue
interface SampleGuiDependencies : Module {
val translation: PluginTranslation
val dispatchers: BukkitDispatchers
val bukkitTranslationContext: BukkitTranslationContext
val viewModelFactory: Factory<DefaultSampleGUIComponent>
class Default(
coreModule: CoreModule,
bukkitModule: BukkitModule,
apiLocalModule: ApiLocalModule
) : SampleGuiDependencies {
override val translation by coreModule.translation
override val dispatchers by bukkitModule.bukkitDispatchers
override val bukkitTranslationContext by bukkitModule.bukkitTranslationContext
private val getRandomColorUseCase = GetRandomColorUseCaseImpl()
private val setDisplayNameUseCase = SetDisplayNameUseCaseImpl(getRandomColorUseCase)
override val viewModelFactory: Factory<DefaultSampleGUIComponent> = Factory {
val localApi = apiLocalModule.localApi
DefaultSampleGUIComponent(
localApi = localApi,
itemStackSpigotAPi = ItemStackSpigotAPI,
getRandomColorUseCase = getRandomColorUseCase,
setDisplayNameUseCase = setDisplayNameUseCase
)
}
}
}
| 0
|
Kotlin
|
0
| 16
|
411b89cdb46b0ea69ece0c1a29674670cfc8056e
| 2,073
|
AstraTemplate
|
MIT License
|
cynops-core/src/commonMain/kotlin/dev/yidafu/cynops/reporter/MetaLogFile.kt
|
yidafu
| 751,432,998
| false
|
{"Kotlin": 98554, "Shell": 339}
|
package dev.yidafu.loki.core.reporter
import kotlinx.io.Buffer
import kotlinx.io.RawSource
import kotlinx.io.files.Path
import kotlinx.io.files.SystemFileSystem
/**
* instance of `meta.json`
*
* constructor class will create a File instance of `meta.json`
*/
internal class LogMetaFile(private val logDirectory: String) : RawSource {
private val metaFilename = "meta.json"
private val closed = false
private val filepath
get() = "$logDirectory/$metaFilename"
private val metaFile = SystemFileSystem.source(Path(filepath))
private var meteFieList: MutableList<LogMeta> = mutableListOf()
private val output =
run {
if (SystemFileSystem.exists(Path(filepath))) {
// val buf = CharArray(1024)
// val reader = FileReader(metaFile)
// val jsonStr = StringBuilder()
// var len = 0
// while (reader.read(buf).also { len = it } != -1) {
// jsonStr.append(buf.sliceArray(0..<len).concatToString())
// }
//
// meteFieList = Json.decodeFromString<MutableList<LogMeta>>(if (jsonStr.isEmpty()) "[]" else jsonStr.toString())
// }
//
// RandomAccessFile(metaFile, "rw").apply {
// write(Json.encodeToString(meteFieList).toByteArray())
}
}
init {
val dir = SystemFileSystem.source(Path(logDirectory))
val fileList = mutableListOf<LogMeta>()
//
// dir.listFiles()?.filterNotNull()
// ?.filter { it.isFile && it.extension == "log" }
// ?.forEach {
// if (!meteFieList.any { f -> f.filepath == it.absolutePath }) {
// // TODO: 暂时不支持 inode
// fileList.add(LogMeta(it.absolutePath, 0, 0))
// }
// }
meteFieList.addAll(fileList)
updateMateFile()
}
/**
* get LogMeta list that has new content to report
*/
fun getNeedReportFiles(): List<LogMeta> {
return meteFieList.filter {
it.isReportable()
}
}
/**
* write data to `meta.json`
*/
fun updateMateFile() {
// if (output.fd.valid()) {
// output.seek(0)
// output.write(Json.encodeToString(meteFieList).toByteArray())
// }
}
/**
* Closes this stream and releases any system resources associated
* with it. If the stream is already closed then invoking this
* method has no effect.
*
*
* As noted in [AutoCloseable.close], cases where the
* close may fail require careful attention. It is strongly advised
* to relinquish the underlying resources and to internally
* *mark* the `Closeable` as closed, prior to throwing
* the `IOException`.
*
* @throws [java.io.IOException] if an I/O error occurs
*/
override fun close() {
if (closed) return
updateMateFile()
// output.close()
}
override fun readAtMostTo(
sink: Buffer,
byteCount: Long,
): Long {
TODO("Not yet implemented")
}
}
| 0
|
Kotlin
|
0
| 0
|
5d9e27e9966898d70d26ac56abbf3cba8422b8dd
| 3,144
|
cynops
|
Apache License 2.0
|
Android/app/src/main/java/org/shibajs/shibasample/MainActivity.kt
|
ShibaJS
| 123,889,912
| false
| null |
package moe.tlaster.shibasample
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.core.view.LayoutInflaterCompat
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import com.fasterxml.jackson.databind.ObjectMapper
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.item_list.view.*
import moe.tlaster.shiba.*
//class Model : INotifyPropertyChanged {
// override var propertyChanged: ((sender: Any, propertyName: String) -> Unit)? = null
// @Binding("text")
// var text = "hello world!"
//}
class MainActivity : AppCompatActivity() {
val dataContext = WithListModel()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val contents = String(resources.openRawResource(R.raw.bundle).use {
ByteArray(it.available()).apply {
it.read(this)
}
})
Shiba.configuration.scriptRuntime.execute(contents)
host.dataContext = object : BaseNotifyObject() {
@get:Binding(name = "text")
@set:Binding(name = "text")
var text = "Android"
set(text) {
field = text
notifyPropertyChanged("text")
}
}
host.component = "index"
}
}
class WithListModel : BaseNotifyObject() {
@get:Binding(name = "androidText")
@set:Binding(name = "androidText")
var text = "Android"
set(text) {
field = text
notifyPropertyChanged("androidText")
}
@get:Binding(name = "jsonNode")
val jsonNode = ObjectMapper().readTree("{\"hello\": {\"world\" : \"hello world\" }}")
@get:Binding(name = "jsonTree")
val jsonList = ObjectMapper().readTree("[{\"hello\": {\"world\" : \"hello world\" }}, {\"hello\": {\"world\" : \"hello world\" }},{\"hello\": {\"world\" : \"hello world\" }}]")
@get:Binding(name = "androidList")
@set:Binding(name = "androidList")
var androidList = (1 until 1000).map { "Text $it" }
@get:Binding(name = "list")
@set:Binding(name = "list")
var list = (1 until 1000).map { Model("Text $it") }
}
| 24
|
C#
|
0
| 45
|
ae4c4f62e2b6bdbeb0acfe9afaf386ebe27d69d8
| 2,614
|
Shiba
|
MIT License
|
src/main/kotlin/dataclass/utils/JacksonToMap.kt
|
masahitojp
| 282,862,097
| false
| null |
package dataclass.utils
import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
val mapper = jacksonObjectMapper()
fun <T> T.serializeToMapWithJackson(): Map<String, Any> {
return mapper.convertValue(
this,
object : TypeReference<Map<String, Any>>() {})
}
| 0
|
Kotlin
|
0
| 0
|
6c8c04024bf9b161054cb6491408f8a4964a117a
| 340
|
dataset-to-map
|
Apache License 2.0
|
reverse-rogue-world/src/main/kotlin/com/degrendel/reverserogue/world/BehaviorAI.kt
|
sirnuke
| 240,949,110
| false
|
{"Tcl": 493141, "Kotlin": 46298, "Shell": 814}
|
package com.degrendel.reverserogue.world
import com.badlogic.ashley.core.Entity
import com.degrendel.reverserogue.common.*
import com.degrendel.reverserogue.common.components.getPosition
class BehaviorAI(private val world: World)
{
// TODO: Lots of room for caching cost maps
fun compute(behaviors: List<Behavior>, creature: Entity): Action
{
val targets = mutableListOf<Position>()
val position = creature.getPosition()
val level = world.getLevel(position.floor)
behaviors.forEach {
when (it)
{
is MoveTowardsRogue -> targets.add(world.rogue.getPosition())
is MoveTowardsConjurer -> targets.add(world.conjurer.getPosition())
}
}
val costMap = NavigationMap(level, targets)
val moveTo = costMap.getMove(position)
return if (moveTo == null)
Sleep(creature)
else
Move(creature, moveTo)
}
}
| 0
|
Tcl
|
0
| 0
|
748b7e1f4c8a8d5e43d81d13f2a79e4996a346d8
| 880
|
reverse-rogue-concept
|
Apache License 2.0
|
warp/src/main/java/com/schibsted/nmp/warp/components/legacy/WarpCheckboxView.kt
|
warp-ds
| 676,900,954
| false
|
{"Kotlin": 410161}
|
package com.schibsted.nmp.warp.components.legacy
import android.content.Context
import android.util.AttributeSet
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.AbstractComposeView
import androidx.core.content.withStyledAttributes
import com.schibsted.nmp.warp.R
import com.schibsted.nmp.warp.components.WarpCheckbox
import com.schibsted.nmp.warp.components.WarpCheckboxStyle
import com.schibsted.nmp.warp.components.ext.getTextFromIdOrString
import org.koin.java.KoinJavaComponent.inject
class WarpCheckboxView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) : AbstractComposeView(context, attrs, defStyle) {
val theme: LegacyWarpTheme by inject(LegacyWarpTheme::class.java)
var style: WarpCheckboxStyle = WarpCheckboxStyle.Default
set(value) {
field = value
disposeComposition()
}
var label = ""
set(value) {
field = value
disposeComposition()
}
var extraText: String? = null
set(value) {
field = value
disposeComposition()
}
var checkboxEnabled = true
set(value) {
field = value
disposeComposition()
}
var checkboxChecked = false
set(value) {
field = value
disposeComposition()
}
var isError = false
set(value) {
field = value
disposeComposition()
}
var slot: @Composable (() -> Unit)? = null
set(value) {
field = value
disposeComposition()
}
private var checkedChangeListener: ((Boolean) -> Unit) = {}
override fun setEnabled(enabled: Boolean) {
super.setEnabled(enabled)
checkboxEnabled = enabled
disposeComposition()
}
fun setOnCheckedChangeListener(onCheckedChangeListener: ((Boolean) -> Unit)) {
this.checkedChangeListener = onCheckedChangeListener
}
fun setChecked(isChecked: Boolean) {
this.checkboxChecked = isChecked
disposeComposition()
}
private var stylesList = listOf(
WarpCheckboxStyle.Default,
WarpCheckboxStyle.Disabled,
WarpCheckboxStyle.Negative
)
init {
context.withStyledAttributes(attrs, R.styleable.WarpCheckbox) {
val styleInt = getInteger(R.styleable.WarpCheckbox_warpCheckboxStyle, 0)
style = stylesList[styleInt]
label = getTextFromIdOrString(R.styleable.WarpCheckbox_checkboxLabel, context) ?: ""
extraText = getTextFromIdOrString(R.styleable.WarpCheckbox_checkboxExtraText, context)
checkboxEnabled = getBoolean(R.styleable.WarpCheckbox_checkboxEnabled, true)
checkboxChecked = getBoolean(R.styleable.WarpCheckbox_checked, false)
isError = getBoolean(R.styleable.WarpCheckbox_checkboxIsError, false)
}
}
@Composable
override fun Content() {
theme {
WarpCheckbox(
label = label,
extraText = extraText,
onCheckedChange = checkedChangeListener,
slot = slot,
style = style,
enabled = checkboxEnabled,
checked = checkboxChecked,
isError = isError
)
}
}
}
| 2
|
Kotlin
|
1
| 2
|
fb676c4fd22d62f9823940c6fedafc9dabf502e5
| 3,392
|
warp-android
|
Apache License 2.0
|
finance/src/main/java/com/scitrader/finance/study/studies/EMAStudy.kt
|
ABTSoftware
| 468,421,926
| false
|
{"Kotlin": 296559, "Java": 3061}
|
package com.scitrader.finance.study.studies
import android.content.Context
import com.scitrader.finance.R
import com.scitrader.finance.core.DataSourceId
import com.scitrader.finance.core.event.IFinanceChartEvent
import com.scitrader.finance.edit.IEditable
import com.scitrader.finance.financeChart.InstrumentPriceFormatChangedEvent
import com.scitrader.finance.indicators.TALibIndicatorProvider
import com.scitrader.finance.pane.PaneId
import com.scitrader.finance.pane.series.LineFinanceSeries
import com.scitrader.finance.study.CandleStudyBase
import com.scitrader.finance.study.StudyId
import com.scitrader.finance.study.tooltips.IStudyTooltip
import com.scitrader.finance.study.tooltips.StudyTooltipBase
class EMAStudy(
pane: PaneId,
id: StudyId = StudyId.uniqueId("EMA"),
xValuesId: DataSourceId = DataSourceId.DEFAULT_X_VALUES_ID,
yValuesId: DataSourceId = DataSourceId.DEFAULT_Y_VALUES_ID,
) : CandleStudyBase(pane, id) {
private val emaOutputId: DataSourceId = DataSourceId.uniqueId(id, "EMA")
@get:com.scitrader.finance.edit.annotations.EditableProperty
val emaIndicator = TALibIndicatorProvider.EMAIndicator(
com.scitrader.finance.study.studies.Constants.Indicator.defaultPeriod,
yValuesId,
emaOutputId
)
@get:com.scitrader.finance.edit.annotations.EditableProperty
val emaSeries: LineFinanceSeries
init {
indicators.add(emaIndicator)
emaSeries = LineFinanceSeries(
R.string.emaIndicatorName,
xValuesId,
emaIndicator.outputId,
yAxisId
)
financeSeries.apply {
add(emaSeries)
}
}
override fun onEvent(event: IFinanceChartEvent) {
super.onEvent(event)
if (event is InstrumentPriceFormatChangedEvent) {
yAxis.textFormatting.updateInitialValue(event.priceFormat)
yAxis.cursorTextFormatting.updateInitialValue(event.priceFormat)
}
}
override fun reset() {
super.reset()
emaIndicator.reset()
emaSeries.reset()
}
override fun isValidEditableForSettings(editable: IEditable): Boolean {
return editable != emaIndicator.input
}
override val title: CharSequence
get() = "EMA(${emaIndicator.input} ${emaIndicator.period})"
override fun getStudyTooltip(context: Context): IStudyTooltip {
return EMATooltip(context, this)
}
class EMATooltip(context: Context, study: EMAStudy) : StudyTooltipBase<EMAStudy>(context, study) {
private val emaSeriesTooltip = study.emaSeries.getTooltip()
init {
orientation = HORIZONTAL
}
override fun onShowSeriesTooltipsChanged(showSeriesTooltips: Boolean) {
super.onShowSeriesTooltipsChanged(showSeriesTooltips)
if (showSeriesTooltips)
emaSeriesTooltip.placeInto(this)
else
emaSeriesTooltip.removeFrom(this)
}
override fun update(x: Float, y: Float) {
super.update(x, y)
emaSeriesTooltip.tryUpdate(x, y)
}
}
}
| 3
|
Kotlin
|
0
| 2
|
00245ef7ee93ee79b1b5a1e8a6a77bce0f02777b
| 3,128
|
Finance.Android
|
Apache License 2.0
|
zowe-imperative/src/jsMain/kotlin/zowe/imperative/imperative/plugins/utilities/PluginIssues.kt
|
lppedd
| 761,812,661
| false
|
{"Kotlin": 1887051}
|
@file:JsModule("@zowe/imperative")
package zowe.imperative.imperative.plugins.utilities
import zowe.imperative.imperative.plugins.doc.IPluginIssue
import zowe.imperative.imperative.plugins.doc.IPluginIssues
import zowe.imperative.imperative.plugins.doc.IPluginJson
/**
* This class is used to record and access plugin errors and warnings. It is a singleton and should
* be accessed via PluginIssues.instance.
*/
external class PluginIssues {
/**
* Reports whether or not a plugin has any issues with any of the specified severities.
*
* @param pluginName The name of the plugin
* @param issueSevs An array of issue severities.
* @return True if any plugin issues have any of the severities. False otherwise.
*/
fun doesPluginHaveIssueSev(
pluginName: String,
issueSevs: Array<IssueSeverity>,
): Boolean
/**
* Get the issues recorded for all plugins.
*
* @return Map of plugin names to their array of issues.
*/
fun getAllIssues(): IPluginIssues
/**
* Get the set of installed plugins. This function should be the only means used to access our
* installedPlugins class variable.
*
* @return The set of installed plugins.
*/
fun getInstalledPlugins(): IPluginJson
/**
* Get the array of issues for the specified plugin.
*
* @param pluginName The name of the plugin
* @return Array of issues for the plugin. If no issues, an empty array is returned.
*/
fun getIssueListForPlugin(pluginName: String): Array<IPluginIssue>
/**
* Remove the specified plugin from the collection of plugin issues.
*
* @param pluginName The name of the plugin to remove
*/
fun removeIssuesForPlugin(pluginName: String)
/**
* Record an issue that was discovered in a plugin into an in-memory structure. The plugin issues
* can later be accessed to report the health of a plugin.
*
* @param pluginName The name of the plugin
* @param issueSev The severity of the issue. Use PluginIssues.ERROR or PluginIssues.WARNING
* @param issueText The issue message text to record.
*/
fun recordIssue(
pluginName: String,
issueSev: IssueSeverity,
issueText: String,
)
companion object {
/**
* Gets a single instance of the PluginIssues. On the first call of PluginIssues.instance, a new
* Plugin Issues object is initialized and returned. Every subsequent call will use the one that
* was first created.
*
* @return The newly initialized PMF object.
*/
val instance: PluginIssues
}
}
| 0
|
Kotlin
|
0
| 3
|
0f493d3051afa3de2016e5425a708c7a9ed6699a
| 2,539
|
kotlin-externals
|
MIT License
|
runtime/src/main/kotlin/io/ringle/rudy/RouteRecord.kt
|
EddieRingle
| 36,129,967
| false
| null |
package io.ringle.rudy
import android.os.Parcel
import android.os.Parcelable
public open class RouteRecord(
val key: Int,
val addToBackstack: Boolean,
val resolution: RouteResolution
) : Parcelable {
var routable: Routable? = null
companion object {
val CREATOR = object : Parcelable.Creator<RouteRecord> {
val cl = javaClass<RouteRecord>().getClassLoader()
override fun createFromParcel(source: Parcel): RouteRecord? =
RouteRecord(
source.readInt(),
source.readInt() == 1,
source.readParcelable(cl)
)
override fun newArray(size: Int): Array<RouteRecord?>? {
return arrayOfNulls(size)
}
}
}
override fun describeContents(): Int = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeInt(key)
dest.writeInt(if (addToBackstack) 1 else 0)
dest.writeParcelable(resolution, 0)
}
}
| 0
|
Kotlin
|
0
| 1
|
28afefae6aae9b9e699b5294c061bdd9d636adc9
| 1,076
|
rudy
|
MIT License
|
enro-core/src/main/java/dev/enro/core/internal/handle/NavigationHandleScope.kt
|
isaac-udy
| 256,179,010
| false
| null |
package dev.enro.core.internal.handle
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import dev.enro.core.NavigationHandle
import dev.enro.core.controller.*
import dev.enro.core.controller.usecase.CreateResultChannel
import dev.enro.core.controller.usecase.NavigationHandleExtras
import java.io.Closeable
internal class NavigationHandleScope(
navigationController: NavigationController,
) : EnroDependencyScope, Closeable {
private var boundNavigationHandle: NavigationHandle? = null
override val container: EnroDependencyContainer = EnroDependencyContainer(
parentScope = navigationController.dependencyScope,
registration = {
register { requireNotNull(boundNavigationHandle) }
register { CreateResultChannel(get(), get()) }
register { NavigationHandleExtras() }
}
)
fun bind(navigationHandle: NavigationHandle): NavigationHandleScope {
boundNavigationHandle = navigationHandle
navigationHandle.lifecycle.addObserver(
LifecycleEventObserver { _, event ->
if(event != Lifecycle.Event.ON_DESTROY) return@LifecycleEventObserver
boundNavigationHandle = null
}
)
return this
}
override fun close() {
container.bindings.values.forEach {
if(it.isInitialized) {
val closeable = it.value as? Closeable ?: return@forEach
closeable.close()
}
}
}
}
| 10
|
Kotlin
|
13
| 222
|
41d36e1fcacb9190175b0df6d2f60247e969a616
| 1,533
|
Enro
|
Apache License 2.0
|
stream-chat-android-compose/src/main/java/io/getstream/chat/android/compose/viewmodel/pinned/PinnedMessageListViewModel.kt
|
GetStream
| 177,873,527
| false
|
{"Kotlin": 8578375, "MDX": 2150736, "Java": 271477, "JavaScript": 6737, "Shell": 5229}
|
/*
* Copyright (c) 2014-2024 Stream.io Inc. All rights reserved.
*
* Licensed under the Stream License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/GetStream/stream-chat-android/blob/main/LICENSE
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.getstream.chat.android.compose.viewmodel.pinned
import androidx.lifecycle.ViewModel
import io.getstream.chat.android.models.Message
import io.getstream.chat.android.ui.common.feature.pinned.PinnedMessageListController
import io.getstream.chat.android.ui.common.state.pinned.PinnedMessageListState
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
/**
* ViewModel responsible for providing pinned messages in the channel.
* Pinned messages are provided in a descending order based on [Message.pinnedAt].
*
* @param controller the [PinnedMessageListController] handling the business logic and the state management for the
* pinned message list.
*/
public class PinnedMessageListViewModel(private val controller: PinnedMessageListController) : ViewModel() {
/**
* The current pinned messages' state.
*/
public val state: StateFlow<PinnedMessageListState> = controller.state
/**
* One shot error events when a query fails.
*/
public val errorEvents: SharedFlow<Unit> = controller.errorEvents
init {
controller.load()
}
/**
* Loads more data when requested.
*
* Does nothing if the end of the list has already been reached or loading is already in progress.
*/
public fun loadMore() {
controller.loadMore()
}
}
| 24
|
Kotlin
|
273
| 1,451
|
8e46f46a68810d8086c48a88f0fff29faa2629eb
| 1,977
|
stream-chat-android
|
FSF All Permissive License
|
example/src/main/java/com/tuanhav95/example/fragment/ExoPlayerTopFragment.kt
|
tuanhav95
| 245,124,467
| false
| null |
package com.tuanhav95.example.fragment
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.google.android.exoplayer2.ExoPlayerFactory
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout
import com.google.android.exoplayer2.upstream.DataSource
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.google.android.exoplayer2.util.Util
import com.tuanhav95.example.R
import kotlinx.android.synthetic.main.fragment_top_exo_player.*
class ExoPlayerTopFragment : Fragment(), Player.EventListener {
companion object {
const val STREAM_URL = "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"
}
private lateinit var simpleExoPlayer: SimpleExoPlayer
private lateinit var mediaDataSourceFactory: DataSource.Factory
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_top_exo_player, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
simpleExoPlayer = ExoPlayerFactory.newSimpleInstance(context)
mediaDataSourceFactory = DefaultDataSourceFactory(context, Util.getUserAgent(context, "mediaPlayerSample"))
val mediaSource = ProgressiveMediaSource.Factory(mediaDataSourceFactory).createMediaSource(Uri.parse(STREAM_URL))
simpleExoPlayer.addListener(this)
simpleExoPlayer.prepare(mediaSource, false, false)
simpleExoPlayer.playWhenReady = true
playerView.setShutterBackgroundColor(Color.TRANSPARENT)
playerView.player = simpleExoPlayer
playerView.requestFocus()
aspectRatioFrameLayout.resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIXED_WIDTH
aspectRatioFrameLayout.setAspectRatio(16f / 9)
}
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
super.onPlayerStateChanged(playWhenReady, playbackState)
if (playbackState == Player.STATE_ENDED) {
simpleExoPlayer.playWhenReady = true
}
}
override fun onStop() {
super.onStop()
simpleExoPlayer.removeListener(this)
simpleExoPlayer.release()
}
}
| 5
|
Kotlin
|
31
| 204
|
be89a9c9762a326ea12f69463cfead7f37cc3c25
| 2,588
|
DragView
|
Apache License 2.0
|
thirdparty/ktfx-jfoenix-layouts/src/test/kotlin/ktfx/jfoenix/layouts/JfxToggleButtonTest.kt
|
hanggrian
| 102,934,147
| false
| null |
package ktfx.jfoenix.layouts
import com.hanggrian.ktfx.test.LayoutsStyledTest
import com.jfoenix.controls.JFXToggleButton
import ktfx.layouts.KtfxPane
class JfxToggleButtonTest : LayoutsStyledTest<KtfxPane, JFXToggleButton>() {
override fun manager() = KtfxPane()
override fun KtfxPane.childCount() = children.size
override fun child1() = jfxToggleButton {}
override fun KtfxPane.child2() = jfxToggleButton()
override fun child3() = styledJfxToggleButton(styleClass = arrayOf("style"))
override fun KtfxPane.child4() = styledJfxToggleButton(styleClass = arrayOf("style"))
}
| 1
| null |
2
| 19
|
6e5ec9fedf8359423c31a2ba64cd175bc9864cd2
| 605
|
ktfx
|
Apache License 2.0
|
src/main/kotlin/uk/gov/justice/digital/hmpps/sentenceplan/data/Goals.kt
|
ministryofjustice
| 783,789,996
| false
|
{"Kotlin": 36938, "Dockerfile": 1145}
|
package uk.gov.justice.digital.hmpps.sentenceplan.data
import com.google.gson.annotations.SerializedName
data class Goals(
@SerializedName("id") var id: Int? = null,
@SerializedName("Name") var Name: String? = null,
@SerializedName("Active") var Active: Boolean? = null,
@SerializedName("Steps") var Steps: ArrayList<Steps> = arrayListOf(),
)
| 1
|
Kotlin
|
0
| 0
|
180358e9ae4447450aff3c9444231e04d17c30e4
| 353
|
hmpps-sentence-plan
|
MIT License
|
ggraphql-plugin/src/main/kotlin/uk/co/lucidsource/ggraphql/plugin/GraphqlPluginExtension.kt
|
lucidsource-uk
| 755,554,093
| false
|
{"Kotlin": 102916}
|
package uk.co.lucidsource.ggraphql.plugin
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.InputDirectory
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.OutputFile
interface GraphqlPluginExtension {
val packageName: Property<String>
val schemas: ListProperty<String>
@get:InputDirectory
val schemaDirectory: DirectoryProperty
@get:OutputFile
val schemaOutFile: RegularFileProperty
@get:OutputDirectory
val kotlinOutputDirectory: DirectoryProperty
}
| 0
|
Kotlin
|
0
| 0
|
8e198823f46f3d6a4e46b84531cc77e37d84dd96
| 666
|
ggraphql
|
MIT License
|
src/main/kotlin/raft/war/language/vjass/openapi/fileTypes/VjassSyntaxHighlighterFactory.kt
|
WarRaft
| 713,961,790
| false
|
{"Kotlin": 503179, "Java": 347321, "Lex": 23647, "HTML": 558}
|
package raft.war.language.vjass.openapi.fileTypes
import com.intellij.openapi.fileTypes.SyntaxHighlighter
import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
internal class VjassSyntaxHighlighterFactory : SyntaxHighlighterFactory() {
override fun getSyntaxHighlighter(project: Project?, virtualFile: VirtualFile?): SyntaxHighlighter {
return VjassSyntaxHighlighterBase()
}
}
| 0
|
Kotlin
|
0
| 2
|
43e499b8c896631cd729a784a097230700322a10
| 492
|
IntelliJASS
|
MIT License
|
gdxmachine-core/src/main/kotlin/com/disgraded/gdxmachine/core/api/graphics/drawable/PointLight.kt
|
DerYeger
| 212,057,902
| true
|
{"Kotlin": 115829, "GLSL": 10412}
|
package com.disgraded.gdxmachine.core.api.graphics.drawable
class PointLight : Light(LightType.POINT)
| 0
| null |
0
| 1
|
1d830e693624aac01a3f8506ac8ddc45533875dc
| 102
|
gdxmachine
|
Apache License 2.0
|
app/src/main/java/projects/jaseem/triptimes/extensions/LiveDataExtensions.kt
|
ajhakeem
| 244,786,914
| false
| null |
package projects.jaseem.triptimes.extensions
import androidx.lifecycle.MutableLiveData
import projects.jaseem.triptimes.state.Resource
import projects.jaseem.triptimes.state.ResourceState
fun <T> MutableLiveData<Resource<T>>.setSuccess(data: T) =
postValue(
Resource(
ResourceState.SUCCESS,
data
)
)
fun <T> MutableLiveData<Resource<T>>.setLoading() =
postValue(
Resource(
ResourceState.LOADING,
value?.data
)
)
fun <T> MutableLiveData<Resource<T>>.setError(errorMessage: String? = null) =
postValue(
Resource(
ResourceState.ERROR,
value?.data,
errorMessage
)
)
| 0
|
Kotlin
|
0
| 0
|
f09007fabd9083c9cf2aad0844a94dc682c77cd9
| 722
|
TripTimes
|
MIT License
|
app/src/main/java/projects/jaseem/triptimes/extensions/LiveDataExtensions.kt
|
ajhakeem
| 244,786,914
| false
| null |
package projects.jaseem.triptimes.extensions
import androidx.lifecycle.MutableLiveData
import projects.jaseem.triptimes.state.Resource
import projects.jaseem.triptimes.state.ResourceState
fun <T> MutableLiveData<Resource<T>>.setSuccess(data: T) =
postValue(
Resource(
ResourceState.SUCCESS,
data
)
)
fun <T> MutableLiveData<Resource<T>>.setLoading() =
postValue(
Resource(
ResourceState.LOADING,
value?.data
)
)
fun <T> MutableLiveData<Resource<T>>.setError(errorMessage: String? = null) =
postValue(
Resource(
ResourceState.ERROR,
value?.data,
errorMessage
)
)
| 0
|
Kotlin
|
0
| 0
|
f09007fabd9083c9cf2aad0844a94dc682c77cd9
| 722
|
TripTimes
|
MIT License
|
utbot-go/src/main/kotlin/org/utbot/go/api/GoTypesApi.kt
|
UnitTestBot
| 480,810,501
| false
| null |
package org.utbot.go.api
import org.utbot.go.framework.api.go.GoFieldId
import org.utbot.go.framework.api.go.GoPackage
import org.utbot.go.framework.api.go.GoTypeId
/**
* Represents real Go primitive type.
*/
class GoPrimitiveTypeId(name: String) : GoTypeId(name) {
override val canonicalName: String = when (name) {
"byte" -> "uint8"
"rune" -> "int32"
else -> simpleName
}
override fun getRelativeName(destinationPackage: GoPackage, aliases: Map<GoPackage, String?>): String = simpleName
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is GoPrimitiveTypeId) return false
return canonicalName == other.canonicalName
}
override fun hashCode(): Int = name.hashCode()
}
class GoStructTypeId(
name: String,
val fields: List<GoFieldId>,
) : GoTypeId(name) {
override val canonicalName: String = name
override fun getRelativeName(destinationPackage: GoPackage, aliases: Map<GoPackage, String?>): String = simpleName
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is GoStructTypeId) return false
return fields == other.fields
}
override fun hashCode(): Int {
return fields.hashCode()
}
}
class GoArrayTypeId(
name: String, elementTypeId: GoTypeId, val length: Int
) : GoTypeId(name, elementTypeId = elementTypeId) {
override val canonicalName: String = "[$length]${elementTypeId.canonicalName}"
override fun getRelativeName(destinationPackage: GoPackage, aliases: Map<GoPackage, String?>): String =
"[$length]${elementTypeId!!.getRelativeName(destinationPackage, aliases)}"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is GoArrayTypeId) return false
return elementTypeId == other.elementTypeId && length == other.length
}
override fun hashCode(): Int = 31 * elementTypeId.hashCode() + length
}
class GoSliceTypeId(
name: String, elementTypeId: GoTypeId,
) : GoTypeId(name, elementTypeId = elementTypeId) {
override val canonicalName: String = "[]${elementTypeId.canonicalName}"
override fun getRelativeName(destinationPackage: GoPackage, aliases: Map<GoPackage, String?>): String =
"[]${elementTypeId!!.getRelativeName(destinationPackage, aliases)}"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is GoSliceTypeId) return false
return elementTypeId == other.elementTypeId
}
override fun hashCode(): Int = elementTypeId.hashCode()
}
class GoMapTypeId(
name: String, val keyTypeId: GoTypeId, elementTypeId: GoTypeId,
) : GoTypeId(name, elementTypeId = elementTypeId) {
override val canonicalName: String = "map[${keyTypeId.canonicalName}]${elementTypeId.canonicalName}"
override fun getRelativeName(destinationPackage: GoPackage, aliases: Map<GoPackage, String?>): String {
val keyType = keyTypeId.getRelativeName(destinationPackage, aliases)
val elementType = elementTypeId!!.getRelativeName(destinationPackage, aliases)
return "map[$keyType]$elementType"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is GoMapTypeId) return false
return keyTypeId == other.keyTypeId && elementTypeId == other.elementTypeId
}
override fun hashCode(): Int = 31 * keyTypeId.hashCode() + elementTypeId.hashCode()
}
class GoInterfaceTypeId(name: String) : GoTypeId(name) {
override val canonicalName: String = name
override fun getRelativeName(destinationPackage: GoPackage, aliases: Map<GoPackage, String?>): String = simpleName
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is GoInterfaceTypeId) return false
return name == other.name
}
override fun hashCode(): Int = name.hashCode()
}
class GoNamedTypeId(
name: String,
override val sourcePackage: GoPackage,
implementsError: Boolean,
val underlyingTypeId: GoTypeId
) : GoTypeId(name, implementsError = implementsError) {
val packageName: String = sourcePackage.packageName
val packagePath: String = sourcePackage.packagePath
override val canonicalName: String = if (sourcePackage.isBuiltin) {
name
} else {
"${sourcePackage.packageName}.$name"
}
fun exported(): Boolean = name.first().isUpperCase()
override fun getRelativeName(destinationPackage: GoPackage, aliases: Map<GoPackage, String?>): String {
val alias = aliases[sourcePackage]
return if (sourcePackage.isBuiltin || sourcePackage == destinationPackage || alias == ".") {
simpleName
} else if (alias == null) {
"${packageName}.${simpleName}"
} else {
"${alias}.${simpleName}"
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is GoNamedTypeId) return false
return sourcePackage == other.sourcePackage && name == other.name
}
override fun hashCode(): Int {
var result = packagePath.hashCode()
result = 31 * result + packageName.hashCode()
result = 31 * result + name.hashCode()
return result
}
}
| 346
|
Kotlin
|
26
| 79
|
5151b1bee58f24b95d05be394b0ef2dda20381c6
| 5,384
|
UTBotJava
|
Apache License 2.0
|
app/src/main/java/com/software/claudiofus/itcq/interface/GenericActivity.kt
|
claudiofus
| 110,263,381
| false
|
{"TSQL": 814972, "Kotlin": 53370}
|
package com.software.claudiofus.itcq.`interface`
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.support.design.widget.NavigationView
import android.support.v4.view.GravityCompat
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AppCompatActivity
import android.support.v7.app.AppCompatDelegate
import android.support.v7.content.res.AppCompatResources
import android.support.v7.widget.Toolbar
import android.view.MenuItem
import android.widget.Toast
import com.software.claudiofus.itcq.R
import com.software.claudiofus.itcq.activity.*
import com.software.claudiofus.itcq.fragment.HomeFragment
import com.software.claudiofus.itcq.utility.Strings
import com.software.claudiofus.itcq.utility.ThemeColors
import com.software.claudiofus.itcq.utility.Utils
abstract class GenericActivity : AppCompatActivity(),
NavigationView.OnNavigationItemSelectedListener
{
/**
* Flag used to close current Fragment.
*/
private var _toClose = false
private lateinit var toolbar : Toolbar
private lateinit var mDrawer : DrawerLayout
private lateinit var mNavigationView : NavigationView
override fun onCreate(savedInstanceState : Bundle?)
{
super.onCreate(savedInstanceState)
val theme = Utils.readPrefsInt(this, Strings.PREFS_COLOR)
val currTheme = if (theme == -1) R.style.AppTheme else theme
val darkPrimary = ThemeColors.darkPrimaryMaps[Utils.getKeyByValue(ThemeColors.colorsMap,
currTheme)]
setTheme(currTheme)
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
setContentView(R.layout.activity_main)
toolbar = findViewById(R.id.toolbar)
mDrawer = findViewById(R.id.drawer_layout)
mNavigationView = findViewById(R.id.nav_view)
mNavigationView.itemIconTintList = AppCompatResources.getColorStateList(this, darkPrimary!!)
setSupportActionBar(toolbar)
val toggle = ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.navigation_drawer_open,
R.string.navigation_drawer_close)
mDrawer.addDrawerListener(toggle)
toggle.syncState()
}
override fun onNavigationItemSelected(item : MenuItem) : Boolean
{
// Assume fragment is never null
var intent = Intent(this, MainActivity::class.java)
val id = item.itemId
mDrawer = findViewById(R.id.drawer_layout)
mNavigationView = findViewById(R.id.nav_view)
mNavigationView.setNavigationItemSelectedListener(this)
mNavigationView.menu.findItem(R.id.nav_home).isChecked = true
when (id)
{
R.id.nav_quiz -> intent = Intent(this, QuizActivity::class.java)
R.id.nav_category -> intent = Intent(this, CategoryActivity::class.java)
R.id.nav_graphs -> intent = Intent(this, GraphActivity::class.java)
R.id.nav_settings -> intent = Intent(this, SettingsActivity::class.java)
R.id.nav_share ->
{
Utils.shareApp(mNavigationView.context)
return true
}
}
startActivity(intent)
mDrawer.closeDrawer(GravityCompat.START)
return true
}
/**
* Override AppCompatActivity onBackPressed method.
*/
override fun onBackPressed()
{
if (_toClose)
{
finishAffinity() // finish activity
}
else
{
Toast.makeText(this, getString(R.string.back_button), Toast.LENGTH_SHORT).show()
_toClose = true
Handler().postDelayed({ _toClose = false }, 2 * 1000 /* 2 seconds */)
mNavigationView = findViewById(R.id.nav_view)
mNavigationView.setNavigationItemSelectedListener(this)
mNavigationView.menu.findItem(R.id.nav_home).isChecked = true
Utils.startFragment(this, HomeFragment())
}
mDrawer = findViewById(R.id.drawer_layout)
if (mDrawer.isDrawerOpen(GravityCompat.START))
{
mDrawer.closeDrawer(GravityCompat.START)
}
}
}
| 0
|
TSQL
|
0
| 0
|
ee0b5be8a5d1f994538bbf45dbd1079bae897fce
| 3,851
|
ITCQ
|
MIT License
|
android/app/src/main/java/com/diafyt/lazarus/ui/AbstractMainFragment.kt
|
diafyt
| 276,907,182
| false
| null |
package com.diafyt.lazarus.ui
import android.nfc.Tag
import androidx.fragment.app.Fragment
/**
* Base class for all fragments displayed in the MainActivity.
*
* This is basically an interface to provide some properties and methods.
*/
abstract class AbstractMainFragment : Fragment() {
/**
* resource id to be used as title in the ViewPager
*/
abstract val tabTitleKey: Int
/**
* NFC event handler.
*
* On an NFC event an intent will be delivered to the MainActivity
* which will call method on the current fragment to delegate the handling.
*/
abstract fun handleNfc(tag: Tag)
}
| 0
|
Kotlin
|
1
| 7
|
2c1d05f9239c936b97969e65fce199bb57b1505b
| 637
|
lazarus
|
Apache License 2.0
|
app/src/main/java/eu/kanade/domain/entries/anime/interactor/GetAnimeFavorites.kt
|
AniFOSS
| 377,170,228
| true
|
{"Kotlin": 4060627}
|
package eu.kanade.domain.entries.anime.interactor
import eu.kanade.domain.entries.anime.model.Anime
import eu.kanade.domain.entries.anime.repository.AnimeRepository
import kotlinx.coroutines.flow.Flow
class GetAnimeFavorites(
private val animeRepository: AnimeRepository,
) {
suspend fun await(): List<Anime> {
return animeRepository.getAnimeFavorites()
}
fun subscribe(sourceId: Long): Flow<List<Anime>> {
return animeRepository.getAnimeFavoritesBySourceId(sourceId)
}
}
| 1
|
Kotlin
|
0
| 0
|
08787976b43da6e02207081e1ecccb7fcd89c307
| 512
|
aniyomi
|
Apache License 2.0
|
src/main/kotlin/com/kvsinyuk/stickergenerator/applicaiton/service/CropImageService.kt
|
kirillsinyuk
| 723,597,911
| false
|
{"Kotlin": 78281, "Dockerfile": 177}
|
package com.kvsinyuk.stickergenerator.applicaiton.service
import java.awt.image.BufferedImage
interface CropImageService {
fun cropImage(image: BufferedImage): BufferedImage
}
| 3
|
Kotlin
|
0
| 0
|
bafccbb3b01a651b3dc5a05deb7154ab6bb2ca0b
| 182
|
sticker-generator
|
Apache License 2.0
|
2019-android-applications/final-meeting/app/src/main/java/dev/codelabs/finalmeeting/NewsDetailsActivity.kt
|
kevin2-cyber
| 437,880,493
| false
|
{"Kotlin": 765037, "CSS": 301626, "SCSS": 287609, "HTML": 208821, "JavaScript": 16612, "Java": 2758, "TypeScript": 366}
|
package dev.codelabs.finalmeeting
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import dev.codelabs.finalmeeting.data.News
class NewsDetailsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_news_details)
// Get news from intent data
val news: News? = intent.extras?.getParcelable<News?>("extra_news")
debugger(news)
// Handling implicit intents
if (intent.action == Intent.ACTION_VIEW) {
// https://ww.google.com/news_url?q=1234567
debugger(intent.data?.getQueryParameters("q"))
}
}
}
| 0
|
Kotlin
|
0
| 1
|
260d0d3bbae9bfaa24df4fb933188e37c82cc8a6
| 747
|
ug-short-course
|
MIT License
|
app/src/main/java/com/example/bysj2020/bean/SearchRecommendBean.kt
|
Xingzuo888
| 238,856,307
| false
|
{"Kotlin": 319568, "Java": 159225}
|
package com.example.bysj2020.bean
/**
* Author : wxz
* Time : 2020/03/25
* Desc :
*/
data class SearchRecommendBean(
val recommendTagList: List<String>
)
| 0
|
Kotlin
|
0
| 0
|
a734212631b74f6a28a98379e4109d28b26d9693
| 175
|
bysj2020
|
Apache License 2.0
|
app/src/test/java/com/exchangerate/converter/presentation/viewmodel/CurrencyConversionViewModelTest.kt
|
ruichard
| 722,125,834
| false
|
{"Kotlin": 49410}
|
package com.exchangerate.converter.presentation.viewmodel
import com.exchangerate.converter.data.model.ExchangeRate
import com.exchangerate.converter.domain.model.Currency
import com.exchangerate.converter.domain.usecase.CalculateConvertedAmountsUseCase
import com.exchangerate.converter.domain.usecase.GetLatestExchangeRatesUseCase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.junit.MockitoJUnitRunner
@OptIn(ExperimentalCoroutinesApi::class)
@RunWith(MockitoJUnitRunner::class)
class CurrencyConversionViewModelTest {
@Mock
private lateinit var getLatestExchangeRatesUseCase: GetLatestExchangeRatesUseCase
@Mock
private lateinit var calculateConvertedAmountsUseCase: CalculateConvertedAmountsUseCase
private lateinit var currencyConversionViewModel: CurrencyConversionViewModel
private val testDispatcher = StandardTestDispatcher()
@Before
fun setUp() {
Dispatchers.setMain(testDispatcher)
currencyConversionViewModel = CurrencyConversionViewModel(
getLatestExchangeRatesUseCase,
calculateConvertedAmountsUseCase
)
}
@Test
fun getCurrencies() = runTest {
val fakeCurrencies = listOf("USD", "EUR", "JPY")
val fakeExchangeRate = ExchangeRate(mapOf("USD" to 1.0, "EUR" to 0.85, "JPY" to 110.0))
`when`(getLatestExchangeRatesUseCase()).thenReturn(flowOf(fakeExchangeRate))
currencyConversionViewModel.fetchCurrencies()
advanceUntilIdle()
val result = currencyConversionViewModel.currencies.first()
assertEquals(fakeCurrencies, result)
}
@Test
fun getExchangeRateState() = runTest {
val fakeConvertedAmounts = listOf(Currency("EUR", 85.0))
`when`(calculateConvertedAmountsUseCase(100.0, "USD"))
.thenReturn(flowOf(fakeConvertedAmounts))
currencyConversionViewModel.handleInput("100", "USD")
advanceUntilIdle()
val result = currencyConversionViewModel.exchangeRateState.value
assertEquals(fakeConvertedAmounts, result)
}
@Test
fun handleInput() = runTest {
val amount = 100.0
val currencyCode = "USD"
val fakeConvertedAmounts = listOf(Currency("EUR", 85.0))
`when`(calculateConvertedAmountsUseCase(amount, currencyCode))
.thenReturn(flowOf(fakeConvertedAmounts))
currencyConversionViewModel.handleInput(amount.toString(), currencyCode)
advanceUntilIdle()
assert(currencyConversionViewModel.exchangeRateState.value == fakeConvertedAmounts)
}
@After
fun tearDown() {
Dispatchers.resetMain()
}
}
| 0
|
Kotlin
|
0
| 0
|
904a9226adf2f13fc55840f8c63d797f387f2cdf
| 3,187
|
ExchangeRateConverter
|
MIT License
|
app/src/main/java/com/noto/app/settings/ThemeDialogFragment.kt
|
androiddevnotesforks
| 346,802,081
| true
|
{"Kotlin": 138791}
|
package com.noto.app.settings
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatDelegate
import androidx.lifecycle.lifecycleScope
import com.noto.app.BaseDialogFragment
import com.noto.app.MainViewModel
import com.noto.app.R
import com.noto.app.Theme
import com.noto.app.databinding.BaseDialogFragmentBinding
import com.noto.app.databinding.ThemeDialogFragmentBinding
import com.noto.app.util.stringResource
import com.noto.app.util.withBinding
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
class ThemeDialogFragment : BaseDialogFragment() {
private val viewModel by sharedViewModel<MainViewModel>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View = ThemeDialogFragmentBinding.inflate(inflater, container, false).withBinding {
BaseDialogFragmentBinding.bind(root).apply {
tvDialogTitle.text = resources.stringResource(R.string.theme)
}
viewModel.theme
.onEach {
when (it) {
Theme.System -> rbSystemTheme.isChecked = true
Theme.Light -> rbLightTheme.isChecked = true
Theme.Dark -> rbDarkTheme.isChecked = true
}
}
.launchIn(lifecycleScope)
rbSystemTheme.setOnClickListener {
dismiss()
viewModel.updateTheme(Theme.System)
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
}
rbLightTheme.setOnClickListener {
dismiss()
viewModel.updateTheme(Theme.Light)
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
}
rbDarkTheme.setOnClickListener {
dismiss()
viewModel.updateTheme(Theme.Dark)
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
}
}
}
| 0
|
Kotlin
|
0
| 2
|
12a7068345e5f18a5e3e5c02839d3dd0d77d46ca
| 2,141
|
Noto
|
Apache License 2.0
|
app/src/b2b/java/eu/ginlo_apps/ginlo/controller/contracts/SetAddressInfoListener.kt
|
cdskev
| 358,279,979
| false
|
{"Git Config": 1, "Gradle": 3, "Markdown": 5, "Java Properties": 2, "Shell": 1, "Ignore List": 1, "Text": 2, "Proguard": 1, "INI": 1, "XML": 393, "Java": 438, "Kotlin": 168, "JSON": 1, "HTML": 1}
|
// Copyright (c) 2020-2024 ginlo.net GmbH
package eu.ginlo_apps.ginlo.controller.contracts
interface SetAddressInfoListener {
fun onSuccess(result: String)
fun onFail(errorMsg: String)
}
| 1
|
Java
|
0
| 5
|
5609a68a539fc5fd9666d3d5f93be750fa5a2b77
| 196
|
ginlo-android
|
Apache License 2.0
|
app/src/main/java/com/example/noteapp/presentation/NoteViewModel.kt
|
Wit0r
| 621,182,013
| false
| null |
package com.example.noteapp.presentation
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.noteapp.core.NoteStateHolder
import com.example.noteapp.domain.model.Note
import com.example.noteapp.domain.model.NoteState
import com.example.noteapp.domain.repository.NoteRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class NoteViewModel @Inject constructor(private val repository: NoteRepository) : ViewModel() {
var expanded by mutableStateOf(false)
var openDialog by mutableStateOf(false)
var note by mutableStateOf(Note(0, "", ""))
private set
val notes = repository.getNotes()
private val _noteState = NoteStateHolder._noteState
val noteState = NoteStateHolder.noteState
private val _snackBarHostState = mutableStateOf(SnackbarHostState())
val snackBarHostState: MutableState<SnackbarHostState> = _snackBarHostState
fun getNote(id: Int) = viewModelScope.launch { note = repository.getNote(id) }
fun addNote(note: Note) = viewModelScope.launch { repository.addNote(note) }
fun updateNote(note: Note) = viewModelScope.launch {
_noteState.emit(NoteState(isLoading = true))
try {
repository.updateNote(note)
_noteState.emit(NoteState(isEdited = true))
} catch (e: Exception) {
_noteState.emit(NoteState(error = e.message))
print(e.message)
}
}
fun deleteById(id: Int) = viewModelScope.launch {
_noteState.emit(NoteState(isLoading = true))
try {
repository.deleteNote(id)
_noteState.emit(NoteState(isDeleted = true))
} catch (e: Exception) {
_noteState.emit(NoteState(error = e.message))
print(e.message)
}
}
fun updateTitle(title: String) {
note = note.copy(title = title)
}
fun updateContent(content: String) {
note = note.copy(content = content)
}
fun openDialog() {
openDialog = true
}
fun closeDialog() {
openDialog = false
}
fun resetNoteState() = viewModelScope.launch {
_noteState.emit(NoteState(isDeleted = false, isEdited = false, isLoading = false))
}
}
| 0
|
Kotlin
|
0
| 0
|
392c854505309c39d3963e9fc0c7124874b78c16
| 2,541
|
NoteApp-JetpackCompose
|
MIT License
|
src/test/kotlin/net/maizegenetics/phgv2/brapi/BrapiSetupUtils.kt
|
maize-genetics
| 696,835,682
| false
|
{"Kotlin": 607160, "Shell": 262}
|
package net.maizegenetics.phgv2.brapi
import com.github.ajalt.clikt.testing.test
import com.google.common.io.Files
import net.maizegenetics.phgv2.cli.*
import net.maizegenetics.phgv2.utils.bgzipAndIndexGVCFfile
import java.io.File
import kotlin.test.assertEquals
/**
* This function creates a tiledb dataset from the smallseq assemblies and loads the smallseq vcf files into it.
* This is needed for testing various brapi endpoint.
* It will also create the AGC compressed files from the smallSeq fastas.
*/
fun createSmallSeqTiledb() {
val setupEnv = SetupEnvironment()
println("createSmallSeqTiledb: calling setupEnv")
setupEnv.test("--output-dir ${TestExtension.tempDir}")
//Run InitDB
println("createSmallSeqTiledb - calling Initdb")
val initdb = Initdb()
initdb.test("--db-path ${TestExtension.testTileDBURI}")
//Create the agc file:
println("createSmallSeqTiledb - calling AgcCompress")
val agcCompress = AgcCompress()
var agcResult = agcCompress.test("--fasta-list ${TestExtension.smallseqAssembliesListFile} --db-path ${TestExtension.testTileDBURI} --reference-file ${TestExtension.smallseqRefFile}")
println(agcResult.output)
//Load All HVCFs into Tile DB
println("createSmallSeqTiledb - calling LoadVcf")
loadVcfFiles()
}
fun resetDirs() {
File(TestExtension.tempDir).deleteRecursively()
File(TestExtension.asmDir).deleteRecursively()
File(TestExtension.testVCFDir).deleteRecursively()
File(TestExtension.testMafDir).deleteRecursively()
File(TestExtension.testInputFastaDir).deleteRecursively()
File(TestExtension.testOutputFastaDir).deleteRecursively()
File(TestExtension.testOutputGVCFDIr).deleteRecursively()
File(TestExtension.testTileDBURI).deleteRecursively()
File(TestExtension.tempDir).mkdirs()
File(TestExtension.asmDir).mkdirs()
File(TestExtension.testVCFDir).mkdirs()
File(TestExtension.testMafDir).mkdirs()
File(TestExtension.testInputFastaDir).mkdirs()
File(TestExtension.testOutputFastaDir).mkdirs()
File(TestExtension.testOutputGVCFDIr).mkdirs()
File(TestExtension.testTileDBURI).mkdirs()
}
fun loadVcfFiles() {
// copy the files from data/test/smallseq to the tempDir
// call bgzip to get the files we need for the test
var origHvcfFile = "data/test/smallseq/Ref.h.vcf"
var testHvcfFile = "${TestExtension.testVCFDir}Ref.h.vcf"
Files.copy(File(origHvcfFile), File(testHvcfFile))
// call bgzipAndIndexGVCFfile to zip and index the file
bgzipAndIndexGVCFfile(testHvcfFile)
// Copy LineA h.vcf
origHvcfFile = "data/test/smallseq/LineA.h.vcf"
testHvcfFile = "${TestExtension.testVCFDir}LineA.h.vcf"
Files.copy(File(origHvcfFile), File(testHvcfFile))
// call bgzipAndIndexGVCFfile to zip and index the file
bgzipAndIndexGVCFfile(testHvcfFile)
// Copy LineB h.vcf
origHvcfFile = "data/test/smallseq/LineB.h.vcf"
testHvcfFile = "${TestExtension.testVCFDir}LineB.h.vcf"
Files.copy(File(origHvcfFile), File(testHvcfFile))
// call bgzipAndIndexGVCFfile to zip and index the file
bgzipAndIndexGVCFfile(testHvcfFile)
// load the vcf files stored in the data/test/smallseq folder
// This will load LineA.gvcf to the gvcf_dataset and Ref.hvcf to the hvcf_dataset
println("loadVcfFiles - loading to tiledb")
val loadVCF = LoadVcf()
val vcfDir = TestExtension.testVCFDir
val dbPath = "${TestExtension.testTileDBURI}"
var result = loadVCF.test("--vcf-dir ${vcfDir} --db-path ${dbPath} ")
assertEquals(result.statusCode, 0)
}
| 2
|
Kotlin
|
0
| 2
|
92a76d0db9cc2e0da1361bf72e68d210101152ba
| 3,587
|
phg_v2
|
Apache License 2.0
|
sudovirtualcards/src/androidTest/java/com/sudoplatform/sudovirtualcardssimulator/types/outputs/ParcelTest.kt
|
sudoplatform
| 287,155,437
| false
|
{"Kotlin": 1055433}
|
/*
* Copyright © 2024 Anonyome Labs, Inc. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package com.sudoplatform.sudovirtualcardssimulator.types.outputs
import android.os.Bundle
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.sudoplatform.sudovirtualcards.simulator.types.inputs.BillingAddress
import com.sudoplatform.sudovirtualcards.simulator.types.outputs.SimulatorMerchant
import com.sudoplatform.sudovirtualcards.types.CurrencyAmount
import io.kotlintest.shouldBe
import org.junit.Test
import org.junit.runner.RunWith
import java.util.Date
/**
* Test the public facing data classes can be written into and read from a [Bundle]
*/
@RunWith(AndroidJUnit4::class)
class ParcelTest {
@Test
fun parcellableClassesCanBeParcelledAndUnparcelled() {
val currency = CurrencyAmount("AUD", 4200)
val merchant = SimulatorMerchant(
id = "id",
name = "Teds Doggie Treats",
description = "The yummiest dog treats around",
mcc = "1234",
city = "Robina",
state = "Queensland",
postalCode = "4230",
country = "AU",
currency = "AUD",
declineAfterAuthorization = false,
declineBeforeAuthorization = false,
createdAt = Date(42L),
updatedAt = Date(43L),
)
val billingAddress = BillingAddress(
addressLine1 = "123 Nowhere St",
addressLine2 = "Flat 202",
city = "Robina",
state = "Queensland",
postalCode = "4230",
country = "AU",
)
val bundle = Bundle()
bundle.putParcelable("currency", currency)
bundle.putParcelable("merchant", merchant)
bundle.putParcelable("billingAddress", billingAddress)
val bundle2 = Bundle(bundle)
val currency2 = bundle2.getParcelable<CurrencyAmount>("currency")
val merchant2 = bundle2.getParcelable<SimulatorMerchant>("merchant")
val billingAddress2 = bundle2.getParcelable<BillingAddress>("billingAddress")
currency2 shouldBe currency
merchant2 shouldBe merchant
billingAddress2 shouldBe billingAddress
}
}
| 0
|
Kotlin
|
0
| 0
|
8e15044222a7b853234fe6994994d5969f6be0da
| 2,233
|
sudo-virtual-cards-android
|
Apache License 2.0
|
debugger/src/main/kotlin/org/wint3794/ftc/pathfollower/debugger/geometry/Line.kt
|
WinT-3794
| 267,687,048
| false
| null |
package org.wint3794.ftc.pathfollower.debugger.geometry
data class Line(var x1: Double, var y1: Double, var x2: Double, var y2: Double)
| 0
|
Kotlin
|
1
| 0
|
8b05c46ddc25317158c9cf92ce9c68fd3e1b9c6e
| 136
|
PathFollower
|
Apache License 2.0
|
src/main/kotlin/pl/michalkowol/configurations/CommonModule.kt
|
michalkowol
| 79,121,224
| false
| null |
package pl.michalkowol.configurations
import com.google.inject.AbstractModule
import com.google.inject.Provides
import com.softwareberg.HttpClient
import com.softwareberg.JsonMapper
import com.softwareberg.SimpleHttpClient
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import pl.michalkowol.jira.TaskCsvFactory
import pl.michalkowol.jira.Tempo
import pl.michalkowol.jira.TempoClient
import pl.michalkowol.jira.TempoController
import pl.michalkowol.web.HttpServer
import pl.michalkowol.web.StaticFilesController
import pl.michalkowol.web.errors.ErrorsController
import javax.inject.Singleton
@Suppress("TooManyFunctions")
class CommonModule : AbstractModule() {
override fun configure() {
// no-op
}
@Singleton
@Provides
private fun provideConfig(): Config = ConfigFactory.load()
@Singleton
@Provides
private fun provideServerConfiguration(config: Config): ServerConfiguration {
val port = config.getInt("server.port")
return ServerConfiguration(port)
}
@Singleton
@Provides
private fun provideJsonMapper(): JsonMapper = JsonMapper.create()
@Singleton
@Provides
private fun provideErrorsController(jsonMapper: JsonMapper): ErrorsController = ErrorsController(jsonMapper)
@Singleton
@Provides
private fun provideStaticFilesController(): StaticFilesController = StaticFilesController()
@Singleton
@Provides
private fun provideTaskCsvFactory(): TaskCsvFactory = TaskCsvFactory()
@Singleton
@Provides
private fun provideHttpClient(): HttpClient = SimpleHttpClient.create()
@Singleton
@Provides
private fun provideTempoClient(httpClient: HttpClient): TempoClient = TempoClient(httpClient)
@Singleton
@Provides
private fun provideTempo(tempoClient: TempoClient): Tempo = Tempo(tempoClient)
@Singleton
@Provides
private fun provideTempoController(
taskCsvFactory: TaskCsvFactory,
tempo: Tempo
): TempoController = TempoController(taskCsvFactory, tempo)
@Singleton
@Provides
private fun provideHttpServer(
serverConfiguration: ServerConfiguration,
errorsController: ErrorsController,
staticFilesController: StaticFilesController,
tempoController: TempoController
): HttpServer = HttpServer(
serverConfiguration,
errorsController,
staticFilesController,
tempoController
)
}
| 0
|
Kotlin
|
0
| 5
|
26b0a4dad6cfb45b0849339aaf068ed8e1c2fec0
| 2,467
|
jira-tempo
|
ISC License
|
kt/godot-library/src/main/kotlin/godot/gen/godot/ENetMultiplayerPeer.kt
|
utopia-rise
| 289,462,532
| false
| null |
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY!
@file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier",
"UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST",
"RemoveRedundantQualifierName", "NOTHING_TO_INLINE", "NON_FINAL_MEMBER_IN_OBJECT",
"RedundantVisibilityModifier", "RedundantUnitReturnType", "MemberVisibilityCanBePrivate")
package godot
import godot.`annotation`.GodotBaseType
import godot.core.GodotError
import godot.core.VariantType.LONG
import godot.core.VariantType.NIL
import godot.core.VariantType.OBJECT
import godot.core.VariantType.STRING
import godot.core.memory.TransferContext
import kotlin.Boolean
import kotlin.Int
import kotlin.Long
import kotlin.String
import kotlin.Suppress
import kotlin.Unit
import kotlin.jvm.JvmOverloads
@GodotBaseType
public open class ENetMultiplayerPeer : MultiplayerPeer() {
public val host: ENetConnection?
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_ENETMULTIPLAYERPEER_GET_HOST,
OBJECT)
return (TransferContext.readReturnValue(OBJECT, true) as ENetConnection?)
}
public override fun new(scriptIndex: Int): Boolean {
callConstructor(ENGINECLASS_ENETMULTIPLAYERPEER, scriptIndex)
return true
}
@JvmOverloads
public fun createServer(
port: Int,
maxClients: Int = 32,
maxChannels: Int = 0,
inBandwidth: Int = 0,
outBandwidth: Int = 0,
): GodotError {
TransferContext.writeArguments(LONG to port.toLong(), LONG to maxClients.toLong(), LONG to maxChannels.toLong(), LONG to inBandwidth.toLong(), LONG to outBandwidth.toLong())
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_ENETMULTIPLAYERPEER_CREATE_SERVER,
LONG)
return GodotError.from(TransferContext.readReturnValue(LONG) as Long)
}
@JvmOverloads
public fun createClient(
address: String,
port: Int,
channelCount: Int = 0,
inBandwidth: Int = 0,
outBandwidth: Int = 0,
localPort: Int = 0,
): GodotError {
TransferContext.writeArguments(STRING to address, LONG to port.toLong(), LONG to channelCount.toLong(), LONG to inBandwidth.toLong(), LONG to outBandwidth.toLong(), LONG to localPort.toLong())
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_ENETMULTIPLAYERPEER_CREATE_CLIENT,
LONG)
return GodotError.from(TransferContext.readReturnValue(LONG) as Long)
}
public fun createMesh(uniqueId: Int): GodotError {
TransferContext.writeArguments(LONG to uniqueId.toLong())
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_ENETMULTIPLAYERPEER_CREATE_MESH,
LONG)
return GodotError.from(TransferContext.readReturnValue(LONG) as Long)
}
public fun addMeshPeer(peerId: Int, host: ENetConnection): GodotError {
TransferContext.writeArguments(LONG to peerId.toLong(), OBJECT to host)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_ENETMULTIPLAYERPEER_ADD_MESH_PEER,
LONG)
return GodotError.from(TransferContext.readReturnValue(LONG) as Long)
}
public fun setBindIp(ip: String): Unit {
TransferContext.writeArguments(STRING to ip)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_ENETMULTIPLAYERPEER_SET_BIND_IP,
NIL)
}
public fun getPeer(id: Int): ENetPacketPeer? {
TransferContext.writeArguments(LONG to id.toLong())
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_ENETMULTIPLAYERPEER_GET_PEER,
OBJECT)
return (TransferContext.readReturnValue(OBJECT, true) as ENetPacketPeer?)
}
public companion object
}
| 47
| null |
28
| 412
|
fe7379a450ed32ad069f3b672709a2520b86f092
| 3,649
|
godot-kotlin-jvm
|
MIT License
|
app/src/main/java/com/developerbreach/developerbreach/repository/database/DataObjectConvertors.kt
|
RajashekarRaju
| 285,625,118
| false
|
{"Kotlin": 164789}
|
package com.developerbreach.developerbreach.repository.database
import com.developerbreach.developerbreach.model.Article
import com.developerbreach.developerbreach.repository.database.entity.FavoritesEntity
fun List<FavoritesEntity>.asDomainModel(): List<Article> {
return map {
Article(
articleId = it.articleId,
name = it.name,
banner = it.banner
)
}
}
fun Article.asDatabaseModel(): FavoritesEntity {
return FavoritesEntity(
articleId = this.articleId,
name = this.name,
banner = this.banner
)
}
| 0
|
Kotlin
|
0
| 0
|
65e3019f6babda8ca722a734f5d5b23012b5f7e9
| 593
|
developers-breach-android
|
Apache License 2.0
|
src/test/java/org/nixos/idea/lang/references/AbstractSymbolNavigationTests.kt
|
NixOS
| 67,685,297
| false
|
{"Java": 237856, "Kotlin": 31246, "Lex": 6061, "Nix": 2837}
|
package org.nixos.idea.lang.references
import com.intellij.find.usages.api.UsageAccess
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.testFramework.PsiTestUtil
import com.intellij.testFramework.fixtures.CodeInsightTestFixture
import org.intellij.lang.annotations.Language
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DynamicNode
import org.nixos.idea._testutil.Markers
import org.nixos.idea._testutil.TestFactoryDsl
import org.nixos.idea._testutil.WithIdeaPlatform
import org.nixos.idea.file.NixFileType
import org.nixos.idea.lang.builtins.NixBuiltin
import org.nixos.idea.lang.references.symbol.NixSymbol
import org.nixos.idea.psi.NixDeclarationHost
import org.nixos.idea.settings.NixSymbolSettings
@WithIdeaPlatform.OnEdt
@WithIdeaPlatform.CodeInsight
@Suppress("UnstableApiUsage")
abstract class AbstractSymbolNavigationTests {
private lateinit var myFixture: CodeInsightTestFixture
private lateinit var mySymbolHelper: SymbolTestHelper
@BeforeEach
fun setUp(fixture: CodeInsightTestFixture) {
myFixture = fixture
mySymbolHelper = SymbolTestHelper(fixture)
}
class Config {
@Language("HTML")
lateinit var code: String
var findDeclarations = true
var findReferences = true
var resolveDeclarations = true
var resolveReferences = true
}
/**
* Test factory for symbol navigation.
*
* ```
* @TestFactory
* fun simple_assignment() = test {
* code = """
* let <symbol>x.<decl>y</decl></symbol> = "..."; in
* x.<ref>y</ref>
* """.trimIndent()
* }
* ```
*
* The code may contain the following tags:
*
* * **`<builtin>...</builtin>`**
* The name of a [NixBuiltin] which is used by the test.
* The location of this tag doesn't have any impact, only the content.
* By convention, it is recommended to but this tag into a comment at the top of the file.
* * **`<symbol>...</symbol>`**
* The attribute path of a [NixUserSymbol] which is used by the test.
* The tag must be located within the corresponding [NixDeclarationHost].
* The exact location within the declaration host doesn't have any impact.
* There must be at most one symbol per declaration host.
* * **`<decl>...</decl>`**
* The identifiers which declare the symbol.
* The test factory verifies that each marked identifier is a declaration
* which resolves to the symbol within the same declaration host.
* * **`<ref>...</ref>`**
* The identifiers which reference the symbols.
* The test factory verifies that each marked identifier is a reference
* which resolves to all the marked symbols and builtins.
*
* Based on the given tags, the method will generate tests for the following scenarios:
*
* * **Go to Declaration:**
* For each symbol, try to resolve all declarations in the same declaration host.
* * **Find Usages:**
* For each symbol, try to find all usages (declarations and references).
* * **Resolve Declaration:**
* For each declaration, try to resolve the matching symbol.
* * **Resolve References:**
* For each reference, try to resolve all symbols.
*/
fun test(init: Config.() -> Unit): List<DynamicNode> {
val config = Config()
config.init()
val markers = Markers.parse(config.code, TAG_BUILTIN, TAG_SYMBOL, TAG_DECL, TAG_REF)
val unmarkedCode = markers.unmarkedText()
val symbolMarkers = markers.markers(TAG_BUILTIN, TAG_SYMBOL)
val declarationMarkers = markers.markers(TAG_DECL)
val referenceMarkers = markers.markers(TAG_REF)
NixSymbolSettings.getInstance().enabled = true
val file = myFixture.configureByText(NixFileType.INSTANCE, unmarkedCode)
PsiTestUtil.checkErrorElements(file) // Fail early if there is a syntax error
return TestFactoryDsl.testFactory {
if (config.findDeclarations) {
containers("go to declaration", symbolMarkers) { symbolMarker ->
test("jump to first declaration = true") {
testGoToDeclaration(file, symbolMarker, declarationMarkers, true)
}
test("jump to first declaration = false") {
testGoToDeclaration(file, symbolMarker, declarationMarkers, false)
}
}
}
if (config.findReferences) {
containers("find usages", symbolMarkers) { symbolMarker ->
test("show declarations as usages = false") {
NixSymbolSettings.getInstance().showDeclarationsAsUsages = false
testFindUsages(file, symbolMarker, referenceMarkers, false)
}
test("show declarations as usages = true") {
NixSymbolSettings.getInstance().showDeclarationsAsUsages = true
if (config.findDeclarations) {
val withDeclarations = referenceMarkers.withMarkers(
declarationMarkers.filterSameHostAs(
file,
symbolMarker.start()
).stream(),
TAG_DECL
)
testFindUsages(file, symbolMarker, withDeclarations, false)
} else {
testFindUsages(file, symbolMarker, referenceMarkers, true)
}
}
}
}
if (config.resolveDeclarations) {
tests("resolve declaration", declarationMarkers) {
val offset = it.start()
val symbols = getSymbols(file, symbolMarkers.filterSameHostAs(file, offset)).toSet()
val declaration = mySymbolHelper.findDeclaration(NixSymbolDeclaration::class.java, file, offset)
Assertions.assertEquals(it.range(), declaration.absoluteRange)
Assertions.assertTrue(declaration.symbol in symbols)
}
}
if (config.resolveReferences) {
tests("resolve reference", referenceMarkers) {
val symbols = getSymbols(file, symbolMarkers).toSet()
val reference = mySymbolHelper.findReference(NixSymbolReference::class.java, file, it.start())
Assertions.assertEquals(it.range(), reference.element.textRange.cutOut(reference.rangeInElement))
Assertions.assertEquals(symbols, reference.resolveReference().toSet())
}
}
}
}
private fun getSymbols(file: PsiFile, symbolMarkers: Iterable<Markers.Marker>): Iterable<NixSymbol> {
return symbolMarkers.map { getSymbol(file, it) }
}
private fun getSymbol(file: PsiFile, marker: Markers.Marker): NixSymbol {
return when (marker.tagName()) {
TAG_BUILTIN -> {
val name = marker.range().substring(file.text)
val instance = NixBuiltin.resolveBuiltin(name)
NixSymbol.builtin(requireNotNull(instance))
}
TAG_SYMBOL -> {
val attrPath = marker.range().substring(file.text)
mySymbolHelper.findSymbol(file, attrPath, marker.start())
}
else -> throw IllegalStateException("Unknown tag name: " + marker.tagName())
}
}
private fun Iterable<Markers.Marker>.filterSameHostAs(file: PsiFile, offset: Int): List<Markers.Marker> {
val needle = PsiTreeUtil.findElementOfClassAtOffset(file, offset, NixDeclarationHost::class.java, false)
return this.filter {
val host = PsiTreeUtil.findElementOfClassAtOffset(file, it.start(), NixDeclarationHost::class.java, false)
host == needle
}
}
private fun testGoToDeclaration(
file: PsiFile,
symbolMarker: Markers.Marker,
declarationMarkers: Markers,
jumpToFirstDeclaration: Boolean
) {
NixSymbolSettings.getInstance().jumpToFirstDeclaration = jumpToFirstDeclaration
val symbol = getSymbol(file, symbolMarker)
val navigationTargets = mySymbolHelper.findNavigationTargets(NixNavigationTarget::class.java, symbol)
var expected = declarationMarkers
.filterSameHostAs(file, symbolMarker.start())
.map { it.range() }
if (jumpToFirstDeclaration) {
expected = expected.stream().limit(1).toList()
}
Assertions.assertEquals(
Markers.create(
declarationMarkers.unmarkedText(),
TAG_DECL,
expected
),
Markers.create(
declarationMarkers.unmarkedText(),
TAG_DECL,
navigationTargets.stream().map { it.rangeInFile }.toList()
)
)
}
private fun testFindUsages(
file: PsiFile,
symbolMarker: Markers.Marker,
usageMarkers: Markers,
ignoreDeclarations: Boolean
) {
val symbol = getSymbol(file, symbolMarker)
Assertions.assertEquals(
usageMarkers,
Markers.create(
usageMarkers.unmarkedText(),
mySymbolHelper.findUsages(symbol, file)
.filter { !it.declaration }
.flatMap {
val nixUsage = it as NixUsage
Assertions.assertEquals(file, nixUsage.file)
val isDeclaration = nixUsage.computeAccess() == UsageAccess.Write
when {
isDeclaration && ignoreDeclarations -> emptyList()
isDeclaration -> listOf(Markers.marker(TAG_DECL, nixUsage.range))
else -> listOf(Markers.marker(TAG_REF, nixUsage.range))
}
},
TAG_DECL, TAG_REF
)
)
}
companion object {
private val TAG_BUILTIN: Markers.TagName = Markers.tagName("builtin")
private val TAG_SYMBOL: Markers.TagName = Markers.tagName("symbol")
private val TAG_REF: Markers.TagName = Markers.tagName("ref")
private val TAG_DECL: Markers.TagName = Markers.tagName("decl")
}
}
| 12
|
Java
|
28
| 176
|
2384013f2699339c985e78f531b2139beb000744
| 10,745
|
nix-idea
|
Apache License 2.0
|
app/src/main/java/com/engdiary/mureng/ui/base/BaseViewModel.kt
|
YAPP-18th
| 331,208,681
| false
| null |
package com.engdiary.mureng.ui.base
import android.content.Context
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.engdiary.mureng.data.domain.SingleLiveEvent
import com.engdiary.mureng.data.request.UserExistRequest
import com.engdiary.mureng.network.MurengRepository
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.disposables.Disposable
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.launch
import timber.log.Timber
import javax.inject.Inject
/**
* BaseViewModel
*/
open class BaseViewModel @Inject constructor(
private val murengRepository: MurengRepository
) : ViewModel() {
private val compositeDisposable = CompositeDisposable()
private val _navigateToSignup = SingleLiveEvent<Unit>()
val navigateToSignup: LiveData<Unit>
get() = _navigateToSignup
private val _navigateToHome = SingleLiveEvent<Unit>()
val navigateToHome: LiveData<Unit>
get() = _navigateToHome
/** viewModelScope 에서 Exception 이 발생할 시 처리하는 핸들러 */
val vmExceptionHandler = CoroutineExceptionHandler { coroutineContext, throwable ->
Timber.i("$coroutineContext $throwable")
}
/** 생성자 개념으로 생각하면 편할듯 */
init {
/**
* viewModelScope 를 사용하면 lifecycle 을 인식하는 CoroutineScope 를 만들 수 있다.
* viewModelScope 블록에서 실행되는 작업은 별도의 처리를 하지 않아도
* ViewModel 이 clear 되는 순간 자동으로 취소된다.
*
* @see [[Android & Coroutine] ViewModelScope, LiveData Builder 사용하기](https://zion830.tistory.com/64)
*/
viewModelScope.launch {}
}
/** UI 의 onDestroy 개념으로 생각하면 편할듯 */
override fun onCleared() {
compositeDisposable.clear()
super.onCleared()
}
/** 카카오 로그인 서버 통신 */
open fun addKakaoUser(accessToken: String, refreshToken: String, userId: Long) {
murengRepository.settingUser(
userExistRequest = UserExistRequest(providerAccessToken = accessToken, providerName = "kakao"),
successAction = {
_navigateToHome.call()
},
failAction = {
_navigateToSignup.call()
})
}
/**
* [Disposable] 객체를 [compositeDisposable] 에 넣는다.
* [compositeDisposable] 에 추가된 [Disposable] 들은
* [onCleared] 단계에서 모두 clear 된다.
*/
protected fun Disposable.addDisposable() {
compositeDisposable.add(this)
}
/**
* UI 단계에서 onResume 일 시 실행해주어야 하는 로직을 명세한다.
* 필수가 아니므로 추상화는 하지 않는다.
*/
open fun onResume() {
}
open fun onAttach(context: Context) {
}
}
| 11
|
Kotlin
|
1
| 3
|
4052cc746ef8be6c922ca7ef523ace28134bd052
| 2,688
|
Android-Team-1-Frontend
|
Apache License 2.0
|
reports/src/main/kotlin/com/jakewharton/diffuse/report/text/JarInfoTextReport.kt
|
usefulness
| 456,081,262
| true
|
{"Kotlin": 143412}
|
package com.jakewharton.diffuse.report.text
import com.jakewharton.diffuse.format.ArchiveFile.Type
import com.jakewharton.diffuse.format.Jar
import com.jakewharton.diffuse.info.toSummaryTable
import com.jakewharton.diffuse.report.Report
internal class JarInfoTextReport(private val jar: Jar) : Report {
override fun write(appendable: Appendable) {
appendable.apply {
appendLine(jar.filename)
appendLine()
appendLine(jar.files.toSummaryTable("JAR", Type.JAR_TYPES))
appendLine()
appendLine(listOf(jar).toSummaryTable("CLASSES"))
}
}
override fun toString() = buildString { write(this) }
}
| 1
|
Kotlin
|
0
| 5
|
6ddb448e783a5868a217ce1b4f4bd2fa5958a9ac
| 635
|
diffuse
|
Apache License 2.0
|
app/src/main/java/ar/com/wolox/android/example/network/NetworkHeaders.kt
|
wolox-training
| 337,096,244
| false
| null |
package ar.com.wolox.android.example.network
object NetworkHeaders {
const val ACCESS_TOKEN = "Access-Token"
const val UID = "Uid"
const val CLIENT = "Client"
}
| 0
|
Kotlin
|
0
| 0
|
4687a08577516d021ab24afd86d229ac877617d0
| 173
|
ldm-android
|
MIT License
|
src/main/kotlin/com/bajdcc/LALR1/interpret/os/user/routine/URGrep.kt
|
bajdcc
| 32,624,604
| false
|
{"Kotlin": 1131761, "HTML": 42480, "CSS": 37889, "JavaScript": 2703}
|
package com.bajdcc.LALR1.interpret.os.user.routine
import com.bajdcc.LALR1.interpret.os.IOSCodePage
import com.bajdcc.util.ResourceLoader
/**
* 【用户态】过滤流
*
* @author bajdcc
*/
class URGrep : IOSCodePage {
override val name: String
get() = "/usr/p/grep"
override val code: String
get() = ResourceLoader.load(javaClass)
}
| 0
|
Kotlin
|
20
| 65
|
90b19af98da99b53bba5b3269ad5666df7c05e49
| 350
|
jMiniLang
|
MIT License
|
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/broken/Man.kt
|
Tlaster
| 560,394,734
| false
|
{"Kotlin": 25133302}
|
package moe.tlaster.icons.vuesax.vuesaxicons.broken
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import moe.tlaster.icons.vuesax.vuesaxicons.BrokenGroup
public val BrokenGroup.Man: ImageVector
get() {
if (_man != null) {
return _man!!
}
_man = Builder(name = "Man", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth
= 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(4.27f, 18.68f)
curveTo(5.69f, 20.4f, 7.84f, 21.5f, 10.25f, 21.5f)
curveTo(14.53f, 21.5f, 18.0f, 18.03f, 18.0f, 13.75f)
curveTo(18.0f, 9.47f, 14.53f, 6.0f, 10.25f, 6.0f)
curveTo(5.97f, 6.0f, 2.5f, 9.47f, 2.5f, 13.75f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(21.5f, 2.5f)
lineTo(16.0f, 8.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(15.0f, 2.5f)
horizontalLineTo(21.5f)
verticalLineTo(9.0f)
}
}
.build()
return _man!!
}
private var _man: ImageVector? = null
| 0
|
Kotlin
|
0
| 2
|
b8a8231e6637c2008f675ae76a3423b82ee53950
| 2,400
|
VuesaxIcons
|
MIT License
|
facebook-android-sdk-main/facebook-core/src/test/kotlin/com/facebook/appevents/AppEventStoreTest.kt
|
PESP-privacy-preserving-social-SDK
| 774,671,173
| false
|
{"Kotlin": 2660453, "Java": 1785287, "Python": 24158, "Shell": 14666, "AIDL": 11889}
|
package com.facebook.appevents
import android.os.Bundle
import com.facebook.FacebookPowerMockTestCase
import com.facebook.appevents.internal.AppEventUtility
import com.facebook.internal.AttributionIdentifiers
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.spy
import com.nhaarman.mockitokotlin2.whenever
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.powermock.api.mockito.PowerMockito
import org.powermock.core.classloader.annotations.PrepareForTest
@PrepareForTest(AppEventStore::class, AppEventUtility::class, PersistedEvents::class)
class AppEventStoreTest : FacebookPowerMockTestCase() {
private lateinit var lastPersistedEvents: PersistedEvents
private val accessTokenAppIdPair = AccessTokenAppIdPair("swagtoken", "yoloapplication")
private val appevent = AppEvent("ctxName", "eventName", 0.0, Bundle(), true, true, null)
private val accessTokenAppIdPair2 = AccessTokenAppIdPair("anothertoken1337", "yoloapplication")
private val sessionEventsState = SessionEventsState(AttributionIdentifiers(), "anonGUID")
@Before
fun init() {
PowerMockito.mockStatic(AppEventStore::class.java)
PowerMockito.mockStatic(AppEventUtility::class.java)
whenever(AppEventStore.persistEvents(any(), any())).thenCallRealMethod()
whenever(AppEventStore.persistEvents(any())).thenCallRealMethod()
whenever(AppEventStore.saveEventsToDisk(any())).thenAnswer {
lastPersistedEvents = it.getArgument(0) as PersistedEvents
null
}
val map = hashMapOf(accessTokenAppIdPair to mutableListOf(appevent))
val persistedEvents = PersistedEvents(map)
whenever(AppEventStore.readAndClearStore()).thenReturn(persistedEvents)
sessionEventsState.addEvent(appevent)
}
@Test
fun `different tokenpair size increase`() {
AppEventStore.persistEvents(accessTokenAppIdPair2, sessionEventsState)
assertEquals(2, lastPersistedEvents.keySet().size)
}
@Test
fun `same tokenpair size same`() {
AppEventStore.persistEvents(accessTokenAppIdPair, sessionEventsState)
assertEquals(1, lastPersistedEvents.keySet().size)
}
@Test
fun `different tokenpair size same persist event collection`() {
val sessionEventsState = spy(SessionEventsState(AttributionIdentifiers(), "anonGUID"))
val appeventCollection: AppEventCollection = mock()
whenever(appeventCollection.get(any())).thenReturn(sessionEventsState)
whenever(appeventCollection.keySet()).thenReturn(mutableSetOf(accessTokenAppIdPair2))
whenever(sessionEventsState.eventsToPersist).thenCallRealMethod()
sessionEventsState.addEvent(appevent)
AppEventStore.persistEvents(appeventCollection)
assertEquals(2, lastPersistedEvents.keySet().size)
}
@Test
fun `same tokenpair size same persist event collection`() {
val sessionEventsState = spy(SessionEventsState(AttributionIdentifiers(), "anonGUID"))
val appeventCollection: AppEventCollection = mock()
whenever(appeventCollection[any()]).thenReturn(sessionEventsState)
whenever(appeventCollection.keySet()).thenReturn(mutableSetOf(accessTokenAppIdPair))
whenever(sessionEventsState.eventsToPersist).thenCallRealMethod()
sessionEventsState.addEvent(appevent)
AppEventStore.persistEvents(appeventCollection)
assertEquals(1, lastPersistedEvents.keySet().size)
}
}
| 0
|
Kotlin
|
0
| 0
|
fcf4852069e2a9625aa663dc22ccc926e2a94799
| 3,400
|
PESP
|
MIT License
|
app/src/main/java/microteam/data/mapper/ArticleFeedExtFuncs.kt
|
yugal-nandurkar
| 876,869,030
| false
|
{"Kotlin": 114257}
|
package microteam.data.mapper
import microteam.data.local.ArticleEntity
import microteam.data.remote.ArticleFeed
import microteam.utils.Utils
fun List<ArticleFeed>.toArticleEntities(): List<ArticleEntity> {
return map { feedItem ->
feedItem.toArticleEntity()
}
}
fun ArticleFeed.toArticleEntity(): ArticleEntity {
return ArticleEntity(
id = feedItem.link.toUrlPath(),
title = feedItem.title,
link = feedItem.link,
author = feedItem.author,
pubDate = Utils.parsePubDateStringToLong(feedItem.pubDate),
image = feedItem.image,
feedTitle = feedTitle,
)
}
| 0
|
Kotlin
|
0
| 0
|
1a68295d839ec5bbd9ce131fe139d4fe63a6ea13
| 635
|
microteam-android-news
|
MIT License
|
website/src/main/kotlin/ru/rxnnct/dummyclientservergame/website/config/WebSecurityConfig.kt
|
rxnnct
| 507,655,234
| false
| null |
package ru.rxnnct.dummyclientservergame.website.config
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.security.crypto.password.PasswordEncoder
import ru.rxnnct.dummyclientservergame.website.service.UserService
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // TODO: 28.06.2022 populate db (first admin)
class WebSecurityConfig(val userService: UserService) : WebSecurityConfigurerAdapter() {
var passwordEncoder: PasswordEncoder = passwordEncoder()
@Throws(Exception::class)
override fun configure(http: HttpSecurity) {
http
.authorizeRequests()
.antMatchers("/", "/registration").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll()
}
@Throws(Exception::class)
override fun configure(auth: AuthenticationManagerBuilder) {
auth.userDetailsService(userService)
.passwordEncoder(passwordEncoder)
}
}
| 0
|
Kotlin
|
0
| 0
|
f080e3dc6487ad36e2506336c11d0905ece90a3a
| 1,732
|
DummyClientServerGame
|
MIT License
|
app/src/main/java/com/hudson/wanandroid/ui/activity/SearchActivity.kt
|
HudsonAndroid
| 278,809,991
| false
| null |
package com.hudson.wanandroid.ui.activity
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import androidx.activity.OnBackPressedCallback
import androidx.activity.viewModels
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.findNavController
import androidx.work.WorkManager
import com.hudson.wanandroid.R
import com.hudson.wanandroid.databinding.ActivitySearchBinding
import com.hudson.wanandroid.ui.fragment.search.SearchDefaultFragmentDirections
import com.hudson.wanandroid.viewmodel.SearchModel
import com.hudson.wanandroid.works.createPeriodicRequest
import dagger.android.DispatchingAndroidInjector
import dagger.android.support.HasSupportFragmentInjector
import javax.inject.Inject
class SearchActivity : AppCompatActivity(), HasSupportFragmentInjector {
@Inject
lateinit var viewModelFactory : ViewModelProvider.Factory
private val searchModel: SearchModel by viewModels {
viewModelFactory
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding =
DataBindingUtil.setContentView<ActivitySearchBinding>(this, R.layout.activity_search)
binding.ivBack.setOnClickListener{
handleBackInvoke()
}
binding.ivSearch.setOnClickListener{
hideSoftInput()
startSearch(binding)
}
binding.etInput.setOnEditorActionListener { view, actionId, event ->
if(actionId == EditorInfo.IME_ACTION_SEARCH){
hideSoftInput()
startSearch(binding)
true
}else false
}
binding.searchWord = searchModel.searchWord
binding.lifecycleOwner = this
// custom handle back press event
val callback = object : OnBackPressedCallback(true){
override fun handleOnBackPressed() {
handleBackInvoke()
}
}
// 可以不需要移除,因为在LifecycleOwner移除的时候,会自动处理remove
// https://developer.android.google.cn/guide/navigation/navigation-custom-back
onBackPressedDispatcher.addCallback(this, callback)
// 定时清理多余的搜索历史
WorkManager.getInstance(this).enqueue(createPeriodicRequest())
}
private fun hideSoftInput(){
val inputMethodManager =
getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(currentFocus?.windowToken,
InputMethodManager.HIDE_NOT_ALWAYS)
}
private fun startSearch(binding: ActivitySearchBinding) {
val queryWord = binding.etInput.text?.toString()
if (!queryWord.isNullOrBlank()) {
val navController = getNavController()
// if current is first page, we should navigate to result fragment
if (navController.graph.startDestination == navController.currentDestination?.id) {
// jump to search result fragment with params
// 在SearchResultFragment中设置了需要传递的参数
val action =
SearchDefaultFragmentDirections
.actionSearchDefaultFragmentToSearchResultFragment(queryWord)
getNavController().navigate(action)
}
// start search
searchModel.searchWord.value = queryWord
}
}
private fun getNavController() = findNavController(R.id.nav_host_fragment)
private fun handleBackInvoke(){
if(!getNavController().navigateUp()){
finish()
}
}
companion object{
fun start(from: Context){
from.startActivity(Intent(from, SearchActivity::class.java))
}
}
@Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment>
override fun supportFragmentInjector() = dispatchingAndroidInjector
}
| 1
|
Kotlin
|
1
| 0
|
4c0a43cf0fc4cb6d8c4b30a79f5e5301aff7a2d8
| 4,126
|
WanAndroidJetpack
|
Apache License 2.0
|
src/main/kotlin/net/ndrei/teslapoweredthingies/machines/cropfarm/VanillaNetherWartSeed.kt
|
MinecraftModDevelopmentMods
| 77,729,751
| false
| null |
package net.ndrei.teslapoweredthingies.machines.cropfarm
import net.minecraft.init.Blocks
import net.minecraft.init.Items
import net.minecraft.item.ItemStack
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
/**
* Created by CF on 2017-07-07.
*/
class VanillaNetherWartSeed(seed: ItemStack)
: VanillaGenericSeed(seed) {
override fun canPlantHere(world: World, pos: BlockPos): Boolean {
val under = world.getBlockState(pos.down()).block
return under === Blocks.SOUL_SAND
}
companion object {
fun isSeed(stack: ItemStack)
= !stack.isEmpty && (stack.item === Items.NETHER_WART)
}
}
| 21
| null |
4
| 2
|
22fdcf629e195a73dd85cf0ac0c5dda551085e71
| 663
|
Tesla-Powered-Thingies
|
MIT License
|
features/news/src/test/kotlin/eu/acaraus/news/test/rules/UTest.kt
|
alexandrucaraus
| 836,093,916
| false
|
{"Kotlin": 146199}
|
package eu.acaraus.news.test.rules
import eu.acaraus.news.di.DomainDi
import eu.acaraus.news.di.PresentationDi
import org.koin.core.module.Module
import org.koin.ksp.generated.module
import eu.acaraus.shared.test.lib.UnitTest as SharedUnitTest
interface UTest : SharedUnitTest {
override val perFeatureModules: Array<Module>
get() = arrayOf(
DomainDi().module,
PresentationDi().module,
)
}
| 0
|
Kotlin
|
0
| 0
|
cebad85a31082161ac779b821e5aa18482dadc03
| 436
|
androidsamplearch
|
MIT License
|
src/main/kotlin/kolbasa/stats/prometheus/PrometheusConfig.kt
|
vgv
| 631,206,401
| false
|
{"Kotlin": 414702}
|
package kolbasa.stats.prometheus
import io.prometheus.metrics.core.metrics.Counter
import io.prometheus.metrics.core.metrics.Gauge
import io.prometheus.metrics.core.metrics.Histogram
import io.prometheus.metrics.model.registry.PrometheusRegistry
import kolbasa.queue.Checks
import kolbasa.queue.Queue
import kolbasa.stats.prometheus.metrics.Const
import java.time.Duration
sealed class PrometheusConfig {
object None : PrometheusConfig()
data class Config(
/**
* By default, the size of the string to send to Prometheus is calculated in characters, not in bytes, which is much
* faster. If you really need to calculate exact string size in bytes, set this option to true (but it's much slower).
*/
val preciseStringSize: Boolean = false,
/**
* By default, kolbasa measures the queue size every
* [DEFAULT_QUEUE_SIZE_MEASURE_INTERVAL][PrometheusConfig.Config.DEFAULT_QUEUE_SIZE_MEASURE_INTERVAL], however, if
* you want to measure more/less often for specific queues – you can change the default measurement interval here.
*
* Please note that current implementation relies on PostgreSQL vacuum statistics, so, if you don't run vacuum every
* five seconds (for example) it's almost nonsense to measure the queue size every five seconds.
*
* Map key: Queue name
* Map value: Interval
*/
val customQueueSizeMeasureInterval: Map<String, Duration> = emptyMap(),
/**
* Prometheus registry. By default, [PrometheusRegistry.defaultRegistry] is used.
* You can use your custom registry, but you need to change the registry before any
* other queue operations (at application startup, for example).
*/
val registry: PrometheusRegistry = PrometheusRegistry.defaultRegistry
) : PrometheusConfig() {
// ----------------------------------------------------------------------------
// Producer metrics
internal val producerSendCounter: Counter = Counter.builder()
.name("kolbasa_producer_send")
.help("Amount of producer send() calls")
.labelNames("queue", "partial_insert_type")
.register(registry)
internal val producerSendRowsCounter: Counter = Counter.builder()
.name("kolbasa_producer_send_rows")
.help("Amount of all (successful and failed) rows sent by producer send() calls")
.labelNames("queue", "partial_insert_type")
.register(registry)
internal val producerSendFailedRowsCounter: Counter = Counter.builder()
.name("kolbasa_producer_send_rows_failed")
.help("Amount of failed rows sent by producer send() calls")
.labelNames("queue", "partial_insert_type")
.register(registry)
internal val producerSendDuration: Histogram = Histogram.builder()
.name("kolbasa_producer_send_duration_seconds")
.help("Producer send() calls duration")
.labelNames("queue", "partial_insert_type")
.classicOnly()
.classicUpperBounds(*Const.histogramBuckets())
.register(registry)
internal val producerSendBytesCounter: Counter = Counter.builder()
.name("kolbasa_producer_send_bytes")
.help("Amount of bytes sent by producer send() calls")
.labelNames("queue", "partial_insert_type")
.register(registry)
internal val producerQueueSizeGauge: Gauge = Gauge.builder()
.name("kolbasa_producer_queue_size")
.help("Producer queue size")
.labelNames("queue")
.register(registry)
// ----------------------------------------------------------------------------
// Consumer metrics
// Receive
internal val consumerReceiveCounter: Counter = Counter.builder()
.name("kolbasa_consumer_receive")
.help("Amount of consumer receive() calls")
.labelNames("queue")
.register(registry)
internal val consumerReceiveBytesCounter: Counter = Counter.builder()
.name("kolbasa_consumer_receive_bytes")
.help("Amount of bytes read by consumer receive() calls")
.labelNames("queue")
.register(registry)
internal val consumerReceiveRowsCounter: Counter = Counter.builder()
.name("kolbasa_consumer_receive_rows")
.help("Amount of rows received by consumer receive() calls")
.labelNames("queue")
.register(registry)
internal val consumerReceiveDuration: Histogram = Histogram.builder()
.name("kolbasa_consumer_receive_duration_seconds")
.help("Consumer receive() calls duration")
.labelNames("queue")
.classicOnly()
.classicUpperBounds(*Const.histogramBuckets())
.register(registry)
// Delete
internal val consumerDeleteCounter: Counter = Counter.builder()
.name("kolbasa_consumer_delete")
.help("Amount of consumer delete() calls")
.labelNames("queue")
.register(registry)
internal val consumerDeleteRowsCounter: Counter = Counter.builder()
.name("kolbasa_consumer_delete_rows")
.help("Amount of rows removed by consumer delete() calls")
.labelNames("queue")
.register(registry)
internal val consumerDeleteDuration: Histogram = Histogram.builder()
.name("kolbasa_consumer_delete_duration_seconds")
.help("Consumer delete() calls duration")
.labelNames("queue")
.classicOnly()
.classicUpperBounds(*Const.histogramBuckets())
.register(registry)
internal val consumerQueueSizeGauge: Gauge = Gauge.builder()
.name("kolbasa_consumer_queue_size")
.help("Consumer queue size")
.labelNames("queue")
.register(registry)
// ----------------------------------------------------------------------------
// Sweep metrics
internal val sweepCounter: Counter = Counter.builder()
.name("kolbasa_sweep")
.help("Number of sweeps")
.labelNames("queue")
.register(registry)
internal val sweepIterationsCounter: Counter = Counter.builder()
.name("kolbasa_sweep_iterations")
.help("Number of sweep iterations (every sweep can have multiple iterations)")
.labelNames("queue")
.register(registry)
internal val sweepRowsRemovedCounter: Counter = Counter.builder()
.name("kolbasa_sweep_removed_rows")
.help("Number of rows removed by sweep")
.labelNames("queue")
.register(registry)
internal val sweepDuration: Histogram = Histogram.builder()
.name("kolbasa_sweep_duration_seconds")
.help("Sweep duration")
.labelNames("queue")
.classicOnly()
.classicUpperBounds(*Const.histogramBuckets())
.register(registry)
init {
customQueueSizeMeasureInterval.forEach { (queueName, customInterval) ->
Checks.checkCustomQueueSizeMeasureInterval(queueName, customInterval)
}
}
class Builder internal constructor() {
private var preciseStringSize: Boolean = false
private var customQueueSizeMeasureInterval: MutableMap<String, Duration> = mutableMapOf()
private var registry: PrometheusRegistry = PrometheusRegistry.defaultRegistry
fun customQueueSizeMeasureInterval(queueName: String, customInterval: Duration) = apply {
customQueueSizeMeasureInterval[queueName] = customInterval
}
fun customQueueSizeMeasureInterval(queue: Queue<*, *>, customInterval: Duration) =
customQueueSizeMeasureInterval(queue.name, customInterval)
fun preciseStringSize(preciseStringSize: Boolean) = apply { this.preciseStringSize = preciseStringSize }
fun registry(registry: PrometheusRegistry) = apply { this.registry = registry }
fun build() = Config(preciseStringSize, customQueueSizeMeasureInterval, registry)
}
companion object {
internal val MIN_QUEUE_SIZE_MEASURE_INTERVAL = Duration.ofSeconds(1)
internal val DEFAULT_QUEUE_SIZE_MEASURE_INTERVAL = Duration.ofSeconds(15)
@JvmStatic
fun builder(): Builder = Builder()
}
}
}
| 7
|
Kotlin
|
1
| 7
|
59027ead3c2c5463ed02ab80dc086978c2aaa79b
| 8,705
|
kolbasa
|
Apache License 2.0
|
app/src/test/java/com/jorgedguezm/elections/data/DataReadWriteTest.kt
|
Narsuf
| 52,900,182
| false
| null |
package com.jorgedguezm.elections.data
import androidx.room.Room
import com.jorgedguezm.elections.data.DataUtils.Companion.generateElection
import com.jorgedguezm.elections.room.Database
import com.jorgedguezm.elections.room.ElectionDao
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.Rule
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.test.core.app.ApplicationProvider
import junit.framework.TestCase.assertEquals
import junit.framework.TestCase.assertTrue
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestCoroutineDispatcher
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.setMain
@RunWith(RobolectricTestRunner::class)
class DataReadWriteTest {
private lateinit var electionDao: ElectionDao
private lateinit var db: Database
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
@ExperimentalCoroutinesApi
private val testDispatcher = TestCoroutineDispatcher()
@ExperimentalCoroutinesApi
@Before
fun createDb() {
db = Room.inMemoryDatabaseBuilder(ApplicationProvider
.getApplicationContext(), Database::class.java)
.allowMainThreadQueries()
.build()
electionDao = db.electionDao()
Dispatchers.setMain(testDispatcher)
}
@After
fun closeDb() {
db.close()
}
@ExperimentalCoroutinesApi
@Test
fun writeElectionAndRead() = runBlockingTest {
val election = generateElection()
electionDao.insertElection(election)
val elections = electionDao.queryElections(election.place, election.chamberName)
val dbElection = electionDao.getElection(election.id)
assertTrue(elections.contains(election))
assertEquals(dbElection, election)
}
}
| 0
|
Kotlin
|
0
| 1
|
d67dc9ee1f96261fefecafb17938f0c21700e351
| 2,007
|
Elections
|
Apache License 2.0
|
noteServer/note/src/test/kotlin/com/rabbitcat/note/controller/member/MemberControllerTest.kt
|
bcc829
| 155,066,475
| false
| null |
package com.rabbitcat.note.controller.member
import com.rabbitcat.note.domain.member.Member
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.web.client.TestRestTemplate
import org.springframework.boot.test.web.client.exchange
import org.springframework.boot.web.server.LocalServerPort
import org.springframework.http.*
import org.springframework.test.context.junit4.SpringRunner
@RunWith(SpringRunner::class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class MemberControllerTest {
// @Autowired
// lateinit var webTestClient : WebTestClient
@Autowired
lateinit var restTemplate: TestRestTemplate
@LocalServerPort
var randomServerPort: Int = 0
var baseURL = ""
@Before
fun setUp() {
// webTestClient = webTestClient
// .mutate()
// .responseTimeout(Duration.ofMillis(30000))
// .build()
baseURL = "http://localhost:$randomServerPort"
}
@Test
fun memberInfoByIdTest(){
// webTestClient.get().uri("/api/v1/member")
// .accept(MediaType.APPLICATION_JSON)
// .header("Authorization", "Basic amVvbmczNDU6MzQ1Njc4")
// .exchange().expectStatus().isOk
// .expectBody(Member::class.java)
var header = HttpHeaders()
header.add("Authorization", "Basic amVvbmczNDU6MzQ1Njc4")
val url = baseURL + "/api/v1/member"
var response: ResponseEntity<Any> = restTemplate.exchange(url, HttpMethod.GET, HttpEntity<Any>(header), Any())
Assert.assertEquals(200, response.statusCodeValue)
}
@Test
fun memberInfoAll(){
// webTestClient.get().uri("/api/v1/member/all")
// .accept(MediaType.APPLICATION_JSON)
// .exchange().expectStatus().isOk
// .expectBodyList(Member::class.java)
val url = baseURL + "/api/v1/member/all"
var response: ResponseEntity<Any> = restTemplate.getForEntity(url, Any::class.java)
Assert.assertEquals(200, response.statusCodeValue)
}
@Test
fun insertMember(){
var member: Member = Member(id = "jeong1", password = "<PASSWORD>", nickname = "정", address = "광주시", email = "<EMAIL>", phoneNumber = "01012341234", regDate = null)
// webTestClient.post().uri("/api/v1/join")
// .body(member.toMono())
// .accept(MediaType.APPLICATION_JSON)
// .exchange().expectStatus().isBadRequest
// .expectBody()
}
}
| 0
|
Kotlin
|
0
| 0
|
86de7b7de8acea55072bf7cc083d3cb85e7f82bb
| 2,760
|
noteServer
|
Apache License 2.0
|
app/src/main/java/com/provatokenlab/extensions/TransitionExtension.kt
|
carlosferreira01
| 242,584,109
| false
| null |
package com.provatokenlab.extensions
import android.app.Activity
import com.provatokenlab.R
fun Activity.executeTransitionInOut(isTransitionOut: Boolean){
if (isTransitionOut)
overridePendingTransition(R.anim.anim_transition_right_in, R.anim.anim_transition_right_out)
else
overridePendingTransition(R.anim.anim_transition_left_in, R.anim.anim_transition_left_out)
}
| 0
|
Kotlin
|
0
| 0
|
e09f6f94c393ea8a7bfaa647bbb1e3ed780947f6
| 393
|
Desafio-App
|
MIT License
|
CCWCL/build-logic/convention/src/main/kotlin/rt/convention/ecosystem/AndroidLibraryConventionPlugin.kt
|
queencodemonkey
| 689,764,341
| false
|
{"Kotlin": 65072}
|
package rt.convention.ecosystem
import com.android.build.api.dsl.LibraryExtension
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.configure
import rt.convention.ecosystem.ext.configureKotlinAndroid
import rt.convention.ext.getPluginId
import rt.convention.ext.versionCatalog
/**
* Convention Plugin for providing common Android library configuration.
*
*
* Adopted from Now in Android:
* https://github.com/android/nowinandroid/blob/main/build-logic/convention/src/main/kotlin/com/google/samples/apps/nowinandroid/AndroidCompose.kt
*
* References:
* https://docs.gradle.org/current/samples/sample_convention_plugins.html
*/
@Suppress("unused")
open class AndroidLibraryConventionPlugin : Plugin<Project> {
override fun apply(target: Project) {
with(target) {
val libs = versionCatalog()
with(pluginManager) {
apply(libs.getPluginId("android-lib"))
apply(libs.getPluginId("kotlin-android"))
}
// Because plugin management happens before catalogs ar defined, at this point
// we cannot use the type-safe accessors to the version catalogs.
// Ref: https://melix.github.io/blog/2021/03/version-catalogs-faq.html#_can_i_use_a_version_catalog_to_declare_plugin_versions
extensions.configure<LibraryExtension> {
configureKotlinAndroid(this)
defaultConfig {
consumerProguardFiles("consumer-rules.pro")
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
b33aeee447412360b768cf24c001ed2112ec11e3
| 1,609
|
composing-creatively-with-custom-layouts
|
MIT License
|
accsaber-integration/src/main/kotlin/de/ixsen/accsaber/integration/model/beatsaver/BeatSaverVersion.kt
|
accsaber
| 317,599,110
| false
|
{"Kotlin": 123363, "Shell": 37}
|
package de.ixsen.accsaber.integration.model.beatsaver
data class BeatSaverVersion(
var coverURL: String? = null,
var createdAt: String? = null,
var downloadURL: String? = null,
var feedback: String? = null,
var hash: String? = null,
var key: String? = null,
var previewURL: String? = null,
var sageScore: Int? = null,
var state: String? = null,
var testplayAt: String? = null,
var diffs: List<BeatSaverMapDifficulty> = ArrayList(),
var testplays: List<BeatSaverTestplay> = ArrayList(),
)
| 3
|
Kotlin
|
0
| 3
|
cece81a90f5834bdee4729278436b44c442eb8c6
| 536
|
accsaber-backend
|
MIT License
|
client-server-api/src/main/kotlin/io/github/matrixkt/clientserver/api/UploadContent.kt
|
Dominaezzz
| 205,671,029
| false
| null |
package io.github.matrixkt.clientserver.api
import io.github.matrixkt.clientserver.MatrixRpc
import io.github.matrixkt.clientserver.RpcMethod
import io.ktor.resources.*
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* Upload some content to the content repository.
*/
public class UploadContent(
public override val url: Url,
/**
* The content to be uploaded.
*/
public override val body: ByteArray
) : MatrixRpc.WithAuth<RpcMethod.Post, UploadContent.Url, ByteArray, UploadContent.Response> {
@Resource("_matrix/media/r0/upload")
@Serializable
public class Url(
/**
* The name of the file being uploaded
*/
public val filename: String? = null
)
@Serializable
public class Response(
/**
* The `MXC URI`_ to the uploaded content.
*/
@SerialName("content_uri")
public val contentUri: String
)
}
| 3
|
Kotlin
|
8
| 28
|
522e067eec51883f4859753c5ad9240a9535544f
| 963
|
matrix-kt
|
Apache License 2.0
|
app/src/main/java/com/ricardoteixeira/app/framework/api/ApiHelperImpl.kt
|
ricardorochateixeira
| 325,117,463
| false
| null |
package com.ricardoteixeira.app.framework.api
import com.ricardoteixeira.app.framework.api.models.futureweather.FutureWeatherApiModel
import com.ricardoteixeira.app.utils.Result
import javax.inject.Inject
class ApiHelperImpl
@Inject constructor(private val weatherService: WeatherService) : ApiHelper {
override suspend fun getWeatherByName(q: String) = try {
val data = weatherService.getCurrentWeatherByName(q)
Result.Success(data)
} catch (error: Throwable) {
Result.Failure(error.message!!)
}
override suspend fun getFutureWeatherByName(q: String): Result<FutureWeatherApiModel> = try {
val data = weatherService.getFutureWeatherByName(q)
Result.Success(data)
} catch (error: Throwable) {
Result.Failure(error.message!!)
}
override suspend fun getWeatherById(id: Int) = try {
val data = weatherService.getCurrentWeatherById(id)
Result.Success(data)
} catch (error: Throwable) {
Result.Failure(error.message!!)
}
override suspend fun getFutureWeatherById(id: Int): Result<FutureWeatherApiModel> = try {
val data = weatherService.getFutureWeatherById(id)
Result.Success(data)
} catch (error: Throwable) {
Result.Failure(error.message!!)
}
}
| 0
|
Kotlin
|
0
| 0
|
242e0528e3c87dd30ad25b4f167f773362669da6
| 1,295
|
WeatherMVVM-clean
|
MIT License
|
app/src/main/java/az/siftoshka/junkyconverter/presentation/components/NewUpdate.kt
|
siftoshka
| 414,198,131
| false
|
{"Kotlin": 100414}
|
package az.siftoshka.junkyconverter.presentation.components
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.MaterialTheme
import androidx.compose.material.OutlinedButton
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@Composable
fun NewUpdate(onPerformClick: () -> Unit) {
OutlinedButton(
onClick = onPerformClick,
shape = RoundedCornerShape(20.dp),
modifier = Modifier
.height(24.dp)
.width(32.dp),
border = BorderStroke(1.dp, MaterialTheme.colors.onBackground),
colors = ButtonDefaults.outlinedButtonColors(
backgroundColor = MaterialTheme.colors.primary,
contentColor = MaterialTheme.colors.primary
),
contentPadding = PaddingValues(0.dp)
) {
Text(
text = "•",
style = MaterialTheme.typography.body2,
color = MaterialTheme.colors.onBackground
)
}
}
| 0
|
Kotlin
|
0
| 1
|
be447ae6a9a5372f24e6dc7933b7e6cd9d615a95
| 1,320
|
junky-converter
|
MIT License
|
app/src/main/java/com/example/codechallenge/home/data/dao/TableDao.kt
|
RenanPdeOliveira
| 645,087,286
| false
| null |
package com.example.codechallenge.home.data.dao
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.example.codechallenge.home.data.entities.TableItem
@Dao
interface TableDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(item: TableItem)
@Query("SELECT * FROM TableItem")
fun getAll(): LiveData<List<TableItem>>
@Query("SELECT SUM(total) FROM TableItem")
fun getTotal(): LiveData<Float>
@Query("SELECT MAX(primeiro) FROM TableItem")
fun getPrimeiraMax(): LiveData<Float>
@Query("SELECT MIN(primeiro) FROM TableItem")
fun getPrimeiraMin(): LiveData<Float>
@Query("SELECT MAX(segundo) FROM TableItem")
fun getSegundaMax(): LiveData<Float>
@Query("SELECT MIN(segundo) FROM TableItem")
fun getSegundaMin(): LiveData<Float>
}
| 0
|
Kotlin
|
0
| 0
|
1a2c9b9f610b909f2e29632fafbc949c84c405ef
| 915
|
CodeChallenge
|
The Unlicense
|
srco/src/main/kotlin/net/realmidc/niuzi/util/Locale.kt
|
Micalhl
| 572,790,591
| false
|
{"Kotlin": 55413}
|
package net.realmidc.niuzi.util
import net.mamoe.mirai.contact.Group
import net.realmidc.niuzi.PluginMain
import org.bukkit.configuration.file.YamlConfiguration
import java.io.File
import java.util.function.Function
object Locale {
private val file: File by lazy {
val file = File(PluginMain.configFolder, "locale.yml")
if (!file.exists()) {
file.createNewFile()
val content = PluginMain.getResource("locale.yml")
if (content != null) {
val config = YamlConfiguration()
config.loadFromString(content)
config.save(file)
}
}
file
}
private val config = YamlConfiguration.loadConfiguration(file)
fun getLang(path: String, vararg args: Any): String {
if (config.contains(path)) {
return if (config.isList(path)) {
config.getStringList(path).joinToString("\n").replaceWithOrder(*args)
} else {
config.getString(path)!!.replaceWithOrder(*args)
}
}
return ""
}
suspend fun Group.sendLang(path: String, vararg args: Any) {
sendMessage(getLang(path, *args))
}
}
| 0
|
Kotlin
|
3
| 8
|
d0e4184e15a9cde723200550e8e1e872d8299a2d
| 1,215
|
NiuZi
|
Creative Commons Zero v1.0 Universal
|
app/src/main/java/com/fphoenixcorneae/widget/demo/MainActivity.kt
|
FPhoenixCorneaE
| 294,912,810
| false
| null |
package com.fphoenixcorneae.widget.demo
import android.graphics.Color
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.fphoenixcorneae.widget.demo.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private var mViewBinding: ActivityMainBinding? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mViewBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(mViewBinding!!.root)
mViewBinding!!.tvDesc.apply {
// 设置最大显示行数
maxLineCount = 3
// 收起文案
collapseText = "收起全部"
// 展开文案
expandText = "查看全文"
// 是否支持收起功能
collapseEnable = false
// 是否给展开收起添加下划线
underlineEnable = false
// 收起文案颜色
collapseTextColor = Color.BLUE
// 展开文案颜色
expandTextColor = Color.RED
// 设置要显示的文字以及状态
setText(getString(R.string.desc), false)
}
}
override fun onDestroy() {
super.onDestroy()
mViewBinding = null
}
}
| 0
|
Kotlin
|
1
| 2
|
966f6b500e465abb6a1314d6a2d65d1e40433f24
| 1,169
|
ExpandCollapseTextView
|
Apache License 2.0
|
komf-core/src/commonMain/kotlin/snd/komf/providers/mangaupdates/model/SearchResultPage.kt
|
Snd-R
| 463,859,568
| false
|
{"Kotlin": 694478, "Dockerfile": 582}
|
package snd.komf.providers.mangaupdates.model
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import snd.komf.providers.mangaupdates.model.SearchResult
@Serializable
data class SearchResultPage(
@SerialName("total_hits")
val totalHits: Int,
val page: Int,
@SerialName("per_page")
val perPage: Int,
val results: Collection<SearchResultHit>
)
@Serializable
data class SearchResultHit(
val record: SearchResult,
@SerialName("hit_title")
val hitTitle: String?,
)
| 30
|
Kotlin
|
19
| 309
|
4c260a3dcd326a5e1d74ac9662eec8124ab7e461
| 532
|
komf
|
MIT License
|
src/main/kotlin/ru/justagod/processing/cutter/config/CutterConfig.kt
|
JustAGod1
| 179,755,842
| false
|
{"Kotlin": 232280, "Java": 12281}
|
package ru.justagod.processing.cutter.config
import ru.justagod.cutter.data.DynSideMarker
import ru.justagod.model.ClassTypeReference
import java.io.Serializable
class CutterConfig(
val annotation: ClassTypeReference,
val validationOverrideAnnotation: ClassTypeReference?,
val removeAnnotations: Boolean,
val primalSides: Set<SideName>,
val targetSides: Set<SideName>,
val invocators: List<InvokeClass>
) : Serializable {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as CutterConfig
if (annotation != other.annotation) return false
if (validationOverrideAnnotation != other.validationOverrideAnnotation) return false
if (removeAnnotations != other.removeAnnotations) return false
if (primalSides != other.primalSides) return false
if (targetSides != other.targetSides) return false
if (invocators != other.invocators) return false
return true
}
override fun hashCode(): Int {
var result = annotation.hashCode()
result = 31 * result + (validationOverrideAnnotation?.hashCode() ?: 0)
result = 31 * result + removeAnnotations.hashCode()
result = 31 * result + primalSides.hashCode()
result = 31 * result + targetSides.hashCode()
result = 31 * result + invocators.hashCode()
return result
}
override fun toString(): String {
return "CutterConfig(annotation=$annotation, validationOverrideAnnotation=$validationOverrideAnnotation, removeAnnotations=$removeAnnotations, primalSides=$primalSides, targetSides=$targetSides, invocators=$invocators)"
}
}
| 0
|
Kotlin
|
0
| 0
|
5f635e045a6e1323571e492723110de280232c5a
| 1,731
|
cutter
|
MIT License
|
biz_home/src/main/java/com/example/biz_home/api/CategoryApi.kt
|
xhh4215
| 435,793,681
| false
|
{"Kotlin": 327550, "Java": 107540}
|
package com.example.biz_home.api
import com.example.library.restful.HiCall
import com.example.library.restful.annotation.GET
import com.example.library.restful.annotation.Path
import com.example.biz_home.model.Subcategory
import com.example.biz_home.model.TabCategory
interface CategoryApi {
@GET("category/categories")
fun queryCategoryList(): HiCall<List<TabCategory>>
@GET("category/subcategories/{categoryId}")
fun querySubcategoryList(@Path("categoryId") categoryId: String): HiCall<List<Subcategory>>
}
| 0
|
Kotlin
|
0
| 1
|
e2359ee06795c6b37b24ffc2a3dbe9f4159ba435
| 528
|
ShopApp
|
Apache License 2.0
|
dorm/core/src/main/kotlin/org/sirius/dorm/model/json/ObjectDescriptorDeserializer.kt
|
coolsamson7
| 856,851,180
| false
|
{"Kotlin": 243947, "ANTLR": 13837}
|
package org.sirius.dorm.model.json
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.deser.std.StdDeserializer
import org.sirius.dorm.model.*
import org.sirius.common.type.Type
open class ObjectDescriptorDeserializer() : StdDeserializer<ObjectDescriptor>(ObjectDescriptor::class.java) {
// override
override fun deserialize(jsonParser: JsonParser, context: DeserializationContext): ObjectDescriptor {
val node: JsonNode = jsonParser.codec.readTree(jsonParser)
val name = node.get("name").asText()
val properties = ArrayList<PropertyDescriptor<Any>>()
val propertyNode = node.get("properties")
for ( propertyName in propertyNode.fieldNames()) {
val property = propertyNode.get(propertyName)
// either attribute or relation
if ( property["type"] !== null) {
val type = jsonParser.getCodec().treeToValue(property.get("type"), Type::class.java)
properties.add(AttributeDescriptor(propertyName, type as Type<Any>, propertyName == "id"))
}
else {
val multiplicity = Multiplicity.valueOf( property["target"].asText())
val cascadeDelete = property["cascadeDelete"].asBoolean()
val removeOrphans = property["removeOrphans"].asBoolean()
properties.add(RelationDescriptor(propertyName, property["target"].asText(), multiplicity, cascadeDelete, removeOrphans, property["inverse"].asText()))
}
}
// done
return ObjectDescriptor(name, properties.toTypedArray())
}
}
| 0
|
Kotlin
|
0
| 1
|
85c2da7608171bb0703d974a5ac0b3ce6034515e
| 1,750
|
dorm
|
Apache License 2.0
|
dorm/core/src/main/kotlin/org/sirius/dorm/model/json/ObjectDescriptorDeserializer.kt
|
coolsamson7
| 856,851,180
| false
|
{"Kotlin": 243947, "ANTLR": 13837}
|
package org.sirius.dorm.model.json
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.deser.std.StdDeserializer
import org.sirius.dorm.model.*
import org.sirius.common.type.Type
open class ObjectDescriptorDeserializer() : StdDeserializer<ObjectDescriptor>(ObjectDescriptor::class.java) {
// override
override fun deserialize(jsonParser: JsonParser, context: DeserializationContext): ObjectDescriptor {
val node: JsonNode = jsonParser.codec.readTree(jsonParser)
val name = node.get("name").asText()
val properties = ArrayList<PropertyDescriptor<Any>>()
val propertyNode = node.get("properties")
for ( propertyName in propertyNode.fieldNames()) {
val property = propertyNode.get(propertyName)
// either attribute or relation
if ( property["type"] !== null) {
val type = jsonParser.getCodec().treeToValue(property.get("type"), Type::class.java)
properties.add(AttributeDescriptor(propertyName, type as Type<Any>, propertyName == "id"))
}
else {
val multiplicity = Multiplicity.valueOf( property["target"].asText())
val cascadeDelete = property["cascadeDelete"].asBoolean()
val removeOrphans = property["removeOrphans"].asBoolean()
properties.add(RelationDescriptor(propertyName, property["target"].asText(), multiplicity, cascadeDelete, removeOrphans, property["inverse"].asText()))
}
}
// done
return ObjectDescriptor(name, properties.toTypedArray())
}
}
| 0
|
Kotlin
|
0
| 1
|
85c2da7608171bb0703d974a5ac0b3ce6034515e
| 1,750
|
dorm
|
Apache License 2.0
|
app/src/main/java/com/codewithfk/expensetracker/android/utils/NavRouts.kt
|
furqanullah717
| 776,577,261
| false
|
{"Kotlin": 71129}
|
package com.codewithfk.expensetracker.android.utils
object NavRouts {
const val login="login"
const val signup="SignUp"
const val forgotpassword="<PASSWORD>"
const val home="home"
const val addscreen="AddScreen"
const val profile="profile"
const val stats="stats"
}
| 11
|
Kotlin
|
5
| 7
|
74d9e9e24a54e6016b7c5941d9165e44e7c453b9
| 294
|
expense-tracker-android
|
MIT License
|
app/src/main/java/me/echeung/moemoekyun/client/api/callback/IsFavoriteCallback.kt
|
goofwear
| 212,941,690
| true
|
{"Kotlin": 165707}
|
package me.echeung.moemoekyun.client.api.callback
interface IsFavoriteCallback : BaseCallback {
fun onSuccess(favoritedSongIds: List<Int>)
}
| 0
| null |
0
| 1
|
0885fcea494d49f2a619d8c037adbcf84a1b55e3
| 146
|
android-app
|
MIT License
|
src/test/kotlin/io/github/kryszak/gwatlin/api/gamemechanics/SpecializationClientTest.kt
|
Kryszak
| 214,791,260
| false
|
{"Kotlin": 443350, "Shell": 665}
|
package io.github.kryszak.gwatlin.api.gamemechanics
import io.github.kryszak.gwatlin.api.ApiLanguage
import io.github.kryszak.gwatlin.api.exception.ApiRequestException
import io.github.kryszak.gwatlin.config.BaseWiremockTest
import io.kotest.assertions.assertSoftly
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.matchers.booleans.shouldBeFalse
import io.kotest.matchers.collections.shouldHaveSize
import io.kotest.matchers.shouldBe
internal class SpecializationClientTest : BaseWiremockTest() {
private val specializationClient = GWSpecializationClient()
init {
should("Get specialization ids") {
// given
stubResponse("/specializations", "/responses/gamemechanics/specialization_ids.json")
// when
val specializationIds = specializationClient.getSpecializationIds()
// then
specializationIds shouldHaveSize 63
}
should("Get specialization") {
// given
val id = 1
val lang = io.github.kryszak.gwatlin.api.ApiLanguage.EN
stubResponse("/specializations/1", "/responses/gamemechanics/specialization.json", language = lang)
// when
val specialization = specializationClient.getSpecialization(id, lang)
// then
assertSoftly(specialization) {
id shouldBe 1
name shouldBe "Dueling"
profession shouldBe "Mesmer"
elite.shouldBeFalse()
minorTraits shouldHaveSize 3
majorTraits shouldHaveSize 9
icon shouldBe "https://render.guildwars2.com/file/43C5400906A104C60F30DFE0A145D1E767353573/1012003.png"
background shouldBe "https://render.guildwars2.com/file/992D53319C5FCD4AE841C592DC2AE91D5906AECF/1012057.png"
}
}
should("Throw exception on non existing specialization") {
// given
val id = 100
stubResponse("/specializations/100", "/responses/gamemechanics/specialization_error.json", responseStatus = 404)
// when
val exception = shouldThrow<ApiRequestException> { specializationClient.getSpecialization(id) }
// then
exception.message shouldBe "RetrieveError(text=no such id)"
}
}
}
| 2
|
Kotlin
|
1
| 6
|
a88fa214ba858452fb05826f0641bb217e0053f6
| 2,361
|
gwatlin
|
MIT License
|
app/src/main/java/com/oneclean/android/booster/ui/base/BaseActivity.kt
|
ysjava
| 481,052,851
| false
|
{"Kotlin": 217307, "Java": 28498}
|
package com.oneclean.android.booster.ui.base
import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.ActivityInfo
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.util.Log
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import com.oneclean.android.booster.OneCleanerApplication
import com.oneclean.android.booster.OneCleanerApplication.Companion.activityList
import com.oneclean.android.booster.ui.popup.For11RequestFailPopup
import com.oneclean.android.booster.ui.popup.ForwardToSettingsPopup
import com.oneclean.android.booster.ui.popup.RequestPermissionPopup
import com.oneclean.android.booster.utils.initWindow
import com.oneclean.android.booster.utils.logd
import com.oneclean.android.booster.utils.putBoolean
import com.permissionx.guolindev.PermissionX
abstract class BaseActivity : AppCompatActivity {
constructor() : super()
constructor(@LayoutRes contentLayoutId: Int) : super(contentLayoutId)
@SuppressLint("SourceLockedOrientationActivity")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initWindow(window)
activityList.add(this)
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
/**
* 请求权限
*
* @param success 当权限获取成功时执行
* @param fail 获取权限失败执行
* */
protected fun requestPermission(
success: (grantedList: List<String>) -> Unit,
fail: (deniedList: List<String>) -> Unit,
for11RequestFail: (() -> Unit)? = null
) {
PermissionX.init(this)
.permissions(
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.INTERNET
)
.explainReasonBeforeRequest()
.onExplainRequestReason { scope, deniedList ->
val dialog = RequestPermissionPopup(this, "message", deniedList)
scope.showRequestReasonDialog(dialog)
}
.onForwardToSettings { scope, deniedList ->
val dialog = ForwardToSettingsPopup(this,deniedList,
"You need to manually open the permission in the application settings",
"I understand",
"Cancel",-1,-1)
scope.showForwardToSettingsDialog(dialog,{
//获取权限去了 暂停热启动逻辑
OneCleanerApplication.cancelTime = true
putBoolean(this,"cancelTime",true,"hot_load")
},{
//处理完成回到这里 恢复
OneCleanerApplication.isRequestPermissionBack = true
putBoolean(this,"isRequestPermissionBack",true,"hot_load")
})
}
.request { allGranted, grantedList, deniedList ->
if (allGranted) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()) {
if (for11RequestFail != null)
for11RequestFail()
} else {
success(grantedList)
}
} else {
fail(deniedList)
}
}
}
override fun onDestroy() {
super.onDestroy()
activityList.remove(this)
}
}
| 0
|
Kotlin
|
0
| 0
|
be4c203132bb53c34aab1a737beb5387a4e1740e
| 3,462
|
OneCleaner
|
Apache License 2.0
|
shared/src/commonMain/kotlin/it/carlo/de/chellis/biometrickmp/biometric/BiometricAuthenticator.kt
|
carlodek
| 741,956,334
| false
|
{"Kotlin": 36725, "Objective-C": 1593, "Swift": 1275}
|
package it.carlo.de.chellis.biometrickmp.biometric
expect class BiometricAuthenticator private constructor() {
constructor(activity: Any?)
fun doAuth(
title: String,
description: String,
denyBtnText: String,
actionDone: (Boolean) -> Unit
)
/**
* Performs a biometric scan availability check
*
* @return true if it is possible to use a biometry, false - if it is not available
*/
fun isBiometricAvailable(): Boolean
}
| 0
|
Kotlin
|
0
| 0
|
7caa8ce95056880c7bdc284d460b92129ca540d6
| 491
|
biometric_kmp
|
Apache License 2.0
|
src/main/kotlin/tech/aaregall/lab/movies/repository/rest/ActorRestRepository.kt
|
ArnauAregall
| 618,907,896
| false
| null |
package tech.aaregall.lab.movies.repository.rest
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.rest.core.annotation.RepositoryRestResource
import tech.aaregall.lab.movies.domain.Actor
@RepositoryRestResource(path = "actors", collectionResourceRel = "actors", itemResourceRel = "actor")
interface ActorRestRepository : JpaRepository<Actor, Long>
| 0
|
Kotlin
|
0
| 1
|
26e35d1b5b04096ef278960415068e1e514af3ce
| 393
|
kotlin-spring-data-rest-movies
|
Apache License 2.0
|
Sushi/app/src/main/java/com/destructo/sushi/model/database/UserMangaEntity.kt
|
destructo570
| 302,356,237
| false
| null |
package com.destructo.sushi.model.database
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.destructo.sushi.model.mal.common.MainPicture
import com.destructo.sushi.model.mal.manga.MyMangaListStatus
import com.destructo.sushi.model.mal.updateUserMangaList.UpdateUserManga
import com.destructo.sushi.model.mal.userMangaList.UserMangaData
@Entity(tableName = "user_manga_list")
data class UserMangaEntity (
@PrimaryKey(autoGenerate = true)
val id: Int?=null,
val malId: Int?=null,
val status: String?=null,
val title: String?=null,
val score: Double?=null,
val myMangaListStatus: MyMangaListStatus?=null,
val myStatus: String? = null,
var media_type: String?=null,
var numChapters: Int?=null,
val mainPicture: MainPicture?=null,
override val time: Long = System.currentTimeMillis(),
): BaseDatabaseEntity{
companion object {
private fun fromUpdateUserManga(data: UserMangaData): UserMangaEntity {
return UserMangaEntity(
malId = data.manga.id,
status = data.manga.status,
title = data.manga.title,
media_type = data.manga.mediaType,
mainPicture = data.manga.mainPicture,
numChapters = data.manga.numChapters,
score = data.manga.mean,
myMangaListStatus = data.manga.myMangaListStatus,
myStatus = data.manga.myMangaListStatus?.status
)
}
fun fromListOfUserMangaData(data: List<UserMangaData?>): List<UserMangaEntity> {
val result = mutableListOf<UserMangaEntity>()
for (anime in data){
anime?.let { result.add(fromUpdateUserManga(it)) }
}
return result
}
}
fun updateUserStatus(data: UpdateUserManga){
myMangaListStatus?.comments = data.comments
myMangaListStatus?.isRereading = data.isRereading
myMangaListStatus?.numChaptersRead = data.numChaptersRead
myMangaListStatus?.numVolumesRead = data.numVolumesRead
myMangaListStatus?.num_times_reread = data.numTimesReread
myMangaListStatus?.priority = data.priority
myMangaListStatus?.reread_value = data.rereadValue
myMangaListStatus?.score = data.score
myMangaListStatus?.status = data.status
myMangaListStatus?.tags = data.tags
myMangaListStatus?.updatedAt = data.updatedAt
}
}
| 3
|
Kotlin
|
5
| 21
|
68317c04caa596103d3fd32b0f34fe43b189a721
| 2,473
|
Sushi-Unofficial-MAL-Client
|
Apache License 2.0
|
subprojects/gradle/lint-report/src/integTest/kotlin/com/avito/android/lint/LintSlackAlertIntegrationTest.kt
|
StanlyT
| 344,157,673
| true
|
{"Kotlin": 2773538, "HTML": 121161, "Shell": 17522, "Python": 14168, "Makefile": 7187, "Dockerfile": 7134}
|
package com.avito.android.lint
import com.avito.android.lint.slack.LintSlackReporter
import com.avito.logger.StubLoggerFactory
import com.avito.slack.SlackClient
import com.avito.slack.model.SlackChannel
import okhttp3.HttpUrl.Companion.toHttpUrl
import org.junit.jupiter.api.Test
import java.io.File
internal class LintSlackAlertIntegrationTest {
private val testChannel = SlackChannel(requireNotNull(System.getProperty("avito.slack.test.channel")))
private val testToken = requireNotNull(System.getProperty("avito.slack.test.token"))
private val workspace = requireNotNull(System.getProperty("avito.slack.test.workspace"))
private val slackClient: SlackClient = SlackClient.Impl(testToken, workspace)
private val loggerFactory = StubLoggerFactory
@Test
fun integrationTest() {
val parser = LintResultsParser(loggerFactory)
val reportModels = parser.parse(
projectPath = ":app",
lintXml = fileFromJarResources<LintSlackAlertIntegrationTest>("lint-results.xml"),
lintHtml = fileFromJarResources<LintSlackAlertIntegrationTest>("lint-results.html")
)
val lintSlackReporter: LintSlackReporter = LintSlackReporter.Impl(slackClient, loggerFactory)
lintSlackReporter.report(
lintReport = reportModels,
channel = testChannel,
channelForLintBugs = testChannel,
buildUrl = "https://stubbuildurl".toHttpUrl()
)
}
}
inline fun <reified C> fileFromJarResources(name: String): File {
val file = C::class.java.classLoader
?.getResource(name)
?.file
?.let { File(it) }
return requireNotNull(file) { "$name not found in resources" }
}
| 0
|
Kotlin
|
0
| 0
|
96463f7714c0550e331d2a37fb32ad98fac9d62d
| 1,724
|
avito-android
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.