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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
features/main/src/main/java/com/zigis/paleontologas/features/main/stories/home/HomeView.kt
|
edgar-zigis
| 240,962,785 | false |
{"Kotlin": 217487}
|
package com.zigis.paleontologas.features.main.stories.home
import android.content.Context
import android.view.LayoutInflater
import android.view.animation.AlphaAnimation
import android.view.animation.AnimationUtils
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.DividerItemDecoration.VERTICAL
import androidx.recyclerview.widget.LinearLayoutManager
import com.nightonke.boommenu.BoomMenuButton
import com.nightonke.boommenu.Eases.EaseType
import com.nightonke.boommenu.Types.BoomType
import com.nightonke.boommenu.Types.ButtonType
import com.nightonke.boommenu.Types.ClickEffectType
import com.nightonke.boommenu.Types.DimType
import com.nightonke.boommenu.Types.OrderType
import com.nightonke.boommenu.Types.PlaceType
import com.nightonke.boommenu.Util
import com.zigis.paleontologas.core.architecture.BaseView
import com.zigis.paleontologas.features.main.R
import com.zigis.paleontologas.features.main.databinding.FragmentHomeBinding
import com.zigis.paleontologas.features.main.stories.home.adapter.HomeListAdapter
class HomeView(
context: Context
) : BaseView<HomeViewState, FragmentHomeBinding>(context) {
var delegate: HomeViewDelegate? = null
override var binding: FragmentHomeBinding? = FragmentHomeBinding.inflate(LayoutInflater.from(context))
private val adapter = HomeListAdapter(emptyList()) {
delegate?.openPeriod(it)
}
init {
with(requireBinding()) {
val pieceColor = ContextCompat.getColor(context, R.color.colorMenuItem)
BoomMenuButton.Builder()
.addSubButton(context, R.drawable.menu_time_scale, intArrayOf(pieceColor, pieceColor), "")
.addSubButton(context, R.drawable.menu_quiz, intArrayOf(pieceColor, pieceColor), "")
.addSubButton(context, R.drawable.menu_language, intArrayOf(pieceColor, pieceColor), "")
.addSubButton(context, R.drawable.menu_about, intArrayOf(pieceColor, pieceColor), "")
.frames(80)
.duration(250)
.delay(100)
.showOrder(OrderType.RANDOM)
.hideOrder(OrderType.RANDOM)
.button(ButtonType.CIRCLE)
.boom(BoomType.LINE)
.place(PlaceType.CIRCLE_4_2)
.showMoveEase(EaseType.EaseOutBack)
.hideMoveEase(EaseType.EaseOutCirc)
.showScaleEase(EaseType.EaseOutBack)
.hideScaleType(EaseType.EaseOutCirc)
.rotateDegree(720)
.showRotateEase(EaseType.EaseOutBack)
.hideRotateType(EaseType.Linear)
.autoDismiss(true)
.cancelable(true)
.dim(DimType.DIM_6)
.clickEffect(ClickEffectType.RIPPLE)
.boomButtonShadow(Util.getInstance().dp2px(2f), Util.getInstance().dp2px(2f))
.subButtonsShadow(Util.getInstance().dp2px(2f), Util.getInstance().dp2px(2f))
.animator(null)
.onSubButtonClick { index ->
when (index) {
1 -> delegate?.openQuiz()
2 -> delegate?.openLanguages()
3 -> delegate?.openAbout()
}
}
.init(menuButton)
periodList.adapter = adapter
periodList.layoutManager = LinearLayoutManager(context)
periodList.addItemDecoration(DividerItemDecoration(context, VERTICAL).also {
it.setDrawable(ContextCompat.getDrawable(context, R.drawable.list_divider)!!)
})
}
addView(requireBinding().root)
}
override fun render(state: HomeViewState) = with(requireBinding()) {
if (state.animateLayoutChanges == true) {
periodList.layoutAnimation =
AnimationUtils.loadLayoutAnimation(context, R.anim.layout_animation_fall_down)
periodList.scheduleLayoutAnimation()
}
adapter.updateItems(items = state.periodItems)
if (state.animateLayoutChanges == true) {
AlphaAnimation(1f, 0f).apply {
duration = 500
fillAfter = true
logoImage.startAnimation(this)
}
}
}
}
| 0 |
Kotlin
|
16
| 123 |
5dbf133cc334c949d10a6caf37a8a698ecd873ca
| 4,348 |
Paleontologas
|
Apache License 2.0
|
library/src/commonMain/kotlin/com/lightningkite/kiteui/views/direct/Button.kt
|
lightningkite
| 778,386,343 | false |
{"Kotlin": 2224994, "Swift": 7449, "Ruby": 4925, "CSS": 4562, "HTML": 4084, "HCL": 880, "JavaScript": 302, "Objective-C": 142, "C": 104, "Shell": 49}
|
package com.lightningkite.kiteui.views.direct
import com.lightningkite.kiteui.models.Icon
import com.lightningkite.kiteui.reactive.Action
import com.lightningkite.kiteui.views.RContext
import com.lightningkite.kiteui.views.ViewDsl
import com.lightningkite.kiteui.views.RView
import com.lightningkite.kiteui.views.RViewWithAction
import kotlin.jvm.JvmInline
import kotlin.contracts.*
expect class Button(context: RContext) : RViewWithAction {
var enabled: Boolean
}
fun Button.onClick(label: String? = null, icon: Icon? = null, action: suspend ()->Unit) {
this.action = Action(label ?: "Press", icon ?: Icon.send, action = action)
}
| 3 |
Kotlin
|
0
| 2 |
58ee76ab3e8e7cab71e65a18c302367c6a641da5
| 644 |
kiteui
|
Apache License 2.0
|
debug-dings/src/main/kotlin/no/nav/dings/authentication/IdTokenAuthenticationProvider.kt
|
nais
| 381,605,449 | false | null |
package no.nav.dings.authentication
import com.auth0.jwt.interfaces.DecodedJWT
import com.auth0.jwt.interfaces.JWTVerifier
import io.ktor.application.ApplicationCall
import io.ktor.application.call
import io.ktor.auth.Authentication
import io.ktor.auth.AuthenticationFailedCause
import io.ktor.auth.AuthenticationPipeline
import io.ktor.auth.AuthenticationProvider
import io.ktor.auth.Principal
import io.ktor.auth.principal
import io.ktor.request.path
import io.ktor.response.respondRedirect
import mu.KotlinLogging
private val log = KotlinLogging.logger { }
class IdTokenAuthenticationProvider internal constructor(config: Configuration) : AuthenticationProvider(config) {
internal val cookieName = config.cookieName
internal val redirectUriCookieName = config.redirectUriCookieName
internal val verifier: ((String) -> JWTVerifier?) = config.verifier
internal val loginUrl: String = config.loginUrl
class Configuration internal constructor(name: String?) : AuthenticationProvider.Configuration(name) {
internal var cookieName: String = "id_token"
internal var redirectUriCookieName: String = "redirect_uri"
internal var loginUrl: String = "/oauth"
internal var verifier: ((String) -> JWTVerifier?) = { null }
internal fun build() = IdTokenAuthenticationProvider(this)
}
}
fun Authentication.Configuration.idToken(
name: String? = null,
configure: IdTokenAuthenticationProvider.Configuration.() -> Unit
) {
val provider = IdTokenAuthenticationProvider.Configuration(name).apply(configure).build()
val verifier = provider.verifier
provider.pipeline.intercept(AuthenticationPipeline.RequestAuthentication) { context ->
val idToken = call.request.cookies[provider.cookieName]
try {
if (idToken != null) {
val decodedJWT = verifier(idToken)?.verify(idToken)
if (decodedJWT != null) {
context.principal(IdTokenPrincipal(decodedJWT))
return@intercept
}
} else {
log.debug("no idtoken cookie found. ")
call.response.cookies.append(provider.redirectUriCookieName, call.request.path())
}
} catch (e: Throwable) {
val message = e.message ?: e.javaClass.simpleName
log.error("Token verification failed: {}", message)
}
context.challenge("JWTAuthKey", AuthenticationFailedCause.InvalidCredentials) {
call.respondRedirect(provider.loginUrl)
it.complete()
}
}
register(provider)
}
data class IdTokenPrincipal(val decodedJWT: DecodedJWT) : Principal
fun ApplicationCall.idTokenPrincipal(): IdTokenPrincipal? = this.principal()
| 13 |
Kotlin
|
0
| 5 |
99015c1f935be995388008b1f938c38daaf66bb8
| 2,764 |
examples
|
MIT License
|
Compose/app/src/main/java/top/chilfish/compose/ui/login/LoginActivity.kt
|
Chilfish
| 610,771,353 | false | null |
package top.chilfish.compose.ui.login
import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import top.chilfish.compose.BaseActivity
import top.chilfish.compose.ui.main.MainActivity
class LoginActivity : BaseActivity() {
private val loginViewModel by viewModels<LoginViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
LoginPage(viewModel = loginViewModel)
}
initEvent()
}
private fun initEvent() {
lifecycleScope.launch {
loginViewModel.loginState.collect {
when (it) {
LoginState.Success -> {
startActivity<MainActivity>()
finish()
}
}
}
}
}
}
| 0 |
Kotlin
|
0
| 0 |
e5b88162f8d3d305a3b8c144653e0bf062e70ae1
| 916 |
Android-demo
|
MIT License
|
app/src/main/java/com/nulltwenty/abnrepos/data/di/CoroutinesQualifiers.kt
|
noloman
| 554,399,113 | false |
{"Kotlin": 51252}
|
package com.nulltwenty.abnrepos.data.di
import javax.inject.Qualifier
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class DefaultCoroutineDispatcher
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class IoCoroutineDispatcher
| 1 |
Kotlin
|
0
| 1 |
109c16731210c92fe228395a062b339c270c4fd1
| 255 |
abnrepos
|
Apache License 2.0
|
src/main/kotlin/gdscript/completion/TypeCompletionContributor.kt
|
exigow
| 202,529,822 | false | null |
package gdscript.completion
import com.intellij.codeInsight.completion.CompletionContributor
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.elementType
import gdscript.completion.utils.LookupFactory
import gdscript.psi.ScriptElementTypes.*
import version.VersionService
class TypeCompletionContributor : CompletionContributor() {
override fun fillCompletionVariants(parameters: CompletionParameters, result: CompletionResultSet) {
val element = parameters.position
if (isInsideType(element) || isAfterTypeOperator(element))
result.caseInsensitive().addAllElements(collectLookups())
}
private fun isInsideType(element: PsiElement) =
element.parent.parent.elementType == TYPE
private fun isAfterTypeOperator(element: PsiElement) =
PsiTreeUtil.prevVisibleLeaf(element).elementType in listOf(IS, AS)
private fun collectLookups(): List<LookupElement> {
val api = VersionService.current()
val primitiveTypes = api.primitives.map { LookupFactory.createKeyword(it.name) }
val classTypes = api.classes.map { LookupFactory.createClass(it) }
return primitiveTypes + classTypes
}
}
| 25 |
Kotlin
|
9
| 98 |
44c934ed885fa733d5766cff359bc3335daab8a0
| 1,415 |
intellij-gdscript
|
MIT License
|
csstype-kotlin/src/jsMain/kotlin/web/cssom/AlignSelf.kt
|
karakum-team
| 393,199,102 | false | null |
// Automatically generated - do not modify!
@file:Suppress(
"NESTED_CLASS_IN_EXTERNAL_INTERFACE",
)
package web.cssom
import seskar.js.JsValue
import seskar.js.JsVirtual
@JsVirtual
sealed external interface AlignSelf {
companion object {
@JsValue("center")
val center: AlignSelf
@JsValue("end")
val end: AlignSelf
@JsValue("flex-end")
val flexEnd: AlignSelf
@JsValue("flex-start")
val flexStart: AlignSelf
@JsValue("self-end")
val selfEnd: AlignSelf
@JsValue("self-start")
val selfStart: AlignSelf
@JsValue("start")
val start: AlignSelf
@JsValue("baseline")
val baseline: AlignSelf
@JsValue("normal")
val normal: AlignSelf
@JsValue("stretch")
val stretch: AlignSelf
}
}
| 0 | null |
8
| 36 |
95b065622a9445caf058ad2581f4c91f9e2b0d91
| 855 |
types-kotlin
|
Apache License 2.0
|
app/src/main/java/com/jnj/vaccinetracker/sync/p2p/common/models/LoginStatus.kt
|
johnsonandjohnson
| 503,902,626 | false |
{"Kotlin": 1690434}
|
package com.jnj.vaccinetracker.sync.p2p.common.models
enum class LoginStatus {
AUTHENTICATED, UNAUTHENTICATED
}
| 2 |
Kotlin
|
1
| 1 |
3b9730f742e488543bed86f4dec6c67e477b1f15
| 117 |
vxnaid
|
Apache License 2.0
|
library/core-resource/src/nativeTest/kotlin/io/matthewnelson/kmp/tor/core/resource/resource_LoremIpsum_gz.kt
|
05nelsonm
| 734,754,834 | false |
{"Kotlin": 130206}
|
/*
* Copyright (c) 2023 Matthew Nelson
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
@file:Suppress("ClassName", "ConstPropertyName")
package io.matthewnelson.kmp.tor.common.core
// This is an automatically generated file.
// DO NOT MODIFY
import io.matthewnelson.kmp.tor.common.api.InternalKmpTorApi
@InternalKmpTorApi
internal object resource_LoremIpsum_gz: NativeResource(
version = 1,
name = "LoremIpsum.gz",
size = 3216L,
sha256 = "e5fa963f1980af1aacb8554763167670b8d68989cca0b4faf27053e5d2d8bb3b",
chunks = 1L,
) {
@Throws(IllegalStateException::class, IndexOutOfBoundsException::class)
override operator fun get(index: Long): Chunk = when (index) {
0L -> _0
else -> throw IndexOutOfBoundsException()
}.toChunk()
private const val _0 =
"""H4sICDhKd2UAA0xvcmVtSXBzdW0AtVrbjiO3EX2fr+AHEPMDeQrsBFjAXiQwkneq
xdEw6Iu2uyns5+fUnZKNBLDhB3tnNN1kserUqVNF/bTtdUntfvQlXbd529PRzlSW
euY0betRp7OefU/l2u7tmNp6S3Vu53v6YS9HWrc1ze3W55Iu7VLXa19yOts6tWtf
T36SnsnpqMu97ums89yP9/SPvdSj4olHO0tNtbdj2a5prtt7+nFb65Q+8O6Ryj71
nO57PRvsO+o1rX2dUsEmWBDG2q54dTp55c9y8CZp7vRJOrZ5blM7+7Wt/BY99QtW
+qj91spJm6Z2TXXfsN/cvvWypI/Sp3ahJ//dHmXBMncsCoPr8a3X9KhrXcsJA+cC
/9VTVpTDXOayXtupbpLT9Hkuy7Tt5INrb+JZ7HTKeY7tWuZ6pKnvB236I/yRPnGw
ve5Y6VH2BhP+049zS/VWz7SU722hJ/+JJ9miPt/7Wc6ayjT15ShrWujgeOTn0ncs
hy0fhT6RFciKkk785cSRKxw3HvDe50dby57T2i6f7Hh4+yyxShaHCXDG49373o/M
r8SWtJvsuNKz7+kLdrrh6W900rrDEaXfYMbbG5+dP/atFWEN7+wUawTnROwRT/H4
tk/tPf29H1OVaJJRGVH6bBO9WHu6fxaAaMf+dcoeenn92srynr6SYeljB8Ib/QTE
ihkfdV/gGOw75APcuu2XhpPDhVND7Opc9TEBOefG/rmtkwEuUGMwq2uDnQSQa7kT
3nDUC/wK/E0NfsOjnkzhsyKg6Wfarm2z1FrKSUvDKYguwmq78o/y/6wAgyUz/kPk
L32mvPKMN8cgH5ZyW0sALLywIIwTjKZPsdgEXjgj1O/pp9/LKJIq7BscgQIviCdr
1TDkY5gNB4RLCY2Z7G7kjWurp0HtX9g84a2EczE4n+EKWJ+N4ITlcC7ekl86yq2x
S3FgwSMfed4ueKU9EwtwK/CTLNn7uRNOwV4UjVYAQ3LNYLwxDNYjd9FpF0nU+vHB
yyL5jBf9YdhJpnr6/9D3cqFnnUKCfRSOA0f47lnpkg4slBh+yJxCgppA99LIGtAd
4tWK2aGrMIB7I6qpE+KBx8tx2FNjQZCEAzORKZWZKCP/bms7jrYIM1mN+CtiCxoz
PsuJUwYWWzkQGsiWbxTiEV/4PVM6aB2QE9HZIj8k583Lbpb6MDxHeaoIc1RUqRxc
3R7b3M878BWczfhXJrfktn/pIFl9Eb5hukPY2gcWIZ8O+w8Exo7+SgSAYFDgjG+Z
BSxxuUT60m40IRJYHXDopjPED1hYmUE0Db183PbyaNeC1eGkXvCTFStxYgSxK5dz
3t63o9e9qlzQ3/TvBBui7oTEmeE0PqpSoy2L+I1/5RQUJuRKwKXQDPoAxzCkC/6s
BHTf2yKsGCWdnefFhGNLptzhT65E5pIo/pZUzLdaNFDNNA3TB3Li4nU7apdi4Jd+
3BFSeKc6u9XvFjja2hAodCmFW/ZBsKTQ8KrCFWZoDsQqdbTrAFAyVkoAQVV0iuZK
HoA6pszSnq0dqYiqPeGQCW6IifAFVUtlEqIKLUZj6Pq+Om8gHIxEolnnNnYZ6TGG
9WiWYPs9/e1Epea6GtWIireoDUMoYDjzysYTsiDhgvjYlZK8ZTkJkhdJOZKq0R2M
IcBqERlEk4BU9QjeuFOOnU7GatJQuiestSDUG7tJMoQcSt7xXCNWFkd5CudBMqpG
6PjQTdFoh/o1yHIusKB2ZRNw5YKLYCh8yB/KAGPkDGXP2GANQocIw4otxKSoTgtl
isA02zQKt3GC5GsIH9/17Y25I+zX6qqShhPj0R51J3IUvWGqpEyak93otZPP8Zcn
CSA4sWiaWjE/yRsjLDwttKiY0MyD+Qq6F80jUjOipCr5pvnhRc9QaSa4qHl92cLM
BReuAuz7aYJZV8nGKCJgWAEL6lTseDcW9V4rO0lsj5QktaUh+915R4qzYds0knpf
VefoiEHWPjceigbX7p5CSmSUg9iOU1lZxvJ2qGr/swJI0VFZUO3UNaA49QuiyBWu
1L8ILJZorHjxKDuBNitdjFeLjC3q+EWUNMrckHIorSzor8qk1iaAD6jQvZCzdMhc
7bO9MTSmJlNJYYUmRgIIUwAoV2bTyhwe9cA0sIozL32A526Fxsr5GLmnTog1jOU6
57vJDNRNzVmj51GLLZ72mSus52KknPozS+E2zhUGxpMEd2pvNYGUR4l6QE+PsdEI
Qrm2iUoJQcs3dNoa0sO6IzhRaBWVyHXzoH4NEazKUoxGDMxZPWxFk5Q0c3o2U0Z6
WqXGcC/B+piPrCEIiCg45YSSorrYw8YwupSmo0szedjCYZTjAlCVG/FFqBak4NNg
hbdweTcB46ZdHXtZJADwFXCMoZFVDhRvwxpDBY+7ymEfKLexeGQk/zCD+1K5nxSi
EwR8Ajfb1DZsjyYTLyA6LD1gDh4hn4KKkONYZTugqTN/Bkaq9xMq57NBW5S6HTZT
MNcMWl0bB9diLzQWddkyW6vVKB9UU/ncgCW/KQWsTfCIuQUh+Kl9Nrb5Y2LYNYAg
GkVyALIOnpzhYNlxFqN1fyMPye8JFMckVWqpQ0MLntawCCf9wweTuvhlFWbQAs9Q
fnsj4mfGZsIbmi0YzRRG64cXvXIwGfy58PiqDakFSaqw6gg+ikIZofTaLkKYkzi/
yNyrZx8rqKExPlU9ORcVlXbfpOXg4ss64omUaR5yVWlhCSnKhDyaQ3ytXrutq/ZO
1JoTwQZFo0TiOh94n61zI5V5AiAdgzGiHSBP0zQmGd/SbBE5h1R4elY7w6vVfzVB
BIkqHZsypk/E55N0W6GaiXQ9qxH+cUbVUSUh1US4KAvdmu1SbocG/zpqsZhB5CEJ
qVAQZ5XwtLdnHE9B91PIymmTjGtTSPvwS04u43HJJz2otLQyZjJ+15y3rtY2Vl+b
ImYXjyt7/mix5PGZBCIaT4+URoilgu7LjtJdAsGrNN1StZ0uGDhBHtb16JTeeciy
ggmT0JxjTGjcpNJ/LEqEiCFleKi4jE2tDk20wkIWmwvVrVHRDbScaf4bH2rgc1v5
dZbp1wuaJC+dVDXJ1XwEIHgcFrS64EMTTmONvFRn+pNMCEbwaA9rZV71hmxTnkcv
qiE8eXnQYbmosuPtLUA/tJScHKRnJYNi8m9wGuJgU0OU+uzLU/Gq3HKAzaNntA5c
Sr05wZLJXyLq/C3Fpqf1pBOiFJx6MRsaO/nI/11EgDjatTkeUE0l+0mUewMoLqnf
ZcJjOk15whQFkYhXfNul2eBbtA9n07iHjJ5QabL3vTTafr6ggmttCkFZd/D9gU+s
VL/cdIipHKeMN9wMLM3onwI/7iCcChcvPJ6KJIDfq3VWa9UffkOXKFIiCsOA0Ga9
p0mBcXTNElEcFGzMxNujZxfvc35yXRBmMUFXtBV2AOeXi5+4sVAEUa2NCm4No4dM
x8qW3TKyG5PA2jKRS5JZTxFjGTRmo4z/Bii7+FQy1is6kd6WRgqIp2Y4aFv5lWYb
jlMp0VmZg+nZRQgekLG/NZPse7+O01GbTUmdFmW861mSn87F5pJnPdmwpbuWFKH1
dJM8qxoilPbPPmSKAOj8TLCoc0jHHFeyzC9E6ooMitRW42GJpmqQEEkNRnKJrogV
cNUmmi+mKYA2Zh2u+liqEfsbrQZoxQQyy+XUwNx/VNkPgyIlAhMNlNXjLfLbm1im
xGiZeSoon/s86+1jGOvDN76ZwIcmmcLZbr3PBLghJ5zkF+bi1JCWlTI3WgfDC2vp
4GyW0zIFDh89CRl9McfMv9vATORsSCcBdHjOtC8xMV9pmXkaXheQv5qcUf8m1cIu
2LRJEBcFuFic8SXA98jKHIhQAuLEtOx+e/vqDajRgMgiHubK+J/brN99GUtGDl7h
O18bmYUq+TObK7//Y3aV7mbo/uQql4eZ4/cjIn9f73KGO69hpMl3ZaddWMa4vcRI
hcndcU+I8RTO2oGugTYt7dloUlEQACEpI6N/J23hOce8hmCwmCaeMnWk2GbnGVaV
kiZ+i9mi1aN7egaKi7dhTctS6ja6+XNUjsG4v/4SQMzj2Ds9Cs+fCQmeAYuXKN+d
EbzwkI9AxkNxiekKpzat4DSg5bDYjUrwh1+wf5GSxF2c9PLZZ4v63ZdzvGkd7i6Z
tvlFEx8vX+uxMjtsNnwpRgInfEOSJN6LTs7uNnR4Jvk5XAHaAafhqpBYGlrOmyIq
BNxQcBMRdOtXwfkJFFJo/39jbfVcLrmFApm5X776xQ6S2YYuygb+FwmveBiXJgAA"""
}
| 1 |
Kotlin
|
0
| 0 |
e5a0604d6722f24a38f3d234cca57287521e4f67
| 5,683 |
kmp-tor-core
|
Apache License 2.0
|
app/src/main/java/host/stjin/anonaddy/ui/customviews/refreshlayout/RefreshLayoutAnimationView.kt
|
anonaddy
| 854,490,200 | false |
{"Kotlin": 1335623}
|
package host.stjin.anonaddy.ui.customviews.refreshlayout
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.util.TypedValue
import android.view.HapticFeedbackConstants
import android.view.View
import kotlin.math.min
class RefreshLayoutAnimationView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
var shouldRefreshOnRelease: Boolean = false
private var alreadyVibrated: Boolean = false
private var pullHeight: Int = 0
private var pullDelta: Int = 0
private var widthOffset: Float = 0.toFloat()
private var aniStatus = AnimatorStatus.PULL_DOWN
private var backPaint: Paint? = null
private var outPaint: Paint? = null
private var path: Path? = null
private var radius: Int = 0
private var localWidth: Int = 0
private var localHeight: Int = 0
private var isRefreshing = true
private var lastHeight: Int = 0
private val relHeight: Int get() = (spriDeta * (1 - relRatio)).toInt()
private var start1: Long = 0
private var stop: Long = 0
private var spriDeta: Int = 0
private val relRatio: Float
get() {
if (System.currentTimeMillis() >= stop) {
return 1f
}
val ratio = (System.currentTimeMillis() - start1) / REL_DRAG_DUR.toFloat()
return min(ratio, 1f)
}
private var onViewAniDone: OnViewAniDone? = null
internal enum class AnimatorStatus {
PULL_DOWN,
DRAG_DOWN,
REL_DRAG,
OUTER_CIR,
REFRESHING,
DONE;
override fun toString(): String = when (this) {
PULL_DOWN -> "pull down"
DRAG_DOWN -> "drag down"
REL_DRAG -> "release drag"
OUTER_CIR -> "outer circle"
REFRESHING -> "refreshing..."
DONE -> "done!"
}
}
init {
initView(context)
}
private fun initView(context: Context) {
pullHeight = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 10f,
context.resources.displayMetrics
)
.toInt()
pullDelta = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 70f,
context.resources.displayMetrics
)
.toInt()
widthOffset = 0.5f
backPaint = Paint()
backPaint!!.isAntiAlias = true
backPaint!!.style = Paint.Style.FILL
backPaint!!.color = -0x746f51
outPaint = Paint()
outPaint!!.isAntiAlias = true
outPaint!!.color = -0x1
outPaint!!.style = Paint.Style.STROKE
outPaint!!.strokeWidth = 5f
path = Path()
}
override fun onMeasure(
widthMeasureSpec: Int,
heightMeasureSpec: Int
) {
var tempHeightMeasureSpec = heightMeasureSpec
val height = MeasureSpec.getSize(tempHeightMeasureSpec)
if (height > pullDelta + pullHeight) {
tempHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
pullDelta + pullHeight,
MeasureSpec.getMode(tempHeightMeasureSpec)
)
}
super.onMeasure(widthMeasureSpec, tempHeightMeasureSpec)
}
override fun onLayout(
changed: Boolean,
left: Int,
top: Int,
right: Int,
bottom: Int
) {
super.onLayout(changed, left, top, right, bottom)
if (changed) {
radius = height / 6
localWidth = width
localHeight = height
when {
localHeight < pullHeight -> aniStatus = AnimatorStatus.PULL_DOWN
}
when {
aniStatus == AnimatorStatus.PULL_DOWN && localHeight >= pullHeight -> aniStatus =
AnimatorStatus.DRAG_DOWN
}
// If almost scrolled to the bottom, change status of shouldRefreshOnRelease
shouldRefreshOnRelease = localHeight >= pullDelta
if (localHeight >= pullDelta) {
if (!alreadyVibrated) {
this.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
alreadyVibrated = true
}
} else {
alreadyVibrated = false
}
}
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
when (aniStatus) {
AnimatorStatus.PULL_DOWN -> {
canvas.drawRect(0f, 0f, localWidth.toFloat(), localHeight.toFloat(), backPaint!!)
}
AnimatorStatus.REL_DRAG, AnimatorStatus.DRAG_DOWN -> {
drawDrag(canvas)
}
AnimatorStatus.OUTER_CIR -> {
invalidate()
}
AnimatorStatus.REFRESHING -> {
invalidate()
}
AnimatorStatus.DONE -> {
invalidate()
}
}
if (aniStatus == AnimatorStatus.REL_DRAG) {
val params = layoutParams
var height: Int
do {
height = relHeight
} while (height == lastHeight && relRatio != 1f)
lastHeight = height
params.height = pullHeight + height
requestLayout()
}
}
private fun drawDrag(canvas: Canvas) {
canvas.drawRect(0f, 0f, localWidth.toFloat(), pullHeight.toFloat(), backPaint!!)
path!!.reset()
path!!.moveTo(0f, pullHeight.toFloat())
path!!.quadTo(
widthOffset * localWidth, (pullHeight + (localHeight - pullHeight) * 2).toFloat(),
localWidth.toFloat(), pullHeight.toFloat()
)
canvas.drawPath(path!!, backPaint!!)
}
fun setRefreshing(isFresh: Boolean) {
isRefreshing = isFresh
}
fun releaseDrag() {
start1 = System.currentTimeMillis()
stop = start1 + REL_DRAG_DUR
aniStatus = AnimatorStatus.REL_DRAG
spriDeta = localHeight - pullHeight
requestLayout()
}
fun setOnViewAniDone(onViewAniDone: OnViewAniDone) {
this.onViewAniDone = onViewAniDone
}
interface OnViewAniDone {
fun viewAniDone()
}
fun setAniBackColor(color: Int) {
backPaint!!.color = color
}
fun setAniForeColor(color: Int) {
outPaint!!.color = color
setBackgroundColor(color)
}
companion object {
private const val REL_DRAG_DUR: Long = 100
}
}
| 0 |
Kotlin
|
0
| 3 |
ac5d5ee3d7ca14cf88711c1c92ec991fb1ce5ef3
| 6,630 |
addy-android
|
MIT License
|
tbs/src/main/java/com/hjhrq1991/library/tbs/WebViewJavascriptBridge.kt
|
angcyo
| 229,037,684 | false |
{"Kotlin": 3430781, "JavaScript": 5542, "HTML": 1598}
|
package com.hjhrq1991.library.tbs
interface WebViewJavascriptBridge {
fun send(data: String?)
fun send(data: String?, responseCallback: CallBackFunction?)
}
| 0 |
Kotlin
|
4
| 4 |
9e5646677153f5fba31c31a1bc8ce5753b84660a
| 165 |
UICoreEx
|
MIT License
|
platform/lang-impl/testSources/com/intellij/openapi/wm/impl/ToolWindowManagerTest.kt
|
JetBrains
| 2,489,216 | false | null |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.wm.impl
import com.intellij.testFramework.ProjectExtension
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.RegisterExtension
class ToolWindowManagerTest {
companion object {
@JvmField
@RegisterExtension
val projectRule = ProjectExtension(runPostStartUpActivities = false, preloadServices = false)
}
@Test
fun testInit() {
val manager = ToolWindowManagerImpl(projectRule.project)
manager.setLayoutOnInit(DesktopLayout(IntellijPlatformDefaultToolWindowLayoutProvider().createDefaultToolWindowLayout()))
}
}
| 186 | null |
4323
| 13,182 |
26261477d6e3d430c5fa50c42b80ea8cfee45525
| 712 |
intellij-community
|
Apache License 2.0
|
data/src/main/java/com/kkkk/data/service/StudyService.kt
|
KKKK-Stempo
| 815,756,494 | false |
{"Kotlin": 162785}
|
package com.kkkk.data.service
import com.kkkk.data.dto.BaseResponse
import com.kkkk.data.dto.request.HomeworkDescriptionDto
import com.kkkk.data.dto.request.HomeworkDto
import com.kkkk.data.dto.response.StudyDto
import retrofit2.http.Body
import retrofit2.http.DELETE
import retrofit2.http.GET
import retrofit2.http.PATCH
import retrofit2.http.POST
import retrofit2.http.Path
import retrofit2.http.Query
interface StudyService {
@GET("api/v1/homeworks")
suspend fun getHomeworks(
@Query("page")
page: Int,
@Query("size")
size: Int,
): BaseResponse<StudyDto>
@POST("api/v1/homeworks")
suspend fun addHomework(
@Body homeworkDescriptionDto: HomeworkDescriptionDto
): BaseResponse<Int>
@DELETE("api/v1/homeworks/{homeworkId}")
suspend fun deleteHomework(
@Path("homeworkId") homeworkId: Int
): BaseResponse<Int>
@PATCH("api/v1/homeworks/{homeworkId}")
suspend fun updateHomework(
@Path("homeworkId") homeworkId: Int,
@Body homeworkDto: HomeworkDto
): BaseResponse<Int>
}
| 0 |
Kotlin
|
0
| 6 |
3a4488fcc196e0df2c6106f7273b4ec7f2e699a1
| 1,085 |
stempo-android
|
MIT License
|
src/main/kotlin/bia/interpreter/DynamicScope.kt
|
cubuspl42
| 451,099,116 | false | null |
package bia.interpreter
import bia.model.Value
abstract class DynamicScope {
companion object {
fun of(values: Map<String, Value>): DynamicScope = SimpleDynamicScope(
values = values,
)
fun delegated(delegate: () -> DynamicScope): DynamicScope = object : DynamicScope() {
override val values: Map<String, Value> by lazy { delegate().values }
}
val empty: DynamicScope = of(values = emptyMap())
}
protected abstract val values: Map<String, Value>
fun extend(name: String, value: Value) = DynamicScope.of(
values = values + (name to value)
)
fun extend(namedValues: List<Pair<String, Value>>) = DynamicScope.of(
values = values + namedValues.toMap()
)
fun getValue(name: String): Value? = values[name]
}
data class SimpleDynamicScope(
override val values: Map<String, Value>,
) : DynamicScope()
| 0 |
Kotlin
|
0
| 4 |
16fef1cc3eba846601f626bcd74b4e8d8407862d
| 918 |
bia
|
Apache License 2.0
|
feature-push-notifications/src/main/java/io/novafoundation/nova/feature_push_notifications/presentation/staking/di/PushStakingSettingsModule.kt
|
novasamatech
| 415,834,480 | false |
{"Kotlin": 11121812, "Rust": 25308, "Java": 17664, "JavaScript": 425}
|
package io.novafoundation.nova.feature_push_notifications.presentation.staking.di
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import dagger.Module
import dagger.Provides
import dagger.multibindings.IntoMap
import io.novafoundation.nova.common.di.viewmodel.ViewModelKey
import io.novafoundation.nova.common.di.viewmodel.ViewModelModule
import io.novafoundation.nova.common.resources.ResourceManager
import io.novafoundation.nova.feature_push_notifications.PushNotificationsRouter
import io.novafoundation.nova.feature_push_notifications.domain.interactor.StakingPushSettingsInteractor
import io.novafoundation.nova.feature_push_notifications.presentation.staking.PushStakingSettingsCommunicator
import io.novafoundation.nova.feature_push_notifications.presentation.staking.PushStakingSettingsRequester
import io.novafoundation.nova.feature_push_notifications.presentation.staking.PushStakingSettingsViewModel
import io.novafoundation.nova.runtime.multiNetwork.ChainRegistry
@Module(includes = [ViewModelModule::class])
class PushStakingSettingsModule {
@Provides
@IntoMap
@ViewModelKey(PushStakingSettingsViewModel::class)
fun provideViewModel(
router: PushNotificationsRouter,
pushStakingSettingsCommunicator: PushStakingSettingsCommunicator,
chainRegistry: ChainRegistry,
request: PushStakingSettingsRequester.Request,
resourceManager: ResourceManager,
stakingPushSettingsInteractor: StakingPushSettingsInteractor
): ViewModel {
return PushStakingSettingsViewModel(
router = router,
pushStakingSettingsResponder = pushStakingSettingsCommunicator,
chainRegistry = chainRegistry,
request = request,
resourceManager = resourceManager,
stakingPushSettingsInteractor = stakingPushSettingsInteractor
)
}
@Provides
fun provideViewModelCreator(
fragment: Fragment,
viewModelFactory: ViewModelProvider.Factory
): PushStakingSettingsViewModel {
return ViewModelProvider(fragment, viewModelFactory).get(PushStakingSettingsViewModel::class.java)
}
}
| 12 |
Kotlin
|
30
| 50 |
127f8739ca86dc74d006f018237daed0de5095a1
| 2,217 |
nova-wallet-android
|
Apache License 2.0
|
backend/src/main/kotlin/com/linkedplanet/ktorbase/config/SessionConfig.kt
|
linked-planet
| 226,285,669 | false | null |
package com.linkedplanet.ktorbase.config
import com.typesafe.config.*
import java.time.Duration
object SessionConfig {
private val config: Config = ConfigFactory.load().getConfig("session")
val expiration: Duration = config.getDuration("expiration")
}
| 2 |
Kotlin
|
0
| 9 |
7b580050ac31383b3c1e9e36b0cc3b5fbc3d3340
| 264 |
ktorbase
|
Creative Commons Zero v1.0 Universal
|
buildSrc/src/main/kotlin/Projects.kt
|
realad
| 269,084,902 | false | null |
object Projects {
const val KileFp = ":kile-fp"
const val KileCore = ":kile-core"
const val KileAdapters = ":kile-adapters"
}
| 0 |
Kotlin
|
1
| 5 |
23d71134ab6ce2132977780e2d1c096245e11e20
| 138 |
kile
|
Apache License 2.0
|
app/src/main/java/com/mohsinajavaid/currencyapp/ui/theme/Color.kt
|
mohsinajavaid1
| 718,497,487 | false |
{"Kotlin": 27218, "Java": 1033}
|
package com.mohsinajavaid.currencyapp.ui.theme
import androidx.compose.ui.graphics.Color
val Purple200 = Color(0xFFBB86FC)
val Purple500 = Color(0xFF6200EE)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
val Orange_700 = Color(0xFFF24F09)
val White_900 = Color(0xFFFFFFFF)
val Label_Color = Color(0xFF8F8F8F)
val Value_Color = Color(0xFF444444)
| 0 |
Kotlin
|
0
| 0 |
0995ff60598cfcd36bf7a7f191630b9ef551ceb1
| 366 |
CurrencyConverterApp
|
MIT License
|
src/main/kotlin/org/xpathqs/driver/navigation/base/IBlockSelectorNavigation.kt
|
xpathqs
| 366,703,320 | false | null |
package org.xpathqs.driver.navigation.base
import org.xpathqs.core.selector.base.ISelector
interface IBlockSelectorNavigation {
fun navigate(elem: ISelector)
}
| 0 |
Kotlin
|
0
| 1 |
b07da59951595b23cb40b8d140862bcca63e6f4a
| 165 |
driver
|
MIT License
|
shared/src/main/java/com/maiconhellmann/shared/networking/exception/EmptyResponseBodyException.kt
|
maiconhellmann
| 640,102,559 | false | null |
package com.maiconhellmann.shared.networking.exception
/**
* Exceção específica quando um corpo vazio é retornado por uma API de serviço.
*/
class EmptyResponseBodyException : Exception()
| 0 |
Kotlin
|
0
| 0 |
78c8904c565d3cc918dc5b7255301ae6ce5f0df4
| 190 |
github-user
|
MIT License
|
src/test/kotlin/no/nav/fo/veilarbregistrering/arbeidsforhold/FlereArbeidsforholdTest.kt
|
navikt
| 131,013,336 | false |
{"Kotlin": 863303, "PLpgSQL": 853, "PLSQL": 546, "Dockerfile": 87}
|
package no.nav.fo.veilarbregistrering.arbeidsforhold
import no.nav.fo.veilarbregistrering.arbeidsforhold.FlereArbeidsforholdTestdataBuilder.flereArbeidsforholdTilfeldigSortert
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import java.time.LocalDate
class FlereArbeidsforholdTest {
@Test
fun `skal hente siste eller paagaaende arbeidsforhold`() {
assertThat(flereArbeidsforholdTilfeldigSortert().siste())
.isEqualTo(ArbeidsforholdTestdata.siste())
val stigendeSortertListe = listOf(
ArbeidsforholdTestdata.eldre(),
ArbeidsforholdTestdata.nestSiste(),
ArbeidsforholdTestdata.siste()
)
assertThat(FlereArbeidsforhold(stigendeSortertListe).siste())
.isEqualTo(ArbeidsforholdTestdata.siste())
val synkendeSortertListe = listOf(
ArbeidsforholdTestdata.siste(),
ArbeidsforholdTestdata.nestSiste(),
ArbeidsforholdTestdata.eldre()
)
assertThat(FlereArbeidsforhold(synkendeSortertListe).siste())
.isEqualTo(ArbeidsforholdTestdata.siste())
// Skal hente paagendeArbeidsforhold
val tilfeldigSortertListeMedPaagaaende = listOf(
ArbeidsforholdTestdata.eldre(),
ArbeidsforholdTestdata.paagaaende(),
ArbeidsforholdTestdata.siste(),
ArbeidsforholdTestdata.nestSiste()
)
assertThat(FlereArbeidsforhold(tilfeldigSortertListeMedPaagaaende).siste())
.isEqualTo(ArbeidsforholdTestdata.paagaaende())
val stigendeSortertListePaagaande = listOf(
ArbeidsforholdTestdata.eldre(),
ArbeidsforholdTestdata.nestSiste(),
ArbeidsforholdTestdata.siste(),
ArbeidsforholdTestdata.paagaaende()
)
assertThat(FlereArbeidsforhold(stigendeSortertListePaagaande).siste())
.isEqualTo(ArbeidsforholdTestdata.paagaaende())
val synkendeSortertListePaagaande = listOf(
ArbeidsforholdTestdata.paagaaende(),
ArbeidsforholdTestdata.siste(),
ArbeidsforholdTestdata.nestSiste(),
ArbeidsforholdTestdata.eldre()
)
assertThat(FlereArbeidsforhold(synkendeSortertListePaagaande).siste())
.isEqualTo(ArbeidsforholdTestdata.paagaaende())
}
@Test
fun `skal hente lengste av pågående arbeidsforhold`() {
val fom3 = LocalDate.of(2017, 1, 1)
val tom3: LocalDate? = null
val fom2 = LocalDate.of(2017, 10, 1)
val tom2: LocalDate? = null
val fom1 = LocalDate.of(2017, 11, 1)
val tom1: LocalDate? = null
val paagaaendeArbeidsforholdVarighet3 = ArbeidsforholdTestdata.medDato(fom3, tom3)
val paagaaendeArbeidsforholdVarighet2 = ArbeidsforholdTestdata.medDato(fom2, tom2)
val paagaaendeArbeidsforholdVarighet1 = ArbeidsforholdTestdata.medDato(fom1, tom1)
val flerePaagendeArbeidsforhold = listOf(
paagaaendeArbeidsforholdVarighet2,
paagaaendeArbeidsforholdVarighet1,
paagaaendeArbeidsforholdVarighet3
)
assertThat(FlereArbeidsforhold(flerePaagendeArbeidsforhold).siste())
.isEqualTo(paagaaendeArbeidsforholdVarighet3)
}
@Test
fun `skal hente lengste av siste arbeidsforhold`() {
val fom3 = LocalDate.of(2017, 1, 1)
val tom3 = LocalDate.of(2017, 11, 30)
val fom2 = LocalDate.of(2017, 10, 1)
val tom2 = LocalDate.of(2017, 11, 30)
val fom1 = LocalDate.of(2017, 11, 1)
val tom1 = LocalDate.of(2017, 11, 30)
val sisteArbeidsforholdVarighet3 = ArbeidsforholdTestdata.medDato(fom3, tom3)
val sisteArbeidsforholdvarighet2 = ArbeidsforholdTestdata.medDato(fom2, tom2)
val sisteArbeidsforholdVarighet1 = ArbeidsforholdTestdata.medDato(fom1, tom1)
val flereSisteArbeidsforhold =
listOf(sisteArbeidsforholdVarighet1, sisteArbeidsforholdvarighet2, sisteArbeidsforholdVarighet3)
assertThat(FlereArbeidsforhold(flereSisteArbeidsforhold).siste())
.isEqualTo(sisteArbeidsforholdVarighet3)
}
@Test
fun `skal default arbeidsforhold`() {
val arbeidsforhold = Arbeidsforhold(null, "utenstyrkkode", null, null, null)
assertThat(FlereArbeidsforhold(emptyList()).siste()).isEqualTo(arbeidsforhold)
}
@Test
fun `skal ha arbeidsforhold på dato`() {
val mnd = LocalDate.of(2017, 12, 1)
val fom1 = LocalDate.of(2017, 10, 1)
val tom1 = LocalDate.of(2017, 12, 1)
val fom2 = LocalDate.of(2017, 12, 1)
val tom2 = LocalDate.of(2017, 12, 30)
val arbeidsforhold1 = ArbeidsforholdTestdata.medDato(fom1, tom1)
val arbeidsforhold2 = ArbeidsforholdTestdata.medDato(fom2, tom2)
val arbeidsforhold = listOf(arbeidsforhold1, arbeidsforhold2)
assertThat(FlereArbeidsforhold(arbeidsforhold).harArbeidsforholdPaaDato(mnd)).isTrue
}
@Test
fun `skal ikke ha arbeidsforhold på dato`() {
val mnd = LocalDate.of(2018, 12, 1)
val fom1 = LocalDate.of(2017, 10, 1)
val tom1 = LocalDate.of(2017, 12, 1)
val fom2 = LocalDate.of(2017, 12, 1)
val tom2 = LocalDate.of(2017, 12, 30)
val arbeidsforhold1 = ArbeidsforholdTestdata.medDato(fom1, tom1)
val arbeidsforhold2 = ArbeidsforholdTestdata.medDato(fom2, tom2)
val arbeidsforhold = listOf(arbeidsforhold1, arbeidsforhold2)
assertThat(FlereArbeidsforhold(arbeidsforhold).harArbeidsforholdPaaDato(mnd)).isFalse
}
@Test
fun `skal være i jobb 2 av 4 mnd`() {
val antallMnd = 4
val minAntallMndSammenhengendeJobb = 2
val dagensDato = LocalDate.of(2017, 12, 20)
val fom1 = LocalDate.of(2017, 10, 1)
val tom1 = LocalDate.of(2017, 10, 31)
val fom2 = LocalDate.of(2017, 9, 1)
val tom2 = LocalDate.of(2017, 9, 30)
val arbeidsforhold1 = ArbeidsforholdTestdata.medDato(fom1, tom1)
val arbeidsforhold2 = ArbeidsforholdTestdata.medDato(fom2, tom2)
val arbeidsforhold = listOf(arbeidsforhold1, arbeidsforhold2)
assertThat(
FlereArbeidsforhold(arbeidsforhold).harJobbetSammenhengendeSisteManeder(dagensDato, minAntallMndSammenhengendeJobb, antallMnd)
).isTrue
}
@Test
fun `skal ikke være i jobb 2 av 4 mnd`() {
val antallMnd = 4
val minAntallMndSammenhengendeJobb = 2
val dagensDato = LocalDate.of(2017, 12, 20)
val fom1 = LocalDate.of(2017, 11, 1)
val tom1 = LocalDate.of(2017, 11, 30)
val fom2 = LocalDate.of(2017, 9, 1)
val tom2 = LocalDate.of(2017, 9, 30)
val arbeidsforhold1 = ArbeidsforholdTestdata.medDato(fom1, tom1)
val arbeidsforhold2 = ArbeidsforholdTestdata.medDato(fom2, tom2)
val arbeidsforhold = listOf(arbeidsforhold1, arbeidsforhold2)
assertThat(
FlereArbeidsforhold(arbeidsforhold).harJobbetSammenhengendeSisteManeder(dagensDato, minAntallMndSammenhengendeJobb, antallMnd)
).isFalse
}
@Test
fun `to tomme arbeidsforhold skal være like`() {
val arbeidsforholdFraSoap = FlereArbeidsforhold(emptyList())
val arbeidsforholdFraRest = FlereArbeidsforhold(emptyList())
assertThat(arbeidsforholdFraSoap.erLik(arbeidsforholdFraRest)).isTrue
}
@Test
fun `to lister med samme innhold skal være like`() {
val arbeidsforholdFraSoap = flereArbeidsforholdTilfeldigSortert()
val arbeidsforholdFraRest = flereArbeidsforholdTilfeldigSortert()
assertThat(arbeidsforholdFraSoap.erLik(arbeidsforholdFraRest)).isTrue
}
@Test
fun `to lister med samme innhold men ulikt sortert skal være like`() {
val arbeidsforholdFraSoap = FlereArbeidsforhold(
listOf(
ArbeidsforholdTestdata.eldre(),
ArbeidsforholdTestdata.siste(),
ArbeidsforholdTestdata.nestSiste()
)
)
val arbeidsforholdFraRest = FlereArbeidsforhold(
listOf(
ArbeidsforholdTestdata.nestSiste(),
ArbeidsforholdTestdata.eldre(),
ArbeidsforholdTestdata.siste()
)
)
assertThat(arbeidsforholdFraSoap.erLik(arbeidsforholdFraRest)).isTrue
}
@Test
fun `to ulike lister skal være ulike`() {
val arbeidsforholdFraSoap = FlereArbeidsforhold(emptyList())
val arbeidsforholdFraRest = FlereArbeidsforhold(
listOf(
ArbeidsforholdTestdata.nestSiste(),
ArbeidsforholdTestdata.eldre(),
ArbeidsforholdTestdata.siste()
)
)
assertThat(arbeidsforholdFraSoap.erLik(arbeidsforholdFraRest)).isFalse
}
}
fun FlereArbeidsforhold.erLik(other: FlereArbeidsforhold): Boolean =
this.flereArbeidsforhold.containsAll(other.flereArbeidsforhold)
&& other.flereArbeidsforhold.containsAll(this.flereArbeidsforhold)
| 18 |
Kotlin
|
5
| 6 |
0ecf248adee242a7eac34b655f86278946641d7e
| 9,041 |
veilarbregistrering
|
MIT License
|
libraries/cache/src/main/java/com/zizohanto/android/tobuy/cache/models/ShoppingListCacheModel.kt
|
zizoh
| 292,960,353 | false |
{"Kotlin": 109143}
|
package com.zizohanto.android.tobuy.cache.models
import androidx.room.Embedded
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.Relation
@Entity(tableName = "shopping_list")
data class ShoppingListCacheModel(
@PrimaryKey
val id: String,
val name: String,
val budget: Double = 0.0,
val dateCreated: Long,
val dateModified: Long
)
data class ShoppingListWithProductsCacheModel(
@Embedded val shoppingList: ShoppingListCacheModel,
@Relation(
parentColumn = "id",
entityColumn = "shoppingListId"
)
val products: List<ProductCacheModel>
)
| 0 |
Kotlin
|
2
| 7 |
8b4b61c563ff09afd1bb530989760c131ea61fcd
| 624 |
Shopping-List-MVI
|
Apache License 2.0
|
kord-extensions/src/main/kotlin/com/kotlindiscord/kord/extensions/utils/_Koin.kt
|
Tom-The-Geek
| 375,451,054 | true |
{"Kotlin": 459547, "Python": 1793, "Groovy": 777}
|
package com.kotlindiscord.kord.extensions.utils
import org.koin.core.Koin
import org.koin.core.module.Module
import org.koin.dsl.ModuleDeclaration
/** Wrapper for [org.koin.dsl.module] that immediately loads the module for the current [Koin] instance. **/
public fun Koin.module(
createdAtStart: Boolean = false,
override: Boolean = false,
moduleDeclaration: ModuleDeclaration
): Module {
val module = org.koin.dsl.module(createdAtStart, override, moduleDeclaration)
loadModules(listOf(module))
return module
}
| 0 | null |
0
| 0 |
c3c7dcfa33c688058c72076ef383c6f40791b795
| 539 |
kord-extensions
|
MIT License
|
agp-7.1.0-alpha01/tools/base/lint/libs/lint-tests/src/test/java/com/android/tools/lint/checks/infrastructure/ResolveCheckerTest.kt
|
jomof
| 502,039,754 | true |
{"Markdown": 63, "Java Properties": 56, "Shell": 31, "Batchfile": 12, "Proguard": 30, "CMake": 10, "Kotlin": 3443, "C++": 594, "Java": 4446, "HTML": 34, "Makefile": 14, "RenderScript": 22, "C": 30, "JavaScript": 2, "CSS": 3, "INI": 11, "Filterscript": 11, "Prolog": 1, "GLSL": 1, "Gradle Kotlin DSL": 5, "Python": 12, "Dockerfile": 2}
|
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.lint.checks.infrastructure
import com.android.testutils.TestUtils
import com.android.tools.lint.checks.AlwaysShowActionDetector
import com.android.tools.lint.checks.ToastDetector
import com.android.tools.lint.checks.infrastructure.TestFiles.java
import com.android.tools.lint.checks.infrastructure.TestFiles.kotlin
import org.junit.Test
import org.junit.Assert.assertEquals
@Suppress("LintDocExample")
class ResolveCheckerTest {
private fun lint(): TestLintTask {
return TestLintTask.lint().sdkHome(TestUtils.getSdk().toFile())
}
@Test
fun testInvalidImport() {
try {
lint().files(
kotlin(
"""
package test.pkg
import java.io.File // OK
import invalid.Cls // ERROR
class Test
"""
)
)
.testModes(TestMode.DEFAULT)
.issues(AlwaysShowActionDetector.ISSUE)
.run()
.expectErrorCount(1)
} catch (e: Throwable) {
assertEquals(
"""
app/src/test/pkg/Test.kt:4: Error:
Couldn't resolve this import [LintError]
import invalid.Cls // ERROR
~~~~~~~~~~~
This usually means that the unit test needs to declare a stub file or
placeholder with the expected signature such that type resolving works.
If this import is immaterial to the test, either delete it, or mark
this unit test as allowing resolution errors by setting
`allowCompilationErrors()`.
(This check only enforces import references, not all references, so if
it doesn't matter to the detector, you can just remove the import but
leave references to the class in the code.)
For more information, see the "Library Dependencies and Stubs" section in
https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-master-dev:lint/docs/api-guide/unit-testing.md.html
""".trimIndent(),
e.message?.replace(" \n", "\n")?.trim()
)
}
}
@Test
fun testInvalidReference() {
try {
lint().files(
java(
"""
package test.pkg;
public class Test {
public void test() {
Object o1 = MenuItem.UNRELATED_REFERENCE_NOT_A_PROBLEM; // OK
Object o2 = MenuItem.SHOW_AS_ACTION_ALWAYS; // ERROR
}
}
"""
)
)
.testModes(TestMode.DEFAULT)
.issues(AlwaysShowActionDetector.ISSUE)
.run()
.expectErrorCount(1)
} catch (e: Throwable) {
assertEquals(
"""
app/src/test/pkg/Test.java:6: Error:
Couldn't resolve this reference [LintError]
Object o2 = MenuItem.SHOW_AS_ACTION_ALWAYS; // ERROR
~~~~~~~~~~~~~~~~~~~~~
The tested detector returns `SHOW_AS_ACTION_ALWAYS` from `getApplicableReferenceNames()`,
which means this reference is probably relevant to the test, but when the
reference cannot be resolved, lint won't invoke `visitReference` on it.
This usually means that the unit test needs to declare a stub file or
placeholder with the expected signature such that type resolving works.
If this reference is immaterial to the test, either delete it, or mark
this unit test as allowing resolution errors by setting
`allowCompilationErrors()`.
For more information, see the "Library Dependencies and Stubs" section in
https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-master-dev:lint/docs/api-guide/unit-testing.md.html
""".trimIndent(),
e.message?.replace(" \n", "\n")?.trim()
)
}
}
@Test
fun testInvalidCall() {
try {
lint().files(
kotlin(
"""
package test.pkg
fun test() {
unrelatedCallsOk()
android.widget.Toast.makeText() // OK
invalid.makeText() // ERROR
}
"""
)
)
.testModes(TestMode.DEFAULT)
.issues(ToastDetector.ISSUE)
.run()
.expectErrorCount(1)
} catch (e: Throwable) {
assertEquals(
"""
app/src/test/pkg/test.kt:5: Error:
Couldn't resolve this call [LintError]
android.widget.Toast.makeText() // OK
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The tested detector returns `makeText` from `getApplicableMethodNames()`,
which means this reference is probably relevant to the test, but when the
call cannot be resolved, lint won't invoke `visitMethodCall` on it.
This usually means that the unit test needs to declare a stub file or
placeholder with the expected signature such that type resolving works.
If this call is immaterial to the test, either delete it, or mark
this unit test as allowing resolution errors by setting
`allowCompilationErrors()`.
For more information, see the "Library Dependencies and Stubs" section in
https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-master-dev:lint/docs/api-guide/unit-testing.md.html
""".trimIndent(),
e.message?.replace(" \n", "\n")?.trim()
)
}
}
}
| 1 | null |
1
| 0 |
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
| 6,978 |
CppBuildCacheWorkInProgress
|
Apache License 2.0
|
kbloc_hilt/src/main/java/cafe/adriel/voyager/hilt/VoyagerHiltViewModelFactories.kt
|
beyondeye
| 509,066,769 | false | null |
package cafe.adriel.voyager.hilt
import android.app.Application
import androidx.activity.ComponentActivity
import androidx.lifecycle.SavedStateViewModelFactory
import androidx.lifecycle.ViewModelProvider
import androidx.savedstate.SavedStateRegistryOwner
import dagger.hilt.EntryPoint
import dagger.hilt.EntryPoints
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ActivityComponent
import dagger.hilt.android.internal.builders.ViewModelComponentBuilder
import dagger.hilt.android.internal.lifecycle.HiltViewModelFactory
import dagger.hilt.android.internal.lifecycle.HiltViewModelMap
import javax.inject.Inject
public object VoyagerHiltViewModelFactories {
public fun getVoyagerFactory(
activity: ComponentActivity,
owner: SavedStateRegistryOwner,
delegateFactory: ViewModelProvider.Factory?
): ViewModelProvider.Factory {
return EntryPoints.get(activity, ViewModelFactoryEntryPoint::class.java)
.internalViewModelFactory()
.fromActivity(activity, owner, delegateFactory)
}
internal class InternalViewModelFactory @Inject internal constructor(
private val application: Application,
@HiltViewModelMap.KeySet private val keySet: Set<String>,
private val viewModelComponentBuilder: ViewModelComponentBuilder
) {
fun fromActivity(
activity: ComponentActivity,
owner: SavedStateRegistryOwner,
delegateFactory: ViewModelProvider.Factory?
): ViewModelProvider.Factory {
val defaultArgs = activity.intent?.extras
val delegate = delegateFactory ?: SavedStateViewModelFactory(application, owner, defaultArgs)
return HiltViewModelFactory(owner, defaultArgs, keySet, delegate, viewModelComponentBuilder)
}
}
@EntryPoint
@InstallIn(ActivityComponent::class)
internal interface ViewModelFactoryEntryPoint {
fun internalViewModelFactory(): InternalViewModelFactory
}
}
| 0 |
Kotlin
|
0
| 9 |
3d5e4998c9215b1cef94f6d56db0a2c4eef8d676
| 2,001 |
compose_bloc
|
Apache License 2.0
|
things/src/main/java/com/example/androidthings/lantern/hardware/BoardDefaults.kt
|
nordprojects
| 118,455,585 | false |
{"Kotlin": 202091, "Java": 16644}
|
package com.example.androidthings.lantern.hardware
import android.os.Build
/**
* Holds the hardware-specific parameters of the app.
*/
object BoardDefaults {
private val DEVICE_RPI3 = "rpi3"
/**
* Return the I2C bus that the accelerometer can be accessed on
*/
val busForAccelerometer: String
get() {
when (Build.DEVICE) {
DEVICE_RPI3 -> return "I2C1"
else -> throw IllegalStateException("Unsupported Build.DEVICE " + Build.DEVICE)
}
}
}
| 1 |
Kotlin
|
50
| 464 |
fa015faa1c9f4f500bc14074a3485750aecf14e1
| 537 |
lantern
|
Apache License 2.0
|
src/main/kotlin/lgbt/mouse/blocks/transfer/CableSidedEnergyContainer.kt
|
msparkles
| 742,009,088 | false |
{"Kotlin": 61349, "Java": 4266}
|
package lgbt.mouse.blocks.transfer
import net.minecraft.block.BlockState
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Direction
import team.reborn.energy.api.base.SimpleSidedEnergyContainer
abstract class CableSidedEnergyContainer(
private val pos: BlockPos,
private val state: BlockState,
private val entity: CableEntity,
private val capacity: Long,
private val maxExtract: Long,
) :
SimpleSidedEnergyContainer() {
val insertSides = mutableSetOf<Direction>()
override fun getCapacity() = capacity
override fun getMaxInsert(side: Direction?): Long {
val dir = side ?: return capacity
return if ((state.block as Cable<*>).canConnectCable(entity.world!!.getBlockState(pos.offset(dir)).block)) {
capacity
} else {
0L
}
}
override fun getMaxExtract(side: Direction?): Long {
side?.let {
if (insertSides.contains(it)) {
return 0L
}
}
return maxExtract
}
}
| 0 |
Kotlin
|
0
| 0 |
e967118f2e339b3ae2a34c7a669a9ad1d1527f17
| 1,051 |
mousewalk-mod
|
MIT License
|
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/HouseCrackAlt.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.HouseCrackAlt: ImageVector
get() {
if (_houseCrackAlt != null) {
return _houseCrackAlt!!
}
_houseCrackAlt = Builder(name = "HouseCrackAlt", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(22.0f, 5.653f)
lineTo(15.076f, 0.94f)
curveToRelative(-1.869f, -1.261f, -4.284f, -1.26f, -6.152f, 0.0f)
lineTo(2.424f, 5.327f)
curveToRelative(-1.518f, 1.024f, -2.424f, 2.728f, -2.424f, 4.559f)
verticalLineToRelative(8.614f)
curveToRelative(0.0f, 3.033f, 2.467f, 5.5f, 5.5f, 5.5f)
horizontalLineToRelative(13.0f)
curveToRelative(3.032f, 0.0f, 5.5f, -2.467f, 5.5f, -5.5f)
verticalLineToRelative(-8.614f)
curveToRelative(0.0f, -1.651f, -0.742f, -3.195f, -2.0f, -4.234f)
close()
moveTo(21.0f, 18.5f)
curveToRelative(0.0f, 1.378f, -1.121f, 2.5f, -2.5f, 2.5f)
horizontalLineToRelative(-2.616f)
lineToRelative(-3.761f, -3.986f)
lineToRelative(2.087f, -1.953f)
curveToRelative(0.51f, -0.509f, 0.79f, -1.187f, 0.79f, -1.907f)
reflectiveCurveToRelative(-0.28f, -1.398f, -0.76f, -1.875f)
lineToRelative(-2.649f, -2.808f)
curveToRelative(-0.568f, -0.602f, -1.517f, -0.63f, -2.12f, -0.062f)
curveToRelative(-0.603f, 0.568f, -0.63f, 1.518f, -0.062f, 2.12f)
lineToRelative(2.464f, 2.61f)
lineToRelative(-2.087f, 1.954f)
curveToRelative(-1.052f, 1.051f, -1.052f, 2.762f, -0.03f, 3.782f)
lineToRelative(2.005f, 2.125f)
horizontalLineToRelative(-6.26f)
curveToRelative(-1.378f, 0.0f, -2.5f, -1.122f, -2.5f, -2.5f)
verticalLineToRelative(-8.614f)
curveToRelative(0.0f, -0.832f, 0.412f, -1.607f, 1.102f, -2.073f)
lineToRelative(6.5f, -4.386f)
curveToRelative(0.425f, -0.287f, 0.912f, -0.43f, 1.398f, -0.43f)
reflectiveCurveToRelative(0.974f, 0.144f, 1.398f, 0.43f)
lineToRelative(6.5f, 4.387f)
curveToRelative(0.689f, 0.465f, 1.102f, 1.24f, 1.102f, 2.072f)
verticalLineToRelative(8.614f)
close()
}
}
.build()
return _houseCrackAlt!!
}
private var _houseCrackAlt: ImageVector? = null
| 1 |
Kotlin
|
0
| 5 |
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 3,421 |
icons
|
MIT License
|
core-ads/src/main/kotlin/com/marcohc/terminator/core/ads/banner/BannerEvent.kt
|
marcohc
| 228,077,707 | false | null |
package com.marcohc.terminator.core.ads.banner
import com.google.android.gms.ads.AdView
internal sealed class BannerEvent {
data class Loaded(val adView: AdView) : BannerEvent()
object FailedToLoad : BannerEvent()
object Opened : BannerEvent()
object Impression : BannerEvent()
object Click : BannerEvent()
object Closed : BannerEvent()
}
| 0 |
Kotlin
|
0
| 2 |
bef69c75478f9ecd40a182fa83c7c95eb1251aec
| 365 |
terminator
|
MIT License
|
app/src/main/java/com/wkw/hot/domain/model/HotResponse.kt
|
zj-wukewei
| 93,613,475 | false | null |
package com.wkw.hot.domain.model
/**
* Created by hzwukewei on 2017-6-6.
*/
class HotResponse<out T>(val showapi_res_code: Int,
val showapi_res_error: String,
val showapi_res_body: T) {
fun isSuccess(): Boolean {
return showapi_res_code == 0
}
}
| 0 |
Kotlin
|
1
| 2 |
4d241aadc7a258a76a197198769e947abbb85b03
| 314 |
Hot_Kotlin
|
Apache License 2.0
|
app/src/main/java/de/drtobiasprinz/summitbook/fragments/BarChartFragment.kt
|
prinztob
| 370,702,913 | false | null |
package de.drtobiasprinz.summitbook.fragments
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import android.widget.Spinner
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.preference.PreferenceManager
import com.github.mikephil.charting.components.LimitLine
import com.github.mikephil.charting.components.MarkerView
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.BarData
import com.github.mikephil.charting.data.BarDataSet
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.formatter.ValueFormatter
import com.github.mikephil.charting.highlight.Highlight
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet
import com.github.mikephil.charting.utils.MPPointF
import de.drtobiasprinz.summitbook.MainActivity
import de.drtobiasprinz.summitbook.R
import de.drtobiasprinz.summitbook.models.SportType
import de.drtobiasprinz.summitbook.models.Summit
import de.drtobiasprinz.summitbook.ui.utils.BarChartCustomRenderer
import de.drtobiasprinz.summitbook.ui.utils.CustomBarChart
import de.drtobiasprinz.summitbook.ui.utils.IntervalHelper
import de.drtobiasprinz.summitbook.ui.utils.SortFilterHelper
import java.text.ParseException
import java.time.Month
import java.util.*
import java.util.function.Supplier
import java.util.stream.Stream
import kotlin.collections.ArrayList
class BarChartFragment(private val sortFilterHelper: SortFilterHelper) : Fragment(), SummationFragment {
private var summitEntries: ArrayList<Summit>? = null
private var filteredEntries: ArrayList<Summit>? = null
private var dataSpinner: Spinner? = null
private var xAxisSpinner: Spinner? = null
private var barChartView: View? = null
private var barChartEntries: MutableList<BarEntry?>? = null
private var unit: String? = "hm"
private var label: String? = "Height meters"
private var barChart: CustomBarChart? = null
private lateinit var intervallHelper: IntervalHelper
private var selectedDataSpinner = 0
private var selectedXAxisSpinner = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setRetainInstance(true)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
barChartView = inflater.inflate(R.layout.fragment_bar_chart, container, false)
setHasOptionsMenu(true)
sortFilterHelper.fragment = this
fillDateSpinner()
summitEntries = sortFilterHelper.entries
intervallHelper = IntervalHelper(summitEntries)
barChart = barChartView?.findViewById(R.id.barChart) // Fragment
val barChartCustomRenderer = BarChartCustomRenderer(barChart, barChart?.animator, barChart?.viewPortHandler)
barChart?.renderer = barChartCustomRenderer
barChart?.setDrawValueAboveBar(false)
resizeChart()
barChartEntries = ArrayList()
filteredEntries = sortFilterHelper.filteredEntries
listenOnDataSpinner()
update(filteredEntries)
return barChartView
}
private fun resizeChart() {
val metrics = DisplayMetrics()
MainActivity.mainActivity?.windowManager?.defaultDisplay?.getMetrics(metrics)
barChart?.minimumHeight = (metrics.heightPixels * 0.7).toInt()
}
private fun drawLineChart() {
val dataSets: MutableList<IBarDataSet?> = ArrayList()
val dataSet = BarDataSet(barChartEntries, label)
setGraphView(dataSet)
dataSets.add(dataSet)
barChart?.data = BarData(dataSets)
setXAxis()
val yAxisLeft = barChart?.axisLeft
setYAxis(yAxisLeft)
val yAxisRight = barChart?.axisRight
setYAxis(yAxisRight)
barChart?.setTouchEnabled(true)
barChart?.marker = CustomMarkerView(barChartView?.context, R.layout.marker_graph_bar_chart)
barChart?.invalidate()
}
private fun setXAxis() {
val xAxis = barChart?.xAxis
xAxis?.position = XAxis.XAxisPosition.TOP
xAxis?.valueFormatter = object : ValueFormatter() {
override fun getFormattedValue(value: Float): String {
return when (selectedXAxisSpinner) {
1 -> String.format("%s", ((value + 0.5) * IntervalHelper.kilometersStep).toInt())
2 -> String.format("%s", ((value + 0.5) * IntervalHelper.elevationGainStep).toInt())
3 -> String.format("%s", ((value + 0.5) * IntervalHelper.topElevationStep).toInt())
else -> if (sortFilterHelper.selectedYear == "" || value > 12) String.format("%s", value.toInt()) else String.format("%s", Month.of(value.toInt()))
}
}
}
}
private fun setYAxis(yAxis: YAxis?) {
yAxis?.valueFormatter = object : ValueFormatter() {
override fun getFormattedValue(value: Float): String {
return String.format(Locale.ENGLISH, "%.0f %s", value, unit)
}
}
}
override fun update(filteredSummitEntries: List<Summit>?) {
filteredEntries = filteredSummitEntries as ArrayList<Summit>
selectedDataSpinner()
drawLineChart()
}
private fun setGraphView(dataSet: BarDataSet) {
dataSet.setDrawValues(false)
dataSet.highLightColor = Color.RED
dataSet.colors = SportType.values().map { ContextCompat.getColor(requireContext(), it.color) }
dataSet.stackLabels = SportType.values().map { getString(it.abbreviationStringId) }.toTypedArray()
}
private fun selectedDataSpinner() {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext())
barChart?.axisLeft?.removeAllLimitLines()
val sortedEntries = filteredEntries
sortedEntries?.sortWith(compareBy { it.date })
barChartEntries?.clear()
try {
var annualTarget: Float = when (selectedDataSpinner) {
1 -> {
sharedPreferences.getString("annual_target_km", "1200")?.toFloat() ?: 1200f
}
2 -> {
sharedPreferences.getString("annual_target", "50000")?.toFloat() ?: 50000f
}
else -> {
sharedPreferences.getString("annual_target_activities", "52")?.toFloat() ?: 52f
}
}
if (sortFilterHelper.selectedYear != "") {
annualTarget /= 12f
}
val line1 = LimitLine(annualTarget)
barChart?.axisLeft?.addLimitLine(line1)
barChart?.setSafeZoneColor(ContextCompat.getColor(requireContext(), R.color.red_50), ContextCompat.getColor(requireContext(), R.color.green_50))
when (selectedXAxisSpinner) {
1 -> updateBarChartWithKilometersAsXAxis()
2 -> updateBarChartWithElevationGainAsXAxis()
3 -> updateBarChartWithTopElevationAsXAxis()
else -> updateBarChartWithDateAsXAxis()
}
} catch (e: ParseException) {
e.printStackTrace()
}
}
@Throws(ParseException::class)
private fun updateBarChartWithDateAsXAxis() {
intervallHelper.setSelectedYear(sortFilterHelper.selectedYear)
intervallHelper.calculate()
for (i in 0 until intervallHelper.dates.size - 1) {
val streamSupplier: Supplier<Stream<Summit?>?> = Supplier { getEntriesBetweenDates(filteredEntries, intervallHelper.dates[i], intervallHelper.dates[i + 1]) }
val xValue = intervallHelper.dateAnnotation[i]
when (selectedDataSpinner) {
1 -> {
label = "Kilometers"
unit = "km"
barChartEntries?.add(BarEntry(xValue, getKilometerPerSportType(streamSupplier)))
}
2 -> {
label = "Elevation Gain"
unit = "m"
barChartEntries?.add(BarEntry(xValue, getElevationGainsPerSportType(streamSupplier)))
}
else -> {
label = "Count"
unit = ""
barChartEntries?.add(BarEntry(xValue, getCountsPerSportType(streamSupplier)))
}
}
}
}
@Throws(ParseException::class)
private fun updateBarChartWithElevationGainAsXAxis() {
intervallHelper.calculate()
for (i in 0 until intervallHelper.elevationGains.size - 1) {
val streamSupplier: Supplier<Stream<Summit?>?> = Supplier { getEntriesBetweenElevationGains(filteredEntries, intervallHelper.elevationGains[i], intervallHelper.elevationGains[i + 1]) }
val xValue = intervallHelper.elevationGainAnnotation[i]
when (selectedDataSpinner) {
1 -> {
label = "Kilometers"
unit = "km"
barChartEntries?.add(BarEntry(xValue, getKilometerPerSportType(streamSupplier)))
}
2 -> {
label = "Elevation Gain"
unit = "m"
barChartEntries?.add(BarEntry(xValue, getElevationGainsPerSportType(streamSupplier)))
}
else -> {
label = "Count"
unit = ""
barChartEntries?.add(BarEntry(xValue, getCountsPerSportType(streamSupplier)))
}
}
}
}
@Throws(ParseException::class)
private fun updateBarChartWithKilometersAsXAxis() {
intervallHelper.calculate()
for (i in 0 until intervallHelper.kilometers.size - 1) {
val streamSupplier: Supplier<Stream<Summit?>?> = Supplier { getEntriesBetweenKilometers(filteredEntries, intervallHelper.kilometers[i], intervallHelper.kilometers[i + 1]) }
val xValue = intervallHelper.kilometerAnnotation[i]
when (selectedDataSpinner) {
1 -> {
label = "Kilometers"
unit = "km"
barChartEntries?.add(BarEntry(xValue, getKilometerPerSportType(streamSupplier)))
}
2 -> {
label = "Elevation Gain"
unit = "m"
barChartEntries?.add(BarEntry(xValue, getElevationGainsPerSportType(streamSupplier)))
}
else -> {
label = "Count"
unit = ""
barChartEntries?.add(BarEntry(xValue, getCountsPerSportType(streamSupplier)))
}
}
}
}
@Throws(ParseException::class)
private fun updateBarChartWithTopElevationAsXAxis() {
intervallHelper.calculate()
for (i in 0 until intervallHelper.topElevations.size - 1) {
val streamSupplier: Supplier<Stream<Summit?>?> = Supplier { getEntriesBetweenTopElevation(filteredEntries, intervallHelper.topElevations[i], intervallHelper.topElevations[i + 1]) }
val xValue = intervallHelper.topElevationAnnotation[i]
when (selectedDataSpinner) {
1 -> {
label = "Kilometers"
unit = "km"
barChartEntries?.add(BarEntry(xValue, getKilometerPerSportType(streamSupplier)))
}
2 -> {
label = "Elevation Gain"
unit = "m"
barChartEntries?.add(BarEntry(xValue, getElevationGainsPerSportType(streamSupplier)))
}
else -> {
label = "Count"
unit = ""
barChartEntries?.add(BarEntry(xValue, getCountsPerSportType(streamSupplier)))
}
}
}
}
private fun getCountsPerSportType(entriesSupplier: Supplier<Stream<Summit?>?>): FloatArray {
val list: MutableList<Float> = mutableListOf()
SportType.values().forEach { sportType -> list.add(getCountsFromStream(entriesSupplier.get()?.filter { it?.sportType == sportType })) }
return list.toFloatArray()
}
private fun getKilometerPerSportType(entriesSupplier: Supplier<Stream<Summit?>?>): FloatArray {
val list: MutableList<Float> = mutableListOf()
SportType.values().forEach { sportType -> list.add(getKilometersFromStream(entriesSupplier.get()?.filter { it?.sportType == sportType })) }
return list.toFloatArray()
}
private fun getElevationGainsPerSportType(entriesSupplier: Supplier<Stream<Summit?>?>): FloatArray {
val list: MutableList<Float> = mutableListOf()
SportType.values().forEach { sportType -> list.add(getElevationGainsFromStream(entriesSupplier.get()?.filter { it?.sportType == sportType })) }
return list.toFloatArray()
}
private fun getEntriesBetweenDates(entries: List<Summit>?, start: Date?, end: Date?): Stream<Summit?>? {
return entries
?.stream()
?.filter { o: Summit? -> o?.date?.after(start) ?: false && o?.date?.before(end) ?: false }
}
private fun getEntriesBetweenTopElevation(entries: List<Summit>?, start: Float, end: Float): Stream<Summit?>? {
return entries
?.stream()
?.filter { o: Summit? -> o != null && o.elevationData.maxElevation >= start && o.elevationData.maxElevation < end }
}
private fun getEntriesBetweenElevationGains(entries: List<Summit>?, start: Float, end: Float): Stream<Summit?>? {
return entries
?.stream()
?.filter { o: Summit? -> o != null && o.elevationData.elevationGain >= start && o.elevationData.elevationGain < end }
}
private fun getEntriesBetweenKilometers(entries: List<Summit>?, start: Float, end: Float): Stream<Summit?>? {
return entries
?.stream()
?.filter { o: Summit? -> o != null && o.kilometers >= start && o.kilometers < end }
}
private fun getCountsFromStream(stream: Stream<Summit?>?): Float {
return stream?.count()?.toFloat() ?: 0.0f
}
private fun getKilometersFromStream(stream: Stream<Summit?>?): Float {
return stream
?.mapToInt { o: Summit? -> o?.kilometers?.toInt() ?: 0 }
?.sum()?.toFloat() ?: 0.0f
}
private fun getElevationGainsFromStream(stream: Stream<Summit?>?): Float {
return stream
?.mapToInt { obj: Summit? -> obj?.elevationData?.elevationGain ?: 0 }
?.sum()?.toFloat() ?: 0.0f
}
private fun listenOnDataSpinner() {
dataSpinner?.onItemSelectedListener = object : OnItemSelectedListener {
override fun onItemSelected(adapterView: AdapterView<*>?, view: View?, i: Int, l: Long) {
selectedDataSpinner = i
selectedDataSpinner()
drawLineChart()
}
override fun onNothingSelected(adapterView: AdapterView<*>?) {}
}
xAxisSpinner?.onItemSelectedListener = object : OnItemSelectedListener {
override fun onItemSelected(adapterView: AdapterView<*>?, view: View?, i: Int, l: Long) {
selectedXAxisSpinner = i
selectedDataSpinner()
drawLineChart()
}
override fun onNothingSelected(adapterView: AdapterView<*>?) {}
}
}
private fun fillDateSpinner() {
val dateAdapter = ArrayAdapter(requireContext(),
android.R.layout.simple_spinner_item, ArrayList(listOf(*resources.getStringArray(R.array.bar_chart_spinner))))
dateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
dataSpinner = barChartView?.findViewById(R.id.bar_chart_spinner_data)
dataSpinner?.adapter = dateAdapter
val xAxisAdapter = ArrayAdapter(requireContext(),
android.R.layout.simple_spinner_item, ArrayList(listOf(*resources.getStringArray(R.array.bar_chart_spinner_x_axis))))
dateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
xAxisSpinner = barChartView?.findViewById(R.id.bar_chart_spinner_x_axis)
xAxisSpinner?.adapter = xAxisAdapter
}
inner class CustomMarkerView(context: Context?, layoutResource: Int) : MarkerView(context, layoutResource) {
private val tvContent: TextView? = findViewById(R.id.tvContent)
override fun refreshContent(e: Entry?, highlight: Highlight?) {
try {
val value: String
if (e != null && highlight != null) {
value = when (selectedXAxisSpinner) {
1 -> String.format("%s - %s km", (e.x * IntervalHelper.kilometersStep).toInt(), ((e.x + 1) * IntervalHelper.kilometersStep).toInt())
2 -> String.format("%s - %s m", (e.x * IntervalHelper.elevationGainStep).toInt(), ((e.x + 1) * IntervalHelper.elevationGainStep).toInt())
3 -> String.format("%s - %s m", (e.x * IntervalHelper.topElevationStep).toInt(), ((e.x + 1) * IntervalHelper.topElevationStep).toInt())
else -> if (e.x > 12 || sortFilterHelper.selectedYear == "") String.format("%s", e.x.toInt()) else String.format("%s %s", Month.of(e.x.toInt()), sortFilterHelper.selectedYear)
}
val selectedValue = (e as BarEntry).yVals[highlight.stackIndex].toInt()
val unitString = if (unit == "") "" else " $unit"
if (selectedValue == 0) {
tvContent?.text = String.format("%s%s\n%s", e.getY().toInt(), unitString, value)
} else {
tvContent?.text = String.format("%s/%s%s\n%s\n%s", selectedValue, e.getY().toInt(), unitString, value, SportType.values()[highlight.stackIndex].name)
}
}
} catch (ex: Exception) {
ex.printStackTrace()
}
}
override fun getOffset(): MPPointF {
return MPPointF(-(width / 2f), (-height).toFloat())
}
}
}
| 0 |
Kotlin
|
0
| 0 |
dae46b5b9781c06cc2c7a47a107c05a8fe0e05d3
| 18,746 |
summitbook
|
MIT License
|
virtualjoystick/src/main/java/com/yoimerdr/android/virtualjoystick/control/Control.kt
|
yoimerdr
| 752,392,779 | false |
{"Kotlin": 112504, "CSS": 2645}
|
package com.yoimerdr.android.virtualjoystick.control
import android.graphics.Canvas
import android.graphics.Color
import androidx.annotation.ColorInt
import com.yoimerdr.android.virtualjoystick.control.drawer.ArcControlDrawer
import com.yoimerdr.android.virtualjoystick.control.drawer.CircleControlDrawer
import com.yoimerdr.android.virtualjoystick.control.drawer.ControlDrawer
import com.yoimerdr.android.virtualjoystick.exceptions.InvalidControlPositionException
import com.yoimerdr.android.virtualjoystick.geometry.Circle
import com.yoimerdr.android.virtualjoystick.geometry.ImmutablePosition
import com.yoimerdr.android.virtualjoystick.geometry.MutablePosition
import com.yoimerdr.android.virtualjoystick.geometry.Plane
import com.yoimerdr.android.virtualjoystick.geometry.Position
import com.yoimerdr.android.virtualjoystick.geometry.Size
import com.yoimerdr.android.virtualjoystick.theme.ColorsScheme
import com.yoimerdr.android.virtualjoystick.views.JoystickView
import com.yoimerdr.android.virtualjoystick.views.JoystickView.Direction
import com.yoimerdr.android.virtualjoystick.views.JoystickView.DirectionType
/**
* Represents a virtual joystick control.
*
* Custom control must inherit from this class.
*/
abstract class Control(
invalidRadius: Float,
/**
* The control directions type.
*
* Used to determine how many directions, in addition to [Direction.NONE],
* will be taken into account when calling [direction].
*/
var directionType: DirectionType
) {
/**
* The control position.
*/
private val mPosition: MutablePosition
/**
* The center of the view.
*/
private val mCenter: MutablePosition
/**
* Circle representing the area of the view where the control is used.
*/
private val viewCircle: Circle
/**
* Invalid radius to be taken into account when obtaining control direction.
*
* @see [Control.direction]
*/
var invalidRadius: Float = invalidRadius
set(value) {
field = value
validateInvalidRadius()
}
/**
* The control drawer.
*
* Must be initialized in classes that inherit from [Control].
*/
abstract var drawer: ControlDrawer
init {
mCenter = Position()
mPosition = Position()
viewCircle = Circle(1f, mCenter)
validateInvalidRadius()
}
enum class DefaultType(val id: Int) {
CIRCLE(0),
ARC(1),
CIRCLE_ARC(2);
companion object {
/**
* @param id The id for the enum value
* @return The enum value for the given id. If not found, returns the value [CIRCLE].
*/
@JvmStatic
fun fromId(id: Int): Control.DefaultType {
for(type in entries)
if(type.id == id)
return type
return CIRCLE
}
}
}
/**
* A builder class to build a control for the default ones.
*
* @see [ArcControl]
* @see [CircleControl]
* @see [CircleArcControl]
*/
class Builder {
private val colors: ColorsScheme = ColorsScheme(Color.RED, Color.WHITE)
private var type: Control.DefaultType = Control.DefaultType.CIRCLE
private var directionType: JoystickView.DirectionType = JoystickView.DirectionType.COMPLETE
private var invalidRadius: Float = 70f
// for arc type
private var arcStrokeWidth: Float = 13f
private var arcSweepAngle: Float = 90f
// for circle type
private var circleRadiusRatio: Float = 0.25f
fun primaryColor(@ColorInt color: Int): Builder {
colors.primary = color
return this
}
fun accentColor(@ColorInt color: Int): Builder {
colors.accent = color
return this
}
fun colors(@ColorInt primary: Int, @ColorInt accent: Int): Builder {
return primaryColor(primary)
.accentColor(accent)
}
fun colors(scheme: ColorsScheme): Builder {
return colors(scheme.primary, scheme.accent)
}
fun invalidRadius(radius: Float): Builder {
invalidRadius = radius
return this
}
fun invalidRadius(radius: Double): Builder = invalidRadius(radius.toFloat())
fun arcStrokeWidth(width: Float): Builder {
arcStrokeWidth = ArcControlDrawer.getStrokeWidth(width)
return this
}
fun arcStrokeWidth(width: Double) = arcStrokeWidth(width.toFloat())
fun arcStrokeWidth(width: Int) = arcStrokeWidth(width.toFloat())
fun arcSweepAngle(angle: Float): Builder {
arcSweepAngle = ArcControlDrawer.getSweepAngle(angle)
return this
}
fun arcSweepAngle(angle: Double) = arcSweepAngle(angle.toFloat())
fun arcSweepAngle(angle: Int) = arcSweepAngle(angle.toFloat())
fun circleRadiusRatio(ratio: Float): Builder {
circleRadiusRatio = CircleControlDrawer.getRadiusRatio(ratio)
return this
}
fun circleRadiusRatio(ratio: Double) = circleRadiusRatio(ratio.toFloat())
fun type(type: Control.DefaultType): Builder {
this.type = type
return this
}
fun directionType(type: JoystickView.DirectionType): Builder {
this.directionType = type
return this
}
fun build(): Control {
return when (type) {
Control.DefaultType.ARC -> ArcControl(
colors,
invalidRadius,
directionType,
arcStrokeWidth,
arcSweepAngle
)
Control.DefaultType.CIRCLE_ARC -> CircleArcControl(
colors,
invalidRadius,
directionType,
arcStrokeWidth,
arcSweepAngle,
circleRadiusRatio
)
Control.DefaultType.CIRCLE -> CircleControl(
colors,
invalidRadius,
directionType,
circleRadiusRatio
)
}
}
}
/**
* Gets the direction to which the control is pointing.
* It is based on the [anglePosition] value, but if [distanceFromCenter] is less than [invalidRadius], the
* direction is considered as [Direction.NONE].
*
* @return A [Direction] enum representing the direction.
*
* If [directionType] is [DirectionType.SIMPLE] possible values are:
* [Direction.NONE], [Direction.LEFT], [Direction.RIGHT],
* [Direction.UP] and [Direction.DOWN].
*
* Otherwise, possible values are all [Direction] enum entries.
*/
open val direction: Direction
get() {
if (distanceFromCenter <= invalidRadius)
return Direction.NONE
val angleDegrees = Math.toDegrees(anglePosition)
if(directionType == DirectionType.COMPLETE)
return when(Plane.quadrantOf(angleDegrees, Plane.MaxQuadrants.EIGHT,true)) {
1 -> Direction.RIGHT
2 -> Direction.DOWN_RIGHT
3 -> Direction.DOWN
4 -> Direction.DOWN_LEFT
5 -> Direction.LEFT
6 -> Direction.UP_LEFT
7 -> Direction.UP
8 -> Direction.UP_RIGHT
else -> Direction.NONE
}
return when(Plane.quadrantOf(angleDegrees, true)) {
1 -> Direction.RIGHT
2 -> Direction.DOWN
3 -> Direction.LEFT
4 -> Direction.UP
else -> Direction.NONE
}
}
/**
* Gets the immutable position of control center.
*
* @return A new instance of the control center as [ImmutablePosition].
*/
val center: ImmutablePosition get() = mCenter.toImmutable()
/**
* Gets the immutable position of control position.
*
* @return A new instance of the control position as [ImmutablePosition].
*/
open val position: ImmutablePosition get() = mPosition.toImmutable()
/**
* Calculates the distance between current position and center.
* @return The calculated distance.
*/
val distanceFromCenter: Float get() = viewCircle.distanceTo(mPosition)
/**
* Calculates the angle (clockwise) formed from the current position and center.
* @return A value in the range from 0 to 2PI radians.
*/
val anglePosition: Double get() = viewCircle.angleTo(mPosition)
/**
* Gets the parametric position of current position in the view circle.
*
* @return A new instance of the parametric position.
*/
val viewParametricPosition: ImmutablePosition get() = viewCircle.parametricPositionOf(anglePosition)
/**
* Gets the radius of the view where the control is used.
*/
val viewRadius: Double get() = viewCircle.radius
/**
* Validates the control position values.
*
* @throws InvalidControlPositionException If any of the position coordinates is negative.
*/
@Throws(InvalidControlPositionException::class)
protected fun validatePositionValues() {
if(mPosition.x < 0 || mPosition.y < 0)
throw InvalidControlPositionException()
}
/**
* Validates the [invalidRadius] value.
*
* @throws IllegalArgumentException If [invalidRadius] value is negative.
*/
@Throws(IllegalArgumentException::class)
private fun validateInvalidRadius() {
if(invalidRadius < 0)
throw IllegalArgumentException("Invalid radius value must be positive.")
}
/**
* Checks if [distanceFromCenter] is greater than the [viewRadius].
* If so, changes the position to the [viewParametricPosition].
*/
private fun validatePositionLimits() {
if (distanceFromCenter > viewRadius)
mPosition.set(viewParametricPosition)
}
/**
* Called (or call it) when the size of the view changes.
*
* It updates the drawer position and center.
* @param size The size of the view.
* @throws InvalidControlPositionException If any of the position coordinates is negative.
*/
@Throws(InvalidControlPositionException::class)
fun onSizeChanged(size: Size) {
size.apply {
(width.coerceAtMost(height) / 2f).also {
mCenter.set(it, it)
viewCircle.radius = it.toDouble()
toCenter()
}
}
}
/**
* Method to draw the control using the [drawer].
* @param canvas The canvas on which the control will be drawn
*
*/
open fun onDraw(canvas: Canvas) {
drawer.draw(canvas, this)
}
/**
* Sets the current position of the control.
*
* @param position The new position to be assigned.
* @throws InvalidControlPositionException If any of the position coordinates is negative.
*/
@Throws(InvalidControlPositionException::class)
fun setPosition(position: ImmutablePosition) {
position.apply {
setPosition(x, y)
}
}
/**
* Sets the current position of the control.
*
* @param x The x coordinate to be assigned.
* @param y The y coordinate to be assigned.
*
* @throws InvalidControlPositionException If any of the position coordinates is negative.
*/
@Throws(InvalidControlPositionException::class)
fun setPosition(x: Float, y: Float) {
mPosition.set(x, y)
validatePositionLimits()
validatePositionValues()
}
/**
* Sets the current position to center.
* @throws InvalidControlPositionException If any of the position coordinates is negative.
*/
@Throws(InvalidControlPositionException::class)
fun toCenter() = setPosition(mCenter)
/**
* Checks if current position is an the same center coordinates.
*
* @return True if is position is equals to center; otherwise, false.
*/
fun isInCenter(): Boolean = mPosition == mCenter
/**
* Calculates the difference in the x-coordinate between the current position and the center.
* @return The calculated difference.
*/
protected fun deltaX(): Float = mPosition.deltaX(mCenter)
/**
* Calculates the difference in the y-coordinate between the current position and the center.
* @return The calculated difference.
*/
protected fun deltaY(): Float = mPosition.deltaY(mCenter)
}
| 0 |
Kotlin
|
0
| 0 |
1ede27026dae3058a37b52ce6fc91272441fb601
| 12,738 |
AndroidVirtualJoystick
|
Apache License 2.0
|
src/main/kotlin/no/nav/helse/fritakagp/koin/Fakes.kt
|
navikt
| 301,987,870 | false |
{"Kotlin": 462281, "Shell": 618, "Dockerfile": 297}
|
package no.nav.helse.fritakagp.koin
import io.mockk.coEvery
import io.mockk.mockk
import kotlinx.serialization.json.Json
import no.nav.helse.arbeidsgiver.integrasjoner.oppgave2.OppgaveKlient
import no.nav.helse.arbeidsgiver.integrasjoner.oppgave2.OppgaveResponse
import no.nav.helse.arbeidsgiver.integrasjoner.oppgave2.OpprettOppgaveRequest
import no.nav.helse.arbeidsgiver.integrasjoner.oppgave2.OpprettOppgaveResponse
import no.nav.helse.arbeidsgiver.integrasjoner.oppgave2.Prioritet
import no.nav.helse.arbeidsgiver.integrasjoner.oppgave2.Status
import no.nav.helse.arbeidsgiver.utils.loadFromResources
import no.nav.helse.fritakagp.integration.brreg.BrregClient
import no.nav.helse.fritakagp.integration.brreg.MockBrregClient
import no.nav.helse.fritakagp.integration.gcp.BucketStorage
import no.nav.helse.fritakagp.integration.gcp.MockBucketStorage
import no.nav.helse.fritakagp.integration.kafka.BrukernotifikasjonBeskjedSender
import no.nav.helse.fritakagp.integration.kafka.MockBrukernotifikasjonBeskjedSender
import no.nav.helse.fritakagp.integration.virusscan.MockVirusScanner
import no.nav.helse.fritakagp.integration.virusscan.VirusScanner
import no.nav.helse.fritakagp.processing.arbeidsgivernotifikasjon.ArbeidsgiverOppdaterNotifikasjonProcessor
import no.nav.helsearbeidsgiver.aareg.AaregClient
import no.nav.helsearbeidsgiver.aareg.Ansettelsesperiode
import no.nav.helsearbeidsgiver.aareg.Arbeidsforhold
import no.nav.helsearbeidsgiver.aareg.Arbeidsgiver
import no.nav.helsearbeidsgiver.aareg.Opplysningspliktig
import no.nav.helsearbeidsgiver.aareg.Periode
import no.nav.helsearbeidsgiver.altinn.AltinnClient
import no.nav.helsearbeidsgiver.altinn.AltinnOrganisasjon
import no.nav.helsearbeidsgiver.dokarkiv.DokArkivClient
import no.nav.helsearbeidsgiver.pdl.PdlClient
import no.nav.helsearbeidsgiver.pdl.domene.FullPerson
import no.nav.helsearbeidsgiver.pdl.domene.PersonNavn
import no.nav.helsearbeidsgiver.tokenprovider.AccessTokenProvider
import org.koin.core.module.Module
import org.koin.core.qualifier.named
import org.koin.dsl.bind
import java.time.LocalDate
import java.time.LocalDateTime
fun Module.mockExternalDependecies() {
single {
mockk<AltinnClient> {
val json = Json { ignoreUnknownKeys = true }
val jsonFile = "altinn-mock/organisasjoner-med-rettighet.json".loadFromResources()
val altinnOrganisasjons = json.decodeFromString<List<AltinnOrganisasjon>>(jsonFile).toSet()
coEvery { hentRettighetOrganisasjoner(any()) } returns altinnOrganisasjons
coEvery { harRettighetForOrganisasjon(any(), any()) } answers {
val organisasjonsNr = secondArg<String>()
altinnOrganisasjons.any {
it.orgnr == organisasjonsNr && it.orgnrHovedenhet != null
}
}
}
}
single { MockBrukernotifikasjonBeskjedSender() } bind BrukernotifikasjonBeskjedSender::class
single(named("TOKENPROVIDER")) {
object : AccessTokenProvider {
override fun getToken(): String {
return "fake token"
}
}
} bind AccessTokenProvider::class
single {
mockk<AaregClient> {
coEvery { hentArbeidsforhold(any(), any()) } returns listOf(
Arbeidsforhold(
Arbeidsgiver("test", "810007842"),
Opplysningspliktig("Juice", "810007702"),
emptyList(),
Ansettelsesperiode(
Periode(LocalDate.MIN, null)
),
LocalDate.MIN.atStartOfDay()
),
Arbeidsforhold(
Arbeidsgiver("test", "910098896"),
Opplysningspliktig("Juice", "910098896"),
emptyList(),
Ansettelsesperiode(
Periode(
LocalDate.MIN,
null
)
),
LocalDate.MIN.atStartOfDay()
),
Arbeidsforhold(
Arbeidsgiver("test", "917404437"),
Opplysningspliktig("Juice", "910098896"),
emptyList(),
Ansettelsesperiode(
Periode(
LocalDate.MIN,
null
)
),
LocalDate.MIN.atStartOfDay()
)
)
}
}
single {
val tokenProvider: AccessTokenProvider = get(qualifier = named("TOKENPROVIDER"))
DokArkivClient("url", 3, tokenProvider::getToken)
} bind DokArkivClient::class
single {
mockk<PdlClient> {
coEvery { personNavn(any()) } returns PersonNavn("Ola", "M", "Avsender")
coEvery { fullPerson(any()) } returns FullPerson(
navn = PersonNavn(fornavn = "Per", mellomnavn = "", etternavn = "Ulv"),
foedselsdato = LocalDate.of(1900, 1, 1),
ident = "aktør-id",
diskresjonskode = "SPSF",
geografiskTilknytning = "SWE"
)
}
}
single {
object : OppgaveKlient {
override suspend fun hentOppgave(oppgaveId: Int, callId: String): OppgaveResponse {
return OppgaveResponse(oppgaveId, 1, oppgavetype = "JFR", aktivDato = LocalDateTime.now().minusDays(3).toLocalDate(), prioritet = Prioritet.NORM.toString())
}
override suspend fun opprettOppgave(
opprettOppgaveRequest: OpprettOppgaveRequest,
callId: String
): OpprettOppgaveResponse = OpprettOppgaveResponse(
1234,
"0100",
tema = "KON",
oppgavetype = "JFR",
versjon = 1,
aktivDato = LocalDate.now(),
Prioritet.NORM,
Status.UNDER_BEHANDLING
)
}
} bind OppgaveKlient::class
single { MockVirusScanner() } bind VirusScanner::class
single { MockBucketStorage() } bind BucketStorage::class
single { MockBrregClient() } bind BrregClient::class
single { mockk<ArbeidsgiverOppdaterNotifikasjonProcessor>(relaxed = true) }
}
| 14 |
Kotlin
|
0
| 0 |
8db3e65b10346567ea689444b60318ee0ced2096
| 6,364 |
fritakagp
|
MIT License
|
place-service/src/main/kotlin/de/clines/places/models/Location.kt
|
d-stoll
| 239,963,269 | false | null |
package de.clines.places.models
import com.google.maps.model.LatLng
data class Location(
val latitude: Double,
val longitude: Double
){
fun toLatLng() = LatLng(latitude, longitude)
}
fun LatLng.toLocation() = Location(lat, lng)
| 0 |
Kotlin
|
0
| 2 |
4fff166b17c2b7fd0adf3117fded94d6ecc58af5
| 250 |
citymatch
|
Apache License 2.0
|
exe-base/src/main/kotlin/com/fleshgrinder/gradle/exe/ExeExtension.kt
|
Fleshgrinder
| 342,896,486 | false | null |
package com.fleshgrinder.gradle.exe
import com.fleshgrinder.platform.Arch
import com.fleshgrinder.platform.Env
import com.fleshgrinder.platform.Os
import com.fleshgrinder.platform.Platform
import org.gradle.api.plugins.ExtensionAware
import org.gradle.api.provider.Provider
public interface ExeExtension : ExtensionAware {
/** @see Arch.parse */
public fun arch(value: Any): Arch =
Arch.parse(value.toString())
/** @see Arch.parse */
public fun arch(value: Provider<out Any>): Provider<Arch> =
value.map(::arch)
/** @see Env.parse */
public fun env(value: Any): Env =
Env.parse(value.toString())
/** @see Env.parse */
public fun env(value: Provider<out Any>): Provider<Env> =
value.map(::env)
/** @see Os.parse */
public fun os(value: Any): Os =
Os.parse(value.toString())
/** @see Os.parse */
public fun os(value: Provider<out Any>): Provider<Os> =
value.map(this::os)
/** @see Platform.parse */
public fun platform(value: Any): Platform =
Platform.parse(value.toString())
/** @see Platform.parse */
public fun platform(value: Provider<out Any>): Provider<Platform> =
value.map(::platform)
}
| 0 |
Kotlin
|
0
| 0 |
f27d62417b46eba07d09418334fc0864569b6a11
| 1,230 |
gradle-exe-plugin
|
The Unlicense
|
structures/src/commonMain/kotlin/com/inkapplications/telegram/structures/Audio.kt
|
InkApplications
| 511,871,853 | false | null |
package com.inkapplications.telegram.structures
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlin.time.Duration
/**
* This object represents an audio file to be treated as music by the
* Telegram clients.
*/
@Serializable
data class Audio(
/**
* Identifier for this file, which can be used to download or reuse the file
*/
@SerialName("file_id")
val fileId: String,
/**
* Unique identifier for this file, which is supposed to be the same
* over time and for different bots.
*
* Can't be used to download or reuse the file.
*/
@SerialName("file_unique_id")
val fileUid: String,
/**
* Duration of the audio in seconds as defined by sender
*/
@Serializable(with = IntSecondsDurationSerializer::class)
val duration: Duration,
/**
* Optional. Performer of the audio as defined by sender or by audio tags
*/
val performer: String? = null,
/**
* Optional. Title of the audio as defined by sender or by audio tags
*/
val title: String? = null,
/**
* Optional. Original filename as defined by sender
*/
@SerialName("file_name")
val fileName: String? = null,
/**
* Optional. MIME type of the file as defined by sender
*/
@SerialName("mime_type")
val mimeType: MimeType? = null,
/**
* Optional. File size in bytes
*/
@SerialName("file_size")
val fileSize: Long? = null,
/**
* Optional. Thumbnail of the album cover to which the music file belongs
*/
@SerialName("thumb")
val thumbnail: PhotoSize? = null,
)
| 0 |
Kotlin
|
0
| 0 |
5cda3570ce2ae4a9bf1f33acbbf8787fc5c95510
| 1,660 |
telegram-kotlin-sdk
|
MIT License
|
modules/core/src/main/java/de/deutschebahn/bahnhoflive/backend/db/ris/model/LocalService.kt
|
dbbahnhoflive
| 267,806,942 | false | null |
package de.deutschebahn.bahnhoflive.backend.db.ris.model
import de.deutschebahn.bahnhoflive.backend.local.model.DailyOpeningHours
import de.deutschebahn.bahnhoflive.backend.local.model.ServiceContentType
class LocalService {
var description: String? = null
var localServiceID: String? = null
var stationID: String? = null
var type: String? = null
var address: AddressWithWeb? = null
var openingHours: String? = null
var parsedOpeningHours: List<DailyOpeningHours>? = null
var contact: Contact? = null
var validFrom: String? = null
var validTo: String? = null
var position: Coordinate2D? = null
val location by lazy {
position?.toLatLng()
}
enum class Type(
val tag: String,
val serviceContentTypeKey: String = tag,
) {
/**
* Informationsstand für Belange im Bahnhof (kein Fahrkartenverkauf)
**/
INFORMATION_COUNTER("INFORMATION_COUNTER", ServiceContentType.DB_INFORMATION),
/**
* Reisezentrum
**/
TRAVEL_CENTER("TRAVEL_CENTER"),
/**
* Video Reisezentrum
**/
VIDEO_TRAVEL_CENTER("VIDEO_TRAVEL_CENTER"),
/**
* 3S Zentrale für Service, Sicherheit & Sauberkeit
**/
TRIPLE_S_CENTER("TRIPLE_S_CENTER"),
/**
* Lounge (DB Lounge z.B.)
**/
TRAVEL_LOUNGE(
"TRAVEL_LOUNGE", ServiceContentType.Local.DB_LOUNGE
),
/**
* Fundbüro
**/
LOST_PROPERTY_OFFICE("LOST_PROPERTY_OFFICE", ServiceContentType.Local.LOST_AND_FOUND),
/**
* Bahnhofsmission
**/
RAILWAY_MISSION(
"RAILWAY_MISSION", ServiceContentType.BAHNHOFSMISSION
),
/**
* Service für mobilitätseingeschränkte Reisende
**/
HANDICAPPED_TRAVELLER_SERVICE(
"HANDICAPPED_TRAVELLER_SERVICE",
ServiceContentType.MOBILITY_SERVICE
),
/**
* Schließfächer
**/
LOCKER("LOCKER"),
/**
* WLan
**/
WIFI("WIFI"),
/**
* Autoparkplatz, ggf. kostenpflichtig
**/
CAR_PARKING("CAR_PARKING"),
/**
* Fahrradparkplätze, ggf. kostenpflichtig
**/
BICYCLE_PARKING("BICYCLE_PARKING"),
/**
* Öffentliches WC, ggf. kostenpflichtig
**/
PUBLIC_RESTROOM("PUBLIC_RESTROOM"),
/**
* Geschäft für den Reisendenbedarf
**/
TRAVEL_NECESSITIES("TRAVEL_NECESSITIES"),
/**
* Car-Sharer oder Mietwagen
**/
CAR_RENTAL("CAR_RENTAL"),
/**
* Mieträder
**/
BICYCLE_RENTAL("BICYCLE_RENTAL"),
/**
* Taxi Stand
**/
TAXI_RANK("TAXI_RANK"),
MOBILE_TRAVEL_SERVICE("MOBILE_TRAVEL_SERVICE", ServiceContentType.MOBILE_SERVICE);
}
}
| 0 |
Kotlin
|
4
| 33 |
3f453685d33215dbc6e9d289ce925ac430550f32
| 2,993 |
dbbahnhoflive-android
|
Apache License 2.0
|
src/main/kotlin/com/simonorono/aoc2015/solutions/Day01.kt
|
simonorono
| 662,846,819 | false |
{"Kotlin": 19391}
|
package com.simonorono.aoc2015.solutions
import com.simonorono.aoc2015.lib.Day
object Day01 : Day(1) {
private val input = getInput()
override fun part1(): String {
var position = 0
for (c in input) {
when (c) {
'(' -> position++
')' -> position--
else -> {}
}
}
return position.toString()
}
override fun part2(): String {
var position = 0
for (c in input.withIndex()) {
when (c.value) {
'(' -> position++
')' -> position--
else -> {}
}
if (position == -1) {
return "${c.index + 1}"
}
}
throw IllegalStateException()
}
}
| 0 |
Kotlin
|
0
| 0 |
783938b4e17b55aa2d7ac957aa98f94380deaee7
| 797 |
aoc2015
|
MIT License
|
app/src/main/java/com/example/mozzartkino/presentation/fragments/WebClientFragment.kt
|
milosursulovic
| 564,806,180 | false |
{"Kotlin": 53750}
|
package com.example.mozzartkino.presentation.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebViewClient
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.navArgs
import com.example.mozzartkino.R
import com.example.mozzartkino.databinding.FragmentWebClientBinding
class WebClientFragment : Fragment() {
private lateinit var binding: FragmentWebClientBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_web_client, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentWebClientBinding.bind(view)
val args: WebClientFragmentArgs by navArgs()
val url = args.url
binding.wvInfo.run {
webViewClient = WebViewClient()
if (url != "") {
loadUrl(url)
}
}
}
}
| 0 |
Kotlin
|
0
| 0 |
f7b88b589706c72c9732b8562eb4aa224b1733cb
| 1,190 |
kino-draws
|
MIT License
|
src/main/kotlin/com/svick/brz/currencyconverter/config/exception/error/DuplicateResourceException.kt
|
souvik-brz
| 857,741,016 | false |
{"Kotlin": 39693, "Shell": 924}
|
package com.svick.brz.currencyconverter.config.exception.error
internal class DuplicateResourceException(message: String, cause: Throwable? = null) : RuntimeException(message, cause)
| 0 |
Kotlin
|
0
| 0 |
44a562a83265da93ced6b6f008945c3408e2dc45
| 183 |
currency-converter-service
|
Apache License 2.0
|
idea/tests/testData/inspectionsLocal/removeRedundantSpreadOperator/intArrayOfWithoutArguments.kt
|
JetBrains
| 278,369,660 | false | null |
fun foo(vararg args: Int) {}
fun test() {
foo(<caret>*intArrayOf())
}
| 0 |
Kotlin
|
30
| 82 |
cc81d7505bc3e9ad503d706998ae8026c067e838
| 74 |
intellij-kotlin
|
Apache License 2.0
|
domain/src/main/java/com/nemesis/rio/domain/mplus/ranks/MythicPlusRanksScope.kt
|
N3-M3-S1S
| 370,791,918 | false | null |
package com.nemesis.rio.domain.mplus.ranks
enum class MythicPlusRanksScope {
GLOBAL, FACTION
}
| 0 |
Kotlin
|
0
| 0 |
62dc309a7b4b80ff36ea624bacfa7b00b5d8607e
| 100 |
rio
|
MIT License
|
app/src/main/java/com/espressif/ui/fragments/SignUpFragment.kt
|
espressif
| 267,619,801 | false |
{"Java": 1742083, "Kotlin": 313057}
|
// Copyright 2023 Espressif Systems (Shanghai) PTE LTD
//
// 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.espressif.ui.fragments
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextPaint
import android.text.TextUtils
import android.text.TextWatcher
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.espressif.AppConstants
import com.espressif.cloudapi.ApiManager
import com.espressif.cloudapi.ApiResponseListener
import com.espressif.cloudapi.CloudException
import com.espressif.rainmaker.BuildConfig
import com.espressif.rainmaker.R
import com.espressif.rainmaker.databinding.FragmentSignupBinding
import com.espressif.ui.Utils
import com.espressif.ui.activities.MainActivity
import com.espressif.ui.user_module.SignUpConfirmActivity
class SignUpFragment : Fragment(R.layout.fragment_signup) {
private var _binding: FragmentSignupBinding? = null
// This property is only valid between onCreateView and onDestroyView.
private val binding get() = _binding!!
private var email: String? = null
private var password: String? = null
private var confirmPassword: String? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentSignupBinding.inflate(inflater, container, false)
val view = binding.root
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initViews()
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun initViews() {
enableRegisterButton()
setupLinks()
binding.etEmail.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable) {
email = s.toString()
enableRegisterButton()
}
})
binding.etPassword.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable) {
password = <PASSWORD>
enableRegisterButton()
}
})
binding.etConfirmPassword.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable) {
confirmPassword = <PASSWORD>
enableRegisterButton()
}
})
binding.etConfirmPassword.setOnEditorActionListener(TextView.OnEditorActionListener { v, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_GO) {
if (binding.checkboxTermsCondition.isChecked) {
doSignUp()
} else {
binding.checkboxTermsCondition.isChecked = true
}
}
false
})
binding.btnRegister.layoutBtn.setOnClickListener { doSignUp() }
}
private fun setupLinks() {
val privacyPolicyClick: ClickableSpan = object : ClickableSpan() {
override fun onClick(textView: View) {
textView.invalidate()
val openURL = Intent(Intent.ACTION_VIEW, Uri.parse(BuildConfig.PRIVACY_URL))
startActivity(openURL)
}
override fun updateDrawState(ds: TextPaint) {
super.updateDrawState(ds)
ds.color = resources.getColor(R.color.colorPrimary)
ds.isUnderlineText = true
}
}
val termsOfUseClick: ClickableSpan = object : ClickableSpan() {
override fun onClick(textView: View) {
textView.invalidate()
val openURL = Intent(Intent.ACTION_VIEW, Uri.parse(BuildConfig.TERMS_URL))
startActivity(openURL)
}
override fun updateDrawState(ds: TextPaint) {
super.updateDrawState(ds)
ds.color = resources.getColor(R.color.colorPrimary)
ds.isUnderlineText = true
}
}
val stringForPolicy = SpannableString(getString(R.string.user_agreement))
stringForPolicy.setSpan(privacyPolicyClick, 83, 97, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
stringForPolicy.setSpan(termsOfUseClick, 102, 114, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
binding.tvTermsCondition.text = stringForPolicy
binding.tvTermsCondition.movementMethod = LinkMovementMethod.getInstance()
}
private fun doSignUp() {
binding.etEmail.error = null
binding.layoutPassword.error = null
binding.layoutConfirmPassword.error = null
email = binding.etEmail.text.toString()
if (TextUtils.isEmpty(email)) {
binding.etEmail.error = getString(R.string.error_username_empty)
return
} else if (!Utils.isValidEmail(email)) {
binding.etEmail.error = getString(R.string.error_invalid_email)
return
}
password = binding.etPassword.getText().toString()
if (TextUtils.isEmpty(password)) {
binding.layoutPassword.error = getString(R.string.error_password_empty)
return
}
confirmPassword = binding.etConfirmPassword.getText().toString()
if (TextUtils.isEmpty(confirmPassword)) {
binding.layoutConfirmPassword.error = getString(R.string.error_confirm_password_empty)
return
}
if (password != confirmPassword) {
binding.layoutConfirmPassword.error = getString(R.string.error_password_not_matched)
return
}
if (!binding.checkboxTermsCondition.isChecked) {
Toast.makeText(activity, R.string.error_user_agreement, Toast.LENGTH_SHORT).show()
return
}
showLoading()
val apiManager = ApiManager.getInstance(activity)
apiManager.createUser(email, password, object : ApiResponseListener {
override fun onSuccess(data: Bundle?) {
hideLoading()
confirmSignUp(email!!, password!!)
}
override fun onResponseFailure(exception: Exception) {
hideLoading()
if (exception is CloudException) {
Utils.showAlertDialog(
activity,
getString(R.string.dialog_title_sign_up_failed),
exception.message,
false
)
} else {
Utils.showAlertDialog(
activity,
"",
getString(R.string.dialog_title_sign_up_failed),
false
)
}
}
override fun onNetworkFailure(exception: Exception) {
hideLoading()
Utils.showAlertDialog(
activity,
getString(R.string.dialog_title_no_network),
getString(R.string.dialog_msg_no_network),
false
)
}
})
}
private fun confirmSignUp(email: String, password: String) {
val intent = Intent(activity, SignUpConfirmActivity::class.java).also {
it.putExtra(AppConstants.KEY_USER_NAME, email)
it.putExtra(AppConstants.KEY_PASSWORD, <PASSWORD>)
}
try {
requireActivity().startActivityForResult(
intent,
MainActivity.SIGN_UP_CONFIRM_ACTIVITY_REQUEST
)
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun enableRegisterButton() {
if (TextUtils.isEmpty(email)
|| TextUtils.isEmpty(password)
|| TextUtils.isEmpty(
confirmPassword
)
) {
binding.btnRegister.layoutBtn.isEnabled = false
binding.btnRegister.layoutBtn.alpha = 0.5f
} else {
binding.btnRegister.layoutBtn.isEnabled = true
binding.btnRegister.layoutBtn.alpha = 1f
}
}
private fun showLoading() {
binding.btnRegister.layoutBtn.isEnabled = false
binding.btnRegister.layoutBtn.alpha = 0.5f
binding.btnRegister.textBtn.text = getString(R.string.btn_registering)
binding.btnRegister.progressIndicator.visibility = View.VISIBLE
binding.btnRegister.ivArrow.visibility = View.GONE
}
private fun hideLoading() {
binding.btnRegister.layoutBtn.isEnabled = true
binding.btnRegister.layoutBtn.alpha = 1f
binding.btnRegister.textBtn.text = getString(R.string.btn_register)
binding.btnRegister.progressIndicator.visibility = View.GONE
binding.btnRegister.ivArrow.visibility = View.VISIBLE
}
}
| 17 |
Java
|
58
| 98 |
d1a4a67e57cbca8ace6cb978bd9018fbd405a914
| 10,370 |
esp-rainmaker-android
|
Apache License 2.0
|
app/src/main/java/com/nvkhang96/dictionary/feature_dictionary/domain/model/Meaning.kt
|
nvkhang96
| 622,523,099 | false | null |
package com.nvkhang96.dictionary.feature_dictionary.domain.model
data class Meaning(
val definitions: List<Definition>,
val partOfSpeech: String,
)
| 0 |
Kotlin
|
0
| 0 |
a9ac63994444ed75308a86e73aac0f731257ec33
| 156 |
Dictionary
|
MIT License
|
contract/abi/src/main/kotlin/com/github/jyc228/keth/solidity/Codec.kt
|
jyc228
| 833,953,853 | false |
{"Kotlin": 217816, "Solidity": 5515}
|
package com.github.jyc228.keth.solidity
import java.math.BigInteger
import java.nio.ByteBuffer
import kotlin.math.ceil
sealed interface Codec {
fun computeEncodeSize(type: Type, data: Any?): Int
fun encode(type: Type, data: Any?, buffer: ByteBuffer)
fun decode(type: Type, context: DecodingContext): Any
@OptIn(ExperimentalStdlibApi::class)
class DecodingContext(
internal val buffer: ByteBuffer,
val primitiveValueConverter: Map<String, (Any) -> Any>
) {
constructor(
hex: String,
primitiveValueConverter: Map<String, (Any) -> Any>
) : this(ByteBuffer.wrap(hex.removePrefix("0x").hexToByteArray()), primitiveValueConverter)
fun read(size: Int) = ByteArray(size).also { buffer.get(it) }
fun readHexString(size: Int) = ByteArray(size).also { buffer.get(it) }.toHexString()
fun read() = buffer.get()
fun skip(count: Int) = apply { buffer.position(buffer.position() + count) }
fun position(newPosition: Int) = apply { buffer.position(newPosition) }
fun position() = buffer.position()
}
companion object : Codec {
fun encode(type: Type, data: Any?): ByteArray {
return ByteBuffer.allocate(computeEncodeSize(type, data)).also { encode(type, data, it) }.array()
}
override fun computeEncodeSize(type: Type, data: Any?): Int = selectCodec(type).computeEncodeSize(type, data)
override fun encode(type: Type, data: Any?, buffer: ByteBuffer) = selectCodec(type).encode(type, data, buffer)
override fun decode(type: Type, context: DecodingContext): Any = selectCodec(type).decode(type, context)
private fun selectCodec(type: Type): Codec = when (type) {
is ArrayType -> ArrayCodec
is TupleType -> TupleCodec
is PrimitiveType -> when (type.name) {
"string" -> StringCodec
"bool" -> BooleanCodec
"address" -> AddressCodec
"bytes" -> BytesCodec
"int" -> NumberCodec
"uint" -> NumberCodec
else -> error { "unsupported type $type" }
}
}
}
}
abstract class PrimitiveCodec<T : Any> : Codec {
override fun decode(type: Type, context: Codec.DecodingContext): Any {
val result = decodeTyped(type, context)
return context.primitiveValueConverter[type.name]?.invoke(result) ?: result
}
abstract fun decodeTyped(type: Type, context: Codec.DecodingContext): T
}
data object BooleanCodec : PrimitiveCodec<Boolean>() {
override fun computeEncodeSize(type: Type, data: Any?): Int = 32
override fun encode(type: Type, data: Any?, buffer: ByteBuffer) = encode(data, buffer)
private fun encode(data: Any?, buffer: ByteBuffer) {
repeat(31) { require(buffer.get() == 0.toByte()) }
buffer.put(if (toBoolean(data)) 1 else 0)
}
private fun toBoolean(value: Any?): Boolean = when (value) {
is Boolean -> value
is Number -> when (value.toInt()) {
0 -> false
1 -> true
else -> error("invalid value $value")
}
is String -> when (value) {
"0" -> false
"1" -> true
"false" -> false
"true" -> true
"0x0", "0X0" -> false
"0x1", "0X1" -> true
else -> error("invalid value $value")
}
else -> error("unsupported type $value")
}
override fun decodeTyped(type: Type, context: Codec.DecodingContext): Boolean {
return context.skip(31).read() == 1.toByte()
}
}
data object NumberCodec : PrimitiveCodec<BigInteger>() {
private data class Limit(val min: BigInteger, val max: BigInteger)
private val limitByType = buildMap {
var base = 256.toBigInteger()
(8..256 step 8).forEach { size ->
this["int${size}"] = Limit(-base / BigInteger.TWO, base / BigInteger.TWO - BigInteger.ONE)
this["uint${size}"] = Limit(BigInteger.ZERO, base - BigInteger.ONE)
base *= 256.toBigInteger()
}
this["int"] = this["int256"]!!
this["uint"] = this["uint56"]!!
}
private val mask = BigInteger.TWO.pow(256)
override fun computeEncodeSize(type: Type, data: Any?): Int = 32
override fun encode(type: Type, data: Any?, buffer: ByteBuffer) = encode(data, buffer)
fun encode(data: Any?, buffer: ByteBuffer) {
val value = when (data is String) {
true -> when {
data.startsWith("0x") -> data.removeRange(0, 2).toBigInteger(16)
data.startsWith("-0x") -> data.removeRange(1, 3).toBigInteger(16)
else -> data.toBigInteger()
}
false -> data.toString().toBigInteger()
}
val unsignedValue = if (value < BigInteger.ZERO) mask + value else value
val hex = unsignedValue.toString(16).padStart(64, '0')
buffer.putHexString(hex)
}
override fun decodeTyped(type: Type, context: Codec.DecodingContext): BigInteger {
val result = context.readHexString(32).toBigInteger(16)
if (type.dynamic) return result
if (result <= limitByType[type.toString()]!!.max) return result
return result - mask
}
}
data object StringCodec : PrimitiveCodec<String>() {
@OptIn(ExperimentalStdlibApi::class)
override fun computeEncodeSize(type: Type, data: Any?): Int =
BytesCodec.computeEncodeSize(type, data.toString().toByteArray(Charsets.UTF_8).toHexString())
@OptIn(ExperimentalStdlibApi::class)
override fun encode(type: Type, data: Any?, buffer: ByteBuffer) {
BytesCodec.encode(type, data.toString().toByteArray(Charsets.UTF_8).toHexString(), buffer)
}
override fun decodeTyped(type: Type, context: Codec.DecodingContext): String {
return BytesCodec.decodeTyped(type, context).toString(Charsets.UTF_8)
}
}
data object BytesCodec : PrimitiveCodec<ByteArray>() {
private val emptyByteArray = byteArrayOf()
override fun computeEncodeSize(type: Type, data: Any?): Int {
if (type.dynamic) {
return 32 + (32 * ceil((data as String).hexBytesLength / 32.0).toInt())
}
return 32
}
override fun encode(type: Type, data: Any?, buffer: ByteBuffer) {
require(data is String) { "unsupported type $data" }
if (type.dynamic) {
NumberCodec.encode(data.hexBytesLength, buffer)
}
buffer.putHexString(data)
}
private val String.hexBytesLength: Int
get() {
var size = length
if (size % 2 == 1) size += 1
if (startsWith("0x")) size -= 2
return size / 2
}
override fun decodeTyped(type: Type, context: Codec.DecodingContext): ByteArray {
if (type.dynamic) {
val size = NumberCodec.decodeTyped(Type.of("uint32"), context)
if (size == BigInteger.ZERO) return emptyByteArray
return context.read(size.toInt()).also { context.skip(32 - (size.toInt() % 32)) }
}
return context.read(requireNotNull(type.size)).also { context.skip(32 - it.size) }
}
}
data object AddressCodec : PrimitiveCodec<String>() {
override fun computeEncodeSize(type: Type, data: Any?): Int = 32
override fun encode(type: Type, data: Any?, buffer: ByteBuffer) = encode(data, buffer)
private fun encode(data: Any?, buffer: ByteBuffer) {
data as String
require(data.length == 40 || data.length == 42) { "invalid address length: ${data.length}" }
buffer.position(12).putHexString(data)
}
override fun decodeTyped(type: Type, context: Codec.DecodingContext): String {
return "0x${context.skip(12).readHexString(20).lowercase()}"
}
}
data object ArrayCodec : Codec {
override fun computeEncodeSize(type: Type, data: Any?): Int {
require(data is Collection<*> && type is ArrayType)
var offset = 0
if (type.dynamic) offset += 32
if (type.elementType.dynamic) offset += data.size * 32
return offset + data.sumOf { Codec.computeEncodeSize(type.elementType, it) }
}
override fun encode(type: Type, data: Any?, buffer: ByteBuffer) {
require(data is Collection<*> && type is ArrayType)
if (type.size != null) {
require(type.size == data.size) { "Given arguments count doesn't match array length" }
}
if (type.dynamic) {
NumberCodec.encode(data.size, buffer)
}
if (type.elementType.dynamic) {
val staticSize = data.size * 32
var dynamicSize = 0
data.forEach {
NumberCodec.encode(staticSize + dynamicSize, buffer)
dynamicSize += Codec.computeEncodeSize(type.elementType, it)
}
}
data.forEach { Codec.encode(type.elementType, it, buffer) }
}
override fun decode(type: Type, context: Codec.DecodingContext): List<*> {
require(type is ArrayType)
val size = type.size ?: NumberCodec.decodeTyped(Type.of("uint32"), context).toInt()
if (type.elementType.dynamic) {
val offset = context.position()
return (0..<size).map {
context.position(offset + it * 32)
val offsetSize = NumberCodec.decodeTyped(Type.of("uint32"), context)
context.position(offset + offsetSize.toInt())
Codec.decode(type.elementType, context)
}
}
return (0..<size).map { Codec.decode(type.elementType, context) }
}
}
data object TupleCodec : Codec {
override fun computeEncodeSize(type: Type, data: Any?): Int {
return asSequence(type, data).sumOf { (type, data) ->
when (type.dynamic) {
true -> 32
false -> 0
} + Codec.computeEncodeSize(type, data)
}
}
override fun encode(type: Type, data: Any?, buffer: ByteBuffer) {
val staticSize = asSequence(type, data).sumOf { (type, data) ->
when (type.dynamic) {
true -> 32
false -> Codec.computeEncodeSize(type, data)
}
}
var dynamicSize = 0
asSequence(type, data).forEach { (type, data) ->
if (type.dynamic) {
NumberCodec.encode(staticSize + dynamicSize, buffer)
val start = buffer.position()
Codec.encode(type, data, buffer)
dynamicSize += buffer.position() - start
} else {
Codec.encode(type, data, buffer)
}
}
}
private fun asSequence(type: Type, data: Any?): Sequence<Pair<Type, Any?>> {
require(type is TupleType && data is Collection<*>)
val dataIterator = data.iterator()
return type.components.asSequence().map { it to dataIterator.next() }
}
override fun decode(type: Type, context: Codec.DecodingContext): List<Any> {
require(type is TupleType)
val offset = context.position()
return type.components.mapIndexed { i, c ->
if (c.dynamic) {
val offsetSize = NumberCodec.decodeTyped(Type.of("uint32"), context)
context.position(offset + offsetSize.toInt())
val result = Codec.decode(c, context)
if (i < type.components.lastIndex) {
context.position(offset + (i + 1) * 32)
}
result
} else {
Codec.decode(c, context)
}
}
}
}
@OptIn(ExperimentalStdlibApi::class)
private fun ByteBuffer.putHexString(hex: String) {
var hex = hex
if (hex.length % 2 == 1) {
hex += '0'
}
put(hex.removePrefix("0x").hexToByteArray())
if (position() % 32 != 0) {
position(position() + 32 - (position() % 32))
}
}
| 0 |
Kotlin
|
0
| 2 |
4fd6f900b4e80b5f731090f33c1ddc10c6ede9ca
| 11,948 |
keth-client
|
Apache License 2.0
|
android/src/main/kotlin/ru/kodazm/device_screen_recorder/DeviceScreenRecorderPlugin.kt
|
akovardin
| 370,436,493 | false | null |
package ru.kodazm.device_screen_recorder
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.media.projection.MediaProjectionManager
import androidx.annotation.NonNull
import android.os.Environment
import java.io.File
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import com.hbisoft.hbrecorder.HBRecorderListener
import com.hbisoft.hbrecorder.HBRecorder
/** ScreenRecorderPlugin */
class DeviceScreenRecorderPlugin : FlutterPlugin, MethodCallHandler, HBRecorderListener, ActivityAware, PluginRegistry.ActivityResultListener {
private lateinit var channel: MethodChannel
private var recorder: HBRecorder? = null
private lateinit var context: Context
private lateinit var activity: Activity
private var path: String? = ""
private var name: String? = ""
private val SCREEN_RECORD_REQUEST_CODE = 333;
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
channel = MethodChannel(flutterPluginBinding.binaryMessenger, "device_screen_recorder")
channel.setMethodCallHandler(this)
context = flutterPluginBinding.applicationContext
}
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
// ActivityAware
override fun onDetachedFromActivity() {
}
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
}
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
activity = binding.activity
binding.addActivityResultListener(this);
recorder = HBRecorder(activity, this)
}
override fun onDetachedFromActivityForConfigChanges() {
}
// PluginRegistry.ActivityResultListener
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
if (requestCode == SCREEN_RECORD_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
//Start screen recording
recorder?.setOutputPath(path)
if (name != "") {
recorder?.fileName = name
}
recorder?.setAudioSource("DEFAULT")
recorder?.isAudioEnabled(true)
recorder?.recordHDVideo(false);
recorder?.startScreenRecording(data, resultCode, activity)
}
}
return true;
}
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
if (call.method == "getPlatformVersion") {
result.success("Android ${android.os.Build.VERSION.RELEASE}")
} else if (call.method == "startRecordScreen") {
var name = call.argument<String?>("name")
var path = call.argument<String?>("path")
startRecordScreen(name , path)
result.success(true)
} else if (call.method == "stopRecordScreen") {
var path = stopRecordScreen()
result.success(path)
} else {
result.notImplemented()
}
}
fun startRecordScreen(name: String? , path: String?) {
this.name = name;
this.path = path;
val mediaProjectionManager = context.getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager?
val permissionIntent = mediaProjectionManager?.createScreenCaptureIntent()
activity.startActivityForResult(
permissionIntent!!,
SCREEN_RECORD_REQUEST_CODE,
null)
}
fun stopRecordScreen(): String? {
recorder?.stopScreenRecording()
return recorder?.getFilePath()
}
// HBRecorderListener
override fun HBRecorderOnStart() {
}
override fun HBRecorderOnComplete() {
}
override fun HBRecorderOnError(errorCode: Int, errorMessage: String) {
}
}
| 2 |
Kotlin
|
1
| 1 |
8f87d6d8dd87da6c5cb0b0bbc9c7d1682cdb02ee
| 4,327 |
device_screen_recorder
|
MIT License
|
src/main/kotlin/no/nav/lydia/appstatus/Helse.kt
|
navikt
| 444,072,054 | false | null |
package no.nav.lydia.appstatus
enum class Helse {
UP, DOWN
}
internal fun Boolean.tilHelse() = if (this) Helse.UP else Helse.DOWN
| 0 |
Kotlin
|
0
| 2 |
4026bea42d89710f23d52baaab4d19d592f247da
| 136 |
lydia-api
|
MIT License
|
attribouter/src/main/java/me/jfenn/attribouter/adapters/WedgeAdapter.kt
|
fennifith
| 124,246,346 | false | null |
package me.jfenn.attribouter.adapters
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import me.jfenn.attribouter.wedges.Wedge
class WedgeAdapter(private val wedges: List<Wedge<*>>) : RecyclerView.Adapter<Wedge.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Wedge.ViewHolder {
val info = wedges[viewType]
return info.getViewHolder(LayoutInflater.from(parent.context).inflate(info.layoutRes, parent, false))
}
override fun onBindViewHolder(holder: Wedge.ViewHolder, position: Int) {
(wedges[position] as? Wedge<Wedge.ViewHolder>)?.bind(holder.itemView.context, holder)
}
override fun getItemViewType(position: Int): Int {
return position
}
override fun getItemCount(): Int {
return wedges.size
}
}
| 5 | null |
14
| 120 |
bfa65610b55a1b88673a321dd3bdd9ac409cf6a0
| 877 |
Attribouter
|
Apache License 2.0
|
src/main/kotlin/com/mohsenoid/compose/svgconvertor/SvgStringConvertorMain.kt
|
mohsenoid
| 470,558,310 | false |
{"Kotlin": 18137}
|
package com.mohsenoid.compose.svgconvertor
import com.mohsenoid.compose.svgconvertor.model.ModelConvertorResult
fun main(args: Array<String>) {
if (args.isEmpty()) {
println("Missing path!")
return
}
val svgPath = args[0]
when (val convertorResult = SvgStringConvertor.convert(svgPath)) {
is ModelConvertorResult.Error.InvalidFile -> throw IllegalStateException()
is ModelConvertorResult.Error.InvalidPath -> println(convertorResult.error)
is ModelConvertorResult.Success -> println(convertorResult.result)
}
}
| 0 |
Kotlin
|
2
| 48 |
02c20271978ed9a89f65250f70f035c11ce8439c
| 577 |
SvgToCompose
|
Apache License 2.0
|
projects/parsing/src/main/kotlin/silentorb/imp/parsing/syntax/Integration.kt
|
silentorb
| 235,929,224 | false | null |
package silentorb.imp.parsing.syntax
fun adoptChildren(parent: Burg, children: List<Burg>): Burg =
if (children.none())
parent
else {
val reduced = children
.mapNotNull { child ->
if (child.type == BurgType.application && child.children.size == 1)
child.children.firstOrNull()?.children?.firstOrNull()
else
child
}
if (reduced.none())
parent
else
parent.copy(
range = rangeFromBurgs(children + parent),
children = parent.children + reduced
)
}
fun newBurg(type: BurgType, children: List<Burg>) =
Burg(
type = type,
range = rangeFromBurgs(children),
children = children
)
fun shouldCollapseLayer(type: BurgType, children: List<Burg>): Boolean =
children.size < 2 && setOf(BurgType.application).contains(type)
//val burgs = if (children.size > 0 && layerType is BurgType && (children.size > 1 || layerType != BurgType.application))
// listOf(newBurg(layerType, children))
//else
// children
fun popChildren(stack: BurgStack, layerType: Any?, children: List<Burg>): BurgStack {
val shortStack = stack.dropLast(1)
val newTop = shortStack.last()
val burgs = if (children.any() && layerType is BurgType && !shouldCollapseLayer(layerType, children))
listOf(newBurg(layerType, children))
else
children
return stack.dropLast(2) + newTop.copy(burgs = newTop.burgs + burgs)
}
fun popChildren(state: ParsingState): ParsingState =
if (state.burgStack.size < 2)
state
else {
val stack = state.burgStack
val top = stack.last()
val children = top.burgs
.filter { it.children.any() || it.value != null } // Empty children are filtered out
val nextStack = if (children.none())
stack.dropLast(1)
else
popChildren(stack, top.type, children)
state.copy(
burgStack = nextStack
)
}
| 3 |
Kotlin
|
0
| 1 |
ca465c2b0a9864ded53114120d8b98dad44551dd
| 1,975 |
imp-kotlin
|
MIT License
|
library/transformer/src/main/java/com/google/android/exoplayer2/transformer/EncoderSelector.kt
|
rezaulkhan111
| 589,317,131 | false |
{"Java Properties": 1, "Gradle": 47, "Markdown": 91, "Shell": 6, "Batchfile": 1, "Text": 16, "Ignore List": 1, "XML": 480, "Java": 1191, "Kotlin": 302, "YAML": 6, "INI": 1, "JSON": 5, "HTML": 1519, "Ruby": 1, "SVG": 43, "JavaScript": 40, "SCSS": 81, "CSS": 5, "GLSL": 15, "Starlark": 1, "Protocol Buffer Text Format": 1, "Makefile": 9, "C++": 10, "CMake": 2}
|
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.transformer
import android.media.MediaCodecInfo
import com.google.common.collect.ImmutableList
/** Selector of [MediaCodec] encoder instances. */
interface EncoderSelector {
/**
* Returns a list of encoders that can encode media in the specified `mimeType`, in priority
* order.
*
* @param mimeType The [MIME type][MimeTypes] for which an encoder is required.
* @return An immutable list of [encoders][MediaCodecInfo] that support the `mimeType`. The list may be empty.
*/
fun selectEncoderInfos(mimeType: String?): ImmutableList<MediaCodecInfo?>?
companion object {
/**
* Default implementation of [EncoderSelector], which returns the preferred encoders for the
* given [MIME type][MimeTypes].
*/
@JvmField
val DEFAULT: EncoderSelector = EncoderSelector { mimeType: String? ->
EncoderUtil.getSupportedEncoders(
mimeType!!
)
}
}
}
| 1 | null |
1
| 1 |
c467e918356f58949e0f7f4205e96f0847f1bcdb
| 1,633 |
ExoPlayer
|
Apache License 2.0
|
src/main/kotlin/org/wfanet/measurement/common/crypto/SigningKeyHandle.kt
|
world-federation-of-advertisers
| 375,798,604 | false |
{"Kotlin": 558460, "Starlark": 111083, "Shell": 7028}
|
// Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.common.crypto
import com.google.protobuf.ByteString
import io.netty.handler.ssl.SslContextBuilder
import java.security.PrivateKey
import java.security.Signature
import java.security.cert.X509Certificate
import kotlinx.coroutines.flow.Flow
import org.wfanet.measurement.storage.StorageClient
/**
* Handle to the private key of a signing key pair.
*
* @throws IllegalArgumentException if there is no [SignatureAlgorithm] for [privateKey] that is
* compatible with [DEFAULT_HASH_ALGORITHM]
*/
data class SigningKeyHandle(val certificate: X509Certificate, private val privateKey: PrivateKey) {
/** Default [SignatureAlgorithm] for [privateKey] using [DEFAULT_HASH_ALGORITHM]. */
val defaultAlgorithm =
requireNotNull(SignatureAlgorithm.fromKeyAndHashAlgorithm(privateKey, DEFAULT_HASH_ALGORITHM)) {
"Cannot determine signature algorithm for (${privateKey.algorithm}, $DEFAULT_HASH_ALGORITHM)"
}
/**
* Signs [data] using the specified [algorithm].
*
* @return the signature
*/
fun sign(algorithm: SignatureAlgorithm, data: ByteString) = privateKey.sign(algorithm, data)
/**
* Signs [data] using the [SignatureAlgorithm] specified in [certificate].
*
* Note that this may result in an error as the [SignatureAlgorithm] may not actually be
* compatible with the [certificate] key.
*/
@Deprecated("Specify algorithm explicitly")
@Suppress("DEPRECATION")
fun sign(data: ByteString): ByteString = privateKey.sign(certificate, data)
/** Returns a new [Signature] initialized for signing with [algorithm]. */
fun newSigner(algorithm: SignatureAlgorithm) = privateKey.newSigner(algorithm)
/**
* Returns a new [Signature] initialized for signing using the [SignatureAlgorithm] specified in
* [certificate].
*
* Note that this may result in an error as the [SignatureAlgorithm] may not actually be
* compatible with the [certificate] key.
*/
@Deprecated("Specify algorithm explicitly")
@Suppress("DEPRECATION")
fun newSigner(): Signature = privateKey.newSigner(certificate)
/**
* Writes this [SigningKeyHandle] to [keyStore].
*
* @return the blob key
*/
suspend fun write(keyStore: SigningKeyStore): String {
return keyStore.write(certificate, privateKey)
}
/** Returns a new server [SslContextBuilder] using this key handle. */
fun newServerSslContextBuilder(): SslContextBuilder =
SslContextBuilder.forServer(privateKey, certificate)
companion object {
val DEFAULT_HASH_ALGORITHM = HashAlgorithm.SHA256
/** @see SslContextBuilder.keyManager */
fun SslContextBuilder.keyManager(keyHandle: SigningKeyHandle): SslContextBuilder =
keyManager(keyHandle.privateKey, keyHandle.certificate)
}
}
/**
* Terminal flow operator that collects the given flow with the provided [action] and digitally
* signs the accumulated values.
*
* @param keyHandle handle of signing private key
* @return the digital signature of the accumulated values
*/
suspend inline fun Flow<ByteString>.collectAndSign(
keyHandle: SigningKeyHandle,
algorithm: SignatureAlgorithm,
crossinline action: suspend (ByteString) -> Unit
): ByteString = collectAndSign({ keyHandle.newSigner(algorithm) }, action)
/**
* Terminal flow operator that collects the given flow with the provided [action] and digitally
* signs the accumulated values.
*
* @param keyHandle handle of signing private key
* @return the digital signature of the accumulated values
*/
@Deprecated("Specify algorithm explicitly")
@Suppress("DEPRECATION")
suspend inline fun Flow<ByteString>.collectAndSign(
keyHandle: SigningKeyHandle,
crossinline action: suspend (ByteString) -> Unit
): ByteString = collectAndSign(keyHandle::newSigner, action)
suspend fun StorageClient.createSignedBlob(
blobKey: String,
content: Flow<ByteString>,
signingKey: SigningKeyHandle,
algorithm: SignatureAlgorithm
): SignedBlob = createSignedBlob(blobKey, content) { signingKey.newSigner(algorithm) }
@Deprecated("Specify algorithm explicitly")
@Suppress("DEPRECATION")
suspend fun StorageClient.createSignedBlob(
blobKey: String,
content: Flow<ByteString>,
signingKey: SigningKeyHandle
): SignedBlob = createSignedBlob(blobKey, content, signingKey::newSigner)
| 15 |
Kotlin
|
3
| 3 |
0b843d209296a2b9eb9655d2033e06d03cb2041a
| 4,892 |
common-jvm
|
Apache License 2.0
|
core-data/src/main/java/io/github/zohrevand/dialogue/core/data/repository/ContactsRepository.kt
|
zohrevand
| 510,113,579 | false |
{"Kotlin": 271495}
|
package io.github.zohrevand.dialogue.core.data.repository
import io.github.zohrevand.core.model.data.Contact
import kotlinx.coroutines.flow.Flow
interface ContactsRepository {
fun getContact(jid: String): Flow<Contact>
fun getContactsStream(): Flow<List<Contact>>
fun getShouldAddToRosterStream(): Flow<List<Contact>>
suspend fun updateContacts(contacts: List<Contact>)
}
| 1 |
Kotlin
|
2
| 11 |
9607aed6f182d3eb051e5da4cee6ddf82c659690
| 394 |
dialogue
|
Apache License 2.0
|
src/main/kotlin/g1601_1700/s1695_maximum_erasure_value/Solution.kt
|
javadev
| 190,711,550 | false |
{"Kotlin": 4909193, "TypeScript": 50446, "Python": 3646, "Shell": 994}
|
package g1601_1700.s1695_maximum_erasure_value
// #Medium #Array #Hash_Table #Sliding_Window
// #2023_06_15_Time_478_ms_(100.00%)_Space_49.8_MB_(100.00%)
class Solution {
fun maximumUniqueSubarray(nums: IntArray): Int {
var ans = 0
var sum = 0
val seen = BooleanArray(10001)
var j = 0
for (num in nums) {
while (seen[num]) {
seen[nums[j]] = false
sum -= nums[j++]
}
seen[num] = true
sum += num
ans = Math.max(sum, ans)
}
return ans
}
}
| 0 |
Kotlin
|
20
| 43 |
62708bc4d70ca2bfb6942e4bbfb4c64641e598e8
| 594 |
LeetCode-in-Kotlin
|
MIT License
|
core/src/commonMain/kotlin/com/erolc/mrouter/model/Route.kt
|
ErolC
| 786,106,502 | false |
{"Kotlin": 215198, "Swift": 620, "HTML": 304}
|
package com.erolc.mrouter.model
import com.erolc.mrouter.route.Args
import com.erolc.mrouter.route.RouteFlag
import com.erolc.mrouter.scope.PageScope
import com.erolc.mrouter.route.emptyArgs
import com.erolc.mrouter.route.transform.Transform
/**
* 路由,由[PageScope.route]方法触发并构建,其中包含:
* 路由代表前往一个页面的方式以及相关。
* @param path 原始的路径
* @param address 下一个页面的地址
* @param args 携带到下一个页面的数据
* @param windowOptions 页面负载到对应window的参数
* @param onResult 页面回退时可将参数从方法传回
* @param panelOptions 局部面板的配置
* @param transform 变换,页面跳转时的动画以及手势
*/
data class Route internal constructor(
val path: String,
val address: String,
val flag: RouteFlag,
val windowOptions: WindowOptions,
val args: Args = emptyArgs,
val onResult: (Args) -> Unit = {},
val panelOptions: PanelOptions? = null,
val transform: Transform = Transform.None,
)
| 0 |
Kotlin
|
0
| 0 |
f03c6eb32d1798ecc1468abf43f8d97121f697d2
| 841 |
MRouter
|
Apache License 2.0
|
cocache-core/src/main/kotlin/me/ahoo/cache/client/ClientSideCache.kt
|
Ahoo-Wang
| 461,189,010 | false | null |
/*
* Copyright [2021-present] [<NAME> <<EMAIL>> (https://github.com/Ahoo-Wang)].
* 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 me.ahoo.cache.client
import me.ahoo.cache.Cache
/**
* Client Side Cache .
*
* @author <NAME>
*/
interface ClientSideCache<V> : Cache<String, V> {
/**
* clear all cache.
*/
fun clear()
}
| 1 |
Kotlin
|
0
| 5 |
166225539a3b692b6e24391d35dea9a84ac55d96
| 854 |
CoCache
|
Apache License 2.0
|
app/src/main/java/com/devmanishpatole/githubusers/base/PagingFragment.kt
|
devmanishpatole
| 310,791,098 | false | null |
package com.devmanishpatole.githubusers.base
import android.os.Bundle
import android.view.View
import androidx.paging.LoadState
import androidx.recyclerview.widget.RecyclerView
import com.devmanishpatole.githubusers.R
import com.devmanishpatole.githubusers.adapter.UserLoadStateAdapter
import com.devmanishpatole.githubusers.exception.NetworkException
/**
* Abstract layer for paging fragment.
* Extracted logic of list initialisation and loading state listeners.
*/
abstract class PagingFragment<VM : BaseViewModel, T : Any, VH : BaseItemViewHolder<T, out BaseItemViewModel<T>>> :
BaseFragment<VM>() {
lateinit var listAdapter: BasePagingAdapter<T, VH>
override fun setupView(view: View, savedInstanceState: Bundle?) {
initList()
addLoadStateChangeListener()
observeData()
}
protected open fun initList() {
listAdapter = getAdapter()
getList().apply {
listAdapter.apply {
adapter = this
adapter = withLoadStateHeaderAndFooter(
header = UserLoadStateAdapter { retry() },
footer = UserLoadStateAdapter { retry() }
)
}
setHasFixedSize(true)
}
}
/**
* Listens to load state changes.
*/
private fun addLoadStateChangeListener() {
listAdapter.addLoadStateListener { loadState ->
when (loadState.source.refresh) {
// Showing list when success
is LoadState.NotLoading -> {
when (listAdapter.itemCount) {
0 -> showError(getString(getErrorMessage()))
else -> hideProgressbarOrError()
}
notLoading()
}
// Showing progress for load
is LoadState.Loading -> showProgressbar()
is LoadState.Error -> {
if ((loadState.source.refresh as LoadState.Error).error is NetworkException) {
showError(getString(R.string.no_internet_connection))
} else {
showError(getString(getErrorMessage()))
}
}
}
// Popping error
val errorState = loadState.source.append as? LoadState.Error
?: loadState.source.prepend as? LoadState.Error
?: loadState.append as? LoadState.Error
?: loadState.prepend as? LoadState.Error
errorState?.let { showMessage("\uD83D\uDE28 Error ${it.error}") }
}
}
abstract fun getAdapter(): BasePagingAdapter<T, VH>
abstract fun observeData()
abstract fun getErrorMessage(): Int
abstract fun getList(): RecyclerView
abstract fun notLoading()
override fun onDestroyView() {
getList().adapter = null
super.onDestroyView()
}
}
| 0 |
Kotlin
|
0
| 0 |
7984da2938e993508f3bd2bb7003d5cfbdf86a2e
| 2,943 |
SearchGitHubUsers
|
MIT License
|
library/src/main/java/app/moviebase/androidx/widget/recyclerview/paging3/LoadStateViewHolder.kt
|
MoviebaseApp
| 255,031,168 | false | null |
package app.moviebase.androidx.widget.recyclerview.paging3
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.paging.LoadState
import androidx.recyclerview.widget.RecyclerView
abstract class LoadStateViewHolder(
parent: ViewGroup,
@LayoutRes resource: Int
) : RecyclerView.ViewHolder(LayoutInflater.from(parent.context).inflate(resource, parent, false)) {
protected val context: Context get() = itemView.context
abstract fun bindTo(loadState: LoadState)
}
| 0 |
Kotlin
|
0
| 1 |
27e06659f68ea642dff11a95a604c927babc8689
| 575 |
android-elements
|
Apache License 2.0
|
app/src/main/java/dev/arkbuilders/arkmemo/ui/viewmodels/ArkMediaPlayerViewModel.kt
|
ARK-Builders
| 504,830,870 | false |
{"Kotlin": 105940}
|
package dev.arkbuilders.arkmemo.ui.viewmodels
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import dev.arkbuilders.arkmemo.media.ArkMediaPlayer
import dev.arkbuilders.arkmemo.utils.millisToString
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import javax.inject.Inject
sealed class ArkMediaPlayerSideEffect {
object StartPlaying: ArkMediaPlayerSideEffect()
object PausePlaying: ArkMediaPlayerSideEffect()
object ResumePlaying: ArkMediaPlayerSideEffect()
object StopPlaying: ArkMediaPlayerSideEffect()
}
data class ArkMediaPlayerState(
val progress: Float,
val duration: String
)
@HiltViewModel
class ArkMediaPlayerViewModel @Inject constructor(
private val arkMediaPlayer: ArkMediaPlayer
): ViewModel() {
private var currentPlayingVoiceNotePath: String = ""
private val arkMediaPlayerSideEffect = MutableStateFlow<ArkMediaPlayerSideEffect?>(null)
private val arkMediaPlayerState = MutableStateFlow<ArkMediaPlayerState?>(null)
fun initPlayer(path: String) {
currentPlayingVoiceNotePath = path
arkMediaPlayer.init(
path,
onCompletion = {
arkMediaPlayerSideEffect.value = ArkMediaPlayerSideEffect.StopPlaying
},
onPrepared = {
arkMediaPlayerState.value = ArkMediaPlayerState(
progress = 0f,
duration = millisToString(arkMediaPlayer.duration().toLong())
)
}
)
}
fun onPlayOrPauseClick(path: String) {
if (currentPlayingVoiceNotePath != path) {
currentPlayingVoiceNotePath = path
arkMediaPlayer.init(
path,
onCompletion = {
arkMediaPlayerSideEffect.value = ArkMediaPlayerSideEffect.StopPlaying
},
onPrepared = {
arkMediaPlayerState.value = ArkMediaPlayerState(
progress = 0f,
duration = millisToString(arkMediaPlayer.duration().toLong())
)
}
)
}
if (arkMediaPlayer.isPlaying()) {
onPauseClick()
return
}
onPlayClick()
}
fun onSeekTo(position: Int) {
val pos = (position.toFloat() / 100f) * arkMediaPlayer.duration()
arkMediaPlayer.seekTo(pos.toInt())
}
fun collect(
stateToUI: (ArkMediaPlayerState) -> Unit,
handleSideEffect: (ArkMediaPlayerSideEffect) -> Unit
) {
viewModelScope.launch {
arkMediaPlayerState.collectLatest {
it?.let {
stateToUI(it)
}
}
}
viewModelScope.launch {
arkMediaPlayerSideEffect.collectLatest {
it?.let {
handleSideEffect(it)
}
}
}
}
private fun startProgressMonitor() {
viewModelScope.launch(Dispatchers.Default) {
var progress: Float
do {
progress = (arkMediaPlayer.currentPosition().toFloat() /
arkMediaPlayer.duration().toFloat()) * 100
arkMediaPlayerState.value = ArkMediaPlayerState(
progress = progress,
duration = millisToString(arkMediaPlayer.duration().toLong())
)
} while(arkMediaPlayer.isPlaying())
}
}
private fun onPlayClick() {
arkMediaPlayer.play()
startProgressMonitor()
arkMediaPlayerSideEffect.value = ArkMediaPlayerSideEffect.StartPlaying
}
private fun onPauseClick() {
arkMediaPlayer.pause()
arkMediaPlayerSideEffect.value = ArkMediaPlayerSideEffect.PausePlaying
}
}
| 14 |
Kotlin
|
3
| 1 |
6157a355d23eecb5db5f3eebae3e3bc54549afb0
| 4,026 |
ARK-Memo
|
MIT License
|
common/src/commonMain/kotlin/io/xorum/codeforceswatcher/db/CWDatabase.kt
|
xorum-io
| 208,440,935 | true | null |
package io.xorum.codeforceswatcher.db
import io.xorum.codeforceswatcher.CWDatabase
import io.xorum.codeforceswatcher.redux.sqlDriver
val database by lazy { CWDatabase(sqlDriver) }
| 33 |
Kotlin
|
15
| 76 |
a921b4a49fcb26bd73c62e582efc15dc2fe913e4
| 182 |
codeforces_watcher
|
MIT License
|
no-waste-requests/src/test/kotlin/edu/ubb/micro/nowaste/requestmanager/RequestManagerApplicationTests.kt
|
kissbudai
| 192,089,735 | false | null |
package edu.ubb.micro.nowaste.requestmanager
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit4.SpringRunner
@RunWith(SpringRunner::class)
@SpringBootTest
class RequestManagerApplicationTests {
@Test
fun contextLoads() {
}
}
| 0 |
Kotlin
|
0
| 0 |
25afa71e987fcbfb85bf6f2588d7654b98e1e0c5
| 342 |
no-waste-api
|
Apache License 2.0
|
permission-kit/src/main/java/com/permission/kit/PermissionConstants.kt
|
ydstar
| 351,710,071 | false | null |
package com.permission.kit
import android.Manifest
import android.os.Build
import androidx.annotation.StringDef
import java.lang.annotation.Retention
import java.lang.annotation.RetentionPolicy
/**
* Author: 信仰年轻
* Date: 2021-03-26 11:20
* Email: <EMAIL>
* Des:申请权限时从这里指定权限名的名称
*/
object PermissionConstants {
const val CALENDAR = Manifest.permission_group.CALENDAR
const val CAMERA = Manifest.permission_group.CAMERA
const val CONTACTS = Manifest.permission_group.CONTACTS
const val LOCATION = Manifest.permission_group.LOCATION
const val MICROPHONE = Manifest.permission_group.MICROPHONE
const val PHONE = Manifest.permission_group.PHONE
const val SENSORS = Manifest.permission_group.SENSORS
const val SMS = Manifest.permission_group.SMS
const val STORAGE = Manifest.permission_group.STORAGE
//日历组
private val GROUP_CALENDAR = arrayOf(
Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR
)
//相机组
private val GROUP_CAMERA = arrayOf(
Manifest.permission.CAMERA
)
//通讯录组
private val GROUP_CONTACTS = arrayOf(
Manifest.permission.READ_CONTACTS,
Manifest.permission.WRITE_CONTACTS,
Manifest.permission.GET_ACCOUNTS
)
//定位组
private val GROUP_LOCATION = arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
)
//麦克风组
private val GROUP_MICROPHONE = arrayOf(
Manifest.permission.RECORD_AUDIO
)
//打电话组
private val GROUP_PHONE = arrayOf(
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.READ_PHONE_NUMBERS,
Manifest.permission.CALL_PHONE,
Manifest.permission.READ_CALL_LOG,
Manifest.permission.WRITE_CALL_LOG,
Manifest.permission.ADD_VOICEMAIL,
Manifest.permission.USE_SIP,
Manifest.permission.PROCESS_OUTGOING_CALLS,
Manifest.permission.ANSWER_PHONE_CALLS
)
//8.0以下打电话组 SDK_INT < 26
private val GROUP_PHONE_BELOW_O = arrayOf(
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.READ_PHONE_NUMBERS,
Manifest.permission.CALL_PHONE,
Manifest.permission.READ_CALL_LOG,
Manifest.permission.WRITE_CALL_LOG,
Manifest.permission.ADD_VOICEMAIL,
Manifest.permission.USE_SIP,
Manifest.permission.PROCESS_OUTGOING_CALLS
)
//传感器组
private val GROUP_SENSORS = arrayOf(
Manifest.permission.BODY_SENSORS
)
//短信组
private val GROUP_SMS = arrayOf(
Manifest.permission.SEND_SMS,
Manifest.permission.RECEIVE_SMS,
Manifest.permission.READ_SMS,
Manifest.permission.RECEIVE_WAP_PUSH,
Manifest.permission.RECEIVE_MMS
)
//存储组
private val GROUP_STORAGE = arrayOf(
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
fun getPermissions(@Permission permission: String): Array<String> {
when (permission) {
CALENDAR -> return GROUP_CALENDAR
CAMERA -> return GROUP_CAMERA
CONTACTS -> return GROUP_CONTACTS
LOCATION -> return GROUP_LOCATION
MICROPHONE -> return GROUP_MICROPHONE
PHONE -> return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
GROUP_PHONE_BELOW_O
} else {
GROUP_PHONE
}
SENSORS -> return GROUP_SENSORS
SMS -> return GROUP_SMS
STORAGE -> return GROUP_STORAGE
}
return arrayOf(permission)
}
@StringDef(
CALENDAR,
CAMERA,
CONTACTS,
LOCATION,
MICROPHONE,
PHONE,
SENSORS,
SMS,
STORAGE
)
@Retention(RetentionPolicy.SOURCE)
annotation class Permission
}
| 0 |
Kotlin
|
7
| 75 |
3ea5973e122f37f1ae333d444b0ccb6ed371699a
| 3,850 |
PermissionKit
|
Apache License 2.0
|
domain/src/main/java/com/stori/interviewtest/domain/usecase/GetProfileUseCase.kt
|
andresbelt
| 799,752,707 | false |
{"Kotlin": 91087}
|
package com.stori.interviewtest.domain.usecase
import com.stori.interviewtest.commons.Either
import com.stori.interviewtest.data.UserStori
import com.stori.interviewtest.data.error.UserErrorContainer
import com.stori.interviewtest.data.repository.StoriRepository
import javax.inject.Inject
import kotlinx.coroutines.flow.Flow
class GetProfileUseCase @Inject constructor(
private val repository: StoriRepository
) {
fun getInfoProfile(): Flow<Either<UserErrorContainer, UserStori?>> {
return repository.loadProfile()
}
}
| 0 |
Kotlin
|
0
| 0 |
53cbdb90f3aad38dcba14f7b25f73a5cbe36b1f2
| 543 |
testStori
|
MIT License
|
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/apigatewayv2/CfnApiCorsPropertyDsl.kt
|
cloudshiftinc
| 667,063,030 | false | null |
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.apigatewayv2
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.Boolean
import kotlin.Number
import kotlin.String
import kotlin.collections.Collection
import kotlin.collections.MutableList
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.apigatewayv2.CfnApi
/**
* The `Cors` property specifies a CORS configuration for an API.
*
* Supported only for HTTP APIs. See [Configuring
* CORS](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-cors.html) for more
* information.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.apigatewayv2.*;
* CorsProperty corsProperty = CorsProperty.builder()
* .allowCredentials(false)
* .allowHeaders(List.of("allowHeaders"))
* .allowMethods(List.of("allowMethods"))
* .allowOrigins(List.of("allowOrigins"))
* .exposeHeaders(List.of("exposeHeaders"))
* .maxAge(123)
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigatewayv2-api-cors.html)
*/
@CdkDslMarker
public class CfnApiCorsPropertyDsl {
private val cdkBuilder: CfnApi.CorsProperty.Builder = CfnApi.CorsProperty.builder()
private val _allowHeaders: MutableList<String> = mutableListOf()
private val _allowMethods: MutableList<String> = mutableListOf()
private val _allowOrigins: MutableList<String> = mutableListOf()
private val _exposeHeaders: MutableList<String> = mutableListOf()
/**
* @param allowCredentials Specifies whether credentials are included in the CORS request.
* Supported only for HTTP APIs.
*/
public fun allowCredentials(allowCredentials: Boolean) {
cdkBuilder.allowCredentials(allowCredentials)
}
/**
* @param allowCredentials Specifies whether credentials are included in the CORS request.
* Supported only for HTTP APIs.
*/
public fun allowCredentials(allowCredentials: IResolvable) {
cdkBuilder.allowCredentials(allowCredentials)
}
/**
* @param allowHeaders Represents a collection of allowed headers.
* Supported only for HTTP APIs.
*/
public fun allowHeaders(vararg allowHeaders: String) {
_allowHeaders.addAll(listOf(*allowHeaders))
}
/**
* @param allowHeaders Represents a collection of allowed headers.
* Supported only for HTTP APIs.
*/
public fun allowHeaders(allowHeaders: Collection<String>) {
_allowHeaders.addAll(allowHeaders)
}
/**
* @param allowMethods Represents a collection of allowed HTTP methods.
* Supported only for HTTP APIs.
*/
public fun allowMethods(vararg allowMethods: String) {
_allowMethods.addAll(listOf(*allowMethods))
}
/**
* @param allowMethods Represents a collection of allowed HTTP methods.
* Supported only for HTTP APIs.
*/
public fun allowMethods(allowMethods: Collection<String>) {
_allowMethods.addAll(allowMethods)
}
/**
* @param allowOrigins Represents a collection of allowed origins.
* Supported only for HTTP APIs.
*/
public fun allowOrigins(vararg allowOrigins: String) {
_allowOrigins.addAll(listOf(*allowOrigins))
}
/**
* @param allowOrigins Represents a collection of allowed origins.
* Supported only for HTTP APIs.
*/
public fun allowOrigins(allowOrigins: Collection<String>) {
_allowOrigins.addAll(allowOrigins)
}
/**
* @param exposeHeaders Represents a collection of exposed headers.
* Supported only for HTTP APIs.
*/
public fun exposeHeaders(vararg exposeHeaders: String) {
_exposeHeaders.addAll(listOf(*exposeHeaders))
}
/**
* @param exposeHeaders Represents a collection of exposed headers.
* Supported only for HTTP APIs.
*/
public fun exposeHeaders(exposeHeaders: Collection<String>) {
_exposeHeaders.addAll(exposeHeaders)
}
/**
* @param maxAge The number of seconds that the browser should cache preflight request results.
* Supported only for HTTP APIs.
*/
public fun maxAge(maxAge: Number) {
cdkBuilder.maxAge(maxAge)
}
public fun build(): CfnApi.CorsProperty {
if(_allowHeaders.isNotEmpty()) cdkBuilder.allowHeaders(_allowHeaders)
if(_allowMethods.isNotEmpty()) cdkBuilder.allowMethods(_allowMethods)
if(_allowOrigins.isNotEmpty()) cdkBuilder.allowOrigins(_allowOrigins)
if(_exposeHeaders.isNotEmpty()) cdkBuilder.exposeHeaders(_exposeHeaders)
return cdkBuilder.build()
}
}
| 1 |
Kotlin
|
0
| 0 |
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
| 4,712 |
awscdk-dsl-kotlin
|
Apache License 2.0
|
app/src/main/java/com/managerofthings/sqllite/tables/Category.kt
|
eliorodr2104
| 793,775,290 | false |
{"Kotlin": 56559}
|
package com.managerofthings.sqllite.tables
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(
tableName = "category"
)
data class Category(
@PrimaryKey val name: String
)
| 0 |
Kotlin
|
0
| 0 |
4e6dcf6261e9f4099fd1f339cf6e1c892571c212
| 199 |
ManagerOfThings
|
MIT License
|
domain/src/main/kotlin/no/nav/su/se/bakover/domain/regulering/Reguleringsfelter.kt
|
navikt
| 227,366,088 | false | null |
package no.nav.su.se.bakover.domain.regulering
import no.nav.su.se.bakover.common.ident.NavIdentBruker
import no.nav.su.se.bakover.domain.behandling.Behandling
import no.nav.su.se.bakover.domain.beregning.Beregning
import no.nav.su.se.bakover.domain.grunnlag.EksterneGrunnlag
import no.nav.su.se.bakover.domain.grunnlag.GrunnlagsdataOgVilkårsvurderinger
import no.nav.su.se.bakover.domain.grunnlag.StøtterIkkeHentingAvEksternGrunnlag
import no.nav.su.se.bakover.domain.oppdrag.simulering.Simulering
interface Reguleringsfelter : Behandling {
override val beregning: Beregning?
override val simulering: Simulering?
override val eksterneGrunnlag: EksterneGrunnlag
get() = StøtterIkkeHentingAvEksternGrunnlag
val saksbehandler: NavIdentBruker.Saksbehandler
val reguleringstype: Reguleringstype
val grunnlagsdataOgVilkårsvurderinger: GrunnlagsdataOgVilkårsvurderinger
}
| 5 |
Kotlin
|
0
| 1 |
42b26070530b0b5a6bc2373ca3f4079465745cce
| 900 |
su-se-bakover
|
MIT License
|
app/src/main/java/io/appwrite/messagewrite/ui/settings/SettingsViewModel.kt
|
abnegate
| 777,669,864 | false |
{"Kotlin": 59858}
|
package io.appwrite.messagewrite.ui.settings
import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class SettingsViewModel @Inject constructor() : ViewModel()
| 0 |
Kotlin
|
0
| 0 |
c8a3574c53c211cb98ea445f645865412716a91a
| 235 |
hackathon-chat
|
MIT License
|
onnx/src/main/kotlin/org/jetbrains/kotlinx/dl/api/inference/onnx/ONNXModels.kt
|
JetBrains
| 249,948,572 | false | null |
/*
* Copyright 2020 JetBrains s.r.o. and Kotlin Deep Learning project contributors. All Rights Reserved.
* Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE.txt file.
*/
package org.jetbrains.kotlinx.dl.api.inference.onnx
import org.jetbrains.kotlinx.dl.api.inference.InferenceModel
import org.jetbrains.kotlinx.dl.api.inference.onnx.facealignment.Fan2D106FaceAlignmentModel
import org.jetbrains.kotlinx.dl.api.inference.imagerecognition.ImageRecognitionModel
import org.jetbrains.kotlinx.dl.api.inference.keras.loaders.*
import org.jetbrains.kotlinx.dl.api.inference.onnx.objectdetection.SSDObjectDetectionModel
import org.jetbrains.kotlinx.dl.dataset.preprocessor.ImageShape
import org.jetbrains.kotlinx.dl.dataset.preprocessor.Transpose
/** Models in the ONNX format and running via ONNX Runtime. */
public object ONNXModels {
/** Image recognition models and preprocessing. */
public sealed class CV<T : InferenceModel>(
override val modelRelativePath: String,
override val channelsFirst: Boolean
) :
ModelType<T, ImageRecognitionModel> {
override fun pretrainedModel(modelHub: ModelHub): ImageRecognitionModel {
return ImageRecognitionModel(modelHub.loadModel(this), this)
}
/** */
public object ResNet18 : CV<OnnxInferenceModel>("models/onnx/cv/resnet/resnet18-v1", channelsFirst = true) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return resNetOnnxPreprocessing(data, tensorShape)
}
}
/** */
public object ResNet34 : CV<OnnxInferenceModel>("models/onnx/cv/resnet/resnet34-v1", channelsFirst = true) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return resNetOnnxPreprocessing(data, tensorShape)
}
}
/** */
public object ResNet50 :
CV<OnnxInferenceModel>("models/onnx/cv/resnet/resnet50-v1", channelsFirst = true) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return resNetOnnxPreprocessing(data, tensorShape)
}
}
/** */
public object ResNet101 :
CV<OnnxInferenceModel>("models/onnx/cv/resnet/resnet101-v1", channelsFirst = true) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return resNetOnnxPreprocessing(data, tensorShape)
}
}
/** */
public object ResNet152 :
CV<OnnxInferenceModel>("models/onnx/cv/resnet/resnet152-v1", channelsFirst = true) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return resNetOnnxPreprocessing(data, tensorShape)
}
}
/** */
public object ResNet18v2 :
CV<OnnxInferenceModel>("models/onnx/cv/resnet/resnet18-v2", channelsFirst = true) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return resNetOnnxPreprocessing(data, tensorShape)
}
}
/** */
public object ResNet34v2 :
CV<OnnxInferenceModel>("models/onnx/cv/resnet/resnet34-v2", channelsFirst = true) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return resNetOnnxPreprocessing(data, tensorShape)
}
}
/** */
public object ResNet50v2 :
CV<OnnxInferenceModel>("models/onnx/cv/resnet/resnet50-v2", channelsFirst = true) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return resNetOnnxPreprocessing(data, tensorShape)
}
}
/** */
public object ResNet101v2 :
CV<OnnxInferenceModel>("models/onnx/cv/resnet/resnet101-v2", channelsFirst = true) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return resNetOnnxPreprocessing(data, tensorShape)
}
}
/** */
public object ResNet152v2 :
CV<OnnxInferenceModel>("models/onnx/cv/resnet/resnet152-v2", channelsFirst = true) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return resNetOnnxPreprocessing(data, tensorShape)
}
}
/** */
public object DenseNet121 :
CV<OnnxInferenceModel>("models/onnx/cv/densenet/densenet121", channelsFirst = true) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
TODO("Not yet implemented")
}
}
/** */
public object EfficientNet4Lite :
CV<OnnxInferenceModel>("models/onnx/cv/efficientnet/efficientnet-lite4", channelsFirst = true) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return preprocessInput(
data,
tensorShape,
inputType = InputType.TF,
channelsLast = false
)
}
}
/** */
public object ResNet50custom :
CV<OnnxInferenceModel>("models/onnx/cv/custom/resnet50", channelsFirst = false) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return preprocessInput(
data,
tensorShape,
inputType = InputType.CAFFE
)
}
}
/** */
public object ResNet50noTopCustom :
CV<OnnxInferenceModel>("models/onnx/cv/custom/resnet50notop", channelsFirst = false) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return preprocessInput(
data,
tensorShape,
inputType = InputType.CAFFE
)
}
}
/** */
public object EfficientNetB0 :
CV<OnnxInferenceModel>("models/onnx/cv/efficientnet/efficientnet-b0", channelsFirst = false) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return data
}
}
/** */
public object EfficientNetB0noTop :
CV<OnnxInferenceModel>("models/onnx/cv/efficientnet/efficientnet-b0-notop", channelsFirst = false) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return data
}
}
/** */
public object EfficientNetB1 :
CV<OnnxInferenceModel>("models/onnx/cv/efficientnet/efficientnet-b1", channelsFirst = false) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return data
}
}
/** */
public object EfficientNetB1noTop :
CV<OnnxInferenceModel>("models/onnx/cv/efficientnet/efficientnet-b1-notop", channelsFirst = false) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return data
}
}
/** */
public object EfficientNetB2 :
CV<OnnxInferenceModel>("models/onnx/cv/efficientnet/efficientnet-b2", channelsFirst = false) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return data
}
}
/** */
public object EfficientNetB2noTop :
CV<OnnxInferenceModel>("models/onnx/cv/efficientnet/efficientnet-b2-notop", channelsFirst = false) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return data
}
}
/** */
public object EfficientNetB3 :
CV<OnnxInferenceModel>("models/onnx/cv/efficientnet/efficientnet-b3", channelsFirst = false) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return data
}
}
/** */
public object EfficientNetB3noTop :
CV<OnnxInferenceModel>("models/onnx/cv/efficientnet/efficientnet-b3-notop", channelsFirst = false) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return data
}
}
/** */
public object EfficientNetB4 :
CV<OnnxInferenceModel>("models/onnx/cv/efficientnet/efficientnet-b4", channelsFirst = false) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return data
}
}
/** */
public object EfficientNetB4noTop :
CV<OnnxInferenceModel>("models/onnx/cv/efficientnet/efficientnet-b4-notop", channelsFirst = false) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return data
}
}
/** */
public object EfficientNetB5 :
CV<OnnxInferenceModel>("models/onnx/cv/efficientnet/efficientnet-b5", channelsFirst = false) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return data
}
}
/** */
public object EfficientNetB5noTop :
CV<OnnxInferenceModel>("models/onnx/cv/efficientnet/efficientnet-b5-notop", channelsFirst = false) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return data
}
}
/** */
public object EfficientNetB6 :
CV<OnnxInferenceModel>("models/onnx/cv/efficientnet/efficientnet-b6", channelsFirst = false) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return data
}
}
/** */
public object EfficientNetB6noTop :
CV<OnnxInferenceModel>("models/onnx/cv/efficientnet/efficientnet-b6-notop", channelsFirst = false) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return data
}
}
/** */
public object EfficientNetB7 :
CV<OnnxInferenceModel>("models/onnx/cv/efficientnet/efficientnet-b7", channelsFirst = false) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return data
}
}
/** */
public object EfficientNetB7noTop :
CV<OnnxInferenceModel>("models/onnx/cv/efficientnet/efficientnet-b7-notop", channelsFirst = false) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
return data
}
}
/** */
public object Lenet : CV<OnnxInferenceModel>("models/onnx/cv/custom/mnist", channelsFirst = false) {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
TODO("Not yet implemented")
}
}
}
/** Object detection models and preprocessing. */
public sealed class ObjectDetection<T : InferenceModel, U : InferenceModel>(
override val modelRelativePath: String,
override val channelsFirst: Boolean = true
) :
ModelType<T, U> {
/**
* This model is a real-time neural network for object detection that detects 80 different classes.
*
* Image shape is (1x3x1200x1200).
*
* The model has 3 outputs:
* - boxes: (1x'nbox'x4)
* - labels: (1x'nbox')
* - scores: (1x'nbox')
*
* @see <a href="https://arxiv.org/abs/1512.02325">
* SSD: Single Shot MultiBox Detector.</a>
* @see <a href="https://github.com/onnx/models/tree/master/vision/object_detection_segmentation/ssd">
* Detailed description of SSD model and its pre- and postprocessing in onnx/models repository.</a>
*/
public object SSD :
ObjectDetection<OnnxInferenceModel, SSDObjectDetectionModel>("models/onnx/objectdetection/ssd") {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
val transposedData = Transpose(axes = intArrayOf(2, 0, 1)).apply(
data,
ImageShape(width = tensorShape[0], height = tensorShape[1], channels = tensorShape[2])
)
// TODO: should be returned from the Transpose from apply method
val transposedShape = longArrayOf(tensorShape[2], tensorShape[0], tensorShape[1])
return preprocessInput(
transposedData,
transposedShape,
inputType = InputType.TORCH,
channelsLast = false
)
}
override fun pretrainedModel(modelHub: ModelHub): SSDObjectDetectionModel {
return modelHub.loadModel(this) as SSDObjectDetectionModel
}
}
/** */
public object YOLOv4 :
ObjectDetection<OnnxInferenceModel, OnnxInferenceModel>("models/onnx/objectdetection/yolov4") {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
TODO("Not yet implemented")
}
override fun pretrainedModel(modelHub: ModelHub): OnnxInferenceModel {
TODO("Not yet implemented")
}
}
}
/** Face alignment models and preprocessing. */
public sealed class FaceAlignment<T : InferenceModel, U : InferenceModel>(
override val modelRelativePath: String,
override val channelsFirst: Boolean = true
) :
ModelType<T, U> {
/** */
public object Fan2d106 :
FaceAlignment<OnnxInferenceModel, Fan2D106FaceAlignmentModel>("models/onnx/facealignment/fan_2d_106") {
override fun preprocessInput(data: FloatArray, tensorShape: LongArray): FloatArray {
val transposedData = Transpose(axes = intArrayOf(2, 0, 1)).apply(
data,
ImageShape(width = tensorShape[0], height = tensorShape[1], channels = tensorShape[2])
)
// TODO: should be returned from the Transpose from apply method
val transposedShape = longArrayOf(tensorShape[2], tensorShape[0], tensorShape[1])
return transposedData
}
override fun pretrainedModel(modelHub: ModelHub): Fan2D106FaceAlignmentModel {
return Fan2D106FaceAlignmentModel(modelHub.loadModel(this))
}
}
}
}
internal fun resNetOnnxPreprocessing(data: FloatArray, tensorShape: LongArray): FloatArray {
val transposedData = Transpose(axes = intArrayOf(2, 0, 1)).apply(
data,
ImageShape(width = tensorShape[0], height = tensorShape[1], channels = tensorShape[2])
)
// TODO: should be returned from the Transpose from apply method
val transposedShape = longArrayOf(tensorShape[2], tensorShape[0], tensorShape[1])
return preprocessInput(
transposedData,
transposedShape,
inputType = InputType.TF,
channelsLast = false
)
}
| 56 |
Kotlin
|
66
| 695 |
a47add7c20147ab5d43ab1c65010e901582fbf78
| 15,922 |
KotlinDL
|
Apache License 2.0
|
app/src/androidTest/java/com/test/api/helper/RetrofitDelegateHelper.kt
|
ManzhulaAnna
| 404,051,375 | false |
{"Kotlin": 111686, "Java": 1387}
|
package com.test.api.helper
import com.google.gson.FieldNamingPolicy
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.test.data.network.EventsService
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.ResponseBody
import okhttp3.ResponseBody.Companion.toResponseBody
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.mock.BehaviorDelegate
import retrofit2.mock.MockRetrofit
import retrofit2.mock.NetworkBehavior
import java.util.concurrent.TimeUnit
class RetrofitDelegateHelper {
fun createResponseBody(contentJson: String?): ResponseBody? {
return contentJson?.toResponseBody("application/json".toMediaTypeOrNull())
}
fun createBehaviorDelegate(baseUrl: String): BehaviorDelegate<EventsService> {
val retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(createCustomGson()))
.baseUrl(baseUrl)
.build()
val mockRetrofit = MockRetrofit.Builder(retrofit)
.networkBehavior(createNetworkBehaviorDelegate())
.build()
return mockRetrofit.create(EventsService::class.java)
}
private fun createCustomGson(): Gson {
return GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create()
}
private fun createNetworkBehaviorDelegate(): NetworkBehavior {
val networkBehavior = NetworkBehavior.create()
networkBehavior.setFailurePercent(0)
networkBehavior.setDelay(0, TimeUnit.MILLISECONDS)
return networkBehavior
}
}
| 0 |
Kotlin
|
1
| 0 |
4a06616b14298e4003fb0ed15b012f2f1b4cd19b
| 1,641 |
RoomPaging3TestProject
|
Apache License 2.0
|
src/test/kotlin/solutions/xml/render/DocTypeRendererTest.kt
|
jeffgbutler
| 126,641,662 | false | null |
package solutions.xml.render
import org.assertj.core.api.Assertions.*
import org.junit.Test
import solutions.xml.render.DocTypeRendererTest.DtdInfo.DTD_LOCATION
import solutions.xml.render.DocTypeRendererTest.DtdInfo.DTD_NAME
import solutions.xml.model.PublicDocType
import solutions.xml.model.SystemDocType
class DocTypeRendererTest {
@Test
fun testPublicDocType() {
val docType = PublicDocType(DTD_LOCATION, DTD_NAME)
val dcType = DocTypeRenderer().render(docType)
assertThat(dcType).isEqualTo("""PUBLIC "$DTD_NAME" "$DTD_LOCATION"""")
}
@Test
fun testSystemDocType() {
val docType = SystemDocType(DTD_LOCATION)
val dcType = DocTypeRenderer().render(docType)
assertThat(dcType).isEqualTo("""SYSTEM "$DTD_LOCATION"""")
}
object DtdInfo {
const val DTD_NAME = "-//Example//EN"
const val DTD_LOCATION = "example.dtd"
}
}
| 0 |
Kotlin
|
0
| 2 |
aa5cc2a55e719e682849fe176e38ccd72aec3d7c
| 927 |
practical-functional-kotlin
|
MIT License
|
app/composeapp/src/main/java/com/xanthenite/isining/composeapp/component/action/ISiningActions.kt
|
ajcatindig
| 534,358,909 | false |
{"Kotlin": 484017}
|
package com.xanthenite.isining.composeapp.component.action
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Lightbulb
import androidx.compose.material.icons.outlined.LightbulbCircle
import androidx.compose.material.icons.outlined.QrCodeScanner
import androidx.compose.material.icons.outlined.Share
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import com.xanthenite.isining.R
@Composable
fun ThemeSwitchAction(onToggle: () -> Unit) {
IconButton(onClick = onToggle) {
Icon(Icons.Outlined.Lightbulb ,
contentDescription = "Theme switch" ,
Modifier.padding(8.dp),
tint = MaterialTheme.colors.onPrimary
)
}
}
@Composable
fun ArScanAction(onClick : () -> Unit) {
IconButton(onClick = onClick) {
Icon(Icons.Outlined.QrCodeScanner,
contentDescription = "AR Scanner",
Modifier.padding(8.dp),
tint = MaterialTheme.colors.onPrimary
)
}
}
@Composable
fun ShareAction(onClick : () -> Unit ) {
IconButton(onClick = onClick) {
Icon(imageVector = Icons.Outlined.Share ,
contentDescription = "Share",
Modifier.padding(8.dp),
tint = MaterialTheme.colors.onPrimary)
}
}
| 1 |
Kotlin
|
2
| 4 |
c91e1d2240fe7f189f001813726e1171e0856047
| 1,576 |
iSining
|
Apache License 2.0
|
app/composeapp/src/main/java/com/xanthenite/isining/composeapp/component/action/ISiningActions.kt
|
ajcatindig
| 534,358,909 | false |
{"Kotlin": 484017}
|
package com.xanthenite.isining.composeapp.component.action
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Lightbulb
import androidx.compose.material.icons.outlined.LightbulbCircle
import androidx.compose.material.icons.outlined.QrCodeScanner
import androidx.compose.material.icons.outlined.Share
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import com.xanthenite.isining.R
@Composable
fun ThemeSwitchAction(onToggle: () -> Unit) {
IconButton(onClick = onToggle) {
Icon(Icons.Outlined.Lightbulb ,
contentDescription = "Theme switch" ,
Modifier.padding(8.dp),
tint = MaterialTheme.colors.onPrimary
)
}
}
@Composable
fun ArScanAction(onClick : () -> Unit) {
IconButton(onClick = onClick) {
Icon(Icons.Outlined.QrCodeScanner,
contentDescription = "AR Scanner",
Modifier.padding(8.dp),
tint = MaterialTheme.colors.onPrimary
)
}
}
@Composable
fun ShareAction(onClick : () -> Unit ) {
IconButton(onClick = onClick) {
Icon(imageVector = Icons.Outlined.Share ,
contentDescription = "Share",
Modifier.padding(8.dp),
tint = MaterialTheme.colors.onPrimary)
}
}
| 1 |
Kotlin
|
2
| 4 |
c91e1d2240fe7f189f001813726e1171e0856047
| 1,576 |
iSining
|
Apache License 2.0
|
app/src/main/java/com/martinszuc/phishing_emails_detection/data/model/Classifier.kt
|
martinszuc
| 698,968,668 | false |
{"Kotlin": 124811, "Python": 16263}
|
package com.martinszuc.phishing_emails_detection.data.model
import android.content.Context
import com.chaquo.python.PyObject
import com.chaquo.python.Python
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import javax.inject.Inject
/**
* Classifier class for phishing email detection.
* @author [email protected]
*/
class Classifier @Inject constructor(private val context: Context) {
private var py: Python? = null // Python instance
private var pyModule: PyObject? = null // Python module
suspend fun initializePython() = withContext(Dispatchers.IO) {
py = Python.getInstance()
pyModule = py?.getModule("classifier")
}
/**
* Classify an email text.
* @param emailText The email text to classify.
* @return The classification result.
*/
fun classify(mboxString: String): Boolean {
// Call the predict_email function and get the result
val prediction = pyModule?.callAttr("predict_email", mboxString).toString()
// Assuming the Python function returns "Phishing" or "Safe"
return prediction == "Phishing"
}
}
| 0 |
Kotlin
|
0
| 0 |
f9edd384994e8656c3f9a9720d3757dccaee276b
| 1,144 |
phishing-emails-detection
|
MIT License
|
src/main/kotlin/no/nav/tiltak/tiltaknotifikasjon/avtale/Tiltakstype.kt
|
navikt
| 718,075,727 | false |
{"Kotlin": 63993, "Dockerfile": 247}
|
package no.nav.arbeidsgiver.tiltakhendelseaktivitetsplan.kafka
enum class Tiltakstype(val beskrivelse: String, val skalTilAktivitetsplan: Boolean) {
ARBEIDSTRENING("Arbeidstrening", false),
MIDLERTIDIG_LONNSTILSKUDD("Midlertidig lønnstilskudd", true),
VARIG_LONNSTILSKUDD("Varig lønnstilskudd", true),
MENTOR("Mentor", false),
INKLUDERINGSTILSKUDD("Inkluderingstilskudd", false),
SOMMERJOBB("Sommerjobb", false);
}
| 4 |
Kotlin
|
0
| 0 |
ee7ea4d2f4afdf841f96be473872246d37ebdf72
| 439 |
tiltak-notifikasjon
|
MIT License
|
generator/graphql-kotlin-federation/src/main/kotlin/com/expediagroup/graphql/generator/federation/execution/resolverexecutor/TypeResolverExecutor.kt
|
ExpediaGroup
| 148,706,161 | false |
{"Kotlin": 2410561, "MDX": 720089, "HTML": 12165, "JavaScript": 10447, "CSS": 297, "Dockerfile": 147}
|
/*
* Copyright 2022 Expedia, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.expediagroup.graphql.generator.federation.execution.resolverexecutor
import com.expediagroup.graphql.generator.federation.execution.FederatedTypeResolver
import graphql.schema.DataFetchingEnvironment
import java.util.concurrent.CompletableFuture
sealed interface TypeResolverExecutor<T : FederatedTypeResolver> {
fun execute(
resolvableEntities: List<ResolvableEntity<T>>,
environment: DataFetchingEnvironment
): CompletableFuture<List<Map<Int, Any?>>>
}
| 68 |
Kotlin
|
345
| 1,739 |
d3ad96077fc6d02471f996ef34c67066145acb15
| 1,091 |
graphql-kotlin
|
Apache License 2.0
|
authentication-service/src/main/kotlin/com/michibaum/authentication_service/config/UsermanagementClient.kt
|
MichiBaum
| 246,055,538 | false |
{"Kotlin": 25094, "TypeScript": 16475, "HTML": 4356, "SCSS": 347, "CSS": 125}
|
package com.michibaum.authentication_service.config
import org.springframework.cloud.openfeign.FeignClient
import com.michibaum.usermanagement_library.UserManagementEndpoints
@FeignClient(value = "usermanagement-service")
interface UsermanagementClient : UserManagementEndpoints
| 4 |
Kotlin
|
0
| 1 |
e616edba060609f7a59a98cfdedff3cfc3b52392
| 280 |
Microservices
|
Apache License 2.0
|
dialog/app/src/main/java/com/example/myapplication/MainActivity.kt
|
Xwyzworms
| 325,579,485 | false | null |
package com.example.myapplication
import android.app.Dialog
import android.content.DialogInterface
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.Window
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import com.google.android.material.snackbar.Snackbar
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btnToast : Button = findViewById(R.id.btnToast)
val btnSnackBar : Button = findViewById(R.id.btnSnackBar)
val btnAlertDialog : Button = findViewById(R.id.btnAlertDialog)
val btnCustom : Button = findViewById(R.id.btnCustomDialog)
btnToast.setOnClickListener {
Toast.makeText(this, "Ini toast" , Toast.LENGTH_LONG).show()
Log.d("Toast","ToastnyaGaMuncul?")
}
btnSnackBar.setOnClickListener{
Snackbar.make(it,"ini Scakbar",Snackbar.LENGTH_SHORT).show()
}
btnAlertDialog.setOnClickListener {
val AlertObj = AlertDialog.Builder(this)
AlertObj.setPositiveButton("Yosh") { dialog, which ->
Toast.makeText(applicationContext,"OK Dipicit",Toast.LENGTH_LONG).show()
dialog.dismiss()
}
AlertObj.setNegativeButton("Cancel") {dialog,which ->
Toast.makeText(applicationContext, "cancel terpicit", Toast.LENGTH_SHORT).show()
dialog.dismiss()
}
AlertObj
.setTitle("Message")
.setMessage("Message Alert Dialog")
AlertObj.create().show()
}
btnCustom.setOnClickListener {
val Dialog = Dialog(this)
Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
Dialog.setCancelable(false)
Dialog.setContentView(R.layout.custom_dialog)
val btnCancel : Button = Dialog.findViewById(R.id.btnCancel)
val btnSubmit : Button = Dialog.findViewById(R.id.btnSubmit)
btnCancel.setOnClickListener {
Toast.makeText(this@MainActivity,"klik Cancel",Toast.LENGTH_LONG).show()
Dialog.dismiss()
}
btnSubmit.setOnClickListener {
Toast.makeText(this@MainActivity,"Sabmit",Toast.LENGTH_LONG).show()
Dialog.dismiss()
}
Dialog.show()
}
}
}
| 0 |
Kotlin
|
0
| 0 |
8b9491cfb1bae007845e42bf55f3590dbf031fe0
| 2,605 |
BunchOfKotlinApps
|
MIT License
|
src/nativeTest/kotlin/Day17Test.kt
|
rubengees
| 576,436,006 | false |
{"Kotlin": 67428}
|
import kotlinx.coroutines.runBlocking
import kotlin.test.Test
import kotlin.test.assertEquals
class Day17Test {
private val day = Day17()
private val example = """
>>><<><>><<<>><>>><<<>>><<<><<<>><>><<>>
""".trimIndent()
@Test
fun part1Example() = runBlocking(workerDispatcher()) {
assertEquals("3068", day.part1(example))
}
@Test
fun part1Input() = runBlocking(workerDispatcher()) {
assertEquals("3059", day.part1(readInputFile(17)))
}
@Test
fun part2Example() = runBlocking(workerDispatcher()) {
assertEquals("", day.part2(example))
}
@Test
fun part2Input() = runBlocking(workerDispatcher()) {
assertEquals("", day.part2(readInputFile(17)))
}
}
| 0 |
Kotlin
|
0
| 0 |
21f03a1c70d4273739d001dd5434f68e2cc2e6e6
| 754 |
advent-of-code-2022
|
MIT License
|
app/src/main/java/com/sergiom/cabishop/ui/cartview/viewAdapter/CartViewAdapter.kt
|
SergioMardez
| 533,396,871 | false |
{"Kotlin": 56418}
|
package com.sergiom.cabishop.ui.cartview.viewAdapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.sergiom.cabishop.databinding.CartRecyclerLayoutBinding
import com.sergiom.cabishop.utils.setDiscount
import com.sergiom.data.model.CartAdapterItem
import com.sergiom.data.model.ShopDiscountModel
import com.sergiom.data.model.ShopItemDataBase
class CartViewAdapter(private val listener: DeleteFromCartListener): RecyclerView.Adapter<CartViewHolder>() {
private val items = ArrayList<CartAdapterItem>()
interface DeleteFromCartListener {
fun onDeleteClicked(item: ShopItemDataBase)
fun setTotalAmount(amount: Double)
}
fun setItems(items: List<ShopItemDataBase>, discounts: ShopDiscountModel) {
this.items.clear()
this.items.addAll(items.setDiscount(discounts))
setTotalPrice()
notifyDataSetChanged()
}
private fun setTotalPrice() {
var amount = 0.0
for (item in items) {
amount += item.priceDiscount
}
listener.setTotalAmount(amount)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CartViewHolder {
val binding: CartRecyclerLayoutBinding = CartRecyclerLayoutBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return CartViewHolder(binding)
}
override fun onBindViewHolder(holder: CartViewHolder, position: Int) {
holder.bind(items[position], listener)
}
override fun getItemCount(): Int = items.size
}
| 0 |
Kotlin
|
0
| 0 |
c891db0dd294f24917db1586024752aa24d9a94f
| 1,589 |
cabifyChallenge
|
Apache License 2.0
|
src/main/java/com/tingfeng/service/impl/GirlServiceImpl.kt
|
huitoukest
| 115,497,936 | false |
{"JavaScript": 26355, "Kotlin": 10003, "HTML": 2513}
|
package com.tingfeng.service.impl
import com.tingfeng.service.GirlService
import org.springframework.stereotype.Service
@Service
class GirlServiceImpl : GirlService {
}
| 0 |
JavaScript
|
0
| 0 |
fc5a4c5e2dcf961f82b3b5dfd6a19023ae69a9b3
| 171 |
springboot-demo-kotlin
|
Apache License 2.0
|
src/main/java/com/tingfeng/service/impl/GirlServiceImpl.kt
|
huitoukest
| 115,497,936 | false |
{"JavaScript": 26355, "Kotlin": 10003, "HTML": 2513}
|
package com.tingfeng.service.impl
import com.tingfeng.service.GirlService
import org.springframework.stereotype.Service
@Service
class GirlServiceImpl : GirlService {
}
| 0 |
JavaScript
|
0
| 0 |
fc5a4c5e2dcf961f82b3b5dfd6a19023ae69a9b3
| 171 |
springboot-demo-kotlin
|
Apache License 2.0
|
shared/src/main/kotlin/com/mazekine/everscale/models/Address.kt
|
vp-mazekine
| 429,726,535 | false |
{"Kotlin": 315585, "Java": 68444, "Max": 156}
|
package com.mazekine.everscale.models
data class Address(
val base64url: String,
val hex: String,
val workchainId: Int
)
| 2 |
Kotlin
|
4
| 8 |
09a2b9cd1226072c18b269e75d3f53b249f517bf
| 134 |
EverCraft
|
Apache License 2.0
|
app/src/main/java/com/lijukay/famecrew/interfaces/OnLongClickInterface.kt
|
Lijukay
| 647,305,191 | false |
{"Kotlin": 167115, "Java": 1135}
|
package com.lijukay.famecrew.interfaces
interface OnLongClickInterface {
fun onLongClick(position: Int)
}
| 0 |
Kotlin
|
0
| 0 |
07e1714cc43d94f75dfb6287bed7fe0e3b246e6f
| 110 |
HomeHarmony
|
MIT License
|
app/src/main/java/com/zasko/boxtool/novel/activity/ReadBookActivity.kt
|
Zhangsongsong
| 678,715,300 | false |
{"Kotlin": 93532, "Java": 54609}
|
package com.zasko.boxtool.novel.activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.viewbinding.ViewBinding
import com.zasko.boxtool.R
import com.zasko.boxtool.base.act.BaseActivity
import com.zasko.boxtool.databinding.NovelBookReadActivityBinding
import com.zasko.boxtool.novel.ArticleBean
import com.zasko.boxtool.novel.fragment.ReadBookFragment
class ReadBookActivity : BaseActivity() {
companion object {
const val KEY_TRANS_DATA = "key_tran_data"
fun start(context: Context, bean: ArticleBean) {
val intent = Intent(context, ReadBookActivity::class.java)
intent.putExtra(KEY_TRANS_DATA, bean)
context.startActivity(intent)
}
}
override fun createViewBind(): ViewBinding {
return NovelBookReadActivityBinding.inflate(layoutInflater)
}
override fun initView() {
super.initView()
supportFragmentManager.beginTransaction().add(R.id.fragmentLayout, ReadBookFragment().apply {
arguments = Bundle().apply {
putSerializable(KEY_TRANS_DATA, intent.getSerializableExtra(KEY_TRANS_DATA))
}
}).commit()
}
}
| 0 |
Kotlin
|
0
| 0 |
1bbb53b0175dfa202eb8e7f1560ea21339f59f31
| 1,224 |
BoxTool
|
Apache License 2.0
|
sample/ios-framework/src/iosMain/kotlin/com/addhen/klocation/sample/shared/MainViewController.kt
|
addhen
| 839,996,776 | false |
{"Kotlin": 50463, "Shell": 1491}
|
// Copyright 2024, Addhen Ltd and the k-location project contributors
// SPDX-License-Identifier: Apache-2.0
package com.addhen.klocation.sample.shared
import androidx.compose.ui.window.ComposeUIViewController
import androidx.navigation.compose.rememberNavController
import com.addhen.klocation.LocationService
import com.addhen.klocation.cllocation
import com.addhen.klocation.sample.shared.permission.LocationPermissionScreen
import com.addhen.klocation.sample.shared.permission.LocationPermissionViewModel
import dev.icerock.moko.permissions.Permission
import dev.icerock.moko.permissions.ios.PermissionsController
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.useContents
import platform.UIKit.UIViewController
@OptIn(ExperimentalForeignApi::class)
@Suppress("standard:function-naming")
public fun mainViewController(): UIViewController = ComposeUIViewController {
val navController = rememberNavController()
SampleApp(
navController = navController,
permissionsController = PermissionsController(),
permissionScreen = {
val viewModel = LocationPermissionViewModel(
PermissionsController(),
Permission.LOCATION,
)
LocationPermissionScreen(viewModel, navController)
},
locationScreen = {
val locationService = LocationService()
val viewModel = LocationViewModel(LocationService())
LocationScreen(viewModel, locationService) { locationState ->
val location = locationState.cllocation
location?.coordinate?.useContents {
"$latitude,$longitude"
} ?: ""
}
},
)
}
| 0 |
Kotlin
|
0
| 7 |
ac6aac259da9632233fca1afc8c97fe314a45e27
| 1,611 |
klocation
|
Apache License 2.0
|
fontawesome/src/de/msrd0/fontawesome/icons/FA_CAMPGROUND.kt
|
msrd0
| 363,665,023 | false | null |
/* @generated
*
* This file is part of the FontAwesome Kotlin library.
* https://github.com/msrd0/fontawesome-kt
*
* This library is not affiliated with FontAwesome.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.msrd0.fontawesome.icons
import de.msrd0.fontawesome.Icon
import de.msrd0.fontawesome.Style
import de.msrd0.fontawesome.Style.SOLID
object FA_CAMPGROUND: Icon {
override val name get() = "Campground"
override val unicode get() = "f6bb"
override val styles get() = setOf(SOLID)
override fun svg(style: Style) = when(style) {
SOLID -> """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><path d="M624 448h-24.68L359.54 117.75l53.41-73.55c5.19-7.15 3.61-17.16-3.54-22.35l-25.9-18.79c-7.15-5.19-17.15-3.61-22.35 3.55L320 63.3 278.83 6.6c-5.19-7.15-15.2-8.74-22.35-3.55l-25.88 18.8c-7.15 5.19-8.74 15.2-3.54 22.35l53.41 73.55L40.68 448H16c-8.84 0-16 7.16-16 16v32c0 8.84 7.16 16 16 16h608c8.84 0 16-7.16 16-16v-32c0-8.84-7.16-16-16-16zM320 288l116.36 160H203.64L320 288z"/></svg>"""
else -> null
}
}
| 0 |
Kotlin
|
0
| 0 |
2fc4755051325e730e9d012c9dfe94f5ea800fdd
| 1,574 |
fontawesome-kt
|
Apache License 2.0
|
app/src/main/java/datlowashere/project/rcoffee/data/repository/AddressRepository.kt
|
SUMMER24-R-Coffee
| 801,556,779 | false |
{"Kotlin": 273830, "Java": 10931}
|
package datlowashere.project.rcoffee.data.repository
import datlowashere.project.rcoffee.data.model.Address
import datlowashere.project.rcoffee.data.network.ApiClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class AddressRepository {
private val apiService = ApiClient.instance
suspend fun getAddresses(emailUser: String, callback: (List<Address>?) -> Unit) {
apiService.getAddresses(emailUser).enqueue(object : Callback<List<Address>> {
override fun onResponse(call: Call<List<Address>>, response: Response<List<Address>>) {
if (response.isSuccessful) {
callback(response.body())
} else {
callback(null)
}
}
override fun onFailure(call: Call<List<Address>>, t: Throwable) {
callback(null)
}
})
}
suspend fun addAddress(address: Address, callback: (Address?) -> Unit) {
apiService.addAddress(address).enqueue(object : Callback<Address> {
override fun onResponse(call: Call<Address>, response: Response<Address>) {
if (response.isSuccessful) {
callback(response.body())
} else {
callback(null)
}
}
override fun onFailure(call: Call<Address>, t: Throwable) {
callback(null)
}
})
}
}
| 0 |
Kotlin
|
0
| 1 |
dbe25b6c2c22d376d30a21e8d11a0b0b6b0ca287
| 1,475 |
R-Coffee_App
|
MIT License
|
clef-workflow-api/clef-workflow-api-store/clef-workflow-api-store-action/src/main/java/io/arkitik/clef/workflow/api/store/action/query/ActionParameterStoreQuery.kt
|
arkitik
| 443,436,455 | false |
{"Kotlin": 433170, "Shell": 268, "Dockerfile": 244}
|
package io.arkitik.clef.workflow.api.store.action.query
import io.arkitik.clef.workflow.api.domain.action.ActionIdentity
import io.arkitik.clef.workflow.api.domain.action.ActionParameterIdentity
import io.arkitik.radix.develop.store.query.StoreQuery
/**
* Created By [**<NAME> **](https://www.linkedin.com/in/iloom/)<br></br>
* Created At **14**, **Sat Mar, 2020**
* Project **clef-workflow** [arkitik.IO](https://arkitik.io/)<br></br>
*/
interface ActionParameterStoreQuery : StoreQuery<String, ActionParameterIdentity> {
fun findAllByAction(
action: ActionIdentity,
): List<ActionParameterIdentity>
}
| 0 |
Kotlin
|
0
| 0 |
785e1b4ee583b6a6e3ea01e656eecd8365f171ef
| 626 |
clef-workflow
|
Apache License 2.0
|
test/ad/kata/aoc2021/day10/AutocompleteScoreTest.kt
|
andrej-dyck
| 433,401,789 | false |
{"Kotlin": 161613}
|
package ad.kata.aoc2021.day10
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.CsvSource
class AutocompleteScoreTest {
@ParameterizedTest
@CsvSource(
"(, 1", // missing )
"[, 2", // missing ]
"{, 3", // missing }
"<, 4", // missing >
)
fun `has following autocomplete score for missing chars in incomplete lines`(
incompleteLine: String,
expectedScore: Long
) {
assertThat(
autocompleteScoreOf(incompleteLine).scores
).containsExactly(
Score(expectedScore)
)
}
@ParameterizedTest
@CsvSource(
"((, 6", // missing ))
"[(, 7", // missing )]
"{(, 8", // missing )}
"<(, 9", // missing )>
"([, 11", // missing ])
"[[, 12", // missing ]]
"{[, 13", // missing ]}
"<[, 14", // missing ]>
"({, 16", // missing })
"[{, 17", // missing }]
"{{, 18", // missing }}
"<{, 19", // missing }>
"(<, 21", // missing >)
"[<, 22", // missing >]
"{<, 23", // missing >}
"<<, 24", // missing >>
"[({(<(())[]>[[{[]{<()<>>, 288957", // missing }}]])})]
"[(()[<>])]({[<{<<[]>>(, 5566", // missing )}>]})
"(((({<>}<{<{<>}{[]{[]{}, 1480781", // missing }}>}>))))
"{<[[]]>}<{[{[{[]{()[[[], 995444", // missing ]]}}]}]}>
"<{([{{}}[<[[[<>{}]]]>[]], 294", // missing ])}>
)
fun `the score of an incomplete line is the missing bracket score plus the intermediate total times 5`(
incompleteLine: String,
expectedScore: Long
) {
assertThat(
autocompleteScoreOf(incompleteLine).scores
).containsExactly(
Score(expectedScore)
)
}
@Test
fun `does not award score points for valid lines`() {
assertThat(autocompleteScoreOf("()").scores).isEmpty()
}
@Test
fun `does not award score points corrupted lines`() {
assertThat(autocompleteScoreOf("(>").scores).isEmpty()
}
@ParameterizedTest
@CsvSource(
"(, 1",
"[, 2",
"{, 3",
"<, 4",
"<^(^[, 2",
"<^(^{, 3",
"<^(^(, 1",
"<^(^<, 4",
"(<^<^(, 4",
"(<^<^(, 4",
"[({(<(())[]>[[{[]{<()<>>^[(()[<>])]({[<{<<[]>>(^(((({<>}<{<{<>}{[]{[]{}, 288957",
"[(()[<>])]({[<{<<[]>>(^{<[[]]>}<{[{[{[]{()[[[]^<{([{{}}[<[[[<>{}]]]>[]], 5566",
)
fun `winning autocomplete score is the middle score`(
incompleteLines: String,
expectedWinnerScore: Long
) {
assertThat(
autocompleteScoreOf(
*incompleteLines.split('^').toTypedArray()
).winner()
).isEqualTo(
Score(expectedWinnerScore)
)
}
@Test
fun `winning autocomplete score for the sample data is 288957`() {
assertThat(
autocompleteScoreOf(
"[({(<(())[]>[[{[]{<()<>>",
"[(()[<>])]({[<{<<[]>>(",
"(((({<>}<{<{<>}{[]{[]{}",
"{<[[]]>}<{[{[{[]{()[[[]",
"<{([{{}}[<[[[<>{}]]]>[]]"
).winner()
).isEqualTo(
Score(points = 288_957)
)
}
}
internal fun autocompleteScoreOf(vararg lines: String) =
AutocompleteScore(NavigationProgram(*lines))
| 0 |
Kotlin
|
0
| 0 |
28d374fee4178e5944cb51114c1804d0c55d1052
| 3,485 |
advent-of-code-2021
|
MIT License
|
src/main/kotlin/me/zama/simple_di/ComponentBuilder.kt
|
giacomozama
| 520,867,423 | false | null |
package me.zama.simple_di
@DslMarker
internal annotation class ComponentBuilderDsl
@ComponentBuilderDsl
internal interface ComponentBuilderScope {
fun module(module: Module)
}
internal class ComponentBuilderScopeImpl(
private val modules: MutableSet<Module>
) : ComponentBuilderScope {
override fun module(module: Module) {
modules.add(module)
}
}
internal fun component(build: ComponentBuilderScope.() -> Unit): Component {
val modules = mutableSetOf<Module>()
ComponentBuilderScopeImpl(modules).build()
return StandardComponent(modules)
}
internal fun componentOf(vararg modules: Module): Component = StandardComponent(modules.toSet())
internal fun validatingComponent(build: ComponentBuilderScope.() -> Unit): Component {
val modules = mutableSetOf<Module>()
ComponentBuilderScopeImpl(modules).build()
return ValidatingComponent(modules)
}
internal fun validatingComponentOf(vararg modules: Module): Component = ValidatingComponent(modules.toSet())
| 0 |
Kotlin
|
0
| 0 |
5a4faeab3a8d5dba614120de312a4fbb5b014caf
| 1,008 |
simple-di
|
MIT License
|
src/main/kotlin/com/prejade/ktadmin/modules/sys/convert/SysPermissionConvert.kt
|
maioria
| 328,279,064 | false | null |
package com.prejade.ktadmin.modules.sys.convert
import com.prejade.ktadmin.common.BaseConvert
import com.prejade.ktadmin.modules.sys.entity.SysPermission
import com.prejade.ktadmin.modules.sys.enumes.SysPermissionType
import com.prejade.ktadmin.modules.sys.model.AddPermission
import com.prejade.ktadmin.modules.sys.model.PermissionTree
import com.prejade.ktadmin.modules.sys.model.SysPermissionModel
import com.prejade.ktadmin.modules.sys.service.SysPermissionService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Lazy
import org.springframework.stereotype.Component
@Component
class SysPermissionConvert : BaseConvert<SysPermission, SysPermissionModel, AddPermission>() {
@Autowired
@Lazy
lateinit var sysPermissionService: SysPermissionService
override fun castModel(entity: SysPermission): SysPermissionModel {
val model = SysPermissionModel()
model.id = entity.id
model.name = entity.name
model.label = entity.label
model.type = entity.type.name
model.typeName = entity.type.getNameValue()
model.parentId = entity.parent?.id
model.parentName = entity.parent?.name
return model
}
override fun copyProperties(ori: SysPermission, tar: SysPermission) {
ori.name = tar.name
ori.label = tar.label
ori.type = tar.type
ori.parent = tar.parent
}
override fun castEntity(model: AddPermission): SysPermission {
val entity = SysPermission()
entity.id = model.id
entity.name = model.name
entity.label = model.label
if (model.parentName != null)
entity.parent = model.parentName?.let { sysPermissionService.findByName(it) }
entity.type = SysPermissionType.valueOf(model.type)
return entity
}
fun castTree(permissions: List<SysPermission>): List<PermissionTree> {
val treeModels: MutableList<PermissionTree> = mutableListOf()
val map = hashMapOf<Int, PermissionTree>()
var treeModel: PermissionTree
var parent: SysPermission?
for (entity in permissions) {
treeModel = PermissionTree()
treeModel.id = entity.id
treeModel.name = entity.name
treeModel.label = entity.label
treeModel.type = entity.type.name
treeModel.typeName = entity.type.getNameValue()
treeModel.parentName = entity.parent?.name
parent = entity.parent
map[entity.id!!] = treeModel
if (parent != null) {
map[parent.id]?.addChildren(treeModel)
} else {
treeModels.add(treeModel)
}
}
return treeModels
}
}
| 0 |
Kotlin
|
0
| 2 |
c91ef44ff9fcd520058e17b4ea20306cd27548ba
| 2,775 |
ktadmin
|
MIT License
|
pinkman-rx3/src/androidTest/java/com/redmadrobot/pinkman_rx3/RxPinkmanTest.kt
|
RedMadRobot
| 273,254,357 | false | null |
package com.redmadrobot.pinkman_rx3
import android.content.Context
import androidx.test.filters.SmallTest
import androidx.test.platform.app.InstrumentationRegistry
import com.redmadrobot.pinkman.Pinkman
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.schedulers.Schedulers
import org.junit.After
import org.junit.Before
import org.junit.Test
import java.io.File
@SmallTest
class RxPinkmanTest {
private lateinit var applicationContext: Context
private lateinit var pinkman: Pinkman
private val testScheduler = Schedulers.trampoline()
@Before
fun setUp() {
applicationContext = InstrumentationRegistry.getInstrumentation().targetContext
pinkman = Pinkman(applicationContext)
}
@After
fun tearDown() {
File(applicationContext.filesDir, "pinkman").delete()
}
@Test
fun createPin() {
pinkman.createPinAsync("0000", scheduler = testScheduler)
.andThen(Single.fromCallable { File(applicationContext.filesDir, "pinkman").exists() })
.test()
.assertValue(true)
}
@Test
fun changePin() {
pinkman.createPinAsync("0000", scheduler = testScheduler)
.andThen(pinkman.changePinAsync("0000", "1111", scheduler = testScheduler))
.andThen(pinkman.isValidPinAsync("1111", scheduler = testScheduler))
.test()
.assertValue(true)
}
@Test
fun isValidPin() {
pinkman.createPinAsync("0000", scheduler = testScheduler)
.andThen(pinkman.isValidPinAsync("0000", scheduler = testScheduler))
.test()
.assertValue(true)
}
}
| 1 |
Kotlin
|
10
| 80 |
137c3d0ffe8504eaa90b6bc99fc72e448f80d8ee
| 1,663 |
PINkman
|
MIT License
|
m5-hw7-vafs-repo-tests/src/main/kotlin/RepoRuleCreateTest.kt
|
smith1984
| 587,390,812 | false | null |
package ru.beeline.vafs.repository.test
import kotlinx.coroutines.ExperimentalCoroutinesApi
import ru.beeline.vafs.common.models.*
import ru.beeline.vafs.common.repo.*
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
@OptIn(ExperimentalCoroutinesApi::class)
abstract class RepoRuleCreateTest {
abstract val repo: IRuleRepository
protected open val lockNew: VafsRuleLock = VafsRuleLock("20000000-0000-0000-0000-000000000002")
private val createObj = VafsRule(
description = "create rule description",
userId = VafsUserId("operator-123"),
priority = 1000,
listForNumberA = listOf("79995551111"),
typeOperationA = VafsTypeOperationList.EXCLUDE,
listForNumberB = listOf("79995551113", "79995551112"),
typeOperationB = VafsTypeOperationList.EXCLUDE,
typeOperationCount = VafsTypeOperationCount.LESS,
targetCount = 3000,
valueIsTrue = false,
typeOperationAB = VafsTypeOperationBool.AND,
typeOperationABCount = VafsTypeOperationBool.AND,
)
@Test
fun createSuccess() = runRepoTest {
val result = repo.createRule(DbRuleRequest(createObj))
val expected = createObj.copy(id = result.data?.id ?: VafsRuleId.NONE)
assertEquals(true, result.isSuccess)
assertEquals(expected.userId, result.data?.userId)
assertEquals(expected.description, result.data?.description)
assertEquals(expected.priority, result.data?.priority)
assertEquals(expected.listForNumberA, result.data?.listForNumberA)
assertEquals(expected.typeOperationA, result.data?.typeOperationA)
assertEquals(expected.listForNumberB, result.data?.listForNumberB)
assertEquals(expected.typeOperationB, result.data?.typeOperationB)
assertEquals(expected.typeOperationCount, result.data?.typeOperationCount)
assertEquals(expected.targetCount, result.data?.targetCount)
assertEquals(expected.valueIsTrue, result.data?.valueIsTrue)
assertEquals(expected.typeOperationAB, result.data?.typeOperationAB)
assertEquals(expected.typeOperationABCount, result.data?.typeOperationABCount)
assertNotEquals(VafsRuleId.NONE, result.data?.id)
assertEquals(emptyList(), result.errors)
}
companion object : BaseInitRules("create") {
override val initObjects: List<VafsRule> = emptyList()
}
}
| 1 |
Kotlin
|
0
| 0 |
69e1d82f348f89d1f7666fbe24a60a8409cc9566
| 2,444 |
otuskotlin
|
Apache License 2.0
|
app/src/main/java/id/novian/flowablecash/view/report/income_statements/IncomeStatementsViewModel.kt
|
novianr90
| 643,599,093 | false | null |
package id.novian.flowablecash.view.report.income_statements
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import dagger.hilt.android.lifecycle.HiltViewModel
import id.novian.flowablecash.base.vm.BaseViewModel
import id.novian.flowablecash.domain.models.TransactionDomain
import id.novian.flowablecash.domain.repository.TransactionRepository
import id.novian.flowablecash.helpers.CalendarHelper
import io.reactivex.rxjava3.core.Scheduler
import javax.inject.Inject
import javax.inject.Named
@HiltViewModel
class IncomeStatementsViewModel @Inject constructor(
@Named("IO") private val schedulerIo: Scheduler,
@Named("MAIN") private val schedulerMain: Scheduler,
private val repo: TransactionRepository,
val calendarHelper: CalendarHelper,
): BaseViewModel() {
val totalPenjualan: MutableLiveData<Int> = MutableLiveData()
val listOfHpp: MutableLiveData<List<TransactionDomain>> = MutableLiveData()
val totalHpp: MutableLiveData<Int> = MutableLiveData()
val listOfBeban: MutableLiveData<List<TransactionDomain>> = MutableLiveData()
val totalBeban: MutableLiveData<Int> = MutableLiveData()
private val _labaKotor: MutableLiveData<Int> = MutableLiveData()
val labaKotor: LiveData<Int> get() = _labaKotor
private val _labaBersih: MutableLiveData<Int> = MutableLiveData()
val labaBersih: LiveData<Int> get() = _labaBersih
private val hpp = listOf("Bahan Baku", "Bahan Tambahan", "Barang Dagang")
override fun viewModelInitialized() {
getAllTransaction()
}
private fun getAllTransaction() {
val disposable = repo.getAllTransactions()
.doOnNext { (pemasukkan, pengeluaran) ->
val penjualan = pemasukkan.sumOf { it.total }
totalPenjualan.postValue(penjualan)
val sortHpp = pengeluaran.filter { it.transactionName in hpp }
val pembelian = sortHpp.sumOf { it.total }
listOfHpp.postValue(sortHpp)
totalHpp.postValue(pembelian)
val sortBeban = pengeluaran
.filter { it.transactionName !in hpp }
.filter { it.transactionName != "Membayar Hutang" }
.filter { it.transactionName != "Pengeluaran untuk Pembelian Alat Usaha" }
val beban = sortBeban.sumOf { it.total }
listOfBeban.postValue(sortBeban)
totalBeban.postValue(beban)
val countLabaKotor = penjualan - pembelian
_labaKotor.postValue(countLabaKotor)
val countLabaBersih = countLabaKotor - beban
_labaBersih.postValue(countLabaBersih)
}
.subscribeOn(schedulerIo)
.observeOn(schedulerMain)
.subscribe({}, {
it.printStackTrace()
})
compositeDisposable.add(disposable)
}
}
| 0 |
Kotlin
|
0
| 0 |
284e48655157599d58bd897f429fa9c167758197
| 2,922 |
flowable-cash
|
MIT License
|
app/src/main/java/io/github/wulkanowy/utils/FragNavControlerExtension.kt
|
bujakpvp
| 167,613,504 | true |
{"Kotlin": 413721, "IDL": 131}
|
package io.github.wulkanowy.utils
import androidx.fragment.app.Fragment
import com.ncapdevi.fragnav.FragNavController
inline fun FragNavController.setOnViewChangeListener(crossinline listener: (fragment: Fragment?) -> Unit) {
transactionListener = object : FragNavController.TransactionListener {
override fun onFragmentTransaction(fragment: Fragment?, transactionType: FragNavController.TransactionType) {
listener(fragment)
}
override fun onTabTransaction(fragment: Fragment?, index: Int) {
listener(fragment)
}
}
}
fun FragNavController.safelyPopFragment() {
if (!isRootFragment) popFragment()
}
| 0 |
Kotlin
|
0
| 0 |
4da812af392ffbdf55960f8bb8d0d0f46721531b
| 671 |
wulkanowy
|
Apache License 2.0
|
wallet-kit/src/main/kotlin/bitcoin/wallet/kit/models/Inv.kt
|
knyghtryda
| 152,536,499 | true |
{"Kotlin": 342789, "Java": 82146}
|
package bitcoin.wallet.kit.models
import bitcoin.walllet.kit.io.BitcoinInput
import java.io.IOException
class Inv {
var inventory: Array<InventoryItem>
@Throws(IOException::class)
constructor(input: BitcoinInput) {
val count = input.readVarInt() // do not store count
inventory = Array(count.toInt()) {
InventoryItem(input)
}
}
}
| 0 |
Kotlin
|
1
| 0 |
a7ee0e75d50796e31f2f0d7953bf18942917eb13
| 386 |
wallet-kit-android
|
MIT License
|
app/src/main/java/com/wastecreative/wastecreative/presentation/adapter/SectionProfilAdapter.kt
|
kadabengarann
| 493,496,488 | false | null |
package com.wastecreative.wastecreative.presentation.adapter
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.wastecreative.wastecreative.presentation.view.profile.FragmentMarket
import com.wastecreative.wastecreative.presentation.view.profile.KerajinanFragment
class SectionProfilAdapter(activity: AppCompatActivity) : FragmentStateAdapter(activity) {
override fun createFragment(position: Int): Fragment {
var fragment: Fragment? = null
when (position) {
0 -> fragment = KerajinanFragment()
1 -> fragment = FragmentMarket()
}
return fragment as Fragment
}
override fun getItemCount(): Int {
return 2
}
}
| 0 |
Kotlin
|
2
| 0 |
99aaae3c13c90f6e2e86b8d87d881b565f9af1c1
| 792 |
waste-creative
|
Apache License 2.0
|
app/src/main/java/jodevapp/mvpkotlin/ui/PostView.kt
|
jodevapp
| 142,818,760 | false | null |
package jodevapp.mvpkotlin.ui
import jodevapp.mvpkotlin.base.BaseMVPPresenter
import jodevapp.mvpkotlin.main.base.BaseMVPView
import jodevapp.mvpkotlin.model.Post
/**
* Created by Jodevapp on 7/30/2018.
*/
interface PostView {
interface View : BaseMVPView {
fun showProgress()
fun onViewSuccess(post: List<Post>?)
fun onViewError(message: String?)
fun hideProgress()
}
abstract class Presenter : BaseMVPPresenter<View>() {
/**
* Request Weather
*
* @param query the String
*/
abstract fun onRequestPost()
}
}
| 0 |
Kotlin
|
0
| 0 |
d4b48f4bc61c8870ea49b7958e74de4ccf414d66
| 620 |
MVP-Kotlin-UnitTest
|
MIT License
|
app/src/main/java/org/grakovne/lissen/ui/screens/common/RequestNotificationPermissions.kt
|
GrakovNe
| 859,536,477 | false |
{"Kotlin": 215059}
|
package org.grakovne.lissen.ui.screens.common
import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.platform.LocalContext
import androidx.core.content.ContextCompat
@Composable
fun RequestNotificationPermissions() {
val context = LocalContext.current
val permissionRequestLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestPermission(),
onResult = { }
)
LaunchedEffect(Unit) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
val permissionStatus = ContextCompat.checkSelfPermission(
context,
Manifest.permission.POST_NOTIFICATIONS
)
when (permissionStatus == PackageManager.PERMISSION_GRANTED) {
true -> {}
false -> permissionRequestLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
}
}
}
}
| 7 |
Kotlin
|
0
| 20 |
b285aa1f51c6bb242ce45b11a20b4b8212aa6f3f
| 1,199 |
lissen-android
|
MIT License
|
app/src/androidTest/kotlin/com/github/jameshnsears/chance/MainActivityInstrumentedTest.kt
|
jameshnsears
| 725,514,594 | false | null |
package com.github.jameshnsears.chance
import androidx.compose.ui.test.assertIsEnabled
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import com.github.jameshnsears.chance.ui.tab.compose.TabRowTestTag
import com.github.jameshnsears.chance.ui.tab.roll.compose.TabRollTestTag
import com.github.jameshnsears.chance.utility.feature.UtilityFeature
import com.github.jameshnsears.chance.utility.feature.UtilityFeature.Flag
import com.github.jameshnsears.chance.utility.logging.UtilityLoggingInstrumentedHelper
import kotlinx.coroutines.test.runTest
import org.junit.Rule
import org.junit.Test
class MainActivityInstrumentedTest : UtilityLoggingInstrumentedHelper() {
init {
UtilityFeature.enabled = setOf(
Flag.NONE,
Flag.USE_PROTO_REPO
)
}
@get:Rule
val androidComposeTestRule = createAndroidComposeRule<MainActivity>()
@Test
fun startAppForFirstTime() = runTest {
androidComposeTestRule
.onNodeWithTag(TabRowTestTag.TAB_ROW)
.assertExists()
androidComposeTestRule
.onNodeWithText(getString(com.github.jameshnsears.chance.ui.R.string.tab_roll))
.performClick()
androidComposeTestRule
.onNodeWithTag(TabRollTestTag.UNDO)
.assertIsEnabled()
androidComposeTestRule
.onNodeWithTag(TabRollTestTag.ROLL)
.performClick()
}
}
| 4 | null |
2
| 6 |
3abfa1d918d8d34dadc2498888793726cba508a0
| 1,572 |
Chance
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.