path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
756M
| is_fork
bool 2
classes | languages_distribution
stringlengths 12
2.44k
⌀ | content
stringlengths 6
6.29M
| issues
float64 0
10k
⌀ | main_language
stringclasses 128
values | forks
int64 0
54.2k
| stars
int64 0
157k
| commit_sha
stringlengths 40
40
| size
int64 6
6.29M
| name
stringlengths 1
100
| license
stringclasses 104
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/test/kotlin/io/github/tmcreative1/playwright/remote/browser/TestBrowser.kt | TMcreative1 | 344,872,041 | false | null | package io.github.tmcreative1.playwright.remote.browser
import io.github.tmcreative1.playwright.remote.base.BaseTest
import io.github.tmcreative1.playwright.remote.core.exceptions.PlaywrightException
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlin.test.fail
class TestBrowser : BaseTest() {
@Test
fun `check to create new page`() {
browserContext.close()
val pg1 = browser.newPage()
assertEquals(1, browser.contexts().size)
val pg2 = browser.newPage()
assertEquals(2, browser.contexts().size)
pg1.close()
assertEquals(1, browser.contexts().size)
pg2.close()
assertEquals(0, browser.contexts().size)
}
@Test
fun `check to throw upon second create new page`() {
val pg = browser.newPage()
try {
pg.context().newPage()
fail("newPage should throw")
} catch (e: PlaywrightException) {
assertTrue(e.message!!.contains("Please use browser.newContext()"))
}
}
} | 0 | Kotlin | 0 | 1 | a4b4d3fe199f0a3e7d740feded801ecd5e2b9992 | 1,086 | playwright-remote | MIT License |
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/filled/MobileOptimized.kt | Konyaco | 574,321,009 | false | {"Kotlin": 11029508, "Java": 256912} |
package com.konyaco.fluent.icons.filled
import androidx.compose.ui.graphics.vector.ImageVector
import com.konyaco.fluent.icons.Icons
import com.konyaco.fluent.icons.fluentIcon
import com.konyaco.fluent.icons.fluentPath
public val Icons.Filled.MobileOptimized: ImageVector
get() {
if (_mobileOptimized != null) {
return _mobileOptimized!!
}
_mobileOptimized = fluentIcon(name = "Filled.MobileOptimized") {
fluentPath {
moveTo(19.25f, 18.5f)
horizontalLineToRelative(2.0f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.1f, 1.5f)
lineTo(20.0f, 20.0f)
verticalLineToRelative(1.25f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, -1.5f, 0.1f)
verticalLineToRelative(-2.1f)
curveToRelative(0.0f, -0.38f, 0.28f, -0.7f, 0.65f, -0.74f)
lineToRelative(0.1f, -0.01f)
horizontalLineToRelative(2.0f)
horizontalLineToRelative(-2.0f)
close()
moveTo(2.75f, 18.5f)
horizontalLineToRelative(2.0f)
curveToRelative(0.38f, 0.0f, 0.7f, 0.28f, 0.74f, 0.65f)
lineToRelative(0.01f, 0.1f)
verticalLineToRelative(2.0f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, -1.5f, 0.1f)
lineTo(4.0f, 20.0f)
lineTo(2.75f, 20.0f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.1f, -1.5f)
horizontalLineToRelative(2.1f)
horizontalLineToRelative(-2.0f)
close()
moveTo(16.75f, 5.5f)
curveToRelative(0.41f, 0.0f, 0.75f, 0.34f, 0.75f, 0.75f)
verticalLineToRelative(11.5f)
curveToRelative(0.0f, 0.41f, -0.34f, 0.75f, -0.75f, 0.75f)
horizontalLineToRelative(-9.5f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.75f, -0.75f)
lineTo(6.5f, 6.25f)
curveToRelative(0.0f, -0.41f, 0.34f, -0.75f, 0.75f, -0.75f)
horizontalLineToRelative(9.5f)
close()
moveTo(12.25f, 12.51f)
horizontalLineToRelative(-2.5f)
lineToRelative(-0.1f, 0.01f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.0f, 1.49f)
horizontalLineToRelative(2.7f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, -0.1f, -1.5f)
close()
moveTo(14.25f, 9.5f)
horizontalLineToRelative(-4.6f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.0f, 1.5f)
lineTo(14.35f, 11.0f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, -0.1f, -1.5f)
close()
moveTo(4.75f, 2.0f)
curveToRelative(0.38f, 0.0f, 0.7f, 0.28f, 0.74f, 0.65f)
lineToRelative(0.01f, 0.1f)
verticalLineToRelative(2.0f)
curveToRelative(0.0f, 0.38f, -0.28f, 0.7f, -0.65f, 0.74f)
lineToRelative(-0.1f, 0.01f)
horizontalLineToRelative(-2.0f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.1f, -1.5f)
lineTo(4.0f, 4.0f)
lineTo(4.0f, 2.75f)
curveToRelative(0.0f, -0.41f, 0.34f, -0.75f, 0.75f, -0.75f)
close()
moveTo(19.25f, 2.0f)
curveToRelative(0.38f, 0.0f, 0.7f, 0.28f, 0.74f, 0.65f)
lineToRelative(0.01f, 0.1f)
lineTo(20.0f, 4.0f)
horizontalLineToRelative(1.25f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.1f, 1.5f)
horizontalLineToRelative(-2.1f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.74f, -0.65f)
lineToRelative(-0.01f, -0.1f)
verticalLineToRelative(-2.0f)
curveToRelative(0.0f, -0.41f, 0.34f, -0.75f, 0.75f, -0.75f)
close()
}
}
return _mobileOptimized!!
}
private var _mobileOptimized: ImageVector? = null
| 4 | Kotlin | 4 | 155 | 9e86d93bf1f9ca63a93a913c990e95f13d8ede5a | 4,226 | compose-fluent-ui | Apache License 2.0 |
app/src/main/java/com/drawiin/yourfavoritemovies/data/repository/DefaultUserRepository.kt | Drawiin | 325,358,210 | false | null | package com.drawiin.yourfavoritemovies.data.repository
import com.drawiin.yourfavoritemovies.data.cache.CacheService
import com.drawiin.yourfavoritemovies.domain.boundaries.UsersRepository
import javax.inject.Inject
class DefaultUserRepository @Inject constructor(
private val cacheService: CacheService
): UsersRepository {
override fun getCurrentProfileUid(): String? {
return cacheService.getCurrentProfileUid()
}
override fun saveCurrentProfileUid(uid: String) {
cacheService.saveCurrentProfileUid(uid)
}
} | 0 | Kotlin | 0 | 0 | ec9e6f91dde7759652a7f0abee2bfcdadfe4202b | 549 | movie-saver | MIT License |
kite-runtime/src/test/java/jp/co/cyberagent/kite/runtime/KiteDslUiTest.kt | cats-oss | 262,991,077 | false | null | package jp.co.cyberagent.kite.runtime
import android.app.Activity
import android.content.Context
import androidx.fragment.app.Fragment
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.lifecycle.Lifecycle.State
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.SavedStateHandle
import androidx.test.core.app.launchActivity
import io.kotest.assertions.throwables.shouldNotThrowAny
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.StringSpec
import io.kotest.experimental.robolectric.RobolectricTest
import io.kotest.matchers.shouldBe
import io.kotest.matchers.types.shouldBeSameInstanceAs
import io.kotest.property.checkAll
import io.kotest.property.exhaustive.exhaustive
import jp.co.cyberagent.kite.androidtestcommon.TestActivity
import jp.co.cyberagent.kite.androidtestcommon.TestFragment
import jp.co.cyberagent.kite.androidtestcommon.TestLifecycleOwner
import jp.co.cyberagent.kite.core.requireByType
@RobolectricTest
class KiteDslUiTest : StringSpec({
"Initialize kiteDsl at INITIALIZED should success" {
val owner = TestLifecycleOwner()
owner.lifecycle.currentState = State.INITIALIZED
shouldNotThrowAny {
kiteDsl(owner, TestKiteViewModelProvider()) { /* no op */ }
}
}
"Initialize kiteDsl not at INITIALIZED should throw exception" {
val owner = TestLifecycleOwner()
val states = listOf(
State.CREATED, State.STARTED, State.RESUMED, State.DESTROYED
).exhaustive()
checkAll(states) { s ->
owner.lifecycle.currentState = s
shouldThrow<IllegalStateException> {
kiteDsl(owner, TestKiteViewModelProvider()) { /* no op */ }
}
}
}
"Activity kiteDsl should initialize with correct KiteContext" {
var invoked = false
TestActivity.onCreateAction = { activity ->
activity.kiteDsl {
kiteContext.requireByType<Activity>() shouldBeSameInstanceAs activity
kiteContext.requireByType<Context>() shouldBeSameInstanceAs activity
kiteContext.requireByType<LifecycleOwner>() shouldBeSameInstanceAs activity
kiteContext.requireByType<SavedStateHandle>()
invoked = true
}
}
launchActivity<TestActivity>().use {
it.moveToState(State.RESUMED)
invoked shouldBe true
}
}
"Fragment kiteDsl should initialize with correct KiteContext" {
var invoked = false
TestFragment.onCreateAction = { fragment ->
fragment.kiteDsl {
kiteContext.requireByType<Activity>() shouldBeSameInstanceAs fragment.requireActivity()
kiteContext.requireByType<Context>() shouldBeSameInstanceAs fragment.requireContext()
kiteContext.requireByType<LifecycleOwner>() shouldBeSameInstanceAs
fragment.viewLifecycleOwner
kiteContext.requireByType<Fragment>() shouldBeSameInstanceAs fragment
kiteContext.requireByType<SavedStateHandle>()
invoked = true
}
}
launchFragmentInContainer<TestFragment>().moveToState(State.RESUMED)
invoked shouldBe true
}
})
| 0 | Kotlin | 1 | 20 | d47da96072d5a964de854cc94c8ca4369fd97dca | 3,049 | kite | Apache License 2.0 |
include/android/src/android/FeatureaActivity.kt | featurea | 407,517,337 | false | null | package featurea.android
import android.content.Intent
import android.content.res.Configuration
import android.os.Handler
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import featurea.runtime.Component
import featurea.runtime.Module
import kotlinx.coroutines.runBlocking
open class FeatureaActivity : AppCompatActivity(), Component {
override lateinit var module: Module
val listeners = mutableListOf<FeatureaActivityListener>()
val handler = Handler()
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
runBlocking {
for (listener in listeners) {
listener.onConfigurationChanged(newConfig)
}
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
runBlocking {
for (listener in listeners) {
listener.onNewIntent(intent)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
runBlocking {
for (listener in listeners) {
listener.onActivityResult(requestCode, resultCode, data)
}
}
}
}
fun Fragment.requireMainActivity(): FeatureaActivity {
return requireActivity() as FeatureaActivity
}
| 30 | Kotlin | 1 | 6 | 07074dc37a838f16ece90c19a4e8d45e743013d3 | 1,425 | engine | MIT License |
material/src/main/java/com/harreke/easyapp/skin/material/helper/SkinNavigationBarViewHelper.kt | Harreke | 547,880,574 | false | {"Kotlin": 99993} | package com.harreke.easyapp.skin.material.helper
import android.annotation.SuppressLint
import android.util.AttributeSet
import android.view.ViewGroup
import android.widget.ImageView
import androidx.appcompat.view.SupportMenuInflater
import androidx.appcompat.view.menu.MenuBuilder
import com.google.android.material.navigation.NavigationBarItemView
import com.google.android.material.navigation.NavigationBarMenuView
import com.google.android.material.navigation.NavigationBarView
import com.harreke.easyapp.skin.core.SkinManager
import com.harreke.easyapp.skin.core.SkinResourcesManager
import com.harreke.easyapp.skin.core.menu.SkinMenuBuilder
import com.harreke.easyapp.skin.material.R
@SuppressLint("RestrictedApi")
class SkinNavigationBarViewHelper(private val view: NavigationBarView, attrs: AttributeSet?, private val previewSkinName: String?) {
private val mContext = view.context
private val mDummyMenuInflater = SupportMenuInflater(mContext)
private val mDummyMenu = SkinMenuBuilder()
private var mMenuId = 0
private var mBackgroundTintId = 0
private var mItemBackgroundId = 0
private var mItemIconTintId = 0
private var mItemTextColorId = 0
init {
val style = mContext.obtainStyledAttributes(attrs, R.styleable.SkinNavigationBarView)
mMenuId = style.getResourceId(R.styleable.SkinNavigationBarView_menu, 0)
mBackgroundTintId = style.getResourceId(R.styleable.SkinNavigationBarView_backgroundTint, 0)
mItemBackgroundId = style.getResourceId(R.styleable.SkinNavigationBarView_itemBackground, 0)
mItemIconTintId = style.getResourceId(R.styleable.SkinNavigationBarView_itemIconTint, 0)
mItemTextColorId = style.getResourceId(R.styleable.SkinNavigationBarView_itemTextColor, 0)
style.recycle()
}
fun setMenuResource(menuId: Int) {
mMenuId = menuId
updateMenu()
}
fun setBackgroundTintResource(backgroundTintId: Int) {
mBackgroundTintId = backgroundTintId
updateBackgroundTint()
}
fun setItemBackgroundResource(itemBackgroundId: Int) {
mItemBackgroundId = itemBackgroundId
updateItemBackground()
}
fun setItemIconTintResource(itemIconTintId: Int) {
mItemIconTintId = itemIconTintId
updateItemIconTint()
}
fun setItemTextColorResource(itemTextColorId: Int) {
mItemTextColorId = itemTextColorId
updateItemTextColor()
}
private fun updateMenu() {
if (mMenuId == 0) return
val context = mContext
val previewSkinName = previewSkinName
val dummyMenu = mDummyMenu
dummyMenu.clear()
mDummyMenuInflater.inflate(mMenuId, dummyMenu)
val menu = view.menu
if (mItemIconTintId == 0) {
view.itemIconTintList = null
}
for (i in 0 until menu.size()) {
val menuItem = menu.getItem(i)
val menuItemId = menuItem.itemId
val dummyMenuItem = dummyMenu.findItem(menuItemId) ?: continue
val dummyMenuIconId = dummyMenuItem.itemIconId
menuItem.icon = SkinResourcesManager.getSkinDrawable(context, dummyMenuIconId, previewSkinName)
}
}
private fun updateBackgroundTint() {
if (mBackgroundTintId == 0) return
view.backgroundTintList = SkinResourcesManager.getSkinColorStateList(view.context, mBackgroundTintId, previewSkinName)
}
private fun updateItemBackground() {
if (mItemBackgroundId == 0) return
view.itemBackground = SkinResourcesManager.getSkinDrawable(view.context, mItemBackgroundId, previewSkinName)
}
private fun updateItemIconTint() {
if (mItemIconTintId == 0) return
view.itemIconTintList = SkinResourcesManager.getSkinColorStateList(view.context, mItemIconTintId, previewSkinName)
}
private fun updateItemTextColor() {
if (mItemTextColorId == 0) return
view.itemTextColor = SkinResourcesManager.getSkinColorStateList(view.context, mItemTextColorId, previewSkinName)
}
fun update() {
updateMenu()
updateBackgroundTint()
updateItemBackground()
updateItemIconTint()
updateItemTextColor()
}
} | 0 | Kotlin | 0 | 0 | 248e6b78a0bb8871021de63ee8da4572ee66c13f | 4,223 | EasyApp-Skin | MIT License |
app/src/main/java/com/dbottillo/replacename/MainActivity.kt | dbottillo | 266,729,743 | false | null | package com.dbottillo.replacename
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.runtime.DisposableEffect
import androidx.core.view.WindowCompat
import com.dbottillo.replacename.designsystem.ReplaceNameAppTheme
import com.dbottillo.replacename.ui.ReplaceNameApp
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, false)
setContent {
val systemUiController = rememberSystemUiController()
val darkTheme = isSystemInDarkTheme()
// Update the dark content of the system bars to match the theme
DisposableEffect(systemUiController, darkTheme) {
systemUiController.systemBarsDarkContentEnabled = !darkTheme
onDispose {}
}
ReplaceNameAppTheme(
darkTheme = darkTheme
) {
ReplaceNameApp()
}
}
}
}
| 0 | Kotlin | 0 | 4 | 62ce367a6c59feb221882a8be41756e4db7c0a62 | 1,306 | AndroidBaseProject | Apache License 2.0 |
src/year_2023/day_11/Day11Test.kt | scottschmitz | 572,656,097 | false | {"Kotlin": 240069} | package year_2023.day_11
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
internal class Day11Test {
private val sampleText = listOf(
"...#......",
".......#..",
"#.........",
"..........",
"......#...",
".#........",
".........#",
"..........",
".......#..",
"#...#.....",
)
@Test
fun testSolution_OneExpansion() {
val solutionOne = Day11.distances(sampleText, 2)
assertEquals(374, solutionOne)
}
@Test
fun testSolution_TenExpansions() {
val solutionOne = Day11.distances(sampleText, 10)
assertEquals(1030, solutionOne)
}
@Test
fun testSolution_OneHundredExpansions() {
val solutionTwo = Day11.distances(sampleText, 100)
assertEquals(8410, solutionTwo)
}
} | 0 | Kotlin | 0 | 0 | 70efc56e68771aa98eea6920eb35c8c17d0fc7ac | 865 | advent_of_code | Apache License 2.0 |
android/src/main/kotlin/com/dormmom/flutter_mapbox_navigation/models/RouteLocationObserver.kt | SoundSonic1 | 370,131,187 | true | {"Kotlin": 88950, "Swift": 44185, "Dart": 40744, "Ruby": 2563, "Objective-C": 822, "Java": 629} | package com.dormmom.flutter_mapbox_navigation.models
import android.location.Location
import com.mapbox.navigation.core.trip.session.LocationObserver
class RouteLocationObserver: LocationObserver {
var location: Location? = null
override fun onEnhancedLocationChanged(enhancedLocation: Location, keyPoints: List<Location>) {
location = enhancedLocation
}
override fun onRawLocationChanged(rawLocation: Location) = Unit
} | 0 | Kotlin | 0 | 1 | 916a4d74be990be4698a6b69896c67a517765872 | 449 | flutter_mapbox_navigation | Apache License 2.0 |
testing/validator/build.gradle.kts | aws-observability | 295,885,890 | false | {"Java": 689908, "Mustache": 75057, "HCL": 14030, "Rust": 10580, "Dockerfile": 3316, "Kotlin": 1568, "Smarty": 352} | /*
* Copyright Amazon.com, Inc. or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
plugins {
id("java")
id("application")
// lombok
id("io.freefair.lombok") version "8.1.0"
}
repositories {
mavenCentral()
mavenLocal()
maven(
"https://jitpack.io",
)
maven {
setUrl("https://oss.sonatype.org/content/repositories/snapshots")
}
}
dependencies {
// junit
testImplementation("org.junit.jupiter:junit-jupiter-api")
// log
implementation(group = "org.apache.logging.log4j", name = "log4j-api", version = "2.20.0")
implementation(group = "org.apache.logging.log4j", name = "log4j-core", version = "2.22.1")
// mustache template
implementation(group = "com.github.spullara.mustache.java", name = "compiler", version = "0.9.10")
// apache io utils
implementation(group = "commons-io", name = "commons-io", version = "2.12.0")
// yaml reader
implementation(group = "com.fasterxml.jackson.dataformat", name = "jackson-dataformat-yaml", version = "2.15.1")
// json flattener
implementation(group = "com.github.wnameless", name = "json-flattener", version = "0.7.1")
implementation(group = "com.github.fge", name = "json-schema-validator", version = "2.0.0")
// command cli
implementation("info.picocli:picocli:4.7.3")
compileOnly("info.picocli:picocli-codegen:4.7.3")
// aws sdk
implementation(platform("com.amazonaws:aws-java-sdk-bom:1.12.506"))
implementation("com.amazonaws:aws-java-sdk-s3")
implementation("com.amazonaws:aws-java-sdk-cloudwatch")
implementation("com.amazonaws:aws-java-sdk-xray")
implementation("com.amazonaws:aws-java-sdk-logs")
implementation("com.amazonaws:aws-java-sdk-sts")
// aws ecs sdk
implementation("com.amazonaws:aws-java-sdk-ecs")
// https://mvnrepository.com/artifact/com.github.awslabs/aws-request-signing-apache-interceptor
implementation("com.github.awslabs:aws-request-signing-apache-interceptor:b3772780da")
// http client
implementation("com.squareup.okhttp3:okhttp:4.9.3")
// command cli
implementation("info.picocli:picocli:4.7.3")
compileOnly("info.picocli:picocli-codegen:4.7.3")
// mockito
testImplementation("org.mockito:mockito-core:5.3.1")
}
application {
// Define the main class for the application.
mainClass.set("com.amazon.aoc.App")
}
| 31 | Java | 40 | 61 | fb25e6d5589abe7ad2985c6c277a10b82bbc15af | 2,769 | aws-otel-java-instrumentation | Apache License 2.0 |
starters/data-mongodb-coroutines/build.gradle.kts | ksvasan | 151,100,484 | true | {"Kotlin": 227981, "Java": 58894, "Shell": 1265, "HTML": 15} | import org.jetbrains.kotlin.gradle.dsl.Coroutines
dependencies {
api("org.springframework.boot:spring-boot-starter-data-mongodb-reactive")
api(project(":coroutines:mongodb"))
}
| 0 | Kotlin | 0 | 0 | a747b8ac4d224ca598398ae834eac53d15c2d895 | 180 | spring-fu | Apache License 2.0 |
Corona-Warn-App/src/test/java/de/rki/coronawarnapp/bugreporting/censors/RegistrationTokenCensorTest.kt | si-covid-19 | 286,833,811 | false | null | package de.rki.coronawarnapp.bugreporting.censors
import de.rki.coronawarnapp.bugreporting.debuglog.LogLine
import de.rki.coronawarnapp.storage.LocalData
import de.rki.coronawarnapp.util.CWADebug
import io.kotest.matchers.shouldBe
import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.mockkObject
import io.mockk.verify
import kotlinx.coroutines.test.runBlockingTest
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import testhelpers.BaseTest
class RegistrationTokenCensorTest : BaseTest() {
private val testToken = "<KEY>"
@BeforeEach
fun setup() {
MockKAnnotations.init(this)
mockkObject(CWADebug)
every { CWADebug.isDeviceForTestersBuild } returns false
mockkObject(LocalData)
every { LocalData.registrationToken() } returns testToken
}
private fun createInstance() = RegistrationTokenCensor()
@Test
fun `censoring replaces the logline message`() = runBlockingTest {
val instance = createInstance()
val filterMe = LogLine(
timestamp = 1,
priority = 3,
message = "I'm a shy registration token: $testToken",
tag = "I'm a tag",
throwable = null
)
instance.checkLog(filterMe) shouldBe filterMe.copy(
message = "I'm a shy registration token: ########-####-####-####-########3a2f"
)
every { CWADebug.isDeviceForTestersBuild } returns true
instance.checkLog(filterMe) shouldBe filterMe.copy(
message = "I'm a shy registration token: <KEY>"
)
verify { LocalData.registrationToken() }
}
@Test
fun `censoring returns null if there is no token`() = runBlockingTest {
every { LocalData.registrationToken() } returns null
val instance = createInstance()
val filterMeNot = LogLine(
timestamp = 1,
priority = 3,
message = "I'm a shy registration token: $testToken",
tag = "I'm a tag",
throwable = null
)
instance.checkLog(filterMeNot) shouldBe null
}
@Test
fun `censoring returns null if there is no match`() = runBlockingTest {
val instance = createInstance()
val filterMeNot = LogLine(
timestamp = 1,
priority = 3,
message = "I'm not a registration token ;)",
tag = "I'm a tag",
throwable = null
)
instance.checkLog(filterMeNot) shouldBe null
}
}
| 6 | Kotlin | 8 | 15 | 5a3b4be63b5b030da49216a0132a3979cad89af1 | 2,598 | ostanizdrav-android | Apache License 2.0 |
devp2p/src/main/kotlin/net/consensys/cava/devp2p/Packet.kt | ConsenSysMesh | 137,528,592 | false | null | /*
* Copyright 2018 ConsenSys AG.
*
* 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 net.consensys.cava.devp2p
import net.consensys.cava.bytes.Bytes
import net.consensys.cava.bytes.Bytes32
import net.consensys.cava.crypto.Hash
import net.consensys.cava.crypto.SECP256K1
import net.consensys.cava.rlp.RLP
import net.consensys.cava.rlp.RLPException
import net.consensys.cava.rlp.RLPWriter
import java.nio.ByteBuffer
internal class DecodingException(message: String, cause: Throwable? = null) : Exception(message, cause)
internal data class SigHash(val signature: SECP256K1.Signature, val hash: Bytes32)
private fun msecToSec(time: Long) = (time + 999) / 1000
private fun secToMsec(time: Long) = time * 1000
internal sealed class Packet(
val nodeId: SECP256K1.PublicKey,
private val signature: SECP256K1.Signature,
val hash: Bytes32,
val expiration: Long
) {
companion object {
const val MIN_SIZE = 104
const val MAX_SIZE = 1280
private const val HASH_INDEX = 0
private const val SIGNATURE_INDEX = 32
private const val PACKET_TYPE_INDEX = 97
private const val PACKET_DATA_INDEX = 98
fun decodeFrom(datagram: ByteBuffer) =
decodeFrom(Bytes.wrapByteBuffer(datagram))
fun decodeFrom(datagram: Bytes): Packet {
val typeByte = datagram.get(PACKET_TYPE_INDEX)
val packetType = PacketType.forType(typeByte) ?: throw DecodingException("Unrecognized packet type: $typeByte")
val signature = SECP256K1.Signature.fromBytes(
datagram.slice(SIGNATURE_INDEX, PACKET_TYPE_INDEX - SIGNATURE_INDEX)
)
val publicKey = SECP256K1.PublicKey.recoverFromSignature(
datagram.slice(PACKET_TYPE_INDEX, datagram.size() - PACKET_TYPE_INDEX),
signature
) ?: throw DecodingException("Invalid packet signature")
val hash = Bytes32.wrap(
datagram.slice(
HASH_INDEX,
SIGNATURE_INDEX
)
)
if (Hash.keccak256(datagram.slice(SIGNATURE_INDEX)) != hash) {
throw DecodingException("Invalid packet hash")
}
return packetType.decode(datagram.slice(PACKET_DATA_INDEX), hash, publicKey, signature)
}
@JvmStatic
protected fun expirationFor(now: Long) = now + PACKET_EXPIRATION_PERIOD_MS
@JvmStatic
protected fun createSignature(
packetType: PacketType,
keyPair: <KEY>.KeyPair,
encoder: (RLPWriter) -> Unit
): SigHash {
val typeByte = Bytes.of(packetType.typeId)
val dataBytes = RLP.encodeList { writer -> encoder(writer) }
val payloadBytes = Bytes.wrap(typeByte, dataBytes)
val signature = SECP256K1.sign(payloadBytes, keyPair)
val hash = Hash.keccak256(Bytes.wrap(signature.bytes(), payloadBytes))
return SigHash(signature, hash)
}
}
fun isExpired(now: Long): Boolean = expiration <= now
abstract fun encodeTo(dst: ByteBuffer): ByteBuffer
protected fun encodeTo(dst: ByteBuffer, packetType: PacketType, contentWriter: (RLPWriter) -> Unit): ByteBuffer {
hash.appendTo(dst)
signature.bytes().appendTo(dst)
dst.put(packetType.typeId)
RLP.encodeListTo(dst, contentWriter)
return dst
}
}
internal class PingPacket private constructor(
nodeId: SECP256K1.PublicKey,
signature: SECP256K1.Signature,
hash: Bytes32,
val from: Endpoint,
val to: Endpoint,
expiration: Long
) : Packet(nodeId, signature, hash, expiration) {
companion object {
private const val VERSION = 4
fun create(keyPair: SECP256K1.KeyPair, now: Long, from: Endpoint, to: Endpoint): PingPacket {
val expiration = expirationFor(now)
val sigHash = createSignature(
PacketType.PING,
keyPair
) { writer ->
encodeTo(writer, from, to, expiration)
}
return PingPacket(
keyPair.publicKey(),
sigHash.signature,
sigHash.hash,
from,
to,
expiration
)
}
fun decode(
payload: Bytes,
hash: Bytes32,
publicKey: SECP256K1.PublicKey,
signature: SECP256K1.Signature
): PingPacket {
try {
return RLP.decodeList(payload) { reader ->
val version = reader.readInt()
val from = reader.readList { r -> Endpoint.readFrom(r) }
val to = reader.readList { r -> Endpoint.readFrom(r) }
val expiration = reader.readLong() // seconds
if (version < VERSION) {
throw DecodingException("Unexpected version $VERSION in ping")
}
PingPacket(publicKey, signature, hash, from, to, secToMsec(expiration))
}
} catch (e: RLPException) {
throw DecodingException("Invalid ping packet", e)
}
}
private fun encodeTo(writer: RLPWriter, from: Endpoint, to: Endpoint, expiration: Long) {
writer.writeInt(VERSION)
writer.writeList { w -> from.writeTo(w) }
writer.writeList { w -> to.writeTo(w) }
writer.writeLong(msecToSec(expiration)) // write in seconds
}
}
override fun encodeTo(dst: ByteBuffer) = encodeTo(dst, PacketType.PING) { writer ->
encodeTo(writer, from, to, expiration)
}
}
internal class PongPacket private constructor(
nodeId: SECP256K1.PublicKey,
signature: SECP256K1.Signature,
hash: Bytes32,
val to: Endpoint,
val pingHash: Bytes32,
expiration: Long
) : Packet(nodeId, signature, hash, expiration) {
companion object {
fun create(keyPair: <KEY>, now: Long, to: Endpoint, pingHash: Bytes32): PongPacket {
val expiration = expirationFor(now)
val sigHash = createSignature(
PacketType.PONG,
keyPair
) { writer ->
encodeTo(writer, to, pingHash, expiration)
}
return PongPacket(
keyPair.publicKey(),
sigHash.signature,
sigHash.hash,
to,
pingHash,
expiration
)
}
fun decode(
payload: Bytes,
hash: Bytes32,
publicKey: SECP256K1.PublicKey,
signature: SECP256K1.Signature
): PongPacket {
try {
return RLP.decodeList(payload) { reader ->
val to = reader.readList { r -> Endpoint.readFrom(r) }
val pingHash = Bytes32.wrap(reader.readValue())
val expiration = reader.readLong() // seconds
PongPacket(publicKey, signature, hash, to, pingHash, secToMsec(expiration))
}
} catch (e: RLPException) {
throw DecodingException("Invalid pong packet", e)
}
}
private fun encodeTo(writer: RLPWriter, to: Endpoint, pingHash: Bytes32, expiration: Long) {
writer.writeList { w -> to.writeTo(w) }
writer.writeValue(pingHash)
writer.writeLong(msecToSec(expiration))
}
}
override fun encodeTo(dst: ByteBuffer) = encodeTo(dst, PacketType.PONG) { writer ->
encodeTo(writer, to, pingHash, expiration)
}
}
internal class FindNodePacket private constructor(
nodeId: SECP256K1.PublicKey,
signature: SECP256K1.Signature,
hash: Bytes32,
val target: SECP256K1.PublicKey,
expiration: Long
) : Packet(nodeId, signature, hash, expiration) {
companion object {
fun create(keyPair: <KEY>.KeyPair, now: Long, target: SECP256K1.PublicKey): FindNodePacket {
val expiration = expirationFor(now)
val sigHash = createSignature(
PacketType.FIND_NODE,
keyPair
) { writer ->
encodeTo(writer, target, expiration)
}
return FindNodePacket(
keyPair.publicKey(),
sigHash.signature,
sigHash.hash,
target,
expiration
)
}
fun decode(
payload: Bytes,
hash: Bytes32,
publicKey: <KEY>.PublicKey,
signature: SECP256K1.Signature
): FindNodePacket {
try {
return RLP.decodeList(payload) { reader ->
val target = SECP256K1.PublicKey.fromBytes(reader.readValue())
val expiration = reader.readLong()
FindNodePacket(publicKey, signature, hash, target, secToMsec(expiration))
}
} catch (e: RLPException) {
throw DecodingException("Invalid find nodes packet", e)
}
}
private fun encodeTo(writer: RLPWriter, target: SECP256K1.PublicKey, expiration: Long) {
writer.writeValue(target.bytes())
writer.writeLong(msecToSec(expiration))
}
}
override fun encodeTo(dst: ByteBuffer) = encodeTo(dst, PacketType.FIND_NODE) { writer ->
encodeTo(writer, target, expiration)
}
}
internal class NeighborsPacket private constructor(
nodeId: SECP256K1.PublicKey,
signature: SECP256K1.Signature,
hash: Bytes32,
val nodes: List<Node>,
expiration: Long
) : Packet(nodeId, signature, hash, expiration) {
companion object {
// an over-estimate of the minimum size, based on a full 64-bit expiration time and a full list length prefix
internal const val RLP_MIN_SIZE = 109
fun create(keyPair: <KEY>KeyPair, now: Long, nodes: List<Node>): NeighborsPacket {
val expiration = expirationFor(now)
val sigHash = createSignature(
PacketType.NEIGHBORS,
keyPair
) { writer ->
encodeTo(writer, nodes, expiration)
}
return NeighborsPacket(
keyPair.publicKey(),
sigHash.signature,
sigHash.hash,
nodes,
expiration
)
}
fun createRequired(keyPair: <KEY>, now: Long, nodes: List<Node>): List<NeighborsPacket> {
val result = mutableListOf<NeighborsPacket>()
var nodeSubset = mutableListOf<Node>()
var size = RLP_MIN_SIZE
for (node in nodes) {
val nodeSize = node.rlpSize()
size += nodeSize
if (size > MAX_SIZE) {
result.add(create(keyPair, now, nodeSubset))
nodeSubset = mutableListOf()
size = RLP_MIN_SIZE + nodeSize
}
nodeSubset.add(node)
}
result.add(create(keyPair, now, nodeSubset))
return result
}
fun decode(
payload: Bytes,
hash: Bytes32,
publicKey: SECP256K1.PublicKey,
signature: SECP256K1.Signature
): NeighborsPacket {
try {
return RLP.decodeList(payload) { reader ->
val nodes = mutableListOf<Node>()
reader.readList { r ->
while (!r.isComplete) {
val node = r.readList { nr -> Node.readFrom(nr) }
nodes.add(node)
}
}
val expiration = reader.readLong()
NeighborsPacket(publicKey, signature, hash, nodes, secToMsec(expiration))
}
} catch (e: RLPException) {
throw DecodingException("Invalid nodes packet", e)
}
}
private fun encodeTo(writer: RLPWriter, nodes: List<Node>, expiration: Long) {
writer.writeList { w -> nodes.forEach { node -> w.writeList { nw -> node.writeTo(nw) } } }
writer.writeLong(msecToSec(expiration))
}
}
override fun encodeTo(dst: ByteBuffer) = encodeTo(dst, PacketType.NEIGHBORS) { writer ->
encodeTo(writer, nodes, expiration)
}
}
| 5 | Java | 33 | 74 | 6bb7cf2162beffc84d6b479473a103994f006ced | 11,452 | cava | Apache License 2.0 |
src/main/kotlin/uk/gov/justice/digital/hmpps/indexer/service/IndexStatusService.kt | ministryofjustice | 276,314,745 | false | null | package uk.gov.justice.digital.hmpps.indexer.service
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import uk.gov.justice.digital.hmpps.indexer.model.INDEX_STATUS_ID
import uk.gov.justice.digital.hmpps.indexer.model.IndexStatus
import uk.gov.justice.digital.hmpps.indexer.repository.IndexStatusRepository
@Service
class IndexStatusService(private val indexStatusRepository: IndexStatusRepository) {
companion object {
val log: Logger = LoggerFactory.getLogger(this::class.java)
}
fun initialiseIndexWhenRequired(): IndexStatusService {
if (!checkIndexStatusExistsIgnoringMissingRepo()) {
indexStatusRepository.save(IndexStatus.newIndex())
.also { log.info("Created missing index status {}", it) }
}
return this
}
private fun checkIndexStatusExistsIgnoringMissingRepo(): Boolean =
try {
indexStatusRepository.existsById("STATUS")
} catch (e: Exception) {
false
}
fun getIndexStatus(): IndexStatus =
indexStatusRepository.findById(INDEX_STATUS_ID).orElseThrow()
fun markBuildInProgress(): IndexStatus {
val currentIndexStatus = getIndexStatus()
if (currentIndexStatus.inProgress().not()) {
return indexStatusRepository.save(currentIndexStatus.toBuildInProgress())
}
return currentIndexStatus
}
fun markBuildCompleteAndSwitchIndex(): IndexStatus {
val currentIndexStatus = getIndexStatus()
if (currentIndexStatus.inProgress()) {
return indexStatusRepository.save(currentIndexStatus.toBuildComplete().toSwitchIndex())
}
return currentIndexStatus
}
fun switchIndex(): IndexStatus {
val currentIndexStatus = getIndexStatus()
if (currentIndexStatus.inProgress()) {
return indexStatusRepository.save(currentIndexStatus.toBuildCancelled().toSwitchIndex())
}
return indexStatusRepository.save(getIndexStatus().toSwitchIndex())
}
fun markBuildCancelled(): IndexStatus {
val currentIndexStatus = getIndexStatus()
if (currentIndexStatus.inProgress()) {
return indexStatusRepository.save(currentIndexStatus.toBuildCancelled())
}
return currentIndexStatus
}
}
| 0 | Kotlin | 1 | 0 | f84b7e1b51b036a2c21ac45affdee7f20328d24d | 2,182 | probation-offender-search-indexer | MIT License |
app/src/main/java/com/nationalplasticfsm/features/viewAllOrder/interf/GenderListOnClick.kt | DebashisINT | 506,900,340 | false | {"Kotlin": 13523333, "Java": 994890} | package com.nationalplasticfsm.features.viewAllOrder.interf
import com.nationalplasticfsm.app.domain.NewOrderGenderEntity
interface GenderListOnClick {
fun genderListOnClick(gender: NewOrderGenderEntity)
} | 0 | Kotlin | 0 | 0 | 760e854492a3dd6b8c2ca3c351f5bd4a32c22a04 | 211 | NationalPlastic | Apache License 2.0 |
app/src/main/java/com/jaakaappi/scriptkiddiebulletin/ui/theme/Type.kt | jaakaappi | 734,854,474 | false | {"Kotlin": 34793} | package com.kaappi.scriptkiddiebulletin.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
),
bodyMedium = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 14.sp,
lineHeight = 15.sp,
letterSpacing = 0.5.sp,
color = TextDarkGrey
),
labelLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 14.sp,
lineHeight = 15.sp,
letterSpacing = 0.5.sp
),
labelMedium = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 10.sp,
lineHeight = 12.sp,
letterSpacing = 0.5.sp,
color = TextDarkGrey
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 9.sp,
lineHeight = 11.sp,
letterSpacing = 0.5.sp,
color = TextDarkGrey
)
) | 0 | Kotlin | 0 | 0 | fb84d584f2fb1f0da5ffabe9c6346d60d3f571fe | 1,443 | script-kiddie-bulletin | MIT License |
src/commonMain/kotlin/wizard/files/composeApp/Readme.kt | terrakok | 618,540,934 | false | {"Kotlin": 214635, "HTML": 296} | package wizard.files.composeApp
import wizard.*
class Readme(info: ProjectInfo) : ProjectFile {
override val path = "README.MD"
override val content = buildString {
appendLine("# Compose Multiplatform Application")
appendLine("")
if (info.hasPlatform(ProjectPlatform.Android) || info.hasPlatform(ProjectPlatform.Ios)) {
appendLine("## Before running!")
if (info.hasPlatform(ProjectPlatform.Ios)) {
appendLine(" - check your system with [KDoctor](https://github.com/Kotlin/kdoctor)")
}
if (info.hasPlatform(ProjectPlatform.Android)) {
appendLine(" - install JDK 17 on your machine")
appendLine(" - add `local.properties` file to the project root and set a path to Android SDK there")
}
appendLine("")
}
if (info.hasPlatform(ProjectPlatform.Android)) {
appendLine("### Android")
appendLine("To run the application on android device/emulator: ")
appendLine(" - open project in Android Studio and run imported android run configuration")
appendLine("")
appendLine("To build the application bundle:")
appendLine(" - run `./gradlew :${info.moduleName}:assembleDebug`")
appendLine(" - find `.apk` file in `${info.moduleName}/build/outputs/apk/debug/${info.moduleName}-debug.apk`")
appendLine("")
}
if (info.hasPlatform(ProjectPlatform.Jvm)) {
appendLine("### Desktop")
appendLine("Run the desktop application: `./gradlew :${info.moduleName}:run`")
appendLine("")
}
if (info.hasPlatform(ProjectPlatform.Ios)) {
appendLine("### iOS")
appendLine("To run the application on iPhone device/simulator:")
appendLine(" - Open `iosApp/iosApp.xcproject` in Xcode and run standard configuration")
appendLine(" - Or use [Kotlin Multiplatform Mobile plugin](https://plugins.jetbrains.com/plugin/14936-kotlin-multiplatform-mobile) for Android Studio")
appendLine("")
}
if (info.hasPlatform(ProjectPlatform.Js)) {
appendLine("### Browser")
appendLine("Run the browser application: `./gradlew :${info.moduleName}:jsBrowserDevelopmentRun`")
appendLine("")
}
}
} | 8 | Kotlin | 26 | 314 | bfca805b3056ce57e681328816bedfc41532f387 | 2,400 | Compose-Multiplatform-Wizard | MIT License |
app/src/main/java/com/sjn/stamp/media/source/LocalMediaSource.kt | sjnyag | 81,733,859 | false | {"Kotlin": 604468, "Java": 113807} | package com.sjn.stamp.media.source
import android.content.Context
import android.support.v4.media.MediaMetadataCompat
import com.sjn.stamp.utils.MediaRetrieveHelper
class LocalMediaSource(private val context: Context, private val callback: MediaRetrieveHelper.PermissionRequiredCallback) : MusicProviderSource {
override fun iterator(): Iterator<MediaMetadataCompat> {
if (!MediaRetrieveHelper.hasPermission(context)) {
callback.onPermissionRequired()
return emptyList<MediaMetadataCompat>().iterator()
}
return MediaRetrieveHelper.createIterator(MediaRetrieveHelper.retrieveAllMedia(context, callback))
}
}
| 59 | Kotlin | 3 | 8 | cb145824f9e06cd17266502a5e85d8a9fa276bb0 | 667 | stamp | Apache License 2.0 |
app/src/main/java/com/fredporciuncula/daggersimpleway/di/RetrofitModule.kt | tfcporciuncula | 146,853,406 | false | null | package com.fredporciuncula.daggersimpleway.di
import com.fredporciuncula.daggersimpleway.service.PostsService
import dagger.Module
import dagger.Provides
import io.reactivex.schedulers.Schedulers
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.moshi.MoshiConverterFactory
import javax.inject.Singleton
@Module
object RetrofitModule {
@JvmStatic @Provides @Singleton
fun provideBooksService(): PostsService = Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(MoshiConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
.build()
.create(PostsService::class.java)
}
| 0 | Kotlin | 12 | 46 | 9341f75b2b11f7d103dc7a8f12ad5896a0e96dda | 806 | dagger-simple-way | Apache License 2.0 |
app/src/main/java/com/example/prioritylist/data/backend/Task.kt | Dzem-z | 628,039,614 | false | {"Kotlin": 332105} | package com.example.prioritylist.data.backend
import androidx.compose.ui.graphics.Color
import com.example.prioritylist.data.backend.Category
import java.util.Calendar
import java.util.Date
/*
TODO(comments)
*/
open class Task(
open val dateOfCreation: Date,
open var evaluatedPriority: Double = 0.0,
open var id: Int = 0,
open val description: String,
open val name: String
){
override operator fun equals(task: Any?)
= (task is Task)
&& dateOfCreation == task.dateOfCreation
&& description == task.description
&& name == task.name
}
data class CategoryTask(
val category: Category,
override val dateOfCreation: Date,
override var evaluatedPriority: Double = 0.0,
override var id: Int = 0,
override val description: String,
override val name: String
) : Task(
dateOfCreation = dateOfCreation,
evaluatedPriority = evaluatedPriority,
id = id,
description = description,
name = name
) {
override fun equals(task: Any?)
= (task is CategoryTask)
&& super.equals(task)
&& category == task.category
}
data class DeadlineTask(
val deadline: Date,
override val dateOfCreation: Date,
override var evaluatedPriority: Double = 0.0,
override var id: Int = 0,
override val description: String,
override val name: String
) : Task(
dateOfCreation = dateOfCreation,
evaluatedPriority = evaluatedPriority,
id = id,
description = description,
name = name
){
override fun equals(task: Any?)
= (task is DeadlineTask)
&& super.equals(task)
&& deadline == task.deadline
}
data class PriorityTask(
val priority: Int,
override val dateOfCreation: Date,
override var evaluatedPriority: Double = 0.0,
override var id: Int = 0,
override val description: String,
override val name: String
) : Task(
dateOfCreation = dateOfCreation,
evaluatedPriority = evaluatedPriority,
id = id,
description = description,
name = name
){
override fun equals(task: Any?)
= (task is PriorityTask)
&& super.equals(task)
&& priority == task.priority
}
data class DeadlinePriorityTask(
val priority: Int,
val deadline: Date,
override val dateOfCreation: Date,
override var evaluatedPriority: Double = 0.0,
override var id: Int = 0,
override val description: String,
override val name: String
) : Task(
dateOfCreation = dateOfCreation,
evaluatedPriority = evaluatedPriority,
id = id,
description = description,
name = name
){
override fun equals(task: Any?)
= (task is DeadlinePriorityTask)
&& super.equals(task)
&& deadline == task.deadline
&& priority == task.priority
}
data class DeadlineCategoryTask(
val deadline: Date,
val category: Category,
override val dateOfCreation: Date,
override var evaluatedPriority: Double = 0.0,
override var id: Int = 0,
override val description: String,
override val name: String
) : Task(
dateOfCreation = dateOfCreation,
evaluatedPriority = evaluatedPriority,
id = id,
description = description,
name = name
){
override fun equals(task: Any?)
= (task is DeadlineCategoryTask)
&& super.equals(task)
&& deadline == task.deadline
&& category == task.category
}
data class DeadlinePriorityCategoryTask(
val deadline: Date,
val category: Category,
val priority: Int,
override val dateOfCreation: Date,
override var evaluatedPriority: Double = 0.0,
override var id: Int = 0,
override val description: String,
override val name: String
) : Task(
dateOfCreation = dateOfCreation,
evaluatedPriority = evaluatedPriority,
id = id,
description = description,
name = name
){
override fun equals(task: Any?)
= (task is DeadlinePriorityCategoryTask)
&& super.equals(task)
&& deadline == task.deadline
&& priority == task.priority
&& category == task.category
}
data class ModifiableTask(
var deadline: Date = Calendar.getInstance().time,
var category: Category? = null,
var priority: Int = 0,
var dateOfCreation: Date = Calendar.getInstance().time,
var evaluatedPriority: Double = 0.0,
var id: Int = 0,
var description: String = "",
var name: String = ""
)
data class Category(
val name: String,
val color: Color,
val description: String,
val priority: Int,
val id: Int
) | 0 | Kotlin | 0 | 2 | 3a2a0fe1eef43904443b48760635a33468af7cf2 | 4,650 | Android-priority-list-app | MIT License |
src/commonMain/kotlin/io/grule/parser/ParserMatcherLexer.kt | 7hens | 376,845,987 | false | null | package io.grule.parser
import io.grule.lexer.Lexer
internal class ParserMatcherLexer(private val lexer: Lexer) : ParserMatcher {
override fun match(status: ParserStatus): ParserStatus {
val token = status.peek()
if (token.lexer == lexer) {
return status.next(lexer.newNode(token))
}
status.panic(lexer)
}
override fun toString(): String {
return "<$lexer>"
}
} | 0 | Kotlin | 0 | 1 | 3c00cfd151e78515a93f20a90369e43dd3b75f73 | 433 | grule | Apache License 2.0 |
app/src/main/java/com/converter/currency/di/component/ActivityComponent.kt | abhinavkumar17 | 256,138,222 | false | null | package com.converter.currency.di.component
import com.converter.currency.MainActivity
import com.converter.currency.di.module.ActivityModule
import dagger.Component
@Component(modules = [ActivityModule::class])
interface ActivityComponent {
fun inject(mainActivity: MainActivity)
} | 0 | Kotlin | 0 | 0 | f51bdb27bf9ea9128fc9b18046dde0ff07af4d7e | 288 | CurrencyApp | MIT License |
memo/src/main/kotlin/com/mistar/memo/domain/model/repository/UserRepository.kt | mike-urssu | 354,238,895 | false | {"Kotlin": 64000} | package com.mistar.memo.domain.model.repository
import com.mistar.memo.domain.model.entity.user.User
import org.springframework.data.domain.Pageable
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
import java.util.*
@Repository
interface UserRepository : JpaRepository<User, Int> {
fun existsByUsername(username: String): Boolean
fun findByUsername(username: String): Optional<User>
fun findAllByIsDeleted(page: Pageable, isDeleted: Boolean): List<User>
fun countByIsDeleted(isDeleted: Boolean): Long
fun findByIdAndIsDeleted(userId: Int, isDeleted: Boolean): Optional<User>
} | 0 | Kotlin | 0 | 0 | ef28332a40a9b8f8422456d3ffaa97f20cdfaf62 | 664 | memo-incubating | Apache License 2.0 |
processor/src/main/java/pers/shawxingkwok/tracer/util/status.kt | ShawxingKwok | 667,099,894 | false | {"Kotlin": 101746} | package pers.shawxingkwok.tracer.util
import com.google.devtools.ksp.symbol.*
import pers.shawxingkwok.ksputil.qualifiedName
private val cache = mutableMapOf<String, Modifier>()
private val KSDeclaration.status: Modifier get() = cache.getOrPut(qualifiedName()!!) {
when {
// consider that bug first: modifiers in the java @interface declaration contain ABSTRACT
this is KSClassDeclaration && classKind == ClassKind.ANNOTATION_CLASS -> Modifier.FINAL
// return directly if its modifiers contain any key modifier
Modifier.FINAL in modifiers || Modifier.JAVA_STATIC in modifiers -> Modifier.FINAL
Modifier.OPEN in modifiers || Modifier.JAVA_DEFAULT in modifiers -> Modifier.OPEN
Modifier.SEALED in modifiers || Modifier.ABSTRACT in modifiers -> Modifier.ABSTRACT
// situations below are property or function with no FINAL, OPEN or ABSTRACT
this is KSClassDeclaration ->
when (classKind) {
ClassKind.INTERFACE -> Modifier.ABSTRACT
ClassKind.CLASS ->
// default kotlin class
if (origin == Origin.KOTLIN || origin == Origin.KOTLIN_LIB)
Modifier.FINAL
else // default java class
Modifier.OPEN
// object, annotation, enum
else -> Modifier.FINAL
}
// this is property or function
else -> {
val parentKSClass = parentDeclaration as? KSClassDeclaration
when (parentKSClass?.classKind) {
// on top level
null -> Modifier.FINAL
ClassKind.INTERFACE -> when (this) {
// constant in java interface was considered above
// and here is from only kotlin
is KSPropertyDeclaration ->
if (Modifier.ABSTRACT in getter!!.modifiers)
Modifier.ABSTRACT
else
Modifier.OPEN
is KSFunctionDeclaration ->
// 'isAbstract' is realized in KSFunctionDeclarationImpl, but that part calls
// an internal function ktFunction.hasBody and can't be taken here.
if (isAbstract) Modifier.ABSTRACT
else Modifier.OPEN
else -> error("")
}
ClassKind.CLASS -> when {
parentKSClass.status == Modifier.FINAL -> Modifier.FINAL
// situations below are in open or abstract class
// default kotlin property or function
origin == Origin.KOTLIN_LIB || origin == Origin.KOTLIN ->
if (Modifier.OVERRIDE in modifiers)
Modifier.OPEN
else
Modifier.FINAL
// java property
this is KSPropertyDeclaration -> Modifier.FINAL
// default java function
this is KSFunctionDeclaration -> Modifier.OPEN
else -> error("")
}
// in an object, annotation, or enum class
else -> Modifier.FINAL
}
}
}
}
private fun KSDeclaration._isMyOpen() = status == Modifier.OPEN
private fun KSDeclaration._isMyAbstract() = status == Modifier.ABSTRACT
private fun KSDeclaration._isFinal() = status == Modifier.FINAL
/**
*
*/
internal fun KSClassDeclaration.isMyOpen(): Boolean = _isMyOpen()
internal fun KSClassDeclaration.isMyAbstract(): Boolean = _isMyAbstract()
internal fun KSClassDeclaration.isFinal(): Boolean = _isFinal()
internal fun KSPropertyDeclaration.isMyOpen(): Boolean = _isMyOpen()
internal fun KSPropertyDeclaration.isMyAbstract(): Boolean = _isMyAbstract()
@Suppress("unused")
internal fun KSPropertyDeclaration.isFinal(): Boolean = _isFinal() | 0 | Kotlin | 0 | 2 | 38f6d5f46a91f2ae55186ae2095594a967e6b6f9 | 4,031 | Tracer | Apache License 2.0 |
bugsnag-android-core/src/test/java/com/bugsnag/android/BreadcrumbStateSerializationTest.kt | bugsnag | 2,406,783 | false | {"Kotlin": 990225, "Java": 488572, "C": 454938, "Gherkin": 173861, "C++": 59962, "Ruby": 25810, "CMake": 5144, "Shell": 3323, "Makefile": 3222} | package com.bugsnag.android
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.junit.runners.Parameterized.Parameter
import org.junit.runners.Parameterized.Parameters
import java.util.Date
@RunWith(Parameterized::class)
internal class BreadcrumbStateSerializationTest {
companion object {
@JvmStatic
@Parameters
fun testCases(): Collection<Pair<JsonStream.Streamable, String>> {
val breadcrumbs = BreadcrumbState(50, CallbackState(), NoopLogger)
val metadata = mutableMapOf<String, Any?>(Pair("direction", "left"))
breadcrumbs.add(Breadcrumb("hello world", BreadcrumbType.MANUAL, metadata, Date(0), NoopLogger))
return generateSerializationTestCases("breadcrumb_state", breadcrumbs)
}
}
@Parameter
lateinit var testCase: Pair<BreadcrumbState, String>
@Test
fun testJsonSerialisation() = verifyJsonMatches(testCase.first, testCase.second)
}
| 17 | Kotlin | 215 | 1,158 | cb0fa7c87fb6178b67a6df3d398e497ece1299a5 | 1,002 | bugsnag-android | MIT License |
idea/idea-completion/testData/basic/common/shadowing/ExtensionShadows.kt | android | 263,405,600 | true | null | class Shadow {
fun shade() {}
}
fun <X> Shadow.shade() {}
fun context() {
Shadow().sha<caret>
}
// EXIST: { lookupString: "shade", itemText: "shade", tailText: "()", typeText: "Unit" }
// EXIST: { lookupString: "shade", itemText: "shade", tailText: "() for Shadow in <root>", typeText: "Unit" }
// NOTHING_ELSE | 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 321 | kotlin | Apache License 2.0 |
app/src/main/java/com/rousetime/sample/startup_annotate/SampleSyncFourAnnotateStartup.kt | VenryZhong | 475,435,314 | true | {"Kotlin": 135914, "AIDL": 589} | package com.rousetime.sample.startup_annotate
import android.content.Context
import com.rousetime.android_startup.AndroidStartup
import com.rousetime.android_startup.Startup
import com.venry.apt_annotation.AutoStartup
@AutoStartup(
callCreateOnMainThread = true,
waitOnMainThread = false,
dependenciesClassName = ["com.rousetime.sample.startup_annotate.SampleAsyncTwoAnnotateStartup"],
mouldName = arrayOf("AsyncAndSync")
)
abstract class SampleSyncFourAnnotateStartup: AndroidStartup<String>() {
private var mResult: String? = null
override fun create(context: Context): String? {
return "$mResult + sync four"
}
override fun onDependenciesCompleted(startup: Startup<*>, result: Any?) {
mResult = result as? String?
}
} | 0 | Kotlin | 0 | 0 | e8b1f78f3e0ee29a4d6fccc72f5508f127aa50d2 | 777 | android-startup | Apache License 2.0 |
app/src/main/java/com/yudistudios/foodland/ui/activities/main/fragments/ActiveOrderFragment.kt | YnsDlbr | 576,026,021 | false | {"Kotlin": 166528} | package com.yudistudios.foodland.ui.activities.main.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.yudistudios.foodland.R
import com.yudistudios.foodland.databinding.FragmentActiveOrderBinding
import com.yudistudios.foodland.models.Order
import com.yudistudios.foodland.ui.activities.main.MainActivity
import com.yudistudios.foodland.ui.activities.main.viewmodels.ActiveOrderViewModel
import com.yudistudios.foodland.ui.adapters.OrderRecyclerViewAdapter
import dagger.hilt.android.AndroidEntryPoint
import java.text.SimpleDateFormat
import java.util.*
@AndroidEntryPoint
class ActiveOrderFragment : Fragment() {
private lateinit var viewModel: ActiveOrderViewModel
private var _binding: FragmentActiveOrderBinding? = null
private val binding get() = _binding!!
private lateinit var callback: OnMapReadyCallback
private lateinit var order: Order
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentActiveOrderBinding.inflate(inflater, container, false)
MainActivity.sShowBottomNavView.value = false
val args: ActiveOrderFragmentArgs by navArgs()
order = args.order
setRecyclerView(order)
setTotalCost(order)
setDateText(order)
back()
return binding.root
}
private fun back() {
binding.buttonBack.setOnClickListener {
findNavController().popBackStack()
}
}
private fun setDateText(order: Order) {
val sdf = SimpleDateFormat("yyyy.MM.dd HH:mm:ss")
val calendar = Calendar.getInstance()
calendar.timeInMillis = order.date
binding.date = sdf.format(calendar.time)
}
private fun setTotalCost(order: Order) {
val totalCost = order.items.map {
(it.foodAmount * it.foodPrice)
}.sum()
binding.totalCost = totalCost.toString()
}
private fun setRecyclerView(order: Order) {
val adapter = OrderRecyclerViewAdapter(order.items)
binding.adapter = adapter
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
callback = OnMapReadyCallback { googleMap ->
val address = LatLng(order.latitude, order.longitude)
googleMap.addMarker(
MarkerOptions().position(address).icon(
BitmapDescriptorFactory.fromResource(R.drawable.motorbike)
)
.title("Marker in address")
)
googleMap.setMinZoomPreference(17.0f)
googleMap.moveCamera(CameraUpdateFactory.newLatLng(address))
}
val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
mapFragment?.getMapAsync(callback)
}
} | 0 | Kotlin | 0 | 0 | d6710e873f9fc3c0c374e77dc96e44ba98a52ef0 | 3,539 | FoodLand | Apache License 2.0 |
libraries/stdlib/common/src/kotlin/ioH.kt | android | 263,405,600 | true | null | /*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package kotlin.io
/** Prints the line separator to the standard output stream. */
public expect fun println()
/** Prints the given [message] and the line separator to the standard output stream. */
public expect fun println(message: Any?)
/** Prints the given [message] to the standard output stream. */
public expect fun print(message: Any?)
internal expect interface Serializable
| 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 598 | kotlin | Apache License 2.0 |
sample/src/main/java/com/getyourguide/uitestglazesample/MainActivity.kt | getyourguide | 607,206,547 | false | {"Kotlin": 58991} | package com.getyourguide.uitestglazesample
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity(R.layout.activity_main)
| 3 | Kotlin | 0 | 31 | 1d3b39f6b7da1bcd4ff161bf496d75015766c2d2 | 156 | UiTestGlaze | Apache License 2.0 |
components/src/main/java/lt/markmerkk/export/entities/ImportLogResponse.kt | marius-m | 67,072,115 | false | null | package lt.markmerkk.export.entities
import lt.markmerkk.TimeProvider
import lt.markmerkk.entities.Log
data class ImportLogResponse(
val start: Long,
val end: Long,
val duration: Long?,
val code: String?,
val comment: String?,
val author: String?
) {
fun toLog(timeProvider: TimeProvider): Log {
return Log.new(
timeProvider= timeProvider,
start = start,
end = end,
code = code ?: "",
comment = comment ?: "",
systemNote = "",
author = author ?: "",
remoteData = null
)
}
} | 1 | Kotlin | 2 | 25 | 6632d6bfd53de4760dbc3764c361f2dcd5b5ebce | 671 | wt4 | Apache License 2.0 |
example/src/main/java/com/thesurix/example/gesturerecycler/adapter/MonthsAdapter.kt | mozomig | 246,526,778 | true | {"Kotlin": 72613} | package com.thesurix.example.gesturerecycler.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import com.thesurix.example.gesturerecycler.R
import com.thesurix.example.gesturerecycler.databinding.GridItemBinding
import com.thesurix.example.gesturerecycler.databinding.HeaderItemBinding
import com.thesurix.example.gesturerecycler.databinding.LinearItemBinding
import com.thesurix.example.gesturerecycler.databinding.LinearItemWithBackgroundBinding
import com.thesurix.example.gesturerecycler.model.MonthItem
import com.thesurix.gesturerecycler.GestureAdapter
import com.thesurix.gesturerecycler.GestureViewHolder
class MonthsAdapter(@param:LayoutRes private val mItemResId: Int) : GestureAdapter<MonthItem, GestureViewHolder<MonthItem>>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GestureViewHolder<MonthItem> {
return if (viewType == MonthItem.MonthItemType.MONTH.ordinal) {
when (mItemResId) {
R.layout.linear_item -> LinearItemViewHolder(LinearItemBinding.inflate(LayoutInflater.from(parent.context), parent, false))
R.layout.linear_item_with_background -> LinearItemWithBackgroundViewHolder(
LinearItemWithBackgroundBinding.inflate(LayoutInflater.from(parent.context), parent, false))
R.layout.grid_item -> GridItemViewHolder(GridItemBinding.inflate(LayoutInflater.from(parent.context), parent, false))
else -> throw UnsupportedOperationException("Unsupported resource")
}
} else {
HeaderViewHolder(HeaderItemBinding.inflate(LayoutInflater.from(parent.context), parent, false))
}
}
override fun getItemViewType(position: Int): Int {
return getItem(position).type.ordinal
}
}
| 0 | Kotlin | 0 | 0 | ce165198ed29dcfd0b729c4292ab08a2e668fcdc | 1,843 | gesture-recycler | Apache License 2.0 |
app/src/main/java/org/simple/clinic/patient/sync/ForPatientSync.kt | simpledotorg | 132,515,649 | false | {"Kotlin": 5970450, "Shell": 1660, "HTML": 545} | package org.simple.clinic.patient.sync
import javax.inject.Qualifier
@Qualifier
annotation class ForPatientSync(val value: Type) {
enum class Type {
RecordRetentionFallbackDuration
}
}
| 4 | Kotlin | 73 | 223 | 58d14c702db2b27b9dc6c1298c337225f854be6d | 196 | simple-android | MIT License |
idea/tests/org/jetbrains/kotlin/idea/decompiler/textBuilder/AbstractDecompiledTextFromJsMetadataTest.kt | android | 263,405,600 | true | null | /*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.decompiler.textBuilder
import com.intellij.openapi.module.Module
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.idea.decompiler.KtDecompiledFile
import org.jetbrains.kotlin.idea.test.SdkAndMockLibraryProjectDescriptor
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtImportList
import org.jetbrains.kotlin.psi.KtPackageDirective
import org.jetbrains.kotlin.serialization.js.JsSerializerProtocol
import org.jetbrains.kotlin.test.InTextDirectivesUtils
import java.io.File
import kotlin.test.assertTrue
private const val CHECK_PACKAGE_DIRECTIVE = "CHECK_PACKAGE"
abstract class AbstractDecompiledTextFromJsMetadataTest(baseDirectory: String) :
AbstractDecompiledTextBaseTest(baseDirectory, true, withRuntime = true) {
override fun getFileToDecompile(): VirtualFile = getKjsmFile(TEST_PACKAGE, module!!)
override fun checkPsiFile(psiFile: PsiFile) =
assertTrue(psiFile is KtDecompiledFile, "Expecting decompiled kotlin javascript file, was: " + psiFile::class.java)
override fun textToCheck(psiFile: PsiFile): String {
if (psiFile !is KtFile) return psiFile.text
val singleClass = findSingleClassToCheck(psiFile) ?: return psiFile.text
// Take top-comments and spaces after them, package directive with space after it, and single class element
return psiFile.children.filter { child ->
when (child) {
is PsiComment -> true
is KtPackageDirective -> true
singleClass -> true
is PsiWhiteSpace -> {
child.prevSibling is KtPackageDirective || child.prevSibling is KtImportList || child.prevSibling is PsiComment
}
else -> false
}
}.joinToString(separator = "") { it.text }
}
private fun findSingleClassToCheck(psiFile: PsiFile): PsiElement? {
val singleClassName = getTestName(false)
val singleClass = psiFile.children.find { child -> child is KtClass && child.name == singleClassName } ?: return null
val mainFilePath = "$TEST_DATA_PATH/$singleClassName/$singleClassName.kt"
val mainFile = File(mainFilePath)
if (mainFile.exists() && InTextDirectivesUtils.isDirectiveDefined(File(mainFilePath).readText(), CHECK_PACKAGE_DIRECTIVE)) {
return null
}
return singleClass
}
}
abstract class AbstractCommonDecompiledTextFromJsMetadataTest : AbstractDecompiledTextFromJsMetadataTest("/decompiler/decompiledText")
abstract class AbstractJsDecompiledTextFromJsMetadataTest : AbstractDecompiledTextFromJsMetadataTest("/decompiler/decompiledTextJs")
fun getKjsmFile(packageName: String, module: Module): VirtualFile {
val root = findTestLibraryRoot(module)!!
root.refresh(false, true)
val packageDir = root.findFileByRelativePath(SdkAndMockLibraryProjectDescriptor.LIBRARY_NAME + "/" + packageName.replace(".", "/"))!!
return packageDir.findChild(JsSerializerProtocol.getKjsmFilePath(FqName(packageName)).substringAfterLast('/'))!!
}
| 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 3,540 | kotlin | Apache License 2.0 |
compiler/testData/diagnostics/tests/j+k/samByProjectedType/genericInReturnType.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // !CHECK_TYPE
// FILE: EventListener.java
public interface EventListener<E> {
E handle(String x);
}
// FILE: A.java
public class A {
public void foo(EventListener<?> l) {
}
public static void bar(EventListener<?> l) {
}
public static void baz(EventListener<? extends CharSequence> l) {
}
}
// FILE: main.kt
fun main() {
A().foo {
x -> x.hashCode()
}
A.bar {
x -> x.hashCode()
}
// baz
A.baz {
x -> x.toString() // OK
}
A.baz {
x -> <!ARGUMENT_TYPE_MISMATCH, TYPE_MISMATCH!>x.hashCode()<!>
}
val block: (String) -> Any? = {
x -> x.hashCode()
}
A().foo(block)
A.bar(block)
val block2: (String) -> CharSequence? = {
x -> x.toString()
}
A.baz(<!ARGUMENT_TYPE_MISMATCH!>block<!>)
A.baz(block2)
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 848 | kotlin | Apache License 2.0 |
src/day20/a/day20a.kt | pghj | 577,868,985 | false | {"Kotlin": 94937} | package day20.a
import readInputLines
import shouldBe
fun main() {
val input = read()
val reordered = ArrayList(input)
rotateOnce(input, reordered)
val j = reordered.indexOfFirst { it.value == 0L }
val answer = (1..3).sumOf { reordered[(j + it * 1000) % reordered.size].value }
shouldBe(7225, answer)
}
fun rotateOnce(order: List<Num>, reordered: ArrayList<Num>) {
order.forEach{ n -> move(reordered, reordered.indexOf(n), n.value) }
}
fun move(list: ArrayList<Num>, idx: Int, dist: Long) {
var d = (dist % (list.size-1)).toInt()
if (d < 0) {
d = -d
val n = list[idx]
if (d <= idx) {
for (i in idx downTo idx - d + 1)
list[i] = list[i - 1]
list[idx - d] = n
} else {
for (i in idx until list.size - d + idx - 1)
list[i] = list[i + 1]
list[list.size - d + idx - 1] = n
}
} else if (d > 0) {
val n = list[idx]
if (idx + d < list.size) {
for (i in idx until idx + d)
list[i] = list[i + 1]
list[idx + d] = n
} else {
for (i in idx downTo idx + d - list.size + 2)
list[i] = list[i - 1]
list[idx + d - list.size + 1] = n
}
}
}
class Num( var value: Long ) {
override fun toString() = value.toString()
}
fun read(): List<Num> {
return readInputLines(20)
.filter { it.isNotBlank() }
.map { line -> line.toInt() }
.map { v -> Num(v.toLong()) }
}
| 0 | Kotlin | 0 | 0 | 4b6911ee7dfc7c731610a0514d664143525b0954 | 1,553 | advent-of-code-2022 | Apache License 2.0 |
js/js.translator/testData/box/es6classes/defaultPrimary.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // EXPECTED_REACHABLE_NODES: 1344
open class A(var value: Int) {
init {
value *= 2
}
}
class B : A {
init {
value /= 6
}
constructor(x: Int) : super(x) {
value *= 18
}
constructor() : this(18) {
value *= 12
}
}
fun box(): String {
val bs1 = B(15)
assertEquals(90, bs1.value)
val bs2 = B()
assertEquals(72 * 18, bs2.value)
return "OK"
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 427 | kotlin | Apache License 2.0 |
kompress/src/main/java/net/theluckycoder/kompress/zip/BinaryTree.kt | TheLuckyCoder | 365,539,006 | false | null | package net.theluckycoder.kompress.zip
import net.theluckycoder.kompress.utils.readFully
import java.io.EOFException
import java.io.IOException
import java.io.InputStream
import java.util.*
import kotlin.math.max
/**
* Binary tree of positive values.
*
* @author <NAME>
*/
internal class BinaryTree(depth: Int) {
/**
* The array representing the binary tree. The root is at index 0,
* the left children are at 2*i+1 and the right children at 2*i+2.
*/
private val tree: IntArray
/**
* Adds a leaf to the tree.
*
* @param node the index of the node where the path is appended
* @param path the path to the leaf (bits are parsed from the right to the left)
* @param depth the number of nodes in the path
* @param value the value of the leaf (must be positive)
*/
fun addLeaf(node: Int, path: Int, depth: Int, value: Int) {
if (depth == 0) {
// end of the path reached, add the value to the current node
if (tree[node] == UNDEFINED) {
tree[node] = value
} else {
throw IllegalArgumentException("Tree value at index " + node + " has already been assigned (" + tree[node] + ")")
}
} else {
// mark the current node as a non leaf node
tree[node] = NODE
// move down the path recursively
val nextChild = 2 * node + 1 + (path and 1)
addLeaf(nextChild, path ushr 1, depth - 1, value)
}
}
/**
* Reads a value from the specified bit stream.
*
* @param stream
* @return the value decoded, or -1 if the end of the stream is reached
*/
@Throws(IOException::class)
fun read(stream: BitStream): Int {
var currentIndex = 0
while (true) {
val bit = stream.nextBit()
if (bit == -1) {
return -1
}
val childIndex = 2 * currentIndex + 1 + bit
val value = tree[childIndex]
currentIndex = if (value == NODE) {
// consume the next bit
childIndex
} else return if (value != UNDEFINED) {
value
} else {
throw IOException("The child $bit of node at index $currentIndex is not defined")
}
}
}
companion object {
/** Value in the array indicating an undefined node */
private const val UNDEFINED = -1
/** Value in the array indicating a non leaf node */
private const val NODE = -2
/**
* Decodes the packed binary tree from the specified stream.
*/
@JvmStatic
@Throws(IOException::class)
fun decode(inputStream: InputStream, totalNumberOfValues: Int): BinaryTree {
require(totalNumberOfValues >= 0) {
"totalNumberOfValues must be bigger than 0, is $totalNumberOfValues"
}
// the first byte contains the size of the structure minus one
val size = inputStream.read() + 1
if (size == 0) {
throw IOException("Cannot read the size of the encoded tree, unexpected end of stream")
}
val encodedTree = ByteArray(size)
val read: Int = inputStream.readFully(encodedTree)
if (read != size) {
throw EOFException()
}
/** The maximum bit length for a value (16 or lower) */
var maxLength = 0
val originalBitLengths = IntArray(totalNumberOfValues)
var pos = 0
for (b in encodedTree) {
// each byte encodes the number of values (upper 4 bits) for a bit length (lower 4 bits)
val numberOfValues: Int = (b.toInt() and 0xF0 shr 4) + 1
if (pos + numberOfValues > totalNumberOfValues) {
throw IOException("Number of values exceeds given total number of values")
}
val bitLength: Int = (b.toInt() and 0x0F) + 1
for (j in 0 until numberOfValues) {
originalBitLengths[pos++] = bitLength
}
maxLength = max(maxLength, bitLength)
}
// sort the array of bit lengths and memorize the permutation used to restore the order of the codes
val permutation = IntArray(originalBitLengths.size)
for (k in permutation.indices) {
permutation[k] = k
}
var c = 0
val sortedBitLengths = IntArray(originalBitLengths.size)
for (k in originalBitLengths.indices) {
// iterate over the values
for (l in originalBitLengths.indices) {
// look for the value in the original array
if (originalBitLengths[l] == k) {
// put the value at the current position in the sorted array...
sortedBitLengths[c] = k
// ...and memorize the permutation
permutation[c] = l
c++
}
}
}
// decode the values of the tree
var code = 0
var codeIncrement = 0
var lastBitLength = 0
val codes = IntArray(totalNumberOfValues)
for (i in totalNumberOfValues - 1 downTo 0) {
code += codeIncrement
if (sortedBitLengths[i] != lastBitLength) {
lastBitLength = sortedBitLengths[i]
codeIncrement = 1 shl 16 - lastBitLength
}
codes[permutation[i]] = code
}
// build the tree
val tree = BinaryTree(maxLength)
for (k in codes.indices) {
val bitLength = originalBitLengths[k]
if (bitLength > 0) {
tree.addLeaf(0, Integer.reverse(codes[k] shl 16), bitLength, k)
}
}
return tree
}
}
init {
require(!(depth < 0 || depth > 30)) {
("depth must be bigger than 0 and not bigger than 30"
+ " but is " + depth)
}
tree = IntArray(((1L shl depth + 1) - 1).toInt())
Arrays.fill(tree, UNDEFINED)
}
} | 1 | Kotlin | 0 | 1 | 67e412a3de9242db983fa2493abd86cccb9d79f7 | 6,421 | Kompress | Apache License 2.0 |
idea/testData/quickfix/expressions/unnecessaryNonNullAssertion1.kt | android | 263,405,600 | true | null | // "Remove unnecessary non-null assertion (!!)" "true"
fun test(value : Int) : Int {
return value<caret>!!
}
| 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 113 | kotlin | Apache License 2.0 |
compiler/testData/diagnostics/tests/generics/varProjection/setterProjectedOutPlusAssignDefined.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // FIR_IDENTICAL
// !DIAGNOSTICS: -UNREACHABLE_CODE
interface Tr<T> {
var v: T
}
class C {
operator fun plusAssign(c: C) {}
}
fun test(t: Tr<out C>) {
// No error because no real assignment happens
t.v += null!!
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 232 | kotlin | Apache License 2.0 |
src/test/enhetstester/kotlin/no/nav/familie/ks/sak/kjerne/behandling/steg/BeslutteVedtakStegTest.kt | navikt | 533,308,075 | false | {"Kotlin": 3012984, "Gherkin": 26795, "Shell": 1039, "Dockerfile": 141} | package no.nav.familie.ks.sak.kjerne.behandling.steg
import io.mockk.every
import io.mockk.impl.annotations.InjectMockKs
import io.mockk.impl.annotations.MockK
import io.mockk.junit5.MockKExtension
import io.mockk.just
import io.mockk.mockk
import io.mockk.runs
import io.mockk.verify
import no.nav.familie.ks.sak.api.dto.BesluttVedtakDto
import no.nav.familie.ks.sak.common.exception.FunksjonellFeil
import no.nav.familie.ks.sak.config.FeatureToggleConfig
import no.nav.familie.ks.sak.config.featureToggle.UnleashNextMedContextService
import no.nav.familie.ks.sak.data.lagBehandling
import no.nav.familie.ks.sak.kjerne.behandling.BehandlingService
import no.nav.familie.ks.sak.kjerne.behandling.domene.BehandlingStatus
import no.nav.familie.ks.sak.kjerne.behandling.domene.BehandlingÅrsak
import no.nav.familie.ks.sak.kjerne.behandling.domene.Beslutning
import no.nav.familie.ks.sak.kjerne.behandling.steg.vedtak.VedtakService
import no.nav.familie.ks.sak.kjerne.behandling.steg.vilkårsvurdering.VilkårsvurderingService
import no.nav.familie.ks.sak.kjerne.beregning.TilkjentYtelseValideringService
import no.nav.familie.ks.sak.kjerne.brev.GenererBrevService
import no.nav.familie.ks.sak.kjerne.logg.LoggService
import no.nav.familie.ks.sak.kjerne.totrinnskontroll.TotrinnskontrollService
import no.nav.familie.prosessering.internal.TaskService
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.extension.ExtendWith
import org.hamcrest.CoreMatchers.`is` as Is
@ExtendWith(MockKExtension::class)
class BeslutteVedtakStegTest {
@MockK
private lateinit var totrinnskontrollService: TotrinnskontrollService
@MockK
private lateinit var vedtakService: VedtakService
@MockK
private lateinit var behandlingService: BehandlingService
@MockK
private lateinit var taskService: TaskService
@MockK
private lateinit var loggService: LoggService
@MockK
private lateinit var vilkårsvurderingService: VilkårsvurderingService
@MockK
private lateinit var unleashService: UnleashNextMedContextService
@MockK
private lateinit var genererBrevService: GenererBrevService
@MockK
private lateinit var tilkjentYtelseValideringService: TilkjentYtelseValideringService
@InjectMockKs
private lateinit var beslutteVedtakSteg: BeslutteVedtakSteg
@BeforeEach
private fun init() {
every { behandlingService.hentBehandling(200) } returns lagBehandling(opprettetÅrsak = BehandlingÅrsak.SØKNAD)
every { unleashService.isEnabled(FeatureToggleConfig.KAN_MANUELT_KORRIGERE_MED_VEDTAKSBREV) } returns false
every { loggService.opprettBeslutningOmVedtakLogg(any(), any(), any()) } returns mockk()
every { taskService.save(any()) } returns mockk()
every { genererBrevService.genererBrevForBehandling(any()) } returns ByteArray(200)
}
@Test
fun `utførSteg skal kaste FunksjonellFeil dersom behandlingen er satt til IVERKSETTER_VEDTAK `() {
every { behandlingService.hentBehandling(200) } returns
lagBehandling(opprettetÅrsak = BehandlingÅrsak.SØKNAD).apply {
status = BehandlingStatus.IVERKSETTER_VEDTAK
}
val funksjonellFeil = assertThrows<FunksjonellFeil> { beslutteVedtakSteg.utførSteg(200, mockk()) }
assertThat(funksjonellFeil.message, Is("Behandlingen er allerede sendt til oppdrag og venter på kvittering"))
}
@Test
fun `utførSteg skal kaste FunksjonellFeil dersom behandlingen er satt til AVSLUTTET `() {
every { behandlingService.hentBehandling(200) } returns
lagBehandling(opprettetÅrsak = BehandlingÅrsak.SØKNAD).apply {
status = BehandlingStatus.AVSLUTTET
}
val funksjonellFeil = assertThrows<FunksjonellFeil> { beslutteVedtakSteg.utførSteg(200, mockk()) }
assertThat(funksjonellFeil.message, Is("Behandlingen er allerede avsluttet"))
}
@Test
fun `utførSteg skal kaste FunksjonellFeil dersom behandling årsaken er satt til KORREKSJON_VEDTAKSBREV og SB ikke har feature togglet på `() {
every { behandlingService.hentBehandling(200) } returns lagBehandling(opprettetÅrsak = BehandlingÅrsak.KORREKSJON_VEDTAKSBREV)
every { unleashService.isEnabled(FeatureToggleConfig.KAN_MANUELT_KORRIGERE_MED_VEDTAKSBREV) } returns false
val funksjonellFeil = assertThrows<FunksjonellFeil> { beslutteVedtakSteg.utførSteg(200, mockk()) }
assertThat(
funksjonellFeil.message,
Is("Årsak Korrigere vedtak med egen brevmal og toggle familie-ks-sak.behandling.korreksjon-vedtaksbrev false"),
)
assertThat(
funksjonellFeil.frontendFeilmelding,
Is("Du har ikke tilgang til å beslutte for denne behandlingen. Ta kontakt med teamet dersom dette ikke stemmer."),
)
}
@Test
fun `utførSteg skal opprette og initiere nytt vedtak dersom vedtaket er underkjent `() {
val besluttVedtakDto = BesluttVedtakDto(Beslutning.UNDERKJENT, "UNDERKJENT")
every {
totrinnskontrollService.besluttTotrinnskontroll(
any(),
any(),
any(),
besluttVedtakDto.beslutning,
emptyList(),
)
} returns mockk(relaxed = true)
every { vilkårsvurderingService.hentAktivVilkårsvurderingForBehandling(any()) } returns mockk()
every { vilkårsvurderingService.oppdater(any()) } returns mockk()
every { vedtakService.opprettOgInitierNyttVedtakForBehandling(any(), any()) } just runs
beslutteVedtakSteg.utførSteg(200, besluttVedtakDto)
verify(exactly = 1) {
totrinnskontrollService.besluttTotrinnskontroll(
any(),
any(),
any(),
besluttVedtakDto.beslutning,
emptyList(),
)
}
verify(exactly = 1) { loggService.opprettBeslutningOmVedtakLogg(any(), any(), any()) }
verify(exactly = 2) { taskService.save(any()) }
verify(exactly = 1) { vilkårsvurderingService.hentAktivVilkårsvurderingForBehandling(any()) }
verify(exactly = 1) { vilkårsvurderingService.oppdater(any()) }
verify(exactly = 1) { vedtakService.opprettOgInitierNyttVedtakForBehandling(any(), any()) }
}
@Test
fun `utførSteg skal oppdatere vedtak med nytt vedtaksbrev dersom vedtaket er godkjent `() {
val besluttVedtakDto = BesluttVedtakDto(Beslutning.GODKJENT, "GODKJENT")
every {
totrinnskontrollService.besluttTotrinnskontroll(
any(),
any(),
any(),
besluttVedtakDto.beslutning,
emptyList(),
)
} returns mockk(relaxed = true)
every { tilkjentYtelseValideringService.validerAtIngenUtbetalingerOverstiger100Prosent(any()) } just runs
every { vedtakService.hentAktivVedtakForBehandling(any()) } returns mockk(relaxed = true)
every { vedtakService.oppdaterVedtak(any()) } returns mockk()
beslutteVedtakSteg.utførSteg(200, besluttVedtakDto)
verify(exactly = 1) {
totrinnskontrollService.besluttTotrinnskontroll(
any(),
any(),
any(),
besluttVedtakDto.beslutning,
emptyList(),
)
}
verify(exactly = 1) { loggService.opprettBeslutningOmVedtakLogg(any(), any(), any()) }
verify(exactly = 1) { genererBrevService.genererBrevForBehandling(any()) }
verify(exactly = 1) { vedtakService.hentAktivVedtakForBehandling(any()) }
verify(exactly = 1) { vedtakService.oppdaterVedtak(any()) }
verify(exactly = 1) { tilkjentYtelseValideringService.validerAtIngenUtbetalingerOverstiger100Prosent(any()) }
}
}
| 5 | Kotlin | 1 | 1 | 5d9e5b709913f3fbe9147ea49bbb5e39654d01f0 | 8,014 | familie-ks-sak | MIT License |
app/src/main/java/com/ngthphong92/gitstar/StarAppConstants.kt | ngthphong92 | 391,243,062 | false | null | package com.ngthphong92.gitstar
object StarAppConstants {
// NETWORK ERROR MESSAGES
const val SERVER_ERROR = "Server error"
const val INTERNET_ERROR = "No internet connection"
const val CONNECT_ERROR = "No connect to server"
// RESPONSE SIZE
const val DEFAULT_PAGE = 1
const val PAGE_SIZE = 30
const val PAGE_LIMIT = 100
const val PAGE_LIMIT_FOR_GS = 10000
const val MIN_PAGE_SIZE = 1
const val PAGE_FACTOR = 2
const val DEFAULT_DELAY_MILLIS = 300L
const val DEFAULT_EXTRA_DELAY_MILLIS = 1500L
// BACK-END RESPONSE ERROR CODES
const val SUCCESS = 200
const val UNAUTHORIZED = 401
const val ACCESS_TOKEN_NOT_PROVIDE = 1001
const val ACCESS_TOKEN_INVALID = 1002
const val EMAIL_NOT_EXIST_IN_DB = 1003
const val EMAIL_ALREADY_TAKEN = 1004
const val WRONG_PASSWORD = <PASSWORD>
const val NEW_PASSWORD_INCORRECT = <PASSWORD>
const val OAUTH_TOKEN_INVALID_OR_EXPIRED = 1007
const val EMAIL_NOT_CONFIRM = 1008
const val ACCOUNT_NOT_ACTIVATED = 1009
const val REFRESH_TOKEN_INVALID = 1011
const val ACCOUNT_SUSPENDED = 1012
const val VALIDATION_ERRORS = 2001
const val RECORD_NOT_FOUND = 2002
const val RECORD_INVALID = 2003
const val FILE_NOT_FOUND = 4001
const val EMPTY_MSG = 9994
const val NULL_MSG = 9995
const val REQUEST_TIME_OUT = 9996
const val NO_SERVER_CONNECTION = 9997
const val NO_INTERNET_CONNECTION = 9998
const val UNKNOWN_ERROR = 9999
} | 0 | Kotlin | 0 | 1 | 131fbdae62c54319191ba7e9f230d56bd90f02d0 | 1,485 | GitStar | The Unlicense |
libraries/tools/kotlin-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/plugin/KotlinMultiplatformPlugin.kt | android | 263,405,600 | true | null | /*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.gradle.plugin
import com.android.build.gradle.BaseExtension
import org.gradle.api.*
import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.ProjectDependency
import org.gradle.api.file.SourceDirectorySet
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.tasks.SourceSet
import org.jetbrains.kotlin.gradle.dsl.kotlinExtension
import org.jetbrains.kotlin.gradle.logging.kotlinWarn
import org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile
import org.jetbrains.kotlin.gradle.utils.SingleWarningPerBuild
abstract class KotlinPlatformPluginBase(protected val platformName: String) : Plugin<Project> {
companion object {
@JvmStatic
protected inline fun <reified T : Plugin<*>> Project.applyPlugin() {
pluginManager.apply(T::class.java)
}
}
}
open class KotlinPlatformCommonPlugin : KotlinPlatformPluginBase("common") {
override fun apply(project: Project) {
warnAboutKotlin12xMppDeprecation(project)
project.applyPlugin<KotlinCommonPluginWrapper>()
}
}
const val EXPECTED_BY_CONFIG_NAME = "expectedBy"
const val IMPLEMENT_CONFIG_NAME = "implement"
const val IMPLEMENT_DEPRECATION_WARNING = "The '$IMPLEMENT_CONFIG_NAME' configuration is deprecated and will be removed. " +
"Use '$EXPECTED_BY_CONFIG_NAME' instead."
open class KotlinPlatformImplementationPluginBase(platformName: String) : KotlinPlatformPluginBase(platformName) {
private val commonProjects = arrayListOf<Project>()
protected open fun configurationsForCommonModuleDependency(project: Project): List<Configuration> =
listOf(project.configurations.getByName("compile"))
override fun apply(project: Project) {
warnAboutKotlin12xMppDeprecation(project)
val implementConfig = project.configurations.create(IMPLEMENT_CONFIG_NAME)
val expectedByConfig = project.configurations.create(EXPECTED_BY_CONFIG_NAME)
implementConfig.dependencies.whenObjectAdded {
if (!implementConfigurationIsUsed) {
implementConfigurationIsUsed = true
project.logger.kotlinWarn(IMPLEMENT_DEPRECATION_WARNING)
}
}
listOf(implementConfig, expectedByConfig).forEach { config ->
config.isTransitive = false
config.dependencies.whenObjectAdded { dep ->
if (dep is ProjectDependency) {
addCommonProject(dep.dependencyProject, project)
// Needed for the projects that depend on this one to recover the common module sources through
// the transitive dependency (also, it will be added to the POM generated by Gradle):
configurationsForCommonModuleDependency(project).forEach { configuration ->
configuration.dependencies.add(dep)
}
} else {
throw GradleException("$project '${config.name}' dependency is not a project: $dep")
}
}
}
val incrementalMultiplatform = PropertiesProvider(project).incrementalMultiplatform ?: true
project.afterEvaluate {
project.tasks.withType(AbstractKotlinCompile::class.java).all { task ->
if (task.incremental && !incrementalMultiplatform) {
task.logger.debug("IC is turned off for task '${task.path}' because multiplatform IC is not enabled")
}
task.incremental = task.incremental && incrementalMultiplatform
}
}
}
private var implementConfigurationIsUsed = false
private fun addCommonProject(commonProject: Project, platformProject: Project) {
commonProjects.add(commonProject)
commonProject.whenEvaluated {
if (!commonProject.pluginManager.hasPlugin("kotlin-platform-common")) {
throw GradleException(
"Platform project $platformProject has an " +
"'$EXPECTED_BY_CONFIG_NAME'${if (implementConfigurationIsUsed) "/'$IMPLEMENT_CONFIG_NAME'" else ""} " +
"dependency to non-common project $commonProject"
)
}
// Since the two projects may add source sets in arbitrary order, and both may do that after the plugin is applied,
// we need to handle all source sets of the two projects and connect them once we get a match:
// todo warn if no match found
matchSymmetricallyByNames(
getKotlinSourceSetsSafe(commonProject),
namedSourceSetsContainer(platformProject)
) { commonSourceSet: Named, _ ->
addCommonSourceSetToPlatformSourceSet(commonSourceSet, platformProject)
// Workaround for older versions of Kotlin/Native overriding the old signature
commonProject.convention.findPlugin(JavaPluginConvention::class.java)
?.sourceSets
?.findByName(commonSourceSet.name)
?.let { javaSourceSet ->
@Suppress("DEPRECATION")
addCommonSourceSetToPlatformSourceSet(javaSourceSet, platformProject)
}
}
}
}
/**
* Applies [whenMatched] to pairs of items with the same name in [containerA] and [containerB],
* regardless of the order in which they are added to the containers.
*/
private fun <A, B> matchSymmetricallyByNames(
containerA: NamedDomainObjectCollection<out A>,
containerB: NamedDomainObjectCollection<out B>,
whenMatched: (A, B) -> Unit
) {
val matchedNames = mutableSetOf<String>()
fun <T, R> NamedDomainObjectCollection<T>.matchAllWith(other: NamedDomainObjectCollection<R>, match: (T, R) -> Unit) {
[email protected] { item ->
val itemName = [email protected](item)
if (itemName !in matchedNames) {
val otherItem = other.findByName(itemName)
if (otherItem != null) {
matchedNames += itemName
match(item, otherItem)
}
}
}
}
containerA.matchAllWith(containerB) { a, b -> whenMatched(a, b) }
containerB.matchAllWith(containerA) { b, a -> whenMatched(a, b) }
}
protected open fun namedSourceSetsContainer(project: Project): NamedDomainObjectContainer<*> =
project.kotlinExtension.sourceSets
protected open fun addCommonSourceSetToPlatformSourceSet(commonSourceSet: Named, platformProject: Project) {
platformProject.whenEvaluated {
// At the point when the source set in the platform module is created, the task does not exist
val platformTasks = platformProject.tasks
.withType(AbstractKotlinCompile::class.java)
.filter { it.sourceSetName == commonSourceSet.name } // TODO use strict check once this code is not run in K/N
val commonSources = getKotlinSourceDirectorySetSafe(commonSourceSet)!!
for (platformTask in platformTasks) {
platformTask.source(commonSources)
platformTask.commonSourceSet += commonSources
}
}
}
private fun getKotlinSourceSetsSafe(project: Project): NamedDomainObjectCollection<out Named> {
// Access through reflection, because another project's KotlinProjectExtension might be loaded by a different class loader:
val kotlinExt = project.extensions.getByName("kotlin")
@Suppress("UNCHECKED_CAST")
val sourceSets = kotlinExt.javaClass.getMethod("getSourceSets").invoke(kotlinExt) as NamedDomainObjectCollection<out Named>
return sourceSets
}
protected fun getKotlinSourceDirectorySetSafe(from: Any): SourceDirectorySet? {
val getKotlin = from.javaClass.getMethod("getKotlin")
return getKotlin(from) as? SourceDirectorySet
}
@Deprecated("Migrate to the new Kotlin source sets and use the addCommonSourceSetToPlatformSourceSet(Named, Project) overload")
protected open fun addCommonSourceSetToPlatformSourceSet(sourceSet: SourceSet, platformProject: Project) = Unit
@Deprecated("Retained for older Kotlin/Native MPP plugin binary compatibility")
protected val SourceSet.kotlin: SourceDirectorySet?
get() {
// Access through reflection, because another project's KotlinSourceSet might be loaded
// by a different class loader:
val convention = (getConvention("kotlin") ?: getConvention("kotlin2js")) ?: return null
val kotlinSourceSetIface = convention.javaClass.interfaces.find { it.name == KotlinSourceSet::class.qualifiedName }
val getKotlin = kotlinSourceSetIface?.methods?.find { it.name == "getKotlin" } ?: return null
return getKotlin(convention) as? SourceDirectorySet
}
}
internal fun <T> Project.whenEvaluated(fn: Project.() -> T) {
if (state.executed) {
fn()
} else {
afterEvaluate { it.fn() }
}
}
open class KotlinPlatformAndroidPlugin : KotlinPlatformImplementationPluginBase("android") {
override fun apply(project: Project) {
project.applyPlugin<KotlinAndroidPluginWrapper>()
super.apply(project)
}
override fun configurationsForCommonModuleDependency(project: Project): List<Configuration> =
(project.configurations.findByName("api"))?.let(::listOf)
?: super.configurationsForCommonModuleDependency(project) // older Android plugins don't have api/implementation configs
override fun namedSourceSetsContainer(project: Project): NamedDomainObjectContainer<*> =
(project.extensions.getByName("android") as BaseExtension).sourceSets
override fun addCommonSourceSetToPlatformSourceSet(commonSourceSet: Named, platformProject: Project) {
val androidExtension = platformProject.extensions.getByName("android") as BaseExtension
val androidSourceSet = androidExtension.sourceSets.findByName(commonSourceSet.name) ?: return
val kotlinSourceSet = androidSourceSet.getConvention(KOTLIN_DSL_NAME) as? KotlinSourceSet
?: return
kotlinSourceSet.kotlin.source(getKotlinSourceDirectorySetSafe(commonSourceSet)!!)
}
}
open class KotlinPlatformJvmPlugin : KotlinPlatformImplementationPluginBase("jvm") {
override fun apply(project: Project) {
project.applyPlugin<KotlinPluginWrapper>()
super.apply(project)
}
}
open class KotlinPlatformJsPlugin : KotlinPlatformImplementationPluginBase("js") {
override fun apply(project: Project) {
project.applyPlugin<Kotlin2JsPluginWrapper>()
super.apply(project)
}
}
internal val KOTLIN_12X_MPP_DEPRECATION_WARNING = "\n" + """
The 'org.jetbrains.kotlin.platform.*' plugins are deprecated and will no longer be available in Kotlin 1.4.
Please migrate the project to the 'org.jetbrains.kotlin.multiplatform' plugin.
See: https://kotlinlang.org/docs/reference/building-mpp-with-gradle.html
""".trimIndent()
private const val KOTLIN_12X_MPP_DEPRECATION_SUPPRESS_FLAG = "kotlin.internal.mpp12x.deprecation.suppress"
private fun warnAboutKotlin12xMppDeprecation(project: Project) {
if (project.findProperty(KOTLIN_12X_MPP_DEPRECATION_SUPPRESS_FLAG) != "true") {
SingleWarningPerBuild.show(project, KOTLIN_12X_MPP_DEPRECATION_WARNING)
}
} | 34 | Kotlin | 49 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 12,215 | kotlin | Apache License 2.0 |
features/explore/src/main/java/taiwan/no/one/feat/explore/data/contracts/DataStore.kt | pokk | 263,073,196 | false | null | /*
* MIT License
*
* Copyright (c) 2022 Jieyi
*
* 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 taiwan.no.one.feat.explore.data.contracts
import taiwan.no.one.entity.SimpleTrackEntity
import taiwan.no.one.feat.explore.data.entities.local.ArtistWithImageAndBioEntityAndStats
import taiwan.no.one.feat.explore.data.entities.remote.NetworkAlbumInfo
import taiwan.no.one.feat.explore.data.entities.remote.NetworkArtistMoreDetail
import taiwan.no.one.feat.explore.data.entities.remote.NetworkArtistPhotos
import taiwan.no.one.feat.explore.data.entities.remote.NetworkArtistSimilar
import taiwan.no.one.feat.explore.data.entities.remote.NetworkArtistTopAlbumInfo
import taiwan.no.one.feat.explore.data.entities.remote.NetworkArtistTopTrackInfo
import taiwan.no.one.feat.explore.data.entities.remote.NetworkTagInfo
import taiwan.no.one.feat.explore.data.entities.remote.NetworkTagTopArtist
import taiwan.no.one.feat.explore.data.entities.remote.NetworkTopAlbumInfo
import taiwan.no.one.feat.explore.data.entities.remote.NetworkTopArtistInfo
import taiwan.no.one.feat.explore.data.entities.remote.NetworkTopTagInfo
import taiwan.no.one.feat.explore.data.entities.remote.NetworkTopTrackInfo
import taiwan.no.one.feat.explore.data.entities.remote.NetworkTrackInfo
import taiwan.no.one.feat.explore.data.entities.remote.NetworkTrackInfo.NetworkTrack
import taiwan.no.one.feat.explore.data.entities.remote.NetworkTrackSimilar
/**
* This interface will common the all data stores.
* Using prefix name (get), (create), (modify), (remove), (store)
*/
internal interface DataStore {
//region Album Data
suspend fun getAlbumInfo(mbid: String): NetworkAlbumInfo
//endregion
//region Artist Data
suspend fun getArtistInfo(name: String?, mbid: String?): ArtistWithImageAndBioEntityAndStats
suspend fun getArtistTopAlbum(name: String?, mbid: String?): NetworkArtistTopAlbumInfo
suspend fun getArtistTopTrack(name: String?, mbid: String?): NetworkArtistTopTrackInfo
suspend fun getSimilarArtistInfo(mbid: String): NetworkArtistSimilar
suspend fun getArtistPhotosInfo(artistName: String, page: Int): NetworkArtistPhotos
suspend fun getArtistMoreInfo(artistName: String): NetworkArtistMoreDetail
suspend fun createArtistMoreInfo(artistName: String, entity: NetworkArtistMoreDetail): Boolean
suspend fun createArtist(entity: ArtistWithImageAndBioEntityAndStats): Boolean
suspend fun removeArtist(entity: ArtistWithImageAndBioEntityAndStats)
//endregion
//region Track Data
suspend fun getTrackInfo(mbid: String): NetworkTrackInfo
suspend fun getSimilarTrackInfo(mbid: String): NetworkTrackSimilar
suspend fun getTrackCover(trackUrl: String, trackEntity: NetworkTrack): NetworkTrack
suspend fun getTrackCover(trackUrl: String, simpleTrackEntity: SimpleTrackEntity): SimpleTrackEntity
//endregion
//region Chart
suspend fun getChartTopTrack(page: Int, limit: Int): NetworkTopTrackInfo
suspend fun createChartTopTrack(page: Int, limit: Int, entity: NetworkTopTrackInfo): Boolean
suspend fun getChartTopArtist(page: Int, limit: Int): NetworkTopArtistInfo
suspend fun createChartTopArtist(page: Int, limit: Int, entity: NetworkTopArtistInfo): Boolean
suspend fun getChartTopTag(page: Int, limit: Int): NetworkTopTagInfo
//endregion
//region Tag Data
suspend fun getTagInfo(mbid: String): NetworkTagInfo
suspend fun getTagTopAlbum(mbid: String): NetworkTopAlbumInfo
suspend fun getTagTopArtist(mbid: String): NetworkTagTopArtist
suspend fun getTagTopTrack(tagName: String): NetworkTopTrackInfo
//endregion
}
| 2 | Kotlin | 3 | 16 | 6d173194dcd3c44db46dfe6b0ef691b9322da975 | 4,677 | DropBeat | MIT License |
analysis/decompiled/light-classes-for-decompiled/src/org/jetbrains/kotlin/analysis/decompiled/light/classes/KtLightClassForDecompiledDeclaration.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.analysis.decompiled.light.classes
import com.intellij.openapi.util.Pair
import com.intellij.psi.*
import com.intellij.psi.impl.PsiClassImplUtil
import com.intellij.psi.impl.PsiImplUtil
import com.intellij.psi.impl.PsiSuperMethodImplUtil
import com.intellij.psi.javadoc.PsiDocComment
import com.intellij.psi.scope.PsiScopeProcessor
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiUtil
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.analysis.decompiled.light.classes.origin.LightMemberOriginForCompiledField
import org.jetbrains.kotlin.analysis.decompiled.light.classes.origin.LightMemberOriginForCompiledMethod
import org.jetbrains.kotlin.analysis.decompiler.psi.file.KtClsFile
import org.jetbrains.kotlin.analysis.providers.createAllLibrariesModificationTracker
import org.jetbrains.kotlin.asJava.classes.ClassInnerStuffCache
import org.jetbrains.kotlin.asJava.classes.getEnumEntriesPsiMethod
import org.jetbrains.kotlin.asJava.classes.lazyPub
import org.jetbrains.kotlin.asJava.isGetEntriesMethod
import org.jetbrains.kotlin.asJava.isSyntheticValuesOrValueOfMethod
import org.jetbrains.kotlin.load.java.structure.LightClassOriginKind
import org.jetbrains.kotlin.psi.KtClassOrObject
internal inline fun <R : PsiElement, T> R.cachedValueWithLibraryTracker(
crossinline computer: () -> T,
): T = CachedValuesManager.getCachedValue(this) {
CachedValueProvider.Result.createSingleDependency(computer(), project.createAllLibrariesModificationTracker())
}
open class KtLightClassForDecompiledDeclaration(
clsDelegate: PsiClass,
clsParent: PsiElement,
protected val file: KtClsFile,
kotlinOrigin: KtClassOrObject?
) : KtLightClassForDecompiledDeclarationBase(clsDelegate, clsParent, kotlinOrigin) {
private val myInnersCache by lazyPub {
ClassInnerStuffCache(
/* aClass = */ this,
/* generateEnumMethods = */ true,
/* modificationTrackers = */ listOf(project.createAllLibrariesModificationTracker()),
)
}
override fun getFields(): Array<PsiField> = myInnersCache.fields
override fun getMethods(): Array<PsiMethod> = myInnersCache.methods
override fun getConstructors(): Array<PsiMethod> = myInnersCache.constructors
override fun getInnerClasses(): Array<PsiClass> = myInnersCache.innerClasses
override fun findFieldByName(name: String, checkBases: Boolean): PsiField? = myInnersCache.findFieldByName(name, checkBases)
override fun findMethodsByName(name: String, checkBases: Boolean): Array<PsiMethod> = myInnersCache.findMethodsByName(name, checkBases)
override fun findInnerClassByName(name: String, checkBases: Boolean): PsiClass? = myInnersCache.findInnerClassByName(name, checkBases)
override fun hasModifierProperty(name: String): Boolean = clsDelegate.hasModifierProperty(name)
override fun findMethodBySignature(patternMethod: PsiMethod?, checkBases: Boolean): PsiMethod? =
patternMethod?.let { PsiClassImplUtil.findMethodBySignature(this, it, checkBases) }
override fun findMethodsBySignature(patternMethod: PsiMethod?, checkBases: Boolean): Array<PsiMethod> = patternMethod?.let {
PsiClassImplUtil.findMethodsBySignature(this, it, checkBases)
} ?: PsiMethod.EMPTY_ARRAY
override fun findMethodsAndTheirSubstitutorsByName(@NonNls name: String?, checkBases: Boolean): List<Pair<PsiMethod, PsiSubstitutor>> =
PsiClassImplUtil.findMethodsAndTheirSubstitutorsByName(this, name, checkBases)
override fun getImplementsList(): PsiReferenceList? = clsDelegate.implementsList
override fun getRBrace(): PsiElement? = null
override fun getLBrace(): PsiElement? = null
override fun getInitializers(): Array<PsiClassInitializer> = clsDelegate.initializers
override fun getContainingClass(): PsiClass? = parent as? PsiClass
override fun isInheritorDeep(baseClass: PsiClass?, classToByPass: PsiClass?): Boolean =
clsDelegate.isInheritorDeep(baseClass, classToByPass)
override fun getAllMethodsAndTheirSubstitutors(): List<Pair<PsiMethod?, PsiSubstitutor?>?> =
PsiClassImplUtil.getAllWithSubstitutorsByMap<PsiMethod>(this, PsiClassImplUtil.MemberType.METHOD)
override fun isInterface(): Boolean = clsDelegate.isInterface
override fun getTypeParameters(): Array<PsiTypeParameter> = clsDelegate.typeParameters
override fun isInheritor(baseClass: PsiClass, checkDeep: Boolean): Boolean = clsDelegate.isInheritor(baseClass, checkDeep)
override fun processDeclarations(
processor: PsiScopeProcessor,
state: ResolveState,
lastParent: PsiElement?,
place: PsiElement
): Boolean = PsiClassImplUtil.processDeclarationsInClass(
/* aClass = */ this,
/* processor = */ processor,
/* state = */ state,
/* visited = */ null,
/* last = */ lastParent,
/* place = */ place,
/* languageLevel = */ PsiUtil.getLanguageLevel(place),
/* isRaw = */ false,
)
override fun isEnum(): Boolean = clsDelegate.isEnum
override fun isRecord(): Boolean = clsDelegate.isRecord
override fun getExtendsListTypes(): Array<PsiClassType> = PsiClassImplUtil.getExtendsListTypes(this)
override fun getTypeParameterList(): PsiTypeParameterList? = clsDelegate.typeParameterList
override fun isAnnotationType(): Boolean = clsDelegate.isAnnotationType
override fun getNameIdentifier(): PsiIdentifier? = clsDelegate.nameIdentifier
override fun getInterfaces(): Array<PsiClass> = PsiClassImplUtil.getInterfaces(this)
override fun getSuperClass(): PsiClass? = PsiClassImplUtil.getSuperClass(this)
override fun getSupers(): Array<PsiClass> = PsiClassImplUtil.getSupers(this)
override fun getSuperTypes(): Array<PsiClassType> = PsiClassImplUtil.getSuperTypes(this)
override fun getVisibleSignatures(): Collection<HierarchicalMethodSignature> = PsiSuperMethodImplUtil.getVisibleSignatures(this)
override fun getQualifiedName(): String? = clsDelegate.qualifiedName
override fun getImplementsListTypes(): Array<PsiClassType> = PsiClassImplUtil.getImplementsListTypes(this)
override fun isDeprecated(): Boolean = clsDelegate.isDeprecated
override fun setName(name: String): PsiElement = clsDelegate.setName(name)
override fun hasTypeParameters(): Boolean = PsiImplUtil.hasTypeParameters(this)
override fun getExtendsList(): PsiReferenceList? = clsDelegate.extendsList
override fun getDocComment(): PsiDocComment? = clsDelegate.docComment
override fun getModifierList(): PsiModifierList? = clsDelegate.modifierList
override fun getScope(): PsiElement = clsDelegate.scope
override fun getAllInnerClasses(): Array<PsiClass> = PsiClassImplUtil.getAllInnerClasses(this)
override fun getAllMethods(): Array<PsiMethod> = PsiClassImplUtil.getAllMethods(this)
override fun getAllFields(): Array<PsiField> = PsiClassImplUtil.getAllFields(this)
override fun getOwnMethods(): List<PsiMethod> = cachedValueWithLibraryTracker {
val isEnum = isEnum
this.clsDelegate.methods.mapNotNull { psiMethod ->
if (isSyntheticValuesOrValueOfMethod(psiMethod)) return@mapNotNull null
if (isEnum && isGetEntriesMethod(psiMethod)) {
return@mapNotNull getEnumEntriesPsiMethod(this)
}
KtLightMethodForDecompiledDeclaration(
funDelegate = psiMethod,
funParent = this,
lightMemberOrigin = LightMemberOriginForCompiledMethod(psiMethod, file)
)
}
}
override fun getOwnFields(): List<PsiField> = cachedValueWithLibraryTracker {
this.clsDelegate.fields.map { psiField ->
if (psiField is PsiEnumConstant) {
KtLightEnumEntryForDecompiledDeclaration(
fldDelegate = psiField,
fldParent = this,
lightMemberOrigin = LightMemberOriginForCompiledField(psiField, file),
file = file,
)
} else {
KtLightFieldForDecompiledDeclaration(
fldDelegate = psiField,
fldParent = this,
lightMemberOrigin = LightMemberOriginForCompiledField(psiField, file),
)
}
}
}
override fun getOwnInnerClasses(): List<PsiClass> = cachedValueWithLibraryTracker {
this.clsDelegate.innerClasses.map { psiClass ->
val innerDeclaration = this.kotlinOrigin
?.declarations
?.filterIsInstance<KtClassOrObject>()
?.firstOrNull { cls -> cls.name == this.clsDelegate.name }
KtLightClassForDecompiledDeclaration(
clsDelegate = psiClass,
clsParent = this,
file = file,
kotlinOrigin = innerDeclaration,
)
}
}
override val originKind: LightClassOriginKind = LightClassOriginKind.BINARY
override fun getNavigationElement() = kotlinOrigin?.navigationElement ?: file
override fun equals(other: Any?): Boolean {
return this === other || other is KtLightClassForDecompiledDeclaration &&
qualifiedName == other.qualifiedName &&
file == other.file
}
override fun hashCode(): Int = qualifiedName?.hashCode() ?: kotlinOrigin?.fqName?.hashCode() ?: 0
override fun copy(): PsiElement = this
override fun clone(): Any = this
override fun toString(): String = "${this.javaClass.simpleName} of $parent"
override fun getName(): String? = clsDelegate.name
override fun isValid(): Boolean = file.isValid && clsDelegate.isValid && (kotlinOrigin?.isValid != false)
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 10,043 | kotlin | Apache License 2.0 |
WatchFaceKotlin/app/src/main/java/com/example/android/wearable/alpha/utils/ComplicationUtils.kt | android | 192,007,253 | false | {"Kotlin": 597606, "Shell": 4267} | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.wearable.alpha.utils
import android.content.Context
import android.graphics.RectF
import androidx.wear.watchface.CanvasComplicationFactory
import androidx.wear.watchface.ComplicationSlot
import androidx.wear.watchface.ComplicationSlotsManager
import androidx.wear.watchface.complications.ComplicationSlotBounds
import androidx.wear.watchface.complications.DefaultComplicationDataSourcePolicy
import androidx.wear.watchface.complications.SystemDataSources
import androidx.wear.watchface.complications.data.ComplicationType
import androidx.wear.watchface.complications.rendering.CanvasComplicationDrawable
import androidx.wear.watchface.complications.rendering.ComplicationDrawable
import androidx.wear.watchface.style.CurrentUserStyleRepository
import com.example.android.wearable.alpha.R
// Information needed for complications.
// Creates bounds for the locations of both right and left complications. (This is the
// location from 0.0 - 1.0.)
// Both left and right complications use the same top and bottom bounds.
private const val LEFT_AND_RIGHT_COMPLICATIONS_TOP_BOUND = 0.4f
private const val LEFT_AND_RIGHT_COMPLICATIONS_BOTTOM_BOUND = 0.6f
private const val LEFT_COMPLICATION_LEFT_BOUND = 0.2f
private const val LEFT_COMPLICATION_RIGHT_BOUND = 0.4f
private const val RIGHT_COMPLICATION_LEFT_BOUND = 0.6f
private const val RIGHT_COMPLICATION_RIGHT_BOUND = 0.8f
private val DEFAULT_COMPLICATION_STYLE_DRAWABLE_ID = R.drawable.complication_red_style
// Unique IDs for each complication. The settings activity that supports allowing users
// to select their complication data provider requires numbers to be >= 0.
internal const val LEFT_COMPLICATION_ID = 100
internal const val RIGHT_COMPLICATION_ID = 101
/**
* Represents the unique id associated with a complication and the complication types it supports.
*/
sealed class ComplicationConfig(val id: Int, val supportedTypes: List<ComplicationType>) {
object Left : ComplicationConfig(
LEFT_COMPLICATION_ID,
listOf(
ComplicationType.RANGED_VALUE,
ComplicationType.MONOCHROMATIC_IMAGE,
ComplicationType.SHORT_TEXT,
ComplicationType.SMALL_IMAGE
)
)
object Right : ComplicationConfig(
RIGHT_COMPLICATION_ID,
listOf(
ComplicationType.RANGED_VALUE,
ComplicationType.MONOCHROMATIC_IMAGE,
ComplicationType.SHORT_TEXT,
ComplicationType.SMALL_IMAGE
)
)
}
// Utility function that initializes default complication slots (left and right).
fun createComplicationSlotManager(
context: Context,
currentUserStyleRepository: CurrentUserStyleRepository,
drawableId: Int = DEFAULT_COMPLICATION_STYLE_DRAWABLE_ID
): ComplicationSlotsManager {
val defaultCanvasComplicationFactory =
CanvasComplicationFactory { watchState, listener ->
CanvasComplicationDrawable(
ComplicationDrawable.getDrawable(context, drawableId)!!,
watchState,
listener
)
}
val leftComplication = ComplicationSlot.createRoundRectComplicationSlotBuilder(
id = ComplicationConfig.Left.id,
canvasComplicationFactory = defaultCanvasComplicationFactory,
supportedTypes = ComplicationConfig.Left.supportedTypes,
defaultDataSourcePolicy = DefaultComplicationDataSourcePolicy(
SystemDataSources.DATA_SOURCE_DAY_OF_WEEK,
ComplicationType.SHORT_TEXT
),
bounds = ComplicationSlotBounds(
RectF(
LEFT_COMPLICATION_LEFT_BOUND,
LEFT_AND_RIGHT_COMPLICATIONS_TOP_BOUND,
LEFT_COMPLICATION_RIGHT_BOUND,
LEFT_AND_RIGHT_COMPLICATIONS_BOTTOM_BOUND
)
)
)
.build()
val rightComplication = ComplicationSlot.createRoundRectComplicationSlotBuilder(
id = ComplicationConfig.Right.id,
canvasComplicationFactory = defaultCanvasComplicationFactory,
supportedTypes = ComplicationConfig.Right.supportedTypes,
defaultDataSourcePolicy = DefaultComplicationDataSourcePolicy(
SystemDataSources.DATA_SOURCE_WATCH_BATTERY,
ComplicationType.SHORT_TEXT
),
bounds = ComplicationSlotBounds(
RectF(
RIGHT_COMPLICATION_LEFT_BOUND,
LEFT_AND_RIGHT_COMPLICATIONS_TOP_BOUND,
RIGHT_COMPLICATION_RIGHT_BOUND,
LEFT_AND_RIGHT_COMPLICATIONS_BOTTOM_BOUND
)
)
).build()
return ComplicationSlotsManager(
listOf(leftComplication, rightComplication),
currentUserStyleRepository
)
}
| 22 | Kotlin | 547 | 976 | 0156b8cff1e4f28cadc581333587e281bb8db452 | 5,335 | wear-os-samples | Apache License 2.0 |
starter/app/src/main/java/com/udacity/project4/locationreminders/reminderslist/ReminderListFragment.kt | romanyn36 | 648,625,666 | false | null | package com.udacity.project4.locationreminders.reminderslist
import android.content.Intent
import android.os.Bundle
import android.view.*
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import com.firebase.ui.auth.AuthUI
import com.google.firebase.auth.FirebaseAuth
import com.udacity.project4.R
import com.udacity.project4.authentication.AuthenticationActivity
import com.udacity.project4.base.BaseFragment
import com.udacity.project4.base.NavigationCommand
import com.udacity.project4.databinding.FragmentRemindersBinding
import com.udacity.project4.locationreminders.RemindersActivity
import com.udacity.project4.utils.setDisplayHomeAsUpEnabled
import com.udacity.project4.utils.setTitle
import com.udacity.project4.utils.setup
import org.koin.androidx.viewmodel.ext.android.viewModel
class ReminderListFragment : BaseFragment() {
//use Koin to retrieve the ViewModel instance
override val _viewModel: RemindersListViewModel by viewModel()
private lateinit var binding: FragmentRemindersBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding =
DataBindingUtil.inflate(
inflater,
R.layout.fragment_reminders, container, false
)
binding.viewModel = _viewModel
setHasOptionsMenu(true)
setDisplayHomeAsUpEnabled(false)
setTitle(getString(R.string.app_name))
binding.refreshLayout.setOnRefreshListener { _viewModel.loadReminders() }
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.lifecycleOwner = this
setupRecyclerView()
binding.addReminderFAB.setOnClickListener {
navigateToAddReminder()
}
}
override fun onResume() {
super.onResume()
//load the reminders list on the ui
_viewModel.loadReminders()
}
private fun navigateToAddReminder() {
//use the navigationCommand live data to navigate between the fragments
_viewModel.navigationCommand.postValue(
NavigationCommand.To(
ReminderListFragmentDirections.toSaveReminder( )
)
)
}
private fun setupRecyclerView() {
val adapter = RemindersListAdapter {
}
// setup the recycler view using the extension function
binding.reminderssRecyclerView.setup(adapter)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.logout -> {
// TODO: add the logout implementation
Toast.makeText(context,"logged out",Toast.LENGTH_SHORT).show()
AuthUI.getInstance().signOut(requireContext()).addOnCompleteListener {
val intent= Intent(context, AuthenticationActivity::class.java)
startActivity(intent)
}
}
}
return super.onOptionsItemSelected(item)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
// display logout as menu item
inflater.inflate(R.menu.main_menu, menu)
}
}
| 1 | Kotlin | 1 | 2 | 7fdec69572732857488d669a61b21277003216a3 | 3,360 | location_reminder | Intel Open Source License |
app/src/main/java/com/redridgeapps/trakx/ui/common/FixedCollapsingToolbarLayout.kt | SaurabhSandav | 162,139,338 | false | null | package com.redridgeapps.trakx.ui.common
import android.content.Context
import android.util.AttributeSet
import androidx.core.view.WindowInsetsCompat
import com.google.android.material.appbar.CollapsingToolbarLayout
/* Fixes empty status bar sized space showing under child views */
class FixedCollapsingToolbarLayout @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) : CollapsingToolbarLayout(context, attrs, defStyle) {
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
var newHeightMeasureSpec = heightMeasureSpec
super.onMeasure(widthMeasureSpec, newHeightMeasureSpec)
val fs = this.javaClass.superclass!!.getDeclaredField("lastInsets")
fs.isAccessible = true
val mLastInsets = fs.get(this) as WindowInsetsCompat?
val mode = MeasureSpec.getMode(newHeightMeasureSpec)
val topInset = mLastInsets?.systemWindowInsetTop ?: 0
if (mode == MeasureSpec.UNSPECIFIED && topInset > 0) {
// fix the bottom empty padding
newHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
measuredHeight - topInset, MeasureSpec.EXACTLY
)
super.onMeasure(widthMeasureSpec, newHeightMeasureSpec)
}
}
}
| 0 | Kotlin | 0 | 0 | 515c1fc662dff80156a6cd4d497ffdb64e3296e1 | 1,302 | TrakX | MIT License |
app/src/main/kotlin/me/sweetll/tucao/model/raw/Movie.kt | blackbbc | 78,953,199 | false | null | package me.sweetll.tucao.model.raw
import me.sweetll.tucao.model.json.Video
import me.sweetll.tucao.model.json.Channel
data class Index(val banners: List<Banner>,
val recommends: List<Pair<Channel,List<Video>>>)
| 13 | Java | 209 | 1,014 | cdae0b953c3fe61c463783de6339e1bea2298fe7 | 231 | Tucao | MIT License |
app/src/test/java/org/simple/clinic/login/activateuser/ActivateUserTest.kt | simpledotorg | 132,515,649 | false | {"Kotlin": 5970450, "Shell": 1660, "HTML": 545} | package org.simple.clinic.login.activateuser
import com.google.common.truth.Truth.assertThat
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.inOrder
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
import org.junit.Test
import org.simple.clinic.FakeCall
import org.simple.sharedTestCode.TestData
import org.simple.clinic.login.LoginOtpSmsListener
import org.simple.clinic.login.UsersApi
import org.simple.clinic.login.activateuser.ActivateUser.Result.IncorrectPin
import org.simple.clinic.login.activateuser.ActivateUser.Result.NetworkError
import org.simple.clinic.login.activateuser.ActivateUser.Result.OtherError
import org.simple.clinic.login.activateuser.ActivateUser.Result.ServerError
import org.simple.clinic.login.activateuser.ActivateUser.Result.Success
import java.net.SocketTimeoutException
import java.util.UUID
class ActivateUserTest {
private val api = mock<UsersApi>()
private val loginOtpSmsListener = mock<LoginOtpSmsListener>()
private val userUuid = UUID.fromString("a2be9a8f-8aab-4ecb-b4d2-9ed74bfbd800")
private val correctPin = "1234"
private val incorrectPin = "1111"
private val activateUser = ActivateUser(api, loginOtpSmsListener)
@Test
fun `when the activate request is successful, return the success result`() {
// given
val userPayload = TestData.loggedInUserPayload(uuid = userUuid)
whenever(api.activate(ActivateUserRequest.create(userUuid, correctPin))) doReturn FakeCall.success(ActivateUserResponse(userPayload))
// when
val result = activateUser.activate(userUuid, correctPin)
// then
assertThat(result).isEqualTo(Success(userPayload))
}
@Test
fun `when the activate request returns a status code of 401, return the incorrect pin result`() {
// given
whenever(api.activate(ActivateUserRequest.create(userUuid, incorrectPin))) doReturn FakeCall.error("", responseCode = 401)
// when
val result = activateUser.activate(userUuid, incorrectPin)
// then
assertThat(result).isEqualTo(IncorrectPin)
}
@Test
fun `when the activate request returns any other status code, return the server error result`() {
// given
whenever(api.activate(ActivateUserRequest.create(userUuid, correctPin))) doReturn FakeCall.error("", responseCode = 500)
// when
val result = activateUser.activate(userUuid, correctPin)
// then
assertThat(result).isEqualTo(ServerError(responseCode = 500))
}
@Test
fun `when the activate request fails with a network error, return the network error result`() {
// given
whenever(api.activate(ActivateUserRequest.create(userUuid, correctPin))) doReturn FakeCall.failure(SocketTimeoutException())
// when
val result = activateUser.activate(userUuid, correctPin)
// then
assertThat(result).isEqualTo(NetworkError)
}
@Test
fun `when the activate request fails with any other error, return the other error result`() {
// given
val cause = RuntimeException()
whenever(api.activate(ActivateUserRequest.create(userUuid, correctPin))) doReturn FakeCall.failure(cause)
// when
val result = activateUser.activate(userUuid, correctPin)
// then
assertThat(result).isEqualTo(OtherError(cause))
}
@Test
fun `before the call to activate the user is made, listening for the login OTP SMS must be done`() {
// given
val inOrder = inOrder(loginOtpSmsListener, api)
// when
activateUser.activate(userUuid, correctPin)
// then
inOrder.verify(loginOtpSmsListener).listenForLoginOtp()
inOrder.verify(api).activate(ActivateUserRequest.create(userUuid, correctPin))
inOrder.verifyNoMoreInteractions()
}
}
| 4 | Kotlin | 73 | 223 | 58d14c702db2b27b9dc6c1298c337225f854be6d | 3,685 | simple-android | MIT License |
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/StarArrowBack.kt | Konyaco | 574,321,009 | false | {"Kotlin": 11029508, "Java": 256912} |
package com.konyaco.fluent.icons.regular
import androidx.compose.ui.graphics.vector.ImageVector
import com.konyaco.fluent.icons.Icons
import com.konyaco.fluent.icons.fluentIcon
import com.konyaco.fluent.icons.fluentPath
public val Icons.Regular.StarArrowBack: ImageVector
get() {
if (_starArrowBack != null) {
return _starArrowBack!!
}
_starArrowBack = fluentIcon(name = "Regular.StarArrowBack") {
fluentPath {
moveTo(10.79f, 3.1f)
curveToRelative(0.5f, -1.0f, 1.92f, -1.0f, 2.42f, 0.0f)
lineToRelative(2.36f, 4.78f)
lineToRelative(5.27f, 0.77f)
curveToRelative(1.1f, 0.16f, 1.55f, 1.52f, 0.75f, 2.3f)
lineToRelative(-0.9f, 0.88f)
arcToRelative(6.46f, 6.46f, 0.0f, false, false, -1.52f, -0.61f)
lineToRelative(1.15f, -1.13f)
lineToRelative(-5.05f, -0.74f)
arcToRelative(1.35f, 1.35f, 0.0f, false, true, -1.01f, -0.74f)
lineTo(12.0f, 4.04f)
lineTo(9.74f, 8.6f)
curveToRelative(-0.2f, 0.4f, -0.58f, 0.68f, -1.02f, 0.74f)
lineToRelative(-5.05f, 0.74f)
lineToRelative(3.66f, 3.56f)
curveToRelative(0.32f, 0.3f, 0.46f, 0.76f, 0.39f, 1.2f)
lineToRelative(-0.87f, 5.02f)
lineTo(11.0f, 17.7f)
curveToRelative(0.02f, 0.54f, 0.1f, 1.07f, 0.24f, 1.57f)
lineToRelative(-3.96f, 2.08f)
arcToRelative(1.35f, 1.35f, 0.0f, false, true, -1.96f, -1.42f)
lineToRelative(0.9f, -5.25f)
lineToRelative(-3.81f, -3.72f)
curveToRelative(-0.8f, -0.78f, -0.36f, -2.14f, 0.75f, -2.3f)
lineToRelative(5.27f, -0.77f)
lineToRelative(2.36f, -4.78f)
close()
moveTo(23.0f, 17.5f)
arcToRelative(5.5f, 5.5f, 0.0f, true, true, -11.0f, 0.0f)
arcToRelative(5.5f, 5.5f, 0.0f, false, true, 11.0f, 0.0f)
close()
moveTo(16.35f, 15.35f)
arcToRelative(0.5f, 0.5f, 0.0f, false, false, -0.7f, -0.7f)
lineToRelative(-1.5f, 1.5f)
arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.0f, 0.7f)
lineToRelative(1.5f, 1.5f)
arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.7f, -0.7f)
lineToRelative(-0.64f, -0.65f)
horizontalLineToRelative(2.04f)
curveToRelative(1.24f, 0.0f, 2.25f, 1.0f, 2.25f, 2.25f)
verticalLineToRelative(0.25f)
arcToRelative(0.5f, 0.5f, 0.0f, false, false, 1.0f, 0.0f)
verticalLineToRelative(-0.25f)
curveToRelative(0.0f, -1.8f, -1.46f, -3.25f, -3.25f, -3.25f)
horizontalLineToRelative(-2.04f)
lineToRelative(0.64f, -0.65f)
close()
}
}
return _starArrowBack!!
}
private var _starArrowBack: ImageVector? = null
| 4 | Kotlin | 4 | 155 | 9e86d93bf1f9ca63a93a913c990e95f13d8ede5a | 3,113 | compose-fluent-ui | Apache License 2.0 |
js/js.translator/testData/box/inlineMultiFile/inlineMultiFileSimple.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // EXPECTED_REACHABLE_NODES: 1282
// FILE: a.kt
package foo
inline fun sum(a: Int, b: Int): Int {
return a + b
}
// FILE: b.kt
package foo
// CHECK_NOT_CALLED: sum
fun box(): String {
val sum3 = sum(1, 2)
assertEquals(3, sum3)
return "OK"
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 262 | kotlin | Apache License 2.0 |
src/co/edu/uniquindio/compiladores/proyecto/Sintaxis/VariableInmutable.kt | jenunezb | 542,360,188 | false | {"Kotlin": 503857, "Java": 255} | package co.edu.uniquindio.compiladores.proyecto.Sintaxis
import co.edu.uniquindio.compiladores.proyecto.Lexico.Error
import co.edu.uniquindio.compiladores.proyecto.Lexico.Token
import co.edu.uniquindio.compiladores.proyecto.Semantica.Ambito
import co.edu.uniquindio.compiladores.proyecto.Semantica.TablaSimbolos
import javafx.scene.control.TreeItem
class VariableInmutable(var tipoDato: Token, var listaIdentificadores: ArrayList<Token>) : DeclaracionVariable() {
override fun getArbolVisual(): TreeItem<String> {
var raiz = TreeItem<String>("Declaracion Variable Inmutable")
raiz.children.add(TreeItem("Tipo de dato: ${tipoDato.lexema}"))
for (p in listaIdentificadores) {
raiz.children.add(TreeItem(" Identificador ${p.lexema}"))
}
return raiz
}
override fun llenarTablaSimbolos(tablaSimbolos: TablaSimbolos, listaErrores: ArrayList<Error>, ambito: Ambito) {
for (i in listaIdentificadores) {
tablaSimbolos.guardarSimboloValor(i.lexema, tipoDato.lexema, false, ambito, i.fila, i.columna)
}
}
fun obtenerNombresIdent(): ArrayList<String> {
var nombres = ArrayList<String>()
if (listaIdentificadores != null) {
for (l in listaIdentificadores) {
nombres.add(l.lexema)
}
}
return nombres
}
override fun toString(): String {
return "${tipoDato.lexema},${obtenerNombresIdent()}"
}
override fun getJavaCode(): String {
var codigo = "final " + tipoDato.getJavaCode() + " "
for (s in listaIdentificadores) {
codigo += s.getJavaCode() + ","
}
codigo = codigo.substring(0, codigo.length - 1)
codigo += ";"
return codigo
}
} | 0 | Kotlin | 0 | 0 | 4f9571e6c8679cf395e33cc4ff057e3c142382d5 | 1,791 | compiladores | Creative Commons Attribution 2.0 Generic |
src/main/kotlin/com/utzcoz/parser/dumpsys/DumpsysParser.kt | utzcoz | 250,768,760 | false | null | package com.utzcoz.parser.dumpsys
import java.io.File
class DumpsysParser {
companion object {
private const val spaceIndent = " "
private const val surfaceFlingerParserName = "surfaceflinger"
@JvmStatic
fun main(args: Array<String>) {
val list = args.toList()
println("DumpsysParser arguments $list")
println()
if (list.isNotEmpty() && list[0] == "-h") {
printHelpInfo()
return
}
if (list.size < 2 || !list.contains("-p")) {
println("Please use -p to select parser to parse content")
return
}
val parser = list[list.indexOf("-p") + 1]
if (list.size < 4 || !list.contains("-f")) {
println("Please use -f to provide dumpsys file")
return
}
val filePath = list[list.indexOf("-f") + 1]
val file = File(filePath)
if (!file.exists()) {
println("Please provide exist file with -f")
return
}
if (list.size < 5 || list[4] != "--") {
println("Please use -- to separate sub-commands for specific parser")
return
}
val subCommands = args.slice(5 until args.size)
when (parser) {
surfaceFlingerParserName ->
SurfaceFlingerParser.parse(subCommands, file.readText())
else ->
println("We don't support parser $parser now.")
}
}
private fun printHelpInfo() {
println("Dumpsys result parser")
println()
println("Show help info: java -jar dumpsys-result-parser.jar -h")
println()
println("Parse specific info: java -jar dumpsys-result-parser.jar -p " +
"PARSE-NAME -- SUB-COMMANDS")
println()
println("PARSE-NAME:")
println("$spaceIndent$surfaceFlingerParserName: parse dumpsys SurfaceFlinger result")
println()
println("SUB-COMMANDS")
SurfaceFlingerParser.showSupportCommands(spaceIndent)
}
}
}
| 1 | Kotlin | 1 | 5 | ab295b377dff078dee4a34943fd4c03867c2e14d | 2,262 | dumpsys-parser | Apache License 2.0 |
kcrypto/src/main/kotlin/org/bouncycastle/kcrypto/spec/EncPairGenSpec.kt | bcgit | 196,159,414 | false | null | package org.bouncycastle.kcrypto.spec
interface EncPairGenSpec: DecGenSpec, EncGenSpec, KeyGenSpec | 1 | Kotlin | 10 | 41 | 317868e703ddbf483b52718847a485f86a5d7903 | 99 | bc-kotlin | MIT License |
mobile/src/main/java/com/github/shadowsocks/service/AccessibilityKeyDetector.kt | Morteza-Rastgoo | 270,647,927 | true | {"Kotlin": 548032, "Python": 8287, "Makefile": 6635, "HTML": 2513, "Shell": 993, "Perl": 280} | package com.github.shadowsocks.service
import android.accessibilityservice.AccessibilityService
import android.util.Log
import android.view.KeyEvent
import android.view.accessibility.AccessibilityEvent
import android.widget.Toast
import com.github.shadowsocks.Core
import timber.log.Timber
class AccessibilityKeyDetector : AccessibilityService() {
private val TAG = "AccessKeyDetector"
public override fun onKeyEvent(event: KeyEvent): Boolean {
Timber.d("Key pressed via accessibility is: " + event.keyCode)
if (event.action == KeyEvent.ACTION_UP) {
if (event.keyCode == KeyEvent.KEYCODE_PROG_GREEN) {
Core.startService()
Toast.makeText(applicationContext, "VPN On", Toast.LENGTH_SHORT).show()
} else if (event.keyCode == KeyEvent.KEYCODE_PROG_RED) {
Core.stopService()
Toast.makeText(applicationContext, "VPN Off", Toast.LENGTH_SHORT).show()
}
}
//This allows the key pressed to function normally after it has been used by your app.
return super.onKeyEvent(event)
}
override fun onServiceConnected() {
Log.d(TAG, "Service connected")
}
override fun onAccessibilityEvent(event: AccessibilityEvent) {
Log.d(TAG, "onAccessibilityEvent $event")
}
override fun onInterrupt() {
Log.d(TAG, "onAccessibilityEvent")
}
} | 0 | Kotlin | 0 | 0 | fdaacfa4e2479327134da3c301c46e8ed8319dec | 1,420 | shadowsocks-android | MIT License |
libs/logging/src/main/kotlin/batect/logging/FileLogSink.kt | batect | 102,647,061 | false | {"Kotlin": 2888008, "Python": 42425, "Shell": 33457, "PowerShell": 8340, "Dockerfile": 3386, "Batchfile": 3234, "Java": 1432, "HTML": 345} | /*
Copyright 2017-2022 <NAME>.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batect.logging
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardOpenOption
import java.time.ZoneOffset
import java.time.ZonedDateTime
class FileLogSink(
val path: Path,
private val writer: LogMessageWriter,
private val standardAdditionalDataSource: StandardAdditionalDataSource,
private val timestampSource: () -> ZonedDateTime,
) : LogSink {
private val lock = Object()
private val fileStream = Files.newOutputStream(path, StandardOpenOption.CREATE, StandardOpenOption.APPEND)
constructor(path: Path, writer: LogMessageWriter, standardAdditionalDataSource: StandardAdditionalDataSource) :
this(path, writer, standardAdditionalDataSource, { ZonedDateTime.now(ZoneOffset.UTC) })
override fun write(severity: Severity, loggerAdditionalData: Map<String, Jsonable>, build: LogMessageBuilder.() -> Unit) {
val builder = LogMessageBuilder(severity, loggerAdditionalData)
build(builder)
val message = builder.build(timestampSource, standardAdditionalDataSource)
synchronized(lock) {
writer.writeTo(message, fileStream)
}
}
}
| 24 | Kotlin | 49 | 687 | 67c942241c7d52b057c5268278d6252301c48087 | 1,768 | batect | Apache License 2.0 |
AndroidLint-7.4.2/lint-plugin/buildSrc/src/main/java/com/buildsrc/kts/Publish.kt | Western-parotia | 642,632,046 | false | null | package com.buildsrc.kts
import com.buildsrc.kts.Repositories.mavenPassword
import org.gradle.api.artifacts.dsl.RepositoryHandler
import org.gradle.api.publish.maven.MavenPublication
object Publish {
private const val VERSION = "0.0.4"
const val SNAPSHOT = false
// 基于 27.1.0版本的 lint gradle 进行二开,对应AGP 4.1.0
// AGP 7.4.2 对应的是 30.4.2
private const val ARTIFACT_ID = "${Dependencies.Lint.version}-lint-gradle"
//由于阿里云 制品 采取分仓管理snapshot版本,默认也会忽略-SNAPSHOT的策略模式,所以这里从group进行区分,便于管理
private val GROUP_ID = if (SNAPSHOT) "com.easelint.snapshot" else "com.easelint"
private fun getTimestamp(): String {
return java.text.SimpleDateFormat(
"yyyy-MM-dd-hh-mm-ss",
java.util.Locale.CHINA
).format(java.util.Date())
}
object Maven {
private val repositoryUserName: String
private val repositoryPassword: String
init {
val lp = PropertiesUtils.localProperties
val name = lp.getProperty("repositoryUserName")
val password = lp.getProperty("repositoryPassword")
if (name.isNullOrEmpty() || password.isNullOrEmpty()) {
throw IllegalArgumentException("请在local.properties添加私有仓库的用户名(repositoryUserName)和密码(repositoryPassword)")
}
repositoryUserName = name
repositoryPassword = <PASSWORD>
}
fun setGAV(mp: MavenPublication) {
mp.groupId = GROUP_ID
mp.artifactId = ARTIFACT_ID
mp.version = VERSION + "-" + getTimestamp()
println("publish=> ${mp.groupId}:${mp.artifactId}:${mp.version}")
}
/**
* 使用本地账号密码(用于推送)
*/
fun aliyunReleaseRepositories(rh: RepositoryHandler) {
rh.mavenPassword(
Repositories.aliyunReleaseAndArtifacts,
repositoryUserName,
repositoryPassword
)
}
fun aliyunSnapshotRepositories(rh: RepositoryHandler) {
rh.mavenPassword(
Repositories.aliyunSnapshotAndArtifacts,
repositoryUserName,
repositoryPassword
)
}
}
}
| 0 | Kotlin | 2 | 14 | a9e3988f1b0d3399a8343bb72fecc14fd71db4fe | 2,384 | EaseLint | MIT License |
compiler/testData/codegen/box/objects/safeAccess.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // KT-5159
object Test {
val a = "OK"
}
fun box(): String? = Test?.a
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 75 | kotlin | Apache License 2.0 |
judokit-android/src/main/java/com/judopay/judokit/android/service/CardTransactionManager.kt | Judopay | 261,378,339 | false | {"Kotlin": 924736} | package com.judopay.judokit.android.service
import android.content.Context
import android.util.Log
import androidx.fragment.app.FragmentActivity
import com.judopay.judo3ds2.exception.SDKAlreadyInitializedException
import com.judopay.judo3ds2.exception.SDKNotInitializedException
import com.judopay.judo3ds2.model.CompletionEvent
import com.judopay.judo3ds2.model.ConfigParameters
import com.judopay.judo3ds2.model.ProtocolErrorEvent
import com.judopay.judo3ds2.model.RuntimeErrorEvent
import com.judopay.judo3ds2.service.ThreeDS2Service
import com.judopay.judo3ds2.service.ThreeDS2ServiceImpl
import com.judopay.judo3ds2.transaction.Transaction
import com.judopay.judo3ds2.transaction.challenge.ChallengeStatusReceiver
import com.judopay.judokit.android.Judo
import com.judopay.judokit.android.api.JudoApiService
import com.judopay.judokit.android.api.factory.JudoApiServiceFactory
import com.judopay.judokit.android.api.model.request.Complete3DS2Request
import com.judopay.judokit.android.api.model.response.JudoApiCallResult
import com.judopay.judokit.android.api.model.response.Receipt
import com.judopay.judokit.android.api.model.response.getCReqParameters
import com.judopay.judokit.android.api.model.response.getChallengeParameters
import com.judopay.judokit.android.api.model.response.recommendation.RecommendationAction
import com.judopay.judokit.android.api.model.response.recommendation.toTransactionDetailsOverrides
import com.judopay.judokit.android.api.model.response.toJudoPaymentResult
import com.judopay.judokit.android.model.CardNetwork
import com.judopay.judokit.android.model.JudoError
import com.judopay.judokit.android.model.JudoPaymentResult
import com.judopay.judokit.android.model.TransactionDetails
import com.judopay.judokit.android.model.TransactionDetailsOverrides
import com.judopay.judokit.android.model.toCheckCardRequest
import com.judopay.judokit.android.model.toPaymentRequest
import com.judopay.judokit.android.model.toPreAuthRequest
import com.judopay.judokit.android.model.toPreAuthTokenRequest
import com.judopay.judokit.android.model.toRegisterCardRequest
import com.judopay.judokit.android.model.toSaveCardRequest
import com.judopay.judokit.android.model.toTokenRequest
import com.judopay.judokit.android.ui.common.getLocale
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import retrofit2.await
import java.util.WeakHashMap
interface ActivityAwareComponent {
fun updateActivity(activity: FragmentActivity)
}
open class SingletonHolder<out T : ActivityAwareComponent>(creator: (FragmentActivity) -> T) {
private var creator: ((FragmentActivity) -> T)? = creator
@Volatile
private var instance: T? = null
fun getInstance(arg: FragmentActivity): T {
val checkInstance = instance
if (checkInstance != null) {
checkInstance.updateActivity(arg)
return checkInstance
}
return synchronized(this) {
val checkInstanceAgain = instance
if (checkInstanceAgain != null) {
checkInstanceAgain.updateActivity(arg)
checkInstanceAgain
} else {
val created = creator!!(arg)
instance = created
creator = null
created
}
}
}
}
interface CardTransactionManagerResultListener {
fun onCardTransactionResult(result: JudoPaymentResult)
}
enum class TransactionType {
PAYMENT,
PRE_AUTH,
PAYMENT_WITH_TOKEN,
PRE_AUTH_WITH_TOKEN,
SAVE,
CHECK,
REGISTER
}
private val TransactionType.canBeSoftDeclined: Boolean
get() = arrayOf(
TransactionType.PAYMENT,
TransactionType.PRE_AUTH,
TransactionType.REGISTER,
TransactionType.PAYMENT_WITH_TOKEN,
TransactionType.PRE_AUTH_WITH_TOKEN
).contains(this)
private const val THREE_DS_TWO_MIN_TIMEOUT = 5
class CardTransactionManager private constructor(private var context: FragmentActivity) : ActivityAwareComponent {
private lateinit var judo: Judo
private lateinit var judoApiService: JudoApiService
private lateinit var recommendationService: RecommendationService
private var threeDS2Service: ThreeDS2Service = ThreeDS2ServiceImpl()
private var transaction: Transaction? = null
private var transactionDetails: TransactionDetails? = null
private val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
private val parameters = ConfigParameters()
private val locale = getLocale(context.resources)
private val listenerMap = WeakHashMap<String, CardTransactionManagerResultListener>()
private val results = HashMap<String, JudoPaymentResult>()
companion object : SingletonHolder<CardTransactionManager>(::CardTransactionManager)
override fun updateActivity(activity: FragmentActivity) {
context = activity
}
fun configureWith(config: Judo) = takeIf {
if (this::judo.isInitialized.not()) {
return@takeIf true
}
config != judo
}?.apply {
judo = config
judoApiService = JudoApiServiceFactory.create(context, config)
recommendationService = RecommendationService(context, config)
try {
threeDS2Service.cleanup(context)
} catch (e: SDKNotInitializedException) {
Log.w(CardTransactionManager::class.java.name, "3DS2 Service not initialized.")
}
try {
threeDS2Service.initialize(context, parameters, locale, judo.uiConfiguration.threeDSUiCustomization)
} catch (e: SDKAlreadyInitializedException) {
Log.w(CardTransactionManager::class.java.name, "3DS2 Service already initialized.")
}
}
fun unRegisterResultListener(
listener: CardTransactionManagerResultListener,
caller: String = listener::class.java.name
) {
listenerMap.remove(caller)
}
fun registerResultListener(
listener: CardTransactionManagerResultListener,
caller: String = listener::class.java.name
) {
listenerMap[caller] = listener
results[caller]?.let {
listener.onCardTransactionResult(it)
results.remove(caller)
}
}
private fun performJudoApiRequest(
type: TransactionType,
details: TransactionDetails,
transaction: Transaction,
overrides: TransactionDetailsOverrides?
) = when (type) {
TransactionType.PAYMENT -> {
val request = details.toPaymentRequest(
judo,
transaction,
overrides
)
judoApiService.payment(request)
}
TransactionType.PRE_AUTH -> {
val request = details.toPreAuthRequest(
judo,
transaction,
overrides
)
judoApiService.preAuthPayment(request)
}
TransactionType.PAYMENT_WITH_TOKEN -> {
val request = details.toTokenRequest(judo, transaction, overrides)
judoApiService.tokenPayment(request)
}
TransactionType.PRE_AUTH_WITH_TOKEN -> {
val request = details.toPreAuthTokenRequest(judo, transaction, overrides)
judoApiService.preAuthTokenPayment(request)
}
TransactionType.SAVE -> {
val request = details.toSaveCardRequest(judo, transaction)
judoApiService.saveCard(request)
}
TransactionType.CHECK -> {
val request = details.toCheckCardRequest(
judo,
transaction,
overrides
)
judoApiService.checkCard(request)
}
TransactionType.REGISTER -> {
val request = details.toRegisterCardRequest(judo, transaction, overrides)
judoApiService.registerCard(request)
}
}
private fun performTransaction(
type: TransactionType,
details: TransactionDetails,
caller: String,
overrides: TransactionDetailsOverrides? = null
) = try {
when {
overrides != null -> performJudoApiCall(type, details, caller, overrides) // soft decline case - we don't need to call recommendation service
recommendationService.isRecommendationFeatureAvailable(type) -> apply3DS2Optimisations(type, details, caller) // recommendation service is available, attempt to call it
else -> performJudoApiCall(type, details, caller) // fallback to default Judo API call
}
} catch (exception: Throwable) {
dispatchException(exception, caller)
}
private fun apply3DS2Optimisations(
type: TransactionType,
details: TransactionDetails,
caller: String
) = try {
val coroutineExceptionHandler = CoroutineExceptionHandler { _, throwable ->
Log.d(CardTransactionManager::class.java.name, "Uncaught Recommendation service exception", throwable)
performJudoApiCall(type, details, caller) // in case of any error, we fallback to Judo API call
}
applicationScope.launch(Dispatchers.Default + coroutineExceptionHandler) {
val result = recommendationService.fetchOptimizationData(details, type).await()
if (result.isValid) {
when (result.data?.action) {
RecommendationAction.PREVENT -> onResult(
JudoPaymentResult.Error(JudoError.judoRecommendationError(context.resources)),
caller
)
else -> performJudoApiCall(type, details, caller, result.toTransactionDetailsOverrides())
}
} else {
performJudoApiCall(type, details, caller) // in case of any error, we fallback to Judo API call
}
}
} catch (exception: Throwable) {
performJudoApiCall(type, details, caller) // in case of any error, we fallback to Judo API call
}
private fun performJudoApiCall(
type: TransactionType,
details: TransactionDetails,
caller: String,
overrides: TransactionDetailsOverrides? = null
) {
try {
val coroutineExceptionHandler = CoroutineExceptionHandler { _, throwable ->
Log.d(CardTransactionManager::class.java.name, "Uncaught 3DS2 Exception", throwable)
dispatchException(throwable, caller)
}
applicationScope.launch(Dispatchers.Default + coroutineExceptionHandler) {
try {
Log.d(CardTransactionManager::class.java.name, "initialize 3DS2 SDK")
threeDS2Service.initialize(
context,
parameters,
locale,
judo.uiConfiguration.threeDSUiCustomization
)
} catch (e: SDKAlreadyInitializedException) {
// This shouldn't cause any side effect.
Log.w(
CardTransactionManager::class.java.name,
"3DS2 Service already initialized."
)
}
val network = details.cardType ?: CardNetwork.OTHER
val directoryServerID = when {
judo.isSandboxed -> "F000000000"
network == CardNetwork.VISA -> "A000000003"
network == CardNetwork.MASTERCARD || network == CardNetwork.MAESTRO -> "A000000004"
network == CardNetwork.AMEX -> "A000000025"
else -> "unknown-id"
}
val myTransaction =
threeDS2Service.createTransaction(
directoryServerID,
judo.threeDSTwoMessageVersion
)
val apiResult = performJudoApiRequest(
type,
details,
myTransaction,
overrides
).await()
transactionDetails = details
transaction = myTransaction
handleJudoApiResult(type, details, caller, apiResult)
}
} catch (exception: Throwable) {
dispatchException(exception, caller)
}
}
private fun onResult(result: JudoPaymentResult, caller: String) {
results[caller] = result
listenerMap[caller]?.let {
it.onCardTransactionResult(result)
results.remove(caller)
}
closeTransaction(context)
}
private fun dispatchException(throwable: Throwable, caller: String) {
val error = JudoError.judoInternalError(throwable.message)
onResult(JudoPaymentResult.Error(error), caller)
}
private fun performComplete3ds2(receipt: Receipt, caller: String) {
val receiptId = receipt.receiptId ?: ""
val version = receipt.getCReqParameters()?.messageVersion ?: judo.threeDSTwoMessageVersion
val cv2 = transactionDetails?.securityNumber
applicationScope.launch {
val result =
judoApiService.complete3ds2(receiptId, Complete3DS2Request(version, cv2)).await()
onResult(result.toJudoPaymentResult(context.resources), caller)
}
}
private fun handleJudoApiResult(
type: TransactionType,
details: TransactionDetails,
caller: String,
result: JudoApiCallResult<Receipt>
) =
when (result) {
is JudoApiCallResult.Failure -> {
onResult(
(result as JudoApiCallResult<Receipt>).toJudoPaymentResult(context.resources),
caller
)
}
is JudoApiCallResult.Success -> if (result.data != null) {
val receipt = result.data
when {
type.canBeSoftDeclined && receipt.isSoftDeclined -> handleStepUpFlow(type, details, caller, receipt.receiptId!!)
receipt.isThreeDSecureTwoRequired -> handleThreeDSecureTwo(receipt, caller)
else -> onResult(result.toJudoPaymentResult(context.resources), caller)
}
} else {
onResult(result.toJudoPaymentResult(context.resources), caller)
}
}
private fun handleThreeDSecureTwo(receipt: Receipt, caller: String) {
val challengeStatusReceiver = object : ChallengeStatusReceiver {
override fun cancelled() {
performComplete3ds2(receipt, caller)
}
override fun completed(completionEvent: CompletionEvent) {
performComplete3ds2(receipt, caller)
}
override fun protocolError(protocolErrorEvent: ProtocolErrorEvent) {
performComplete3ds2(receipt, caller)
}
override fun runtimeError(runtimeErrorEvent: RuntimeErrorEvent) {
performComplete3ds2(receipt, caller)
}
override fun timedout() {
performComplete3ds2(receipt, caller)
}
}
transaction!!.doChallenge(
context,
receipt.getChallengeParameters(),
challengeStatusReceiver,
THREE_DS_TWO_MIN_TIMEOUT
)
}
fun payment(details: TransactionDetails, caller: String) {
performTransaction(TransactionType.PAYMENT, details, caller)
}
fun preAuth(details: TransactionDetails, caller: String) {
performTransaction(TransactionType.PRE_AUTH, details, caller)
}
fun paymentWithToken(details: TransactionDetails, caller: String) {
performTransaction(TransactionType.PAYMENT_WITH_TOKEN, details, caller)
}
fun preAuthWithToken(details: TransactionDetails, caller: String) {
performTransaction(TransactionType.PRE_AUTH_WITH_TOKEN, details, caller)
}
fun save(details: TransactionDetails, caller: String) {
performTransaction(TransactionType.SAVE, details, caller)
}
fun check(details: TransactionDetails, caller: String) {
performTransaction(TransactionType.CHECK, details, caller)
}
fun register(details: TransactionDetails, caller: String) {
performTransaction(TransactionType.REGISTER, details, caller)
}
private fun closeTransaction(context: Context) {
transaction?.close()
transaction = null
try {
threeDS2Service.cleanup(context)
} catch (exception: SDKNotInitializedException) {
Log.w(CardTransactionManager::class.java.name, exception.toString())
}
}
private fun handleStepUpFlow(
type: TransactionType,
details: TransactionDetails,
caller: String,
softDeclineReceiptId: String
) {
closeTransaction(context)
val overrides = TransactionDetailsOverrides(softDeclineReceiptId)
performTransaction(type, details, caller, overrides)
}
}
| 2 | Kotlin | 6 | 4 | 9255f02d876e1a19f750d13ff4ce4578c1bbf69d | 17,240 | JudoKit-Android | MIT License |
src/main/kotlin/com/ort/howlingwolf/domain/model/message/MessageType.kt | h-orito | 176,481,255 | false | null | package com.ort.howlingwolf.domain.model.message
import com.ort.dbflute.allcommon.CDef
data class MessageType(
val code: String,
val name: String
) {
constructor(
cdefMessageType: CDef.MessageType
) : this(
code = cdefMessageType.code(),
name = cdefMessageType.alias()
)
companion object {
val requiredCountTypeList: List<CDef.MessageType> = listOf(
CDef.MessageType.通常発言,
CDef.MessageType.死者の呻き,
CDef.MessageType.独り言,
CDef.MessageType.人狼の囁き,
CDef.MessageType.見学発言,
CDef.MessageType.共鳴発言
)
}
fun toCdef(): CDef.MessageType = CDef.MessageType.codeOf(code)
// 何回目の発言かを登録すべきか
fun shouldSetCount(): Boolean {
val cdefMessageType = this.toCdef()
return requiredCountTypeList.contains(cdefMessageType)
}
} | 0 | Kotlin | 1 | 3 | 7ef6d01ade6cfeb96935d6430a1a404bd67ae54e | 956 | howling-wolf-api | MIT License |
kotlintest-runner/kotlintest-runner-junit5/src/main/kotlin/io/kotlintest/runner/junit5/JUnitTestRunnerListener.kt | utikeev | 155,193,641 | true | {"Kotlin": 870811, "Java": 6857} | package io.kotlintest.runner.junit5
import com.google.common.io.Files
import io.kotlintest.Description
import io.kotlintest.Spec
import io.kotlintest.TestCase
import io.kotlintest.TestResult
import io.kotlintest.TestStatus
import io.kotlintest.TestType
import io.kotlintest.runner.jvm.TestEngineListener
import io.kotlintest.runner.jvm.TestSet
import org.junit.platform.engine.EngineExecutionListener
import org.junit.platform.engine.TestDescriptor
import org.junit.platform.engine.TestExecutionResult
import org.junit.platform.engine.UniqueId
import org.junit.platform.engine.support.descriptor.AbstractTestDescriptor
import org.junit.platform.engine.support.descriptor.ClassSource
import org.junit.platform.engine.support.descriptor.EngineDescriptor
import org.slf4j.LoggerFactory
import java.nio.charset.Charset
import java.nio.file.Paths
import kotlin.reflect.KClass
/**
* Notifies JUnit Platform of test statuses via a [EngineExecutionListener].
*
* JUnit platform supports out of order notification of tests, in that sibling
* tests can be executing in parallel and updating JUnit out of order. However the gradle test
* task gets confused if we are executing two or more tests directly under the root at once.
* Therefore we must queue up notifications until each spec is completed.
*
* Gradle test run observations:
*
* Top level descriptors must have a source attached or the execution will fail with a parent attached exception.
* Type.CONTAINER_TEST doesn't seem to work as a top level descriptor, it will hang
* leaf tests do not need to be completed but they will be marked as uncomplete in intellij.
* Dynamic test can be called after or before addChild.
* A Type.TEST can be a child of a Type.TEST.
* Intermediate Type.CONTAINER seem to be ignored in output.
* Intermediate containers can have same class source as parent.
* Type.TEST as top level seems to hang.
* A TEST doesn't seem to be able to have the same source as a parent, or hang.
* A TEST seems to hang if it has a ClassSource.
* MethodSource seems to be ok with a TEST.
* Container test names seem to be taken from a Source.
* Nested tests are outputted as siblings.
* Can complete executions out of order.
* Child failures will fail parent CONTAINER.
* Sibling containers can start and finish in parallel.
*
* Intellij runner observations:
*
* Intermediate Type.CONTAINERs are shown.
* Intermediate Type.TESTs are shown.
* A Type.TEST can be a child of a Type.TEST
* MethodSource seems to be ok with a TEST.
* Container test names seem to be taken from the name property.
* Nested tests are outputted as nested.
* Child failures will not fail containing TEST.
* child failures will fail a containing CONTAINER.
* Call addChild _before_ registering test otherwise will appear in the display out of order.
* Must start tests after their parent or they can go missing.
* Sibling containers can start and finish in parallel.
*/
class JUnitTestRunnerListener(private val listener: EngineExecutionListener,
val root: EngineDescriptor) : TestEngineListener {
private val logger = LoggerFactory.getLogger(this.javaClass)
data class ResultState(val testCase: TestCase, val result: TestResult)
// contains a mapping of a Description to a junit TestDescription
private val descriptors = HashMap<Description, TestDescriptor>()
// contains every test that was discovered but not necessarily executed
private val discovered = HashSet<Pair<Description, TestType>>()
// contains a set of all the tests we have notified as started, to avoid
// double notification when a test is set to run multiple times
private val started = HashSet<Description>()
// contains all the results generated by tests in this spec
// we store them all and mark the tests as finished only when we exit the spec
private val results = HashSet<ResultState>()
override fun engineStarted(classes: List<KClass<out Spec>>) {
logger.debug("Engine started; classes=[$classes]")
listener.executionStarted(root)
}
override fun engineFinished(t: Throwable?) {
logger.debug("Engine finished; throwable=[$t]")
val failures = results.filter { it.result.status == TestStatus.Failure || it.result.status == TestStatus.Error }.map { it.testCase.spec.javaClass.canonicalName }.distinct().joinToString("\n")
val dir = Paths.get(".kotlintest")
dir.toFile().mkdirs()
val path = dir.resolve("spec_failures").toAbsolutePath()
logger.debug("Writing report to $path")
Files.write(failures, path.toFile(), Charset.forName("UTF-8"))
val result = if (t == null) TestExecutionResult.successful() else TestExecutionResult.failed(t)
listener.executionFinished(root, result)
}
override fun prepareSpec(description: Description, klass: KClass<out Spec>) {
logger.debug("prepareSpec [$description]")
try {
val descriptor = createSpecDescriptor(description, klass)
listener.executionStarted(descriptor)
} catch (t: Throwable) {
logger.error("Error in JUnit Platform listener", t)
}
}
override fun prepareTestCase(testCase: TestCase) {
discovered.add(Pair(testCase.description, testCase.type))
}
override fun testRun(set: TestSet, k: Int) {
// we only "start" a test once, the first time a test is actually run, because
// at that point we know the test cannot be skipped. This is required because JUnit requires
// that we do not "start" a test that is later marked as skipped.
if (!started.contains(set.testCase.description)) {
started.add(set.testCase.description)
val clazz: KClass<out Spec> = Class.forName(set.testCase.spec.canonicalName()).kotlin as KClass<out Spec>
val descriptor = createTestCaseDescriptor(set.testCase.description, set.testCase.type, clazz)
logger.debug("Notifying junit of start event ${descriptor.uniqueId}")
listener.executionStarted(descriptor)
}
}
override fun completeTestCase(testCase: TestCase, result: TestResult) {
logger.debug("completeTestCase ${testCase.description} with result $result")
// we don't immediately finish a test, we just store the result until we have completed the spec
// this allows us to handle multiple invocations of the same test case, deferring the notification
// to junit until all invocations have completed
results.add(ResultState(testCase, result))
}
override fun completeSpec(description: Description, klass: KClass<out Spec>, t: Throwable?) {
logger.debug("completeSpec [$description]")
// we should have a result for at least every test that was discovered
// we wait until the spec is completed before completing all child scopes, because we need
// to wait until all possible invocations of each scope have completed.
// for each description we can grab the best result and use that
discovered
.filter { description.isAncestorOf(it.first) }
.sortedBy { it.first.depth() }
.reversed()
.forEach {
val descriptor = descriptors[it.first] ?: getOrCreateDescriptor(it.first, it.second, klass)
// find an error by priority
val result = findResultFor(it.first)
if (result == null) {
logger.error("Could not find result for $it")
throw RuntimeException("Every description must have a result but could not find one for $it")
} else {
logger.debug("Notifying junit of test case completion ${descriptor.uniqueId}=$result")
try {
when (result.status) {
TestStatus.Success -> listener.executionFinished(descriptor, TestExecutionResult.successful())
TestStatus.Error, TestStatus.Failure -> listener.executionFinished(descriptor, TestExecutionResult.failed(result.error))
TestStatus.Ignored -> listener.executionSkipped(descriptor, result.reason ?: "Test Ignored")
}
} catch (t: Throwable) {
logger.error("Error in JUnit Platform listener", t)
}
}
}
// now we can complete the spec
val descriptor = descriptors[description]
if (descriptor == null) {
logger.error("Spec descriptor cannot be null $description")
throw RuntimeException("Spec descriptor cannot be null")
} else {
val result = if (t == null) TestExecutionResult.successful() else TestExecutionResult.failed(t)
logger.debug("Notifying junit that spec finished ${descriptor.uniqueId} $result")
listener.executionFinished(descriptor, result)
}
}
private fun getOrCreateDescriptor(description: Description, type: TestType, klazz: KClass<out Spec>? = null): TestDescriptor {
if (klazz == null){
return descriptors.getOrPut(description) { createTestCaseDescriptor(description, type) }
} else {
return descriptors.getOrPut(description) { createTestCaseDescriptor(description, type, klazz) }
}
}
// returns the most important result for a given description
// by searching all the results stored for that description and child descriptions
private fun findResultFor(description: Description): TestResult? {
fun findByStatus(status: TestStatus): TestResult? = results
.filter { it.testCase.description == description || description.isAncestorOf(it.testCase.description) }
.filter { it.result.status == status }
.map { it.result }
.firstOrNull()
var result = findByStatus(TestStatus.Error)
if (result == null)
result = findByStatus(TestStatus.Failure)
if (result == null)
result = findByStatus(TestStatus.Success)
if (result == null)
result = findByStatus(TestStatus.Ignored)
return result
}
private fun createTestCaseDescriptor(description: Description, type: TestType, klazz: KClass<out Spec>? = null): TestDescriptor {
logger.debug("Creating test case descriptor $description/$type")
val parentDescription = description.parent() ?: throw RuntimeException("All test cases must have a parent")
val parent = descriptors[parentDescription]!!
val id = parent.uniqueId.append("test", description.name)
var descriptor: AbstractTestDescriptor
val source = ClassSource.from(klazz?.java) ?: null
descriptor = object : AbstractTestDescriptor(id, description.name, source) {
override fun getType(): TestDescriptor.Type {
// there is a bug in gradle 4.7+ whereby CONTAINER_AND_TEST breaks test reporting, as it is not handled
// see https://github.com/gradle/gradle/issues/4912
// so we can't use CONTAINER_AND_TEST for our test scopes, but simply container
return when (type) {
TestType.Container -> TestDescriptor.Type.CONTAINER
TestType.Test -> TestDescriptor.Type.TEST
}
}
override fun mayRegisterTests(): Boolean = type == TestType.Container
}
descriptors[description] = descriptor
parent.addChild(descriptor)
listener.dynamicTestRegistered(descriptor)
return descriptor
}
private fun createSpecDescriptor(description: Description, klass: KClass<out Spec>): TestDescriptor {
val id = root.uniqueId.appendSpec(description)
val source = ClassSource.from(klass.java)
val descriptor = object : AbstractTestDescriptor(id, description.name, source) {
override fun getType(): TestDescriptor.Type = TestDescriptor.Type.CONTAINER
override fun mayRegisterTests(): Boolean = true
}
descriptors[description] = descriptor
// we need to synchronize because we don't want to allow multiple specs adding
// to the root container at the same time
root.addChild(descriptor)
listener.dynamicTestRegistered(descriptor)
return descriptor
}
}
fun UniqueId.appendSpec(description: Description) = this.append("spec", description.name)!! | 1 | Kotlin | 0 | 0 | f7e08859343c09289778c17b16830b4325046f11 | 11,865 | kotlintest | Apache License 2.0 |
src/main/kotlin/de/debuglevel/cvodb2xml/import/odb/OdbImporter.kt | debuglevel | 162,049,850 | false | {"HTML": 24551, "Kotlin": 22759, "XSLT": 3919, "Shell": 1743, "Dockerfile": 1480, "Batchfile": 236} | package de.debuglevel.cvodb2xml.import.odb
import com.github.rjeschke.txtmark.Processor
import de.debuglevel.cvodb2xml.import.Importer
import de.debuglevel.cvodb2xml.model.Position
import de.debuglevel.cvodb2xml.model.Skill
import de.debuglevel.cvodb2xml.model.SkillComparison
import mu.KotlinLogging
import java.nio.file.Path
import java.sql.Connection
import java.sql.DriverManager
import java.sql.SQLException
import java.time.LocalDate
class OdbImporter(private val odbPath: Path) : Importer {
private val logger = KotlinLogging.logger {}
init {
logger.debug { "Initializing OdbImporter..." }
logger.debug { "Loading OdbDriver..." }
Class.forName("de.debuglevel.odbjdbc.OdbDriver")
}
override val positions: List<Position>
get() {
val databasePath = odbPath.toFile().invariantSeparatorsPath
var connection: Connection? = null
val database = "jdbc:odb://file=$databasePath"
val positions = mutableListOf<Position>()
try {
// Create database connection
logger.debug { "Opening connection to $database..." }
connection = DriverManager.getConnection(database)
// Create and execute statement
val statement = connection.createStatement()
val resultset = statement.executeQuery("SELECT * FROM \"PUBLIC\".\"Positionen\"")
while (resultset.next()) {
logger.debug { "Reading next position from database..." }
val position = Position(
resultset.getString("id").toInt(),
resultset.getString("positiontitle"),
Processor.process(resultset.getString("description")),
LocalDate.parse(resultset.getString("begindate")),
if (resultset.getString("enddate").isNullOrBlank()) null else LocalDate.parse(
resultset.getString(
"enddate"
)
),
resultset.getString("place"),
resultset.getString("placeurl"),
resultset.getString("category"),
resultset.getString("industrialsector"),
resultset.getString("placesize"),
resultset.getString("department"),
resultset.getString("activity")
)
positions.add(position)
logger.debug { "Added position: $position" }
}
resultset.close()
statement.close()
} catch (e: SQLException) {
logger.error(e) { "Error handling database" }
throw e
} finally {
try {
connection?.close()
} catch (e: SQLException) {
logger.error(e) { "Error handling database" }
throw e
}
}
return positions
}
override val skills: List<Skill>
get() {
val databasePath = odbPath.toFile().invariantSeparatorsPath
var connection: Connection? = null
val database = "jdbc:odb://file=$databasePath"
val skills = mutableListOf<Skill>()
try {
// Create database connection
logger.debug { "Opening connection to $database..." }
connection = DriverManager.getConnection(database)
// Create and execute statement
val statement = connection.createStatement()
val resultset = statement.executeQuery("SELECT * FROM \"PUBLIC\".\"Fähigkeiten\"")
while (resultset.next()) {
logger.debug { "Reading next skill from database..." }
val skill = Skill(
resultset.getString("id").toInt(),
resultset.getString("category"),
resultset.getString("level"),
resultset.getString("label"),
resultset.getString("description"),
resultset.getString("subcategory")
)
skills.add(skill)
logger.debug { "Added skill: $skill" }
}
resultset.close()
statement.close()
} catch (e: SQLException) {
logger.error(e) { "Error handling database" }
throw e
} finally {
try {
connection?.close()
} catch (e: SQLException) {
logger.error(e) { "Error handling database" }
throw e
}
}
return skills
}
override val skillComparisons: List<SkillComparison>
get() {
val skills = this.skills
val databasePath = odbPath.toFile().invariantSeparatorsPath
var connection: Connection? = null
val database = "jdbc:odb://file=$databasePath"
val skillComparisons = mutableListOf<SkillComparison>()
try {
// Create database connection
logger.debug { "Opening connection to $database..." }
connection = DriverManager.getConnection(database)
// Create and execute statement
val statement = connection.createStatement()
val resultset = statement.executeQuery("SELECT * FROM \"PUBLIC\".\"SkillVergleich\"")
while (resultset.next()) {
logger.debug { "Reading next skill comparison from database..." }
val betterSkillId = resultset.getString("better_skill").toInt()
val worseSkillId = resultset.getString("worse_skill").toInt()
val skillComparison = SkillComparison(
betterSkillId,
worseSkillId,
skills.single { it.id == betterSkillId },
skills.single { it.id == worseSkillId }
)
skillComparisons.add(skillComparison)
logger.debug { "Added skill comparison: $skillComparison" }
}
resultset.close()
statement.close()
} catch (e: SQLException) {
logger.error(e) { "Error handling database" }
throw e
} finally {
try {
connection?.close()
} catch (e: SQLException) {
logger.error(e) { "Error handling database" }
throw e
}
}
return skillComparisons
}
} | 0 | HTML | 0 | 0 | 65abb4bd1e464dcd29c116b5ba8e2acec88dae04 | 7,004 | cv-odb-converter | The Unlicense |
app/src/main/kotlin/org/mifos/mobile/cn/ui/utils/ProgressBarHandler.kt | openMF | 133,982,000 | false | null | package org.mifos.mobile.cn.ui.utils
import android.R.attr
import android.R.id
import android.app.Activity
import android.content.Context
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import android.widget.RelativeLayout
import android.widget.RelativeLayout.LayoutParams
/**
* @author <NAME>
*/
class ProgressBarHandler constructor(context: Context) {
private val progressBar: ProgressBar
init {
val layout = (context as Activity).findViewById<View>(id.content).rootView as ViewGroup
progressBar = ProgressBar(context, null, attr.progressBarStyleInverse)
progressBar.isIndeterminate = true
val params = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
val relativeLayout = RelativeLayout(context)
relativeLayout.gravity = Gravity.CENTER
relativeLayout.addView(progressBar)
layout.addView(relativeLayout, params)
hide()
}
fun show() {
progressBar.visibility = View.VISIBLE
}
fun hide() {
progressBar.visibility = View.INVISIBLE
}
} | 66 | Kotlin | 65 | 37 | 2dd8750cb34e62e9458469da09c3fb55a258b067 | 1,157 | mifos-mobile-cn | Apache License 2.0 |
compiler/cli/cli-js/src/org/jetbrains/kotlin/cli/js/dce/K2JSDce.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.cli.js.dce
import org.jetbrains.kotlin.cli.common.CLITool
import org.jetbrains.kotlin.cli.common.ExitCode
import org.jetbrains.kotlin.cli.common.arguments.DevModeOverwritingStrategies
import org.jetbrains.kotlin.cli.common.arguments.K2JSDceArguments
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.config.Services
import org.jetbrains.kotlin.js.dce.*
import org.jetbrains.kotlin.js.sourceMap.RelativePathCalculator
import org.jetbrains.kotlin.js.parser.sourcemaps.*
import java.io.*
import java.util.zip.ZipFile
class K2JSDce : CLITool<K2JSDceArguments>() {
override fun createArguments(): K2JSDceArguments = K2JSDceArguments()
override fun execImpl(messageCollector: MessageCollector, services: Services, arguments: K2JSDceArguments): ExitCode {
val baseDir = File(arguments.outputDirectory ?: "min")
val files = arguments.freeArgs.flatMap { arg ->
collectInputFiles(baseDir, arg, messageCollector)
}
if (messageCollector.hasErrors()) return ExitCode.COMPILATION_ERROR
if (files.isEmpty() && !arguments.version) {
messageCollector.report(CompilerMessageSeverity.ERROR, "no source files")
return ExitCode.COMPILATION_ERROR
}
val existingFiles = mutableMapOf<String, InputFile>()
for (file in files) {
existingFiles[file.outputPath]?.let {
messageCollector.report(
CompilerMessageSeverity.ERROR,
"duplicate target file will be created for '${file.resource.name}' and '${it.resource.name}'"
)
return ExitCode.COMPILATION_ERROR
}
existingFiles[file.outputPath] = file
if (File(file.outputPath).isDirectory) {
messageCollector.report(CompilerMessageSeverity.ERROR, "cannot open output file '${file.outputPath}': it is a directory")
return ExitCode.COMPILATION_ERROR
}
}
return if (!arguments.devMode) {
performDce(files, arguments, messageCollector)
} else {
val devModeOverwritingStrategy =
arguments.devModeOverwritingStrategy ?:
System.getProperty("kotlin.js.dce.devmode.overwriting.strategy", DevModeOverwritingStrategies.OLDER)
val overwriteOnlyOlderFiles = devModeOverwritingStrategy == DevModeOverwritingStrategies.OLDER
copyFiles(files, overwriteOnlyOlderFiles)
ExitCode.OK
}
}
private fun performDce(files: List<InputFile>, arguments: K2JSDceArguments, messageCollector: MessageCollector): ExitCode {
val includedDeclarations = arguments.declarationsToKeep.orEmpty().toSet()
val logConsumer = { level: DCELogLevel, message: String ->
val severity = when (level) {
DCELogLevel.ERROR -> CompilerMessageSeverity.ERROR
DCELogLevel.WARN -> CompilerMessageSeverity.WARNING
DCELogLevel.INFO -> CompilerMessageSeverity.LOGGING
}
messageCollector.report(severity, message)
}
val dceResult = DeadCodeElimination.run(
files,
includedDeclarations,
arguments.printReachabilityInfo,
logConsumer
)
if (dceResult.status == DeadCodeEliminationStatus.FAILED) return ExitCode.COMPILATION_ERROR
if (arguments.printReachabilityInfo) {
val reachabilitySeverity = CompilerMessageSeverity.INFO
messageCollector.report(reachabilitySeverity, "")
for (node in dceResult.reachableNodes.extractReachableRoots(dceResult.context!!)) {
printTree(
node, { messageCollector.report(reachabilitySeverity, it) },
printNestedMembers = false, showLocations = true
)
}
}
return ExitCode.OK
}
private fun copyFiles(files: List<InputFile>, overwriteOnlyOlderFiles: Boolean) {
for (file in files) {
copyResource(file.resource, File(file.outputPath), overwriteOnlyOlderFiles)
file.sourceMapResource?.let { sourceMap ->
val sourceMapTarget = File(file.outputPath + ".map")
val inputFile = File(sourceMap.name)
if (!inputFile.exists() || !mapSourcePaths(inputFile, sourceMapTarget)) {
copyResource(sourceMap, sourceMapTarget, overwriteOnlyOlderFiles)
}
}
}
}
private fun copyResource(resource: InputResource, targetFile: File, overwriteOnlyOlderFiles: Boolean) {
// TODO shouldn't it be "<="?
if (overwriteOnlyOlderFiles && targetFile.exists() && resource.lastModified() < targetFile.lastModified()) return
targetFile.parentFile.mkdirs()
resource.reader().use { input ->
FileOutputStream(targetFile).use { output ->
input.copyTo(output)
}
}
}
private fun mapSourcePaths(inputFile: File, targetFile: File): Boolean {
val jsonOut = StringWriter()
val pathCalculator = RelativePathCalculator(targetFile.parentFile)
val sourceMapChanged = try {
SourceMap.mapSources(inputFile.readText(), jsonOut) {
val result = pathCalculator.calculateRelativePathTo(File(inputFile.parentFile, it))
if (result != null) {
if (File(targetFile.parentFile, result).exists()) {
result
} else {
it
}
} else {
it
}
}
} catch (e: SourceMapSourceReplacementException) {
false
}
if (!sourceMapChanged) return false
targetFile.parentFile.mkdirs()
OutputStreamWriter(FileOutputStream(targetFile), "UTF-8").use { it.write(jsonOut.toString()) }
return true
}
private fun collectInputFiles(baseDir: File, fileName: String, messageCollector: MessageCollector): List<InputFile> {
val file = File(fileName)
return when {
file.isDirectory -> {
collectInputFilesFromDirectory(baseDir, fileName)
}
file.isFile -> {
when {
fileName.endsWith(".js") -> {
listOf(singleInputFile(baseDir, fileName))
}
fileName.endsWith(".zip") || fileName.endsWith(".jar") -> {
collectInputFilesFromZip(baseDir, fileName)
}
else -> {
messageCollector.report(
CompilerMessageSeverity.WARNING,
"invalid file name '${file.absolutePath}'; must end either with '.js', '.zip' or '.jar'"
)
emptyList()
}
}
}
else -> {
messageCollector.report(CompilerMessageSeverity.ERROR, "source file or directory not found: $fileName")
emptyList()
}
}
}
private fun singleInputFile(baseDir: File, path: String): InputFile {
val moduleName = getModuleNameFromPath(path)
val pathToSourceMapCandidate = "$path.map"
val pathToSourceMap = if (File(pathToSourceMapCandidate).exists()) pathToSourceMapCandidate else null
return InputFile(
InputResource.file(path), pathToSourceMap?.let { InputResource.file(it) },
File(baseDir, "$moduleName.js").absolutePath, moduleName
)
}
private fun collectInputFilesFromZip(baseDir: File, path: String): List<InputFile> {
return ZipFile(path).use { zipFile ->
zipFile.entries().asSequence()
.filter { !it.isDirectory }
.filter { it.name.endsWith(".js") }
.filter { zipFile.getEntry(it.name.metaJs()) != null }
.distinctBy { it.name }
.map { entry ->
val moduleName = getModuleNameFromPath(entry.name)
val pathToSourceMapCandidate = "${entry.name}.map"
val pathToSourceMap = if (zipFile.getEntry(pathToSourceMapCandidate) != null) pathToSourceMapCandidate else null
InputFile(
InputResource.zipFile(path, entry.name), pathToSourceMap?.let { InputResource.zipFile(path, it) },
File(baseDir, "$moduleName.js").absolutePath, moduleName
)
}
.toList()
}
}
private fun collectInputFilesFromDirectory(baseDir: File, path: String): List<InputFile> {
return File(path).walkTopDown().asSequence()
.filter { !it.isDirectory }
.filter { it.name.endsWith(".js") }
.filter { File(it.path.metaJs()).exists() }
.map { entry ->
val moduleName = getModuleNameFromPath(entry.name)
val pathToSourceMapCandidate = "${entry.path}.map"
val pathToSourceMap = if (File(pathToSourceMapCandidate).exists()) pathToSourceMapCandidate else null
InputFile(
InputResource.file(entry.path), pathToSourceMap?.let { InputResource.file(it) },
File(baseDir, "$moduleName.js").absolutePath, moduleName
)
}
.toList()
}
private fun String.metaJs() = removeSuffix(".js") + ".meta.js"
private fun getModuleNameFromPath(path: String): String {
val dotIndex = path.lastIndexOf('.')
val slashIndex = maxOf(path.lastIndexOf('/'), path.lastIndexOf('\\'))
return path.substring(slashIndex + 1, if (dotIndex < 0) path.length else dotIndex)
}
override fun executableScriptFileName(): String = "kotlin-dce-js"
companion object {
@JvmStatic
fun main(args: Array<String>) {
CLITool.doMain(K2JSDce(), args)
}
}
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 10,478 | kotlin | Apache License 2.0 |
app/src/main/java/com/comseung/matrixexpert/MainActivity.kt | comseung18 | 612,627,693 | false | null | package com.comseung.matrixexpert
import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.ContextWrapper
import android.content.pm.ActivityInfo
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AddCircle
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Color.Companion.Yellow
import androidx.compose.ui.platform.LocalContext
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.comseung.matrixexpert.presentation.add_matrix.AddMatrixScreen
import com.comseung.matrixexpert.presentation.home.HomeScreen
import com.comseung.matrixexpert.presentation.home.HomeViewModel
import com.comseung.matrixexpert.ui.theme.MatrixExpertTheme
import dagger.hilt.android.AndroidEntryPoint
import dagger.hilt.android.lifecycle.HiltViewModel
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
@OptIn(ExperimentalMaterial3Api::class)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MatrixExpertTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
val navController = rememberNavController()
Scaffold(
topBar = {
TopAppBar(
title = {
Text(
text = "Matrix Expert",
color = MaterialTheme.colorScheme.onPrimary
)
},
colors = TopAppBarDefaults.smallTopAppBarColors(
containerColor =
MaterialTheme.colorScheme.primary
),
actions = {
IconButton(onClick = {
navController.navigate("add_matrix")
}) {
Icon(
imageVector = Icons.Filled.AddCircle,
contentDescription = "Share",
tint = Color.White
)
}
}
)
},
) { paddingValues ->
MyAppNavHost(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues),
navController = navController
)
}
}
}
}
}
@Composable
private fun MyAppNavHost(
modifier: Modifier = Modifier,
navController: NavHostController,
startDestination: String = "home"
) {
NavHost(
modifier = modifier,
navController = navController,
startDestination = startDestination
) {
composable("home") {
HomeScreen(
onNavigationToAddMatrix = { navController.navigate("add_matrix") },
viewModel = hiltViewModel(),
)
}
composable("add_matrix") {
AddMatrixScreen(
onNavigationToHome = { navController.navigate("home") },
viewModel = hiltViewModel(),
)
}
}
}
}
private fun Context.findActivity(): Activity? = when (this) {
is Activity -> this
is ContextWrapper -> baseContext.findActivity()
else -> null
}
@Composable
fun LockScreenOrientation(orientation: Int) {
val context = LocalContext.current
DisposableEffect(orientation) {
val activity = context.findActivity() ?: return@DisposableEffect onDispose {}
val originalOrientation = activity.requestedOrientation
activity.requestedOrientation = orientation
onDispose {
// restore original orientation when view disappears
activity.requestedOrientation = originalOrientation
}
}
} | 0 | Kotlin | 0 | 0 | 3e1af5ca45325d102e268dc6c5d575584b9279a9 | 5,225 | MatrixExpert | Apache License 2.0 |
app/src/unitTest/kotlin/batect/execution/model/stages/RunStagePlannerSpec.kt | batect | 102,647,061 | false | {"Kotlin": 2888008, "Python": 42425, "Shell": 33457, "PowerShell": 8340, "Dockerfile": 3386, "Batchfile": 3234, "Java": 1432, "HTML": 345} | /*
Copyright 2017-2022 <NAME>.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batect.execution.model.stages
import batect.config.BuildImage
import batect.config.Container
import batect.config.ContainerMap
import batect.config.LiteralValue
import batect.config.PortMapping
import batect.config.PullImage
import batect.config.Task
import batect.config.TaskMap
import batect.config.TaskRunConfiguration
import batect.config.TaskSpecialisedConfiguration
import batect.execution.ContainerDependencyGraph
import batect.execution.model.rules.TaskStepRule
import batect.execution.model.rules.run.BuildImageStepRule
import batect.execution.model.rules.run.CreateContainerStepRule
import batect.execution.model.rules.run.PrepareTaskNetworkStepRule
import batect.execution.model.rules.run.PullImageStepRule
import batect.execution.model.rules.run.RunContainerSetupCommandsStepRule
import batect.execution.model.rules.run.RunContainerStepRule
import batect.execution.model.rules.run.WaitForContainerToBecomeHealthyStepRule
import batect.testutils.createLoggerForEachTest
import batect.testutils.given
import batect.testutils.on
import batect.testutils.pathResolutionContextDoesNotMatter
import batect.testutils.runForEachTest
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.hasElement
import com.natpryce.hamkrest.hasSize
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.Suite
import org.spekframework.spek2.style.specification.describe
object RunStagePlannerSpec : Spek({
describe("a run stage planner") {
val logger by createLoggerForEachTest()
fun Suite.itCreatesStageWithRules(graph: ContainerDependencyGraph, expectedRules: Map<String, TaskStepRule>) {
val stage by runForEachTest { RunStagePlanner(graph, logger).createStage() }
expectedRules.forEach { (description, expectedRule) ->
it("includes a rule to $description") {
assertThat(stage.rules, hasElement(expectedRule))
}
}
it("only includes the expected rules") {
assertThat(stage.rules, hasSize(equalTo(expectedRules.size)))
}
it("passes the main container to the stage") {
assertThat(stage.taskContainer, equalTo(graph.taskContainerNode.container))
}
}
given("the task has a single container") {
given("the task has no additional environment variables or port mappings") {
val task = Task("the-task", TaskRunConfiguration("the-container"))
on("that container pulls an existing image") {
val container = Container(task.runConfiguration!!.container, PullImage("some-image"))
val config = TaskSpecialisedConfiguration("the-project", TaskMap(task), ContainerMap(container))
val graph = ContainerDependencyGraph(config, task)
itCreatesStageWithRules(
graph,
mapOf(
"prepare the task network" to PrepareTaskNetworkStepRule,
"pull the image for the task container" to PullImageStepRule(PullImage("some-image")),
"create the task container" to CreateContainerStepRule(container),
"run the task container" to RunContainerStepRule(container, emptySet()),
"wait for the task container to become healthy" to WaitForContainerToBecomeHealthyStepRule(container),
"run setup commands for the task container" to RunContainerSetupCommandsStepRule(container),
),
)
}
on("that container builds an image from a Dockerfile") {
val imageSource = BuildImage(LiteralValue("./my-image"), pathResolutionContextDoesNotMatter(), mapOf("some_arg" to LiteralValue("some_value")), "some-Dockerfile")
val container = Container(task.runConfiguration!!.container, imageSource)
val config = TaskSpecialisedConfiguration("the-project", TaskMap(task), ContainerMap(container))
val graph = ContainerDependencyGraph(config, task)
itCreatesStageWithRules(
graph,
mapOf(
"prepare the task network" to PrepareTaskNetworkStepRule,
"build the image for the task container" to BuildImageStepRule(container),
"create the task container" to CreateContainerStepRule(container),
"run the task container" to RunContainerStepRule(container, emptySet()),
"wait for the task container to become healthy" to WaitForContainerToBecomeHealthyStepRule(container),
"run setup commands for the task container" to RunContainerSetupCommandsStepRule(container),
),
)
}
}
}
given("the task has multiple containers") {
val task = Task("the-task", TaskRunConfiguration("task-container", additionalEnvironmentVariables = mapOf("SOME_VAR" to LiteralValue("some value")), additionalPortMappings = setOf(PortMapping(123, 456))))
given("each container has a unique build directory or existing image to pull") {
val container1ImageSource = BuildImage(LiteralValue("./container-1"), pathResolutionContextDoesNotMatter())
val container1 = Container("container-1", container1ImageSource)
val container2ImageSource = PullImage("image-2")
val container2 = Container("container-2", container2ImageSource)
val container3ImageSource = PullImage("image-3")
val container3 = Container("container-3", container3ImageSource, dependencies = setOf(container2.name))
val taskContainerImageSource = BuildImage(LiteralValue("./task-container"), pathResolutionContextDoesNotMatter())
val taskContainer = Container(task.runConfiguration!!.container, taskContainerImageSource, dependencies = setOf(container1.name, container2.name, container3.name))
val config = TaskSpecialisedConfiguration("the-project", TaskMap(task), ContainerMap(taskContainer, container1, container2, container3))
val graph = ContainerDependencyGraph(config, task)
itCreatesStageWithRules(
graph,
mapOf(
"prepare the task network" to PrepareTaskNetworkStepRule,
"build the image for the task container" to BuildImageStepRule(taskContainer),
"build the image for container 1" to BuildImageStepRule(container1),
"pull the image for container 2" to PullImageStepRule(container2ImageSource),
"pull the image for container 3" to PullImageStepRule(container3ImageSource),
"create the task container" to CreateContainerStepRule(taskContainer),
"create the container for container 1" to CreateContainerStepRule(container1),
"create the container for container 2" to CreateContainerStepRule(container2),
"create the container for container 3" to CreateContainerStepRule(container3),
"run the task container" to RunContainerStepRule(taskContainer, graph.nodeFor(taskContainer).dependsOnContainers),
"run container 1" to RunContainerStepRule(container1, graph.nodeFor(container1).dependsOnContainers),
"run container 2" to RunContainerStepRule(container2, graph.nodeFor(container2).dependsOnContainers),
"run container 3" to RunContainerStepRule(container3, graph.nodeFor(container3).dependsOnContainers),
"wait for the task container to become healthy" to WaitForContainerToBecomeHealthyStepRule(taskContainer),
"wait for container 1 to become healthy" to WaitForContainerToBecomeHealthyStepRule(container1),
"wait for container 2 to become healthy" to WaitForContainerToBecomeHealthyStepRule(container2),
"wait for container 3 to become healthy" to WaitForContainerToBecomeHealthyStepRule(container3),
"run setup commands for the task container" to RunContainerSetupCommandsStepRule(taskContainer),
"run setup commands for container 1" to RunContainerSetupCommandsStepRule(container1),
"run setup commands for container 2" to RunContainerSetupCommandsStepRule(container2),
"run setup commands for container 3" to RunContainerSetupCommandsStepRule(container3),
),
)
}
given("some containers share an existing image to pull") {
val sharedImageSource = PullImage("shared-image")
val container1 = Container("container-1", sharedImageSource)
val container2 = Container("container-2", sharedImageSource)
val taskContainerImageSource = PullImage("task-image")
val taskContainer = Container(task.runConfiguration!!.container, taskContainerImageSource, dependencies = setOf(container1.name, container2.name))
val config = TaskSpecialisedConfiguration("the-project", TaskMap(task), ContainerMap(taskContainer, container1, container2))
val graph = ContainerDependencyGraph(config, task)
itCreatesStageWithRules(
graph,
mapOf(
"prepare the task network" to PrepareTaskNetworkStepRule,
"pull the image for the task container" to PullImageStepRule(taskContainerImageSource),
"pull the image shared by both container 1 and 2" to PullImageStepRule(sharedImageSource),
"create the task container" to CreateContainerStepRule(taskContainer),
"create the container for container 1" to CreateContainerStepRule(container1),
"create the container for container 2" to CreateContainerStepRule(container2),
"run the task container" to RunContainerStepRule(taskContainer, graph.nodeFor(taskContainer).dependsOnContainers),
"run container 1" to RunContainerStepRule(container1, graph.nodeFor(container1).dependsOnContainers),
"run container 2" to RunContainerStepRule(container2, graph.nodeFor(container2).dependsOnContainers),
"wait for the task container to become healthy" to WaitForContainerToBecomeHealthyStepRule(taskContainer),
"wait for container 1 to become healthy" to WaitForContainerToBecomeHealthyStepRule(container1),
"wait for container 2 to become healthy" to WaitForContainerToBecomeHealthyStepRule(container2),
"run setup commands for the task container" to RunContainerSetupCommandsStepRule(taskContainer),
"run setup commands for container 1" to RunContainerSetupCommandsStepRule(container1),
"run setup commands for container 2" to RunContainerSetupCommandsStepRule(container2),
),
)
}
}
}
})
| 24 | Kotlin | 49 | 687 | 67c942241c7d52b057c5268278d6252301c48087 | 12,283 | batect | Apache License 2.0 |
js/js.translator/testData/box/number/numberIsCheck.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // EXPECTED_REACHABLE_NODES: 1286
package foo
// For now, check is Byte(is Short, is Int is Float, is Double) translates to typeof ... == "number"
fun testNum(numX: Number) {
assertEquals(true, numX is Number, "numX is Number")
assertEquals(true, numX is Int, "numX is Int")
assertEquals(true, numX is Short, "numX is Short")
assertEquals(true, numX is Byte, "numX is Byte")
assertEquals(false, numX is Long, "numX is Long")
assertEquals(true, numX is Double, "numX is Double")
assertEquals(true, numX is Float, "numX is Float")
}
fun testAny(anyX: Any) {
assertEquals(true, anyX is Number, "anyX is Number")
assertEquals(true, anyX is Int, "anyX is Int")
assertEquals(true, anyX is Short, "anyX is Short")
assertEquals(true, anyX is Byte, "anyX is Byte")
assertEquals(false, anyX is Long, "anyX is Long")
assertEquals(true, anyX is Double, "anyX is Double")
assertEquals(true, anyX is Float, "anyX is Float")
}
fun box(): String {
val intX = 100
assertEquals(true, intX is Number, "intX is Number")
assertEquals(true, intX is Int, "intX is Int")
var anyX: Any = "A"
assertEquals(false, anyX is Number, "anyX is Number")
testNum(100)
testNum(100.toShort())
testNum(100.toByte())
testNum(100.0)
testNum(100.0f)
anyX = 100L
assertEquals(true, anyX is Number, "anyX is Number")
assertEquals(true, anyX is Long, "anyX is Long")
assertEquals(false, anyX is Int, "anyX is Int")
return "OK"
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 1,515 | kotlin | Apache License 2.0 |
src/test/java/nextstep/subway/multitenant/LGUPlusEventAcceptanceTest.kt | just-hazard | 387,483,236 | false | {"SCSS": 108481, "Vue": 68909, "Kotlin": 50715, "JavaScript": 23883, "HTML": 1000} | package nextstep.subway.multitenant
import com.funnc.shop.api.event.lguplus.dto.LgEventCouponRequest
import io.restassured.RestAssured
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.web.server.LocalServerPort
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DisplayName("LGU+ 관련 이벤트")
class LGUPlusEventAcceptanceTest {
@LocalServerPort
var port = 0
@BeforeEach
fun setUp() {
if (RestAssured.port == RestAssured.UNDEFINED_PORT) {
RestAssured.port = port
}
}
@Test
fun `이벤트 쿠폰 등록`() {
// 시나리오
// 이벤트 쿠폰 request가 넘어옴
// 해당 값을 통해 (로그인 회원, 이미 등록된 코드인지, 존재하는 쿠폰인지, 유예기간에 해당하는지
val request = LgEventCouponRequest("강아지","htbdHMFP","001")
val response = RestAssured
.given().log().all()
.body(request)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.`when`()
.post("/v1/lg/event")
.then().log().all().extract()
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK.value())
// given
// when
// then
}
// private fun requestHeader() : Map<String, String> {
// return mapOf(
// ("X-Client-Id" to TestAuthRequestContext.DEV_CLIENT_ID),
// ("X-Client-Secret" to TestAuthRequestContext.DEV_CLIENT_SECRET),
// ("X-Client-User-Agent" to TestAuthRequestContext.DEV_CLIENT_USER_AGENT),
// ("X-Client-User-Ip-Address" to TestAuthRequestContext.getIpAddress()))
// }
}
| 0 | SCSS | 0 | 0 | 392b13f821c1ed48bba71a023f2d5d91f49aaf88 | 1,978 | kotlin-subway-admin | MIT License |
Android/Podium/app/src/main/java/xyz/thisisjames/boulevard/android/podium/network/PodiumApiService.kt | Podium-App | 677,914,448 | false | {"Kotlin": 76766, "JavaScript": 13790} | package xyz.thisisjames.boulevard.android.podium.network
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.HTTP
import retrofit2.http.POST
import retrofit2.http.Query
import xyz.thisisjames.boulevard.android.podium.models.ExamRequest
import xyz.thisisjames.boulevard.android.podium.models.OneSubject
import xyz.thisisjames.boulevard.android.podium.models.ResponseAS
import xyz.thisisjames.boulevard.android.podium.models.Session
import java.util.concurrent.TimeUnit
//base url pointing to render service with the podium base endpoint added
private const val BASE_URL = "https://podiumbyblvrd.onrender.com/podium/"
//Build the Moshi object with kotlin adapter factory that retrofit will be using
private val moshi =
Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
private val okHttpClient = OkHttpClient
.Builder()
.readTimeout(25, TimeUnit.SECONDS)
.connectTimeout(25, TimeUnit.SECONDS)
.build()
// Create retrofit object with the Moshi converter
private val retrofit =
Retrofit.Builder().addConverterFactory(MoshiConverterFactory.create(moshi)).
baseUrl(BASE_URL).client(okHttpClient).build()
/**
* A public interface that exposes the endpoint methods
*/
interface PodiumApiService {
/**
* Returns a all subjects for which there are test available and this method can be called from a Coroutine.
* The @GET annotation indicates that the "allsubjects" endpoint will be requested with the GET
* HTTP method
*/
@GET("allsubjects")
suspend fun getAllSubjects(): ResponseAS
@GET("onesubject")
suspend fun getOneSubject() : OneSubject
// @GET("getsession")
@HTTP(method = "POST", path = "getsession", hasBody = true)
suspend fun getSession( @Body requestBody : ExamRequest) : Session
}
/**
* A public Api object that exposes the lazy-initialized Retrofit service
*/
object PodiumApi {
val retrofitService: PodiumApiService by lazy {
retrofit.create(PodiumApiService::class.java)
}
}
| 0 | Kotlin | 0 | 0 | e633b979a35437db0515e3098b384c87e397d316 | 2,232 | Podium | Apache License 2.0 |
compiler/testData/diagnostics/tests/declarationChecks/kt1141.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // FIR_IDENTICAL
//KT-1141 No check that object in 'object expression' implements all abstract members of supertype
package kt1141
public interface SomeTrait {
fun foo()
}
fun foo() {
val x = <!ABSTRACT_MEMBER_NOT_IMPLEMENTED!>object<!> : SomeTrait {
}
x.foo()
}
<!ABSTRACT_MEMBER_NOT_IMPLEMENTED!>object Rr<!> : SomeTrait {}
<!ABSTRACT_MEMBER_NOT_IMPLEMENTED!>class C<!> : SomeTrait {}
fun foo2() {
val r = <!ABSTRACT_MEMBER_NOT_IMPLEMENTED!>object<!> : Runnable {} //no error
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 506 | kotlin | Apache License 2.0 |
app/instrumentation-tests/src/org/commcare/androidTests/DeveloperOptionsTests.kt | dimagi | 20,939,877 | false | {"Java": 3950235, "JavaScript": 466293, "Kotlin": 333852, "Python": 33986, "Shell": 1376, "Ruby": 894, "CSS": 824} | package org.commcare.androidTests
import android.content.Intent
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.typeText
import androidx.test.espresso.assertion.PositionAssertions.isAbove
import androidx.test.espresso.assertion.PositionAssertions.isBelow
import androidx.test.espresso.matcher.ViewMatchers
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.uiautomator.UiDevice
import org.commcare.CommCareApplication
import org.commcare.annotations.BrowserstackTests
import org.commcare.dalvik.R
import org.commcare.utils.CustomMatchers
import org.commcare.utils.InstrumentationUtility
import org.commcare.utils.isDisplayed
import org.commcare.utils.isPresent
import org.hamcrest.Matchers.*
import org.junit.After
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@LargeTest
@BrowserstackTests
class DeveloperOptionsTests : BaseTest() {
companion object {
const val CCZ_NAME = "basic_tests.ccz"
const val APP_NAME = "Basic Tests"
}
@Before
fun setup() {
installApp(APP_NAME, CCZ_NAME)
InstrumentationUtility.login("test1", "123")
}
@After
fun tearDown() {
InstrumentationUtility.logout()
}
@Test
fun testDevelopersOptions() {
InstrumentationUtility.enableDeveloperMode()
InstrumentationUtility.openOptionsMenu()
onView(withText("Settings"))
.perform(click())
onView(withText("Developer Options"))
.perform(click())
onView(withText("Developer Mode Enabled")).isPresent()
onView(withText("Show Update Options Item")).isPresent()
onView(withText("Image Above Question Text Enabled")).isPresent()
onView(withText("Detect and Trigger Purge on Form Save")).isPresent()
InstrumentationUtility.gotoHome()
testUpdateOptions()
testImageAboveText()
testImageBelowText()
}
fun testUpdateOptions(){
InstrumentationUtility.openOptionsMenu()
onView(withText("Settings"))
.perform(click())
onView(withText("Developer Options"))
.perform(click())
onView(withText("Show Update Options Item"))
.perform(click())
onView(withText("Enabled"))
.perform(click())
InstrumentationUtility.gotoHome()
InstrumentationUtility.openOptionsMenu()
onView(withText("Settings"))
.perform(click())
onView(withText("Update Options"))
.perform(click())
onView(withText("Latest saved state"))
.perform(click())
InstrumentationUtility.gotoHome()
InstrumentationUtility.openOptionsMenu()
onView(withText("Update App"))
.perform(click())
InstrumentationUtility.waitForView(withText("App is up to date"))
onView(withText("App is up to date")).isPresent()
InstrumentationUtility.gotoHome()
}
fun testImageAboveText(){
InstrumentationUtility.openOptionsMenu()
onView(withText("Settings"))
.perform(click())
onView(withText("Developer Options"))
.perform(click())
onView(withText("Image Above Question Text Enabled"))
.perform(click())
onView(withText("Enabled"))
.perform(click())
InstrumentationUtility.gotoHome()
InstrumentationUtility.openForm(0,0)
onView(withId(R.id.image)).check(isAbove(withSubstring("Enter a Name")))
onView(withClassName(endsWith("EditText"))).perform(typeText("Image above text"))
InstrumentationUtility.exitForm(R.string.do_not_save)
InstrumentationUtility.gotoHome()
}
fun testImageBelowText(){
InstrumentationUtility.openOptionsMenu()
onView(withText("Settings"))
.perform(click())
onView(withText("Developer Options"))
.perform(click())
onView(withText("Image Above Question Text Enabled"))
.perform(click())
onView(withText("Disabled"))
.perform(click())
InstrumentationUtility.gotoHome()
InstrumentationUtility.openForm(0,0)
onView(withId(R.id.image)).check(isBelow(withSubstring("Enter a Name")))
onView(withClassName(endsWith("EditText"))).perform(typeText("Image below text"))
InstrumentationUtility.exitForm(R.string.do_not_save)
InstrumentationUtility.gotoHome()
}
}
| 35 | Java | 24 | 35 | a79691b7e45a51ad81ce53f3e399228243ed392c | 4,811 | commcare-android | Apache License 2.0 |
Mobile/Android/app/src/main/java/com/razvantmz/onemove/ui/base/CoreApplication.kt | razvantmzz | 315,075,478 | false | null | package com.razvantmz.onemove.ui.base
import android.app.Application
import android.content.Context
import com.razvantmz.onemove.core.interfaces.IViewContainer
class CoreApplication : Application() {
override fun onCreate() {
super.onCreate()
Instance = this
}
var intentData:String? = null
companion object
{
lateinit var Instance: CoreApplication
var currentActivity: IViewContainer?= null
}
} | 0 | Kotlin | 0 | 1 | 05bde5b64e54f6091dedcdd2da7093c3bfa4f522 | 456 | gym-app | MIT License |
features/home/src/main/kotlin/com/bertholucci/home/extensions/StringExtensions.kt | raphaelbertholucci | 595,403,542 | false | null | package com.bertholucci.home.extensions
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.Date
import java.util.Calendar
const val DATE_PATTERN_1 = "yyyy-MM-dd"
const val DATE_PATTERN_2 = "dd MMM yyyy"
fun String.getYear(): String {
val dateFormatted = SimpleDateFormat(DATE_PATTERN_1, Locale.getDefault()).parse(this) ?: Date()
return Calendar.getInstance().apply { time = dateFormatted }.get(Calendar.YEAR).toString()
}
fun String.getDateFormatted(pattern: String = DATE_PATTERN_1, toPattern: String): String {
val dateFormatted = SimpleDateFormat(pattern, Locale.getDefault()).parse(this) ?: Date()
return SimpleDateFormat(toPattern, Locale.US).format(dateFormatted)
}
fun String.ifNotEmpty(defaultValue: () -> String) = if (isNotEmpty()) defaultValue() else this
| 1 | Kotlin | 0 | 0 | 36f6a1dcd1e030613c5b23cdd526a123dd53a6ec | 813 | JobSeries | MIT License |
app/src/main/java/com/dlogan/android/tvmaze/workers/ShowDatabaseLoaderWorker.kt | davelogan | 191,637,515 | false | null | package com.dlogan.android.tvmaze.workers
import android.content.Context
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.dlogan.android.tvmaze.data.epg.EpgDatabase
import com.dlogan.android.tvmaze.data.epg.ScheduledShow
import com.dlogan.android.tvmaze.proxy.TVMazeApiService
import com.dlogan.android.tvmaze.proxy.dto.ScheduleItemDto
import com.dlogan.android.tvmaze.utilities.DaoMapper
import com.dlogan.android.tvmaze.utilities.LogUtil
import com.dlogan.android.tvmaze.utilities.Prefs
class ShowDatabaseLoaderWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
companion object {
//refresh at most every 12 hours
const val minInterval = 43200000L
//1 min
//const val minInterval = 60000L
}
override fun doWork(): Result {
val db = EpgDatabase.getDatabase(applicationContext)
val prefs = Prefs(applicationContext)
if (!db.needsSync(applicationContext)) {
// No need to get the data from the api again
LogUtil.debug("ShowDatabaseLoaderWorker", "No need to get the data from the api again. We already have updated data")
return Result.success()
}
try {
val api = TVMazeApiService.create()
val shows = api.getShows().execute()
if (shows.isSuccessful) {
shows.let {
sync(it.body()!!)
//save last sync time
prefs.setLastSyncTimestamp(System.currentTimeMillis())
return Result.success()
}
}
return Result.failure()
} catch (ex: Exception) {
return Result.failure()
}
}
private fun sync(scheduleItems: List<ScheduleItemDto>) {
LogUtil.debug("ShowDatabaseLoaderWorker", "syncing db")
val db = EpgDatabase.getDatabase(applicationContext)
val shows: ArrayList<ScheduledShow> = ArrayList()
for(item in scheduleItems) {
var show: ScheduledShow? = convert(item)
if (show != null) {
// db.scheduledShowDao().insert(show)
shows.add(show)
}
}
db.scheduledShowDao().insertAll(shows)
}
private fun convert(dto: ScheduleItemDto): ScheduledShow? {
return try {
DaoMapper.convert(dto)
} catch (ex: java.lang.Exception) {
null
}
}
} | 0 | Kotlin | 0 | 0 | fd74bd0e3838f8b9e3e50c7da4b3d8637b70042e | 2,496 | TVMaze | Apache License 2.0 |
bugsnag-plugin-react-native/src/test/java/com/bugsnag/android/DeviceDeserializerTest.kt | bugsnag | 2,406,783 | false | {"Kotlin": 990225, "Java": 488572, "C": 454938, "Gherkin": 173861, "C++": 59962, "Ruby": 25810, "CMake": 5144, "Shell": 3323, "Makefile": 3222} | package com.bugsnag.android
import com.bugsnag.android.internal.DateUtils
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import java.util.Date
import java.util.HashMap
class DeviceDeserializerTest {
private val map = HashMap<String, Any>()
/**
* Generates a map for verifying the serializer
*/
@Before
fun setup() {
map["cpuAbi"] = arrayOf("x86")
map["jailbroken"] = true
map["id"] = "509a0f934"
map["locale"] = "en-US"
map["totalMemory"] = 490209823402
map["manufacturer"] = "google"
map["model"] = "pixel 3a"
map["osName"] = "android"
map["osBuild"] = "bulldog"
map["fingerprint"] = "foo"
map["cpuAbis"] = arrayOf("x86")
map["tags"] = "enabled"
map["brand"] = "pixel"
map["osVersion"] = "8.1"
map["apiLevel"] = 27
map["runtimeVersions"] = mapOf(Pair("androidApiLevel", "27"), Pair("osBuild", "bulldog"))
map["freeDisk"] = 4092340985
map["freeMemory"] = 50923422234
map["orientation"] = "portrait"
map["time"] = DateUtils.toIso8601(Date(0))
}
@Test
fun deserialize() {
val device = DeviceDeserializer().deserialize(map)
assertArrayEquals(arrayOf("x86"), device.cpuAbi)
assertTrue(device.jailbroken!!)
assertEquals("509a0f934", device.id)
assertEquals("en-US", device.locale)
assertEquals(490209823402, device.totalMemory)
assertEquals("google", device.manufacturer)
assertEquals("pixel 3a", device.model)
assertEquals("android", device.osName)
assertEquals("8.1", device.osVersion)
assertEquals(mapOf(Pair("androidApiLevel", "27"), Pair("osBuild", "bulldog")), device.runtimeVersions)
assertEquals(4092340985, device.freeDisk)
assertEquals(50923422234, device.freeMemory)
assertEquals("portrait", device.orientation)
assertEquals(0, device.time!!.time)
}
}
| 17 | Kotlin | 215 | 1,158 | cb0fa7c87fb6178b67a6df3d398e497ece1299a5 | 2,098 | bugsnag-android | MIT License |
compiler/testData/codegen/bytecodeListing/jvmStatic/jvmStaticExternal.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // WITH_STDLIB
// JVM_TARGET: 1.8
object TestObject {
@JvmStatic
external fun foo()
}
class TestClassCompanion {
companion object {
@JvmStatic
external fun foo()
}
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 200 | kotlin | Apache License 2.0 |
src/main/kotlin/com/plugin/frege/stubs/index/FregeClassNameIndex.kt | IntelliJ-Frege | 343,041,006 | false | null | package com.plugin.frege.stubs.index
import com.intellij.psi.stubs.StubIndexKey
import com.plugin.frege.psi.FregePsiClass
object FregeClassNameIndex : FregeNameIndex<FregePsiClass>() {
private val KEY = StubIndexKey.createIndexKey<Int, FregePsiClass>(
"com.plugin.frege.stubs.index.FregeClassNameIndex"
)
override fun getKey(): StubIndexKey<Int, FregePsiClass> = KEY
override fun nameMatched(element: FregePsiClass, name: String): Boolean {
return element.qualifiedName == name
}
}
| 25 | Kotlin | 0 | 39 | 20c3653b79b0d9c45c32d44b30f3cc6bbe275727 | 522 | intellij-frege | Apache License 2.0 |
compiler/testData/codegen/box/increment/postfixIncrementOnSmartCast.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | fun box() : String {
var i : Int?
i = 10
// Postfix increment on a smart cast should work
// Specific: i.inc() type is Int but i and j types are both Int?
val j = i++
return if (j == 10 && 11 == i) "OK" else "fail j = $j i = $i"
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 256 | kotlin | Apache License 2.0 |
app/src/main/java/com/comjeong/nomadworker/ui/permission/UserPermission.kt | HUFSummer-Hackathon | 512,365,622 | false | {"Kotlin": 281486} | package com.comjeong.nomadworker.ui.permission
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.comjeong.nomadworker.ui.permission.UserPermission.requestPhotoGalleryPermission
import java.util.jar.Manifest
object UserPermission {
fun Activity.isGrantedLocationPermission() : Boolean {
val fineLocation = ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
val coarseLocation = ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_COARSE_LOCATION)
return (fineLocation == PackageManager.PERMISSION_GRANTED) && (coarseLocation == PackageManager.PERMISSION_GRANTED)
}
fun Activity.isGrantedPhotoGalleryPermission() : Boolean {
val photoGalleryRead = ContextCompat.checkSelfPermission(this,
android.Manifest.permission.READ_EXTERNAL_STORAGE)
val photoGalleryWrite = ContextCompat.checkSelfPermission(this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
return (photoGalleryRead == PackageManager.PERMISSION_GRANTED) && (photoGalleryWrite == PackageManager.PERMISSION_GRANTED)
}
fun Activity.isGrantedAllPermission() : Boolean {
return isGrantedLocationPermission() && isGrantedPhotoGalleryPermission()
}
fun Activity.requestLocationPermission(){
ActivityCompat.requestPermissions(this,
arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION),1)
}
fun Activity.requestPhotoGalleryPermission(){
ActivityCompat.requestPermissions(this,
arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE), 2)
}
fun Activity.requestAllPermission(){
ActivityCompat.requestPermissions(this,
arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE),3)
}
fun isGrantedPermission(grantResults : IntArray) : Boolean {
var i = 0
while (i < grantResults.size){
if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
return false
}
i += 1
}
return true
}
} | 2 | Kotlin | 0 | 0 | 5857dbe020888785367e0e4596a7b342aa1ec4a7 | 2,779 | NomadWorker-Android | MIT License |
sqldelight-compiler/src/test/kotlin/com/squareup/sqldelight/core/QueriesTypeTest.kt | christofferqa | 169,524,028 | true | {"Kotlin": 592814, "Java": 9352, "Shell": 1970, "HTML": 57} | package com.squareup.sqldelight.core
import com.google.common.truth.Truth.assertThat
import com.squareup.sqldelight.core.compiler.SqlDelightCompiler
import com.squareup.sqldelight.test.util.FixtureCompiler
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
class QueriesTypeTest {
@get:Rule val temporaryFolder = TemporaryFolder()
@Test fun `queries file is generated properly via compilation`() {
val result = FixtureCompiler.compileSql("""
|CREATE TABLE data (
| id INTEGER PRIMARY KEY,
| value TEXT AS kotlin.collections.List
|);
|
|insertData:
|INSERT INTO data
|VALUES (?, ?);
|
|selectForId:
|SELECT *
|FROM data
|WHERE id = ?;
""".trimMargin(), temporaryFolder, SqlDelightCompiler::writeQueriesType, fileName = "Data.sq")
val select = result.compiledFile.namedQueries.first()
val insert = result.compiledFile.namedMutators.first()
assertThat(result.errors).isEmpty()
val dataQueries = File(result.outputDirectory, "com/example/DataQueries.kt")
assertThat(result.compilerOutput[dataQueries].toString()).isEqualTo("""
|package com.example
|
|import com.squareup.sqldelight.Query
|import com.squareup.sqldelight.Transacter
|import com.squareup.sqldelight.db.SqlCursor
|import com.squareup.sqldelight.db.SqlDriver
|import kotlin.Any
|import kotlin.Long
|import kotlin.collections.List
|import kotlin.collections.MutableList
|
|class DataQueries(private val database: TestDatabase, private val driver: SqlDriver) :
| Transacter(driver) {
| internal val selectForId: MutableList<Query<*>> =
| com.squareup.sqldelight.internal.copyOnWriteList()
|
| fun <T : Any> selectForId(id: Long, mapper: (id: Long, value: List?) -> T): Query<T> =
| SelectForId(id) { cursor ->
| mapper(
| cursor.getLong(0)!!,
| cursor.getString(1)?.let(database.dataAdapter.valueAdapter::decode)
| )
| }
|
| fun selectForId(id: Long): Query<Data> = selectForId(id, Data::Impl)
|
| fun insertData(id: Long?, value: List?) {
| driver.execute(${insert.id}, ""${'"'}
| |INSERT INTO data
| |VALUES (?1, ?2)
| ""${'"'}.trimMargin(), 2) {
| bindLong(1, id)
| bindString(2, if (value == null) null else
| database.dataAdapter.valueAdapter.encode(value))
| }
| notifyQueries(database.dataQueries.selectForId)
| }
|
| private inner class SelectForId<out T : Any>(private val id: Long, mapper: (SqlCursor) -> T) :
| Query<T>(selectForId, mapper) {
| override fun execute(): SqlCursor = driver.executeQuery(${select.id}, ""${'"'}
| |SELECT *
| |FROM data
| |WHERE id = ?1
| ""${'"'}.trimMargin(), 1) {
| bindLong(1, id)
| }
| }
|}
|""".trimMargin())
}
}
| 0 | Kotlin | 0 | 0 | 45adbc015110fd38de64492837a37e3849bc38a2 | 3,223 | sqldelight | Apache License 2.0 |
runners/gradle-plugin/src/main/kotlin/org/jetbrains/dokka/gradle/tasks/AbstractDokkaParentTask.kt | vmishenev | 406,989,990 | true | {"Kotlin": 2886741, "CSS": 37194, "JavaScript": 24849, "TypeScript": 12496, "HTML": 6859, "FreeMarker": 3872, "SCSS": 2472, "Java": 2188, "Shell": 863} | @file:Suppress("PackageDirectoryMismatch")
package org.jetbrains.dokka.gradle
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.Nested
import org.gradle.work.DisableCachingByDefault
private const val DEPRECATION_MESSAGE = """
It is an anti-pattern to declare cross-project dependencies as it leads to various build problems.
For this reason, this API wil be removed with the introduction of project isolation.
When it happens, we will provide a migration guide. In the meantime, you can keep using this API
if you have to, but please don't rely on it if possible. If you don't want to document a certain project,
don't apply the Dokka plugin for it, or disable individual project tasks using the Gradle API .
"""
@Suppress("DEPRECATION")
@DisableCachingByDefault(because = "Abstract super-class, not to be instantiated directly")
abstract class AbstractDokkaParentTask : AbstractDokkaTask() {
@get:Internal
internal var childDokkaTaskPaths: Set<String> = emptySet()
private set
@get:Nested
internal val childDokkaTasks: Set<AbstractDokkaTask>
get() = childDokkaTaskPaths
.mapNotNull { path -> project.tasks.findByPath(path) }
.map(::checkIsAbstractDokkaTask)
.toSet()
/* By task reference */
@Deprecated(message = DEPRECATION_MESSAGE, level = DeprecationLevel.WARNING)
fun addChildTask(task: AbstractDokkaTask) {
childDokkaTaskPaths = childDokkaTaskPaths + task.path
}
@Deprecated(message = DEPRECATION_MESSAGE, level = DeprecationLevel.WARNING)
fun removeChildTask(task: AbstractDokkaTask) {
childDokkaTaskPaths = childDokkaTaskPaths - task.path
}
/* By path */
@Deprecated(message = DEPRECATION_MESSAGE, level = DeprecationLevel.WARNING)
fun addChildTask(path: String) {
childDokkaTaskPaths = childDokkaTaskPaths + project.absoluteProjectPath(path)
}
@Deprecated(message = DEPRECATION_MESSAGE, level = DeprecationLevel.WARNING)
fun removeChildTask(path: String) {
childDokkaTaskPaths = childDokkaTaskPaths - project.absoluteProjectPath(path)
}
/* By project reference and name */
@Deprecated(message = DEPRECATION_MESSAGE, level = DeprecationLevel.WARNING)
fun addChildTasks(projects: Iterable<Project>, childTasksName: String) {
projects.forEach { project ->
addChildTask(project.absoluteProjectPath(childTasksName))
}
}
@Deprecated(message = DEPRECATION_MESSAGE, level = DeprecationLevel.WARNING)
fun removeChildTasks(projects: Iterable<Project>, childTasksName: String) {
projects.forEach { project ->
removeChildTask(project.absoluteProjectPath(childTasksName))
}
}
@Deprecated(message = DEPRECATION_MESSAGE, level = DeprecationLevel.WARNING)
fun addSubprojectChildTasks(childTasksName: String) {
addChildTasks(project.subprojects, childTasksName)
}
@Deprecated(message = DEPRECATION_MESSAGE, level = DeprecationLevel.WARNING)
fun removeSubprojectChildTasks(childTasksName: String) {
removeChildTasks(project.subprojects, childTasksName)
}
@Deprecated(message = DEPRECATION_MESSAGE, level = DeprecationLevel.WARNING)
fun removeChildTasks(project: Project) {
childDokkaTaskPaths = childDokkaTaskPaths.filter { path ->
parsePath(path).parent != parsePath(project.path)
}.toSet()
}
@Deprecated(message = DEPRECATION_MESSAGE, level = DeprecationLevel.WARNING)
fun removeChildTasks(projects: Iterable<Project>) {
projects.forEach { project -> removeChildTasks(project) }
}
private fun checkIsAbstractDokkaTask(task: Task): AbstractDokkaTask {
if (task is AbstractDokkaTask) {
return task
}
throw IllegalArgumentException(
"Only tasks of type ${AbstractDokkaTask::class.java.name} can be added as child for " +
"${AbstractDokkaParentTask::class.java.name} tasks.\n" +
"Found task ${task.path} of type ${task::class.java.name} added to $path"
)
}
}
| 1 | Kotlin | 1 | 0 | a1c3b89871a3a4f90d6441db356685d48a84ab63 | 4,203 | dokka | Apache License 2.0 |
compiler/testData/diagnostics/tests/sealed/RedundantAbstract.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // FIR_IDENTICAL
<!REDUNDANT_MODIFIER!>abstract<!> sealed class Base {
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 73 | kotlin | Apache License 2.0 |
core/util.runtime/src/org/jetbrains/kotlin/container/PlatformSpecificExtension.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.container
/**
* This is a marker-interface for components which are needed for common resolve
* facilities (like resolve, or deserialization), but are platform-specific.
*
* PlatformSpecificExtensions has to be present in the container in exactly one
* instance (hence common pattern with providing no-op DEFAULT/EMPTY implementation
* in the corresponding interface)
*
* In multiplatform modules such components require special treatment. Namely,
* if several components of the same type are provided, then it's not an illegal state;
* rather, we have to carefully resolve clash on case-by-case basis.
* See also [PlatformExtensionsClashResolver].
*/
interface PlatformSpecificExtension<S : PlatformSpecificExtension<S>>
/**
* Allows to specify which [PlatformSpecificExtension] should be used if there were two or more registrations
* for [applicableTo] class in the container.
*
* [PlatformExtensionsClashResolver] should be registred in the container via [useClashResolver]-extension.
*
* NB. YOU DON'T NEED this mechanism for the most popular case of "one or several default vs.
* zero or one non-default". Just use [DefaultImplementation], and default instances will be automatically
* discriminated (see respective KDoc).
* Use [PlatformExtensionsClashResolver] only for cases when you need more invloved logic.
*
* Example: [org.jetbrains.kotlin.resolve.IdentifierChecker]. It is used in platform-agnostic code,
* which resolves and checks identifiers for correctness. Each platform has it's own rules
* regarding identifier correctness. In MPP modules we can't choose only one IdentifierChecker;
* instead, we have to provide a "composite" IdentifierChecker which will launch checks of *each*
* platform.
*
*/
abstract class PlatformExtensionsClashResolver<E : PlatformSpecificExtension<E>>(val applicableTo: Class<E>) {
abstract fun resolveExtensionsClash(extensions: List<E>): E
class FallbackToDefault<E : PlatformSpecificExtension<E>>(
private val defaultValue: E,
applicableTo: Class<E>
) : PlatformExtensionsClashResolver<E>(applicableTo) {
override fun resolveExtensionsClash(extensions: List<E>): E = defaultValue
}
class FirstWins<E : PlatformSpecificExtension<E>>(applicableTo: Class<E>) : PlatformExtensionsClashResolver<E>(applicableTo) {
override fun resolveExtensionsClash(extensions: List<E>): E = extensions.first()
}
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 2,630 | kotlin | Apache License 2.0 |
core/src/main/java/com/beomsu317/core/data/local/data_store/serializer/UserSerializer.kt | beomsu317 | 485,776,806 | false | {"Kotlin": 275900} | package com.beomsu317.core.data.local.data_store.serializer
import androidx.datastore.core.Serializer
import com.beomsu317.core.domain.model.Settings
import com.beomsu317.core.domain.model.User
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json
import java.io.InputStream
import java.io.OutputStream
class UserSerializer : Serializer<User> {
override val defaultValue: User = User()
override suspend fun readFrom(input: InputStream): User {
return try {
Json.decodeFromString(
deserializer = User.serializer(),
string = input.readBytes().decodeToString()
)
} catch (e: SerializationException) {
e.printStackTrace()
defaultValue
}
}
override suspend fun writeTo(t: User, output: OutputStream) {
output.write(
Json.encodeToString(
serializer = User.serializer(),
value = t
).encodeToByteArray()
)
}
} | 0 | Kotlin | 0 | 0 | 4ff38347196aaebb75d2729d62289bc717f14370 | 1,039 | private-chat-app | Apache License 2.0 |
app/src/main/java/com/buchi/fullentry/utilities/Constants.kt | SunnyBe | 370,745,596 | false | null | package com.buchi.fullentry.utilities
object Constants {
const val MOVIE_ITEM = "movie"
const val IMAGE_BASE_URL = "https://image.tmdb.org/t/p/w500/"
} | 0 | Kotlin | 1 | 0 | f4c1d6c8067c4149d357a4ded6e6455b60b15156 | 160 | MovieApp | The Unlicense |
src/main/kotlin/com/chromaticnoise/multiplatformswiftpackage/dsl/TargetPlatformDsl.kt | ge-org | 303,140,022 | false | {"Kotlin": 53566} | package com.chromaticnoise.multiplatformswiftpackage.dsl
import com.chromaticnoise.multiplatformswiftpackage.domain.Either
import com.chromaticnoise.multiplatformswiftpackage.domain.PlatformVersion
import com.chromaticnoise.multiplatformswiftpackage.domain.PluginConfiguration.PluginConfigurationError
import com.chromaticnoise.multiplatformswiftpackage.domain.PluginConfiguration.PluginConfigurationError.InvalidTargetName
import com.chromaticnoise.multiplatformswiftpackage.domain.TargetName
import com.chromaticnoise.multiplatformswiftpackage.domain.TargetPlatform
import groovy.lang.Closure
import org.gradle.util.ConfigureUtil
/**
* DSL to create instances of [TargetPlatform].
*/
public class TargetPlatformDsl {
internal var targetPlatforms = mutableListOf<Either<List<PluginConfigurationError>, TargetPlatform>>()
/**
* Adds all iOS targets as a [TargetPlatform] using the provided [version].
*
* @param version builder for an instance of [PlatformVersion]
*/
public fun iOS(version: PlatformVersionDsl.() -> Unit) {
targetsInternal(listOf(Either.Right(TargetName.IOSarm64), Either.Right(TargetName.IOSx64)), version)
}
public fun iOS(version: Closure<PlatformVersionDsl>) {
iOS { ConfigureUtil.configure(version, this) }
}
/**
* Adds all watchOS targets as a [TargetPlatform] using the provided [version].
*
* @param version builder for an instance of [PlatformVersion]
*/
public fun watchOS(version: PlatformVersionDsl.() -> Unit) {
targetsInternal(listOf(
Either.Right(TargetName.WatchOSarm32),
Either.Right(TargetName.WatchOSarm64),
Either.Right(TargetName.WatchOSx86),
Either.Right(TargetName.WatchOSx64)),
version
)
}
public fun watchOS(version: Closure<PlatformVersionDsl>) {
watchOS { ConfigureUtil.configure(version, this) }
}
/**
* Adds all tvOS targets as a [TargetPlatform] using the provided [version].
*
* @param version builder for an instance of [PlatformVersion]
*/
public fun tvOS(version: PlatformVersionDsl.() -> Unit) {
targetsInternal(listOf(Either.Right(TargetName.TvOSarm64), Either.Right(TargetName.TvOSx64)), version)
}
public fun tvOS(version: Closure<PlatformVersionDsl>) {
tvOS { ConfigureUtil.configure(version, this) }
}
/**
* Adds all macOS targets as a [TargetPlatform] using the provided [version].
*
* @param version builder for an instance of [PlatformVersion]
*/
public fun macOS(version: PlatformVersionDsl.() -> Unit) {
targetsInternal(listOf(Either.Right(TargetName.MacOSx64)), version)
}
public fun macOS(version: Closure<PlatformVersionDsl>) {
macOS { ConfigureUtil.configure(version, this) }
}
/**
* Adds a [TargetPlatform] with targets for the given [names] and the provided [version].
* The [names] corresponds to the Kotlin multiplatform target names.
*
* @param names of the targets. E.g. iosArm64, iosX64
* @param version builder for an instance of [PlatformVersion]
*/
public fun targets(vararg names: String, version: PlatformVersionDsl.() -> Unit) {
targetsInternal(names.asList().toTargetNames(), version)
}
public fun targets(names: Collection<String>, version: Closure<PlatformVersionDsl>) {
targetsInternal(names.toTargetNames()) { ConfigureUtil.configure(version, this) }
}
private fun targetsInternal(names: Collection<Either<PluginConfigurationError, TargetName>>, configure: PlatformVersionDsl.() -> Unit) {
if (names.isEmpty()) return
val platformVersion = PlatformVersionDsl().apply(configure).version ?: return
val errors = names.filterIsInstance<Either.Left<PluginConfigurationError, TargetName>>().map { it.value }
val targetNames = names.filterIsInstance<Either.Right<PluginConfigurationError, TargetName>>().map { it.value }
val platform: Either<List<PluginConfigurationError>, TargetPlatform> = when {
errors.isNotEmpty() -> Either.Left(errors)
else -> Either.Right(TargetPlatform(version = platformVersion, targets = targetNames))
}
targetPlatforms.add(platform)
}
private fun Collection<String>.toTargetNames() = map { Either.ofNullable(TargetName.of(it), InvalidTargetName(it)) }
/**
* DSL to create instances of [PlatformVersion].
*/
public class PlatformVersionDsl {
internal var version: PlatformVersion? = null
/**
* Creates a [PlatformVersion] for the given [versionName].
* The [versionName] corresponds to the SupportedPlatform section of a Package.swift file
*
* @param versionName of the platform version. E.g. 13, 11.0.1
*
* @see "https://docs.swift.org/package-manager/PackageDescription/PackageDescription.html#supportedplatform"
*/
public fun v(versionName: String) {
PlatformVersion.of(versionName)?.let {
this.version = it
}
}
}
}
| 21 | Kotlin | 40 | 293 | 8d7c25ecc19841d4af515db885ae3426f7f32274 | 5,152 | multiplatform-swiftpackage | Apache License 2.0 |
app/src/main/java/com/utradia/catalogueappv2/module/recomendedItems/RecomendedPresenter.kt | Sunfocus | 164,079,839 | false | null | package com.utradia.catalogueappv2.module.recomendedItems
import android.app.Activity
import com.utradia.catalogueappv2.api.RestService
import com.utradia.catalogueappv2.base.UtradiaApplication
import com.utradia.catalogueappv2.constants.ApiConstants
import com.utradia.catalogueappv2.mvpbase.BasePresenter
import com.utradia.catalogueappv2.utils.AppUtils
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import javax.inject.Inject
class RecomendedPresenter @Inject constructor(): BasePresenter<RecomendedView>(){
@Inject
lateinit var mAppUtils: AppUtils
@Inject
lateinit var mRestService: RestService
private var mSubscription: Subscription? = null
internal fun cancelAllAsync() {
if (mSubscription != null && !mSubscription!!.isUnsubscribed)
mSubscription!!.unsubscribe()
}
internal fun injectDependencies(context: Activity) {
(context.applicationContext as UtradiaApplication).appComponent?.inject(this)
}
internal fun getRecommendedItems(user_id:String,page:String) {
mvpView?.showProgress()
mSubscription= mRestService.getRecommendedItems(user_id,page)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ response ->
if (isViewAttached) {
mvpView?.hideProgress()
if (response.success == ApiConstants.STATUS_SUCCESS_1) {
mvpView?.onOffersFound(response)
} else if (response.success== ApiConstants.STATUS_SUCCESS_0) {
mvpView?.onOffersNotFound(response.error_message)
}
}
}, { throwable ->
if (isViewAttached) {
mvpView?.hideProgress()
mvpView?.onError(throwable)
}
})
}
} | 0 | Kotlin | 0 | 1 | 684f0a2621ef7b906c8b19d6b003a704d6edca1c | 2,025 | Utradia-Catlog- | Apache License 2.0 |
idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceProperty/IntroducePropertyAction.kt | android | 263,405,600 | true | null | /*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.refactoring.introduce.introduceProperty
import com.intellij.lang.refactoring.RefactoringSupportProvider
import com.intellij.refactoring.RefactoringActionHandler
import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSupportProvider
import org.jetbrains.kotlin.idea.refactoring.introduce.AbstractIntroduceAction
class IntroducePropertyAction : AbstractIntroduceAction() {
override fun getRefactoringHandler(provider: RefactoringSupportProvider): RefactoringActionHandler? =
(provider as? KotlinRefactoringSupportProvider)?.getIntroducePropertyHandler()
}
| 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 819 | kotlin | Apache License 2.0 |
file-writer-compat/core/src/main/java/com/akexorcist/library/filewritercompat/core/manager/ExternalShareableFile.kt | akexorcist | 624,903,744 | false | null | package com.akexorcist.library.filewritercompat.core.manager
import android.net.Uri
import android.os.Environment
import androidx.fragment.app.FragmentActivity
import com.akexorcist.library.filewritercompat.core.WriteExecutor
import com.akexorcist.library.filewritercompat.core.permission.StoragePermissionRequest
import com.akexorcist.library.filewritercompat.core.FileResult
import com.akexorcist.library.filewritercompat.core.utility.FileHelper
import com.akexorcist.library.filewritercompat.core.utility.PermissionHelper
import com.akexorcist.library.filewritercompat.core.utility.VersionHelper
import java.io.File
class ExternalShareableFile {
sealed class ErrorReason {
@Suppress("unused")
class InvalidFileNameWithExtension(
val fileNameWithExtension: String
) : ErrorReason()
@Suppress("unused")
class InvalidDirectoryType(
val directoryType: String
) : ErrorReason()
@Suppress("unused")
class CannotCreateDirectory(
val directory: String
) : ErrorReason()
object WriteExternalStoragePermissionDenied : ErrorReason()
@Suppress("unused")
class CannotWriteFile(
val exception: Exception
) : ErrorReason()
@Suppress("unused")
class CannotScanFile(
val filePath: String
) : ErrorReason()
}
class Builder(
private var directoryType: String,
private var fileNameWithExtension: String,
private var storagePermissionRequest: StoragePermissionRequest,
private var childPath: String?,
) {
fun setChildPath(childPath: String) = this.apply {
this.childPath = childPath
}
fun setStoragePermissionRequest(storagePermissionRequest: StoragePermissionRequest) = this.apply {
this.storagePermissionRequest = storagePermissionRequest
}
fun build(): WriteExecutor<Uri, ErrorReason> = Executor(
directoryType = directoryType,
childPath = childPath ?: "",
fileNameWithExtension = fileNameWithExtension,
storagePermissionRequest = storagePermissionRequest,
)
}
class Executor(
private val directoryType: String,
private val childPath: String,
private val fileNameWithExtension: String,
private val storagePermissionRequest: StoragePermissionRequest,
) : WriteExecutor<Uri, ErrorReason> {
override suspend fun <DATA> write(activity: FragmentActivity, data: DATA, writer: suspend (DATA, File) -> Unit): FileResult<Uri, ErrorReason> {
if (!FileHelper.isValidFileNameWithExtension(fileNameWithExtension)) {
return FileResult.Error(ErrorReason.InvalidFileNameWithExtension(fileNameWithExtension))
}
if (!FileHelper.isValidDirectoryType(directoryType)) {
return FileResult.Error(ErrorReason.InvalidDirectoryType(directoryType))
}
if (VersionHelper.isAtLeastApi23() &&
VersionHelper.isApi29OrLower() &&
PermissionHelper.isWriteExternalStoragePermissionDenied(activity)
) {
storagePermissionRequest.requestWriteExternalStoragePermission(activity)
if (PermissionHelper.isWriteExternalStoragePermissionDenied(activity))
return FileResult.Error(ErrorReason.WriteExternalStoragePermissionDenied)
}
val directory = File(Environment.getExternalStoragePublicDirectory(directoryType), childPath)
val isDirectoryExist = FileHelper.createMissingDirectory(directory)
if (!isDirectoryExist) {
return FileResult.Error(ErrorReason.CannotCreateDirectory(directory.absolutePath))
}
val file = File(directory, fileNameWithExtension)
try {
writer(data, file)
} catch (e: Exception) {
return FileResult.Error(ErrorReason.CannotWriteFile(e))
}
val uri = try {
FileHelper.scanFile(activity, file)
} catch (e: Exception) {
return FileResult.Error(ErrorReason.CannotScanFile(file.absolutePath))
}
return FileResult.Success(uri)
}
}
}
| 0 | Kotlin | 1 | 13 | 74f582a32b9de0fd6728f8ce6886419eee4b4cb8 | 4,343 | FileWriterCompat | Apache License 2.0 |
app/src/main/java/com/example/jungomarket/ui/PathUtil.kt | dogukandmrl | 619,548,857 | false | {"Kotlin": 17606} | package com.example.meditationuicompose
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.geometry.Offset
import kotlin.math.abs
fun Path.standardQuadFromTo(from: Offset, to: Offset) {
quadraticBezierTo(
from.x,
from.y,
abs(from.x + to.x) / 2f,
abs(from.y + to.y) / 2f
)
} | 0 | Kotlin | 0 | 0 | 5083a861210122adb7072785f6c0a67eaed4b977 | 334 | Kotlin_Compose | MIT License |
compiler/testData/diagnostics/tests/smartCasts/castchecks/insideCall.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // !LANGUAGE: +SafeCastCheckBoundSmartCasts
// See KT-19007
// Stub
fun String.indexOf(arg: String) = this.length - arg.length
// Stub
fun String.toLowerCase() = this
fun foo(a: Any) {
// Should compile in 1.2
(a as? String)?.indexOf(a.toLowerCase())
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 263 | kotlin | Apache License 2.0 |
src/test/kotlin/no/nav/helse/flex/behandlingsdager/BehandlingsdagerFeatureSwitchTest.kt | navikt | 475,306,289 | false | {"Kotlin": 1694951, "Dockerfile": 267} | package no.nav.helse.flex.behandlingsdager
import no.nav.helse.flex.FellesTestOppsett
import no.nav.helse.flex.hentSoknad
import no.nav.helse.flex.hentSoknaderMetadata
import no.nav.helse.flex.sendSykmelding
import no.nav.helse.flex.testdata.behandingsdager
import no.nav.helse.flex.testdata.sykmeldingKafkaMessage
import no.nav.helse.flex.unleash.UNLEASH_CONTEXT_TIL_SLUTT_SPORSMAL
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.MethodOrderer
import org.junit.jupiter.api.Order
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestMethodOrder
@TestMethodOrder(MethodOrderer.OrderAnnotation::class)
class BehandlingsdagerFeatureSwitchTest : FellesTestOppsett() {
private val fnr = "12345678900"
@AfterEach
fun teardown() {
databaseReset.resetDatabase()
fakeUnleash.resetAll()
fakeUnleash.disable(UNLEASH_CONTEXT_TIL_SLUTT_SPORSMAL)
}
@Test
@Order(1)
fun `oppretter søknad med featureswitch på`() {
fakeUnleash.resetAll()
fakeUnleash.enable(UNLEASH_CONTEXT_TIL_SLUTT_SPORSMAL)
sendSykmelding(
sykmeldingKafkaMessage(
fnr = fnr,
sykmeldingsperioder = behandingsdager(),
),
)
val soknader = hentSoknaderMetadata(fnr)
val soknad1 = hentSoknad(soknader[0].id, fnr)
assertThat(soknad1.sporsmal!!.map { it.tag }).isEqualTo(
listOf(
"ANSVARSERKLARING",
"ENKELTSTAENDE_BEHANDLINGSDAGER_0",
"FERIE_V2",
"ARBEID_UTENFOR_NORGE",
"ANDRE_INNTEKTSKILDER",
"TIL_SLUTT",
),
)
}
@Test
@Order(2)
fun `oppretter søknad med featureswitch av`() {
sendSykmelding(
sykmeldingKafkaMessage(
fnr = fnr,
sykmeldingsperioder = behandingsdager(),
),
)
val soknader = hentSoknaderMetadata(fnr)
val soknad1 = hentSoknad(soknader[0].id, fnr)
assertThat(soknad1.sporsmal!!.map { it.tag }).isEqualTo(
listOf(
"ANSVARSERKLARING",
"ENKELTSTAENDE_BEHANDLINGSDAGER_0",
"FERIE_V2",
"ARBEID_UTENFOR_NORGE",
"ANDRE_INNTEKTSKILDER",
"VAER_KLAR_OVER_AT",
"BEKREFT_OPPLYSNINGER",
),
)
}
}
| 3 | Kotlin | 0 | 4 | 46f4bc29cdc7631a26bf673f23c25ec208bc3fc3 | 2,491 | sykepengesoknad-backend | MIT License |
app/src/androidTest/java/org/simple/clinic/storage/DeleteSyncGroupDatabaseAndroidTest.kt | simpledotorg | 132,515,649 | false | {"Kotlin": 5970450, "Shell": 1660, "HTML": 545} | package org.simple.clinic.storage
import com.google.common.truth.Truth.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.simple.clinic.AppDatabase
import org.simple.clinic.TestClinicApp
import org.simple.sharedTestCode.TestData
import org.simple.clinic.overdue.Appointment
import org.simple.clinic.overdue.AppointmentCancelReason
import org.simple.clinic.patient.PatientRepository
import org.simple.clinic.patient.SyncStatus
import java.util.UUID
import javax.inject.Inject
class DeleteSyncGroupDatabaseAndroidTest {
@Inject
lateinit var database: AppDatabase
@Inject
lateinit var patientRepository: PatientRepository
private val facilityDao by lazy { database.facilityDao() }
private val appointmentDao by lazy { database.appointmentDao() }
private val bloodPressureMeasurementDao by lazy { database.bloodPressureDao() }
private val bloodSugarMeasurementDao by lazy { database.bloodSugarDao() }
private val prescribedDrugDao by lazy { database.prescriptionDao() }
private val medicalHistoryDao by lazy { database.medicalHistoryDao() }
private val groupUuid = UUID.fromString("c30b1c77-3b30-413b-8f42-270ae0a6543d")
private val currentSyncGroup = "1b247820-c070-40f7-8731-75fe986d0147"
private val otherSyncGroup = "49aa2533-54e7-4456-b741-e203f3bf7ce1"
private val currentFacility = TestData.facility(
uuid = UUID.fromString("b141c2f3-a0b7-4bc0-8475-748a6c7a6e41"),
name = "PHC Obvious",
syncGroup = currentSyncGroup,
groupUuid = groupUuid
)
private val otherFacilityInCurrentSyncGroup = TestData.facility(
uuid = UUID.fromString("bfb99432-f4d7-4522-8229-85d9ec94a979"),
name = "<NAME>",
syncGroup = currentSyncGroup,
groupUuid = groupUuid
)
private val facilityInAnotherSyncGroup = TestData.facility(
uuid = UUID.fromString("90582970-9aed-46e4-a16b-45671859701a"),
name = "CHC RTSL",
syncGroup = otherSyncGroup,
groupUuid = groupUuid
)
@Before
fun setUp() {
TestClinicApp.appComponent().inject(this)
facilityDao.save(listOf(currentFacility, otherFacilityInCurrentSyncGroup, facilityInAnotherSyncGroup))
}
@After
fun tearDown() {
database.clearAllTables()
}
@Test
fun deleting_the_sync_group_data_should_delete_all_patients_not_registered_or_assigned_in_current_sync_group() {
// given
val patientRegisteredInCurrentFacility = TestData.patientProfile(
patientUuid = UUID.fromString("5ee3a570-b561-4b5c-bfd9-d8a680f0a16c"),
syncStatus = SyncStatus.DONE,
patientRegisteredFacilityId = currentFacility.uuid,
patientAssignedFacilityId = facilityInAnotherSyncGroup.uuid
)
val patientAssignedToCurrentFacility = TestData.patientProfile(
patientUuid = UUID.fromString("771beb4d-3f5b-4cf6-b5f1-8db97d2d2ba2"),
syncStatus = SyncStatus.DONE,
patientRegisteredFacilityId = facilityInAnotherSyncGroup.uuid,
patientAssignedFacilityId = currentFacility.uuid
)
val patientRegisteredAtOtherFacilityInCurrentSyncGroup = TestData.patientProfile(
patientUuid = UUID.fromString("58076d1b-0fd9-430e-8bc4-d452f1af5f97"),
syncStatus = SyncStatus.DONE,
patientRegisteredFacilityId = otherFacilityInCurrentSyncGroup.uuid,
patientAssignedFacilityId = facilityInAnotherSyncGroup.uuid
)
val patientAssignedToOtherFacilityInCurrentSyncGroup = TestData.patientProfile(
patientUuid = UUID.fromString("72ce2033-4b46-4617-9c0d-fd2a54c3ddfa"),
syncStatus = SyncStatus.DONE,
patientRegisteredFacilityId = facilityInAnotherSyncGroup.uuid,
patientAssignedFacilityId = otherFacilityInCurrentSyncGroup.uuid
)
val patientInAnotherSyncGroup = TestData.patientProfile(
patientUuid = UUID.fromString("7f9a581d-8a0c-414b-9b39-c3c3877172fa"),
syncStatus = SyncStatus.DONE,
patientRegisteredFacilityId = facilityInAnotherSyncGroup.uuid,
patientAssignedFacilityId = facilityInAnotherSyncGroup.uuid
)
val unsyncedPatientInAnotherSyncGroup = TestData.patientProfile(
patientUuid = UUID.fromString("b6a540b4-f4b4-45c3-8d3c-70a8a577022e"),
syncStatus = SyncStatus.PENDING,
patientRegisteredFacilityId = facilityInAnotherSyncGroup.uuid,
patientAssignedFacilityId = facilityInAnotherSyncGroup.uuid
)
val allPatientProfiles = listOf(
patientRegisteredInCurrentFacility,
patientAssignedToCurrentFacility,
patientRegisteredAtOtherFacilityInCurrentSyncGroup,
patientAssignedToOtherFacilityInCurrentSyncGroup,
patientInAnotherSyncGroup,
unsyncedPatientInAnotherSyncGroup
)
patientRepository.save(allPatientProfiles)
assertThat(patientRepository.allPatientProfiles()).containsExactlyElementsIn(allPatientProfiles)
// when
database.deletePatientsNotInFacilitySyncGroup(currentFacility)
// then
assertThat(patientRepository.allPatientProfiles()).containsExactly(
patientRegisteredInCurrentFacility,
patientAssignedToCurrentFacility,
patientRegisteredAtOtherFacilityInCurrentSyncGroup,
patientAssignedToOtherFacilityInCurrentSyncGroup,
unsyncedPatientInAnotherSyncGroup
)
}
@Test
fun deleting_the_sync_group_data_should_not_delete_patients_having_a_scheduled_appointment_in_the_current_sync_group() {
// given
val patientWithScheduledAppointmentInCurrentFacility = TestData.patientProfile(
patientUuid = UUID.fromString("7f9a581d-8a0c-414b-9b39-c3c3877172fa"),
syncStatus = SyncStatus.DONE,
patientRegisteredFacilityId = facilityInAnotherSyncGroup.uuid,
patientAssignedFacilityId = facilityInAnotherSyncGroup.uuid
)
val patientWithScheduledAppointmentInOtherFacilityInCurrentSyncGroup = TestData.patientProfile(
patientUuid = UUID.fromString("5e539613-28d1-4d72-96aa-2ce24052e643"),
syncStatus = SyncStatus.DONE,
patientRegisteredFacilityId = facilityInAnotherSyncGroup.uuid,
patientAssignedFacilityId = facilityInAnotherSyncGroup.uuid
)
val patientWithCancelledAppointment = TestData.patientProfile(
patientUuid = UUID.fromString("b6a540b4-f4b4-45c3-8d3c-70a8a577022e"),
syncStatus = SyncStatus.DONE,
patientRegisteredFacilityId = facilityInAnotherSyncGroup.uuid,
patientAssignedFacilityId = facilityInAnotherSyncGroup.uuid
)
val patientWithVisitedAppointment = TestData.patientProfile(
patientUuid = UUID.fromString("16276cd1-36e9-42a2-8d2f-cb7d9da6de14"),
syncStatus = SyncStatus.DONE,
patientRegisteredFacilityId = facilityInAnotherSyncGroup.uuid,
patientAssignedFacilityId = facilityInAnotherSyncGroup.uuid
)
val allPatientProfiles = listOf(
patientWithScheduledAppointmentInCurrentFacility,
patientWithScheduledAppointmentInOtherFacilityInCurrentSyncGroup,
patientWithCancelledAppointment,
patientWithVisitedAppointment
)
patientRepository.save(allPatientProfiles)
assertThat(patientRepository.allPatientProfiles()).containsExactlyElementsIn(allPatientProfiles)
val scheduledAppointmentInCurrentFacility = TestData.appointment(
uuid = UUID.fromString("ffe584b3-e613-4056-848a-3c53ffce5986"),
patientUuid = patientWithScheduledAppointmentInCurrentFacility.patientUuid,
facilityUuid = currentFacility.uuid,
status = Appointment.Status.Scheduled,
cancelReason = null,
creationFacilityUuid = facilityInAnotherSyncGroup.uuid
)
val scheduledAppointmentInOtherFacilityInCurrentSyncGroup = TestData.appointment(
uuid = UUID.fromString("df48b2ef-af5d-4127-9e8e-0877e4ff0402"),
patientUuid = patientWithScheduledAppointmentInOtherFacilityInCurrentSyncGroup.patientUuid,
facilityUuid = otherFacilityInCurrentSyncGroup.uuid,
status = Appointment.Status.Scheduled,
cancelReason = null,
creationFacilityUuid = facilityInAnotherSyncGroup.uuid
)
val cancelledAppointment = TestData.appointment(
uuid = UUID.fromString("4280ab0c-4c9e-4de1-b01c-966a85ec753e"),
patientUuid = patientWithCancelledAppointment.patientUuid,
facilityUuid = currentFacility.uuid,
status = Appointment.Status.Cancelled,
cancelReason = AppointmentCancelReason.PatientNotResponding,
creationFacilityUuid = facilityInAnotherSyncGroup.uuid
)
val visitedAppointment = TestData.appointment(
uuid = UUID.fromString("4280ab0c-4c9e-4de1-b01c-966a85ec753e"),
patientUuid = patientWithCancelledAppointment.patientUuid,
facilityUuid = currentFacility.uuid,
status = Appointment.Status.Visited,
cancelReason = null,
creationFacilityUuid = facilityInAnotherSyncGroup.uuid
)
val allAppointments = listOf(
scheduledAppointmentInCurrentFacility,
scheduledAppointmentInOtherFacilityInCurrentSyncGroup,
cancelledAppointment,
visitedAppointment
)
appointmentDao.save(allAppointments)
// when
database.deletePatientsNotInFacilitySyncGroup(currentFacility)
// then
assertThat(patientRepository.allPatientProfiles()).containsExactly(
patientWithScheduledAppointmentInCurrentFacility,
patientWithScheduledAppointmentInOtherFacilityInCurrentSyncGroup
)
}
@Test
fun deleting_the_sync_group_data_should_delete_blood_pressure_measurements_which_do_not_have_a_linked_patient() {
// given
val patientInCurrentFacility = TestData.patientProfile(
patientUuid = UUID.fromString("d1523ba6-bad3-42f2-a920-a503f1a503e3"),
syncStatus = SyncStatus.DONE,
patientRegisteredFacilityId = currentFacility.uuid,
patientAssignedFacilityId = currentFacility.uuid
)
val patientInOtherFacilityInSyncGroup = TestData.patientProfile(
patientUuid = UUID.fromString("cc131584-b88b-42b8-8f4c-29c93021765f"),
syncStatus = SyncStatus.DONE,
patientRegisteredFacilityId = otherFacilityInCurrentSyncGroup.uuid,
patientAssignedFacilityId = otherFacilityInCurrentSyncGroup.uuid
)
val patientInOtherSyncGroup = TestData.patientProfile(
patientUuid = UUID.fromString("5cbe9277-d18a-49ad-a73b-1840a7aba0a9"),
syncStatus = SyncStatus.DONE,
patientRegisteredFacilityId = facilityInAnotherSyncGroup.uuid,
patientAssignedFacilityId = facilityInAnotherSyncGroup.uuid
)
patientRepository.save(listOf(
patientInCurrentFacility,
patientInOtherFacilityInSyncGroup,
patientInOtherSyncGroup
))
val bloodPressuresForPatientInCurrentFacility = listOf(
TestData.bloodPressureMeasurement(
uuid = UUID.fromString("a8ad7e61-19d3-4bb0-97bc-3aff2c5b3165"),
patientUuid = patientInCurrentFacility.patientUuid,
facilityUuid = currentFacility.uuid,
syncStatus = SyncStatus.DONE
),
TestData.bloodPressureMeasurement(
uuid = UUID.fromString("6536ca4a-c053-4d12-8fc6-f05dd210c0d2"),
patientUuid = patientInCurrentFacility.patientUuid,
facilityUuid = otherFacilityInCurrentSyncGroup.uuid,
syncStatus = SyncStatus.DONE
),
TestData.bloodPressureMeasurement(
uuid = UUID.fromString("222ebe94-dfd3-4632-95a4-4ecde30a8ee9"),
patientUuid = patientInCurrentFacility.patientUuid,
facilityUuid = facilityInAnotherSyncGroup.uuid,
syncStatus = SyncStatus.DONE
)
)
val bloodPressuresForPatientInOtherFacilityInCurrentSyncGroup = listOf(
TestData.bloodPressureMeasurement(
uuid = UUID.fromString("79c98115-4894-4fb7-8264-fb442a48b225"),
patientUuid = patientInOtherFacilityInSyncGroup.patientUuid,
facilityUuid = currentFacility.uuid,
syncStatus = SyncStatus.DONE
),
TestData.bloodPressureMeasurement(
uuid = UUID.fromString("092de4a7-6493-4313-bfab-6bd2741ec143"),
patientUuid = patientInOtherFacilityInSyncGroup.patientUuid,
facilityUuid = otherFacilityInCurrentSyncGroup.uuid,
syncStatus = SyncStatus.DONE
),
TestData.bloodPressureMeasurement(
uuid = UUID.fromString("cae126b9-515d-4056-8262-6d37b4a251e1"),
patientUuid = patientInOtherFacilityInSyncGroup.patientUuid,
facilityUuid = facilityInAnotherSyncGroup.uuid,
syncStatus = SyncStatus.DONE
)
)
val unsyncedBloodPressureMeasurementForPatientInOtherSyncGroup = TestData.bloodPressureMeasurement(
uuid = UUID.fromString("ba9b72e9-da63-4d69-a023-0339a274c34e"),
patientUuid = patientInOtherSyncGroup.patientUuid,
facilityUuid = facilityInAnotherSyncGroup.uuid,
syncStatus = SyncStatus.PENDING
)
val bloodPressuresForPatientInOtherSyncGroup = listOf(
TestData.bloodPressureMeasurement(
uuid = UUID.fromString("75de9139-a7e0-4c55-9cb1-058b76e06da7"),
patientUuid = patientInOtherSyncGroup.patientUuid,
facilityUuid = currentFacility.uuid,
syncStatus = SyncStatus.DONE
),
TestData.bloodPressureMeasurement(
uuid = UUID.fromString("a3ac1607-fcee-4d8c-b2ea-f6c77b301a33"),
patientUuid = patientInOtherSyncGroup.patientUuid,
facilityUuid = otherFacilityInCurrentSyncGroup.uuid,
syncStatus = SyncStatus.DONE
),
TestData.bloodPressureMeasurement(
uuid = UUID.fromString("2b625418-16b1-46aa-97af-76f9245d9ece"),
patientUuid = patientInOtherSyncGroup.patientUuid,
facilityUuid = facilityInAnotherSyncGroup.uuid,
syncStatus = SyncStatus.DONE
),
unsyncedBloodPressureMeasurementForPatientInOtherSyncGroup
)
val allBloodPressureMeasurements = bloodPressuresForPatientInCurrentFacility +
bloodPressuresForPatientInOtherFacilityInCurrentSyncGroup +
bloodPressuresForPatientInOtherSyncGroup
bloodPressureMeasurementDao.save(allBloodPressureMeasurements)
assertThat(bloodPressureMeasurementDao.getAllBloodPressureMeasurements()).containsExactlyElementsIn(allBloodPressureMeasurements)
// when
database.deletePatientsNotInFacilitySyncGroup(currentFacility)
// then
val expectedBloodPressureMeasurements = bloodPressuresForPatientInCurrentFacility +
bloodPressuresForPatientInOtherFacilityInCurrentSyncGroup +
unsyncedBloodPressureMeasurementForPatientInOtherSyncGroup
assertThat(bloodPressureMeasurementDao.getAllBloodPressureMeasurements()).containsExactlyElementsIn(expectedBloodPressureMeasurements)
}
@Test
fun deleting_the_sync_group_data_should_delete_blood_sugar_measurements_which_do_not_have_a_linked_patient() {
// given
val patientInCurrentFacility = TestData.patientProfile(
patientUuid = UUID.fromString("d1523ba6-bad3-42f2-a920-a503f1a503e3"),
syncStatus = SyncStatus.DONE,
patientRegisteredFacilityId = currentFacility.uuid,
patientAssignedFacilityId = currentFacility.uuid
)
val patientInOtherFacilityInSyncGroup = TestData.patientProfile(
patientUuid = UUID.fromString("cc131584-b88b-42b8-8f4c-29c93021765f"),
syncStatus = SyncStatus.DONE,
patientRegisteredFacilityId = otherFacilityInCurrentSyncGroup.uuid,
patientAssignedFacilityId = otherFacilityInCurrentSyncGroup.uuid
)
val patientInOtherSyncGroup = TestData.patientProfile(
patientUuid = UUID.fromString("5cbe9277-d18a-49ad-a73b-1840a7aba0a9"),
syncStatus = SyncStatus.DONE,
patientRegisteredFacilityId = facilityInAnotherSyncGroup.uuid,
patientAssignedFacilityId = facilityInAnotherSyncGroup.uuid
)
patientRepository.save(listOf(
patientInCurrentFacility,
patientInOtherFacilityInSyncGroup,
patientInOtherSyncGroup
))
val bloodSugarsForPatientInCurrentFacility = listOf(
TestData.bloodSugarMeasurement(
uuid = UUID.fromString("a8ad7e61-19d3-4bb0-97bc-3aff2c5b3165"),
patientUuid = patientInCurrentFacility.patientUuid,
facilityUuid = currentFacility.uuid,
syncStatus = SyncStatus.DONE
),
TestData.bloodSugarMeasurement(
uuid = UUID.fromString("6536ca4a-c053-4d12-8fc6-f05dd210c0d2"),
patientUuid = patientInCurrentFacility.patientUuid,
facilityUuid = otherFacilityInCurrentSyncGroup.uuid,
syncStatus = SyncStatus.DONE
),
TestData.bloodSugarMeasurement(
uuid = UUID.fromString("222ebe94-dfd3-4632-95a4-4ecde30a8ee9"),
patientUuid = patientInCurrentFacility.patientUuid,
facilityUuid = facilityInAnotherSyncGroup.uuid,
syncStatus = SyncStatus.DONE
)
)
val bloodSugarsForPatientInOtherFacilityInCurrentSyncGroup = listOf(
TestData.bloodSugarMeasurement(
uuid = UUID.fromString("79c98115-4894-4fb7-8264-fb442a48b225"),
patientUuid = patientInOtherFacilityInSyncGroup.patientUuid,
facilityUuid = currentFacility.uuid,
syncStatus = SyncStatus.DONE
),
TestData.bloodSugarMeasurement(
uuid = UUID.fromString("092de4a7-6493-4313-bfab-6bd2741ec143"),
patientUuid = patientInOtherFacilityInSyncGroup.patientUuid,
facilityUuid = otherFacilityInCurrentSyncGroup.uuid,
syncStatus = SyncStatus.DONE
),
TestData.bloodSugarMeasurement(
uuid = UUID.fromString("cae126b9-515d-4056-8262-6d37b4a251e1"),
patientUuid = patientInOtherFacilityInSyncGroup.patientUuid,
facilityUuid = facilityInAnotherSyncGroup.uuid,
syncStatus = SyncStatus.DONE
)
)
val unsyncedBloodSugarMeasurementForPatientInOtherSyncGroup = TestData.bloodSugarMeasurement(
uuid = UUID.fromString("ba9b72e9-da63-4d69-a023-0339a274c34e"),
patientUuid = patientInOtherSyncGroup.patientUuid,
facilityUuid = facilityInAnotherSyncGroup.uuid,
syncStatus = SyncStatus.PENDING
)
val bloodSugarsForPatientInOtherSyncGroup = listOf(
TestData.bloodSugarMeasurement(
uuid = UUID.fromString("75de9139-a7e0-4c55-9cb1-058b76e06da7"),
patientUuid = patientInOtherSyncGroup.patientUuid,
facilityUuid = currentFacility.uuid,
syncStatus = SyncStatus.DONE
),
TestData.bloodSugarMeasurement(
uuid = UUID.fromString("a3ac1607-fcee-4d8c-b2ea-f6c77b301a33"),
patientUuid = patientInOtherSyncGroup.patientUuid,
facilityUuid = otherFacilityInCurrentSyncGroup.uuid,
syncStatus = SyncStatus.DONE
),
TestData.bloodSugarMeasurement(
uuid = UUID.fromString("2b625418-16b1-46aa-97af-76f9245d9ece"),
patientUuid = patientInOtherSyncGroup.patientUuid,
facilityUuid = facilityInAnotherSyncGroup.uuid,
syncStatus = SyncStatus.DONE
),
unsyncedBloodSugarMeasurementForPatientInOtherSyncGroup
)
val allBloodSugarMeasurements = bloodSugarsForPatientInCurrentFacility +
bloodSugarsForPatientInOtherFacilityInCurrentSyncGroup +
bloodSugarsForPatientInOtherSyncGroup
bloodSugarMeasurementDao.save(allBloodSugarMeasurements)
assertThat(bloodSugarMeasurementDao.getAllBloodSugarMeasurements()).containsExactlyElementsIn(allBloodSugarMeasurements)
// when
database.deletePatientsNotInFacilitySyncGroup(currentFacility)
// then
val expectedBloodSugarMeasurements = bloodSugarsForPatientInCurrentFacility +
bloodSugarsForPatientInOtherFacilityInCurrentSyncGroup +
unsyncedBloodSugarMeasurementForPatientInOtherSyncGroup
assertThat(bloodSugarMeasurementDao.getAllBloodSugarMeasurements()).containsExactlyElementsIn(expectedBloodSugarMeasurements)
}
@Test
fun deleting_the_sync_group_data_should_delete_appointments_which_do_not_have_a_linked_patient() {
// given
val patientInCurrentFacility = TestData.patientProfile(
patientUuid = UUID.fromString("d1523ba6-bad3-42f2-a920-a503f1a503e3"),
syncStatus = SyncStatus.DONE,
patientRegisteredFacilityId = currentFacility.uuid,
patientAssignedFacilityId = currentFacility.uuid
)
val patientInOtherFacilityInSyncGroup = TestData.patientProfile(
patientUuid = UUID.fromString("cc131584-b88b-42b8-8f4c-29c93021765f"),
syncStatus = SyncStatus.DONE,
patientRegisteredFacilityId = otherFacilityInCurrentSyncGroup.uuid,
patientAssignedFacilityId = otherFacilityInCurrentSyncGroup.uuid
)
val patientInOtherSyncGroup = TestData.patientProfile(
patientUuid = UUID.fromString("5cbe9277-d18a-49ad-a73b-1840a7aba0a9"),
syncStatus = SyncStatus.DONE,
patientRegisteredFacilityId = facilityInAnotherSyncGroup.uuid,
patientAssignedFacilityId = facilityInAnotherSyncGroup.uuid
)
patientRepository.save(listOf(
patientInCurrentFacility,
patientInOtherFacilityInSyncGroup,
patientInOtherSyncGroup
))
val appointmentsForPatientInCurrentFacility = listOf(
TestData.appointment(
uuid = UUID.fromString("a8ad7e61-19d3-4bb0-97bc-3aff2c5b3165"),
patientUuid = patientInCurrentFacility.patientUuid,
facilityUuid = currentFacility.uuid,
syncStatus = SyncStatus.DONE
),
TestData.appointment(
uuid = UUID.fromString("6536ca4a-c053-4d12-8fc6-f05dd210c0d2"),
patientUuid = patientInCurrentFacility.patientUuid,
facilityUuid = otherFacilityInCurrentSyncGroup.uuid,
syncStatus = SyncStatus.DONE
),
TestData.appointment(
uuid = UUID.fromString("222ebe94-dfd3-4632-95a4-4ecde30a8ee9"),
patientUuid = patientInCurrentFacility.patientUuid,
facilityUuid = facilityInAnotherSyncGroup.uuid,
syncStatus = SyncStatus.DONE
)
)
val appointmentsForPatientInOtherFacilityInCurrentSyncGroup = listOf(
TestData.appointment(
uuid = UUID.fromString("79c98115-4894-4fb7-8264-fb442a48b225"),
patientUuid = patientInOtherFacilityInSyncGroup.patientUuid,
facilityUuid = currentFacility.uuid,
syncStatus = SyncStatus.DONE
),
TestData.appointment(
uuid = UUID.fromString("092de4a7-6493-4313-bfab-6bd2741ec143"),
patientUuid = patientInOtherFacilityInSyncGroup.patientUuid,
facilityUuid = otherFacilityInCurrentSyncGroup.uuid,
syncStatus = SyncStatus.DONE
),
TestData.appointment(
uuid = UUID.fromString("cae126b9-515d-4056-8262-6d37b4a251e1"),
patientUuid = patientInOtherFacilityInSyncGroup.patientUuid,
facilityUuid = facilityInAnotherSyncGroup.uuid,
syncStatus = SyncStatus.DONE
)
)
val unsyncedAppointmentForPatientInOtherSyncGroup = TestData.appointment(
uuid = UUID.fromString("ba9b72e9-da63-4d69-a023-0339a274c34e"),
patientUuid = patientInOtherSyncGroup.patientUuid,
facilityUuid = facilityInAnotherSyncGroup.uuid,
status = Appointment.Status.Visited,
cancelReason = null,
syncStatus = SyncStatus.PENDING
)
val appointmentsForPatientInOtherSyncGroup = listOf(
TestData.appointment(
uuid = UUID.fromString("75de9139-a7e0-4c55-9cb1-058b76e06da7"),
patientUuid = patientInOtherSyncGroup.patientUuid,
facilityUuid = currentFacility.uuid,
syncStatus = SyncStatus.DONE,
status = Appointment.Status.Visited,
cancelReason = null
),
TestData.appointment(
uuid = UUID.fromString("a3ac1607-fcee-4d8c-b2ea-f6c77b301a33"),
patientUuid = patientInOtherSyncGroup.patientUuid,
facilityUuid = otherFacilityInCurrentSyncGroup.uuid,
syncStatus = SyncStatus.DONE,
status = Appointment.Status.Visited,
cancelReason = null
),
TestData.appointment(
uuid = UUID.fromString("2b625418-16b1-46aa-97af-76f9245d9ece"),
patientUuid = patientInOtherSyncGroup.patientUuid,
facilityUuid = facilityInAnotherSyncGroup.uuid,
syncStatus = SyncStatus.DONE,
status = Appointment.Status.Visited,
cancelReason = null
),
unsyncedAppointmentForPatientInOtherSyncGroup
)
val allAppointments = appointmentsForPatientInCurrentFacility +
appointmentsForPatientInOtherFacilityInCurrentSyncGroup +
appointmentsForPatientInOtherSyncGroup
appointmentDao.save(allAppointments)
assertThat(appointmentDao.getAllAppointments()).containsExactlyElementsIn(allAppointments)
// when
database.deletePatientsNotInFacilitySyncGroup(currentFacility)
// then
val expectedAppointments = appointmentsForPatientInCurrentFacility +
appointmentsForPatientInOtherFacilityInCurrentSyncGroup +
unsyncedAppointmentForPatientInOtherSyncGroup
assertThat(appointmentDao.getAllAppointments()).containsExactlyElementsIn(expectedAppointments)
}
@Test
fun deleting_the_sync_group_data_should_delete_prescribed_drugs_which_do_not_have_a_linked_patient() {
// given
val patientInCurrentFacility = TestData.patientProfile(
patientUuid = UUID.fromString("d1523ba6-bad3-42f2-a920-a503f1a503e3"),
syncStatus = SyncStatus.DONE,
patientRegisteredFacilityId = currentFacility.uuid,
patientAssignedFacilityId = currentFacility.uuid
)
val patientInOtherFacilityInSyncGroup = TestData.patientProfile(
patientUuid = UUID.fromString("cc131584-b88b-42b8-8f4c-29c93021765f"),
syncStatus = SyncStatus.DONE,
patientRegisteredFacilityId = otherFacilityInCurrentSyncGroup.uuid,
patientAssignedFacilityId = otherFacilityInCurrentSyncGroup.uuid
)
val patientInOtherSyncGroup = TestData.patientProfile(
patientUuid = UUID.fromString("5cbe9277-d18a-49ad-a73b-1840a7aba0a9"),
syncStatus = SyncStatus.DONE,
patientRegisteredFacilityId = facilityInAnotherSyncGroup.uuid,
patientAssignedFacilityId = facilityInAnotherSyncGroup.uuid
)
patientRepository.save(listOf(
patientInCurrentFacility,
patientInOtherFacilityInSyncGroup,
patientInOtherSyncGroup
))
val prescribedDrugsForPatientInCurrentFacility = listOf(
TestData.prescription(
uuid = UUID.fromString("a8ad7e61-19d3-4bb0-97bc-3aff2c5b3165"),
patientUuid = patientInCurrentFacility.patientUuid,
facilityUuid = currentFacility.uuid,
syncStatus = SyncStatus.DONE
),
TestData.prescription(
uuid = UUID.fromString("6536ca4a-c053-4d12-8fc6-f05dd210c0d2"),
patientUuid = patientInCurrentFacility.patientUuid,
facilityUuid = otherFacilityInCurrentSyncGroup.uuid,
syncStatus = SyncStatus.DONE
),
TestData.prescription(
uuid = UUID.fromString("222ebe94-dfd3-4632-95a4-4ecde30a8ee9"),
patientUuid = patientInCurrentFacility.patientUuid,
facilityUuid = facilityInAnotherSyncGroup.uuid,
syncStatus = SyncStatus.DONE
)
)
val prescribedDrugsForPatientInOtherFacilityInCurrentSyncGroup = listOf(
TestData.prescription(
uuid = UUID.fromString("79c98115-4894-4fb7-8264-fb442a48b225"),
patientUuid = patientInOtherFacilityInSyncGroup.patientUuid,
facilityUuid = currentFacility.uuid,
syncStatus = SyncStatus.DONE
),
TestData.prescription(
uuid = UUID.fromString("092de4a7-6493-4313-bfab-6bd2741ec143"),
patientUuid = patientInOtherFacilityInSyncGroup.patientUuid,
facilityUuid = otherFacilityInCurrentSyncGroup.uuid,
syncStatus = SyncStatus.DONE
),
TestData.prescription(
uuid = UUID.fromString("cae126b9-515d-4056-8262-6d37b4a251e1"),
patientUuid = patientInOtherFacilityInSyncGroup.patientUuid,
facilityUuid = facilityInAnotherSyncGroup.uuid,
syncStatus = SyncStatus.DONE
)
)
val unsyncedPrescribedDrugForPatientInOtherSyncGroup = TestData.prescription(
uuid = UUID.fromString("ba9b72e9-da63-4d69-a023-0339a274c34e"),
patientUuid = patientInOtherSyncGroup.patientUuid,
facilityUuid = facilityInAnotherSyncGroup.uuid,
syncStatus = SyncStatus.PENDING
)
val prescribedDrugsForPatientInOtherSyncGroup = listOf(
TestData.prescription(
uuid = UUID.fromString("75de9139-a7e0-4c55-9cb1-058b76e06da7"),
patientUuid = patientInOtherSyncGroup.patientUuid,
facilityUuid = currentFacility.uuid,
syncStatus = SyncStatus.DONE
),
TestData.prescription(
uuid = UUID.fromString("a3ac1607-fcee-4d8c-b2ea-f6c77b301a33"),
patientUuid = patientInOtherSyncGroup.patientUuid,
facilityUuid = otherFacilityInCurrentSyncGroup.uuid,
syncStatus = SyncStatus.DONE
),
TestData.prescription(
uuid = UUID.fromString("2b625418-16b1-46aa-97af-76f9245d9ece"),
patientUuid = patientInOtherSyncGroup.patientUuid,
facilityUuid = facilityInAnotherSyncGroup.uuid,
syncStatus = SyncStatus.DONE
),
unsyncedPrescribedDrugForPatientInOtherSyncGroup
)
val allPrescribedDrugs = prescribedDrugsForPatientInCurrentFacility +
prescribedDrugsForPatientInOtherFacilityInCurrentSyncGroup +
prescribedDrugsForPatientInOtherSyncGroup
prescribedDrugDao.save(allPrescribedDrugs)
assertThat(prescribedDrugDao.getAllPrescribedDrugs()).containsExactlyElementsIn(allPrescribedDrugs)
// when
database.deletePatientsNotInFacilitySyncGroup(currentFacility)
// then
val expectedPrescribedDrugs = prescribedDrugsForPatientInCurrentFacility +
prescribedDrugsForPatientInOtherFacilityInCurrentSyncGroup +
unsyncedPrescribedDrugForPatientInOtherSyncGroup
assertThat(prescribedDrugDao.getAllPrescribedDrugs()).containsExactlyElementsIn(expectedPrescribedDrugs)
}
@Test
fun deleting_the_sync_group_data_should_delete_medical_histories_which_do_not_have_a_linked_patient() {
// given
val patientInCurrentFacility = TestData.patientProfile(
patientUuid = UUID.fromString("d1523ba6-bad3-42f2-a920-a503f1a503e3"),
syncStatus = SyncStatus.DONE,
patientRegisteredFacilityId = currentFacility.uuid,
patientAssignedFacilityId = currentFacility.uuid
)
val patientInOtherFacilityInSyncGroup = TestData.patientProfile(
patientUuid = UUID.fromString("cc131584-b88b-42b8-8f4c-29c93021765f"),
syncStatus = SyncStatus.DONE,
patientRegisteredFacilityId = otherFacilityInCurrentSyncGroup.uuid,
patientAssignedFacilityId = otherFacilityInCurrentSyncGroup.uuid
)
val patientInOtherSyncGroup = TestData.patientProfile(
patientUuid = UUID.fromString("5cbe9277-d18a-49ad-a73b-1840a7aba0a9"),
syncStatus = SyncStatus.DONE,
patientRegisteredFacilityId = facilityInAnotherSyncGroup.uuid,
patientAssignedFacilityId = facilityInAnotherSyncGroup.uuid
)
patientRepository.save(listOf(
patientInCurrentFacility,
patientInOtherFacilityInSyncGroup,
patientInOtherSyncGroup
))
val medicalHistoryPatientInCurrentFacility = listOf(
TestData.medicalHistory(
uuid = UUID.fromString("a8ad7e61-19d3-4bb0-97bc-3aff2c5b3165"),
patientUuid = patientInCurrentFacility.patientUuid,
syncStatus = SyncStatus.DONE
)
)
val medicalHistoryForPatientInOtherFacilityInCurrentSyncGroup = listOf(
TestData.medicalHistory(
uuid = UUID.fromString("79c98115-4894-4fb7-8264-fb442a48b225"),
patientUuid = patientInOtherFacilityInSyncGroup.patientUuid,
syncStatus = SyncStatus.DONE
)
)
val unsyncedMedicalHistoryForPatientInOtherSyncGroup = TestData.medicalHistory(
uuid = UUID.fromString("ba9b72e9-da63-4d69-a023-0339a274c34e"),
patientUuid = patientInOtherSyncGroup.patientUuid,
syncStatus = SyncStatus.PENDING
)
val medicalHistoryForPatientInOtherSyncGroup = listOf(
TestData.medicalHistory(
uuid = UUID.fromString("75de9139-a7e0-4c55-9cb1-058b76e06da7"),
patientUuid = patientInOtherSyncGroup.patientUuid,
syncStatus = SyncStatus.DONE
),
unsyncedMedicalHistoryForPatientInOtherSyncGroup
)
val allMedicalHistories = medicalHistoryPatientInCurrentFacility +
medicalHistoryForPatientInOtherFacilityInCurrentSyncGroup +
medicalHistoryForPatientInOtherSyncGroup
medicalHistoryDao.saveHistories(allMedicalHistories)
assertThat(medicalHistoryDao.getAllMedicalHistories()).containsExactlyElementsIn(allMedicalHistories)
// when
database.deletePatientsNotInFacilitySyncGroup(currentFacility)
// then
val expectedMedicalHistories = medicalHistoryPatientInCurrentFacility +
medicalHistoryForPatientInOtherFacilityInCurrentSyncGroup +
unsyncedMedicalHistoryForPatientInOtherSyncGroup
assertThat(medicalHistoryDao.getAllMedicalHistories()).containsExactlyElementsIn(expectedMedicalHistories)
}
}
| 4 | Kotlin | 73 | 223 | 58d14c702db2b27b9dc6c1298c337225f854be6d | 33,854 | simple-android | MIT License |
compiler/testData/codegen/box/compileKotlinAgainstKotlin/jvmPackageNameInRootPackage.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // TARGET_BACKEND: JVM
// WITH_STDLIB
// MODULE: lib
// FILE: A.kt
@file:Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
@file:JvmPackageName("bar")
fun f() = "OK"
var v: Int = 1
// MODULE: main(lib)
// FILE: B.kt
fun box(): String {
v = 2
if (v != 2) return "Fail"
return f()
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 301 | kotlin | Apache License 2.0 |
bedrock/build.gradle.kts | alexsocha | 181,845,813 | false | {"Kotlin": 429248, "Dockerfile": 861, "JavaScript": 402, "Shell": 114} | import java.io.File
import java.util.UUID
import org.apache.commons.text.CaseUtils
import mod.lucky.build.*
val rootProjectProps = RootProjectProperties.fromProjectYaml(rootProject.rootDir)
repositories {
mavenCentral()
gradlePluginPortal()
}
plugins {
kotlin("jvm")
}
dependencies {
implementation(project(":common"))
}
buildscript {
dependencies {
classpath(files("$rootDir/tools/build/classes"))
classpath("org.apache.commons:commons-text:1.9")
}
}
val addonDistDir = "$rootDir/bedrock/build/processedResources/js/main/addon"
tasks.named<ProcessResources>("processResources") {
from("../common/src/jvmMain/resources/game/assets/lucky/textures/blocks") {
into("addon/resource_pack/textures/blocks")
}
from("../common/src/jvmMain/resources/game/assets/lucky/textures/blocks") {
into("addon/resource_pack")
include("lucky_block.png")
rename("lucky_block.png", "pack_icon.png")
}
from("../common/src/jvmMain/resources/game/assets/lucky/textures/blocks") {
into("addon/behavior_pack")
include("lucky_block.png")
rename("lucky_block.png", "pack_icon.png")
}
}
tasks.register<Delete>("clearStructures") {
delete(File("$addonDistDir/behavior_pack/structures/lucky").walkTopDown().toList())
}
tasks.register<JavaExec>("generateBedrockDrops") {
classpath = fileTree("$rootDir/tools/build/install/tools/lib")
mainClass.set("mod.lucky.tools.MainKt")
args = listOf(
"generate-bedrock-drops",
"--inputConfigFolder",
"$rootDir/bedrock/src/main/resources/lucky-config",
"--inputJsTemplateFile",
"$rootDir/bedrock/src/main/resources/serverScript.template.js",
"--blockId",
"lucky_block",
"--outputJsFile",
"$rootDir/bedrock/build/processedResources/serverScript.js",
"--outputStructuresFolder",
"$addonDistDir/behavior_pack/structures/lucky",
)
dependsOn(project(":tools").tasks.getByName("installDist"))
}
tasks.register<JavaExec>("nbtToMcstructure") {
classpath = fileTree("$rootDir/tools/build/install/tools/lib")
mainClass.set("mod.lucky.tools.MainKt")
args = listOf(
"nbt-to-mcstructure",
"$rootDir/common/src/jvmMain/resources/lucky-config/structures",
"--outputStructuresFolder",
"$addonDistDir/behavior_pack/structures/lucky",
"--blockConversionFile",
"$rootDir/tools/block_conversion.yaml",
"--outputGeneratedBlockConversionFile",
"$rootDir/tools/.debug/block_conversion.generated.yaml",
)
dependsOn(project(":tools").tasks.getByName("installDist"))
}
tasks.register<Copy>("copyTemplateAddon") {
val bedrockTemplateAddonBlockId = "custom_lucky_block"
fun getUuid(suffix: String): String {
val bedrockTemplateAddonUuid = UUID.nameUUIDFromBytes(
"lucky:${bedrockTemplateAddonBlockId}".toByteArray()
).toString()
return UUID.nameUUIDFromBytes("${bedrockTemplateAddonUuid}-${suffix}".toByteArray()).toString()
}
doFirst {
delete(fileTree("./build/processedResources/template-addon"))
}
from("./template-addon")
into("./build/template-addon")
inputs.property("blockId", bedrockTemplateAddonBlockId)
filesMatching(listOf("**/*.json", "**/*.lang")) {
expand(
"blockId" to bedrockTemplateAddonBlockId,
"addonId" to CaseUtils.toCamelCase(bedrockTemplateAddonBlockId, true, '_'),
"blockName" to bedrockTemplateAddonBlockId.split("_").joinToString(" ") {
it.capitalize() // TODO: use replaceFirstChar once gradle is updated to Kotlin 1.6
},
"behaviorPackUuid" to getUuid("behavior-pack"),
"behaviorPackModuleUuid" to getUuid("behavior-pack-module"),
"resourcePackUuid" to getUuid("resource-pack"),
"resourcePackModuleUuid" to getUuid("resource-pack-module"),
)
}
rename { fileName ->
fileName.replace("\${blockId}", "$bedrockTemplateAddonBlockId")
}
}
tasks.register<JavaExec>("buildTemplateAddon") {
classpath = fileTree("$rootDir/tools/build/install/tools/lib")
mainClass.set("mod.lucky.tools.MainKt")
args = listOf(
"generate-bedrock-config",
"--inputConfigFolder",
"./template-addon",
"--outputAddonFolder",
"./build/template-addon",
)
dependsOn(project(":tools").tasks.getByName("installDist"))
dependsOn("copyTemplateAddon")
}
tasks.register<Sync>("copyRuntimePacks") {
val addonPaths = mapOf(
"LuckyBlock" to "./build/processedResources/js/main/addon",
"LuckyBlockCustom" to "./build/processedResources/js/main/template-addons/template-addon-1-bedrock",
)
for ((addonName, addonPath) in addonPaths) {
from("$addonPath/resource_pack") {
into("development_resource_packs/${addonName}RP")
}
from("$addonPath/behavior_pack") {
into("development_behavior_packs/${addonName}BP")
}
}
into("./run")
dependsOn("copyServerScript")
dependsOn("clearStructures")
dependsOn("generateBedrockDrops")
dependsOn("nbtToMcstructure")
// workaround: gradle doesn't always detect that the input folder has changed
outputs.upToDateWhen { false }
}
tasks.register<Copy>("copyServerScript") {
from("./build/distributions/serverScript.js")
into("$addonDistDir/behavior_pack/scripts/server")
dependsOn("generateBedrockDrops")
}
tasks.register<Zip>("zipPack") {
archiveFileName.set("pack.zip")
destinationDirectory.set(file("./dist"))
from("./build/main/resources/pack")
dependsOn("processResources")
}
tasks.register<Zip>("exportDist") {
val version = rootProjectProps.projects[ProjectName.LUCKY_BLOCK_BEDROCK]!!.version
val distName = "${ProjectName.LUCKY_BLOCK_BEDROCK.fullName}-${version}"
val distDir = file("$rootDir/dist/$distName")
destinationDirectory.set(file("$rootDir/dist/$distName"))
archiveFileName.set("$distName.mcpack")
doFirst {
val distMeta = rootProjectProps.getDistMeta(rootDir, ProjectName.LUCKY_BLOCK_BEDROCK)
file(distDir).mkdirs()
file("$distDir/meta.yaml").writeText(distMeta.toYaml())
}
from("$rootDir/bedrock/build/processedResources/js/main/pack")
}
tasks.named("build").configure {
tasks.getByName("browserProductionWebpack").dependsOn("generateBedrockDrops")
tasks.getByName("browserProductionWebpack").inputs.file("./build/processedResources/serverScript.js")
tasks.getByName("copyServerScript").dependsOn("browserProductionWebpack")
tasks.getByName("exportDist").dependsOn("browserProductionWebpack")
dependsOn("browserProductionWebpack")
dependsOn("copyServerScript")
dependsOn("exportDist")
dependsOn("copyRuntimePacks")
}
tasks.register("buildDev").configure {
tasks.getByName("browserDevelopmentWebpack").dependsOn("generateBedrockDrops")
tasks.getByName("browserDevelopmentWebpack").inputs.file("./build/processedResources/generated-config.js")
tasks.getByName("copyServerScript").dependsOn("browserDevelopmentWebpack")
dependsOn("browserDevelopmentWebpack")
dependsOn("copyServerScript")
dependsOn("copyRuntimePacks")
}
dependencyLocking {
lockAllConfigurations()
lockMode.set(LockMode.LENIENT)
}
| 24 | Kotlin | 19 | 32 | ecccf2ae066b6c511bce35f16c0b1e06519c31c0 | 7,402 | luckyblock | FSF All Permissive License |
autodispose/build.gradle.kts | uber | 77,168,103 | false | {"Java": 350318, "Kotlin": 121569, "Shell": 1073} | /*
* Copyright (C) 2017. Uber Technologies
*
* 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.
*/
plugins {
alias(libs.plugins.kotlin.jvm)
alias(libs.plugins.android.lint)
alias(libs.plugins.animalSniffer)
alias(libs.plugins.mavenPublish)
}
lint {
abortOnError = true
warningsAsErrors = true
}
dependencies {
api(libs.rx.java)
compileOnly(libs.build.errorProneAnnotations)
signature(libs.build.animalSniffer) {
artifact {
name = "java17"
type = "signature"
}
}
lintChecks(project(":static-analysis:autodispose-lint"))
testImplementation(project(":test-utils"))
}
| 8 | Java | 233 | 3,343 | fe914d5ed63246eedb13c26744c302ea3cae0b4e | 1,120 | AutoDispose | Apache License 2.0 |
agp-7.1.0-alpha01/tools/base/build-system/gradle-core/src/test/java/com/android/build/gradle/internal/variant/VariantModelFixtures.kt | jomof | 374,736,765 | false | {"Java": 35519326, "Kotlin": 22849138, "C++": 2171001, "HTML": 1377915, "Starlark": 915536, "C": 141955, "Shell": 110207, "RenderScript": 58853, "Python": 25635, "CMake": 18109, "Batchfile": 12180, "Perl": 9310, "Dockerfile": 5690, "Makefile": 4535, "CSS": 4148, "JavaScript": 3488, "PureBasic": 2359, "GLSL": 1628, "AIDL": 1117, "Prolog": 277} | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.build.gradle.internal.variant
import com.android.build.gradle.internal.BuildTypeData
import com.android.build.gradle.internal.DefaultConfigData
import com.android.build.gradle.internal.ProductFlavorData
import com.android.build.gradle.internal.api.DefaultAndroidSourceSet
import com.android.build.gradle.internal.dependency.SourceSetManager
import com.android.build.gradle.internal.dsl.BuildType
import com.android.build.gradle.internal.dsl.DefaultConfig
import com.android.build.gradle.internal.dsl.ProductFlavor
import com.android.build.gradle.internal.dsl.SigningConfig
import com.android.build.gradle.internal.services.DslServices
import com.android.build.gradle.internal.services.createDslServices
import com.android.builder.core.BuilderConstants
import com.google.common.collect.ImmutableList
import org.gradle.api.Named
import org.mockito.Mockito
/**
* Basic DSL entry point for simulating a [VariantInputModel]
*
* This may later be replaced by the real DSL extension if they can be run without a full
* project/plugin
*/
interface VariantInputModelDsl {
fun defaultConfig(action: DefaultConfig.() -> Unit)
fun buildTypes(action: Container<BuildType>.() -> Unit)
fun productFlavors(action: Container<ProductFlavor>.() -> Unit)
}
/**
* Fake DSL Container to simulate [VariantInputModel]
*
* This may later be replaced by the real DSL extension if they can be run without a full
* project/plugin
*/
interface Container<T: Named> {
fun create(name: String): T
fun create(name: String, action: T.() -> Unit): T
}
/**
* DSL-type builder to create instances of [VariantInputModel].
*
* After running the DSL, use [toModel]
*/
class VariantInputModelBuilder(
private val dslServices: DslServices = createDslServices()
): VariantInputModelDsl {
val defaultConfig: DefaultConfig = DefaultConfig(BuilderConstants.MAIN, dslServices)
val buildTypes: ContainerImpl<BuildType> = ContainerImpl { name ->
dslServices.newInstance(BuildType::class.java, name, dslServices)
}
val productFlavors: ContainerImpl<ProductFlavor> = ContainerImpl { name ->
dslServices.newInstance(ProductFlavor::class.java, name, dslServices)
}
override fun defaultConfig(action: DefaultConfig.() -> Unit) {
action(defaultConfig)
}
override fun buildTypes(action: Container<BuildType>.() -> Unit) {
action(buildTypes)
}
override fun productFlavors(action: Container<ProductFlavor>.() -> Unit) {
action(productFlavors)
}
fun toModel() : TestVariantInputModel {
val buildTypes = buildTypes.values.map {
val mainSourceSet = Mockito.mock(DefaultAndroidSourceSet::class.java)
val testFixturesSourceSet = Mockito.mock(DefaultAndroidSourceSet::class.java)
val androidTestSourceSet = Mockito.mock(DefaultAndroidSourceSet::class.java)
val unitTestSourceSet = Mockito.mock(DefaultAndroidSourceSet::class.java)
BuildTypeData(it, mainSourceSet, testFixturesSourceSet, androidTestSourceSet, unitTestSourceSet)
}.associateBy { it.buildType.name }
val flavors = productFlavors.values.map {
val mainSourceSet = Mockito.mock(DefaultAndroidSourceSet::class.java)
val testFixturesSourceSet = Mockito.mock(DefaultAndroidSourceSet::class.java)
val androidTestSourceSet = Mockito.mock(DefaultAndroidSourceSet::class.java)
val unitTestSourceSet = Mockito.mock(DefaultAndroidSourceSet::class.java)
ProductFlavorData(it, mainSourceSet, testFixturesSourceSet, androidTestSourceSet, unitTestSourceSet)
}.associateBy { it.productFlavor.name }
// the default Config
val defaultConfig = DefaultConfigData(
defaultConfig,
Mockito.mock(DefaultAndroidSourceSet::class.java),
Mockito.mock(DefaultAndroidSourceSet::class.java),
Mockito.mock(DefaultAndroidSourceSet::class.java),
Mockito.mock(DefaultAndroidSourceSet::class.java)
)
// compute the implicit dimension list
val dimensionBuilder = ImmutableList.builder<String>()
val nameSet = mutableSetOf<String>()
for (flavor in productFlavors.values) {
val dim = flavor.dimension ?: continue
if (!nameSet.contains(dim)) {
nameSet.add(dim)
dimensionBuilder.add(dim)
}
}
return TestVariantInputModel(
defaultConfig,
buildTypes,
flavors,
mapOf(),
dimensionBuilder.build()
)
}
fun createDefaults() {
buildTypes {
create("debug") {
isDebuggable = true
}
create("release")
}
}
}
class ContainerImpl<T: Named>(
private val factory: (String) -> T
): Container<T> {
val values: MutableList<T> = mutableListOf()
override fun create(name: String) : T = maybeCreate(name)
override fun create(name: String, action: T.() -> Unit) = maybeCreate(name).also { action(it) }
private fun maybeCreate(name: String): T {
val result = values.find { it.name == name }
if (result != null) {
return result
}
return factory(name).also { values.add(it) }
}
}
/**
* Implementation of [VariantInputModel] adding an implicit flavor dimension list.
*/
class TestVariantInputModel(
override val defaultConfigData: DefaultConfigData<DefaultConfig>,
override val buildTypes: Map<String, BuildTypeData<BuildType>>,
override val productFlavors: Map<String, ProductFlavorData<ProductFlavor>>,
override val signingConfigs: Map<String, SigningConfig>,
/**
* Implicit dimension list, gathered from looking at all the flavors in the order
* they were added.
* This allows not having to declare them during tests to simplify the fake DSL.
*/
val implicitFlavorDimensions: List<String>,
override val sourceSetManager: SourceSetManager = Mockito.mock(SourceSetManager::class.java)
): VariantInputModel<DefaultConfig, BuildType, ProductFlavor, SigningConfig>
| 1 | Java | 1 | 0 | 9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51 | 6,801 | CppBuildCacheWorkInProgress | Apache License 2.0 |
compiler/testData/diagnostics/tests/controlFlowAnalysis/unnecessaryLateinit/secondaryConstructorDelegateLoop.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // FIR_IDENTICAL
// !DIAGNOSTICS: -UNUSED_PARAMETER
class Foo {
<!UNNECESSARY_LATEINIT!>lateinit<!> var bar: String
constructor() {
bar = ""
}
constructor(a: Int) : <!CYCLIC_CONSTRUCTOR_DELEGATION_CALL!>this<!>(a) {
bar = "a"
}
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 269 | kotlin | Apache License 2.0 |
app/src/main/java/com/yassineabou/clock/data/repository/AlarmRepository.kt | yassineAbou | 603,165,906 | false | {"Kotlin": 166506} | package com.yassineabou.clock.data.repository
import com.yassineabou.clock.data.local.AlarmDao
import com.yassineabou.clock.data.model.Alarm
import kotlinx.coroutines.flow.distinctUntilChanged
import javax.inject.Inject
class AlarmRepository @Inject constructor(
private val alarmDao: AlarmDao,
) {
val alarmsList = alarmDao.getAlarmsList().distinctUntilChanged()
suspend fun insert(alarm: Alarm) = alarmDao.insert(alarm)
suspend fun update(alarm: Alarm) = alarmDao.update(alarm)
suspend fun delete(alarm: Alarm) = alarmDao.delete(alarm)
suspend fun getLastId() = alarmDao.getLastId()
suspend fun clear() = alarmDao.clear()
suspend fun getAlarmById(id: Int) = alarmDao.getAlarmById(id)
fun getAlarmByTime(hour: String, minute: String, recurring: Boolean) =
alarmDao.getAlarmByTime(hour, minute, recurring)
}
| 0 | Kotlin | 0 | 4 | 7eb70533931fd4f3d2e827e6b072d6cae0a1a210 | 861 | Clock | Apache License 2.0 |