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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
demo/src/main/java/com/example/demo/MainActivity.kt
|
HubSpot
| 758,702,773
| false
|
{"Kotlin": 64424, "CSS": 391}
|
package com.example.demo
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.NavController
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.example.demo.databinding.ActivityMainBinding
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.hubspot.mobilesdk.HubspotManager
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@SuppressLint("RestrictedApi")
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var appBarConfiguration: AppBarConfiguration
private val navController by lazy {
(supportFragmentManager.findFragmentById(R.id.navHostFragment) as NavHostFragment).navController
}
private val listener by lazy {
NavController.OnDestinationChangedListener { _, destination, arguments ->
val screensToHideLayout = listOf(R.id.navigation_webview, R.id.fragment_custom_chat_flow, R.id.fragment_sdk_option, R.id.fragment_setting)
when {
screensToHideLayout.contains(destination.id) -> {
binding.bottomNavView.visibility = View.GONE
supportActionBar?.setShowHideAnimationEnabled(false)
supportActionBar?.hide()
}
else -> {
binding.bottomNavView.visibility = View.VISIBLE
supportActionBar?.setShowHideAnimationEnabled(false)
supportActionBar?.show()
}
}
}
}
@Inject
lateinit var hubspotManager: HubspotManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolbar)
val navView: BottomNavigationView = binding.bottomNavView
val navController = findNavController(R.id.navHostFragment)
appBarConfiguration = AppBarConfiguration(
setOf(
R.id.navigation_home, R.id.navigation_fab_button, R.id.navigation_webview
)
)
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)
}
override fun onResume() {
super.onResume()
navController.addOnDestinationChangedListener(listener)
}
override fun onPause() {
navController.removeOnDestinationChangedListener(listener)
super.onPause()
}
}
| 0
|
Kotlin
|
1
| 1
|
185ee0e42bd5af2a413c11fa2937a66601d19c54
| 2,907
|
mobile-chat-sdk-android
|
MIT License
|
ICT4DNews/app/src/test/kotlin/at/ict4d/ict4dnews/dao/AuthorDaoTests.kt
|
ICT4Dat
| 132,874,779
| false
| null |
package at.ict4d.ict4dnews.dao
import at.ict4d.ict4dnews.persistence.database.dao.AuthorDao
import at.ict4d.ict4dnews.utils.generateAuthor
import at.ict4d.ict4dnews.utils.generateAuthorListAndInsert
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class AuthorDaoTests : BaseDaoTest() {
private lateinit var authorDao: AuthorDao
@Before
override fun createDatabase() {
super.createDatabase()
authorDao = appDatabase.authorDao()
}
@Test
fun testInsert() {
val result = authorDao.insert(generateAuthor())
Assert.assertEquals(1L, result)
}
@Test
fun testInsertAll() {
val list = generateAuthorListAndInsert(authorDao)
val result = authorDao.insertAll(list)
Assert.assertEquals(list.size, result.size)
}
@Test
fun testGetAuthorDetailsBy() =
runBlocking {
val list = generateAuthorListAndInsert(authorDao)
var result = authorDao.getAuthorDetailsBy(list.first().link).first()
Assert.assertNotNull(result)
Assert.assertEquals(list.first(), result)
result = authorDao.getAuthorDetailsBy(list.last().link).first()
Assert.assertNotNull(result)
Assert.assertEquals(list.last(), result)
result = authorDao.getAuthorDetailsBy(list.joinToString { it.link }).first()
Assert.assertNull(result)
}
}
| 16
|
Kotlin
|
1
| 5
|
61d40e82c06c203070d4e8d2f00533bce6be3ef1
| 1,632
|
ict4dat-news-android
|
Apache License 2.0
|
js/js.translator/testData/box/simple/classInstantiation.kt
|
gigliovale
| 89,726,097
| false
| null |
// EXPECTED_REACHABLE_NODES: 996
package foo
class Test() {
}
fun box(): String {
var test = Test()
return "OK"
}
| 0
| null |
4
| 6
|
ce145c015d6461c840050934f2200dbc11cb3d92
| 123
|
kotlin
|
Apache License 2.0
|
iteration7/music-matters/core/i8n/src/main/java/com/odesa/musicMatters/core/i8n/Belarusian.kt
|
Odhiambo-Michael-Allan
| 740,198,682
| false
|
{"Kotlin": 9540063}
|
package com.odesa.musicMatters.services.i18n
object Belarusian : Language {
override val locale: String
get() = "be"
override val nativeName: String
get() = "Беларуская"
override val englishName: String
get() = "Belarusian"
override val unknownSymbol: String
get() = "?"
override val helloThere: String
get() = "Вітаю!"
override val introductoryMessage: String
get() = """
Дзякуем вам за ўдзел у адкрытым бэта-тэставанні Symphony. Калі вы сутыкнуліся з
якімі-небудзь памылкамі ці хочаце прапанаваць паляпшэнні, калі ласка, адкрыйце
праблему ў нашым рэпазітары Github. Далучайцеся да нашай супольнасці Discord і Reddit,
каб дзяліцца сваімі водгукамі і быць у курсе распрацоўкі.
Symphony цалкам падтрымліваецца ахвяраваннямі праз Github Sponsors, Ko-fi і Patreon.
Яшчэ раз дзякуй, што паспрабавалі Symphony!
""".trimIndent()
override val songs: String
get() = "Трэкі"
override val artists: String
get() = "Выканаўцы"
override val albums: String
get() = "Альбомы"
override val settings: String
get() = "Налады"
override val details: String
get() = "Звесткі"
override val path: String
get() = "Шлях да файла"
override val filename: String
get() = "Імя файла"
override val size: String
get() = "Памер"
override val dateAdded: String
get() = "Час дадання"
override val lastModified: String
get() = "Апошняя змена"
override val length: String
get() = "Даўжыня"
override val bitrate: String
get() = "Бітрэйт"
override val trackName: String
get() = "Назва трэка"
override val artist: String
get() = "Выканаўца"
override val album: String
get() = "Альбом"
override val albumArtist: String
get() = "Альбом выканаўцы"
override val composer: String
get() = "Кампазітар"
override val nothingIsBeingPlayedRightNow: String
get() = "Цяпер нічога не гуляе"
override val addToQueue: String
get() = "Дадаць у чаргу"
override val queue: String
get() = "Чарга"
override val playNext: String
get() = "Гуляць далей"
override val nowPlaying: String
get() = "Цяпер гуляе"
override val language: String
get() = "Мова"
override val materialYou: String
get() = "Material You"
override val system: String
get() = "Як у сістэме"
override val light: String
get() = "Светлая"
override val dark: String
get() = "Цёмная"
override val black: String
get() = "Чорная"
override val viewArtist: String
get() = "Паглядзець выканаўца"
override val title: String
get() = "Назва"
override val duration: String
get() = "Працягласць"
override val year: String
get() = "Год"
override val viewAlbum: String
get() = "Паглядзець альбом"
override val searchYourMusic: String
get() = "Знайдзіце сваю музыку"
override val noResultsFound: String
get() = "Няма вынікаў"
override val albumCount: String
get() = "Колькасць альбомаў"
override val trackCount: String
get() = "Колькасць трэкаў"
override val filteringResults: String
get() = "Фільтруем вынікі..."
override val appearance: String
get() = "Знешні выгляд"
override val about: String
get() = "Пра нас"
override val github: String
get() = "Github"
override val play: String
get() = "Гуляць"
override val previous: String
get() = "Папярэдняе"
override val next: String
get() = "Наступнае"
override val pause: String
get() = "Паўза"
override val done: String
get() = "Ужыць"
override val groove: String
get() = "Канал"
override val songsFilterPattern: String
get() = "Шаблон фільтрацыі трэкаў"
override val reset: String
get() = "Скід"
override val theme: String
get() = "Тэма"
override val checkForUpdates: String
get() = "Правяраць наяўнасць абнаўленняў"
override val version: String
get() = "Версія"
override val shufflePlay: String
get() = "Змяшаць"
override val viewAlbumArtist: String
get() = "Паглядзець альбом выканаўцы"
override val stop: String
get() = "Стоп"
override val all: String
get() = "Усё"
override val fadePlaybackInOut: String
get() = "Плаўны пераход"
override val requireAudioFocus: String
get() = "Патрабаваць аўдыё-фокус"
override val ignoreAudioFocusLoss: String
get() = "Ігнараваць аўдыё-фокус"
override val player: String
get() = "Плэер"
override val playOnHeadphonesConnect: String
get() = "Гуляць пры падключэнні навушнікаў"
override val pauseOnHeadphonesDisconnect: String
get() = "Паўза пры адключэнні навушнікаў"
override val genre: String
get() = "Жанр"
override val damnThisIsSoEmpty: String
get() = "Божа, тут так пуста!"
override val primaryColor: String
get() = "Асноўны колер"
override val playAll: String
get() = "Гуляць усё"
override val forYou: String
get() = "Для вас"
override val suggestedAlbums: String
get() = "Прапанаваныя альбомы"
override val suggestedArtists: String
get() = "Прапанаваныя выканаўцы"
override val recentlyAddedSongs: String
get() = "Нядаўна дададзеныя трэкі"
override val sponsorViaGithub: String
get() = "Спансаваць праз Github"
override val clearSongCache: String
get() = "Ачысціць кэш трэкаў"
override val songCacheCleared: String
get() = "Кеш трэкаў ачышчаны"
override val albumArtists: String
get() = "Альбомы выканаўцаў"
override val genres: String
get() = "Жанры"
override val cancel: String
get() = "Адмена"
override val homeTabs: String
get() = "Асноўныя ўкладкі"
override val selectAtleast2orAtmost5Tabs: String
get() = "Абярыце не менш за 2 ці не больш за 5 укладак"
override val folders: String
get() = "Тэчкі"
override val invisible: String
get() = "Утоены"
override val alwaysVisible: String
get() ="Заўсёды бачныя"
override val visibleWhenActive: String
get() = "Толькі на бягучай укладцы"
override val bottomBarLabelVisibility: String
get() = "Назвы ўкладак"
override val playlists: String
get() = "Плэйлісты"
override val newPlaylist: String
get() = "Новы плэйліст"
override val importPlaylist: String
get() = "Імпартаваць плэйліст"
override val noInAppPlaylistsFound: String
get() = "Плэйлісты ў дадатку не знойдзены"
override val noLocalPlaylistsFound: String
get() = "Лакальны плэйлісты не знойдзены"
override val custom: String
get() = "Свой"
override val playlist: String
get() = "Плэйліст"
override val addSongs: String
get() = "Дадаць трэкі"
override val addToPlaylist: String
get() = "Дадаць у плэйліст"
override val isLocalPlaylist: String
get() = "Гэта ўнутраны плэйліст?"
override val yes: String
get() = "Ды"
override val no: String
get() = "Не"
override val manageSongs: String
get() = "Кіраванне трэкамі"
override val delete: String
get() = "Выдаліць"
override val deletePlaylist: String
get() = "Выдаліць плэйліст"
override val trackNumber: String
get() = "Нумар трэка"
override val tree: String
get() = "Дрэва"
override val loading: String
get() = "Загрузка..."
override val name: String
get() = "Імя"
override val addFolder: String
get() = "Дадаць тэчку"
override val blacklistFolders: String
get() = "Чорны спіс тэчак"
override val whitelistFolders: String
get() = "Белы спіс тэчак"
override val pickFolder: String
get() = "Абярыце тэчку"
override val invalidM3uFile: String
get() = "Няверны M3U файл"
override val discord: String
get() = "Discord"
override val reddit: String
get() = "Reddit"
override val reportAnIssue: String
get() = "Паведаміць аб праблеме"
override val noFoldersFound: String
get() = "Тэчкі не знойдзены"
override val sleepTimer: String
get() = "Таймер сну"
override val hours: String
get() = "Гадзіны"
override val minutes: String
get() = "Хвіліны"
override val quitAppOnEnd: String
get() = "Выйсці з плэера па заканчэнні таймера"
override val favorite: String
get() = "Падабаецца"
override val unfavorite: String
get() = "Падабаецца"
override val bitDepth: String
get() = "Глыбіня гуку"
override val samplingRate: String
get() = "Частата дыскрэтызацыі"
override val showAudioInformation: String
get() = "Паказаць аўдыёінфармацыю"
override val fastRewindDuration: String
get() = "Даўжыня перамоткі таму"
override val fastForwardDuration: String
get() = "Даўжыня перамоткі наперад"
override val suggestedAlbumArtists: String
get() = "Прапанаваныя альбомы выканаўцаў"
override val areYouSureThatYouWantToDeleteThisPlaylist: String
get() = "Вы ўпэўненыя, што хочаце выдаліць гэты плэйліст?"
override val removeFromPlaylist: String
get() = "Выдаліць з плэйліста"
override val speed: String
get() = "Хуткасць"
override val pitch: String
get() = "Вышыня"
override val persistUntilQueueEnd: String
get() = "Захаваць да канца чаргі"
override val noLyrics: String
get() = "Няма тэксту песні"
override val sponsorViaPatreon: String
get() = "Спансаваць праз Patreon"
override val fDroid: String
get() = "F-Droid"
override val izzyOnDroid: String
get() = "IzzyOnDroid"
override val miniPlayer: String
get() = "Міні-плэер"
override val showTrackControls: String
get() = "Кіраванне дарожкамі"
override val showSeekControls: String
get() = "Кіраванне перамоткай"
override val font: String
get() = "Шрыфт"
override val codec: String
get() = "Кодэк"
override val controlsLayout: String
get() = "Элементы кіравання"
override val default: String
get() = "Па змаўчанні"
override val traditional: String
get() = "Традыцыйна"
override val enabled: String
get() = "Уключаны"
override val disabled: String
get() = "Адключаны"
override val showUpdateToast: String
get() = "Паказваць апавяшчэнне аб абнаўленні"
override val sponsorViaKofi: String
get() = "Спансаваць праз Ko-fi"
override val playlistStoreLocation: String
get() = "месца захоўвання плейлістаў"
override val appBuiltIn: String
get() = "ўбудаваны дадатак"
override val localStorage: String
get() = "лакальнае захоўванне"
override val systemLightDark: String
get() = "Як у сістэме (Светлая + Цёмная)"
override val systemLightBlack: String
get() = "Як у сістэме (Светлая + Чорная)"
override val fontScale: String
get() = "Памер тэксту"
override val contentScale: String
get() = "Памер кантэнту"
override val viewGenre: String
get() = "Паглядзець жанр"
override val Interface: String
get() = "Інтэрфейс"
override val rescan: String
get() = "Перасканаваць"
override val updates: String
get() = "Абнаўленні"
override val considerDonating: String
get() = "Разгледзім ахвяраванне!"
override val help: String
get() = "Даведка"
override val shareSong: String
get() = "Падзяліцца трэкам"
override val pauseOnCurrentSongEnd: String
get() = "Паўза ў канцы бягучага трэка"
override val export: String
get() = "Экспарт"
override val renamePlaylist: String
get() = "Перайменаваць плэйліст"
override val rename: String
get() = "Перайменаваць"
override val equalizer: String
get() = "Эквалайзер"
override val considerContributing: String
get() = "Разгледзьце магчымасць унесці свой уклад!"
override val lyrics: String
get() = "Тэкст песні"
override val lyricsLayout: String
get() = "Макет тэксту"
override val replaceArtwork: String
get() = "Замена вокладкі"
override val separatePage: String
get() = "Бягучы радок міні-плэера"
override val miniPlayerTextMarquee: String
get() = "Бягучы радок міні-плэера"
override val addItem: String
get() = "Дадаць раздзел"
override val artistTagValueSeparators: String
get() = "Раздзяляльнікі значэнняў тэгаў выканаўцаў"
override val genreTagValueSeparators: String
get() = "Раздзяляльнікі значэнняў тэгаў жанру"
override val discNumber: String
get() = "Нумар дыска"
override val setAsRingtone: String
get() = "усталяваць у якасці рынгтона"
override fun playingXofY( x: String, y: String ) = "Гуляе $x з $y"
override fun unknownArtistX( x: String ) = "Невядомы выканаўца (${x})"
override fun xSongs( x: String ) = "$x трэкаў"
override fun unknownAlbumId( id: String ) = "Невядомы альбом (${id})"
override fun xArtists( x: String ) = "$x выканаўцаў"
override fun xAlbums( x: String ) = "$x альбомаў"
override fun madeByX( x: String ) = "Створана $x"
override fun newVersionAvailableX( x: String ) = "Даступная новая версія! (${x})"
override fun xKbps(x: String) = "$x Кбіт/с"
override fun xSecs( x: String ) = "${x}с"
override fun unknownGenreX( x: String ) = "Невядомы жанр $x"
override fun xGenres( x: String ) = "$x жанраў"
override fun xFoldersYfiles(x: String, y: String) = "$x тэчак, $y файлаў"
override fun xItems( x: String ) = "$x раздзелаў"
override fun xPlaylists( x: String ) = "$x плэйлістоў"
override fun unknownPlaylistX( x: String ) = "Невядомы плэйліст (ID: ${x})"
override fun xFolders( x: String ) = "$x тэчак"
override fun xBit( x: String ) = "${x}-біт"
override fun xKHZ( x: String ) = "$x кГц"
override fun shareFailedX( x: String ) = "Не ўдалося падзяліцца"
override fun exportFailedX( x: String ) = "Экспарт не атрымаўся (Памылка: ${x})"
override fun exportedX( x: String ) = "Экспартавана $x"
override fun launchingEqualizerFailedX( x: String ) = "Не ўдалося запусціць эквалайзер (Памылка: ${x})"
override fun unknownAlbumX( x: String ) = "Невядомы альбом (${x})"
override fun copiedXtoClipboard( x: String ) = "Скапіявана '${x}' у буфер абмену"
}
| 0
|
Kotlin
|
0
| 3
|
05ad5e08002a78958ed7763e6685a0e15f635fae
| 14,919
|
music-matters
|
Apache License 2.0
|
src/test/kotlin/kotlinmudv2/fight/FightServiceTest.kt
|
danielmunro
| 515,227,142
| false
|
{"Kotlin": 214222, "Dockerfile": 179, "Makefile": 134}
|
package kotlinmudv2.fight
import assertk.assertThat
import assertk.assertions.isLessThan
import assertk.assertions.isNull
import kotlinmudv2.game.Attribute
import kotlinmudv2.test.createTestService
import kotlin.test.Test
class FightServiceTest {
@Test
fun testFightRoundReducesHpInTarget() {
// setup
val test = createTestService()
// given
val mob1 = test.getPlayerMob().also {
it.attributes[Attribute.Hit] = 20
it.attributes[Attribute.Dam] = 20
}
val mob2 = test.createMob().also {
it.attributes[Attribute.Hit] = 20
it.attributes[Attribute.Dam] = 20
}
test.setupFight()
// when -- randomness taken into account
repeat(10) {
test.executeFight()
}
// then
assertThat(mob1.hp + mob2.hp).isLessThan(mob1.calc(Attribute.Hp) + mob2.calc(Attribute.Hp))
}
@Test
fun testDeathResetsTargets() {
// setup
val test = createTestService()
val mob1 = test.getPlayerMob()
val mob2 = test.createMob()
// given
mob1.attributes[Attribute.Hit] = 20
mob1.attributes[Attribute.Dam] = 20
mob2.attributes[Attribute.Hit] = 20
mob2.attributes[Attribute.Dam] = 20
test.setupFight()
// when -- randomness taken into account
repeat(100) {
test.executeFight()
}
// then
assertThat(mob1.target).isNull()
assertThat(mob2.target).isNull()
}
}
| 0
|
Kotlin
|
0
| 0
|
28b5a049c54ad072ccade19c9ad2bb36b9cf8909
| 1,550
|
kotlinmud-v2
|
MIT License
|
app/src/commonMain/kotlin/com/materialkolor/builder/core/UrlLauncher.kt
|
jordond
| 860,167,006
| false
|
{"Kotlin": 441363, "Shell": 6336, "HTML": 4360, "Swift": 614, "CSS": 102}
|
package com.materialkolor.builder.core
import co.touchlab.kermit.Logger
interface UrlLauncher {
fun launch(url: String)
fun launch(url: UrlLink) = launch(url.value)
}
class DefaultUrlLauncher : UrlLauncher {
private val logger = Logger.withTag("LinkLauncher")
override fun launch(url: String) {
try {
logger.d { "Launching link: $url" }
launchUrl(url)
} catch (cause: Exception) {
logger.e(cause) { "Failed to launch link: $url" }
}
}
}
internal expect fun launchUrl(url: String)
| 5
|
Kotlin
|
2
| 26
|
acd61c7309d24df1e014d5a0e1b9674ad8cb692b
| 567
|
MaterialKolorBuilder
|
MIT License
|
src/test/kotlin/org/unbrokendome/gradle/plugins/helm/command/tasks/HelmInitTest.kt
|
Haardt
| 243,044,316
| true
|
{"Kotlin": 260778}
|
package org.unbrokendome.gradle.plugins.helm.command.tasks
import assertk.assertThat
import assertk.assertions.isDirectory
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.unbrokendome.gradle.plugins.helm.AbstractGradleProjectTest
import org.unbrokendome.gradle.plugins.helm.command.HelmCommandsPlugin
class HelmInitTest : AbstractGradleProjectTest() {
@BeforeEach
fun applyHelmCommandsPlugin() {
project.plugins.apply(HelmCommandsPlugin::class.java)
}
@Test
fun `should run helmInit`() {
val task = project.tasks.create("helmInit", HelmInit::class.java) { task ->
task.clientOnly.set(true)
task.home.set(project.buildDir.resolve("helm/home"))
}
task.helmInit()
assertThat(project.buildDir.resolve("helm/home")).isDirectory()
}
}
| 0
| null |
0
| 0
|
f5e5ef51272526eaf2cf2f8f94a51d7a7da4bbd9
| 863
|
gradle-helm-plugin
|
MIT License
|
src/main/kotlin/com/blueanvil/tekst/WordCursor.kt
|
blueanvil
| 276,079,873
| false
| null |
package com.blueanvil.tekst
data class WordCursor(val startIndex: Int) {
private val text = StringBuilder()
fun addChar(char: Char) {
text.append(char)
}
fun word(): TextMatch {
return TextMatch(text.toString(), startIndex)
}
}
| 0
|
Kotlin
|
0
| 0
|
b1b8aa34973ff7b760f3d53365a6d5bfe3ee97db
| 267
|
tekst
|
Apache License 2.0
|
app/src/main/java/de/beatbrot/screenshotassistant/EditingMode.kt
|
beatbrot
| 200,832,747
| false
| null |
package de.beatbrot.screenshotassistant
enum class EditingMode {
CROP, PAINT
}
| 15
| null |
11
| 49
|
3d8ce0dc0e2580a6ba55d3379654b67ad79d9112
| 84
|
ScreenshotAssistant
|
Apache License 2.0
|
plugins/kotlin/idea/tests/testData/findUsages/kotlin/conventions/invokeExtension.0.kt
|
JetBrains
| 2,489,216
| false
| null |
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtNamedFunction
// OPTIONS: usages
package pack
class P
operator fun P.<caret>invoke() = 1
fun f(p: P) {
p()
p.invoke()
}
| 191
| null |
4372
| 13,319
|
4d19d247824d8005662f7bd0c03f88ae81d5364b
| 173
|
intellij-community
|
Apache License 2.0
|
fxgl/src/main/kotlin/com/almasb/fxgl/saving/SaveFile.kt
|
Ravanla
| 205,673,093
| false
| null |
/*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB (<EMAIL>).
* See LICENSE for details.
*/
package com.almasb.fxgl.saving
import java.io.Serializable
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
/**
* Data structure for save files.
* The actual data saved is in [DataFile].
*
* @author <NAME> (<EMAIL>)
*/
data class SaveFile(
/**
* Save file name without the extension.
* So "file1.sav" becomes "file1".
*/
val name: String,
/**
* Date and time of the save.
*/
val dateTime: LocalDateTime) : Serializable {
companion object RECENT_FIRST : Comparator<SaveFile> {
private val serialVersionUid: Long = 1
override fun compare(o1: SaveFile, o2: SaveFile) = o2.dateTime.compareTo(o1.dateTime)
}
override fun toString() = "%-25.25s %s".format(name, dateTime.format(DateTimeFormatter.ofPattern("dd-MM-yyyy HH-mm")))
}
| 0
| null |
0
| 1
|
25433dbdebb4c358eabe622063fac0ccc8a910f6
| 989
|
FXGL
|
MIT License
|
src/main/kotlin/modic/io/model/Attribute.kt
|
modicio
| 526,521,528
| false
|
{"Kotlin": 150415}
|
/**
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 modic.io.model
import jakarta.persistence.*
import jakarta.xml.bind.annotation.XmlAccessType
import jakarta.xml.bind.annotation.XmlAccessorType
import jakarta.xml.bind.annotation.XmlAttribute
import jakarta.xml.bind.annotation.XmlTransient
/**
* The [Attribute] represents the model element typically known as attribute or property.
* By default, only [Node]s can have Attributes.
* An Attribute consists of identifiers and a key-datatype pair expressing the physical attribute model.
*/
@Entity
@XmlAccessorType(XmlAccessType.NONE)
class Attribute(
/**
* Technical database (JPA) identifier used for relation joins.
* The [dataID] is system specific and not exported to XML.
* It must not be used to identify elements in distributed use-cases.
* It should not be used to identify elements from outside the service. All model elements provide other
* suitable identifiers to be used.
*/
@field:Id
@field:Column
@field:GeneratedValue(strategy = GenerationType.IDENTITY)
@field:XmlTransient
var dataID: Long? = null,
/**
* The unique naming URI of the [Attribute] in its current [Model].
* The uri must not take variant/version into account which is stored separately.
* A modicio URI is defined as a "xs:anyURI" base with the schema extension "modicio:.*"
*/
@field:Column
@field:XmlAttribute(name = "uri")
var uri: String = "",
/**
* The name of an Attribute, also called key.
* Uniqueness is optional but should be enforced on the level of a single [Node].
*/
@field:Column
@field:XmlAttribute(name = "name")
var name: String = "",
/**
* The data type of the attribute serialized as string.
* TODO: right now, arbitrary types are supported. A later type checker must predefine a set of type values.
*/
@field:Column
@field:XmlAttribute(name = "dType")
var dType: String = "",
/**
* Backlink to [Model] to improve traversal.
*/
@field:Transient
@field:XmlTransient
var node: Node? = null
) {
constructor() : this(null)
fun initializeZeroIDs(){
dataID = 0
}
}
| 6
|
Kotlin
|
0
| 8
|
d26f616fb622cda73134506a4c961600ffc41ef0
| 2,767
|
modicio
|
Apache License 2.0
|
app/src/main/java/com/carl/apkdemo/activities/MainActivity.kt
|
wen-carl
| 162,534,076
| false
| null |
package com.carl.apkdemo.activities
import android.content.Intent
import android.os.Bundle
import android.view.View
import com.carl.apkdemo.R
import com.carl.apkdemo.base.BaseActivity
class MainActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
addContentView(R.layout.activity_main)
}
override fun onFabClick(view: View) {
startActivity(Intent(this, SwitchActivity::class.java))
}
}
| 0
|
Kotlin
|
0
| 0
|
cf3fd618451547faa4c674f1bc2f6842ce432bad
| 493
|
ApkDemo
|
MIT License
|
codetextfield/src/main/java/com/king/compose/codetextfield/TextFieldCursor.kt
|
jenly1314
| 568,473,395
| false
|
{"Kotlin": 18347, "Shell": 636}
|
package com.king.compose.codetextfield
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.keyframes
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.isUnspecified
import androidx.compose.ui.unit.dp
/**
* 光标
* @author <a href="mailto:<EMAIL>">Jenly</a>
*/
@Suppress("ModifierInspectorInfo")
internal fun Modifier.cursor(
cursorBrush: Brush,
cursorRect: Rect,
enabled: Boolean
) = if (enabled) composed {
val cursorAlpha = remember { Animatable(1f) }
val isBrushSpecified = !(cursorBrush is SolidColor && cursorBrush.value.isUnspecified)
if (isBrushSpecified) {
LaunchedEffect(cursorBrush) {
cursorAlpha.animateTo(0f, cursorAnimationSpec)
}
drawWithContent {
this.drawContent()
val cursorAlphaValue = cursorAlpha.value.coerceIn(0f, 1f)
if (cursorAlphaValue != 0f) {
val cursorWidth = DefaultCursorThickness.toPx()
val cursorX = (cursorRect.left + cursorWidth / 2)
.coerceAtMost(size.width - cursorWidth / 2)
drawLine(
cursorBrush,
Offset(cursorX, cursorRect.top),
Offset(cursorX, cursorRect.bottom),
alpha = cursorAlphaValue,
strokeWidth = cursorWidth
)
}
}
} else {
Modifier
}
} else this
/**
* 光标动画
*/
private val cursorAnimationSpec: AnimationSpec<Float>
get() = infiniteRepeatable(
animation = keyframes {
durationMillis = 1000
1f at 0
1f at 499
0f at 500
0f at 999
}
)
/**
* 光标的宽度
*/
private val DefaultCursorThickness = 2.dp
| 0
|
Kotlin
|
0
| 20
|
7e6d96b8b02fb957b6640e4c49ed7054f9ab1df1
| 2,258
|
CodeTextField
|
MIT License
|
chat-index-cassandra/src/test/kotlin/com/demo/chat/test/index/TopicIndexTests.kt
|
marios-code-path
| 181,180,043
| false
|
{"Kotlin": 924762, "Shell": 36602, "C": 3160, "HTML": 2714, "Starlark": 278}
|
package com.demo.chat.test.index
import com.demo.chat.domain.MessageTopic
import com.demo.chat.index.cassandra.domain.ChatTopicName
import com.demo.chat.index.cassandra.domain.ChatTopicNameKey
import com.demo.chat.index.cassandra.repository.TopicByNameRepository
import com.demo.chat.service.core.IndexService
import com.demo.chat.service.core.TopicIndexService
import com.demo.chat.service.core.TopicIndexService.Companion.NAME
import com.demo.chat.index.cassandra.impl.TopicIndex
import com.demo.chat.test.anyObject
import com.demo.chat.test.randomAlphaNumeric
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.BDDMockito
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.test.context.junit.jupiter.SpringExtension
import reactor.core.publisher.Mono
import reactor.test.StepVerifier
import java.util.*
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@ExtendWith(SpringExtension::class)
class TopicIndexTests {
@MockBean
lateinit var nameRepo: TopicByNameRepository<UUID>
lateinit var topicIndex: TopicIndexService<UUID, Map<String, String>>
private val testTopicId = UUID.randomUUID()
private val testTopicName = "TEST_TOPIC"
private val topicByName = ChatTopicName(ChatTopicNameKey(testTopicId, testTopicName), true)
fun getIndex(): IndexService<UUID, MessageTopic<UUID>, Map<String, String>> = topicIndex
@BeforeEach
fun setUp() {
topicIndex = TopicIndex(nameRepo)
}
@Test
fun `should search by topic name`() {
BDDMockito.given(nameRepo.save(anyObject<ChatTopicName<UUID>>()))
.willReturn(Mono.just(topicByName))
BDDMockito.given(nameRepo.findByKeyName(anyObject()))
.willReturn(Mono.just(topicByName))
StepVerifier
.create(
topicIndex.findBy(mapOf(Pair(NAME, randomAlphaNumeric(5))))
)
.expectSubscription()
.assertNext {
Assertions
.assertThat(it)
.isNotNull
.hasNoNullFieldsOrProperties()
.extracting("id")
.isInstanceOf(UUID::class.java)
}
.verifyComplete()
}
}
| 2
|
Kotlin
|
1
| 9
|
2ae59375cd44e8fb58093b0f24596fc3111fd447
| 2,487
|
demo-chat
|
MIT License
|
graph/graph-adapter-output-spring-data-neo4j-sdn6/src/main/kotlin/org/orkg/graph/adapter/output/neo4j/internal/Neo4jPredicateIdGenerator.kt
|
TIBHannover
| 197,416,205
| false
|
{"Kotlin": 2966676, "Cypher": 216833, "Python": 4881, "Groovy": 1936, "Shell": 1803, "HTML": 240}
|
package org.orkg.graph.adapter.output.neo4j.internal
import org.orkg.common.ThingId
import org.springframework.stereotype.Component
@Component
class Neo4jPredicateIdGenerator(
private val repository: Neo4jPredicateIdCounterRepository
) : RepositoryBasedIdGenerator<ThingId, Neo4jPredicateIdCounter>() {
override fun createCounterNode() = Neo4jPredicateIdCounter()
override fun idFromLong(value: Long) = ThingId("P$value")
override fun repository() = repository
}
| 0
|
Kotlin
|
1
| 5
|
f9de52bdf498fdc200e7f655a52cecff215c1949
| 484
|
orkg-backend
|
MIT License
|
app/src/main/java/com/pr0gramm/app/ui/VerticallyUnboundedFrameLayout.kt
|
mopsalarm
| 30,804,448
| false
| null |
package com.pr0gramm.app.ui
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
/**
*/
class VerticallyUnboundedFrameLayout @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
override fun measureChildWithMargins(child: View,
parentWidthMeasureSpec: Int, widthUsed: Int,
parentHeightMeasureSpec: Int, heightUsed: Int) {
super.measureChildWithMargins(child,
parentWidthMeasureSpec, widthUsed,
View.MeasureSpec.UNSPECIFIED, heightUsed)
}
}
| 39
| null |
38
| 284
|
d6917f3ec16b6664a90a4519843f3d3d4ccae2cf
| 744
|
Pr0
|
MIT License
|
system/src/test/kotlin/com/commonsense/android/kotlin/system/compat/SpannedCompatKtTest.kt
|
Tvede-dk
| 82,486,921
| false
| null |
package com.commonsense.android.kotlin.system.compat
import com.commonsense.android.kotlin.test.*
import org.junit.*
import org.robolectric.annotation.*
/**
* Created by <NAME> on 22-05-2018.
* Purpose:
*/
@Config(sdk = [18, 25])
class SpannedCompatKtTest : BaseRoboElectricTest() {
@Test
fun fromHtml() {
val empty = "".fromHtml()
empty.length.assert(0)
val text = "test".fromHtml()
text.length.assert(4)
val invalidHtml = "<li><p></></p> </".fromHtml()
invalidHtml.length.assert(0, "bad html should get \"discarded\"" +
" thus its full of nothing (ignoring whitespaces)")
val simpleText = "<p>test</p>".fromHtml()
simpleText.length.assertLargerOrEqualTo(4, "test should be there, " +
"plus some styling regarding the tags")
}
}
| 9
|
Kotlin
|
0
| 8
|
eae2deb915804d4c431c3fc9d93c33f011a98e5c
| 848
|
CommonsenseAndroidKotlin
|
MIT License
|
app/src/main/java/com/masterplus/trdictionary/features/settings/domain/repo/StorageService.kt
|
Ramazan713
| 634,957,286
| false
|
{"Kotlin": 658244}
|
package com.masterplus.trdictionary.features.settings.domain.repo
import com.masterplus.trdictionary.core.domain.util.Resource
import com.masterplus.trdictionary.features.settings.domain.model.User
import com.masterplus.trdictionary.features.settings.domain.model.BackupMeta
interface StorageService {
suspend fun getFiles(user: User): Resource<List<BackupMeta>>
suspend fun getFileData(user: User, fileName: String): Resource<ByteArray>
suspend fun deleteFile(user: User, fileName: String): Resource<Unit>
suspend fun uploadData(user: User, fileName: String, data: ByteArray): Resource<Unit>
}
| 0
|
Kotlin
|
0
| 1
|
efde17c1a0036bed47a735564f12f831332134cd
| 616
|
Turkce-ve-Osmanlica-Sozluk
|
Apache License 2.0
|
kapitel_06/ServiceDemo3_Service/app/src/main/java/com/thomaskuenneth/androidbuch/servicedemo3_service/MainActivity.kt
|
tkuenneth
| 239,271,728
| false
| null |
package com.thomaskuenneth.androidbuch.servicedemo3_service
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
finish()
}
}
| 0
|
Kotlin
|
0
| 1
|
977f93b8ff9bdd50d45a1a51d009b1eba75b7eb0
| 302
|
begleitmaterialien-zu-android-11
|
Apache License 2.0
|
diktat-test-framework/src/main/kotlin/org/cqfn/diktat/test/framework/processing/FileComparator.kt
|
cqfn
| 275,879,956
| false
| null |
package org.cqfn.diktat.test.framework.processing
import io.github.petertrr.diffutils.diff
import io.github.petertrr.diffutils.patch.ChangeDelta
import io.github.petertrr.diffutils.text.DiffRowGenerator
import org.slf4j.LoggerFactory
import java.io.File
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Paths
import java.util.ArrayList
import java.util.stream.Collectors
/**
* A class that is capable of comparing files content
*/
class FileComparator {
private val expectedResultFile: File
private val actualResultList: List<String>
private val diffGenerator = DiffRowGenerator(
showInlineDiffs = true,
mergeOriginalRevised = false,
inlineDiffByWord = false,
oldTag = { _, start -> if (start) "[" else "]" },
newTag = { _, start -> if (start) "<" else ">" },
)
constructor(expectedResultFile: File, actualResultList: List<String>) {
this.expectedResultFile = expectedResultFile
this.actualResultList = actualResultList
}
constructor(expectedResultFile: File, actualResultFile: File) {
this.expectedResultFile = expectedResultFile
this.actualResultList = readFile(actualResultFile.absolutePath)
}
/**
* @return true in case files are different
* false - in case they are equals
*/
@Suppress(
"ReturnCount",
"FUNCTION_BOOLEAN_PREFIX",
"TOO_LONG_FUNCTION"
)
fun compareFilesEqual(): Boolean {
try {
val expect = readFile(expectedResultFile.absolutePath)
if (expect.isEmpty()) {
return false
}
val regex = (".*// ;warn:(\\d+):(\\d+): (.*)").toRegex()
val expectWithoutWarn = expect.filterNot { line ->
line.contains(regex)
}
val patch = diff(expectWithoutWarn, actualResultList)
if (patch.deltas.isEmpty()) {
return true
}
val joinedDeltas = patch.deltas.joinToString(System.lineSeparator()) { delta ->
when (delta) {
is ChangeDelta -> diffGenerator
.generateDiffRows(delta.source.lines, delta.target.lines)
.joinToString(prefix = "ChangeDelta, position ${delta.source.position}, lines:\n", separator = "\n\n") {
"""-${it.oldLine}
|+${it.newLine}
|""".trimMargin()
}
.let { "ChangeDelta, position ${delta.source.position}, lines:\n$it" }
else -> delta.toString()
}
}
log.error("""
|Expected result from <${expectedResultFile.name}> and actual formatted are different.
|See difference below:
|$joinedDeltas
""".trimMargin()
)
} catch (e: RuntimeException) {
log.error("Not able to prepare diffs between <${expectedResultFile.name}> and <$actualResultList>", e)
}
return false
}
/**
* @param fileName - file where to write these list to, separated with newlines
* @return a list of lines from the file
*/
private fun readFile(fileName: String): List<String> {
var list: List<String> = ArrayList()
try {
Files.newBufferedReader(Paths.get(fileName)).use { list = it.lines().collect(Collectors.toList()) }
} catch (e: IOException) {
log.error("Not able to read file: $fileName")
}
return list
}
companion object {
private val log = LoggerFactory.getLogger(FileComparator::class.java)
}
}
| 93
|
Kotlin
|
23
| 361
|
d8c4cea250a651244fb6bad0ecf9bad505ece89b
| 3,740
|
diKTat
|
MIT License
|
Common/src/main/java/at/petrak/hexcasting/common/casting/actions/eval/OpThanos.kt
|
FallingColors
| 441,721,272
| false
| null |
package at.petrak.hexcasting.common.casting.operators.eval
import at.petrak.hexcasting.api.casting.castables.Action
import at.petrak.hexcasting.api.casting.eval.CastingEnvironment
import at.petrak.hexcasting.api.casting.eval.OperationResult
import at.petrak.hexcasting.api.casting.eval.vm.CastingImage
import at.petrak.hexcasting.api.casting.eval.vm.SpellContinuation
import at.petrak.hexcasting.api.casting.iota.DoubleIota
import at.petrak.hexcasting.api.mod.HexConfig
import at.petrak.hexcasting.common.lib.hex.HexEvalSounds
object OpThanos : Action {
override fun operate(env: CastingEnvironment, image: CastingImage, continuation: SpellContinuation): OperationResult {
val opsLeft = HexConfig.server().maxOpCount() - image.opsConsumed
val stack = image.stack.toMutableList()
stack.add(DoubleIota(opsLeft.toDouble()))
val image2 = image.withUsedOp().copy(stack = stack)
return OperationResult(image2, listOf(), continuation, HexEvalSounds.NORMAL_EXECUTE)
}
}
| 173
| null |
80
| 97
|
1aa53ca97faebc7e8fcca3215c58239ab35ad428
| 1,012
|
HexMod
|
MIT License
|
app/src/main/java/softspark/com/inventorypilot/users/domain/useCases/ValidateUserUseCase.kt
|
Landony04
| 836,511,304
| false
|
{"Kotlin": 259920}
|
package softspark.com.inventorypilot.users.domain.useCases
import kotlinx.coroutines.flow.Flow
import softspark.com.inventorypilot.users.domain.entities.AddUserResult
interface ValidateUserUseCase {
suspend operator fun invoke(
email: String,
firstName: String,
lastName: String,
role: String,
cellPhone: String
): Flow<AddUserResult>
}
| 5
|
Kotlin
|
0
| 0
|
844c46e48ce44a50e0d44ce99df78f281af5c3b7
| 386
|
inventory-pilot
|
MIT License
|
app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderPresenter.kt
|
smokeofc
| 178,956,464
| false
| null |
package eu.kanade.tachiyomi.ui.reader
import android.os.Bundle
import android.os.Environment
import android.webkit.MimeTypeMap
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.cache.ChapterCache
import eu.kanade.tachiyomi.data.cache.CoverCache
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.History
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.database.models.Track
import eu.kanade.tachiyomi.data.download.DownloadManager
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.data.preference.getOrDefault
import eu.kanade.tachiyomi.data.track.TrackManager
import eu.kanade.tachiyomi.source.LocalSource
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.online.HttpSource
import eu.kanade.tachiyomi.source.online.all.EHentai
import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter
import eu.kanade.tachiyomi.util.DiskUtil
import eu.kanade.tachiyomi.util.RetryWithDelay
import eu.kanade.tachiyomi.util.SharedData
import eu.kanade.tachiyomi.util.toast
import rx.Observable
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import timber.log.Timber
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.io.File
import java.net.URLConnection
import java.util.Comparator
import java.util.Date
/**
* Presenter of [ReaderActivity].
*/
class ReaderPresenter(
val prefs: PreferencesHelper = Injekt.get(),
val db: DatabaseHelper = Injekt.get(),
val downloadManager: DownloadManager = Injekt.get(),
val trackManager: TrackManager = Injekt.get(),
val sourceManager: SourceManager = Injekt.get(),
val chapterCache: ChapterCache = Injekt.get(),
val coverCache: CoverCache = Injekt.get()
) : BasePresenter<ReaderActivity>() {
private val context = prefs.context
/**
* Manga being read.
*/
lateinit var manga: Manga
private set
/**
* Active chapter.
*/
lateinit var chapter: ReaderChapter
private set
/**
* Previous chapter of the active.
*/
private var prevChapter: ReaderChapter? = null
/**
* Next chapter of the active.
*/
private var nextChapter: ReaderChapter? = null
/**
* Source of the manga.
*/
/* private */ val source by lazy { sourceManager.getOrStub(manga.source) }
/**
* Chapter list for the active manga. It's retrieved lazily and should be accessed for the first
* time in a background thread to avoid blocking the UI.
*/
private val chapterList by lazy {
val dbChapters = db.getChapters(manga).executeAsBlocking().map { it.toModel() }
val sortFunction: (Chapter, Chapter) -> Int = when (manga.sorting) {
Manga.SORTING_SOURCE -> { c1, c2 -> c2.source_order.compareTo(c1.source_order) }
Manga.SORTING_NUMBER -> { c1, c2 -> c1.chapter_number.compareTo(c2.chapter_number) }
else -> throw NotImplementedError("Unknown sorting method")
}
dbChapters.sortedWith(Comparator<Chapter> { c1, c2 -> sortFunction(c1, c2) })
}
/**
* Map of chapters that have been loaded in the reader.
*/
private val loadedChapters = hashMapOf<Long?, ReaderChapter>()
/**
* List of manga services linked to the active manga, or null if auto syncing is not enabled.
*/
private var trackList: List<Track>? = null
/**
* Chapter loader whose job is to obtain the chapter list and initialize every page.
*/
/* private */ val loader by lazy { ChapterLoader(downloadManager, manga, source) }
/**
* Subscription for appending a chapter to the reader (seamless mode).
*/
private var appenderSubscription: Subscription? = null
/**
* Subscription for retrieving the adjacent chapters to the current one.
*/
private var adjacentChaptersSubscription: Subscription? = null
/**
* Whether the active chapter has been loaded.
*/
private var chapterLoaded = false
companion object {
/**
* Id of the restartable that loads the active chapter.
*/
private const val LOAD_ACTIVE_CHAPTER = 1
}
override fun onCreate(savedState: Bundle?) {
super.onCreate(savedState)
if (savedState == null) {
val event = SharedData.get(ReaderEvent::class.java) ?: return
manga = event.manga
chapter = event.chapter.toModel()
} else {
manga = savedState.getSerializable(ReaderPresenter::manga.name) as Manga
chapter = savedState.getSerializable(ReaderPresenter::chapter.name) as ReaderChapter
}
// Send the active manga to the view to initialize the reader.
Observable.just(manga)
.subscribeLatestCache({ view, manga -> view.onMangaOpen(manga) })
// Retrieve the sync list if auto syncing is enabled.
if (prefs.autoUpdateTrack()) {
add(db.getTracks(manga).asRxSingle()
.subscribe({ trackList = it }))
}
restartableLatestCache(LOAD_ACTIVE_CHAPTER,
{ loadChapterObservable(chapter) },
{ view, _ -> view.onChapterReady(this.chapter) },
{ view, error -> view.onChapterError(error) })
if (savedState == null) {
loadChapter(chapter)
}
}
override fun onSave(state: Bundle) {
chapter.requestedPage = chapter.last_page_read
state.putSerializable(ReaderPresenter::manga.name, manga)
state.putSerializable(ReaderPresenter::chapter.name, chapter)
super.onSave(state)
}
override fun onDestroy() {
loader.cleanup()
onChapterLeft()
super.onDestroy()
}
/**
* Converts a chapter to a [ReaderChapter] if needed.
*/
private fun Chapter.toModel(): ReaderChapter {
if (this is ReaderChapter) return this
return ReaderChapter(this)
}
/**
* Returns an observable that loads the given chapter, discarding any previous work.
*
* @param chapter the now active chapter.
*/
private fun loadChapterObservable(chapter: ReaderChapter): Observable<ReaderChapter> {
loader.restart()
return loader.loadChapter(chapter)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext { chapterLoaded = true }
}
/**
* Obtains the adjacent chapters of the given one in a background thread, and notifies the view
* when they are known.
*
* @param chapter the current active chapter.
*/
private fun getAdjacentChapters(chapter: ReaderChapter) {
// Keep only one subscription
adjacentChaptersSubscription?.let { remove(it) }
adjacentChaptersSubscription = Observable
.fromCallable { getAdjacentChaptersStrategy(chapter) }
.doOnNext { pair ->
prevChapter = loadedChapters.getOrElse(pair.first?.id) { pair.first }
nextChapter = loadedChapters.getOrElse(pair.second?.id) { pair.second }
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeLatestCache({ view, pair ->
view.onAdjacentChapters(pair.first, pair.second)
})
}
/**
* Returns the previous and next chapters of the given one in a [Pair] according to the sorting
* strategy set for the manga.
*
* @param chapter the current active chapter.
* @param previousChapterAmount the desired number of chapters preceding the current active chapter (Default: 1).
* @param nextChapterAmount the desired number of chapters succeeding the current active chapter (Default: 1).
*/
private fun getAdjacentChaptersStrategy(chapter: ReaderChapter, previousChapterAmount: Int = 1, nextChapterAmount: Int = 1) = when (manga.sorting) {
Manga.SORTING_SOURCE -> {
val currChapterIndex = chapterList.indexOfFirst { chapter.id == it.id }
val nextChapter = chapterList.getOrNull(currChapterIndex + nextChapterAmount)
val prevChapter = chapterList.getOrNull(currChapterIndex - previousChapterAmount)
Pair(prevChapter, nextChapter)
}
Manga.SORTING_NUMBER -> {
val currChapterIndex = chapterList.indexOfFirst { chapter.id == it.id }
val chapterNumber = chapter.chapter_number
var prevChapter: ReaderChapter? = null
for (i in (currChapterIndex - previousChapterAmount) downTo 0) {
val c = chapterList[i]
if (c.chapter_number < chapterNumber && c.chapter_number >= chapterNumber - previousChapterAmount) {
prevChapter = c
break
}
}
var nextChapter: ReaderChapter? = null
for (i in (currChapterIndex + nextChapterAmount) until chapterList.size) {
val c = chapterList[i]
if (c.chapter_number > chapterNumber && c.chapter_number <= chapterNumber + nextChapterAmount) {
nextChapter = c
break
}
}
Pair(prevChapter, nextChapter)
}
else -> throw NotImplementedError("Unknown sorting method")
}
/**
* Loads the given chapter and sets it as the active one. This method also accepts a requested
* page, which will be set as active when it's displayed in the view.
*
* @param chapter the chapter to load.
* @param requestedPage the requested page from the view.
*/
private fun loadChapter(chapter: ReaderChapter, requestedPage: Int = 0) {
// Cleanup any append.
appenderSubscription?.let { remove(it) }
this.chapter = loadedChapters.getOrPut(chapter.id) { chapter }
// If the chapter is partially read, set the starting page to the last the user read
// otherwise use the requested page.
chapter.requestedPage = if (!chapter.read /* --> EH */ || prefs
.eh_preserveReadingPosition()
.getOrDefault() /* <-- EH */) chapter.last_page_read else requestedPage
// Reset next and previous chapter. They have to be fetched again
nextChapter = null
prevChapter = null
chapterLoaded = false
start(LOAD_ACTIVE_CHAPTER)
getAdjacentChapters(chapter)
}
/**
* Changes the active chapter, but doesn't load anything. Called when changing chapters from
* the reader with the seamless mode.
*
* @param chapter the chapter to set as active.
*/
fun setActiveChapter(chapter: ReaderChapter) {
onChapterLeft()
this.chapter = chapter
nextChapter = null
prevChapter = null
getAdjacentChapters(chapter)
}
/**
* Appends the next chapter to the reader, if possible.
*/
fun appendNextChapter() {
appenderSubscription?.let { remove(it) }
val nextChapter = nextChapter ?: return
val chapterToLoad = loadedChapters.getOrPut(nextChapter.id) { nextChapter }
appenderSubscription = loader.loadChapter(chapterToLoad)
.subscribeOn(Schedulers.io())
.retryWhen(RetryWithDelay(1, { 3000 }))
.observeOn(AndroidSchedulers.mainThread())
.subscribeLatestCache({ view, chapter ->
view.onAppendChapter(chapter)
}, { view, _ ->
view.onChapterAppendError()
})
}
/**
* Retries a page that failed to load due to network error or corruption.
*
* @param page the page that failed.
*/
fun retryPage(page: Page?) {
if (page != null && source is HttpSource) {
page.status = Page.QUEUE
val imageUrl = page.imageUrl
if (imageUrl != null && !page.chapter.isDownloaded) {
val key = DiskUtil.hashKeyForDisk(page.url)
chapterCache.removeFileFromCache(key)
}
// --> EH
//If we are using EHentai/ExHentai, get a new image URL
if(source is EHentai)
page.imageUrl = null
// <-- EH
loader.retryPage(page)
}
}
/**
* Called before loading another chapter or leaving the reader. It allows to do operations
* over the chapter read like saving progress
*/
fun onChapterLeft() {
// Reference these locally because they are needed later from another thread.
val chapter = chapter
val pages = chapter.pages ?: return
Observable.fromCallable {
// Cache current page list progress for online chapters to allow a faster reopen
if (!chapter.isDownloaded) {
source.let {
if (it is HttpSource) chapterCache.putPageListToCache(chapter, pages)
}
}
try {
if (chapter.read) {
val removeAfterReadSlots = prefs.removeAfterReadSlots()
when (removeAfterReadSlots) {
// Setting disabled
-1 -> { /* Empty function */ }
// Remove current read chapter
0 -> deleteChapter(chapter, manga)
// Remove previous chapter specified by user in settings.
else -> getAdjacentChaptersStrategy(chapter, removeAfterReadSlots)
.first?.let { deleteChapter(it, manga) }
}
}
} catch (error: Exception) {
// TODO find out why it crashes
Timber.e(error)
}
db.updateChapterProgress(chapter).executeAsBlocking()
try {
val history = History.create(chapter).apply { last_read = Date().time }
db.updateHistoryLastRead(history).executeAsBlocking()
} catch (error: Exception) {
// TODO find out why it crashes
Timber.e(error)
}
}
.subscribeOn(Schedulers.io())
.subscribe()
}
/**
* Called when the active page changes in the reader.
*
* @param page the active page
*/
fun onPageChanged(page: Page) {
val chapter = page.chapter
chapter.last_page_read = page.index
if (chapter.pages!!.last() === page) {
chapter.read = true
}
if (!chapter.isDownloaded && page.status == Page.QUEUE) {
loader.loadPriorizedPage(page)
}
}
/**
* Delete selected chapter
*
* @param chapter chapter that is selected
* @param manga manga that belongs to chapter
*/
fun deleteChapter(chapter: ReaderChapter, manga: Manga) {
chapter.isDownloaded = false
chapter.pages?.forEach { it.status == Page.QUEUE }
downloadManager.deleteChapter(chapter, manga, source)
}
/**
* Returns the chapter to be marked as last read in sync services or 0 if no update required.
*/
fun getTrackChapterToUpdate(): Int {
val trackList = trackList
if (chapter.pages == null || trackList == null || trackList.isEmpty())
return 0
val prevChapter = prevChapter
// Get the last chapter read from the reader.
val lastChapterRead = if (chapter.read)
Math.floor(chapter.chapter_number.toDouble()).toInt()
else if (prevChapter != null && prevChapter.read)
Math.floor(prevChapter.chapter_number.toDouble()).toInt()
else
return 0
return if (trackList.any { lastChapterRead > it.last_chapter_read })
lastChapterRead
else
0
}
/**
* Starts the service that updates the last chapter read in sync services
*/
fun updateTrackLastChapterRead(lastChapterRead: Int) {
trackList?.forEach { track ->
val service = trackManager.getService(track.sync_id)
if (service != null && service.isLogged && lastChapterRead > track.last_chapter_read) {
track.last_chapter_read = lastChapterRead
// We wan't these to execute even if the presenter is destroyed and leaks for a
// while. The view can still be garbage collected.
Observable.defer { service.update(track) }
.map { db.insertTrack(track).executeAsBlocking() }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({}, { Timber.e(it) })
}
}
}
/**
* Loads the next chapter.
*
* @return true if the next chapter is being loaded, false if there is no next chapter.
*/
fun loadNextChapter(): Boolean {
// Avoid skipping chapters.
if (!chapterLoaded) return true
nextChapter?.let {
onChapterLeft()
loadChapter(it, 0)
return true
}
return false
}
/**
* Loads the next chapter.
*
* @return true if the previous chapter is being loaded, false if there is no previous chapter.
*/
fun loadPreviousChapter(): Boolean {
// Avoid skipping chapters.
if (!chapterLoaded) return true
prevChapter?.let {
onChapterLeft()
loadChapter(it, if (it.read) -1 else 0)
return true
}
return false
}
/**
* Returns true if there's a next chapter.
*/
fun hasNextChapter(): Boolean {
return nextChapter != null
}
/**
* Returns true if there's a previous chapter.
*/
fun hasPreviousChapter(): Boolean {
return prevChapter != null
}
/**
* Updates the viewer for this manga.
*
* @param viewer the id of the viewer to set.
*/
fun updateMangaViewer(viewer: Int) {
manga.viewer = viewer
db.insertManga(manga).executeAsBlocking()
}
/**
* Update cover with page file.
*/
internal fun setImageAsCover(page: Page) {
try {
if (manga.source == LocalSource.ID) {
val input = context.contentResolver.openInputStream(page.uri)
LocalSource.updateCover(context, manga, input)
context.toast(R.string.cover_updated)
return
}
val thumbUrl = manga.thumbnail_url ?: throw Exception("Image url not found")
if (manga.favorite) {
val input = context.contentResolver.openInputStream(page.uri)
coverCache.copyToCache(thumbUrl, input)
context.toast(R.string.cover_updated)
} else {
context.toast(R.string.notification_first_add_to_library)
}
} catch (error: Exception) {
context.toast(R.string.notification_cover_update_failed)
Timber.e(error)
}
}
/**
* Save page to local storage.
*/
internal fun savePage(page: Page) {
if (page.status != Page.READY)
return
// Used to show image notification.
val imageNotifier = SaveImageNotifier(context)
// Remove the notification if it already exists (user feedback).
imageNotifier.onClear()
// Pictures directory.
val pictureDirectory = Environment.getExternalStorageDirectory().absolutePath +
File.separator + Environment.DIRECTORY_PICTURES +
File.separator + context.getString(R.string.app_name)
// Copy file in background.
Observable
.fromCallable {
// Folder where the image will be saved.
val destDir = File(pictureDirectory)
destDir.mkdirs()
// Find out file mime type.
val mime = context.contentResolver.getType(page.uri)
?: context.contentResolver.openInputStream(page.uri).buffered().use {
URLConnection.guessContentTypeFromStream(it)
}
// Build destination file.
val ext = MimeTypeMap.getSingleton().getExtensionFromMimeType(mime) ?: "jpg"
val filename = DiskUtil.buildValidFilename(
"${manga.title} - ${chapter.name}") + " - ${page.number}.$ext"
val destFile = File(destDir, filename)
context.contentResolver.openInputStream(page.uri).use { input ->
destFile.outputStream().use { output ->
input.copyTo(output)
}
}
DiskUtil.scanMedia(context, destFile)
imageNotifier.onComplete(destFile)
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
context.toast(R.string.picture_saved)
}, { error ->
Timber.e(error)
imageNotifier.onError(error.message)
})
}
}
| 1
| null |
1
| 2
|
7b9e2de475e672b4b8635f3e1b6102db57533a35
| 21,781
|
TachiyomiEH
|
Apache License 2.0
|
transport/src/commonMain/kotlin/com/genesys/cloud/messenger/transport/core/events/EventHandlerImpl.kt
|
MyPureCloud
| 425,920,457
| false
|
{"Kotlin": 702568, "Swift": 120644, "Shell": 5872, "Ruby": 4062}
|
package com.genesys.cloud.messenger.transport.core.events
import com.genesys.cloud.messenger.transport.shyrka.receive.PresenceEvent
import com.genesys.cloud.messenger.transport.shyrka.receive.StructuredMessageEvent
import com.genesys.cloud.messenger.transport.shyrka.receive.TypingEvent
import com.genesys.cloud.messenger.transport.shyrka.receive.Unknown
import com.genesys.cloud.messenger.transport.util.logs.Log
import com.genesys.cloud.messenger.transport.util.logs.LogMessages
import com.genesys.cloud.messenger.transport.util.logs.LogTag
private const val FALLBACK_TYPING_INDICATOR_DURATION = 5000L
internal class EventHandlerImpl(
internal val log: Log = Log(enableLogs = false, LogTag.EVENT_HANDLER),
) : EventHandler {
override var eventListener: ((Event) -> Unit)? = null
override fun onEvent(event: Event) {
log.i { LogMessages.onEvent(event) }
eventListener?.invoke(event)
}
}
internal fun StructuredMessageEvent.toTransportEvent(): Event? {
return when (this) {
is TypingEvent -> {
Event.AgentTyping(typing.duration ?: FALLBACK_TYPING_INDICATOR_DURATION)
}
is PresenceEvent -> {
when (presence.type) {
PresenceEvent.Presence.Type.Join -> Event.ConversationAutostart
PresenceEvent.Presence.Type.Disconnect -> Event.ConversationDisconnect
PresenceEvent.Presence.Type.Clear -> null // Ignore. Event.ConversationClear should be dispatched upon receiving SessionClearedEvent and not StructuredMessageEvent with Type.Clear
}
}
is Unknown -> null
}
}
| 1
|
Kotlin
|
6
| 9
|
0d5cb13d9247d1c5a3b5d4e9fab61a17ba4620a0
| 1,626
|
genesys-messenger-transport-mobile-sdk
|
MIT License
|
src/main/kotlin/me/bscal/runecraft/stats/StatRegistry.kt
|
bscal
| 414,444,966
| false
| null |
package me.bscal.runecraft.stats
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap
import me.bscal.runecraft.RuneCraft
import me.bscal.runecraft.stats.spells.actions.DamageAction
import me.bscal.runecraft.stats.spells.conditions.ChanceCondition
import me.bscal.runecraft.stats.spells.targets.AreaTarget
import org.bukkit.NamespacedKey
/**
* Registry for all base RuneCraft stats and 3rd party instances.
*/
object StatRegistry
{
val Registry = Object2ObjectOpenHashMap<NamespacedKey, BaseStat>()
val VANILLA_STAT: VanillaStat = Register(VanillaStat(NamespacedKey(RuneCraft.INSTANCE, "vanilla_stat"))) as VanillaStat
val POTION_STAT: PotionStat = Register(PotionStat(NamespacedKey(RuneCraft.INSTANCE, "potion_stat"))) as PotionStat
val EARTH_SHOCK_STAT: SpellStat = Register(
SpellStat(NamespacedKey(RuneCraft.INSTANCE, "earthshock_stat"), "Earth Shock", 3, SpellType.DAMAGE_DONE, ChanceCondition(),
AreaTarget(), DamageAction())) as SpellStat
fun Register(stat: BaseStat): BaseStat
{
Registry[stat.Id] = stat
return stat
}
}
| 0
|
Kotlin
|
0
| 0
|
29470ea09d74e83a3fabe0789d8f169de6a3fc20
| 1,058
|
RuneCraft
|
MIT License
|
app/src/main/java/com/exorabeveragefsm/features/addAttendence/model/WorkTypeResponseModel.kt
|
DebashisINT
| 614,840,078
| false
| null |
package com.exorabeveragefsm.features.addAttendence.model
import com.exorabeveragefsm.base.BaseResponse
/**
* Created by Saikat on 31-08-2018.
*/
class WorkTypeResponseModel : BaseResponse() {
var worktype_list: ArrayList<WorkTypeListData>? = null
}
| 0
|
Kotlin
|
0
| 0
|
11801c2d74a940c23e66b51cf53fec14b1a8560b
| 258
|
ExoraBeverage
|
Apache License 2.0
|
app/src/main/java/com/exorabeveragefsm/features/addAttendence/model/WorkTypeResponseModel.kt
|
DebashisINT
| 614,840,078
| false
| null |
package com.exorabeveragefsm.features.addAttendence.model
import com.exorabeveragefsm.base.BaseResponse
/**
* Created by Saikat on 31-08-2018.
*/
class WorkTypeResponseModel : BaseResponse() {
var worktype_list: ArrayList<WorkTypeListData>? = null
}
| 0
|
Kotlin
|
0
| 0
|
11801c2d74a940c23e66b51cf53fec14b1a8560b
| 258
|
ExoraBeverage
|
Apache License 2.0
|
serialization/src/test/java/type/Byte32Test.kt
|
BlueWatson
| 215,914,738
| false
|
{"Kotlin": 149510, "Java": 797}
|
package type
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import org.nervos.ckb.type.fixed.Byte32
import org.nervos.ckb.utils.Numeric
/** Copyright © 2019 Nervos Foundation. All rights reserved. */
class Byte32Test {
@Test
fun byte32InitEmptyErrorTest() {
Assertions.assertThrows(
UnsupportedOperationException::class.java
) {
val bytes = byteArrayOf()
val byte32 = Byte32(bytes)
byte32.toBytes()
}
}
@Test
fun byte32InitErrorTest() {
Assertions.assertThrows(
UnsupportedOperationException::class.java
) {
val bytes = byteArrayOf(0x01, 0x02, 0x02, 0x03)
val byte32 = Byte32(bytes)
byte32.toBytes()
}
}
@Test
fun byte32InitTest() {
Assertions.assertDoesNotThrow {
val bytes = byteArrayOf(
0x01,
0x01,
0x01,
0x01,
0x01,
0x01,
0x01,
0x01,
0x01,
0x01,
0x01,
0x01,
0x01,
0x01,
0x01,
0x01,
0x01,
0x01,
0x01,
0x01,
0x01,
0x01,
0x01,
0x01,
0x01,
0x01,
0x01,
0x01,
0x01,
0x01,
0x01,
0x01
)
val byte32 = Byte32(bytes)
byte32.toBytes()
}
}
@Test
fun toBytesTest() {
val byte32 = Byte32("68d5438ac952d2f584abf879527946a537e82c7f3c1cbf6d8ebf9767437d8e88")
val expected = Numeric.hexStringToByteArray(
"68d5438ac952d2f584abf879527946a537e82c7f3c1cbf6d8ebf9767437d8e88"
)
Assertions.assertArrayEquals(expected, byte32.toBytes())
}
}
| 0
| null |
0
| 0
|
b947c6229a183bb5726c6389beec1a7a4459e1a8
| 1,660
|
ckb-sdk-kotlin
|
MIT License
|
demo/src/main/java/com/commonsware/ggweb/MainMotor.kt
|
OfekRv
| 365,845,709
| false
|
{"Gradle": 4, "Java Properties": 2, "Text": 1, "Ignore List": 3, "EditorConfig": 1, "Markdown": 1, "XML": 12, "Java": 14, "Kotlin": 4, "INI": 1, "Proguard": 1, "JavaScript": 1, "HTML": 1}
|
/*
* Copyright (c) 2021 CommonsWare, LLC
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package com.commonsware.ggweb
import androidx.lifecycle.ViewModel
import publishers.C2PublishManager
import publishers.C2Publisher
data class Message(
val text: String,
val wasSent: Boolean
)
class MainMotor : ViewModel() {
private lateinit var _publisher: C2Publisher
fun setPublisher(publisher: C2Publisher) {
_publisher = publisher
}
fun handleMessage(text: String) {
Thread { _publisher.publish(text) }.start()
}
}
| 1
| null |
1
| 1
|
18a8b1a1bd5a586486af46406eb4b342a4769fd7
| 1,625
|
Black-Widow-Slave
|
MIT License
|
app/src/main/java/com/valerityoss/randomuserinfo/ui/ModernApplication.kt
|
shvets-denis
| 207,673,191
| false
| null |
package com.valerityoss.randomuserinfo.ui
import dagger.android.AndroidInjector
import dagger.android.DaggerApplication
class ModernApplication : DaggerApplication() {
override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
return DaggerAppComponent.builder().create(this)
}
}
| 0
|
Kotlin
|
0
| 0
|
ea21c46bbdb95bfe3ed6ab70d5f504e3416112ac
| 315
|
RandomUserInfo
|
Apache License 2.0
|
src/main/kotlin/g2801_2900/s2839_check_if_strings_can_be_made_equal_with_operations_i/Solution.kt
|
javadev
| 190,711,550
| false
|
{"Kotlin": 4909193, "TypeScript": 50446, "Python": 3646, "Shell": 994}
|
package g2801_2900.s2839_check_if_strings_can_be_made_equal_with_operations_i
// #Easy #String #2023_12_18_Time_154_ms_(100.00%)_Space_35.3_MB_(83.33%)
class Solution {
fun canBeEqual(s1: String, s2: String): Boolean {
return isOk(s1, s2, 0) && isOk(s1, s2, 1)
}
private fun isOk(s1: String, s2: String, i: Int): Boolean {
val a = s1[i]
val b = s1[i + 2]
val c = s2[i]
val d = s2[i + 2]
if (a == c && b == d) {
return true
}
return a == d && b == c
}
}
| 0
|
Kotlin
|
20
| 43
|
62708bc4d70ca2bfb6942e4bbfb4c64641e598e8
| 548
|
LeetCode-in-Kotlin
|
MIT License
|
src/main/kotlin/SymmetricState.kt
|
sander
| 606,774,943
| false
| null |
package nl.sanderdijkhuis.noise
data class SymmetricState(val cipherState: CipherState, val key: ChainingKey, val handshakeHash: HandshakeHash) {
val cryptography get() = cipherState.cryptography
fun mixKey(inputKeyMaterial: InputKeyMaterial) = let {
val result = deriveKeys(cryptography, key, inputKeyMaterial)
copy(
cipherState = CipherState(cryptography = cryptography, key = result.second.cipherKey),
key = result.first.chainingKey
)
}
fun mixHash(data: Data) = let {
val result = copy(handshakeHash = HandshakeHash(cryptography.hash(handshakeHash.digest.data + data)))
println("Mixing $handshakeHash + $data = ${result.handshakeHash}")
result
}
fun encryptAndHash(plaintext: Plaintext) = let {
println("Encrypting and hashing $handshakeHash $plaintext")
cipherState.encryptWithAssociatedData(handshakeHash.digest.data, plaintext).let {
State(copy(cipherState = it.current).mixHash(it.result.data), it.result)
}
}
fun decryptAndHash(ciphertext: Ciphertext) = let {
println("Decrypting and hashing $handshakeHash $ciphertext")
cipherState.decryptWithAssociatedData(handshakeHash.digest.data, ciphertext)?.let {
State(copy(cipherState = it.current).mixHash(ciphertext.data), it.result)
}
}
fun split() = let {
val zeroLen = InputKeyMaterial(Data.empty)
val temporaryKeys = deriveKeys(cryptography, key, zeroLen)
val c1 = CipherState(cryptography, temporaryKeys.first.cipherKey)
val c2 = CipherState(cryptography, temporaryKeys.second.cipherKey)
Pair(c1, c2)
}
companion object {
fun initialize(cryptography: Cryptography, protocolName: ProtocolName) = let {
println("Initializing $cryptography $protocolName ${protocolName.data.size} ${Digest.SIZE}")
val h = if (protocolName.data.size <= Digest.SIZE)
Digest(Data(Digest.SIZE.byteArray { protocolName.data.value.getOrElse(it) { 0x00 } }))
else
cryptography.hash(protocolName.data)
val ck = ChainingKey(h)
val state = CipherState(cryptography)
SymmetricState(state, ck, HandshakeHash(h))
}
private val BLOCK_SIZE = Size(64)
/** https://www.ietf.org/rfc/rfc2104.txt */
private fun authenticateMessage(cryptography: Cryptography, key: MessageAuthenticationKey, data: Data) = let {
fun block(init: (Int) -> Byte) = Data(ByteArray(BLOCK_SIZE.value, init))
val keyData =
if (key.data.size <= BLOCK_SIZE)
block { key.data.value.getOrElse(it) { 0x00 } }
else cryptography.hash(key.data).data
val innerPadding = block { 0x36 }
val outerPadding = block { 0x5c }
val digest =
cryptography.hash(keyData.xor(outerPadding) + cryptography.hash(keyData.xor(innerPadding) + data).data)
MessageAuthenticationData(digest)
}
internal fun deriveKeys(cryptography: Cryptography, key: ChainingKey, material: InputKeyMaterial) = let {
val temporaryKey =
authenticateMessage(cryptography, key.digest.messageAuthenticationKey, material.data)
val output1 =
authenticateMessage(cryptography, temporaryKey.digest.messageAuthenticationKey, Data(byteArrayOf(0x01)))
val output2 = authenticateMessage(
cryptography,
temporaryKey.digest.messageAuthenticationKey,
output1.digest.data + Data(byteArrayOf(0x02))
)
Pair(output1, output2)
}
}
}
| 1
|
Kotlin
|
0
| 0
|
5b961e181eb30ae5807f160ed04c629d0ebc5916
| 3,758
|
noise-kotlin
|
MIT License
|
app/src/main/java/com/dicoding/liveproject/RegisterActivity.kt
|
emdileven
| 793,342,706
| false
|
{"Kotlin": 5420}
|
package com.dicoding.liveproject
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.dicoding.liveproject.databinding.ActivityRegisterBinding
import com.google.firebase.auth.FirebaseAuth
class RegisterActivity : AppCompatActivity() {
private lateinit var binding: ActivityRegisterBinding
private lateinit var firebaseAuth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityRegisterBinding.inflate(layoutInflater)
setContentView(binding.root)
firebaseAuth = FirebaseAuth.getInstance()
binding.textView.setOnClickListener {
val intent = Intent(this@RegisterActivity, LoginActivity::class.java)
startActivity(intent)
}
binding.button.setOnClickListener {
val email = binding.emailEt.text.toString()
val password = binding.passET.text.toString()
val retypePassword = binding.retypepassET.text.toString()
if (email.isNotEmpty() && password.isNotEmpty() && retypePassword.isNotEmpty()) {
if (password == retypePassword) {
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener {
if (it.isSuccessful) {
val intent =
Intent(this@RegisterActivity, LoginActivity::class.java)
startActivity(intent)
} else {
Toast.makeText(this, it.exception.toString(), Toast.LENGTH_SHORT)
.show()
}
}
} else {
Toast.makeText(
this@RegisterActivity,
getString(R.string.password_isnt_matching),
Toast.LENGTH_SHORT
).show()
}
} else {
Toast.makeText(
this@RegisterActivity,
getString(R.string.field_must_be_filled),
Toast.LENGTH_SHORT
).show()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
b6f66973cf430f10deb5b2db6bf57f4632310a94
| 2,367
|
villagee
|
Apache License 2.0
|
projects/prison-custody-status-to-delius/src/main/kotlin/uk/gov/justice/digital/hmpps/integrations/delius/recall/reason/RecallReasonRepository.kt
|
ministryofjustice
| 500,855,647
| false
| null |
package uk.gov.justice.digital.hmpps.integrations.delius.recall.reason
import org.springframework.data.jpa.repository.JpaRepository
import uk.gov.justice.digital.hmpps.exception.NotFoundException
interface RecallReasonRepository : JpaRepository<RecallReason, Long> {
fun findByCodeAndSelectable(code: String, selectable: Boolean = true): RecallReason?
}
fun RecallReasonRepository.getByCodeAndSelectableIsTrue(code: String): RecallReason =
findByCodeAndSelectable(code) ?: throw NotFoundException("RecallReason", "code", code)
| 4
|
Kotlin
|
0
| 2
|
404fca1520f49953b96a792d266ee3d3d12ee73a
| 539
|
hmpps-probation-integration-services
|
MIT License
|
src/main/kotlin/org/crystal/intellij/psi/CrUnaryExpression.kt
|
asedunov
| 353,165,557
| false
| null |
package org.crystal.intellij.psi
import com.intellij.lang.ASTNode
import com.intellij.psi.tree.IElementType
import com.intellij.psi.util.elementType
class CrUnaryExpression(node: ASTNode) : CrExpressionImpl(node) {
override fun accept(visitor: CrVisitor) = visitor.visitUnaryExpression(this)
val opSign: IElementType?
get() = firstChild?.elementType
val argument: CrExpression?
get() = childOfType()
}
| 15
|
Kotlin
|
3
| 30
|
5dc69f80df256131bbca575ac0e0f3d05e12965f
| 433
|
intellij-crystal-lang
|
Apache License 2.0
|
src/main/kotlin/Market.kt
|
magnusesp
| 148,985,156
| false
| null |
@file:Suppress("unused")
package screeps
external interface Market {
val credits: Double
val incomingTransactions: Array<Transaction>
val orders: Record<String, Order>
val outgoingTransactions: Array<Transaction>
fun calcTransactionCost(amount: Int, roomName1: String, roomName2: String): Int
fun cancelOrder(orderId: String): ScreepsReturnCode
fun changeOrderPrice(orderId: String, newPrice: Double): ScreepsReturnCode
fun createOrder(
type: String,
resourceType: MarketResourceConstant,
price: Double,
totalAmount: Int,
roomName: String? = definedExternally
): ScreepsReturnCode
fun deal(orderId: String, amount: Int, targetRoomName: String? = definedExternally): ScreepsReturnCode
fun extendOrder(orderId: String, addAmount: Int): ScreepsReturnCode
fun getAllOrders(filter: Order.Filter? = definedExternally): Array<Order>
fun getAllOrders(filter: ((o: Order) -> Boolean)? = definedExternally): Array<Order>
fun getAllOrders(): Array<Order>
fun getOrderById(id: String): Order?
interface Order {
val id: String
val created: Int
val active: Boolean
val type: OrderConstant
val resourceType: MarketResourceConstant
val roomName: String
val amount: Int
val remainingAmount: Int
val totalAmount: Int
val price: Double
interface Filter {
val id: String?
val created: Int?
val type: OrderConstant?
val resourceType: MarketResourceConstant
val roomName: String?
val amount: Int?
val remainingAmount: Int?
val price: Double?
}
}
interface Transaction {
val transactionId: String
val time: Int
val sender: Owned.Owner
val recipient: Owned.Owner
val resourceType: MarketResourceConstant
val amount: Int
val from: String
val to: String
val description: String
val order: Order?
interface Order {
val id: String
val type: OrderConstant
val price: Double
}
}
}
| 0
|
Kotlin
|
1
| 0
|
d3501c3ae5855967fcbb1ba5d9f04e3ccc4baa02
| 1,978
|
kotlin-screeps
|
MIT License
|
lib/src/main/java/com/github/eklipse2k8/charting/jobs/AnimatedZoomJob.kt
|
eklipse2k8
| 403,391,938
| true
|
{"Kotlin": 945921, "Java": 57298}
|
package com.github.eklipse2k8.charting.jobs
import android.animation.Animator
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.graphics.Matrix
import android.view.View
import com.github.eklipse2k8.charting.charts.BarLineChartBase
import com.github.eklipse2k8.charting.components.YAxis
import com.github.eklipse2k8.charting.utils.ObjectPool
import com.github.eklipse2k8.charting.utils.ObjectPool.Poolable
import com.github.eklipse2k8.charting.utils.Transformer
import com.github.eklipse2k8.charting.utils.ViewPortHandler
/** Created by Philipp Jahoda on 19/02/16. */
@SuppressLint("NewApi")
class AnimatedZoomJob(
viewPortHandler: ViewPortHandler?,
v: View?,
trans: Transformer?,
private var yAxis: YAxis?,
private var xAxisRange: Float,
scaleX: Float,
scaleY: Float,
xOrigin: Float,
yOrigin: Float,
private var zoomCenterX: Float,
private var zoomCenterY: Float,
private var zoomOriginX: Float,
private var zoomOriginY: Float,
duration: Long
) :
AnimatedViewPortJob(viewPortHandler, scaleX, scaleY, trans, v, xOrigin, yOrigin, duration),
Animator.AnimatorListener {
companion object {
private var pool: ObjectPool<AnimatedZoomJob>? = null
fun getInstance(
viewPortHandler: ViewPortHandler?,
v: View?,
trans: Transformer?,
axis: YAxis?,
xAxisRange: Float,
scaleX: Float,
scaleY: Float,
xOrigin: Float,
yOrigin: Float,
zoomCenterX: Float,
zoomCenterY: Float,
zoomOriginX: Float,
zoomOriginY: Float,
duration: Long
): AnimatedZoomJob? {
val result = pool?.get() ?: return null
result.viewPortHandler = viewPortHandler
result.xValue = scaleX
result.yValue = scaleY
result.transformer = trans
result.view = v
result.xOrigin = xOrigin
result.yOrigin = yOrigin
result.yAxis = axis
result.xAxisRange = xAxisRange
result.resetAnimator()
result.animator.duration = duration
return result
}
init {
pool =
ObjectPool.create(
8, AnimatedZoomJob(null, null, null, null, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0L)) as
ObjectPool<AnimatedZoomJob>?
}
}
private var onAnimationUpdateMatrixBuffer = Matrix()
override fun onAnimationUpdate(animation: ValueAnimator) {
if (viewPortHandler == null) {
return
}
val scaleX = xOrigin + (xValue - xOrigin) * phase
val scaleY = yOrigin + (yValue - yOrigin) * phase
with(requireNotNull(viewPortHandler)) {
onAnimationUpdateMatrixBuffer =
setZoom(scaleX = scaleX, scaleY = scaleY, inputMatrix = onAnimationUpdateMatrixBuffer)
refresh(onAnimationUpdateMatrixBuffer, view, true)
}
val valsInView = (yAxis?.mAxisRange ?: 0f) / viewPortHandler!!.scaleY
val xsInView = xAxisRange / viewPortHandler!!.scaleX
pts[0] = zoomOriginX + (zoomCenterX - xsInView / 2f - zoomOriginX) * phase
pts[1] = zoomOriginY + (zoomCenterY + valsInView / 2f - zoomOriginY) * phase
transformer?.pointValuesToPixel(pts)
viewPortHandler?.translate(pts, onAnimationUpdateMatrixBuffer)
viewPortHandler?.refresh(onAnimationUpdateMatrixBuffer, view, true)
}
override fun onAnimationEnd(animation: Animator) {
if (view is BarLineChartBase<*, *, *>) {
(view as BarLineChartBase<*, *, *>).calculateOffsets()
}
view?.postInvalidate()
}
override fun onAnimationCancel(animation: Animator) = Unit
override fun onAnimationRepeat(animation: Animator) = Unit
override fun recycleSelf() = Unit
override fun onAnimationStart(animation: Animator) = Unit
override fun instantiate(): Poolable {
return AnimatedZoomJob(null, null, null, null, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0L)
}
init {
animator.addListener(this)
}
}
| 0
|
Kotlin
|
0
| 0
|
29d416f36d7fd1b6af13082c2ef6b7d6abe0cab8
| 3,905
|
ComposeChart
|
Apache License 2.0
|
app/src/main/java/iambedoy/coco/MainActivity.kt
|
cbedoy
| 278,022,344
| false
| null |
package iambedoy.coco
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.Fragment
import iambedoy.coco.explorer.ExplorerFragment
import iambedoy.coco.messages.MessagesFragment
import iambedoy.coco.settings.SettingsFragment
import kotlinx.android.synthetic.main.activity_main.*
import org.koin.android.ext.android.inject
class MainActivity : AppCompatActivity() {
private val messagesFragment : MessagesFragment by inject()
private val explorerFragment: ExplorerFragment by inject()
private val settingsFragment: SettingsFragment by inject()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bottom_navigation.setOnNavigationItemSelectedListener {
when(it.itemId){
R.id.action_messages -> {
showFragment(messagesFragment)
}
R.id.action_explorer -> {
showFragment(explorerFragment)
}
R.id.action_settings -> {
showFragment(settingsFragment)
}
}
true
}
showFragment(messagesFragment)
}
}
| 0
|
Kotlin
|
0
| 0
|
6ce2c3874d0acd3258bf00f1860d5f15598b4f9c
| 1,271
|
Coco
|
Apache License 2.0
|
app/src/main/java/iambedoy/coco/MainActivity.kt
|
cbedoy
| 278,022,344
| false
| null |
package iambedoy.coco
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.Fragment
import iambedoy.coco.explorer.ExplorerFragment
import iambedoy.coco.messages.MessagesFragment
import iambedoy.coco.settings.SettingsFragment
import kotlinx.android.synthetic.main.activity_main.*
import org.koin.android.ext.android.inject
class MainActivity : AppCompatActivity() {
private val messagesFragment : MessagesFragment by inject()
private val explorerFragment: ExplorerFragment by inject()
private val settingsFragment: SettingsFragment by inject()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bottom_navigation.setOnNavigationItemSelectedListener {
when(it.itemId){
R.id.action_messages -> {
showFragment(messagesFragment)
}
R.id.action_explorer -> {
showFragment(explorerFragment)
}
R.id.action_settings -> {
showFragment(settingsFragment)
}
}
true
}
showFragment(messagesFragment)
}
}
| 0
|
Kotlin
|
0
| 0
|
6ce2c3874d0acd3258bf00f1860d5f15598b4f9c
| 1,271
|
Coco
|
Apache License 2.0
|
app/src/main/java/io/horizontalsystems/bankwallet/modules/manageaccount/ManageAccountViewModel.kt
|
horizontalsystems
| 142,825,178
| false
| null |
package io.exzocoin.wallet.modules.manageaccount
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import io.exzocoin.wallet.core.Clearable
import io.exzocoin.wallet.core.subscribeIO
import io.exzocoin.wallet.entities.Account
import io.exzocoin.coinkit.models.CoinType
import io.exzocoin.core.SingleLiveEvent
import io.reactivex.disposables.CompositeDisposable
class ManageAccountViewModel(
private val service: ManageAccountService,
private val clearables: List<Clearable>
) : ViewModel() {
val disposable = CompositeDisposable()
val keyActionStateLiveData = MutableLiveData<KeyActionState>()
val saveEnabledLiveData = MutableLiveData<Boolean>()
val finishLiveEvent = SingleLiveEvent<Unit>()
val additionalViewItemsLiveData = MutableLiveData<List<AdditionalViewItem>>()
val account: Account
get() = service.account
init {
service.stateObservable
.subscribeIO { syncState(it) }
.let { disposable.add(it) }
service.accountObservable
.subscribeIO { syncAccount(it) }
.let { disposable.add(it) }
service.accountDeletedObservable
.subscribeIO { finishLiveEvent.postValue(Unit) }
.let { disposable.add(it) }
syncState(service.state)
syncAccount(service.account)
syncAccountSettings()
}
private fun syncState(state: ManageAccountService.State) {
when (state) {
ManageAccountService.State.CanSave -> saveEnabledLiveData.postValue(true)
ManageAccountService.State.CannotSave -> saveEnabledLiveData.postValue(false)
}
}
private fun syncAccount(account: Account) {
keyActionStateLiveData.postValue(if (account.isBackedUp) KeyActionState.ShowRecoveryPhrase else KeyActionState.BackupRecoveryPhrase)
}
private fun syncAccountSettings() {
val additionalViewItems = service.accountSettingsInfo.map { (coin, restoreSettingType, value) ->
AdditionalViewItem(coin.type, service.getSettingsTitle(restoreSettingType, coin), value)
}
additionalViewItemsLiveData.postValue(additionalViewItems)
}
fun onChange(name: String?) {
service.setName(name ?: "")
}
fun onSave() {
service.saveAccount()
finishLiveEvent.postValue(Unit)
}
fun onUnlink() {
service.deleteAccount()
}
override fun onCleared() {
disposable.clear()
clearables.forEach(Clearable::clear)
}
enum class KeyActionState {
ShowRecoveryPhrase, BackupRecoveryPhrase
}
data class AdditionalViewItem(
val coinType: CoinType,
val title: String,
val value: String
)
}
| 163
| null |
219
| 402
|
5ce20e6e4e0f75a76496051ba6f78312bc641a51
| 2,793
|
unstoppable-wallet-android
|
MIT License
|
inventory-api/src/main/kotlin/de/fllip/inventory/api/module/InventoryModule.kt
|
FllipEis
| 319,325,120
| false
| null |
/*
* MIT License
*
* Copyright (c) 2020 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package de.fllip.inventory.api.module
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.module.SimpleModule
import com.google.inject.AbstractModule
import com.google.inject.name.Names
import de.fllip.inventory.api.section.AbstractInventorySection
import de.fllip.inventory.api.section.deserializer.InventorySectionDeserializer
import de.fllip.inventory.api.storage.IStorageLoader
import org.bukkit.plugin.java.JavaPlugin
/**
* Created by IntelliJ IDEA.
* User: Philipp.Eistrach
* Date: 02.12.2020
* Time: 17:41
*/
class InventoryModule(
private val javaPlugin: JavaPlugin,
private val storageLoaderClass: Class<out IStorageLoader>
) : AbstractModule() {
override fun configure() {
val objectMapper = ObjectMapper()
val module = SimpleModule()
module.addDeserializer(AbstractInventorySection::class.java, InventorySectionDeserializer())
objectMapper.registerModule(module)
bind(IStorageLoader::class.java).to(storageLoaderClass)
bind(ObjectMapper::class.java).annotatedWith(Names.named("inventoryapi")).toInstance(objectMapper)
bind(JavaPlugin::class.java).toInstance(javaPlugin)
}
}
| 1
|
Kotlin
|
2
| 4
|
3fa9e1f49acf4db3c9771bcd47bb9096f5299e66
| 2,333
|
inventory-api
|
MIT License
|
prime-router/src/main/kotlin/azure/DatabaseAccess.kt
|
CDCgov
| 304,423,150
| false
| null |
package gov.cdc.prime.router.azure
import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import gov.cdc.prime.router.Organization
import gov.cdc.prime.router.Report
import gov.cdc.prime.router.ReportId
import gov.cdc.prime.router.azure.db.Tables
import gov.cdc.prime.router.azure.db.Tables.COVID_RESULT_METADATA
import gov.cdc.prime.router.azure.db.Tables.EMAIL_SCHEDULE
import gov.cdc.prime.router.azure.db.Tables.JTI_CACHE
import gov.cdc.prime.router.azure.db.Tables.RECEIVER_CONNECTION_CHECK_RESULTS
import gov.cdc.prime.router.azure.db.Tables.REPORT_FACILITIES
import gov.cdc.prime.router.azure.db.Tables.REPORT_LINEAGE
import gov.cdc.prime.router.azure.db.Tables.SETTING
import gov.cdc.prime.router.azure.db.Tables.TASK
import gov.cdc.prime.router.azure.db.enums.SettingType
import gov.cdc.prime.router.azure.db.enums.TaskAction
import gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE
import gov.cdc.prime.router.azure.db.tables.pojos.CovidResultMetadata
import gov.cdc.prime.router.azure.db.tables.pojos.ItemLineage
import gov.cdc.prime.router.azure.db.tables.pojos.JtiCache
import gov.cdc.prime.router.azure.db.tables.pojos.ReportFile
import gov.cdc.prime.router.azure.db.tables.pojos.Setting
import gov.cdc.prime.router.azure.db.tables.pojos.Task
import gov.cdc.prime.router.azure.db.tables.records.CovidResultMetadataRecord
import gov.cdc.prime.router.azure.db.tables.records.TaskRecord
import org.apache.logging.log4j.kotlin.Logging
import org.flywaydb.core.Flyway
import org.jooq.Configuration
import org.jooq.DSLContext
import org.jooq.Field
import org.jooq.JSON
import org.jooq.SQLDialect
import org.jooq.impl.DSL
import org.jooq.impl.DSL.count
import org.jooq.impl.DSL.inline
import org.postgresql.Driver
import java.sql.Connection
import java.sql.DriverManager
import java.time.OffsetDateTime
import java.time.ZoneOffset
import java.util.UUID
import javax.sql.DataSource
const val databaseVariable = "POSTGRES_URL"
const val userVariable = "POSTGRES_USER"
const val passwordVariable = "POSTGRES_PASSWORD"
// general max length of free from metadata strings since jooq/postgres
// does not truncate values when persisting to the database
const val METADATA_MAX_LENGTH = 512
typealias DataAccessTransaction = Configuration
/**
* A data access layer for the database. The idea or abstraction is CRUD on tables in the database.
* The interface uses the POJO abstractions of the database tables.
*
* The companion object does the connection pooling and settings.
*/
class DatabaseAccess(private val create: DSLContext) : Logging {
constructor(
dataSource: DataSource = commonDataSource
) : this(DSL.using(dataSource, SQLDialect.POSTGRES))
constructor(connection: Connection) : this(DSL.using(connection, SQLDialect.POSTGRES))
fun checkConnection() {
create.selectFrom(REPORT_FILE).where(REPORT_FILE.REPORT_ID.eq(UUID.randomUUID())).fetch()
}
/** Make the other calls in the context of a SQL transaction */
fun transact(block: (txn: DataAccessTransaction) -> Unit) {
create.transaction { txn: Configuration -> block(txn) }
}
/** Make the other calls in the context of a SQL transaction, returning a result */
fun <T> transactReturning(block: (txn: DataAccessTransaction) -> T): T {
return create.transactionResult { txn: Configuration -> block(txn) }
}
/*
* Task queries
*/
/** Fetch a task record and lock it so other connections can grab it */
fun fetchAndLockTask(reportId: ReportId, txn: DataAccessTransaction): Task {
return DSL.using(txn)
.selectFrom(TASK)
.where(TASK.REPORT_ID.eq(reportId))
.forUpdate()
.fetchOne()
?.into(Task::class.java)
?: error("Could not find $reportId that matches a task")
}
/** Fetch multiple task records and lock them so other connections can not grab them */
fun fetchAndLockTasks(
nextAction: TaskAction,
at: OffsetDateTime?,
receiverFullName: String,
limit: Int,
txn: DataAccessTransaction
): List<Task> {
val cond =
if (at == null) {
TASK.RECEIVER_NAME.eq(receiverFullName).and(TASK.NEXT_ACTION.eq(nextAction))
} else {
TASK.RECEIVER_NAME
.eq(receiverFullName)
.and(TASK.NEXT_ACTION.eq(nextAction))
.and(TASK.NEXT_ACTION_AT.eq(at))
}
return DSL.using(txn)
.selectFrom(TASK)
.where(cond)
.limit(limit)
.forUpdate()
.skipLocked() // Allows the same query to run in parallel. Otherwise, the query
// would lock the table.
.fetch()
.into(Task::class.java)
}
fun fetchTask(reportId: ReportId): Task {
return create.selectFrom(TASK)
.where(TASK.REPORT_ID.eq(reportId))
.fetchOne()
?.into(Task::class.java)
?: error("Could not find $reportId that matches a task")
}
/** Take a report and put into the database after already serializing the body of the report */
fun insertTask(
report: Report,
bodyFormat: String,
bodyUrl: String,
nextAction: Event,
txn: DataAccessTransaction? = null,
) {
fun insert(txn: Configuration) {
val task = createTaskRecord(report, bodyFormat, bodyUrl, nextAction)
DSL.using(txn).executeInsert(task)
}
if (txn != null) {
insert(txn)
} else {
create.transaction { innerTxn -> insert(innerTxn) }
}
}
fun updateTask(
reportId: ReportId,
nextAction: TaskAction,
nextActionAt: OffsetDateTime?,
retryToken: String?,
finishedField: Field<OffsetDateTime>,
txn: DataAccessTransaction?
) {
val ctx = if (txn != null) DSL.using(txn) else create
ctx.update(TASK)
.set(TASK.NEXT_ACTION, nextAction)
.set(TASK.NEXT_ACTION_AT, nextActionAt)
.set(TASK.RETRY_TOKEN, if (retryToken != null) JSON.valueOf(retryToken) else null)
.set(finishedField, OffsetDateTime.now())
.where(TASK.REPORT_ID.eq(reportId))
.execute()
}
/*
* ActionHistory queries
*/
/** You should include org as a search criteria to enforce authorization to get that report. */
fun fetchReportFile(
reportId: ReportId,
org: Organization? = null,
txn: DataAccessTransaction? = null
): ReportFile {
val ctx = if (txn != null) DSL.using(txn) else create
val cond =
if (org == null) {
Tables.REPORT_FILE.REPORT_ID.eq(reportId)
} else {
Tables.REPORT_FILE
.REPORT_ID
.eq(reportId)
.and(Tables.REPORT_FILE.RECEIVING_ORG.eq(org.name))
}
return ctx.selectFrom(Tables.REPORT_FILE)
.where(cond)
.fetchOne()
?.into(ReportFile::class.java)
?: error(
"Could not find $reportId in REPORT_FILE" +
if (org != null) {
" associated with organization ${org.name}"
} else ""
)
}
fun fetchAllInternalReports(
createdDateTime: OffsetDateTime? = null,
txn: DataAccessTransaction? = null
): List<ReportFile> {
val createdDt = createdDateTime ?: OffsetDateTime.now().minusDays(30)
val ctx = if (txn != null) DSL.using(txn) else create
val cond =
Tables.REPORT_FILE
.SENDING_ORG
.isNotNull
.and(Tables.REPORT_FILE.BODY_FORMAT.eq("INTERNAL"))
.and(Tables.REPORT_FILE.CREATED_AT.ge(createdDt))
return ctx.selectFrom(Tables.REPORT_FILE).where(cond).fetchArray().map {
it.into(ReportFile::class.java)
}
}
/** Returns null if report has no item-level lineage info tracked. */
fun fetchItemLineagesForReport(
reportId: ReportId,
itemCount: Int,
txn: DataAccessTransaction? = null
): List<ItemLineage>? {
val ctx = if (txn != null) DSL.using(txn) else create
val itemLineages =
ctx.selectFrom(Tables.ITEM_LINEAGE)
.where(Tables.ITEM_LINEAGE.CHILD_REPORT_ID.eq(reportId))
.orderBy(
Tables.ITEM_LINEAGE.CHILD_INDEX
) // todo Don't know if this will be too slow? Use a map in mem?
.fetch()
.into(ItemLineage::class.java)
.toList()
// sanity check. If there are lineages, every record up to itemCount should have at least
// one lineage.
// OK to have more than one lineage. Eg, a merge.
if (itemLineages.isEmpty()) {
return null
} else {
if (itemLineages.size < itemCount)
error(
"For $reportId, must have at least $itemCount item lineages. There were ${itemLineages.size}"
)
val uniqueIndexCount = itemLineages.map { it.childIndex }.toSet().size
if (uniqueIndexCount != itemCount)
error(
"For report $reportId, expected $itemCount unique indexes; there were $uniqueIndexCount"
)
}
return itemLineages
}
fun fetchDownloadableReportFiles(
since: OffsetDateTime?,
orgName: String,
txn: DataAccessTransaction? = null,
): List<ReportFile> {
val ctx = if (txn != null) DSL.using(txn) else create
val cond =
if (since == null) {
Tables.REPORT_FILE
.RECEIVING_ORG
.eq(orgName)
.and(Tables.REPORT_FILE.NEXT_ACTION.eq(TaskAction.send))
} else {
Tables.REPORT_FILE
.RECEIVING_ORG
.eq(orgName)
.and(Tables.REPORT_FILE.NEXT_ACTION.eq(TaskAction.send))
.and(Tables.REPORT_FILE.CREATED_AT.ge(since))
}
return ctx.selectFrom(Tables.REPORT_FILE)
.where(cond)
.fetch()
.into(ReportFile::class.java)
.toList()
}
fun fetchChildReports(
parentReportId: UUID,
txn: DataAccessTransaction? = null,
): List<ReportId> {
val ctx = if (txn != null) DSL.using(txn) else create
return ctx.select(REPORT_LINEAGE.CHILD_REPORT_ID)
.from(REPORT_LINEAGE)
.where(REPORT_LINEAGE.PARENT_REPORT_ID.eq(parentReportId))
.fetch()
.into(ReportId::class.java)
.toList()
}
/** Settings queries */
fun fetchSetting(
type: SettingType,
name: String,
parentId: Int?,
txn: DataAccessTransaction
): Setting? {
return DSL.using(txn)
.selectFrom(SETTING)
.where(
SETTING.IS_ACTIVE.isTrue,
SETTING.TYPE.eq(type),
SETTING.NAME.eq(name),
if (parentId != null) SETTING.ORGANIZATION_ID.eq(parentId)
else SETTING.ORGANIZATION_ID.isNull
)
.fetchOne()
?.into(Setting::class.java)
}
fun fetchSetting(
type: SettingType,
name: String,
organizationName: String,
txn: DataAccessTransaction
): Setting? {
val org = SETTING.`as`("org")
val item = SETTING.`as`("item")
return DSL.using(txn)
.select(item.asterisk())
.from(item)
.join(org)
.on(item.ORGANIZATION_ID.eq(org.SETTING_ID))
.where(
item.IS_ACTIVE.isTrue,
item.TYPE.eq(type),
item.NAME.eq(name),
org.IS_ACTIVE.isTrue,
org.TYPE.eq(SettingType.ORGANIZATION),
org.ORGANIZATION_ID.isNull,
org.NAME.eq(organizationName),
)
.fetchOne()
?.into(Setting::class.java)
}
/**
* Fetch both the item and the organization of the item at the same time to optimize db queries
*/
fun fetchOrganizationAndSetting(
type: SettingType,
name: String,
organizationName: String,
txn: DataAccessTransaction? = null
): Pair<Setting, Setting>? {
val org = SETTING.`as`("org")
val item = SETTING.`as`("item")
val ctx = if (txn != null) DSL.using(txn) else create
val result =
ctx.select(item.asterisk(), org.asterisk())
.from(item)
.join(org)
.on(item.ORGANIZATION_ID.eq(org.SETTING_ID))
.where(
item.IS_ACTIVE.isTrue,
item.TYPE.eq(type),
item.NAME.eq(name),
org.IS_ACTIVE.isTrue,
org.TYPE.eq(SettingType.ORGANIZATION),
org.ORGANIZATION_ID.isNull,
org.NAME.eq(organizationName),
)
.fetchOne()
?: return null
val itemSetting =
Setting(
result.get(item.SETTING_ID),
result.get(item.TYPE),
result.get(item.NAME),
result.get(item.ORGANIZATION_ID),
result.get(item.VALUES),
result.get(item.IS_DELETED),
result.get(item.IS_ACTIVE),
result.get(item.VERSION),
result.get(item.CREATED_BY),
result.get(item.CREATED_AT)
)
val orgSetting =
Setting(
result.get(org.SETTING_ID),
result.get(org.TYPE),
result.get(org.NAME),
result.get(org.ORGANIZATION_ID),
result.get(org.VALUES),
result.get(org.IS_DELETED),
result.get(org.IS_ACTIVE),
result.get(org.VERSION),
result.get(org.CREATED_BY),
result.get(org.CREATED_AT)
)
return Pair(orgSetting, itemSetting)
}
fun fetchSettings(type: SettingType, txn: DataAccessTransaction): List<Setting> {
return DSL.using(txn)
.selectFrom(SETTING)
.where(SETTING.IS_ACTIVE.isTrue, SETTING.TYPE.eq(type))
.orderBy(SETTING.SETTING_ID)
.fetch()
.into(Setting::class.java)
}
fun fetchSettings(
type: SettingType,
organizationId: Int,
txn: DataAccessTransaction
): List<Setting> {
return DSL.using(txn)
.select()
.from(SETTING)
.where(
SETTING.IS_ACTIVE.isTrue,
SETTING.TYPE.eq(type),
SETTING.ORGANIZATION_ID.eq(organizationId)
)
.orderBy(SETTING.SETTING_ID)
.fetch()
.into(Setting::class.java)
}
fun insertSetting(setting: Setting, txn: DataAccessTransaction): Int {
return DSL.using(txn)
.insertInto(SETTING)
.set(SETTING.SETTING_ID, DSL.defaultValue(SETTING.SETTING_ID))
.set(SETTING.TYPE, setting.type)
.set(SETTING.ORGANIZATION_ID, setting.organizationId)
.set(SETTING.NAME, setting.name)
.set(SETTING.IS_ACTIVE, setting.isActive)
.set(SETTING.IS_DELETED, setting.isDeleted)
.set(SETTING.VALUES, setting.values)
.set(SETTING.VERSION, setting.version)
.set(SETTING.CREATED_AT, setting.createdAt)
.set(SETTING.CREATED_BY, setting.createdBy)
.returningResult(SETTING.SETTING_ID)
.fetchOne()
?.value1()
?: error("Fetch error")
}
fun updateOrganizationId(
currentOrganizationId: Int,
newOrganizationId: Int,
txn: DataAccessTransaction
) {
DSL.using(txn)
.update(SETTING)
.set(SETTING.ORGANIZATION_ID, newOrganizationId)
.where(SETTING.ORGANIZATION_ID.eq(currentOrganizationId), SETTING.IS_ACTIVE.isTrue)
.execute()
}
/** search for a setting and it children, insert a deleted setting for those found */
fun insertDeletedSettingAndChildren(
settingId: Int,
settingMetadata: SettingMetadata,
txn: DataAccessTransaction
) {
DSL.using(txn)
.insertInto(
SETTING,
SETTING.TYPE,
SETTING.ORGANIZATION_ID,
SETTING.NAME,
SETTING.VALUES,
SETTING.IS_DELETED,
SETTING.IS_ACTIVE,
SETTING.VERSION,
SETTING.CREATED_BY,
SETTING.CREATED_AT
)
.select(
DSL.select(
SETTING.TYPE,
SETTING.ORGANIZATION_ID,
SETTING.NAME,
SETTING.VALUES,
DSL.value(true, SETTING.IS_DELETED),
DSL.value(false, SETTING.IS_ACTIVE),
SETTING.VERSION.plus(1),
DSL.value(settingMetadata.createdBy, SETTING.CREATED_BY),
DSL.value(settingMetadata.createdAt, SETTING.CREATED_AT)
)
.from(SETTING)
.where(
SETTING.SETTING_ID
.eq(settingId)
.or(SETTING.ORGANIZATION_ID.eq(settingId)),
SETTING.IS_ACTIVE.isTrue
)
)
.execute()
}
fun deactivateSetting(settingId: Int, txn: DataAccessTransaction) {
DSL.using(txn)
.update(SETTING)
.set(SETTING.IS_ACTIVE, false)
.where(SETTING.SETTING_ID.eq(settingId))
.execute()
}
fun deactivateSettingAndChildren(settingId: Int, txn: DataAccessTransaction) {
DSL.using(txn)
.update(SETTING)
.set(SETTING.IS_ACTIVE, false)
.where(
SETTING.SETTING_ID.eq(settingId).or(SETTING.ORGANIZATION_ID.eq(settingId)),
SETTING.IS_ACTIVE.isTrue
)
.execute()
}
/**
* Find the current setting version looking through inactive and active settings. Return -1 no
* setting is found.
*/
fun findSettingVersion(
type: SettingType,
name: String,
organizationId: Int?,
txn: DataAccessTransaction
): Int {
return DSL.using(txn)
.select(DSL.max(SETTING.VERSION))
.from(SETTING)
.where(
SETTING.TYPE.eq(type),
SETTING.NAME.eq(name),
if (organizationId == null) SETTING.ORGANIZATION_ID.isNull
else SETTING.ORGANIZATION_ID.eq(organizationId)
)
.fetchOne()
?.getValue(DSL.max(SETTING.VERSION))
?: -1
}
fun insertJti(jti: String, expiresAt: OffsetDateTime? = null, txn: DataAccessTransaction) {
val jtiCache = JtiCache()
jtiCache.jti = jti
jtiCache.expiresAt = expiresAt
DSL.using(txn).newRecord(JTI_CACHE, jtiCache).store()
}
fun deleteExpiredJtis(txn: DataAccessTransaction) {
DSL.using(txn)
.deleteFrom(JTI_CACHE)
.where(JTI_CACHE.EXPIRES_AT.lt(OffsetDateTime.now()))
.execute()
}
fun fetchJti(jti: String, txn: DataAccessTransaction): JtiCache? {
return DSL.using(txn)
.selectFrom(JTI_CACHE)
.where(JTI_CACHE.JTI.eq(jti))
.fetchOne()
?.into(JtiCache::class.java)
}
/** EmailSchedule queries */
fun fetchEmailSchedules(txn: DataAccessTransaction? = null): List<String> {
val ctx = if (txn != null) DSL.using(txn) else create
return ctx.select(EMAIL_SCHEDULE.VALUES)
.from(EMAIL_SCHEDULE)
.where(EMAIL_SCHEDULE.IS_ACTIVE.eq(true))
.fetch()
.into(String::class.java)
}
fun insertEmailSchedule(body: String?, user: String, txn: DataAccessTransaction? = null): Int? {
val ctx = if (txn != null) DSL.using(txn) else create
return ctx.insertInto(EMAIL_SCHEDULE)
.set(
EMAIL_SCHEDULE.EMAIL_SCHEDULE_ID,
DSL.defaultValue(EMAIL_SCHEDULE.EMAIL_SCHEDULE_ID)
)
.set(EMAIL_SCHEDULE.VALUES, JSON.valueOf(body))
.set(EMAIL_SCHEDULE.IS_ACTIVE, true)
.set(EMAIL_SCHEDULE.VERSION, 1)
.set(EMAIL_SCHEDULE.CREATED_BY, user)
.set(EMAIL_SCHEDULE.CREATED_AT, OffsetDateTime.now())
.returningResult(EMAIL_SCHEDULE.EMAIL_SCHEDULE_ID)
.fetchOne()
?.into(Int::class.java)
}
fun deleteEmailSchedule(id: Int, txn: DataAccessTransaction? = null) {
val ctx = if (txn != null) DSL.using(txn) else create
ctx.update(EMAIL_SCHEDULE)
.set(EMAIL_SCHEDULE.IS_ACTIVE, false)
.where(EMAIL_SCHEDULE.EMAIL_SCHEDULE_ID.eq(id))
.execute()
}
/**
* Saves metadata to database. Since jooq/postgres does not truncate data that is too long, any
* columns that can be of varying length are truncated so the batch transaction is not lost. All
* of these columns have been normalized to METADATA_MAX_LENGTH out of convenience.
* @param testData : the report meta data to persist
* @param txn : the database transaction to use for this insert/update
*/
fun saveTestData(testData: List<CovidResultMetadata>, txn: DataAccessTransaction) {
DSL.using(txn)
.batchInsert(
testData.map { td ->
CovidResultMetadataRecord().also { record ->
record.messageId = td.messageId?.take(METADATA_MAX_LENGTH)
record.reportId = td.reportId
record.reportIndex = td.reportIndex
record.orderingProviderName =
td.orderingProviderName?.take(METADATA_MAX_LENGTH)
record.orderingProviderCounty =
td.orderingProviderCounty?.take(METADATA_MAX_LENGTH)
record.orderingProviderId =
td.orderingProviderId?.take(METADATA_MAX_LENGTH)
record.orderingProviderPostalCode = td.orderingProviderPostalCode
record.orderingProviderState =
td.orderingProviderState?.take(METADATA_MAX_LENGTH)
record.orderingFacilityCity =
td.orderingFacilityCity?.take(METADATA_MAX_LENGTH)
record.orderingFacilityCounty =
td.orderingFacilityCounty?.take(METADATA_MAX_LENGTH)
record.orderingFacilityName =
td.orderingFacilityName?.take(METADATA_MAX_LENGTH)
record.orderingFacilityPostalCode = td.orderingFacilityPostalCode
record.orderingFacilityState =
td.orderingFacilityState?.take(METADATA_MAX_LENGTH)
record.testResult = td.testResult?.take(METADATA_MAX_LENGTH)
record.testResultCode = td.testResultCode
record.equipmentModel = td.equipmentModel?.take(METADATA_MAX_LENGTH)
record.specimenCollectionDateTime = td.specimenCollectionDateTime
record.testingLabCity = td.testingLabCity?.take(METADATA_MAX_LENGTH)
record.testingLabClia = td.testingLabClia
record.testingLabCounty =
td.testingLabCounty?.take(METADATA_MAX_LENGTH)
record.testingLabName = td.testingLabName?.take(METADATA_MAX_LENGTH)
record.testingLabPostalCode = td.testingLabPostalCode
record.testingLabState =
td.testingLabState?.take(METADATA_MAX_LENGTH)
record.patientAge = td.patientAge
record.patientCounty = td.patientCounty?.take(METADATA_MAX_LENGTH)
record.patientEthnicity = td.patientEthnicity
record.patientEthnicityCode = td.patientEthnicityCode
record.patientGender = td.patientGender
record.patientGenderCode = td.patientGenderCode
record.patientPostalCode = td.patientPostalCode
record.patientRace = td.patientRace
record.patientRaceCode = td.patientRaceCode
record.patientState = td.patientState?.take(METADATA_MAX_LENGTH)
record.siteOfCare = td.siteOfCare?.take(METADATA_MAX_LENGTH)
record.senderId = td.senderId?.take(METADATA_MAX_LENGTH)
record.testKitNameId = td.testKitNameId?.take(METADATA_MAX_LENGTH)
record.testPerformedLoincCode = td.testPerformedLoincCode?.take(METADATA_MAX_LENGTH)
}
}
)
.execute()
}
fun getFacilitiesForDownloadableReport(
reportId: ReportId,
txn: DataAccessTransaction? = null
): List<Facility> {
val ctx = if (txn != null) DSL.using(txn) else create
val result =
ctx.select(
REPORT_FACILITIES.TESTING_LAB_NAME,
REPORT_FACILITIES.TESTING_LAB_CITY,
REPORT_FACILITIES.TESTING_LAB_STATE,
REPORT_FACILITIES.TESTING_LAB_CLIA,
REPORT_FACILITIES.POSITIVE,
REPORT_FACILITIES.COUNT_RECORDS
)
.from(REPORT_FACILITIES(reportId))
.fetch()
return result.map {
Facility.Builder(
facility = it.get(COVID_RESULT_METADATA.TESTING_LAB_NAME),
CLIA = it.get(COVID_RESULT_METADATA.TESTING_LAB_CLIA),
total = it.get(REPORT_FACILITIES.COUNT_RECORDS),
positive = it.get(REPORT_FACILITIES.POSITIVE),
location =
if (it.get(COVID_RESULT_METADATA.TESTING_LAB_CITY)
.isNullOrBlank()
)
it.get(COVID_RESULT_METADATA.TESTING_LAB_STATE)
else
"${it.get(COVID_RESULT_METADATA.TESTING_LAB_CITY)}, " +
it.get(COVID_RESULT_METADATA.TESTING_LAB_STATE)
)
.build()
}
}
fun deleteTestDataForReportId(reportId: UUID, txn: DataAccessTransaction) {
DSL.using(txn)
.deleteFrom(COVID_RESULT_METADATA)
.where(COVID_RESULT_METADATA.REPORT_ID.eq(reportId))
.execute()
}
fun checkReportExists(reportId: ReportId, txn: DataAccessTransaction): Boolean {
// this is how you do a select 1 from ... in jooq
return (
DSL.using(txn)
.select(inline(1))
.from(REPORT_FILE)
.where(REPORT_FILE.REPORT_ID.eq(reportId))
.count()
) > 0
}
/** Fetch the newest CreatedAt timestamp, active or deleted. */
fun fetchLastModified(txn: DataAccessTransaction? = null): OffsetDateTime? {
val ctx = if (txn != null) DSL.using(txn) else create
return ctx.select(DSL.max(SETTING.CREATED_AT))
.from(SETTING)
.fetchOne()
?.getValue(DSL.max(SETTING.CREATED_AT))
}
/**
* Saves the connection check result to the db
*/
fun saveRemoteConnectionCheck(
txn: DataAccessTransaction? = null,
connectionCheck: CheckFunction.RemoteConnectionCheck
) {
val ctx = if (txn != null) DSL.using(txn) else create
val initiatedOn = connectionCheck.initiatedOn.atOffset(ZoneOffset.UTC)
val completedOn = connectionCheck.completedAt.atOffset(ZoneOffset.UTC)
ctx.insertInto(RECEIVER_CONNECTION_CHECK_RESULTS)
.set(RECEIVER_CONNECTION_CHECK_RESULTS.ORGANIZATION_ID, connectionCheck.organizationId)
.set(RECEIVER_CONNECTION_CHECK_RESULTS.RECEIVER_ID, connectionCheck.receiverId)
.set(RECEIVER_CONNECTION_CHECK_RESULTS.CONNECTION_CHECK_RESULT, connectionCheck.checkResult)
.set(RECEIVER_CONNECTION_CHECK_RESULTS.CONNECTION_CHECK_SUCCESSFUL, connectionCheck.checkSuccessful)
.set(RECEIVER_CONNECTION_CHECK_RESULTS.CONNECTION_CHECK_STARTED_AT, initiatedOn)
.set(RECEIVER_CONNECTION_CHECK_RESULTS.CONNECTION_CHECK_COMPLETED_AT, completedOn)
.execute()
}
/** Common companion object */
companion object {
/** Global var. Set to false prior to the lazy init, to prevent flyway migrations */
var isFlywayMigrationOK = true
/**
* Create a connection pool
*
* Dev Note: Why a connection pool with a "stateless" Azure function? The reason is that
* Azure functions are actually deployed in a web server. That is functions amortize startup
* costs by reusing an existing process for a function invocation. Hence, a connection pool
* is a win in latency after the first initialization.
*/
private val hikariDataSource: HikariDataSource by lazy {
DriverManager.registerDriver(Driver())
val password = System.getenv(passwordVariable)
val user = System.getenv(userVariable)
val databaseUrl = System.getenv(databaseVariable)
val config = HikariConfig()
config.jdbcUrl = databaseUrl
config.username = user
config.password = password
config.addDataSourceProperty(
"dataSourceClassName",
"org.postgresql.ds.PGSimpleDataSource"
)
config.addDataSourceProperty("cachePrepStmts", "true")
config.addDataSourceProperty("prepStmtCacheSize", "250")
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048")
config.addDataSourceProperty(
"connectionTimeout",
"60000"
) // Default is 30000 (30 seconds)
// See this info why these are a good value
// https://github.com/brettwooldridge/HikariCP/wiki/About-Pool-Sizing
config.minimumIdle = 2
config.maximumPoolSize = 25
// This strongly recommended to be set "be several seconds shorter than any database or
// infrastructure
// imposed connection time limit". Not sure what value is but have observed that
// connection are closed
// after about 10 minutes
config.maxLifetime = 180000
val dataSource = HikariDataSource(config)
val flyway = Flyway.configure().dataSource(dataSource).load()
if (isFlywayMigrationOK) {
flyway.migrate()
}
dataSource
}
val commonDataSource: DataSource
get() = hikariDataSource
fun createTaskRecord(
report: Report,
bodyFormat: String,
bodyUrl: String,
nextAction: Event,
): TaskRecord {
return TaskRecord(
report.id,
nextAction.eventAction.toTaskAction(),
nextAction.at,
report.schema.name,
report.destination?.fullName ?: "",
report.itemCount,
bodyFormat,
bodyUrl,
report.createdDateTime,
null,
null,
null,
null,
null,
null
)
}
fun createTask(
report: Report,
bodyFormat: String,
bodyUrl: String,
nextAction: Event,
): Task {
return Task(
report.id,
nextAction.eventAction.toTaskAction(),
nextAction.at,
report.schema.name,
report.destination?.fullName ?: "",
report.itemCount,
bodyFormat,
bodyUrl,
report.createdDateTime,
null,
null,
null,
null,
null,
null,
)
}
}
}
| 834
| null |
35
| 35
|
2d9551487ce5b352a9043cd677b67ab7711ea509
| 33,059
|
prime-reportstream
|
Creative Commons Zero v1.0 Universal
|
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/hardware/ZaPaiplain.kt
|
gitRaiku
| 696,241,983
| false
|
{"Kotlin": 148480, "Java": 50671}
|
package org.firstinspires.ftc.teamcode.hardware
import com.acmerobotics.dashboard.config.Config
import org.firstinspires.ftc.teamcode.hardware.CameraControls.AutoMinBlocksBlue
import org.firstinspires.ftc.teamcode.hardware.CameraControls.AutoMinBlocksRed
import org.firstinspires.ftc.teamcode.hardware.CameraControls.AutoRed
import org.firstinspires.ftc.teamcode.hardware.CameraControls.AutoResult
import org.firstinspires.ftc.teamcode.hardware.CameraControls.COL_INDEX
import org.firstinspires.ftc.teamcode.hardware.CameraControls.CUR_DONE_CORRECTION
import org.firstinspires.ftc.teamcode.hardware.CameraControls.CameraMidPos
import org.firstinspires.ftc.teamcode.hardware.CameraControls.DO_I_EVEN_PROCESS_FRAME
import org.firstinspires.ftc.teamcode.hardware.CameraControls.DRAW_BOXES
import org.firstinspires.ftc.teamcode.hardware.CameraControls.DRAW_MEDIAN
import org.firstinspires.ftc.teamcode.hardware.CameraControls.LUP
import org.firstinspires.ftc.teamcode.hardware.CameraControls.LUT
import org.firstinspires.ftc.teamcode.hardware.CameraControls.PSTEP
import org.firstinspires.ftc.teamcode.hardware.CameraControls.PaiplainColBloo
import org.firstinspires.ftc.teamcode.hardware.CameraControls.PaiplainMaxBloo
import org.firstinspires.ftc.teamcode.hardware.CameraControls.PaiplainMaxRed
import org.firstinspires.ftc.teamcode.hardware.CameraControls.PaiplainMinSat
import org.firstinspires.ftc.teamcode.hardware.CameraControls.PaiplainMinVal
import org.firstinspires.ftc.teamcode.hardware.CameraControls.PaiplainColRed
import org.firstinspires.ftc.teamcode.hardware.CameraControls.XOFF
import org.firstinspires.ftc.teamcode.hardware.CameraControls.YOFF
import org.firstinspires.ftc.teamcode.utils.RobotFuncs.log
import org.firstinspires.ftc.teamcode.utils.RobotFuncs.lom
import org.firstinspires.ftc.teamcode.utils.RobotFuncs.send_log
import org.firstinspires.ftc.teamcode.utils.Util.angDiff
import org.opencv.core.Mat
import org.opencv.core.Point
import org.opencv.core.Rect
import org.opencv.core.Scalar
import org.opencv.imgproc.Imgproc
import org.opencv.imgproc.Imgproc.COLOR_RGB2HSV
import org.openftc.easyopencv.OpenCvPipeline
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.max
@Config
object CameraControls {
@JvmField
var PSTEP: Int = 5
@JvmField
var LUP: Int = 100
@JvmField
var LUT: Int = 290
@JvmField
var XOFF: Int = 320
@JvmField
var YOFF: Int = 300
@JvmField
var COL_INDEX: Int = 0
@JvmField
var DRAW_BOXES: Boolean = true
@JvmField
var DRAW_MEDIAN: Boolean = true
@JvmField
var DO_I_EVEN_PROCESS_FRAME: Boolean = true
@JvmField
var CUR_DONE_CORRECTION: Int = 0
@JvmField
var CameraMidPos: Double = 400.0
@JvmField
var PaiplainMinSat = 20
@JvmField
var PaiplainMinVal = 20
@JvmField
var PaiplainMaxBloo = 0.2
@JvmField
var PaiplainColBloo = 2.4
@JvmField
var PaiplainColRed = 0.2
@JvmField
var PaiplainMaxRed = 0.2
@JvmField
var AutoRed = true
@JvmField
var AutoMinBlocksRed = 20
@JvmField
var AutoMinBlocksBlue = 45
@JvmField
var AutoResult = 1
}
class ZaPaiplain : OpenCvPipeline() {
private fun isRed(col: DoubleArray): Boolean {
val h = (col[0] / 255.0) * PI * 2
val s = col[1]
val v = col[2]
return abs(angDiff(h, PaiplainColRed)) < PaiplainMaxRed && s > PaiplainMinSat && v > PaiplainMinVal
}
private fun isBlue(col: DoubleArray): Boolean {
val h = (col[0] / 255.0) * PI * 2
val s = col[1]
val v = col[2]
return abs(angDiff(h, PaiplainColBloo)) < PaiplainMaxBloo && s > PaiplainMinSat && v > PaiplainMinVal
}
private fun checkCol(col: DoubleArray): Boolean {
return if (AutoRed) {
isRed(col)
} else {
isBlue(col)
}
}
private val frame = Mat()
private val ff = Mat()
override fun processFrame(input: Mat): Mat {
if (input.empty()) {
return input
}
if (DO_I_EVEN_PROCESS_FRAME) {
input.copyTo(frame)
Imgproc.cvtColor(frame, frame, COLOR_RGB2HSV)
if (DRAW_BOXES || DRAW_MEDIAN) {
frame.copyTo(ff)
}
var medXS = 0
var redc = 0
var midBlocks = 0
var rightBlocks = 0
for (cx in -LUT + XOFF..LUT + XOFF step PSTEP) {
for (cy in -LUP + YOFF..LUP + YOFF step PSTEP) {
val vl = frame[cy, cx] ?: continue
//log ("KMSKMS", "${vl[0]} ${vl[1]} ${vl[2]}")
if (checkCol(vl)) {
if (cx < CameraMidPos) {
++midBlocks
} else {
++rightBlocks
}
medXS += cx
++redc
if (DRAW_BOXES) {
Imgproc.rectangle(ff, Rect(cx, cy, PSTEP, PSTEP), Scalar(255.0, 255.0, 255.0), -1)
}
} else {
if (DRAW_BOXES) {
Imgproc.rectangle(ff, Rect(cx, cy, PSTEP, PSTEP), Scalar(
max(vl[COL_INDEX] - 10.0, 0.0),
max(vl[COL_INDEX] - 10.0, 0.0),
max(vl[COL_INDEX] - 10.0, 0.0)), -1)
}
}
}
}
lom.telemetry.addData("MidBoxes", midBlocks)
lom.telemetry.addData("RightBoxes", rightBlocks)
log("MidBoxes", midBlocks)
log("RightBoxes", rightBlocks)
send_log()
AutoResult = if (AutoRed) {
if (midBlocks > AutoMinBlocksRed) {
1
} else if (rightBlocks > AutoMinBlocksRed) {
0
} else {
2
}
} else {
if (midBlocks > AutoMinBlocksBlue) {
1
} else if (rightBlocks > AutoMinBlocksBlue) {
2
} else {
0
}
}
lom.telemetry.addData("GOT RESULT", AutoResult)
lom.telemetry.update()
val w = frame.width()
Imgproc.line(ff, Point(CameraMidPos, 80.0), Point(CameraMidPos, 380.0), Scalar(255.0, 0.0, 0.0, 255.0), 4)
if (DRAW_MEDIAN && !ff.empty()) {
val c1 = Point(w / 2.0 + CUR_DONE_CORRECTION * 20, 10.0)
val c2 = Point(w / 2.0, 10.0)
Imgproc.line(ff, c1, c2, Scalar(100.0, if (AutoResult == 0) 0.0 else 100.0, if (AutoResult == 1) 0.0 else 100.0, 255.0), 9)
}
return if ((DRAW_BOXES || DRAW_MEDIAN) && !ff.empty()) {
ff
} else {
frame
}
} else {
return input
}
}
}
| 0
|
Kotlin
|
0
| 0
|
b7f92f36dbbbac1e1b6bcdc05268cababafd31fa
| 7,089
|
CenterStage
|
BSD 3-Clause Clear License
|
shared/src/commonMain/kotlin/com/architect/kmpessentials/share/KmpShare.kt
|
TheArchitect123
| 801,452,364
| false
|
{"Kotlin": 15856, "Ruby": 2156}
|
package com.architect.kmpessentials.share
class KmpShare {
}
| 0
|
Kotlin
|
0
| 1
|
5db28aae309308396ebde16e29bdced3352dc706
| 61
|
KmpEssentials
|
MIT License
|
app/src/androidTest/java/com/task/di/TestDataModule.kt
|
quachhongkhoait
| 319,358,965
| false
| null |
package com.task.di
import com.task.TestDataRepository
import com.task.data.DataRepositorySource
import dagger.Binds
import dagger.Module
import javax.inject.Singleton
@Module
abstract class TestDataModule {
@Binds
@Singleton
abstract fun provideDataRepository(dataRepository: TestDataRepository): DataRepositorySource
}
| 0
|
Kotlin
|
0
| 0
|
58201bb80b1147e20718d75afd705ae930727a47
| 334
|
TemplateMVVM
|
Apache License 2.0
|
data/src/main/java/com.devdd.recipe.data/utils/DataStorePreferencesExtensions.kt
|
deepakdawade
| 354,909,155
| false
| null |
package com.devdd.recipe.data.utils
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.preferencesDataStore
import com.devdd.recipe.base.constants.DATA_STORE_NAME
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import java.io.IOException
private val Context.mDataStore: DataStore<Preferences> by preferencesDataStore(name = DATA_STORE_NAME)
val Context.dataStore: DataStore<Preferences>
get() = mDataStore
/***
* handy function to save key-value pairs in Preference. Sets or updates the value in Preference
* @param key used to identify the preference
* @param value the value to be saved in the preference
*/
suspend fun <T> DataStore<Preferences>.setValue(
key: Preferences.Key<T>,
value: T
) {
this.edit { preferences ->
// save the value in prefs
preferences[key] = value
}
}
/***
* handy function to return Preference value based on the Preference key
* @param key used to identify the preference
* @param defaultValue value in case the Preference does not exists
* @throws Exception if there is some error in getting the value
* @return [Flow] of [T?]
*/
fun <T> DataStore<Preferences>.getValueAsFlow(
key: Preferences.Key<T>,
defaultValue: T
): Flow<T> {
return this.data.catch { exception ->
// dataStore.data throws an IOException when an error is encountered when reading data
if (exception is IOException) {
// we try again to store the value in the map operator
emit(emptyPreferences())
} else {
throw exception
}
}.map { preferences ->
// return the default value if it doesn't exist in the storage
preferences[key] ?: defaultValue
}
}
| 0
|
Kotlin
|
0
| 6
|
8272959b3b692bd4ee797e15e76d57282efa7ad4
| 1,986
|
Recipe-Finder
|
Apache License 2.0
|
ehr-common-model/src/main/kotlin/org/openehr/proc/taskplanning/ContextValue.kt
|
better-care
| 343,543,899
| false
| null |
/* Copyright 2021 Better Ltd (www.better.care)
*
* 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.openehr.proc.taskplanning
import care.better.openehr.rm.RmObject
import care.better.platform.annotation.Open
import care.better.platform.annotation.Required
import care.better.platform.proc.taskplanning.visitor.VisitableByModelVisitor
import javax.xml.bind.annotation.*
/**
* @author <NAME>
* @since 3.1.0
*/
@SuppressWarnings("ClassReferencesSubclass")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CONTEXT_VALUE", propOrder = ["name", "type"])
@XmlSeeAlso(value = [ContextVariable::class, ContextExpression::class, ContextConstant::class])
@Open
abstract class ContextValue<T>() : RmObject(), VisitableByModelVisitor {
companion object {
private const val serialVersionUID: Long = 0L
}
@XmlElement(required = true)
@Required
var name: String? = null
@XmlElement(required = true)
@Required
private var type: ExprTypeDef<T>? = null
protected constructor(type: ExprTypeDef<T>?) : this() {
this.type = type
}
protected constructor(name: String?, type: ExprTypeDef<T>?) : this(type) {
this.name = name
}
fun getType(): ExprTypeDef<T>? = type
fun setType(type: ExprTypeDef<T>?) {
this.type = type
}
override fun toString(): String =
"ContextValue{" +
"name='$name'" +
", type=$type" +
"} ${super.toString()}"
}
| 0
| null |
1
| 2
|
368cae4a0464dcd90cbae48a1c6b3d4615450d6f
| 1,999
|
ehr-common
|
Apache License 2.0
|
app/src/main/java/cn/lyric/getter/hook/app/Api.kt
|
xiaowine
| 650,612,086
| false
| null |
package cn.lyric.getter.hook.app
import android.content.Context
import cn.lyric.getter.BuildConfig
import cn.lyric.getter.hook.BaseHook
import cn.lyric.getter.tool.EventTools.cleanLyric
import cn.lyric.getter.tool.EventTools.sendLyric
import cn.lyric.getter.tool.HookTools.isApi
import cn.lyric.getter.tool.LogTools.log
import cn.lyric.getter.tool.Tools.isNot
import cn.lyric.getter.tool.Tools.isNotNull
import com.github.kyuubiran.ezxhelper.HookFactory.`-Static`.createHook
import com.github.kyuubiran.ezxhelper.ObjectHelper.Companion.objectHelper
import com.github.kyuubiran.ezxhelper.finders.ConstructorFinder.`-Static`.constructorFinder
import com.github.kyuubiran.ezxhelper.finders.MethodFinder.`-Static`.methodFinder
object Api : BaseHook() {
override val name: String get() = this.javaClass.simpleName
override fun init() {
hook()
}
fun hook(classLoader: ClassLoader? = null) {
isApi(classLoader) { clazz ->
clazz.constructorFinder().first().createHook {
before { hookParam ->
hookParam.thisObject.objectHelper {
val objectOrNullAs = getObjectOrNullAs<Int>("API_VERSION")
if (objectOrNullAs.isNotNull() || objectOrNullAs!! == BuildConfig.API_VERSION) {
clazz.methodFinder().first { name == "hasEnable" }.createHook { returnConstant(true) }
clazz.methodFinder().filterByParamCount(7).first { name == "sendLyric" }.createHook {
after { hookParam ->
sendLyric(hookParam.args[0] as Context, hookParam.args[1] as String, hookParam.args[2] as Boolean, hookParam.args[3] as String, hookParam.args[4] as Boolean, hookParam.args[5] as String, hookParam.args[6] as String)
}
}
clazz.methodFinder().first { name == "stopLyric" }.createHook {
after { hookParam ->
cleanLyric(hookParam.args[0] as Context)
}
}
} else {
"The APIs do not match".log()
}
}
}
}
}.isNot {
"Not found Api class".log()
}
}
}
| 1
| null |
2
| 89
|
220c886911e7c158cc12abc6ceabfddde40824c8
| 2,423
|
Lyric-Getter
|
Apache License 2.0
|
glib-core/src/main/java/com/glib/core/ui/view/GRadioButton.kt
|
hgani
| 223,511,724
| false
|
{"Gradle": 5, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Git Attributes": 1, "Markdown": 1, "Java Properties": 1, "Proguard": 3, "XML": 22, "Kotlin": 222, "Java": 19}
|
package com.glib.core.ui.view
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.appcompat.widget.AppCompatRadioButton
class GRadioButton : AppCompatRadioButton, IView {
private val helper = ViewHelper(this)
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
override fun width(width: Int?): GRadioButton {
helper.width(width)
return self()
}
override fun height(height: Int?): GRadioButton {
helper.height(height)
return self()
}
override fun padding(l: Int?, t: Int?, r: Int?, b: Int?): GRadioButton {
helper.padding(l, t, r, b)
return self()
}
override fun margin(l: Int?, t: Int?, r: Int?, b: Int?): GRadioButton {
helper.margin(l, t, r, b)
return self()
}
override fun bgColor(color: Int): GRadioButton {
helper.bgColor(color)
return self()
}
fun text(text: String): GRadioButton {
this.text = text
return self()
}
fun tag(tag: Any): GRadioButton {
this.tag = tag
return self()
}
fun generatedId(): GRadioButton {
this.id = View.generateViewId()
return self()
}
private fun self(): GRadioButton {
return this
}
}
| 0
|
Kotlin
|
0
| 0
|
9a7c56236d664f2b518310d12e5b0839382c2920
| 1,376
|
glib-android
|
Apache License 2.0
|
src/main/kotlin/org/wagham/utils/DateUtils.kt
|
kaironbot
| 566,988,243
| false
|
{"Kotlin": 584271, "Dockerfile": 237}
|
package org.wagham.utils
import org.wagham.db.utils.daysInBetween
import java.time.LocalDateTime
import java.time.ZonedDateTime
import java.util.*
import kotlin.time.Duration.Companion.milliseconds
fun getStartingInstantOnNextDay(hour: Int, minute: Int, second: Int, transformer: (LocalDateTime) -> LocalDateTime = { it }): Date {
val timeZone = TimeZone.getTimeZone("GMT+2")
val calendar = Calendar.getInstance(timeZone)
val localDate = LocalDateTime.of(
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH)+1,
calendar.get(Calendar.DAY_OF_MONTH),
hour + timeZone.dstSavings,
minute,
second
).plusDays(1).let(transformer)
return Date.from(ZonedDateTime.of(localDate, timeZone.toZoneId()).toInstant())
}
fun daysToToday(pastDate: Date) = daysInBetween(pastDate, Calendar.getInstance().time).toInt()
fun maxOrNull(first: Date?, second: Date?): Date? =
when {
first == null && second == null -> null
first == null -> second
second == null -> first
first > second -> first
else -> second
}
/**
* @return the offset, in minutes, between the current timezone and the UTC timezone
*/
fun getTimezoneOffset(): Long {
val calendar = Calendar.getInstance()
val timeZone = calendar.timeZone
val isDaylightTime = timeZone.inDaylightTime(Date())
return timeZone.rawOffset.milliseconds.inWholeMinutes + (60.takeIf { isDaylightTime } ?: 0)
}
| 3
|
Kotlin
|
0
| 0
|
62769fdbe0c2f4976edfbc1dab2d832db61d751f
| 1,474
|
kairon-bot
|
MIT License
|
module_base/src/main/java/com/swensun/base/BaseActivity.kt
|
zxzxzxygithub
| 196,017,442
| true
|
{"Kotlin": 851364, "Java": 211187}
|
package com.swensun.base
import android.os.Bundle
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_base.*
import kotlinx.android.synthetic.main.content_base.*
abstract class BaseActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_base)
setSupportActionBar(toolbar)
layoutInflater.inflate(getContentSubView(), container)
}
@LayoutRes
abstract fun getContentSubView(): Int
}
| 0
|
Kotlin
|
0
| 0
|
a235b1464fdeacc0f5e0484e76b622ab550ce8fd
| 609
|
Potato
|
Apache License 2.0
|
sykepenger-model/src/test/kotlin/no/nav/helse/spleis/e2e/RevurderInntektFlereArbeidsgivereTest.kt
|
navikt
| 193,907,367
| false
| null |
package no.nav.helse.spleis.e2e
import no.nav.helse.Toggle
import no.nav.helse.hendelser.*
import no.nav.helse.hendelser.Søknad.Søknadsperiode.Sykdom
import no.nav.helse.inspectors.Kilde
import no.nav.helse.somOrganisasjonsnummer
import no.nav.helse.testhelpers.januar
import no.nav.helse.økonomi.Prosentdel.Companion.prosent
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import java.time.LocalDate
import java.util.*
internal class RevurderInntektFlereArbeidsgivereTest: AbstractEndToEndTest() {
private companion object {
val AG1 = "123456789".somOrganisasjonsnummer()
val AG2 = "987654321".somOrganisasjonsnummer()
}
@Test
fun `kun den arbeidsgiveren som har fått overstyrt inntekt som faktisk lagrer inntekten`() {
nyttVedtak(1.januar(2017), 31.januar(2017), 100.prosent, orgnummer= AG2) // gammelt vedtak
håndterSykmelding(Sykmeldingsperiode(1.januar, 31.januar, 100.prosent), orgnummer = AG1)
håndterSøknad(Sykdom(1.januar, 31.januar, 100.prosent), orgnummer = AG1)
håndterInntektsmelding(listOf(1.januar til 16.januar), orgnummer = AG1)
håndterYtelser(orgnummer = AG1)
val skjæringstidspunkt = inspektør(AG1).skjæringstidspunkt(1.vedtaksperiode)
håndterVilkårsgrunnlag(
1.vedtaksperiode, orgnummer = AG1, inntektsvurdering = Inntektsvurdering(
inntekter = listOf(
sammenligningsgrunnlag(AG1, skjæringstidspunkt, INNTEKT.repeat(12))
)
),
inntektsvurderingForSykepengegrunnlag = InntektForSykepengegrunnlag(
inntekter = listOf(
grunnlag(AG1, skjæringstidspunkt, INNTEKT.repeat(3))
), arbeidsforhold = emptyList()
),
arbeidsforhold = listOf(
Arbeidsforhold(AG1.toString(), LocalDate.EPOCH, null),
Arbeidsforhold(AG2.toString(), LocalDate.EPOCH, null)
)
)
håndterYtelser(orgnummer = AG1)
håndterSimulering(orgnummer = AG1)
håndterUtbetalingsgodkjenning(orgnummer = AG1)
håndterUtbetalt(orgnummer = AG1)
håndterOverstyrInntekt(orgnummer = AG1, skjæringstidspunkt = 1.januar)
assertEquals(1, inspektør(AG1).inntektInspektør.antallOpplysinger(Kilde.SAKSBEHANDLER))
assertEquals(0, inspektør(AG2).inntektInspektør.antallOpplysinger(Kilde.SAKSBEHANDLER))
}
@Test
fun `alle perioder for alle arbeidsgivere med aktuelt skjæringstidspunkt skal ha hendelseIden`() {
Toggle.RevurdereInntektMedFlereArbeidsgivere.enable {
nyeVedtak(1.januar, 31.januar, AG1, AG2)
val hendelseId = UUID.randomUUID()
håndterOverstyrInntekt(orgnummer = AG1, skjæringstidspunkt = 1.januar, meldingsreferanseId = hendelseId)
assertHarHendelseIder(1.vedtaksperiode, hendelseId, orgnummer = AG1)
assertHarIkkeHendelseIder(1.vedtaksperiode, hendelseId, orgnummer = AG2)
}
}
}
| 0
| null |
3
| 4
|
22fe9640780c8c8c13165c2efb0dfc4d96ba9965
| 3,042
|
helse-spleis
|
MIT License
|
src/main/kotlin/at/cath/simpletabs/gui/MouseActionCallback.kt
|
otcathatsya
| 495,090,255
| false
| null |
package at.cath.simpletabs.gui
interface MouseActionCallback {
fun onLeftClick() {}
fun onRightClick() {}
fun onMouseMiddleClick() {}
}
enum class MouseAction {
LEFT_CLICK,
RIGHT_CLICK,
MIDDLE_MOUSE;
companion object {
fun create(numeric: Int): MouseAction? {
return when (numeric) {
0 -> LEFT_CLICK
1 -> RIGHT_CLICK
2 -> MIDDLE_MOUSE
else -> null
}
}
}
}
| 0
|
Kotlin
|
1
| 6
|
0f7a981f77b2e345ea9145a69df6b4c7095f822e
| 494
|
simple-tabs
|
MIT License
|
src/main/kotlin/graph/variation/WrongEdgeWeight.kt
|
yx-z
| 106,589,674
| false
| null |
package graph.variation
import graph.core.Vertex
import graph.core.WeightedGraph
import graph.core.dijkstra
import util.min
// suppose you have computed the all pairs shortest path (apsp) table
// but later you find out that your edge weight for u -> v is wrong during
// the computation... that is, w(u -> v) is used but w'(u -> v) is true weight
// 1. suppose w'(u -> v) < w(u -> v), restore the table in O(V^2) time
fun <V> HashMap<Vertex<V>, HashMap<Vertex<V>, Int>>.restore(
u: Vertex<V>,
v: Vertex<V>,
newWeight: Int) {
// dist[x, y] = min{ dist[x, y], dist[x, u] + w'(u -> v) + dist[v, y] }
val dist = this
forEach { (x, map) ->
map.forEach { (y, _) ->
map[y] = min(map[y]!!, map[u]!! + newWeight + dist[v]!![y]!!)
}
}
}
// 2. use O(1) time to check whether your computed table is correct or not
// (yes it can still be correct), still assuming w'(u -> v) < w(u -> v)
fun <V> HashMap<Vertex<V>, HashMap<Vertex<V>, Int>>.isCorrect(
u: Vertex<V>,
v: Vertex<V>,
newWeight: Int) = this[u]!![v]!! <= newWeight
// we actually just need to check if there exists a shortest path from u to v
// that doesn't use the edge u -> v!
// 3. ues O(VE) time to check whether your computed table is correct or not
// , but without restriction that w'(u -> v) < w(u -> v)
fun <V> HashMap<Vertex<V>, HashMap<Vertex<V>, Int>>.isCorrect(
u: Vertex<V>,
v: Vertex<V>,
g: WeightedGraph<V, Int>,
newWeight: Int) = g.dijkstra(u).second[v] !== u && this[u]!![v]!! <= newWeight
// the idea is similar: check if the shortest path from u to v
// is actually using the edge u -> v, if it is then it must be wrong
// if it is NOT, it still can be wrong if the newWeight is smaller! we should use the new weight
| 0
|
Kotlin
|
0
| 1
|
15494d3dba5e5aa825ffa760107d60c297fb5206
| 1,727
|
AlgoKt
|
MIT License
|
src/app/react-player.kt
|
maochaokuo
| 228,109,383
| false
| null |
@file:JsModule("react-player")
package app
import react.*
@JsName("default")
external val ReactPlayer: RClass<ReactPlayerProps>
external interface ReactPlayerProps : RProps {
var url: String
}
| 12
|
Kotlin
|
0
| 0
|
c94fc2ea6027992bb9cae6848afe6e5e9afd3bcf
| 201
|
kotlin-react2
|
MIT License
|
src/main/kotlin/com/sunrayapps/jira/plugin/dependencies/downloader/Jta.kt
|
SunrayApps
| 122,542,980
| false
| null |
package com.sunrayapps.jira.plugin.dependencies.downloader
import java.io.File
import java.net.URI
import org.apache.commons.io.FileUtils.*
import org.rauschig.jarchivelib.ArchiveFormat
import org.rauschig.jarchivelib.ArchiverFactory
import java.nio.file.Path
class Jta(
private val installDirectory: Path,
private val maven: Maven
) {
private val jarName = "jta-1.0.1.jar"
private val archiveFileName = "jta-1.0.1.jar.zip"
private val url = "http://www.java2s.com/Code/JarDownload/jta/$archiveFileName"
fun download(): Jta {
copyURLToFile(
URI.create(url).toURL(),
File(installDirectory
.resolve(archiveFileName)
.toUri())
)
return this
}
fun unzip(): Jta {
val archive = File(archiveFileName)
val destination = installDirectory.toFile()
val archiver = ArchiverFactory.createArchiver(ArchiveFormat.ZIP)
archiver.extract(archive, destination)
return this
}
fun install(): Jta {
Shell().exec(
maven.mavenExecutable,
"install:install-file",
"-Dfile=${installDirectory.resolve(jarName).toAbsolutePath()}",
"-DgroupId=jta",
"-DartifactId=jta",
"-Dversion=1.0.1",
"-Dpackaging=jar"
)
return this
}
fun clean(): Jta {
File(archiveFileName).delete()
File(jarName).delete()
return this
}
}
| 0
|
Kotlin
|
0
| 0
|
df03aff3b610c616fd840d09eca638b8ed74887c
| 1,492
|
jira-plugin-dependencies-downloader
|
Apache License 2.0
|
fire-core/src/main/java/com/vdreamers/fire/core/IFireAbility.kt
|
CodePoem
| 362,539,863
| false
| null |
/*
* Copyright 2021 CodePoem
*
* 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.vdreamers.fire.core
/**
* Log Ability interface exposed Api
* <p>
* date 2021/05/26 16:14:11
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
interface IFireAbility {
fun v(message: String?)
fun v(custom: Map<String, Any>?)
fun v(message: String?, custom: Map<String, Any>?)
fun v(t: Throwable?, message: String?)
fun v(t: Throwable?, custom: Map<String, Any>?)
fun v(t: Throwable?, message: String?, custom: Map<String, Any>?)
fun d(message: String?)
fun d(custom: Map<String, Any>?)
fun d(message: String?, custom: Map<String, Any>?)
fun d(t: Throwable?, message: String?)
fun d(t: Throwable?, custom: Map<String, Any>?)
fun d(t: Throwable?, message: String?, custom: Map<String, Any>?)
fun i(message: String?)
fun i(custom: Map<String, Any>?)
fun i(message: String?, custom: Map<String, Any>?)
fun i(t: Throwable?, message: String?)
fun i(t: Throwable?, custom: Map<String, Any>?)
fun i(t: Throwable?, message: String?, custom: Map<String, Any>?)
fun w(message: String?)
fun w(custom: Map<String, Any>?)
fun w(message: String?, custom: Map<String, Any>?)
fun w(t: Throwable?, message: String?)
fun w(t: Throwable?, custom: Map<String, Any>?)
fun w(t: Throwable?, message: String?, custom: Map<String, Any>?)
fun e(message: String?)
fun e(custom: Map<String, Any>?)
fun e(message: String?, custom: Map<String, Any>?)
fun e(t: Throwable?, message: String?)
fun e(t: Throwable?, custom: Map<String, Any>?)
fun e(t: Throwable?, message: String?, custom: Map<String, Any>?)
fun wtf(message: String?)
fun wtf(custom: Map<String, Any>?)
fun wtf(message: String?, custom: Map<String, Any>?)
fun wtf(t: Throwable?, message: String?)
fun wtf(t: Throwable?, custom: Map<String, Any>?)
fun wtf(t: Throwable?, message: String?, custom: Map<String, Any>?)
fun log(priority: Int, message: String?, custom: Map<String, Any>?)
fun log(priority: Int, custom: Map<String, Any>?)
fun log(priority: Int, t: Throwable?, message: String?, custom: Map<String, Any>?)
fun log(priority: Int, t: Throwable?, custom: Map<String, Any>?)
}
| 0
|
Kotlin
|
0
| 2
|
8997fd997363ca16622cf4c06b0c3ad0978c2aca
| 2,826
|
Fire
|
Apache License 2.0
|
app/src/main/java/com/example/stsotre/ui/basket/NextShoppingCart.kt
|
shirinvn
| 711,298,897
| false
|
{"Kotlin": 193308, "Java": 7887}
|
package com.example.stsotre.ui.basket
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.stsotre.data.model.basket.CartItem
import com.example.stsotre.data.model.basket.CartStatus
import com.example.stsotre.viewmodel.BasketViewModel
import kotlinx.coroutines.flow.collectLatest
@Composable
fun NextShoppingCart(
viewModel: BasketViewModel = hiltViewModel()
) {
val nextCartItems = remember {
mutableStateOf(emptyList<CartItem>())
}
LaunchedEffect(true) {
viewModel.nextCartItems.collectLatest { list ->
nextCartItems.value = list
}
}
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
.padding(bottom = 60.dp),
) {
if (nextCartItems.value.isEmpty()) {
item { EmptyNextShoppingList() }
} else {
items(nextCartItems.value) { item ->
CartItemCard(item , CartStatus.NEXT_CART)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
4d9d291f9432a3ee8d397914a678eee15ff3727c
| 1,572
|
STStore
|
MIT License
|
platform/lang-impl/src/com/intellij/util/indexing/diagnostic/IndexDiagnosticDumper.kt
|
hieuprogrammer
| 284,920,751
| false
| null |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.indexing.diagnostic
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.util.indexing.diagnostic.dto.JsonIndexDiagnostic
import com.intellij.util.io.createDirectories
import com.intellij.util.io.delete
import java.nio.file.Files
import java.nio.file.Paths
import java.time.LocalDateTime
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeParseException
import kotlin.streams.asSequence
object IndexDiagnosticDumper {
private val LOG = Logger.getInstance(IndexDiagnosticDumper::class.java)
private val jacksonMapper by lazy {
jacksonObjectMapper().registerKotlinModule().writerWithDefaultPrettyPrinter()
}
private val diagnosticDateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss")
@Synchronized
fun dumpProjectIndexingHistoryToLogSubdirectory(projectIndexingHistory: ProjectIndexingHistory) {
val logPath = PathManager.getLogPath()
try {
val indexDiagnosticDirectory = Paths.get(logPath).resolve("indexing-time-diagnostic")
indexDiagnosticDirectory.createDirectories()
val fileNamePrefix = "diagnostic-"
val timestamp = LocalDateTime.now().format(diagnosticDateTimeFormatter)
val diagnosticJson = indexDiagnosticDirectory.resolve("$fileNamePrefix$timestamp.json")
val jsonIndexDiagnostic = JsonIndexDiagnostic.generateForHistory(projectIndexingHistory)
jacksonMapper.writeValue(diagnosticJson.toFile(), jsonIndexDiagnostic)
val limitOfHistories = 20
val survivedHistories = Files.list(indexDiagnosticDirectory).use { files ->
files.asSequence()
.filter { it.fileName.toString().startsWith(fileNamePrefix) && it.fileName.toString().endsWith(".json") }
.sortedByDescending { file ->
val timeStamp = file.fileName.toString().substringAfter(fileNamePrefix).substringBefore(".json")
try {
LocalDateTime.parse(timeStamp, diagnosticDateTimeFormatter)
}
catch (e: DateTimeParseException) {
LocalDateTime.ofEpochSecond(0, 0, ZoneOffset.UTC)
}
}
.take(limitOfHistories)
.toSet()
}
Files
.list(indexDiagnosticDirectory)
.use { files ->
files
.asSequence()
.filterNot { it in survivedHistories }
.forEach { it.delete() }
}
}
catch (e: Exception) {
LOG.warn("Failed to dump index diagnostic", e)
}
}
}
| 1
| null |
1
| 2
|
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
| 2,854
|
intellij-community
|
Apache License 2.0
|
app/src/main/java/me/grey/picquery/data/model/Embedding.kt
|
greyovo
| 676,960,803
| false
| null |
package me.grey.picquery.data.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.io.Serializable
@Entity
data class Embedding(
@PrimaryKey @ColumnInfo(name = "photo_id")
val photoId: Long,
@ColumnInfo(name = "album_id")
val albumId: Long,
@ColumnInfo(name = "data", typeAffinity = ColumnInfo.BLOB)
val data: ByteArray // Actually a `FloatArray`. Need to be converted before using.
) : Serializable {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Embedding
if (photoId != other.photoId) return false
if (albumId != other.albumId) return false
return true
}
override fun hashCode(): Int {
var result = photoId.hashCode()
result = 31 * result + albumId.hashCode()
return result
}
}
| 7
| null |
27
| 92
|
eda7d169cde517fed8f4ef0b70bdc4c1e32013ab
| 945
|
PicQuery
|
MIT License
|
projects/android/koin-android/src/main/java/org/koin/android/scope/ScopeService.kt
|
InsertKoinIO
| 93,515,203
| false
|
{"Kotlin": 825588, "Java": 4138, "Shell": 259}
|
/*
* Copyright 2017-2021 the original author or 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.koin.android.scope
import android.app.Service
import org.koin.core.scope.Scope
/**
* ScopeService
*
* Service component, allow to create & destroy tied Koin scope
*
* @author <NAME>
*/
abstract class ScopeService(
private val initialiseScope: Boolean = true,
) : Service(), AndroidScopeComponent {
override val scope: Scope by serviceScope()
override fun onCreate() {
super.onCreate()
if (initialiseScope) {
scope.logger.debug("Open Service Scope: $scope")
}
}
override fun onDestroy() {
super.onDestroy()
scope.logger.debug("Close service scope: $scope")
if (!scope.closed)
scope.close()
}
}
| 83
|
Kotlin
|
711
| 8,934
|
f870a02fd32a2cf1ff8b69406ebf555c26ffe39f
| 1,339
|
koin
|
Apache License 2.0
|
twitch/src/main/kotlin/net/serverpeon/twitcharchiver/twitch/LegacyTwitchApi.kt
|
Kiskae
| 22,880,077
| false
| null |
package net.serverpeon.twitcharchiver.twitch
import hu.akarnokd.rxjava.interop.RxJavaInterop
import net.serverpeon.twitcharchiver.twitch.api.KrakenApi
import net.serverpeon.twitcharchiver.twitch.errors.TwitchApiException
import net.serverpeon.twitcharchiver.twitch.playlist.Playlist
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.slf4j.LoggerFactory
import rx.Observable
import rx.Single
import java.util.*
/**
* Unified access to all the API calls required to download broadcasts from twitch.
*/
class LegacyTwitchApi(token: OAuthToken) {
companion object {
private val log = LoggerFactory.getLogger(LegacyTwitchApi::class.java)
}
private val client: OkHttpClient = OkHttpClient.Builder()
.addInterceptor(OAuthInterceptor.dynamic(token, TwitchApi.TWITCH_CLIENT_ID)).apply {
System.getProperty("http.debug")?.let { level ->
val interceptLogger = LoggerFactory.getLogger(OkHttpClient::class.java)
addInterceptor(
HttpLoggingInterceptor(HttpLoggingInterceptor.Logger {
interceptLogger.trace(it)
}).setLevel(HttpLoggingInterceptor.Level.valueOf(level.toUpperCase()))
)
}
}.build()
private val internalClient = TwitchApi(TwitchApi.createGson(), client)
/**
* Retrieves the user associated with the provided [OAuthToken]
*
* If the OAuth token is invalid then the optional will be empty
*/
fun retrieveUser(): Single<Optional<String>> {
log.trace("retrieveUser()")
return RxJavaInterop.toV1Single(internalClient.retrieveUser().map {
Optional.of(it)
}.toSingle(Optional.empty()))
}
/**
* Retrieves a list of videos for the given channel, if no limit is given then it will
* provide all the videos available on the channel.
*/
fun videoList(channelName: String, limit: Int = -1): Observable<KrakenApi.VideoListResponse.Video> {
return RxJavaInterop.toV1Observable(internalClient.videoList(channelName, limit))
}
/**
* Retrieves the video playlist for the given broadcast.
*
* This method makes heavy use of internal APIs and reverse-engineering.
* If something breaks, check here first.
*/
@Throws(TwitchApiException::class)
fun loadPlaylist(broadcastId: String): Single<Playlist> {
return RxJavaInterop.toV1Single(internalClient.loadPlaylist(broadcastId))
}
}
| 3
|
Kotlin
|
0
| 6
|
fbdba1f4c6787cf74625eb72cb8af8c6f48552cc
| 2,508
|
Twitch-Archiver
|
MIT License
|
app/src/main/java/eu/kanade/tachiyomi/data/backup/models/BackupCategory.kt
|
komikku-app
| 743,200,516
| false
|
{"Kotlin": 5965492}
|
package eu.kanade.tachiyomi.data.backup.models
import kotlinx.serialization.Serializable
import kotlinx.serialization.protobuf.ProtoNumber
import tachiyomi.domain.category.model.Category
@Serializable
class BackupCategory(
@ProtoNumber(1) var name: String,
@ProtoNumber(2) var order: Long = 0,
// @ProtoNumber(3) val updateInterval: Int = 0, 1.x value not used in 0.x
@ProtoNumber(100) var flags: Long = 0,
// KMK -->
@ProtoNumber(900) var hidden: Boolean = false,
// KMK <--
// SY specific values
/*@ProtoNumber(600) var mangaOrder: List<Long> = emptyList(),*/
) {
fun toCategory(id: Long) = Category(
id = id,
name = this@BackupCategory.name,
flags = this@BackupCategory.flags,
order = this@BackupCategory.order,
// KMK -->
hidden = this@BackupCategory.hidden,
// KMK <--
/*mangaOrder = this@BackupCategory.mangaOrder*/
)
}
val backupCategoryMapper = { category: Category ->
BackupCategory(
name = category.name,
order = category.order,
flags = category.flags,
// KMK -->
hidden = category.hidden,
// KMK <--
)
}
| 72
|
Kotlin
|
12
| 342
|
387e019e3a56f8ffbc94ec4fef82db1eccc98ddf
| 1,182
|
komikku
|
Apache License 2.0
|
error/src/main/kotlin/studio/lunabee/onesafe/error/OSImportExportError.kt
|
LunabeeStudio
| 624,544,471
| false
| null |
/*
* Copyright (c) 2023 Lunabee Studio
*
* 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.
*
* Created by Lunabee Studio / Date - 4/7/2023 - for the oneSafe6 SDK.
* Last modified 4/7/23, 12:24 AM
*/
package studio.lunabee.onesafe.error
data class OSImportExportError(
override val code: Code,
override val message: String = code.message,
override val cause: Throwable? = null,
) : OSError(message, cause, code) {
enum class Code(val message: String) : ErrorCode {
METADATA_FILE_NOT_FOUND("Metadata file was not found"),
ARCHIVE_MALFORMED("Unexpected archive content"),
DATA_FILE_NOT_FOUND("Data file was not found"),
ID_NOT_FOUND("Unexpected error while retrieving new id"),
EXPORT_METADATA_FAILURE("Fail to export metadata"),
EXPORT_DATA_FAILURE("Fail to export data"),
EXPORT_ICON_FAILURE("Fail to export icons"),
WRONG_CREDENTIALS("Wrong credentials"),
UNEXPECTED_ERROR("Unexpected error occurred"),
METADATA_NOT_IN_CACHE("Metadata not in cache"),
SALT_INVALID("Salt is empty or invalid"),
}
}
| 1
| null |
1
| 2
|
352c38bfbe7c9a576b8069a0d7ca217b22409c7a
| 1,617
|
oneSafe6_SDK_Android
|
Apache License 2.0
|
app/src/main/java/com/szhua/pagedemo/CustomPageDataSource.kt
|
szhua
| 325,485,049
| false
|
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 77, "XML": 66, "JSON": 3, "Java": 14}
|
package com.szhua.pagedemo
import java.lang.reflect.Constructor
private const val SHOE_START_INDEX = 0;
class CustomPageDataSource{
}
| 1
| null |
1
| 1
|
c53f4d8c5dd82614e4ad366a556ac46bed7c082b
| 139
|
AndroidPractice
|
Apache License 2.0
|
types/src/commonMain/kotlin/app/meetacy/sdk/types/exception/ConnectionException.kt
|
meetacy
| 604,657,616
| false
| null |
package app.meetacy.sdk.types.exception
public class ConnectionException(cause: Throwable) : MeetacyException(
message = "Error while connecting to server",
cause = cause
)
| 3
|
Kotlin
|
1
| 24
|
d455f77c70dde7620936275b89e563fbd414d9a5
| 182
|
sdk
|
MIT License
|
SceytChatUiKit/src/main/java/com/sceyt/chatuikit/presentation/helpers/ExoPlayerHelper.kt
|
sceyt
| 549,073,085
| false
|
{"Kotlin": 2361738, "Java": 107894}
|
package com.sceyt.sceytchatuikit.presentation.common
import android.content.Context
import androidx.media3.common.MediaItem
import androidx.media3.common.PlaybackException
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
class ExoPlayerHelper(private val context: Context,
private val playerView: PlayerView,
private val errorListener: ((PlaybackException) -> Unit)? = null,
private val listener: PlayerStateChangeCallback? = null,
private val playingListener: ((Boolean) -> Unit)? = null) : Player.Listener {
private lateinit var exoPlayer: ExoPlayer
private var isSetMediaPath = false
init {
initializePlayer()
}
companion object {
var lastPlayer: ExoPlayer? = null
}
private fun initializePlayer() {
lastPlayer?.stop()
lastPlayer?.release()
exoPlayer = ExoPlayer.Builder(context).build().also {
lastPlayer = it
}
player.repeatMode = Player.REPEAT_MODE_OFF
playerView.player = exoPlayer
exoPlayer.addListener(this)
}
fun setMediaPath(url: String?, playVideo: Boolean) {
if (isSetMediaPath) return
url?.let {
exoPlayer.setMediaItem(MediaItem.fromUri(it))
exoPlayer.prepare()
exoPlayer.playWhenReady = playVideo
isSetMediaPath = true
}
}
fun pausePlayer() {
exoPlayer.playWhenReady = false
}
fun resumePlayer() {
exoPlayer.playWhenReady = true
}
fun retryPlayer() {
exoPlayer.prepare()
}
fun releasePlayer() {
exoPlayer.release()
}
fun restartVideo() {
exoPlayer.seekTo(0)
exoPlayer.playWhenReady = true
}
fun isPlaying(): Boolean {
return exoPlayer.isPlaying
}
override fun onPlaybackStateChanged(state: Int) {
when (state) {
Player.STATE_BUFFERING -> listener?.updateState(State.Buffering)
Player.STATE_ENDED -> listener?.updateState(State.Ended)
Player.STATE_IDLE -> listener?.updateState(State.Idle)
Player.STATE_READY -> listener?.updateState(State.Ready)
else -> listener?.updateState(State.Unknown)
}
}
override fun onIsPlayingChanged(isPlaying: Boolean) {
super.onIsPlayingChanged(isPlaying)
playingListener?.invoke(isPlaying)
}
override fun onPlayerError(error: PlaybackException) {
super.onPlayerError(error)
errorListener?.invoke(error)
}
val videoDuration: Int
get() = exoPlayer.duration.toInt()
fun seekToStart() {
exoPlayer.seekTo(0)
exoPlayer.playWhenReady = false
}
val player: ExoPlayer
get() = exoPlayer
fun interface PlayerStateChangeCallback {
fun updateState(state: State)
}
enum class State {
Buffering,
Ended,
Idle,
Ready,
Unknown;
fun isReady(): Boolean {
return this == Ready
}
}
}
| 0
|
Kotlin
|
1
| 2
|
aa03d3d9f046243cd1bbb98bd5e9d5abcfeae822
| 3,157
|
sceyt-chat-android-uikit
|
MIT License
|
bitcoin/src/main/java/com/brentpanther/bitcoinwidget/ui/WarningBanner.kt
|
hwki
| 8,993,387
| false
| null |
package com.brentpanther.bitcoinwidget.ui
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import com.brentpanther.bitcoinwidget.BuildConfig
import com.brentpanther.bitcoinwidget.R
import com.brentpanther.bitcoinwidget.ui.theme.Highlight
@Composable
fun WarningBanner(viewModel: BannersViewModel) {
val context = LocalContext.current
OnLifecycleEvent { event ->
if (event == Lifecycle.Event.ON_RESUME) viewModel.loadBanners()
}
val banners = viewModel.visibleBanners
Column(Modifier.fillMaxWidth()) {
if ("data" in banners) {
Banner(viewModel, "data", R.string.warning_data_saver, R.string.button_settings) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
context.startActivity(
Intent(
Settings.ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS,
Uri.parse("package:${BuildConfig.APPLICATION_ID}")
)
)
}
}
}
if ("battery" in banners) {
Banner(viewModel, "battery", R.string.warning_battery_saver, buttonText = null)
}
}
}
@Composable
fun Banner(viewModel: BannersViewModel, key: String, @StringRes text: Int,
@StringRes buttonText: Int?, onClick: () -> Unit = {}) {
Surface(color = Highlight) {
Column(
Modifier
.fillMaxWidth()
.padding(8.dp)) {
Row(Modifier.fillMaxWidth()) {
Icon(painterResource(id = R.drawable.ic_outline_info_24), null, tint = MaterialTheme.colors.secondary)
Text(stringResource(id = text), lineHeight = 22.sp, fontSize = 16.sp, modifier = Modifier.padding(start=8.dp), color = Color.Black)
}
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
TextButton(onClick = {
viewModel.setDismissed(key)
}) {
Text(stringResource(id = R.string.dismiss))
}
buttonText?.let {
TextButton(onClick = onClick) {
Text(stringResource(id = it))
}
}
}
}
}
}
@Composable
fun OnLifecycleEvent(onEvent: (event: Lifecycle.Event) -> Unit) {
val eventHandler = rememberUpdatedState(onEvent)
val lifecycleOwner = rememberUpdatedState(LocalLifecycleOwner.current)
DisposableEffect(lifecycleOwner.value) {
val lifecycle = lifecycleOwner.value.lifecycle
val observer = LifecycleEventObserver { _, event ->
eventHandler.value(event)
}
lifecycle.addObserver(observer)
onDispose {
lifecycle.removeObserver(observer)
}
}
}
| 3
| null |
56
| 98
|
4c5679fd470ee14e98c1d1e7725e2777aff575c1
| 3,989
|
SimpleBitcoinWidget
|
MIT License
|
app/src/main/java/com/epiccrown/smartpark/repository/AdminRepository.kt
|
Orthoepiccrown0
| 631,601,191
| false
| null |
package com.epiccrown.smartpark.repository
import com.epiccrown.smartpark.model.request.AddParkRequest
import com.epiccrown.smartpark.model.request.AddZoneRequest
import com.epiccrown.smartpark.model.request.CarRevealedRequest
import com.epiccrown.smartpark.model.request.ProcessDataRequest
import com.epiccrown.smartpark.model.response.AllZonesResponse
import com.epiccrown.smartpark.model.response.ProcessDataResponse
import com.epiccrown.smartpark.model.response.SuccessResponse
import com.epiccrown.smartpark.repository.network.BaseRepository
import com.epiccrown.smartpark.repository.network.NetworkResult
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
class AdminRepository() : BaseRepository.Unauthenticated("api/") {
private val service = getService<AdminService>()
suspend fun processData(request: ProcessDataRequest): NetworkResult<ProcessDataResponse> {
return safeApiCall { service.processData(request) }
}
suspend fun getAllZones():NetworkResult<AllZonesResponse>{
return safeApiCall { service.getAllZones() }
}
suspend fun addPark(request: AddParkRequest):NetworkResult<SuccessResponse>{
return safeApiCall { service.addPark(request) }
}
suspend fun addZone(request: AddZoneRequest):NetworkResult<SuccessResponse>{
return safeApiCall { service.addZone(request) }
}
suspend fun carRevealed(request: CarRevealedRequest):NetworkResult<SuccessResponse>{
return safeApiCall { service.carRevealed(request) }
}
interface AdminService {
@POST("process-data")
suspend fun processData(@Body request: ProcessDataRequest): Response<ProcessDataResponse>
@GET("getAllZones")
suspend fun getAllZones(): Response<AllZonesResponse>
@POST("addPark")
suspend fun addPark(@Body request: AddParkRequest): Response<SuccessResponse>
@POST("addZone")
suspend fun addZone(@Body request: AddZoneRequest): Response<SuccessResponse>
@POST("addLotWithCar")
suspend fun carRevealed(@Body request: CarRevealedRequest): Response<SuccessResponse>
}
}
| 0
|
Kotlin
|
0
| 1
|
65bde1b86213daabb7337c97aa4952cbf4ad340b
| 2,174
|
SmartPark
|
MIT License
|
bye-bye-jetifier/src/main/java/com/dipien/byebyejetifier/scanner/ScannerContext.kt
|
dipien
| 312,684,686
| false
| null |
package com.dipien.byebyejetifier.scanner
import com.dipien.byebyejetifier.archive.ArchiveFile
import com.dipien.byebyejetifier.common.LoggerHelper
import com.dipien.byebyejetifier.common.toFilePath
import com.dipien.byebyejetifier.core.TypeRewriter
import com.dipien.byebyejetifier.core.config.Config
import com.dipien.byebyejetifier.core.type.JavaType
class ScannerContext(val config: Config, private val excludedFilesFromScanning: List<String>) {
val typeRewriter: TypeRewriter = TypeRewriter(config)
fun isExcludedFileFromScanning(archiveFile: ArchiveFile): Boolean =
excludedFilesFromScanning
.any { archiveFile.relativePath.toString().startsWith(it.toFilePath()) }
fun reportNoMappingFoundFailure(tag: String, type: JavaType) {
LoggerHelper.warn("No mapping for: $type", tag)
}
}
| 13
|
Kotlin
|
4
| 193
|
348c9bd0f324641367a5e16500f1521f3d77d573
| 835
|
bye-bye-jetifier
|
Apache License 2.0
|
src/main/kotlin/ink/ptms/adyeshach/Metrics.kt
|
l89669
| 349,965,165
| true
|
{"Gradle": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Java Properties": 1, "Java": 4, "YAML": 5, "JSON": 1, "Kotlin": 277}
|
package ink.ptms.adyeshach
import ink.ptms.adyeshach.api.AdyeshachAPI
import ink.ptms.adyeshach.api.event.AdyeshachEntityCreateEvent
import ink.ptms.adyeshach.common.script.ScriptHandler
import io.izzel.taboolib.metrics.BStats
import io.izzel.taboolib.module.inject.TListener
import io.izzel.taboolib.module.inject.TSchedule
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
object Metrics {
lateinit var metrics: BStats
private set
private var createdEntities = 0
@TSchedule
fun init() {
metrics = BStats(Adyeshach.plugin)
metrics.addCustomChart(BStats.SingleLineChart("entities") {
val sizePublic = AdyeshachAPI.getEntityManagerPublic().getEntities().size
val sizePublicTemporary = AdyeshachAPI.getEntityManagerPublicTemporary().getEntities().size
sizePublic + sizePublicTemporary
})
metrics.addCustomChart(BStats.SingleLineChart("scripts") {
ScriptHandler.workspace.scripts.size
})
metrics.addCustomChart(BStats.SingleLineChart("entity_created") {
createdEntities
})
metrics.addCustomChart(BStats.AdvancedPie("entity_types") {
val map = HashMap<String, Int>()
AdyeshachAPI.getEntityManagerPublic().getEntities().forEach {
map[it.entityType.name] = (map[it.entityType.name] ?: 0) + 1
}
AdyeshachAPI.getEntityManagerPublicTemporary().getEntities().forEach {
map[it.entityType.name] = (map[it.entityType.name] ?: 0) + 1
}
map
})
}
@TListener
class MetricsListener : Listener {
@EventHandler
fun e(e: AdyeshachEntityCreateEvent) {
createdEntities++
}
}
}
| 0
|
Kotlin
|
0
| 0
|
7e08e8d3660e737a7c5d7aa9f4284fb2dfe7ebc8
| 1,792
|
Adyeshach
|
MIT License
|
src/main/kotlin/ink/ptms/adyeshach/Metrics.kt
|
l89669
| 349,965,165
| true
|
{"Gradle": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Java Properties": 1, "Java": 4, "YAML": 5, "JSON": 1, "Kotlin": 277}
|
package ink.ptms.adyeshach
import ink.ptms.adyeshach.api.AdyeshachAPI
import ink.ptms.adyeshach.api.event.AdyeshachEntityCreateEvent
import ink.ptms.adyeshach.common.script.ScriptHandler
import io.izzel.taboolib.metrics.BStats
import io.izzel.taboolib.module.inject.TListener
import io.izzel.taboolib.module.inject.TSchedule
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
object Metrics {
lateinit var metrics: BStats
private set
private var createdEntities = 0
@TSchedule
fun init() {
metrics = BStats(Adyeshach.plugin)
metrics.addCustomChart(BStats.SingleLineChart("entities") {
val sizePublic = AdyeshachAPI.getEntityManagerPublic().getEntities().size
val sizePublicTemporary = AdyeshachAPI.getEntityManagerPublicTemporary().getEntities().size
sizePublic + sizePublicTemporary
})
metrics.addCustomChart(BStats.SingleLineChart("scripts") {
ScriptHandler.workspace.scripts.size
})
metrics.addCustomChart(BStats.SingleLineChart("entity_created") {
createdEntities
})
metrics.addCustomChart(BStats.AdvancedPie("entity_types") {
val map = HashMap<String, Int>()
AdyeshachAPI.getEntityManagerPublic().getEntities().forEach {
map[it.entityType.name] = (map[it.entityType.name] ?: 0) + 1
}
AdyeshachAPI.getEntityManagerPublicTemporary().getEntities().forEach {
map[it.entityType.name] = (map[it.entityType.name] ?: 0) + 1
}
map
})
}
@TListener
class MetricsListener : Listener {
@EventHandler
fun e(e: AdyeshachEntityCreateEvent) {
createdEntities++
}
}
}
| 0
|
Kotlin
|
0
| 0
|
7e08e8d3660e737a7c5d7aa9f4284fb2dfe7ebc8
| 1,792
|
Adyeshach
|
MIT License
|
src/main/kotlin/no/nav/syfo/oppfolgingstilfelle/kafka/KafkaOppfolgingstilfellePerson.kt
|
navikt
| 189,998,720
| false
| null |
package no.nav.syfo.oppfolgingstilfelle.kafka
import no.nav.syfo.domain.Virksomhetsnummer
import no.nav.syfo.personstatus.domain.*
import no.nav.syfo.util.nowUTC
import java.time.LocalDate
import java.time.OffsetDateTime
import java.util.*
data class KafkaOppfolgingstilfellePerson(
val uuid: String,
val createdAt: OffsetDateTime,
val personIdentNumber: String,
val oppfolgingstilfelleList: List<KafkaOppfolgingstilfelle>,
val referanseTilfelleBitUuid: String,
val referanseTilfelleBitInntruffet: OffsetDateTime,
)
data class KafkaOppfolgingstilfelle(
val arbeidstakerAtTilfelleEnd: Boolean,
val start: LocalDate,
val end: LocalDate,
val virksomhetsnummerList: List<String>,
)
// TODO: Hent latest oppfolgingstilfelle fra this
fun KafkaOppfolgingstilfellePerson.toPersonOversiktStatus(
latestKafkaOppfolgingstilfelle: KafkaOppfolgingstilfelle,
) = PersonOversiktStatus(
veilederIdent = null,
fnr = this.personIdentNumber,
navn = null,
enhet = null,
motebehovUbehandlet = null,
oppfolgingsplanLPSBistandUbehandlet = null,
dialogmotesvarUbehandlet = false,
dialogmotekandidat = null,
dialogmotekandidatGeneratedAt = null,
motestatus = null,
motestatusGeneratedAt = null,
latestOppfolgingstilfelle = this.toPersonOppfolgingstilfelle(
latestKafkaOppfolgingstilfelle = latestKafkaOppfolgingstilfelle,
),
aktivitetskrav = null,
aktivitetskravStoppunkt = null,
aktivitetskravSistVurdert = null,
aktivitetskravVurderingFrist = null,
behandlerdialogSvarUbehandlet = false,
behandlerdialogUbesvartUbehandlet = false,
behandlerdialogAvvistUbehandlet = false,
)
// TODO: Hent latest oppfolgingstilfelle fra this
fun KafkaOppfolgingstilfellePerson.toPersonOppfolgingstilfelle(
latestKafkaOppfolgingstilfelle: KafkaOppfolgingstilfelle,
) = Oppfolgingstilfelle(
updatedAt = nowUTC(),
generatedAt = this.createdAt,
oppfolgingstilfelleStart = latestKafkaOppfolgingstilfelle.start,
oppfolgingstilfelleEnd = latestKafkaOppfolgingstilfelle.end,
oppfolgingstilfelleBitReferanseInntruffet = this.referanseTilfelleBitInntruffet,
oppfolgingstilfelleBitReferanseUuid = UUID.fromString(this.referanseTilfelleBitUuid),
virksomhetList = latestKafkaOppfolgingstilfelle.virksomhetsnummerList.map { virksomhetsnummer ->
PersonOppfolgingstilfelleVirksomhet(
uuid = UUID.randomUUID(),
createdAt = nowUTC(),
virksomhetsnummer = Virksomhetsnummer(virksomhetsnummer),
virksomhetsnavn = null,
)
},
)
| 4
|
Kotlin
|
0
| 0
|
e5bf6ed6f4efdfd3bb9f5ad94ae41490b03cf1c4
| 2,601
|
syfooversiktsrv
|
MIT License
|
src/main/kotlin/no/nav/syfo/oppfolgingstilfelle/kafka/KafkaOppfolgingstilfellePerson.kt
|
navikt
| 189,998,720
| false
| null |
package no.nav.syfo.oppfolgingstilfelle.kafka
import no.nav.syfo.domain.Virksomhetsnummer
import no.nav.syfo.personstatus.domain.*
import no.nav.syfo.util.nowUTC
import java.time.LocalDate
import java.time.OffsetDateTime
import java.util.*
data class KafkaOppfolgingstilfellePerson(
val uuid: String,
val createdAt: OffsetDateTime,
val personIdentNumber: String,
val oppfolgingstilfelleList: List<KafkaOppfolgingstilfelle>,
val referanseTilfelleBitUuid: String,
val referanseTilfelleBitInntruffet: OffsetDateTime,
)
data class KafkaOppfolgingstilfelle(
val arbeidstakerAtTilfelleEnd: Boolean,
val start: LocalDate,
val end: LocalDate,
val virksomhetsnummerList: List<String>,
)
// TODO: Hent latest oppfolgingstilfelle fra this
fun KafkaOppfolgingstilfellePerson.toPersonOversiktStatus(
latestKafkaOppfolgingstilfelle: KafkaOppfolgingstilfelle,
) = PersonOversiktStatus(
veilederIdent = null,
fnr = this.personIdentNumber,
navn = null,
enhet = null,
motebehovUbehandlet = null,
oppfolgingsplanLPSBistandUbehandlet = null,
dialogmotesvarUbehandlet = false,
dialogmotekandidat = null,
dialogmotekandidatGeneratedAt = null,
motestatus = null,
motestatusGeneratedAt = null,
latestOppfolgingstilfelle = this.toPersonOppfolgingstilfelle(
latestKafkaOppfolgingstilfelle = latestKafkaOppfolgingstilfelle,
),
aktivitetskrav = null,
aktivitetskravStoppunkt = null,
aktivitetskravSistVurdert = null,
aktivitetskravVurderingFrist = null,
behandlerdialogSvarUbehandlet = false,
behandlerdialogUbesvartUbehandlet = false,
behandlerdialogAvvistUbehandlet = false,
)
// TODO: Hent latest oppfolgingstilfelle fra this
fun KafkaOppfolgingstilfellePerson.toPersonOppfolgingstilfelle(
latestKafkaOppfolgingstilfelle: KafkaOppfolgingstilfelle,
) = Oppfolgingstilfelle(
updatedAt = nowUTC(),
generatedAt = this.createdAt,
oppfolgingstilfelleStart = latestKafkaOppfolgingstilfelle.start,
oppfolgingstilfelleEnd = latestKafkaOppfolgingstilfelle.end,
oppfolgingstilfelleBitReferanseInntruffet = this.referanseTilfelleBitInntruffet,
oppfolgingstilfelleBitReferanseUuid = UUID.fromString(this.referanseTilfelleBitUuid),
virksomhetList = latestKafkaOppfolgingstilfelle.virksomhetsnummerList.map { virksomhetsnummer ->
PersonOppfolgingstilfelleVirksomhet(
uuid = UUID.randomUUID(),
createdAt = nowUTC(),
virksomhetsnummer = Virksomhetsnummer(virksomhetsnummer),
virksomhetsnavn = null,
)
},
)
| 4
|
Kotlin
|
0
| 0
|
e5bf6ed6f4efdfd3bb9f5ad94ae41490b03cf1c4
| 2,601
|
syfooversiktsrv
|
MIT License
|
app/src/main/java/com/example/notesapp/data/NotesDatabase.kt
|
nikolamanushev48
| 696,311,253
| false
|
{"Kotlin": 34066}
|
package com.example.notesapp.data
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(
entities = [Note::class],
version = 1,
)
abstract class NotesDatabase : RoomDatabase() {
abstract fun noteDao(): NoteDao
companion object {
val DB_NAME = "notes_db"
}
}
| 0
|
Kotlin
|
0
| 0
|
a6cf874e97bb6f3e5148b834e29d89e8f671de7b
| 308
|
WriteItDown
|
MIT License
|
src/test/kotlin/ch/sourcemotion/vertx/kinesis/consumer/orchestra/impl/redis/lua/LuaDeleteValuesByKeyPatternReturnDeletedCountTest.kt
|
wem
| 253,237,315
| false
| null |
package ch.sourcemotion.vertx.kinesis.consumer.orchestra.impl.redis.lua
import ch.sourcemotion.vertx.kinesis.consumer.orchestra.impl.ext.okResponseAsBoolean
import ch.sourcemotion.vertx.kinesis.consumer.orchestra.testing.AbstractRedisTest
import io.kotest.matchers.booleans.shouldBeTrue
import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.shouldBe
import io.vertx.junit5.VertxTestContext
import io.vertx.kotlin.coroutines.await
import io.vertx.redis.client.Command
import io.vertx.redis.client.Request
import org.junit.jupiter.api.Test
import kotlin.LazyThreadSafetyMode.NONE
class LuaDeleteValuesByKeyPatternReturnDeletedCountTest : AbstractRedisTest() {
private val luaExecutor by lazy(NONE) { LuaExecutor(redisClient) }
private val luaScript = DefaultLuaScriptDescription.DELETE_VALUES_BY_KEY_PATTERN_RETURN_DELETED_COUNT
@Test
internal fun single_key(testContext: VertxTestContext) = asyncTest(testContext) {
val value = "1"
val key = "some-key"
val pattern = "some-*"
redisClient.send(Request.cmd(Command.SET).arg(key).arg(value)).await().okResponseAsBoolean().shouldBeTrue()
val luaResponse = luaExecutor.execute(luaScript, listOf(), listOf(pattern))
luaResponse.shouldNotBeNull()
luaResponse.toInteger().shouldBe(1)
}
@Test
internal fun multi_key(testContext: VertxTestContext) = asyncTest(testContext) {
val value = "1"
val key = "some-key"
val otherKey = "other-key"
val pattern = "*-key"
redisClient.send(Request.cmd(Command.SET).arg(key).arg(value)).await().okResponseAsBoolean().shouldBeTrue()
redisClient.send(Request.cmd(Command.SET).arg(otherKey).arg(value)).await().okResponseAsBoolean().shouldBeTrue()
val luaResponse = luaExecutor.execute(luaScript,listOf(),listOf(pattern))
luaResponse.shouldNotBeNull()
luaResponse.toInteger().shouldBe(2)
}
}
| 10
|
Kotlin
|
0
| 3
|
a2290613daf15c96034bf5d3d67103ddc8741776
| 1,955
|
vertx-kinesis-consumer-orchestra
|
MIT License
|
Sources/Android/domain/src/main/java/com/indeema/domain/interactor/interfaces/AuthInteractor.kt
|
IndeemaSoftware
| 143,034,862
| false
| null |
package com.indeema.domain.interactor.interfaces
import com.indeema.data.entities.RedmineResponce
import com.indeema.domain.action.Error
import com.indeema.domain.action.Next
/**
* @author <NAME>
* Date: May, 19, 2018
* Time: 20:42
*/
interface AuthInteractor : BaseInteractor {
fun login(next: Next<RedmineResponce>, error: Error, credential: String)
}
| 1
|
Kotlin
|
4
| 4
|
47334c564f391d34e33de5ed3dd354c4a5a7e4e3
| 366
|
SmartLock
|
MIT License
|
bot/engine/src/main/kotlin/fr/vsct/tock/bot/engine/BotVerticle.kt
|
sycomix
| 136,461,807
| true
|
{"Kotlin": 1448205, "TypeScript": 301273, "HTML": 102491, "CSS": 27660, "JavaScript": 5174, "Shell": 1303}
|
/*
* Copyright (C) 2017 VSCT
*
* 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 fr.vsct.tock.bot.engine
import fr.vsct.tock.shared.error
import fr.vsct.tock.shared.property
import fr.vsct.tock.shared.security.initEncryptor
import fr.vsct.tock.shared.vertx.WebVerticle
import io.vertx.ext.auth.AuthProvider
import io.vertx.ext.web.Router
import io.vertx.ext.web.RoutingContext
import mu.KLogger
import mu.KotlinLogging
/**
*
*/
internal class BotVerticle : WebVerticle() {
override val logger: KLogger = KotlinLogging.logger {}
private val handlers: MutableMap<String, (Router) -> Unit> = mutableMapOf()
override fun authProvider(): AuthProvider? = defaultAuthProvider()
fun registerServices(rootPath: String, installer: (Router) -> Unit) {
if (!(handlers as Map<String, (Router) -> Unit>).containsKey(rootPath)) {
handlers.put(rootPath, installer)
} else {
logger.debug("path $rootPath already registered - skip")
}
}
override fun protectedPath(): String {
return property("tock_bot_protected_path", "/admin")
}
override fun configure() {
initEncryptor()
handlers.forEach {
try {
it.value.invoke(router)
} catch (e: Exception) {
logger.error(e)
}
}
}
override fun healthcheck(): (RoutingContext) -> Unit {
return BotRepository.healthcheckHandler
}
}
| 0
|
Kotlin
|
0
| 0
|
e8ee0dcc3de16f89878e138dc06920ed8b96aa20
| 1,980
|
tock
|
Apache License 2.0
|
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/resource/TileType.kt
|
Xanik
| 282,687,897
| false
| null |
package org.hexworks.zircon.internal.resource
enum class TileType {
CHARACTER_TILE,
GRAPHIC_TILE,
IMAGE_TILE
}
| 1
| null |
1
| 2
|
bf435cddeb55f7c3a9da5dd5c29be13af8354d0f
| 124
|
zircon
|
Apache License 2.0
|
android/src/main/kotlin/live/hms/hmssdk_flutter/HMSTrackExtension.kt
|
Arunshaik4321
| 400,066,935
| true
|
{"Dart": 122269, "Kotlin": 31296, "Swift": 29312, "Ruby": 2157, "Objective-C": 730}
|
package live.hms.hmssdk_flutter
import live.hms.video.media.tracks.HMSTrack
import live.hms.video.media.tracks.HMSTrackSource
import live.hms.video.media.tracks.HMSTrackType
import live.hms.video.sdk.models.enums.HMSTrackUpdate
class HMSTrackExtension {
companion object{
fun toDictionary(track:HMSTrack?):HashMap<String,Any>?{
val hashMap=HashMap<String,Any>()
if(track==null)return null
hashMap.put("track_id",track.trackId)
hashMap.put("track_description",track.description)
hashMap.put("track_kind", getKindInString(track.type)!!)
hashMap.put("track_source", getSourceInString(track.source.uppercase()))
return hashMap
}
private fun getSourceInString(source:String):String{
return when(source){
"REGULAR"->{
"kHMSTrackSourceRegular"
}
"SCREEN"->{
"kHMSTrackSourceScreen"
}
"PLUGIN"->{
"kHMSTrackSourcePlugin"
}
else->{
""
}
}
}
private fun getKindInString(type:HMSTrackType?):String?{
if(type==null)return null
return when(type){
HMSTrackType.AUDIO->{
"kHMSTrackKindAudio"
}
HMSTrackType.VIDEO->{
"kHMSTrackKindVideo"
}
else->{
""
}
}
}
fun getTrackUpdateInString(hmsTrackUpdate: HMSTrackUpdate?):String?{
if (hmsTrackUpdate==null)return null
return when(hmsTrackUpdate){
HMSTrackUpdate.TRACK_UNMUTED-> "trackUnmuted"
HMSTrackUpdate.TRACK_MUTED-> "trackMuted"
HMSTrackUpdate.TRACK_REMOVED-> "trackRemoved"
HMSTrackUpdate.TRACK_DESCRIPTION_CHANGED-> "trackDescriptionChanged"
HMSTrackUpdate.TRACK_ADDED-> "trackAdded"
else->{
"defaultUpdate"
}
}
}
}
}
| 0
| null |
0
| 0
|
85605f495f967362e009a39e751f0c4c92f13896
| 2,207
|
100ms-flutter
|
MIT License
|
app/src/main/java/com/tyler/app/kotlinkaiyan/ui/adapter/CategoryListAdapter.kt
|
TylerWang1110
| 195,174,131
| false
| null |
package com.tyler.app.kotlinkaiyan.ui.adapter
import android.widget.ImageView
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.tyler.app.kotlinkaiyan.BaseApp.Companion.context
import com.tyler.app.kotlinkaiyan.GlideApp
import com.tyler.app.kotlinkaiyan.R
import com.tyler.app.kotlinkaiyan.dp2px
import com.tyler.app.kotlinkaiyan.mvp.model.bean.CategoryBean
/**
* @创建者 <NAME>.
* @创建时间 2019/7/12 9:27.
* @描述 ${分类}.
*/
class CategoryListAdapter :
BaseQuickAdapter<CategoryBean, BaseViewHolder>(R.layout.item_list_category, ArrayList<CategoryBean>()) {
override fun convert(helper: BaseViewHolder?, item: CategoryBean?) {
helper?.setText(R.id.tv_list_category, "#${item?.name}")
val iv: ImageView? = helper?.getView(R.id.iv_list_category)
if (iv != null) {
GlideApp.with(mContext)
.load(item?.bgPicture)
.placeholder(R.drawable.shape_base_img_black_dp5)
.error(R.drawable.shape_base_img_black_dp5)
.apply(RequestOptions().transforms(CenterCrop(), RoundedCorners(context.dp2px(5f))))
.into(iv)
}
}
}
| 1
| null |
1
| 1
|
7945cdfbaeff8b67cf3a1123cd663a18c419168c
| 1,403
|
kotlin-kaiyan
|
Apache License 2.0
|
app/src/main/java/org/p2p/wallet/utils/chacha/ChaCha20Poly1305Encryptor.kt
|
p2p-org
| 306,035,988
| false
|
{"Kotlin": 4545395, "HTML": 3064848, "Java": 296567, "Groovy": 1601, "Shell": 1252}
|
package org.p2p.wallet.utils.chacha
import org.bouncycastle.crypto.modes.ChaCha20Poly1305
import org.bouncycastle.crypto.params.KeyParameter
import org.bouncycastle.crypto.params.ParametersWithIV
import org.p2p.wallet.utils.processBytesKt
class ChaCha20Poly1305Encryptor(
private val chaCha20Poly1305: ChaCha20Poly1305
) {
fun encryptData(
privateKey: ByteArray,
nonce: ByteArray,
dataToEncrypt: ByteArray
): ByteArray {
chaCha20Poly1305.init(
true,
ParametersWithIV(
KeyParameter(privateKey.copyOf()),
nonce.copyOf()
)
)
val resultSize = chaCha20Poly1305.getOutputSize(dataToEncrypt.size)
val encryptionResult = ByteArray(resultSize)
val finalOff = chaCha20Poly1305.processBytesKt(
inBytes = dataToEncrypt,
len = dataToEncrypt.size,
outBytes = encryptionResult,
)
chaCha20Poly1305.doFinal(encryptionResult, finalOff)
chaCha20Poly1305.reset()
return encryptionResult
}
}
| 8
|
Kotlin
|
18
| 34
|
d091e18b7d88c936b7c6c627f4fec96bcf4a0356
| 1,092
|
key-app-android
|
MIT License
|
crabzilla-pgclient/src/main/kotlin/io/github/crabzilla/pgclient/EventTopics.kt
|
crabzilla
| 91,769,036
| false
| null |
package io.github.crabzilla.pgclient
enum class EventTopics {
STATE_TOPIC,
VIEW_TOPIC
}
| 1
|
Kotlin
|
8
| 62
|
09cb11ffb7cc9ecb328cf47f15d79587137b1895
| 93
|
crabzilla
|
Apache License 2.0
|
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/lakeformation/CfnTagDsl.kt
|
cloudshiftinc
| 667,063,030
| false
|
{"Kotlin": 63959868}
|
@file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.lakeformation
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import kotlin.String
import kotlin.collections.Collection
import kotlin.collections.MutableList
import software.amazon.awscdk.services.lakeformation.CfnTag
import software.constructs.Construct
/**
* The `AWS::LakeFormation::Tag` resource represents an LF-tag, which consists of a key and one or
* more possible values for the key.
*
* During a stack operation, AWS CloudFormation calls the AWS Lake Formation `CreateLFTag` API to
* create a tag, and `UpdateLFTag` API to update a tag resource, and a `DeleteLFTag` to delete it.
*
* 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.lakeformation.*;
* CfnTag cfnTag = CfnTag.Builder.create(this, "MyCfnTag")
* .tagKey("tagKey")
* .tagValues(List.of("tagValues"))
* // the properties below are optional
* .catalogId("catalogId")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lakeformation-tag.html)
*/
@CdkDslMarker
public class CfnTagDsl(
scope: Construct,
id: String,
) {
private val cdkBuilder: CfnTag.Builder = CfnTag.Builder.create(scope, id)
private val _tagValues: MutableList<String> = mutableListOf()
/**
* Catalog id string, not less than 1 or more than 255 bytes long, matching the
* [single-line string pattern](https://docs.aws.amazon.com/lake-formation/latest/dg/aws-lake-formation-api-aws-lake-formation-api-common.html)
* .
*
* The identifier for the Data Catalog . By default, the account ID. The Data Catalog is the
* persistent metadata store. It contains database definitions, table definitions, and other
* control information to manage your AWS Lake Formation environment.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lakeformation-tag.html#cfn-lakeformation-tag-catalogid)
*
* @param catalogId Catalog id string, not less than 1 or more than 255 bytes long, matching the
* [single-line string pattern](https://docs.aws.amazon.com/lake-formation/latest/dg/aws-lake-formation-api-aws-lake-formation-api-common.html)
* .
*/
public fun catalogId(catalogId: String) {
cdkBuilder.catalogId(catalogId)
}
/**
* UTF-8 string, not less than 1 or more than 255 bytes long, matching the
* [single-line string pattern](https://docs.aws.amazon.com/lake-formation/latest/dg/aws-lake-formation-api-aws-lake-formation-api-common.html)
* .
*
* The key-name for the LF-tag.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lakeformation-tag.html#cfn-lakeformation-tag-tagkey)
*
* @param tagKey UTF-8 string, not less than 1 or more than 255 bytes long, matching the
* [single-line string pattern](https://docs.aws.amazon.com/lake-formation/latest/dg/aws-lake-formation-api-aws-lake-formation-api-common.html)
* .
*/
public fun tagKey(tagKey: String) {
cdkBuilder.tagKey(tagKey)
}
/**
* An array of UTF-8 strings, not less than 1 or more than 50 strings.
*
* A list of possible values of the corresponding `TagKey` of an LF-tag key-value pair.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lakeformation-tag.html#cfn-lakeformation-tag-tagvalues)
*
* @param tagValues An array of UTF-8 strings, not less than 1 or more than 50 strings.
*/
public fun tagValues(vararg tagValues: String) {
_tagValues.addAll(listOf(*tagValues))
}
/**
* An array of UTF-8 strings, not less than 1 or more than 50 strings.
*
* A list of possible values of the corresponding `TagKey` of an LF-tag key-value pair.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lakeformation-tag.html#cfn-lakeformation-tag-tagvalues)
*
* @param tagValues An array of UTF-8 strings, not less than 1 or more than 50 strings.
*/
public fun tagValues(tagValues: Collection<String>) {
_tagValues.addAll(tagValues)
}
public fun build(): CfnTag {
if (_tagValues.isNotEmpty()) cdkBuilder.tagValues(_tagValues)
return cdkBuilder.build()
}
}
| 3
|
Kotlin
|
0
| 3
|
c59c6292cf08f0fc3280d61e7f8cff813a608a62
| 4,727
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
app/src/main/java/com/clay/covid_19tracker/BaseApplication.kt
|
Clay-CL
| 285,233,861
| false
| null |
package com.clay.covid_19tracker
import android.app.Application
import timber.log.Timber
class BaseApplication: Application() {
override fun onCreate() {
super.onCreate()
Timber.plant(Timber.DebugTree())
}
}
| 0
|
Kotlin
|
0
| 0
|
5405682445eace6f1cf95099d57ad673e400e4b3
| 233
|
COVID-19-Cases-Tracking-App
|
MIT License
|
src/test/kotlin/org/rust/ide/intentions/IfLetToMatchIntentionTest.kt
|
intellij-rust
| 42,619,487
| false
| null |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
import org.rust.ProjectDescriptor
import org.rust.WithStdlibRustProjectDescriptor
@ProjectDescriptor(WithStdlibRustProjectDescriptor::class)
class IfLetToMatchIntentionTest : RsIntentionTestBase(IfLetToMatchIntention::class) {
fun `test availability range`() = checkAvailableInSelectionOnly("""
fn foo() {
let x = Some(42);
<selection>if let</selection> Some(value) <selection>=</selection> x {
println!("some")
}
}
""")
fun `test option with some`() = doAvailableTest("""
fn main() {
let x = Some(42);
/*caret*/if let Some(value) = x {
println!("some")
}
}
""", """
fn main() {
let x = Some(42);
match x {
Some(value) => {
println!("some")
}
None => {}
}
}
""")
fun `test option with refutable some`() = doAvailableTest("""
fn main() {
let x = Some(42);
/*caret*/if let Some(42) = x {
println!("some")
}
}
""", """
fn main() {
let x = Some(42);
match x {
Some(42) => {
println!("some")
}
_ => {}
}
}
""")
fun `test option with wild some`() = doAvailableTest("""
fn main() {
let x = Some(42);
/*caret*/if let Some(_) = x {
println!("some")
}
}
""", """
fn main() {
let x = Some(42);
match x {
Some(_) => {
println!("some")
}
None => {}
}
}
""")
fun `test option with range`() = doAvailableTest("""
fn main() {
let x = Some(42);
/*caret*/if let Some(1..=5) = x {
println!("some")
}
}
""", """
fn main() {
let x = Some(42);
match x {
Some(1..=5) => {
println!("some")
}
_ => {}
}
}
""")
fun `test option with none`() = doAvailableTest("""
fn main() {
let x = Some(42);
/*caret*/if let None = x {
println!("none")
}
}
""", """
fn main() {
let x = Some(42);
match x {
None => {
println!("none")
}
Some(..) => {}
}
}
""")
fun `test option with unnecessary parentheses around pattern`() = doAvailableTest("""
fn main() {
let x = Some(42);
/*caret*/if let (((None))) = x {
println!("none")
}
}
""", """
fn main() {
let x = Some(42);
match x {
(((None))) => {
println!("none")
}
Some(..) => {}
}
}
""")
fun `test option full 1`() = doAvailableTest("""
fn main() {
let x = Some(42);
/*caret*/if let Some(value) = x {
println!("some")
} else {
println!("none")
}
}
""", """
fn main() {
let x = Some(42);
match x {
Some(value) => {
println!("some")
}
None => {
println!("none")
}
}
}
""")
fun `test option full 2`() = doAvailableTest("""
fn main() {
let x = Some(42);
/*caret*/if let None = x {
println!("none")
} else {
println!("some")
}
}
""", """
fn main() {
let x = Some(42);
match x {
None => {
println!("none")
}
Some(..) => {
println!("some")
}
}
}
""")
fun `test option full with unnecessary parentheses around pattern`() = doAvailableTest("""
fn main() {
let x = Some(42);
/*caret*/if let ((((None)))) = x {
println!("none")
} else if let Some(a) = x {
println!("some")
}
}
""", """
fn main() {
let x = Some(42);
match x {
((((None)))) => {
println!("none")
}
Some(a) => {
println!("some")
}
}
}
""")
fun `test result with ok`() = doAvailableTest("""
fn main() {
let x: Result<i32, i32> = Ok(42);
/*caret*/if let Ok(value) = x {
println!("ok")
}
}
""", """
fn main() {
let x: Result<i32, i32> = Ok(42);
match x {
Ok(value) => {
println!("ok")
}
Err(..) => {}
}
}
""")
fun `test result with err`() = doAvailableTest("""
fn main() {
let x: Result<i32, i32> = Err(42);
/*caret*/if let Err(e) = x {
println!("err")
}
}
""", """
fn main() {
let x: Result<i32, i32> = Err(42);
match x {
Err(e) => {
println!("err")
}
Ok(..) => {}
}
}
""")
fun `test result full 1`() = doAvailableTest("""
fn main() {
let x: Result<i32, i32> = Ok(42);
/*caret*/if let Ok(value) = x {
println!("ok")
} else {
println!("err")
}
}
""", """
fn main() {
let x: Result<i32, i32> = Ok(42);
match x {
Ok(value) => {
println!("ok")
}
Err(..) => {
println!("err")
}
}
}
""")
fun `test result full 2`() = doAvailableTest("""
fn main() {
let x: Result<i32, i32> = Ok(42);
/*caret*/if let Err(e) = x {
println!("err")
} else {
println!("ok")
}
}
""", """
fn main() {
let x: Result<i32, i32> = Ok(42);
match x {
Err(e) => {
println!("err")
}
Ok(..) => {
println!("ok")
}
}
}
""")
fun `test simple else`() = doAvailableTest("""
fn main() {
let x = Some(42);
/*caret*/if let Some(val) = x {
} else {
println!("it work")
}
}
""", """
fn main() {
let x = Some(42);
match x {
Some(val) => {}
None => {
println!("it work")
}
}
}
""")
fun `test else if`() = doAvailableTest("""
fn main() {
if let A(value) = x {
} else /*caret*/if let B(value) = x {
}
}
""", """
fn main() {
match x {
A(value) => {}
B(value) => {}
_ => {}
}
}
""")
fun `test full option else if`() = doAvailableTest("""
fn main() {
let x = Some(42);
/*caret*/if let Some(value) = x {
println!("some")
} else if let None = x {
println!("none")
}
}
""", """
fn main() {
let x = Some(42);
match x {
Some(value) => {
println!("some")
}
None => {
println!("none")
}
}
}
""")
fun `test full result else if`() = doAvailableTest("""
fn main() {
let x: Result<i32, i32> = Ok(42);
/*caret*/if let Ok(value) = x {
println!("ok")
} else if let Err(e) = x {
println!("err")
}
}
""", """
fn main() {
let x: Result<i32, i32> = Ok(42);
match x {
Ok(value) => {
println!("ok")
}
Err(e) => {
println!("err")
}
}
}
""")
fun `test else if else`() = doAvailableTest("""
fn main() {
/*caret*/if let A(value) = x {
} else if let B(value) = x {
} else {
}
}
""", """
fn main() {
match x {
A(value) => {}
B(value) => {}
_ => {}
}
}
""")
fun `test trackback if`() = doAvailableTest("""
fn main() {
/*caret*/if let A(value) = x {
} else if let B(value) = x {
} else {
}
}
""", """
fn main() {
match x {
A(value) => {}
B(value) => {}
_ => {}
}
}
""")
fun `test apply on same target`() = doUnavailableTest("""
fn main() {
/*caret*/if let A(value) = x {
} else if let B(value) = y {
}
}
""")
fun `test available with range`() = doAvailableTest("""
fn main() {
let e = 4;
/*caret*/if let 1..=5 = e {
println!("got {}", e)
};
}
""", """
fn main() {
let e = 4;
match e {
1..=5 => {
println!("got {}", e)
}
_ => {}
};
}
""")
fun `test available with const`() = doAvailableTest("""
fn main() {
let e = 4;
/*caret*/if let 4 = e {
println!("got {}", e)
};
}
""", """
fn main() {
let e = 4;
match e {
4 => {
println!("got {}", e)
}
_ => {}
};
}
""")
fun `test available with struct`() = doAvailableTest("""
struct Point {
x: bool,
y: bool,
}
fn main() {
let point = Point { x: false, y: true };
/*caret*/if let Point { x: true, .. } = point {
println!("42")
}
}
""", """
struct Point {
x: bool,
y: bool,
}
fn main() {
let point = Point { x: false, y: true };
match point {
Point { x: true, .. } => {
println!("42")
}
_ => {}
}
}
""")
fun `test available with struct 2`() = doAvailableTest("""
struct Point {
x: bool,
y: bool,
}
fn main() {
let point = Point { x: false, y: true };
/*caret*/if let Point { x: true, y: f } = point {
println!("42")
}
}
""", """
struct Point {
x: bool,
y: bool,
}
fn main() {
let point = Point { x: false, y: true };
match point {
Point { x: true, y: f } => {
println!("42")
}
_ => {}
}
}
""")
fun `test available pattern with tup`() = doAvailableTest("""
fn main() {
let e = Some(32);
/*caret*/if let (Some(42)) = e {
println!("got {:?}", a)
}
}
""", """
fn main() {
let e = Some(32);
match e {
(Some(42)) => {
println!("got {:?}", a)
}
_ => {}
}
}
""")
fun `test available pattern with tup 2`() = doAvailableTest("""
fn main() {
let e = (42, 50);
/*caret*/if let (a, 50) = e {
println!("got {:?}", a)
}
}
""", """
fn main() {
let e = (42, 50);
match e {
(a, 50) => {
println!("got {:?}", a)
}
_ => {}
}
}
""")
fun `test available with slice`() = doAvailableTest("""
fn main() {
let x = [1, 2];
/*caret*/if let [1, ..] = x {
println!("42")
}
}
""", """
fn main() {
let x = [1, 2];
match x {
[1, ..] => {
println!("42")
}
_ => {}
}
}
""")
fun `test available with box`() = doAvailableTest("""
fn main() {
let x = box 42;
/*caret*/if let box 42 = x {
println!("42")
}
}
""", """
fn main() {
let x = box 42;
match x {
box 42 => {
println!("42")
}
_ => {}
}
}
""")
fun `test available with ref`() = doAvailableTest("""
fn main() {
let x = &42;
/*caret*/if let &42 = x {
println!("42")
}
}
""", """
fn main() {
let x = &42;
match x {
&42 => {
println!("42")
}
_ => {}
}
}
""")
fun `test multiple if let pattern`() = doAvailableTest("""
enum V { V1(i32), V2(i32), V3 }
fn foo(v: V) {
/*caret*/if let V1(x) | V2(x) = v {
println!("{}", x);
}
}
""", """
enum V { V1(i32), V2(i32), V3 }
fn foo(v: V) {
match v {
V1(x) | V2(x) => {
println!("{}", x);
}
_ => {}
}
}
""")
fun `test multiple if let pattern with leading |`() = doAvailableTest("""
enum V { V1(i32), V2(i32), V3 }
fn foo(v: V) {
/*caret*/if let | V1(x) | V2(x) = v {
println!("{}", x);
}
}
""", """
enum V { V1(i32), V2(i32), V3 }
fn foo(v: V) {
match v {
| V1(x) | V2(x) => {
println!("{}", x);
}
_ => {}
}
}
""")
fun `test irrefutable pattern`() = doAvailableTest("""
struct Id(u32);
struct S { a: Id, b: u32 }
fn foo(s: S) {
/*caret*/if let S { a: Id(ref name), .. } = s {
let _x = name;
}
}
""", """
struct Id(u32);
struct S { a: Id, b: u32 }
fn foo(s: S) {
match s {
S { a: Id(ref name), .. } => {
let _x = name;
}
}
}
""")
fun `test irrefutable pattern with else`() = doAvailableTest("""
struct Id(u32);
struct S { a: Id, b: u32 }
fn foo(s: S) {
/*caret*/if let S { a: Id(ref name), .. } = s {
let _x = name;
}
else {
let _y = 0;
}
}
""", """
struct Id(u32);
struct S { a: Id, b: u32 }
fn foo(s: S) {
match s {
S { a: Id(ref name), .. } => {
let _x = name;
}
_ => {
let _y = 0;
}
}
}
""")
fun `test irrefutable single variant enum`() = doAvailableTest("""
enum V { V1 }
fn foo(v: V) {
/*caret*/if let V::V1 = v {
println!("hello");
}
}
""", """
enum V { V1 }
fn foo(v: V) {
match v {
V::V1 => {
println!("hello");
}
}
}
""")
fun `test irrefutable struct`() = doAvailableTest("""
struct S;
fn foo(s: S) {
/*caret*/if let S = s {
println!("hello");
}
}
""", """
struct S;
fn foo(s: S) {
match s {
S => {
println!("hello");
}
}
}
""")
}
| 1,841
| null |
380
| 4,528
|
c6657c02bb62075bf7b7ceb84d000f93dda34dc1
| 17,342
|
intellij-rust
|
MIT License
|
app/src/main/java/rs/smobile/chucknorrisjokes/ui/JokesScreenComposable.kt
|
stevan-milovanovic
| 602,084,634
| false
|
{"Kotlin": 44108, "Shell": 346}
|
package rs.smobile.chucknorrisjokes.ui
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedButton
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.paint
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Devices
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import rs.smobile.chucknorrisjokes.R
import rs.smobile.chucknorrisjokes.data.api.model.Joke
import rs.smobile.chucknorrisjokes.ui.theme.ChuckNorrisJokesTheme
const val PROGRESS_INDICATOR_TEST_TAG = "main_progress_indicator_test_tag"
const val JOKE_CARD_TEST_TAG = "joke_card_test_tag"
@Composable
fun JokesScreenComposable(
uiState: JokeUiState,
fetchNewJoke: () -> Unit,
onJokeCategorySelected: (String) -> Unit
) {
ChuckNorrisJokesTheme {
JokeGeneratorSection(
uiState,
fetchNewJoke,
onJokeCategorySelected
)
}
}
@Composable
private fun JokeGeneratorSection(
uiState: JokeUiState,
onGenerateJokeButtonClick: () -> Unit,
onJokeCategorySelected: (String) -> Unit
) {
Column(
modifier = Modifier
.fillMaxSize()
.paint(
painterResource(id = R.drawable.liquid_cheese),
contentScale = ContentScale.FillBounds,
alpha = 0.4f
),
horizontalAlignment = Alignment.CenterHorizontally
) {
GenerateJokeButton(onGenerateJokeButtonClick)
when (uiState) {
is JokeUiState.Loading -> LinearProgressIndicator(
modifier = Modifier
.padding(top = 20.dp)
.testTag(PROGRESS_INDICATOR_TEST_TAG)
)
else -> JokeCard(uiState)
}
LazyVerticalGrid(
columns = GridCells.Adaptive(128.dp),
modifier = Modifier.padding(top = 8.dp),
contentPadding = PaddingValues(
start = 12.dp,
top = 16.dp,
end = 12.dp,
bottom = 16.dp
),
content = {
items(uiState.categories) { category ->
JokeCategory(
category = category,
isSelected = uiState.selectedCategory != null && uiState.selectedCategory == category,
onJokeCategorySelected = onJokeCategorySelected
)
}
}
)
}
}
@Composable
private fun JokeCategory(
category: String,
isSelected: Boolean,
onJokeCategorySelected: (String) -> Unit
) {
ElevatedCard(
modifier = Modifier
.padding(4.dp)
.fillMaxWidth()
.clickable { onJokeCategorySelected(category) },
shape = MaterialTheme.shapes.small,
colors = CardDefaults.cardColors(
containerColor = if (isSelected) MaterialTheme.colorScheme.secondary
else MaterialTheme.colorScheme.tertiary,
contentColor = MaterialTheme.colorScheme.onPrimary
)
) {
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = category,
fontWeight = FontWeight.Bold,
style = MaterialTheme.typography.bodyLarge,
color = if (isSelected) MaterialTheme.colorScheme.onSecondary else
MaterialTheme.colorScheme.onTertiary,
textAlign = TextAlign.Center,
modifier = Modifier.padding(vertical = 16.dp, horizontal = 8.dp)
)
}
}
}
@Composable
private fun GenerateJokeButton(
onClick: () -> Unit
) {
ElevatedButton(
onClick = onClick,
modifier = Modifier.padding(vertical = 40.dp),
shape = MaterialTheme.shapes.small,
colors = ButtonDefaults.filledTonalButtonColors()
) {
Text(
text = stringResource(R.string.generate_new_joke),
style = MaterialTheme.typography.headlineSmall
)
}
}
@Composable
private fun JokeCard(
uiState: JokeUiState
) {
ElevatedCard(
modifier = Modifier
.padding(horizontal = 40.dp)
.fillMaxWidth()
.testTag(JOKE_CARD_TEST_TAG),
shape = MaterialTheme.shapes.small,
colors = CardDefaults.cardColors(
containerColor = if (uiState is JokeUiState.Success) MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.error,
contentColor = MaterialTheme.colorScheme.onPrimary
)
) {
Text(
text = when (uiState) {
is JokeUiState.Success -> uiState.joke?.value.orEmpty()
is JokeUiState.Failure -> uiState.message.orEmpty()
else -> ""
},
modifier = Modifier
.padding(horizontal = 20.dp, vertical = 20.dp)
.fillMaxWidth(),
style = MaterialTheme.typography.titleMedium
)
}
}
@Preview(showBackground = true, device = Devices.PIXEL_4, showSystemUi = true)
@Composable
private fun SuccessPreview() {
ChuckNorrisJokesTheme {
JokeGeneratorSection(
JokeUiState.Success(
joke = Joke(
categories = emptyList(),
createdAt = "",
iconUrl = "",
id = "",
updatedAt = "",
url = "",
value = "Q: Which is heavier, a ton of bricks or a ton of feathers? A: Chuck Norris."
),
categories = listOf(),
selectedCategory = null
),
{}
) {}
}
}
@Preview(showBackground = true, device = Devices.PIXEL_4, showSystemUi = true)
@Composable
private fun FailurePreview() {
ChuckNorrisJokesTheme {
JokeGeneratorSection(
JokeUiState.Failure(
categories = emptyList(),
selectedCategory = null,
message = "Joke couldn't be fetched."
), {}
) {}
}
}
@Preview(showBackground = true, device = Devices.PIXEL_4, showSystemUi = true)
@Composable
private fun LoadingPreview() {
ChuckNorrisJokesTheme {
JokeGeneratorSection(
JokeUiState.Loading(categories = emptyList(), selectedCategory = null), {}
) {}
}
}
@Preview
@Composable
private fun JokeCategoryPreview() {
ChuckNorrisJokesTheme {
JokeCategory(category = "general", isSelected = false) {}
}
}
| 0
|
Kotlin
|
0
| 1
|
9a4b981c6bb030d778b5eb8599959f0bdc47e715
| 7,713
|
Chuck-Norris-Jokes
|
Apache License 2.0
|
src/main/kotlin/icu/windea/pls/localisation/editor/ParadoxLocalisationColorSettingsPage.kt
|
DragonKnightOfBreeze
| 328,104,626
| false
| null |
package icu.windea.pls.localisation.editor
import com.intellij.openapi.fileTypes.*
import com.intellij.openapi.options.colors.*
import icu.windea.pls.*
import icu.windea.pls.localisation.*
import icu.windea.pls.localisation.highlighter.*
class ParadoxLocalisationColorSettingsPage : ColorSettingsPage {
companion object{
private val attributesDescriptors = arrayOf(
AttributesDescriptor(PlsBundle.message("localisation.displayName.operator"), ParadoxLocalisationAttributesKeys.OPERATOR_KEY),
AttributesDescriptor(PlsBundle.message("localisation.displayName.marker"), ParadoxLocalisationAttributesKeys.MARKER_KEY),
AttributesDescriptor(PlsBundle.message("localisation.displayName.comment"), ParadoxLocalisationAttributesKeys.COMMENT_KEY),
AttributesDescriptor(PlsBundle.message("localisation.displayName.number"), ParadoxLocalisationAttributesKeys.NUMBER_KEY),
AttributesDescriptor(PlsBundle.message("localisation.displayName.locale"), ParadoxLocalisationAttributesKeys.LOCALE_KEY),
AttributesDescriptor(PlsBundle.message("localisation.displayName.propertyKey"), ParadoxLocalisationAttributesKeys.PROPERTY_KEY_KEY),
AttributesDescriptor(PlsBundle.message("localisation.displayName.string"), ParadoxLocalisationAttributesKeys.STRING_KEY),
AttributesDescriptor(PlsBundle.message("localisation.displayName.propertyReference"), ParadoxLocalisationAttributesKeys.PROPERTY_REFERENCE_KEY),
AttributesDescriptor(PlsBundle.message("localisation.displayName.icon"), ParadoxLocalisationAttributesKeys.ICON_KEY),
AttributesDescriptor(PlsBundle.message("localisation.displayName.iconParameter"), ParadoxLocalisationAttributesKeys.ICON_PARAMETER_KEY),
AttributesDescriptor(PlsBundle.message("localisation.displayName.commandScope"), ParadoxLocalisationAttributesKeys.COMMAND_SCOPE_KEY),
AttributesDescriptor(PlsBundle.message("localisation.displayName.commandField"), ParadoxLocalisationAttributesKeys.COMMAND_FIELD_KEY),
AttributesDescriptor(PlsBundle.message("localisation.displayName.color"), ParadoxLocalisationAttributesKeys.COLOR_KEY),
AttributesDescriptor(PlsBundle.message("localisation.displayName.validEscape"), ParadoxLocalisationAttributesKeys.VALID_ESCAPE_KEY),
AttributesDescriptor(PlsBundle.message("localisation.displayName.invalidEscape"), ParadoxLocalisationAttributesKeys.INVALID_ESCAPE_KEY),
AttributesDescriptor(PlsBundle.message("localisation.displayName.badCharacter"), ParadoxLocalisationAttributesKeys.BAD_CHARACTER_KEY),
AttributesDescriptor(PlsBundle.message("localisation.displayName.localisation"), ParadoxLocalisationAttributesKeys.LOCALISATION_KEY),
AttributesDescriptor(PlsBundle.message("localisation.displayName.syncedLocalisation"), ParadoxLocalisationAttributesKeys.SYNCED_LOCALISATION_KEY)
)
}
override fun getHighlighter() = SyntaxHighlighterFactory.getSyntaxHighlighter(ParadoxLocalisationLanguage, null, null)
override fun getAdditionalHighlightingTagToDescriptorMap() = null
override fun getIcon() = PlsIcons.ParadoxLocalisationFile
override fun getAttributeDescriptors() = attributesDescriptors
override fun getColorDescriptors() = ColorDescriptor.EMPTY_ARRAY
override fun getDisplayName() = paradoxLocalisationName
override fun getDemoText() = paradoxLocalisationColorSettingsDemoText
}
| 1
|
Kotlin
|
1
| 7
|
037b9b4ba467ed49ea221b99efb0a26cd630bb67
| 3,301
|
Paradox-Language-Support
|
MIT License
|
tools/diff-cli/src/commonMain/kotlin/io/matthewnelson/diff/cli/internal/apply/Apply.kt
|
05nelsonm
| 439,021,869
| false
| null |
/*
* 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.
**/
package io.matthewnelson.diff.cli.internal.apply
import io.matthewnelson.diff.cli.internal.ArgDiffFile
import io.matthewnelson.diff.cli.internal.ArgDiffFile.Companion.diffFileArgument
import io.matthewnelson.diff.cli.internal.OptQuiet.Companion.quietOption
import io.matthewnelson.diff.cli.internal.Subcommand
import io.matthewnelson.diff.core.Diff
import io.matthewnelson.diff.core.Options
import kotlinx.cli.ArgType
import kotlinx.cli.default
internal class Apply: Subcommand(
name = NAME_CMD,
description = """
Applies a diff to it's associated file.
$NAME_FILE is modified in place.
""",
additionalIndent = 7,
), ArgDiffFile
{
override val diffFileArg: String by diffFileArgument(
description = "The previously created diff file to be applied (e.g. /path/to/diffs/file.diff)",
)
private val fileArg: String by argument(
type = ArgType.String,
fullName = NAME_FILE,
description = "The file to apply the diff to (e.g. /path/to/unsigned/file)",
)
private val dryRunOpt: Boolean by option(
type = ArgType.Boolean,
fullName = "dry-run",
description = "Will apply the diff to its associated file, but leaves the '.bak' in place instead of atomically moving it"
).default(false)
override val quietOpt: Boolean by quietOption()
override fun execute() {
Diff.apply(diffFileArg, fileArg, Options.Apply {
dryRun = dryRunOpt
})
with(settings()) {
if (dryRunOpt) {
println("Diff applied to [$fileArg.bak]")
} else {
println("Diff applied to [$fileArg]")
}
}
}
internal companion object {
internal const val NAME_CMD = "apply"
internal const val NAME_FILE = "file"
}
}
| 13
| null |
1
| 4
|
4daac97e3999aecfa1f6bfac5c125fc00d0cc3e4
| 2,434
|
kmp-tor-binary
|
Apache License 2.0
|
seskar/seskar-compiler-plugin/src/main/kotlin/seskar/compiler/union/backend/UnionTransformer.kt
|
turansky
| 279,976,108
| false
|
{"Kotlin": 59449, "Shell": 286}
|
package seskar.compiler.union.backend
import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.declarations.IrClass
import org.jetbrains.kotlin.ir.visitors.IrElementTransformer
internal class UnionTransformer(
private val context: IrPluginContext,
) : IrElementTransformer<ValueMode?> {
override fun visitClass(
declaration: IrClass,
data: ValueMode?,
): IrStatement {
val unionBody = declaration.toJsUnionBody()
if (unionBody != null) {
declaration.annotations += JsName(context, declaration, unionBody)
}
val mode = when {
declaration.isJsUnion()
-> ValueMode.ROOT
data == ValueMode.ROOT && declaration.isCompanion
-> ValueMode.COMPANION
else -> null
}
return super.visitClass(declaration, mode)
}
}
| 0
|
Kotlin
|
3
| 30
|
1a6f9c75347af4947f9e3358b721e14496494204
| 947
|
seskar
|
Apache License 2.0
|
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsmanageadjudicationsapi/services/reported/DamagesServiceTest.kt
|
ministryofjustice
| 416,301,250
| false
|
{"Kotlin": 1581794, "Dockerfile": 1411}
|
package uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.services.reported
import org.assertj.core.api.Assertions
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.mockito.ArgumentCaptor
import org.mockito.kotlin.any
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.controllers.draft.DamageRequestItem
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities.DamageCode
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities.ReportedAdjudication
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities.ReportedDamage
import java.time.LocalDateTime
import javax.persistence.EntityNotFoundException
class DraftDamagesServiceTest : ReportedAdjudicationTestBase() {
private val damagesService = DamagesService(
reportedAdjudicationRepository, offenceCodeLookupService, authenticationFacade
)
private val reportedAdjudication = entityBuilder.reportedAdjudication(dateTime = DATE_TIME_OF_INCIDENT)
.also {
it.damages = mutableListOf(
ReportedDamage(code = DamageCode.CLEANING, details = "details", reporter = "Rod"),
ReportedDamage(code = DamageCode.REDECORATION, details = "details 3", reporter = "Fred")
)
}
@BeforeEach
fun init() {
whenever(reportedAdjudicationRepository.findByReportNumber(any())).thenReturn(reportedAdjudication)
whenever(reportedAdjudicationRepository.save(any())).thenReturn(reportedAdjudication)
whenever(authenticationFacade.currentUsername).thenReturn("Fred")
reportedAdjudication.createdByUserId = "Jane"
reportedAdjudication.createDateTime = LocalDateTime.now()
}
@Test
fun `update damages for adjudication`() {
val response = damagesService.updateDamages(
1,
listOf(
DamageRequestItem(
reportedAdjudication.damages.first().code,
reportedAdjudication.damages.first().details,
reportedAdjudication.damages.first().reporter
),
DamageRequestItem(DamageCode.ELECTRICAL_REPAIR, "details 2", "Fred")
)
)
val argumentCaptor = ArgumentCaptor.forClass(ReportedAdjudication::class.java)
verify(reportedAdjudicationRepository).save(argumentCaptor.capture())
assertThat(argumentCaptor.value.damages.size).isEqualTo(2)
assertThat(argumentCaptor.value.damages.first().code).isEqualTo(DamageCode.CLEANING)
assertThat(argumentCaptor.value.damages.first().details).isEqualTo("details")
assertThat(argumentCaptor.value.damages.first().reporter).isEqualTo("Rod")
assertThat(argumentCaptor.value.damages.last().code).isEqualTo(DamageCode.ELECTRICAL_REPAIR)
assertThat(argumentCaptor.value.damages.last().details).isEqualTo("details 2")
assertThat(argumentCaptor.value.damages.last().reporter).isEqualTo("Fred")
assertThat(response).isNotNull
}
@Test
override fun `throws an entity not found if the reported adjudication for the supplied id does not exists`() {
whenever(reportedAdjudicationRepository.findByReportNumber(any())).thenReturn(null)
Assertions.assertThatThrownBy {
damagesService.updateDamages(1, listOf(DamageRequestItem(DamageCode.CLEANING, "details")))
}.isInstanceOf(EntityNotFoundException::class.java)
.hasMessageContaining("ReportedAdjudication not found for 1")
}
}
| 4
|
Kotlin
|
0
| 3
|
d0495310b909bde1bd21f78edcac586fa2ff87b4
| 3,455
|
hmpps-manage-adjudications-api
|
MIT License
|
microservices-kotlin/src/main/kotlin/br/com/ivisondsb/controllers/MathController.kt
|
ivisondsb
| 870,804,861
| false
|
{"Kotlin": 2222}
|
package br.com.ivisondsb.controllers
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RestController
@RestController
class MathController {
@GetMapping(value = ["/sum/{numberOne}/{numberTwo}"])
fun sum(
@PathVariable(value = "numberOne") numberOne: String?,
@PathVariable(value = "numberTwo") numberTwo: String?
): Double {
if (!isNumeric(numberOne) || !isNumeric(numberTwo)) throw Exception()
return convertToDouble(numberOne) + convertToDouble(numberTwo)
}
private fun convertToDouble(strNumber: String?): Double {
if (strNumber.isNullOrBlank()) return 0.0
val number = strNumber.replace(",".toRegex(), ".")
return if (isNumeric(number)) number.toDouble() else 0.0
}
private fun isNumeric(strNumber: String?): Boolean {
if (strNumber.isNullOrBlank()) return false
val number = strNumber.replace(",".toRegex(), ".")
return number.matches("""[-+]?[0-9]*\.?[0-9]+""".toRegex())
}
}
| 0
|
Kotlin
|
0
| 0
|
13a8091969270c4cd25433e91cdbe941413555d6
| 1,114
|
microservices-kotlin
|
Apache License 2.0
|
collect_app/src/main/java/org/odk/collect/android/formentry/FormEntryUseCases.kt
|
getodk
| 40,213,809
| false
|
{"Java": 3378614, "Kotlin": 2749754, "JavaScript": 2830, "Shell": 2689}
|
package org.odk.collect.android.formentry
import org.apache.commons.io.FileUtils.readFileToByteArray
import org.javarosa.core.model.FormDef
import org.javarosa.core.model.instance.InstanceInitializationFactory
import org.javarosa.core.model.instance.TreeReference
import org.javarosa.core.model.instance.utils.DefaultAnswerResolver
import org.javarosa.core.reference.ReferenceManager
import org.javarosa.form.api.FormEntryController
import org.javarosa.xform.parse.XFormParser
import org.javarosa.xform.util.XFormUtils
import org.odk.collect.android.dynamicpreload.ExternalAnswerResolver
import org.odk.collect.android.javarosawrapper.FailedValidationResult
import org.odk.collect.android.javarosawrapper.FormController
import org.odk.collect.android.javarosawrapper.JavaRosaFormController
import org.odk.collect.android.utilities.FileUtils
import org.odk.collect.android.utilities.FormUtils
import org.odk.collect.entities.EntitiesRepository
import org.odk.collect.forms.Form
import org.odk.collect.forms.FormsRepository
import org.odk.collect.forms.instances.Instance
import org.odk.collect.forms.instances.InstancesRepository
import java.io.File
object FormEntryUseCases {
fun loadFormDef(
instance: Instance,
formsRepository: FormsRepository,
projectRootDir: File,
formDefCache: FormDefCache
): Pair<FormDef, Form>? {
val form =
formsRepository.getAllByFormIdAndVersion(instance.formId, instance.formVersion).firstOrNull()
return if (form == null) {
null
} else {
val formDef = loadFormDef(form, projectRootDir, formDefCache)
return if (formDef == null) {
null
} else {
Pair(formDef, form)
}
}
}
fun loadFormDef(
form: Form,
projectRootDir: File,
formDefCache: FormDefCache
): FormDef? {
val xForm = File(form.formFilePath)
if (!xForm.exists()) {
return null
}
val formMediaDir = File(form.formMediaPath)
FormUtils.setupReferenceManagerForForm(
ReferenceManager.instance(),
projectRootDir,
formMediaDir
)
return createFormDefFromCacheOrXml(xForm, formDefCache)!!
}
fun loadBlankForm(
form: Form,
formEntryController: FormEntryController,
instanceFile: File
): FormController {
val instanceInit = InstanceInitializationFactory()
formEntryController.model.form.initialize(true, instanceInit)
return JavaRosaFormController(
File(form.formMediaPath),
formEntryController,
instanceFile
)
}
@JvmStatic
fun loadDraft(
form: Form,
instance: Instance,
formEntryController: FormEntryController
): FormController? {
val instanceInit = InstanceInitializationFactory()
val instanceFile = File(instance.instanceFilePath)
if (!instanceFile.exists()) {
return null
}
importInstance(instanceFile, formEntryController)
formEntryController.model.form.initialize(false, instanceInit)
return JavaRosaFormController(
File(form.formMediaPath),
formEntryController,
instanceFile
)
}
fun saveDraft(
form: Form,
formController: FormController,
instancesRepository: InstancesRepository
): Instance {
saveFormToDisk(formController)
return instancesRepository.save(
Instance.Builder()
.formId(form.formId)
.formVersion(form.version)
.instanceFilePath(formController.getInstanceFile()!!.absolutePath)
.status(Instance.STATUS_INCOMPLETE)
.build()
)
}
@JvmStatic
fun finalizeDraft(
formController: FormController,
instancesRepository: InstancesRepository,
entitiesRepository: EntitiesRepository
): Instance? {
val instance =
getInstanceFromFormController(formController, instancesRepository)!!
val valid = finalizeInstance(formController, entitiesRepository)
return if (valid) {
saveFormToDisk(formController)
val instanceName = formController.getSubmissionMetadata()?.instanceName
instancesRepository.save(
Instance.Builder(instance)
.status(Instance.STATUS_COMPLETE)
.canEditWhenComplete(formController.isSubmissionEntireForm())
.displayName(instanceName ?: instance.displayName)
.build()
)
} else {
instancesRepository.save(
Instance.Builder(instance)
.status(Instance.STATUS_INVALID)
.build()
)
null
}
}
private fun getInstanceFromFormController(
formController: FormController,
instancesRepository: InstancesRepository
): Instance? {
val instancePath = formController.getInstanceFile()!!.absolutePath
return instancesRepository.getOneByPath(instancePath)
}
private fun saveFormToDisk(formController: FormController) {
val payload = formController.getSubmissionXml()
FileUtils.write(formController.getInstanceFile(), payload!!.payloadBytes)
}
@JvmStatic
private fun finalizeInstance(
formController: FormController,
entitiesRepository: EntitiesRepository
): Boolean {
val validationResult = formController.validateAnswers(false)
if (validationResult is FailedValidationResult) {
return false
}
formController.finalizeForm()
formController.getEntities().forEach { entity -> entitiesRepository.save(entity) }
return true
}
private fun createFormDefFromCacheOrXml(xForm: File, formDefCache: FormDefCache): FormDef? {
val formDefFromCache = formDefCache.readCache(xForm)
if (formDefFromCache != null) {
return formDefFromCache
}
val lastSavedSrc = FileUtils.getOrCreateLastSavedSrc(xForm)
return XFormUtils.getFormFromFormXml(xForm.absolutePath, lastSavedSrc)?.also {
formDefCache.writeCache(it, xForm.path)
}
}
private fun importInstance(instanceFile: File, formEntryController: FormEntryController) {
// convert files into a byte array
val fileBytes = readFileToByteArray(instanceFile)
// get the root of the saved and template instances
val savedRoot = XFormParser.restoreDataModel(fileBytes, null).root
val templateRoot = formEntryController.model.form.instance.root.deepCopy(true)
// weak check for matching forms
if (savedRoot.name != templateRoot.name || savedRoot.mult != 0) {
return
}
// populate the data model
val tr = TreeReference.rootRef()
tr.add(templateRoot.name, TreeReference.INDEX_UNBOUND)
// Here we set the Collect's implementation of the IAnswerResolver.
// We set it back to the default after select choices have been populated.
XFormParser.setAnswerResolver(ExternalAnswerResolver())
templateRoot.populate(savedRoot, formEntryController.model.form)
XFormParser.setAnswerResolver(DefaultAnswerResolver())
// FormInstanceParser.parseInstance is responsible for initial creation of instances. It explicitly sets the
// main instance name to null so we force this again on deserialization because some code paths rely on the main
// instance not having a name. Must be before the call on setRoot because setRoot also sets the root's name.
formEntryController.model.form.instance.name = null
// populated model to current form
formEntryController.model.form.instance.root = templateRoot
// fix any language issues
// :
// http://bitbucket.org/javarosa/main/issue/5/itext-n-appearing-in-restored-instances
if (formEntryController.model.languages != null) {
formEntryController.model.form
.localeChanged(
formEntryController.model.language,
formEntryController.model.form.localizer
)
}
}
}
| 283
|
Java
|
1372
| 717
|
63050fdd265c42f3c340f0ada5cdff3c52a883bc
| 8,427
|
collect
|
Apache License 2.0
|
app/shared/state-machine/ui/public/src/commonMain/kotlin/build/wallet/statemachine/fwup/FwupUpdateErrorModel.kt
|
proto-at-block
| 761,306,853
| false
|
{"C": 10424094, "Kotlin": 7156393, "Rust": 2046237, "Swift": 700307, "Python": 331492, "HCL": 271992, "Shell": 111209, "TypeScript": 102700, "C++": 64770, "Meson": 64234, "JavaScript": 36227, "Just": 28071, "Ruby": 9428, "Dockerfile": 5731, "Makefile": 3839, "Open Policy Agent": 1552, "Procfile": 80}
|
package build.wallet.statemachine.fwup
import build.wallet.analytics.events.screen.id.FwupEventTrackerScreenId
import build.wallet.platform.device.DeviceInfo
import build.wallet.platform.device.DevicePlatform.IOS
import build.wallet.statemachine.core.ButtonDataModel
import build.wallet.statemachine.core.ErrorFormBottomSheetModel
import build.wallet.statemachine.core.SheetModel
/**
* @param deviceInfoProvider: Provides information about the phone in order to customize messaging.
* @param wasInProgress: Whether or not the FWUP was in progress before the error occurred.
*/
fun FwupUpdateErrorModel(
deviceInfo: DeviceInfo,
wasInProgress: Boolean,
onClosed: () -> Unit,
onRelaunchFwup: () -> Unit,
) = when (wasInProgress) {
true -> InProgressFwupUpdateErrorModel(deviceInfo, onClosed, onRelaunchFwup)
false -> NotInProgressFwupUpdateErrorModel(deviceInfo, onClosed)
}
private fun InProgressFwupUpdateErrorModel(
deviceInfo: DeviceInfo,
onClosed: () -> Unit,
onRelaunchFwup: () -> Unit,
): SheetModel {
val iosInProgressSubline = "$BASE_SUBLINE Continue the update to resume where it left off."
val isAirplaneModeRecommendedForDevice = deviceInfo.isAirplaneModeRecommendedForDevice()
return ErrorFormBottomSheetModel(
onClosed = onClosed,
title = "Device update not complete",
subline =
when (deviceInfo.devicePlatform) {
IOS ->
if (isAirplaneModeRecommendedForDevice) {
"$iosInProgressSubline\n\n$iOS_AIRPLANE_MODE_MESSAGE"
} else {
iosInProgressSubline
}
else -> BASE_SUBLINE
},
// On iOS, we encourage the customer to retry the update directly from the error sheet.
primaryButton =
when (deviceInfo.devicePlatform) {
IOS -> ButtonDataModel(text = "Continue", onClick = onRelaunchFwup)
else -> ButtonDataModel(text = "Got it", onClick = onClosed)
},
eventTrackerScreenId = FwupEventTrackerScreenId.FWUP_UPDATE_ERROR_SHEET
)
}
private fun NotInProgressFwupUpdateErrorModel(
deviceInfo: DeviceInfo,
onClosed: () -> Unit,
): SheetModel {
val isAirplaneModeRecommendedForDevice = deviceInfo.isAirplaneModeRecommendedForDevice()
return ErrorFormBottomSheetModel(
onClosed = onClosed,
title = "Unable to update device",
subline =
if (isAirplaneModeRecommendedForDevice) {
"$BASE_SUBLINE\n\n$iOS_AIRPLANE_MODE_MESSAGE"
} else {
BASE_SUBLINE
},
primaryButton = ButtonDataModel(text = "Got it", onClick = onClosed),
eventTrackerScreenId = FwupEventTrackerScreenId.FWUP_UPDATE_ERROR_SHEET
)
}
// Common subline to use that will be further added to for specific device models
const val BASE_SUBLINE =
"Make sure you hold your device to the back of your phone during the entire update."
@Suppress("TopLevelPropertyNaming")
const val iOS_AIRPLANE_MODE_MESSAGE =
"If problems persist, turn on Airplane Mode to minimize interruptions."
| 0
|
C
|
10
| 98
|
1f9f2298919dac77e6791aa3f1dbfd67efe7f83c
| 2,965
|
bitkey
|
MIT License
|
app/src/main/java/com/therxmv/dirolreader/domain/usecase/client/CreateClientUseCase.kt
|
therxmv
| 651,629,829
| false
|
{"Kotlin": 163264}
|
package com.therxmv.dirolreader.domain.usecase.client
import com.therxmv.dirolreader.domain.repository.ClientRepository
import org.drinkless.td.libcore.telegram.Client.ResultHandler
class CreateClientUseCase(private val clientRepository: ClientRepository) {
operator fun invoke(updateHandler: ResultHandler) =
clientRepository.createClient(updateHandler)
}
| 1
|
Kotlin
|
0
| 22
|
9e6428cdc18a79b8cb5168d1966aa2869f997700
| 370
|
Dirol-Reader
|
MIT License
|
sketch-compose/src/main/kotlin/com/github/panpf/sketch/compose/SingletonAsyncImagePainter.kt
|
panpf
| 14,798,941
| false
|
{"Kotlin": 3225805, "Shell": 724}
|
/*
* Copyright (C) 2022 panpf <panpfpanpf@outlook.com>
*
* 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.github.panpf.sketch.compose
import androidx.compose.foundation.Image
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.runtime.Composable
import androidx.compose.runtime.NonRestartableComposable
import androidx.compose.ui.graphics.FilterQuality
import androidx.compose.ui.graphics.drawscope.DrawScope.Companion.DefaultFilterQuality
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.Constraints
import com.github.panpf.sketch.compose.AsyncImageState.Companion.DefaultTransform
import com.github.panpf.sketch.request.DisplayRequest
import com.github.panpf.sketch.sketch
/**
* Return an [AsyncImagePainter] that executes an [DisplayRequest] asynchronously and renders the result.
*
* **This is a lower-level API than [AsyncImage] and may not work as expected in all situations. **
*
* - [AsyncImagePainter] will not finish loading if [AsyncImagePainter.onDraw] is not called.
* This can occur if a composable has an unbounded (i.e. [Constraints.Infinity]) width/height
* constraint. For example, to use [AsyncImagePainter] with [LazyRow] or [LazyColumn], you must
* set a bounded width or height respectively using `Modifier.width` or `Modifier.height`.
* - [AsyncImageState.painterState] will not transition to [PainterState.Success] synchronously during the
* composition phase. Use [SubcomposeAsyncImage] or set a custom [DisplayRequest.Builder.resizeSize] value
* (e.g. `resizeSize(Size(100, 100))`) if you need this.
*
* @param imageUri [DisplayRequest.uriString] value.
* @param state [AsyncImageState] that will be used to store the state of the request.
* @param placeholder A [Painter] that is displayed while the image is loading.
* @param error A [Painter] that is displayed when the image request is unsuccessful.
* @param uriEmpty A [Painter] that is displayed when the request's [DisplayRequest.uriString] is empty.
* @param onLoading Called when the image request begins loading.
* @param onSuccess Called when the image request completes successfully.
* @param onError Called when the image request completes unsuccessfully.
* @param contentScale Used to determine the aspect ratio scaling to be used if the canvas bounds
* are a different size from the intrinsic size of the image loaded by [imageUri]. This should be set
* to the same value that's passed to [Image].
* @param filterQuality Sampling algorithm applied to a bitmap when it is scaled and drawn into the
* destination.
*/
@Composable
@NonRestartableComposable
fun rememberAsyncImagePainter(
imageUri: String?,
state: AsyncImageState = rememberAsyncImageState(),
placeholder: Painter? = null,
error: Painter? = null,
uriEmpty: Painter? = error,
onLoading: ((PainterState.Loading) -> Unit)? = null,
onSuccess: ((PainterState.Success) -> Unit)? = null,
onError: ((PainterState.Error) -> Unit)? = null,
contentScale: ContentScale = ContentScale.Fit,
filterQuality: FilterQuality = DefaultFilterQuality,
): AsyncImagePainter = rememberAsyncImagePainter(
imageUri = imageUri,
sketch = LocalContext.current.sketch,
state = state,
placeholder = placeholder,
uriEmpty = uriEmpty,
onLoading = onLoading,
onSuccess = onSuccess,
onError = onError,
contentScale = contentScale,
filterQuality = filterQuality,
)
/**
* Return an [AsyncImagePainter] that executes an [DisplayRequest] asynchronously and renders the result.
*
* **This is a lower-level API than [AsyncImage] and may not work as expected in all situations. **
*
* - [AsyncImagePainter] will not finish loading if [AsyncImagePainter.onDraw] is not called.
* This can occur if a composable has an unbounded (i.e. [Constraints.Infinity]) width/height
* constraint. For example, to use [AsyncImagePainter] with [LazyRow] or [LazyColumn], you must
* set a bounded width or height respectively using `Modifier.width` or `Modifier.height`.
* - [AsyncImageState.painterState] will not transition to [PainterState.Success] synchronously during the
* composition phase. Use [SubcomposeAsyncImage] or set a custom [DisplayRequest.Builder.resizeSize] value
* (e.g. `resizeSize(Size(100, 100))`) if you need this.
*
* @param imageUri [DisplayRequest.uriString] value.
* @param state [AsyncImageState] that will be used to store the state of the request.
* @param transform A callback to transform a new [PainterState] before it's applied to the
* [AsyncImagePainter]. Typically this is used to overwrite the state's [Painter].
* @param onPainterState Called when the painterState changes.
* @param contentScale Used to determine the aspect ratio scaling to be used if the canvas bounds
* are a different size from the intrinsic size of the image loaded by [imageUri]. This should be set
* to the same value that's passed to [Image].
* @param filterQuality Sampling algorithm applied to a bitmap when it is scaled and drawn into the
* destination.
*/
@Composable
@NonRestartableComposable
fun rememberAsyncImagePainter(
imageUri: String?,
state: AsyncImageState = rememberAsyncImageState(),
transform: (PainterState) -> PainterState = DefaultTransform,
onPainterState: ((PainterState) -> Unit)? = null,
contentScale: ContentScale = ContentScale.Fit,
filterQuality: FilterQuality = DefaultFilterQuality,
): AsyncImagePainter = rememberAsyncImagePainter(
imageUri = imageUri,
sketch = LocalContext.current.sketch,
state = state,
transform = transform,
onPainterState = onPainterState,
contentScale = contentScale,
filterQuality = filterQuality
)
/**
* Return an [AsyncImagePainter] that executes an [DisplayRequest] asynchronously and renders the result.
*
* **This is a lower-level API than [AsyncImage] and may not work as expected in all situations. **
*
* - [AsyncImagePainter] will not finish loading if [AsyncImagePainter.onDraw] is not called.
* This can occur if a composable has an unbounded (i.e. [Constraints.Infinity]) width/height
* constraint. For example, to use [AsyncImagePainter] with [LazyRow] or [LazyColumn], you must
* set a bounded width or height respectively using `Modifier.width` or `Modifier.height`.
* - [AsyncImageState.painterState] will not transition to [PainterState.Success] synchronously during the
* composition phase. Use [SubcomposeAsyncImage] or set a custom [DisplayRequest.Builder.resizeSize] value
* (e.g. `resizeSize(Size(100, 100))`) if you need this.
*
* @param request [DisplayRequest].
* @param state [AsyncImageState] that will be used to store the state of the request.
* @param placeholder A [Painter] that is displayed while the image is loading.
* @param error A [Painter] that is displayed when the image request is unsuccessful.
* @param uriEmpty A [Painter] that is displayed when the request's [DisplayRequest.uriString] is empty.
* @param onLoading Called when the image request begins loading.
* @param onSuccess Called when the image request completes successfully.
* @param onError Called when the image request completes unsuccessfully.
* @param contentScale Used to determine the aspect ratio scaling to be used if the canvas bounds
* are a different size from the intrinsic size of the image loaded by [request]. This should be set
* to the same value that's passed to [Image].
* @param filterQuality Sampling algorithm applied to a bitmap when it is scaled and drawn into the
* destination.
*/
@Composable
@NonRestartableComposable
fun rememberAsyncImagePainter(
request: DisplayRequest,
state: AsyncImageState = rememberAsyncImageState(),
placeholder: Painter? = null,
error: Painter? = null,
uriEmpty: Painter? = error,
onLoading: ((PainterState.Loading) -> Unit)? = null,
onSuccess: ((PainterState.Success) -> Unit)? = null,
onError: ((PainterState.Error) -> Unit)? = null,
contentScale: ContentScale = ContentScale.Fit,
filterQuality: FilterQuality = DefaultFilterQuality,
): AsyncImagePainter = rememberAsyncImagePainter(
request = request,
sketch = LocalContext.current.sketch,
state = state,
placeholder = placeholder,
error = error,
uriEmpty = uriEmpty,
onLoading = onLoading,
onSuccess = onSuccess,
onError = onError,
contentScale = contentScale,
filterQuality = filterQuality,
)
/**
* Return an [AsyncImagePainter] that executes an [DisplayRequest] asynchronously and renders the result.
*
* **This is a lower-level API than [AsyncImage] and may not work as expected in all situations. **
*
* - [AsyncImagePainter] will not finish loading if [AsyncImagePainter.onDraw] is not called.
* This can occur if a composable has an unbounded (i.e. [Constraints.Infinity]) width/height
* constraint. For example, to use [AsyncImagePainter] with [LazyRow] or [LazyColumn], you must
* set a bounded width or height respectively using `Modifier.width` or `Modifier.height`.
* - [AsyncImageState.painterState] will not transition to [PainterState.Success] synchronously during the
* composition phase. Use [SubcomposeAsyncImage] or set a custom [DisplayRequest.Builder.resizeSize] value
* (e.g. `resizeSize(Size(100, 100))`) if you need this.
*
* @param request [DisplayRequest].
* @param state [AsyncImageState] that will be used to store the state of the request.
* @param transform A callback to transform a new [PainterState] before it's applied to the
* [AsyncImagePainter]. Typically this is used to overwrite the state's [Painter].
* @param onPainterState Called when the painterState changes.
* @param contentScale Used to determine the aspect ratio scaling to be used if the canvas bounds
* are a different size from the intrinsic size of the image loaded by [request]. This should be set
* to the same value that's passed to [Image].
* @param filterQuality Sampling algorithm applied to a bitmap when it is scaled and drawn into the
* destination.
*/
@Composable
@NonRestartableComposable
fun rememberAsyncImagePainter(
request: DisplayRequest,
state: AsyncImageState = rememberAsyncImageState(),
transform: (PainterState) -> PainterState = DefaultTransform,
onPainterState: ((PainterState) -> Unit)? = null,
contentScale: ContentScale = ContentScale.Fit,
filterQuality: FilterQuality = DefaultFilterQuality,
): AsyncImagePainter = rememberAsyncImagePainter(
request = request,
sketch = LocalContext.current.sketch,
state = state,
transform = transform,
onPainterState = onPainterState,
contentScale = contentScale,
filterQuality = filterQuality
)
| 1
|
Kotlin
|
308
| 1,978
|
82ffde1ff148311bb5b36eb70a4c82224d1f3af4
| 11,384
|
sketch
|
Apache License 2.0
|
app/src/main/java/com/okta/idx/android/directauth/sdk/forms/SelectFactorForm.kt
|
okta
| 331,106,204
| false
| null |
/*
* Copyright 2021-Present Okta, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.okta.idx.android.directauth.sdk.forms
import com.okta.idx.android.directauth.sdk.Form
import com.okta.idx.android.directauth.sdk.FormAction
import com.okta.idx.sdk.api.client.Authenticator
import com.okta.idx.sdk.api.model.AuthenticationStatus
class SelectFactorForm internal constructor(
val viewModel: ViewModel,
private val formAction: FormAction,
) : Form {
class ViewModel internal constructor(
val factors: List<Authenticator.Factor>,
val canSkip: Boolean,
val title: String,
)
fun select(factor: Authenticator.Factor) {
formAction.proceed {
val response = authenticationWrapper.selectFactor(
proceedContext,
factor
)
handleTerminalTransitions(response)
when (response.authenticationStatus) {
AuthenticationStatus.AWAITING_AUTHENTICATOR_VERIFICATION_DATA -> {
verifyForm(response)
}
AuthenticationStatus.AWAITING_AUTHENTICATOR_ENROLLMENT_DATA -> {
registerVerifyForm(response, factor)
}
else -> handleKnownTransitions(response)
}
}
}
fun skip() {
formAction.skip()
}
fun signOut() {
formAction.signOut()
}
}
| 2
|
Kotlin
|
11
| 8
|
4fb9da487db591f35d8bf1e7baf6c389d035febe
| 1,941
|
okta-idx-android
|
Apache License 2.0
|
src/main/kotlin/nl/meine/aoc/_2023/Day7.kt
|
mtoonen
| 158,697,380
| false
|
{"Kotlin": 201978, "Java": 138385}
|
package nl.meine.aoc._2023
class Day7 {
fun one(input: String): Int {
val lines = createHands(input)
val h = orderHands(lines)
h.forEach { println(it) }
return h.mapIndexed { rank, hand -> (rank + 1) * hand.bid }
.sum()
}
fun createHands(input: String): MutableList<Hand> {
return input.split("\n")
.map { it.split(" ") }
.map { Hand(it[0].chunked(1).map { c -> Card.getCard(c) }.toList(), it[1].toInt()) }
.map { processJokers(it) }
.toMutableList()
}
fun orderHands(hand: MutableList<Hand>): MutableList<Hand> {
hand.sort()
hand.reversed()
return hand
}
fun processJokers(hand: Hand): Hand {
val initial = hand.hand.filter { it.name != "J" }.groupingBy { it }.eachCount().toMutableMap()
if (initial.isEmpty()) {
initial[Card.A] = 0
}
val a = initial.maxBy { it.value }.key
initial[a] = initial[a]!! + hand.hand.count { it.name == "J" }
hand.counts = initial
return hand
}
fun two(input: String): Int {
val lines = createHands(input)
val h = orderHands(lines)
h.forEach { println(it) }
return h.mapIndexed { rank, hand -> (rank + 1) * hand.bid }
.sum()
}
}
// two: 250665479
// 250665248
fun main() {
val inputReal =
"""9A35J 469
75T32 237
6T8JQ 427
3366A 814
K2AK9 982
J8KTT 9
94936 970
Q8AK9 15
3QQ32 940
65555 484
8K88K 674
Q67T5 788
77575 476
KAKAA 785
AA3AA 240
44767 423
Q923A 300
KK444 650
QQQ6Q 313
5JA22 167
7A264 837
TTKTT 646
K62JJ 682
34A63 532
7J554 393
Q86T6 745
9963K 718
92K85 97
3KKJ3 604
98Q26 257
7AJ6Q 132
K48T5 125
554J4 408
T6333 178
5757J 479
8J222 488
KKJ6A 460
95T38 944
23J22 796
AK333 69
25AK9 978
77779 123
K9T83 56
46A39 730
655J5 77
A2T2A 78
J8Q75 847
QA82A 700
TTT67 443
KT9A5 343
6969T 582
A7779 703
3QA93 597
6JT6T 558
28888 290
26TT2 147
T9356 587
6T542 482
3J733 140
TQT72 534
3K3K3 208
5JA6J 833
64646 277
86K68 795
24455 997
3633K 504
K3K36 790
22KK2 731
AA8AA 991
A6666 312
38395 712
46J44 229
52529 268
49AA9 573
J7J94 258
87TKA 947
J2999 555
T9KJK 194
7KK3K 146
T255T 875
9QAT4 475
759A2 169
22322 510
27T69 299
644K6 4
44J84 227
6A722 806
775KJ 25
37425 679
7TA8T 226
3Q6TK 391
8T3J4 196
67534 339
5QQ55 565
J33A3 305
8A8AJ 732
2QQJ5 523
AAAJA 618
97733 858
2A6Q2 433
J8QT3 390
3333J 910
K2AK2 884
AQTTQ 810
55666 855
7Q7QJ 743
K8KK3 489
4AKKJ 619
QQKQQ 373
QJ59A 688
2687J 622
7Q77J 512
578A3 120
T2662 737
JKJK7 807
44T94 223
454Q5 607
75J58 551
A686J 763
TAT4T 108
75356 591
96989 977
K7KTK 775
5252Q 318
77A5A 599
22K87 359
JJQQQ 930
8TKT8 436
A9QQ8 374
4T2JA 30
777AJ 463
8J888 87
42K8Q 657
J5JJ5 713
AKQJ3 45
T59K4 765
22A77 266
K8KK8 219
6T666 349
72T7T 92
3JQJQ 964
AA2J9 672
66997 803
5A8A2 467
KKKQ7 98
67Q5J 669
J57A6 503
98347 331
6J668 279
9K7KK 319
84848 337
33353 974
A333T 576
66636 461
6AAA2 281
Q52QQ 691
7876A 892
533T8 966
5A9Q7 533
A6AAQ 21
688Q6 100
K8483 764
62865 453
39323 189
TTJJT 498
5J437 306
55A7A 876
9A366 562
8J479 249
65544 640
83T88 325
AK45A 321
39QQ3 849
83838 749
43394 602
33722 843
T5KTJ 428
JJKK9 549
33737 27
4KKK4 638
KK398 246
J6828 372
99229 23
2963K 577
3ATJJ 862
6488T 912
48554 903
3A353 627
86923 768
79A98 540
77TTT 965
TK2T7 188
2A644 687
QT943 253
K2QJT 887
J5KK5 915
9Q2JA 980
J237J 28
A46Q2 264
7T2TT 621
A4T8J 57
Q5QT5 217
K9AK7 248
TAJTT 973
82822 919
858AA 265
5555J 800
552J2 908
Q5248 272
A5KK5 529
K8J9T 85
888TT 477
665Q5 823
Q42AT 449
4843A 83
Q5476 885
Q52T2 409
6A2TJ 580
92A99 483
Q9Q6Q 734
36662 134
88899 401
KQQQ9 389
JQ259 658
57895 639
KQ654 852
94273 612
77KT7 987
3Q4AQ 364
6KQK6 651
4AQ23 163
34TTT 107
T98T2 870
J78Q9 756
3K3J3 404
J993J 328
Q8JQA 678
96759 326
2J22J 383
2T222 236
76666 772
QQ5QJ 225
A47AA 505
967TJ 924
Q3TJ4 63
2KK29 879
44Q4Q 685
TTQ9T 659
7244J 414
T22TJ 269
55552 3
J78TK 474
3J3J3 559
8QJ42 382
28T86 740
TKTT8 381
22J44 579
J8668 242
88TT6 709
KKKJ9 192
478K2 501
3Q66J 22
K9KAJ 774
K3333 113
4TJT4 945
Q55KK 609
Q7272 955
6AKAA 490
964T5 971
36Q3Q 51
3T9AT 969
Q8TQT 256
4A833 632
5499J 812
44222 176
6QQ6Q 317
TJT2T 206
A862Q 468
36663 464
54JK9 302
8J828 103
32QQ2 38
66675 595
2J8TQ 50
2QQQQ 783
333QQ 282
67KKK 511
2996J 518
J824K 44
K6656 726
Q7Q5T 793
KQ27T 494
T2KQA 308
AAAA2 441
24J49 716
K58TT 873
7TA49 39
6KQ7T 298
6Q555 455
66AJA 819
5A9A3 922
AAA88 170
42324 962
22Q22 616
44QJQ 399
9J3TA 342
56K3A 588
99T9A 224
56T66 869
77997 671
53222 161
8KKJT 384
37777 567
TKTK5 42
6J622 127
387Q5 417
T3A73 360
28AKA 868
K26Q5 288
J6J88 692
KKKK9 690
2A5QA 435
K83T4 158
QAA3A 104
T7Q66 914
A3A6A 270
J888J 838
3JTKQ 867
7KKKK 451
K7766 824
Q4Q9Q 620
65A33 957
99A9A 781
A9AAA 344
44744 935
6666J 804
A8QJ9 155
AQKAA 681
6K7KJ 853
A99JA 366
65JJ5 47
4TQ8T 769
66555 457
TJ226 222
78777 758
5K488 999
Q65T4 362
4Q738 80
5JJ55 323
8Q65A 918
A5TT5 353
294J3 471
33Q44 102
66668 254
7663Q 516
AAAJJ 798
3344J 10
85888 507
68868 144
588T5 124
TT4TT 834
QQ7QK 168
75555 593
849KA 446
9QT7A 165
5AA7A 697
J99J9 213
6834K 5
TQQQT 292
7A655 403
982AQ 143
A6237 334
QK5T6 963
99895 232
56366 376
34J35 231
AAQAQ 150
78887 485
QQQQJ 263
TAQ98 197
425J5 895
JQ7QQ 992
J9JJ9 61
5888J 665
6J6K6 496
78J82 293
22292 73
TT2TT 911
ATAAT 322
339AA 953
A7465 413
AA4AA 283
QT3TQ 84
QQA5Q 66
J472J 784
T3JTT 131
333A4 210
79299 550
88A8J 594
J9749 584
J735K 902
933JQ 109
5T926 481
4T4T4 561
87TK6 247
98964 159
78997 354
36JT4 29
59464 771
2AA5A 33
77J43 244
37T7T 448
23QJ3 925
K7K5Q 792
QQQQ9 411
KK568 278
49TK7 961
55TAA 817
33J4Q 984
5QJK9 105
9A9J9 623
AK62Q 842
38333 735
9A8J8 333
9T243 204
6K2J3 547
78JKQ 959
AA3A9 634
KJJKT 13
KJKKJ 921
99934 310
4J929 431
55559 445
TT62T 355
32K25 825
622A6 480
334Q9 412
26922 114
638KJ 900
364T8 462
QQJT7 234
TK586 525
K342K 816
TTT99 699
JT658 315
36388 24
2666J 185
53455 592
4AJAA 304
J3QQ8 228
22J2A 416
99768 927
TKJ9A 487
5A55J 744
QKQ44 613
336QA 81
66622 200
JTTTK 717
59ATT 513
33938 813
66AKJ 466
3976Q 941
8888T 491
JJK47 836
99Q7Q 654
Q896K 633
Q8JKQ 553
J6K6K 811
2T323 750
KKAKK 952
Q6JJ4 929
77J77 993
9KQJT 989
44254 857
4AA5A 514
TATJA 715
74422 145
33332 544
5T5QT 311
78JT8 913
JKKT2 94
26QK7 71
444JJ 287
99979 133
Q999Q 314
48888 649
33T8K 368
77T57 711
4T42Q 351
89Q99 89
69666 846
3A33A 890
8Q8A3 636
4A888 603
9TQTA 747
9AAA9 52
TJ4TT 267
J76J7 72
K773Q 370
77Q77 329
636QQ 575
ATQAA 917
2743Q 932
2KKKJ 452
93929 686
4ATTA 458
42222 252
35225 402
45JKA 160
4TAT6 201
7A278 839
4A7Q5 543
Q33T6 641
JQ99Q 238
A793A 86
78575 187
49T9T 303
8542K 198
25A82 786
77A77 363
244KK 397
87877 689
T6T6T 778
KKKK4 392
22T2J 171
T77A7 174
99KJK 180
2444J 761
QAQQA 508
3373T 121
222TT 137
736T2 8
4444J 12
33555 566
487A4 230
22626 439
QQQQ8 336
5T552 521
QTQQQ 872
63836 614
66695 450
AKAAA 361
95A95 111
644JK 701
ATAAA 840
9J99T 35
3333A 664
99992 99
5A5A5 680
Q7J5J 405
59999 954
2KTQ9 255
6QQ96 149
37333 67
QJ6Q3 425
Q6K29 415
J7277 126
AA29Q 220
AAKJK 831
27QQ2 986
AJ367 891
33292 666
Q8786 933
TAJ28 554
K4448 585
Q8225 931
46242 598
7AT98 693
78J56 369
TTTTJ 371
TKJKK 990
66767 802
56956 789
544K4 275
46699 215
26666 710
AQQQQ 116
6A858 757
55757 142
J2KA4 723
6229K 906
6K366 179
4378K 527
AA664 832
72242 499
2TT2Q 998
5QQQ5 647
5858J 856
555KJ 655
7788J 524
36J5J 82
99666 2
9AKK3 177
47447 596
9266J 572
4TTQ4 946
999J9 110
T74K4 899
Q27J8 156
98AK5 754
3TJ6T 396
75QK7 517
K22KJ 741
9699T 916
66QAQ 202
7329Q 32
89JAT 708
444Q4 841
73366 880
677QK 683
48J84 394
2966T 6
9KT9K 531
8544T 746
2222A 934
T2QKT 615
8J282 430
K9K9K 214
336TJ 904
9JTJ9 777
QKAKK 68
62A66 48
49499 280
97967 46
8T66T 273
94349 379
57777 719
2QT5K 827
4TTT2 40
J2252 859
A3TQA 426
468JA 611
57745 662
424AA 938
J33AT 309
99339 610
872KJ 570
K2395 571
77A5Q 996
JQ7Q6 340
973J9 776
J6K92 14
5J5Q9 191
Q5555 773
A7KA7 11
54545 851
AJ9A8 968
QQAJ7 821
T6JTT 670
3T2TT 151
TTTT3 886
33933 850
KKKQQ 656
T2TT2 54
QA44J 995
89J27 335
3742A 212
T7Q88 260
TT666 75
JKQ28 724
548T3 698
3883K 148
39966 864
69424 320
4QJ5J 332
J4297 346
78A66 605
82333 809
4K777 644
9739T 936
JJ433 755
88688 43
3TJ33 988
J37K3 628
3KK3T 583
A433J 195
89K46 262
JKKQK 545
7AA27 437
977T8 828
757Q7 759
7T7A8 805
33336 19
KJKKK 118
44445 586
84Q8K 205
439K3 909
6J663 762
33777 975
9AAQA 564
JJ8JJ 91
24555 696
62644 707
AA3J5 31
6T2KQ 135
24244 34
3QK3K 560
9J3T9 787
7QTA8 705
A22JA 528
84844 537
87667 937
QJ5K4 90
2K326 239
59878 421
7J377 536
857K7 350
2K2A2 704
39T9T 493
QKT86 829
3AQJT 714
7AAAJ 600
9QK56 983
35K33 193
89888 589
TQ477 432
777K7 59
86AQJ 17
QQQJ3 407
68K25 166
32288 748
TKTQK 65
J9K56 530
AA323 960
27266 112
22722 675
73367 497
Q7JJ3 16
444T4 438
22323 74
3QQ6K 348
A68J8 454
42K64 367
3AA7J 889
AT492 398
AAA6A 673
2Q9QQ 95
A7477 815
4A8KA 444
6JJ66 893
84445 429
7997J 101
A5A6A 958
K27A2 486
4A4J4 327
464TJ 434
5554J 766
KTKT8 801
573K5 64
JKK88 522
A9999 291
T787T 338
39648 502
46464 733
AQAAA 357
8TTTT 797
64444 515
8588T 53
AKAKK 617
8AJ99 888
3TAAJ 874
338Q3 694
TT443 578
86227 419
9J9JQ 736
22522 943
823J3 866
24444 519
A7A7A 207
5JJ99 36
K2896 250
66A5J 129
JJJJJ 668
8J548 721
J8J63 385
3Q442 79
8K868 141
AAA67 767
T968K 289
5QJ5K 245
TKQK5 96
54774 122
89666 568
95596 538
9K3J4 380
66665 20
7759A 209
6JTA6 702
29574 88
AA6A4 181
Q28T4 152
777KQ 386
47888 271
K8KKQ 738
J7337 162
JQA88 820
QQ4QQ 276
TKKTT 728
JTKTK 316
3J334 684
9944Q 830
8485A 753
JKKJ8 221
A9QJ6 948
KJ3KQ 727
Q5QQQ 695
Q8QTQ 542
2QQQ8 119
JJ55Q 845
52725 950
QAJ33 808
JAA7J 557
Q22AA 183
Q8Q8Q 661
J55JT 410
KKQJJ 901
Q5455 539
AQJJ9 956
7QJ7T 896
K5KKJ 994
388KK 822
2QQ2K 218
3J4K3 285
256K7 923
K2KKA 157
QQTKQ 139
48TTT 1
TTT44 770
JJ777 898
Q466K 117
TQ4QQ 172
43333 883
855T3 324
8T933 645
579K9 347
A76Q4 729
3TTT3 115
QJAQA 928
65T65 541
77A7A 625
29J9J 472
TKT74 926
A934K 643
JT533 199
TT4AJ 216
KKKK6 55
6J3K5 676
398J3 18
778K8 653
79773 406
25446 606
54323 76
2T992 601
8A888 241
9AJQK 509
3Q3QK 739
KKKK8 667
JJ494 590
83JKT 203
J9957 751
JJAQQ 296
4835Q 301
333T3 722
KKK2K 535
8Q2QJ 378
5J396 652
TQ7J8 624
5JJ22 447
TT777 62
TTJT7 60
TA2QT 626
T3Q79 791
K6QQ8 294
28K52 967
6K374 663
7877A 495
24226 352
88KAK 907
J242T 546
K77JT 465
Q77Q5 863
TQTQT 284
49K62 26
6TTT8 569
Q77QQ 779
99T6T 70
K4AKA 130
J5TT5 979
KQJT8 175
96K99 648
A56J3 422
53585 58
6QJTQ 794
9QJ77 388
88944 235
55A2Q 780
9Q992 297
96699 660
682QJ 865
6TTTK 799
Q47QQ 358
2929K 920
J5535 752
T3383 631
6737Q 894
9QT72 440
844J9 470
6AA6A 211
5AA5A 981
8KJ88 49
55855 93
5J495 261
8QQQ5 629
J4493 860
ATTKA 818
77264 877
55K58 365
QQ666 106
238T6 459
77QQK 848
5757A 233
84AT3 951
TT7TT 642
72236 345
TQ333 760
77744 720
QQ4QK 478
Q82A2 506
AJ3AA 942
JJ958 526
AJ4A4 341
A26J8 742
5TK28 871
865J3 136
66A6A 556
Q4A55 552
K8429 37
7QQ9Q 442
323J5 375
6J456 608
73Q6A 424
8QQ68 976
J9KA7 286
Q5Q5J 418
74472 154
KKQT9 637
Q8Q88 574
7543A 190
KA87J 456
2877K 635
J76A4 330
83Q69 128
A88A8 377
9999K 630
J698Q 878
67777 243
A232A 844
8K66J 835
QJ36A 420
22QQ6 782
3339K 677
K72QK 563
86777 307
323JJ 972
955KQ 826
33443 259
88Q88 897
85778 939
7T268 356
5T85J 861
833J8 387
4AA4A 7
QTQJJ 725
TT36T 395
6KJAJ 520
5J525 473
T88JT 182
44T66 173
Q75A8 251
K777A 985
88T33 905
99575 949
62222 186
22923 492
J4Q42 706
AA872 500
JA895 153
TT562 295
34434 854
2222J 881
69K46 882
TK74J 274
T46TT 548
K54KJ 164
9999Q 184
3QTJJ 400
8QK59 41
994Q9 1000
347J4 581
Q7289 138"""
val ins = Day7()
println(ins.two(inputReal))
}
data class Hand(val hand: List<Card>, val bid: Int) : Comparable<Hand> {
var counts: Map<Card, Int> = emptyMap()
fun getRank(): Int {
return when (counts.values.max()) {
5 -> 7
4 -> 6
3 -> if (counts.values.contains(2)) 5 else 4
2 -> if (counts.values.count { it == 2 } == 2) 3 else 2
1 -> 1
else -> 0
}
}
override fun toString(): String {
return getRank().toString() + ": " + hand.toString()
}
override fun compareTo(other: Hand): Int {
val left = other.getRank()
val right = this.getRank()
return if (left == right) {
for (i in 0..<other.hand.size) {
val comp = this.hand[i].value.compareTo(other.hand[i].value)
if (comp != 0) {
return comp
}
}
return 0
} else {
compareValues(right, left)
}
}
}
enum class Card(val value: Int) {
_2(1),
_3(2),
_4(3),
_5(4),
_6(5),
_7(6),
_8(7),
_9(8),
T(9),
J(0),
Q(11),
K(12),
A(13);
companion object {
fun getCard(c: String) = run {
try {
Card.valueOf(c)
} catch (e: IllegalArgumentException) {
Card.valueOf("_$c")
}
}
}
override fun toString(): String {
return this.name.replace("_", "")
}
}
| 0
|
Kotlin
|
0
| 0
|
a36addef07f61072cbf4c7c71adf2236a53959a5
| 12,865
|
advent-code
|
MIT License
|
task-shell-app/src/main/kotlin/com/malt/task/TaskCommandsMockup.kt
|
Maltcommunity
| 367,014,843
| false
|
{"Gradle Kotlin DSL": 6, "Shell": 1, "Text": 2, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "YAML": 3, "SQL": 4, "INI": 1, "Kotlin": 34, "Java": 4, "XML": 1}
|
package com.malt.task
import org.springframework.shell.standard.ShellComponent
import org.springframework.shell.standard.ShellMethod
import org.springframework.shell.standard.ShellOption
@ShellComponent
class TaskCommandsMockup {
@ShellMethod(key = ["show-task"], value = "Show a task")
fun showTask(
@ShellOption(help = "TASK_ID")
taskId: String
) = """
Task: #1
Summary: Some task
Description: Do something
""".trimIndent()
}
| 1
| null |
1
| 1
|
7e7ee7f07f404c99ef0d7c911319d68731be44df
| 496
|
repository-test-example
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.