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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
graphql-simple-bindings-boot-shell/src/test/kotlin/community/flock/graphqlsimplebindings/GraphqlSimpleBindingsApplicationTests.kt | flock-community | 197,765,392 | false | null | package community.flock.graphqlsimplebindings
import community.flock.graphqlsimplebindings.emitter.JavaEmitter
import community.flock.graphqlsimplebindings.emitter.KotlinEmitter
import community.flock.graphqlsimplebindings.emitter.ScalaEmitter
import community.flock.graphqlsimplebindings.emitter.TypeScriptEmitter
import community.flock.graphqlsimplebindings.emitter.common.Emitter
import community.flock.graphqlsimplebindings.parser.Parser
import graphql.language.Document
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit.jupiter.SpringExtension
import java.io.File
@ExtendWith(SpringExtension::class)
@SpringBootTest
class GraphqlSimpleBindingsApplicationTests {
@Value("\${exampleDirectory:#{null}}")
var examples: String? = null
private val scalarsKotlin = mapOf("Date" to "java.time.LocalDate")
private val scalarsScala = mapOf("Date" to "java.time.LocalDate")
private val scalarsJava = mapOf("Date" to "java.time.LocalDate")
private val scalarsTypeScript = mapOf("Date" to "Date")
private val input = readInput().readText().let { Parser.parseSchema(it) }
@Test
fun `Kotlin Emitter`() = input emittedWith KotlinEmitter(packageName = "kotlin", scalars = scalarsKotlin, enableOpenApiAnnotations = false) writtenTo "App.kt".file
@Test
fun `Scala Emitter`() = input emittedWith ScalaEmitter(packageName = "scala", scalars = scalarsScala, enableOpenApiAnnotations = false) writtenTo "App.scala".file
@Test
fun `Java Emitter`() = input emittedWith JavaEmitter(packageName = "java", scalars = scalarsJava, enableOpenApiAnnotations = false) writtenTo "App.java".file
@Test
fun `TypeScript Emitter`() = input emittedWith TypeScriptEmitter(scalars = scalarsTypeScript) writtenTo "appFromKt.ts".file
private fun readInput() = GraphqlSimpleBindingsApplicationTests::class.java.getResource("/input.graphql")
?: throw RuntimeException("No /input.graphql found")
private infix fun Document.emittedWith(emitter: Emitter) = emitter
.emitDocument("App", this, true)
.joinToString("\n") { (_, string) -> string }
private infix fun String.writtenTo(file: File?) = file?.writeText(this) ?: println(this)
private val String.file
get() = examples?.let { if (File("$it/dist").exists()) File("$it/dist/$this") else null }
}
| 2 | Kotlin | 1 | 2 | e35df5164ef0abe11b8473012c7f1797ace792fc | 2,529 | graphql-simple-bindings | MIT License |
saved-sites/saved-sites-store/src/main/java/com/duckduckgo/savedsites/store/SavedSitesRelationsDao.kt | duckduckgo | 78,869,127 | false | null | /*
* Copyright (c) 2023 DuckDuckGo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.duckduckgo.savedsites.store
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.duckduckgo.savedsites.api.models.SavedSitesNames
import io.reactivex.Single
import kotlinx.coroutines.flow.Flow
@Dao
interface SavedSitesRelationsDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(relation: Relation): Long
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertList(relations: List<Relation>)
@Query("select * from relations")
fun relations(): List<Relation>
@Query("select * from relations where folderId =:folderId")
fun relations(folderId: String): Flow<List<Relation>>
@Query("select * from relations where folderId =:folderId")
fun relationsObservable(folderId: String): Single<List<Relation>>
@Query("update relations set folderId = :newId where folderId = :oldId")
fun updateFolderId(oldId: String, newId: String)
@Query("update relations set entityId = :newId where entityId = :oldId")
fun updateEntityId(oldId: String, newId: String)
@Query(
"select count(*) from entities inner join relations on entities.entityId = relations.entityId " +
"and entities.type = :type and relations.folderId = :folderId and entities.deleted = 0",
)
fun countEntitiesInFolder(
folderId: String,
type: EntityType,
): Int
@Query("select * from relations where relations.entityId = :entityId and relations.folderId <> :favoritesRoot")
fun relationByEntityId(entityId: String, favoritesRoot: String = SavedSitesNames.FAVORITES_ROOT): Relation?
@Query("select * from relations where relations.entityId = :entityId")
fun relationsByEntityId(entityId: String): List<Relation>
@Query("select CAST(COUNT(*) AS BIT) from relations")
fun hasRelations(): Boolean
@Update(onConflict = OnConflictStrategy.REPLACE)
fun update(relation: Relation)
@Delete
fun delete(relation: Relation)
@Query("delete from relations where folderId = :folderId")
fun delete(folderId: String)
@Query("delete from relations where entityId = :entityId")
fun deleteRelationByEntity(entityId: String)
@Query("delete from relations where relations.entityId = :entityId and relations.folderId = :folderId")
fun deleteRelationByEntityAndFolder(entityId: String, folderId: String)
@Query("delete from relations where entityId = :entityId AND folderId = :folderId")
fun deleteRelationByEntity(
entityId: String,
folderId: String,
)
@Query(
"select count(*) from entities inner join relations on entities.entityId = relations.entityId " +
"where entities.url LIKE :domain AND folderId == :folderId AND entities.deleted = 0",
)
fun countFavouritesByUrl(
domain: String,
folderId: String = SavedSitesNames.FAVORITES_ROOT,
): Int
@Query("delete from relations")
fun deleteAll()
}
| 62 | null | 868 | 3,302 | 9b7fda539c6d1c323a7cd5542767c4c492e628c8 | 3,665 | Android | Apache License 2.0 |
analysis/low-level-api-fir/testdata/inBlockModification/memberGetterWithBodyWithContractWithoutName.kt | HardFatal | 387,140,840 | false | null | import kotlin.contracts.contract
class A {
var : Int
ge<caret>t() {
contract {
req
}
fun doSmth(i: String) = 4
return doSmth("str")
}
set(value) = Unit
}
| 1 | null | 1 | 1 | 5424c54fae7b4836506ec711edc0135392b445d6 | 216 | kotlin | Apache License 2.0 |
src/main/kotlin/pieces/PieceType.kt | lwaschuk | 593,435,412 | false | null | package pieces
/**
* The various "classes" a chess piece can be
* @author Lukas Waschuk
*/
enum class PieceType {
EMPTY, PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING
} | 0 | Kotlin | 0 | 2 | 26379a4f73c703debabfe0e006ac8d3811d9ee71 | 170 | Kotlin-Command-Line-Chess | Apache License 2.0 |
simplified-analytics-api/src/main/java/org/nypl/simplified/analytics/api/AnalyticsConfiguration.kt | ThePalaceProject | 367,082,997 | false | {"Kotlin": 3308998, "JavaScript": 853788, "Java": 374503, "CSS": 65407, "HTML": 49220, "Shell": 5017, "Ruby": 178} | package org.nypl.simplified.analytics.api
import android.content.Context
import org.librarysimplified.http.api.LSHTTPClientType
/**
* General configuration for analytics systems.
*/
data class AnalyticsConfiguration(
/**
* An Android context, used by systems if necessary.
*/
val context: Context,
/**
* The HTTP interface used for analytics requests, if necessary.
*/
val http: LSHTTPClientType
)
| 1 | Kotlin | 4 | 8 | 95ea5f21c6408207eddccb7210721743d57a500f | 427 | android-core | Apache License 2.0 |
viewlegacyTests/src/androidMain/kotlin/tech/skot/view/tests/SKTestScreenViewProxy.kt | skot-framework | 235,318,194 | false | null | package tech.skot.view.tests
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.fragment.app.Fragment
import tech.skot.core.components.*
import tech.skot.core.components.presented.SKBottomSheetViewProxy
import tech.skot.core.components.presented.SKDialogView
import tech.skot.core.components.presented.SKDialogViewProxy
import tech.skot.core.toColor
import tech.skot.core.view.Color
import tech.skot.view.tests.SKTestView.Companion.dummyVisiblityListener
import tech.skot.viewlegacytests.databinding.TestScreenBinding
class SKTestScreenViewProxy(
content: List<SKComponentViewProxy<*>>,
private val vertical: Boolean = true,
private val color: Color? = null
) :
SKScreenViewProxy<TestScreenBinding>() {
override val visibilityListener = dummyVisiblityListener()
private val box = SKBoxViewProxy(
itemsInitial = content,
hiddenInitial = false,
)
val dialog: SKDialogViewProxy = SKDialogViewProxy()
val bottomSheet: SKBottomSheetViewProxy = SKBottomSheetViewProxy()
override fun bindTo(
activity: SKActivity,
fragment: Fragment?,
binding: TestScreenBinding,
): SKScreenView<TestScreenBinding> = SKTestScreenView(this, activity, fragment, binding).apply {
dialog._bindTo(activity, fragment, Unit).also { subViews.add(it) }
bottomSheet._bindTo(activity, fragment, Unit).also { subViews.add(it) }
if (!vertical) {
binding.box.orientation = LinearLayout.HORIZONTAL
}
color?.let { binding.box.setBackgroundColor(it.toColor(context)) }
box._bindTo(activity, fragment, binding.box)
}
override fun inflate(
layoutInflater: LayoutInflater,
parent: ViewGroup?,
attachToParent: Boolean
): TestScreenBinding = TestScreenBinding.inflate(layoutInflater, parent, attachToParent)
}
class SKTestScreenView(
override val proxy: SKTestScreenViewProxy,
activity: SKActivity,
fragment: Fragment?,
binding: TestScreenBinding
) : SKScreenView<TestScreenBinding>(proxy, activity, fragment, binding) | 1 | null | 4 | 6 | 8fcff82c719c9775e63da9c3808817704068cbba | 2,142 | skot | Apache License 2.0 |
app/src/main/java/com/herry/test/app/main/MainFragment.kt | HerryPark | 273,154,769 | false | null | package com.herry.test.app.main
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import androidx.appcompat.widget.AppCompatImageView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.herry.libs.app.activity_caller.module.ACNavigation
import com.herry.libs.app.activity_caller.module.ACPermission
import com.herry.libs.app.nav.NavBundleUtil
import com.herry.libs.log.Trace
import com.herry.libs.nodeview.NodeForm
import com.herry.libs.nodeview.NodeHolder
import com.herry.libs.nodeview.model.NodeRoot
import com.herry.libs.nodeview.recycler.NodeRecyclerAdapter
import com.herry.libs.nodeview.recycler.NodeRecyclerForm
import com.herry.libs.util.BundleUtil
import com.herry.libs.widget.extension.navigateTo
import com.herry.libs.widget.extension.setImage
import com.herry.libs.widget.extension.setOnProtectClickListener
import com.herry.test.R
import com.herry.test.app.base.nav.BaseNavView
import com.herry.test.app.nbnf.NBNFActivity
import com.herry.test.app.nestedfragments.NestedNavFragmentsActivity
import com.herry.test.app.sample.SampleActivity
import com.herry.test.widget.Popup
import com.herry.test.widget.TitleBarForm
/**
* Created by herry.park on 2020/06/11.
**/
class MainFragment : BaseNavView<MainContract.View, MainContract.Presenter>(), MainContract.View {
override fun onCreatePresenter(): MainContract.Presenter = MainPresenter()
override fun onCreatePresenterView(): MainContract.View = this
override val root: NodeRoot
get() = adapter.root
private val adapter: Adapter = Adapter()
private var container: View? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
if (null == this.container) {
this.container = inflater.inflate(R.layout.main_fragment, container, false)
init(this.container)
}
return this.container
}
private fun init(view: View?) {
view ?: return
TitleBarForm(activity = { requireActivity() }).apply {
bindFormHolder(view.context, view.findViewById(R.id.main_fragment_title))
bindFormModel(view.context, TitleBarForm.Model(title = "Test List"))
}
view.findViewById<RecyclerView>(R.id.main_fragment_list)?.apply {
layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
setHasFixedSize(true)
if (itemAnimator is SimpleItemAnimator) {
(itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
}
adapter = [email protected]
}
}
inner class Adapter: NodeRecyclerAdapter(::requireContext) {
override fun onBindForms(list: MutableList<NodeForm<out NodeHolder, *>>) {
list.add(TestItemForm())
}
}
override fun onScreen(type: MainContract.TestItemType) {
when (type) {
MainContract.TestItemType.SCHEME_TEST -> {
navigateTo(destinationId = R.id.intent_list_fragment)
}
MainContract.TestItemType.GIF_DECODER -> {
activityCaller?.call(
ACPermission.Caller(
arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
onGranted = {
Handler(Looper.getMainLooper()).post {
navigateTo(destinationId = R.id.gif_list_fragment)
}
}
))
}
MainContract.TestItemType.CHECKER_LIST -> {
navigateTo(destinationId = R.id.data_checker_main_fragment)
}
MainContract.TestItemType.LAYOUT_SAMPLE -> {
navigateTo(destinationId = R.id.layout_sample_fragment)
}
MainContract.TestItemType.PICK -> {
navigateTo(destinationId = R.id.pick_list_fragment)
}
MainContract.TestItemType.NESTED_FRAGMENTS -> {
//.navigateTo(destinationId = R.id.nested_nav_fragments_navigation)
activityCaller?.call(
ACNavigation.IntentCaller(
Intent(requireActivity(), NestedNavFragmentsActivity::class.java), onResult = { result ->
if (result.resultCode == Activity.RESULT_OK) {
Trace.d("Herry", "result = OK")
}
}
))
}
MainContract.TestItemType.NESTED_BOTTOM_NAV_FRAGMENTS -> {
activityCaller?.call(ACNavigation.IntentCaller(Intent(requireActivity(), NBNFActivity::class.java)))
}
MainContract.TestItemType.APP_DIALOG -> {
navigateTo(destinationId = R.id.app_dialog_list_fragment)
}
MainContract.TestItemType.LIST -> {
navigateTo(destinationId = R.id.list_fragment)
}
MainContract.TestItemType.SKELETON -> {
navigateTo(destinationId = R.id.skeleton_fragment)
}
MainContract.TestItemType.RESIZING_UI -> {
navigateTo(destinationId = R.id.resizing_ui_fragment)
}
MainContract.TestItemType.SAMPLE_APP -> {
activityCaller?.call(ACNavigation.IntentCaller(Intent(requireActivity(), SampleActivity::class.java)))
}
MainContract.TestItemType.PAINTER -> {
navigateTo(destinationId = R.id.painter_fragment)
}
MainContract.TestItemType.TENSOR_FLOW_LITE -> {
navigateTo(destinationId = R.id.tflite_list_fragment)
}
}
}
override fun onNavigateUpResult(fromNavigationId: Int, result: Bundle) {
if (fromNavigationId == R.id.painter_fragment) {
if (NavBundleUtil.isNavigationResultOk(result)) {
val activity = this.activity ?: return
val bitmapArray = BundleUtil[result, "bitmap", ByteArray::class.java] ?: return
val bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.size)
Popup(activity).apply {
val imageView = AppCompatImageView(activity)
imageView.layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
imageView.setImage(BitmapDrawable(bitmap))
this.setView(imageView)
this.setPositiveButton(android.R.string.ok)
}.show()
}
}
}
private inner class TestItemForm : NodeForm<TestItemForm.Holder, MainContract.TestItemType>(Holder::class, MainContract.TestItemType::class) {
inner class Holder(context: Context, view: View) : NodeHolder(context, view) {
val title: TextView? = view.findViewById(R.id.main_test_item_title)
init {
view.setOnProtectClickListener {
NodeRecyclerForm.getBindModel(this@TestItemForm, this@Holder)?.let {
presenter?.moveToScreen(it)
}
}
}
}
override fun onCreateHolder(context: Context, view: View): Holder = Holder(context, view)
override fun onLayout(): Int = R.layout.main_test_item
override fun onBindModel(context: Context, holder: TestItemForm.Holder, model: MainContract.TestItemType) {
holder.title?.text = when (model) {
MainContract.TestItemType.SCHEME_TEST -> "Intent"
MainContract.TestItemType.GIF_DECODER -> "GIF Decoder"
MainContract.TestItemType.CHECKER_LIST -> "Data Checker"
MainContract.TestItemType.LAYOUT_SAMPLE -> "Layout Sample"
MainContract.TestItemType.PICK -> "Pick"
MainContract.TestItemType.NESTED_FRAGMENTS -> "Nested Fragments"
MainContract.TestItemType.NESTED_BOTTOM_NAV_FRAGMENTS -> "Nested Bottom Navigator Fragments"
MainContract.TestItemType.APP_DIALOG -> "App Dialog"
MainContract.TestItemType.LIST -> "List"
MainContract.TestItemType.SKELETON -> "Skeleton"
MainContract.TestItemType.RESIZING_UI -> "Resizing UI"
MainContract.TestItemType.SAMPLE_APP -> "Sample Application"
MainContract.TestItemType.PAINTER -> "Painter"
MainContract.TestItemType.TENSOR_FLOW_LITE -> "Tensorflow-lite"
}
}
}
} | 0 | Kotlin | 0 | 0 | aad2b081795d518bbc3126298eb50bc5f7e01f47 | 9,121 | HerryApiDemo | Apache License 2.0 |
Library/src/main/java/com/xfhy/library/basekit/presenter/IPresenter.kt | xfhy | 258,978,567 | false | null | package com.xfhy.library.basekit.presenter
import com.xfhy.library.basekit.view.IBaseView
/**
* author xfhy
* create at 2017/9/15 13:44
* description:MVP Presenter的父接口
*/
interface IPresenter<T : IBaseView> {
fun setView(view: T)
/**
* 模拟界面的生命周期 onCreate()
*/
fun onCreate()
/**
* 模拟界面的生命周期 onResume()
*/
fun onResume()
/**
* 模拟界面的生命周期 onDestroy()
*/
fun onDestroy()
}
| 1 | Kotlin | 5 | 6 | 294cd16f0549f97d13304d659e76c776189e44ff | 438 | AllInOne | Apache License 2.0 |
src/main/kotlin/io/github/gaming32/worldhostserver/proxyServer.kt | Gaming32 | 609,157,750 | false | {"Kotlin": 76469, "Java": 5869} | package io.github.gaming32.worldhostserver
import io.github.gaming32.worldhostserver.ConnectionId.Companion.toConnectionId
import io.github.gaming32.worldhostserver.util.cast
import io.github.oshai.KotlinLogging
import io.ktor.network.selector.*
import io.ktor.network.sockets.*
import io.ktor.util.network.*
import io.ktor.utils.io.*
import io.ktor.utils.io.core.*
import io.ktor.utils.io.errors.*
import io.ktor.utils.io.streams.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.ClosedReceiveChannelException
import org.intellij.lang.annotations.Language
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.net.InetSocketAddress
import java.util.*
import kotlin.io.use
private val logger = KotlinLogging.logger {}
suspend fun WorldHostServer.runProxyServer() = coroutineScope {
if (config.baseAddr == null) {
logger.info("Proxy server disabled by request")
return@coroutineScope
}
if (EXTERNAL_SERVERS?.any { it.addr == null } == false) {
logger.info(
"Same-process proxy server is enabled, but it is not present in external_proxies.json. This means"
)
logger.info(
"that it will be used only as a fallback if the client's best choice for external proxy goes down."
)
}
logger.info("Starting proxy server")
aSocket(SelectorManager(Dispatchers.IO)).tcp().bind(port = config.inJavaPort).use { serverSocket ->
var nextConnectionId = 0L
logger.info("Started proxy server on {}", serverSocket.localAddress)
while (true) {
val proxySocket = serverSocket.accept()
logger.info("Accepted proxy connection from {}", proxySocket.remoteAddress)
val connectionId = nextConnectionId++
launch {
var connection: Connection? = null
try {
val receiveChannel = proxySocket.openReadChannel()
val sendChannel = proxySocket.openWriteChannel()
val handshakeData = ByteArray(receiveChannel.readVarInt()).also { receiveChannel.readFully(it) }
val inp = ByteArrayInputStream(handshakeData)
inp.readVarInt() // Packet ID
inp.readVarInt() // Protocol version
val thisAddr = inp.readString(255)
inp.skip(2) // Port
val nextState = inp.readVarInt()
val cidStr = thisAddr.substringBefore('.')
val destCid = try {
cidStr.toConnectionId()
} catch (e: Exception) {
if (thisAddr == config.baseAddr) {
// Star Trek humor
return@launch disconnect(sendChannel, nextState, "I'm a proxy server, not an engineer!")
}
return@launch disconnect(sendChannel, nextState, "Invalid ConnectionId: ${e.localizedMessage}")
}
connection = whConnections.byId(destCid) ?:
return@launch disconnect(sendChannel, nextState, "Couldn't find that server")
proxyConnections.withLock {
this[connectionId] = Pair(connection!!.id, sendChannel)
}
connection.socket.sendMessage(WorldHostS2CMessage.ProxyConnect(
connectionId,
proxySocket.remoteAddress.toJavaAddress().cast<InetSocketAddress>().address
))
connection.socket.sendMessage(WorldHostS2CMessage.ProxyC2SPacket(
connectionId,
ByteArrayOutputStream().apply {
writeVarInt(handshakeData.size)
write(handshakeData)
}.toByteArray()
))
val buffer = ByteArray(64 * 1024)
proxyLoop@ while (!sendChannel.isClosedForWrite) {
if (!connection!!.open) {
sendChannel.close()
break
}
val n = receiveChannel.readAvailable(buffer)
if (n == 0) continue
if (n == -1) {
sendChannel.close()
break
}
if (!connection.open) {
val failureStart = System.currentTimeMillis()
do {
if ((System.currentTimeMillis() - failureStart) > 5000) {
sendChannel.close()
break@proxyLoop
}
yield()
connection = whConnections.byId(destCid)
} while (connection == null || !connection.open)
}
connection.socket.sendMessage(WorldHostS2CMessage.ProxyC2SPacket(
connectionId, buffer.copyOf(n)
))
}
} catch (_: ClosedReceiveChannelException) {
} catch (e: Exception) {
if (
e !is IOException ||
e.message != "An existing connection was forcibly closed by the remote host"
) {
logger.error("An error occurred in proxy client handling", e)
}
} finally {
proxyConnections.withLock { this -= connectionId }
if (connection?.open == true) {
connection.socket.sendMessage(WorldHostS2CMessage.ProxyDisconnect(connectionId))
}
logger.info("Proxy connection closed")
}
}
}
}
}
private suspend fun disconnect(sendChannel: ByteWriteChannel, nextState: Int, message: String) {
@Language("JSON") val jsonMessage = """{"text":"$message","color":"red"}"""
val out = ByteArrayOutputStream()
out.writeVarInt(0x00)
if (nextState == 1) {
//language=JSON
out.writeString("""{"description":$jsonMessage}""")
} else if (nextState == 2) {
out.writeString(jsonMessage, 262144)
}
val out2 = ByteArrayOutputStream()
out2.writeVarInt(out.size())
@Suppress("BlockingMethodInNonBlockingContext")
out2.write(out.toByteArray())
sendChannel.writeFully(out2.toByteArray())
sendChannel.flush()
if (nextState == 1) {
out.reset()
out.writeVarInt(0x01)
repeat(8) {
out.write(0)
}
out2.reset()
out2.writeVarInt(out.size())
@Suppress("BlockingMethodInNonBlockingContext")
out2.write(out.toByteArray())
sendChannel.writeFully(out2.toByteArray())
sendChannel.flush()
}
sendChannel.close()
}
| 0 | Kotlin | 0 | 2 | e92092a9d47644a76433a6f46f2a01a52bf57e0e | 7,154 | world-host-server-kotlin | MIT License |
compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/lazy/AbstractFir2IrLazyDeclaration.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.lazy
import org.jetbrains.kotlin.fir.FirAnnotationContainer
import org.jetbrains.kotlin.fir.backend.Fir2IrComponents
import org.jetbrains.kotlin.ir.declarations.IrDeclaration
import org.jetbrains.kotlin.ir.declarations.IrFactory
import org.jetbrains.kotlin.ir.declarations.lazy.IrLazyDeclarationBase
import org.jetbrains.kotlin.ir.declarations.lazy.lazyVar
import org.jetbrains.kotlin.ir.expressions.IrConstructorCall
import org.jetbrains.kotlin.ir.util.DeclarationStubGenerator
import org.jetbrains.kotlin.ir.util.TypeTranslator
import org.jetbrains.kotlin.utils.addToStdlib.shouldNotBeCalled
import kotlin.properties.ReadWriteProperty
interface AbstractFir2IrLazyDeclaration<F> :
IrDeclaration, IrLazyDeclarationBase, Fir2IrComponents where F : FirAnnotationContainer {
val fir: F
override val factory: IrFactory
get() = irFactory
override fun createLazyAnnotations(): ReadWriteProperty<Any?, List<IrConstructorCall>> = lazyVar(lock) {
fir.annotations.mapNotNull {
callGenerator.convertToIrConstructorCall(it) as? IrConstructorCall
}
}
override val stubGenerator: DeclarationStubGenerator
get() = shouldNotBeCalled()
override val typeTranslator: TypeTranslator
get() = shouldNotBeCalled()
}
internal fun mutationNotSupported(): Nothing =
error("Mutation of Fir2Ir lazy elements is not possible")
| 184 | null | 5706 | 48,889 | c46c3c26038158cf80a739431ac8807ac4bbbc0c | 1,632 | kotlin | Apache License 2.0 |
main/src/androidTest/java/de/janniskilian/basket/BaseUiTest.kt | janniskilian | 160,101,734 | false | null | package de.janniskilian.basket
import androidx.annotation.StringRes
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performTextInput
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import de.janniskilian.basket.feature.main.MainActivity
import org.junit.Rule
@HiltAndroidTest
open class BaseUiTest {
@get:Rule(order = 0)
var hiltRule = HiltAndroidRule(this)
@get:Rule(order = 1)
val composeTestRule = createAndroidComposeRule<MainActivity>()
fun skipOnboarding() {
clickOn(R.string.onboarding_button)
}
fun getString(@StringRes resId: Int): String =
composeTestRule.activity.getString(resId)
fun clickOn(@StringRes resId: Int) {
clickOn(getString(resId))
}
fun clickOn(text: String) {
composeTestRule
.onNodeWithText(text)
.performClick()
}
fun clickOnContentDescription(@StringRes resId: Int) {
composeTestRule
.onNodeWithContentDescription(getString(resId))
.performClick()
}
fun writeTo(@StringRes resId: Int, text: String) {
composeTestRule
.onNodeWithText(getString(resId))
.performTextInput(text)
}
}
| 0 | Kotlin | 0 | 0 | e183a520fe2ab7332afaaedc6dd34f5e332d4358 | 1,452 | basket | Apache License 2.0 |
app/src/test/java/com/takusemba/jethub/viewmodel/SearchReposViewModelTest.kt | winterdl | 241,266,325 | true | {"Kotlin": 98490} | package com.takusemba.jethub.viewmodel
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.Observer
import com.takusemba.jethub.model.Repository
import com.takusemba.jethub.repository.SearchReposRepository
import com.takusemba.jethub.util.createRepository
import io.mockk.MockKAnnotations
import io.mockk.coEvery
import io.mockk.impl.annotations.MockK
import io.mockk.mockk
import io.mockk.verify
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.ObsoleteCoroutinesApi
import kotlinx.coroutines.newSingleThreadContext
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@ObsoleteCoroutinesApi
@RunWith(JUnit4::class)
class SearchReposViewModelTest {
@get:Rule var instantTaskExecutorRule: InstantTaskExecutorRule = InstantTaskExecutorRule()
@MockK private lateinit var searchReposRepository: SearchReposRepository
private val mainThreadSurrogate = newSingleThreadContext("UI thread")
@Before
fun setUp() {
MockKAnnotations.init(this)
Dispatchers.setMain(mainThreadSurrogate)
}
@After
fun tearDown() {
Dispatchers.resetMain()
mainThreadSurrogate.close()
}
@Test
fun `initial state`() {
runBlocking {
val observer = mockk<Observer<List<Repository>>>(relaxed = true)
coEvery { searchReposRepository.searchRepos("") } returns listOf(
createRepository(id = 1),
createRepository(id = 2),
createRepository(id = 3)
)
val viewModel = SearchReposViewModel(searchReposRepository)
viewModel.searchedRepos.observeForever(observer)
viewModel.coroutineContext[Job]!!.children.forEach { it.join() }
verify { observer.onChanged(match { it.size == 3 }) }
}
}
@Test
fun `search repos`() {
runBlocking {
val observer = mockk<Observer<List<Repository>>>(relaxed = true)
coEvery { searchReposRepository.searchRepos("") } returns emptyList()
coEvery { searchReposRepository.searchRepos("something") } returns listOf(
createRepository(id = 1),
createRepository(id = 2),
createRepository(id = 3)
)
val viewModel = SearchReposViewModel(searchReposRepository)
viewModel.search("something")
viewModel.searchedRepos.observeForever(observer)
viewModel.coroutineContext[Job]!!.children.forEach { it.join() }
verify { observer.onChanged(match { it.size == 3 }) }
}
}
}
| 0 | Kotlin | 0 | 0 | 72a28bb77032135608f3a9508663815e7bbecf8f | 2,668 | JetHub | Apache License 2.0 |
ui-details/src/main/java/com/nikitin/ui_details/DetailsFeatureFragment.kt | IstrajI | 478,113,719 | false | null | package com.nikitin.ui_details
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import com.nikitin.base.BaseFeatureFragment
import com.nikitin.ui_components.navigation.models.DetailsFeatureNavArgs
import com.nikitin.ui_details.databinding.FragmentDetailsFeatureBinding
class DetailsFeatureFragment: BaseFeatureFragment<FragmentDetailsFeatureBinding>() {
private val viewModel by viewModels<DetailsFeatureViewModel> { viewModelFactory }
override val bindingInflater =
{ layoutInflater: LayoutInflater, viewGroup: ViewGroup?, attachToParent: Boolean ->
FragmentDetailsFeatureBinding.inflate(
layoutInflater,
viewGroup,
attachToParent
)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
arguments?.let {
val featureArgs = DetailsFeatureNavArgs.fromBundle(it)
viewModel.setFeatureArguments(featureArgs)
}
}
} | 0 | Kotlin | 1 | 1 | 86d3ad1250037aa3ff6c4a95a02be8170d000b54 | 1,133 | android-feature-module-architecture | Apache License 2.0 |
deployment/src/main/kotlin/tz/co/asoft/deployment/target/Deployment.kt | aSoft-Ltd | 258,530,471 | false | null | package tz.co.asoft.deployment.target
import java.io.Serializable
data class Deployment(val name: String, var values: Map<String, Any>) : Serializable
| 0 | Kotlin | 3 | 1 | 8233558139144a26c40ae30526bfd0b26bc7b3cb | 153 | kotlin | MIT License |
kotlin/kotlin-dbms/src/main/kotlin/com/hypo/driven/simpledb/log/LogIterator.kt | kackey0-1 | 542,333,436 | false | null | package com.hypo.driven.simpledb.log
import com.hypo.driven.simpledb.file.BlockId
import com.hypo.driven.simpledb.file.FileManager
import com.hypo.driven.simpledb.file.Page
/**
* ログブロックのコンテンツを保持するためのページを割り当てるクラス
*
* @property fm ファイルマネージャー
* @property blockId イテレータで保持する内容を持つブロック
* @property page イテレータで保持する内容を持つページ
* @property currentPosition ページ内の現在の読み込んでいる場所
* @property boundary
*/
class LogIterator(val fm: FileManager, var blockId: BlockId): Iterator<ByteArray> {
private var page: Page
private var currentPosition = 0
private var boundary = 0
/**
* ログファイルの末尾のブロックの最初のログレコードにイテレータを配置する
*/
init {
val b = ByteArray(fm.blockSize)
page = Page(b)
moveToBlock(blockId)
}
/**
* 現在のログレコードがログファイルの中で最も古いレコードかを判定する
* -> 次のログレコードがあるか
* @return ログレコードがあればtrue
*/
override fun hasNext(): Boolean {
return currentPosition < fm.blockSize || blockId.number > 0
}
/**
* ページ内の次のログレコードに移動する
* レコードがない場合は、前のブロックを読み込み、ブロックの最初のレコードを返す
* @return ログレコードをバイト配列として返す
*/
override fun next(): ByteArray {
if (currentPosition == fm.blockSize) {
blockId = BlockId(blockId.filename, blockId.number-1)
moveToBlock(blockId)
}
val record = page.getBytes(currentPosition)
currentPosition += Integer.BYTES + record.size
return record
}
/**
* [blk]のブロックの内容をページに読み込み、現在の場所に設定する
*/
private fun moveToBlock(blk: BlockId) {
fm.read(blk, page)
boundary = page.getInt(0)
currentPosition = boundary
}
}
| 3 | Kotlin | 0 | 0 | d9dffb6a17f624ea0dec86434906fa58be98970b | 1,620 | from-scrach | Apache License 2.0 |
skiko/src/jsMain/kotlin/org/jetbrains/skiko/SkiaLayer.js.kt | JetBrains | 282,864,178 | false | null | package org.jetbrains.skiko
import kotlinx.browser.window
import org.w3c.dom.HTMLCanvasElement
import org.w3c.dom.events.InputEvent
import org.w3c.dom.events.KeyboardEvent
import org.w3c.dom.events.MouseEvent
import org.w3c.dom.events.WheelEvent
actual open class SkiaLayer {
private var state: CanvasRenderer? = null
actual var renderApi: GraphicsApi = GraphicsApi.WEBGL
actual val contentScale: Float
get() = window.devicePixelRatio.toFloat()
actual var fullscreen: Boolean
get() = false
set(value) {
if (value) throw Exception("Fullscreen is not supported!")
}
actual var transparency: Boolean
get() = false
set(value) {
if (value) throw Exception("Transparency is not supported!")
}
actual fun needRedraw() {
state?.needRedraw()
}
actual var skikoView: SkikoView? = null
actual fun attachTo(container: Any) {
attachTo(container as HTMLCanvasElement, false)
}
actual fun detach() {
// TODO: when switch to the frame dispatcher - stop it here.
}
private var isPointerPressed = false
private var desiredWidth = 0
private var desiredHeight = 0
fun attachTo(htmlCanvas: HTMLCanvasElement, autoDetach: Boolean = true) {
// Scale canvas to allow high DPI rendering as suggested in
// https://www.khronos.org/webgl/wiki/HandlingHighDPI.
desiredWidth = htmlCanvas.width
desiredHeight = htmlCanvas.height
htmlCanvas.style.width = "${desiredWidth}px"
htmlCanvas.style.height = "${desiredHeight}px"
setOnChangeScaleNotifier()
state = object: CanvasRenderer(htmlCanvas) {
override fun drawFrame(currentTimestamp: Double) {
// currentTimestamp is in milliseconds.
val currentNanos = currentTimestamp * 1_000_000
skikoView?.onRender(canvas!!, width, height, currentNanos.toLong())
}
}.apply { initCanvas(desiredWidth, desiredHeight, contentScale) }
// See https://www.w3schools.com/jsref/dom_obj_event.asp
// https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events
htmlCanvas.addEventListener("pointerdown", { event ->
event as MouseEvent
isPointerPressed = true
skikoView?.onPointerEvent(toSkikoEvent(event, true, SkikoPointerEventKind.DOWN))
})
htmlCanvas.addEventListener("pointerup", { event ->
event as MouseEvent
isPointerPressed = false
skikoView?.onPointerEvent(toSkikoEvent(event, true, SkikoPointerEventKind.UP))
})
htmlCanvas.addEventListener("pointermove", { event ->
event as MouseEvent
if (isPointerPressed) {
skikoView?.onPointerEvent(toSkikoDragEvent(event))
} else {
skikoView?.onPointerEvent(toSkikoEvent(event, false, SkikoPointerEventKind.MOVE))
}
})
htmlCanvas.addEventListener("wheel", { event ->
event as WheelEvent
skikoView?.onPointerEvent(toSkikoScrollEvent(event, isPointerPressed))
})
htmlCanvas.addEventListener("contextmenu", { event ->
event.preventDefault()
})
htmlCanvas.addEventListener("keydown", { event ->
event as KeyboardEvent
skikoView?.onKeyboardEvent(toSkikoEvent(event, SkikoKeyboardEventKind.DOWN))
})
htmlCanvas.addEventListener("keyup", { event ->
event as KeyboardEvent
skikoView?.onKeyboardEvent(toSkikoEvent(event, SkikoKeyboardEventKind.UP))
})
}
private fun setOnChangeScaleNotifier() {
state?.initCanvas(desiredWidth, desiredHeight, contentScale)
window.matchMedia("(resolution: ${contentScale}dppx)").addEventListener("change", { setOnChangeScaleNotifier() }, true)
onContentScaleChanged?.invoke(contentScale)
}
}
var onContentScaleChanged: ((Float) -> Unit)? = null
actual typealias SkikoGesturePlatformEvent = Any
actual typealias SkikoPlatformInputEvent = InputEvent
actual typealias SkikoPlatformKeyboardEvent = KeyboardEvent
// MouseEvent is base class of PointerEvent
actual typealias SkikoPlatformPointerEvent = MouseEvent
| 80 | null | 95 | 840 | cf67c819f15ffcd8b6ecee3edb29ae2cdce1f2fe | 4,309 | skiko | Apache License 2.0 |
tools/debug.kts | cfig | 56,238,465 | false | null | import java.io.File
import java.nio.file.Files
import java.nio.file.Paths
if (null == System.getenv("ANDROID_PRODUCT_OUT")) {
println("ANDROID_PRODUCT_OUT not set, did U envsetup/lunch product?")
System.exit(1)
}
val xbins = listOf("su")
val bins = listOf("sh", "logcat", "logcatd", "logd", "linker", "toolbox", "toybox", "applypatch", "debuggerd", "reboot")
val libs = listOf("libnetutils.so", "libdl.so", "libutils.so", "libc++.so", "libc.so", "libm.so", "libz.so", "libstdc++.so", "libcutils.so", "libselinux.so", "liblog.so", "libpcrecpp.so", "libpcre2.so", "libsysutils.so", "libnl.so", "libbase.so", "libbacktrace.so", "libunwind.so", "libcrypto.so", "libpackagelistparser.so", "libpcrecpp.so", "liblzma.so", "liblogcat.so")
val initrcFiles = listOf("logcatd.rc", "logd.rc")
val toolboxLinks = listOf("df", "getevent", "iftop", "ioctl", "ionice", "log", "lsof", "nandread", "newfs_msdos", "ps", "prlimit", "renice", "sendevent", "start", "stop", "top", "uptime", "watchprops", "dd", "du")
val toyboxLinks = listOf("ps", "ls", "acpi", "basename", "blockdev", "bzcat", "cal", "cat", "chcon", "chgrp", "chmod", "chown", "chroot", "cksum", "clear", "comm", "cmp", "cp", "cpio", "cut", "date", "dirname", "dmesg", "dos2unix", "echo", "env", "expand", "expr", "fallocate", "false", "find", "free", "getenforce", "getprop", "groups", "head", "hostname", "hwclock", "id", "ifconfig", "inotifyd", "insmod", "kill", "load_policy", "ln", "logname", "losetup", "lsmod", "lsusb", "md5sum", "mkdir", "mknod", "mkswap", "mktemp", "modinfo", "more", "mount", "mountpoint", "mv", "netstat", "nice", "nl", "nohup", "od", "paste", "patch", "grep", "pidof", "pkill", "pmap", "printenv", "printf", "pwd", "readlink", "realpath", "restorecon", "rm", "rmdir", "rmmod", "route", "runcon", "sed", "seq", "setenforce", "setprop", "setsid", "sha1sum", "sleep", "sort", "split", "stat", "strings", "swapoff", "swapon", "sync", "sysctl", "tac", "tail", "tar", "taskset", "tee", "time", "timeout", "touch", "tr", "true", "truncate", "umount", "uname", "uniq", "unix2dos", "usleep", "vmstat", "wc", "which", "whoami", "xargs", "yes")
val workdir: String = "build/unzip_boot"
File("$workdir/root/system/bin").mkdirs()
File("$workdir/root/system/xbin").mkdirs()
File("$workdir/root/system/lib").mkdirs()
xbins.forEach { it ->
val bin = System.getenv("ANDROID_PRODUCT_OUT") + "/system/xbin/" + it
val binTgt = workdir + "/root/system/xbin/" + it
println("$bin -> $binTgt")
File(bin).copyTo(File(binTgt), true)
}
bins.forEach { it ->
val bin = System.getenv("ANDROID_PRODUCT_OUT") + "/system/bin/" + it
val binTgt = workdir + "/root/system/bin/" + it
println("$bin -> $binTgt")
File(bin).copyTo(File(binTgt), true)
}
libs.forEach { it ->
val lib = System.getenv("ANDROID_PRODUCT_OUT") + "/system/lib/" + it
val libTgt = workdir + "/root/system/lib/" + it
println("$lib -> $libTgt")
File(lib).copyTo(File(libTgt), true)
}
toolboxLinks.forEach { it ->
val bin = workdir + "/root/system/bin/" + it
Files.deleteIfExists(File(bin).toPath())
Files.createSymbolicLink(Paths.get(bin), Paths.get("toolbox"));
}
toyboxLinks.forEach { it ->
val bin = workdir + "/root/system/bin/" + it
Files.deleteIfExists(File(bin).toPath())
Files.createSymbolicLink(Paths.get(bin), Paths.get("toybox"));
}
File(workdir + "/root/system/etc/init").mkdirs()
initrcFiles.forEach { it ->
val bin = System.getenv("ANDROID_PRODUCT_OUT") + "/system/etc/init/" + it
val binTgt = workdir + "/root/system/etc/init/" + it
Files.deleteIfExists(File(binTgt).toPath())
File(bin).copyTo(File(binTgt), true)
}
fun enableShell() {
val bin = "src/resources/console.rc"
val binTgt = workdir + "/root/system/etc/init/" + "console.rc"
Files.deleteIfExists(File(binTgt).toPath())
File(bin).copyTo(File(binTgt), true)
}
enableShell()
| 20 | null | 222 | 972 | cae7591d55647084d9ec0f73631caac7d43481d3 | 3,879 | Android_boot_image_editor | Apache License 2.0 |
pensjon-brevbaker/src/main/kotlin/no/nav/pensjon/etterlatte/maler/fraser/common/Felles.kt | navikt | 375,334,697 | false | {"Kotlin": 2148171, "TypeScript": 257242, "TeX": 12815, "Shell": 9753, "CSS": 7595, "Python": 4661, "JavaScript": 4298, "Dockerfile": 2406, "HTML": 1053} | package no.nav.pensjon.etterlatte.maler.fraser.common
import no.nav.pensjon.brev.template.LangBokmalNynorskEnglish
import no.nav.pensjon.brev.template.Language
import no.nav.pensjon.brev.template.Language.Bokmal
import no.nav.pensjon.brev.template.Language.Nynorsk
import no.nav.pensjon.brev.template.Language.English
import no.nav.pensjon.brev.template.OutlinePhrase
import no.nav.pensjon.brev.template.dsl.OutlineOnlyScope
import no.nav.pensjon.brev.template.dsl.text
object Felles {
object BlankTekst : OutlinePhrase<LangBokmalNynorskEnglish>() {
override fun OutlineOnlyScope<LangBokmalNynorskEnglish, Unit>.template() {
paragraph {
text(
Bokmal to "",
Nynorsk to "",
English to "",
)
}
}
}
object HjelpFraAndreForvaltningsloven12 : OutlinePhrase<LangBokmalNynorskEnglish>() {
override fun OutlineOnlyScope<LangBokmalNynorskEnglish, Unit>.template() {
title2 {
text(
Bokmal to "Hjelp fra andre - forvaltningsloven § 12",
Nynorsk to "Hjelp frå andre – forvaltingslova § 12",
English to "Help from others – Section 12 of the Public Administration Act",
)
}
paragraph {
text(
Bokmal to "Du kan be om hjelp fra andre under hele saksbehandlingen, for eksempel av advokat, " +
"rettshjelper, en organisasjon du er medlem av eller en annen myndig person. Hvis den som " +
"hjelper deg ikke er advokat, må du gi denne personen en skriftlig fullmakt. Bruk gjerne " +
"skjemaet du finner på ${Constants.FULLMAKT_URL}.",
Nynorsk to "Du har under heile saksbehandlinga høve til å be om hjelp frå til dømes advokat, " +
"rettshjelpar, organisasjonar du er medlem av, eller andre myndige personar. " +
"Dersom personen som hjelper deg, ikkje er advokat, " +
"må du gi vedkomande ei skriftleg fullmakt. " +
"Bruk gjerne skjemaet du finn på ${Constants.FULLMAKT_URL}.",
English to "You can ask for help from others throughout case processing, such as an attorney, " +
"legal aid, an organization of which you are a member or another person of legal age. " +
"If the person helping you is not an attorney, " +
"you must give this person a written power of attorney. " +
"Feel free to use the form you find here: ${Constants.Engelsk.FULLMAKT_URL}.",
)
}
}
}
object SlikUttalerDuDeg : OutlinePhrase<LangBokmalNynorskEnglish>() {
override fun OutlineOnlyScope<LangBokmalNynorskEnglish, Unit>.template() {
title2 {
text(
Bokmal to "Slik uttaler du deg",
Nynorsk to "Slik uttaler du deg",
English to "How to provide a statement",
)
}
paragraph {
text(
Bokmal to "Du kan sende uttalelsen din ved å logge deg inn på " +
"${Constants.BESKJED_TIL_NAV_URL} og velge «Send beskjed til NAV». Du kan også sende " +
"uttalelsen din til oss i posten. Adressen finner du på ${Constants.ETTERSENDELSE_URL}.",
Nynorsk to "Du kan sende svar til oss ved å logge inn på " +
"${Constants.BESKJED_TIL_NAV_URL} og velje «Send beskjed til NAV». Alternativt kan du " +
"sende oss svar i posten. Adressa finn du på ${Constants.ETTERSENDELSE_URL}.",
English to "You can send us a statement regarding the matter by logging in to: " +
"${Constants.BESKJED_TIL_NAV_URL} and selecting «Send beskjed til NAV». You can also " +
"send us your statement by post. The address can be found at: ${Constants.ETTERSENDELSE_URL}.",
)
}
}
}
object HvaSkjerVidereIDinSak : OutlinePhrase<LangBokmalNynorskEnglish>() {
override fun OutlineOnlyScope<LangBokmalNynorskEnglish, Unit>.template() {
title2 {
text(
Bokmal to "Hva skjer videre i din sak",
Nynorsk to "Kva som skjer vidare i saka",
English to "What will happen further in your case",
)
}
paragraph {
text(
Bokmal to "Når fristen for uttale er gått ut, vil vi gjøre et vedtak og sende det " +
"til deg. Hvis du må betale tilbake hele eller deler av beløpet, gir vi beskjed i " +
"vedtaket om hvordan du betaler tilbake.",
Nynorsk to "Når svarfristen har gått ut, fattar vi eit vedtak og sender det til deg. " +
"Dersom du må betale tilbake heile eller delar av beløpet, forklarer vi i vedtaket " +
"korleis du betaler tilbake.",
English to "When the deadline for providing statements has expired, we will make a decision " +
"and send it to you. If you are required to repay the whole or part of the amount, we will " +
"inform you in the decision of how to make repayments.",
)
}
}
}
} | 3 | Kotlin | 3 | 1 | 419a0c4ff89459bccad6402e40762629f4134952 | 5,745 | pensjonsbrev | MIT License |
twitter4j-v2-support/src/main/kotlin/twitter4j/UsersResponse.kt | takke | 280,848,830 | false | null | package twitter4j
import java.util.HashMap
class UsersResponse : TwitterResponse {
@Transient
private var rateLimitStatus: RateLimitStatus? = null
@Transient
private var accessLevel = 0
val users: List<User2> = mutableListOf()
// includes.polls
val pollsMap = HashMap<Long, Poll>()
// includes.users
val usersMap = HashMap<Long, User2>()
// includes.tweets
val tweetsMap = HashMap<Long, Tweet>()
constructor(res: HttpResponse, isJSONStoreEnabled: Boolean) {
rateLimitStatus = RateLimitStatusJSONImpl.createFromResponseHeader(res)
accessLevel = ParseUtil.toAccessLevel(res)
parse(res.asJSONObject(), isJSONStoreEnabled)
}
constructor(json: JSONObject, isJSONStoreEnabled: Boolean = false) {
parse(json, isJSONStoreEnabled)
}
private fun parse(jsonObject: JSONObject, isJSONStoreEnabled: Boolean) {
val users = users as MutableList
users.clear()
val includes = jsonObject.optJSONObject("includes")
//--------------------------------------------------
// create maps from includes
//--------------------------------------------------
V2Util.collectPolls(includes, pollsMap)
V2Util.collectUsers(includes, usersMap)
V2Util.collectTweets(includes, tweetsMap)
// TODO includes.places, includes.media ...
//--------------------------------------------------
// create users from data
//--------------------------------------------------
val dataArray = jsonObject.optJSONArray("data")
if (dataArray != null) {
for (i in 0 until dataArray.length()) {
val data = dataArray.getJSONObject(i)
users.add(User2.parse(data))
}
}
if (isJSONStoreEnabled) {
TwitterObjectFactory.registerJSONObject(this, jsonObject)
}
}
override fun getRateLimitStatus(): RateLimitStatus? {
return rateLimitStatus
}
override fun getAccessLevel(): Int {
return accessLevel
}
override fun toString(): String {
return "UsersResponse(rateLimitStatus=$rateLimitStatus, accessLevel=$accessLevel, users=$users, pollsMap=$pollsMap, usersMap=$usersMap, tweetsMap=$tweetsMap)"
}
} | 6 | null | 6 | 82 | f13b6f15f47078517251e72bbee9854ec07285a5 | 2,319 | twitter4j-v2 | Apache License 2.0 |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/medialive/CfnChannelAribSourceSettingsPropertyDsl.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 63959868} | @file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.medialive
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import software.amazon.awscdk.services.medialive.CfnChannel
/**
* Information about the ARIB captions to extract from the input.
*
* The parent of this entity is CaptionSelectorSettings.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.medialive.*;
* AribSourceSettingsProperty aribSourceSettingsProperty =
* AribSourceSettingsProperty.builder().build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-aribsourcesettings.html)
*/
@CdkDslMarker
public class CfnChannelAribSourceSettingsPropertyDsl {
private val cdkBuilder: CfnChannel.AribSourceSettingsProperty.Builder =
CfnChannel.AribSourceSettingsProperty.builder()
public fun build(): CfnChannel.AribSourceSettingsProperty = cdkBuilder.build()
}
| 3 | Kotlin | 0 | 3 | c59c6292cf08f0fc3280d61e7f8cff813a608a62 | 1,267 | awscdk-dsl-kotlin | Apache License 2.0 |
app/src/main/java/com/testwther/source/local/repository/city/CityLocalRepository.kt | Pawlo210286 | 274,120,293 | false | null | package com.testwther.source.local.repository.city
import com.testwther.source.local.entity.CityLocalEntity
import com.testwther.source.local.repository.LocalDatabase
class CityLocalRepository(
private val database: LocalDatabase
) : ICityLocalRepository {
override suspend fun saveCity(city: CityLocalEntity): Long = database.cityDao().insert(city)
override suspend fun clearCities() = database.cityDao().clear()
override suspend fun getCityByName(cityName: String): CityLocalEntity? =
database.cityDao().getCityByName(cityName)
} | 0 | Kotlin | 0 | 0 | a8e2c2a7eb2ce6fc8e9f4d2d6218229de7d2dc24 | 560 | testWther | MIT License |
app/src/main/java/kittoku/osc/layer/PppClient.kt | kittoku | 173,106,265 | false | null | package com.app.amigo.layer
import com.app.amigo.ControlClientVPN
import com.app.amigo.misc.*
import com.app.amigo.negotiator.*
import com.app.amigo.unit.*
import org.chromium.base.Log
internal enum class LcpState {
REQ_SENT, ACK_RCVD, ACK_SENT, OPENED
}
internal enum class IpcpState {
REQ_SENT, ACK_RCVD, ACK_SENT, OPENED
}
internal enum class Ipv6cpState {
REQ_SENT, ACK_RCVD, ACK_SENT, OPENED
}
internal class PppClient(parent: ControlClientVPN) : Client(parent) {
internal var globalIdentifier: Byte = -1
internal var currentLcpRequestId: Byte = 0
internal var currentIpcpRequestId: Byte = 0
internal var currentIpv6cpRequestId: Byte = 0
internal var currentAuthRequestId: Byte = 0
internal val lcpTimer = Timer(3_000L)
internal val lcpCounter = Counter(10)
internal var lcpState = LcpState.REQ_SENT
private var isInitialLcp = true
internal val authTimer = Timer(3_000L)
internal var isAuthFinished = false
private var isInitialAuth = true
internal val ipcpTimer = Timer(3_000L)
internal val ipcpCounter = Counter(10)
internal var ipcpState = IpcpState.REQ_SENT
private var isInitialIpcp = true
internal val ipv6cpTimer = Timer(3_000L)
internal val ipv6cpCounter = Counter(10)
internal var ipv6cpState = Ipv6cpState.REQ_SENT
private var isInitialIpv6cp = true
internal val echoTimer = Timer(60_000L)
internal val echoCounter = Counter(1)
private val hasIncoming: Boolean
get() = incomingBuffer.pppLimit > incomingBuffer.position()
private val canStartPpp: Boolean
get() {
if (status.sstp == SstpStatus.CLIENT_CALL_CONNECTED) return true
if (status.sstp == SstpStatus.CLIENT_CONNECT_ACK_RECEIVED) return true
return false
}
private fun readAsDiscarded() {
incomingBuffer.position(incomingBuffer.pppLimit)
}
private fun proceedLcp() {
if (lcpTimer.isOver) {
sendLcpConfigureRequest()
if (lcpState == LcpState.ACK_RCVD) lcpState = LcpState.REQ_SENT
return
}
if (!hasIncoming) return
if (PppProtocol.resolve(incomingBuffer.getShort()) != PppProtocol.LCP) readAsDiscarded()
else {
val code = incomingBuffer.getByte()
when (LcpCode.resolve(code)) {
LcpCode.CONFIGURE_REQUEST -> receiveLcpConfigureRequest()
LcpCode.CONFIGURE_ACK -> receiveLcpConfigureAck()
LcpCode.CONFIGURE_NAK -> receiveLcpConfigureNak()
LcpCode.CONFIGURE_REJECT -> receiveLcpConfigureReject()
LcpCode.TERMINATE_REQUEST, LcpCode.CODE_REJECT -> {
parent.informInvalidUnit(::proceedLcp)
kill()
return
}
else -> readAsDiscarded()
}
}
incomingBuffer.forget()
}
private fun proceedPap() {
if (authTimer.isOver) {
parent.informTimerOver(::proceedPap)
kill()
return
}
if (!hasIncoming) return
if (PppProtocol.resolve(incomingBuffer.getShort()) != PppProtocol.PAP) readAsDiscarded()
else {
val code = incomingBuffer.getByte()
when (PapCode.resolve(code)) {
PapCode.AUTHENTICATE_ACK -> receivePapAuthenticateAck()
PapCode.AUTHENTICATE_NAK -> receivePapAuthenticateNak()
else -> readAsDiscarded()
}
}
incomingBuffer.forget()
}
private fun proceedChap() {
if (authTimer.isOver) {
parent.informTimerOver(::proceedChap)
kill()
return
}
if (!hasIncoming) return
if (PppProtocol.resolve(incomingBuffer.getShort()) != PppProtocol.CHAP) readAsDiscarded()
else {
val code = incomingBuffer.getByte()
when (ChapCode.resolve(code)) {
ChapCode.CHALLENGE -> receiveChapChallenge()
ChapCode.SUCCESS -> receiveChapSuccess()
ChapCode.FAILURE -> receiveChapFailure()
else -> readAsDiscarded()
}
}
incomingBuffer.forget()
}
private fun proceedIpcp() {
if (ipcpTimer.isOver) {
sendIpcpConfigureRequest()
if (ipcpState == IpcpState.ACK_RCVD) ipcpState = IpcpState.REQ_SENT
return
}
if (!hasIncoming) return
when (PppProtocol.resolve(incomingBuffer.getShort())) {
PppProtocol.LCP -> {
if (LcpCode.resolve(incomingBuffer.getByte()) == LcpCode.PROTOCOL_REJECT) {
receiveLcpProtocolReject(PppProtocol.IPCP)
} else readAsDiscarded()
}
PppProtocol.IPCP -> {
val code = incomingBuffer.getByte()
when (IpcpCode.resolve(code)) {
IpcpCode.CONFIGURE_REQUEST -> receiveIpcpConfigureRequest()
IpcpCode.CONFIGURE_ACK -> receiveIpcpConfigureAck()
IpcpCode.CONFIGURE_NAK -> receiveIpcpConfigureNak()
IpcpCode.CONFIGURE_REJECT -> receiveIpcpConfigureReject()
IpcpCode.TERMINATE_REQUEST, IpcpCode.CODE_REJECT -> {
parent.informInvalidUnit(::proceedIpcp)
kill()
return
}
else -> readAsDiscarded()
}
}
else -> readAsDiscarded()
}
incomingBuffer.forget()
}
private fun proceedIpv6cp() {
if (ipv6cpTimer.isOver) {
sendIpv6cpConfigureRequest()
if (ipv6cpState == Ipv6cpState.ACK_RCVD) ipv6cpState = Ipv6cpState.REQ_SENT
return
}
if (!hasIncoming) return
when (PppProtocol.resolve(incomingBuffer.getShort())) {
PppProtocol.LCP -> {
if (LcpCode.resolve(incomingBuffer.getByte()) == LcpCode.PROTOCOL_REJECT) {
receiveLcpProtocolReject(PppProtocol.IPV6CP)
}
}
PppProtocol.IPV6CP -> {
val code = incomingBuffer.getByte()
when (Ipv6cpCode.resolve(code)) {
Ipv6cpCode.CONFIGURE_REQUEST -> receiveIpv6cpConfigureRequest()
Ipv6cpCode.CONFIGURE_ACK -> receiveIpv6cpConfigureAck()
Ipv6cpCode.CONFIGURE_NAK -> receiveIpv6cpConfigureNak()
Ipv6cpCode.CONFIGURE_REJECT -> receiveIpv6cpConfigureReject()
Ipv6cpCode.TERMINATE_REQUEST, Ipv6cpCode.CODE_REJECT -> {
parent.informInvalidUnit(::proceedIpv6cp)
kill()
return
}
else -> readAsDiscarded()
}
}
else -> readAsDiscarded()
}
incomingBuffer.forget()
}
private fun proceedNetwork() {
if (echoTimer.isOver) sendLcpEchoRequest()
if (!hasIncoming) return
else {
echoTimer.reset()
echoCounter.reset()
}
when (PppProtocol.resolve(incomingBuffer.getShort())) {
PppProtocol.LCP -> {
when (LcpCode.resolve(incomingBuffer.getByte())) {
LcpCode.ECHO_REQUEST -> receiveLcpEchoRequest()
LcpCode.ECHO_REPLY -> receiveLcpEchoReply()
else -> {
parent.informInvalidUnit(::proceedNetwork)
kill()
return
}
}
}
PppProtocol.CHAP -> {
val code = incomingBuffer.getByte()
when (ChapCode.resolve(code)) {
ChapCode.CHALLENGE -> receiveChapChallenge()
ChapCode.SUCCESS -> receiveChapSuccess()
ChapCode.FAILURE -> receiveChapFailure()
else -> readAsDiscarded()
}
}
PppProtocol.IP, PppProtocol.IPV6 -> incomingBuffer.convey()
else -> readAsDiscarded()
}
incomingBuffer.forget()
}
override fun proceed() {
if (!canStartPpp) return
when (status.ppp) {
PppStatus.NEGOTIATE_LCP -> {
if (isInitialLcp) {
sendLcpConfigureRequest()
isInitialLcp = false
}
proceedLcp()
if (lcpState == LcpState.OPENED) status.ppp = PppStatus.AUTHENTICATE
}
PppStatus.AUTHENTICATE -> {
when (networkSetting.currentAuth) {
AuthSuite.PAP -> {
if (isInitialAuth) {
sendPapRequest()
isInitialAuth = false
}
proceedPap()
if (isAuthFinished) {
status.ppp = if (networkSetting.PPP_IPv4_ENABLED) {
PppStatus.NEGOTIATE_IPCP
} else {
PppStatus.NEGOTIATE_IPV6CP
}
}
}
AuthSuite.MSCHAPv2 -> {
if (isInitialAuth) {
networkSetting.chapSetting = ChapSetting()
authTimer.reset()
isInitialAuth = false
}
proceedChap()
if (isAuthFinished) {
status.ppp = if (networkSetting.PPP_IPv4_ENABLED) {
PppStatus.NEGOTIATE_IPCP
} else {
PppStatus.NEGOTIATE_IPV6CP
}
}
}
}
}
PppStatus.NEGOTIATE_IPCP -> {
if (isInitialIpcp) {
sendIpcpConfigureRequest()
isInitialIpcp = false
}
proceedIpcp()
if (ipcpState == IpcpState.OPENED) {
if (networkSetting.PPP_IPv6_ENABLED) {
status.ppp = PppStatus.NEGOTIATE_IPV6CP
} else startNetworking()
}
}
PppStatus.NEGOTIATE_IPV6CP -> {
if (isInitialIpv6cp) {
sendIpv6cpConfigureRequest()
isInitialIpv6cp = false
}
proceedIpv6cp()
if (ipv6cpState == Ipv6cpState.OPENED) startNetworking()
}
PppStatus.NETWORK -> proceedNetwork()
}
}
private fun startNetworking() {
Log.e("@!@PppClient :", "startNetworking")
parent.attachNetworkObserver()
parent.ipTerminal?.also {
try {
it.initializeTun()
} catch (e: Exception) {
parent.inform("Failed to create VPN interface", e)
kill()
return
}
}
status.ppp = PppStatus.NETWORK
// parent.reconnectionSettings.resetCount() // -10.01.22
parent.launchJobData()
echoTimer.reset()
}
private var TAG = "@!@PppClient"
internal fun kill() {
status.sstp = SstpStatus.CALL_DISCONNECT_IN_PROGRESS_1
parent.inform("PPP layer turned down", null)
}
}
| 5 | null | 25 | 81 | 0f926734a1cceb4a16fe111b433427fa7d5b4f88 | 11,758 | Open-SSTP-Client | MIT License |
telegram-bot/src/commonMain/kotlin/eu/vendeli/tgbot/api/media/Audio.kt | vendelieu | 496,567,172 | false | null | @file:Suppress("MatchingDeclarationName")
package eu.vendeli.tgbot.api.media
import eu.vendeli.tgbot.interfaces.BusinessActionExt
import eu.vendeli.tgbot.interfaces.MediaAction
import eu.vendeli.tgbot.interfaces.features.CaptionFeature
import eu.vendeli.tgbot.interfaces.features.MarkupFeature
import eu.vendeli.tgbot.interfaces.features.OptionsFeature
import eu.vendeli.tgbot.types.Message
import eu.vendeli.tgbot.types.internal.ImplicitFile
import eu.vendeli.tgbot.types.internal.InputFile
import eu.vendeli.tgbot.types.internal.TgMethod
import eu.vendeli.tgbot.types.internal.options.AudioOptions
import eu.vendeli.tgbot.utils.getReturnType
import eu.vendeli.tgbot.utils.handleImplicitFile
import eu.vendeli.tgbot.utils.toImplicitFile
class SendAudioAction(audio: ImplicitFile) :
MediaAction<Message>(),
BusinessActionExt<Message>,
OptionsFeature<SendAudioAction, AudioOptions>,
MarkupFeature<SendAudioAction>,
CaptionFeature<SendAudioAction> {
override val method = TgMethod("sendAudio")
override val returnType = getReturnType()
override val options = AudioOptions()
init {
handleImplicitFile(audio, "audio")
}
}
/**
* Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
* For sending voice messages, use the sendVoice method instead.
*
* [Api reference](https://core.telegram.org/bots/api#sendaudio)
* @param businessConnectionId Unique identifier of the business connection on behalf of which the message will be sent
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param messageThreadId Unique identifier for the target message thread (topic) of the forum; for forum supergroups only
* @param audio Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files: https://core.telegram.org/bots/api#sending-files
* @param caption Audio caption, 0-1024 characters after entities parsing
* @param parseMode Mode for parsing entities in the audio caption. See formatting options for more details.
* @param captionEntities A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
* @param duration Duration of the audio in seconds
* @param performer Performer
* @param title Track name
* @param thumbnail Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass "attach://<file_attach_name>" if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files: https://core.telegram.org/bots/api#sending-files
* @param disableNotification Sends the message silently. Users will receive a notification with no sound.
* @param protectContent Protects the contents of the sent message from forwarding and saving
* @param replyParameters Description of the message to reply to
* @param replyMarkup Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user. Not supported for messages sent on behalf of a business account
* @returns [Message]
*/
@Suppress("NOTHING_TO_INLINE")
inline fun audio(file: ImplicitFile) = SendAudioAction(file)
inline fun audio(block: () -> String) = audio(block().toImplicitFile())
@Suppress("NOTHING_TO_INLINE")
inline fun audio(ba: ByteArray) = audio(ba.toImplicitFile("audio.mp3"))
@Suppress("NOTHING_TO_INLINE")
inline fun audio(file: InputFile) = audio(file.toImplicitFile())
inline fun sendAudio(block: () -> String) = audio(block)
@Suppress("NOTHING_TO_INLINE")
inline fun sendAudio(file: ImplicitFile) = audio(file)
| 6 | null | 9 | 165 | c1ddf4a42c577410af31249dc650858320668263 | 4,407 | telegram-bot | Apache License 2.0 |
app/src/main/java/com/example/medlemma/View/DialogMyMemberships.kt | Stuhren | 700,369,616 | false | {"Kotlin": 130052, "Java": 201} | package com.example.medlemma.View
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Alignment.Companion.CenterHorizontally
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import coil.compose.rememberImagePainter
import com.example.medlemma.ui.theme.SoftGray
// Replace with the actual Softgray color value
@Composable
fun SimpleDialog(
Category: String,
logo: String,
Name: String,
Qr: String,
onDismiss: () -> Unit,
onRemoveClick: () -> Unit // Add this callback
) {
Dialog(
onDismissRequest = { onDismiss() },
properties = DialogProperties(
dismissOnBackPress = true,
dismissOnClickOutside = true
)
) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
shape = RoundedCornerShape(16.dp),
) {
Box(modifier = Modifier.background(SoftGray)) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(10.dp)
) {
Text(
text = Name,
modifier = Modifier.padding(bottom = 16.dp)
)
Text(
text = Category,
modifier = Modifier.padding(bottom = 16.dp)
)
Image(
painter = rememberImagePainter(data = logo),
contentDescription = null,
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
.clip(shape = RoundedCornerShape(16.dp)),
contentScale = ContentScale.Crop
)
Spacer(modifier = Modifier.height(32.dp))
Image(
painter = rememberImagePainter(data = Qr),
contentDescription = null,
modifier = Modifier
.size(120.dp)
.align(alignment = CenterHorizontally)
.clip(shape = RoundedCornerShape(16.dp)),
contentScale = ContentScale.Crop
)
Spacer(modifier = Modifier.height(32.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
Button(
onClick = {
onRemoveClick() // Call the onRemoveClick callback
onDismiss()
},
modifier = Modifier
.weight(1f)
.padding(end = 8.dp),
colors = ButtonDefaults.buttonColors(containerColor = Color.Red)
) {
Text(text = "Remove", color = Color.White)
}
Button(
onClick = {
onDismiss()
},
modifier = Modifier
.weight(1f),
) {
Text(text = "Close")
}
}
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | c04e3beff763b1566ab560b2ba4d11b8f60c451d | 4,416 | Medlemma | Apache License 2.0 |
app/src/main/java/com/example/chuculture/Utils.kt | myhbaba | 398,739,776 | false | null | package com.example.chuculture
import android.animation.Animator
import android.animation.TimeInterpolator
import android.animation.ValueAnimator
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.view.ViewGroup
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.ImageView
import androidx.viewpager2.widget.ViewPager2
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.MultiTransformation
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target
import com.example.chuculture.network.NetWorkClient
import com.google.gson.Gson
import jp.wasabeef.glide.transformations.BlurTransformation
object Utils {
fun ViewPager2.setCurrentItemLowSpeed(
item: Int,
duration: Long,
interpolator: TimeInterpolator = AccelerateDecelerateInterpolator(),
pagePxWidth: Int = width // 使用viewpager2.getWidth()获取
) {
val pxToDrag: Int = pagePxWidth * (item - currentItem)
val animator = ValueAnimator.ofInt(0, pxToDrag)
var previousValue = 0
animator.addUpdateListener { valueAnimator ->
val currentValue = valueAnimator.animatedValue as Int
val currentPxToDrag = (currentValue - previousValue).toFloat()
fakeDragBy(-currentPxToDrag)
previousValue = currentValue
}
animator.addListener(object : Animator.AnimatorListener {
override fun onAnimationStart(animation: Animator?) { beginFakeDrag() }
override fun onAnimationEnd(animation: Animator?) { endFakeDrag() }
override fun onAnimationCancel(animation: Animator?) { }
override fun onAnimationRepeat(animation: Animator?) { }
})
animator.interpolator = interpolator
animator.duration = duration
animator.start()
}
fun ImageView.loadBanner(url:String){
Glide.with(this.context)
.load(url)
.addListener(object: RequestListener<Drawable> {
override fun onLoadFailed(
e: GlideException?,
model: Any?,
target: Target<Drawable>?,
isFirstResource: Boolean
): Boolean {
return false
}
override fun onResourceReady(
resource: Drawable?,
model: Any?,
target: Target<Drawable>?,
dataSource: DataSource?,
isFirstResource: Boolean
): Boolean {
resource?.let {
val params: ViewGroup.LayoutParams = [email protected]
val imgWidth=resource.intrinsicWidth
val imgHeight=resource.intrinsicHeight
val [email protected]
val scale: Double = imgWidth/(viewWidth*1.0)
val viewHeight=(imgHeight/scale).toInt()
params.width=viewWidth
params.height=viewHeight
[email protected]=params
}
return false
}
})
.into(this)
}
fun ImageView.loadBanner(url:Int){
Glide.with(this.context)
.load(url)
.addListener(object: RequestListener<Drawable> {
override fun onLoadFailed(
e: GlideException?,
model: Any?,
target: Target<Drawable>?,
isFirstResource: Boolean
): Boolean {
return false
}
override fun onResourceReady(
resource: Drawable?,
model: Any?,
target: Target<Drawable>?,
dataSource: DataSource?,
isFirstResource: Boolean
): Boolean {
resource?.let {
val params: ViewGroup.LayoutParams = [email protected]
val imgWidth=resource.intrinsicWidth
val imgHeight=resource.intrinsicHeight
val [email protected]
val scale: Double = imgWidth/(viewWidth*1.0)
val viewHeight=(imgHeight/scale).toInt()
params.width=viewWidth
params.height=viewHeight
[email protected]=params
}
return false
}
})
.into(this)
}
fun ImageView.loadNormal(url:String){
Glide.with(this.context).load("${NetWorkClient.BASE_IMAGE_URL}$url").into(this)
}
fun ImageView.loadNormal(url:Int){
Glide.with(this.context).load(url).into(this)
}
fun getGson()= Gson()
fun ImageView.loadBlur(image:String){
val blur = MultiTransformation<Bitmap>(
BlurTransformation(25)
)
Glide.with(this.context)
.load("${NetWorkClient.BASE_IMAGE_URL}$image")
.apply(RequestOptions.bitmapTransform(blur))
.into(this)
}
fun ImageView.loadLocalBanner(image:String){
loadBanner("${NetWorkClient.BASE_IMAGE_URL}$image")
}
fun ImageView.load(url: String){
Glide.with(this.context).load(url).into(this)
}
} | 0 | Kotlin | 0 | 0 | 21f86d905e68d838a55e3d0ca2b5d94182475ace | 5,731 | ChuCulture | Apache License 2.0 |
src/test/kotlin/no/nav/helse/validering/OmsorgstilbudValideringTest.kt | navikt | 161,643,240 | false | null | package no.nav.helse.validering
import no.nav.helse.dusseldorf.ktor.core.Violation
import no.nav.helse.soknad.*
import java.time.Duration
import java.time.LocalDate
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class OmsorgstilbudValideringTest {
val gyldigOmsorgstilbud = Omsorgstilbud(
svarFortid = OmsorgstilbudSvarFortid.JA,
svarFremtid = OmsorgstilbudSvarFremtid.JA,
erLiktHverUke = true,
ukedager = PlanUkedager(
mandag = Duration.ofHours(3)
),
enkeltdager = null
)
@Test
fun `Gyldig omsorgstilbud gir ingen feil`() {
gyldigOmsorgstilbud.validate().assertIngenFeil()
}
@Test
fun `Skal gi feil dersom svarFortid=JA, svarFremtid=JA og både ukedager og enkeldager er null`() {
gyldigOmsorgstilbud.copy(
svarFortid = OmsorgstilbudSvarFortid.JA,
svarFremtid = OmsorgstilbudSvarFremtid.JA,
ukedager = null,
enkeltdager = null
).validate().assertFeilPå(
listOf(
"Ved svarFortid=JA kan ikke både enkeltdager og ukedager være null.",
"Ved svarFremtid=JA kan ikke både enkeltdager og ukedager være null.",
"Hvis erLiktHverUke er true må ukedager være satt."
)
)
}
@Test
fun `Skal gi feil dersom både ukedager og enkeldager er satt`() {
gyldigOmsorgstilbud.copy(
ukedager = PlanUkedager(
mandag = Duration.ofHours(3)
),
enkeltdager = listOf(Enkeltdag(LocalDate.now(), Duration.ofHours(3)))
).validate().assertFeilPå(
listOf(
"Kan ikke ha både enkeltdager og ukedager satt, må velge en av de.",
"Hvis erLiktHverUke er true må enkeldager være null."
)
)
}
@Test
fun `Skal gi feil dersom erLiktHverUke er true og ukedager er null`() {
gyldigOmsorgstilbud.copy(
svarFortid = OmsorgstilbudSvarFortid.JA,
svarFremtid = OmsorgstilbudSvarFremtid.NEI,
erLiktHverUke = true,
ukedager = null,
enkeltdager = listOf(Enkeltdag(LocalDate.now(), Duration.ofHours(3)))
).validate().assertFeilPå(
listOf(
"Hvis erLiktHverUke er true må ukedager være satt.",
"Hvis erLiktHverUke er true må enkeldager være null."
)
)
}
@Test
fun `Skal gi feil dersom erLiktHverUke er true og enkeldager er satt`() {
gyldigOmsorgstilbud.copy(
erLiktHverUke = true,
enkeltdager = listOf(Enkeltdag(LocalDate.now(), Duration.ofHours(3)))
).validate().assertFeilPå(
listOf(
"Hvis erLiktHverUke er true må enkeldager være null.",
"Kan ikke ha både enkeltdager og ukedager satt, må velge en av de."
)
)
}
@Test
fun `Skal gi feil dersom erLiktHverUke er false og ukedager er satt`() {
gyldigOmsorgstilbud.copy(
erLiktHverUke = false,
ukedager = PlanUkedager(mandag = Duration.ofHours(2))
).validate().assertFeilPå(
listOf(
"Hvis erLiktHverUke er false kan ikke ukedager være satt.",
"Hvis erLiktHverUke er false kan ikke enkeltdager være null."
)
)
}
@Test
fun `Skal gi feil dersom erLiktHverUke er false og enkeltdager er null`() {
gyldigOmsorgstilbud.copy(
erLiktHverUke = false,
enkeltdager = null
).validate().assertFeilPå(
listOf(
"Hvis erLiktHverUke er false kan ikke enkeltdager være null.",
"Hvis erLiktHverUke er false kan ikke ukedager være satt."
)
)
}
}
internal fun MutableSet<Violation>.assertIngenFeil() {
assertTrue(size == 0)
}
internal fun MutableSet<Violation>.assertFeilPå(reason: List<String> = emptyList()) {
println(this)
assertEquals(size, reason.size)
forEach {
assertTrue(reason.contains(it.reason))
}
} | 9 | Kotlin | 0 | 0 | e9cbaf2d5b4711335b51d2a30fd35118a5d1f585 | 4,150 | pleiepengesoknad-api | MIT License |
src/main/kotlin/com/github/mrbean355/admiralbulldog/mods/OldModMigration.kt | MrBean355 | 181,222,587 | false | null | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.mrbean355.admiralbulldog.mods
import com.github.mrbean355.admiralbulldog.persistence.ConfigPersistence
import org.slf4j.LoggerFactory
import java.io.File
object OldModMigration {
private val logger = LoggerFactory.getLogger(OldModMigration::class.java)
/**
* Try to delete old mod directories.
* It doesn't matter if it fails (e.g. Dota is running); they are unused anyway.
*/
fun run() {
val modDir = File(ConfigPersistence.getDotaPath(), "game")
val toDelete = listOf(
"base-mod",
"custom-spell-icons",
"custom-spell-sounds",
"elegiggle-deny",
"fat-mango",
"manly-bullwhip",
"mask-of-maldness",
"old-hero-icons",
"twitch-emotes",
"yep-ping",
)
try {
toDelete.forEach {
File(modDir, it).deleteRecursively()
}
} catch (t: Throwable) {
logger.error("Error deleting old mod directories", t)
}
}
} | 7 | null | 5 | 31 | 24f2f5de5c8d8397c9aec94795f6da3bfaac3611 | 1,659 | admiralbulldog-sounds | Apache License 2.0 |
krate-moshi-core/src/main/kotlin/hu/autsoft/krate/moshi/ValidatedFunctions.kt | AutSoft | 143,710,217 | false | null | @file:[Suppress("unused") OptIn(InternalKrateApi::class)]
package hu.autsoft.krate.moshi
import hu.autsoft.krate.Krate
import hu.autsoft.krate.internal.InternalKrateApi
import hu.autsoft.krate.moshi.default.MoshiDelegateWithDefault
import hu.autsoft.krate.moshi.optional.MoshiDelegate
import hu.autsoft.krate.validation.ValidatedPreferenceDelegate
import java.lang.reflect.Type
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.javaType
import kotlin.reflect.typeOf
/**
* Creates a validated, optional preference of type T with the given [key] in this [Krate] instance.
* This value will be serialized using Moshi.
*/
@OptIn(ExperimentalStdlibApi::class)
@Deprecated(
message = "Use .validate {} on a moshiPref instead",
level = DeprecationLevel.WARNING,
replaceWith = ReplaceWith(
"this.moshiPref<T>(key).validate(isValid)",
imports = arrayOf("hu.autsoft.krate.validation.validate"),
),
)
public inline fun <reified T : Any> Krate.moshiPref(
key: String,
noinline isValid: (newValue: T?) -> Boolean,
): ReadWriteProperty<Krate, T?> {
return moshiPrefImpl(key, typeOf<T>().javaType, isValid)
}
@PublishedApi
internal fun <T : Any> Krate.moshiPrefImpl(
key: String,
type: Type,
isValid: (newValue: T?) -> Boolean,
): ReadWriteProperty<Krate, T?> {
return ValidatedPreferenceDelegate(MoshiDelegate(key, type), isValid)
}
/**
* Creates a validated, non-optional preference of type T with the given [key] and [defaultValue]
* in this [Krate] instance.
* This value will be serialized using Moshi.
*/
@OptIn(ExperimentalStdlibApi::class)
@Deprecated(
message = "Use .validate {} on a moshiPref instead",
level = DeprecationLevel.WARNING,
replaceWith = ReplaceWith(
"this.moshiPref(key, defaultValue).validate(isValid)",
imports = arrayOf("hu.autsoft.krate.validation.validate"),
),
)
public inline fun <reified T : Any> Krate.moshiPref(
key: String,
defaultValue: T,
noinline isValid: (newValue: T) -> Boolean,
): ReadWriteProperty<Krate, T> {
return moshiPrefImpl(key, defaultValue, typeOf<T>().javaType, isValid)
}
@PublishedApi
internal fun <T : Any> Krate.moshiPrefImpl(
key: String,
defaultValue: T,
type: Type,
isValid: (newValue: T) -> Boolean,
): ReadWriteProperty<Krate, T> {
return ValidatedPreferenceDelegate(MoshiDelegateWithDefault(key, defaultValue, type), isValid)
}
| 3 | null | 10 | 257 | f36966d653e771dce32e2587f84b757dfe74f716 | 2,545 | Krate | Apache License 2.0 |
app/src/main/java/io/github/fate_grand_automata/ui/onboarding/OnboardingScreen.kt | Fate-Grand-Automata | 245,391,245 | false | null | package io.github.fate_grand_automata.ui.onboarding
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.spring
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.KeyboardArrowLeft
import androidx.compose.material.icons.outlined.KeyboardArrowRight
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.launch
@Composable
fun OnboardingScreen(
vm: OnboardingViewModel = viewModel(),
navigateToHome: () -> Unit
) {
OnboardingContent(
vm,
navigateToHome
)
}
@Composable
fun OnboardingContent(
vm: OnboardingViewModel = viewModel(),
navigateToHome: () -> Unit
) {
val pages = remember {
listOf(
WelcomeScreen(vm),
PickDirectory(vm),
DisableBatteryOptimization(vm),
YoutubeVideo(vm)
).filter { !it.shouldSkip() }
}
val scope = rememberCoroutineScope()
val pageState = rememberPagerState()
var nextEnabled by remember { mutableStateOf(true) }
Column(modifier = Modifier.fillMaxSize()) {
TopSection(
onBackClick = {
if (pageState.currentPage + 1 > 1) scope.launch {
pageState.scrollToPage(pageState.currentPage - 1)
nextEnabled = true
}
}
)
HorizontalPager(
pageCount = pages.size,
state = pageState,
modifier = Modifier
.fillMaxWidth()
.weight(1f),
userScrollEnabled = false
) { page ->
OnBoardingPage {
pages[page].UI {
nextEnabled = true
}
}
}
BottomSection(size = pages.size, index = pageState.currentPage, enabled = nextEnabled) {
if (pageState.currentPage + 1 < pages.size) scope.launch {
pageState.scrollToPage(pageState.currentPage + 1)
// enable next button if the new screen is optional or if the requirements were fulfilled
nextEnabled = pages[pageState.currentPage]
.let { it.canSkip || it.shouldSkip() }
} else {
vm.prefs.completedOnboarding()
navigateToHome()
}
}
}
}
@Composable
fun TopSection(onBackClick: () -> Unit = {}) {
Box(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp)
) {
// Back button
IconButton(
onClick = onBackClick,
modifier = Modifier.align(Alignment.CenterStart)
) {
Icon(imageVector = Icons.Outlined.KeyboardArrowLeft, contentDescription = null)
}
}
}
@Composable
fun BottomSection(size: Int, index: Int, enabled: Boolean, onButtonClick: () -> Unit = {}) {
Box(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp)
) {
// Indicators
Indicators(size, index)
Button(
onClick = onButtonClick,
enabled = enabled,
modifier = Modifier
.align(Alignment.CenterEnd)
.clip(RoundedCornerShape(15.dp, 15.dp, 15.dp, 15.dp))
) {
Icon(
Icons.Outlined.KeyboardArrowRight,
tint = Color.White,
contentDescription = "Localized description"
)
}
}
}
@Composable
fun BoxScope.Indicators(size: Int, index: Int) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.align(Alignment.CenterStart)
) {
repeat(size) {
Indicator(isSelected = it == index)
}
}
}
@Composable
fun Indicator(isSelected: Boolean) {
val width = animateDpAsState(
targetValue = if (isSelected) 25.dp else 10.dp,
animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy)
)
Box(
modifier = Modifier
.height(10.dp)
.width(width.value)
.clip(CircleShape)
.background(
color = if (isSelected) MaterialTheme.colorScheme.primary else Color(0XFFF8E2E7)
)
) {
}
}
@Composable
fun OnBoardingPage(content: @Composable () -> Unit) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier
.fillMaxSize()
.padding(start = 20.dp, end = 20.dp)
) {
content()
}
} | 175 | null | 272 | 993 | eb630b8efcdb56782f796de2e17b36fdf9e19f3b | 6,143 | FGA | MIT License |
handshake/src/main/kotlin/com/guet/flexbox/handshake/HostAddressFinder.kt | jiankehtt | 240,469,855 | false | {"Java Properties": 4, "Gradle": 11, "Shell": 2, "Markdown": 2, "Batchfile": 2, "Text": 1, "Ignore List": 10, "Proguard": 5, "Java": 141, "Kotlin": 170, "XML": 47, "JSON": 17, "INI": 2, "JavaScript": 9, "HTML": 2, "CSS": 3} | package com.guet.flexbox.handshake
import java.net.Inet4Address
import java.net.NetworkInterface
object HostAddressFinder {
fun findHostAddress(): String? {
try {
Inet4Address.getLocalHost()
return NetworkInterface.getNetworkInterfaces()
.asSequence()
.map {
it.inetAddresses.toList()
}.flatten()
.firstOrNull { ip ->
ip is Inet4Address && !ip.isLoopbackAddress
&& ip.hostAddress.indexOf(":") == -1
}?.hostAddress
} catch (e: Exception) {
e.printStackTrace()
}
return null
}
} | 1 | null | 1 | 1 | 79d4fe4191ae36689f58ce3c5b5d455d3e8b8bc8 | 734 | Gbox | Apache License 2.0 |
app/src/main/java/com/takusemba/jethub/database/entity/RepositoryEntity.kt | harveyhaha | 168,356,217 | true | {"Kotlin": 125216} | package com.takusemba.jethub.database.entity
import androidx.room.Entity
import androidx.room.PrimaryKey
/**
* Repository Entity
*/
@Entity(tableName = "repository")
class RepositoryEntity(
@PrimaryKey
var id: Int,
var name: String,
var owner: String
) | 0 | Kotlin | 0 | 0 | 72a28bb77032135608f3a9508663815e7bbecf8f | 264 | JetHub | Apache License 2.0 |
src/test/kotlin/com/zup/edu/exceptions/GlobalExceptionHandlerTest.kt | FelipeB4C | 401,862,370 | true | {"Kotlin": 18994} | package com.zup.edu.exceptions
import io.grpc.Status
import io.grpc.StatusRuntimeException
import io.micronaut.http.HttpRequest
import io.micronaut.http.HttpStatus
import io.micronaut.http.hateoas.JsonError
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
internal class GlobalExceptionHandlerTest {
val requestGenerica = HttpRequest.GET<Any>("/")
@Test
internal fun `deve retornar 404 quando statusException for not found`(){
val mensagem = "Não encontrado"
val notFoundException = StatusRuntimeException(Status.NOT_FOUND.withDescription(mensagem))
val resposta = GlobalExceptionHandler().handle(requestGenerica, notFoundException)
assertEquals(HttpStatus.NOT_FOUND, resposta.status)
assertNotNull(resposta.body())
assertEquals(mensagem, (resposta.body() as JsonError).message)
}
@Test
internal fun `deve retornar 422 quando statusException for already existis`(){
val mensagem = "Chave pix já existente"
val alreadyExistsException = StatusRuntimeException(Status.ALREADY_EXISTS.withDescription(mensagem))
val resposta = GlobalExceptionHandler().handle(requestGenerica, alreadyExistsException)
assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, resposta.status)
assertNotNull(resposta.body())
assertEquals(mensagem, (resposta.body() as JsonError).message)
}
@Test
internal fun `deve retornar 400 quando statusException for Invalid Argument`(){
val mensagem = "Dados da requisição estão inválidos"
val invalidArgumentException = StatusRuntimeException(Status.INVALID_ARGUMENT.withDescription(mensagem))
val resposta = GlobalExceptionHandler().handle(requestGenerica, invalidArgumentException)
assertEquals(HttpStatus.BAD_REQUEST, resposta.status)
assertNotNull(resposta.body())
assertEquals(mensagem, (resposta.body() as JsonError).message)
}
@Test
internal fun `deve retornar 500 quando statusException for erro inesperado`(){
val mensagem = "Erro inesperado"
val erroInesperado = StatusRuntimeException(Status.UNKNOWN.withDescription(mensagem))
val resposta = GlobalExceptionHandler().handle(requestGenerica, erroInesperado)
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, resposta.status)
assertNotNull(resposta.body())
assertEquals("Não foi possível completar a requisição devido ao erro: ${mensagem} (UNKNOWN)", (resposta.body() as JsonError).message)
}
} | 0 | Kotlin | 0 | 0 | 9e987f047bbd073018fc88bedd9dcdbbe19f446b | 2,545 | orange-talents-06-template-pix-keymanager-rest | Apache License 2.0 |
app/src/main/kotlin/cz/lsrom/webviewtest/qr/ui/QrScannerActivity.kt | lsrom | 126,248,585 | false | null | package ak.singh.webviewtest.qr.ui
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import com.google.zxing.Result
import ak.singh.webviewtest.R
import ak.singh.webviewtest.app.MainActivity
import kotlinx.android.synthetic.main.qr_scanner_view.*
import me.dm7.barcodescanner.zxing.ZXingScannerView
import timber.log.Timber
const val URL_EXTRA = "url"
class QrScannerActivity : AppCompatActivity(),
ZXingScannerView.ResultHandler {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.qr_scanner_view)
if (!permissionGranted()) {
requestPermission()
}
request_permission.setOnClickListener {
requestPermission()
}
}
private fun permissionGranted(): Boolean {
return ContextCompat.checkSelfPermission(
this,
Manifest.permission.CAMERA
) == PackageManager.PERMISSION_GRANTED
}
private fun requestPermission() {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.CAMERA),
666
)
}
public override fun onPause() {
super.onPause()
if (permissionGranted()) {
qr_scanner_view.stopCamera()
}
}
public override fun onResume() {
super.onResume()
if (permissionGranted()) {
qr_scanner_view.setResultHandler(this)
qr_scanner_view.startCamera()
}
}
override fun handleResult(rawResult: Result) {
startActivity(activityIntent(rawResult.text))
}
private fun activityIntent(url: String): Intent{
return Intent(baseContext, MainActivity::class.java).apply {
putExtra(URL_EXTRA, url)
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
Timber.d("request permission result")
if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
request_permission.isVisible = true
qr_scanner_view.isVisible = false
} else {
request_permission.isVisible = false
qr_scanner_view.isVisible = true
qr_scanner_view.startCamera()
}
}
}
| 0 | null | 4 | 19 | 03ef2922e1b80edd303da9add1498c3eb7db67f7 | 2,649 | webview-tester | MIT License |
composeApp/src/commonMain/kotlin/com/mmartosdev/photofx/ui/playground/PlaygroundViewModel.kt | manuel-martos | 815,172,471 | false | {"Kotlin": 59735, "HTML": 708, "Swift": 522} | package com.mmartosdev.photofx.ui.playground
import androidx.lifecycle.ViewModel
import com.mmartosdev.photofx.ui.EffectConfig
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
class PlaygroundViewModel(
effect: EffectConfig,
) : ViewModel() {
private val _effectConfig: MutableStateFlow<EffectConfig> = MutableStateFlow(effect)
val effectConfig: StateFlow<EffectConfig> = _effectConfig.asStateFlow()
fun onEffectConfigChanged(config: EffectConfig) {
_effectConfig.update { config }
}
}
| 0 | Kotlin | 1 | 2 | 450c1071c085f13676d5c7d5796e29c3a1c92f4a | 639 | Photo-FX | MIT License |
app/src/main/java/com/b_lam/resplash/ui/photo/detail/PhotoDetailViewModel.kt | vipulasri | 366,834,420 | true | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 177, "XML": 159, "Java": 1, "JSON": 3} | package com.b_lam.resplash.ui.photo.detail
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.liveData
import androidx.lifecycle.viewModelScope
import com.b_lam.resplash.data.collection.model.Collection
import com.b_lam.resplash.data.photo.model.Photo
import com.b_lam.resplash.di.Properties
import com.b_lam.resplash.domain.collection.CollectionRepository
import com.b_lam.resplash.domain.login.LoginRepository
import com.b_lam.resplash.domain.photo.PhotoRepository
import com.b_lam.resplash.ui.base.BaseViewModel
import com.b_lam.resplash.util.Result
import com.b_lam.resplash.util.livedata.lazyMap
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.*
class PhotoDetailViewModel(
private val photoRepository: PhotoRepository,
private val collectionRepository: CollectionRepository,
private val loginRepository: LoginRepository
) : BaseViewModel() {
private val _photoDetailsLiveData: Map<String, LiveData<Photo>> = lazyMap {
val liveData = MutableLiveData<Photo>()
viewModelScope.launch {
val result = photoRepository.getPhotoDetails(it)
when (result) {
is Result.Success -> {
liveData.postValue(result.value)
_currentUserCollectionIds.postValue(
result.value.current_user_collections?.map { it.id }?.toMutableList())
}
}
}
return@lazyMap liveData
}
private val _currentUserCollectionIds = MutableLiveData<MutableList<Int>?>()
val currentUserCollectionIds: LiveData<MutableList<Int>?> = _currentUserCollectionIds
private val _userCollections = MutableLiveData<MutableList<Collection>?>()
val userCollections: LiveData<MutableList<Collection>?> = _userCollections
var downloadId: Long? = null
var downloadUUID: UUID? = null
fun photoDetailsLiveData(id: String): LiveData<Photo> = _photoDetailsLiveData.getValue(id)
fun likePhoto(id: String) = viewModelScope.launch { photoRepository.likePhoto(id) }
fun unlikePhoto(id: String) = viewModelScope.launch { photoRepository.unlikePhoto(id) }
fun isUserAuthorized() = loginRepository.isAuthorized()
fun addPhotoToCollection(collectionId: Int, photoId: String, position: Int) =
liveData(viewModelScope.coroutineContext) {
emit(Result.Loading)
val result = collectionRepository.addPhotoToCollection(collectionId, photoId)
if (result is Result.Success) {
val newIdList = _currentUserCollectionIds.value ?: mutableListOf()
newIdList.add(collectionId)
_currentUserCollectionIds.postValue(newIdList)
val newCollectionsList = _userCollections.value
result.value.collection?.let { newCollectionsList?.set(position, it) }
_userCollections.postValue(newCollectionsList)
}
emit(result)
}
fun removePhotoFromCollection(collectionId: Int, photoId: String, position: Int) =
liveData(viewModelScope.coroutineContext) {
emit(Result.Loading)
val result = collectionRepository.removePhotoFromCollection(collectionId, photoId)
if (result is Result.Success) {
val newList = _currentUserCollectionIds.value ?: mutableListOf()
newList.remove(collectionId)
_currentUserCollectionIds.postValue(newList)
val newCollectionsList = _userCollections.value
result.value.collection?.let { newCollectionsList?.set(position, it) }
_userCollections.postValue(newCollectionsList)
}
emit(result)
}
private var page = 1
var isLoading = false
var onLastPage = false
fun refresh() {
page = 1
isLoading = false
onLastPage = false
loadMore()
}
fun loadMore() {
viewModelScope.launch(Dispatchers.Default) {
isLoading = true
val username = loginRepository.getUsername() ?: return@launch
val result = collectionRepository.getUserCollections(username, page)
if (result is Result.Success) {
val newList = _userCollections.value ?: mutableListOf()
newList.addAll(result.value)
_userCollections.postValue(newList)
onLastPage = result.value.isEmpty() || result.value.size < Properties.DEFAULT_PAGE_SIZE
page++
}
isLoading = false
}
}
fun createCollection(
title: String,
description: String?,
private: Boolean?,
photoId: String
) = liveData {
emit(Result.Loading)
val createResult = collectionRepository.createCollection(title, description, private)
if (createResult is Result.Success) {
var newCollection = createResult.value
val addResult = collectionRepository.addPhotoToCollection(newCollection.id, photoId)
if (addResult is Result.Success) {
val newIdList = _currentUserCollectionIds.value ?: mutableListOf()
newIdList.add(newCollection.id)
_currentUserCollectionIds.postValue(newIdList)
addResult.value.collection?.let { newCollection = it }
}
val newList = _userCollections.value ?: mutableListOf()
newList.add(0, newCollection)
_userCollections.postValue(newList)
}
emit(createResult)
}
}
| 0 | null | 0 | 0 | 86a5a79465c40c000f7522f8e9b0f5af775951b1 | 5,647 | Resplash | The Unlicense |
src/main/kotlin/no/nav/syfo/infrastructure/database/repository/AktivitetskravVurderingQueries.kt | navikt | 554,767,872 | false | {"Kotlin": 508056, "Dockerfile": 226} | package no.nav.syfo.infrastructure.database.repository
import no.nav.syfo.domain.Aktivitetskrav
import no.nav.syfo.domain.AktivitetskravVurdering
import no.nav.syfo.infrastructure.database.NoElementInsertedException
import no.nav.syfo.infrastructure.database.toList
import no.nav.syfo.util.nowUTC
import java.sql.*
import java.sql.Date
const val queryCreateAktivitetskravVurdering =
"""
INSERT INTO AKTIVITETSKRAV_VURDERING (
id,
uuid,
aktivitetskrav_id,
created_at,
created_by,
status,
beskrivelse,
arsaker,
frist
) values (DEFAULT, ?, ?, ?, ?, ?, ?, ?, ?)
RETURNING *
"""
fun Connection.createAktivitetskravVurdering(
aktivitetskravId: Int,
aktivitetskravVurdering: AktivitetskravVurdering,
): PAktivitetskravVurdering {
val aktivitetskravVurderinger = this.prepareStatement(queryCreateAktivitetskravVurdering).use {
it.setString(1, aktivitetskravVurdering.uuid.toString())
it.setInt(2, aktivitetskravId)
it.setObject(3, aktivitetskravVurdering.createdAt)
it.setString(4, aktivitetskravVurdering.createdBy)
it.setString(5, aktivitetskravVurdering.status.name)
it.setString(6, aktivitetskravVurdering.beskrivelse)
it.setString(7, aktivitetskravVurdering.arsaker.joinToString(",") { arsak -> arsak.value })
it.setDate(8, aktivitetskravVurdering.frist?.let { frist -> Date.valueOf(frist) })
it.executeQuery().toList { toPAktivitetskravVurdering() }
}
if (aktivitetskravVurderinger.size != 1) {
throw NoElementInsertedException("Creating AKTIVITETSKRAV_VURDERING failed, no rows affected.")
}
return aktivitetskravVurderinger.first()
}
const val queryUpdateAktivitetskrav =
"""
UPDATE AKTIVITETSKRAV SET status=?, stoppunkt_at=?, updated_at=? WHERE uuid = ? RETURNING id
"""
fun Connection.updateAktivitetskrav(
aktivitetskrav: Aktivitetskrav,
): Int {
val aktivitetskravUuid = aktivitetskrav.uuid
val updatedIds = this.prepareStatement(queryUpdateAktivitetskrav).use { preparedStatement ->
preparedStatement.setString(1, aktivitetskrav.status.name)
preparedStatement.setDate(2, Date.valueOf(aktivitetskrav.stoppunktAt))
preparedStatement.setObject(3, nowUTC())
preparedStatement.setString(4, aktivitetskravUuid.toString())
preparedStatement.executeQuery().toList { getInt("id") }
}
if (updatedIds.size != 1) {
throw SQLException("Failed to update aktivitetskrav with uuid $aktivitetskravUuid - Unexpected update count: ${updatedIds.size}")
}
return updatedIds.first()
}
| 3 | Kotlin | 1 | 0 | 55c4a23f24c6776d947cafc6788d23f919c84de5 | 2,670 | isaktivitetskrav | MIT License |
app/src/main/java/com/mux/video/vod/demo/upload/viewmodel/CreateUploadViewModel.kt | muxinc | 591,110,834 | false | {"Kotlin": 185627} | package com.mux.video.vod.demo.upload.viewmodel
import android.app.Application
import android.database.Cursor
import android.graphics.Bitmap
import android.media.MediaMetadataRetriever
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.mux.video.upload.api.MuxUpload
import com.mux.video.vod.demo.backend.ImaginaryBackend
import com.mux.video.vod.demo.upload.model.MediaStoreVideo
import com.mux.video.vod.demo.upload.model.extractThumbnail
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.joda.time.DateTime
import org.joda.time.DateTimeZone
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
class CreateUploadViewModel(private val app: Application) : AndroidViewModel(app) {
val videoState: LiveData<State> by this::videoStateLiveData
private val videoStateLiveData =
MutableLiveData(State(prepareState = PrepareState.NONE, thumbnail = null))
private var prepareJob: Job? = null
fun prepareForUpload(contentUri: Uri) {
videoStateLiveData.value = State(PrepareState.PREPARING, null)
prepareJob = viewModelScope.launch {
try {
val uploadUri = ImaginaryBackend.createUploadUrl().let { Uri.parse(it) }
val videoFile = copyIntoTempFile(contentUri)
val thumbnailBitmap = extractThumbnail(videoFile) // val thumbnailBitmap = ...
videoStateLiveData.postValue(
State(
PrepareState.READY,
videoFile,
thumbnailBitmap,
uploadUri
)
)
} catch (e: Exception) {
Log.e("CreateUploadViewModel", "Error preparing upload", e)
videoStateLiveData.value = State(PrepareState.ERROR, null)
}
} // prepareJob = viewModelScope.launch { ...
}
fun beginUpload() {
if (((videoState.value?.prepareState) ?: PrepareState.NONE) == PrepareState.READY) {
// If the state is READY, these values are expected to be filled
MuxUpload.Builder(
videoState.value!!.uploadUri!!,
videoState.value!!.chosenFile!!
).build()
// Force restart when creating brand new uploads (because we're making new Direct uploads)
.start(forceRestart = true)
}
}
/**
* In order to upload a file from the device's media store, the file must be copied into the app's
* temp directory. (Technically we could stream it from the source, but this prevents the other
* app from modifying the file if we pause the upload for a long time or whatever)
* TODO<em> Is this something that should go in the SDK? This is a common workflow
*/
@Throws
private suspend fun copyIntoTempFile(contentUri: Uri): File {
// Create a unique name for our temp file. There are a ton of ways to do this, but this one is
// pretty easy to implement and protects from unsafe characters
val basename = android.util.Base64.encode(
contentUri.pathSegments.joinToString(separator = "-").encodeToByteArray(),
0
).decodeToString()
val cacheDir = File(app.cacheDir, "mux-upload")
cacheDir.mkdirs()
val destFile = File(cacheDir, basename)
withContext(Dispatchers.IO) {
val output = FileOutputStream(destFile).channel
val fileDescriptor = app.contentResolver.openFileDescriptor(contentUri, "r")
val input = FileInputStream(fileDescriptor!!.fileDescriptor).channel
try {
val fileSize = input.size()
var read = 0L
do {
read += input.transferTo(read, 10 * 1024, output)
} while (read < fileSize)
} finally {
input.close()
fileDescriptor.close()
output.close()
}
}
return destFile
}
private suspend fun fetchVideos(): List<MediaStoreVideo> {
fun ownerPackageName(cursor: Cursor): String {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
cursor.getString(MediaStore.Video.VideoColumns.OWNER_PACKAGE_NAME) ?: "??"
} else {
"??"
}
}
fun columns(): Array<String> {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
arrayOf(
MediaStore.Video.VideoColumns.DISPLAY_NAME,
MediaStore.Video.VideoColumns.DATA,
MediaStore.Video.VideoColumns.OWNER_PACKAGE_NAME,
MediaStore.Video.VideoColumns.DATE_ADDED,
MediaStore.Video.VideoColumns.DATE_TAKEN
)
} else {
arrayOf(
MediaStore.Video.VideoColumns.DISPLAY_NAME,
MediaStore.Video.VideoColumns.DATA,
MediaStore.Video.VideoColumns.DATE_ADDED,
MediaStore.Video.VideoColumns.DATE_TAKEN
)
}
}
withContext(Dispatchers.IO) {
app.contentResolver.query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
columns(),
null,
null,
null,
)!!
}.use { cursor ->
if (cursor.count <= 0) {
Log.w(javaClass.simpleName, "No videos found")
return listOf()
}
val videos = mutableListOf<MediaStoreVideo>()
cursor.moveToFirst()
do {
val title = cursor.getString(MediaStore.Video.VideoColumns.DISPLAY_NAME) ?: "[no name]"
val file = cursor.getString(MediaStore.Video.VideoColumns.DATA) ?: continue
val fromApp = ownerPackageName(cursor)
val dateMillis = cursor.getLong(MediaStore.Video.VideoColumns.DATE_ADDED)
val dateTime =
DateTime.now().withMillis(dateMillis * 1000)
.withZoneRetainFields(DateTimeZone.getDefault())
val vid = MediaStoreVideo(
title = title,
file = File(file),
fromApp = fromApp,
date = dateTime.toString()
)
videos += vid
} while (cursor.moveToNext())
return videos
}
}
private fun Cursor.getLong(columnName: String): Long {
val colIdx = getColumnIndexOrThrow(columnName)
return getLong(colIdx)
}
private fun Cursor.getString(columnName: String): String? {
val colIdx = getColumnIndexOrThrow(columnName)
return getString(colIdx)
}
enum class PrepareState { NONE, PREPARING, ERROR, READY }
data class State(
val prepareState: PrepareState,
val chosenFile: File? = null,
val thumbnail: Bitmap? = null,
val uploadUri: Uri? = null
)
}
| 5 | Kotlin | 1 | 5 | 1fb2d37aa79d9f400e696a4ec47025c0a5de30b0 | 6,556 | android-upload-sdk | Apache License 2.0 |
app/src/play/java/com/duckduckgo/app/di/PlayStoreReferralModule.kt | duckduckgo | 78,869,127 | false | null | /*
* Copyright (c) 2019 DuckDuckGo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.duckduckgo.app.di
import com.duckduckgo.app.referral.*
import com.duckduckgo.app.statistics.AtbInitializerListener
import com.duckduckgo.di.scopes.AppScope
import com.duckduckgo.referral.PlayStoreAppReferrerStateListener
import com.squareup.anvil.annotations.ContributesTo
import dagger.Module
import dagger.Provides
import dagger.multibindings.IntoSet
import dagger.SingleInstanceIn
@Module
@ContributesTo(
scope = AppScope::class,
replaces = [StoreReferralModule::class]
)
class PlayStoreReferralModule {
@Provides
@SingleInstanceIn(AppScope::class)
fun appInstallationReferrerStateListener(
playStoreAppReferrerStateListener: PlayStoreAppReferrerStateListener
): AppInstallationReferrerStateListener = playStoreAppReferrerStateListener
@Provides
@IntoSet
fun providedReferrerAtbInitializerListener(
playStoreAppReferrerStateListener: PlayStoreAppReferrerStateListener
): AtbInitializerListener = playStoreAppReferrerStateListener
}
| 67 | null | 901 | 3,823 | 6415f0f087a11a51c0a0f15faad5cce9c790417c | 1,606 | Android | Apache License 2.0 |
capy/src/test/java/com/jocmp/capy/fixtures/FeedFixture.kt | jocmp | 610,083,236 | false | {"Kotlin": 446273, "Ruby": 1214, "Makefile": 780} | package com.jocmp.capy.fixtures
import com.jocmp.capy.Feed
import com.jocmp.capy.db.Database
import com.jocmp.capy.persistence.FeedRecords
import kotlinx.coroutines.runBlocking
import java.security.SecureRandom
class FeedFixture(database: Database) {
private val records = FeedRecords(database)
fun create(
feedID: String = randomID(),
feedURL: String = "https://example.com",
title: String = "My Feed",
): Feed = runBlocking {
records.upsert(
feedID = feedID,
subscriptionID = randomID(),
title = title,
feedURL = feedURL,
siteURL = feedURL,
faviconURL = null,
)!!
}
private fun randomID() = SecureRandom.getInstanceStrong().nextInt().toString()
}
| 9 | Kotlin | 0 | 38 | 7d4bc3ed6807cb4d67d3e29b75d4d600bd8bad60 | 785 | capyreader | MIT License |
src/org/jetbrains/r/run/visualize/RDataFrameViewerImpl.kt | JetBrains | 214,212,060 | false | {"Kotlin": 2849970, "Java": 814635, "R": 36890, "CSS": 23692, "Lex": 14307, "HTML": 10063, "Rez": 245, "Rebol": 64} | /*
* Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package org.jetbrains.r.run.visualize
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import org.jetbrains.concurrency.*
import org.jetbrains.r.RBundle
import org.jetbrains.r.packages.RequiredPackage
import org.jetbrains.r.packages.RequiredPackageException
import org.jetbrains.r.packages.RequiredPackageInstaller
import org.jetbrains.r.rinterop.*
import org.jetbrains.r.rinterop.DataFrameInfoResponse.ColumnType.*
import org.jetbrains.r.util.tryRegisterDisposable
import javax.swing.RowSorter
import kotlin.math.min
import kotlin.reflect.KClass
class RDataFrameViewerImpl(private val ref: RPersistentRef) : RDataFrameViewer {
private val rInterop: RInterop = ref.rInterop
override val nColumns: Int get() = columns.size
override var nRows: Int = 0
override val project get() = rInterop.project
private lateinit var columns: Array<ColumnInfo>
private lateinit var chunks: Array<Array<Array<Any?>>?>
private lateinit var promises: Array<Promise<Unit>?>
private var disposableParent: Disposable? = null
private var virtualFile: RTableVirtualFile? = null
override var canRefresh: Boolean = false
private data class ColumnInfo(val name: String, val type: KClass<*>, val sortable: Boolean = true,
val isRowNames: Boolean = false,
val parseValue: (DataFrameGetDataResponse.Value) -> Any?)
private var currentProxyDisposable: Disposable? = null
init {
Disposer.register(this, ref)
val project = rInterop.project
ensureDplyrInstalled(project)
initInfo(rInterop.dataFrameGetInfo(ref).getWithCheckCanceled())
}
private fun initInfo(dataFrameInfo: DataFrameInfoResponse) {
nRows = dataFrameInfo.nRows
columns = dataFrameInfo.columnsList.map { col ->
when (col.type) {
INTEGER -> ColumnInfo(col.name, Int::class, col.sortable, col.isRowNames) { if (it.hasNa()) null else it.intValue }
DOUBLE -> ColumnInfo(col.name, Double::class, col.sortable, col.isRowNames) { if (it.hasNa()) null else it.doubleValue }
BOOLEAN -> ColumnInfo(col.name, Boolean::class, col.sortable, col.isRowNames) { if (it.hasNa()) null else it.booleanValue }
else -> ColumnInfo(col.name, String::class, col.sortable, col.isRowNames) { if (it.hasNa()) null else it.stringValue }
}
}.toTypedArray()
chunks = Array((nRows + CHUNK_SIZE - 1) / CHUNK_SIZE) { null }
promises = Array(chunks.size) { null }
canRefresh = dataFrameInfo.canRefresh
}
override fun getColumnName(index: Int) = columns[index].name
override fun getColumnType(index: Int): KClass<*> {
return columns[index].type
}
override fun isColumnSortable(index: Int) = columns[index].sortable
override fun isRowNames(index: Int) = columns[index].isRowNames
override fun getValueAt(row: Int, col: Int): Any? {
ensureLoaded(row, col).blockingGet(Int.MAX_VALUE)
val chunkIndex = row / CHUNK_SIZE
return chunks.getOrNull(chunkIndex)?.getOrNull(col)?.getOrNull(row % CHUNK_SIZE)
}
override fun ensureLoaded(row: Int, col: Int, onLoadCallback: (() -> Unit)?): Promise<Unit> {
val chunkIndex = row / CHUNK_SIZE
if (chunks[chunkIndex] != null) return resolvedPromise()
promises[chunkIndex]?.let {
when (it.state) {
Promise.State.PENDING -> return it
Promise.State.SUCCEEDED -> return resolvedPromise()
Promise.State.REJECTED -> Unit
}
}
if (!rInterop.isAlive) {
return rejectedPromise("RInterop is not alive")
}
val start = chunkIndex * CHUNK_SIZE
val end = min((chunkIndex + 1) * CHUNK_SIZE, nRows)
val promise: Promise<Unit> = rInterop.dataFrameGetData(ref, start, end)
.also { tryRegisterDisposable(Disposable { it.cancel() }) }
.then { response ->
chunks[chunkIndex] = Array(nColumns) { col ->
Array(end - start) { row ->
columns[col].parseValue(response.getColumns(col).getValues(row))
}
}
onLoadCallback?.invoke()
}
promises[chunkIndex] = promise
return promise
}
override fun sortBy(sortKeys: List<RowSorter.SortKey>): RDataFrameViewer {
try {
return RDataFrameViewerImpl(rInterop.dataFrameSort(ref, sortKeys)).also { newDataFrame ->
disposableParent?.let { newDataFrame.registerDisposable(it, virtualFile) }
}
} catch (e: RInteropTerminated) {
throw RDataFrameException(RBundle.message("rinterop.terminated"))
}
}
override fun filter(f: DataFrameFilterRequest.Filter): RDataFrameViewer {
try {
return RDataFrameViewerImpl(rInterop.dataFrameFilter(ref, f)).also { newDataFrame ->
disposableParent?.let { newDataFrame.registerDisposable(it, virtualFile) }
}
} catch (e: RInteropTerminated) {
throw RDataFrameException(RBundle.message("rinterop.terminated"))
}
}
override fun refresh(): Promise<Boolean> {
if (!canRefresh) return resolvedPromise(false)
return rInterop.dataFrameRefresh(ref).thenAsync {
if (!it) return@thenAsync resolvedPromise(false)
rInterop.dataFrameGetInfo(ref).thenAsync { info ->
AsyncPromise<Boolean>().also { promise ->
invokeLater {
promise.compute {
initInfo(info)
true
}
}
}
}
}
}
override fun registerDisposable(parent: Disposable, virtualFile: RTableVirtualFile?) {
disposableParent = parent
this.virtualFile = virtualFile
currentProxyDisposable = object : Disposable {
override fun dispose() {
if (this == currentProxyDisposable &&
virtualFile?.getUserData(FileEditorManagerImpl.CLOSING_TO_REOPEN) != java.lang.Boolean.TRUE) {
Disposer.dispose(this)
}
}
}.also {
Disposer.register(parent, it)
}
}
companion object {
private const val CHUNK_SIZE = 256
fun ensureDplyrInstalled(project: Project) {
val requiredPackages = listOf(RequiredPackage("dplyr"))
if (RequiredPackageInstaller.getInstance(project).getMissingPackages(requiredPackages).isNotEmpty()) {
throw RequiredPackageException(requiredPackages)
}
}
}
} | 2 | Kotlin | 12 | 62 | d4d5cf9c09804454f811df7de0c02506d6ef12d3 | 6,518 | Rplugin | Apache License 2.0 |
commons/src/commonMain/kotlin/org/jetbrains/letsPlot/commons/intern/json/JsonLexer.kt | JetBrains | 176,771,727 | false | null | /*
* Copyright (c) 2020. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package jetbrains.datalore.base.json
internal class JsonLexer(
private val input: String
) {
private var i = 0
private var tokenStart = 0
var currentToken: Token? = null
private set
private val currentChar: Char
get() = input[i]
init {
nextToken() // read first token
}
fun nextToken() {
advanceWhile { it.isWhitespace() }
if (isFinished()) {
return
}
when {
currentChar == '{' -> Token.LEFT_BRACE.also { advance() }
currentChar == '}' -> Token.RIGHT_BRACE.also { advance() }
currentChar == '[' -> Token.LEFT_BRACKET.also { advance() }
currentChar == ']' -> Token.RIGHT_BRACKET.also { advance() }
currentChar == ',' -> Token.COMMA.also { advance() }
currentChar == ':' -> Token.COLON.also { advance() }
currentChar == 't' -> Token.TRUE.also { read("true") }
currentChar == 'f' -> Token.FALSE.also { read("false") }
currentChar == 'n' -> Token.NULL.also { read("null") }
currentChar == '"' -> Token.STRING.also { readString() }
readNumber() -> Token.NUMBER
else -> error("$i:${currentChar} - unkown token")
}.also { currentToken = it }
}
fun tokenValue() = input.substring(tokenStart, i)
private fun readString() {
startToken()
advance() // opening quote
while(!(currentChar == '"')) {
if(currentChar == '\\') {
advance()
when {
currentChar == 'u' -> {
advance()
repeat(4) {
require(currentChar.isHex());
advance()
}
}
currentChar in SPECIAL_CHARS -> advance()
else -> error("Invalid escape sequence")
}
} else {
advance()
}
}
advance() // closing quote
}
private fun readNumber(): Boolean {
if (!(currentChar.isDigit() || currentChar == '-')) {
return false
}
startToken()
advanceIfCurrent('-')
advanceWhile { it.isDigit() }
advanceIfCurrent('.') {
require(currentChar.isDigit()) { "Number should have decimal part" }
advanceWhile { it.isDigit() }
}
advanceIfCurrent('e', 'E') {
advanceIfCurrent('+', '-')
advanceWhile { it.isDigit() }
}
return true
}
fun isFinished(): Boolean = i == input.length
private fun startToken() { tokenStart = i }
private fun advance() { ++i }
private fun read(str: String) {
return str.forEach {
require(currentChar == it) { "Wrong data: $str" }
require(!isFinished()) { "Unexpected end of string" }
advance()
}
}
private fun advanceWhile(pred: (Char) -> Boolean) {
while (!isFinished() && pred(currentChar)) advance()
}
private fun advanceIfCurrent(vararg expected: Char, then: () -> Unit = {}) {
if (!isFinished() && currentChar in expected) {
advance()
then()
}
}
companion object {
private val digits: CharRange = '0'..'9'
private fun Char?.isDigit() = this in digits
private fun Char.isHex(): Boolean { return isDigit() || this in 'a'..'f' || this in 'A'..'F' }
}
}
| 97 | Kotlin | 47 | 889 | c5c66ceddc839bec79b041c06677a6ad5f54e416 | 3,695 | lets-plot | MIT License |
sdk-scrapper/src/main/kotlin/io/github/wulkanowy/sdk/scrapper/school/SchoolPlus.kt | wulkanowy | 138,756,468 | false | {"Kotlin": 705036, "HTML": 70768} | package io.github.wulkanowy.sdk.scrapper.school
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
internal data class SchoolPlus(
@SerialName("nazwa") val name: String,
@SerialName("imienia") val patron: String,
@SerialName("numer") val number: String,
@SerialName("miejscowosc") val town: String,
@SerialName("ulica") val street: String,
@SerialName("kodPocztowy") val postcode: String,
@SerialName("nrDomu") val buildingNumber: String,
@SerialName("nrMieszkania") val apartmentNumber: String,
@SerialName("dyrektorzy") val headmasters: List<String>?,
@SerialName("stronaWwwUrl") val website: String,
@SerialName("mail") val email: String,
@SerialName("telSluzbowy") val workPhone: String,
@SerialName("telKomorkowy") val mobilePhone: String,
@SerialName("telDomowy") val homePhone: String,
)
| 11 | Kotlin | 5 | 8 | 340245d8ccc2790dcb75219c2839e8bdd8b448a4 | 898 | sdk | Apache License 2.0 |
module_setting/src/main/kotlin/life/chenshi/keepaccounts/module/setting/vm/EditAssetsAccountViewModel.kt | SMAXLYB | 340,857,932 | false | null | package life.chenshi.keepaccounts.module.setting.vm
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import androidx.databinding.ObservableLong
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import life.chenshi.keepaccounts.module.common.base.BaseViewModel
import life.chenshi.keepaccounts.module.common.constant.CURRENT_ASSET_ACCOUNT_ID
import life.chenshi.keepaccounts.module.common.database.entity.AssetsAccount
import life.chenshi.keepaccounts.module.common.utils.BigDecimalUtil
import life.chenshi.keepaccounts.module.common.utils.ifNullOrBlank
import life.chenshi.keepaccounts.module.common.utils.storage.KVStoreHelper
import life.chenshi.keepaccounts.module.setting.bean.assets.IAssetIcon
import life.chenshi.keepaccounts.module.setting.repo.AssetsAccountRepo
import java.util.*
import javax.inject.Inject
@HiltViewModel
class EditAssetsAccountViewModel @Inject constructor(private val repo: AssetsAccountRepo) : BaseViewModel() {
val assetsAccount = MutableLiveData<AssetsAccount>()
val assetType = ObservableField<IAssetIcon>()
val assetName = ObservableField<String>()
val assetNumber = ObservableField<String>()
val assetRemark = ObservableField<String>()
val assetExpireDate = ObservableLong(System.currentTimeMillis())
val assetBalance = ObservableField<String>()
val usedDefault = ObservableBoolean()
val includedInAll = ObservableBoolean()
suspend fun insertOrUpdateAssetsAccount() {
val assets = AssetsAccount(
assetsAccount.value?.id,
assetName.get() ?: "",
BigDecimalUtil.fromString(assetBalance.get()),
assetRemark.get(),
assetNumber.get().ifNullOrBlank { null },
includedInAll.get(),
Date(assetExpireDate.get()),
assetType.get()?.name ?: ""
)
assetsAccount.value?.createTime?.let {
assets.createTime = it
}
val id = if (assets.id == null) {
repo.insertAssetsAccount(assets)
} else {
repo.updateAssetsAccount(assets)
requireNotNull(assets.id) { "更新操作必须有id" }
}
if (usedDefault.get()) {
KVStoreHelper.write(CURRENT_ASSET_ACCOUNT_ID, id)
} else {
if (KVStoreHelper.read(CURRENT_ASSET_ACCOUNT_ID, -1L) == id) {
KVStoreHelper.remove(CURRENT_ASSET_ACCOUNT_ID)
}
}
}
fun deleteAssetsAccountBy(assetsAccount: AssetsAccount) {
viewModelScope.launch {
repo.deleteAssetsAccount(assetsAccount)
}
}
} | 0 | Kotlin | 0 | 2 | 389632d87e90588555c10682a5804f6fddba5278 | 2,729 | KeepAccount | Apache License 2.0 |
src/main/kotlin/com/helltar/aibot/dao/tables/SlowmodeTable.kt | Helltar | 591,327,331 | false | {"Kotlin": 88527} | package com.helltar.artific_intellig_bot.dao.tables
import org.jetbrains.exposed.sql.Table
object SlowMode : Table() {
val userId = long("id")
val username = varchar("username", 32).nullable()
val firstName = varchar("firstName", 64)
val limit = integer("limit")
val requests = integer("requests")
val lastRequestTimestamp = long("lastRequestTimestamp")
override val primaryKey = PrimaryKey(userId)
} | 0 | Kotlin | 3 | 21 | 1a446727f4206d26c786a2958b3a275b1593eefb | 432 | artific_intellig_bot | MIT License |
src/main/kotlin/io/github/bayang/jelu/dao/UserTable.kt | bayang | 426,792,636 | false | null | package io.github.bayang.jelu.dao
import io.github.bayang.jelu.dto.UserDto
import org.jetbrains.exposed.dao.UUIDEntity
import org.jetbrains.exposed.dao.UUIDEntityClass
import org.jetbrains.exposed.dao.id.EntityID
import org.jetbrains.exposed.dao.id.UUIDTable
import org.jetbrains.exposed.sql.Column
import org.jetbrains.exposed.sql.javatime.timestamp
import java.util.*
object UserTable : UUIDTable("user") {
val creationDate = timestamp("creation_date")
val modificationDate = timestamp("modification_date")
val login: Column<String> = varchar("login", 50)
val password: Column<String> = varchar("password", 1000)
val isAdmin: Column<Boolean> = bool("is_admin")
val provider = enumerationByName("provider", 200, Provider::class)
}
class User(id: EntityID<UUID>) : UUIDEntity(id) {
fun toUserDto(): UserDto = UserDto(
id = this.id.value,
creationDate = this.creationDate,
modificationDate = this.modificationDate,
login = this.login,
password = "****",
isAdmin = this.isAdmin,
provider = this.provider,
)
companion object : UUIDEntityClass<User>(UserTable)
var creationDate by UserTable.creationDate
var modificationDate by UserTable.modificationDate
var login by UserTable.login
var password by UserTable.password
var isAdmin by UserTable.isAdmin
var provider by UserTable.provider
val userBooks by UserBook referrersOn UserBookTable.book
}
enum class Provider {
LDAP,
JELU_DB,
PROXY,
}
| 16 | null | 7 | 340 | 32de3210e27f64102052cc596e6602258b433a83 | 1,525 | jelu | MIT License |
src/main/java/uk/gov/justice/hmpps/probationteams/security/UserSecurityUtils.kt | nickmcmahon01 | 269,607,691 | false | null | package uk.gov.justice.digital.hmpps.cmd.api.security
import org.springframework.security.core.Authentication
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.stereotype.Component
@Component
@SuppressWarnings("ConstantConditions")
class UserSecurityUtils : AuthenticationFacade {
val authentication: Authentication
get() = SecurityContextHolder.getContext().authentication
override fun getCurrentUsername(): String? {
val username: String?
val userPrincipal = userPrincipal
if (userPrincipal is String) {
username = userPrincipal
} else if (userPrincipal is UserDetails) {
username = userPrincipal.username
} else if (userPrincipal is Map<*, *>) {
username = (userPrincipal["username"] as String?)!!
} else {
username = null
}
return username
}
private val userPrincipal: Any?
get() {
val auth = authentication
return auth.principal
}
}
| 1 | null | 2 | 1 | ce38a364438a0ff218490d1f80b071bb8b7e2e39 | 1,043 | probation-teams | MIT License |
libraries/tools/kotlin-gradle-plugin/src/common/kotlin/org/jetbrains/kotlin/gradle/testing/internal/TestReportService.kt | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | /*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.gradle.testing.internal
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.logging.Logging
import org.gradle.api.provider.Property
import org.gradle.api.provider.Provider
import org.gradle.api.services.BuildService
import org.gradle.api.services.BuildServiceParameters
import org.gradle.api.tasks.Internal
import org.jetbrains.kotlin.gradle.tasks.withType
import org.jetbrains.kotlin.gradle.utils.SingleActionPerProject
import java.io.*
import java.util.concurrent.ConcurrentHashMap
internal typealias TaskError = Pair<String, Error>
internal interface UsesTestReportService : Task {
@get:Internal
val testReportServiceProvider: Property<TestReportService>
}
/**
* A build service required for correct test failures detection in [KotlinTestReport] as it requires cross-task interaction.
*/
internal abstract class TestReportService : BuildService<TestReportService.TestReportServiceParameters>, AutoCloseable {
internal interface TestReportServiceParameters : BuildServiceParameters {
val testTasksStateFile: RegularFileProperty
}
private val log = Logging.getLogger(this.javaClass)
private val previouslyFailedTestTasks = readPreviouslyFailedTasks()
private val reportHasFailedTests = ConcurrentHashMap<String, Boolean>()
private val testTaskSuppressedFailures = ConcurrentHashMap<String, MutableList<TaskError>>()
/**
* Marks [KotlinTestReport] with [reportTaskPath] as a report containing failed tests during the build.
* [testTaskPath] is a path of the actual test task with failed tests.
*/
fun testFailed(reportTaskPath: String, testTaskPath: String) {
reportHasFailedTests[reportTaskPath] = true
previouslyFailedTestTasks.add(testTaskPath)
}
/**
* Checks whether [KotlinTestReport] defined by [path] contains any children test tasks that failed during the build
*/
fun hasFailedTests(path: String): Boolean {
return reportHasFailedTests[path] ?: false
}
/**
* Reports a test task execution failure (not test failure).
* @param failedTaskPath is a path of the failed test task
* @param parentTaskPath is a path of a [KotlinTestReport] that the task reports to
*/
fun reportFailure(failedTaskPath: String, parentTaskPath: String, failure: Error) {
testTaskSuppressedFailures.computeIfAbsent(parentTaskPath) { mutableListOf() }.add(failedTaskPath to failure)
}
/**
* Returns all the test task execution failures (not test failures) related to the [KotlinTestReport] defined by [taskPath]
*/
fun getAggregatedTaskFailures(taskPath: String): List<TaskError> {
return testTaskSuppressedFailures[taskPath] ?: emptyList()
}
override fun close() {
writePreviouslyFailedTasks()
}
/**
* Checks whether the test task defined by [path] had failed previously (doesn't matter if it's caused by failed test or any runtime problem).
* This function is not idempotent as it resets the task's failed state.
*/
fun hasTestTaskFailedPreviously(path: String) = previouslyFailedTestTasks.remove(path)
private val binaryStateFile: File
get() = parameters.testTasksStateFile.get().asFile
private fun readPreviouslyFailedTasks(): MutableSet<String> {
val failedTasksSet: MutableSet<String> = ConcurrentHashMap.newKeySet()
if (!binaryStateFile.exists()) return failedTasksSet
try {
ObjectInputStream(FileInputStream(binaryStateFile)).use {
@Suppress("UNCHECKED_CAST")
failedTasksSet.addAll(it.readObject() as Set<String>)
}
} catch (e: Exception) {
log.error("Cannot read test tasks state from $binaryStateFile", e)
}
return failedTasksSet
}
private fun writePreviouslyFailedTasks() {
previouslyFailedTestTasks += testTaskSuppressedFailures.values.flatMap { taskErrors -> taskErrors.map { (taskPath, _) -> taskPath } }
binaryStateFile.parentFile.mkdirs()
try {
ObjectOutputStream(FileOutputStream(binaryStateFile)).use {
it.writeObject(previouslyFailedTestTasks.toSet())
}
} catch (e: Exception) {
log.error("Cannot store test tasks state into $binaryStateFile", e)
}
}
companion object {
fun registerIfAbsent(project: Project): Provider<TestReportService> =
project.gradle.sharedServices
.registerIfAbsent(
"${TestReportService::class.java.canonicalName}_${project.path}",
TestReportService::class.java
) { spec ->
spec.parameters.testTasksStateFile.set(project.layout.buildDirectory.file("test-results/kotlin-test-tasks-state.bin"))
}.also { serviceProvider ->
SingleActionPerProject.run(project, UsesTestReportService::class.java.name) {
project.tasks.withType<UsesTestReportService>().configureEach { task ->
task.usesService(serviceProvider)
}
}
}
}
} | 7 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 5,493 | kotlin | Apache License 2.0 |
src/main/kotlin/horus/commands/discord/defaults/BotInfo.kt | GlitchLib | 152,699,467 | false | null | package horus.commands.discord.defaults
import com.sun.management.OperatingSystemMXBean
import horus.Info
import horus.commands.discord.api.DiscordCategory
import horus.commands.discord.api.DiscordCommand
import horus.commands.discord.api.DiscordCommandEvent
import horus.core.utils.Colors
import java.lang.management.ManagementFactory
import java.time.Instant
import javax.swing.filechooser.FileSystemView
class BotInfo : DiscordCommand("botinfo", arrayOf("bot"), "Bot Info", DiscordCategory.INFO) {
private val osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean::class.java)
val cpu: String
get() = "${osBean.processCpuLoad.format(2)}%"
val memory: (Boolean) -> String
get() = {
val size = (osBean.totalPhysicalMemorySize - osBean.freePhysicalMemorySize)
val total = osBean.totalPhysicalMemorySize
"${size.toProperSize(it)}/${total.toProperSize(it)} (${((size.toDouble() / total.toDouble()) * 100).format(2)}%)"
}
val drive: (Boolean) -> String
get() = { b ->
val roots = FileSystemView.getFileSystemView().roots
if (roots.size > 1) {
roots.joinToString("\n", prefix = "\n") { "- $it - ${(it.totalSpace - it.freeSpace).toProperSize(b)}/${it.totalSpace.toProperSize(b)}" }
} else {
roots.joinToString { "${(it.totalSpace - it.freeSpace).toProperSize(b)}/${it.totalSpace.toProperSize(b)}" }
}
}
override fun run(event: DiscordCommandEvent) {
val bytes = event.args.any { it.equals("--bytes", true) }
event.client.applicationInfo.zipWhen { event.client.getUserById(it.id) }.flatMap {
val app = it.t1
val bot = it.t2
event.replay {
setEmbed {
it.setThumbnail(bot.avatarUrl)
it.setColor(Colors.INFO)
it.setDescription("""
**Name:** ${bot.mention}
**Server Count:** ${event.client.guilds.toIterable().toList().size}
""".trimIndent())
it.addField(Info.BOT_DESCRIPTION, "${Info.BOT_VERSION} rev.*${Info.BOT_REVISION}*", true)
it.addField("Discord4J", Info.DISCORD, true)
it.addField("Usage", """
**Memory:** ${memory(bytes)}
**CPU:** $cpu
**Drive:** ${drive(bytes)}
""".trimIndent(), true)
it.setTimestamp(Instant.now())
it.setFooter("App ID: ${app.id}", null)
}
}
}.subscribe()
}
private fun Double.format(digits: Int) = String.format("%.${digits}f", this)
private fun Long.toProperSize(bytes: Boolean): String {
var doubled = this.toDouble()
val realD = doubled
var unit = "Bytes"
if (!bytes) {
while (doubled > 1024.0) {
when (unit) {
"Bytes" -> unit = "kB"
"kB" -> unit = "MB"
"MB" -> unit = "GB"
"GB" -> unit = "TB"
"TB" -> unit = "PB"
}
doubled /= 1024
}
}
return "${if (doubled % 1.0 == 0.0) doubled.format(0) else doubled.format(2)} $unit"
}
} | 0 | Kotlin | 0 | 0 | 0726199426a57ce95a9e193ff99ea7cfb3589137 | 3,411 | bot-butler | MIT License |
src/main/kotlin/de/flapdoodle/generics/local/k/HasLocalTypeMethod.kt | flapdoodle-oss | 180,553,828 | false | null | package de.flapdoodle.generics.local.k
import java.util.function.Supplier
class HasLocalTypeMethod {
fun <T> outer(factory: Factory<T, *>, value: T): T {
@Suppress("UNCHECKED_CAST")
return sample(factory as Factory<T, Supplier<T>>, value)
}
fun <T, R : Supplier<T>> sample(factory: Factory<T, R>, value: T): T {
val supplier = factory.create(value)
return supplier.get()
}
}
| 0 | Kotlin | 1 | 0 | 14d401c34c300e55ec26e5c72fda883984113ccc | 403 | kotlin-or-java | Apache License 2.0 |
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/filled/CircleArrowUpLeft.kt | walter-juan | 868,046,028 | false | {"Kotlin": 34345428} | package com.woowla.compose.icon.collections.tabler.tabler.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.tabler.tabler.FilledGroup
public val FilledGroup.CircleArrowUpLeft: ImageVector
get() {
if (_circleArrowUpLeft != null) {
return _circleArrowUpLeft!!
}
_circleArrowUpLeft = Builder(name = "CircleArrowUpLeft", defaultWidth = 24.0.dp,
defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(17.0f, 3.34f)
arcToRelative(10.0f, 10.0f, 0.0f, true, true, -14.995f, 8.984f)
lineToRelative(-0.005f, -0.324f)
lineToRelative(0.005f, -0.324f)
arcToRelative(10.0f, 10.0f, 0.0f, false, true, 14.995f, -8.336f)
close()
moveTo(15.0f, 8.0f)
horizontalLineToRelative(-6.0f)
lineToRelative(-0.117f, 0.007f)
lineToRelative(-0.149f, 0.029f)
lineToRelative(-0.105f, 0.035f)
lineToRelative(-0.113f, 0.054f)
lineToRelative(-0.111f, 0.071f)
arcToRelative(1.01f, 1.01f, 0.0f, false, false, -0.112f, 0.097f)
lineToRelative(-0.08f, 0.09f)
lineToRelative(-0.067f, 0.096f)
lineToRelative(-0.052f, 0.098f)
lineToRelative(-0.044f, 0.11f)
lineToRelative(-0.03f, 0.112f)
lineToRelative(-0.017f, 0.126f)
lineToRelative(-0.003f, 6.075f)
lineToRelative(0.007f, 0.117f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 0.993f, 0.883f)
lineToRelative(0.117f, -0.007f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 0.883f, -0.993f)
verticalLineToRelative(-3.585f)
lineToRelative(4.293f, 4.292f)
lineToRelative(0.094f, 0.083f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 1.32f, -1.497f)
lineToRelative(-4.292f, -4.293f)
horizontalLineToRelative(3.585f)
lineToRelative(0.117f, -0.007f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, -0.117f, -1.993f)
close()
}
}
.build()
return _circleArrowUpLeft!!
}
private var _circleArrowUpLeft: ImageVector? = null
| 0 | Kotlin | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 3,104 | compose-icon-collections | MIT License |
src/main/kotlin/no/nav/klage/clients/FileClient.kt | navikt | 253,461,869 | false | null | package no.nav.klage.clients
import no.nav.klage.util.TokenUtil
import no.nav.klage.util.getLogger
import org.springframework.http.HttpHeaders
import org.springframework.http.client.MultipartBodyBuilder
import org.springframework.stereotype.Component
import org.springframework.web.reactive.function.BodyInserters
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.reactive.function.client.bodyToMono
@Component
class FileClient(
private val fileWebClient: WebClient,
private val tokenUtil: TokenUtil
) {
companion object {
@Suppress("JAVA_CLASS_ON_COMPANION")
private val logger = getLogger(javaClass.enclosingClass)
}
//TODO: Rydd i fillageret nå som vi ikke lenger trenger det.
fun uploadVedleggFile(vedleggFile: ByteArray, originalFilename: String): String {
logger.debug("Uploading attachment to file store.")
val bodyBuilder = MultipartBodyBuilder()
bodyBuilder.part("file", vedleggFile).filename(originalFilename)
val response = fileWebClient
.post()
.uri { it.path("/attachment").build() }
.header(HttpHeaders.AUTHORIZATION, "Bearer ${tokenUtil.getAppAccessTokenWithKlageFileApiScope()}")
.body(BodyInserters.fromMultipartData(bodyBuilder.build()))
.retrieve()
.bodyToMono<VedleggResponse>()
.block()
requireNotNull(response)
logger.debug("Attachment uploaded to file store with id: {}", response.id)
return response.id
}
fun getVedleggFile(vedleggRef: String): ByteArray {
logger.debug("Fetching vedlegg file with vedlegg ref {}", vedleggRef)
return fileWebClient.get()
.uri { it.path("/attachment/{id}").build(vedleggRef) }
.header(HttpHeaders.AUTHORIZATION, "Bearer ${tokenUtil.getAppAccessTokenWithKlageFileApiScope()}")
.retrieve()
.bodyToMono<ByteArray>()
.block() ?: throw RuntimeException("Attachment could not be fetched")
}
fun deleteVedleggFile(vedleggRef: String): Boolean {
logger.debug("Deleting vedlegg file with vedlegg ref {}", vedleggRef)
val deletedInFileStore = fileWebClient.delete()
.uri { it.path("/attachment/{id}").build(vedleggRef) }
.header(HttpHeaders.AUTHORIZATION, "Bearer ${tokenUtil.getAppAccessTokenWithKlageFileApiScope()}")
.retrieve()
.bodyToMono<Boolean>()
.block()!!
if (deletedInFileStore) {
logger.debug("Attachment successfully deleted in file store.")
} else {
logger.debug("Attachment $vedleggRef was not deleted in file store. File could be missing from filestore.")
}
return deletedInFileStore
}
}
data class VedleggResponse(val id: String) | 2 | Kotlin | 1 | 0 | 8a93a0934e99a3d94165fd85d809ac830f1100b8 | 2,861 | klage-dittnav-api | MIT License |
idea/src/org/jetbrains/kotlin/idea/roots/KotlinNonJvmOrderEnumerationHandler.kt | JetBrains | 278,369,660 | false | null | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.roots
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.ModuleRootModel
import com.intellij.openapi.roots.OrderEnumerationHandler
import com.intellij.openapi.roots.OrderRootType
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
import org.jetbrains.kotlin.config.TestResourceKotlinRootType
import org.jetbrains.kotlin.config.TestSourceKotlinRootType
object KotlinNonJvmOrderEnumerationHandler : OrderEnumerationHandler() {
class Factory : OrderEnumerationHandler.Factory() {
override fun isApplicable(module: Module) = true
override fun createHandler(module: Module) = KotlinNonJvmOrderEnumerationHandler
}
private val kotlinTestSourceRootTypes: Set<JpsModuleSourceRootType<*>> =
setOf(TestSourceKotlinRootType, TestResourceKotlinRootType)
override fun addCustomModuleRoots(
type: OrderRootType,
rootModel: ModuleRootModel,
result: MutableCollection<String>,
includeProduction: Boolean,
includeTests: Boolean
): Boolean {
if (type == OrderRootType.SOURCES) {
if (includeProduction) {
rootModel.getSourceRoots(includeTests).mapTo(result) { it.url }
} else {
rootModel.getSourceRoots(kotlinTestSourceRootTypes).mapTo(result) { it.url }
}
return true
}
return false
}
} | 191 | null | 4372 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 1,598 | intellij-kotlin | Apache License 2.0 |
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppschallengesupportinterventionplanapi/model/request/UpdateReferralRequest.kt | ministryofjustice | 797,799,207 | false | {"Kotlin": 464802, "Mermaid": 28845, "Shell": 1890, "Dockerfile": 1372} | package uk.gov.justice.digital.hmpps.hmppschallengesupportinterventionplanapi.model.request
import com.fasterxml.jackson.annotation.JsonFormat
import io.swagger.v3.oas.annotations.media.Schema
import jakarta.validation.Valid
import jakarta.validation.constraints.Size
import uk.gov.justice.digital.hmpps.hmppschallengesupportinterventionplanapi.enumeration.OptionalYesNoAnswer
import java.time.LocalDate
import java.time.LocalTime
@Schema(
description = "The request body for updating a CSIP Record",
)
data class UpdateCsipRecordRequest(
@Schema(
description = "User entered identifier for the CSIP record. Defaults to the prison code.",
)
@field:Size(max = 10, message = "Log code must be <= 10 characters")
val logCode: String?,
@field:Valid
val referral: UpdateReferral?,
)
@Schema(
description = "The detail for updating a CSIP referral",
)
data class UpdateReferral(
@Schema(
description = "The date the incident that motivated the CSIP referral occurred",
example = "2021-09-27",
)
@JsonFormat(pattern = "yyyy-MM-dd")
val incidentDate: LocalDate,
@Schema(
description = "The time the incident that motivated the CSIP referral occurred",
example = "14:19:25",
type = "String",
pattern = "HH:mm:SS",
)
@JsonFormat(pattern = "HH:mm:ss")
val incidentTime: LocalTime?,
@Schema(
description = "The type of incident that motivated the CSIP referral.",
)
@field:Size(min = 1, max = 12, message = "Incident Type code must be <= 12 characters")
val incidentTypeCode: String,
@Schema(
description = "The location of incident that motivated the CSIP referral.",
)
@field:Size(min = 1, max = 12, message = "Incident Location code must be <= 12 characters")
val incidentLocationCode: String,
@Schema(
description = "The person reporting the incident or creating the CSIP referral.",
)
@field:Size(min = 1, max = 240, message = "Referer name must be <= 240 characters")
val referredBy: String,
@Schema(
description = "The area of work of the person reporting the incident or creating the CSIP referral.",
)
@field:Size(min = 1, max = 12, message = "Area code must be <= 12 characters")
val refererAreaCode: String,
@Schema(
description = "Was this referral proactive or preventative.",
)
val isProactiveReferral: Boolean?,
@Schema(
description = "Were any members of staff assaulted in the incident.",
)
val isStaffAssaulted: Boolean?,
@Schema(
description = "Name or names of assaulted members of staff if any.",
)
@field:Size(min = 0, max = 1000, message = "Name or names must be <= 1000 characters")
val assaultedStaffName: String?,
@Schema(
description = "The type of involvement the person had in the incident",
)
@field:Size(min = 1, max = 12, message = "Involvement code must be <= 12 characters")
val incidentInvolvementCode: String?,
@Schema(
description = "The reasons why there is cause for concern.",
)
val descriptionOfConcern: String?,
@Schema(
description = "The reasons already known about the causes of the incident or motivation for CSIP referral.",
)
val knownReasons: String?,
@Schema(
description = "Any other information about the incident or reasons for CSIP referral.",
)
val otherInformation: String?,
@Schema(
description = "Records whether the safer custody team been informed.",
)
val isSaferCustodyTeamInformed: OptionalYesNoAnswer,
@Schema(
description = "Is the referral complete.",
)
val isReferralComplete: Boolean?,
@Schema(
description = "The date the referral was completed.",
example = "2024-07-29",
)
@JsonFormat(pattern = "yyyy-MM-dd")
val completedDate: LocalDate?,
@Schema(
description = "The username of the person who completed the referral.",
)
@field:Size(min = 0, max = 32, message = "Completed by username must be <= 32 characters")
val completedBy: String?,
@Schema(
description = "The displayable name of the person who completed the referral.",
)
@field:Size(min = 0, max = 255, message = "Completed by display name must be <= 255 characters")
val completedByDisplayName: String?,
)
| 2 | Kotlin | 0 | 0 | e7c97c8f0482ed16f5f61994c80555671cdc5543 | 4,188 | hmpps-challenge-support-intervention-plan-api | MIT License |
src/main/kotlin/org/bloqly/machine/controller/data/BlockController.kt | abaracadaor | 147,365,768 | false | {"Gradle": 1, "Shell": 9, "Text": 2, "Ignore List": 2, "Batchfile": 1, "Markdown": 2, "INI": 1, "YAML": 7, "JSON": 3, "JavaScript": 6, "Kotlin": 129, "Java": 4, "XML": 1, "SVG": 1} | package org.bloqly.machine.controller.data
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiParam
import org.bloqly.machine.service.BlockService
import org.bloqly.machine.vo.block.BlockDataList
import org.bloqly.machine.vo.block.BlockRangeRequest
import org.bloqly.machine.vo.block.BlockRequest
import org.bloqly.machine.vo.block.BlockVO
import org.springframework.context.annotation.Profile
import org.springframework.http.HttpStatus.NOT_FOUND
import org.springframework.http.HttpStatus.OK
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@Api(
value = "/api/v1/data/blocks",
description = "Operations providing data access to blocks",
consumes = "application/json",
produces = "application/json"
)
@Profile("server")
@RestController()
@RequestMapping("/api/v1/data/blocks")
class BlockController(
private val blockService: BlockService
) {
@ApiOperation(
value = "Returns last best known block",
response = BlockVO::class,
nickname = "getLastBlock"
)
@PostMapping("last")
fun getLastBlock(@RequestBody blockRequest: BlockRequest): ResponseEntity<BlockVO> {
return if (blockService.existsBySpaceId(blockRequest.spaceId)) {
ResponseEntity(blockService.getLastBlockBySpace(blockRequest.spaceId).toVO(), OK)
} else {
ResponseEntity(NOT_FOUND)
}
}
@ApiOperation(
value = "Returns LIB (last irreversible block)",
response = BlockVO::class,
nickname = "getLIB"
)
@PostMapping("lib")
fun getLIB(@RequestBody blockRequest: BlockRequest): ResponseEntity<BlockVO> {
return if (blockService.existsBySpaceId(blockRequest.spaceId)) {
val lastBlock = blockService.getLastBlockBySpace(blockRequest.spaceId)
ResponseEntity(blockService.getLIBForBlock(lastBlock).toVO(), OK)
} else {
ResponseEntity(NOT_FOUND)
}
}
@ApiOperation(
value = "Returns blocks range",
response = BlockDataList::class,
nickname = "getBlocksRange"
)
@PostMapping("search")
fun getDelta(@RequestBody blockRangeRequest: BlockRangeRequest): ResponseEntity<BlockDataList> {
return ResponseEntity(blockService.getBlockDataList(blockRangeRequest), OK)
}
@ApiOperation(
value = "Returns block by provided hash",
response = BlockVO::class,
nickname = "getBlockByHash"
)
@GetMapping("{blockHash}")
fun getBlockByHash(@ApiParam("The block hash") @PathVariable("blockHash") blockHash: String): ResponseEntity<BlockVO> {
return blockService.findByHash(blockHash)
?.let { ResponseEntity(it.toVO(), OK) }
?: ResponseEntity(NOT_FOUND)
}
} | 1 | null | 1 | 1 | cfe046f6d93ebc51d12b2fecdbf0215181152a03 | 3,150 | bloqly | MIT License |
samples/ktor-all-platforms-app/server/src/test/kotlin/kotlinx/rpc/sample/ApplicationTest.kt | Kotlin | 739,292,079 | false | null | /*
* Copyright 2023-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
import io.ktor.server.testing.*
import kotlinx.coroutines.flow.toList
import kotlinx.rpc.withService
import kotlinx.rpc.serialization.json
import kotlinx.rpc.streamScoped
import kotlinx.rpc.transport.ktor.client.installRPC
import kotlinx.rpc.transport.ktor.client.rpc
import kotlinx.rpc.transport.ktor.client.rpcConfig
import kotlin.test.Test
import kotlin.test.assertEquals
class ApplicationTest {
@Test
fun testRoot() = testApplication {
val service = createClient {
installRPC()
}.rpc("/api") {
rpcConfig {
serialization {
json()
}
}
}.withService<MyService>()
assertEquals(
expected = "Nice to meet you Alex, how is it in address1?",
actual = service.hello("Alex", UserData("address1", "last")),
)
streamScoped {
assertEquals(
expected = List(10) { "Article number $it" },
actual = service.subscribeToNews().toList(),
)
}
}
}
| 26 | null | 17 | 733 | b946964ca7838d40ba68ad98fe4056f3ed17c635 | 1,197 | kotlinx-rpc | Apache License 2.0 |
server/src/main/kotlin/io/typestream/config/KafkaConfig.kt | typestreamio | 685,423,176 | false | {"Kotlin": 324308, "Go": 32564, "Shell": 2073, "Makefile": 467} | package io.typestream.config
data class KafkaConfig(
val bootstrapServers: String,
val fsRefreshRate: Int = 60,
val schemaRegistry: SchemaRegistryConfig,
val saslConfig: SaslConfig? = null,
)
| 4 | Kotlin | 2 | 42 | edbfb9b21db426ac521e10b85e61983b94e0cd6a | 209 | typestream | Apache License 2.0 |
engine/src/main/kotlin/io/kotless/gen/factory/route/AbstractRouteFactory.kt | cybernetics | 214,768,441 | true | {"Kotlin": 176487} | package io.kotless.gen.factory.route
import io.kotless.URIPath
import io.kotless.gen.GenerationContext
import io.kotless.gen.factory.apigateway.RestAPIFactory
import io.kotless.hcl.ref
import io.kotless.terraform.provider.aws.resource.apigateway.api_gateway_resource
import io.kotless.utils.Storage
/**
* Generic implementation of ApiGateway resources creation
*
* Will create all intermediate resources
*/
abstract class AbstractRouteFactory {
companion object {
private val resource = Storage.Key<HashMap<URIPath, String>>()
}
fun getResource(resourcePath: URIPath, api: RestAPIFactory.RestAPIOutput, context: GenerationContext): String {
val resources = context.storage.getOrPut(resource) { HashMap() }
if (URIPath() !in resources) {
resources[URIPath()] = api.root_resource_id
}
var path = URIPath()
for (part in resourcePath.parts) {
val prev = path
path = URIPath(path, part)
if (path !in resources) {
val resource = api_gateway_resource(context.names.tf(path.parts)) {
rest_api_id = api.rest_api_id
parent_id = resources[prev]!!
path_part = part
}
context.entities.register(resource)
resources[path] = resource::id.ref
}
}
return resources[path]!!
}
}
| 0 | null | 0 | 0 | 84efd97c6fde0771cf28cb9059a025c92a44950b | 1,434 | kotless | Apache License 2.0 |
app/src/main/java/com/example/lemonade/MainActivity.kt | barnett-yuxiang | 802,696,491 | false | null |
package com.example.lemonade
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import com.example.lemonade.ui.theme.AppTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
setContent {
AppTheme {
LemonadeApp()
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LemonadeApp() {
var currentStep by remember { mutableStateOf(1) }
var squeezeCount by remember { mutableStateOf(0) }
Scaffold(
topBar = {
CenterAlignedTopAppBar(
title = {
Text(
text = "Lemonade",
fontWeight = FontWeight.Bold
)
},
colors = TopAppBarDefaults.largeTopAppBarColors(
containerColor = MaterialTheme.colorScheme.primaryContainer
)
)
}
) { innerPadding ->
Surface(
modifier = Modifier
.fillMaxSize()
.padding(innerPadding)
.background(MaterialTheme.colorScheme.tertiaryContainer),
color = MaterialTheme.colorScheme.background
) {
when (currentStep) {
1 -> {
LemonTextAndImage(
textLabelResourceId = R.string.lemon_select,
drawableResourceId = R.drawable.lemon_tree,
contentDescriptionResourceId = R.string.lemon_tree_content_description,
onImageClick = {
currentStep = 2
squeezeCount = (2..4).random()
}
)
}
2 -> {
LemonTextAndImage(
textLabelResourceId = R.string.lemon_squeeze,
drawableResourceId = R.drawable.lemon_squeeze,
contentDescriptionResourceId = R.string.lemon_content_description,
onImageClick = {
squeezeCount--
if (squeezeCount == 0) {
currentStep = 3
}
}
)
}
3 -> {
LemonTextAndImage(
textLabelResourceId = R.string.lemon_drink,
drawableResourceId = R.drawable.lemon_drink,
contentDescriptionResourceId = R.string.lemonade_content_description,
onImageClick = {
currentStep = 4
}
)
}
4 -> {
LemonTextAndImage(
textLabelResourceId = R.string.lemon_empty_glass,
drawableResourceId = R.drawable.lemon_restart,
contentDescriptionResourceId = R.string.empty_glass_content_description,
onImageClick = {
currentStep = 1
}
)
}
}
}
}
}
@Composable
fun LemonTextAndImage(
textLabelResourceId: Int,
drawableResourceId: Int,
contentDescriptionResourceId: Int,
onImageClick: () -> Unit,
modifier: Modifier = Modifier
) {
Box(
modifier = modifier
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxSize()
) {
Button(
onClick = onImageClick,
shape = RoundedCornerShape(dimensionResource(R.dimen.button_corner_radius)),
colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.tertiaryContainer)
) {
Image(
painter = painterResource(drawableResourceId),
contentDescription = stringResource(contentDescriptionResourceId),
modifier = Modifier
.width(dimensionResource(R.dimen.button_image_width))
.height(dimensionResource(R.dimen.button_image_height))
.padding(dimensionResource(R.dimen.button_interior_padding))
)
}
Spacer(modifier = Modifier.height(dimensionResource(R.dimen.padding_vertical)))
Text(
text = stringResource(textLabelResourceId),
style = MaterialTheme.typography.bodyLarge
)
}
}
}
@Preview
@Composable
fun LemonPreview() {
AppTheme() {
LemonadeApp()
}
} | 0 | null | 0 | 1 | 7b13a8f565b34d13aaa44f135f62f347be9307ac | 6,538 | LemonadeApp | MIT License |
src/main/kotlin/com/autonomousapps/internal/android/BaseAndroidGradlePlugin.kt | autonomousapps | 217,134,508 | false | null | package com.autonomousapps.internal.android
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.api.Task
import java.lang.reflect.Method
abstract class BaseAndroidGradlePlugin(
protected val project: Project,
protected val agpVersion: String
) : AndroidGradlePlugin {
protected abstract val bundleTaskType: String
protected abstract val bundleTaskOutputMethodName: String
@Suppress("UNCHECKED_CAST")
protected fun getBundleTaskType(): Class<out Task> = try {
Class.forName(bundleTaskType) as Class<Task>
} catch (e: ClassNotFoundException) {
throw GradleException("Cannot find bundle class for AGP $agpVersion")
}
protected fun getOutputMethod(type: Class<out Task>): Method = try {
type.getDeclaredMethod(bundleTaskOutputMethodName)
} catch (e: NoSuchMethodException) {
throw GradleException("Cannot find output method name for AGP $agpVersion")
}
}
| 41 | null | 55 | 910 | da02a56a0b7a00a26876cdaa29321f8376bf7099 | 928 | dependency-analysis-android-gradle-plugin | Apache License 2.0 |
syft/src/test/java/org/openmined/syft/unit/monitor/battery/RobolectricBatteryDataSource.kt | OpenMined | 232,324,117 | false | null | package fl.wearable.autosport.unit.monitor.battery
import android.content.Context
import android.content.Intent
import android.os.BatteryManager
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.notNull
import io.reactivex.processors.PublishProcessor
import io.reactivex.schedulers.TestScheduler
import org.junit.Test
import org.junit.runner.RunWith
import fl.wearable.autosport.monitor.StateChangeMessage
import fl.wearable.autosport.monitor.battery.BatteryStatusDataSource
import org.robolectric.RobolectricTestRunner
import org.robolectric.shadow.api.Shadow
import java.util.concurrent.TimeUnit
@ExperimentalUnsignedTypes
@RunWith(RobolectricTestRunner::class)
class RobolectricBatteryDataSource {
@Test
fun `getBatteryLevel returns the battery percentage from intent`() {
val intent = Shadow.newInstanceOf(Intent::class.java)
intent.putExtra(BatteryManager.EXTRA_LEVEL, 1000)
intent.putExtra(BatteryManager.EXTRA_SCALE, 4000)
val contextMock = mock<Context> {
on { registerReceiver(eq(null), any()) }
.thenReturn(intent)
}
val batteryStatusDataSource = BatteryStatusDataSource(contextMock, true)
assert(batteryStatusDataSource.getBatteryLevel() == 25.0f)
}
@Test
fun `checkIfCharging returns true when charging`() {
val intent = Shadow.newInstanceOf(Intent::class.java)
intent.putExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_CHARGING)
val contextMock = mock<Context> {
on { registerReceiver(eq(null), any()) }
.thenReturn(intent)
}
val batteryStatusDataSource = BatteryStatusDataSource(contextMock, true)
assert(batteryStatusDataSource.checkIfCharging())
}
@Test
fun `checkIfCharging returns false when not charging`() {
val intent = Shadow.newInstanceOf(Intent::class.java)
intent.putExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_DISCHARGING)
val contextMock = mock<Context> {
on { registerReceiver(eq(null), any()) }
.thenReturn(intent)
}
val batteryStatusDataSource = BatteryStatusDataSource(contextMock, true)
assert(!batteryStatusDataSource.checkIfCharging())
}
@RunWith(RobolectricTestRunner::class)
class BatteryChangeReceiverTest {
private val testScheduler = TestScheduler()
private val statusProcessor = PublishProcessor.create<StateChangeMessage>()
private val contextMock = mock<Context> {
on { registerReceiver(eq(null), any()) }
.thenReturn(null)
on { registerReceiver(notNull(), any()) }
.thenReturn(null)
}
private val batterySource = BatteryStatusDataSource(contextMock, true, statusProcessor)
private val batteryChangeReceiver = batterySource.BatteryChangeReceiver()
@Test
fun `status processor offers battery disconnected message when receiver gets the intent`() {
val intent = Shadow.newInstanceOf(Intent::class.java)
intent.action = Intent.ACTION_POWER_DISCONNECTED
val testReceiver = batterySource.subscribeStateChange()
.subscribeOn(testScheduler)
.observeOn(testScheduler)
.test()
testScheduler.advanceTimeBy(1L, TimeUnit.MILLISECONDS)
batteryChangeReceiver.onReceive(null, intent)
testScheduler.advanceTimeBy(1L, TimeUnit.MILLISECONDS)
testReceiver.assertValue(StateChangeMessage.Charging(false))
testReceiver.dispose()
}
@Test
fun `status processor offers battery charging message when receiver gets the intent`() {
val intent = Shadow.newInstanceOf(Intent::class.java)
intent.action = Intent.ACTION_POWER_CONNECTED
val testReceiver = batterySource.subscribeStateChange()
.subscribeOn(testScheduler)
.observeOn(testScheduler)
.test()
testScheduler.advanceTimeBy(1L, TimeUnit.MILLISECONDS)
batteryChangeReceiver.onReceive(null, intent)
testScheduler.advanceTimeBy(1L, TimeUnit.MILLISECONDS)
testReceiver.assertValue(StateChangeMessage.Charging(true))
testReceiver.dispose()
}
}
} | 75 | null | 26 | 79 | da8a442586700e32de0d01d52fde941199951ea9 | 4,530 | KotlinSyft | Apache License 2.0 |
clearnet/src/main/java/clearnet/interfaces.kt | xelevra | 176,962,795 | true | {"Gradle": 6, "Markdown": 3, "Java Properties": 1, "Shell": 1, "Ignore List": 5, "Batchfile": 1, "Kotlin": 51, "Java": 35, "Proguard": 1, "XML": 2, "INI": 1} | package clearnet.interfaces
import clearnet.CoreTask
import clearnet.InvocationBlockType
import clearnet.error.ClearNetworkException
import clearnet.error.ConversionException
import clearnet.error.HTTPCodeError
import clearnet.model.MergedInvocationStrategy
import clearnet.model.PostParams
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.disposables.Disposable
import io.reactivex.internal.schedulers.ImmediateThinScheduler
import io.reactivex.schedulers.Schedulers
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import java.lang.reflect.Type
import java.util.*
interface ConversionStrategy {
@Throws(JSONException::class, ConversionStrategyError::class)
fun checkErrorOrResult(response: JSONObject): String?
fun init(parameter: String){
// nop
}
class ConversionStrategyError(val serializedError: String?, val errorType: Type) : Exception()
object SmartConverter {
@Throws(ClearNetworkException::class)
fun convert(converter: ISerializer, body: String, type: Type, strategy: ConversionStrategy): Any? {
return converter.deserialize(getStringResultOrThrow(converter, body, strategy), type)
}
@Throws(ClearNetworkException::class)
fun getStringResultOrThrow(converter: ISerializer, body: String, strategy: ConversionStrategy): String? {
try {
return getStringResultOrThrow(converter, JSONObject(body), strategy)
} catch (e: JSONException) {
throw ConversionException(e)
}
}
@Throws(ClearNetworkException::class)
fun getStringResultOrThrow(converter: ISerializer, body: JSONObject, strategy: ConversionStrategy): String? {
try {
return strategy.checkErrorOrResult(body)
} catch (e: JSONException) {
throw ConversionException(e)
} catch (e: ConversionStrategyError) {
throw clearnet.error.ResponseErrorException(converter.deserialize(e.serializedError, e.errorType))
}
}
}
}
/**
* Validates fields of model instances which has been deserialized from the server response.
* The validator must check required fields and can contains some additional checking rules.
*/
interface IBodyValidator {
@Throws(clearnet.error.ValidationException::class)
fun validate(body: Any?)
}
interface ICacheProvider {
fun store(key: String, value: String, expiresAfter: Long)
fun obtain(key: String): String?
}
/**
* The upper level abstraction of [IRequestExecutor].
* It should serialize the object, send the request and deserialize the response to the model.
*/
interface IConverterExecutor {
fun executePost(postParams: PostParams)
}
/**
* Request executor which should just push data to server and return response as String
*/
interface IRequestExecutor {
@Throws(IOException::class, HTTPCodeError::class)
fun executeGet(headers: Map<String, String>, queryParams: Map<String, String> = emptyMap()): Pair<String, Map<String, String>>
@Throws(IOException::class, HTTPCodeError::class)
fun executePost(body: String, headers: Map<String, String>, queryParams: Map<String, String> = emptyMap()): Pair<String, Map<String, String>>
}
/**
* Serializes and deserializes models to/from String
*/
interface ISerializer {
@Throws(ConversionException::class)
fun serialize(obj: Any?): String
@Throws(ConversionException::class)
fun deserialize(body: String?, objectType: Type): Any?
}
interface ISmartConverter {
@Throws(ClearNetworkException::class)
fun convert(body: String, type: Type, strategy: ConversionStrategy): Any?
}
/**
* Request executor non typed callback for inner use
*/
@Deprecated("Use reactive streams")
interface RequestCallback<T> {
/**
* @param response – the deserialized model
*/
fun onSuccess(response: T)
/**
* @param exception – the exception, which can be caught during request, conversation or validation processes
*/
fun onFailure(exception: ClearNetworkException)
}
interface ICallbackHolder {
val scheduler: Scheduler
get() = ImmediateThinScheduler.INSTANCE
fun init()
fun hold(disposable: Disposable)
fun clear()
@Deprecated("")
fun <I> createEmpty(type: Class<in I>): I
@Deprecated("")
fun <I> wrap(source: I, interfaceType: Class<in I>): I
}
interface HeaderProvider {
fun obtainHeadersList(): Map<String, String>
}
interface HeaderListener {
fun onNewHeader(method: String, name: String, value: String)
}
interface HeaderObserver {
fun register(method: String, listener: HeaderListener, vararg header: String): Subscription
}
interface ICallbackStorage {
fun <T> observe(method: String): Observable<T>
@Deprecated("")
fun subscribe(method: String, callback: RequestCallback<*>, once: Boolean = false): Subscription
}
@Deprecated("")
interface Subscription {
fun unsubscribe()
}
interface IInvocationBlock {
val invocationBlockType: InvocationBlockType
val queueAlgorithm: QueueAlgorithm
get() = QueueAlgorithm.IMMEDIATE
val queueTimeThreshold: Long
get() = 100L
fun onEntity(promise: CoreTask.Promise) {
promise.next(invocationBlockType)
}
fun onQueueConsumed(promises: List<CoreTask.Promise>) {}
enum class QueueAlgorithm {
IMMEDIATE, TIME_THRESHOLD
}
}
interface TaskTimeTracker {
fun onTaskFinished(invocationStrategy: MergedInvocationStrategy, method: String, time: Long)
}
interface IInvocationStrategy {
val algorithm: Map<InvocationBlockType, Decision>
val metaData: Map<String, String>
class Decision(private val onResult: Array<InvocationBlockType>, private val onError: Array<InvocationBlockType> = emptyArray()) {
constructor(onResult: InvocationBlockType) : this(arrayOf(onResult))
constructor(onResult: InvocationBlockType, onError: InvocationBlockType) : this(arrayOf(onResult), arrayOf(onError))
constructor(onResult: Array<InvocationBlockType>, onError: InvocationBlockType) : this(onResult, arrayOf(onError))
operator fun get(hasResult: Boolean) = if (hasResult) onResult else onError
}
} | 0 | Kotlin | 0 | 0 | e9a6e5658b358110d90d0cd7129a9d77ff18af49 | 6,292 | clearnet | Apache License 2.0 |
src/main/kotlin/net/casual/arcade/minigame/events/lobby/Lobby.kt | CasualChampionships | 621,955,934 | false | {"Kotlin": 779326, "Java": 132970, "GLSL": 2247} | package net.casual.arcade.minigame.events.lobby
import net.casual.arcade.area.PlaceableArea
import net.casual.arcade.gui.bossbar.TimerBossBar
import net.casual.arcade.gui.countdown.Countdown
import net.casual.arcade.utils.PlayerUtils.teleportTo
import net.casual.arcade.utils.impl.Location
import net.minecraft.server.level.ServerPlayer
public interface Lobby {
public val area: PlaceableArea
public val spawn: Location
public fun getCountdown(): Countdown
public fun createBossbar(): TimerBossBar
public fun getSpawn(player: ServerPlayer): Location {
return this.spawn
}
public fun forceTeleportToSpawn(player: ServerPlayer) {
player.teleportTo(this.getSpawn(player))
}
public fun tryTeleportToSpawn(player: ServerPlayer): Boolean {
if (player.level() != this.spawn.level || !this.area.getEntityBoundingBox().contains(player.position())) {
this.forceTeleportToSpawn(player)
return true
}
return false
}
} | 1 | Kotlin | 1 | 2 | 6a65e30cea14e052d24a92c624682edefb2a7fe2 | 1,016 | arcade | MIT License |
app/src/main/java/com/magicfluids/MyGLSurfaceView2.kt | coderspacedev | 846,482,266 | false | {"Kotlin": 215806, "Java": 52620, "JavaScript": 51961, "GLSL": 50151, "HTML": 34763} | package com.magicfluids
import android.content.*
import android.graphics.*
import android.opengl.*
import android.util.*
import android.view.*
import com.fluidsimulation.App.Companion.app
import com.fluidsimulation.ext.*
import com.fluidsimulation.helper.*
import com.fluidsimulation.model.*
import kotlinx.coroutines.*
class MyGLSurfaceView2 : GLSurfaceView {
private var renderer: GLES20Renderer2? = null
private var orientationSensor: OrientationSensor? = null
private var nativeInterface: NativeInterface? = null
constructor(context: Context?, attributeSet: AttributeSet?) : super(context, attributeSet)
constructor(context: Context?) : super(context){
initView(context)
}
private fun initView(context: Context?) {
nativeInterface = NativeInterface()
orientationSensor = app?.let { context?.let { it1 -> OrientationSensor(it1, it) } }
setEGLContextClientVersion(2)
setEGLConfigChooser(8, 8, 8, 8, 16, 0)
renderer = GLES20Renderer2(null, nativeInterface, orientationSensor, Settings.Current)
holder?.setFormat(PixelFormat.TRANSLUCENT)
setZOrderOnTop(true)
setRenderer(renderer)
renderer?.setInitialScreenSize(300, 200)
nativeInterface?.setAssetManager(context?.assets)
nativeInterface?.onCreate(300, 200, true)
context?.apply {
runBlocking {
initPresets()
QualitySetting.init()
Settings.Current?.let { loadSettingsFromMap(it, DEFAULT_SETTING, true) }
if (getNumLwpRuns(this@apply) == 0) {
presetList?.get(TinyDB(this@apply).getInt(SELECTED_PRESET, 0))?.setting?.let {
Settings.Current?.setFromInternalPreset(it)
QualitySetting.setQualitySettingsFromPerf(it, nativeInterface)
}
}
} }
Settings.Current?.process()
Settings.Current?.let { nativeInterface?.updateSettings(it) }
renderMode = RENDERMODE_CONTINUOUSLY
}
override fun onTouchEvent(motionEvent: MotionEvent): Boolean {
InputBuffer.Instance.addEvent(motionEvent)
return true
}
override fun onPause() {
super.onPause()
}
override fun onResume() {
super.onResume()
}
} | 0 | Kotlin | 0 | 1 | c07827113483608964d9b931a788b2f0a585f843 | 2,299 | FluidTouch | The Unlicense |
feature_curation_list/src/main/java/com/phicdy/mycuration/curationlist/CurationListView.kt | phicdy | 24,188,186 | false | {"Kotlin": 688608, "HTML": 1307, "Shell": 1127} | package com.phicdy.mycuration.presentation.view
import com.phicdy.mycuration.entity.Curation
interface CurationListView {
fun startEditCurationActivity(editCurationId: Int)
fun setNoRssTextToEmptyView()
fun registerContextMenu()
fun initListBy(curations: List<Curation>)
fun showRecyclerView()
fun hideRecyclerView()
fun showEmptyView()
fun hideEmptyView()
}
| 46 | Kotlin | 9 | 30 | 052bc1776a80df0457399e96e001c9ad527d53f2 | 393 | MyCuration | The Unlicense |
app/src/main/java/com/example/buahin/repository/CategoryRepository.kt | SimiPrambos | 440,445,933 | false | null | /*
* Copyright (C) 2021 SimiPrambos <<EMAIL>> - All Rights Reserved
* CategoryRepository.kt
* Buahin <https://github.com/SimiPrambos/buahin.git>
* UI Design by Afsar <https://www.figma.com/community/file/882645007956337261>
*/
package com.example.buahin.repository
import com.example.buahin.model.Category
import com.example.buahin.model.Category.Companion.toCategory
import com.google.firebase.firestore.FirebaseFirestore
import kotlinx.coroutines.tasks.await
class CategoryRepository(private val firestore: FirebaseFirestore) {
suspend fun findSummary(): List<Category> {
return try {
firestore.collection("categories").limit(3).get()
.await().documents.mapNotNull { it.toCategory() }
} catch (e: Exception) {
emptyList()
}
}
suspend fun findAll(): List<Category> {
return try {
firestore.collection("categories").get()
.await().documents.mapNotNull { it.toCategory() }
} catch (e: Exception) {
emptyList()
}
}
} | 0 | Kotlin | 0 | 0 | 5c6a2cd40ac9e96dbfb61eefba9654b5f0fd6636 | 1,067 | buahin | MIT License |
app/src/main/java/chenmc/sms/data/ExpressCodeSms.kt | zhidao8 | 105,611,156 | false | null | package chenmc.sms.data
/**
* 取件码短信
* Created by 明明 on 2017/7/1.
*/
class ExpressCodeSms : CodeSms {
constructor()
constructor(code: String) : super(code)
constructor(serviceProvider: String, expressCode: String) : super(serviceProvider, expressCode)
constructor(serviceProvider: String, code: String, content: String) : super(serviceProvider, code, content)
}
| 3 | Kotlin | 10 | 69 | 8c83419e2574c464be5cdd7d2e7a50e4beb08ee9 | 390 | SmsCodeHelper | Apache License 2.0 |
app/src/main/java/com/example/reservations/ui/screens/ClientSelectionScreen.kt | jameswills | 834,645,101 | false | {"Kotlin": 29138} | package com.example.reservations.ui.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.material3.BottomAppBar
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.example.reservations.R
import com.example.reservations.viewmodels.ClientSelectionViewModel
import com.example.reservations.fakes.FakeClientSelectionViewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ClientSelectionScreen(navController: NavController, viewModel: ClientSelectionViewModel) {
var selectedTimeIndex by remember { mutableStateOf<Int?>(null) }
Scaffold(
topBar = {
TopAppBar(title = { Text(stringResource(R.string.client_selection_toolbar_title)) })
},
bottomBar = {
BottomAppBar {
ConfirmButton(
navController = navController,
selectedTimeIndex = selectedTimeIndex
)
}
}
) { innerPadding ->
viewModel.providerAvailability.value?.let { providerAvailability ->
Column(
modifier = Modifier
.padding(innerPadding)
.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
providerAvailability.availableSlots.forEach { availableSlots ->
TitleText(
providerName = providerAvailability.providerName,
date = availableSlots.date
)
LazyVerticalGrid(
modifier = Modifier
.padding(innerPadding)
.fillMaxSize(),
columns = GridCells.Fixed(2),
contentPadding = PaddingValues(8.dp),
verticalArrangement = Arrangement.spacedBy(4.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
val filteredTimeSlots = viewModel.getFilteredTimeSlots(availableSlots)
if (filteredTimeSlots.isNotEmpty()) {
itemsIndexed(items = filteredTimeSlots) { index, timeSlot ->
SelectableTimeSlotButton(
timeSlot = timeSlot.availableTime,
isSelected = selectedTimeIndex == index,
index = index,
onSelect = { newIndex ->
selectedTimeIndex =
if (selectedTimeIndex == newIndex) null else newIndex
viewModel.updateSelection(
timeSlot.availableTime,
availableSlots.date,
providerAvailability.providerName
)
}
)
}
} else {
item(span = { GridItemSpan(2) }) {
NoAppointmentsAvailableText()
}
}
}
}
}
}
}
}
@Composable
private fun TitleText(providerName: String, date: String) {
Text(
modifier = Modifier.padding(8.dp),
text = stringResource(R.string.client_selection_provider_title, providerName, date),
textAlign = TextAlign.Center
)
}
@Composable
private fun SelectableTimeSlotButton(
timeSlot: String,
isSelected: Boolean,
index: Int,
onSelect: (Int) -> Unit
) {
OutlinedButton(
onClick = { onSelect(index) },
modifier = Modifier.padding(4.dp),
colors = ButtonDefaults.outlinedButtonColors(
contentColor = if (isSelected) Color.White else Color.Black,
containerColor = if (isSelected) Color.Blue else Color.Transparent
)
) {
Text(text = timeSlot)
}
}
@Composable
private fun NoAppointmentsAvailableText() {
Text(
text = stringResource(R.string.client_selection_no_appts_available),
modifier = Modifier.padding(16.dp),
textAlign = TextAlign.Center,
fontWeight = FontWeight.Bold,
style = TextStyle(fontSize = 24.sp)
)
}
@Composable
private fun ConfirmButton(
navController: NavController,
selectedTimeIndex: Int? = null,
) {
Button(
onClick = { navController.navigate("confirmation") },
enabled = selectedTimeIndex != null,
modifier = Modifier.fillMaxWidth()
) {
Text(
modifier = Modifier.padding(8.dp),
text = stringResource(R.string.client_selection_continue_button)
)
}
}
@Preview
@Composable
private fun ClientSelectionScreenScreenPreview() {
ClientSelectionScreen(
navController = NavController(LocalContext.current),
viewModel = FakeClientSelectionViewModel()
)
}
| 0 | Kotlin | 0 | 0 | c5746e130f85a5068573ef3b03a1d5f36a6cd57f | 6,678 | Henry-Reservation | Apache License 2.0 |
utils/jwt/src/main/kotlin/io/bluetape4k/jwt/codec/Lz4Codec.kt | debop | 625,161,599 | false | {"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82} | package io.bluetape4k.jwt.codec
import io.bluetape4k.io.compressor.Compressors
import io.bluetape4k.io.compressor.LZ4Compressor
import io.bluetape4k.logging.KLogging
import io.bluetape4k.support.unsafeLazy
import io.jsonwebtoken.impl.compression.AbstractCompressionCodec
class Lz4Codec: AbstractCompressionCodec() {
companion object: KLogging() {
const val ALGORITHM = "LZ4"
}
private val lz4: LZ4Compressor by unsafeLazy { Compressors.LZ4 }
override fun getAlgorithmName(): String {
return ALGORITHM
}
override fun doCompress(payload: ByteArray?): ByteArray {
return lz4.compress(payload)
}
override fun doDecompress(compressed: ByteArray?): ByteArray {
return lz4.decompress(compressed)
}
}
| 0 | Kotlin | 0 | 1 | ce3da5b6bddadd29271303840d334b71db7766d2 | 768 | bluetape4k | MIT License |
src/main/kotlin/br/anhembi/funmodechild/service/PaymentService.kt | svbgabriel | 199,749,038 | false | {"Kotlin": 43080, "JavaScript": 12575} | package br.anhembi.funmodechild.service
import br.anhembi.funmodechild.model.common.PaymentException
import br.anhembi.funmodechild.model.request.PaymentRequest
import br.anhembi.funmodechild.model.response.PaymentResponse
import br.anhembi.funmodechild.repository.OrderRepository
import br.anhembi.funmodechild.repository.PaymentRepository
import org.springframework.stereotype.Service
@Service
class PaymentService(private val paymentRepository: PaymentRepository, private val orderRepository: OrderRepository) {
fun makePayment(request: PaymentRequest, orderId: String, customerId: String): PaymentResponse {
val order = orderRepository.findByIdAndCustomerId(orderId, customerId)
?: throw PaymentException("Order doesn't match the customer")
val payment = request.toDoc(order)
val savedPayment = paymentRepository.save(payment)
return savedPayment.toApiResponse()
}
}
| 3 | Kotlin | 0 | 0 | 35c91197e3709f60073766048bf295c51dee6eae | 929 | fun-mode-child | MIT License |
RefactoringToDesignPatterns/FacadePatternPractice/task/src/main/kotlin/jetbrains/refactoring/course/patterns/Main.kt | Nikolay1580 | 774,957,920 | false | {"Kotlin": 16061} | package jetbrains.refactoring.course.patterns
fun main(args: Array<String>) {
val originalVideoName = args[0]
val processedVideoName = args[1]
val videoConverter = VideoConversionFacade()
val video = videoConverter.getVideoLoader().loadVideo(originalVideoName)
val processedVideo = videoConverter.getVideoProcessor().processVideo(video)
val encodedVideo = videoConverter.getVideoEncoder().encodeVideo(processedVideo)
videoConverter.getVideoSaver().saveVideo(encodedVideo, processedVideoName)
}
| 0 | Kotlin | 0 | 0 | c8ca3ab60fd7ce382ac10c28b9e13c9e9a5d10da | 525 | Refactoring_Course-2 | MIT License |
pluto-no-op/src/main/java/com/mocklets/pluto/modules/exceptions/ANRException.kt | mocklets | 459,260,997 | false | null | package com.mocklets.pluto.modules.exceptions
import androidx.annotation.Keep
@Keep
class ANRException(thread: Thread) : Exception("ANR detected in Pluto-No-Op") {
val threadStateMap: String
init {
stackTrace = thread.stackTrace
threadStateMap = ""
}
}
| 0 | null | 2 | 8 | 87dc5a27272e0fc5c38e042fa95689a143ae5446 | 285 | pluto | Apache License 2.0 |
product-farm-api/src/main/kotlin/io/github/ayushmaanbhav/productFarm/constant/ProductTemplateType.kt | ayushmaanbhav | 633,602,472 | false | {"Kotlin": 739672, "Shell": 1175, "Dockerfile": 1119} | package io.github.ayushmaanbhav.productFarm.constant
enum class ProductTemplateType {
INSURANCE
}
| 0 | Kotlin | 0 | 0 | ee3f2aa48e9bf764d693436a44bf99ac92408bf3 | 103 | product-farm | Apache License 2.0 |
coordinates/src/commonMain/kotlin/geo/serializers/LatLngAltSerializer.kt | aSoft-Ltd | 694,870,214 | false | {"Kotlin": 15901} | package geo.serializers
import geo.LatLngAlt
import geo.internal.LatLngAltImpl
import kotlinx.serialization.KSerializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.descriptors.buildClassSerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
object LatLngAltSerializer : KSerializer<LatLngAlt> {
override val descriptor: SerialDescriptor = buildClassSerialDescriptor("geo.LatLngAlt")
private val surrogate by lazy { LatLngAltImpl.serializer() }
override fun deserialize(decoder: Decoder): LatLngAlt = decoder.decodeSerializableValue(surrogate)
override fun serialize(encoder: Encoder, value: LatLngAlt) = encoder.encodeSerializableValue(surrogate, value.toImpl())
private fun LatLngAlt.toImpl() = LatLngAltImpl(lat, lng, alt)
} | 0 | Kotlin | 0 | 0 | 191d605ede8135525b0da0024a00a8b6a9cd59fb | 848 | geo-api | MIT License |
src/commonMain/kotlin/mapgen/predicate/CellContainedIn2d.kt | stewsters | 272,030,492 | false | null | package mapgen.predicate
//class CellContainedIn2d<T>(container: Container2d) : CellPredicate2d<Any?> {
// var container: Container2d
// fun belongs(generatedMap2d: Matrix2d<T>, x: Int, y: Int): Boolean {
// return container.contains(x, y)
// }
//
// init {
// this.container = container
// }
//} | 1 | Kotlin | 1 | 9 | c5b657801d325e2072dad9736db24144d29eddf8 | 327 | dungeon | MIT License |
buildSrc/src/main/kotlin/Shared.kt | gbaldeck | 94,640,750 | false | null | import org.gradle.api.Project
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.MavenPom
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.kotlin.dsl.getByType
import org.gradle.kotlin.dsl.withType
fun MavenPom.defaultPom() {
name.set("snabbdom-kotlin")
description.set("Kotlin definition files for the Snabbdom virtual DOM library.")
url.set("https://github.com/gbaldeck/snabbdom-kotlin")
licenses {
license {
name.set("MIT")
url.set("https://opensource.org/licenses/MIT")
}
}
developers {
developer {
id.set("gbaldeck")
name.set("<NAME>")
}
}
scm {
url.set("https://github.com/gbaldeck/snabbdom-kotlin.git")
connection.set("scm:git:git://github.com/gbaldeck/snabbdom-kotlin.git")
developerConnection.set("scm:git:git://github.com/gbaldeck/snabbdom-kotlin.git")
}
}
fun Project.setupPublication() {
plugins.apply("maven-publish")
extensions.getByType<PublishingExtension>().run {
publications.withType<MavenPublication>().all {
pom {
defaultPom()
}
}
repositories {
maven {
url = uri("https://api.bintray.com/maven/rjaros/kotlin/${project.name}/;publish=0;override=1")
credentials {
username = findProperty("buser")?.toString()
password = findProperty("bkey")?.toString()
}
}
}
}
}
| 0 | Kotlin | 1 | 4 | 3de0752966e4b4231efe3200b140142565520087 | 1,580 | snabbdom-kotlin | MIT License |
generators/app/templates/presentation/src/main/java/com/kristal/generator/presentation/view/activity/HomeActivity.kt | rochze | 132,592,386 | true | {"Kotlin": 180920, "JavaScript": 6984, "Java": 809} | package <%= appPackage %>.presentation.view.activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import <%= appPackage %>.presentation.example.recyclerview.view.fragment.RecyclerViewFragment
import <%= appPackage %>.presentation.view.activity.base.BaseActivity
class HomeActivity : BaseActivity() {
override fun setup(): Setup = Setup(TAG)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
addFragment(RecyclerViewFragment())
}
companion object {
val TAG = HomeActivity::class.java.simpleName!!
fun getIntent(context: Context): Intent = Intent(context, HomeActivity::class.java)
}
}
| 0 | Kotlin | 0 | 0 | 4133b44eb99c594155111fdb3be0b72730c0d6a2 | 720 | Generator-Kristal | The Unlicense |
service/src/main/kotlin/com/spring/service/controller/CustomerHttpController.kt | DavidVasconcelos | 554,422,167 | false | null | package com.spring.service.controller
import com.spring.service.entity.CustomerEntity
import com.spring.service.repository.CustomerRepository
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.ResponseBody
import reactor.core.publisher.Flux
@Controller
@ResponseBody
class CustomerHttpController(val customerRepository: CustomerRepository) {
@GetMapping("/customers")
fun get(): Flux<CustomerEntity> = customerRepository.findAll()
} | 0 | Kotlin | 0 | 0 | 66906b7e17c73dc4561252fb5948319b3230f2e3 | 546 | spring-kubernetes-native | Apache License 2.0 |
lib/src/main/java/me/wsj/lib/utils/DateUtil.kt | codingwatching | 391,791,972 | false | null | package me.wsj.lib.utils
import java.text.SimpleDateFormat
import java.util.*
class DateUtil {
companion object {
@JvmStatic
fun getNowHour(): Int {
return Calendar.getInstance().get(Calendar.HOUR_OF_DAY)
}
/**
* HH:mm
*/
@JvmStatic
fun getNowTime(): String {
val simpleDateFormat = SimpleDateFormat("HH:mm")
// 获取当前时间
val date = Date(System.currentTimeMillis());
return simpleDateFormat.format(date)
}
}
} | 0 | null | 0 | 1 | 38d80055d01c4edcd69637b522511e7d1782a2f6 | 553 | FengYunWeather | Apache License 2.0 |
lib/src/main/java/me/wsj/lib/utils/DateUtil.kt | codingwatching | 391,791,972 | false | null | package me.wsj.lib.utils
import java.text.SimpleDateFormat
import java.util.*
class DateUtil {
companion object {
@JvmStatic
fun getNowHour(): Int {
return Calendar.getInstance().get(Calendar.HOUR_OF_DAY)
}
/**
* HH:mm
*/
@JvmStatic
fun getNowTime(): String {
val simpleDateFormat = SimpleDateFormat("HH:mm")
// 获取当前时间
val date = Date(System.currentTimeMillis());
return simpleDateFormat.format(date)
}
}
} | 0 | null | 0 | 1 | 38d80055d01c4edcd69637b522511e7d1782a2f6 | 553 | FengYunWeather | Apache License 2.0 |
app/src/main/java/eu/kanade/presentation/category/MangaCategoryScreen.kt | aniyomiorg | 358,887,741 | false | null | package eu.kanade.presentation.category
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import eu.kanade.presentation.category.components.CategoryFloatingActionButton
import eu.kanade.presentation.category.components.CategoryListItem
import eu.kanade.tachiyomi.ui.category.anime.AnimeCategoryScreenState
import tachiyomi.domain.category.model.Category
import tachiyomi.i18n.MR
import tachiyomi.presentation.core.components.material.Scaffold
import tachiyomi.presentation.core.components.material.padding
import tachiyomi.presentation.core.components.material.topSmallPaddingValues
import tachiyomi.presentation.core.screens.EmptyScreen
import tachiyomi.presentation.core.util.plus
@Composable
fun AnimeCategoryScreen(
state: AnimeCategoryScreenState.Success,
onClickCreate: () -> Unit,
onClickRename: (Category) -> Unit,
onClickHide: (Category) -> Unit,
onClickDelete: (Category) -> Unit,
onClickMoveUp: (Category) -> Unit,
onClickMoveDown: (Category) -> Unit,
) {
val lazyListState = rememberLazyListState()
Scaffold(
floatingActionButton = {
CategoryFloatingActionButton(
lazyListState = lazyListState,
onCreate = onClickCreate,
)
},
) { paddingValues ->
if (state.isEmpty) {
EmptyScreen(
stringRes = MR.strings.information_empty_category,
modifier = Modifier.padding(paddingValues),
)
return@Scaffold
}
CategoryContent(
categories = state.categories,
lazyListState = lazyListState,
paddingValues = paddingValues + topSmallPaddingValues + PaddingValues(
horizontal = MaterialTheme.padding.medium,
),
onClickRename = onClickRename,
onClickHide = onClickHide,
onClickDelete = onClickDelete,
onMoveUp = onClickMoveUp,
onMoveDown = onClickMoveDown,
)
}
}
@Composable
private fun CategoryContent(
categories: List<Category>,
lazyListState: LazyListState,
paddingValues: PaddingValues,
onClickRename: (Category) -> Unit,
onClickHide: (Category) -> Unit,
onClickDelete: (Category) -> Unit,
onMoveUp: (Category) -> Unit,
onMoveDown: (Category) -> Unit,
) {
LazyColumn(
state = lazyListState,
contentPadding = paddingValues,
verticalArrangement = Arrangement.spacedBy(MaterialTheme.padding.small),
) {
itemsIndexed(
items = categories,
key = { _, category -> "category-${category.id}" },
) { index, category ->
CategoryListItem(
modifier = Modifier.animateItemPlacement(),
category = category,
canMoveUp = index != 0,
canMoveDown = index != categories.lastIndex,
onMoveUp = onMoveUp,
onMoveDown = onMoveDown,
onRename = { onClickRename(category) },
onHide = { onClickHide(category) },
onDelete = { onClickDelete(category) },
)
}
}
}
| 234 | null | 315 | 4,992 | 823099f775ef608b7c11f096da1f50762dab82df | 3,613 | aniyomi | Apache License 2.0 |
main/java/gameRPG/src/org/RPG/www/game/item/Item.kt | dragoues | 344,530,130 | false | null | package org.academiadecodigo.www.game.item
abstract class Item(val name: String, val bonus: Int, itemKind: KindOfItem) :
org.academiadecodigo.www.game.GameObjects() {
private val itemKind: KindOfItem
fun getItemKind(): KindOfItem {
return itemKind
}
override fun toString(): String {
return name
}
init {
this.itemKind = itemKind
}
} | 0 | Kotlin | 0 | 0 | af4677748e15713e38c037eb6e80e9985dbdad8e | 392 | game_app_KT | Apache License 2.0 |
app/src/main/java/ru/igla/duocamera/ui/widgets/AboutDialog.kt | iglaweb | 414,899,591 | false | {"Kotlin": 85927, "Java": 2752} | package ru.igla.duocamera.ui.widgets
import android.app.Dialog
import android.os.Build
import android.os.Bundle
import android.text.Html
import android.text.Spanned
import androidx.annotation.Nullable
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentActivity
import ru.igla.duocamera.BuildConfig
import ru.igla.duocamera.R
import timber.log.Timber
import java.util.*
class AboutDialog : DialogFragment() {
companion object {
private const val TAG = "[ABOUT_DIALOG]"
fun show(context: FragmentActivity) =
AboutDialog().show(context.supportFragmentManager, TAG)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val body = String.format(
Locale.US,
getString(R.string.about_body)
)
return AlertDialog.Builder(requireContext())
.setTitle(getString(R.string.about_title, BuildConfig.VERSION_NAME))
.setMessage(fromHtml(body))
.setCancelable(true)
.create()
}
@Suppress("DEPRECATION")
@Nullable
private fun fromHtml(source: String): Spanned? {
try {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(source, Html.FROM_HTML_MODE_LEGACY)
} else {
Html.fromHtml(source)
}
} catch (e: Exception) {
Timber.e(e)
}
return null
}
} | 1 | Kotlin | 0 | 6 | 5743d5c22fdc96d2d2f0f0e2b00e17ee4c75147e | 1,510 | DuoCamera | Apache License 2.0 |
app/src/main/java/com/example/rocketreserver/di/RepositoryModule.kt | artyomefimov | 357,857,288 | false | null | package com.example.rocketreserver.di
import com.example.rocketreserver.data.mapper.LaunchDetailsMapper
import com.example.rocketreserver.data.mapper.LaunchListMapper
import com.example.rocketreserver.data.mapper.LoginDetailsMapper
import com.example.rocketreserver.data.repository.SpaceXRepositoryImpl
import com.example.rocketreserver.data.token.TokenStorage
import com.example.rocketreserver.data.token.TokenStorageImpl
import com.example.rocketreserver.domain.mapper.Mapper
import com.example.rocketreserver.domain.repository.SpaceXRepository
import kotlinx.coroutines.Dispatchers
import org.koin.core.qualifier.named
import org.koin.dsl.bind
import org.koin.dsl.module
private const val LAUNCH_LIST_MAPPER = "LAUNCH_LIST_MAPPER"
private const val LAUNCH_DETAILS_MAPPER = "LAUNCH_DETAILS_MAPPER"
private const val LOGIN_DETAILS_MAPPER = "LOGIN_DETAILS_MAPPER"
fun repositoryModule() = module {
single(qualifier = named(LAUNCH_LIST_MAPPER)) {
LaunchListMapper()
} bind Mapper::class
single(qualifier = named(LAUNCH_DETAILS_MAPPER)) {
LaunchDetailsMapper()
} bind Mapper::class
single(qualifier = named(LOGIN_DETAILS_MAPPER)) {
LoginDetailsMapper()
} bind Mapper::class
single<TokenStorage> { TokenStorageImpl(context = get()) }
single<SpaceXRepository> {
SpaceXRepositoryImpl(
dispatcher = Dispatchers.IO,
apolloClient = get(),
launchListMapper = get(qualifier = named(LAUNCH_LIST_MAPPER)),
listDetailsMapper = get(qualifier = named(LAUNCH_DETAILS_MAPPER)),
loginDetailsMapper = get(qualifier = named(LOGIN_DETAILS_MAPPER)),
tokenStorage = get()
)
}
}
| 0 | Kotlin | 0 | 0 | 69bccb1dec438e71d3f433a22a477b51ba32b0f9 | 1,706 | spacex_graphql | MIT License |
usvm-core/src/main/kotlin/org/usvm/ps/StateLoopStatistic.kt | UnitTestBot | 586,907,774 | false | {"Kotlin": 2623144, "Java": 476836} | package org.usvm.ps
import kotlinx.collections.immutable.PersistentList
import kotlinx.collections.immutable.persistentListOf
import org.usvm.PathNode
import org.usvm.UState
class StateLoopStatistic<Stmt, Method, Loop : Any, State : UState<*, Method, Stmt, *, *, State>>(
private val loopTracker: StateLoopTracker<Loop, Stmt, State>,
) {
private val emptyStatsFrames = hashMapOf<Method, StateStackFrameStats<Method, Stmt, Loop>>()
fun updateStats(referenceStats: StateStats<Method, Stmt, Loop>, state: State): StateStats<Method, Stmt, Loop> {
val stats = updateStackFrames(referenceStats, state)
val stateLocation = state.pathNode
val loop = loopTracker.findLoopEntrance(stateLocation.statement)
if (loop == null) {
return stats.copy(forksCount = state.forkPoints.depth)
}
val currentFrame = stats.frames.last()
val loopStats = currentFrame.getLoopStats(loop)
val updatedLoopStats = if (loopStats == null) {
// first loop iteration
LoopStats(loop, stateLocation, iterations = 0, nonConcreteIterations = 0)
} else {
val forkedInPreviousLoopIteration = loopIterationForkedInPreviousIteration(state, loopStats, loop)
var nonConcreteIterations = loopStats.nonConcreteIterations
if (forkedInPreviousLoopIteration) {
nonConcreteIterations++
}
LoopStats(loop, stateLocation, loopStats.iterations + 1, nonConcreteIterations)
}
val updatedFrame = currentFrame.updateLoopStats(updatedLoopStats)
return stats.copy(
frames = stats.frames.let { frames -> frames.set(frames.lastIndex, updatedFrame) },
forksCount = state.forkPoints.depth
)
}
/**
* Check if the state has forks during last [loop] iteration, that
* can affect the [loop] iteration number.
* */
private fun loopIterationForkedInPreviousIteration(
state: State,
loopStats: LoopStats<Stmt, Loop>,
loop: Loop
): Boolean {
var forkPoint = state.forkPoints
while (forkPoint.depth > 0 && forkPoint.statement.depth >= loopStats.previousLoopEnter.depth) {
if (loopTracker.isLoopIterationFork(loop, forkPoint.statement.statement)) {
return true
}
forkPoint = forkPoint.parent ?: break
}
return false
}
/**
* Ensure that [stats] stack frames match [state] stack frames.
* */
private fun updateStackFrames(stats: StateStats<Method, Stmt, Loop>, state: State): StateStats<Method, Stmt, Loop> {
val frames = stats.frames.builder()
val stack = state.callStack
var idx = 0
var stackFramesMatch = true
while (idx < stack.size) {
val method = stack[idx].method
if (stackFramesMatch && idx < frames.size && method == frames[idx].method) {
idx++
continue
}
stackFramesMatch = false
val emptyFrame = emptyStatsFrames.getOrPut(method) {
StateStackFrameStats(method, loops = null, maxNonConcreteIteration = 0)
}
if (idx < frames.size) {
frames[idx] = emptyFrame
} else {
frames.add(emptyFrame)
}
idx++
}
while (frames.size > idx) {
frames.removeLast()
}
val updatedFrames = frames.build()
if (updatedFrames === stats.frames) {
return stats
}
return stats.copy(frames = updatedFrames)
}
companion object {
private val rootStats = StateStats<Any?, Any?, Any?>(frames = persistentListOf(), forksCount = 0)
@Suppress("UNCHECKED_CAST")
fun <Method, Stmt, Loop> rootStats(): StateStats<Method, Stmt, Loop> =
rootStats as StateStats<Method, Stmt, Loop>
}
}
/**
* Single loop statistic.
*
* [previousLoopEnter] -- start of the previous iteration.
* [iterations] -- total number of the iterations (concrete and non-concrete).
* [nonConcreteIterations] -- number of iterations that can be affected via some symbolic values.
* */
data class LoopStats<Stmt, Loop>(
val loop: Loop,
val previousLoopEnter: PathNode<Stmt>,
val iterations: Int,
val nonConcreteIterations: Int
)
/**
* Loop stats for a single state stack frame.
*
* [loops] -- compressed loop stats representation.
* null -- method has no loops, or state didn't enter any loop on the current frame.
* LoopStats -- state enter only a single loop on the current frame.
* Array<LoopStats> -- state enter many loops.
* */
data class StateStackFrameStats<Method, Stmt, Loop>(
val method: Method,
private val loops: Any? = null,
val maxNonConcreteIteration: Int,
) {
fun updateLoopStats(stats: LoopStats<Stmt, Loop>): StateStackFrameStats<Method, Stmt, Loop> =
StateStackFrameStats(
method = method,
loops = updateLoops(stats),
maxNonConcreteIteration = maxOf(maxNonConcreteIteration, stats.nonConcreteIterations)
)
@Suppress("UNCHECKED_CAST")
fun getLoopStats(loop: Loop): LoopStats<Stmt, Loop>? {
val loopsStats = loops ?: return null
if (loopsStats is LoopStats<*, *>) {
return if (loopsStats.loop == loop) loopsStats as LoopStats<Stmt, Loop> else null
}
loopsStats as Array<LoopStats<*, *>>
for (stats in loopsStats) {
if (stats.loop == loop) return stats as LoopStats<Stmt, Loop>
}
return null
}
@Suppress("UNCHECKED_CAST")
private fun updateLoops(stats: LoopStats<Stmt, Loop>): Any {
val loopsStats = loops ?: return stats
if (loopsStats is LoopStats<*, *>) {
if (loopsStats.loop == stats.loop) return stats
return arrayOf(loopsStats, stats)
}
loopsStats as Array<LoopStats<*, *>>
for (i in loopsStats.indices) {
if (loopsStats[i].loop == stats.loop) {
return loopsStats.copyOf().also { it[i] = stats }
}
}
val result = loopsStats.copyOf(loopsStats.size + 1)
result[result.lastIndex] = stats
return result
}
}
data class StateStats<Method, Stmt, Loop>(
val frames: PersistentList<StateStackFrameStats<Method, Stmt, Loop>>,
val forksCount: Int,
) {
val maxLoopIteration: Int
get() = frames.maxOfOrNull { it.maxNonConcreteIteration } ?: 0
}
| 36 | Kotlin | 4 | 9 | 819268c3c77c05d798891be826164bbede63fdfb | 6,596 | usvm | Apache License 2.0 |
tapi/src/main/java/inc/brody/tapi/TApi.kt | DimaBrody | 191,914,846 | false | null | package inc.brody.tapi
import android.content.Context
import android.util.Log
import inc.brody.tapi.data.State
import inc.brody.tapi.data.appdata.TConstants
import inc.brody.tapi.requests.TCheckAuthenticationCode
import inc.brody.tapi.requests.TCheckAuthenticationPassword
import inc.brody.tapi.requests.TGetCurrentState
import inc.brody.tapi.requests.TSetAuthenticationPhoneNumber
import inc.brody.tapi.utils.Session
import inc.brody.tapi.utils.TelegramAPIController
import org.drinkless.td.libcore.telegram.TdApi
class TApi {
private val TAG = "TApi"
companion object {
private var instance: TApi? = null
@JvmStatic
fun init(context: Context): TApi =
instance ?: synchronized(this) {
instance = TApi()
TelegramAPIController.init()
Session.init(context)
instance!!.initInternalProcesses()
return instance!!
}
}
private var _authState: Int = -1
set(value) {
stateInstance.value = value
stateInstance.listener?.onChange()
field = value
}
/*private var _signedState: Int = -1
set(value) {
signedInstance.value = value
signedInstance.listener?.onChange()
field = value
}
private val signedInstance = State()
val signedState: State
get() = signedInstance*/
private val stateInstance = State()
val authState: State
get() = stateInstance
fun sendCodeOnPhone(phone: String) {
Session.myPhone = phone
TSetAuthenticationPhoneNumber {}
}
fun loginWithPassword(password: String) {
Session.myPassword = password
TCheckAuthenticationPassword {}
}
fun loginWithReceivedCode(code: String) {
Session.myCode = code
TCheckAuthenticationCode {
Log.d("TApi", it.toString() + "Hurray")
}
}
fun logout() = Session.confirmLogout()
fun initInternalProcesses() {
TGetCurrentState (
onError = {
authState.error = it
_authState = TConstants.AUTH_ERROR
},
onSuccess = {
when (it) {
is TdApi.Updates ->
_authState = Session.checkAuthState(
(it.updates[0]) as TdApi.UpdateAuthorizationState
)
is TdApi.UpdateAuthorizationState -> {
_authState = Session.checkAuthState(it)
}
else -> {
// Log.d("TApiTEST", it.toString())
}
}
})
}
} | 1 | null | 1 | 4 | 43204081e9dd62c14eb918ca0736b9470f5e9894 | 2,746 | TApi | MIT License |
pensjon-brevbaker/src/main/kotlin/no/nav/pensjon/brev/maler/ProductionTemplates.kt | navikt | 375,334,697 | false | {"Kotlin": 3421494, "TypeScript": 519756, "TeX": 12813, "Shell": 9251, "CSS": 8104, "Python": 4661, "JavaScript": 4382, "Dockerfile": 2406, "HTML": 1053} | package no.nav.pensjon.brev.api
import no.nav.pensjon.brev.api.model.maler.BrevbakerBrevdata
import no.nav.pensjon.brev.api.model.maler.RedigerbarBrevdata
import no.nav.pensjon.brev.maler.*
import no.nav.pensjon.brev.maler.adhoc.*
import no.nav.pensjon.brev.maler.redigerbar.InformasjonOmSaksbehandlingstid
import no.nav.pensjon.brev.maler.ufoereBrev.VarselSaksbehandlingstidAuto
import no.nav.pensjon.brev.template.AutobrevTemplate
import no.nav.pensjon.brev.template.RedigerbarTemplate
object ProductionTemplates {
val autobrev: Set<AutobrevTemplate<BrevbakerBrevdata>> = setOf(
AdhocAlderspensjonFraFolketrygden,
AdhocGjenlevendEtter1970,
AdhocUfoeretrygdEtterbetalingDagpenger,
AdhocUfoeretrygdKombiDagpenger,
AdhocUfoeretrygdKombiDagpengerInntektsavkorting,
AdhocVarselOpphoerMedHvilendeRett,
ForhaandsvarselEtteroppgjoerUfoeretrygdAuto,
OmsorgEgenAuto,
OpphoerBarnetilleggAuto,
OpptjeningVedForhoeyetHjelpesats,
UfoerOmregningEnslig,
UngUfoerAuto,
VarselSaksbehandlingstidAuto,
)
val redigerbare: Set<RedigerbarTemplate<out RedigerbarBrevdata<*, *>>> = setOf(
InformasjonOmSaksbehandlingstid
)
} | 6 | Kotlin | 3 | 1 | ec81ca12f0bc17173b0e38e43441ddde8ae70922 | 1,231 | pensjonsbrev | MIT License |
libraries/data/src/main/java/com/zizohanto/android/currencyconverter/data/repository/ConverterRepositoryImpl.kt | zizoh | 315,755,201 | false | null | package com.zizohanto.android.currencyconverter.data.repository
import com.zizohanto.android.currencyconverter.data.contract.cache.ConverterCache
import com.zizohanto.android.currencyconverter.data.contract.remote.ConverterRemote
import com.zizohanto.android.currencyconverter.data.models.HistoricalDataEntity
import com.zizohanto.android.currencyconverter.domain.factory.DomainFactory
import com.zizohanto.android.currencyconverter.domain.models.HistoricalData
import com.zizohanto.android.currencyconverter.domain.repository.ConverterRepository
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import javax.inject.Inject
class ConverterRepositoryImpl @Inject constructor(
private val converterRemote: ConverterRemote,
private val converterCache: ConverterCache
) : ConverterRepository {
override fun getSymbols(): Flow<List<String>> {
return flow {
val symbolsCache = converterCache.getSymbols()
if (symbolsCache.isNotEmpty()) {
emit(symbolsCache)
return@flow
}
val symbolsRemote: List<String> = converterRemote.getSymbols()
converterCache.saveSymbols(symbolsRemote)
emit(symbolsRemote)
}
}
override fun getRates(
date: String,
amount: Double,
base: String,
target: String
): Flow<HistoricalData> {
return flow {
val dataFromCache: HistoricalDataEntity? =
converterCache.getHistoricalData(base, target)
if (dataFromCache != null) {
val historicalData = getHistoricalData(dataFromCache, amount)
emit(historicalData)
}
val id = "${base}${target}"
val dataFromRemote: HistoricalDataEntity =
converterRemote.getHistoricalData(date, base, target).copy(id = id)
converterCache.saveHistoricalData(dataFromRemote)
val historicalData = getHistoricalData(dataFromRemote, amount)
emit(historicalData)
}
}
override suspend fun getRatesWithinPeriod(
dates: List<String>,
base: String,
target: String
): List<HistoricalData> {
// make stubNetworkCall false to make network call to get historical data
val stubNetworkCall = true
return if (stubNetworkCall) DomainFactory.makeHistoricalDataForPeriod(dates)
else makeNetworkCall(dates, base, target)
}
private suspend fun makeNetworkCall(
dates: List<String>,
base: String,
target: String
): List<HistoricalData> {
return coroutineScope {
return@coroutineScope (dates).map { date ->
async { converterRemote.getHistoricalData(date, base, target) }
}.awaitAll().map { getHistoricalData(it, 1.0) }
}
}
fun getHistoricalData(
historicalDataFromCache: HistoricalDataEntity,
amount: Double
): HistoricalData {
val convertedRate: Double = getConversion(historicalDataFromCache, amount)
return HistoricalData(convertedRate, historicalDataFromCache.timestamp)
}
fun getConversion(
historicalData: HistoricalDataEntity,
amount: Double
): Double {
val oneEuroToTargetRate = historicalData.oneEuroToTargetRate
val oneEuroToBaseRate = historicalData.oneEuroToBaseRate
return amount * (oneEuroToTargetRate / oneEuroToBaseRate)
}
} | 0 | Kotlin | 0 | 0 | 3cc5bc91b0d3af5c8986f100fecbf06270926a4e | 3,522 | Currency-Converter | Apache License 2.0 |
src/main/kotlin/br/com/zupacademy/validation/ValidPixKey.kt | sergio-ads | 388,237,743 | true | {"Kotlin": 120453, "Smarty": 2172, "Dockerfile": 198} | package br.com.zupacademy.validation
import br.com.zupacademy.model.request.RegistraChavePixRequest
import io.micronaut.core.annotation.AnnotationValue
import io.micronaut.validation.validator.constraints.ConstraintValidator
import io.micronaut.validation.validator.constraints.ConstraintValidatorContext
import javax.inject.Singleton
import javax.validation.Constraint
import javax.validation.Payload
import kotlin.annotation.AnnotationRetention.RUNTIME
import kotlin.annotation.AnnotationTarget.CLASS
import kotlin.annotation.AnnotationTarget.TYPE
import kotlin.reflect.KClass
@MustBeDocumented
@Target(CLASS, TYPE)
@Retention(RUNTIME)
@Constraint(validatedBy = [ValidPixKeyValidator::class])
annotation class ValidPixKey(
val message: String = "chave Pix inválida (\${validatedValue.tipo})",
val groups: Array<KClass<Any>> = [],
val payload: Array<KClass<Payload>> = [],
)
/**
* Using Bean Validation API because we wanted to use Custom property paths
* https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-custom-property-paths
*/
@Singleton
class ValidPixKeyValidator: javax.validation.ConstraintValidator<ValidPixKey, RegistraChavePixRequest> {
override fun isValid(value: RegistraChavePixRequest?, context: javax.validation.ConstraintValidatorContext): Boolean {
// must be validated with @NotNull
if (value?.tipo == null) {
return true
}
val valid = value.tipo.valida(value.chave)
if (!valid) {
// https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-custom-property-paths
context.disableDefaultConstraintViolation()
context
.buildConstraintViolationWithTemplate(context.defaultConstraintMessageTemplate) // or "chave Pix inválida (${value.tipo})"
.addPropertyNode("chave").addConstraintViolation()
}
return valid
}
} | 0 | Kotlin | 0 | 0 | e37b39e0c7ca5821cb9c10d00ef3ca55f39f4db4 | 1,959 | orange-talents-05-template-pix-keymanager-grpc | Apache License 2.0 |
app/src/main/java/com/elhady/movies/core/data/repository/mappers/cash/LocalPopularPeopleMapper.kt | islamelhady | 301,591,032 | false | {"Kotlin": 584524} | package com.elhady.movies.core.data.repository.mappers.cash
import com.elhady.movies.BuildConfig
import com.elhady.movies.core.mapper.Mapper
import com.elhady.movies.core.data.local.database.dto.PopularPeopleLocalDto
import com.elhady.movies.core.data.remote.response.dto.PeopleRemoteDto
import javax.inject.Inject
class LocalPopularPeopleMapper @Inject constructor() :
Mapper<PeopleRemoteDto, PopularPeopleLocalDto> {
override fun map(input: PeopleRemoteDto): PopularPeopleLocalDto {
return PopularPeopleLocalDto(
id = input.id ?: 0,
imagerUrl = BuildConfig.IMAGE_BASE_PATH + input.profilePath,
name = input.name ?: "",
popularity = input.popularity ?: 0.0
)
}
} | 1 | Kotlin | 0 | 0 | d9b6c3f241b5de6c334fa2dcc9f2653de3c04762 | 741 | movie-night-v2 | Apache License 2.0 |
pgpainless-core/src/main/kotlin/org/pgpainless/key/modification/secretkeyring/SecretKeyRingEditorInterface.kt | pgpainless | 135,846,104 | false | null | // SPDX-FileCopyrightText: 2023 <NAME> <<EMAIL>>
//
// SPDX-License-Identifier: Apache-2.0
package org.pgpainless.key.modification.secretkeyring
import java.io.IOException
import java.security.InvalidAlgorithmParameterException
import java.security.NoSuchAlgorithmException
import java.util.*
import org.bouncycastle.openpgp.*
import org.pgpainless.algorithm.KeyFlag
import org.pgpainless.key.OpenPgpFingerprint
import org.pgpainless.key.generation.KeySpec
import org.pgpainless.key.protection.KeyRingProtectionSettings
import org.pgpainless.key.protection.SecretKeyRingProtector
import org.pgpainless.key.util.RevocationAttributes
import org.pgpainless.signature.subpackets.RevocationSignatureSubpackets
import org.pgpainless.signature.subpackets.SelfSignatureSubpackets
import org.pgpainless.util.Passphrase
import org.pgpainless.util.selection.userid.SelectUserId
interface SecretKeyRingEditorInterface {
/**
* Editors reference time. This time is used as creation date for new signatures, or as
* reference when evaluating expiration of existing signatures.
*/
val referenceTime: Date
/**
* Add a user-id to the key ring.
*
* @param userId user-id
* @param protector protector to unlock the secret key
* @return the builder
* @throws PGPException in case we cannot generate a signature for the user-id
*/
@Throws(PGPException::class)
fun addUserId(userId: CharSequence, protector: SecretKeyRingProtector) =
addUserId(userId, null, protector)
/**
* Add a user-id to the key ring.
*
* @param userId user-id
* @param callback callback to modify the self-signature subpackets
* @param protector protector to unlock the secret key
* @return the builder
* @throws PGPException in case we cannot generate a signature for the user-id
*/
@Throws(PGPException::class)
fun addUserId(
userId: CharSequence,
callback: SelfSignatureSubpackets.Callback? = null,
protector: SecretKeyRingProtector
): SecretKeyRingEditorInterface
/**
* Add a user-id to the key ring and mark it as primary. If the user-id is already present, a
* new certification signature will be created.
*
* @param userId user id
* @param protector protector to unlock the secret key
* @return the builder
* @throws PGPException in case we cannot generate a signature for the user-id
*/
@Throws(PGPException::class)
fun addPrimaryUserId(
userId: CharSequence,
protector: SecretKeyRingProtector
): SecretKeyRingEditorInterface
/**
* Convenience method to revoke selected user-ids using soft revocation signatures. The
* revocation will use [RevocationAttributes.Reason.USER_ID_NO_LONGER_VALID], so that the
* user-id can be re-certified at a later point.
*
* @param selector selector to select user-ids
* @param protector protector to unlock the primary key
* @return the builder
* @throws PGPException in case we cannot generate a revocation signature for the user-id
*/
@Deprecated(
"Use of SelectUserId class is deprecated.",
ReplaceWith("removeUserId(protector, predicate)"))
@Throws(PGPException::class)
fun removeUserId(selector: SelectUserId, protector: SecretKeyRingProtector) =
removeUserId(protector, selector)
/**
* Convenience method to revoke selected user-ids using soft revocation signatures. The
* revocation will use [RevocationAttributes.Reason.USER_ID_NO_LONGER_VALID], so that the
* user-id can be re-certified at a later point.
*
* @param protector protector to unlock the primary key
* @param predicate predicate to select user-ids for revocation
* @return the builder
* @throws PGPException in case we cannot generate a revocation signature for the user-id
*/
@Throws(PGPException::class)
fun removeUserId(
protector: SecretKeyRingProtector,
predicate: (String) -> Boolean
): SecretKeyRingEditorInterface
/**
* Convenience method to revoke a single user-id using a soft revocation signature. The
* revocation will use [RevocationAttributes.Reason.USER_ID_NO_LONGER_VALID] so that the user-id
* can be re-certified at a later point.
*
* @param userId user-id to revoke
* @param protector protector to unlock the primary key
* @return the builder
* @throws PGPException in case we cannot generate a revocation signature for the user-id
*/
@Throws(PGPException::class)
fun removeUserId(
userId: CharSequence,
protector: SecretKeyRingProtector
): SecretKeyRingEditorInterface
/**
* Replace a user-id on the key with a new one. The old user-id gets soft revoked and the new
* user-id gets bound with the same signature subpackets as the old one, with one exception: If
* the old user-id was implicitly primary (did not carry a
* [org.bouncycastle.bcpg.sig.PrimaryUserID] packet, but effectively was primary), then the new
* user-id will be explicitly marked as primary.
*
* @param oldUserId old user-id
* @param newUserId new user-id
* @param protector protector to unlock the secret key
* @return the builder
* @throws PGPException in case we cannot generate a revocation and certification signature
* @throws java.util.NoSuchElementException if the old user-id was not found on the key; or if
* the oldUserId was already invalid
*/
@Throws(PGPException::class)
fun replaceUserId(
oldUserId: CharSequence,
newUserId: CharSequence,
protector: SecretKeyRingProtector
): SecretKeyRingEditorInterface
/**
* Add a subkey to the key ring. The subkey will be generated from the provided [KeySpec].
*
* @param keySpec key specification
* @param subkeyPassphrase passphrase to encrypt the sub key
* @param callback callback to modify the subpackets of the subkey binding signature
* @param protector protector to unlock the secret key of the key ring
* @return the builder
* @throws InvalidAlgorithmParameterException in case the user wants to use invalid parameters
* for the key
* @throws NoSuchAlgorithmException in case of missing algorithm support in the crypto backend
* @throws PGPException in case we cannot generate a binding signature for the subkey
* @throws IOException in case of an IO error
*/
@Throws(
PGPException::class,
IOException::class,
InvalidAlgorithmParameterException::class,
NoSuchAlgorithmException::class)
fun addSubKey(
keySpec: KeySpec,
subkeyPassphrase: Passphrase,
callback: SelfSignatureSubpackets.Callback? = null,
protector: SecretKeyRingProtector
): SecretKeyRingEditorInterface
/**
* Add a subkey to the key ring.
*
* @param subkey subkey key pair
* @param callback callback to modify the subpackets of the subkey binding signature
* @param subkeyProtector protector to unlock and encrypt the subkey
* @param primaryKeyProtector protector to unlock the primary key
* @param keyFlag first mandatory key flag for the subkey
* @param keyFlags optional additional key flags
* @return builder
* @throws PGPException in case we cannot generate a binding signature for the subkey
* @throws IOException in case of an IO error
*/
@Throws(PGPException::class, IOException::class)
fun addSubKey(
subkey: PGPKeyPair,
callback: SelfSignatureSubpackets.Callback?,
subkeyProtector: SecretKeyRingProtector,
primaryKeyProtector: SecretKeyRingProtector,
keyFlag: KeyFlag,
vararg keyFlags: KeyFlag
): SecretKeyRingEditorInterface
/**
* Revoke the key ring using a hard revocation.
*
* @param protector protector of the primary key
* @return the builder
* @throws PGPException in case we cannot generate a revocation signature
*/
@Throws(PGPException::class)
fun revoke(protector: SecretKeyRingProtector) = revoke(protector, null as RevocationAttributes?)
/**
* Revoke the key ring using the provided revocation attributes. The attributes define, whether
* the revocation was a hard revocation or not.
*
* @param protector protector of the primary key
* @param revocationAttributes reason for the revocation
* @return the builder
* @throws PGPException in case we cannot generate a revocation signature
*/
@Throws(PGPException::class)
fun revoke(
protector: SecretKeyRingProtector,
revocationAttributes: RevocationAttributes? = null
): SecretKeyRingEditorInterface
/**
* Revoke the key ring. You can use the [RevocationSignatureSubpackets.Callback] to modify the
* revocation signatures subpackets, e.g. in order to define whether this is a hard or soft
* revocation.
*
* @param protector protector to unlock the primary secret key
* @param callback callback to modify the revocations subpackets
* @return builder
* @throws PGPException in case we cannot generate a revocation signature
*/
@Throws(PGPException::class)
fun revoke(
protector: SecretKeyRingProtector,
callback: RevocationSignatureSubpackets.Callback?
): SecretKeyRingEditorInterface
/**
* Revoke the subkey binding signature of a subkey. The subkey with the provided fingerprint
* will be revoked. If no suitable subkey is found, a [NoSuchElementException] will be thrown.
*
* @param fingerprint fingerprint of the subkey to be revoked
* @param protector protector to unlock the primary key
* @return the builder
* @throws PGPException in case we cannot generate a revocation signature for the subkey
*/
@Throws(PGPException::class)
fun revokeSubKey(fingerprint: OpenPgpFingerprint, protector: SecretKeyRingProtector) =
revokeSubKey(fingerprint, protector, null)
/**
* Revoke the subkey binding signature of a subkey. The subkey with the provided fingerprint
* will be revoked. If no suitable subkey is found, a [NoSuchElementException] will be thrown.
*
* @param fingerprint fingerprint of the subkey to be revoked
* @param protector protector to unlock the primary key
* @param revocationAttributes reason for the revocation
* @return the builder
* @throws PGPException in case we cannot generate a revocation signature for the subkey
*/
@Throws(PGPException::class)
fun revokeSubKey(
fingerprint: OpenPgpFingerprint,
protector: SecretKeyRingProtector,
revocationAttributes: RevocationAttributes? = null
): SecretKeyRingEditorInterface =
revokeSubKey(fingerprint.keyId, protector, revocationAttributes)
/**
* Revoke the subkey binding signature of a subkey. The subkey with the provided key-id will be
* revoked. If no suitable subkey is found, a [NoSuchElementException] will be thrown.
*
* @param subkeyId id of the subkey
* @param protector protector to unlock the primary key
* @return the builder
* @throws PGPException in case we cannot generate a revocation signature for the subkey
*/
@Throws(PGPException::class)
fun revokeSubKey(subkeyId: Long, protector: SecretKeyRingProtector) =
revokeSubKey(subkeyId, protector, null as RevocationAttributes?)
/**
* Revoke the subkey binding signature of a subkey. The subkey with the provided key-id will be
* revoked. If no suitable subkey is found, a [NoSuchElementException] will be thrown.
*
* @param subkeyId id of the subkey
* @param protector protector to unlock the primary key
* @param revocationAttributes reason for the revocation
* @return the builder
* @throws PGPException in case we cannot generate a revocation signature for the subkey
*/
@Throws(PGPException::class)
fun revokeSubKey(
subkeyId: Long,
protector: SecretKeyRingProtector,
revocationAttributes: RevocationAttributes? = null
): SecretKeyRingEditorInterface
/**
* Revoke the subkey binding signature of a subkey. The subkey with the provided key-id will be
* revoked. If no suitable subkey is found, a [NoSuchElementException] will be thrown.
*
* The provided subpackets callback is used to modify the revocation signatures subpackets.
*
* @param subkeyId id of the subkey
* @param protector protector to unlock the secret key ring
* @param callback callback which can be used to modify the subpackets of the revocation
* signature
* @return the builder
* @throws PGPException in case we cannot generate a revocation signature for the subkey
*/
@Throws(PGPException::class)
fun revokeSubKey(
subkeyId: Long,
protector: SecretKeyRingProtector,
callback: RevocationSignatureSubpackets.Callback?
): SecretKeyRingEditorInterface
/**
* Hard-revoke the given userID.
*
* @param userId userId to revoke
* @param protector protector to unlock the primary key
* @return the builder
* @throws PGPException in case we cannot generate a revocation signature for the user-id
*/
@Throws(PGPException::class)
fun revokeUserId(userId: CharSequence, protector: SecretKeyRingProtector) =
revokeUserId(userId, protector, null as RevocationAttributes?)
/**
* Revoke the given userID using the provided revocation attributes.
*
* @param userId userId to revoke
* @param protector protector to unlock the primary key
* @param revocationAttributes reason for the revocation
* @return the builder
* @throws PGPException in case we cannot generate a revocation signature for the user-id
*/
@Throws(PGPException::class)
fun revokeUserId(
userId: CharSequence,
protector: SecretKeyRingProtector,
revocationAttributes: RevocationAttributes? = null
): SecretKeyRingEditorInterface
/**
* Revoke the provided user-id. Note: If you don't provide a
* [RevocationSignatureSubpackets.Callback] which sets a revocation reason
* ([RevocationAttributes]), the revocation will be considered hard. So if you intend to
* re-certify the user-id at a later point to make it valid again, make sure to set a soft
* revocation reason in the signatures hashed area using the subpacket callback.
*
* @param userId userid to be revoked
* @param protector protector to unlock the primary secret key
* @param callback callback to modify the revocations subpackets
* @return builder
* @throws PGPException in case we cannot generate a revocation signature for the user-id
*/
@Throws(PGPException::class)
fun revokeUserId(
userId: CharSequence,
protector: SecretKeyRingProtector,
callback: RevocationSignatureSubpackets.Callback?
): SecretKeyRingEditorInterface
/**
* Revoke all user-ids that match the provided [SelectUserId] filter. The provided
* [RevocationAttributes] will be set as reason for revocation in each revocation signature.
*
* Note: If you intend to re-certify these user-ids at a later point, make sure to choose a soft
* revocation reason. See [RevocationAttributes.Reason] for more information.
*
* @param selector user-id selector
* @param protector protector to unlock the primary secret key
* @param revocationAttributes revocation attributes
* @return builder
* @throws PGPException in case we cannot generate a revocation signature for the user-id
*/
@Throws(PGPException::class)
@Deprecated(
"Use of SelectUserId class is deprecated.",
ReplaceWith("revokeUserIds(protector, revocationAttributes, predicate)"))
fun revokeUserIds(
selector: SelectUserId,
protector: SecretKeyRingProtector,
revocationAttributes: RevocationAttributes?
) = revokeUserIds(protector, revocationAttributes, selector)
/**
* Revoke all user-ids that match the provided [SelectUserId] filter. The provided
* [RevocationAttributes] will be set as reason for revocation in each revocation signature.
*
* Note: If you intend to re-certify these user-ids at a later point, make sure to choose a soft
* revocation reason. See [RevocationAttributes.Reason] for more information.
*
* @param protector protector to unlock the primary secret key
* @param revocationAttributes revocation attributes
* @param predicate to select user-ids for revocation
* @return builder
* @throws PGPException in case we cannot generate a revocation signature for the user-id
*/
@Throws(PGPException::class)
fun revokeUserIds(
protector: SecretKeyRingProtector,
revocationAttributes: RevocationAttributes?,
predicate: (String) -> Boolean
): SecretKeyRingEditorInterface
/**
* Revoke all user-ids that match the provided [SelectUserId] filter. The provided
* [RevocationSignatureSubpackets.Callback] will be used to modify the revocation signatures
* subpackets.
*
* Note: If you intend to re-certify these user-ids at a later point, make sure to set a soft
* revocation reason in the revocation signatures hashed subpacket area using the callback.
*
* See [RevocationAttributes.Reason] for more information.
*
* @param selector user-id selector
* @param protector protector to unlock the primary secret key
* @param callback callback to modify the revocations subpackets
* @return builder
* @throws PGPException in case we cannot generate a revocation signature for the user-id
*/
@Throws(PGPException::class)
@Deprecated(
"Use of SelectUserId class is deprecated.",
ReplaceWith("revokeUserIds(protector, callback, predicate)"))
fun revokeUserIds(
selector: SelectUserId,
protector: SecretKeyRingProtector,
callback: RevocationSignatureSubpackets.Callback?
) = revokeUserIds(protector, callback, selector)
/**
* Revoke all user-ids that match the provided [SelectUserId] filter. The provided
* [RevocationSignatureSubpackets.Callback] will be used to modify the revocation signatures
* subpackets.
*
* Note: If you intend to re-certify these user-ids at a later point, make sure to set a soft
* revocation reason in the revocation signatures hashed subpacket area using the callback.
*
* See [RevocationAttributes.Reason] for more information.
*
* @param protector protector to unlock the primary secret key
* @param callback callback to modify the revocations subpackets
* @param predicate to select user-ids for revocation
* @return builder
* @throws PGPException in case we cannot generate a revocation signature for the user-id
*/
@Throws(PGPException::class)
fun revokeUserIds(
protector: SecretKeyRingProtector,
callback: RevocationSignatureSubpackets.Callback?,
predicate: (String) -> Boolean
): SecretKeyRingEditorInterface
/**
* Set the expiration date for the primary key of the key ring. If the key is supposed to never
* expire, then an expiration date of null is expected.
*
* @param expiration new expiration date or null
* @param protector to unlock the secret key
* @return the builder
* @throws PGPException in case we cannot generate a new self-signature with the changed
* expiration date
*/
@Throws(PGPException::class)
fun setExpirationDate(
expiration: Date?,
protector: SecretKeyRingProtector
): SecretKeyRingEditorInterface
/**
* Create a minimal, self-authorizing revocation certificate, containing only the primary key
* and a revocation signature. This type of revocation certificates was introduced in OpenPGP
* v6. This method has no side effects on the original key and will leave it intact.
*
* @param protector protector to unlock the primary key.
* @param revocationAttributes reason for the revocation (key revocation)
* @return minimal revocation certificate
* @throws PGPException in case we cannot generate a revocation signature
*/
@Throws(PGPException::class)
fun createMinimalRevocationCertificate(
protector: SecretKeyRingProtector,
revocationAttributes: RevocationAttributes?
): PGPPublicKeyRing
/**
* Create a detached revocation certificate, which can be used to revoke the whole key. The
* original key will not be modified by this method.
*
* @param protector protector to unlock the primary key.
* @param revocationAttributes reason for the revocation
* @return revocation certificate
* @throws PGPException in case we cannot generate a revocation certificate
*/
@Throws(PGPException::class)
fun createRevocation(
protector: SecretKeyRingProtector,
revocationAttributes: RevocationAttributes?
): PGPSignature
/**
* Create a detached revocation certificate, which can be used to revoke the specified subkey.
* The original key will not be modified by this method.
*
* @param subkeyId id of the subkey to be revoked
* @param protector protector to unlock the primary key.
* @param revocationAttributes reason for the revocation
* @return revocation certificate
* @throws PGPException in case we cannot generate a revocation certificate
*/
@Throws(PGPException::class)
fun createRevocation(
subkeyId: Long,
protector: SecretKeyRingProtector,
revocationAttributes: RevocationAttributes?
): PGPSignature
/**
* Create a detached revocation certificate, which can be used to revoke the specified subkey.
* The original key will not be modified by this method.
*
* @param subkeyId id of the subkey to be revoked
* @param protector protector to unlock the primary key.
* @param callback callback to modify the subpackets of the revocation certificate.
* @return revocation certificate
* @throws PGPException in case we cannot generate a revocation certificate
*/
@Throws(PGPException::class)
fun createRevocation(
subkeyId: Long,
protector: SecretKeyRingProtector,
callback: RevocationSignatureSubpackets.Callback?
): PGPSignature
/**
* Create a detached revocation certificate, which can be used to revoke the specified subkey.
* The original key will not be modified by this method.
*
* @param subkeyFingerprint fingerprint of the subkey to be revoked
* @param protector protector to unlock the primary key.
* @param revocationAttributes reason for the revocation
* @return revocation certificate
* @throws PGPException in case we cannot generate a revocation certificate
*/
@Throws(PGPException::class)
fun createRevocation(
subkeyFingerprint: OpenPgpFingerprint,
protector: SecretKeyRingProtector,
revocationAttributes: RevocationAttributes?
): PGPSignature
/**
* Change the passphrase of the whole key ring.
*
* @param oldPassphrase old passphrase (empty, if the key was unprotected)
* @return next builder step
*/
fun changePassphraseFromOldPassphrase(oldPassphrase: Passphrase) =
changePassphraseFromOldPassphrase(
oldPassphrase, KeyRingProtectionSettings.secureDefaultSettings())
/**
* Change the passphrase of the whole key ring.
*
* @param oldPassphrase old passphrase (empty, if the key was unprotected)
* @param oldProtectionSettings custom settings for the old passphrase
* @return next builder step
*/
fun changePassphraseFromOldPassphrase(
oldPassphrase: Passphrase,
oldProtectionSettings: KeyRingProtectionSettings =
KeyRingProtectionSettings.secureDefaultSettings()
): WithKeyRingEncryptionSettings
/**
* Change the passphrase of a single subkey in the key ring.
*
* Note: While it is a valid use-case to have different passphrases per subKey, this is one of
* the reasons why OpenPGP sucks in practice.
*
* @param keyId id of the subkey
* @param oldPassphrase old passphrase (empty if the key was unprotected)
* @return next builder step
*/
fun changeSubKeyPassphraseFromOldPassphrase(keyId: Long, oldPassphrase: Passphrase) =
changeSubKeyPassphraseFromOldPassphrase(
keyId, oldPassphrase, KeyRingProtectionSettings.secureDefaultSettings())
/**
* Change the passphrase of a single subkey in the key ring.
*
* Note: While it is a valid use-case to have different passphrases per subKey, this is one of
* the reasons why OpenPGP sucks in practice.
*
* @param keyId id of the subkey
* @param oldPassphrase old passphrase (empty if the key was unprotected)
* @param oldProtectionSettings custom settings for the old passphrase
* @return next builder step
*/
fun changeSubKeyPassphraseFromOldPassphrase(
keyId: Long,
oldPassphrase: Passphrase,
oldProtectionSettings: KeyRingProtectionSettings
): WithKeyRingEncryptionSettings
interface WithKeyRingEncryptionSettings {
/**
* Set secure default settings for the symmetric passphrase encryption. Note that this
* obviously has no effect if you decide to set [WithPassphrase.toNoPassphrase].
*
* @return next builder step
*/
fun withSecureDefaultSettings(): WithPassphrase
/**
* Set custom settings for the symmetric passphrase encryption.
*
* @param settings custom settings
* @return next builder step
*/
fun withCustomSettings(settings: KeyRingProtectionSettings): WithPassphrase
}
interface WithPassphrase {
/**
* Set the passphrase.
*
* @param passphrase passphrase
* @return editor builder
* @throws PGPException in case the passphrase cannot be changed
*/
@Throws(PGPException::class)
fun toNewPassphrase(passphrase: Passphrase): SecretKeyRingEditorInterface
/**
* Leave the key unprotected.
*
* @return editor builder
* @throws PGPException in case the passphrase cannot be changed
*/
@Throws(PGPException::class) fun toNoPassphrase(): SecretKeyRingEditorInterface
}
/**
* Return the [PGPSecretKeyRing].
*
* @return the key
*/
fun done(): PGPSecretKeyRing
fun addSubKey(
keySpec: KeySpec,
subkeyPassphrase: Passphrase,
protector: SecretKeyRingProtector
): SecretKeyRingEditorInterface
}
| 28 | null | 23 | 156 | de4a11352853b6e18146b10a87a928b2984a0fab | 27,183 | pgpainless | Apache License 2.0 |
photopicker/src/main/java/com/github/basshelal/unsplashpicker/presentation/PhotoShowFragment.kt | basshelal | 198,377,924 | false | null | @file:Suppress("RedundantVisibilityModifier", "MemberVisibilityCanBePrivate", "NOTHING_TO_INLINE")
package com.github.basshelal.unsplashpicker.presentation
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.UnderlineSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.annotation.IdRes
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.transition.AutoTransition
import com.github.basshelal.unsplashpicker.R
import com.github.basshelal.unsplashpicker.UnsplashPhotoPickerConfig
import com.github.basshelal.unsplashpicker.data.UnsplashPhoto
import com.squareup.picasso.Callback
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.fragment_photo_show.*
/**
* Used to show a single [UnsplashPhoto] on the screen.
*
* You should use [PhotoShowFragment.show] or [PhotoShowFragment.newInstance].
*/
public class PhotoShowFragment : Fragment() {
private val onBackPressed = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() = finish()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enterTransition = AutoTransition()
exitTransition = AutoTransition()
activity?.onBackPressedDispatcher?.addCallback(onBackPressed)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_photo_show, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
arguments?.getParcelable<UnsplashPhoto>(PHOTO)?.also { photo ->
arguments?.getString(PHOTO_SIZE)?.also { size ->
setUpPhotoView(photo, PhotoSize.valueOf(size))
setUpTextViews(photo)
}
}
}
private inline fun setUpPhotoView(photo: UnsplashPhoto, photoSize: PhotoSize) {
Picasso.get()
.load(photoSize.get(photo.urls))
.into(image_photoView, object : Callback.EmptyCallback() {
override fun onSuccess() {
image_photoView?.apply {
aspectRatio = photo.height.D / photo.width.D
updateLayoutParams<ViewGroup.MarginLayoutParams> {
topMargin = if (photo.isSponsored) convertDpToPx(32, context!!) else 0
}
}
image_progressBar?.isVisible = false
}
})
}
private inline fun setUpTextViews(photo: UnsplashPhoto) {
photoBy_textView?.apply {
text = arguments!!.getString(PHOTO_BY_STRING)
}
user_textView?.apply {
text = SpannableStringBuilder(" ${photo.user.name} ").also {
it.setSpan(UnderlineSpan(), 1, it.length - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
setOnClickListener {
goToUrl("https://unsplash.com/@${photo.user.username}")
}
}
on_textView?.apply {
text = arguments!!.getString(ON_STRING)
}
unsplash_textView?.apply {
text = SpannableStringBuilder(" $text ").also {
it.setSpan(UnderlineSpan(), 1, it.length - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
setOnClickListener {
goToUrl("https://unsplash.com/photos/${photo.id}")
}
}
sponsored_linearLayout?.apply {
isVisible = photo.isSponsored
setOnClickListener {
goToUrl("https://unsplash.com/brands")
}
}
}
private inline fun goToUrl(url: String) {
context?.startActivity(
Intent().apply {
action = Intent.ACTION_VIEW
addCategory(Intent.CATEGORY_BROWSABLE)
data = Uri.parse(
"$url?utm_source=${UnsplashPhotoPickerConfig.unsplashAppName}&utm_medium=referral"
)
})
}
private inline fun finish() {
onBackPressed.isEnabled = false
activity?.supportFragmentManager?.beginTransaction()
?.remove(this)
?.commit()
}
override fun onDestroy() {
super.onDestroy()
onBackPressed.isEnabled = false
}
companion object {
const val TAG = "UnsplashPhotoPickerPhotoShowFragment"
private const val PHOTO = "PHOTO"
private const val PHOTO_SIZE = "PHOTO_SIZE"
private const val PHOTO_BY_STRING = "PHOTO_BY_STRING"
private const val ON_STRING = "ON_STRING"
/**
* Creates a new [PhotoShowFragment] with the provided arguments.
*
* You should only use this instead of [show] if you want to show the [PhotoShowFragment]
* yourself, meaning perform the [androidx.fragment.app.FragmentTransaction] yourself.
* Otherwise you should use [show] instead.
*
* Shows the provided [photo] with the provided [photoSize].
*
* Use [photoByString] and [onString] to change the text displayed at the bottom
* used to credit the author and Unsplash, this is only used for translation and
* internationalization (i18n). Both strings must not contain leading or trailing spaces.
*/
public fun newInstance(
photo: UnsplashPhoto,
photoSize: PhotoSize = PhotoSize.REGULAR,
photoByString: String = "Photo by",
onString: String = "on"
): PhotoShowFragment {
return PhotoShowFragment().apply {
this.arguments = Bundle().also {
it.putParcelable(PHOTO, photo)
it.putString(PHOTO_SIZE, photoSize.name)
it.putString(PHOTO_BY_STRING, photoByString)
it.putString(ON_STRING, onString)
}
}
}
/**
* Shows the provided [photo] with the provided [photoSize] and returns the [PhotoShowFragment].
*
* You must provide the calling [FragmentActivity] which will show this [PhotoShowFragment].
*
* This just performs the [androidx.fragment.app.FragmentTransaction] for you, if you'd like to do so yourself,
* you can use [newInstance].
*
* Use [photoByString] and [onString] to change the text displayed at the bottom
* used to credit the author and Unsplash, this is only used for translation and
* internationalization (i18n). Both strings must not contain leading or trailing spaces.
*/
public fun show(
activity: FragmentActivity,
photo: UnsplashPhoto,
@IdRes container: Int = android.R.id.content,
photoSize: PhotoSize = PhotoSize.REGULAR,
photoByString: String = "Photo by",
onString: String = "on"
): PhotoShowFragment {
val fragment = newInstance(photo, photoSize, photoByString, onString)
activity.supportFragmentManager
.beginTransaction()
.add(container, fragment, TAG)
.commit()
return fragment
}
}
} | 2 | Kotlin | 5 | 31 | 1a404d3d970c60f513f47a5bb5adf0854f85fad6 | 7,823 | UnsplashPhotoPicker | MIT License |
src/main/kotlin/com/ilirus/widget/pack/group/ModItemGroup.kt | ChaosAlphard | 368,902,478 | false | null | package com.ilirus.widget.pack.group
import com.ilirus.widget.pack.consts.ModConst
import com.ilirus.widget.pack.item.ModIcon
import net.fabricmc.fabric.api.client.itemgroup.FabricItemGroupBuilder
import net.minecraft.item.ItemGroup
import net.minecraft.item.ItemStack
import net.minecraft.util.Identifier
/**
* @author wan
* @version 1.0.0
* Date 2021/05/19 23:37
*/
class ModItemGroup {
companion object {
@JvmStatic
val ITEM: ItemGroup = FabricItemGroupBuilder
.build(Identifier(ModConst.namespace,"item"))
{ ItemStack(ModIcon.instance) }
}
}
| 0 | Kotlin | 0 | 0 | 001db0805324444a56eb95f0a9310a447afb0dae | 601 | fabric-widget-pack | Creative Commons Zero v1.0 Universal |
library/src/main/java/ru/yandex/money/android/sdk/impl/paymentOptionList/PaymentOptionListPresenter.kt | GorshkovNikita | 144,304,854 | false | {"Gradle": 7, "CODEOWNERS": 1, "Java Properties": 3, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Text": 1, "Markdown": 1, "Proguard": 2, "XML": 94, "Java": 10, "Kotlin": 255, "HTML": 1} | /*
* The MIT License (MIT)
* Copyright © 2018 NBCO Yandex.Money LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the “Software”), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
* OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package ru.yandex.money.android.sdk.impl.paymentOptionList
import android.content.Context
import ru.yandex.money.android.sdk.R
import ru.yandex.money.android.sdk.impl.extensions.getAdditionalInfo
import ru.yandex.money.android.sdk.impl.extensions.getIcon
import ru.yandex.money.android.sdk.impl.extensions.getTitle
import ru.yandex.money.android.sdk.model.ErrorPresenter
import ru.yandex.money.android.sdk.model.PaymentOption
import ru.yandex.money.android.sdk.model.Presenter
import ru.yandex.money.android.sdk.model.Wallet
import ru.yandex.money.android.sdk.payment.loadOptionList.PaymentOptionListIsEmptyException
internal class PaymentOptionListPresenter(
context: Context,
private val showLogo: Boolean
) : Presenter<List<PaymentOption>, PaymentOptionListSuccessViewModel> {
private val context = context.applicationContext
override fun invoke(output: List<PaymentOption>) = constructOptionListSuccessViewModel(context, output, showLogo)
}
internal class ChangePaymentOptionPresenter(
context: Context,
private val showLogo: Boolean
) : Presenter<List<PaymentOption>, PaymentOptionListViewModel> {
private val context = context.applicationContext
override fun invoke(output: List<PaymentOption>): PaymentOptionListViewModel {
if (output.size <= 1) {
return PaymentOptionListCloseViewModel
} else {
return constructOptionListSuccessViewModel(context, output, showLogo)
}
}
}
private fun constructOptionListSuccessViewModel(context: Context, output: List<PaymentOption>, showLogo: Boolean) =
PaymentOptionListSuccessViewModel(
paymentOptions = output.map {
PaymentOptionListItemViewModel(
optionId = it.id,
icon = it.getIcon(context),
title = it.getTitle(context),
additionalInfo = it.getAdditionalInfo(),
canLogout = it is Wallet
)
},
showLogo = showLogo
)
internal class PaymentOptionListErrorPresenter(
context: Context,
private val showLogo: Boolean,
private val errorPresenter: ErrorPresenter
) : Presenter<Exception, PaymentOptionListFailViewModel> {
private val noPaymentOptionsError = context.applicationContext.getText(R.string.ym_no_payment_options_error)
override fun invoke(e: Exception) = PaymentOptionListFailViewModel(
error = noPaymentOptionsError.takeIf { e is PaymentOptionListIsEmptyException } ?: errorPresenter(e),
showLogo = showLogo
)
}
internal class PaymentOptionListProgressPresenter(
showLogo: Boolean
) : Presenter<Unit, PaymentOptionListProgressViewModel> {
private val progressViewModel = PaymentOptionListProgressViewModel(showLogo)
override fun invoke(ignored: Unit) = progressViewModel
}
| 1 | null | 1 | 1 | fa44a3b0a3872d9f1ede52ebbf90fc1d68dcf386 | 3,954 | yandex-checkout-android-sdk | MIT License |
app/src/main/java/com/srilakshmikanthanp/clipbirdroid/ui/gui/Clipbird.kt | srilakshmikanthanp | 679,518,906 | false | {"Kotlin": 178253} | package com.srilakshmikanthanp.clipbirdroid.ui.gui
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import com.srilakshmikanthanp.clipbirdroid.controller.AppController
import com.srilakshmikanthanp.clipbirdroid.ui.gui.composables.DrawerItems
import com.srilakshmikanthanp.clipbirdroid.ui.gui.composables.NavDrawer
import com.srilakshmikanthanp.clipbirdroid.ui.gui.screens.AboutUs
import com.srilakshmikanthanp.clipbirdroid.ui.gui.screens.Devices
import com.srilakshmikanthanp.clipbirdroid.ui.gui.screens.History
import com.srilakshmikanthanp.clipbirdroid.utility.functions.generateX509Certificate
import kotlinx.coroutines.launch
/**
* Clipbird Composable
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Clipbird(controller: AppController) {
// Composable States and Scope
val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
val scope = rememberCoroutineScope()
var selected by remember { mutableStateOf(DrawerItems.DEVICES) }
val context = LocalContext.current
// Handler For Item Click
val onItemClicked: (DrawerItems) -> Unit = {
// Close the Drawer on Item Click
scope.launch { drawerState.close() }
// Handle the Item Click
selected = it
}
// Menu click handler
val onMenuClick: () -> Unit = {
scope.launch {
drawerState.open()
}
}
// Render the Content
NavDrawer(
onItemClicked = onItemClicked,
selected = selected,
drawerState = drawerState,
) {
when (selected) {
DrawerItems.DEVICES -> Devices(controller, onMenuClick)
DrawerItems.ABOUT -> AboutUs(onMenuClick)
DrawerItems.HISTORY -> History(controller, onMenuClick)
}
}
}
/**
* Preview Clipbird
*/
@Preview(showBackground = true)
@Composable
private fun PreviewClipbird() {
Clipbird(AppController(generateX509Certificate(LocalContext.current), LocalContext.current))
}
| 0 | Kotlin | 0 | 0 | da88e5cf16163c3520852dfceed62e7b823512e2 | 2,351 | clipbirdroid | MIT License |
misk-clustering/src/test/kotlin/misk/clustering/kubernetes/KubernetesClusterTest.kt | cashapp | 113,107,217 | false | {"Kotlin": 3843790, "TypeScript": 232251, "Java": 83564, "JavaScript": 5073, "Shell": 3462, "HTML": 1536, "CSS": 58} | package misk.clustering.kubernetes
import com.google.inject.Module
import com.google.inject.util.Modules
import io.kubernetes.client.openapi.models.V1ContainerStatus
import io.kubernetes.client.openapi.models.V1ObjectMeta
import io.kubernetes.client.openapi.models.V1Pod
import io.kubernetes.client.openapi.models.V1PodStatus
import io.kubernetes.client.util.Watches
import misk.MiskTestingServiceModule
import misk.clustering.Cluster
import misk.clustering.ClusterHashRing
import misk.clustering.DefaultCluster
import misk.clustering.kubernetes.KubernetesClusterWatcher.Companion.CHANGE_TYPE_ADDED
import misk.clustering.kubernetes.KubernetesClusterWatcher.Companion.CHANGE_TYPE_DELETED
import misk.clustering.kubernetes.KubernetesClusterWatcher.Companion.CHANGE_TYPE_MODIFIED
import misk.inject.KAbstractModule
import misk.testing.MiskTest
import misk.testing.MiskTestModule
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import jakarta.inject.Inject
@MiskTest(startService = true)
internal class KubernetesClusterTest {
@MiskTestModule val module: Module = Modules.combine(
MiskTestingServiceModule(),
object : KAbstractModule() {
override fun configure() {
install(
KubernetesClusterModule(
KubernetesConfig(
my_pod_namespace = TEST_NAMESPACE,
my_pod_name = TEST_SELF_NAME,
my_pod_ip = TEST_SELF_IP
)
)
)
}
}
)
@Inject private lateinit var cluster: DefaultCluster
@Test fun startsWithSelfNotReady() {
val self = cluster.snapshot.self
assertThat(self.ipAddress).isEqualTo(TEST_SELF_IP)
assertThat(self.name).isEqualTo(TEST_SELF_NAME)
assertThat(cluster.snapshot.selfReady).isEqualTo(false)
}
@Test fun startsWithNoReadyMembers() {
assertThat(cluster.snapshot.readyMembers).isEmpty()
}
@Test fun selfReadyNotReady() {
val ready = CountDownLatch(1)
val changes = mutableListOf<Cluster.Changes>()
cluster.watch { changes.add(it) }
handleWatch(CHANGE_TYPE_ADDED, newPod(TEST_SELF_NAME, true, TEST_SELF_IP))
handleWatch(CHANGE_TYPE_MODIFIED, newPod(TEST_SELF_NAME, false, TEST_SELF_IP))
cluster.syncPoint { ready.countDown() }
assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue()
assertThat(changes).containsExactly(
Cluster.Changes(
snapshot = Cluster.Snapshot(
self = expectedSelf,
selfReady = false,
readyMembers = setOf(),
resourceMapper = ClusterHashRing(setOf())
)
),
Cluster.Changes(
snapshot = Cluster.Snapshot(
self = expectedSelf,
selfReady = true,
readyMembers = setOf(expectedSelf),
resourceMapper = ClusterHashRing(setOf(expectedSelf))
),
added = setOf(expectedSelf)
),
Cluster.Changes(
snapshot = Cluster.Snapshot(
self = expectedSelf,
selfReady = false,
readyMembers = setOf(),
resourceMapper = ClusterHashRing(setOf())
),
removed = setOf(expectedSelf)
)
)
}
@Test fun memberAddedIfReadyAndIPAddressAssigned() {
val ready = CountDownLatch(1)
val changes = mutableListOf<Cluster.Changes>()
cluster.watch { changes.add(it) }
handleWatch("ADDED", newPod("larry-blerp", true, "10.0.0.3"))
handleWatch("ADDED", newPod("larry-blerp2", true, "10.0.0.4"))
cluster.syncPoint { ready.countDown() }
assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue()
assertThat(changes).containsExactly(
Cluster.Changes(
snapshot = Cluster.Snapshot(
self = expectedSelf,
selfReady = false,
readyMembers = setOf(),
resourceMapper = ClusterHashRing(setOf())
)
),
Cluster.Changes(
snapshot = Cluster.Snapshot(
self = expectedSelf,
selfReady = false,
readyMembers = setOf(Cluster.Member("larry-blerp", "10.0.0.3")),
resourceMapper = ClusterHashRing(setOf(Cluster.Member("larry-blerp", "10.0.0.3")))
),
added = setOf(Cluster.Member("larry-blerp", "10.0.0.3"))
),
Cluster.Changes(
snapshot = Cluster.Snapshot(
self = expectedSelf,
selfReady = false,
readyMembers = setOf(
Cluster.Member("larry-blerp", "10.0.0.3"),
Cluster.Member("larry-blerp2", "10.0.0.4")
),
resourceMapper = ClusterHashRing(
setOf(
Cluster.Member("larry-blerp", "10.0.0.3"),
Cluster.Member("larry-blerp2", "10.0.0.4")
)
)
),
added = setOf(Cluster.Member("larry-blerp2", "10.0.0.4"))
)
)
}
@Test fun memberRemovedIfDeleted() {
val changes = mutableListOf<Cluster.Changes>()
val ready = CountDownLatch(1)
// Start with members
handleWatch(CHANGE_TYPE_ADDED, newPod("larry-blerp", true, "10.0.0.3"))
handleWatch(CHANGE_TYPE_ADDED, newPod("larry-blerp2", true, "10.0.0.4"))
// Explicitly remove a member
cluster.watch { changes.add(it) }
handleWatch(CHANGE_TYPE_DELETED, newPod("larry-blerp"))
cluster.syncPoint { ready.countDown() }
assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue()
assertThat(changes).containsExactly(
Cluster.Changes(
snapshot = Cluster.Snapshot(
self = expectedSelf,
selfReady = false,
readyMembers = setOf(
Cluster.Member("larry-blerp", "10.0.0.3"),
Cluster.Member("larry-blerp2", "10.0.0.4")
),
resourceMapper = ClusterHashRing(
setOf(
Cluster.Member("larry-blerp", "10.0.0.3"),
Cluster.Member("larry-blerp2", "10.0.0.4")
)
)
)
),
Cluster.Changes(
snapshot = Cluster.Snapshot(
self = expectedSelf,
selfReady = false,
readyMembers = setOf(Cluster.Member("larry-blerp2", "10.0.0.4")),
resourceMapper = ClusterHashRing(
setOf(
Cluster.Member("larry-blerp2", "10.0.0.4")
)
)
),
removed = setOf(Cluster.Member("larry-blerp", ""))
)
)
}
@Test fun memberNotAddedIfNotReady() {
val changes = mutableListOf<Cluster.Changes>()
val ready = CountDownLatch(1)
cluster.watch { changes.add(it) }
handleWatch(CHANGE_TYPE_ADDED, newPod("larry-blerp", false, "10.0.0.3"))
cluster.syncPoint { ready.countDown() }
assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue()
// Not ready, so shouldn't be added or marked as removed
assertThat(changes).containsExactly(
Cluster.Changes(
snapshot = Cluster.Snapshot(
self = expectedSelf,
selfReady = false,
readyMembers = setOf(),
resourceMapper = ClusterHashRing(setOf())
)
)
)
}
@Test fun memberNotAddedIfNoIPAddressAssigned() {
val changes = mutableListOf<Cluster.Changes>()
val ready = CountDownLatch(1)
cluster.watch { changes.add(it) }
handleWatch(CHANGE_TYPE_ADDED, newPod("larry-blerp", true))
cluster.syncPoint { ready.countDown() }
assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue()
// No IP address, so shouldn't be added or marked as removed
assertThat(changes).containsExactly(
Cluster.Changes(
snapshot = Cluster.Snapshot(
self = expectedSelf,
selfReady = false,
readyMembers = setOf(),
resourceMapper = ClusterHashRing(setOf())
)
)
)
}
@Test fun memberRemovedIfTransitionsToNotReady() {
val ready = CountDownLatch(1)
val changes = mutableListOf<Cluster.Changes>()
// Start as an existing member
handleWatch(CHANGE_TYPE_ADDED, newPod("larry-blerp", true, "10.0.0.3"))
handleWatch(CHANGE_TYPE_ADDED, newPod("larry-blerp2", true, "10.0.0.4"))
// Transition to not ready - should remove from the list
cluster.watch { changes.add(it) }
handleWatch(CHANGE_TYPE_MODIFIED, newPod("larry-blerp", false, "10.0.0.3"))
cluster.syncPoint { ready.countDown() }
assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue()
assertThat(changes).containsExactly(
Cluster.Changes(
snapshot = Cluster.Snapshot(
self = expectedSelf,
selfReady = false,
readyMembers = setOf(
Cluster.Member("larry-blerp", "10.0.0.3"),
Cluster.Member("larry-blerp2", "10.0.0.4")
),
resourceMapper = ClusterHashRing(
setOf(
Cluster.Member("larry-blerp", "10.0.0.3"),
Cluster.Member("larry-blerp2", "10.0.0.4")
)
)
)
),
Cluster.Changes(
snapshot = Cluster.Snapshot(
self = expectedSelf,
selfReady = false,
readyMembers = setOf(Cluster.Member("larry-blerp2", "10.0.0.4")),
resourceMapper = ClusterHashRing(
setOf(
Cluster.Member("larry-blerp2", "10.0.0.4")
)
)
),
removed = setOf(Cluster.Member("larry-blerp", "10.0.0.3"))
)
)
}
@Test fun memberRemovedIfIPAddressLost() {
val ready = CountDownLatch(1)
val changes = mutableListOf<Cluster.Changes>()
// Start as an existing member
handleWatch(CHANGE_TYPE_ADDED, newPod("larry-blerp", true, "10.0.0.3"))
handleWatch(CHANGE_TYPE_ADDED, newPod("larry-blerp2", true, "10.0.0.4"))
// Transition to no IP address
cluster.watch { changes.add(it) }
handleWatch(CHANGE_TYPE_MODIFIED, newPod("larry-blerp", true))
cluster.syncPoint { ready.countDown() }
assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue()
assertThat(changes).containsExactly(
Cluster.Changes(
snapshot = Cluster.Snapshot(
self = expectedSelf,
selfReady = false,
readyMembers = setOf(
Cluster.Member("larry-blerp", "10.0.0.3"),
Cluster.Member("larry-blerp2", "10.0.0.4")
),
resourceMapper = ClusterHashRing(
setOf(
Cluster.Member("larry-blerp", "10.0.0.3"),
Cluster.Member("larry-blerp2", "10.0.0.4")
)
)
)
),
Cluster.Changes(
snapshot = Cluster.Snapshot(
self = expectedSelf,
selfReady = false,
readyMembers = setOf(Cluster.Member("larry-blerp2", "10.0.0.4")),
resourceMapper = ClusterHashRing(
setOf(
Cluster.Member("larry-blerp2", "10.0.0.4")
)
)
),
removed = setOf(Cluster.Member("larry-blerp", ""))
)
)
}
private fun handleWatch(type: String, pod: V1Pod) {
Watches.newResponse(type, pod).applyTo(cluster)
}
private fun newPod(name: String, isReady: Boolean = false, ipAddress: String? = null): V1Pod {
val containerStatus = V1ContainerStatus()
containerStatus.ready = isReady
containerStatus.name = TEST_NAMESPACE
val pod = V1Pod()
pod.metadata = V1ObjectMeta()
pod.metadata!!.namespace = TEST_NAMESPACE
pod.metadata!!.name = name
pod.status = V1PodStatus()
pod.status!!.containerStatuses = listOf(containerStatus)
pod.status!!.podIP = ipAddress
return pod
}
companion object {
const val TEST_NAMESPACE = "larry"
const val TEST_SELF_NAME = "larry-76485b7568-l5rmm"
const val TEST_SELF_IP = "10.133.66.206"
val expectedSelf = Cluster.Member(TEST_SELF_NAME, TEST_SELF_IP)
}
}
| 169 | Kotlin | 169 | 400 | 13dcba0c4e69cc2856021270c99857e7e91af27d | 11,691 | misk | Apache License 2.0 |
src/me/anno/remsstudio/objects/GFXArray.kt | AntonioNoack | 266,471,164 | false | null | package me.anno.objects
import me.anno.config.DefaultConfig
import me.anno.gpu.GFX
import me.anno.io.ISaveable
import me.anno.io.base.BaseWriter
import me.anno.language.translation.Dict
import me.anno.objects.animation.AnimatedProperty
import me.anno.objects.modes.ArraySelectionMode
import me.anno.ui.base.groups.PanelListY
import me.anno.ui.editor.SettingCategory
import me.anno.ui.style.Style
import org.joml.*
import java.util.*
import java.util.Random
class GFXArray(parent: Transform? = null) : GFXTransform(parent) {
val perChildTranslation = AnimatedProperty.pos()
val perChildRotation = AnimatedProperty.rotYXZ()
val perChildScale = AnimatedProperty.scale()
val perChildSkew = AnimatedProperty.skew()
var perChildDelay = AnimatedProperty.double()
// val perChildTimeDilation = FloatArray(MAX_ARRAY_DIMENSION) // useful?, power vs linear
// per child skew?
override fun getSymbol() = DefaultConfig["ui.symbol.array", "[[["]
val instanceCount = AnimatedProperty.intPlus(10)
var selectionSeed = AnimatedProperty.long()
var selectionMode = ArraySelectionMode.ROUND_ROBIN
override fun acceptsWeight(): Boolean = true
override fun save(writer: BaseWriter) {
super.save(writer)
writer.writeObject(this, "instanceCount", instanceCount, true)
writer.writeObject(this, "perChildTranslation", perChildTranslation)
writer.writeObject(this, "perChildRotation", perChildRotation)
writer.writeObject(this, "perChildScale", perChildScale)
writer.writeObject(this, "perChildSkew", perChildSkew)
writer.writeObject(this, "perChildDelay", perChildDelay)
writer.writeObject(this, "selectionSeed", selectionSeed)
}
override fun readObject(name: String, value: ISaveable?) {
when (name) {
"instanceCount" -> instanceCount.copyFrom(value)
"perChildTranslation" -> perChildTranslation.copyFrom(value)
"perChildRotation" -> perChildRotation.copyFrom(value)
"perChildScale" -> perChildScale.copyFrom(value)
"perChildSkew" -> perChildSkew.copyFrom(value)
"perChildDelay" -> perChildDelay.copyFrom(value)
"selectionSeed" -> selectionSeed.copyFrom(value)
else -> super.readObject(name, value)
}
}
override fun onDraw(stack: Matrix4fArrayList, time: Double, color: Vector4fc) {
super.onDraw(stack, time, color)
// todo make text replacement simpler???
val instanceCount = instanceCount[time]
if (instanceCount > 0 && children.isNotEmpty()) {
val seed = selectionSeed[time]
val random = Random(seed)
random.nextInt() // first one otherwise is always 1 (with two elements)
val perChildDelay = perChildDelay[time]
drawArrayChild(
stack, time, perChildDelay, color, 0, instanceCount, random,
perChildTranslation[time], perChildRotation[time], perChildScale[time], perChildSkew[time]
)
}
}
fun drawArrayChild(
transform: Matrix4fArrayList, time: Double, perChildDelay: Double, color: Vector4fc,
index: Int, instanceCount: Int, random: Random,
position: Vector3fc, euler: Vector3fc, scale: Vector3fc, skew: Vector2fc
) {
val childIndex = selectionMode[index, children.size, random]
drawChild(transform, time, color, children[childIndex])
if (index + 1 < instanceCount) {
//val position = perChildTranslation[time]
if (position.x() != 0f || position.y() != 0f || position.z() != 0f) {
transform.translate(position)
}
//val euler = perChildRotation[time]
if (euler.y() != 0f) transform.rotate(GFX.toRadians(euler.y()), yAxis)
if (euler.x() != 0f) transform.rotate(GFX.toRadians(euler.x()), xAxis)
if (euler.z() != 0f) transform.rotate(GFX.toRadians(euler.z()), zAxis)
//val scale = perChildScale[time]
if (scale.x() != 1f || scale.y() != 1f || scale.z() != 1f) transform.scale(scale)
// val skew = perChildSkew[time]
if (skew.x() != 0f || skew.y() != 0f) transform.mul3x3(// works
1f, skew.y(), 0f,
skew.x(), 1f, 0f,
0f, 0f, 1f
)
drawArrayChild(
transform,
time + perChildDelay, perChildDelay, color, index + 1, instanceCount, random,
position, euler, scale, skew
)
}
}
override fun drawChildrenAutomatically() = false
override fun createInspector(
list: PanelListY,
style: Style,
getGroup: (title: String, description: String, dictSubPath: String) -> SettingCategory
) {
super.createInspector(list, style, getGroup)
// todo create apply button?
// todo we need to be able to insert properties...
// todo replace? :D, # String Array
val child = getGroup("Per-Child Transform", "For the n-th child, it is applied (n-1) times.", "per-child")
child += vi(
"Offset/Child",
"",
"array.offset",
perChildTranslation,
style
)
child += vi("Rotation/Child", "", "array.rotation", perChildRotation, style)
child += vi("Scale/Child", "", "array.scale", perChildScale, style)
child += vi("Delay/Child", "Temporal delay between each child", "array.delay", perChildDelay, style)
val instances = getGroup("Instances", "", "children")
instances += vi("Instance Count", "", "array.instanceCount", instanceCount, style)
instances += vi("Selection Mode", "", "array.selectionMode", null, selectionMode, style) { selectionMode = it }
instances += vi(
"Selection Seed",
"Only for randomized selection mode; change it, if you have bad luck, or copies of this array, which shall look different",
"array.selectionSeed",
selectionSeed,
style
)
}
override fun getClassName() = "GFXArray"
override fun getDefaultDisplayName() = Dict["Array", "obj.array"]
} | 0 | Kotlin | 1 | 8 | e5f0bb17202552fa26c87c230e31fa44cd3dd5c6 | 6,258 | RemsStudio | Apache License 2.0 |
Man10Bank/src/main/java/red/man10/man10bank/loan/LocalLoan.kt | forest611 | 267,747,865 | false | {"Kotlin": 113959, "C#": 68321, "Dockerfile": 603, "Shell": 84} | package red.man10.man10bank.loan
import net.kyori.adventure.text.Component.text
import net.kyori.adventure.text.event.ClickEvent.runCommand
import org.bukkit.Bukkit
import org.bukkit.Material
import org.bukkit.NamespacedKey
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerInteractEvent
import org.bukkit.inventory.ItemStack
import org.bukkit.persistence.PersistentDataType
import red.man10.man10bank.Man10Bank.Companion.threadPool
import red.man10.man10bank.Man10Bank.Companion.instance
import red.man10.man10bank.Man10Bank.Companion.vault
import red.man10.man10bank.Permissions
import red.man10.man10bank.status.StatusManager
import red.man10.man10bank.api.APIBank
import red.man10.man10bank.api.APILocalLoan
import red.man10.man10bank.util.Utility.format
import red.man10.man10bank.util.Utility.loggerInfo
import red.man10.man10bank.util.Utility.msg
import red.man10.man10bank.util.Utility.prefix
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.*
import kotlin.math.floor
object LocalLoan: Listener,CommandExecutor{
private lateinit var property: APILocalLoan.LocalLoanProperty
fun setup(){
property = APILocalLoan.property()
loggerInfo("個人間借金の設定を読み込みました")
loggerInfo("最小金利:${property.minimumInterest}")
loggerInfo("最大金利:${property.maximumInterest}")
loggerInfo("手数料:${property.fee}")
}
/**
* 個人間借金を作る
*/
private fun create(lender:Player, borrower:Player, amount:Double, interest:Double, due:Int){
val withdrawAmount = amount * (1 + property.fee)
if (!vault.withdraw(lender.uniqueId,withdrawAmount)){
msg(borrower,"提案者の所持金が足りませんでした。")
msg(lender,"所持金が足りないためお金を貸すことができません!")
return
}
val paybackDate = calcDue(due)
//返済額=貸出額+(貸出額x利子x日数)
val payment = amount + (amount * interest * due)
val ret = APILocalLoan.create(
APILocalLoan.LocalLoanTable(
0,
lender.name,
lender.uniqueId.toString(),
borrower.name,
borrower.uniqueId.toString(),
LocalDateTime.now(),
paybackDate,
payment
))
//サーバーへの問い合わせ失敗や発行失敗
if (ret<=0){
msg(lender,"手形の発行に失敗。銀行への問い合わせができませんでした")
msg(borrower,"手形の発行に失敗。銀行への問い合わせができませんでした")
vault.deposit(lender.uniqueId, withdrawAmount)
return
}
val note = getNote(ret)
//手形の発行失敗
if (note == null){
msg(lender,"手形の発行に失敗。銀行への問い合わせができませんでした")
msg(borrower,"手形の発行に失敗。銀行への問い合わせができませんでした")
vault.deposit(lender.uniqueId, withdrawAmount)
return
}
lender.inventory.addItem(note)
vault.deposit(borrower.uniqueId,amount)
msg(lender,"手形の発行に成功")
msg(borrower,"手形の発行に成功")
}
/**
* 手形を発行する
*/
private fun getNote(id:Int): ItemStack? {
val data = APILocalLoan.getInfo(id)?:return null
val note = ItemStack(Material.PAPER)
val meta = note.itemMeta
meta.setCustomModelData(2)
meta.displayName(text("§c§l約束手形 §7§l(Promissory Note)"))
meta.lore = mutableListOf(
"§4§l========[Man10Bank]========",
" §7§l債務者: ${Bukkit.getOfflinePlayer(data.borrow_uuid).name}",
" §8§l有効日: ${data.payback_date.format(DateTimeFormatter.ISO_LOCAL_DATE)}",
" §7§l支払額: ${format(data.amount)}",
"§4§l==========================")
meta.persistentDataContainer.set(NamespacedKey(instance,"id"), PersistentDataType.INTEGER,id)
note.itemMeta = meta
return note
}
private fun calcDue(day:Int,borrow:LocalDateTime = LocalDateTime.now()):LocalDateTime{
borrow.plusDays(day.toLong())
// val calender = Calendar.getInstance()
// calender.time = borrow
// calender.add(Calendar.DAY_OF_YEAR,day)
return borrow
}
@EventHandler
fun asyncUseNote(e:PlayerInteractEvent){
if (!e.hasItem() || !e.action.isRightClick)return
val item = e.item?:return
val meta = item.itemMeta?:return
val id = meta.persistentDataContainer[NamespacedKey(instance,"id"), PersistentDataType.INTEGER]?:return
val p = e.player
//一旦手形を削除
item.amount = 0
threadPool.execute {
//ここでnullが帰ってきたら手形じゃないと判定
val data = APILocalLoan.getInfo(id)?:return@execute
if (!StatusManager.status.enableLocalLoan){
msg(p,"現在メンテナンスにより個人間借金は行えません")
return@execute
}
val uuid = UUID.fromString(data.borrow_uuid)
val vaultMoney = vault.getBalance(uuid)
val bankMoney = APIBank.getBalance(uuid)
var paidMoney = 0.0
//銀行
if (APIBank.takeBank(APIBank.TransactionData(uuid.toString(),
bankMoney,
instance.name,
"paybackmoney",
"借金の返済")) == APIBank.BankResult.SUCCESSFUL){
paidMoney += bankMoney
}
//電子マネー
if (vault.withdraw(uuid,vaultMoney)){
paidMoney += vaultMoney
}
when(APILocalLoan.pay(id,paidMoney)){
"Paid"->{
msg(p,"${data.borrow_player}から${format(paidMoney)}円の回収を行いました")
vault.deposit(p.uniqueId,paidMoney)
//債務者への通知
val b = Bukkit.getPlayer(uuid)
if (b!=null){
msg(b,"${format(paidMoney)}円の個人間借金の回収を行いました")
}
}
"AllPaid"->{
val diff = paidMoney - data.amount
msg(p,"${data.borrow_player}から${format(paidMoney-diff)}円の回収を行いました")
msg(p,"全額回収完了")
vault.deposit(p.uniqueId,paidMoney-diff)
APIBank.addBank(
APIBank.TransactionData(
uuid.toString(),
diff,
instance.name,
"PaybackDifference",
"差額の返金"
))
//債務者への通知
val b = Bukkit.getPlayer(uuid)
if (b!=null){
msg(b,"${format(paidMoney)}円の個人間借金の回収を行いました")
msg(b,"完済し終わりました!お疲れ様です!")
}
}
else ->{
APIBank.addBank(
APIBank.TransactionData(
uuid.toString(),
paidMoney,
instance.name,
"Payback",
"不具合による返金"
)
)
msg(p,"借金の回収に失敗しました")
}
}
p.inventory.addItem(getNote(id)!!)
}
}
private val map = HashMap<UUID,CommandParam>()
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>?): Boolean {
if (label != "mlend")return true
if (sender !is Player)return true
if (!StatusManager.status.enableLocalLoan){
msg(sender,"現在メンテナンスにより個人間借金は行えません")
return false
}
if (args.isNullOrEmpty()){
msg(sender,"§a/mlend <貸す相手> <金額> <返済日(日)> " +
"<金利(日)${format(property.minimumInterest,1)}〜${format(property.maximumInterest,1)}>")
if (property.fee>0.0){
msg(sender,"§a貸出額の${format(property.fee,2)}%を貸出側から手数料としていただきます")
}
return true
}
if (args[0] == "property"){
if (!sender.hasPermission(Permissions.BANK_OP_COMMAND)){
msg(sender,"§c§lあなたには権限がありません")
return true
}
msg(sender,"最小金利:${property.minimumInterest}")
msg(sender,"最大金利:${property.maximumInterest}")
msg(sender,"手数料:${property.fee}")
return true
}
if (args[0] == "allow"){
val data = map[sender.uniqueId]?:return true
val lendP = Bukkit.getPlayer(data.lender)
if (lendP == null){
msg(sender,"提案者がログアウトしたようです")
return true
}
map.remove(sender.uniqueId)
threadPool.execute {
create(lendP,sender,data.amount,data.interest,data.due)
}
return true
}
if (args[0] == "deny"){
val data = map[sender.uniqueId]?:return true
val p = Bukkit.getPlayer(data.lender)
if (p!=null){
msg(p,"提案が断られました")
}
msg(sender,"提案を断りました")
map.remove(sender.uniqueId)
return true
}
if (args.size != 4){
msg(sender,"§a/mlend <貸す相手> <金額> <返済日(日)> " +
"<金利(日)${format(property.minimumInterest,1)}〜${format(property.maximumInterest,1)}>")
if (property.fee>0.0){
msg(sender,"§a貸出額の${format(property.fee,2)}%を貸出側から手数料としていただきます")
}
return true
}
val borrower = Bukkit.getPlayer(args[0])
val amount = args[1].toDoubleOrNull()
val due = args[2].toIntOrNull()
val interest = args[3].toDoubleOrNull()
if (borrower == null){
msg(sender,"オンラインでないプレイヤーです")
return true
}
if (amount == null || amount<0){
msg(sender,"金額は数字で1円以上を入力してください")
return true
}
val fixedAmount = floor(amount)
if (due == null || due < 0){
msg(sender,"期日は数字で1日以上を入力してください")
return true
}
if (interest == null || interest !in property.minimumInterest..property.maximumInterest){
msg(sender,"金利は数字で指定金利内で入力してください")
return true
}
val data = CommandParam(sender.uniqueId,fixedAmount, due, interest)
map[borrower.uniqueId] = data
val allowOrDeny = text("${prefix}§b§l§n[借りる] ").clickEvent(runCommand("/mlend allow"))
.append(text("§c§l§n[借りない]").clickEvent(runCommand("/mlend deny")))
msg(sender,"§a§l借金の提案を相手に提示しました")
msg(borrower,"§e§l=======================")
msg(borrower,"§e§kXX§b§l借金の提案§e§kXX")
msg(borrower,"§e貸し出す人:${sender.name}")
msg(borrower,"§e貸し出される金額:${format(fixedAmount)}")
msg(borrower,"§e返す金額:${format(fixedAmount + (fixedAmount * interest * due))}")
msg(borrower,"§e返す日:$${calcDue(due).format(DateTimeFormatter.ISO_LOCAL_DATE)}")
borrower.sendMessage(allowOrDeny)
msg(borrower,"§e§l=======================")
return true
}
data class CommandParam(
val lender: UUID,
val amount : Double,
val due : Int,
val interest : Double
)
} | 0 | Kotlin | 0 | 0 | bf579e3906ab9b7a3544f6d5fc67a40c9631ebdb | 11,361 | Man10Bank | Apache License 2.0 |
src/main/kotlin/icu/windea/pls/lang/model/ParadoxExpressionInfo.kt | DragonKnightOfBreeze | 328,104,626 | false | null | package icu.windea.pls.lang.model
import com.intellij.psi.*
import com.intellij.util.*
import icu.windea.pls.script.psi.*
/**
*
* @property elementOffset 对应的[ParadoxScriptExpressionElement]在文件中的起始位置。
* @property gameType 对应的游戏类型。
* @property file 对应的文件。使用[QueryExecutor]进行查询时才能获取。
*/
interface ParadoxExpressionInfo {
val elementOffset: Int
val gameType: ParadoxGameType
val file: PsiFile?
}
| 8 | Kotlin | 4 | 22 | c6c558b82c84b9e88c0ee179f64cbfdda66b8082 | 411 | Paradox-Language-Support | MIT License |
schoolDomain/src/main/kotlin/com/intelligentbackpack/schooldomain/entities/person/Person.kt | IntelligentBackpack | 629,745,884 | false | null | package com.intelligentbackpack.schooldomain.entities.person
/**
* A person.
*
* @property name the name of the person
* @property surname the surname of the person
* @property email the email of the person
*/
interface Person {
val name: String
val surname: String
val email: String
}
| 0 | Kotlin | 0 | 0 | 61bfdc8c21801a14d67c62b69a07a0fb341aab6d | 305 | IntelligentBackpackApp | MIT License |
v-customview/src/main/java/com/vension/customview/svga_player/SVGAVideoSpriteEntity.kt | Vension | 126,779,607 | false | null | package com.opensource.svgaplayer
import com.opensource.svgaplayer.proto.SpriteEntity
import org.json.JSONObject
/**
* Created by cuiminghui on 2016/10/17.
*/
class SVGAVideoSpriteEntity {
val imageKey: String?
val frames: List<SVGAVideoSpriteFrameEntity>
constructor(obj: JSONObject) {
this.imageKey = obj.optString("imageKey")
val mutableFrames: MutableList<SVGAVideoSpriteFrameEntity> = mutableListOf()
obj.optJSONArray("frames")?.let {
for (i in 0 until it.length()) {
it.optJSONObject(i)?.let {
val frameItem = SVGAVideoSpriteFrameEntity(it)
if (frameItem.shapes.isNotEmpty()) {
frameItem.shapes.first().let {
if (it.isKeep && mutableFrames.size > 0) {
frameItem.shapes = mutableFrames.last().shapes
}
}
}
mutableFrames.add(frameItem)
}
}
}
frames = mutableFrames.toList()
}
constructor(obj: SpriteEntity) {
this.imageKey = obj.imageKey
var lastFrame: SVGAVideoSpriteFrameEntity? = null
frames = obj.frames?.map {
val frameItem = SVGAVideoSpriteFrameEntity(it)
if (frameItem.shapes.isNotEmpty()) {
frameItem.shapes.first().let {
if (it.isKeep) {
lastFrame?.let {
frameItem.shapes = it.shapes
}
}
}
}
lastFrame = frameItem
return@map frameItem
} ?: listOf()
}
}
| 65 | null | 477 | 8 | 878f17d8ab80f61437adc770015ec72b27279b3b | 1,752 | KV-Frame | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.