path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/algorithms/Recursion.kt
|
kuya32
| 383,611,005
| false
| null |
package algorithms
class Recursion {
fun findFactorialRecursive(number: Int): Int {
return if (number < 2) {
1
} else {
return number * findFactorialRecursive(number - 1)
}
}
fun findFactorialIterative(number: Int): Int {
return if (number < 2) {
1
} else {
var result = 1
for (i in 2..number) {
result *= i
}
result
}
}
}
| 0
|
Kotlin
|
0
| 0
|
e28e15cb2b719920305bd6e1b211ee29ac0df329
| 490
|
Data-Structures-and-Algorithms-Kotlin
|
MIT License
|
search/core/src/main/java/io/em2m/search/core/parser/SimpleSchemaMapper.kt
|
em2m
| 114,274,216
| false
|
{"Kotlin": 589728}
|
package io.em2m.search.core.parser
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import java.util.*
class SimpleSchemaMapper(private val defaultField: String, val objectMapper: ObjectMapper = jacksonObjectMapper()) : SchemaMapper {
private val aliases = HashMap<String, String>()
private val types = HashMap<String, Class<*>>()
override fun typeOf(field: String): Class<out Any>? {
val f = aliases.getOrDefault(field, field)
return types[f]
}
override fun mapPath(field: String): String {
var result: String? = aliases[field]
if (result == null || result.isEmpty()) {
result = field
}
return result
}
override fun toString(field: String, value: Any): String? {
return convertValue(value, String::class.java)
}
override fun valueOf(field: String, str: String): Any? {
var type: Class<*>? = types[field]
if (type == null) {
type = String::class.java
}
return convertValue(str, type)
}
private fun <T> convertValue(from: Any?, typeRef: Class<T>): T {
return objectMapper.convertValue(from, typeRef)
}
fun withMapping(field: String, type: Class<*>): SimpleSchemaMapper {
types[field] = type
return this
}
fun withAlias(alias: String, value: String): SimpleSchemaMapper {
aliases[alias] = value
return this
}
}
| 3
|
Kotlin
|
16
| 3
|
35d6b94a9b77685f441b0b9bc272f9a51d550178
| 1,501
|
em2m-java-sdk
|
Apache License 2.0
|
notifications-module/src/main/kotlin/com/build/stats/notification/manager/NtfTypesStartupManager.kt
|
SHvatov
| 571,232,915
| false
|
{"Kotlin": 118267, "HTML": 50649, "Dockerfile": 1800, "Shell": 372, "CSS": 186}
|
package com.build.stats.notification.manager
interface NtfTypesStartupManager {
fun updateNtfTypes()
}
| 0
|
Kotlin
|
0
| 0
|
49739408dbcabb0fc6e4b1d6bacbaa893b115068
| 108
|
build-stats
|
Apache License 2.0
|
src/main/kotlin/org/goodmath/simplex/runtime/values/primitives/NoneValue.kt
|
MarkChuCarroll
| 831,231,194
| false
|
{"Kotlin": 326391, "JavaScript": 5595, "ANTLR": 3455, "Emacs Lisp": 1296, "Scheme": 450}
|
/*
* Copyright 2024 Mark C. Chu-Carroll
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.goodmath.simplex.runtime.values.primitives
import org.goodmath.simplex.ast.types.Type
import org.goodmath.simplex.runtime.values.Value
import org.goodmath.simplex.runtime.values.ValueType
import org.goodmath.simplex.twist.Twist
object NoneValue : Value {
override val valueType: ValueType = NoneValueType
override fun twist(): Twist {
return Twist.obj("None")
}
}
object NoneValueType : ValueType() {
override val name: String = "None"
override val asType: Type by lazy {
Type.simple(name)
}
override fun isTruthy(v: Value): Boolean {
return false
}
override val providesFunctions: List<PrimitiveFunctionValue> = emptyList()
override val providesPrimitiveMethods: List<PrimitiveMethod> = emptyList()
override val providesVariables: Map<String, Value> by lazy { mapOf("none" to NoneValue) }
override fun assertIs(v: Value): Value {
return if (v == NoneValue) {
v
} else {
throwTypeError(v)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
739843a9beea38240790979373bfd53860567e5f
| 1,643
|
simplex
|
Apache License 2.0
|
Kotlin/src/main/kotlin/reference/coroutines/cancel/Cancel08.kt
|
totemtec
| 370,664,275
| false
|
{"Kotlin": 86166, "Java": 388}
|
package reference.coroutines.cancel
import kotlinx.coroutines.*
var acquired = 0
class Resource {
init { acquired++ }
fun close() { acquired-- }
}
fun main() = runBlocking<Unit> {
repeat(100_000) {
launch {
val resource = withTimeout(60) {
delay(50)
Resource()
}
resource.close()
}
}
println(acquired)
}
| 0
|
Kotlin
|
0
| 0
|
5c8c40dcedfa949a2640c776feb110ae44e4ded4
| 412
|
kotlin
|
Apache License 2.0
|
src/main/kotlin/Table.kt
|
evilthreads669966
| 716,315,772
| false
|
{"Kotlin": 18581}
|
/*
Copyright 2023 Chris Basinger
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.
*/
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import org.koin.core.qualifier.named
class Table: KoinComponent {
val dealer: Participant by inject(qualifier = named("dealer"))
val player: Participant by inject(qualifier = named("player"))
fun request(request: Request): TableState {
return when(request){
Request.HIT -> (dealer as Dealer).hit(player.hand)
Request.FOLD -> (dealer as Dealer).fold(player.hand)
Request.DEAL -> (dealer as Dealer).deal(player.hand)
}
}
fun showHandsAndScores(){
println("Player Score: ${player.score}")
println("Dealer Score: ${dealer.score}")
println("Player hand ${player.hand}")
println("Dealer hand ${dealer.hand}")
}
}
| 0
|
Kotlin
|
0
| 0
|
1808c97b5841f88fa2e3c65e220d61fd6c6a9fe7
| 1,358
|
heads_up_blackjack
|
Apache License 2.0
|
src/main/kotlin/com/between_freedom_and_space/mono_backend/posts/internal/reactions/service/model/UpdateCommentReactionModel.kt
|
Between-Freedom-and-Space
| 453,797,438
| false
|
{"Kotlin": 614504, "HTML": 8733, "Dockerfile": 503, "Shell": 166}
|
package com.between_freedom_and_space.mono_backend.posts.internal.reactions.service.model
import com.between_freedom_and_space.mono_backend.posts.internal.reactions.entities.Reaction
data class UpdateCommentReactionModel(
val newReaction: Reaction?,
)
| 0
|
Kotlin
|
0
| 1
|
812d8257e455e7d5b1d0c703a66b55ed2e1dcd35
| 259
|
Mono-Backend
|
Apache License 2.0
|
local/src/main/java/com/cheise_proj/local/db/LocalDb.kt
|
alvinmarshall
| 249,792,945
| false
| null |
package com.cheise_proj.local.db
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.cheise_proj.local.db.converter.ListConverters
import com.cheise_proj.local.db.converter.PortfolioConverter
import com.cheise_proj.local.db.dao.MessageDao
import com.cheise_proj.local.db.dao.PostDao
import com.cheise_proj.local.db.dao.UserDao
import com.cheise_proj.local.model.*
@Database(
entities = [UserLocal::class, ProfileLocal::class, ReviewsLocal::class, PostLocal::class, MessageLocal::class, SentMessageLocal::class],
version = 1,
exportSchema = false
)
@TypeConverters(ListConverters::class, PortfolioConverter::class)
abstract class LocalDb : RoomDatabase() {
abstract fun userDao(): UserDao
abstract fun postDao(): PostDao
abstract fun messageDao(): MessageDao
}
| 3
|
Kotlin
|
1
| 9
|
f64214c986ac8d228e5bc627ee847c0a74bd197f
| 845
|
Spiice-ui-challenge
|
MIT License
|
src/main/kotlin/com/github/mrgaabriel/ayla/website/routes/controllers/callbacks/UpdateAvailableCallbackController.kt
|
MrGaabriel
| 143,538,052
| false
| null |
package com.github.mrgaabriel.ayla.website.routes.controllers.callbacks
import com.github.kevinsawicki.http.HttpRequest
import com.github.mrgaabriel.ayla.utils.Constants
import com.github.mrgaabriel.ayla.utils.Static
import com.github.mrgaabriel.ayla.utils.extensions.await
import com.github.mrgaabriel.ayla.utils.extensions.ayla
import com.github.salomonbrys.kotson.*
import org.jooby.MediaType
import org.jooby.Request
import org.jooby.Response
import org.jooby.mvc.GET
import org.jooby.mvc.Path
import java.io.File
import java.net.URL
import kotlin.concurrent.thread
@Path("/api/update-available")
class UpdateAvailableCallbackController {
@GET
fun handle(req: Request, res: Response) {
res.type(MediaType.json)
// TODO: Mudar o sistema de autenticação
val header = req.header("Authorization")
if (!header.isSet) {
res.send(jsonObject(
"api:code" to 1,
"error" to "Needs authorization"
))
return
}
val content = header.value()
if (content != ayla.config.websiteMasterToken) {
res.send(jsonObject(
"api:code" to 1,
"error" to "Needs valid authorization"
))
return
}
thread {
Thread.sleep(5000)
val body = HttpRequest.get("https://teamcity.mrgaabriel.space/httpAuth/app/rest/builds/status:success/artifacts?guest=1")
.userAgent(Constants.USER_AGENT)
.accept("application/json")
.body()
val payload = Static.JSON_PARSER.parse(body).obj
val artifacts = payload["file"].array
val firstArtifact = artifacts.first()
val content = firstArtifact["content"].obj
val relativePath = content["href"].string
val bytes = HttpRequest.get("https://teamcity.mrgaabriel.space$relativePath?guest=1")
.userAgent(Constants.USER_AGENT)
.bytes()
File("Ayla-Update.jar").writeBytes(bytes)
ayla.shardManager.shutdown()
System.exit(0)
}
res.send("{}")
}
}
| 20
|
Kotlin
|
1
| 4
|
51768344e6b0b53fbbb5fb298cb88dea848a5faa
| 2,197
|
Ayla
|
MIT License
|
src/test/kotlin/no/nav/syfo/testutil/assertion/PPersonOppfolgingstilfelleAssertion.kt
|
navikt
| 189,998,720
| false
| null |
package no.nav.syfo.testutil.assertion
import no.nav.syfo.oversikthendelsetilfelle.domain.KOversikthendelsetilfelle
import no.nav.syfo.oversikthendelsetilfelle.domain.PPersonOppfolgingstilfelle
import org.amshove.kluent.shouldBeEqualTo
fun checkPPersonOppfolgingstilfelle(
pPersonOppfolgingstilfelle: PPersonOppfolgingstilfelle,
oversikthendelsetilfelle: KOversikthendelsetilfelle,
personId: Int,
) {
pPersonOppfolgingstilfelle.personOversiktStatusId shouldBeEqualTo personId
pPersonOppfolgingstilfelle.virksomhetsnummer shouldBeEqualTo oversikthendelsetilfelle.virksomhetsnummer
pPersonOppfolgingstilfelle.gradert shouldBeEqualTo oversikthendelsetilfelle.gradert
pPersonOppfolgingstilfelle.fom shouldBeEqualTo oversikthendelsetilfelle.fom
pPersonOppfolgingstilfelle.tom shouldBeEqualTo oversikthendelsetilfelle.tom
}
| 0
|
Kotlin
|
0
| 0
|
e5bf6ed6f4efdfd3bb9f5ad94ae41490b03cf1c4
| 852
|
syfooversiktsrv
|
MIT License
|
game/core/src/com/lyeeedar/AI/BehaviourTree/Actions/WaitBehaviourAction.kt
|
Lyeeedar
| 257,323,195
| false
| null |
package com.lyeeedar.AI.BehaviourTree.Actions
import com.badlogic.gdx.utils.ObjectMap
import com.lyeeedar.AI.BehaviourTree.BehaviourTreeState
import com.lyeeedar.AI.BehaviourTree.EvaluationState
import com.lyeeedar.AI.BehaviourTree.Nodes.AbstractBehaviourNode
import com.lyeeedar.AI.Tasks.TaskWait
import com.lyeeedar.Components.task
import com.lyeeedar.Util.CompiledExpression
import com.lyeeedar.Util.DataClass
import com.lyeeedar.Util.XmlData
import com.lyeeedar.Util.round
import ktx.collections.set
@DataClass(category = "Action")
class WaitBehaviourAction : AbstractBehaviourAction()
{
lateinit var count: CompiledExpression
override fun evaluate(state: BehaviourTreeState): EvaluationState
{
val task = state.entity.get()?.task() ?: return EvaluationState.FAILED
val num = count.evaluate(state.getVariables(), state.rng).round()
for (i in 0 until num)
{
task.tasks.add(TaskWait.obtain())
}
return EvaluationState.COMPLETED
}
//region generated
override fun load(xmlData: XmlData)
{
super.load(xmlData)
count = CompiledExpression(xmlData.get("Count", "1")!!)
}
override val classID: String = "Wait"
override fun resolve(nodes: ObjectMap<String, AbstractBehaviourNode>)
{
super.resolve(nodes)
}
//endregion
}
| 0
|
Kotlin
|
0
| 0
|
5068af2489fa6ff52a99016bceafca5690864754
| 1,254
|
PortalClosers
|
Apache License 2.0
|
src/test/kotlin/no/nav/omsorgspenger/routes/DokarkivproxyRouteTest.kt
|
navikt
| 314,496,410
| false
| null |
package no.nav.omsorgspenger.routes
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpMethod
import io.ktor.http.HttpStatusCode
import io.ktor.server.testing.TestApplicationEngine
import io.ktor.server.testing.handleRequest
import io.ktor.server.testing.setBody
import no.nav.omsorgspenger.testutils.AuthorizationHeaders.medAzure
import no.nav.omsorgspenger.testutils.TestApplicationExtension
import no.nav.omsorgspenger.testutils.mocks.ProxiedHeader
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
@ExtendWith(TestApplicationExtension::class)
internal class DokarkivproxyRouteTest(
private val testApplicationEngine: TestApplicationEngine
) {
private val dokarkivproxyUrl = "/dokarkivproxy-mock/test"
@Test
fun `ingen token gir 401`() {
with(testApplicationEngine) {
handleRequest(HttpMethod.Put, dokarkivproxyUrl) {}.apply {
assertThat(response.status()).isEqualTo(HttpStatusCode.Unauthorized)
}
}
}
@Test
fun `PUT - token utstedt til oms-proxy proxyer request`() {
with(testApplicationEngine) {
handleRequest(HttpMethod.Put, dokarkivproxyUrl) {
medAzure()
addHeader(HttpHeaders.ContentType, "application/json")
addHeader(ProxiedHeader, "anything")
setBody("{}")
}.apply {
assertThat(response.status()).isEqualTo(HttpStatusCode.OK)
assertThat(response.headers[HttpHeaders.ContentType]).isEqualTo("application/json")
}
}
}
@Test
fun `token scopet til annen tjeneste gir 403`() {
with(testApplicationEngine) {
handleRequest(HttpMethod.Put, dokarkivproxyUrl) {
medAzure(audience = "ikke-oms-proxy")
addHeader(HttpHeaders.ContentType, "application/json")
addHeader(ProxiedHeader, "anything")
}.apply {
assertThat(response.status()).isEqualTo(HttpStatusCode.Forbidden)
}
}
}
@Test
fun `token fra en ikke authorized client gir 403`() {
with(testApplicationEngine) {
handleRequest(HttpMethod.Put, dokarkivproxyUrl) {
medAzure(clientId = "not-allowed")
addHeader(HttpHeaders.ContentType, "application/json")
addHeader(ProxiedHeader, "anything")
}.apply {
assertThat(response.status()).isEqualTo(HttpStatusCode.Forbidden)
}
}
}
}
| 5
|
Kotlin
|
0
| 0
|
9d31fbb006adabefe190200b9881fafa98754bb4
| 2,613
|
omsorgspenger-proxy
|
MIT License
|
app/src/main/java/com/ouday/pokemon/details/ui/PokemonDetailsFragment.kt
|
oudaykhaled
| 325,652,014
| false
| null |
package com.ouday.pokemon.details.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.google.android.material.snackbar.Snackbar
import com.ouday.pokemon.R
import com.ouday.pokemon.core.Status
import com.ouday.pokemon.databinding.FragmentPokemonDetailsBinding
import com.ouday.pokemon.details.data.model.response.PokemonDetailsResponse
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
private const val BUNDLE_KEY_POKEMON_ID = "BUNDLE_KEY_POKEMON_ID"
@AndroidEntryPoint
class PokemonDetailsFragment : Fragment(R.layout.fragment_pokemon_details) {
private lateinit var viewModel: PokemonDetailsViewModel
private var pokemonID: Int = -1
@Inject
lateinit var viewModelFactory: PokemonDetailsViewModelFactory
private var _binding: FragmentPokemonDetailsBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentPokemonDetailsBinding.inflate(inflater, container, false)
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
pokemonID = requireArguments().getInt(BUNDLE_KEY_POKEMON_ID)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel =
ViewModelProvider(this, viewModelFactory).get(PokemonDetailsViewModel::class.java)
viewModel.pokemonDetailsWorker.observe(viewLifecycleOwner, { worker ->
when (worker.status) {
Status.SUCCESS -> binData(worker.data)
Status.LOADING -> showLoader()
Status.ERROR -> showError()
}
})
viewModel.fetchPokemonDetails(pokemonID)
}
private fun showLoader() {
binding.progressCircleDeterminate.visibility = View.VISIBLE
binding.content.visibility = View.GONE
}
private fun showError() {
val snackbar =
Snackbar.make(binding.coordinatorLayout, "Oops, failed to get pokemon details", Snackbar.LENGTH_INDEFINITE)
snackbar.setAction("Retry") {
viewModel.fetchPokemonDetails(pokemonID)
}
snackbar.show()
}
private fun binData(pokemonDetails: PokemonDetailsResponse?) {
binding.progressCircleDeterminate.visibility = View.GONE
binding.content.visibility = View.VISIBLE
val pokemonAbilities = StringBuilder()
val pokemonTypes = StringBuilder()
val pokemonMoves = StringBuilder()
pokemonDetails?.apply {
abilities.forEach {
pokemonAbilities.append("${it.ability.name.replace('-', ' ')}\n")
}
types.forEach {
pokemonTypes.append("${it.type.name.replace('-', ' ')}\n")
}
moves.forEach {
pokemonMoves.append("${it.move.name.replace('-', ' ')}\n")
}
}
binding.lblAbilities.text = pokemonAbilities.toString()
binding.lblTypes.text = pokemonTypes.toString()
binding.lblMoves.text = pokemonMoves.toString()
}
companion object {
fun wrapBundle(pokemonID: Int): Bundle {
val bundle = Bundle()
bundle.putInt(BUNDLE_KEY_POKEMON_ID, pokemonID)
return bundle
}
}
}
| 0
|
Kotlin
|
0
| 0
|
7b5116f006766e795feb07b84b5ce1e14d0ab216
| 3,708
|
Pokemonv2
|
Apache License 2.0
|
pulsar-skeleton/src/main/kotlin/ai/platon/pulsar/experimental/transport/crawl/CrawlPipeline.kt
|
platonai
| 124,882,400
| false
| null |
package ai.platon.pulsar.experimental.transport.crawl
import ai.platon.pulsar.common.urls.UrlAware
import ai.platon.pulsar.crawl.WebPageHandler
import ai.platon.pulsar.dom.FeaturedDocument
import ai.platon.pulsar.experimental.transport.*
import ai.platon.pulsar.persist.WebPage
import java.util.concurrent.ExecutorService
class UrlContext(
val url: String,
pipeline: DefaultChannelPipeline,
executor: ExecutorService,
name: String,
override var handler: ChannelHandler
) : AbstractChannelHandlerContext(pipeline, executor, name, handler::class) {
override val channel: Channel = pipeline.channel
}
class UrlHandle : ChannelHandlerAdapter() {
override fun handlerAdded(context: ChannelHandlerContext) {
TODO("Not yet implemented")
}
override fun handlerRemoved(context: ChannelHandlerContext) {
TODO("Not yet implemented")
}
override fun channelRead(context: ChannelHandlerContext, msg: Any?) {
TODO("Not yet implemented")
}
override fun channelWrite(context: ChannelHandlerContext, msg: Any?) {
TODO("Not yet implemented")
}
}
class UrlAwareHandlerContext(
val url: UrlAware,
pipeline: DefaultChannelPipeline,
executor: ExecutorService,
name: String,
override var handler: ChannelHandler,
) : AbstractChannelHandlerContext(pipeline, executor, name, handler) {
override val channel: Channel = pipeline.channel
}
class WebPageHandlerContext(
val page: WebPage,
pipeline: DefaultChannelPipeline,
executor: ExecutorService,
name: String,
override var handler: ChannelHandler,
) : AbstractChannelHandlerContext(pipeline, executor, name, handler) {
override val channel: Channel = pipeline.channel
}
class HtmlDocumentHandlerContext(
val document: FeaturedDocument,
pipeline: DefaultChannelPipeline,
executor: ExecutorService,
name: String,
override var handler: ChannelHandler,
) : AbstractChannelHandlerContext(pipeline, executor, name, handler) {
override val channel: Channel = pipeline.channel
}
class MyWebPageHandlerPipeline : WebPageHandler() {
private val registeredHandlers = mutableListOf<WebPageHandler>()
fun addFirst(handler: WebPageHandler): MyWebPageHandlerPipeline {
registeredHandlers.add(0, handler)
return this
}
fun addFirst(vararg handlers: WebPageHandler): MyWebPageHandlerPipeline {
handlers.toCollection(registeredHandlers)
return this
}
fun addLast(handler: WebPageHandler): MyWebPageHandlerPipeline {
registeredHandlers.add(handler)
return this
}
fun addLast(vararg handlers: WebPageHandler): MyWebPageHandlerPipeline {
handlers.toCollection(registeredHandlers)
return this
}
override operator fun invoke(page: WebPage) {
registeredHandlers.forEach { it(page) }
}
}
| 1
|
HTML
|
32
| 110
|
f93bccf5075009dc7766442d3a23b5268c721f54
| 2,879
|
pulsar
|
Apache License 2.0
|
css-gg/src/commonMain/kotlin/compose/icons/cssggicons/Moon.kt
|
DevSrSouza
| 311,134,756
| false
|
{"Kotlin": 36719092}
|
package compose.icons.cssggicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
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 compose.icons.CssGgIcons
public val CssGgIcons.Moon: ImageVector
get() {
if (_moon != null) {
return _moon!!
}
_moon = Builder(name = "Moon", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd) {
moveTo(12.226f, 2.003f)
curveTo(9.592f, 1.943f, 6.939f, 2.919f, 4.929f, 4.929f)
curveTo(1.024f, 8.834f, 1.024f, 15.166f, 4.929f, 19.071f)
curveTo(8.834f, 22.976f, 15.166f, 22.976f, 19.071f, 19.071f)
curveTo(21.081f, 17.061f, 22.056f, 14.408f, 21.997f, 11.774f)
curveTo(21.98f, 10.977f, 21.867f, 10.182f, 21.66f, 9.406f)
curveTo(21.093f, 9.949f, 20.508f, 10.428f, 19.916f, 10.842f)
curveTo(18.565f, 11.791f, 17.183f, 12.405f, 15.93f, 12.684f)
curveTo(14.024f, 13.107f, 12.716f, 12.716f, 12.0f, 12.0f)
curveTo(11.284f, 11.284f, 10.893f, 9.976f, 11.316f, 8.07f)
curveTo(11.595f, 6.817f, 12.209f, 5.435f, 13.158f, 4.084f)
curveTo(13.572f, 3.492f, 14.051f, 2.907f, 14.594f, 2.34f)
curveTo(13.818f, 2.133f, 13.023f, 2.02f, 12.226f, 2.003f)
close()
moveTo(17.657f, 17.657f)
curveTo(18.908f, 16.406f, 19.658f, 14.843f, 19.907f, 13.219f)
curveTo(16.361f, 15.264f, 12.638f, 15.466f, 10.586f, 13.414f)
curveTo(8.534f, 11.362f, 8.736f, 7.639f, 10.781f, 4.093f)
curveTo(9.157f, 4.342f, 7.594f, 5.092f, 6.343f, 6.343f)
curveTo(3.219f, 9.467f, 3.219f, 14.533f, 6.343f, 17.657f)
curveTo(9.467f, 20.781f, 14.533f, 20.781f, 17.657f, 17.657f)
close()
}
}
.build()
return _moon!!
}
private var _moon: ImageVector? = null
| 17
|
Kotlin
|
25
| 571
|
a660e5f3033e3222e3553f5a6e888b7054aed8cd
| 2,649
|
compose-icons
|
MIT License
|
app/src/main/java/com/example/sceneformar/ScanFragment.kt
|
SaaHeal
| 669,189,493
| false
|
{"Java": 978158, "Kotlin": 22086}
|
package com.example.sceneformar
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.budiyev.android.codescanner.AutoFocusMode
import com.budiyev.android.codescanner.CodeScanner
import com.budiyev.android.codescanner.CodeScannerView
import com.budiyev.android.codescanner.DecodeCallback
import com.budiyev.android.codescanner.ErrorCallback
import com.budiyev.android.codescanner.ScanMode
class ScanFragment : Fragment() {
private lateinit var codeScanner: CodeScanner
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
val view=inflater.inflate(R.layout.fragment_scan, container, false)
return view;
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val scannerView = view.findViewById<CodeScannerView>(R.id.scanner_view)
val activity = requireActivity()
codeScanner = CodeScanner(activity, scannerView)
codeScanner.decodeCallback = DecodeCallback {
activity.runOnUiThread {
val intent = Intent(activity, ARActivity::class.java)
val name = when(it.text)
{
"prod1" ->
{
"Laptop (Windows 10)"
}
"prod5" ->{
"Smart TV (Android)"
}
else ->
{
"no"
}
}
if(name.equals("no"))
{
Toast.makeText(activity,"Sorry, currently AR view for this product isn't available",Toast.LENGTH_SHORT).show()
}
else
{
intent.putExtra("name",name)
startActivity(intent)
}
}
}
scannerView.setOnClickListener {
codeScanner.startPreview()
}
}
override fun onResume() {
super.onResume()
codeScanner.startPreview()
}
override fun onPause() {
codeScanner.releaseResources()
super.onPause()
}
}
| 1
| null |
1
| 1
|
379d61bbaa307a040a29a833206bb0f220831218
| 2,391
|
WallARt
|
Apache License 2.0
|
AstroYoga/astroyoga/src/main/java/com/shushant/astroyoga/navigation/AstroYogaHomeNavigation.kt
|
ShushantTiwari-ashu
| 667,410,698
| false
| null |
package com.shushant.astroyoga.navigation
import androidx.navigation.NavGraphBuilder
import androidx.navigation.navigation
import com.shushant.astroyoga.compatibility.navigation.compatibilityScreen
import com.shushant.astroyoga.compatibility.navigation.profileScreen
import com.shushant.astroyoga.data.datastore.PrefStorage
import com.shushant.astroyoga.horoscope.navigation.horoscopeScreen
import com.shushant.astroyoga.onboard.navigation.OnBoarding
import com.shushant.astroyoga.onboard.navigation.astroOnBoarding
import com.shushant.astroyoga.onboard.navigation.astroSplash
import com.shushant.navigation.AppComposeNavigator
import com.shushant.navigation.Graph
import com.shushant.navigation.destinations.BottomNavItem
fun NavGraphBuilder.onBoardingGraph(
composeNavigator: AppComposeNavigator,
) {
navigation(
route = Graph.ONBOARDING,
startDestination = OnBoarding.OnBoard.name
) {
astroOnBoarding(composeNavigator)
}
}
fun NavGraphBuilder.splashGraph(
composeNavigator: AppComposeNavigator,
preferences: PrefStorage,
) {
navigation(
route = Graph.SPLASH,
startDestination = OnBoarding.Splash.name
) {
astroSplash(
composeNavigator = composeNavigator,
preferences = preferences,
)
}
}
fun NavGraphBuilder.homeGraph(
composeNavigator: AppComposeNavigator,
) {
navigation(
route = Graph.HOME,
startDestination = BottomNavItem.Horoscope.screen_route
) {
horoscopeScreen(composeNavigator)
compatibilityScreen(composeNavigator)
profileScreen(composeNavigator)
}
}
| 0
|
Kotlin
|
0
| 0
|
9882d51d4a1d975249109c097da0c7b141e6ff69
| 1,645
|
AstroYoga-Full-kotlin-stack-App
|
Apache License 2.0
|
buildSrc/src/main/kotlin/IosTarget.kt
|
stefanthaler
| 595,257,790
| false
| null |
import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension
import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget
// https://kotlinlang.org/docs/multiplatform-mobile-ios-dependencies.html#workaround-to-enable-ide-support-for-the-shared-ios-source-set
fun KotlinMultiplatformExtension.iosTarget(
configure: KotlinNativeTarget.() -> Unit = { }
) {
iosX64(configure)
iosArm64(configure)
iosSimulatorArm64(configure)
}
| 0
|
Kotlin
|
0
| 0
|
55a517cb69166d4ac139200004c5fdfc57c5065e
| 451
|
kmp-template
|
Apache License 2.0
|
app/src/androidTest/java/com/gobinda/notepad/ui/screens/addEditNote/ContentInputViewTest.kt
|
gobinda1547
| 772,135,935
| false
|
{"Kotlin": 120416}
|
package com.gobinda.notepad.ui.screens.addEditNote
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertTextEquals
import androidx.compose.ui.test.hasTestTag
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.performTextClearance
import androidx.compose.ui.test.performTextInput
import com.gobinda.notepad.ui.screens.common.TestTag
import org.junit.Rule
import org.junit.Test
class ContentInputViewTest {
companion object {
private const val HINT_TEXT = "this is a hint text"
private const val MAIN_TEXT = "the is a test text"
}
@get:Rule
val composeRule = createComposeRule()
@Test
fun contentInputView_showHintText_whenMainTextIsEmpty() {
composeRule.setContent {
ContentInputView(
text = "",
hintText = HINT_TEXT,
onValueChanged = { }
)
}
val hintText = hasTestTag(TestTag.ContentInputView_HintText)
composeRule.onNode(hintText).assertIsDisplayed()
composeRule.onNode(hintText).assertTextEquals(HINT_TEXT)
}
@Test
fun contentInputView_hideHintText_whenMainTextIsNotEmpty() {
composeRule.setContent {
ContentInputView(
text = MAIN_TEXT,
hintText = HINT_TEXT,
onValueChanged = { }
)
}
val hintTextView = hasTestTag(TestTag.ContentInputView_HintText)
val mainTextView = hasTestTag(TestTag.ContentInputView_InputField)
composeRule.onNode(hintTextView).assertDoesNotExist()
composeRule.onNode(mainTextView).assertIsDisplayed()
composeRule.onNode(mainTextView).assertTextEquals(MAIN_TEXT)
}
@Test
fun contentInputView_updateMainText_whenWriteSomething() {
val textInputData = mutableStateOf("")
composeRule.setContent {
ContentInputView(
text = textInputData.value,
hintText = HINT_TEXT,
onValueChanged = { textInputData.value = it }
)
}
val hintTextView = hasTestTag(TestTag.ContentInputView_HintText)
val inputField = hasTestTag(TestTag.ContentInputView_InputField)
// initially hint will be visible
composeRule.onNode(hintTextView).assertIsDisplayed()
composeRule.onNode(hintTextView).assertTextEquals(HINT_TEXT)
composeRule.onNode(inputField).assertTextEquals("")
// writing some text in the input field
composeRule.onNode(inputField).performTextInput("new text")
// now hint will be invisible & input field will be visible
composeRule.onNode(hintTextView).assertDoesNotExist()
composeRule.onNode(inputField).assertIsDisplayed()
composeRule.onNode(inputField).assertTextEquals("new text")
// again writing some text in the input field
composeRule.onNode(inputField).performTextInput(" done")
// so hint will be invisible & input field will be visible
composeRule.onNode(hintTextView).assertDoesNotExist()
composeRule.onNode(inputField).assertIsDisplayed()
composeRule.onNode(inputField).assertTextEquals("new text done")
// now clear text from the input field
composeRule.onNode(inputField).performTextClearance()
// so again - hint will be visible
composeRule.onNode(hintTextView).assertIsDisplayed()
composeRule.onNode(hintTextView).assertTextEquals(HINT_TEXT)
composeRule.onNode(inputField).assertTextEquals("")
}
}
| 0
|
Kotlin
|
0
| 1
|
76baccd61cc71523cd5c64112559a53c174e0efa
| 3,653
|
Notepad-Android-App
|
MIT License
|
catalogue/src/main/kotlin/com/tidal/sdk/catalogue/generated/models/ExternalLink.kt
|
tidal-music
| 806,866,286
| false
|
{"Kotlin": 1644272, "Shell": 9249}
|
/**
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package com.tidal.sdk.catalogue.generated.models
import com.tidal.sdk.catalogue.generated.models.ExternalLinkMeta
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerialName
import kotlinx.serialization.Contextual
/**
*
*
* @param href link to something that is related to a resource
* @param meta
*/
@Serializable
data class ExternalLink (
/* link to something that is related to a resource */
@SerialName(value = "href")
val href: kotlin.String,
@SerialName(value = "meta")
val meta: ExternalLinkMeta
)
| 27
|
Kotlin
|
0
| 22
|
127085338619bab6d540bedf05f7d34a3cd1a9da
| 834
|
tidal-sdk-android
|
Apache License 2.0
|
calendarheatmaplib/src/main/java/com/eudycontreras/calendarheatmaplibrary/animations/MatrixRevealAnimation.kt
|
EudyContreras
| 256,645,326
| false
| null |
package com.eudycontreras.calendarheatmaplibrary.animations
import android.view.animation.Interpolator
import androidx.core.math.MathUtils
import androidx.interpolator.view.animation.FastOutSlowInInterpolator
import com.eudycontreras.calendarheatmaplibrary.MAX_OFFSET
import com.eudycontreras.calendarheatmaplibrary.MIN_OFFSET
import com.eudycontreras.calendarheatmaplibrary.common.Animateable
import com.eudycontreras.calendarheatmaplibrary.common.CalHeatMap
import com.eudycontreras.calendarheatmaplibrary.manDistance
import com.eudycontreras.calendarheatmaplibrary.mapRange
import com.eudycontreras.calendarheatmaplibrary.properties.Index
/**
* Copyright (C) 2020 Project X
*
* @Project ProjectX
* @author <NAME>.
* @since April 2020
*/
internal class MatrixRevealAnimation<T : Animateable> : HeatMapAnimation<Array<Array<T>>> {
override var interpolator: Interpolator = FastOutSlowInInterpolator()
override var duration: Long = 0
override var delay: Long = 0
override var onEnd: (() -> Unit)? = null
override var onStart: (() -> Unit)? = null
var fromIndex: Index? = null
var stagger: Long = 0
override fun animate(heatMap: CalHeatMap, animateable: Array<Array<T>>) {
val midRowIndex = animateable.size / 2
val midColIndex = animateable[midRowIndex].size / 2
val epiCenter = fromIndex ?: Index(
row = midRowIndex,
col = midColIndex
)
performSequentialAnimation(epiCenter, heatMap, animateable)
}
private fun performSequentialAnimation(
epiCenter: Index,
heatMap: CalHeatMap,
animateable: Array<Array<T>>
) {
val indexMaps = createOrder(animateable.size, animateable[0].size, epiCenter)
val startPoints = Array(animateable.size) {
Array(animateable[it].size) { Pair(MIN_OFFSET, MIN_OFFSET) }
}
val values: Array<Array<Pair<Float, Float>>> = Array(animateable.size) {
Array(animateable[it].size) { Pair(MIN_OFFSET, MIN_OFFSET) }
}
var start = 0L
var end = start + duration
var totalDuration = duration
startPoints[0][0] = (start.toFloat() to end.toFloat())
for (entries in indexMaps) {
start += stagger
end = start + duration
totalDuration += stagger
for (index in entries.value) {
values[index.row][index.col] = (MIN_OFFSET to MAX_OFFSET)
startPoints[index.row][index.col] = (start.toFloat() to end.toFloat())
}
}
val indexes = indexMaps.values.flatten()
val animation = AnimationEvent(
duration = totalDuration,
startDelay = delay,
onEnd = onEnd,
onStart = {
for (row in animateable) {
for (col in row) {
col.onPreAnimation()
}
}
onStart?.invoke()
},
updateListener = { _, currentPlayTime, _ ->
for (index in indexes) {
val rowIndex = index.row
val colIndex = index.col
val currentTime = currentPlayTime.toFloat()
val animate = MathUtils.clamp(
mapRange(
currentTime,
startPoints[rowIndex][colIndex].first,
startPoints[rowIndex][colIndex].second,
values[rowIndex][colIndex].first,
values[rowIndex][colIndex].second
),
values[rowIndex][colIndex].first,
values[rowIndex][colIndex].second
)
animateable[rowIndex][colIndex].onAnimate(interpolator.getInterpolation(animate))
}
}
)
heatMap.addAnimation(animation)
}
private fun createOrder(
itemRowCount: Int,
itemColCount: Int,
fromIndex: Index
): Map<Int, List<Index>> {
val indexes: ArrayList<Index> = ArrayList()
for (row in 0 until itemRowCount) {
for (col in 0 until itemColCount) {
indexes.add(
Index(
row = row,
col = col,
weight = manDistance(fromIndex.row, fromIndex.col, row, col)
)
)
}
}
indexes.sortBy { it.weight }
return indexes.groupBy { it.weight }
}
}
| 1
|
Kotlin
|
1
| 8
|
973203fb1e063ded41133b44925ce87a018ba6ec
| 4,643
|
Calendar-HeatMap
|
MIT License
|
src/main/kotlin/br/com/zup/pix/remove/RemoveChaveService.kt
|
abner-ribeiro
| 407,355,686
| true
|
{"Kotlin": 39027}
|
package br.com.zup.pix.remove
import br.com.zup.pix.client.bcb.BancoCentralClient
import br.com.zup.pix.client.bcb.deletaChave.DeletaChavePixBcbRequest
import br.com.zup.pix.client.itau.ClienteResponse
import br.com.zup.pix.client.itau.ErpItauClient
import br.com.zup.pix.dto.RemoveChaveDto
import br.com.zup.pix.registra.ClienteNaoEncontradoException
import br.com.zup.repositorio.ChavePixRepository
import io.micronaut.http.HttpResponse
import io.micronaut.http.HttpStatus
import io.micronaut.validation.Validated
import jakarta.inject.Singleton
import java.lang.Exception
import javax.validation.Valid
@Validated
@Singleton
class RemoveChaveService(val chavePixRepository: ChavePixRepository,
val erpItauClient: ErpItauClient,
val bcbClient: BancoCentralClient
) {
fun validaERemove(@Valid removeChaveDto: RemoveChaveDto){
try {
val clientResponse: HttpResponse<ClienteResponse> = erpItauClient.consulta(removeChaveDto.clienteId!!)
}catch(e: Exception){
throw ClienteNaoEncontradoException()
}
val possivelChave = chavePixRepository.findByIdAndClienteId(
removeChaveDto.pixId,
removeChaveDto.clienteId
)
if(possivelChave.isEmpty)
throw ChaveNaoEncontradaException()
val chave = possivelChave.get()
val bcbResponse = bcbClient.delete(chave.chave!!, DeletaChavePixBcbRequest(chave.chave!!))
if (bcbResponse.status != HttpStatus.OK) {
throw IllegalStateException("Erro ao remover chave Pix no Banco Central do Brasil (BCB)")
}
chavePixRepository.deleteById(removeChaveDto.pixId)
}
}
| 0
|
Kotlin
|
0
| 0
|
99f36d1d0f5f6a54b8b9c73516f8128bac5128a8
| 1,707
|
orange-talents-07-template-pix-keymanager-grpc
|
Apache License 2.0
|
app/src/main/java/com/pr0gramm/app/services/SettingsTrackerService.kt
|
Egosar93
| 232,908,553
| true
|
{"Kotlin": 1230722, "Shell": 6886, "Python": 1124}
|
package com.pr0gramm.app.services
import com.pr0gramm.app.*
import okhttp3.OkHttpClient
import proguard.annotation.KeepPublicClassMemberNames
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.Body
import retrofit2.http.POST
class SettingsTrackerService(httpClient: OkHttpClient) {
private val logger = Logger("SettingsTrackerService")
private val settings: Settings = Settings.get()
private val httpInterface: HttpInterface = Retrofit.Builder()
.baseUrl("$ServiceBaseURL/")
.client(httpClient)
.addConverterFactory(MoshiConverterFactory.create(MoshiInstance))
.validateEagerly(BuildConfig.DEBUG)
.build()
.create(HttpInterface::class.java)
suspend fun track() {
val values = settings.raw().all.filterKeys { it.startsWith("pref_") }
val payload = mapOf(
"version" to BuildConfig.VERSION_CODE,
"settings" to values)
httpInterface.track(payload)
logger.debug { "Tracked settings successfully." }
}
@KeepPublicClassMemberNames
private interface HttpInterface {
@POST("track-settings")
suspend fun track(@Body values: Any)
}
}
| 0
| null |
0
| 0
|
0981f6a2b2f13824071001a3a02193a1b0eee998
| 1,269
|
Pr0
|
MIT License
|
sdk/src/main/java/com/localehub/sdk/data/enums/Culture+EnglishDescription.kt
|
locale-hub
| 383,744,946
| false
| null |
package com.localehub.sdk.data.enums
fun Culture.englishDescription(): String {
return when(this) {
Culture.af_ZA -> "Afrikaans (South Africa)"
Culture.ar_AE -> "Arabic (U.A.E.)"
Culture.ar_BH -> "Arabic (Bahrain)"
Culture.ar_DJ -> "Arabic (Djibouti)"
Culture.ar_DZ -> "Arabic (Algeria)"
Culture.ar_EG -> "Arabic (Egypt)"
Culture.ar_EH -> "Arabic (Western Sahara)"
Culture.ar_ER -> "Arabic (Eritrea)"
Culture.ar_IL -> "Arabic (Israel)"
Culture.ar_IQ -> "Arabic (Iraq)"
Culture.ar_JO -> "Arabic (Jordan)"
Culture.ar_KM -> "Arabic (Comoros)"
Culture.ar_KW -> "Arabic (Kuwait)"
Culture.ar_LB -> "Arabic (Lebanon)"
Culture.ar_LY -> "Arabic (Libya)"
Culture.ar_MA -> "Arabic (Morocco)"
Culture.ar_MR -> "Arabic (Mauritania)"
Culture.ar_OM -> "Arabic (Oman)"
Culture.ar_PS -> "Arabic (Palestinian Territories)"
Culture.ar_QA -> "Arabic (Qatar)"
Culture.ar_SA -> "Arabic (Saudi Arabia)"
Culture.ar_SD -> "Arabic (Sudan)"
Culture.ar_SO -> "Arabic (Somalia)"
Culture.ar_SS -> "Arabic (South Sudan)"
Culture.ar_SY -> "Arabic (Syria)"
Culture.ar_TD -> "Arabic (Chad)"
Culture.ar_TN -> "Arabic (Tunisia)"
Culture.ar_YE -> "Arabic (Yemen)"
Culture.as_IN -> "Assamese (India)"
Culture.asa_TZ -> "Asu (Tanzania)"
Culture.az_AZ -> "Azeri (Latin) (Azerbaijan)"
Culture.az_Cyrl -> "Azerbaijani (Cyrillic)"
Culture.az_Cyrl_AZ -> "Azeri (Cyrillic) (Azerbaijan)"
Culture.az_Latn -> "Azerbaijani (Latin)"
Culture.az_Latn_AZ -> "Azerbaijani (Latin Azerbaijan)"
Culture.bas_CM -> "Basaa (Cameroon)"
Culture.be_BY -> "Belarusian (Belarus)"
Culture.bem_ZM -> "Bemba (Zambia)"
Culture.bez_TZ -> "Bena (Tanzania)"
Culture.bg_BG -> "Bulgarian (Bulgaria)"
Culture.bm_ML -> "Bambara (Mali)"
Culture.bn_BD -> "Bengali (Bangladesh)"
Culture.bn_IN -> "Bengali (India)"
Culture.bo_CN -> "Tibetan (China)"
Culture.bo_IN -> "Tibetan (India)"
Culture.br_FR -> "Breton (France)"
Culture.brx_IN -> "Bodo (India)"
Culture.bs_BA -> "Bosnian (Bosnia and Herzegovina)"
Culture.bs_Cyrl -> "Bosnian (Cyrillic)"
Culture.bs_Cyrl_BA -> "Bosnian (Cyrillic Bosnia & Herzegovina)"
Culture.bs_Latn -> "Bosnian (Latin)"
Culture.bs_Latn_BA -> "Bosnian (Latin Bosnia & Herzegovina)"
Culture.ca_AD -> "Catalan (Andorra)"
Culture.ca_ES -> "Catalan (Spain)"
Culture.ca_FR -> "Catalan (France)"
Culture.ca_IT -> "Catalan (Italy)"
Culture.ce_RU -> "Chechen (Russia)"
Culture.cgg_UG -> "Chiga (Uganda)"
Culture.chr_US -> "Cherokee (U.S.)"
Culture.cs_CZ -> "Czech (Czech Republic)"
Culture.cy_GB -> "Welsh (U.K.)"
Culture.da_DK -> "Danish (Denmark)"
Culture.dav_KE -> "Taita (Kenya)"
Culture.de_AT -> "German (Austria)"
Culture.de_BE -> "German (Belgium)"
Culture.de_CH -> "German (Switzerland)"
Culture.de_DE -> "German (Germany)"
Culture.de_IT -> "German (Italy)"
Culture.de_LI -> "German (Liechtenstein)"
Culture.de_LU -> "German (Luxembourg)"
Culture.dje_NE -> "Zarma (Niger)"
Culture.dsb_DE -> "Lower Sorbian (Germany)"
Culture.dua_CM -> "Duala (Cameroon)"
Culture.dv_MV -> "Divehi (Maldives)"
Culture.dyo_SN -> "Jola-Fonyi (Senegal)"
Culture.dz_BT -> "Dzongkha (Bhutan)"
Culture.ebu_KE -> "Embu (Kenya)"
Culture.ee_GH -> "Ewe (Ghana)"
Culture.ee_TG -> "Ewe (Togo)"
Culture.el_CY -> "Greek (Cyprus)"
Culture.el_GR -> "Greek (Greece)"
Culture.en_AG -> "English (Antigua & Barbuda)"
Culture.en_AI -> "English (Anguilla)"
Culture.en_AS -> "English (American Samoa)"
Culture.en_AT -> "English (Austria)"
Culture.en_AU -> "English (Australia)"
Culture.en_BB -> "English (Barbados)"
Culture.en_BE -> "English (Belgium)"
Culture.en_BI -> "English (Burundi)"
Culture.en_BM -> "English (Bermuda)"
Culture.en_BS -> "English (Bahamas)"
Culture.en_BW -> "English (Botswana)"
Culture.en_BZ -> "English (Belize)"
Culture.en_CA -> "English (Canada)"
Culture.en_CB -> "English (Caribbean)"
Culture.en_CC -> "English (Cocos [Keeling] Islands)"
Culture.en_CH -> "English (Switzerland)"
Culture.en_CK -> "English (Cook Islands)"
Culture.en_CM -> "English (Cameroon)"
Culture.en_CX -> "English (Christmas Island)"
Culture.en_CY -> "English (Cyprus)"
Culture.en_DE -> "English (Germany)"
Culture.en_DG -> "English (Diego Garcia)"
Culture.en_DK -> "English (Denmark)"
Culture.en_DM -> "English (Dominica)"
Culture.en_ER -> "English (Eritrea)"
Culture.en_FI -> "English (Finland)"
Culture.en_FJ -> "English (Fiji)"
Culture.en_FK -> "English (Falkland Islands)"
Culture.en_FM -> "English (Micronesia)"
Culture.en_GB -> "English (U.K.)"
Culture.en_GD -> "English (Grenada)"
Culture.en_GG -> "English (Guernsey)"
Culture.en_GH -> "English (Ghana)"
Culture.en_GI -> "English (Gibraltar)"
Culture.en_GM -> "English (Gambia)"
Culture.en_GU -> "English (Guam)"
Culture.en_GY -> "English (Guyana)"
Culture.en_HK -> "English (Hong Kong SAR China)"
Culture.en_IE -> "English (Ireland)"
Culture.en_IL -> "English (Israel)"
Culture.en_IM -> "English (Isle of Man)"
Culture.en_IN -> "English (India)"
Culture.en_IO -> "English (British Indian Ocean Territory)"
Culture.en_JE -> "English (Jersey)"
Culture.en_JM -> "English (Jamaica)"
Culture.en_KE -> "English (Kenya)"
Culture.en_KI -> "English (Kiribati)"
Culture.en_KN -> "English (St. Kitts & Nevis)"
Culture.en_KY -> "English (Cayman Islands)"
Culture.en_LC -> "English (St. Lucia)"
Culture.en_LR -> "English (Liberia)"
Culture.en_LS -> "English (Lesotho)"
Culture.en_MG -> "English (Madagascar)"
Culture.en_MH -> "English (Marshall Islands)"
Culture.en_MO -> "English (Macau SAR China)"
Culture.en_MP -> "English (Northern Mariana Islands)"
Culture.en_MS -> "English (Montserrat)"
Culture.en_MT -> "English (Malta)"
Culture.en_MU -> "English (Mauritius)"
Culture.en_MW -> "English (Malawi)"
Culture.en_MY -> "English (Malaysia)"
Culture.en_NA -> "English (Namibia)"
Culture.en_NF -> "English (Norfolk Island)"
Culture.en_NG -> "English (Nigeria)"
Culture.en_NL -> "English (Netherlands)"
Culture.en_NR -> "English (Nauru)"
Culture.en_NU -> "English (Niue)"
Culture.en_NZ -> "English (New Zealand)"
Culture.en_PG -> "English (Papua New Guinea)"
Culture.en_PH -> "English (Republic of the Philippines)"
Culture.en_PK -> "English (Pakistan)"
Culture.en_PN -> "English (Pitcairn Islands)"
Culture.en_PR -> "English (Puerto Rico)"
Culture.en_PW -> "English (Palau)"
Culture.en_RW -> "English (Rwanda)"
Culture.en_SB -> "English (Solomon Islands)"
Culture.en_SC -> "English (Seychelles)"
Culture.en_SD -> "English (Sudan)"
Culture.en_SE -> "English (Sweden)"
Culture.en_SG -> "English (Singapore)"
Culture.en_SH -> "English (St. Helena)"
Culture.en_SI -> "English (Slovenia)"
Culture.en_SL -> "English (Sierra Leone)"
Culture.en_SS -> "English (South Sudan)"
Culture.en_SX -> "English (Sint Maarten)"
Culture.en_SZ -> "English (Swaziland)"
Culture.en_TC -> "English (Turks & Caicos Islands)"
Culture.en_TK -> "English (Tokelau)"
Culture.en_TO -> "English (Tonga)"
Culture.en_TT -> "English (Trinidad and Tobago)"
Culture.en_TV -> "English (Tuvalu)"
Culture.en_TZ -> "English (Tanzania)"
Culture.en_UG -> "English (Uganda)"
Culture.en_UM -> "English (U.S. Outlying Islands)"
Culture.en_US -> "English (U.S.)"
Culture.en_VC -> "English (St. Vincent & Grenadines)"
Culture.en_VG -> "English (British Virgin Islands)"
Culture.en_VI -> "English (U.S. Virgin Islands)"
Culture.en_VU -> "English (Vanuatu)"
Culture.en_WS -> "English (Samoa)"
Culture.en_ZA -> "English (South Africa)"
Culture.en_ZM -> "English (Zambia)"
Culture.en_ZW -> "English (Zimbabwe)"
Culture.eo_PL -> "Esperanto (Poland)"
Culture.es_AR -> "Spanish (Argentina)"
Culture.es_BO -> "Spanish (Bolivia)"
Culture.es_BR -> "Spanish (Brazil)"
Culture.es_BZ -> "Spanish (Belize)"
Culture.es_CL -> "Spanish (Chile)"
Culture.es_CO -> "Spanish (Colombia)"
Culture.es_CR -> "Spanish (Costa Rica)"
Culture.es_CU -> "Spanish (Cuba)"
Culture.es_DO -> "Spanish (Dominican Republic)"
Culture.es_EA -> "Spanish (Ceuta & Melilla"
Culture.es_EC -> "Spanish (Ecuador)"
Culture.es_ES -> "Spanish (Spain)"
Culture.es_GQ -> "Spanish (Equatorial Guinea)"
Culture.es_GT -> "Spanish (Guatemala)"
Culture.es_HN -> "Spanish (Honduras)"
Culture.es_IC -> "Spanish (Canary Islands)"
Culture.es_MX -> "Spanish (Mexico)"
Culture.es_NI -> "Spanish (Nicaragua)"
Culture.es_PA -> "Spanish (Panama)"
Culture.es_PE -> "Spanish (Peru)"
Culture.es_PR -> "Spanish (Puerto Rico)"
Culture.es_PY -> "Spanish (Paraguay)"
Culture.es_SV -> "Spanish (El Salvador)"
Culture.es_US -> "Spanish (U.S.)"
Culture.es_UY -> "Spanish (Uruguay)"
Culture.es_VE -> "Spanish (Venezuela)"
Culture.et_EE -> "Estonian (Estonia)"
Culture.eu_ES -> "Basque (Spain)"
Culture.ewo_CM -> "Ewondo (Cameroon)"
Culture.fa_AF -> "Persian (Afghanistan)"
Culture.fa_IR -> "Farsi (Iran)"
Culture.ff_CM -> "Fulah (Cameroon"
Culture.ff_GN -> "Fulah (Guinea)"
Culture.ff_MR -> "Fulah (Mauritania)"
Culture.ff_SN -> "Fulah (Senegal)"
Culture.fi_FI -> "Finnish (Finland)"
Culture.fil_PH -> "Filipino (Philippines)"
Culture.fo_DK -> "Faroese (Denmark)"
Culture.fo_FO -> "Faroese (Faroe Islands)"
Culture.fr_BE -> "French (Belgium)"
Culture.fr_BF -> "French (Burkina Faso)"
Culture.fr_BI -> "French (Burundi)"
Culture.fr_BJ -> "French (Benin)"
Culture.fr_BL -> "French (St. Barthélemy)"
Culture.fr_CA -> "French (Canada)"
Culture.fr_CD -> "French (Congo - Kinshasa)"
Culture.fr_CF -> "French (Central African Republic)"
Culture.fr_CG -> "French (Congo - Brazzaville)"
Culture.fr_CH -> "French (Switzerland)"
Culture.fr_CI -> "French (Côte d'Ivoire)"
Culture.fr_CM -> "French (Cameroon)"
Culture.fr_DJ -> "French (Djibouti)"
Culture.fr_DZ -> "French (Algeria)"
Culture.fr_FR -> "French (France)"
Culture.fr_GA -> "French (Gabon)"
Culture.fr_GF -> "French (French Guiana)"
Culture.fr_GN -> "French (Guinea)"
Culture.fr_GP -> "French (Guadeloupe)"
Culture.fr_GQ -> "French (Equatorial Guinea)"
Culture.fr_HT -> "French (Haiti)"
Culture.fr_KM -> "French (Comoros)"
Culture.fr_LU -> "French (Luxembourg)"
Culture.fr_MA -> "French (Morocco)"
Culture.fr_MC -> "French (Principality of Monaco)"
Culture.fr_MF -> "French (St. Martin)"
Culture.fr_MG -> "French (Madagascar)"
Culture.fr_ML -> "French (Mali)"
Culture.fr_MQ -> "French (Martinique)"
Culture.fr_MR -> "French (Mauritania)"
Culture.fr_MU -> "French (Mauritius)"
Culture.fr_NC -> "French (New Caledonia)"
Culture.fr_NE -> "French (Niger)"
Culture.fr_PF -> "French (French Polynesia)"
Culture.fr_PM -> "French (St. Pierre & Miquelon)"
Culture.fr_RE -> "French (Réunion)"
Culture.fr_RW -> "French (Rwanda)"
Culture.fr_SC -> "French (Seychelles)"
Culture.fr_SN -> "French (Senegal)"
Culture.fr_SY -> "French (Syria)"
Culture.fr_TD -> "French (Chad)"
Culture.fr_TG -> "French (Togo)"
Culture.fr_TN -> "French (Tunisia)"
Culture.fr_VU -> "French (Vanuatu)"
Culture.fr_WF -> "French (Wallis & Futuna)"
Culture.fr_YT -> "French (Mayotte)"
Culture.fur_IT -> "Friulian (Italy)"
Culture.fy_NL -> "Western Frisian (Netherlands)"
Culture.ga_IE -> "Irish (Ireland)"
Culture.gd_GB -> "Scottish Gaelic (U.K.)"
Culture.gl_ES -> "Galician (Spain)"
Culture.gsw_CH -> "Swiss German (Switzerland)"
Culture.gsw_FR -> "Swiss German (France)"
Culture.gsw_LI -> "Swiss German (Liechtenstein)"
Culture.gu_IN -> "Gujarati (India)"
Culture.guz_KE -> "Gusii (Kenya)"
Culture.gv_IM -> "Manx (Isle of Man)"
Culture.ha_GH -> "Hausa (Ghana)"
Culture.ha_NE -> "Hausa (Niger)"
Culture.ha_NG -> "Hausa (Nigeria)"
Culture.haw_US -> "Hawaiian (U.S.)"
Culture.he_IL -> "Hebrew (Israel)"
Culture.hi_IN -> "Hindi (India)"
Culture.hr_BA -> "Croatian (Bosnia and Herzegovina)"
Culture.hr_HR -> "Croatian (Croatia)"
Culture.hsb_DE -> "Upper Sorbian (Germany)"
Culture.hu_HU -> "Hungarian (Hungary)"
Culture.hy_AM -> "Armenian (Armenia)"
Culture.id_ID -> "Indonesian (Indonesia)"
Culture.ig_NG -> "Igbo (Nigeria)"
Culture.ii_CN -> "Sichuan Yi (China)"
Culture.in_ID -> "Indonesian (Indonesia)"
Culture.is_IS -> "Icelandic (Iceland)"
Culture.it_CH -> "Italian (Switzerland)"
Culture.it_IT -> "Italian (Italy)"
Culture.it_SM -> "Italian (San Marino)"
Culture.it_VA -> "Italian (Vatican City)"
Culture.iw_IL -> "Hebrew (Israel)"
Culture.ja_JP -> "Japanese (Japan)"
Culture.jgo_CM -> "Ngomba (Cameroon)"
Culture.jmc_TZ -> "Machame (Tanzania)"
Culture.ka_GE -> "Georgian (Georgia)"
Culture.kab_DZ -> "Kabyle (Algeria)"
Culture.kam_KE -> "Kamba (Kenya)"
Culture.kde_TZ -> "Makonde (Tanzania)"
Culture.kea_CV -> "Kabuverdianu (Cape Verde)"
Culture.khq_ML -> "Koyra Chiini (Mali)"
Culture.ki_KE -> "Kikuyu (Kenya)"
Culture.kk_KZ -> "Kazakh (Kazakhstan)"
Culture.kkj_CM -> "Kako (Cameroon)"
Culture.kl_GL -> "Kalaallisut (Greenland)"
Culture.kln_KE -> "Kalenjin (Kenya)"
Culture.km_KH -> "Khmer (Cambodia)"
Culture.kn_IN -> "Kannada (India)"
Culture.ko_KP -> "Korean (North Korea)"
Culture.ko_KR -> "Korean (Korea)"
Culture.kok_IN -> "Konkani (India)"
Culture.ks_IN -> "Kashmiri (India)"
Culture.ksb_TZ -> "Shambala (Tanzania)"
Culture.ksf_CM -> "Bafia (Cameroon)"
Culture.ksh_DE -> "Colognian (Germany)"
Culture.kw_GB -> "Cornish (U.K.)"
Culture.ky_KG -> "Kyrgyz (Kyrgyzstan)"
Culture.lag_TZ -> "Langi (Tanzania)"
Culture.lb_LU -> "Luxembourgish (Luxembourg)"
Culture.lg_UG -> "Ganda (Uganda)"
Culture.lt_LT -> "Lithuanian (Lithuania)"
Culture.lv_LV -> "Latvian (Latvia)"
Culture.mi_NZ -> "Maori (New Zealand)"
Culture.mk_MK -> "FYRO Macedonian (Former Yugoslav Republic of Macedonia"
Culture.mn_MN -> "Mongolian (Mongolia)"
Culture.mr_IN -> "Marathi (India)"
Culture.ms_BN -> "Malay (Brunei Darussalam)"
Culture.ms_MY -> "Malay (Malaysia)"
Culture.mt_MT -> "Maltese (Malta)"
Culture.nb_NO -> "Norwegian (Bokm?l) (Norway)"
Culture.nl_BE -> "Dutch (Belgium)"
Culture.nl_NL -> "Dutch (Netherlands)"
Culture.nn_NO -> "Norwegian (Nynorsk) (Norway)"
Culture.no_NO -> "Norwegian (Norway)"
Culture.no_NO_NY -> "Norwegian (Norway Nynorsk)"
Culture.ns_ZA -> "Northern Sotho (South Africa)"
Culture.pa_IN -> "Punjabi (India)"
Culture.pl_PL -> "Polish (Poland)"
Culture.ps_AR -> "Pashto (Afghanistan)"
Culture.pt_AO -> "Portuguese (Angola)"
Culture.pt_BR -> "Portuguese (Brazil)"
Culture.pt_CH -> "Portuguese (Switzerland)"
Culture.pt_CV -> "Portuguese (Cape Verde)"
Culture.pt_GQ -> "Portuguese (Equatorial Guinea)"
Culture.pt_GW -> "Portuguese (Guinea-Bissau)"
Culture.pt_LU -> "Portuguese (Luxembourg)"
Culture.pt_MO -> "Portuguese (Macau SAR China)"
Culture.pt_MZ -> "Portuguese (Mozambique)"
Culture.pt_PT -> "Portuguese (Portugal)"
Culture.pt_ST -> "Portuguese (São Tomé & Príncipe)"
Culture.pt_TL -> "Portuguese (Timor-Leste)"
Culture.qu_BO -> "Quechua (Bolivia)"
Culture.qu_EC -> "Quechua (Ecuador)"
Culture.qu_PE -> "Quechua (Peru)"
Culture.ro_RO -> "Romanian (Romania)"
Culture.ru_BY -> "Russian (Belarus)"
Culture.ru_KG -> "Russian (Kyrgyzstan)"
Culture.ru_KZ -> "Russian (Kazakhstan)"
Culture.ru_MD -> "Russian (Moldova)"
Culture.ru_RU -> "Russian (Russia)"
Culture.ru_UA -> "Russian (Ukraine)"
Culture.sa_IN -> "Sanskrit (India)"
Culture.se_FI -> "Sami (Finland)"
Culture.se_NO -> "Sami (Norway)"
Culture.se_SE -> "Sami (Sweden)"
Culture.sk_SK -> "Slovak (Slovakia)"
Culture.sl_SI -> "Slovenian (Slovenia)"
Culture.sq_AL -> "Albanian (Albania)"
Culture.sr_BA -> "Serbian (Latin) (Bosnia and Herzegovina)"
Culture.sr_CS -> "Serbian (Serbia and Montenegro)"
Culture.sr_Cyrl_BA -> "Serbian (Cyrillic) (Bosnia and Herzegovina)"
Culture.sr_Cyrl_SP -> "Serbian (Cyrillic) (Serbia and Montenegro)"
Culture.sr_ME -> "Serbian (Montenegro)"
Culture.sr_RS -> "Serbian (Serbia)"
Culture.sr_SP -> "Serbian (Latin) (Serbia and Montenegro)"
Culture.sv_FI -> "Swedish (Finland)"
Culture.sv_SE -> "Swedish (Sweden)"
Culture.sw_KE -> "Swahili (Kenya)"
Culture.syr_SY -> "Syriac (Syria)"
Culture.ta_IN -> "Tamil (India)"
Culture.te_IN -> "Telugu (India)"
Culture.th_TH -> "Thai (Thailand)"
Culture.th_TH_TH -> "Thai (Thailand)"
Culture.tl_PH -> "Tagalog (Philippines)"
Culture.tn_ZA -> "Tswana (South Africa)"
Culture.tr_TR -> "Turkish (Turkey)"
Culture.ts_MZ -> "Tsonga (Mozambique)"
Culture.ts_SZ -> "Tsonga (Eswatini)"
Culture.ts_ZA -> "Tsonga (South Africa)"
Culture.ts_ZW -> "Tsonga (Zimbabwe)"
Culture.tt_RU -> "Tatar (Russia)"
Culture.uk_UA -> "Ukrainian (Ukraine)"
Culture.ur_PK -> "Urdu (Islamic Republic of Pakistan)"
Culture.uz_Cyrl_UZ -> "Uzbek (Cyrillic) (Uzbekistan)"
Culture.uz_UZ -> "Uzbek (Latin) (Uzbekistan)"
Culture.vi_VN -> "Vietnamese (Viet Nam)"
Culture.xh_ZA -> "Xhosa (South Africa)"
Culture.zh_CN -> "Chinese (S)"
Culture.zh_HK -> "Chinese (Hong Kong)"
Culture.zh_Hans -> "Chinese (Simplified)(zh-Hans)"
Culture.zh_Hans_HK -> "Chinese (Simplified Hong Kong SAR China)"
Culture.zh_Hans_MO -> "Chinese (Simplified Macau SAR China)"
Culture.zh_Hans_SG -> "Chinese (Simplified Singapore)"
Culture.zh_Hant -> "Chinese (Traditional)"
Culture.zh_Hant_HK -> "Chinese (Traditional Hong Kong SAR China)"
Culture.zh_Hant_MO -> "Chinese (Traditional Macau SAR China)"
Culture.zh_Hant_TW -> "Chinese (Traditional Taiwan)"
Culture.zh_MO -> "Chinese (Macau)"
Culture.zh_SG -> "Chinese (Singapore)"
Culture.zh_TW -> "Chinese (T)"
Culture.zu_ZA -> "Zulu (South Africa)"
}
}
| 0
|
Kotlin
|
0
| 2
|
f7adeac45da6d7b3e0a2ff9084fdb8cb9c787796
| 20,215
|
sdk-android
|
MIT License
|
generators/app/templates/conductor/app/src/main/kotlin/nolambda/androidstarter/screens/ApiExampleController.kt
|
nootanghimire
| 107,947,255
| true
|
{"Kotlin": 18581, "JavaScript": 10041}
|
package <%= appPackage %>.screens
import android.os.Bundle
import android.view.View
import android.widget.TextView
import butterknife.BindView
import io.reactivex.android.schedulers.AndroidSchedulers
import <%= appPackage %>.R
import <%= appPackage %>.commons.AbsController
import <%= appPackage %>.network.ApiService
import javax.inject.Inject
class ApiExampleController : AbsController() {
@BindView(R.id.main_txt_hello) lateinit var txtTitle: TextView
@Inject lateinit var apiService: ApiService
override fun onSetupComponent() {
component.inject(this)
}
override fun getLayoutResId(): Int = R.layout.controller_main
override fun onViewBound(bindingResult: View, savedState: Bundle?) {
txtTitle.setOnClickListener {
apiService.getUserAgent()
.observeOn(AndroidSchedulers.mainThread())
.subscribe { (userAgent), _ ->
txtTitle.text = userAgent
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
6f8ed53b3fbba9dbf96430d9cd92415eb5d7a93c
| 1,008
|
generator-android-conductor
|
Apache License 2.0
|
core-v4/core-v4-bus/src/test/java/com/github/teracy/odpt/core/v4/bus/response/OdptBusRoutePatternTest.kt
|
teracy
| 193,032,147
| false
| null |
package com.github.teracy.odpt.core.v4.bus.response
import com.github.teracy.odpt.core.geojson.adapter.GeometryAdapter
import com.github.teracy.odpt.core.geojson.response.LineString
import com.github.teracy.odpt.model.adapter.ArrayOrObjectAdapter
import com.github.teracy.odpt.testutil.ApiResponseTest
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.experimental.runners.Enclosed
import org.junit.runner.RunWith
@RunWith(Enclosed::class)
class OdptBusRoutePatternTest {
/**
* デシリアライズのテスト
*/
class DeserializeTest : ApiResponseTest {
private val parameterizedType = Types.newParameterizedType(List::class.java, OdptBusRoutePattern::class.java)
lateinit var jsonAdapter: JsonAdapter<List<OdptBusRoutePattern>>
@Before
fun setUp() {
jsonAdapter = Moshi.Builder()
.add(ArrayOrObjectAdapter.FACTORY)
.add(GeometryAdapter.FACTORY)
.build()
.adapter(parameterizedType)
}
// NOTE: 東京公共交通オープンデータチャレンジAPIサンプルデータは必須要件のものすら備えておらず、typoも多いため利用困難と判断した
/**
* 実データ(東京都交通局梅77甲より)
* NOTE: 東京公共交通オープンデータチャレンジAPIサンプルデータが使い物にならないため、実データで確かめた
*/
@Test
fun toei_Ume77Kou_28603_2() {
// テストデータ
val json = readJsonFile("BusRoutePattern_Toei_Ume77Kou_28603_2.json")
val busRoutePatternList = jsonAdapter.fromJson(json)
assertThat(busRoutePatternList).isNotNull
assertThat(busRoutePatternList!!.size).isEqualTo(1)
val busRoutePattern0 = busRoutePatternList[0]
assertThat(busRoutePattern0.id).isEqualTo("urn:ucode:_00001C0000000000000100000322BB7E")
assertThat(busRoutePattern0.sameAs).isEqualTo("odpt.BusroutePattern:Toei.Ume77Kou.28603.2")
assertThat(busRoutePattern0.date).isEqualTo("2019-05-31T03:04:58+09:00")
assertThat(busRoutePattern0.valid).isNull()
assertThat(busRoutePattern0.title).isEqualTo("梅77甲 青梅駅前行")
assertThat(busRoutePattern0.kana).isNull()
// NOTE: APIではArrayで定義されているが東京都交通局実データではObject
assertThat(busRoutePattern0.operatorList.size).isEqualTo(1)
assertThat(busRoutePattern0.operatorList[0]).isEqualTo("odpt.Operator:Toei")
assertThat(busRoutePattern0.busRoute).isEqualTo("odpt.Busroute:Toei.Ume77Kou")
assertThat(busRoutePattern0.pattern).isEqualTo("28603")
assertThat(busRoutePattern0.direction).isEqualTo("2")
assertThat(busRoutePattern0.region).isNotNull
assertThat(busRoutePattern0.region?.javaClass).isEqualTo(LineString::class.java)
val lineString = busRoutePattern0.region as LineString
// 外側のリストのサイズ(=座標の数)は67のはず
assertThat(lineString.coordinates.size).isEqualTo(67)
// 内側のリストのサイズ(=座標)は2のはず
assertThat(lineString.coordinates[0].size).isEqualTo(2)
// 内側のリストから抽出
// 0番目の経度
assertThat(lineString.coordinates[0][0]).isEqualTo(139.28513)
// 0番目の緯度
assertThat(lineString.coordinates[0][1]).isEqualTo(35.78465)
assertThat(busRoutePattern0.busStopPoleOrder).isNotNull
assertThat(busRoutePattern0.busStopPoleOrder).isNotEmpty
assertThat(busRoutePattern0.busStopPoleOrder!!.size).isEqualTo(22)
val busStopPoleOrder0 = busRoutePattern0.busStopPoleOrder!![0]
assertThat(busStopPoleOrder0.busStopPole).isEqualTo("odpt.BusstopPole:Toei.KabeStationKitaguchi.338.1")
assertThat(busStopPoleOrder0.index).isEqualTo(1)
assertThat(busStopPoleOrder0.note).isEqualTo("河辺駅北口")
assertThat(busStopPoleOrder0.openingDoorsToGetOnList).isNull()
assertThat(busStopPoleOrder0.openingDoorsToGetOffList).isNull()
assertThat(busStopPoleOrder0.busStopPoleId.id).isEqualTo("odpt.BusstopPole:Toei.KabeStationKitaguchi.338.1")
assertThat(busRoutePattern0.note).isEqualTo("梅77甲:河辺駅北口→青梅駅前:28603:2")
assertThat(busRoutePattern0.busLocationUrl).isNull()
assertThat(busRoutePattern0.busRoutePatternId.id).isEqualTo("odpt.BusroutePattern:Toei.Ume77Kou.28603.2")
// NOTE: APIではArrayで定義されているが東京都交通局実データではObject
assertThat(busRoutePattern0.operatorIdList.size).isEqualTo(1)
assertThat(busRoutePattern0.operatorIdList[0].id).isEqualTo("odpt.Operator:Toei")
assertThat(busRoutePattern0.busRouteId).isNotNull
assertThat(busRoutePattern0.busRouteId!!.id).isEqualTo("odpt.Busroute:Toei.Ume77Kou")
}
}
}
| 0
|
Kotlin
|
0
| 1
|
002554e4ca6e2f460207cfd1cb8265c2267f149d
| 4,818
|
odpt
|
Apache License 2.0
|
src/main/kotlin/utils/Utils.kt
|
liefswanson
| 130,515,078
| false
| null |
package utils
import kotlin.reflect.KClass
import kotlin.reflect.full.isSubclassOf
fun <R> Throwable.multicatch(vararg classes: KClass<*>, block: () -> R): R {
if (classes.any { this::class.isSubclassOf(it) }) {
return block()
} else {
throw this
}
}
fun align(vararg lines: String): List<String> {
val len = lines
.map { it.length }
.max() ?: 0
return lines.map { it.padEnd(len, ' ') }
}
| 2
|
Kotlin
|
0
| 0
|
9b293ad974775825d94f8189f1cad4c4adc689d4
| 452
|
auto-sudoku
|
MIT License
|
app/src/main/java/com/misit/faceidchecklogptabp/Response/ImageResponse.kt
|
borisreyson
| 354,711,920
| false
| null |
package com.misit.faceidchecklogptabp.Response
import com.google.gson.annotations.SerializedName
data class ImageResponse(
@field:SerializedName("image")
val image: String? = null,
@field:SerializedName("res")
val res: String? = null,
@field:SerializedName("tidak_dikenal")
val tidak_dikenal: Boolean = true
)
| 0
|
Kotlin
|
0
| 0
|
2a0b507559cfeddd3bff624f447ce088d334d85a
| 320
|
FaceIdChecklogPTABP
|
MIT License
|
presentation/src/main/java/com/gauvain/seigneur/presentation/model/TrackData.kt
|
GauvainSeigneur
| 267,048,711
| false
| null |
package com.gauvain.seigneur.presentation.model
import com.gauvain.seigneur.domain.model.TrackListModel
import com.gauvain.seigneur.domain.model.TrackModel
import com.gauvain.seigneur.presentation.R
import com.gauvain.seigneur.presentation.utils.QuantityStringPresenter
data class TrackData(
val tracks: List<TrackItemData>,
val total: QuantityStringPresenter
)
fun TrackListModel.toTrackData() = TrackData(
tracks = this.tracks.map {
it.toData()
},
total = QuantityStringPresenter(
R.plurals.albums_tracks_duration,
this.total, this.total
)
)
data class TrackItemData(
val id: Long,
val title: String,
val artistName: String,
val isExplicitLyrics: Boolean
)
fun TrackModel.toData(): TrackItemData = TrackItemData(
id = this.id,
title = this.title,
artistName = this.artist,
isExplicitLyrics = this.isExplicitLyrics
)
| 0
|
Kotlin
|
0
| 0
|
5cd5d9ec1a9aefe7150ec631032467210fd18d80
| 906
|
ShinyAlbums
|
Apache License 2.0
|
app/src/main/java/com/sformica/hilt_app_test/di/EatDependency.kt
|
MisterAnt92
| 615,738,322
| false
| null |
package com.sformica.hilt_app_test.di
import javax.inject.Inject
/**
* Eat dependency
*
* @constructor Create empty Eat dependency
*/
class EatDependency @Inject constructor() {
/**
* Eat pizza dependency
*
*/
fun eatPizzaDependency() {}
/**
* Eat pasta dependency
*
*/
fun eatPastaDependency() {}
}
| 0
|
Kotlin
|
0
| 0
|
b8e420807cb33b8ae7c1ca66ce47d8723ae42703
| 354
|
hilt-sample
|
Apache License 2.0
|
oldAndroidProjects/More Projects/PraticeProjects/Khaata/app/src/main/java/com/shivathapa/khaata/data/repository/expense/ExpenseRepository.kt
|
shivathapaa
| 800,628,391
| false
|
{"Kotlin": 3413631, "Shell": 2341}
|
package com.shivathapa.khaata.data.repository.expense
import com.shivathapa.khaata.data.CategoryWithExpenses
import com.shivathapa.khaata.data.Expense
import kotlinx.coroutines.flow.Flow
interface ExpenseRepository {
// Expense
fun getAllExpenses(): Flow<List<Expense>>
fun getExpense(expenseId: Int): Flow<Expense>
suspend fun deleteExpense(expense: Expense)
suspend fun insertExpense(expense: Expense)
suspend fun updateExpense(expense: Expense)
fun getExpensesByCategoryIdWithTransaction(categoryId: Int): Flow<CategoryWithExpenses>
}
| 0
|
Kotlin
|
0
| 0
|
19185d178bb0ff390c9c2c43adbd9ddefc9a2288
| 574
|
Android-Practice-Projects
|
The Unlicense
|
src/test/kotlin/com/emberjs/gts/GtsFileTest.kt
|
patricklx
| 412,986,421
| false
|
{"Kotlin": 680201, "JavaScript": 31431, "HTML": 8237, "Handlebars": 2507, "Java": 207, "Scala": 172, "CSS": 144, "SCSS": 96}
|
package com.emberjs.hbs
import com.emberjs.gts.GjsFileType
import com.emberjs.gts.GtsFileType
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.lang.javascript.inspections.ES6UnusedImportsInspection
import com.intellij.lang.javascript.inspections.JSUnusedLocalSymbolsInspection
import com.intellij.lang.javascript.psi.impl.JSFileImpl
import com.intellij.testFramework.fixtures.BasePlatformTestCase
import junit.framework.TestCase
import org.junit.Test
class GtsFileTest : BasePlatformTestCase() {
@Test
fun testGtsStub() {
val gts = """
import x from "a";
export const a = 2;
""".trimIndent()
myFixture.configureByText(GtsFileType.INSTANCE, gts)
(myFixture.file as JSFileImpl).calcStubTree()
assertNotNull("should have stub definition", (myFixture.file as JSFileImpl).greenStub)
}
@Test
fun testGjsImportUsed() {
val gts = """
import x from "a";
import { y, quux } from "a";
import qux from "a";
import { Foo } from "a";
const bar = () => null;
const Baz = {};
const grault = {};
function corge() {};
function corge2() {};
export default <template>
<Foo />
<Baz />
{{x}}
{{y}}
{{corge}}
{{bar}}
</template>
""".trimIndent()
myFixture.configureByText(GjsFileType.INSTANCE, gts)
myFixture.enableInspections(ES6UnusedImportsInspection(), JSUnusedLocalSymbolsInspection())
val highlightInfos: List<HighlightInfo> = myFixture.doHighlighting().filter { it.inspectionToolId == "ES6UnusedImports" || it.inspectionToolId == "JSUnusedLocalSymbols" }
TestCase.assertEquals(4, highlightInfos.size)
TestCase.assertTrue(highlightInfos[0].description.contains("quux"))
TestCase.assertTrue(highlightInfos[1].description.contains("qux"))
TestCase.assertTrue(highlightInfos[2].description.contains("grault"))
TestCase.assertTrue(highlightInfos[3].description.contains("corge2"))
}
@Test
fun testGtsImportUsed() {
val gts = """
import x from "a";
import { y, quux } from "a";
import qux from "a";
import { Foo } from "a";
const bar = () => null;
const Baz = {};
export default <template>
<Foo />
<Baz />
{{x}}
{{y}}
{{bar}}
</template>
""".trimIndent()
myFixture.configureByText(GtsFileType.INSTANCE, gts)
myFixture.enableInspections(ES6UnusedImportsInspection())
val highlightInfos: List<HighlightInfo> = myFixture.doHighlighting().filter { it.inspectionToolId == "ES6UnusedImports" }
TestCase.assertEquals(highlightInfos.size, 2)
TestCase.assertTrue(highlightInfos.first().description.contains("quux"))
TestCase.assertTrue(highlightInfos.last().description.contains("qux"))
}
}
| 3
|
Kotlin
|
6
| 12
|
b99019865227958bf1e84e34032b3cf8c15cc64a
| 3,245
|
intellij-emberjs-experimental
|
Apache License 2.0
|
app/src/main/java/com/snorlax/snorlax/utils/adapter/viewpager/AttendancePageAdapter.kt
|
OliverRhyme
| 219,249,108
| false
| null |
/*
* Copyright 2019 <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
*
* 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.snorlax.snorlax.utils.adapter.viewpager
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.snorlax.snorlax.ui.home.attendance.AttendanceListFragment
import com.snorlax.snorlax.utils.TimeUtils.getTodayDateLocal
import com.snorlax.snorlax.utils.TimeUtils.positionToTime
class AttendancePageAdapter(
fragment: Fragment
/* private val callback: (date: Date) -> Observable<List<Attendance>>*/
) : FragmentStateAdapter(fragment) {
override fun getItemCount() = (getTodayDateLocal().time / 86_400_000).toInt() + 1
override fun createFragment(position: Int): Fragment {
val date = positionToTime(position)
return AttendanceListFragment(/*callback(positionToTime(position))*/).apply {
arguments = Bundle().apply {
putSerializable(AttendanceListFragment.ATTENDANCE_DATE, date)
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
a41eaddf9b2bfb3c7feb6aaac9050482186eb98c
| 1,574
|
Snorlax
|
Apache License 2.0
|
app/src/main/kotlin/space/reul/ticketmasterchallenge/app/ui/composables/AsyncImageCell.kt
|
reul
| 764,954,876
| false
|
{"Kotlin": 53026}
|
package space.reul.ticketmasterchallenge.app.ui.composables
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.material3.Card
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.BrushPainter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.tooling.preview.Preview
import coil.compose.AsyncImage
@Composable
fun AsyncImageCell(modifier: Modifier = Modifier, url: String) {
Card(modifier.fillMaxHeight()) {
Row {
AsyncImage(
modifier = modifier.fillMaxHeight(),
model = url,
contentDescription = null,
contentScale = ContentScale.Crop,
placeholder = BrushPainter(
Brush.linearGradient(
listOf(
Color(color = 0xFFFFFFFF),
Color(color = 0xFF222222),
)
)
)
)
}
}
}
@Preview
@Composable
fun AsyncImageCellPreview() {
AsyncImageCell(url="")
}
| 0
|
Kotlin
|
0
| 0
|
7ca0c967da83b3704894b19c27dad666cf440936
| 1,286
|
tiago-reul-ticketmaster-challenge
|
The Unlicense
|
kaff4-core/kaff4-core-model/kaff4-core-model-api/src/main/kotlin/net/navatwo/kaff4/model/rdf/GraphQuerySafeExtensions.kt
|
Nava2
| 555,850,412
| false
| null |
package net.navatwo.kaff4.model.rdf
import org.eclipse.rdf4j.model.Statement
import org.eclipse.rdf4j.query.GraphQuery
fun GraphQuery.evaluateSequence(): Sequence<Statement> {
return sequence {
evaluate().use { yieldAll(it) }
}
}
| 7
|
Kotlin
|
0
| 1
|
b0df931c9be6378bd9fc7f6d182d1a35b3034c2f
| 240
|
kaff4
|
MIT License
|
src/main/kotlin/com/vadeen/dns/constants/DynamicEnum.kt
|
FelixStridsberg
| 210,037,588
| false
| null |
package com.vadeen.dns.constants
/**
* Since we must be able to handle operation and response codes that we have not implemented, we cannot use enums.
*
* Instead we can use sealed classes like so:
*
* sealed class ResponseCode(code: Byte) : DynamicEnum(code) {
* KnownCode : ResponseCode(1),
* ...
* UnknownCode(code: Byte) : ResponseCode(code)
* }
*
* This way we can get the benefit of a enum like structure, but still the ability to handle unknown data, without
* having to define the boiler plate every time.
*/
open class DynamicEnum<E>(val value: E) {
override fun equals(other: Any?): Boolean {
if (this === other)
return true
if (other == null)
return false
if (other.javaClass != javaClass)
return false
other as DynamicEnum<*>
if (value == null)
return other.value == null
return value == other.value
}
override fun hashCode() = value?.hashCode() ?: 0
}
| 0
|
Kotlin
|
0
| 3
|
4c66e4311cc108ad9485a392020a36588799138d
| 1,013
|
dns
|
MIT License
|
app/src/main/java/com/wiliamks/temaqui/ui/detail/repository/DetailsRepositoryImpl.kt
|
wiliamks
| 658,372,597
| false
| null |
package com.wiliamks.temaqui.ui.detail.repository
import com.wiliamks.temaqui.commons.Session
import com.wiliamks.temaqui.commons.model.CartItem
class DetailsRepositoryImpl : DetailsRepository {
override suspend fun addItemToCart(item: CartItem) {
Session.cartSelection.forEachIndexed { index, cartItem ->
if (cartItem.product?.id == item.product?.id) {
Session.cartSelection.removeAt(index)
}
}
Session.cartSelection.add(item)
Session.personalizationSelection.forEach {
Session.cartSelection.add(
CartItem(
partner = it,
amountSelected = 1
)
)
}
Session.personalizationSelection = arrayListOf()
}
}
| 0
|
Kotlin
|
0
| 0
|
dfdda9b0fff73ee6133e266574129fa1a52a31c9
| 796
|
temaqui
|
MIT License
|
data/src/main/java/com/example/data/features/rates/api/IRatesApi.kt
|
egorushkin
| 583,336,377
| false
| null |
package com.example.data.features.rates.api
import com.example.data.features.rates.repository.remote.models.RatesResponse
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
interface IRatesApi {
companion object {
const val RATES = "api/android/latest"
const val BASE_QUERY = "base"
}
@GET(RATES)
suspend fun getRatesResultAsync(
@Query(BASE_QUERY) baseCurrency: String
): Response<RatesResponse>
}
| 0
|
Kotlin
|
0
| 0
|
90e1a91b64ab3315e494de9750a3fc0f97c5ed3d
| 475
|
android-app-skeleton
|
Apache License 2.0
|
src/jvmTest/kotlin/examples/LexicalEquality.kt
|
adriantodt
| 251,127,025
| false
| null |
package examples
import com.github.adriantodt.tartar.api.dsl.CharPredicate
import com.github.adriantodt.tartar.api.lexer.Lexer
import com.github.adriantodt.tartar.api.lexer.Source
import com.github.adriantodt.tartar.api.lexer.classpath
import com.github.adriantodt.tartar.api.parser.StringToken
import com.github.adriantodt.tartar.api.parser.SyntaxException
import com.github.adriantodt.tartar.api.parser.Token
import com.github.adriantodt.tartar.extensions.lexer.*
import examples.extra.CTokenType
import examples.extra.CTokenType.*
fun main() {
/*
* A minimal subset of C was implemented.
*/
val lexer = Lexer.create<Token<CTokenType>> {
// NOOP
' '()
'\n'()
// Tokens
'+' { processToken(PLUS) }
'-' { processToken(MINUS) }
'*' { processToken(TIMES) }
"++" { processToken(INCREMENT, 2) }
"--" { processToken(DECREMENT, 2) }
'=' { processToken(ASSIGN) }
"==" { processToken(EQ, 2) }
'>' { processToken(GT) }
'<' { processToken(LT) }
">=" { processToken(GE, 2) }
"<=" { processToken(LE, 2) }
';' { processToken(SEMICOLON) }
'(' { processToken(LPAREN) }
')' { processToken(RPAREN) }
'{' { processToken(LBRACKET) }
'}' { processToken(RBRACKET) }
matching(CharPredicate.isDigit).configure {
when (val n = readNumber(it)) {
is LexicalNumber.Decimal -> processToken(NUMBER, n.string)
is LexicalNumber.Integer -> processToken(NUMBER, n.string)
else -> throw SyntaxException("Illegal number", section(n.string.length))
}
}
matching { it.isLetter() || it == '_' }.configure {
processToken(IDENTIFIER, readIdentifier(it))
}
}
val list1 = lexer.parseToList(Source.classpath { "input.c" })
val list2 = lexer.parseToList(Source.classpath { "input.min.c" }.copy(name = "input.c"))
// Compares types and values, but not sections.
val isEqual = list1.zip(list2).all { (o1, o2) ->
o1.type == o2.type && o1::class == o2::class && (o1 !is StringToken || o2 !is StringToken || o1.value == o2.value)
}
println(isEqual)
}
| 2
|
Kotlin
|
0
| 2
|
0f09816d34de09c2f061fad621de2c5b30bfdc99
| 2,236
|
tartar
|
Apache License 2.0
|
plugins/com.flinty.docsflow.server.core/source/com/flinty/docsflow/server/core/workspace/storage/DocsFlowWorkspaceProvider.kt
|
flint80
| 413,383,841
| false
|
{"Kotlin": 291036, "HTML": 8515, "CSS": 317}
|
/*****************************************************************
* Gridnine AB http://www.gridnine.com
* Project: JTasks
*****************************************************************/
package com.flinty.docsflow.server.core.workspace.storage
import com.flinty.docsflow.common.core.model.domain.*
import com.gridnine.jasmine.common.core.model.BaseAsset
import com.gridnine.jasmine.common.core.storage.Storage
import com.gridnine.jasmine.common.core.utils.AuthUtils
import com.gridnine.jasmine.common.standard.model.domain.*
import com.gridnine.jasmine.server.standard.model.WorkspaceProvider
class DocsFlowWorkspaceProvider : WorkspaceProvider {
override fun getWorkspace(): Workspace {
val loginName = AuthUtils.getCurrentUser()
return Storage.get().loadDocument(Workspace::class, "${loginName}_workspace")
?: createStandardWorkspace(loginName)
}
override fun saveWorkspace(workspace: Workspace):Workspace {
val loginName = AuthUtils.getCurrentUser()
workspace.uid = "${loginName}_workspace"
workspace.setValue(BaseAsset.revision, -1)
Storage.get().saveDocument(workspace)
return workspace
}
private fun createStandardWorkspace(loginName: String): Workspace {
val result = Workspace()
result.uid = "${loginName}_workspace"
run {
val group = WorkspaceGroup()
group.displayName = "Настройки"
val item = ListWorkspaceItem()
item.columns.add(UserAccountIndex.loginProperty.name)
item.columns.add(UserAccountIndex.nameProperty.name)
item.filters.add(UserAccountIndex.loginProperty.name)
val order = SortOrder()
order.orderType = SortOrderType.ASC
order.field = UserAccountIndex.loginProperty.name
item.listId = UserAccountIndex::class.qualifiedName
item.displayName = "Профили"
group.items.add(item)
result.groups.add(group)
}
run {
val group = WorkspaceGroup()
group.displayName = "Поставщики"
val item = ListWorkspaceItem()
item.columns.add(SupplierIndex.nameProperty.name)
val order = SortOrder()
order.orderType = SortOrderType.ASC
order.field = SupplierIndex.nameProperty.name
item.displayName = "Все поставщики"
item.listId = SupplierIndex::class.qualifiedName
group.items.add(item)
result.groups.add(group)
}
run {
val group = WorkspaceGroup()
group.displayName = "Проекты"
val item = ListWorkspaceItem()
item.columns.add(ProjectIndex.nameProperty.name)
item.columns.add(ProjectIndex.codeProperty.name)
val order = SortOrder()
order.orderType = SortOrderType.ASC
order.field = ProjectIndex.nameProperty.name
item.displayName = "Все проекты"
item.listId = ProjectIndex::class.qualifiedName
group.items.add(item)
result.groups.add(group)
}
run {
val group = WorkspaceGroup()
group.displayName = "Исходные спецификации"
run {
val item = ListWorkspaceItem()
item.columns.add(SpecificationIndex.nameProperty.name)
item.columns.add(SpecificationIndex.statusProperty.name)
item.columns.add(SpecificationIndex.projectProperty.name)
item.filters.add(SpecificationIndex.statusProperty.name)
item.filters.add(SpecificationIndex.projectProperty.name)
val order = SortOrder()
order.orderType = SortOrderType.ASC
order.field = SpecificationIndex.nameProperty.name
item.displayName = "Все спецификации"
item.listId = SpecificationIndex::class.qualifiedName
group.items.add(item)
}
run {
val item = ListWorkspaceItem()
item.columns.add(SpecificationIndex.nameProperty.name)
item.columns.add(SpecificationIndex.statusProperty.name)
item.columns.add(SpecificationIndex.projectProperty.name)
item.filters.add(SpecificationIndex.statusProperty.name)
item.filters.add(SpecificationIndex.projectProperty.name)
val order = SortOrder()
order.orderType = SortOrderType.ASC
order.field = SpecificationIndex.nameProperty.name
item.displayName = "Новые спецификации"
item.listId = SpecificationIndex::class.qualifiedName
item.criterions.add(
SimpleWorkspaceCriterion().also {
it.property = SpecificationIndex.statusProperty.name
it.condition = WorkspaceSimpleCriterionCondition.EQUALS
it.value = WorkspaceSimpleCriterionEnumValues().also { crit ->
crit.enumClassName = SpecificationStatus::class.qualifiedName+"JS"
crit.values.add(SpecificationStatus.NEW.name)
crit.values.add(SpecificationStatus.PARTIALLY_ORDERED.name)
}
})
group.items.add(item)
}
result.groups.add(group)
}
run {
val group = WorkspaceGroup()
group.displayName = "Заказы"
run {
val item = ListWorkspaceItem()
item.columns.add(SpecificationOrderIndex.codeProperty.name)
item.columns.add(SpecificationOrderIndex.supplierProperty.name)
item.columns.add(SpecificationOrderIndex.statusProperty.name)
val order = SortOrder()
order.orderType = SortOrderType.ASC
order.field = SpecificationOrderIndex.codeProperty.name
item.displayName = "Все заказы"
item.listId = SpecificationOrderIndex::class.qualifiedName
group.items.add(item)
}
run {
val item = ListWorkspaceItem()
item.columns.add(SpecificationOrderIndex.codeProperty.name)
item.columns.add(SpecificationOrderIndex.supplierProperty.name)
item.columns.add(SpecificationOrderIndex.statusProperty.name)
val order = SortOrder()
order.orderType = SortOrderType.ASC
order.field = SpecificationOrderIndex.codeProperty.name
item.displayName = "Черновики"
item.listId = SpecificationOrderIndex::class.qualifiedName
item.criterions.add(
SimpleWorkspaceCriterion().also {
it.property = SpecificationOrderIndex.statusProperty.name
it.condition = WorkspaceSimpleCriterionCondition.EQUALS
it.value = WorkspaceSimpleCriterionEnumValues().also { crit ->
crit.enumClassName = OrderStatus::class.qualifiedName+"JS"
crit.values.add(OrderStatus.DRAFT.name)
}
})
group.items.add(item)
}
result.groups.add(group)
}
run {
val group = WorkspaceGroup()
group.displayName = "Счета"
run {
val item = ListWorkspaceItem()
item.columns.add(InvoiceIndex.invoiceNumberProperty.name)
item.columns.add(InvoiceIndex.specificationOrderProperty.name)
item.columns.add(InvoiceIndex.statusProperty.name)
item.columns.add(InvoiceIndex.supplierProperty.name)
val order = SortOrder()
order.orderType = SortOrderType.ASC
order.field = InvoiceIndex.invoiceNumberProperty.name
item.displayName = "Все счета"
item.listId = InvoiceIndex::class.qualifiedName
group.items.add(item)
}
run {
val item = ListWorkspaceItem()
item.columns.add(InvoiceIndex.invoiceNumberProperty.name)
item.columns.add(InvoiceIndex.specificationOrderProperty.name)
item.columns.add(InvoiceIndex.statusProperty.name)
item.columns.add(InvoiceIndex.supplierProperty.name)
val order = SortOrder()
order.orderType = SortOrderType.ASC
order.field = InvoiceIndex.invoiceNumberProperty.name
item.displayName = "Черновики"
item.listId = InvoiceIndex::class.qualifiedName
item.criterions.add(
SimpleWorkspaceCriterion().also {
it.property = InvoiceIndex.statusProperty.name
it.condition = WorkspaceSimpleCriterionCondition.EQUALS
it.value = WorkspaceSimpleCriterionEnumValues().also { crit ->
crit.enumClassName = InvoiceStatus::class.qualifiedName+"JS"
crit.values.add(InvoiceStatus.DRAFT.name)
}
})
group.items.add(item)
}
result.groups.add(group)
}
run {
val group = WorkspaceGroup()
group.displayName = "Излишки"
run {
val item = ListWorkspaceItem()
item.columns.add(SurplusIndex.articleProperty.name)
item.columns.add(SurplusIndex.nameProperty.name)
item.columns.add(SurplusIndex.amountProperty.name)
item.columns.add(SurplusIndex.unitProperty.name)
item.columns.add(SurplusIndex.invoiceProperty.name)
item.columns.add(SurplusIndex.statusProperty.name)
item.columns.add(SurplusIndex.specificationOrderProperty.name)
val order = SortOrder()
order.orderType = SortOrderType.ASC
order.field = SurplusIndex.nameProperty.name
item.displayName = "Все излишки"
item.listId = SurplusIndex::class.qualifiedName
group.items.add(item)
}
run {
val item = ListWorkspaceItem()
item.columns.add(SurplusIndex.articleProperty.name)
item.columns.add(SurplusIndex.nameProperty.name)
item.columns.add(SurplusIndex.amountProperty.name)
item.columns.add(SurplusIndex.unitProperty.name)
item.columns.add(SurplusIndex.invoiceProperty.name)
item.columns.add(SurplusIndex.statusProperty.name)
item.columns.add(SurplusIndex.specificationOrderProperty.name)
val order = SortOrder()
order.orderType = SortOrderType.ASC
order.field = SurplusIndex.nameProperty.name
item.displayName = "Черновики"
item.listId = SurplusIndex::class.qualifiedName
item.criterions.add(
SimpleWorkspaceCriterion().also {
it.property = SurplusIndex.statusProperty.name
it.condition = WorkspaceSimpleCriterionCondition.EQUALS
it.value = WorkspaceSimpleCriterionEnumValues().also { crit ->
crit.enumClassName = SurplusStatus::class.qualifiedName+"JS"
crit.values.add(SurplusStatus.DRAFT.name)
}
})
group.items.add(item)
}
result.groups.add(group)
}
run {
val group = WorkspaceGroup()
group.displayName = "Накладные"
run {
val item = ListWorkspaceItem()
item.columns.add(WaybillIndex.waybillNumberProperty.name)
item.columns.add(WaybillIndex.statusProperty.name)
item.columns.add(WaybillIndex.invoiceProperty.name)
item.columns.add(WaybillIndex.supplierProperty.name)
val order = SortOrder()
order.orderType = SortOrderType.ASC
order.field = WaybillIndex.waybillNumberProperty.name
item.displayName = "Все накладные"
item.listId = WaybillIndex::class.qualifiedName
group.items.add(item)
}
run {
val item = ListWorkspaceItem()
item.columns.add(WaybillIndex.waybillNumberProperty.name)
item.columns.add(WaybillIndex.statusProperty.name)
item.columns.add(WaybillIndex.invoiceProperty.name)
item.columns.add(WaybillIndex.supplierProperty.name)
val order = SortOrder()
order.orderType = SortOrderType.ASC
order.field = SurplusIndex.nameProperty.name
item.displayName = "Черновики(накладные)"
item.listId = WaybillIndex::class.qualifiedName
item.criterions.add(
SimpleWorkspaceCriterion().also {
it.property = WaybillIndex.statusProperty.name
it.condition = WorkspaceSimpleCriterionCondition.EQUALS
it.value = WorkspaceSimpleCriterionEnumValues().also { crit ->
crit.enumClassName = WaybillStatus::class.qualifiedName+"JS"
crit.values.add(WaybillStatus.DRAFT.name)
}
})
group.items.add(item)
}
result.groups.add(group)
}
saveWorkspace(result)
return result
}
}
| 0
|
Kotlin
|
0
| 0
|
d64d64bd2f539a6579ee80dc2c89b22b4c644ddc
| 13,972
|
coralina-docs-flow
|
MIT License
|
api/src/main/kotlin/db/migration/client/v1/v0/V0001_0000_0020__create_table_centrocusto.kt
|
IvoSestren
| 331,951,557
| false
| null |
package db.migration.client.v1.v0
import db.migration.base.postgresql.PostgreSQLMigration
@Suppress("ClassName", "unused")
class V0001_0000_0020__create_table_centrocusto: PostgreSQLMigration() {
override fun createSequences() {
createSequence("sq_centrocusto")
}
override fun createTables() {
execute("""
create table centrocusto (
id bigint not null default nextval('sq_centrocusto'),
handle varchar(36) not null,
codigo varchar(20),
nome varchar(100) not null,
id_centrocustopai bigint,
created_at timestamp with time zone not null default current_timestamp,
updated_at timestamp with time zone,
deleted_at timestamp with time zone,
constraint pk_centrocusto primary key (id),
constraint uk_centrocusto_handle unique (handle),
constraint fk_centrocusto_pai foreign key (id_centrocustopai) references centrocusto(id)
)
""".trimIndent())
}
}
| 0
|
Kotlin
|
0
| 0
|
a955b4a4b8b4e4f2b746bbe5bc4fe3674ab9caf1
| 1,085
|
erp_001
|
The Unlicense
|
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/BoxAlt.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.rounded.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Bold.BoxAlt: ImageVector
get() {
if (_boxAlt != null) {
return _boxAlt!!
}
_boxAlt = Builder(name = "BoxAlt", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(18.5f, 0.0f)
horizontalLineToRelative(-13.0f)
arcToRelative(5.507f, 5.507f, 0.0f, false, false, -5.5f, 5.5f)
verticalLineToRelative(13.0f)
arcToRelative(5.507f, 5.507f, 0.0f, false, false, 5.5f, 5.5f)
horizontalLineToRelative(13.0f)
arcToRelative(5.507f, 5.507f, 0.0f, false, false, 5.5f, -5.5f)
verticalLineToRelative(-13.0f)
arcToRelative(5.507f, 5.507f, 0.0f, false, false, -5.5f, -5.5f)
close()
moveTo(20.949f, 5.0f)
horizontalLineToRelative(-4.949f)
verticalLineToRelative(-2.0f)
horizontalLineToRelative(2.5f)
arcToRelative(2.5f, 2.5f, 0.0f, false, true, 2.449f, 2.0f)
close()
moveTo(11.0f, 3.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(4.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, -2.0f, 0.0f)
close()
moveTo(5.5f, 3.0f)
horizontalLineToRelative(2.5f)
verticalLineToRelative(2.0f)
horizontalLineToRelative(-4.949f)
arcToRelative(2.5f, 2.5f, 0.0f, false, true, 2.449f, -2.0f)
close()
moveTo(18.5f, 21.0f)
horizontalLineToRelative(-13.0f)
arcToRelative(2.5f, 2.5f, 0.0f, false, true, -2.5f, -2.5f)
verticalLineToRelative(-10.5f)
horizontalLineToRelative(5.142f)
arcToRelative(3.981f, 3.981f, 0.0f, false, false, 7.716f, 0.0f)
horizontalLineToRelative(5.142f)
verticalLineToRelative(10.5f)
arcToRelative(2.5f, 2.5f, 0.0f, false, true, -2.5f, 2.5f)
close()
moveTo(19.0f, 17.5f)
arcToRelative(1.5f, 1.5f, 0.0f, false, true, -1.5f, 1.5f)
horizontalLineToRelative(-3.0f)
arcToRelative(1.5f, 1.5f, 0.0f, false, true, 0.0f, -3.0f)
horizontalLineToRelative(3.0f)
arcToRelative(1.5f, 1.5f, 0.0f, false, true, 1.5f, 1.5f)
close()
}
}
.build()
return _boxAlt!!
}
private var _boxAlt: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 3,454
|
icons
|
MIT License
|
app/src/main/java/com/concordium/wallet/ui/cis2/retrofit/MetadataApi.kt
|
Concordium
| 358,250,608
| false
| null |
package com.concordium.wallet.ui.cis2.retrofit
import com.concordium.wallet.data.model.TokenMetadata
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Url
interface MetadataApi {
@GET suspend fun metadata(@Url url: String?): Response<TokenMetadata>
}
| 6
|
Kotlin
|
2
| 9
|
ff6970fca016387fc0ecaade085a6f2dabbaa18e
| 281
|
concordium-reference-wallet-android
|
Apache License 2.0
|
defitrack-protocols/hop/src/main/java/io/defitrack/protocol/contract/HopSwapContract.kt
|
decentri-fi
| 426,174,152
| false
| null |
package io.defitrack.protocol.contract
import io.defitrack.evm.contract.BlockchainGateway
import io.defitrack.evm.contract.EvmContract
import java.math.BigInteger
class HopSwapContract(
blockchainGateway: BlockchainGateway,
abi: String,
address: String
) : EvmContract(blockchainGateway, abi, address) {
suspend fun virtualPrice(): BigInteger {
return readWithAbi("getVirtualPrice")[0].value as BigInteger
}
}
| 17
|
Kotlin
|
6
| 9
|
cba6769eaa7a2700ccf5658c3ea9e3db7bdfca36
| 440
|
defi-hub
|
MIT License
|
kmath-optimization/src/commonMain/tmp/minuit/MnUserFcn.kt
|
SciProgCentre
| 129,486,382
| false
|
{"Kotlin": 1988014, "ANTLR": 887}
|
/*
* Copyright 2015 <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
*
* 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 ru.inr.mass.minuit
import ru.inr.mass.maths.MultiFunction
/**
*
* @version $Id$
*/
internal class MnUserFcn(fcn: MultiFunction?, errDef: Double, trafo: MnUserTransformation) : MnFcn(fcn, errDef) {
private val theTransform: MnUserTransformation = trafo
override fun value(v: RealVector): Double {
return super.value(theTransform.transform(v))
}
}
| 88
|
Kotlin
|
55
| 645
|
3e8f44166c4a4ed6e99e1676a7200ed044645224
| 972
|
kmath
|
Apache License 2.0
|
src/test/kotlin/skillx/utils/MathTest.kt
|
Techest
| 544,072,945
| false
| null |
package skillx.utils
import com.mojang.math.Vector3f
import org.junit.jupiter.api.Test
import kotlin.math.abs
class MathTest {
@Test
fun testRotateByAxisDegree() {
val toRotate = Vector3f(0F, 1F, 1F)
val axis = Vector3f(1F, 0F, 0F)
val degree = 180F.degree()
val rotated = rotateByAxis(toRotate, axis, degree)
assert(rotated.distanceSqr(Vector3f(0F, -1F, -1F)) < 0.0001)
}
@Test
fun testRotateByAxisRadian() {
val toRotate = Vector3f(0F, 1F, 1F)
val axis = Vector3f(1F, 0F, 0F)
val radian = 3.1415927F.radian()
val rotated = rotateByAxis(toRotate, axis, radian)
assert(rotated.distanceSqr(Vector3f(0F, -1F, -1F)) < 0.0001)
}
@Test
fun testAngle() {
val v1 = Vector3f(1F, 0F, 0F)
val v2 = Vector3f(1F, 1F, 0F)
val angle = v1.angle(v2)
assert(abs(angle.radian - (3.1415927F / 4)) < 0.01) { "벡터 각도 측정 알고리즘 실패! 목표값: π/4, 측정값: ${angle.radian}" }
}
}
| 0
|
Kotlin
|
1
| 3
|
3d87c88b3f8e01743c413b17c526c4b665480bf5
| 998
|
SkillX
|
MIT License
|
app/src/main/java/com/example/sample/data/JSONProvider.kt
|
retlat
| 293,239,056
| false
| null |
package com.example.sample.data
import org.chromium.net.UploadDataProvider
import org.chromium.net.UploadDataSink
import org.json.JSONObject
import java.io.IOException
import java.nio.ByteBuffer
import kotlin.math.min
class JSONProvider(json: JSONObject) : UploadDataProvider() {
private val data: ByteArray = json.toString().toByteArray()
private var position = 0
override fun getLength(): Long {
return data.size.toLong()
}
override fun read(uploadDataSink: UploadDataSink?, byteBuffer: ByteBuffer?) {
if (byteBuffer == null) {
throw IOException("Null buffer given")
}
val end = min(position + byteBuffer.limit(), data.size)
byteBuffer.put(data.copyOfRange(position, end))
uploadDataSink?.onReadSucceeded(false)
}
override fun rewind(uploadDataSink: UploadDataSink?) {
position = 0
uploadDataSink?.onRewindSucceeded()
}
}
| 0
|
Kotlin
|
0
| 0
|
30ec24718474faf6ee180dd729ec2e59627cdbfd
| 941
|
Cronet-Sample
|
Apache License 2.0
|
sam-kotlin-core/src/test/kotlin/software/elborai/api/models/AccountUpdateParamsTest.kt
|
DefinitelyATestOrg
| 787,029,213
| false
|
{"Kotlin": 12996764, "Shell": 3638, "Dockerfile": 366}
|
// File generated from our OpenAPI spec by Stainless.
package software.elborai.api.models
import java.time.LocalDate
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
import java.util.UUID
import org.junit.jupiter.api.Test
import org.assertj.core.api.Assertions.assertThat
import org.apache.hc.core5.http.ContentType
import software.elborai.api.core.ContentTypes
import software.elborai.api.core.JsonNull
import software.elborai.api.core.JsonString
import software.elborai.api.core.JsonValue
import software.elborai.api.core.MultipartFormValue
import software.elborai.api.models.*
import software.elborai.api.models.AccountUpdateParams
import software.elborai.api.models.AccountUpdateParams.AccountUpdateBody
class AccountUpdateParamsTest {
@Test
fun createAccountUpdateParams() {
AccountUpdateParams.builder()
.accountId("account_id")
.name("x")
.build()
}
@Test
fun getBody() {
val params = AccountUpdateParams.builder()
.accountId("account_id")
.name("x")
.build()
val body = params.getBody()
assertThat(body).isNotNull
assertThat(body.name()).isEqualTo("x")
}
@Test
fun getBodyWithoutOptionalFields() {
val params = AccountUpdateParams.builder()
.accountId("account_id")
.build()
val body = params.getBody()
assertThat(body).isNotNull
}
@Test
fun getPathParam() {
val params = AccountUpdateParams.builder()
.accountId("account_id")
.build()
assertThat(params).isNotNull
// path param "accountId"
assertThat(params.getPathParam(0)).isEqualTo("account_id")
// out-of-bound path param
assertThat(params.getPathParam(1)).isEqualTo("")
}
}
| 1
|
Kotlin
|
0
| 0
|
3a5229b8bc5cf400f07efbd41e00b9cf40663f97
| 1,802
|
sam-kotlin
|
Apache License 2.0
|
feedbacktree/src/main/java/com/feedbacktree/flow/ui/core/modals/AlertModal.kt
|
eliomaroun
| 254,332,538
| true
|
{"Kotlin": 114906}
|
/*
* Created by eliek on 9/26/2019
* Copyright (c) 2019 eliekarouz. All rights reserved.
*/
package com.feedbacktree.flow.ui.core.modals
data class AlertModal(
val buttons: Map<Button, String> = emptyMap(),
val message: String = "",
val title: String = "",
val cancelable: Boolean = true,
val onEvent: (Event) -> Unit
) : Modal {
enum class Button {
POSITIVE,
NEGATIVE,
NEUTRAL
}
sealed class Event {
data class ButtonClicked(val button: Button) : Event()
object Canceled : Event()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as AlertModal
return buttons == other.buttons &&
message == other.message &&
title == other.title &&
cancelable == other.cancelable
}
override fun hashCode(): Int {
var result = buttons.hashCode()
result = 31 * result + message.hashCode()
result = 31 * result + title.hashCode()
result = 31 * result + cancelable.hashCode()
return result
}
}
| 0
| null |
0
| 0
|
67517c75c452629b2036686b743c942f4c35be62
| 1,178
|
FeedbackTree
|
MIT License
|
dataprotocol/src/main/java/com/corndog/dataprotocol/buffered/ProtocolBuffer.kt
|
binchoo
| 285,145,554
| false
| null |
package dataprotocol.buffered
import dataprotocol.DataProtocol
import dataprotocol.Protocol
import java.lang.IllegalStateException
import java.nio.ByteBuffer
import java.nio.ByteOrder
class ProtocolBuffer(
private val byteBuffer: ByteBuffer,
private val protocol: Protocol
): Iterator<Any> {
private lateinit var componentBuffer: ByteBuffer
init {
rewind()
allocComponentBuffer()
}
fun rewind() {
byteBuffer.rewind()
protocol.headTo(0)
}
override fun hasNext(): Boolean {
return (currentComponentRemaining() > 0) || ((currentComponentRemaining() <= 0) && (hasValidNextComponent()))
}
private fun hasValidNextComponent(): Boolean {
val nextComponent = protocol.getNextComponent()
return (nextComponent.size <= byteBuffer.remaining())
}
override fun next(): Any {
if (currentComponentRemaining() <= 0) {
headToNextComponent()
allocComponentBuffer()
}
val value = protocol.getCurrentComponent().fetch(componentBuffer)!!
byteBuffer.position(byteBuffer.position() + currentComponentPrimitiveSize())
return value
}
private fun headToNextComponent() {
protocol.headToNextComponent()
if (currentComponentDataCount() == DataProtocol.DECLARE_LAZY_COUNT)
throw IllegalStateException("Component's data count has not been lazily initialized.")
}
private fun allocComponentBuffer() {
componentBuffer = byteBuffer.slice().limit(currentComponentSize()) as ByteBuffer
}
fun currentComponentRemaining(): Int {
return componentBuffer.remaining()
}
fun currentComponentDataCount(): Int {
return protocol.getCurrentComponent().count
}
fun currentComponentIndex(): Int {
return protocol.getCurrentComponentIndex()
}
fun currentComponentPrimitiveSize(): Int {
return protocol.getCurrentComponent().primitiveSize
}
fun currentComponentOrder(): ByteOrder {
return protocol.getCurrentComponent().order
}
fun currentComponentSize(): Int {
return protocol.getCurrentComponent().size
}
fun changeComponentDataCount(componentIndex: Int, count: Int) {
protocol.changeComponentNumber(componentIndex, count)
}
}
| 0
|
Kotlin
|
0
| 1
|
00f10f5f79ac6567d22d234ad93056d5244b3a71
| 2,332
|
kotlin-dataprotocol
|
MIT License
|
vscode/src/jsMain/kotlin/vscode/Extension.kt
|
lppedd
| 761,812,661
| false
|
{"Kotlin": 1887051}
|
package vscode
/**
* Represents an extension.
*
* To get an instance of an `Extension` use [vscode.extensions.getExtension].
*/
external interface Extension<T> {
/**
* The canonical extension identifier in the form of: `publisher.name`.
*/
val id: String
/**
* The uri of the directory containing the extension.
*/
val extensionUri: Uri
/**
* The absolute file path of the directory containing this extension. Shorthand
* notation for `Extension.extensionUri.fsPath` (independent of the uri scheme).
*/
val extensionPath: String
/**
* `true` if the extension has been activated.
*/
val isActive: Boolean
/**
* The parsed contents of the extension's package.json.
*/
val packageJSON: Any?
/**
* The extension kind describes if an extension runs where the UI runs
* or if an extension runs where the remote extension host runs. The extension kind
* is defined in the `package.json`-file of extensions but can also be refined
* via the `remote.extensionKind`-setting. When no remote extension host exists,
* the value is [ExtensionKind.UI].
*/
var extensionKind: ExtensionKind
/**
* The public API exported by this extension (return value of `activate`).
* It is an invalid action to access this field before this extension has been activated.
*/
val exports: T
/**
* Activates this extension and returns its public API.
*
* @return A promise that will resolve when this extension has been activated.
*/
fun activate(): Thenable<T>
}
| 0
|
Kotlin
|
0
| 3
|
0f493d3051afa3de2016e5425a708c7a9ed6699a
| 1,547
|
kotlin-externals
|
MIT License
|
examples/chatgpt/site/src/jvmMain/kotlin/chatgpt/api/Chat.kt
|
varabyte
| 397,003,009
| false
|
{"FreeMarker": 43473}
|
package chatgpt.api
import apis.openai.endpoints.chat.sendMessageToChatGpt
import chatgpt.init.ChatHistories
import chatgpt.model.MessageChunkResponse
import chatgpt.model.MessageRequest
import com.varabyte.kobweb.api.data.getValue
import com.varabyte.kobweb.api.stream.ApiStream
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import okhttp3.OkHttpClient
val chat = object : ApiStream() {
override suspend fun onTextReceived(ctx: TextReceivedContext) {
val json = ctx.data.getValue<Json>()
val httpClient = ctx.data.getValue<OkHttpClient>()
val histories = ctx.data.getValue<ChatHistories>()
val messageRequest = json.decodeFromString<MessageRequest>(ctx.text)
sendMessageToChatGpt(
json,
httpClient,
messageRequest.text,
histories.getFor(messageRequest.chatId),
).collect { chunk ->
chunk.choices.firstOrNull()?.delta?.content?.let { content ->
ctx.stream.send(json.encodeToString(MessageChunkResponse(content)))
} ?: run {
ctx.stream.disconnect()
}
}
}
}
| 0
|
FreeMarker
|
4
| 12
|
7b676edb93160d789c1a88fa01142358739e95cc
| 1,177
|
kobweb-templates
|
Apache License 2.0
|
defitrack-rest/defitrack-protocol-service/src/main/java/io/defitrack/protocol/balancer/pooling/BalancerPolygonPoolingMarketProvider.kt
|
decentri-fi
| 426,174,152
| false
|
{"Kotlin": 1038532, "Java": 1948, "Dockerfile": 909}
|
package io.defitrack.protocol.balancer.pooling
import io.defitrack.common.network.Network
import io.defitrack.conditional.ConditionalOnCompany
import io.defitrack.protocol.Company
import io.defitrack.protocol.balancer.contract.BalancerService
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.stereotype.Component
@Component
@ConditionalOnCompany(Company.BALANCER)
@ConditionalOnProperty(value = ["polygon.enabled"], havingValue = "true", matchIfMissing = true)
class BalancerPolygonPoolingMarketProvider(balancerService: BalancerService) :
BalancerPoolingMarketProvider(balancerService) {
override fun getNetwork(): Network {
return Network.POLYGON
}
}
| 53
|
Kotlin
|
7
| 9
|
e65843453e4c44f5c2626870ceb923eb7ab3c4d0
| 731
|
defi-hub
|
MIT License
|
src/test/kotlin/solved/p2221/SolutionTest.kt
|
mr-nothing
| 469,475,608
| false
| null |
package solved.p2221
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.DynamicTest
import org.junit.jupiter.api.TestFactory
internal class SolutionTest {
@TestFactory
fun `test solution`() = listOf(
arrayOf(1,2,3,4,5) to 8,
arrayOf(5) to 5
).map { (inputData, expected) ->
DynamicTest.dynamicTest("The triangle sum of [${inputData.joinToString()}] sequence is $expected") {
Assertions.assertEquals(expected, Solution().triangularSum(inputData.toIntArray()))
}
}
}
| 0
|
Kotlin
|
0
| 0
|
0f7418ecc8675d8361ef31cbc1ee26ea51f7708a
| 544
|
leetcode
|
Apache License 2.0
|
cinescout/screenplay/domain/src/commonMain/kotlin/cinescout/screenplay/domain/model/SeasonNumber.kt
|
fardavide
| 280,630,732
| false
| null |
package cinescout.screenplay.domain.model
import kotlinx.serialization.Serializable
@JvmInline
@Serializable
value class SeasonNumber(val value: Int)
| 10
|
Kotlin
|
2
| 6
|
7a875cd67a3df0ab98af520485122652bd5de560
| 152
|
CineScout
|
Apache License 2.0
|
shared/src/commonMain/kotlin/com/presta/customer/ui/components/savingsTransactionHistory/SavingsTransactionHistoryComponent.kt
|
morgan4080
| 726,765,347
| false
|
{"Kotlin": 2170913, "Swift": 2162, "Ruby": 382, "Shell": 228}
|
package com.presta.customer.ui.components.savingsTransactionHistory
import com.arkivanov.decompose.value.Value
interface SavingsTransactionHistoryComponent {
val model: Value<Model>
fun onSelected(item: String)
data class Model(
val items: List<String>,
)
}
| 0
|
Kotlin
|
0
| 0
|
0850928853c87390a97953cfec2d21751904d3a9
| 287
|
kmp
|
Apache License 2.0
|
inspektifySample/composeApp/src/commonMain/kotlin/sp/bvantur/inspektify/sample/domain/usecase/CreateUserUseCase.kt
|
BVantur
| 844,048,160
| false
|
{"Kotlin": 169455, "Swift": 1303}
|
package sp.bvantur.inspektify.sample.domain.usecase
import sp.bvantur.inspektify.sample.data.user.UserRepository
import sp.bvantur.inspektify.sample.domain.model.User
import sp.bvantur.inspektify.sample.domain.utils.toUser
interface CreateUserUseCase {
suspend operator fun invoke(): Result<User?>
}
class CreateUserUseCaseImpl(private val userRepository: UserRepository) : CreateUserUseCase {
override suspend fun invoke(): Result<User?> {
val response = userRepository.createUser()
if (response.isFailure) {
return Result.failure(response.exceptionOrNull() ?: Exception("Unknown error"))
}
return Result.success(response.getOrNull()?.toUser())
}
}
| 2
|
Kotlin
|
4
| 88
|
f824a3fe4eb81d35400dab76ce39e14dca84edf0
| 710
|
inspektify
|
MIT License
|
app/src/main/java/com/friendly_machines/frbpdoctor/watchprotocol/command/WatchChangeAlarmAction.kt
|
daym
| 744,679,396
| false
|
{"Kotlin": 177161}
|
package com.friendly_machines.frbpdoctor.watchprotocol.command
enum class WatchChangeAlarmAction(val code: Byte) {
Edit(0),
Add(1);
}
| 0
|
Kotlin
|
1
| 1
|
f6c5c0c8320ca29f976b8eb57c397e0db01bc13c
| 143
|
frbpdoctor
|
BSD 2-Clause FreeBSD License
|
core/domain/src/main/java/com/kursatkumsuz/domain/model/coin/CoinItem.kt
|
kursatkumsuz
| 554,661,928
| false
|
{"Kotlin": 166960}
|
package com.kursatkumsuz.domain.model.coin
data class CoinItem(
val id: Int,
val name: String,
val quote: Quote,
val symbol: String
)
| 0
|
Kotlin
|
7
| 41
|
664e597b49a981867966dab9a292c02e28cc61cf
| 151
|
crypto-portfolio-jetpack-compose
|
Apache License 2.0
|
src/Day03/Day03.kt
|
hectdel
| 573,376,349
| false
| null |
package Day03
import java.io.File
fun main() {
val chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
fun Char.toValue(): Int = chars.indexOf(this) + 1
check('p'.toValue() == 16)
check('L'.toValue() == 38)
fun part1(input: String): Int {
var commonChars = mutableListOf<Char>()
input.lines()
.map { it.substring(0, it.length.div(2)) to it.substring(it.length.div(2), it.length) }
.map {
it.first.iterator().forEach { char ->
if (it.second.contains(char)) {
commonChars.add(char)
return@map
}
}
}
return commonChars.map { it.toValue() }.sum()
}
fun containsChar(c: Char, line:String):Boolean {
return line.contains(c)
}
fun calculateResult(n: Int, input: String) : Int{
val grouped = input
.lines()
.chunked(n)
return grouped.sumOf {
it.first()
.toCharArray()
.first { char -> IntRange(1, n - 1).all { n -> containsChar(char, it[n]) } }
.toValue()
}
}
fun part2(input: String): Int {
return calculateResult(3, input)
}
val testInput = File("src/Day03/test_data.txt").readText()
println(part1(testInput))
check(part1(testInput) == 157)
check(part2(testInput) == 70 )
val input = File("src/Day03/data.txt").readText()
println(part1(input))
println(part2(input))
}
| 0
|
Kotlin
|
0
| 0
|
cff5677a654a18ceb199cc52fdd1c865dea46e1e
| 1,569
|
aco-kotlin-2022
|
Apache License 2.0
|
src/main/java/org/web25/http/HttpRegistry.kt
|
Web25
| 66,868,564
| true
|
{"Kotlin": 325176, "Shell": 369}
|
package org.web25.http
/**
* Created by felix on 3/18/17.
*/
interface HttpRegistry {
fun addSerializer(serializer: HttpSerializer<*, *>)
fun <T: Any> serialize(value: T): HttpEntity
fun deserialize(data: ByteArray, contentType: String): HttpEntity
}
| 6
|
Kotlin
|
0
| 0
|
363f9cdd3e3bfdcc3f5444d46fa044b53519b6d0
| 268
|
http
|
MIT License
|
app/src/main/java/com/breezedealmatrix/features/orderList/model/NewOrderListResponseModel.kt
|
DebashisINT
| 865,411,090
| false
|
{"Kotlin": 15862964, "Java": 1029932}
|
package com.breezedealmatrix.features.orderList.model
import com.breezedealmatrix.base.BaseResponse
/**
* Created by Saikat on 03-12-2018.
*/
class NewOrderListResponseModel : BaseResponse() {
var order_list: ArrayList<NewOrderListDataModel>? = null
}
| 0
|
Kotlin
|
0
| 0
|
032400c3fce3853a1488e2b580bee07a8e447c90
| 259
|
DealMatrixPvtLtd
|
Apache License 2.0
|
example/server/src/main/kotlin/com/yt8492/commonjudgesystem/example/server/test/application/gettweet/GetTweetError.kt
|
yt8492
| 419,847,372
| false
|
{"Kotlin": 62662}
|
package com.yt8492.commonjudgesystem.example.server.test.application.gettweet
import com.yt8492.commonjudgesystem.library.Error
sealed interface GetTweetError : Error {
object TweetNotFound : GetTweetError
object UnexpectedJson : GetTweetError
object ConnectionRefused : GetTweetError
object Unknown : GetTweetError
}
| 0
|
Kotlin
|
0
| 0
|
e8bde9962b0883bc200cee88af2841731d14ed64
| 336
|
CommonJudgeSystem
|
MIT License
|
app/src/main/kotlin/com/dleibovich/todokotlin/calendar/CalendarActivity.kt
|
ariedov
| 25,394,337
| false
| null |
package com.dleibovich.todokotlin.calendar
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.view.MenuItem
import android.view.View
import com.dleibovich.todokotlin.R
import com.dleibovich.todokotlin.TodoApp
import kotlinx.android.synthetic.main.activity_calendar.*
import java.util.*
import javax.inject.Inject
class CalendarActivity : AppCompatActivity(), CalendarView {
@Inject lateinit var presenter: CalendarPresenter
private val adapter = CalendarAdapter(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_calendar)
(application as TodoApp)
.dataComponent()
.inject(this)
setSupportActionBar(toolbar)
supportActionBar?.title = getString(R.string.calendar)
supportActionBar?.setDisplayShowHomeEnabled(true)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
list.layoutManager = LinearLayoutManager(this)
list.adapter = adapter
presenter.setView(this)
presenter.requestData()
}
override fun onStop() {
super.onStop()
presenter.stop()
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (item?.itemId == android.R.id.home) {
onBackPressed()
return true
}
return super.onOptionsItemSelected(item)
}
override fun setDates(dates: List<Date>) {
adapter.setDates(dates)
list.visibility = View.VISIBLE
empty.visibility = View.GONE
}
override fun setEmpty() {
list.visibility = View.GONE
empty.visibility = View.VISIBLE
}
}
| 0
|
Kotlin
|
0
| 1
|
81515dc36145175b91562a63cd04eaf640c8dedb
| 1,787
|
TODOKotlin
|
Apache License 2.0
|
app/src/main/java/com/peteralexbizjak/europaopen/db/repositories/IRegionDBRepository.kt
|
sunderee
| 375,731,952
| false
| null |
package com.peteralexbizjak.europaopen.db.repositories
import com.peteralexbizjak.europaopen.db.entities.RegionEntity
internal interface IRegionDBRepository {
suspend fun storeRegions(regions: List<RegionEntity>)
suspend fun retrieveRegionsByCountryCode(countryCode: String): List<RegionEntity>
}
| 0
|
Kotlin
|
0
| 2
|
968705e28f1a5ae012338452d8100f364e886a20
| 306
|
EuropaOpen
|
MIT License
|
shared/src/commonMain/kotlin/ca/josuelubaki/countryapp/presentation/country/CountryViewModel.kt
|
josue-lubaki
| 698,621,660
| false
|
{"Kotlin": 66805, "Ruby": 1975, "Swift": 971, "Shell": 228}
|
package ca.josuelubaki.countryapp.presentation.country
import ca.josuelubaki.countryapp.data.repository.CountryRepositoryImpl
import ca.josuelubaki.countryapp.domain.usecases.GetCountryDetailsByCodeUseCase
import ca.josuelubaki.countryapp.presentation.countries.CurrentBottomSheetContent
import ca.josuelubaki.countryapp.utils.HttpError
import com.apollographql.apollo3.exception.ApolloException
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import moe.tlaster.precompose.viewmodel.ViewModel
import moe.tlaster.precompose.viewmodel.viewModelScope
/**
* created by <NAME>
* date : 2023-10-01
* version : 1.0.0
*/
class CountryViewModel(
private val getCountryDetailsByCodeUseCase: GetCountryDetailsByCodeUseCase,
private val dispatcher : CoroutineDispatcher
) : ViewModel() {
private val _state = MutableStateFlow<CountryState>(CountryState.Idle)
val state get() : StateFlow<CountryState> = _state.asStateFlow()
private val _currentBottomSheetContent = MutableStateFlow(CurrentBottomSheetContent.STATES)
val currentBottomSheetContent = _currentBottomSheetContent.asStateFlow()
fun onEvent(event: CountryEvent){
when (event){
is CountryEvent.OnLoadCountry -> {
getCountryDetails(event.code)
}
is CountryEvent.OnSetCurrentBottomSheet -> {
setCurrentBottomSheet(event.currentBottomSheetContent)
}
}
}
private fun setCurrentBottomSheet(currentBottomSheetContent: CurrentBottomSheetContent) {
_currentBottomSheetContent.value = currentBottomSheetContent
}
private fun getCountryDetails(countryCode : String?) {
viewModelScope.launch(dispatcher) {
countryCode?.let {
_state.value = CountryState.Loading
_state.value = try {
val country = getCountryDetailsByCodeUseCase(it)
CountryState.Success(country)
} catch (exception: Exception) {
CountryState.Error(
if ((exception as ApolloException).suppressedExceptions.isNotEmpty()) HttpError.APOLLO_EXCEPTION
else HttpError.UNKNOWN
)
}
} ?: kotlin.run {
_state.value = CountryState.Error(error = HttpError.CODE_MISSING)
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
86c35e1cca6610b3e96f482844bfa25d494ca388
| 2,634
|
sample-graphql-kmp
|
MIT License
|
app/src/main/java/dev/haenara/githubsearch/repo/github/GithubUserRepoImpl.kt
|
HaenaraShin
| 254,657,864
| false
| null |
package dev.haenara.githubsearch.repo.github
import dev.haenara.githubsearch.api.GitHubSearchRetrofit
import dev.haenara.githubsearch.model.User
import dev.haenara.githubsearch.model.UserList
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class GithubUserRepoImpl : GithubUserRepo {
private val cached = hashMapOf<Pair<String, Int>, List<User>>()
override fun getUserList(
name: String,
page: Int,
success: (List<User>) -> Unit,
error: (String) -> Unit
) {
if (isCached(name, page)) {
getFromCache(name, page, success, error)
} else {
getFromApi(name, page, success, error)
}
}
private fun getFromApi(
name: String,
page: Int,
success: (List<User>) -> Unit,
error: (String) -> Unit
) {
GitHubSearchRetrofit.create().searchUsers("$name+in:login", page).enqueue(
object : Callback<UserList> {
override fun onFailure(call: Call<UserList>, t: Throwable) {
t.printStackTrace()
error(t.localizedMessage ?: "")
}
override fun onResponse(call: Call<UserList>, response: Response<UserList>) {
if (response.isSuccessful && response.body()?.items != null) {
caching(name, page, response.body()?.items!!)
success(response.body()?.items!!)
}
}
}
)
}
private fun caching(name: String, page: Int, items: List<User>) {
cached[Pair(name, page)] = items
}
private fun getFromCache(
name: String,
page: Int,
success: (List<User>) -> Unit,
error: (String) -> Unit
) {
try {
success(cached[Pair(name, page)]!!)
} catch (e: NoSuchElementException) {
error(e.localizedMessage ?: "")
}
}
private fun isCached(name: String, page: Int) = cached.containsKey(Pair(name, page))
}
| 0
|
Kotlin
|
0
| 2
|
3d1c84cb0518814ee5752157cd3d941c894a310c
| 2,070
|
GithubUserSearch
|
MIT License
|
src/backend/ci/core/common/common-api/src/main/kotlin/com/tencent/devops/common/api/util/Watcher.kt
|
necrohuang
| 227,612,065
| true
|
{"Kotlin": 12321904, "Vue": 3575964, "Java": 1424480, "JavaScript": 914356, "CSS": 428463, "TSQL": 287717, "Lua": 204919, "Go": 136780, "HTML": 46195, "TypeScript": 33124, "Shell": 29974, "Python": 3714, "PLSQL": 2378, "Batchfile": 2174, "Makefile": 669}
|
package com.tencent.devops.common.api.util
import org.springframework.util.StopWatch
/**
* 非线程安全
* 针对running值导致抛出异常的位置主动做了stop,并增加了一个全部耗时统计
*/
class Watcher(id: String = "") : StopWatch(id) {
private var createTime: Long = System.currentTimeMillis()
fun elapsed() = System.currentTimeMillis() - createTime
override fun start() {
if (isRunning) {
stop()
}
super.start()
}
override fun start(taskName: String?) {
if (isRunning) {
stop()
}
super.start(taskName)
}
override fun toString(): String {
if (isRunning) {
stop()
}
return super.toString()
}
override fun shortSummary(): String {
return super.shortSummary() + ", elapsed=${elapsed()}ms"
}
override fun stop() {
if (isRunning) {
super.stop()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
237eeb686b2f443a16e1147ab26d88fe4897d2d7
| 905
|
bk-ci
|
MIT License
|
android/app/src/main/kotlin/com/example/timeline/MainActivity.kt
|
samKenpachi011
| 280,711,411
| false
|
{"Dart": 8167, "Swift": 404, "Kotlin": 125, "Objective-C": 38}
|
package com.example.timeline
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0
|
Dart
|
0
| 0
|
d163ad08479bbac109d16cbfb9652e9bfba0385c
| 125
|
Flutter-Simple-TimeLine
|
MIT License
|
app/src/main/java/org/stepic/droid/ui/custom/CustomFontURLSpan.kt
|
kartmatias
| 276,363,514
| true
|
{"Kotlin": 2846749, "Java": 1006902, "CSS": 5370, "Shell": 618, "Prolog": 98}
|
package org.stepic.droid.ui.custom
import android.text.TextPaint
import android.text.style.URLSpan
class CustomFontURLSpan(url: String) : URLSpan(url) {
override fun updateDrawState(ds: TextPaint) {
super.updateDrawState(ds)
ds.isUnderlineText = false
}
}
| 0
| null |
0
| 0
|
ac7ff5e6ebac469578c27217e246f110a1f444c5
| 281
|
stepik-android
|
Apache License 2.0
|
feature/tv/player/src/main/kotlin/com/flixclusive/feature/tv/player/controls/settings/common/ConfirmButton.kt
|
flixclusiveorg
| 659,237,375
| false
|
{"Kotlin": 1904772, "Java": 18011}
|
package com.flixclusive.feature.tv.player.controls.settings.common
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.tv.material3.Border
import androidx.tv.material3.ClickableSurfaceDefaults
import androidx.tv.material3.ExperimentalTvMaterial3Api
import androidx.tv.material3.Glow
import androidx.tv.material3.MaterialTheme
import androidx.tv.material3.Surface
import androidx.tv.material3.Text
import com.flixclusive.core.ui.common.util.onMediumEmphasis
@OptIn(ExperimentalTvMaterial3Api::class)
@Composable
internal fun ConfirmButton(
modifier: Modifier = Modifier,
label: String,
isEmphasis: Boolean,
onClick: () -> Unit
) {
val (containerColor, contentColor) = when(isEmphasis) {
true -> MaterialTheme.colorScheme.onSurface to MaterialTheme.colorScheme.surface.onMediumEmphasis(0.8F)
false -> Color(0xFF5F5F5F) to Color(0xFFFFFFFF).onMediumEmphasis()
}
Surface(
onClick = onClick,
colors = ClickableSurfaceDefaults.colors(
containerColor = containerColor,
contentColor = contentColor,
focusedContainerColor = containerColor,
focusedContentColor = contentColor
),
border = ClickableSurfaceDefaults.border(
focusedBorder = Border(
border = BorderStroke(
width = 2.dp,
color = MaterialTheme.colorScheme.primary
),
shape = MaterialTheme.shapes.extraSmall
)
),
glow = ClickableSurfaceDefaults.glow(
focusedGlow = Glow(
elevationColor = MaterialTheme.colorScheme.primary,
elevation = 15.dp
),
pressedGlow = Glow(
elevationColor = MaterialTheme.colorScheme.primary,
elevation = 40.dp
),
),
shape = ClickableSurfaceDefaults.shape(MaterialTheme.shapes.extraSmall),
modifier = modifier
.heightIn(min = 20.dp)
.width(150.dp)
) {
Text(
text = label,
style = MaterialTheme.typography.labelLarge.copy(
fontSize = 15.sp,
fontWeight = FontWeight.Black
),
modifier = Modifier
.align(Alignment.Center)
.padding(5.dp)
)
}
}
| 26
|
Kotlin
|
29
| 362
|
f488f6d1b2de3ec0737a8437ce1c981bc2f55c31
| 2,798
|
Flixclusive
|
MIT License
|
app/src/sharedTest/java/org/oppia/app/profile/AdminAuthActivityTest.kt
|
sajalasati
| 269,276,236
| true
|
{"Kotlin": 3567791, "Starlark": 86669, "Java": 27558, "Shell": 1855}
|
package org.oppia.app.profile
import android.app.Application
import android.content.Context
import android.os.Build
import android.view.View
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.test.core.app.ActivityScenario.launch
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.UiController
import androidx.test.espresso.ViewAction
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.closeSoftKeyboard
import androidx.test.espresso.action.ViewActions.pressImeActionButton
import androidx.test.espresso.action.ViewActions.typeText
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.intent.Intents
import androidx.test.espresso.intent.Intents.intended
import androidx.test.espresso.intent.matcher.IntentMatchers.hasComponent
import androidx.test.espresso.matcher.ViewMatchers.isDescendantOfA
import androidx.test.espresso.matcher.ViewMatchers.isEnabled
import androidx.test.espresso.matcher.ViewMatchers.isRoot
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.runners.AndroidJUnit4
import dagger.Component
import org.hamcrest.Matcher
import org.hamcrest.Matchers.allOf
import org.junit.After
import org.junit.Before
import org.junit.Ignore
import org.junit.Test
import org.junit.runner.RunWith
import org.oppia.app.R
import org.oppia.app.activity.ActivityComponent
import org.oppia.app.administratorcontrols.AdministratorControlsActivity
import org.oppia.app.application.ActivityComponentFactory
import org.oppia.app.application.ApplicationComponent
import org.oppia.app.application.ApplicationInjector
import org.oppia.app.application.ApplicationInjectorProvider
import org.oppia.app.application.ApplicationModule
import org.oppia.app.application.ApplicationStartupListenerModule
import org.oppia.app.player.state.hintsandsolution.HintsAndSolutionConfigModule
import org.oppia.app.shim.ViewBindingShimModule
import org.oppia.app.utility.OrientationChangeAction.Companion.orientationLandscape
import org.oppia.domain.classify.InteractionsModule
import org.oppia.domain.classify.rules.continueinteraction.ContinueModule
import org.oppia.domain.classify.rules.dragAndDropSortInput.DragDropSortInputModule
import org.oppia.domain.classify.rules.fractioninput.FractionInputModule
import org.oppia.domain.classify.rules.imageClickInput.ImageClickInputModule
import org.oppia.domain.classify.rules.itemselectioninput.ItemSelectionInputModule
import org.oppia.domain.classify.rules.multiplechoiceinput.MultipleChoiceInputModule
import org.oppia.domain.classify.rules.numberwithunits.NumberWithUnitsRuleModule
import org.oppia.domain.classify.rules.numericinput.NumericInputRuleModule
import org.oppia.domain.classify.rules.ratioinput.RatioInputModule
import org.oppia.domain.classify.rules.textinput.TextInputRuleModule
import org.oppia.domain.onboarding.ExpirationMetaDataRetrieverModule
import org.oppia.domain.oppialogger.LogStorageModule
import org.oppia.domain.oppialogger.loguploader.LogUploadWorkerModule
import org.oppia.domain.oppialogger.loguploader.WorkManagerConfigurationModule
import org.oppia.domain.question.QuestionModule
import org.oppia.domain.topic.PrimeTopicAssetsControllerModule
import org.oppia.testing.TestAccessibilityModule
import org.oppia.testing.TestCoroutineDispatchers
import org.oppia.testing.TestDispatcherModule
import org.oppia.testing.TestLogReportingModule
import org.oppia.util.caching.testing.CachingTestModule
import org.oppia.util.gcsresource.GcsResourceModule
import org.oppia.util.logging.LoggerModule
import org.oppia.util.logging.firebase.FirebaseLogUploaderModule
import org.oppia.util.parser.GlideImageLoaderModule
import org.oppia.util.parser.HtmlParserEntityTypeModule
import org.oppia.util.parser.ImageParsingModule
import org.robolectric.annotation.Config
import org.robolectric.annotation.LooperMode
import javax.inject.Inject
import javax.inject.Singleton
@RunWith(AndroidJUnit4::class)
@LooperMode(LooperMode.Mode.PAUSED)
@Config(
application = AdminAuthActivityTest.TestApplication::class,
qualifiers = "port-xxhdpi"
)
class AdminAuthActivityTest {
@Inject
lateinit var context: Context
@Inject
lateinit var testCoroutineDispatchers: TestCoroutineDispatchers
private val internalProfileId: Int = 0
@Before
fun setUp() {
Intents.init()
setUpTestApplicationComponent()
testCoroutineDispatchers.registerIdlingResource()
}
@After
fun tearDown() {
testCoroutineDispatchers.unregisterIdlingResource()
Intents.release()
}
private fun setUpTestApplicationComponent() {
ApplicationProvider.getApplicationContext<TestApplication>().inject(this)
}
@Test
fun testAdminAuthActivity_inputCorrectPassword_opensAddProfileActivity() {
launch<AdminAuthActivity>(
AdminAuthActivity.createAdminAuthActivityIntent(
context,
"12345",
internalProfileId,
-10710042,
AdminAuthEnum.PROFILE_ADD_PROFILE.value
)
).use {
testCoroutineDispatchers.runCurrent()
onView(allOf(withId(R.id.input), isDescendantOfA(withId(R.id.admin_auth_input_pin)))).perform(
appendText("12345"),
closeSoftKeyboard()
)
onView(withId(R.id.admin_auth_submit_button)).perform(click())
testCoroutineDispatchers.runCurrent()
intended(hasComponent(AddProfileActivity::class.java.name))
}
}
// TODO(#962): Reenable once IME_ACTIONS work correctly on ProfileInputView.
@Ignore("IME_ACTIONS doesn't work properly in ProfileInputView")
@Test
fun testAdminAuthActivity_inputCorrectPassword_clickImeActionButton_opensAddProfileActivity() {
launch<AdminAuthActivity>(
AdminAuthActivity.createAdminAuthActivityIntent(
context,
"12345",
internalProfileId,
-10710042,
AdminAuthEnum.PROFILE_ADD_PROFILE.value
)
).use {
onView(allOf(withId(R.id.input), isDescendantOfA(withId(R.id.admin_auth_input_pin)))).perform(
typeText("12345"),
pressImeActionButton()
)
intended(hasComponent(AddProfileActivity::class.java.name))
}
}
@Test
fun testAdminAuthActivity_inputCorrectPassword_opensAddAdministratorControlsActivity() {
launch<AdminAuthActivity>(
AdminAuthActivity.createAdminAuthActivityIntent(
context,
"12345",
internalProfileId,
-10710042,
AdminAuthEnum.PROFILE_ADMIN_CONTROLS.value
)
).use {
testCoroutineDispatchers.runCurrent()
onView(allOf(withId(R.id.input), isDescendantOfA(withId(R.id.admin_auth_input_pin)))).perform(
appendText("12345"),
closeSoftKeyboard()
)
onView(withId(R.id.admin_auth_submit_button)).perform(click())
testCoroutineDispatchers.runCurrent()
intended(hasComponent(AdministratorControlsActivity::class.java.name))
}
}
// TODO(#962): Reenable once IME_ACTIONS work correctly on ProfileInputView.
@Ignore("IME_ACTIONS doesn't work properly in ProfileInputView")
@Test
fun testAdminAuthActivity_inputCorrectPassword_clickImeActionButton_opensAddAdministratorControlsActivity() { // ktlint-disable max-line-length
launch<AdminAuthActivity>(
AdminAuthActivity.createAdminAuthActivityIntent(
context,
"12345",
internalProfileId,
-10710042,
AdminAuthEnum.PROFILE_ADMIN_CONTROLS.value
)
).use {
onView(allOf(withId(R.id.input), isDescendantOfA(withId(R.id.admin_auth_input_pin)))).perform(
typeText("12345"),
pressImeActionButton()
)
intended(hasComponent(AdministratorControlsActivity::class.java.name))
}
}
@Test
fun testAdminAuthActivity_inputIncorrectPassword_checkError() {
launch<AdminAuthActivity>(
AdminAuthActivity.createAdminAuthActivityIntent(
context,
"12345",
internalProfileId,
-10710042,
AdminAuthEnum.PROFILE_ADMIN_CONTROLS.value
)
).use {
testCoroutineDispatchers.runCurrent()
onView(allOf(withId(R.id.input), isDescendantOfA(withId(R.id.admin_auth_input_pin)))).perform(
appendText("12354"),
closeSoftKeyboard()
)
onView(withId(R.id.admin_auth_submit_button)).perform(click())
onView(
allOf(
withId(R.id.error_text),
isDescendantOfA(withId(R.id.admin_auth_input_pin))
)
).check(matches(withText(context.resources.getString(R.string.admin_auth_incorrect))))
}
}
// TODO(#962): Reenable once IME_ACTIONS work correctly on ProfileInputView.
@Ignore("IME_ACTIONS doesn't work properly in ProfileInputView")
@Test
fun testAdminAuthActivity_inputIncorrectPassword_clickImeActionButton_checkError() {
launch<AdminAuthActivity>(
AdminAuthActivity.createAdminAuthActivityIntent(
context,
"12345",
internalProfileId,
-10710042,
AdminAuthEnum.PROFILE_ADMIN_CONTROLS.value
)
).use {
onView(allOf(withId(R.id.input), isDescendantOfA(withId(R.id.admin_auth_input_pin)))).perform(
typeText("12354"),
pressImeActionButton()
)
onView(
allOf(
withId(R.id.error_text),
isDescendantOfA(withId(R.id.admin_auth_input_pin))
)
).check(matches(withText(context.resources.getString(R.string.admin_auth_incorrect))))
}
}
@Test
fun testAdminAuthActivity_inputIncorrectPassword_inputAgain_checkErrorIsGone() {
launch<AdminAuthActivity>(
AdminAuthActivity.createAdminAuthActivityIntent(
context,
"12345",
internalProfileId,
-10710042,
AdminAuthEnum.PROFILE_ADMIN_CONTROLS.value
)
).use {
onView(allOf(withId(R.id.input), isDescendantOfA(withId(R.id.admin_auth_input_pin)))).perform(
typeText("123"),
closeSoftKeyboard()
)
onView(withId(R.id.admin_auth_submit_button)).perform(click())
onView(allOf(withId(R.id.input), isDescendantOfA(withId(R.id.admin_auth_input_pin)))).perform(
typeText("4"),
closeSoftKeyboard()
)
onView(
allOf(
withId(R.id.error_text),
isDescendantOfA(withId(R.id.admin_auth_input_pin))
)
).check(matches(withText("")))
}
}
// TODO(#962): Reenable once IME_ACTIONS work correctly on ProfileInputView.
@Ignore("IME_ACTIONS doesn't work properly in ProfileInputView")
@Test
fun testAdminAuthActivity_inputIncorrectPassword_inputAgain_clickImeActionButton_checkErrorIsGone() { // ktlint-disable max-line-length
launch<AdminAuthActivity>(
AdminAuthActivity.createAdminAuthActivityIntent(
context,
"12345",
internalProfileId,
-10710042,
AdminAuthEnum.PROFILE_ADMIN_CONTROLS.value
)
).use {
onView(allOf(withId(R.id.input), isDescendantOfA(withId(R.id.admin_auth_input_pin)))).perform(
typeText("123"),
pressImeActionButton()
)
onView(allOf(withId(R.id.input), isDescendantOfA(withId(R.id.admin_auth_input_pin)))).perform(
typeText("4"),
closeSoftKeyboard()
)
onView(
allOf(
withId(R.id.error_text),
isDescendantOfA(withId(R.id.admin_auth_input_pin))
)
).check(matches(withText("")))
}
}
@Test
fun testAdminAuthActivity_buttonState_configurationChanged_buttonStateIsPreserved() {
launch<AdminAuthActivity>(
AdminAuthActivity.createAdminAuthActivityIntent(
context,
"12345",
internalProfileId,
-10710042,
AdminAuthEnum.PROFILE_ADMIN_CONTROLS.value
)
).use {
onView(allOf(withId(R.id.input), isDescendantOfA(withId(R.id.admin_auth_input_pin)))).perform(
typeText("12345"),
closeSoftKeyboard()
)
onView(isRoot()).perform(orientationLandscape())
onView(withId(R.id.admin_auth_submit_button)).check(matches(isEnabled()))
}
}
@Test
fun testAdminAuthActivity_openedFromAdminControls_configurationChanged_checkHeadingSubHeadingIsPreserved() { // ktlint-disable max-line-length
launch<AdminAuthActivity>(
AdminAuthActivity.createAdminAuthActivityIntent(
context,
"12345",
internalProfileId,
-10710042,
AdminAuthEnum.PROFILE_ADMIN_CONTROLS.value
)
).use {
onView(withId(R.id.admin_auth_heading_textview)).check(
matches(
withText(
context.resources.getString(
R.string.admin_auth_heading
)
)
)
)
onView(withId(R.id.admin_auth_sub_text))
.check(
matches(
withText(
context.resources.getString(
R.string.admin_auth_admin_controls_sub
)
)
)
)
onView(isRoot()).perform(orientationLandscape())
onView(withId(R.id.admin_auth_sub_text))
.check(
matches(
withText(
context.resources.getString(R.string.admin_auth_admin_controls_sub)
)
)
)
onView(withId(R.id.admin_auth_heading_textview)).check(
matches(
withText(
context.resources.getString(
R.string.admin_auth_heading
)
)
)
)
}
}
@Test
fun testAdminAuthActivity_openedFromProfile_configurationChanged_checkHeadingSubHeadingIsPreserved() { // ktlint-disable max-line-length
launch<AdminAuthActivity>(
AdminAuthActivity.createAdminAuthActivityIntent(
context,
"12345",
internalProfileId,
-10710042,
AdminAuthEnum.PROFILE_ADD_PROFILE.value
)
).use {
onView(withId(R.id.admin_auth_heading_textview)).check(
matches(
withText(
context.resources.getString(
R.string.admin_auth_heading
)
)
)
)
onView(withId(R.id.admin_auth_sub_text))
.check(
matches(
withText(
context.resources.getString(
R.string.admin_auth_sub
)
)
)
)
onView(isRoot()).perform(orientationLandscape())
onView(withId(R.id.admin_auth_sub_text))
.check(
matches(
withText(
context.resources.getString(
R.string.admin_auth_sub
)
)
)
)
onView(withId(R.id.admin_auth_heading_textview)).check(
matches(
withText(
context.resources.getString(
R.string.admin_auth_heading
)
)
)
)
}
}
@Test
fun testAdminAuthActivity_inputText_configurationChanged_inputTextIsPreserved() {
launch<AdminAuthActivity>(
AdminAuthActivity.createAdminAuthActivityIntent(
context,
"12345",
internalProfileId,
-10710042,
AdminAuthEnum.PROFILE_ADMIN_CONTROLS.value
)
).use {
testCoroutineDispatchers.runCurrent()
onView(allOf(withId(R.id.input), isDescendantOfA(withId(R.id.admin_auth_input_pin)))).perform(
appendText("12345"),
closeSoftKeyboard()
)
onView(isRoot()).perform(orientationLandscape())
onView(allOf(withId(R.id.input), isDescendantOfA(withId(R.id.admin_auth_input_pin)))).check(
matches(
withText("12345")
)
)
}
}
@Test
fun testAdminAuthActivity_inputIncorrectPasswordLandscape_checkError() {
launch<AdminAuthActivity>(
AdminAuthActivity.createAdminAuthActivityIntent(
context,
"12345",
internalProfileId,
-10710042,
AdminAuthEnum.PROFILE_ADMIN_CONTROLS.value
)
).use {
testCoroutineDispatchers.runCurrent()
onView(allOf(withId(R.id.input), isDescendantOfA(withId(R.id.admin_auth_input_pin)))).perform(
appendText("12354"),
closeSoftKeyboard()
)
onView(withId(R.id.admin_auth_submit_button)).perform(click())
onView(
allOf(
withId(R.id.error_text),
isDescendantOfA(withId(R.id.admin_auth_input_pin))
)
).check(matches(withText(context.resources.getString(R.string.admin_auth_incorrect))))
onView(isRoot()).perform(orientationLandscape())
onView(
allOf(
withId(R.id.error_text),
isDescendantOfA(withId(R.id.admin_auth_input_pin))
)
).check(matches(withText(context.resources.getString(R.string.admin_auth_incorrect))))
}
}
// TODO(#962): Reenable once IME_ACTIONS work correctly on ProfileInputView.
@Ignore("IME_ACTIONS doesn't work properly in ProfileInputView")
@Test
fun testAdminAuthActivity_inputIncorrectPasswordLandscape_clickImeActionButton_checkError() {
launch<AdminAuthActivity>(
AdminAuthActivity.createAdminAuthActivityIntent(
context,
"12345",
internalProfileId,
-10710042,
AdminAuthEnum.PROFILE_ADMIN_CONTROLS.value
)
).use {
onView(allOf(withId(R.id.input), isDescendantOfA(withId(R.id.admin_auth_input_pin)))).perform(
typeText("12354"),
pressImeActionButton()
)
onView(
allOf(
withId(R.id.error_text),
isDescendantOfA(withId(R.id.admin_auth_input_pin))
)
).check(matches(withText(context.resources.getString(R.string.admin_auth_incorrect))))
onView(isRoot()).perform(orientationLandscape())
onView(
allOf(
withId(R.id.error_text),
isDescendantOfA(withId(R.id.admin_auth_input_pin))
)
).check(matches(withText(context.resources.getString(R.string.admin_auth_incorrect))))
}
}
// TODO(#1840): Introduce central utility file for appendText in Testing
/**
* Appends the specified text to a view. This is needed because Robolectric doesn't seem to
* properly input digits for text views using 'android:digits'. See
* https://github.com/robolectric/robolectric/issues/5110 for specifics.
*/
private fun appendText(text: String): ViewAction {
val typeTextViewAction = typeText(text)
return object : ViewAction {
override fun getDescription(): String = typeTextViewAction.description
override fun getConstraints(): Matcher<View> = typeTextViewAction.constraints
override fun perform(uiController: UiController?, view: View?) {
// Appending text only works on Robolectric, whereas Espresso needs to use typeText().
if (Build.FINGERPRINT.contains("robolectric", ignoreCase = true)) {
(view as? EditText)?.append(text)
testCoroutineDispatchers.runCurrent()
} else {
typeTextViewAction.perform(uiController, view)
}
}
}
}
// TODO(#59): Figure out a way to reuse modules instead of needing to re-declare them.
// TODO(#1675): Add NetworkModule once data module is migrated off of Moshi.
@Singleton
@Component(
modules = [
TestDispatcherModule::class, ApplicationModule::class,
LoggerModule::class, ContinueModule::class, FractionInputModule::class,
ItemSelectionInputModule::class, MultipleChoiceInputModule::class,
NumberWithUnitsRuleModule::class, NumericInputRuleModule::class, TextInputRuleModule::class,
DragDropSortInputModule::class, ImageClickInputModule::class, InteractionsModule::class,
GcsResourceModule::class, GlideImageLoaderModule::class, ImageParsingModule::class,
HtmlParserEntityTypeModule::class, QuestionModule::class, TestLogReportingModule::class,
TestAccessibilityModule::class, LogStorageModule::class, CachingTestModule::class,
PrimeTopicAssetsControllerModule::class, ExpirationMetaDataRetrieverModule::class,
ViewBindingShimModule::class, RatioInputModule::class,
ApplicationStartupListenerModule::class, LogUploadWorkerModule::class,
WorkManagerConfigurationModule::class, HintsAndSolutionConfigModule::class,
FirebaseLogUploaderModule::class
]
)
interface TestApplicationComponent : ApplicationComponent, ApplicationInjector {
@Component.Builder
interface Builder : ApplicationComponent.Builder
fun inject(adminAuthActivityTest: AdminAuthActivityTest)
}
class TestApplication : Application(), ActivityComponentFactory, ApplicationInjectorProvider {
private val component: TestApplicationComponent by lazy {
DaggerAdminAuthActivityTest_TestApplicationComponent.builder()
.setApplication(this)
.build() as TestApplicationComponent
}
fun inject(adminAuthActivityTest: AdminAuthActivityTest) {
component.inject(adminAuthActivityTest)
}
override fun createActivityComponent(activity: AppCompatActivity): ActivityComponent {
return component.getActivityComponentBuilderProvider().get().setActivity(activity).build()
}
override fun getApplicationInjector(): ApplicationInjector = component
}
}
| 0
|
Kotlin
|
0
| 0
|
cb45e456caf79d5612ca4c28d8ef3bf1c25e5965
| 21,204
|
oppia-android
|
Apache License 2.0
|
src/commonMain/kotlin/clipper2/engine/LocalMinima.kt
|
urbanistic
| 617,653,496
| false
|
{"Kotlin": 1342096}
|
@file:Suppress("unused")
package clipper2.engine
import clipper2.core.PathType
class LocalMinima {
var vertex: ClipperBase.Vertex? = null
var polytype: PathType? = PathType.Subject
var isOpen = false
constructor()
constructor(vertex: ClipperBase.Vertex?, polytype: PathType?) : this(vertex, polytype, false)
constructor(vertex: ClipperBase.Vertex?, polytype: PathType?, isOpen: Boolean) {
this.vertex = vertex
this.polytype = polytype
this.isOpen = isOpen
}
fun opEquals(o: LocalMinima): Boolean {
return vertex === o.vertex
}
fun opNotEquals(o: LocalMinima): Boolean {
return vertex !== o.vertex
}
override fun equals(other: Any?): Boolean {
if (other is LocalMinima) {
return this === other
}
return false
}
override fun hashCode(): Int {
return vertex.hashCode()
}
protected fun clone(): LocalMinima {
val varCopy = LocalMinima()
varCopy.vertex = vertex
varCopy.polytype = polytype
varCopy.isOpen = isOpen
return varCopy
}
}
| 1
|
Kotlin
|
0
| 2
|
b9186b0e42396f88ff6b01b73d58bcb68ffeeaf0
| 1,129
|
clipper2-kotlin
|
Boost Software License 1.0
|
charset/src/com/fleeksoft/charset/cs/utf/UTF_32Coder.kt
|
fleeksoft
| 874,918,183
| false
|
{"Kotlin": 8845941}
|
package com.fleeksoft.charset.cs.utf
import com.fleeksoft.charset.Charset
import com.fleeksoft.charset.CharsetDecoder
import com.fleeksoft.charset.CharsetEncoder
import com.fleeksoft.charset.CoderResult
import com.fleeksoft.charset.io.ByteBuffer
import com.fleeksoft.charset.io.CharBuffer
import com.fleeksoft.charset.lang.Character
object UTF_32Coder {
internal const val BOM_BIG: Int = 0xFEFF
internal const val BOM_LITTLE: Int = -0x20000
internal const val NONE: Int = 0
internal const val BIG: Int = 1
internal const val LITTLE: Int = 2
open class Decoder(cs: Charset, private val expectedBO: Int) : CharsetDecoder(cs, 0.25f, 1.0f) {
private var currentBO: Int
init {
this.currentBO = NONE
}
private fun getCP(src: ByteBuffer): Int {
return if (currentBO == BIG)
(((src.get() and 0xff) shl 24) or
((src.get() and 0xff) shl 16) or
((src.get() and 0xff) shl 8) or
(src.get() and 0xff))
else
((src.get() and 0xff) or
((src.get() and 0xff) shl 8) or
((src.get() and 0xff) shl 16) or
((src.get() and 0xff) shl 24))
}
override fun decodeLoop(src: ByteBuffer, dst: CharBuffer): CoderResult {
if (src.remaining() < 4) return CoderResult.UNDERFLOW
var mark: Int = src.position()
var cp: Int
try {
if (currentBO == NONE) {
cp = ((src.get() and 0xff) shl 24) or
((src.get() and 0xff) shl 16) or
((src.get() and 0xff) shl 8) or
(src.get() and 0xff)
if (cp == BOM_BIG && expectedBO != LITTLE) {
currentBO = BIG
mark += 4
} else if (cp == BOM_LITTLE && expectedBO != BIG) {
currentBO = LITTLE
mark += 4
} else {
if (expectedBO == NONE) currentBO = BIG
else currentBO = expectedBO
src.position(mark)
}
}
while (src.remaining() >= 4) {
cp = getCP(src)
if (Character.isBmpCodePoint(cp)) {
if (!dst.hasRemaining()) return CoderResult.OVERFLOW
mark += 4
dst.put(cp.toChar())
} else if (Character.isValidCodePoint(cp)) {
if (dst.remaining() < 2) return CoderResult.OVERFLOW
mark += 4
dst.put(Character.highSurrogate(cp))
dst.put(Character.lowSurrogate(cp))
} else {
return CoderResult.malformedForLength(4)
}
}
return CoderResult.UNDERFLOW
} finally {
src.position(mark)
}
}
override fun implReset() {
currentBO = NONE
}
}
open class Encoder(cs: Charset, private val byteOrder: Int, doBOM: Boolean) : CharsetEncoder(
cs, 4.0f,
if (doBOM) 8.0f else 4.0f,
if (byteOrder == BIG)
byteArrayOf(0.toByte(), 0.toByte(), 0xff.toByte(), 0xfd.toByte())
else
byteArrayOf(0xfd.toByte(), 0xff.toByte(), 0.toByte(), 0.toByte())
) {
private var doBOM = false
private var doneBOM = true
protected fun put(cp: Int, dst: ByteBuffer) {
if (byteOrder == BIG) {
dst.put((cp shr 24).toByte())
dst.put((cp shr 16).toByte())
dst.put((cp shr 8).toByte())
dst.put(cp.toByte())
} else {
dst.put(cp.toByte())
dst.put((cp shr 8).toByte())
dst.put((cp shr 16).toByte())
dst.put((cp shr 24).toByte())
}
}
init {
this.doBOM = doBOM
this.doneBOM = !doBOM
}
override fun encodeLoop(src: CharBuffer, dst: ByteBuffer): CoderResult {
var mark: Int = src.position()
if (!doneBOM && src.hasRemaining()) {
if (dst.remaining() < 4) return CoderResult.OVERFLOW
put(BOM_BIG, dst)
doneBOM = true
}
try {
while (src.hasRemaining()) {
val c: Char = src.get()
if (!Character.isSurrogate(c)) {
if (dst.remaining() < 4) return CoderResult.OVERFLOW
mark++
put(c.code, dst)
} else if (Character.isHighSurrogate(c)) {
if (!src.hasRemaining()) return CoderResult.UNDERFLOW
val low: Char = src.get()
if (Character.isLowSurrogate(low)) {
if (dst.remaining() < 4) return CoderResult.OVERFLOW
mark += 2
put(Character.toCodePoint(c, low), dst)
} else {
return CoderResult.malformedForLength(1)
}
} else {
// assert Character.isLowSurrogate(c);
return CoderResult.malformedForLength(1)
}
}
return CoderResult.UNDERFLOW
} finally {
src.position(mark)
}
}
override fun implReset() {
doneBOM = !doBOM
}
}
}
| 1
|
Kotlin
|
0
| 2
|
a16af685a558ad177749c12d7840a7b67aece66c
| 5,859
|
charset
|
MIT License
|
base/src/main/kotlin/browser/webviewTag/PointerLockPermissionRequest.kt
|
DATL4G
| 372,873,797
| false
| null |
@file:JsModule("webextension-polyfill")
@file:JsQualifier("webviewTag")
package browser.webviewTag
/**
* The type of <code>request</code> object which accompanies a <code>pointerLock</code> <a
* href="#event-permissionrequest">permissionrequest</a></code> DOM event.
*/
public external interface PointerLockPermissionRequest {
/**
* Whether or not pointer lock was requested as a result of a user input gesture.
*/
public var userGesture: Boolean
/**
* Whether or not the requesting frame was the most recent client to hold pointer lock.
*/
public var lastUnlockedBySelf: Boolean
/**
* The URL of the frame requesting pointer lock.
*/
public var url: String
/**
* Allow the permission request.
*/
public fun allow(): Nothing
/**
* Deny the permission request. This is the default behavior if <code>allow</code> is not called.
*/
public fun deny(): Nothing
}
| 0
|
Kotlin
|
1
| 37
|
ab2a825dd8dd8eb704278f52c603dbdd898d1875
| 917
|
Kromex
|
Apache License 2.0
|
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/ChannelObject.kt
|
Danilo-Araujo-Silva
| 271,904,885
| false
| null |
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/** \!RowBox[{"ChannelObject", "[", StyleBox[ represents a channel specified by a given URL. \!RowBox[{"ChannelObject", "[", represents a channel at an absolute path on the channel broker.
*```` * RowBox[{RowBox[{"\"mqtts", ":"}], "//", StyleBox["…", "TR"],"\""}], AutoSpacing -> False], "]"}] * ChannelObject["relpath"] represents a channel for the currently authenticated user at a relative path. * StyleBox[ *
* * ChannelObject["id : path"] represents a channel for the user with the specified Wolfram ID at the given path. * Usage: StyleBox[RowBox[{"\"/","abspath\""}], "TI", ShowStringCharacters->True], AutoSpacing -> False], "]"}] * ChannelBase :> $ChannelBase
* Name: ChannelObject * * ChannelBrokerAction -> None
* * ChannelPreSendFunction -> None
* Full name: System`ChannelObject * HandlerFunctions -> None
* * Initialization -> None
* ChannelObject[] gives a new anonymous channel specification. * MetaInformation -> {}
* * Method -> Automatic
* NotificationFunction -> Inherited
* Permissions -> Automatic
* Options: URLRendering -> Automatic
*
* Protected
* Attributes: ReadProtected
*
* local: paclet:ref/ChannelObject
* Documentation: web: http://reference.wolfram.com/language/ref/ChannelObject.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun channelObject(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("ChannelObject", arguments.toMutableList(), options)
}
| 2
|
Kotlin
|
0
| 3
|
4fcf68af14f55b8634132d34f61dae8bb2ee2942
| 16,244
|
mathemagika
|
Apache License 2.0
|
BottomNavigationAndHttpRequest/app/src/main/java/com/example/basicapp/Constants.kt
|
BennyZhang-Canviz
| 255,919,665
| false
| null |
package com.example.basicapp
const val DATABASE_NAME = "plant.db"
| 0
|
Kotlin
|
0
| 0
|
55ae049d5c880b67251e40cf658c4535d52cd017
| 66
|
Android
|
Apache License 2.0
|
app/src/main/java/avanger/co/id/MainActivity.kt
|
ridohendrawan
| 356,727,545
| false
| null |
package avanger.co.id
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import avanger.co.id.databinding.ActivityMainBinding
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
class MainActivity : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
// Firebase Authentication
auth = Firebase.auth
binding.lupapassword.setOnClickListener { openLupaPassword() }
binding.login.setOnClickListener {
val username = binding.username.text.toString()
val password = binding.password.text.toString()
val usernameSuffix = getString(R.string.firebase_email)
val firebaseUsername = "$username@$usernameSuffix"
if (username.isNotBlank() && password.isNotBlank()) {
// Tampilkan progress bar.
binding.formProgress.visibility = View.VISIBLE
// Ketika seorang user berhasil login, tidak perlu apa-apa lagi karena sudah berada di Firebase.
// Segi security, sangat aman - Firebase does all of the abstractions.
auth.signInWithEmailAndPassword(firebaseUsername, password).addOnCompleteListener { task ->
binding.formProgress.visibility = View.GONE
if (task.isSuccessful) {
openMainMenu()
} else {
Snackbar.make(binding.activityMainView, getString(R.string.main_fail_auth), Snackbar.LENGTH_LONG).show()
}
}.addOnFailureListener {
Snackbar.make(binding.activityMainView, getString(R.string.main_fail), Snackbar.LENGTH_LONG).show()
}
} else {
Snackbar.make(binding.activityMainView, getString(R.string.required_fields), Snackbar.LENGTH_LONG).show()
}
}
}
private fun openLupaPassword() {
val intent = Intent(this@MainActivity, LupaPassword::class.java)
startActivity(intent)
}
private fun openMainMenu() {
val intent = Intent(this@MainActivity, MainMenu::class.java)
startActivity(intent)
finish()
}
}
| 0
|
Kotlin
|
1
| 1
|
0d8f5851b34f2fc86a9e5a94b54691a3324438d1
| 2,624
|
Kompleks
|
MIT License
|
kotlin_spark/src/test/java/com/sleazyweasel/eboshi/ClientDataAccessTest.kt
|
botandrose
| 43,263,644
| false
| null |
package com.sleazyweasel.eboshi
import org.junit.Assert.assertEquals
import org.junit.Test
import org.mockito.Mockito.`when`
import org.mockito.Mockito.verify
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.jdbc.core.simple.SimpleJdbcInsert
import java.util.*
class ClientDataAccessTest {
val jdbcTemplate = mock(JdbcTemplate::class)
@Test
fun testAllClients() {
val clientMap = mapOf("id" to 1, "name" to "John")
`when`(jdbcTemplate.queryForList("select * from clients")).thenReturn(listOf(clientMap))
val testClass = ClientDataAccess(jdbcTemplate)
val results = testClass.allClients()
assertEquals(listOf(Client(clientMap)), results)
}
@Test
fun testInsert() {
val clientMap = linkedMapOf("name" to "John", "address" to "1121 NE Glisan", "created_at" to Date(), "updated_at" to Date())
val client = Client(clientMap)
val jdbcInsert = mock(SimpleJdbcInsert::class)
val testClass = ClientDataAccess(jdbcTemplate, jdbcInsert)
`when`(jdbcInsert.executeAndReturnKey(clientMap)).thenReturn(4)
val result = testClass.insert(client)
assertEquals(Client(clientMap.plus("id" to 4)), result)
}
@Test
fun testDelete() {
val testClass = ClientDataAccess(jdbcTemplate)
testClass.delete(555)
verify(jdbcTemplate).update("delete from clients where id = ?", 555)
}
}
| 15
|
Kotlin
|
5
| 1
|
43b6143487a461a2025de286e2b6d915b3d20f4e
| 1,450
|
eboshi_api_shootout
|
MIT License
|
src/main/kotlin/dev/minn/jda/ktx/interactions/components/textinput.kt
|
MinnDevelopment
| 259,655,475
| false
| null |
/*
* Copyright 2020 <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
*
* 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 dev.minn.jda.ktx.interactions.components
import net.dv8tion.jda.api.interactions.components.text.TextInput
import net.dv8tion.jda.api.interactions.components.text.TextInputStyle
/**
* Defaults used for text inputs.
*
* These can be changed but keep in mind they will apply globally.
*/
object TextInputDefaults {
var required = true
var value: String? = null
var placeholder: String? = null
var requiredLength: IntRange? = null
}
/**
* Creates a new [InlineTextInput] builder for the provided parameters.
*
* This is a kotlin idiomatic replacement for [TextInput.Builder]
*
* Uses [TextInputDefaults] for default values.
*
* @param[id] The component id used for events
* @param[label] The label to display above the input box
* @param[style] The [TextInputStyle]
* @param[required] Whether the user must provide an input for this field (uses requiredLength)
* @param[value] The prepopulated value for the input (this will be shown as typed input that the user can replace or keep)
* @param[placeholder] The placeholder text to display when the user hasn't typed anything yet
* @param[requiredLength] The minimum and maximum length of the input (Example: 2..1024)
* @param[builder] Inline builder function
*
* @return [InlineTextInput]
*
* @see TextInput
*/
inline fun TextInputBuilder(
id: String,
label: String,
style: TextInputStyle,
required: Boolean = TextInputDefaults.required,
value: String? = TextInputDefaults.value,
placeholder: String? = TextInputDefaults.placeholder,
requiredLength: IntRange? = TextInputDefaults.requiredLength,
builder: InlineTextInput.() -> Unit = {}
): InlineTextInput = InlineTextInput(TextInput.create(id, label, style)).also {
it.required = required
it.value = value
it.placeholder = placeholder
requiredLength?.apply {
it.requiredLength = this
}
it.builder()
}
/**
* Creates a new [TextInput] for the provided parameters.
*
* Uses [TextInputDefaults] for default values.
*
* @param[id] The component id used for events
* @param[label] The label to display above the input box
* @param[style] The [TextInputStyle]
* @param[required] Whether the user must provide an input for this field (uses requiredRange)
* @param[value] The prepopulated value for the input (this will be shown as typed input that the user can replace or keep)
* @param[placeholder] The placeholder text to display when the user hasn't typed anything yet
* @param[requiredLength] The minimum and maximum length of the input (Example: 2..1024)
* @param[builder] Inline builder function
*
* @return [TextInput]
*
* @see TextInputBuilder
*/
inline fun TextInput(
id: String,
label: String,
style: TextInputStyle,
required: Boolean = TextInputDefaults.required,
value: String? = TextInputDefaults.value,
placeholder: String? = TextInputDefaults.placeholder,
requiredLength: IntRange? = TextInputDefaults.requiredLength,
builder: InlineTextInput.() -> Unit = {}
) = TextInputBuilder(id, label, style, required, value, placeholder, requiredLength, builder).build()
/**
* Kotlin idiomatic builder for [TextInput]
*/
class InlineTextInput(val builder: TextInput.Builder) {
/** Delegated property for [TextInput.Builder.setId] */
var id: String
get() = builder.id
set(value) {
builder.id = value
}
/** Delegated property for [TextInput.Builder.setLabel] */
var label: String
get() = builder.label
set(value) {
builder.label = value
}
/** Delegated property for [TextInput.Builder.setStyle] */
var style: TextInputStyle
get() = builder.style
set(value) {
builder.style = value
}
/** Delegated property for [TextInput.Builder.setRequired] */
var required: Boolean
get() = builder.isRequired
set(value) {
builder.isRequired = value
}
/** Delegated property for [TextInput.Builder.setValue] */
var value: String?
get() = builder.value
set(value) {
builder.value = value
}
/** Delegated property for [TextInput.Builder.setPlaceholder] */
var placeholder: String?
get() = builder.placeholder
set(value) {
builder.placeholder = value
}
/** Delegated property for [TextInput.Builder.setRequiredRange] */
var requiredLength: IntRange
get() = builder.minLength..builder.maxLength
set(value) {
builder.setRequiredRange(value.first, value.last)
}
/**
* Builds the [TextInput]
*
* @return [TextInput]
*/
fun build() = builder.build()
}
| 1
|
Kotlin
|
10
| 93
|
9370cb13cc64646862e6f885959d67eb4b157e4a
| 5,384
|
jda-ktx
|
Apache License 2.0
|
ui/src/main/kotlin/org/jetbrains/jewel/ui/component/IconActionButton.kt
|
JetBrains
| 440,164,967
| false
|
{"Kotlin": 1615027, "Java": 22778, "Shell": 361}
|
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.jewel.ui.component
import androidx.compose.foundation.TooltipPlacement
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.dp
import org.jetbrains.jewel.foundation.theme.JewelTheme
import org.jetbrains.jewel.ui.component.styling.IconButtonStyle
import org.jetbrains.jewel.ui.component.styling.TooltipStyle
import org.jetbrains.jewel.ui.icon.IconKey
import org.jetbrains.jewel.ui.painter.PainterHint
import org.jetbrains.jewel.ui.theme.iconButtonStyle
import org.jetbrains.jewel.ui.theme.tooltipStyle
@Composable
public fun IconActionButton(
key: IconKey,
contentDescription: String?,
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
focusable: Boolean = true,
style: IconButtonStyle = JewelTheme.iconButtonStyle,
colorFilter: ColorFilter? = null,
hint: PainterHint? = null,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
iconClass: Class<*> = key::class.java,
) {
BaseIconActionButton(
key = key,
contentDescription = contentDescription,
iconClass = iconClass,
enabled = enabled,
focusable = focusable,
style = style,
interactionSource = interactionSource,
modifier = modifier,
colorFilter = colorFilter,
hint = hint,
onClick = onClick,
)
}
@Composable
public fun IconActionButton(
key: IconKey,
contentDescription: String?,
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
focusable: Boolean = true,
style: IconButtonStyle = JewelTheme.iconButtonStyle,
colorFilter: ColorFilter? = null,
hint: PainterHint? = null,
tooltipStyle: TooltipStyle = JewelTheme.tooltipStyle,
tooltipModifier: Modifier = Modifier,
tooltipPlacement: TooltipPlacement = FixedCursorPoint(offset = DpOffset(0.dp, 16.dp)),
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
iconClass: Class<*> = key::class.java,
tooltip: @Composable () -> Unit,
) {
Tooltip(tooltip, style = tooltipStyle, modifier = tooltipModifier, tooltipPlacement = tooltipPlacement) {
BaseIconActionButton(
key = key,
contentDescription = contentDescription,
iconClass = iconClass,
enabled = enabled,
focusable = focusable,
style = style,
interactionSource = interactionSource,
modifier = modifier,
colorFilter = colorFilter,
hint = hint,
onClick = onClick,
)
}
}
@Composable
public fun IconActionButton(
key: IconKey,
contentDescription: String?,
hints: Array<PainterHint>,
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
focusable: Boolean = true,
style: IconButtonStyle = JewelTheme.iconButtonStyle,
colorFilter: ColorFilter? = null,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
iconClass: Class<*> = key::class.java,
) {
CoreIconActionButton(
key = key,
contentDescription = contentDescription,
iconClass = iconClass,
enabled = enabled,
focusable = focusable,
style = style,
interactionSource = interactionSource,
modifier = modifier,
colorFilter = colorFilter,
hints = hints,
onClick = onClick,
)
}
@Composable
public fun IconActionButton(
key: IconKey,
contentDescription: String?,
hints: Array<PainterHint>,
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
focusable: Boolean = true,
style: IconButtonStyle = JewelTheme.iconButtonStyle,
colorFilter: ColorFilter? = null,
tooltipStyle: TooltipStyle = JewelTheme.tooltipStyle,
tooltipModifier: Modifier = Modifier,
tooltipPlacement: TooltipPlacement = FixedCursorPoint(offset = DpOffset(0.dp, 16.dp)),
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
iconClass: Class<*> = key::class.java,
tooltip: @Composable () -> Unit,
) {
Tooltip(tooltip, style = tooltipStyle, modifier = tooltipModifier, tooltipPlacement = tooltipPlacement) {
CoreIconActionButton(
key = key,
modifier = modifier,
contentDescription = contentDescription,
iconClass = iconClass,
enabled = enabled,
focusable = focusable,
style = style,
interactionSource = interactionSource,
colorFilter = colorFilter,
hints = hints,
onClick = onClick,
)
}
}
@Composable
private fun BaseIconActionButton(
key: IconKey,
contentDescription: String?,
iconClass: Class<*>,
enabled: Boolean,
focusable: Boolean,
style: IconButtonStyle,
interactionSource: MutableInteractionSource,
modifier: Modifier,
colorFilter: ColorFilter?,
hint: PainterHint?,
onClick: () -> Unit,
) {
if (hint != null) {
CoreIconActionButton(
key = key,
contentDescription = contentDescription,
iconClass = iconClass,
enabled = enabled,
focusable = focusable,
style = style,
interactionSource = interactionSource,
modifier = modifier,
colorFilter = colorFilter,
hint = hint,
onClick = onClick,
)
} else {
CoreIconActionButton(
key = key,
contentDescription = contentDescription,
iconClass = iconClass,
enabled = enabled,
focusable = focusable,
style = style,
interactionSource = interactionSource,
modifier = modifier,
colorFilter = colorFilter,
hints = emptyArray(),
onClick = onClick,
)
}
}
@Composable
private fun CoreIconActionButton(
key: IconKey,
contentDescription: String?,
iconClass: Class<*>,
enabled: Boolean,
focusable: Boolean,
style: IconButtonStyle,
interactionSource: MutableInteractionSource,
modifier: Modifier,
colorFilter: ColorFilter?,
hints: Array<PainterHint>,
onClick: () -> Unit,
) {
IconButton(onClick, modifier, enabled, focusable, style, interactionSource) {
Icon(key, contentDescription, iconClass = iconClass, colorFilter = colorFilter, hints = hints)
}
}
@Composable
private fun CoreIconActionButton(
key: IconKey,
contentDescription: String?,
iconClass: Class<*>,
enabled: Boolean,
focusable: Boolean,
style: IconButtonStyle,
interactionSource: MutableInteractionSource,
modifier: Modifier,
colorFilter: ColorFilter?,
hint: PainterHint,
onClick: () -> Unit,
) {
IconButton(onClick, modifier, enabled, focusable, style, interactionSource) {
Icon(key, contentDescription, iconClass = iconClass, hint = hint, colorFilter = colorFilter)
}
}
@Composable
public fun IconActionButton(
painter: Painter,
contentDescription: String?,
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
focusable: Boolean = true,
style: IconButtonStyle = JewelTheme.iconButtonStyle,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
) {
CoreIconActionButton(painter, contentDescription, enabled, focusable, style, interactionSource, modifier, onClick)
}
@Composable
public fun IconActionButton(
painter: Painter,
contentDescription: String?,
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
focusable: Boolean = true,
style: IconButtonStyle = JewelTheme.iconButtonStyle,
tooltipStyle: TooltipStyle = JewelTheme.tooltipStyle,
tooltipModifier: Modifier = Modifier,
tooltipPlacement: TooltipPlacement = FixedCursorPoint(offset = DpOffset(0.dp, 16.dp)),
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
tooltip: @Composable () -> Unit,
) {
Tooltip(tooltip, style = tooltipStyle, modifier = tooltipModifier, tooltipPlacement = tooltipPlacement) {
CoreIconActionButton(
painter = painter,
modifier = modifier,
contentDescription = contentDescription,
enabled = enabled,
focusable = focusable,
style = style,
interactionSource = interactionSource,
onClick = onClick,
)
}
}
@Composable
private fun CoreIconActionButton(
painter: Painter,
contentDescription: String?,
enabled: Boolean,
focusable: Boolean,
style: IconButtonStyle,
interactionSource: MutableInteractionSource,
modifier: Modifier = Modifier,
onClick: () -> Unit,
) {
IconButton(onClick, modifier, enabled, focusable, style, interactionSource) { Icon(painter, contentDescription) }
}
| 94
|
Kotlin
|
39
| 722
|
e0e6f1b4a46ca1c27ce1c13524ff11f75a2bed54
| 9,950
|
jewel
|
Apache License 2.0
|
airbyte-workload-launcher/src/test/kotlin/config/EnvVarConfigBeanFactoryTest.kt
|
lj-michale
| 719,837,726
| true
|
{"Java Properties": 2, "Gradle Kotlin DSL": 49, "Shell": 54, "Markdown": 70, "Batchfile": 1, "Kotlin": 422, "Dockerfile": 25, "Java": 1531, "INI": 7, "JavaScript": 20, "TypeScript": 428, "HTML": 5, "CSS": 3, "Python": 7, "SQL": 14}
|
/*
* Copyright (c) 2023 Airbyte, Inc., all rights reserved.
*/
package config
import io.airbyte.workers.process.Metadata.AWS_ACCESS_KEY_ID
import io.airbyte.workers.process.Metadata.AWS_SECRET_ACCESS_KEY
import io.airbyte.workload.launcher.config.EnvVarConfigBeanFactory
import io.airbyte.workload.launcher.config.EnvVarConfigBeanFactory.Companion.AWS_ASSUME_ROLE_ACCESS_KEY_ID_ENV_VAR
import io.airbyte.workload.launcher.config.EnvVarConfigBeanFactory.Companion.AWS_ASSUME_ROLE_SECRET_ACCESS_KEY_ENV_VAR
import io.airbyte.workload.launcher.config.EnvVarConfigBeanFactory.Companion.WORKLOAD_API_BEARER_TOKEN_ENV_VAR
import io.fabric8.kubernetes.api.model.EnvVarSource
import io.fabric8.kubernetes.api.model.SecretKeySelector
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Test
class EnvVarConfigBeanFactoryTest {
companion object {
const val AWS_ASSUMED_ROLE_ACCESS_KEY = "accessKey"
const val AWS_ASSUMED_ROLE_SECRET_KEY = "secretKey"
const val AWS_ASSUMED_ROLE_SECRET_NAME = "secretName"
const val BEARER_TOKEN_SECRET_NAME = "secretName"
const val BEARER_TOKEN_SECRET_KEY = "secretKey"
const val ENV_VAR_NAME1 = "envVarName1"
const val ENV_VAR_VALUE1 = "envVarValue1"
const val ENV_VAR_NAME2 = "envVarName2"
const val ENV_VAR_VALUE2 = "envVarValue2"
const val ENV_VAR_NAME3 = "envVarName3"
}
@Test
fun `workload api secret env creation`() {
val factory = EnvVarConfigBeanFactory()
val envMap =
factory.workloadApiSecretEnv(
BEARER_TOKEN_SECRET_NAME,
BEARER_TOKEN_SECRET_KEY,
)
assertEquals(1, envMap.size)
val envVarSource = envMap[WORKLOAD_API_BEARER_TOKEN_ENV_VAR]
val secretKeyRef = envVarSource!!.secretKeyRef
assertEquals(BEARER_TOKEN_SECRET_NAME, secretKeyRef.name)
assertEquals(BEARER_TOKEN_SECRET_KEY, secretKeyRef.key)
}
@Test
fun `orchestrator aws assumed role secret creation`() {
val factory = EnvVarConfigBeanFactory()
val envMap =
factory.orchestratorAwsAssumedRoleSecretEnv(
AWS_ASSUMED_ROLE_ACCESS_KEY,
AWS_ASSUMED_ROLE_SECRET_KEY,
AWS_ASSUMED_ROLE_SECRET_NAME,
)
assertEquals(2, envMap.size)
val awsAccessKey = envMap[AWS_ASSUME_ROLE_ACCESS_KEY_ID_ENV_VAR]
val awsAccessKeySecretRef = awsAccessKey!!.secretKeyRef
assertEquals(AWS_ASSUMED_ROLE_SECRET_NAME, awsAccessKeySecretRef.name)
assertEquals(AWS_ASSUMED_ROLE_ACCESS_KEY, awsAccessKeySecretRef.key)
val awsSecretKey = envMap[AWS_ASSUME_ROLE_SECRET_ACCESS_KEY_ENV_VAR]
val awsSecretKeyRef = awsSecretKey!!.secretKeyRef
assertEquals(AWS_ASSUMED_ROLE_SECRET_NAME, awsSecretKeyRef.name)
assertEquals(AWS_ASSUMED_ROLE_SECRET_KEY, awsSecretKeyRef.key)
}
@Test
fun `workload api secret env creation with blank names`() {
val factory = EnvVarConfigBeanFactory()
val envMap =
factory.workloadApiSecretEnv(
"",
BEARER_TOKEN_SECRET_KEY,
)
assertEquals(0, envMap.size)
}
@Test
fun `orchestrator aws assumed role secret creation with blank names`() {
val factory = EnvVarConfigBeanFactory()
val envMap =
factory.orchestratorAwsAssumedRoleSecretEnv(
AWS_ASSUMED_ROLE_ACCESS_KEY,
AWS_ASSUMED_ROLE_SECRET_KEY,
"",
)
assertEquals(0, envMap.size)
}
@Test
fun `connector aws assumed role secret creation`() {
val factory = EnvVarConfigBeanFactory()
val envList =
factory.connectorAwsAssumedRoleSecretEnv(
AWS_ASSUMED_ROLE_ACCESS_KEY,
AWS_ASSUMED_ROLE_SECRET_KEY,
AWS_ASSUMED_ROLE_SECRET_NAME,
)
val awsAccessKey = envList.find { it.name == AWS_ACCESS_KEY_ID }
val awsAccessKeySecretRef = awsAccessKey!!.valueFrom.secretKeyRef
assertEquals(AWS_ASSUMED_ROLE_SECRET_NAME, awsAccessKeySecretRef.name)
assertEquals(AWS_ASSUMED_ROLE_ACCESS_KEY, awsAccessKeySecretRef.key)
val awsSecretKey = envList.find { it.name == AWS_SECRET_ACCESS_KEY }
val awsSecretKeyRef = awsSecretKey!!.valueFrom.secretKeyRef
assertEquals(AWS_ASSUMED_ROLE_SECRET_NAME, awsSecretKeyRef.name)
assertEquals(AWS_ASSUMED_ROLE_SECRET_KEY, awsSecretKeyRef.key)
}
@Test
fun `test final env vars contain secret env vars an non-secret env vars`() {
val factory = EnvVarConfigBeanFactory()
val orchestratorEnvVars =
factory.orchestratorEnvVars(
mapOf(Pair(ENV_VAR_NAME1, ENV_VAR_VALUE1), Pair(ENV_VAR_NAME2, ENV_VAR_VALUE2)),
mapOf(Pair(ENV_VAR_NAME3, EnvVarSource(null, null, null, SecretKeySelector(BEARER_TOKEN_SECRET_KEY, BEARER_TOKEN_SECRET_NAME, false)))),
).sortedBy { it.name }
assertEquals(ENV_VAR_NAME1, orchestratorEnvVars[0].name)
assertEquals(ENV_VAR_VALUE1, orchestratorEnvVars[0].value)
assertEquals(ENV_VAR_NAME2, orchestratorEnvVars[1].name)
assertEquals(ENV_VAR_VALUE2, orchestratorEnvVars[1].value)
assertEquals(ENV_VAR_NAME3, orchestratorEnvVars[2].name)
assertNull(orchestratorEnvVars[2].value)
assertEquals(BEARER_TOKEN_SECRET_NAME, orchestratorEnvVars[2].valueFrom.secretKeyRef.name)
assertEquals(BEARER_TOKEN_SECRET_KEY, orchestratorEnvVars[2].valueFrom.secretKeyRef.key)
}
}
| 0
|
Java
|
0
| 1
|
e554884ac0c8a22e423f470213de3d4cfa384938
| 5,265
|
airbyte-platform
|
MIT License
|
play-basic/src/main/kotlin/org/example/basic/demos/parents/AOPKotlinParentKotlinDemo.kt
|
dowenliu-xyz
| 808,693,582
| false
|
{"Gradle Kotlin DSL": 13, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 2, "Java": 399, "YAML": 4, "INI": 6, "Kotlin": 354, "Java Properties": 1}
|
package org.example.basic.demos.parents
import org.example.basic.biz.Greeting
import org.example.basic.biz.Greeting.doFallback
import org.springframework.stereotype.Component
@Suppress("unused")
@Component
class AOPKotlinParentKotlinDemo : AOPKotlinParentForKotlin() {
override fun greeting(name: String?): String {
return Greeting.doGreeting(name)
}
private fun fallback(name: String, e: Throwable): String {
return doFallback(name, e)
}
}
| 0
|
Java
|
0
| 1
|
8b6df6f693a0c7efa25c3a7d634823d7b8ec4915
| 476
|
sentinel-plays
|
Apache License 2.0
|
src/main/kotlin/kilobyte/common/instruction/DecompiledInstruction.kt
|
leksak
| 72,142,371
| false
|
{"Java": 116992, "Kotlin": 104979, "TeX": 66969, "Assembly": 23400, "Makefile": 915, "Shell": 686}
|
package kilobyte.common.instruction
import kilobyte.common.machinecode.MachineCode
import kilobyte.common.machinecode.opcode
import java.util.*
sealed class DecompiledInstruction {
class Valid(val instruction: Instruction) : DecompiledInstruction()
class PartiallyValid(val instruction: Instruction, val errors: List<String>) : DecompiledInstruction()
class UnknownInstruction(val machineCode: MachineCode) : DecompiledInstruction()
override fun toString(): String {
when (this) {
is Valid -> return instruction.toString()
is PartiallyValid -> {
val sj = StringJoiner("\", \"", "[\"", "\"]")
errors.map { sj.add(it) }
return instruction.toString() + " error(s)=" + sj.toString()
}
is UnknownInstruction -> {
val op = machineCode.opcode()
val sj = StringJoiner(" ")
sj.add("Unknown instruction: \"$machineCode\". opcode=\"$op\".")
val eitherFormatOrString = Instruction.formatFrom(op)
if (eitherFormatOrString.isLeft) {
// We were able to infer a format so we can decompose the machineCode
val actualFormat = eitherFormatOrString.left().get()
// The EXIT-instruction is not a real instruction, so check that
// we are dealing with some other kind of format.
if (actualFormat != Format.EXIT) {
sj.add("Format=\"${actualFormat.name}\".")
sj.add("Decomposition=${actualFormat.decompose(machineCode)}")
}
} else {
sj.add(eitherFormatOrString.right().get())
}
return sj.toString()
}
}
}
fun asInstruction(): Instruction {
when (this) { is Valid -> return instruction }
println(this)
throw IllegalStateException("\"asInstruction\" called on a non-valid instruction")
}
fun isValid(): Boolean {
when (this) { is Valid -> return true
}
return false
}
fun isUnknown(): Boolean {
when (this) { is UnknownInstruction -> return true
}
return false
}
fun isPartiallyValid(): Boolean {
when (this) { is PartiallyValid -> return true
}
return false
}
fun errors(): List<String> {
when (this) { is PartiallyValid -> return errors
}
return emptyList()
}
companion object {
@JvmStatic fun from(machineCode: MachineCode): DecompiledInstruction = Instruction.decompile(machineCode)
@JvmStatic fun printAllInstructions() {
Instruction.primordialSet.forEach(::println)
}
}
}
| 1
| null |
1
| 1
|
ab25af00f96c0c4dc28e997385e1df436bd6ffb1
| 2,498
|
kilobyte
|
MIT License
|
app/src/main/java/deakin/gopher/guardian/model/RegistrationStatusMessage.kt
|
ShreyasNair067
| 714,569,652
| true
|
{"Java Properties": 2, "Gradle": 3, "Shell": 1, "Markdown": 8, "Batchfile": 1, "Text": 1, "Ignore List": 2, "XML": 129, "YAML": 1, "Proguard": 1, "JSON": 1, "Kotlin": 55, "Java": 33}
|
package deakin.gopher.guardian.model
import deakin.gopher.guardian.R
sealed class RegistrationStatusMessage(val message: Int) {
data object Success : RegistrationStatusMessage(R.string.registration_success)
data object Failure : RegistrationStatusMessage(R.string.registration_failure)
}
| 1
|
Java
|
0
| 0
|
a381ece710e42cda48eec74929c2baea411e777e
| 298
|
Project-Guardian
|
MIT License
|
sample-kotlin/src/main/java/com/your_company/ui_bindings_kotlin_sample/CouponsActivity.kt
|
nearit
| 102,874,273
| false
|
{"Java": 673856, "Kotlin": 29259, "Shell": 4056}
|
package com.your_company.ui_bindings_kotlin_sample
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import com.nearit.ui_bindings.NearITUIBindings
import com.your_company.ui_bindings_kotlin_sample.factories.CouponFactory
/**
* @author <NAME>
*/
class CouponsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_coupons)
}
/* COUPON LIST EXAMPLES */
fun onDefaultClicked(view: View) {
// start an activity that shows a list of REAL coupons, with jagged borders
startActivity(NearITUIBindings.getInstance(this@CouponsActivity)
.couponListIntentBuilder()
.setTitle("My coupon list")
.jaggedBorders()
.build())
}
fun onValidClicked(view: View) {
startActivity(NearITUIBindings.getInstance(this@CouponsActivity)
.couponListIntentBuilder()
.validCoupons()
.build())
}
fun onInactiveClicked(view: View) {
startActivity(NearITUIBindings.getInstance(this@CouponsActivity)
.couponListIntentBuilder()
.inactiveCoupons()
.build())
}
fun onExpiredClicked(view: View) {
startActivity(NearITUIBindings.getInstance(this@CouponsActivity)
.couponListIntentBuilder()
.expiredCoupons()
.build())
}
fun onRedeemedClicked(view: View) {
startActivity(NearITUIBindings.getInstance(this@CouponsActivity)
.couponListIntentBuilder()
.redeemedCoupons()
.build())
}
fun onValidAndInactiveClicked(view: View) {
startActivity(NearITUIBindings.getInstance(this@CouponsActivity)
.couponListIntentBuilder()
.validCoupons()
.inactiveCoupons()
.build())
}
fun onValidAndExpiredClicked(view: View) {
startActivity(NearITUIBindings.getInstance(this@CouponsActivity)
.couponListIntentBuilder()
.validCoupons()
.expiredCoupons()
.build())
}
fun onValidAndRedeemedClicked(view: View) {
startActivity(NearITUIBindings.getInstance(this@CouponsActivity)
.couponListIntentBuilder()
.validCoupons()
.redeemedCoupons()
.build())
}
fun onInactiveAndExpiredClicked(view: View) {
startActivity(NearITUIBindings.getInstance(this@CouponsActivity)
.couponListIntentBuilder()
.inactiveCoupons()
.expiredCoupons()
.build())
}
fun onInactiveAndRedeemedClicked(view: View) {
startActivity(NearITUIBindings.getInstance(this@CouponsActivity)
.couponListIntentBuilder()
.inactiveCoupons()
.redeemedCoupons()
.build())
}
fun onExpiredAndRedeemedClicked(view: View) {
startActivity(NearITUIBindings.getInstance(this@CouponsActivity)
.couponListIntentBuilder()
.expiredCoupons()
.redeemedCoupons()
.build())
}
fun onPlainCouponListClicked(view: View) {
// start a plain activity that shows the fragment fullscreen
// please check it
startActivity(Intent(this@CouponsActivity, CouponListPlainActivity::class.java))
}
/* COUPON DETAIL EXAMPLES */
fun onValidDetailClicked(view: View) {
// In a real scenario the coupon is provided by the NearIT SDK
val validCoupon = CouponFactory.getValidCoupon()
startActivity(
// Basic example with a valid coupon
NearITUIBindings.getInstance(this@CouponsActivity)
.couponIntentBuilder(validCoupon)
.build())
}
fun onInactiveDetailClicked(view: View) {
// In a real scenario the coupon is provided by the NearIT SDK
val validCoupon = CouponFactory.getInactiveCoupon()
startActivity(
// Basic example with a not yet valid coupon
NearITUIBindings.getInstance(this@CouponsActivity)
.couponIntentBuilder(validCoupon)
.build())
}
fun onExpiredDetailClicked(view: View) {
val expiredCoupon = CouponFactory.getExpiredCoupon()
startActivity(
// Basic example with an expired coupon
// + enable tap outside the dialog to close it
NearITUIBindings.getInstance(this@CouponsActivity)
.couponIntentBuilder(expiredCoupon)
.enableTapOutsideToClose()
.build())
}
fun onCustomIconDetailClicked(view: View) {
// In a real scenario the coupon is provided by the NearIT SDK
val validCoupon = CouponFactory.getValidCoupon()
startActivity(
// Change the default icon placeholder
NearITUIBindings.getInstance(this@CouponsActivity)
.couponIntentBuilder(validCoupon)
.setIconPlaceholderResourceId(R.drawable.my_custom_placeholder)
.build())
}
fun onPlainCouponClicked(view: View) {
// start a plain activity that shows the fragment fullscreen
// please check it
startActivity(Intent(this@CouponsActivity, CouponPlainActivity::class.java))
}
}
| 1
| null |
1
| 1
|
5267e8e63e186ee8fc71ba7eaed1e014ec1446a9
| 5,736
|
Android-UI-Bindings
|
MIT License
|
Sample/src/main/kotlin/com/heroslender/hmf/sample/menu/TestMenu.kt
|
heroslender
| 341,310,824
| false
| null |
package com.heroslender.hmf.sample.menu
import com.heroslender.hmf.bukkit.BaseMenu
import com.heroslender.hmf.bukkit.MenuOptions
import com.heroslender.hmf.bukkit.manager.BukkitMenuManager
import com.heroslender.hmf.bukkit.map.Color
import com.heroslender.hmf.bukkit.modifiers.clickable
import com.heroslender.hmf.bukkit.privateFor
import com.heroslender.hmf.core.Preview
import com.heroslender.hmf.core.mutableStateOf
import com.heroslender.hmf.core.ui.Alignment
import com.heroslender.hmf.core.ui.Composable
import com.heroslender.hmf.core.ui.components.*
import com.heroslender.hmf.core.ui.modifier.Modifier
import com.heroslender.hmf.core.ui.modifier.modifiers.*
import com.heroslender.hmf.core.ui.withState
import com.heroslender.hmf.sample.menu.components.ButtonBackgroundColors
import com.heroslender.hmf.sample.menu.components.Text
import com.heroslender.hmf.sample.menu.components.TextButton
import org.bukkit.entity.Player
@Preview(
name = "Preview 1",
width = 512,
height = 512,
)
fun Composable.menuPreview() {
val counter = mutableStateOf(0)
Column(
modifier = Modifier.fillSize().background(Color.BLUE_3)
) {
Header()
Row(
modifier = Modifier
.padding(5, 3)
) {
TextButton("Increment") {
counter.value++
}
TextButton("Decrement", modifier = Modifier.padding(left = 5)) {
counter.value--
}
}
val count = withState(counter)
Text("Counter: $count", modifier = Modifier.padding(left = 5))
}
}
@Preview(
name = "Menu 2",
width = 512,
height = 380,
)
fun Composable.menuPreview2() {
val counter = mutableStateOf(0)
Column(
modifier = Modifier.fillSize().background(Color.GREEN_12)
) {
Header()
Row(
modifier = Modifier
.padding(5, 3)
) {
TextButton("Increment") {
counter.value++
}
TextButton("Decrement", modifier = Modifier.padding(left = 5)) {
counter.value--
}
}
val count = withState(counter)
Text("Counter: $count", modifier = Modifier.padding(left = 5))
}
}
@Preview
fun Composable.defaultP() {
val counter = mutableStateOf(0)
Column(
modifier = Modifier.fillSize().background(Color.GREEN_12)
) {
Header()
Row(
modifier = Modifier
.padding(5, 3)
) {
TextButton("Increment") {
counter.value++
}
TextButton("Decrement", modifier = Modifier.padding(left = 5)) {
counter.value--
}
}
val count = withState(counter)
Text("Counter: $count", modifier = Modifier.padding(left = 5))
}
}
class TestMenu(player: Player, manager: BukkitMenuManager) : BaseMenu(
opts = MenuOptions.builder {
width = 4
height = 3
privateFor(player)
},
manager = manager,
) {
private val counter = mutableStateOf(0)
override fun Composable.getUi() {
Column(
modifier = Modifier.fillSize().background(Color.BLUE_3)
) {
Header()
Row(
modifier = Modifier
.padding(5, 3)
) {
TextButton("Increment") {
counter.value++
}
TextButton("Decrement", modifier = Modifier.padding(left = 5)) {
counter.value--
}
}
val count = withState(counter)
Text("Counter: $count", modifier = Modifier.padding(left = 5))
}
}
}
private fun Composable.Header() {
Row(
modifier = Modifier
.maxSize(height = 44)
.fillWidth()
) {
HeaderButton("Home")
HeaderButton("Map")
HeaderButton("Guild")
HeaderButton("Settings")
HeaderCloseButton()
}
}
private fun Composable.HeaderButton(text: String) {
TextButton(
text = text,
modifier = Modifier
.weight(1)
.fillHeight(),
padding = paddingValuesOf(5),
colors = ButtonBackgroundColors(
main = Color.CYAN_3,
light = Color.CYAN_1,
dark = Color.CYAN_4,
)
)
}
private fun Composable.HeaderCloseButton() {
Box(
alignment = Alignment.Center,
modifier = Modifier
.border(Color.CYAN_6)
.background(Color.CYAN_3)
.clickable {
// Close the menu
renderContext.menu.close()
}
.padding(5)
) {
Image("icons/32/Close.png")
}
}
| 2
|
Kotlin
|
4
| 57
|
f205b21bb7024899bd3ca14a44fb6f30493bce7f
| 4,810
|
menu-framework
|
MIT License
|
plantor/app/src/main/java/com/mobapps/plantor/data/Plant.kt
|
btu-mobapps
| 334,424,370
| false
| null |
package com.mobapps.plantor.data
import com.google.firebase.database.IgnoreExtraProperties
@IgnoreExtraProperties
data class Plant(
var name: String? = null,
var imgUri: String? = null,
var lastWaterDate: String? = null,
var waterHour: String? = null,
var waterDays: String? = null
)
| 0
|
Kotlin
|
0
| 0
|
1ea0c224c68acb739ce154b4f1367a9c2d953706
| 305
|
plantor
|
MIT License
|
sample/src/release/kotlin/com/redmadrobot/debug_sample/debug_data/DebugServersProvider.kt
|
RedMadRobot
| 516,407,635
| false
| null |
package com.redmadrobot.debug_sample.debug_data
import com.redmadrobot.debug_panel_core.data.DebugDataProvider
import com.redmadrobot.servers_plugin.data.model.DebugServer
class DebugServersProvider : DebugDataProvider<List<DebugServer>> {
override fun provideData(): List<DebugServer> {
return emptyList()
}
}
| 0
|
Kotlin
|
0
| 5
|
34d38784098552aed469b8accf0dd237cb9f77b7
| 330
|
debug-panel-android
|
MIT License
|
content/common/src/main/kotlin/br/com/mrocigno/bigbrother/common/utils/_booleanUtils.kt
|
mrocigno
| 574,215,368
| false
|
{"Kotlin": 343969, "HTML": 7133}
|
package br.com.mrocigno.bigbrother.common.utils
fun Boolean.ifTrue(block: () -> Unit) =
if (this) block() else Unit
fun Boolean.ifFalse(block: () -> Unit) =
if (!this) block() else Unit
| 0
|
Kotlin
|
0
| 4
|
8deac7d4cf1b1395e5c23dc3b788266beb1fa19b
| 195
|
big-brother
|
Apache License 2.0
|
adaptive-kotlin-plugin/test/hu/simplexion/adaptive/kotlin/runners/runtimeClassPath.kt
|
spxbhuhb
| 788,711,010
| false
|
{"Kotlin": 1463989, "Java": 17672, "HTML": 2540, "JavaScript": 970}
|
/*
* Copyright © 2020-2024, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package hu.simplexion.adaptive.kotlin.runners
import java.io.File
import java.nio.file.Files
import java.nio.file.Paths
import kotlin.io.path.getLastModifiedTime
import kotlin.io.path.name
import kotlin.streams.toList
fun runtimeClassPath() : List<File> {
val result = mutableListOf<File>()
Files.list(Paths.get("../adaptive-core/build/libs/"))
.filter { it.name.startsWith("adaptive-core-jvm-") && it.name.endsWith(".jar") }
.forEach { result += it.toFile() }
check(result.isNotEmpty()) { "Runtime JAR does not exist. Please run :adaptive-core:build" }
val latest = result.maxBy { it.lastModified() }
result.clear()
result += latest
result += File(System.getProperty("adaptive.kotlin.test.kotlinx-coroutines-core"))
result += File(System.getProperty("adaptive.kotlin.test.kotlinx-datetime"))
return result
}
| 13
|
Kotlin
|
0
| 0
|
2f97d34731f19163e62da8c578802c2915a48572
| 1,003
|
adaptive
|
Apache License 2.0
|
nuget-tests/src/jetbrains/buildServer/nuget/tests/integration/feed/server/NuGetServiceFeedUploadMetadataHandlerTest.kt
|
JetBrains
| 2,046,399
| false
|
{"Gradle": 9, "INI": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 2, "Text": 14, "Markdown": 1, "JSON": 4, "XML": 140, "Java": 427, "Kotlin": 122, "Microsoft Visual Studio Solution": 20, "C#": 113, "Java Server Pages": 18, "CSS": 1, "JavaScript": 1, "SVG": 1}
|
package jetbrains.buildServer.nuget.tests.integration.feed.server
import jetbrains.buildServer.nuget.feed.server.controllers.serviceFeed.upload.NuGetServiceFeedUploadHandlerContext
import jetbrains.buildServer.nuget.feed.server.controllers.serviceFeed.upload.NuGetServiceFeedUploadMetadataHandlerImpl
import jetbrains.buildServer.nuget.feed.server.index.NuGetFeedData
import jetbrains.buildServer.nuget.feed.server.index.impl.NuGetBuildFeedsProvider
import jetbrains.buildServer.serverSide.RunningBuildEx
import jetbrains.buildServer.serverSide.metadata.MetadataStorage
import org.jmock.Expectations
import org.jmock.Mockery
import org.springframework.web.multipart.MultipartHttpServletRequest
import org.testng.annotations.BeforeMethod
import org.testng.annotations.DataProvider
import org.testng.annotations.Test
import javax.servlet.http.HttpServletResponse
@Test
class NuGetServiceFeedUploadMetadataHandlerTest {
private var myIsPersonal: Boolean = false
private var myBuildId: Long = 123L
private lateinit var myFeedsProvider: NuGetBuildFeedsProvider
private lateinit var myContext: NuGetServiceFeedUploadHandlerContext
private lateinit var myResponse: HttpServletResponse
private lateinit var myBuild: RunningBuildEx
private lateinit var myRequest: MultipartHttpServletRequest
private lateinit var myStorage: MetadataStorage
private lateinit var m : Mockery
@DataProvider
fun targetFeedsProvider(): Array<Array<out Any?>> {
return arrayOf(
arrayOf(setOf<NuGetFeedData>()),
arrayOf(setOf<NuGetFeedData>(NuGetFeedData("projectId1", "feedId1"))),
arrayOf(setOf<NuGetFeedData>(
NuGetFeedData("projectId1", "feedId1"),
NuGetFeedData("projectId2", "feedId2")
))
)
}
@BeforeMethod
fun setupMethod() {
m = Mockery()
myStorage = m.mock(MetadataStorage::class.java)
myRequest = m.mock(MultipartHttpServletRequest::class.java)
myResponse = m.mock(HttpServletResponse::class.javaObjectType)
myBuild = m.mock(RunningBuildEx::class.java)
myContext = m.mock(NuGetServiceFeedUploadHandlerContext::class.java)
myFeedsProvider = m.mock(NuGetBuildFeedsProvider::class.java)
myBuildId = 123L
myIsPersonal = true
m.checking(object: Expectations() {
init {
allowing(myBuild).buildId
will(returnValue(myBuildId))
allowing(myBuild).buildNumber
will(returnValue("Build Number"))
allowing(myBuild).buildTypeExternalId
will(returnValue("Build TYpe External Id"))
allowing(myBuild).isPersonal
will(returnValue(myIsPersonal))
}
})
}
@Test(dataProvider = "targetFeedsProvider")
fun shouldHandleMetadata(targetFeeds : Set<NuGetFeedData>) {
// Given
val instance = createInstance()
val key = "packageId"
val metadata = HashMap<String, String>()
m.checking(object: Expectations() {
init {
oneOf(myFeedsProvider).getFeeds(myBuild)
will(returnValue(targetFeeds))
for(feed in targetFeeds) {
oneOf(myStorage).addBuildEntry(myBuildId, "nuget.${feed.projectId}.${feed.feedId}", key, metadata, !myIsPersonal)
}
}
})
// When
instance.handleMetadata(myRequest , myResponse, myContext, myBuild, key, metadata)
// Then
m.assertIsSatisfied()
}
private fun createInstance() : NuGetServiceFeedUploadMetadataHandlerImpl {
return NuGetServiceFeedUploadMetadataHandlerImpl(myStorage, myFeedsProvider)
}
}
| 13
|
Java
|
11
| 43
|
a5d36942395a56bc6a124805b4f76c620aeddfb5
| 3,820
|
teamcity-nuget-support
|
Apache License 2.0
|
app/src/main/java/com/bth/reciperadar/presentation/viewmodels/CuisineViewModel.kt
|
BryanAafjes
| 718,555,578
| false
|
{"Kotlin": 52345}
|
package com.bth.reciperadar.presentation.viewmodels
import com.bth.reciperadar.domain.models.Cuisine
data class CuisineViewModel (
var id: String,
var name: String,
var description: String?,
)
fun CuisineViewModel.toDomain(): Cuisine {
return Cuisine(
id = this.id,
name = this.name,
description = this.description
)
}
fun Cuisine.toViewModel(): CuisineViewModel {
return CuisineViewModel(
id = this.id,
name = this.name,
description = this.description
)
}
| 0
|
Kotlin
|
0
| 0
|
396474807f3d6499aceb1d55fbd7361f86d312f7
| 536
|
RecipeRadar
|
MIT License
|
src/test/kotlin/org/ktapi/db/MigrationTest.kt
|
ktapi
| 561,554,216
| false
| null |
package org.ktapi.db
import io.kotlintest.shouldBe
import io.kotlintest.specs.StringSpec
import org.ktapi.db.Database.Type
import org.ktapi.db.Database.param
import org.ktapi.db.Database.result
import java.io.File
class MigrationTest : StringSpec({
"create sql migration" {
val root = File("src/test")
val sqlMigration = Migration.create(
rootDir = root,
name = "setup",
isKotlin = false,
repeatable = false,
baseline = false,
undo = null
)
val kotlinMigration = Migration.create(
rootDir = root,
name = "setup",
isKotlin = true,
repeatable = false,
baseline = false,
undo = null
)
sqlMigration.exists() shouldBe true
sqlMigration.delete()
kotlinMigration.exists() shouldBe true
kotlinMigration.delete()
}
"run migrations" {
Database.execute("drop table if exists something_else")
Database.execute("drop table if exists something")
Database.execute("drop table if exists flyway_schema_history")
Migration.run()
val results =
Database.query("select name from something where id = ?", param(1), result("name", Type.String))
results.size shouldBe 1
results.first().string("name") shouldBe "FirstValue"
}
})
| 0
|
Kotlin
|
0
| 0
|
9a035f1a340c3a2cfc5036e2e9c2e1e0af26a758
| 1,410
|
ktapi
|
Apache License 2.0
|
src/domain/TransactionStatus.kt
|
jurabek
| 241,881,120
| false
|
{"Kotlin": 54913}
|
package domain
enum class TransactionStatus(val value: Int) {
COMPLETED(1),
FAILED(2)
}
| 0
|
Kotlin
|
0
| 2
|
e930978815b49549015278b8d36f68481ade94f6
| 96
|
money-transfer
|
MIT License
|
persistance/src/main/java/com/linhtetko/persistance/databases/Schema.kt
|
lin-htet-ko
| 726,358,254
| false
|
{"Kotlin": 95925, "CMake": 1249, "C++": 502}
|
package com.linhtetko.persistance.databases
object Schema {
const val DB_NAME = "efficient_app.db"
const val DB_VERSION = 1
object Table {
const val TB_WEATHER = "weathers"
}
}
| 0
|
Kotlin
|
0
| 0
|
dea33ddf60850d8e3ec8fc6d121cb161ea65bd1a
| 205
|
efficient_weather_app
|
Apache License 2.0
|
avro-kotlin/src/test/kotlin/model/FloatTypeTest.kt
|
toolisticon
| 493,962,736
| false
|
{"Kotlin": 346114, "Java": 1511}
|
package io.toolisticon.kotlin.avro.model
import io.toolisticon.kotlin.avro.builder.AvroBuilder.primitiveSchema
import io.toolisticon.kotlin.avro.model.SchemaType.FLOAT
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
internal class FloatTypeTest {
@Test
fun `floatType with simple jsonString`() {
val json = primitiveSchema(FLOAT).json
assertThat(json.value).isEqualTo(
"""
{
"type" : "float"
}
""".trimIndent()
)
}
}
| 11
|
Kotlin
|
0
| 4
|
6e0c6a42d02f2e4d6e89d3975fd80fd658f9bea0
| 505
|
avro-kotlin
|
Apache License 2.0
|
app/src/test/java/com/saintmarina/alphatraining/ExampleUnitTest.kt
|
saintmarina
| 421,152,743
| false
| null |
package com.saintmarina.alphatraining
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
val result = 2+2
assertEquals(4, result)
}
}
| 0
|
Kotlin
|
0
| 3
|
519ecc329aaba7c5deff5eb473e57c8c0ccfa2d1
| 381
|
neurofit
|
MIT License
|
src/main/kotlin/org/smart/home/simulator/entities/smartMeter/FlowDirection.kt
|
NLCProject
| 494,882,867
| false
| null |
package org.smart.home.simulator.entities.smartMeter
import org.isc.utils.annotations.GenerateTsModel
import org.isc.utils.annotations.I18nKeys
/**
* Power flow direction
*/
@I18nKeys
@GenerateTsModel
enum class FlowDirection {
/**
* Power is imported and bought.
*/
Import,
/**
* Power is exported and sold.
*/
Export
}
| 0
|
Kotlin
|
0
| 0
|
ea4e3c44fcca642ca8ade4c0498a1cdd6c9ba440
| 363
|
SmartHomeSimulator
|
The Unlicense
|
app/src/main/java/com/nikol412/artroom/ui/overview/OverviewViewModel.kt
|
nikol412
| 360,528,593
| false
| null |
package com.nikol412.artroom.ui.overview
import androidx.lifecycle.ViewModel
class OverviewViewModel : ViewModel() {
// TODO: Implement the ViewModel
}
| 0
|
Kotlin
|
0
| 0
|
6578884cc4a81e6ca5912930625056583bc61b44
| 157
|
ArtRoom
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.