path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/com/ahmed/schedulebot/services/ImageService.kt | Ahmed-no-oil | 637,725,671 | false | null | package com.ahmed.schedulebot.services
import com.ahmed.schedulebot.entities.Week
import com.ahmed.schedulebot.repositories.ScheduleEntryRepository
import com.ahmed.schedulebot.repositories.WeekRepository
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.cache.annotation.CacheEvict
import org.springframework.cache.annotation.Cacheable
import org.springframework.stereotype.Service
import java.text.SimpleDateFormat
import java.util.*
@Service
class ImageService(val scheduleEntryRepository: ScheduleEntryRepository,
val weekRepository: WeekRepository,
val scheduleImageBuilder: ScheduleImageBuilder) {
private val LOGGER: Logger = LoggerFactory.getLogger(ImageService::class.java)
@Cacheable(value = ["schedule-image"], unless = "#result.length == 0")
fun getImage(year: Int, week: Int): ByteArray {
val weekObject = weekRepository.findByYearAndWeekNumber(year, week) ?: weekRepository.save(Week(year, week))
val scheduleEntries = scheduleEntryRepository.findByWeek(weekObject) ?: mutableListOf()
val imageStream = scheduleImageBuilder.create(scheduleEntries)
.drawBackground()
.drawWeekDates(getWeekDates(year, week))
.drawBubbles()
.writeDaysNames()
.writeStreamOrNot()
.writeTimes()
.writeComments()
.build()
return imageStream.readAllBytes() ?: byteArrayOf()
}
@CacheEvict(value = ["schedule-image"], allEntries = true)
fun clearImageCache() {
LOGGER.info("cleared image cache")
}
private fun getWeekDates(year: Int, week: Int): String {
var result: String
Calendar.getInstance().let {
it.firstDayOfWeek = Calendar.MONDAY
it[Calendar.YEAR] = year
it[Calendar.WEEK_OF_YEAR] = week
it[Calendar.DAY_OF_WEEK] = it.firstDayOfWeek
result = it[Calendar.DAY_OF_MONTH].toString()
it.add(Calendar.DAY_OF_WEEK, 6)
result += "-" + SimpleDateFormat("dd MMM", Locale.ENGLISH).format(it.time)
}
return result
}
}
| 0 | Kotlin | 0 | 0 | c92c2ddff514490520d5f7ca9bb78239bc021760 | 2,170 | Schedule-Bot | MIT No Attribution |
NeuroID/src/test/java/com/neuroid/tracker/events/NIDIdentityAllViewsTest.kt | Neuro-ID | 433,158,128 | false | {"Kotlin": 600757, "JavaScript": 1588, "Shell": 1330, "HTML": 755} | package com.neuroid.tracker.events
import android.text.Editable
import android.widget.EditText
import android.widget.ImageButton
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.RatingBar
import android.widget.SeekBar
import android.widget.ToggleButton
import androidx.appcompat.widget.SwitchCompat
import com.neuroid.tracker.getMockedNeuroID
import com.neuroid.tracker.getMockedView
import com.neuroid.tracker.utils.NIDLogWrapper
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.runs
import io.mockk.verify
import org.junit.Test
class NIDIdentityAllViewsTest {
@Test
fun identifyAllViews_edit_text() {
val editText = mockk<EditText>()
val editTextEditable = mockk<Editable>()
val view = getMockedView(editText)
every { editTextEditable.length } returns "this is edit text1 text".length
every { editText.context } returns view.context
every { editText.contentDescription } returns "edit text 1"
every { editText.text } returns editTextEditable
every { editText.parent } returns null
every { editText.addTextChangedListener(any()) } just runs
every { editText.getCustomSelectionActionModeCallback() } returns null
every { editText.setCustomSelectionActionModeCallback(any()) } just runs
val logger = mockk<NIDLogWrapper>()
every { logger.d(any(), any()) } just runs
every { logger.e(any(), any()) } just runs
val nidMock = getMockedNeuroID()
val registrationIdentificationHelper = RegistrationIdentificationHelper(nidMock, logger)
registrationIdentificationHelper.identifySingleView(view, "someguid")
verify {
logger.d(
"NID test output",
"etn: INPUT, et: EditText, eid: edit text 1, v:S~C~~23",
)
}
}
@Test
fun identifyAllViews_ToggleButton() {
val toggleButton = mockk<ToggleButton>()
val view = getMockedView(toggleButton)
every { toggleButton.context } returns view.context
every { toggleButton.contentDescription } returns "toggle button 1"
every { toggleButton.parent } returns null
val logger = mockk<NIDLogWrapper>()
every { logger.d(any(), any()) } just runs
every { logger.e(any(), any()) } just runs
val nidMock = getMockedNeuroID()
val registrationIdentificationHelper = RegistrationIdentificationHelper(nidMock, logger)
registrationIdentificationHelper.identifySingleView(view, "someguid")
verify {
logger.d(
"NID test output",
"etn: INPUT, et: ToggleButton, eid: toggle button 1, v:S~C~~0",
)
}
}
@Test
fun identifyAllViews_SwitchCompat() {
val switchCompat = mockk<SwitchCompat>()
val view = getMockedView(switchCompat)
every { switchCompat.context } returns view.context
every { switchCompat.contentDescription } returns "switch compat"
every { switchCompat.parent } returns null
val logger = mockk<NIDLogWrapper>()
every { logger.d(any(), any()) } just runs
every { logger.e(any(), any()) } just runs
val nidMock = getMockedNeuroID()
val registrationIdentificationHelper = RegistrationIdentificationHelper(nidMock, logger)
registrationIdentificationHelper.identifySingleView(view, "someguid")
verify {
logger.d(
"NID test output",
"etn: INPUT, et: SwitchCompat, eid: switch compat, v:S~C~~0",
)
}
}
@Test
fun identifyAllViews_ImageButton() {
val imageButton = mockk<ImageButton>()
val view = getMockedView(imageButton)
every { imageButton.context } returns view.context
every { imageButton.contentDescription } returns "image button"
every { imageButton.parent } returns null
val logger = mockk<NIDLogWrapper>()
every { logger.d(any(), any()) } just runs
every { logger.e(any(), any()) } just runs
val nidMock = getMockedNeuroID()
val registrationIdentificationHelper = RegistrationIdentificationHelper(nidMock, logger)
registrationIdentificationHelper.identifySingleView(view, "someguid")
verify {
logger.d(
"NID test output",
"etn: INPUT, et: ImageButton, eid: image button, v:S~C~~0",
)
}
}
@Test
fun identifyAllViews_SeekBar() {
val seekBar = mockk<SeekBar>()
val view = getMockedView(seekBar)
every { seekBar.context } returns view.context
every { seekBar.contentDescription } returns "seek bar"
every { seekBar.parent } returns null
val logger = mockk<NIDLogWrapper>()
every { logger.d(any(), any()) } just runs
every { logger.e(any(), any()) } just runs
val nidMock = getMockedNeuroID()
val registrationIdentificationHelper = RegistrationIdentificationHelper(nidMock, logger)
registrationIdentificationHelper.identifySingleView(view, "someguid")
verify { logger.d("NID test output", "etn: INPUT, et: SeekBar, eid: seek bar, v:S~C~~0") }
}
@Test
fun identifyAllViews_RatingBar() {
val ratingBar = mockk<RatingBar>()
val view = getMockedView(ratingBar)
every { ratingBar.context } returns view.context
every { ratingBar.contentDescription } returns "rating bar"
every { ratingBar.parent } returns null
val logger = mockk<NIDLogWrapper>()
every { logger.d(any(), any()) } just runs
every { logger.e(any(), any()) } just runs
val nidMock = getMockedNeuroID()
val registrationIdentificationHelper = RegistrationIdentificationHelper(nidMock, logger)
registrationIdentificationHelper.identifySingleView(view, "someguid")
verify {
logger.d(
"NID test output",
"etn: INPUT, et: RatingBar, eid: rating bar, v:S~C~~0",
)
}
}
@Test
fun identifyAllViews_radio_button_group() {
val radioButtonViewParent4 = mockk<RadioGroup>()
val radioButtonViewParent3 = mockk<RadioGroup>()
val radioButtonViewParent2 = mockk<RadioGroup>()
val radioButtonViewParent = mockk<RadioGroup>()
val radioButton = mockk<RadioButton>()
val radioGroup = mockk<RadioGroup>()
val view = getMockedView(radioGroup)
every { radioButton.context } returns view.context
every { radioButtonViewParent4.id } returns 13
every { radioButtonViewParent3.parent } returns radioButtonViewParent4
every { radioButtonViewParent3.id } returns 12
every { radioButtonViewParent2.parent } returns radioButtonViewParent3
every { radioButtonViewParent2.id } returns 11
every { radioButtonViewParent.parent } returns null
every { radioButtonViewParent.contentDescription } returns "RadioGroupParent"
every { radioButtonViewParent.id } returns 10
every { radioGroup.context } returns view.context
every { radioGroup.parent } returns null
every { radioGroup.setOnHierarchyChangeListener(any()) } just runs
every { radioGroup.checkedRadioButtonId } returns 12
every { radioGroup.contentDescription } returns "RadioGroup"
every { radioGroup.childCount } returns 1
every { radioGroup.getChildAt(0) } returns radioButton
every { radioButton.contentDescription } returns "RadioButton"
every { radioButton.isChecked } returns true
every { radioButton.parent } returns radioButtonViewParent
val logger = mockk<NIDLogWrapper>()
every { logger.d(any(), any()) } just runs
every { logger.e(any(), any()) } just runs
val nidMock = getMockedNeuroID()
val registrationIdentificationHelper = RegistrationIdentificationHelper(nidMock, logger)
registrationIdentificationHelper.identifySingleView(view, "someguid")
verify { logger.d("NID test output", "etn: INPUT, et: RadioGroup, eid: RadioGroup, v:12") }
verify(exactly = 2) {
logger.d(
"NID test output",
"etn: INPUT, et: RadioButton, eid: RadioButton, v:true",
)
}
}
}
| 1 | Kotlin | 3 | 2 | 5e40d3cc444c9a260441d9e9088643032cb3a5eb | 8,437 | neuroid-android-sdk | MIT License |
buildSrc/src/main/kotlin/Versions.kt | ACINQ | 192,964,514 | false | null | object Versions {
const val lightningKmp = "1.5.12-SNAPSHOT"
const val secp256k1 = "0.10.1"
const val torMobile = "0.2.0"
const val kotlin = "1.8.21"
const val coroutines = "1.7.2"
const val serialization = "1.5.1"
const val ktor = "2.3.2"
const val sqlDelight = "1.5.5"
const val kodeinMemory = "0.8.0"
const val slf4j = "1.7.30"
const val junit = "4.13"
const val fcmPlugin = "4.3.10"
object Android {
const val coreKtx = "1.9.0"
const val lifecycle = "2.5.1"
const val prefs = "1.2.0"
const val datastore = "1.0.0"
const val compose = "1.4.3"
const val composeCompiler = "1.4.7"
const val navCompose = "2.5.3"
const val accompanist = "0.30.1"
const val composeConstraintLayout = "1.1.0-alpha09"
const val biometrics = "1.1.0"
const val zxing = "4.1.0"
const val fcm = "22.0.0"
const val logback = "2.0.0"
const val testRunner = "1.3.0"
const val espresso = "3.3.0"
}
object AndroidLegacy {
const val eclair = "0.4.22-android-phoenix"
const val safeArgs = "2.4.2"
const val appCompat = "1.3.0"
const val material = "1.7.0"
const val navigation = "2.4.2"
const val constraint = "2.0.4"
const val lifecycleExtensions = "2.2.0"
const val lifecycle = "2.4.0"
const val work = "2.8.1"
const val viewpager = "1.0.0"
const val eventbus = "3.1.1"
const val torWrapper = "0.0.5"
const val torCtl = "0.4"
}
}
| 86 | null | 91 | 537 | 6c3e4f976cab8ec86d0fdaceb3b038484b7d333c | 1,598 | phoenix | Apache License 2.0 |
buildSrc/src/main/kotlin/Versions.kt | ACINQ | 192,964,514 | false | null | object Versions {
const val lightningKmp = "1.5.12-SNAPSHOT"
const val secp256k1 = "0.10.1"
const val torMobile = "0.2.0"
const val kotlin = "1.8.21"
const val coroutines = "1.7.2"
const val serialization = "1.5.1"
const val ktor = "2.3.2"
const val sqlDelight = "1.5.5"
const val kodeinMemory = "0.8.0"
const val slf4j = "1.7.30"
const val junit = "4.13"
const val fcmPlugin = "4.3.10"
object Android {
const val coreKtx = "1.9.0"
const val lifecycle = "2.5.1"
const val prefs = "1.2.0"
const val datastore = "1.0.0"
const val compose = "1.4.3"
const val composeCompiler = "1.4.7"
const val navCompose = "2.5.3"
const val accompanist = "0.30.1"
const val composeConstraintLayout = "1.1.0-alpha09"
const val biometrics = "1.1.0"
const val zxing = "4.1.0"
const val fcm = "22.0.0"
const val logback = "2.0.0"
const val testRunner = "1.3.0"
const val espresso = "3.3.0"
}
object AndroidLegacy {
const val eclair = "0.4.22-android-phoenix"
const val safeArgs = "2.4.2"
const val appCompat = "1.3.0"
const val material = "1.7.0"
const val navigation = "2.4.2"
const val constraint = "2.0.4"
const val lifecycleExtensions = "2.2.0"
const val lifecycle = "2.4.0"
const val work = "2.8.1"
const val viewpager = "1.0.0"
const val eventbus = "3.1.1"
const val torWrapper = "0.0.5"
const val torCtl = "0.4"
}
}
| 86 | null | 91 | 537 | 6c3e4f976cab8ec86d0fdaceb3b038484b7d333c | 1,598 | phoenix | Apache License 2.0 |
forger-data-jpa/src/main/kotlin/com/github/wenslo/forger/data/jpa/model/LongIdEntity.kt | wenslo | 547,177,354 | false | null | package com.github.wenslo.forger.data.jpa.model
import org.springframework.data.annotation.CreatedDate
import org.springframework.data.annotation.LastModifiedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import java.time.LocalDateTime
import javax.persistence.*
@MappedSuperclass
@EntityListeners(AuditingEntityListener::class)
abstract class LongIdEntity(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long? = null,
@CreatedDate
@Column(nullable = false, updatable = false)
var createdAt: LocalDateTime? = null,
@LastModifiedDate
@Column(nullable = false, updatable = true)
var updatedAt: LocalDateTime? = null
)
| 0 | Kotlin | 0 | 1 | dc3be4d08e7fe945bbdbaa3008ccdc267438cb0b | 705 | forger | Apache License 2.0 |
app/src/main/java/com/github/chudoxl/testcontacts/moxy/BaseMvpPresenter.kt | chudoxl | 178,079,862 | false | null | package com.github.chudoxl.testcontacts.moxy
import com.arellomobile.mvp.MvpPresenter
import com.arellomobile.mvp.MvpView
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
abstract class BaseMvpPresenter<V : MvpView> : MvpPresenter<V>() {
private val disposables = CompositeDisposable()
protected fun disposeOnDestroy(subscription: Disposable) {
disposables.add(subscription)
}
override fun onDestroy() {
super.onDestroy()
disposables.clear()
}
}
| 0 | Kotlin | 0 | 0 | 18cbb0a1f4726ebe4f5cdc6cb4da86c3ad15c555 | 541 | TestContacts | Apache License 2.0 |
app/src/main/java/io/github/msh91/arch/ui/base/adapter/SingleLayoutAdapter.kt | msh91 | 134,849,661 | false | null | package io.github.msh91.arch.ui.base.adapter
import androidx.databinding.ViewDataBinding
/**
* Simple implementation of [BaseAdapter] to use as a single layout adapter.
*/
open class SingleLayoutAdapter<T : Any, B : ViewDataBinding>(
private val layoutId: Int,
var items: List<T> = emptyList(),
onItemClicked: ((T) -> Unit)? = null,
onBind: B.(Int) -> Unit = {}
) : BaseAdapter<T, B>(items = items, onItemClicked = onItemClicked, onBind = onBind) {
override fun getLayoutId(position: Int): Int = layoutId
}
| 1 | null | 7 | 25 | 9f0bf81e3493ee733a0b64c9a64249eacd8b652b | 532 | arch | Apache License 2.0 |
fuel-kotlinx-serialization/src/test/kotlin/com/github/kittinunf/fuel/FuelKotlinxSerializationTest.kt | kittinunf | 36,847,034 | false | null | package com.github.kittinunf.fuel
import com.github.kittinunf.fuel.core.FuelError
import com.github.kittinunf.fuel.core.Handler
import com.github.kittinunf.fuel.core.Request
import com.github.kittinunf.fuel.core.Response
import com.github.kittinunf.fuel.jackson.jacksonDeserializerOf
import com.github.kittinunf.fuel.jackson.responseObject
import com.github.kittinunf.result.Result
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.CoreMatchers.instanceOf
import org.hamcrest.CoreMatchers.isA
import org.hamcrest.CoreMatchers.not
import org.hamcrest.CoreMatchers.notNullValue
import org.hamcrest.CoreMatchers.nullValue
import org.junit.After
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertThat
import org.junit.Before
import org.junit.Test
import org.mockserver.matchers.Times
import java.net.HttpURLConnection
class FuelJacksonTest {
init {
Fuel.testMode {
timeout = 15000
}
}
private lateinit var mock: MockHelper
@Before
fun setup() {
this.mock = MockHelper()
this.mock.setup()
}
@After
fun tearDown() {
this.mock.tearDown()
}
//Model
data class HttpBinUserAgentModel(var userAgent: String = "")
@Test
fun jacksonTestResponseObject() {
mock.chain(
request = mock.request().withPath("/user-agent"),
response = mock.reflect()
)
Fuel.get(mock.path("user-agent"))
.responseObject(jacksonDeserializerOf<HttpBinUserAgentModel>()) { _, _, result ->
assertThat(result.component1(), instanceOf(HttpBinUserAgentModel::class.java))
assertThat(result.component1()?.userAgent, not(""))
assertThat(result.component2(), instanceOf(FuelError::class.java))
}
}
@Test
fun jacksonTestResponseObjectError() {
mock.chain(
request = mock.request().withPath("/user-agent"),
response = mock.response().withStatusCode(HttpURLConnection.HTTP_NOT_FOUND)
)
Fuel.get(mock.path("user-agent"))
.responseObject(jacksonDeserializerOf<HttpBinUserAgentModel>()) { _, _, result ->
assertThat(result.component1(), notNullValue())
assertThat(result.component2(), instanceOf(Result.Failure::class.java))
}
}
@Test
fun jacksonTestResponseDeserializerObject() {
mock.chain(
request = mock.request().withPath("/user-agent"),
response = mock.reflect()
)
Fuel.get(mock.path("user-agent"))
.responseObject<HttpBinUserAgentModel> { _, _, result ->
assertThat(result.component1(), notNullValue())
assertThat(result.component2(), notNullValue())
}
}
@Test
fun jacksonTestResponseDeserializerObjectError() {
mock.chain(
request = mock.request().withPath("/user-agent"),
response = mock.response().withStatusCode(HttpURLConnection.HTTP_NOT_FOUND)
)
Fuel.get(mock.path("user-agent"))
.responseObject<HttpBinUserAgentModel> { _, _, result ->
assertThat(result.component1(), notNullValue())
assertThat(result.component2(), instanceOf(Result.Failure::class.java))
}
}
@Test
fun jacksonTestResponseHandlerObject() {
mock.chain(
request = mock.request().withPath("/user-agent"),
response = mock.reflect()
)
Fuel.get(mock.path("user-agent"))
.responseObject(object : Handler<HttpBinUserAgentModel> {
override fun success(request: Request, response: Response, value: HttpBinUserAgentModel) {
assertThat(value, notNullValue())
}
override fun failure(request: Request, response: Response, error: FuelError) {
assertThat(error, notNullValue())
}
})
}
@Test
fun jacksonTestResponseHandlerObjectError() {
mock.chain(
request = mock.request().withPath("/user-agent"),
response = mock.response().withStatusCode(HttpURLConnection.HTTP_NOT_FOUND)
)
Fuel.get(mock.path("user-agent"))
.responseObject(object : Handler<HttpBinUserAgentModel> {
override fun success(request: Request, response: Response, value: HttpBinUserAgentModel) {
assertThat(value, notNullValue())
}
override fun failure(request: Request, response: Response, error: FuelError) {
assertThat(error, instanceOf(Result.Failure::class.java))
}
})
}
@Test
fun jacksonTestResponseSyncObject() {
mock.chain(
request = mock.request().withPath("/issues/1"),
response = mock.response().withBody(
"{ \"id\": 1, \"title\": \"issue 1\", \"number\": null }"
).withStatusCode(HttpURLConnection.HTTP_OK)
)
val (_, res, result) = Fuel.get(mock.path("issues/1")).responseObject<IssueInfo>()
assertThat(res, notNullValue())
assertThat(result.get(), notNullValue())
assertThat(result.get(), isA(IssueInfo::class.java))
assertThat(result, notNullValue())
}
@Test
fun jacksonTestResponseSyncObjectError() {
mock.chain(
request = mock.request().withPath("/issues/1"),
response = mock.response().withStatusCode(HttpURLConnection.HTTP_NOT_FOUND)
)
val (_, res, result) = Fuel.get(mock.path("issues/1")).responseObject<IssueInfo>()
assertThat(res, notNullValue())
assertThat(result, notNullValue())
val (value, error) = result
assertThat(value, nullValue())
assertThat(error, notNullValue())
assertThat((error as FuelError).response.statusCode, equalTo(HttpURLConnection.HTTP_NOT_FOUND))
}
data class IssueInfo(val id: Int, val title: String, val number: Int)
@Test
fun testProcessingGenericList() {
mock.chain(
request = mock.request().withPath("/issues"),
response = mock.response().withBody("[ " +
"{ \"id\": 1, \"title\": \"issue 1\", \"number\": null }, " +
"{ \"id\": 2, \"title\": \"issue 2\", \"number\": 32 }, " +
" ]").withStatusCode(HttpURLConnection.HTTP_OK)
)
Fuel.get(mock.path("issues")).responseObject<List<IssueInfo>> { _, _, result ->
val issues = result.get()
assertNotEquals(issues.size, 0)
assertThat(issues[0], isA(IssueInfo::class.java))
}
}
@Test
fun manualDeserializationShouldWork() {
mock.chain(
request = mock.request().withPath("/issues"),
response = mock.response().withBody("[ " +
"{ \"id\": 1, \"title\": \"issue 1\", \"number\": null }, " +
"{ \"id\": 2, \"title\": \"issue 2\", \"number\": 32 }, " +
" ]").withStatusCode(HttpURLConnection.HTTP_OK),
times = Times.exactly(2)
)
Fuel.get(mock.path("issues")).response { _: Request, response: Response, result: Result<ByteArray, FuelError> ->
var issueList = jacksonDeserializerOf<List<IssueInfo>>().deserialize(response)
assertThat(issueList[0], isA(IssueInfo::class.java))
issueList = jacksonDeserializerOf<List<IssueInfo>>().deserialize(response.dataStream)!!
assertThat(issueList[0], isA(IssueInfo::class.java))
issueList = jacksonDeserializerOf<List<IssueInfo>>().deserialize(response.dataStream.reader())!!
assertThat(issueList[0], isA(IssueInfo::class.java))
issueList = jacksonDeserializerOf<List<IssueInfo>>().deserialize(result.get())!!
assertThat(issueList[0], isA(IssueInfo::class.java))
}
Fuel.get(mock.path("issues")).responseString { _: Request, _: Response, result: Result<String, FuelError> ->
val issueList = jacksonDeserializerOf<List<IssueInfo>>().deserialize(result.get())!!
assertThat(issueList[0], isA(IssueInfo::class.java))
}
}
}
| 83 | null | 397 | 4,181 | 105d3111d71623cb831af3f411ea253db766f369 | 8,307 | fuel | MIT License |
app/src/main/java/com/blocksdecoded/dex/utils/ui/DimenUtils.kt | Sakshamappinternational | 214,494,204 | true | {"Kotlin": 464312} | package com.blocksdecoded.dex.utils.ui
import android.content.Context
import com.blocksdecoded.dex.App
import kotlin.math.ceil
object DimenUtils {
fun dp(dp: Float, context: Context? = App.instance) = context?.let {
val density = context.resources.displayMetrics.density
if (dp == 0f) 0 else ceil((density * dp).toDouble()).toInt()
} ?: dp.toInt()
} | 0 | null | 0 | 0 | d9940d1210e54dc32bb135ef344b1d2e713f84ba | 357 | dex-app-android | MIT License |
app/src/main/kotlin/com/ivanovsky/passnotes/data/repository/encdb/EncryptedDatabaseKey.kt | aivanovski | 95,774,290 | false | {"Kotlin": 1165807, "Java": 109948, "Ruby": 2719} | package com.ivanovsky.passnotes.data.repository.encdb
import com.ivanovsky.passnotes.data.entity.KeyType
interface EncryptedDatabaseKey {
val type: KeyType
} | 7 | Kotlin | 2 | 24 | acd12d6deb37a91f27206b516e93f6d71dd03d4c | 163 | kpassnotes | Apache License 2.0 |
thymeleaf/src/main/kotlin/de/tschuehly/spring/viewcomponent/thymeleaf/ThymeleafViewContextContainerMethodReturnValueHandler.kt | tschuehly | 604,349,993 | false | null | package de.tschuehly.spring.viewcomponent.thymeleaf
import de.tschuehly.spring.viewcomponent.core.ViewContextContainer
import de.tschuehly.spring.viewcomponent.core.toMap
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.core.MethodParameter
import org.springframework.web.context.request.NativeWebRequest
import org.springframework.web.context.support.WebApplicationObjectSupport
import org.springframework.web.method.support.HandlerMethodReturnValueHandler
import org.springframework.web.method.support.ModelAndViewContainer
import org.thymeleaf.spring6.view.ThymeleafView
import org.thymeleaf.spring6.view.ThymeleafViewResolver
import java.util.*
class ThymeleafViewContextContainerMethodReturnValueHandler(
private val thymeleafViewResolver: ThymeleafViewResolver
) : HandlerMethodReturnValueHandler, WebApplicationObjectSupport() {
override fun supportsReturnType(returnType: MethodParameter): Boolean {
return ViewContextContainer::class.java.isAssignableFrom(returnType.parameterType)
}
override fun handleReturnValue(
returnValue: Any?,
returnType: MethodParameter,
mavContainer: ModelAndViewContainer,
webRequest: NativeWebRequest
) {
val request = webRequest.getNativeRequest(HttpServletRequest::class.java)!!
val response = webRequest.getNativeResponse(HttpServletResponse::class.java)!!
val viewContextContainer = returnValue as ViewContextContainer
viewContextContainer.viewContexts.forEach { viewContext ->
val view: ThymeleafView =
thymeleafViewResolver.resolveViewName(viewContext.componentTemplate!!, Locale.GERMAN) as ThymeleafView
view.render(viewContext.contextAttributes.toMap(), request, response)
}
mavContainer.isRequestHandled = true
}
}
| 3 | Kotlin | 5 | 94 | fc632f3ae32a43a1baf65e5f12bf37256d3356c1 | 1,894 | spring-view-component | MIT License |
app/src/main/java/com/mycompany/movies/view/adapter/TabViewPagerAdapter.kt | SeltonAlves | 654,772,779 | false | null | package com.mycompany.movies.view.adapter
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.mycompany.movies.view.fragment.CurrentlyInMoviesFragment
import com.mycompany.movies.view.fragment.FutureMoviesFragment
class TabViewPagerAdapter(
fragment: FragmentActivity
) : FragmentStateAdapter(fragment) {
private val tab = arrayOf("Atualmente nos Cinemas", "Estão Por vim")
private val fragment = arrayOf(CurrentlyInMoviesFragment(), FutureMoviesFragment())
override fun getItemCount(): Int = fragment.size
override fun createFragment(position: Int): Fragment {
return fragment[position]
}
fun getTabText(position: Int): String {
return tab[position]
}
} | 0 | Kotlin | 0 | 0 | 1fe1c42a5b5ad2313c4f28bd41c08582247900d4 | 806 | popcorn_movies_app | MIT License |
app/src/main/java/com/example/androidcomposeguideapp/StepListScreen.kt | Jsk1n22 | 853,761,030 | false | {"Kotlin": 39802} | package com.example.androidcomposeguideapp
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Card
import androidx.compose.material3.Icon
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ExpandLess
import androidx.compose.material.icons.filled.ExpandMore
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.androidcomposeguideapp.model.Step
import com.example.androidcomposeguideapp.model.StepRepository
import com.example.androidcomposeguideapp.ui.theme.Shapes
import com.example.androidcomposeguideapp.ui.theme.Typography
@Composable
fun GuideList(contentPadding: PaddingValues = PaddingValues(0.dp)) {
LazyColumn(
contentPadding = contentPadding
) {
items(StepRepository.steps) {
StepItem(it)
}
}
}
@Composable
private fun StepItem(
step: Step,
modifier: Modifier = Modifier
) {
var expanded by remember {
mutableStateOf(false)
}
val color by animateColorAsState(
targetValue = if (expanded) MaterialTheme.colorScheme.primaryContainer
else MaterialTheme.colorScheme.secondaryContainer,
label = "Colour Animation",
)
Card(
modifier = modifier
.padding(
top = dimensionResource(id = R.dimen.padding_medium),
start = dimensionResource(id = R.dimen.padding_small),
end = dimensionResource(id = R.dimen.padding_small)
)
.animateContentSize(
animationSpec = spring(
dampingRatio = Spring.DampingRatioNoBouncy,
stiffness = Spring.StiffnessMedium
)
)
) {
Column(
modifier
.fillMaxWidth()
.background(color)
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(dimensionResource(id = R.dimen.padding_medium))
) {
Text(
text = stringResource(id = step.stepName),
style = Typography.titleLarge,
modifier = Modifier.weight(1f)
)
ExpandButton(
expanded = expanded,
onClick = {expanded = !expanded}
)
}
if (expanded) {
Image(
painter = painterResource(id = step.stepImg),
contentDescription = null,
contentScale = ContentScale.Fit,
modifier = Modifier
.padding(horizontal = dimensionResource(id = R.dimen.padding_medium))
.align(Alignment.CenterHorizontally)
.clip(Shapes.small)
)
Text(
text = stringResource(id = step.stepInfo),
style = Typography.bodyLarge,
modifier = Modifier.padding(dimensionResource(id = R.dimen.padding_medium))
)
}
}
}
}
@Composable
fun ExpandButton(
expanded: Boolean,
onClick: () -> Unit,
modifier: Modifier = Modifier
) {
IconButton(
onClick = onClick,
modifier = modifier
) {
Icon(
imageVector = if (expanded) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore,
contentDescription = stringResource(id = R.string.expand_button_content_description),
tint = MaterialTheme.colorScheme.secondary,
modifier = Modifier.size(dimensionResource(id = R.dimen.icon_size))
)
}
}
@Composable
@Preview (showBackground = true, showSystemUi = false)
private fun StepItemPreview() {
StepItem(StepRepository.steps[3])
} | 0 | Kotlin | 0 | 0 | 8048b5091d4727bd217a0e4f9729c0822d1f9ed5 | 5,265 | Android_Compose_Guide_App | Apache License 2.0 |
compose-designer/src/com/android/tools/idea/compose/pickers/preview/utils/DeviceUtils.kt | JetBrains | 60,701,247 | false | {"Kotlin": 47327090, "Java": 36711107, "HTML": 1217549, "Starlark": 856686, "C++": 321587, "Python": 100400, "C": 71515, "Lex": 66732, "NSIS": 58538, "AIDL": 35209, "Shell": 28699, "CMake": 26717, "JavaScript": 18437, "Batchfile": 7828, "Smali": 7580, "RenderScript": 4411, "Makefile": 2298, "IDL": 269, "QMake": 18} | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.compose.pickers.preview.utils
import com.android.resources.ScreenOrientation
import com.android.resources.ScreenRound
import com.android.resources.ScreenSize
import com.android.sdklib.devices.Device
import com.android.sdklib.devices.DeviceManager
import com.android.sdklib.devices.Hardware
import com.android.sdklib.devices.Screen
import com.android.sdklib.devices.Software
import com.android.sdklib.devices.State
import com.android.tools.idea.avdmanager.AvdScreenData
import com.android.tools.idea.compose.pickers.preview.enumsupport.devices.CHIN_SIZE_PX_FOR_ROUND_CHIN
import com.android.tools.idea.compose.pickers.preview.property.DeviceConfig
import com.android.tools.idea.compose.pickers.preview.property.DimUnit
import com.android.tools.idea.compose.pickers.preview.property.MutableDeviceConfig
import com.android.tools.idea.compose.pickers.preview.property.Orientation
import com.android.tools.idea.compose.pickers.preview.property.Shape
import com.android.tools.idea.compose.pickers.preview.property.toMutableConfig
import com.android.tools.idea.configurations.Configuration
import com.android.tools.idea.configurations.ConfigurationManager
import com.android.tools.idea.flags.StudioFlags
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.module.Module
import kotlin.math.roundToInt
import kotlin.math.sqrt
import org.jetbrains.android.facet.AndroidFacet
import org.jetbrains.android.sdk.StudioAndroidSdkData
/** Prefix used by device specs to find devices by id. */
internal const val DEVICE_BY_ID_PREFIX = "id:"
/** Prefix used by device specs to find devices by name. */
internal const val DEVICE_BY_NAME_PREFIX = "name:"
/** Prefix used by device specs to create devices by hardware specs. */
internal const val DEVICE_BY_SPEC_PREFIX = "spec:"
/** id for the default device when no device is specified by the user. */
internal const val DEFAULT_DEVICE_ID = "pixel_5"
/** Full declaration for the default device. */
internal const val DEFAULT_DEVICE_ID_WITH_PREFIX = DEVICE_BY_ID_PREFIX + DEFAULT_DEVICE_ID
internal fun Device.toDeviceConfig(): DeviceConfig {
val config = MutableDeviceConfig().apply { dimUnit = DimUnit.px }
val deviceState = this.defaultState
val screen = deviceState.hardware.screen
config.width = screen.xDimension.toFloat()
config.height = screen.yDimension.toFloat()
config.dpi = screen.pixelDensity.dpiValue
config.orientation =
when (deviceState.orientation) {
ScreenOrientation.LANDSCAPE -> Orientation.landscape
else -> Orientation.portrait
}
if (screen.screenRound == ScreenRound.ROUND) {
if (StudioFlags.COMPOSE_PREVIEW_DEVICESPEC_INJECTOR.get()) {
config.shape = Shape.Round
config.chinSize = screen.chin.toFloat()
} else {
config.shape = if (screen.chin != 0) Shape.Chin else Shape.Round
}
} else {
config.shape = Shape.Normal
}
// Set the backing ID at the end, otherwise there's risk of deleting it by changing other
// properties
if (this.id != Configuration.CUSTOM_DEVICE_ID) {
config.parentDeviceId = this.id
}
return config
}
internal fun DeviceConfig.createDeviceInstance(): Device {
val deviceConfig =
if (this !is MutableDeviceConfig) {
this.toMutableConfig()
} else {
this
}
val customDevice =
Device.Builder()
.apply {
setTagId("")
setName("Custom")
setId(Configuration.CUSTOM_DEVICE_ID)
setManufacturer("")
addSoftware(Software())
addState(
State().apply {
isDefaultState = true
hardware = Hardware()
}
)
}
.build()
customDevice.defaultState.apply {
orientation =
when (deviceConfig.orientation) {
Orientation.landscape -> ScreenOrientation.LANDSCAPE
Orientation.portrait -> ScreenOrientation.PORTRAIT
}
hardware =
Hardware().apply {
screen =
Screen().apply {
// For "proper" conversions, the dpi in the DeviceConfig should be updated to the
// resolved density. This is to guarantee that the
// dimension as defined by the user reflects exactly in the Device (both the value and
// the unit), since this change in density
// may introduce an error when calculating the Screen dimensions
val resolvedDensity =
AvdScreenData.getScreenDensity(false, deviceConfig.dpi.toDouble(), 0)
deviceConfig.dpi = resolvedDensity.dpiValue
deviceConfig.dimUnit = DimUnit.px // Transforms dimension to Pixels
xDimension = deviceConfig.width.roundToInt()
yDimension = deviceConfig.height.roundToInt()
pixelDensity = resolvedDensity
diagonalLength =
sqrt((1.0 * xDimension * xDimension) + (1.0 * yDimension * yDimension)) /
pixelDensity.dpiValue
screenRound = if (deviceConfig.isRound) ScreenRound.ROUND else ScreenRound.NOTROUND
chin =
when {
deviceConfig.shape == Shape.Chin -> CHIN_SIZE_PX_FOR_ROUND_CHIN
deviceConfig.isRound -> deviceConfig.chinSize.roundToInt()
else -> 0
}
size = ScreenSize.getScreenSize(diagonalLength)
ratio = AvdScreenData.getScreenRatio(xDimension, yDimension)
}
}
}
return customDevice
}
/** Returns the [Device] used when there's no device specified by the user. */
internal fun ConfigurationManager.getDefaultPreviewDevice(): Device? =
devices.find { device -> device.id == DEFAULT_DEVICE_ID } ?: defaultDevice
/**
* Based on [deviceDefinition], returns a [Device] from the collection that matches the name or id,
* if it's a custom spec, returns a created custom [Device].
*
* Note that if it's a custom spec, the dimensions will be converted to pixels to instantiate the
* custom [Device].
*
* @see createDeviceInstance
*/
internal fun Collection<Device>.findOrParseFromDefinition(
deviceDefinition: String,
logger: Logger = Logger.getInstance(MutableDeviceConfig::class.java)
): Device? {
return when {
deviceDefinition.isBlank() -> null
deviceDefinition.startsWith(DEVICE_BY_SPEC_PREFIX) -> {
val deviceBySpec =
DeviceConfig.toMutableDeviceConfigOrNull(deviceDefinition, this)?.createDeviceInstance()
if (deviceBySpec == null) {
logger.warn("Unable to parse device configuration: $deviceDefinition")
}
return deviceBySpec
}
else -> findByIdOrName(deviceDefinition, logger)
}
}
internal fun Collection<Device>.findByIdOrName(
deviceDefinition: String,
logger: Logger = Logger.getInstance(MutableDeviceConfig::class.java)
): Device? {
val availableDevices = this
return when {
deviceDefinition.isBlank() -> null
deviceDefinition.startsWith(DEVICE_BY_ID_PREFIX) -> {
val id = deviceDefinition.removePrefix(DEVICE_BY_ID_PREFIX)
val deviceById = availableDevices.firstOrNull { it.id == id }
if (deviceById == null) {
logger.warn("Unable to find device with id '$id'")
}
return deviceById
}
deviceDefinition.startsWith(DEVICE_BY_NAME_PREFIX) -> {
val name = deviceDefinition.removePrefix(DEVICE_BY_NAME_PREFIX)
val deviceByName = availableDevices.firstOrNull { it.displayName == name }
if (deviceByName == null) {
logger.warn("Unable to find device with name '$name'")
}
return deviceByName
}
else -> {
logger.warn("Unsupported device definition: $deviceDefinition")
null
}
}
}
/**
* Returns the [Device]s present in the Sdk.
*
* @see DeviceManager
*/
internal fun getSdkDevices(module: Module): List<Device> {
return AndroidFacet.getInstance(module)?.let { facet ->
StudioAndroidSdkData.getSdkData(facet)
?.deviceManager
?.getDevices(DeviceManager.ALL_DEVICES)
?.filter { !it.isDeprecated }
?.toList()
}
?: emptyList()
}
| 3 | Kotlin | 230 | 912 | d88742a5542b0852e7cb2dd6571e01576cb52841 | 8,645 | android | Apache License 2.0 |
app/src/main/java/com/example/countryapplication/data/converters/StringListConverter.kt | ArnoudBury | 736,748,076 | false | {"Kotlin": 247251} | package com.example.countryapplication.data.converters
import androidx.room.TypeConverter
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
/**
* Type converter for converting a list of strings to and from a JSON string representation.
*/
class StringListConverter {
private val gson = Gson()
/**
* Converts a list of strings into a JSON string representation.
*
* @param stringList The list of strings to convert.
* @return A JSON string representing the list of strings.
*/
@TypeConverter
fun fromStringList(stringList: List<String>): String {
return gson.toJson(stringList)
}
/**
* Converts a JSON string into a list of strings.
*
* @param json The JSON string representing a list of strings.
* @return A list of strings parsed from the JSON string.
*/
@TypeConverter
fun toStringList(json: String): List<String> {
val listType = object : TypeToken<List<String>>() {}.type
return gson.fromJson(json, listType)
}
}
| 0 | Kotlin | 0 | 0 | 4ed765c89955b19b70809eb1ce654539fe15036f | 1,053 | Android_Arnoud_Bury_G3A2 | MIT License |
16_CameraIntent/CriminalIntent/app/src/main/java/com/bignerdranch/android/criminalintent/CriminalIntentApplication.kt | sby5388 | 373,231,323 | false | null | package com.bignerdranch.android.criminalintent
import android.app.Application
class CriminalIntentApplication : Application() {
override fun onCreate() {
super.onCreate()
CrimeRepository.initialize(this)
}
} | 1 | null | 4 | 8 | b0fc2c08e17e5333a50e4d57e1d47634e4db562c | 235 | AndroidBianChengQuanWeiZhiNanV4-kotlin | Apache License 2.0 |
src/main/kotlin/org/wagham/commands/Command.kt | kaironbot | 566,988,243 | false | null | package org.wagham.commands
import dev.kord.common.Locale
import dev.kord.core.Kord
import dev.kord.core.entity.interaction.response.PublicMessageInteractionResponse
import dev.kord.core.event.interaction.GuildChatInputCommandInteractionCreateEvent
import dev.kord.rest.builder.RequestBuilder
import dev.kord.rest.builder.message.modify.InteractionResponseModifyBuilder
import org.wagham.components.CacheManager
import org.wagham.components.Identifiable
import org.wagham.db.KabotMultiDBClient
import org.wagham.entities.InteractionParameters
import org.wagham.exceptions.GuildNotFoundException
interface Command<T: RequestBuilder<*>> : Identifiable {
val kord: Kord
val db: KabotMultiDBClient
val cacheManager: CacheManager
val commandName: String
val defaultDescription: String
val localeDescriptions: Map<Locale, String>
suspend fun registerCommand()
fun registerCallback()
suspend fun execute(event: GuildChatInputCommandInteractionCreateEvent): T.() -> Unit
suspend fun handleResponse(
builder: T.() -> Unit,
event: GuildChatInputCommandInteractionCreateEvent)
fun GuildChatInputCommandInteractionCreateEvent.extractCommonParameters(): InteractionParameters {
val guildId = this.interaction.data.guildId.value ?: throw GuildNotFoundException()
val locale = this.interaction.locale?.language ?: this.interaction.guildLocale?.language ?: "en"
return InteractionParameters(guildId, locale)
}
} | 2 | Kotlin | 0 | 0 | cd857d9dad1d9fbc4a9b72973ec036e30d6bbeca | 1,487 | kairon-bot | MIT License |
kotlin-electron/src/jsMain/generated/electron/common/WebContentsWillNavigateEventParams.kt | JetBrains | 93,250,841 | false | {"Kotlin": 12635434, "JavaScript": 423801} | // Generated by Karakum - do not modify it manually!
package electron.common
typealias WebContentsWillNavigateEventParams = electron.core.WebContentsWillNavigateEventParams
| 38 | Kotlin | 162 | 1,347 | 997ed3902482883db4a9657585426f6ca167d556 | 175 | kotlin-wrappers | Apache License 2.0 |
backend/src/test/kotlin/xyz/poeschl/roborush/test/utils/builder/Builders.kt | Poeschl | 722,426,258 | false | {"Kotlin": 258310, "Vue": 118735, "TypeScript": 46733, "Java": 4509, "SCSS": 2877, "Python": 2562, "HTML": 1711, "Dockerfile": 1520, "Batchfile": 570, "Shell": 542, "JavaScript": 270} | package xyz.poeschl.roborush.test.utils.builder
import org.junit.jupiter.api.Disabled
import xyz.poeschl.roborush.configuration.Builder
@Disabled("Marking this file as a test class, to allow a relaxed linting")
class Builders {
companion object {
/***
* This builds an instance of the given builder
* @param builder A builder (prefixed with '$'
* @return A created instance
*/
fun <T> a(builder: Builder<T>): T {
return builder.build()
}
/***
* This builds a single list with one element in it, the created instance.
* @param builder A builder (prefixed with '$'
* @return A list with one element and the built instance in it.
*/
fun <T> listWithOne(builder: Builder<T>): List<T> {
return listOf(builder.build())
}
/***
* This builds a single set with one element in it, the created instance.
* @param builder A builder (prefixed with '$'
* @return A set with one element and the built instance in it.
*/
fun <T> setWithOne(builder: Builder<T>): Set<T> {
return setOf(builder.build())
}
/**
* This returns a time-related instance.
* @param builder The builder which determine the time.
* @return A instance of this time
*/
fun <T> time(builder: TimeBuilder<T>): T {
return builder.build()
}
}
}
fun interface TimeBuilder<T> : Builder<T>
| 9 | Kotlin | 0 | 1 | 31d56d0f012bd5ffc5e6893e9785ba3a504f8622 | 1,400 | RoboRush | Apache License 2.0 |
app/src/main/java/com/howto/coredux/HowToVideoListAdapter.kt | mosofsky | 264,519,104 | false | null | package com.howto.coredux
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.howto.coredux.HowToReduxAction.*
class HowToVideoListAdapter(val mainActivity: MainActivity, private val howToVideos: List<HowToVideo>) : RecyclerView.Adapter<HowToVideoViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HowToVideoViewHolder {
return HowToVideoViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.video_list_item,
parent,
false
)
)
}
override fun getItemCount(): Int {
return howToVideos.size
}
override fun onBindViewHolder(howToVideoViewHolder: HowToVideoViewHolder, position: Int) {
val howToVideo = howToVideos[position]
howToVideoViewHolder.videoNameTextView.text = howToVideo.name
howToVideoViewHolder.itemView.setOnClickListener {
mainActivity.howToViewModel.dispatchAction(ShowVideoFragment_Start(howToVideo))
}
}
}
class HowToVideoViewHolder(view: View): RecyclerView.ViewHolder(view) {
val videoNameTextView: TextView = view.findViewById(R.id.videoNameTextView)
} | 0 | Kotlin | 0 | 0 | c8f001c09d5b4aec052c85368280596d3e23afcd | 1,314 | how-to-coredux | MIT License |
src/main/kotlin/com/github/christophpickl/derbauer/DerBauer.kt | christophpickl | 162,885,556 | false | null | package com.github.christophpickl.derbauer
import ch.qos.logback.classic.Level
import com.github.christophpickl.derbauer.home.HomeView
import com.github.christophpickl.derbauer.misc.Debugger
import com.github.christophpickl.derbauer.misc.DerBauerVersionChecker
import com.github.christophpickl.derbauer.model.Model
import com.github.christophpickl.derbauer.ui.Keyboard
import com.github.christophpickl.derbauer.ui.MainFrame
import com.github.christophpickl.derbauer.ui.MainTextArea
import com.github.christophpickl.derbauer.ui.Prompt
import com.github.christophpickl.derbauer.ui.RendererImpl
import com.github.christophpickl.derbauer.ui.isDigit
import com.github.christophpickl.derbauer.ui.isLowercaseLetter
import com.github.christophpickl.kpotpourri.common.version.Version2
import com.github.christophpickl.kpotpourri.logback4k.Logback4k
import com.github.christophpickl.kpotpourri.swing.AbortingExceptionHandler
import mu.KotlinLogging
import javax.swing.SwingUtilities
val CHEAT_MODE_PROPERTY = "derbauer.cheat"
val DEV_MODE_PROPERTY = "derbauer.dev"
private val log = KotlinLogging.logger {}
val CHEAT_MODE get() = (System.getProperty(CHEAT_MODE_PROPERTY) != null)
val DEV_MODE get() = (System.getProperty(DEV_MODE_PROPERTY) != null)
val currentVersion = Version2.parse(
DerBauer.javaClass.getResourceAsStream("/derbauer/version.txt").bufferedReader().use { it.readText() })!!
object DerBauer {
private val exceptionHandler = AbortingExceptionHandler()
@JvmStatic
@Suppress("TooGenericExceptionCaught")
fun main(args: Array<String>) {
try {
initLogging()
startDerBauer()
} catch (e: Exception) {
exceptionHandler.uncaughtException(Thread.currentThread(), e)
}
}
private fun startDerBauer() {
log.info { "Starting DerBauer v$currentVersion" }
Model.currentView = HomeView()
val prompt = Prompt()
val text = MainTextArea()
val keyboard = Keyboard { e ->
e.isDigit || e.isLowercaseLetter || e.keyChar == '.'
}
val renderer = RendererImpl(text, prompt)
val engine = Router(renderer)
text.addKeyListener(keyboard)
text.addKeyListener(Debugger.asKeyListener())
keyboard.dispatcher.add(prompt)
prompt.dispatcher.add(engine)
renderer.render()
if (CHEAT_MODE) {
log.info { "CHEAT MODE enabling all features." }
Model.features.all.forEach { it.enableCheat() }
}
SwingUtilities.invokeLater {
log.debug { "Showing user interface." }
Thread.currentThread().uncaughtExceptionHandler = exceptionHandler
MainFrame().buildAndShow(text)
}
DerBauerVersionChecker.checkLatestVersion()
}
private fun initLogging() {
Logback4k.reconfigure {
rootLevel = Level.WARN
packageLevel(Level.ALL, "com.github.christophpickl.derbauer")
packageLevel(Level.DEBUG, "com.github.christophpickl.kpotpourri")
addConsoleAppender {
pattern = "%d{HH:mm:ss} [%gray(%thread)] [%highlight(%-5level)] %cyan(%logger{30}) - %msg%n"
}
}
if (CHEAT_MODE) {
log.info { "CHEAT MODE enabled" }
}
if (DEV_MODE) {
log.info { "DEV MODE enabled" }
}
}
}
| 0 | Kotlin | 0 | 2 | 687b1608f30dd7988e67c1bcba1fe10faaa84423 | 3,390 | derbauer | Apache License 2.0 |
j2k/new/tests/testData/newJ2k/comments/commentsForConstructors.kt | JetBrains | 278,369,660 | false | null | internal class A // this is a primary constructor
// this is a secondary constructor 1
// end of primary constructor body
@JvmOverloads constructor(p: Int = 1) {
private val v = 1
// this is a secondary constructor 2
constructor(s: String) : this(s.length) {} // end of secondary constructor 2 body
// end of secondary constructor 1 body
}
internal class B // this constructor will disappear
// end of constructor body
(private val x: Int) {
fun foo() {}
}
internal class CtorComment /*
* The magic of comments
*/
// single line magic comments
{
var myA = "a"
}
internal class CtorComment2 /*
* The magic of comments
*/
// single line magic comments
| 284 | null | 5162 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 702 | intellij-kotlin | Apache License 2.0 |
revolver/src/commonMain/kotlin/com/umain/revolver/RevolverErrorHandler.kt | apegroup | 623,454,493 | false | {"Kotlin": 21984, "Shell": 177} | package com.umain.revolver
/**
* interface for implementing error handlers that can be reused
* and shared between multiple ViewModels
*/
interface MviErrorHandler<STATE, EFFECT, ERROR> {
suspend fun handleError(exception: ERROR, emit: Emitter<STATE, EFFECT>)
}
| 5 | Kotlin | 1 | 33 | 59931988ac6457df57e8ba57943623c2cfe3f5d0 | 271 | revolver | MIT License |
compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/modifier/ModifierLocalSameLayoutNodeTest.kt | JetBrains | 351,708,598 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.modifier
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.testutils.expectError
import androidx.compose.ui.Modifier
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.unit.dp
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import com.google.common.truth.Truth.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@MediumTest
@RunWith(AndroidJUnit4::class)
class ModifierLocalSameLayoutNodeTest {
@get:Rule val rule = createComposeRule()
private val defaultValue = "Default Value"
@Test
fun exceptionInsteadOfDefaultValue() {
// Arrange.
val localString = modifierLocalOf<String> { error("No default value") }
rule.setContent {
Box(
Modifier.modifierLocalConsumer {
expectError<IllegalStateException>(expectedMessage = "No default value") {
localString.current
}
}
)
}
}
@Test
fun defaultValue() {
// Arrange.
val localString = modifierLocalOf { defaultValue }
lateinit var readValue: String
rule.setContent { Box(Modifier.modifierLocalConsumer { readValue = localString.current }) }
// Assert.
rule.runOnIdle { assertThat(readValue).isEqualTo(defaultValue) }
}
@Test
fun doesNotReadValuesProvidedAfterThisModifier() {
// Arrange.
val localString = modifierLocalOf { defaultValue }
val providedValue = "Provided Value"
lateinit var readValue: String
rule.setContent {
Box(
Modifier.modifierLocalConsumer { readValue = localString.current }
.modifierLocalProvider(localString) { providedValue }
)
}
// Assert.
rule.runOnIdle { assertThat(readValue).isEqualTo(defaultValue) }
}
@Test
fun readValueProvidedImmediatelyBeforeThisModifier() {
// Arrange.
val localString = modifierLocalOf { defaultValue }
val providedValue = "Provided Value"
lateinit var readValue: String
rule.setContent {
Box(
Modifier.modifierLocalProvider(localString) { providedValue }
.modifierLocalConsumer { readValue = localString.current }
)
}
// Assert.
rule.runOnIdle { assertThat(readValue).isEqualTo(providedValue) }
}
@Test
fun readValueProvidedBeforeThisModifier() {
// Arrange.
val localString = modifierLocalOf { defaultValue }
val providedValue = "Provided Value"
lateinit var readValue: String
rule.setContent {
Box(
Modifier.modifierLocalProvider(localString) { providedValue }
.size(100.dp)
.modifierLocalConsumer { readValue = localString.current }
)
}
// Assert.
rule.runOnIdle { assertThat(readValue).isEqualTo(providedValue) }
}
@Test
fun readsTheLastValueProvidedBeforeThisModifier() {
// Arrange.
val localString = modifierLocalOf { defaultValue }
val providedValue1 = "Provided Value 1"
val providedValue2 = "Provided Value 2"
lateinit var readValue: String
rule.setContent {
Box(
Modifier.modifierLocalProvider(localString) { providedValue1 }
.modifierLocalProvider(localString) { providedValue2 }
.modifierLocalConsumer { readValue = localString.current }
)
}
// Assert.
rule.runOnIdle { assertThat(readValue).isEqualTo(providedValue2) }
}
@Test
fun multipleModifierLocalsOfSameDataType() {
// Arrange.
val localString1 = modifierLocalOf { defaultValue }
val localString2 = modifierLocalOf { defaultValue }
val providedValue1 = "Provided Value 1"
val providedValue2 = "Provided Value 2"
lateinit var readValue1: String
lateinit var readValue2: String
rule.setContent {
Box(
Modifier.modifierLocalProvider(localString1) { providedValue1 }
.modifierLocalProvider(localString2) { providedValue2 }
.modifierLocalConsumer {
readValue1 = localString1.current
readValue2 = localString2.current
}
)
}
// Assert.
rule.runOnIdle {
assertThat(readValue1).isEqualTo(providedValue1)
assertThat(readValue2).isEqualTo(providedValue2)
}
}
@Test
fun multipleModifierLocalsWithDifferentDataType() {
// Arrange.
val localString = modifierLocalOf { defaultValue }
val localInteger = modifierLocalOf { Int.MIN_VALUE }
val providedString = "Provided Value"
val providedInteger = 100
lateinit var readString: String
var readInteger = 0
rule.setContent {
Box(
Modifier.modifierLocalProvider(localString) { providedString }
.modifierLocalProvider(localInteger) { providedInteger }
.modifierLocalConsumer {
readString = localString.current
readInteger = localInteger.current
}
)
}
// Assert.
rule.runOnIdle {
assertThat(readString).isEqualTo(providedString)
assertThat(readInteger).isEqualTo(providedInteger)
}
}
@Test
fun modifierLocalProviderChanged() {
// Arrange.
val localString = modifierLocalOf { defaultValue }
val provider1value = "Provider1"
val provider2value = "Provider2"
var useFirstProvider by mutableStateOf(true)
lateinit var readString: String
rule.setContent {
Box(
Modifier.then(
if (useFirstProvider) {
Modifier.modifierLocalProvider(localString) { provider1value }
} else {
Modifier.modifierLocalProvider(localString) { provider2value }
}
)
.modifierLocalConsumer { readString = localString.current }
)
}
// Act.
rule.runOnIdle { useFirstProvider = false }
// Assert.
rule.runOnIdle { assertThat(readString).isEqualTo(provider2value) }
}
@Test
fun modifierLocalProviderChanged_returnsDefaultValueBeforeNewValue() {
// Arrange.
val localString = modifierLocalOf { defaultValue }
val provider1value = "Provider1"
val provider2value = "Provider2"
var useFirstProvider by mutableStateOf(true)
val receivedValues = mutableListOf<String>()
rule.setContent {
Box(
Modifier.then(
if (useFirstProvider) {
Modifier.modifierLocalProvider(localString) { provider1value }
} else {
Modifier.modifierLocalProvider(localString) { provider2value }
}
)
.modifierLocalConsumer { receivedValues.add(localString.current) }
)
}
// Act.
rule.runOnIdle { useFirstProvider = false }
// Assert.
rule.runOnIdle {
assertThat(receivedValues).containsExactly(provider1value, provider2value).inOrder()
}
}
@Test
fun modifierLocalConsumer_returnsDefaultValueWhenModifierIsDisposed() {
// Arrange.
val modifierLocal = modifierLocalOf { defaultValue }
var hasProvider by mutableStateOf(true)
lateinit var receivedValue: String
rule.setContent {
Box(
Modifier.then(
if (hasProvider) {
Modifier.modifierLocalProvider(modifierLocal) { "ProvidedValue" }
} else Modifier
)
.modifierLocalConsumer { receivedValue = modifierLocal.current }
)
}
// Act.
rule.runOnIdle { hasProvider = false }
// Assert.
rule.runOnIdle { assertThat(receivedValue).isEqualTo(defaultValue) }
}
@Test
fun modifierLocalConsumer_returnsDefaultValueWhenComposableIsDisposed() {
// Arrange.
val modifierLocal = modifierLocalOf { defaultValue }
var includeComposable by mutableStateOf(true)
lateinit var receivedValue: String
rule.setContent {
if (includeComposable) {
Box(
Modifier.modifierLocalProvider(modifierLocal) { "ProvidedValue" }
.modifierLocalConsumer { receivedValue = modifierLocal.current }
)
}
}
// Act.
rule.runOnIdle { includeComposable = false }
// Assert.
rule.runOnIdle { assertThat(receivedValue).isEqualTo(defaultValue) }
}
@Test
fun modifierLocalProviderValueChanged() {
// Arrange.
val localString = modifierLocalOf { defaultValue }
val value1 = "Value1"
val value2 = "Value2"
var useFirstValue by mutableStateOf(true)
lateinit var readString: String
rule.setContent {
Box(
Modifier.modifierLocalProvider(localString) {
if (useFirstValue) value1 else value2
}
.modifierLocalConsumer { readString = localString.current }
)
}
// Act.
rule.runOnIdle { useFirstValue = false }
// Assert.
rule.runOnIdle { assertThat(readString).isEqualTo(value2) }
}
@Test
fun modifierLocalProviderAdded() {
// Arrange.
val localString = modifierLocalOf { defaultValue }
val providedByParent1 = "Parent1"
var secondParentAdded by mutableStateOf(false)
val providedByParent2 = "Parent2"
lateinit var readString: String
rule.setContent {
Box(
Modifier.modifierLocalProvider(localString) { providedByParent1 }
.then(
if (secondParentAdded) {
Modifier.modifierLocalProvider(localString) { providedByParent2 }
} else {
Modifier
}
)
.modifierLocalConsumer { readString = localString.current }
)
}
// Act.
rule.runOnIdle { secondParentAdded = true }
// Assert.
rule.runOnIdle { assertThat(readString).isEqualTo(providedByParent2) }
}
@Test
fun modifierLocalProviderRemoved_readsDefaultValue() {
// Arrange.
val localString = modifierLocalOf { defaultValue }
val providedValue = "Parent"
var providerRemoved by mutableStateOf(false)
lateinit var readString: String
rule.setContent {
Box(
Modifier.then(
if (providerRemoved) {
Modifier
} else {
Modifier.modifierLocalProvider(localString) { providedValue }
}
)
.modifierLocalConsumer { readString = localString.current }
)
}
// Act.
rule.runOnIdle { providerRemoved = true }
// Assert.
rule.runOnIdle { assertThat(readString).isEqualTo(defaultValue) }
}
@Test
fun modifierLocalProviderRemoved_readsPreviousParent() {
// Arrange.
val localString = modifierLocalOf { defaultValue }
val providedByParent1 = "Parent1"
var secondParentRemoved by mutableStateOf(false)
val providedByParent2 = "Parent2"
lateinit var readString: String
rule.setContent {
Box(
Modifier.modifierLocalProvider(localString) { providedByParent1 }
.then(
if (secondParentRemoved) {
Modifier
} else {
Modifier.modifierLocalProvider(localString) { providedByParent2 }
}
)
.modifierLocalConsumer { readString = localString.current }
)
}
// Act.
rule.runOnIdle { secondParentRemoved = true }
// Assert.
rule.runOnIdle { assertThat(readString).isEqualTo(providedByParent1) }
}
@Test
fun modifierLocalProviderMoved_readsDefaultValue() {
// Arrange.
val localString = modifierLocalOf { defaultValue }
var providerMoved by mutableStateOf(false)
val providedValue = "ProvidedValue"
val providerModifier = Modifier.modifierLocalProvider(localString) { providedValue }
lateinit var readString: String
rule.setContent {
Box(
Modifier.then(if (providerMoved) Modifier else providerModifier)
.modifierLocalConsumer { readString = localString.current }
.then(if (providerMoved) providerModifier else Modifier)
)
}
// Act.
rule.runOnIdle { providerMoved = true }
// Assert.
rule.runOnIdle { assertThat(readString).isEqualTo(defaultValue) }
}
@Test
fun modifierLocalProviderMoved_readsPreviousParent() {
// Arrange.
val localString = modifierLocalOf { defaultValue }
val providedByParent1 = "Parent1"
var secondParentMoved by mutableStateOf(false)
val providedByParent2 = "Parent2"
val parent2Modifier = Modifier.modifierLocalProvider(localString) { providedByParent2 }
lateinit var readString: String
rule.setContent {
Box(
Modifier.modifierLocalProvider(localString) { providedByParent1 }
.then(if (secondParentMoved) Modifier else parent2Modifier)
.modifierLocalConsumer { readString = localString.current }
.then(if (secondParentMoved) parent2Modifier else Modifier)
)
}
// Act.
rule.runOnIdle { secondParentMoved = true }
// Assert.
rule.runOnIdle { assertThat(readString).isEqualTo(providedByParent1) }
}
@Test
fun modifierLocalProviderMoved_readsSameValue() {
// Arrange.
val localString = modifierLocalOf { defaultValue }
var providerMoved by mutableStateOf(false)
val providedValue = "ProvidedValue"
val providerModifier = Modifier.modifierLocalProvider(localString) { providedValue }
lateinit var readString: String
rule.setContent {
Box(
Modifier.then(if (providerMoved) Modifier else providerModifier)
.size(100.dp)
.then(if (providerMoved) providerModifier else Modifier)
.modifierLocalConsumer { readString = localString.current }
)
}
// Act.
rule.runOnIdle { providerMoved = true }
// Assert.
rule.runOnIdle { assertThat(readString).isEqualTo(providedValue) }
}
/** We don't want the same modifier local invalidated multiple times for the same change. */
@Test
fun modifierLocalCallsOnce() {
var calls = 0
val localString = modifierLocalOf { defaultValue }
val provider1 = Modifier.modifierLocalProvider(localString) { "ProvidedValue" }
val provider2 = Modifier.modifierLocalProvider(localString) { "Another ProvidedValue" }
var providerChoice by mutableStateOf(provider1)
val consumer =
Modifier.modifierLocalConsumer {
localString.current // read the value
calls++
}
rule.setContent { Box(providerChoice.then(consumer)) }
rule.runOnIdle {
calls = 0
providerChoice = provider2
}
rule.runOnIdle { assertThat(calls).isEqualTo(1) }
}
}
| 6 | null | 946 | 59 | e18ad812b77fc8babb00aacfcea930607b0794b5 | 17,332 | androidx | Apache License 2.0 |
app/src/main/java/com/example/translate/LetterMeaningsListFragment.kt | Evilangel-kk | 846,406,768 | false | {"Kotlin": 46610} | package com.example.translate
import android.annotation.SuppressLint
import android.graphics.drawable.PictureDrawable
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.translate.Letter.meanings
import com.example.translate.databinding.FragmentLetterContentBinding
import com.example.translate.databinding.FragmentLetterMeaningsListBinding
import java.util.Calendar
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [LetterMeaningsListFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class LetterMeaningsListFragment : Fragment() {
private lateinit var binding: FragmentLetterMeaningsListBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
binding= FragmentLetterMeaningsListBinding.inflate(inflater,container,false)
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val layoutManager = LinearLayoutManager(activity)
binding.letterMeaningsListRecyclerView.layoutManager=layoutManager
// 配置适配器
val adapter = NewsAdapter(Letter.meanings)
binding.letterMeaningsListRecyclerView.adapter = adapter
}
@SuppressLint("NotifyDataSetChanged")
fun setMeanings(result:Int) {
if(result==1){
(binding.letterMeaningsListRecyclerView.adapter as? NewsAdapter)?.updateMeanings(1)
Log.d("Notify",Letter.meanings.toString())
}
}
inner class NewsAdapter(private var meaningsList: List<String>) :
RecyclerView.Adapter<NewsAdapter.ViewHolder>() {
private lateinit var binding: FragmentLetterContentBinding
@SuppressLint("NotifyDataSetChanged")
fun updateMeanings(result:Int) {
if(result==1){
requireActivity().runOnUiThread{
meaningsList=Letter.meanings
notifyDataSetChanged()
Log.d("notifyDataSetChanged",meaningsList.toString())
}
}
}
inner class ViewHolder(binding: FragmentLetterContentBinding) : RecyclerView.ViewHolder(binding.root) {
val meaning=binding.meaning
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
binding=FragmentLetterContentBinding.inflate(LayoutInflater.from(parent.context),parent,false)
val holder = ViewHolder(binding)
return holder
}
@SuppressLint("DiscouragedApi")
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val meaning = meaningsList[position]
holder.meaning.text=meaning
}
override fun getItemCount() = meaningsList.size
}
} | 0 | Kotlin | 0 | 0 | b423520bd449d58e2368a7f5c30976384d376c9a | 3,300 | WordTranslate | MIT License |
app/src/main/java/h/lillie/reborntube/fragments/Home.kt | LillieH1000 | 517,439,028 | false | null | package h.lillie.reborntube.fragments
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import android.widget.LinearLayout
import android.view.View
import android.view.ViewGroup
import android.view.LayoutInflater
import com.google.gson.Gson
import h.lillie.reborntube.classes.Extractor
import h.lillie.reborntube.R
import h.lillie.reborntube.views.VideoView
import h.lillie.reborntube.classes.VideoViewData
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
class Home(private val appCompatActivity: AppCompatActivity) : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view: View = inflater.inflate(R.layout.home, container, false)
val applicationContext = activity?.applicationContext
if (applicationContext != null) {
val homeScrollView: LinearLayout = view.findViewById(R.id.homeScrollLayout)
homeScrollView.removeAllViews()
val extractor = Extractor()
val browseRequest = extractor.browseRequest(applicationContext, "FEtrending", null)
val jsonObject = JSONObject(browseRequest)
val browseContents: JSONArray = jsonObject.getJSONObject("contents").getJSONObject("singleColumnBrowseResultsRenderer").getJSONArray("tabs").getJSONObject(0).getJSONObject("tabRenderer").getJSONObject("content").getJSONObject("sectionListRenderer").getJSONArray("contents")
val videoIDs: MutableList<String> = arrayListOf()
for (i in 0 until browseContents.length()) {
try {
val videoID: String = browseContents.getJSONObject(i).getJSONObject("itemSectionRenderer").getJSONArray("contents").getJSONObject(0).getJSONObject("videoWithContextRenderer").getJSONObject("navigationEndpoint").getJSONObject("watchEndpoint").optString("videoId").toString()
videoIDs.add(videoID)
} catch (e: IOException) {
Log.e("IOException", e.toString())
} catch (e: JSONException) {
Log.e("JSONException", e.toString())
}
}
var count: Int = 0
for (i in 0 until browseContents.length()) {
try {
val videoID: String = browseContents.getJSONObject(i).getJSONObject("itemSectionRenderer").getJSONArray("contents").getJSONObject(0).getJSONObject("videoWithContextRenderer").getJSONObject("navigationEndpoint").getJSONObject("watchEndpoint").optString("videoId").toString()
val videoTitle: String = browseContents.getJSONObject(i).getJSONObject("itemSectionRenderer").getJSONArray("contents").getJSONObject(0).getJSONObject("videoWithContextRenderer").getJSONObject("headline").getJSONArray("runs").getJSONObject(0).optString("text").toString()
val videoArtworkArray = browseContents.getJSONObject(i).getJSONObject("itemSectionRenderer").getJSONArray("contents").getJSONObject(0).getJSONObject("videoWithContextRenderer").getJSONObject("thumbnail").getJSONArray("thumbnails")
val videoArtworkUrl: String = videoArtworkArray.getJSONObject((videoArtworkArray.length() - 1)).optString("url").toString()
val videoAuthor: String = browseContents.getJSONObject(i).getJSONObject("itemSectionRenderer").getJSONArray("contents").getJSONObject(0).getJSONObject("videoWithContextRenderer").getJSONObject("shortBylineText").getJSONArray("runs").getJSONObject(0).optString("text").toString()
val videoTime: String = browseContents.getJSONObject(i).getJSONObject("itemSectionRenderer").getJSONArray("contents").getJSONObject(0).getJSONObject("videoWithContextRenderer").getJSONObject("lengthText").getJSONArray("runs").getJSONObject(0).optString("text").toString()
val videoViewCount = browseContents.getJSONObject(i).getJSONObject("itemSectionRenderer").getJSONArray("contents").getJSONObject(0).getJSONObject("videoWithContextRenderer").getJSONObject("shortViewCountText").getJSONArray("runs").getJSONObject(0).optString("text").toString()
val gson = Gson()
val videoViewInfo: String = gson.toJson(VideoViewData(
videoID,
videoIDs,
count,
false,
videoTitle,
videoArtworkUrl,
videoAuthor,
videoTime,
null,
videoViewCount
))
val videoView = VideoView()
activity?.windowManager?.currentWindowMetrics?.bounds?.let { videoView.addView(appCompatActivity, applicationContext, videoViewInfo, homeScrollView, it.width()) }
count += 1
} catch (e: IOException) {
Log.e("IOException", e.toString())
} catch (e: JSONException) {
Log.e("JSONException", e.toString())
}
}
}
return view
}
} | 3 | null | 1 | 9 | dfdd3c9dd36edac8a633ec719d730a067d136bb7 | 5,292 | RebornTube | MIT License |
app/src/main/java/org/stepik/android/view/injection/step/StepComponent.kt | StepicOrg | 42,045,161 | false | null | package org.stepik.android.view.injection.step
import dagger.BindsInstance
import dagger.Subcomponent
import org.stepic.droid.persistence.model.StepPersistentWrapper
import org.stepik.android.domain.lesson.model.LessonData
import org.stepik.android.view.injection.attempt.AttemptDataModule
import org.stepik.android.view.injection.discussion_thread.DiscussionThreadDataModule
import org.stepik.android.view.injection.step_content.StepContentModule
import org.stepik.android.view.injection.step_content_text.TextStepContentComponent
import org.stepik.android.view.injection.step_content_video.VideoStepContentComponent
import org.stepik.android.view.injection.step_source.StepSourceModule
import org.stepik.android.view.injection.step_quiz.StepQuizModule
import org.stepik.android.view.injection.step_quiz.StepQuizPresentationModule
import org.stepik.android.view.injection.step_source.StepSourceDataModule
import org.stepik.android.view.injection.submission.SubmissionDataModule
import org.stepik.android.view.step.ui.fragment.StepFragment
import org.stepik.android.view.step_source.ui.dialog.EditStepSourceDialogFragment
import org.stepik.android.view.step_quiz.ui.fragment.DefaultStepQuizFragment
import org.stepik.android.view.step_quiz_unsupported.ui.fragment.UnsupportedStepQuizFragment
@Subcomponent(modules = [
StepModule::class,
StepSourceModule::class,
StepContentModule::class,
StepQuizModule::class,
StepQuizPresentationModule::class,
AttemptDataModule::class,
DiscussionThreadDataModule::class,
SubmissionDataModule::class,
StepSourceDataModule::class
])
interface StepComponent {
@Subcomponent.Builder
interface Builder {
fun build(): StepComponent
@BindsInstance
fun lessonData(lessonData: LessonData): Builder
@BindsInstance
fun stepWrapper(stepPersistentWrapper: StepPersistentWrapper): Builder
}
fun videoStepContentComponentBuilder(): VideoStepContentComponent.Builder
fun textStepContentComponentBuilder(): TextStepContentComponent.Builder
fun inject(stepFragment: StepFragment)
fun inject(editStepContentDialogFragment: EditStepSourceDialogFragment)
fun inject(defaultStepQuizFragment: DefaultStepQuizFragment)
fun inject(unsupportedStepQuizFragment: UnsupportedStepQuizFragment)
} | 13 | null | 54 | 189 | dd12cb96811a6fc2a7addcd969381570e335aca7 | 2,320 | stepik-android | Apache License 2.0 |
YRWidget/src/main/java/com/apemans/quickui/label/LabelTextSwitchBtnView.kt | xiongwen-lin | 480,680,777 | false | null | /*
* Copyright (c) 2021 独角鲸 Inc. All rights reserved.
*/
package com.apemans.quickui.label
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.core.content.ContextCompat
import com.apemans.quickui.databinding.LayoutLabelTextSwitchBtnBinding
/***********************************************************
* 作者: [email protected]
* 日期: 2021/9/22 10:56 上午
* 说明:
*
* 备注:文本标签控件-支持开关
*
***********************************************************/
class LabelTextSwitchBtnView(context : Context, attrs : AttributeSet) : BaseLabelTextView<LayoutLabelTextSwitchBtnBinding>(context, attrs) {
var mListener : ((Boolean) -> Unit)? = null
override fun refreshViewOnChange(configure: LabelTextConfigure?) {
super.refreshViewOnChange(configure)
configure?.let {
binding?.apply {
tvLabelTextTitle.text = it.text
tvLabelTextTitle.setTextColor(ContextCompat.getColor(context,it.textColor))
if (sbLabelText.isChecked != it.switchOn) {
sbLabelText.toggleNoCallback()
}
ivLabelTextDividerLine.visibility = it.dividerLineVisible
}
}
}
override fun init() {
super.init()
binding = LayoutLabelTextSwitchBtnBinding.inflate(LayoutInflater.from(context), this, true)
uiState.value?.apply {
switchOn = false
}
binding?.sbLabelText?.setOnCheckedChangeListener { view, isChecked ->
mListener?.invoke(isChecked)
}
}
} | 0 | Kotlin | 0 | 0 | 84704832a8a27e22fa5642ae092af50e2905b952 | 1,609 | SmartFastUi | Apache License 2.0 |
src/main/kotlin/com/maomengte/Application.kt | evendevil66 | 876,136,576 | false | null | package com.sslukess
import com.sslukess.plugins.*
import io.ktor.server.application.*
fun main(args: Array<String>) {
io.ktor.server.netty.EngineMain.main(args)
}
fun Application.module() {
configureSerialization()
configureRouting()
}
| 0 | null | 0 | 2 | b79626aaefcd8a41cdf4863ed2cb9178923f3f8d | 252 | mp-chatglm | Apache License 2.0 |
compiler/tests-spec/testData/diagnostics/notLinked/dfa/pos/6.kt | JetBrains | 3,432,266 | false | null | // !LANGUAGE: +NewInference
// !DIAGNOSTICS: -UNUSED_EXPRESSION
// SKIP_TXT
/*
* KOTLIN DIAGNOSTICS NOT LINKED SPEC TEST (POSITIVE)
*
* SECTIONS: dfa
* NUMBER: 6
* DESCRIPTION: Raw data flow analysis test
* HELPERS: classes, enumClasses, interfaces, objects, typealiases, properties, functions
*/
// FILE: other_types.kt
package othertypes
// TESTCASE NUMBER: 12, 48
class EmptyClass12_48 {}
// FILE: main.kt
import othertypes.*
// TESTCASE NUMBER: 1
fun case_1(x: Any?) {
val y = null
if (x != <!DEBUG_INFO_CONSTANT!>y<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any & kotlin.Any?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any & kotlin.Any?")!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any & kotlin.Any?")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any & kotlin.Any?")!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any & kotlin.Any?")!>x<!>.funNullableAny()
}
}
/*
* TESTCASE NUMBER: 2
* UNEXPECTED BEHAVIOUR
* ISSUES: KT-28159
*/
fun case_2(x: Nothing?) {
val y = null
if (<!DEBUG_INFO_CONSTANT!>x<!> !== <!DEBUG_INFO_CONSTANT!>y<!>) {
<!DEBUG_INFO_CONSTANT, DEBUG_INFO_EXPRESSION_TYPE("kotlin.Nothing?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Nothing?")!>x<!>.hashCode()
}
}
// TESTCASE NUMBER: 3
fun case_3() {
val y = null
if (Object.prop_1 == <!DEBUG_INFO_CONSTANT!>y<!>)
else {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number & kotlin.Number?")!>Object.prop_1<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number"), DEBUG_INFO_SMARTCAST!>Object.prop_1<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number"), DEBUG_INFO_SMARTCAST!>Object.prop_1<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number"), DEBUG_INFO_SMARTCAST!>Object.prop_1<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number & kotlin.Number?")!>Object.prop_1<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number & kotlin.Number?")!>Object.prop_1<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number"), DEBUG_INFO_SMARTCAST!>Object.prop_1<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number"), DEBUG_INFO_SMARTCAST!>Object.prop_1<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number & kotlin.Number?")!>Object.prop_1<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number & kotlin.Number?")!>Object.prop_1<!>.funNullableAny()
}
}
// TESTCASE NUMBER: 4
fun case_4(x: Char?, y: Nothing?) {
if (x != <!DEBUG_INFO_CONSTANT!>y<!> && true) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Char & kotlin.Char?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Char & kotlin.Char?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Char & kotlin.Char?"), DEBUG_INFO_SMARTCAST!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Char & kotlin.Char?"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Char & kotlin.Char?")!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Char & kotlin.Char?")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Char & kotlin.Char?"), DEBUG_INFO_SMARTCAST!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Char & kotlin.Char?"), DEBUG_INFO_SMARTCAST!>x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Char & kotlin.Char?")!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Char & kotlin.Char?")!>x<!>.funNullableAny()
}
}
// TESTCASE NUMBER: 5
fun case_5() {
val x: Unit? = null
val y: Nothing? = null
if (x !== <!DEBUG_INFO_CONSTANT!>y<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Unit & kotlin.Unit?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Unit & kotlin.Unit?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Unit & kotlin.Unit?"), DEBUG_INFO_SMARTCAST!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Unit & kotlin.Unit?"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Unit & kotlin.Unit?")!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Unit & kotlin.Unit?")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Unit & kotlin.Unit?"), DEBUG_INFO_SMARTCAST!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Unit & kotlin.Unit?"), DEBUG_INFO_SMARTCAST!>x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Unit & kotlin.Unit?")!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Unit & kotlin.Unit?")!>x<!>.funNullableAny()
}
}
// TESTCASE NUMBER: 6
fun case_6(x: EmptyClass?, z: Nothing?) {
val y = true
if (x != <!DEBUG_INFO_CONSTANT!>z<!> && !y) {
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyClass & EmptyClass?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyClass & EmptyClass?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyClass & EmptyClass?"), DEBUG_INFO_SMARTCAST!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyClass & EmptyClass?"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyClass & EmptyClass?")!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyClass & EmptyClass?")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyClass & EmptyClass?"), DEBUG_INFO_SMARTCAST!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyClass & EmptyClass?"), DEBUG_INFO_SMARTCAST!>x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyClass & EmptyClass?")!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyClass & EmptyClass?")!>x<!>.funNullableAny()
}
}
// TESTCASE NUMBER: 7
fun case_7(x: EmptyObject?) {
val y = null
if (x != <!DEBUG_INFO_CONSTANT!>y<!> || <!DEBUG_INFO_CONSTANT, DEBUG_INFO_EXPRESSION_TYPE("EmptyObject? & kotlin.Nothing?")!>x<!> != <!DEBUG_INFO_CONSTANT!>y<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyObject & EmptyObject?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyObject & EmptyObject?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyObject & EmptyObject?"), DEBUG_INFO_SMARTCAST!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyObject & EmptyObject?"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyObject & EmptyObject?")!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyObject & EmptyObject?")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyObject & EmptyObject?"), DEBUG_INFO_SMARTCAST!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyObject & EmptyObject?"), DEBUG_INFO_SMARTCAST!>x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyObject & EmptyObject?")!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyObject & EmptyObject?")!>x<!>.funNullableAny()
}
}
// TESTCASE NUMBER: 8
fun case_8(x: TypealiasNullableString) {
val y = null
if (x !== <!DEBUG_INFO_CONSTANT!>y<!> && <!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */")!>x<!> != <!DEBUG_INFO_CONSTANT!>y<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */"), DEBUG_INFO_SMARTCAST!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */")!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */"), DEBUG_INFO_SMARTCAST!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */"), DEBUG_INFO_SMARTCAST!>x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */")!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */")!>x<!>.funNullableAny()
}
}
// TESTCASE NUMBER: 9
fun case_9(x: TypealiasNullableString<!REDUNDANT_NULLABLE!>?<!>, y: Nothing?) {
if (x === <!DEBUG_INFO_CONSTANT!>y<!>) {
} else if (false) {
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString? /* = kotlin.String? */")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString? /* = kotlin.String? */"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString? /* = kotlin.String? */"), DEBUG_INFO_SMARTCAST!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString? /* = kotlin.String? */"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString? /* = kotlin.String? */")!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString? /* = kotlin.String? */")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString? /* = kotlin.String? */"), DEBUG_INFO_SMARTCAST!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString? /* = kotlin.String? */"), DEBUG_INFO_SMARTCAST!>x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString? /* = kotlin.String? */")!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString? /* = kotlin.String? */")!>x<!>.funNullableAny()
}
}
// TESTCASE NUMBER: 10
fun case_10() {
val a = Class()
val b = null
if (a.prop_4 === <!DEBUG_INFO_CONSTANT!>b<!> || true) {
if (a.prop_4 != null) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Float & kotlin.Float?")!>a.prop_4<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Float"), DEBUG_INFO_SMARTCAST!>a.prop_4<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Float"), DEBUG_INFO_SMARTCAST!>a.prop_4<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Float"), DEBUG_INFO_SMARTCAST!>a.prop_4<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Float & kotlin.Float?")!>a.prop_4<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Float & kotlin.Float?")!>a.prop_4<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Float"), DEBUG_INFO_SMARTCAST!>a.prop_4<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Float"), DEBUG_INFO_SMARTCAST!>a.prop_4<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Float & kotlin.Float?")!>a.prop_4<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Float & kotlin.Float?")!>a.prop_4<!>.funNullableAny()
}
}
}
// TESTCASE NUMBER: 11
fun case_11(x: TypealiasNullableString<!REDUNDANT_NULLABLE!>?<!>, y: TypealiasNullableString) {
val z = null
val u: TypealiasNullableString = null
val v = null
if (x == <!DEBUG_INFO_CONSTANT!>z<!> && <!DEBUG_INFO_CONSTANT!>x<!> == <!DEBUG_INFO_CONSTANT!>v<!>) {
} else {
if (y != <!DEBUG_INFO_CONSTANT!>z<!>) {
if (nullableStringProperty == <!DEBUG_INFO_CONSTANT!>z<!>) {
if (u != <!DEBUG_INFO_CONSTANT!>z<!> || <!DEBUG_INFO_CONSTANT!>u<!> != <!DEBUG_INFO_CONSTANT!>v<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString? /* = kotlin.String? */")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString? /* = kotlin.String? */"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString? /* = kotlin.String? */"), DEBUG_INFO_SMARTCAST!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString? /* = kotlin.String? */"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString? /* = kotlin.String? */")!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString? /* = kotlin.String? */")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString? /* = kotlin.String? */"), DEBUG_INFO_SMARTCAST!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString? /* = kotlin.String? */"), DEBUG_INFO_SMARTCAST!>x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString? /* = kotlin.String? */")!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString? /* = kotlin.String? */")!>x<!>.funNullableAny()
}
}
}
}
}
// TESTCASE NUMBER: 12
fun case_12(x: TypealiasNullableString, y: TypealiasNullableString, z1: Nothing?, z2: Nothing?) = if (x == <!DEBUG_INFO_CONSTANT!>z1<!> || x == <!DEBUG_INFO_CONSTANT!>z2<!>) "1"
else if (y === <!DEBUG_INFO_CONSTANT!>z1<!> && <!DEBUG_INFO_CONSTANT!>y<!> == <!DEBUG_INFO_CONSTANT!>z2<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */"), DEBUG_INFO_SMARTCAST!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */")!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */"), DEBUG_INFO_SMARTCAST!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */"), DEBUG_INFO_SMARTCAST!>x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */")!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */")!>x<!>.funNullableAny()
} else "-1"
// TESTCASE NUMBER: 13
fun case_13(x: EmptyClass12_48?, z: Nothing?) =
if (x == <!DEBUG_INFO_CONSTANT!>z<!> || x === <!DEBUG_INFO_CONSTANT!>z<!> && x == <!DEBUG_INFO_CONSTANT!>z<!>) {
throw Exception()
} else {
<!DEBUG_INFO_EXPRESSION_TYPE("othertypes.EmptyClass12_48 & othertypes.EmptyClass12_48?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("othertypes.EmptyClass12_48 & othertypes.EmptyClass12_48?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("othertypes.EmptyClass12_48 & othertypes.EmptyClass12_48?"), DEBUG_INFO_SMARTCAST!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("othertypes.EmptyClass12_48 & othertypes.EmptyClass12_48?"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("othertypes.EmptyClass12_48 & othertypes.EmptyClass12_48?")!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("othertypes.EmptyClass12_48 & othertypes.EmptyClass12_48?")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("othertypes.EmptyClass12_48 & othertypes.EmptyClass12_48?"), DEBUG_INFO_SMARTCAST!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("othertypes.EmptyClass12_48 & othertypes.EmptyClass12_48?"), DEBUG_INFO_SMARTCAST!>x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("othertypes.EmptyClass12_48 & othertypes.EmptyClass12_48?")!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("othertypes.EmptyClass12_48 & othertypes.EmptyClass12_48?")!>x<!>.funNullableAny()
}
// TESTCASE NUMBER: 14
class Case14 {
val x: TypealiasNullableString<!REDUNDANT_NULLABLE!>?<!>
init {
x = TypealiasNullableString()
}
}
fun case_14() {
val a = Case14()
val x = null
val y = <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!>
if (a.x != <!DEBUG_INFO_CONSTANT!>x<!> && a.x != <!DEBUG_INFO_CONSTANT!>y<!> || a.x != <!DEBUG_INFO_CONSTANT!>y<!> && <!SENSELESS_COMPARISON!>a.x !== null<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString? /* = kotlin.String? */")!>a.x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */"), DEBUG_INFO_SMARTCAST!>a.x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */"), DEBUG_INFO_SMARTCAST!>a.x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */"), DEBUG_INFO_SMARTCAST!>a.x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString? /* = kotlin.String? */")!>a.x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString? /* = kotlin.String? */")!>a.x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */"), DEBUG_INFO_SMARTCAST!>a.x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */"), DEBUG_INFO_SMARTCAST!>a.x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString? /* = kotlin.String? */")!>a.x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString? /* = kotlin.String? */")!>a.x<!>.funNullableAny()
}
}
// TESTCASE NUMBER: 15
fun case_15(x: TypealiasNullableString) {
val y = null
val <!UNUSED_VARIABLE!>z<!> = if (x === null || <!DEBUG_INFO_CONSTANT!>y<!> == x && x === <!DEBUG_INFO_CONSTANT!>y<!> || <!SENSELESS_COMPARISON!>null === x<!>) "" else {
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */"), DEBUG_INFO_SMARTCAST!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */")!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */"), DEBUG_INFO_SMARTCAST!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */"), DEBUG_INFO_SMARTCAST!>x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */")!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String */ & TypealiasNullableString /* = kotlin.String? */")!>x<!>.funNullableAny()
}
}
// TESTCASE NUMBER: 16
fun case_16() {
val x: TypealiasNullableNothing = null
val y: Nothing? = null
if (<!DEBUG_INFO_CONSTANT!>x<!> !== <!DEBUG_INFO_CONSTANT!>y<!>) {
<!DEBUG_INFO_CONSTANT, DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableNothing /* = kotlin.Nothing? */")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableNothing /* = kotlin.Nothing? */")!>x<!>.hashCode()
}
}
// TESTCASE NUMBER: 17
val case_17 = if (nullableIntProperty === <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!>) 0 else {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>nullableIntProperty<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>nullableIntProperty<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>nullableIntProperty<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>nullableIntProperty<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>nullableIntProperty<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>nullableIntProperty<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>nullableIntProperty<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>nullableIntProperty<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>nullableIntProperty<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>nullableIntProperty<!>.funNullableAny()
}
//TESTCASE NUMBER: 18
fun case_18(a: DeepObject.A.B.C.D.E.F.G.J?, b: Boolean) {
val x = null
val y = null
if (a != (if (b) <!DEBUG_INFO_CONSTANT!>x<!> else <!DEBUG_INFO_CONSTANT!>y<!>) || <!DEBUG_INFO_CONSTANT!>x<!> !== <!DEBUG_INFO_CONSTANT!>a<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?")!>a<!>
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?"), DEBUG_INFO_SMARTCAST!>a<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?"), DEBUG_INFO_SMARTCAST!>a<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?"), DEBUG_INFO_SMARTCAST!>a<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?")!>a<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?")!>a<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?"), DEBUG_INFO_SMARTCAST!>a<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?"), DEBUG_INFO_SMARTCAST!>a<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?")!>a<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?")!>a<!>.funNullableAny()
}
}
// TESTCASE NUMBER: 19
fun case_19(b: Boolean) {
val z = null
val a = if (b) {
object {
val B19 = if (b) {
object {
val C19 = if (b) {
object {
val D19 = if (b) {
object {
val x: Number? = 10
}
} else <!DEBUG_INFO_CONSTANT!>z<!>
}
} else <!DEBUG_INFO_CONSTANT!>z<!>
}
} else <!DEBUG_INFO_CONSTANT!>z<!>
}
} else <!DEBUG_INFO_CONSTANT!>z<!>
if (a != <!DEBUG_INFO_CONSTANT!>z<!> && <!DEBUG_INFO_SMARTCAST!>a<!>.B19 !== <!DEBUG_INFO_CONSTANT!>z<!> && <!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!>a<!>.B19<!>.C19 != <!DEBUG_INFO_CONSTANT!>z<!> && <!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!>a<!>.B19<!>.C19<!>.D19 != <!DEBUG_INFO_CONSTANT!>z<!> && <!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!>a<!>.B19<!>.C19<!>.D19<!>.x !== <!DEBUG_INFO_CONSTANT!>z<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number & kotlin.Number?")!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!>a<!>.B19<!>.C19<!>.D19<!>.x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number"), DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!>a<!>.B19<!>.C19<!>.D19<!>.x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number"), DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!>a<!>.B19<!>.C19<!>.D19<!>.x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number"), DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!>a<!>.B19<!>.C19<!>.D19<!>.x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number & kotlin.Number?")!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!>a<!>.B19<!>.C19<!>.D19<!>.x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number & kotlin.Number?")!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!>a<!>.B19<!>.C19<!>.D19<!>.x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number"), DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!>a<!>.B19<!>.C19<!>.D19<!>.x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number"), DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!>a<!>.B19<!>.C19<!>.D19<!>.x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number & kotlin.Number?")!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!>a<!>.B19<!>.C19<!>.D19<!>.x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number & kotlin.Number?")!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!>a<!>.B19<!>.C19<!>.D19<!>.x<!>.funNullableAny()
}
}
// TESTCASE NUMBER: 20
fun case_20(x: Boolean, y: Nothing?) {
val z = object {
val B19 = object {
val C19 = object {
val D19 = if (x) {
object {}
} else <!DEBUG_INFO_CONSTANT!>y<!>
}
}
}
if (z.B19.C19.D19 !== <!DEBUG_INFO_CONSTANT!>y<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("case_20.<no name provided>.B19.<no name provided>.C19.<no name provided>.D19.<no name provided> & case_20.<no name provided>.B19.<no name provided>.C19.<no name provided>.D19.<no name provided>?")!>z.B19.C19.D19<!>
<!DEBUG_INFO_EXPRESSION_TYPE("case_20.<no name provided>.B19.<no name provided>.C19.<no name provided>.D19.<no name provided>"), DEBUG_INFO_SMARTCAST!>z.B19.C19.D19<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("case_20.<no name provided>.B19.<no name provided>.C19.<no name provided>.D19.<no name provided>"), DEBUG_INFO_SMARTCAST!>z.B19.C19.D19<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("case_20.<no name provided>.B19.<no name provided>.C19.<no name provided>.D19.<no name provided>"), DEBUG_INFO_SMARTCAST!>z.B19.C19.D19<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("case_20.<no name provided>.B19.<no name provided>.C19.<no name provided>.D19.<no name provided> & case_20.<no name provided>.B19.<no name provided>.C19.<no name provided>.D19.<no name provided>?")!>z.B19.C19.D19<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("case_20.<no name provided>.B19.<no name provided>.C19.<no name provided>.D19.<no name provided> & case_20.<no name provided>.B19.<no name provided>.C19.<no name provided>.D19.<no name provided>?")!>z.B19.C19.D19<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("case_20.<no name provided>.B19.<no name provided>.C19.<no name provided>.D19.<no name provided>"), DEBUG_INFO_SMARTCAST!>z.B19.C19.D19<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("case_20.<no name provided>.B19.<no name provided>.C19.<no name provided>.D19.<no name provided>"), DEBUG_INFO_SMARTCAST!>z.B19.C19.D19<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("case_20.<no name provided>.B19.<no name provided>.C19.<no name provided>.D19.<no name provided> & case_20.<no name provided>.B19.<no name provided>.C19.<no name provided>.D19.<no name provided>?")!>z.B19.C19.D19<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("case_20.<no name provided>.B19.<no name provided>.C19.<no name provided>.D19.<no name provided> & case_20.<no name provided>.B19.<no name provided>.C19.<no name provided>.D19.<no name provided>?")!>z.B19.C19.D19<!>.funNullableAny()
}
}
// TESTCASE NUMBER: 21
fun case_21() {
if (EnumClassWithNullableProperty.A.prop_1 !== <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>EnumClassWithNullableProperty.A.prop_1<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int"), DEBUG_INFO_SMARTCAST!>EnumClassWithNullableProperty.A.prop_1<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int"), DEBUG_INFO_SMARTCAST!>EnumClassWithNullableProperty.A.prop_1<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int"), DEBUG_INFO_SMARTCAST!>EnumClassWithNullableProperty.A.prop_1<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>EnumClassWithNullableProperty.A.prop_1<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>EnumClassWithNullableProperty.A.prop_1<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int"), DEBUG_INFO_SMARTCAST!>EnumClassWithNullableProperty.A.prop_1<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int"), DEBUG_INFO_SMARTCAST!>EnumClassWithNullableProperty.A.prop_1<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>EnumClassWithNullableProperty.A.prop_1<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>EnumClassWithNullableProperty.A.prop_1<!>.funNullableAny()
}
}
// TESTCASE NUMBER: 22
fun case_22(a: (() -> Unit)?) {
if (a != <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Unit")!><!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)? & () -> kotlin.Unit"), DEBUG_INFO_SMARTCAST!>a<!>()<!>
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)? & () -> kotlin.Unit"), DEBUG_INFO_SMARTCAST!>a<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)? & () -> kotlin.Unit"), DEBUG_INFO_SMARTCAST!>a<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)? & () -> kotlin.Unit"), DEBUG_INFO_SMARTCAST!>a<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)? & () -> kotlin.Unit")!>a<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)? & () -> kotlin.Unit")!>a<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)? & () -> kotlin.Unit"), DEBUG_INFO_SMARTCAST!>a<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)? & () -> kotlin.Unit"), DEBUG_INFO_SMARTCAST!>a<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)? & () -> kotlin.Unit")!>a<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)? & () -> kotlin.Unit")!>a<!>.funNullableAny()
}
}
// TESTCASE NUMBER: 23
fun case_23(a: ((Float) -> Int?)?, b: Float?, z: Nothing?) {
if (a != <!DEBUG_INFO_CONSTANT!>z<!> && b !== <!DEBUG_INFO_CONSTANT!>z<!> && b !== <!DEBUG_INFO_CONSTANT!>z<!>) {
val x = <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int?")!><!DEBUG_INFO_EXPRESSION_TYPE("((kotlin.Float) -> kotlin.Int?)? & (kotlin.Float) -> kotlin.Int?"), DEBUG_INFO_SMARTCAST!>a<!>(<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Float & kotlin.Float?"), DEBUG_INFO_SMARTCAST!>b<!>)<!>
if (x != <!DEBUG_INFO_CONSTANT!>z<!> || <!DEBUG_INFO_CONSTANT!>x<!> !== <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!>.funNullableAny()
}
}
}
// TESTCASE NUMBER: 24
fun case_24(a: ((() -> Unit) -> Unit)?, b: (() -> Unit)?, z: Nothing?) =
if (a !== <!DEBUG_INFO_CONSTANT!>z<!> && b !== <!DEBUG_INFO_CONSTANT!>z<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("((() -> kotlin.Unit) -> kotlin.Unit)? & (() -> kotlin.Unit) -> kotlin.Unit"), DEBUG_INFO_SMARTCAST!>a<!>(<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)? & () -> kotlin.Unit"), DEBUG_INFO_SMARTCAST!>b<!>)
<!DEBUG_INFO_EXPRESSION_TYPE("((() -> kotlin.Unit) -> kotlin.Unit)? & (() -> kotlin.Unit) -> kotlin.Unit"), DEBUG_INFO_SMARTCAST!>a<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("((() -> kotlin.Unit) -> kotlin.Unit)? & (() -> kotlin.Unit) -> kotlin.Unit"), DEBUG_INFO_SMARTCAST!>a<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("((() -> kotlin.Unit) -> kotlin.Unit)? & (() -> kotlin.Unit) -> kotlin.Unit"), DEBUG_INFO_SMARTCAST!>a<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("((() -> kotlin.Unit) -> kotlin.Unit)? & (() -> kotlin.Unit) -> kotlin.Unit")!>a<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("((() -> kotlin.Unit) -> kotlin.Unit)? & (() -> kotlin.Unit) -> kotlin.Unit")!>a<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("((() -> kotlin.Unit) -> kotlin.Unit)? & (() -> kotlin.Unit) -> kotlin.Unit"), DEBUG_INFO_SMARTCAST!>a<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("((() -> kotlin.Unit) -> kotlin.Unit)? & (() -> kotlin.Unit) -> kotlin.Unit"), DEBUG_INFO_SMARTCAST!>a<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("((() -> kotlin.Unit) -> kotlin.Unit)? & (() -> kotlin.Unit) -> kotlin.Unit")!>a<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("((() -> kotlin.Unit) -> kotlin.Unit)? & (() -> kotlin.Unit) -> kotlin.Unit")!>a<!>.funNullableAny()
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)? & () -> kotlin.Unit"), DEBUG_INFO_SMARTCAST!>b<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)? & () -> kotlin.Unit"), DEBUG_INFO_SMARTCAST!>b<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)? & () -> kotlin.Unit"), DEBUG_INFO_SMARTCAST!>b<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)? & () -> kotlin.Unit")!>b<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)? & () -> kotlin.Unit")!>b<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)? & () -> kotlin.Unit"), DEBUG_INFO_SMARTCAST!>b<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)? & () -> kotlin.Unit"), DEBUG_INFO_SMARTCAST!>b<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)? & () -> kotlin.Unit")!>b<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)? & () -> kotlin.Unit")!>b<!>.funNullableAny()
} else <!DEBUG_INFO_CONSTANT!>z<!>
// TESTCASE NUMBER: 25
fun case_25(b: Boolean, z: Nothing?) {
val x = {
if (b) object {
val a = 10
} else <!DEBUG_INFO_CONSTANT!>z<!>
}
val y = if (b) x else <!DEBUG_INFO_CONSTANT!>z<!>
if (y !== <!DEBUG_INFO_CONSTANT!>z<!> || <!DEBUG_INFO_CONSTANT!>y<!> != <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!>) {
val z1 = <!DEBUG_INFO_EXPRESSION_TYPE("case_25.<anonymous>.<no name provided>?")!><!DEBUG_INFO_EXPRESSION_TYPE("(() -> case_25.<anonymous>.<no name provided>?)? & () -> case_25.<anonymous>.<no name provided>?"), DEBUG_INFO_SMARTCAST!>y<!>()<!>
if (z1 != <!DEBUG_INFO_CONSTANT!>z<!> && <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!> !== z1) {
<!DEBUG_INFO_EXPRESSION_TYPE("case_25.<anonymous>.<no name provided> & case_25.<anonymous>.<no name provided>?"), DEBUG_INFO_SMARTCAST!>z1<!>.a
<!DEBUG_INFO_EXPRESSION_TYPE("case_25.<anonymous>.<no name provided> & case_25.<anonymous>.<no name provided>?"), DEBUG_INFO_SMARTCAST!>z1<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("case_25.<anonymous>.<no name provided> & case_25.<anonymous>.<no name provided>?"), DEBUG_INFO_SMARTCAST!>z1<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("case_25.<anonymous>.<no name provided> & case_25.<anonymous>.<no name provided>?"), DEBUG_INFO_SMARTCAST!>z1<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("case_25.<anonymous>.<no name provided> & case_25.<anonymous>.<no name provided>?")!>z1<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("case_25.<anonymous>.<no name provided> & case_25.<anonymous>.<no name provided>?")!>z1<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("case_25.<anonymous>.<no name provided> & case_25.<anonymous>.<no name provided>?"), DEBUG_INFO_SMARTCAST!>z1<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("case_25.<anonymous>.<no name provided> & case_25.<anonymous>.<no name provided>?"), DEBUG_INFO_SMARTCAST!>z1<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("case_25.<anonymous>.<no name provided> & case_25.<anonymous>.<no name provided>?")!>z1<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("case_25.<anonymous>.<no name provided> & case_25.<anonymous>.<no name provided>?")!>z1<!>.funNullableAny()
}
}
}
// TESTCASE NUMBER: 26
fun case_26(a: ((Float) -> Int?)?, b: Float?) {
var z = null
if (a != <!DEBUG_INFO_CONSTANT!>z<!> == true && b != <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!> == true) {
val x = <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int?")!><!DEBUG_INFO_EXPRESSION_TYPE("((kotlin.Float) -> kotlin.Int?)? & (kotlin.Float) -> kotlin.Int?"), DEBUG_INFO_SMARTCAST!>a<!>(<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Float & kotlin.Float?"), DEBUG_INFO_SMARTCAST!>b<!>)<!>
if (x != <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!> == true || <!DEBUG_INFO_CONSTANT!>z<!> !== <!DEBUG_INFO_CONSTANT!>x<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!>.funNullableAny()
}
}
}
// TESTCASE NUMBER: 27
fun case_27(z: Nothing?) {
if (Object.prop_1 == <!DEBUG_INFO_CONSTANT!>z<!> == true == true == true == true == true == true == true == true == true == true == true == true == true == true)
else {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number & kotlin.Number?")!>Object.prop_1<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number"), DEBUG_INFO_SMARTCAST!>Object.prop_1<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number"), DEBUG_INFO_SMARTCAST!>Object.prop_1<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number"), DEBUG_INFO_SMARTCAST!>Object.prop_1<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number & kotlin.Number?")!>Object.prop_1<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number & kotlin.Number?")!>Object.prop_1<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number"), DEBUG_INFO_SMARTCAST!>Object.prop_1<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number"), DEBUG_INFO_SMARTCAST!>Object.prop_1<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number & kotlin.Number?")!>Object.prop_1<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number & kotlin.Number?")!>Object.prop_1<!>.funNullableAny()
}
}
// TESTCASE NUMBER: 28
fun case_28(a: DeepObject.A.B.C.D.E.F.G.J?) =
if (a != <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!> == true == false == false == false == true == false == true == false == false == true == true) {
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?"), DEBUG_INFO_SMARTCAST!>a<!>.x
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?"), DEBUG_INFO_SMARTCAST!>a<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?"), DEBUG_INFO_SMARTCAST!>a<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?"), DEBUG_INFO_SMARTCAST!>a<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?")!>a<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?")!>a<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?"), DEBUG_INFO_SMARTCAST!>a<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?"), DEBUG_INFO_SMARTCAST!>a<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?")!>a<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?")!>a<!>.funNullableAny()
} else -1
/*
* TESTCASE NUMBER: 29
* UNEXPECTED BEHAVIOUR
* ISSUES: KT-28328, KT-28329
*/
fun case_29(x: Boolean) {
val v = null
val z = {
if (x) object {
val a = 10
} else null
}
val y = if (x) z else null
if (false || false || false || false || y !== <!DEBUG_INFO_CONSTANT!>v<!>) {
val t = <!DEBUG_INFO_EXPRESSION_TYPE("case_29.<anonymous>.<no name provided>?")!><!UNSAFE_CALL!>y<!>()<!>
if (<!EQUALITY_NOT_APPLICABLE!>z !== t<!> || false) {
<!DEBUG_INFO_EXPRESSION_TYPE("case_29.<anonymous>.<no name provided>?")!>t<!><!UNSAFE_CALL!>.<!>a
<!DEBUG_INFO_EXPRESSION_TYPE("case_29.<anonymous>.<no name provided>?")!>t<!><!UNSAFE_CALL!>.<!>equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("case_29.<anonymous>.<no name provided>?")!>t<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("case_29.<anonymous>.<no name provided>?")!>t<!><!UNSAFE_CALL!>.<!>propAny
<!DEBUG_INFO_EXPRESSION_TYPE("case_29.<anonymous>.<no name provided>?")!>t<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("case_29.<anonymous>.<no name provided>?")!>t<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("case_29.<anonymous>.<no name provided>?")!>t<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("case_29.<anonymous>.<no name provided>?")!>t<!><!UNSAFE_CALL!>.<!>funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("case_29.<anonymous>.<no name provided>?")!>t<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("case_29.<anonymous>.<no name provided>?")!>t<!>.funNullableAny()
}
}
}
// TESTCASE NUMBER: 30
fun case_30(a: ((Float) -> Int?)?, b: Float?) {
if (<!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!> != a == true && b != <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!> == true || false || false || false || false || false || false || false || false || false) {
val x = <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int?")!><!DEBUG_INFO_EXPRESSION_TYPE("((kotlin.Float) -> kotlin.Int?)? & (kotlin.Float) -> kotlin.Int?"), DEBUG_INFO_SMARTCAST!>a<!>(<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Float & kotlin.Float?"), DEBUG_INFO_SMARTCAST!>b<!>)<!>
if (false || <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!> != x == true) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!>.funNullableAny()
}
}
}
// TESTCASE NUMBER: 31
fun case_31(z1: Boolean?, z: Nothing?) {
if (false || EnumClassWithNullableProperty.A.prop_1 != <!DEBUG_INFO_CONSTANT!>z<!> && z1 !== <!DEBUG_INFO_CONSTANT!>z<!> && <!DEBUG_INFO_SMARTCAST!>z1<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>EnumClassWithNullableProperty.A.prop_1<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int"), DEBUG_INFO_SMARTCAST!>EnumClassWithNullableProperty.A.prop_1<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int"), DEBUG_INFO_SMARTCAST!>EnumClassWithNullableProperty.A.prop_1<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int"), DEBUG_INFO_SMARTCAST!>EnumClassWithNullableProperty.A.prop_1<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>EnumClassWithNullableProperty.A.prop_1<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>EnumClassWithNullableProperty.A.prop_1<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int"), DEBUG_INFO_SMARTCAST!>EnumClassWithNullableProperty.A.prop_1<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int"), DEBUG_INFO_SMARTCAST!>EnumClassWithNullableProperty.A.prop_1<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>EnumClassWithNullableProperty.A.prop_1<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>EnumClassWithNullableProperty.A.prop_1<!>.funNullableAny()
}
}
// TESTCASE NUMBER: 32
fun case_32(a: DeepObject.A.B.C.D.E.F.G.J?) =
if (a == <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!> == true == false == false == false == true == false == true == false == false == true == true && true) {
-1
} else {
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?"), DEBUG_INFO_SMARTCAST!>a<!>.x
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?"), DEBUG_INFO_SMARTCAST!>a<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?"), DEBUG_INFO_SMARTCAST!>a<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?"), DEBUG_INFO_SMARTCAST!>a<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?")!>a<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?")!>a<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?"), DEBUG_INFO_SMARTCAST!>a<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?"), DEBUG_INFO_SMARTCAST!>a<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?")!>a<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J & DeepObject.A.B.C.D.E.F.G.J?")!>a<!>.funNullableAny()
}
// TESTCASE NUMBER: 33
fun case_33(a: ((Float) -> Int?)?, b: Float?, c: Boolean?) {
var z = null
if (true && a == <!DEBUG_INFO_CONSTANT!>z<!> == true || b == null == true) {
} else {
val x = <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int?")!><!DEBUG_INFO_EXPRESSION_TYPE("((kotlin.Float) -> kotlin.Int?)? & (kotlin.Float) -> kotlin.Int?"), DEBUG_INFO_SMARTCAST!>a<!>(<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Float & kotlin.Float?"), DEBUG_INFO_SMARTCAST!>b<!>)<!>
if (x == <!DEBUG_INFO_CONSTANT!>z<!> == true && <!DEBUG_INFO_CONSTANT!>x<!> === <!DEBUG_INFO_CONSTANT!>z<!> || (c != <!DEBUG_INFO_CONSTANT!>z<!> && !<!DEBUG_INFO_SMARTCAST!>c<!>)) {
} else {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!>.funNullableAny()
}
}
}
/*
* TESTCASE NUMBER: 34
* UNEXPECTED BEHAVIOUR
* ISSUES: KT-28329
*/
fun case_34(z1: Boolean?) {
var z = null
if (true && true && true && true && EnumClassWithNullableProperty.A.prop_1 != <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!> && <!SENSELESS_COMPARISON!>EnumClassWithNullableProperty.A.prop_1 !== null<!> && EnumClassWithNullableProperty.A.prop_1 !== <!DEBUG_INFO_CONSTANT!>z<!> || z1 != <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!> || <!ALWAYS_NULL!>z1<!>!! && true && true) {
} else {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int?")!>EnumClassWithNullableProperty.A.prop_1<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int?")!>EnumClassWithNullableProperty.A.prop_1<!><!UNSAFE_CALL!>.<!>equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int?")!>EnumClassWithNullableProperty.A.prop_1<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int?")!>EnumClassWithNullableProperty.A.prop_1<!><!UNSAFE_CALL!>.<!>propAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int?")!>EnumClassWithNullableProperty.A.prop_1<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int?")!>EnumClassWithNullableProperty.A.prop_1<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int?")!>EnumClassWithNullableProperty.A.prop_1<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int?")!>EnumClassWithNullableProperty.A.prop_1<!><!UNSAFE_CALL!>.<!>funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int?")!>EnumClassWithNullableProperty.A.prop_1<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int?")!>EnumClassWithNullableProperty.A.prop_1<!>.funNullableAny()
}
}
// TESTCASE NUMBER: 35
fun case_35(a: DeepObject.A.B.C.D.E.F.G.J?) {
val itest = false
if (true && a != <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!> && a !== <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!> || itest || !itest || true || !true) {
} else {
<!DEBUG_INFO_CONSTANT, DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J? & kotlin.Nothing?")!>a<!>
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J? & kotlin.Nothing?")!>a<!>.hashCode()
}
}
// TESTCASE NUMBER: 36
fun case_36(x: Any) {
var z = null
if (x == <!DEBUG_INFO_CONSTANT!>z<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any & kotlin.Nothing")!>x<!>
}
}
// TESTCASE NUMBER: 37
fun case_37(x: Nothing?, y: Nothing?) {
if (<!DEBUG_INFO_CONSTANT!>x<!> == <!DEBUG_INFO_CONSTANT!>y<!>) {
<!DEBUG_INFO_CONSTANT, DEBUG_INFO_EXPRESSION_TYPE("kotlin.Nothing?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Nothing?")!>x<!>.hashCode()
}
}
// TESTCASE NUMBER: 38
fun case_38() {
val z = null
if (Object.prop_2 != <!DEBUG_INFO_CONSTANT!>z<!>)
else {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Nothing & kotlin.Number")!>Object.prop_2<!>
}
}
// TESTCASE NUMBER: 39
fun case_39(x: Char?) {
if (x == <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!> && true) {
<!DEBUG_INFO_CONSTANT, DEBUG_INFO_EXPRESSION_TYPE("kotlin.Char? & kotlin.Nothing?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Char? & kotlin.Nothing?")!>x<!>.hashCode()
}
}
// TESTCASE NUMBER: 40
fun case_40() {
val x: Unit? = null
var z = null
if (x == <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!> || <!DEBUG_INFO_CONSTANT!>z<!> === x) {
<!DEBUG_INFO_CONSTANT, DEBUG_INFO_EXPRESSION_TYPE("kotlin.Nothing? & kotlin.Unit?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Nothing? & kotlin.Unit?")!>x<!>.hashCode()
}
}
// TESTCASE NUMBER: 41
fun case_41(x: EmptyClass?, z: Nothing?) {
val y = true
if (x === <!DEBUG_INFO_CONSTANT!>z<!> && !y) {
<!DEBUG_INFO_CONSTANT, DEBUG_INFO_EXPRESSION_TYPE("EmptyClass? & kotlin.Nothing?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyClass? & kotlin.Nothing?")!>x<!>.hashCode()
}
}
// TESTCASE NUMBER: 42
fun case_42() {
if (EmptyObject == <!DEBUG_INFO_CONSTANT!>nullableNothingProperty<!> || <!DEBUG_INFO_EXPRESSION_TYPE("EmptyObject")!>EmptyObject<!> === <!DEBUG_INFO_CONSTANT!>nullableNothingProperty<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyObject & kotlin.Nothing")!>EmptyObject<!>
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyObject")!>EmptyObject<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyObject")!>EmptyObject<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyObject")!>EmptyObject<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyObject")!>EmptyObject<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyObject")!>EmptyObject<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyObject")!>EmptyObject<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyObject")!>EmptyObject<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyObject")!>EmptyObject<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("EmptyObject")!>EmptyObject<!>.funNullableAny()
}
}
// TESTCASE NUMBER: 43
fun case_43(x: TypealiasNullableString) {
val z = null
if (x == <!DEBUG_INFO_CONSTANT!>z<!> && <!DEBUG_INFO_CONSTANT, DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String? */ & kotlin.Nothing?")!>x<!> == <!DEBUG_INFO_CONSTANT!>z<!>) {
<!DEBUG_INFO_CONSTANT, DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String? */ & kotlin.Nothing?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String? */ & kotlin.Nothing?")!>x<!>.hashCode()
}
}
/*
* TESTCASE NUMBER: 44
* UNEXPECTED BEHAVIOUR
* ISSUES: KT-28329
*/
fun case_44(x: TypealiasNullableString<!REDUNDANT_NULLABLE!>?<!>, z1: Nothing?) {
if (true && true && true && true && x !== <!DEBUG_INFO_CONSTANT!>z1<!>) {
} else if (false) {
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString? /* = kotlin.String? */")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString? /* = kotlin.String? */")!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString? /* = kotlin.String? */")!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString? /* = kotlin.String? */")!>x<!><!UNSAFE_CALL!>.<!>propAny
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString? /* = kotlin.String? */")!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString? /* = kotlin.String? */")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString? /* = kotlin.String? */")!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString? /* = kotlin.String? */")!>x<!><!UNSAFE_CALL!>.<!>funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString? /* = kotlin.String? */")!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString? /* = kotlin.String? */")!>x<!>.funNullableAny()
}
}
// TESTCASE NUMBER: 45
fun case_45() {
val a = Class()
var z: Nothing? = null
if (a.prop_4 != <!DEBUG_INFO_CONSTANT!>z<!> || true) {
if (a.prop_4 == null) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Float? & kotlin.Nothing?")!>a.prop_4<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Float? & kotlin.Nothing?")!>a.prop_4<!>.hashCode()
}
}
}
// TESTCASE NUMBER: 46
fun case_46(x: TypealiasNullableString<!REDUNDANT_NULLABLE!>?<!>, y: TypealiasNullableString) {
val t: TypealiasNullableString = null
var z: Nothing? = null
if (x != <!DEBUG_INFO_CONSTANT!>nullableNothingProperty<!>) {
} else {
if (y === <!DEBUG_INFO_CONSTANT!>nullableNothingProperty<!>) {
if (<!DEBUG_INFO_CONSTANT!>z<!> != nullableStringProperty) {
if (<!DEBUG_INFO_CONSTANT!>z<!> === t || t == <!DEBUG_INFO_CONSTANT!>nullableNothingProperty<!>) {
<!DEBUG_INFO_CONSTANT, DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString? /* = kotlin.String? */ & kotlin.Nothing?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString? /* = kotlin.String? */ & kotlin.Nothing?")!>x<!>.hashCode()
}
}
}
}
}
/*
* TESTCASE NUMBER: 47
* UNEXPECTED BEHAVIOUR
* ISSUES: KT-28328
*/
fun case_47(x: TypealiasNullableString, y: TypealiasNullableString, z: Nothing?) = if (x !== <!DEBUG_INFO_CONSTANT!>z<!> && true && true && true) "1"
else if (y != <!DEBUG_INFO_CONSTANT!>z<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String? */")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String? */")!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String? */")!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String? */")!>x<!><!UNSAFE_CALL!>.<!>propAny
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String? */")!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String? */")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String? */")!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String? */")!>x<!><!UNSAFE_CALL!>.<!>funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String? */")!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String? */")!>x<!>.funNullableAny()
} else "-1"
// TESTCASE NUMBER: 48
fun case_48(x: EmptyClass12_48?, z: Nothing?) =
if (x != <!DEBUG_INFO_CONSTANT!>z<!> && true) {
throw Exception()
} else {
<!DEBUG_INFO_CONSTANT, DEBUG_INFO_EXPRESSION_TYPE("kotlin.Nothing? & othertypes.EmptyClass12_48?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Nothing? & othertypes.EmptyClass12_48?")!>x<!>.hashCode()
}
// TESTCASE NUMBER: 49
class Case49 {
val x: TypealiasNullableString<!REDUNDANT_NULLABLE!>?<!>
init {
x = TypealiasNullableString()
}
}
fun case_49() {
val a = Case49()
var z = null
if (a.x === <!DEBUG_INFO_CONSTANT!>z<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString? /* = kotlin.String? */ & kotlin.Nothing?")!>a.x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString? /* = kotlin.String? */ & kotlin.Nothing?")!>a.x<!>.hashCode()
}
}
// TESTCASE NUMBER: 50
fun case_50(x: TypealiasNullableString) {
val z1 = null
val z2 = null
val <!UNUSED_VARIABLE!>t<!> = if (x != <!DEBUG_INFO_CONSTANT!>z1<!> && <!DEBUG_INFO_CONSTANT!>z2<!> !== x) "" else {
<!DEBUG_INFO_CONSTANT, DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String? */ & kotlin.Nothing?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableString /* = kotlin.String? */ & kotlin.Nothing?")!>x<!>.hashCode()
}
}
// TESTCASE NUMBER: 51
fun case_51() {
val x: TypealiasNullableNothing = null
val z: Nothing? = null
if (<!DEBUG_INFO_CONSTANT!>x<!> === <!DEBUG_INFO_CONSTANT!>z<!> || <!DEBUG_INFO_CONSTANT!>z<!> == <!DEBUG_INFO_CONSTANT!>x<!> && <!DEBUG_INFO_CONSTANT!>x<!> == <!DEBUG_INFO_CONSTANT!>z<!> || false || false || false) {
<!DEBUG_INFO_CONSTANT, DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableNothing /* = kotlin.Nothing? */")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("TypealiasNullableNothing /* = kotlin.Nothing? */")!>x<!>.hashCode()
}
}
// TESTCASE NUMBER: 52
val case_52 = if (nullableIntProperty !== <!DEBUG_INFO_CONSTANT!>nullableNothingProperty<!> && <!DEBUG_INFO_CONSTANT!>nullableNothingProperty<!> != nullableIntProperty) 0 else {
<!DEBUG_INFO_CONSTANT, DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int? & kotlin.Nothing?")!>nullableIntProperty<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int? & kotlin.Nothing?")!>nullableIntProperty<!>.hashCode()
}
//TESTCASE NUMBER: 53
fun case_53(a: DeepObject.A.B.C.D.E.F.G.J?) {
if (a == DeepObject.prop_2) {
<!DEBUG_INFO_CONSTANT, DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J? & kotlin.Nothing?")!>a<!>
<!DEBUG_INFO_EXPRESSION_TYPE("DeepObject.A.B.C.D.E.F.G.J? & kotlin.Nothing?")!>a<!>.hashCode()
}
}
// TESTCASE NUMBER: 54
fun case_54(b: Boolean) {
val a = if (b) {
object {
var z = null
val B54 = if (b) {
object {
val C54 = if (b) {
object {
val D54 = if (b) {
object {
val x: Number? = 10
}
} else null
}
} else null
}
} else null
}
} else null
val z = null
if (a != <!DEBUG_INFO_CONSTANT!>z<!> && <!DEBUG_INFO_SMARTCAST!>a<!>.B54 !== <!DEBUG_INFO_SMARTCAST!>a<!>.z && <!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!>a<!>.B54<!>.C54 != <!DEBUG_INFO_SMARTCAST!>a<!>.z && <!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!>a<!>.B54<!>.C54<!>.D54 != <!DEBUG_INFO_SMARTCAST!>a<!>.z && <!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!>a<!>.B54<!>.C54<!>.D54<!>.x === <!DEBUG_INFO_SMARTCAST!>a<!>.z) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Nothing? & kotlin.Number?")!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!>a<!>.B54<!>.C54<!>.D54<!>.x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Nothing? & kotlin.Number?")!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!><!DEBUG_INFO_SMARTCAST!>a<!>.B54<!>.C54<!>.D54<!>.x<!>.hashCode()
}
}
// TESTCASE NUMBER: 55
fun case_55(b: Boolean) {
val a = object {
val B19 = object {
val C19 = object {
var z = null
val D19 = if (b) {
object {}
} else null
}
}
}
if (a.B19.C19.D19 === a.B19.C19.z) {
<!DEBUG_INFO_EXPRESSION_TYPE("case_55.<no name provided>.B19.<no name provided>.C19.<no name provided>.D19.<no name provided>? & kotlin.Nothing?")!>a.B19.C19.D19<!>
}
}
// TESTCASE NUMBER: 56
fun case_56() {
if (EnumClassWithNullableProperty.A.prop_1 == <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int? & kotlin.Nothing?")!>EnumClassWithNullableProperty.A.prop_1<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int? & kotlin.Nothing?")!>EnumClassWithNullableProperty.A.prop_1<!>.hashCode()
}
}
// TESTCASE NUMBER: 57
fun case_57(a: (() -> Unit)) {
var z = null
if (a == <!DEBUG_INFO_CONSTANT!>z<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("() -> kotlin.Unit & kotlin.Nothing")!>a<!>
}
}
// TESTCASE NUMBER: 58
fun case_58(a: ((Float) -> Int?)?, b: Float?, z: Nothing?) {
if (a === <!DEBUG_INFO_CONSTANT!>z<!> && b == <!DEBUG_INFO_CONSTANT!>z<!> || <!DEBUG_INFO_CONSTANT!>z<!> == a && <!DEBUG_INFO_CONSTANT!>z<!> === b) {
<!DEBUG_INFO_CONSTANT, DEBUG_INFO_EXPRESSION_TYPE("((kotlin.Float) -> kotlin.Int?)? & kotlin.Nothing?")!>a<!>
<!DEBUG_INFO_CONSTANT, DEBUG_INFO_EXPRESSION_TYPE("kotlin.Float? & kotlin.Nothing?")!>b<!>
if (<!DEBUG_INFO_CONSTANT!>a<!> != <!DEBUG_INFO_CONSTANT!>z<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("((kotlin.Float) -> kotlin.Int?)? & (kotlin.Float) -> kotlin.Int? & kotlin.Nothing")!>a<!>
}
}
}
/*
* TESTCASE NUMBER: 59
* UNEXPECTED BEHAVIOUR
* ISSUES: KT-28329
*/
fun case_59(a: ((() -> Unit) -> Unit)?, b: (() -> Unit)?, z: Nothing?) {
if (false || false || a == <!DEBUG_INFO_CONSTANT!>z<!> && b === <!DEBUG_INFO_CONSTANT!>z<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("((() -> kotlin.Unit) -> kotlin.Unit)?")!>a<!>
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)?")!>b<!>
<!DEBUG_INFO_EXPRESSION_TYPE("((() -> kotlin.Unit) -> kotlin.Unit)?")!>a<!><!UNSAFE_CALL!>.<!>equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("((() -> kotlin.Unit) -> kotlin.Unit)?")!>a<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("((() -> kotlin.Unit) -> kotlin.Unit)?")!>a<!><!UNSAFE_CALL!>.<!>propAny
<!DEBUG_INFO_EXPRESSION_TYPE("((() -> kotlin.Unit) -> kotlin.Unit)?")!>a<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("((() -> kotlin.Unit) -> kotlin.Unit)?")!>a<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("((() -> kotlin.Unit) -> kotlin.Unit)?")!>a<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("((() -> kotlin.Unit) -> kotlin.Unit)?")!>a<!><!UNSAFE_CALL!>.<!>funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("((() -> kotlin.Unit) -> kotlin.Unit)?")!>a<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("((() -> kotlin.Unit) -> kotlin.Unit)?")!>a<!>.funNullableAny()
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)?")!>b<!><!UNSAFE_CALL!>.<!>equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)?")!>b<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)?")!>b<!><!UNSAFE_CALL!>.<!>propAny
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)?")!>b<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)?")!>b<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)?")!>b<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)?")!>b<!><!UNSAFE_CALL!>.<!>funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)?")!>b<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("(() -> kotlin.Unit)?")!>b<!>.funNullableAny()
}
}
// TESTCASE NUMBER: 60
fun case_60(b: Boolean) {
val x = {
if (b) object {
val a = 10
} else <!DEBUG_INFO_CONSTANT!>nullableNothingProperty<!>
}
val y = if (b) x else <!DEBUG_INFO_CONSTANT!>nullableNothingProperty<!>
if (y != <!DEBUG_INFO_CONSTANT!>nullableNothingProperty<!>) {
val z = <!DEBUG_INFO_EXPRESSION_TYPE("case_60.<anonymous>.<no name provided>?")!><!DEBUG_INFO_EXPRESSION_TYPE("(() -> case_60.<anonymous>.<no name provided>?)? & () -> case_60.<anonymous>.<no name provided>?"), DEBUG_INFO_SMARTCAST!>y<!>()<!>
if (z == <!DEBUG_INFO_CONSTANT!>nullableNothingProperty<!>) {
<!DEBUG_INFO_CONSTANT, DEBUG_INFO_EXPRESSION_TYPE("case_60.<anonymous>.<no name provided>? & kotlin.Nothing?")!>z<!>
}
}
}
// TESTCASE NUMBER: 61
fun case_61(x: Any?) {
if (x is Number?) {
if (x !== <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any & kotlin.Any? & kotlin.Number")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Number"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Number"), DEBUG_INFO_SMARTCAST!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Number"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Number"), DEBUG_INFO_SMARTCAST!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any & kotlin.Any? & kotlin.Number")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Number"), DEBUG_INFO_SMARTCAST!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Number"), DEBUG_INFO_SMARTCAST!>x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Number"), DEBUG_INFO_SMARTCAST!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any & kotlin.Any? & kotlin.Number")!>x<!>.funNullableAny()
}
}
}
// TESTCASE NUMBER: 62
fun case_62(x: Any?) {
var z = null
if (x is Number? && x is Int? && x != <!DEBUG_INFO_CONSTANT!>z<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any & kotlin.Any? & kotlin.Int & kotlin.Number")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Number"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Int"), DEBUG_INFO_SMARTCAST!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Number"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Int"), DEBUG_INFO_SMARTCAST!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any & kotlin.Any? & kotlin.Int & kotlin.Number")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Int"), DEBUG_INFO_SMARTCAST!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Number"), DEBUG_INFO_SMARTCAST!>x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Int"), DEBUG_INFO_SMARTCAST!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any & kotlin.Any? & kotlin.Int & kotlin.Number")!>x<!>.funNullableAny()
}
}
// TESTCASE NUMBER: 63
fun case_63(x: Any?, b: Boolean) {
val z1 = null
val z2 = null
val z3 = null
if (x is Number?) {
if (x !== when (b) { true -> <!DEBUG_INFO_CONSTANT!>z1<!>; false -> <!DEBUG_INFO_CONSTANT!>z2<!>; <!REDUNDANT_ELSE_IN_WHEN!>else<!> -> <!DEBUG_INFO_CONSTANT!>z3<!> }) {
if (x is Int?) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any & kotlin.Any? & kotlin.Int & kotlin.Number")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Number"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Int"), DEBUG_INFO_SMARTCAST!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Number"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Int"), DEBUG_INFO_SMARTCAST!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any & kotlin.Any? & kotlin.Int & kotlin.Number")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Int"), DEBUG_INFO_SMARTCAST!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Number"), DEBUG_INFO_SMARTCAST!>x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Int"), DEBUG_INFO_SMARTCAST!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any & kotlin.Any? & kotlin.Int & kotlin.Number")!>x<!>.funNullableAny()
}
}
}
}
// TESTCASE NUMBER: 64
fun case_64(x: Any?) {
if (x != try {<!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!>} finally {}) {
if (x is Number) {
if (x is Int?) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any & kotlin.Any? & kotlin.Int & kotlin.Number")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Number"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Int"), DEBUG_INFO_SMARTCAST!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Number"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Int"), DEBUG_INFO_SMARTCAST!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any & kotlin.Any? & kotlin.Int & kotlin.Number")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Int"), DEBUG_INFO_SMARTCAST!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Number"), DEBUG_INFO_SMARTCAST!>x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Int"), DEBUG_INFO_SMARTCAST!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any & kotlin.Any? & kotlin.Int & kotlin.Number")!>x<!>.funNullableAny()
}
}
}
}
// TESTCASE NUMBER: 65
fun case_65(x: Any?, z: Nothing?) {
if (x is ClassLevel1?) {
if (x is ClassLevel2?) {
if (x is ClassLevel3?) {
if (x is ClassLevel4?) {
if (x is ClassLevel5?) {
if (x != <!DEBUG_INFO_CONSTANT!>z<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & ClassLevel2 & ClassLevel3 & ClassLevel4 & ClassLevel5 & kotlin.Any & kotlin.Any?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel5 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel5 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & ClassLevel2 & ClassLevel3 & ClassLevel4 & ClassLevel5 & kotlin.Any & kotlin.Any?")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel5 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel5 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & ClassLevel2 & ClassLevel3 & ClassLevel4 & ClassLevel5 & kotlin.Any & kotlin.Any?")!>x<!>.funNullableAny()
}
}
}
}
}
}
}
// TESTCASE NUMBER: 66
fun case_66(x: Any?, z1: Nothing?, z2: Nothing?, b: Boolean) {
if (x is ClassLevel1?) {
if (x is ClassLevel2?) {
if (x is ClassLevel3?) {
if (x != if (b) { <!DEBUG_INFO_CONSTANT!>z1<!> } else { <!DEBUG_INFO_CONSTANT!>z2<!> } && x is ClassLevel4?) {
if (x is ClassLevel5?) {
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & ClassLevel2 & ClassLevel3 & ClassLevel4 & ClassLevel5 & kotlin.Any & kotlin.Any?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel5 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel5 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & ClassLevel2 & ClassLevel3 & ClassLevel4 & ClassLevel5 & kotlin.Any & kotlin.Any?")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel5 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel5 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & ClassLevel2 & ClassLevel3 & ClassLevel4 & ClassLevel5 & kotlin.Any & kotlin.Any?")!>x<!>.funNullableAny()
}
}
}
}
}
}
// TESTCASE NUMBER: 67
fun case_67(x: Any?) {
var z = null
if (x is ClassLevel1? && x is ClassLevel2? && x is ClassLevel3?) {
if (x is ClassLevel4? && x != (fun (): Nothing? { return <!DEBUG_INFO_CONSTANT!>z<!> })() && x is ClassLevel5?) {
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & ClassLevel2 & ClassLevel3 & ClassLevel4 & ClassLevel5 & kotlin.Any & kotlin.Any?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel5 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel5 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & ClassLevel2 & ClassLevel3 & ClassLevel4 & ClassLevel5 & kotlin.Any & kotlin.Any?")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel5 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel5 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & ClassLevel2 & ClassLevel3 & ClassLevel4 & ClassLevel5 & kotlin.Any & kotlin.Any?")!>x<!>.funNullableAny()
}
}
}
// TESTCASE NUMBER: 68
fun case_68(x: Any?, z: Nothing?) {
if (x is ClassLevel1? && x is ClassLevel2? && x is ClassLevel3?) {
if (x is ClassLevel4? && x != (fun (): Nothing? { return <!DEBUG_INFO_CONSTANT!>z<!> })() && x is ClassLevel5?) {
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & ClassLevel2 & ClassLevel3 & ClassLevel4 & ClassLevel5 & kotlin.Any & kotlin.Any?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel5 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel5 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & ClassLevel2 & ClassLevel3 & ClassLevel4 & ClassLevel5 & kotlin.Any & kotlin.Any?")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel5 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel5 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & ClassLevel2 & ClassLevel3 & ClassLevel4 & ClassLevel5 & kotlin.Any & kotlin.Any?")!>x<!>.funNullableAny()
}
}
}
// TESTCASE NUMBER: 69
fun case_69(x: Any?, z: Nothing?) {
if (x is ClassLevel1? && x is ClassLevel2? && x is ClassLevel3? && x is ClassLevel4? && x != try { <!DEBUG_INFO_CONSTANT!>z<!> } catch (e: Exception) { <!DEBUG_INFO_CONSTANT!>z<!> } && x is ClassLevel5?) {
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & ClassLevel2 & ClassLevel3 & ClassLevel4 & ClassLevel5 & kotlin.Any & kotlin.Any?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel5 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel5 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & ClassLevel2 & ClassLevel3 & ClassLevel4 & ClassLevel5 & kotlin.Any & kotlin.Any?")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel5 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel5 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & ClassLevel2 & ClassLevel3 & ClassLevel4 & ClassLevel5 & kotlin.Any & kotlin.Any?")!>x<!>.funNullableAny()
}
}
// TESTCASE NUMBER: 70
fun case_70(x: Any?) {
if (x is ClassLevel1? && x is ClassLevel2? && x is ClassLevel3?) {
if (x is ClassLevel4?) {
} else if (x is ClassLevel5? && x != <!DEBUG_INFO_CONSTANT!>nullableNothingProperty<!> || x != <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & ClassLevel2 & ClassLevel3 & kotlin.Any & kotlin.Any?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel3 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel3 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & ClassLevel2 & ClassLevel3 & kotlin.Any & kotlin.Any?")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel3 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel3 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & ClassLevel2 & ClassLevel3 & kotlin.Any & kotlin.Any?")!>x<!>.funNullableAny()
}
} else if (x is ClassLevel4? && x !== <!DEBUG_INFO_CONSTANT!>nullableNothingProperty<!> && x is ClassLevel5?) {
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel4 & ClassLevel5 & kotlin.Any & kotlin.Any?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel4 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel5 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel4 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel5 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel4 & ClassLevel5 & kotlin.Any & kotlin.Any?")!>x<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel5 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel4 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel5 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>x<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel4 & ClassLevel5 & kotlin.Any & kotlin.Any?")!>x<!>.funNullableAny()
}
}
/*
* TESTCASE NUMBER: 71
* NOTE: lazy smartcasts
* DISCUSSION
* ISSUES: KT-28362
*/
fun case_71(t: Any?) {
val z1 = null
var z2 = <!DEBUG_INFO_CONSTANT!>z1<!>
if (t is Interface1?) {
if (t is Interface2?) {
if (t != <!DEBUG_INFO_CONSTANT!>z2<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("Interface1 & Interface2 & kotlin.Any & kotlin.Any?")!>t<!>
<!DEBUG_INFO_EXPRESSION_TYPE("Interface1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>t<!>.itest1()
<!DEBUG_INFO_EXPRESSION_TYPE("Interface2 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>t<!>.itest2()
<!DEBUG_INFO_EXPRESSION_TYPE("Interface2 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>t<!>.itest()
<!DEBUG_INFO_EXPRESSION_TYPE("Interface1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>t<!>.let { <!DEBUG_INFO_EXPRESSION_TYPE("{Any & Interface1 & Interface2}")!>it<!>.itest1(); <!DEBUG_INFO_EXPRESSION_TYPE("{Any & Interface1 & Interface2}")!>it<!>.itest2() }
}
}
}
}
/*
* TESTCASE NUMBER: 72
* NOTE: lazy smartcasts
* DISCUSSION
* ISSUES: KT-28362, KT-27032
*/
fun case_72(t: Any?, z1: Nothing?) {
var z2 = null
if (t is Interface1? && t != <!DEBUG_INFO_CONSTANT!>z1<!> ?: <!DEBUG_INFO_CONSTANT!>z2<!> && t is Interface2?) {
<!DEBUG_INFO_EXPRESSION_TYPE("Interface1 & Interface2 & kotlin.Any & kotlin.Any?")!>t<!>
<!DEBUG_INFO_EXPRESSION_TYPE("Interface1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>t<!>.itest1()
<!DEBUG_INFO_EXPRESSION_TYPE("Interface2 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>t<!>.itest2()
<!DEBUG_INFO_EXPRESSION_TYPE("Interface2 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>t<!>.itest()
<!DEBUG_INFO_EXPRESSION_TYPE("Interface1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>t<!>.let { <!DEBUG_INFO_EXPRESSION_TYPE("{Any & Interface1 & Interface2}")!>it<!>.itest1(); <!DEBUG_INFO_EXPRESSION_TYPE("{Any & Interface1 & Interface2}")!>it<!>.itest2() }
}
}
/*
* TESTCASE NUMBER: 73
* NOTE: lazy smartcasts
* DISCUSSION
* ISSUES: KT-28362
*/
fun case_73(t: Any?) {
val `null` = null
if (t is Interface2?) {
if (t is ClassLevel1?) {
if (t is ClassLevel2? && t is Interface1?) {
if (t !is Interface3?) {} else if (false) {
if (t != <!DEBUG_INFO_CONSTANT!>`null`<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("Interface2 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>t<!>.itest2()
<!DEBUG_INFO_EXPRESSION_TYPE("Interface1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>t<!>.itest1()
<!DEBUG_INFO_EXPRESSION_TYPE("Interface3 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>t<!>.itest()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>t<!>.test1()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel2 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>t<!>.test2()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & ClassLevel2 & Interface1 & Interface2 & Interface3 & kotlin.Any & kotlin.Any?")!>t<!>
}
}
}
}
}
}
/*
* TESTCASE NUMBER: 74
* NOTE: lazy smartcasts
* DISCUSSION
* ISSUES: KT-28362
*/
fun case_74(t: Any?) {
if (t is Interface2?) {
if (t is ClassLevel1?) {
if (t == <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!> || t === <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!> || t !is Interface1?) else {
if (t is ClassLevel2?) {
if (t is Interface3?) {
<!DEBUG_INFO_EXPRESSION_TYPE("Interface2 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>t<!>.itest2()
<!DEBUG_INFO_EXPRESSION_TYPE("Interface1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>t<!>.itest1()
<!DEBUG_INFO_EXPRESSION_TYPE("Interface3 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>t<!>.itest()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>t<!>.test1()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel2 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>t<!>.test2()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & ClassLevel2 & Interface1 & Interface2 & Interface3 & kotlin.Any & kotlin.Any?")!>t<!>
}
}
}
}
}
}
/*
* TESTCASE NUMBER: 75
* NOTE: lazy smartcasts
* DISCUSSION
* ISSUES: KT-28362
*/
fun case_75(t: Any?, z: Nothing?) {
if (t !is ClassLevel2? || <!USELESS_IS_CHECK!>t !is ClassLevel1?<!>) else {
if (t === ((((((<!DEBUG_INFO_CONSTANT!>z<!>)))))) || t !is Interface1?) else {
if (t !is Interface2? || t !is Interface3?) {} else {
<!DEBUG_INFO_EXPRESSION_TYPE("Interface2 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>t<!>.itest2()
<!DEBUG_INFO_EXPRESSION_TYPE("Interface1 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>t<!>.itest1()
<!DEBUG_INFO_EXPRESSION_TYPE("Interface3 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>t<!>.itest()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel2 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>t<!>.test1()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel2 & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>t<!>.test2()
<!DEBUG_INFO_EXPRESSION_TYPE("ClassLevel1 & ClassLevel2 & Interface1 & Interface2 & Interface3 & kotlin.Any & kotlin.Any?"), DEBUG_INFO_SMARTCAST!>t<!>
}
}
}
}
// TESTCASE NUMBER: 76
fun case_76(a: Any?, b: Int = if (<!DEPRECATED_IDENTITY_EQUALS!>a !is Number? === true<!> || a !is Int? == true || a != null == false == true) 0 else <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any & kotlin.Any? & kotlin.Int"), DEBUG_INFO_SMARTCAST!>a<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any?")!>a<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int")!>b<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int")!>b<!>.equals(null)
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int")!>b<!>.propT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int")!>b<!>.propAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int")!>b<!>.propNullableT
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int")!>b<!>.propNullableAny
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int")!>b<!>.funT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int")!>b<!>.funAny()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int")!>b<!>.funNullableT()
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int")!>b<!>.funNullableAny()
}
| 184 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 93,474 | kotlin | Apache License 2.0 |
embrace-test-fakes/src/main/kotlin/io/embrace/android/embracesdk/fakes/FakeMetadataService.kt | embrace-io | 704,537,857 | false | {"Kotlin": 2807710, "C": 190147, "Java": 175321, "C++": 13140, "CMake": 4261} | package io.embrace.android.embracesdk.fakes
import android.content.Context
import io.embrace.android.embracesdk.internal.capture.metadata.MetadataService
import io.embrace.android.embracesdk.internal.payload.AppInfo
import io.embrace.android.embracesdk.internal.payload.DeviceInfo
import io.embrace.android.embracesdk.internal.payload.DiskUsage
/**
* Fake implementation of [MetadataService] that represents an Android device. A [UnsupportedOperationException] will be thrown
* if you attempt set info about Flutter/Unity/ReactNative on this fake, which is decided for an Android device.
*/
public class FakeMetadataService(sessionId: String? = null) : MetadataService {
private companion object {
private val androidAppInfo = AppInfo(
appVersion = "1.0.0",
buildId = "100",
buildType = "release",
buildFlavor = "oem",
environment = "prod",
bundleVersion = "5ac7fe",
sdkSimpleVersion = "53",
sdkVersion = "5.11.0",
buildGuid = "5092abc",
reactNativeBundleId = "fakeReactNativeBundleId",
reactNativeVersion = "fakeRnSdkVersion",
javaScriptPatchNumber = "js",
hostedPlatformVersion = "19",
hostedSdkVersion = "1.2.0"
)
private val androidDeviceInfo = DeviceInfo(
manufacturer = "Samsung",
model = "SM-G950U",
architecture = "arm64-v8a",
jailbroken = false,
internalStorageTotalCapacity = 10000000L,
operatingSystemType = "Android",
operatingSystemVersion = "8.0.0",
operatingSystemVersionCode = 26,
screenResolution = "1080x720",
cores = 8
)
private val diskUsage = DiskUsage(
appDiskUsage = 10000000L,
deviceDiskFree = 500000000L
)
private const val APP_STATE_FOREGROUND = "foreground"
private const val APP_STATE_BACKGROUND = "background"
}
public var fakeUnityVersion: String = "fakeUnityVersion"
public var fakeUnityBuildIdNumber: String = "fakeUnityBuildIdNumber"
public var fakeUnitySdkVersion: String = "fakeUnitySdkVersion"
public var appUpdated: Boolean = false
public var osUpdated: Boolean = false
public var fakeAppId: String = "o0o0o"
public var fakeDeviceId: String = "07D85B44E4E245F4A30E559BFC0D07FF"
public var fakeReactNativeBundleId: String? = "fakeReactNativeBundleId"
public var forceUpdate: Boolean? = null
public var fakeFlutterSdkVersion: String? = "fakeFlutterSdkVersion"
public var fakeDartVersion: String? = "fakeDartVersion"
public var fakeReactNativeVersion: String? = "fakeReactNativeVersion"
public var fakeJavaScriptPatchNumber: String? = "fakeJavaScriptPatchNumber"
public var fakeRnSdkVersion: String? = "fakeRnSdkVersion"
public val fakePackageName: String = "com.embrace.fake"
private lateinit var appState: String
private var appSessionId: String? = null
init {
setAppForeground()
appSessionId = sessionId
}
public fun setAppForeground() {
appState = APP_STATE_FOREGROUND
}
public fun setAppId(id: String) {
fakeAppId = id
}
public fun setAppBackground() {
appState = APP_STATE_BACKGROUND
}
override fun getAppInfo(): AppInfo = androidAppInfo
override fun getLightweightAppInfo(): AppInfo = androidAppInfo
override fun getDeviceInfo(): DeviceInfo = androidDeviceInfo
override fun getLightweightDeviceInfo(): DeviceInfo = androidDeviceInfo
override fun getDiskUsage(): DiskUsage = diskUsage
override fun setReactNativeBundleId(context: Context, jsBundleUrl: String?, forceUpdate: Boolean?) {
fakeReactNativeBundleId = jsBundleUrl
this.forceUpdate = forceUpdate
}
override fun getReactNativeBundleId(): String? {
return fakeReactNativeBundleId
}
override fun precomputeValues() {}
}
| 22 | Kotlin | 8 | 133 | e5b92a8e0ed1ea64602b68ec071780369e0ea915 | 4,023 | embrace-android-sdk | Apache License 2.0 |
app/src/main/java/github/alexzhirkevich/studentbsuby/di/TimetableModule.kt | geugenm | 689,629,461 | false | null | package github.alexzhirkevich.studentbsuby.di
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ViewModelComponent
import github.alexzhirkevich.studentbsuby.repo.TimetableRepository
import github.alexzhirkevich.studentbsuby.ui.screens.drawer.timetable.Timetable
import github.alexzhirkevich.studentbsuby.ui.screens.drawer.timetable.TimetableEvent
import github.alexzhirkevich.studentbsuby.ui.screens.drawer.timetable.TimetableEventHandler
import github.alexzhirkevich.studentbsuby.ui.screens.drawer.timetable.TimetableEventHandlerImpl
import github.alexzhirkevich.studentbsuby.util.Calendar
import github.alexzhirkevich.studentbsuby.util.ConnectivityManager
import github.alexzhirkevich.studentbsuby.util.DataState
import github.alexzhirkevich.studentbsuby.util.SuspendEventHandler
import github.alexzhirkevich.studentbsuby.util.communication.StateCommunication
import github.alexzhirkevich.studentbsuby.util.communication.StateFlowCommunication
import javax.inject.Qualifier
@Qualifier
annotation class IsTimetableUpdatingQualifier
@Module
@InstallIn(ViewModelComponent::class)
class TimetableModule {
private val isUpdatingCommunication = StateFlowCommunication(false)
private val timetableCommunication = StateFlowCommunication<DataState<Timetable>>(DataState.Empty)
@Provides
@IsTimetableUpdatingQualifier
fun provideIsUpdatingCommunication() : StateCommunication<Boolean> =
isUpdatingCommunication
@Provides
fun provideTimetableCommunication() : StateCommunication<DataState<Timetable>> =
timetableCommunication
@Provides
fun provideEventHandler(
calendar: Calendar,
timetableRepository: TimetableRepository,
connectivityManager: ConnectivityManager
) : TimetableEventHandler = TimetableEventHandlerImpl(
timetableRepository = timetableRepository,
calendar = calendar,
timetableMapper = timetableCommunication,
isUpdatingMapper = isUpdatingCommunication,
connectivityManager = connectivityManager
)
} | 3 | null | 0 | 6 | a89ff407beb83aa9a6fb5c21c319e6bf84e75e2a | 2,098 | student-bsu-by | MIT License |
app/src/main/java/pl/droidsonroids/droidsmap/feature/room/api/RoomImagesInteractor.kt | DroidsOnRoids | 92,831,794 | false | null | package pl.droidsonroids.droidsmap.feature.room.api
import android.net.Uri
import com.google.android.gms.tasks.OnCompleteListener
import io.reactivex.Single
import io.reactivex.Single.create
import pl.droidsonroids.droidsmap.base.BaseFirebaseStorageInteractor
class RoomImagesInteractor : BaseFirebaseStorageInteractor(), RoomImagesEndpoint {
override fun setStorageNode() {
storageQueryNode = firebaseStorage.reference
.child("rooms")
}
override fun getRoomImageUrl(imageId: String): Single<String> {
return create { emitter ->
setStorageNode()
val downloadingTask = storageQueryNode.child(imageId + ".svg").downloadUrl
val queryListener = OnCompleteListener<Uri> { task ->
if (task.isSuccessful) {
emitter.onSuccess(task.result.toString())
} else {
task.exception?.let(emitter::onError)
}
}
downloadingTask.addOnCompleteListener(queryListener)
}
}
} | 0 | Kotlin | 0 | 1 | 310db4cd84410691743a42834587d05f79144bf2 | 1,060 | DroidsMap | MIT License |
src/main/kotlin/net/savagelabs/skyblockx/listener/ShopListener.kt | ryderbelserion | 669,876,085 | false | null | package net.savagelabs.skyblockx.listener
import com.cryptomorin.xseries.XMaterial
import net.savagelabs.skyblockx.core.Island
import net.savagelabs.skyblockx.core.color
import net.savagelabs.skyblockx.core.getIPlayer
import net.savagelabs.skyblockx.core.getIslandFromLocation
import net.savagelabs.skyblockx.manager.ChestShopResponse
import net.savagelabs.skyblockx.manager.IslandShopManager
import net.savagelabs.skyblockx.manager.IslandShopManager.buildHologram
import net.savagelabs.skyblockx.manager.IslandShopManager.chestHasShop
import net.savagelabs.skyblockx.manager.IslandShopManager.encode
import net.savagelabs.skyblockx.manager.IslandShopManager.getSignDirectionalBlock
import net.savagelabs.skyblockx.persist.Config
import net.savagelabs.skyblockx.persist.Message
import net.savagelabs.skyblockx.registry.Identifier
import net.savagelabs.skyblockx.registry.impl.HologramRegistry
import org.bukkit.Material
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority
import org.bukkit.event.Listener
import org.bukkit.event.block.Action
import org.bukkit.event.block.BlockBreakEvent
import org.bukkit.event.block.SignChangeEvent
import org.bukkit.event.player.PlayerInteractEvent
/**
* This listener handles all shop related events.
*/
object ShopListener : Listener {
/**
* This event handles the base of creating a chest shop.
*/
@EventHandler(priority = EventPriority.HIGHEST)
private fun SignChangeEvent.onCreation() {
// make sure it's not cancelled...
if (isCancelled) {
return
}
// the sign's sign line has to either be [BUY] or [SELL]
val size = lines.size
val first = lines.elementAt(0)
if (!first.equals("[BUY]", true) && !first.equals("[SELL]", true)) {
return
}
// necessity
val islandPlayer = player.getIPlayer()
val chestBlock = block.getSignDirectionalBlock() ?: return
val message = Message.instance
// tell the player to specify a valid material
val material = XMaterial.matchXMaterial(lines.elementAt(1).ifEmpty { "JUST_FOR_ERROR_PURPOSE" })
if (size == 1 || !material.isPresent) {
islandPlayer.message(message.chestShopSpecifyMaterial)
return
}
// tell the player to specify a valid amount and make sure it's below limit
val amount = lines.elementAt(2).toIntOrNull()
if (size == 2 || amount == null || amount <= 0) {
islandPlayer.message(message.chestShopSpecifyAmount)
return
}
val maximumAmount = Config.instance.chestShopMaximumAmount
if (amount > maximumAmount) {
islandPlayer.message(message.chestShopAmountTooHigh, maximumAmount.toString())
return
}
// tell the player to specify a valid price
val price = lines.elementAt(3).toIntOrNull()
if (size == 3 || price == null || price < 0) {
islandPlayer.message(message.chestShopSpecifyPrice)
return
}
// make sure it's on their island
val location = block.location
val island = getIslandFromLocation(location)
if (!islandPlayer.hasIsland() || island == null || islandPlayer.getIsland() != island) {
islandPlayer.message(message.chestShopCreationAtOtherIsland)
return
}
// make sure shop doesn't exist at this location
if (chestBlock.chestHasShop(island)) {
islandPlayer.message(message.chestShopAlreadyExist)
return
}
// format sign, set up shop and then register hologram
val type = if (first == "[BUY]") "BUY" else "SELL"
val exactMaterial = material.get()
val materialName = exactMaterial.name
for ((index, line) in Config.instance.chestShopSignFormat.withIndex()) {
setLine(index, color(
line
.replace("{player}", player.name)
.replace("{material}", materialName)
.replace("{price}", price.toString())
.replace("{amount}", amount.toString())
.replace("{type}", type)
))
}
with (Island.ChestShop(
location.world?.environment ?: return, location, chestBlock.location,
islandPlayer.uuid, type, exactMaterial, amount.toShort(), price
)) {
island.chestShops[encode(location)] = this
this.handleHologram()
}
// send the successful creation message
islandPlayer.message(
message.chestShopCreationSuccess
.joinToString("\n")
.format(materialName, amount, price, type.toLowerCase().capitalize()),
true
)
}
/**
* This event handles all shop interaction.
*/
@EventHandler(priority = EventPriority.HIGHEST)
private fun PlayerInteractEvent.onShop() {
// make sure it's not cancelled and the clicked block is not null
if (isCancelled || clickedBlock == null || action != Action.RIGHT_CLICK_BLOCK) {
return
}
// necessity
val relativeBlock = clickedBlock?.getSignDirectionalBlock() ?: return
val location = relativeBlock.location
val island = getIslandFromLocation(location) ?: return
val shop = island.chestShops[encode(clickedBlock?.location ?: return)] ?: return
val isBuy = shop.type == "BUY"
// make sure the player that is clicking is not the owner
val islandPlayer = player.getIPlayer()
if (shop.owner == player.uniqueId) {
islandPlayer.message(Message.instance.chestShopInteractingIsOwner)
return
}
// handle purchase / retail
val message = Message.instance
val price = shop.price.toString()
val amount = shop.amount.toString()
val material = shop.material.toString()
val playerName = player.name
val owner = shop.islandPlayerOfOwner
val ownerName = owner?.name ?: "Unknown"
if (isBuy) {
when (IslandShopManager.purchase(islandPlayer, shop)) {
ChestShopResponse.SHOP_NOT_IN_STOCK ->
islandPlayer.message(message.chestShopNotInStock)
ChestShopResponse.PLAYER_INSUFFICIENT_FUNDS ->
islandPlayer.message(message.chestShopPlayerInsufficientFunds, price)
ChestShopResponse.SUCCESS -> {
islandPlayer.message(message.chestShopPurchased, amount, material, ownerName, price)
owner?.message(message.chestShopPurchasedSeller, amount, material, playerName, price)
}
else -> {}
}
return
}
when (IslandShopManager.sell(islandPlayer, shop)) {
ChestShopResponse.PLAYER_NOT_IN_STOCK ->
islandPlayer.message(message.chestShopPlayerNotInStock)
ChestShopResponse.SHOP_NO_SPACE ->
islandPlayer.message(message.chestShopNoSpace)
ChestShopResponse.SHOP_INSUFFICIENT_FUNDS ->
islandPlayer.message(message.chestShopInsufficientFunds)
ChestShopResponse.SUCCESS -> {
islandPlayer.message(message.chestShopSold, amount, material, ownerName, price)
owner?.message(message.chestShopSoldSeller, playerName, amount, material, price)
}
else -> {}
}
}
/**
* This event handles the shop breaking pace.
*/
@EventHandler(priority = EventPriority.HIGHEST)
private fun BlockBreakEvent.onShop() {
// make sure it's not cancelled and that it is a sign
val type = block.type
if (isCancelled || !type.name.contains("WALL_SIGN") && block.type != Material.CHEST) {
return
}
// necessity
val blockLocation = block.location
val island = getIslandFromLocation(blockLocation) ?: return
// if it's a chest
if (type == Material.CHEST) {
val shop = island.chestShops.values.find { it.chestLocation == blockLocation } ?: return
shop.destroy()
island.chestShops.values.remove(shop)
return
}
// sign
val encoded = encode(blockLocation)
val shop = island.chestShops[encoded] ?: return
// handle
shop.destroy()
island.chestShops.remove(encoded)
}
/**
* Handle a shop's hologram..
*/
internal fun Island.ChestShop.handleHologram() {
if (!Config.instance.chestShopUseHologram) {
return
}
HologramRegistry.register(
Identifier(this.hologramId.toString()),
buildHologram(chestLocation.clone().add(0.5, Config.instance.chestShopHologramYOffset, 0.5), this)
)
}
} | 0 | Kotlin | 0 | 0 | 23e430fd51a76e22f95847520e6976e2250058b3 | 9,003 | Skyblock | MIT License |
gmaven/src/main/kotlin/ru/rzn/gmyasoedov/gmaven/project/MavenProjectResolver.kt | grisha9 | 586,299,688 | false | {"Kotlin": 437066, "Java": 266381, "HTML": 339} | package ru.rzn.gmyasoedov.gmaven.project
import com.intellij.externalSystem.JavaProjectData
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.externalSystem.importing.ProjectResolverPolicy
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.ExternalSystemException
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.*
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkUtil
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkUtil.USE_INTERNAL_JAVA
import com.intellij.openapi.externalSystem.service.execution.ProjectJdkNotFoundException
import com.intellij.openapi.externalSystem.service.project.ExternalSystemProjectResolver
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.util.registry.Registry
import com.intellij.pom.java.LanguageLevel
import org.jdom.Element
import ru.rzn.gmyasoedov.gmaven.GMavenConstants
import ru.rzn.gmyasoedov.gmaven.extensionpoints.plugin.MavenFullImportPlugin
import ru.rzn.gmyasoedov.gmaven.project.externalSystem.model.SourceSetData
import ru.rzn.gmyasoedov.gmaven.project.policy.ReadProjectResolverPolicy
import ru.rzn.gmyasoedov.gmaven.server.GServerRemoteProcessSupport
import ru.rzn.gmyasoedov.gmaven.server.GServerRequest
import ru.rzn.gmyasoedov.gmaven.server.getProjectModel
import ru.rzn.gmyasoedov.gmaven.settings.MavenExecutionSettings
import ru.rzn.gmyasoedov.gmaven.util.toFeatureString
import ru.rzn.gmyasoedov.serverapi.model.MavenResult
import java.io.File
import java.nio.file.Path
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import kotlin.io.path.Path
import kotlin.io.path.absolutePathString
class MavenProjectResolver : ExternalSystemProjectResolver<MavenExecutionSettings> {
private val cancellationMap = ConcurrentHashMap<ExternalSystemTaskId, GServerRemoteProcessSupport>()
override fun cancelTask(id: ExternalSystemTaskId, listener: ExternalSystemTaskNotificationListener): Boolean {
cancellationMap[id]?.stopAll()
return true
}
override fun resolveProjectInfo(
id: ExternalSystemTaskId,
projectPath: String,
isPreviewMode: Boolean,
settings: MavenExecutionSettings?,
resolverPolicy: ProjectResolverPolicy?,
listener: ExternalSystemTaskNotificationListener
): DataNode<ProjectData> {
settings ?: throw ExternalSystemException("settings is empty")
val sdk = settings.jdkName?.let { getSdk(it) }
if (isPreviewMode) {
return getPreviewProjectDataNode(projectPath, settings)
}
sdk ?: throw ProjectJdkNotFoundException() //InvalidJavaHomeException
val mavenHome = getMavenHome(settings.distributionSettings)
val buildPath = Path.of(settings.executionWorkspace.projectBuildFile ?: projectPath)
val request = getServerRequest(id, buildPath, mavenHome, sdk, listener, settings, resolverPolicy)
try {
val projectModel = getProjectModel(request) { cancellationMap[id] = it }
return getProjectDataNode(projectPath, projectModel, settings)
} finally {
cancellationMap.remove(id)
}
}
private fun getServerRequest(
id: ExternalSystemTaskId,
buildPath: Path,
mavenHome: Path,
sdk: Sdk,
listener: ExternalSystemTaskNotificationListener,
settings: MavenExecutionSettings,
resolverPolicy: ProjectResolverPolicy?
): GServerRequest {
return GServerRequest(
id, buildPath, mavenHome, sdk,
listener = listener,
settings = settings,
readOnly = resolverPolicy is ReadProjectResolverPolicy
)
}
private fun getPreviewProjectDataNode(
projectPath: String,
settings: MavenExecutionSettings
): DataNode<ProjectData> {
val projectDirectory = getProjectDirectory(projectPath).absolutePathString()
val projectName = File(projectDirectory).name
val projectData = ProjectData(GMavenConstants.SYSTEM_ID, projectName, projectDirectory, projectDirectory)
val projectDataNode = DataNode(ProjectKeys.PROJECT, projectData, null)
val ideProjectPath = settings.ideProjectPath
val mainModuleFileDirectoryPath = ideProjectPath ?: projectDirectory
projectDataNode
.createChild(
ProjectKeys.MODULE, ModuleData(
projectName, GMavenConstants.SYSTEM_ID, getDefaultModuleTypeId(),
projectName, mainModuleFileDirectoryPath, projectDirectory
)
)
.createChild(ProjectKeys.CONTENT_ROOT, ContentRootData(GMavenConstants.SYSTEM_ID, projectDirectory))
return projectDataNode
}
private fun getProjectDataNode(
projectPath: String, mavenResult: MavenResult, settings: MavenExecutionSettings
): DataNode<ProjectData> {
val container = mavenResult.projectContainer
val project = container.project
val projectName = project.displayName
val absolutePath = project.file.parent
val projectData = ProjectData(GMavenConstants.SYSTEM_ID, projectName, absolutePath, absolutePath)
projectData.version = project.version
projectData.group = project.groupId
val projectDataNode = DataNode(ProjectKeys.PROJECT, projectData, null)
val sdkName: String = settings.jdkName!! //todo
val projectSdkData = ProjectSdkData(sdkName)
projectDataNode.createChild(ProjectSdkData.KEY, projectSdkData)
val languageLevel = LanguageLevel.parse(sdkName)
val javaProjectData = JavaProjectData(
GMavenConstants.SYSTEM_ID, project.outputDirectory, languageLevel,
languageLevel!!.toFeatureString()
)
projectDataNode.createChild(JavaProjectData.KEY, javaProjectData)
var ideProjectPath = settings.ideProjectPath
ideProjectPath = ideProjectPath ?: projectPath
val context = ProjectResolverContext(
projectDataNode, settings, absolutePath, ideProjectPath, mavenResult, languageLevel
)
val moduleNode = createModuleData(container, projectDataNode, context)
addDependencies(container, projectDataNode, context)
populateProfiles(projectDataNode, context.mavenResult.settings)
moduleNode.data.setProperty(GMavenConstants.MODULE_PROP_LOCAL_REPO, mavenResult.settings.localRepository)
return projectDataNode
}
private fun getProjectDirectory(projectPath: String): Path {
val projectNioPath = Path(projectPath)
return if (projectNioPath.toFile().isDirectory) projectNioPath else projectNioPath.parent
}
private fun getSdk(it: String) = if (ApplicationManager.getApplication().isUnitTestMode)
ExternalSystemJdkUtil.getJdk(null, USE_INTERNAL_JAVA) else ExternalSystemJdkUtil.getJdk(null, it)
class ProjectResolverContext(
val projectNode: DataNode<ProjectData>,
val settings: MavenExecutionSettings,
val rootProjectPath: String,
val ideaProjectPath: String,
val mavenResult: MavenResult,
val projectLanguageLevel: LanguageLevel,
val contextElementMap: MutableMap<String, Element> = HashMap(),
val moduleDataByArtifactId: MutableMap<String, ModuleContextHolder> = TreeMap(),
val libraryDataMap: MutableMap<String, DataNode<LibraryData>> = TreeMap(),
val pluginExtensionMap: Map<String, MavenFullImportPlugin> = MavenFullImportPlugin.EP_NAME.extensions
.associateBy { it.key }
) {
val lifecycles = Registry.stringValue("gmaven.lifecycles").split(",")
.map { it.trim() }
.filter { it.isNotEmpty() }
}
class ModuleContextHolder(
val moduleNode: DataNode<ModuleData>,
val perSourceSetModules: PerSourceSetModules?,
)
class PerSourceSetModules(
val mainNode: DataNode<SourceSetData>,
val testNode: DataNode<SourceSetData>,
)
} | 5 | Kotlin | 0 | 12 | f660c1c047a6f890887014dbebb0bc2fcade8a64 | 8,335 | gmaven-plugin | Apache License 2.0 |
app/src/main/kotlin/com/thundermaps/apilib/android/impl/resources/StandardMethods.kt | SaferMe | 240,105,080 | false | null | package com.thundermaps.apilib.android.impl.resources
import com.thundermaps.apilib.android.api.com.thundermaps.apilib.android.logging.ELog
import com.thundermaps.apilib.android.api.com.thundermaps.apilib.android.logging.SafermeException
import com.thundermaps.apilib.android.api.fromJsonString
import com.thundermaps.apilib.android.api.requests.RequestParameters
import com.thundermaps.apilib.android.api.requests.SaferMeApiError
import com.thundermaps.apilib.android.api.requests.SaferMeApiResult
import com.thundermaps.apilib.android.api.requests.SaferMeApiStatus
import com.thundermaps.apilib.android.api.resources.SaferMeDatum
import com.thundermaps.apilib.android.impl.AndroidClient
import com.thundermaps.apilib.android.impl.AndroidClient.Companion.gsonSerializer
import io.ktor.client.call.HttpClientCall
import io.ktor.client.call.call
import io.ktor.client.call.receive
import io.ktor.client.request.HttpRequestBuilder
import io.ktor.client.request.url
import io.ktor.http.ContentType
import io.ktor.http.HttpMethod
import io.ktor.http.contentType
import io.ktor.util.toByteArray
import io.ktor.util.toMap
class StandardMethods {
companion object {
/**
* Standardized RESTful create call. Uses POST, expects a valid item to send
* to the server.
*
* @param api Reference to client
* @param path The endpoint to send the request to
* @param parameters Request parameters to use
* @param item The resource data to create on the server
* @param success Invoked if the request was successful
* @param failure Invoked if the request failed
*/
suspend inline fun <reified T : Any> create(
api: AndroidClient,
path: String,
parameters: RequestParameters,
item: T,
crossinline success: (SaferMeApiResult<T>) -> Unit,
crossinline failure: (Exception) -> Unit
) {
try {
standardCall(api, HttpMethod.Post, path, parameters, item) { call ->
when (val status = SaferMeApiStatus.statusForCode(call.response.status.value)) {
SaferMeApiStatus.CREATED -> success(
SaferMeApiResult(
data = call.receive(),
serverStatus = status,
requestHeaders = call.request.headers.toMap(),
responseHeaders = call.response.headers.toMap()
)
)
SaferMeApiStatus.ACCEPTED -> success(
SaferMeApiResult(
data = item,
serverStatus = status,
requestHeaders = call.request.headers.toMap(),
responseHeaders = call.response.headers.toMap()
)
)
SaferMeApiStatus.OTHER_200 -> success(
SaferMeApiResult(
data = item,
serverStatus = status,
requestHeaders = call.request.headers.toMap(),
responseHeaders = call.response.headers.toMap()
)
)
SaferMeApiStatus.OTHER_400 -> {
failure(
SaferMeApiError(
serverStatus = status,
requestHeaders = call.request.headers.toMap(),
responseHeaders = call.response.headers.toMap()
)
)
}
else -> failure(
SaferMeApiError(
serverStatus = status,
requestHeaders = call.request.headers.toMap(),
responseHeaders = call.response.headers.toMap()
)
)
}
call.response.close()
}
} catch (ex: Exception) {
if (ex.message != null) {
ELog.e(SafermeException.Builder(th = ex, message = ex.message!!).build())
} else {
ELog.e(SafermeException.Builder(th = ex).build())
}
failure(ex)
}
}
/**
* Standardized RESTful GET call. Uses GET, expects the path to reference a valid
* resoure on the server.
*
* @param api Reference to client
* @param path The endpoint to send the request to
* @param parameters Request parameters to use
* @param item The resource data to create on the server
* @param success Invoked if the request was successful
* @param failure Invoked if the request failed
*/
suspend inline fun <reified T : Any> read(
api: AndroidClient,
path: String,
parameters: RequestParameters,
crossinline success: (SaferMeApiResult<T>) -> Unit,
crossinline failure: (Exception) -> Unit
) {
try {
standardCall(api, HttpMethod.Get, path, parameters, null) { call ->
when (val status = SaferMeApiStatus.statusForCode(call.response.status.value)) {
SaferMeApiStatus.OK -> success(
SaferMeApiResult(
data = call.receive(),
serverStatus = status,
requestHeaders = call.request.headers.toMap(),
responseHeaders = call.response.headers.toMap()
)
)
else -> failure(
SaferMeApiError(
serverStatus = status,
requestHeaders = call.request.headers.toMap(),
responseHeaders = call.response.headers.toMap()
)
)
}
call.response.close()
}
} catch (ex: Exception) {
if (ex.message != null) {
ELog.e(SafermeException.Builder(th = ex, message = ex.message!!).build())
} else {
ELog.e(SafermeException.Builder(th = ex).build())
}
failure(ex)
}
}
/**
* Standardized RESTful update call. Uses PATCH, expects a valid item to send
* to the server.
*
* @param api Reference to client
* @param path The endpoint to send the request to
* @param parameters Request parameters to use
* @param item The resource data to create on the server
* @param success Invoked if the request was successful
* @param failure Invoked if the request failed
*/
suspend inline fun <reified Resource : SaferMeDatum> update(
api: AndroidClient,
path: String,
parameters: RequestParameters,
item: Resource,
crossinline success: (SaferMeApiResult<Resource>) -> Unit,
crossinline failure: (Exception) -> Unit
) {
try {
standardCall(api, HttpMethod.Patch, path, parameters, item) { call ->
when (val status = SaferMeApiStatus.statusForCode(call.response.status.value)) {
SaferMeApiStatus.ACCEPTED, SaferMeApiStatus.OTHER_200, SaferMeApiStatus.NO_CONTENT -> {
/** Unlike create, we may receive an empty body **/
// If this is the case, we need to set data to what was sent in the request
val json = String(call.response.content.toByteArray())
val data: Resource? =
if (json == "" || json.trim() == "{}") null
else gsonSerializer.fromJsonString(json)
success(
SaferMeApiResult(
data = data ?: item,
serverStatus = status,
requestHeaders = call.request.headers.toMap(),
responseHeaders = call.response.headers.toMap()
)
)
}
else -> failure(
SaferMeApiError(
serverStatus = status,
requestHeaders = call.request.headers.toMap(),
responseHeaders = call.response.headers.toMap()
)
)
}
call.response.close()
}
} catch (ex: Exception) {
if (ex.message != null) {
ELog.e(SafermeException.Builder(th = ex, message = ex.message!!).build())
} else {
ELog.e(SafermeException.Builder(th = ex).build())
}
failure(ex)
}
}
/**
* Standardized RESTful index call. Uses GET, expects a valid index path.
* A little different fro the others as the serializer has trouble working
* out which type of list to create due to the generics, so an explicit type
* needs to be provided.
*
* @param api Reference to client
* @param path The endpoint to send the request to
* @param parameters Request parameters to use
* @param success Invoked if the request was successful
* @param failure Invoked if the request failed
*/
suspend inline fun <reified T : Any> index(
api: AndroidClient,
path: String,
parameters: RequestParameters,
success: (SaferMeApiResult<T>) -> Unit,
failure: (Exception) -> Unit
) {
try {
standardCall(api, HttpMethod.Get, path, parameters, null) { call ->
when (val status = SaferMeApiStatus.statusForCode(call.response.status.value)) {
SaferMeApiStatus.OK -> {
val json = String(call.response.content.toByteArray())
val result = gsonSerializer.fromJsonString<T>(json)
success(
SaferMeApiResult(
data = result,
serverStatus = status,
requestHeaders = call.request.headers.toMap(),
responseHeaders = call.response.headers.toMap()
)
)
}
else -> failure(
SaferMeApiError(
serverStatus = status,
requestHeaders = call.request.headers.toMap(),
responseHeaders = call.response.headers.toMap()
)
)
}
call.response.close()
}
} catch (ex: Exception) {
if (ex.message != null) {
ELog.e(SafermeException.Builder(th = ex, message = ex.message!!).build())
} else {
ELog.e(SafermeException.Builder(th = ex).build())
}
failure(ex)
}
}
/**
* Standardized RESTful update call. Uses PATCH, expects a valid item to send
* to the server.
*
* @param api Reference to client
* @param path The endpoint to send the request to
* @param parameters Request parameters to use
* @param item The resource data to create on the server
* @param success Invoked if the request was successful
* @param failure Invoked if the request failed
*/
public suspend inline fun <reified Resource : SaferMeDatum> delete(
api: AndroidClient,
path: String,
parameters: RequestParameters,
item: Resource,
crossinline success: (SaferMeApiResult<Resource>) -> Unit,
crossinline failure: (Exception) -> Unit
) {
try {
standardCall(api, HttpMethod.Delete, path, parameters, item) { call ->
when (val status = SaferMeApiStatus.statusForCode(call.response.status.value)) {
SaferMeApiStatus.ACCEPTED, SaferMeApiStatus.OTHER_200, SaferMeApiStatus.NO_CONTENT -> {
success(
SaferMeApiResult(
data = item,
serverStatus = status,
requestHeaders = call.request.headers.toMap(),
responseHeaders = call.response.headers.toMap()
)
)
}
SaferMeApiStatus.OTHER_400 -> {
failure(
SaferMeApiError(
serverStatus = status,
requestHeaders = call.request.headers.toMap(),
responseHeaders = call.response.headers.toMap()
)
)
}
else -> failure(
SaferMeApiError(
serverStatus = status,
requestHeaders = call.request.headers.toMap(),
responseHeaders = call.response.headers.toMap()
)
)
}
call.response.close()
}
} catch (ex: Exception) {
if (ex.message != null) {
ELog.e(SafermeException.Builder(th = ex, message = ex.message!!).build())
} else {
ELog.e(SafermeException.Builder(th = ex).build())
}
failure(ex)
}
}
// Commonly pattern for HttpRequests
suspend inline fun <T> standardCall(
api: AndroidClient,
requestMethod: HttpMethod,
path: String,
params: RequestParameters,
payload: T?,
result: (call: HttpClientCall) -> Unit
) {
val (client, template) = api.client(params)
val jsonBody = payload?.let {
gsonSerializer.toJsonTree(payload)
}
val call = client.call(HttpRequestBuilder().takeFrom(template).apply {
method = requestMethod
url(AndroidClient.baseUrlBuilder(params).apply {
encodedPath = "${this.encodedPath}$path"
}.build())
if (jsonBody != null) {
contentType(ContentType.Application.Json)
body = jsonBody
}
})
result(call)
}
}
}
| 2 | Kotlin | 0 | 0 | e10d64c126cb13e56e5089e8bedd249534dc2ccf | 16,010 | saferme-api-client-android | MIT License |
tea-time-travel-plugin/src/main/java/com/oliynick/max/tea/core/debug/app/feature/presentation/ui/components/theme/WidgetTheme.kt | Xlopec | 188,455,731 | false | null | /*
* Copyright (C) 2021. <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.oliynick.max.tea.core.debug.app.feature.presentation.ui.components.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.MaterialTheme
import androidx.compose.material.MaterialTheme.shapes
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
@Composable
fun WidgetTheme(
content: @Composable () -> Unit,
) {
val colors = lightColors(
onPrimary = Color.White,
primary = Color(70, 109, 148),
onSurface = Color.Black
)
val swingColor = SwingColor()
MaterialTheme(
colors = colors.copy(
background = swingColor.background,
onBackground = swingColor.onBackground,
surface = swingColor.background,
onSurface = swingColor.onBackground,
),
typography = typography,
shapes = shapes.copy(
small = RoundedCornerShape(size = 0.dp),
medium = RoundedCornerShape(size = 0.dp),
large = RoundedCornerShape(size = 0.dp)
),
content = content
)
}
| 0 | Kotlin | 0 | 10 | 343f1c7ea7755db989c752722a02cf85236cf9e2 | 1,772 | Tea-bag | MIT License |
tools/generator/src/main/kotlin/top/bettercode/summer/tools/autodoc/model/Field.kt | top-bettercode | 387,652,015 | false | null | package top.bettercode.autodoc.core.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonPropertyOrder
/**
*
* @author Peter Wu
*/
@JsonPropertyOrder(
"name",
"type",
"description",
"defaultVal",
"value",
"nullable",
"canCover",
"children"
)
@JsonIgnoreProperties(ignoreUnknown = true)
data class Field(
var name: String = "",
var type: String = "",
var description: String = " ",
var defaultVal: String = "",
var value: String = "",
var required: Boolean = false,
/**
* 从数据库生成字段描述时是否可覆盖
*/
var canCover: Boolean = true,
var partType: String = "",
var children: LinkedHashSet<Field> = LinkedHashSet()
) : Comparable<Field> {
override fun compareTo(other: Field): Int {
return name.compareTo(other.name)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Field) return false
if (name != other.name) return false
if (type != other.type) return false
return true
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + type.hashCode()
return result
}
/**
* 是否必填
*/
val requiredDescription: String
@JsonIgnore
get() = if (required) "是" else "否"
/**
* postman 字段描述
*/
val postmanDescription: String
@JsonIgnore
get() = (if (required) "必填," else "") + description
} | 0 | Kotlin | 0 | 2 | 3e4c089f6a05cf0dcd658e1e792f0f3edcbff649 | 1,598 | summer | Apache License 2.0 |
plugins/kotlin/idea/tests/testData/intentions/convertLambdaToSingleLine/simple5.kt | ingokegel | 72,937,917 | true | null | // WITH_STDLIB
// AFTER-WARNING: Parameter 's' is never used, could be renamed to _
fun test(list: List<String>) {
list.forEachIndexed { index, s -> println(index) }<caret>
} | 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 178 | intellij-community | Apache License 2.0 |
app/src/main/java/com/exceptionhell/todoapp/fragments/databindingadapters/BindingAdapters.kt | SainiShubham2k5 | 666,831,965 | false | null | package com.exceptionhell.todoapp.fragments.databindingadapters
import android.view.View
import androidx.databinding.BindingAdapter
import androidx.lifecycle.MutableLiveData
import androidx.navigation.findNavController
import com.exceptionhell.todoapp.R
import com.google.android.material.floatingactionbutton.FloatingActionButton
class BindingAdapters {
companion object {
@BindingAdapter("android:navToAdd")
@JvmStatic
fun navToAddFragment(view: FloatingActionButton, isNavigate: Boolean) {
view.setOnClickListener {
if (isNavigate) {
view.findNavController().navigate(R.id.action_listFragment_to_addFragment)
}
}
}
@BindingAdapter("android:emptyData")
@JvmStatic
fun emptyDataBase(view: View, databaseList: MutableLiveData<Boolean>) {
when (databaseList.value) {
true -> view.visibility = View.VISIBLE
false -> view.visibility = View.GONE
}
}
}
} | 0 | Kotlin | 0 | 0 | d03497a0cbaec76153a050be143d8de5ab93997e | 1,059 | todo | Apache License 2.0 |
cache-proxy/src/jsTest/kotlin/com/github/burrunan/gradle/proxy/CacheProxyTest.kt | burrunan | 282,982,149 | false | {"Kotlin": 249412, "JavaScript": 1621} | /*
* Copyright 2020 Vladimir Sitnikov <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.burrunan.gradle.proxy
import actions.exec.exec
import actions.glob.removeFiles
import com.github.burrunan.gradle.cache.CacheService
import com.github.burrunan.test.runTest
import com.github.burrunan.wrappers.nodejs.mkdir
import js.core.get
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.encodeToDynamic
import node.fs.copyFile
import node.fs.writeFile
import node.process.process
import kotlin.test.Test
import kotlin.test.assertTrue
import kotlin.test.fail
class CacheProxyTest {
// Emulates Azure Cache Backend for @actions/cache
val cacheService = CacheService()
// Implements Gradle HTTP Build Cache via @actions/cache
val cacheProxy = CacheProxy()
@Test
fun abc() = runTest {
val z = mapOf("a" to 4, "b" to 6)
println("json: " + JSON.stringify(Json.encodeToDynamic(z)))
}
@Test
fun cacheProxyWorks() = runTest {
val dir = "remote_cache_test"
mkdir(dir)
val root = process.cwd() + "/../../../.."
console.log(root)
cacheService {
cacheProxy {
val outputFile = "build/out.txt"
removeFiles(listOf("$dir/$outputFile"))
copyFile("$root/gradlew", dir + "/gradlew")
mkdir("$dir/gradle")
mkdir("$dir/gradle/wrapper")
copyFile("$root/gradle/wrapper/gradle-wrapper.jar", "$dir/gradle/wrapper/gradle-wrapper.jar")
copyFile("$root/gradle/wrapper/gradle-wrapper.properties", "$dir/gradle/wrapper/gradle-wrapper.properties")
writeFile(
"$dir/settings.gradle",
"""
rootProject.name = 'sample'
boolean gradle6Plus = org.gradle.util.GradleVersion.current() >= org.gradle.util.GradleVersion.version('6.0')
buildCache {
local {
// Only remote cache should be used
enabled = false
}
remote(HttpBuildCache) {
url = '${process.env["GHA_CACHE_URL"]}'
push = true
if (gradle6Plus) {
allowInsecureProtocol = true
}
}
}
""".trimIndent(),
)
writeFile(
"$dir/build.gradle",
"""
tasks.create('props', WriteProperties) {
outputFile = file("$outputFile")
property("hello", "world")
}
tasks.create('props2', WriteProperties) {
outputFile = file("${outputFile}2")
property("hello", "world2")
}
""".trimIndent(),
)
writeFile(
"$dir/gradle.properties",
"""
org.gradle.caching=true
#org.gradle.caching.debug=true
""".trimIndent(),
)
val out = exec("./gradlew", "props", "-i", "--build-cache", captureOutput = true) {
cwd = dir
silent = true
ignoreReturnCode = true
}
if (out.exitCode != 0) {
fail("Unable to execute :props task: STDOUT: ${out.stdout}, STDERR: ${out.stderr}")
}
assertTrue(
"1 actionable task: 1 executed" in out.stdout,
"Output should include <<1 actionable task: 1 executed>>, got: " + out.stdout,
)
removeFiles(listOf("$dir/$outputFile"))
val out2 = exec("./gradlew", "props", "-i", "--build-cache", captureOutput = true) {
cwd = dir
silent = true
ignoreReturnCode = true
}
if (out.exitCode != 0) {
fail("Unable to execute :props task: STDOUT: ${out.stdout}, STDERR: ${out.stderr}")
}
assertTrue("1 actionable task: 1 from cache" in out2.stdout, out2.stdout)
}
}
}
}
| 29 | Kotlin | 13 | 149 | 115e59dadf4d17b5b57f7a604290a6d2736f81ad | 5,118 | gradle-cache-action | Apache License 2.0 |
app/src/main/java/com/mw/beam/beamwallet/screens/change_address/ChangeAddressPresenter.kt | BeamMW | 156,687,787 | false | {"Kotlin": 1454975, "Java": 16801, "Shell": 4651, "IDL": 1} | /*
* // Copyright 2018 Beam Development
* //
* // 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.mw.beam.beamwallet.screens.change_address
import com.mw.beam.beamwallet.base_screen.BasePresenter
import com.mw.beam.beamwallet.core.entities.WalletAddress
import com.mw.beam.beamwallet.core.helpers.TrashManager
import io.reactivex.disposables.Disposable
class ChangeAddressPresenter(view: ChangeAddressContract.View?, repository: ChangeAddressContract.Repository, private val state: ChangeAddressState)
: BasePresenter<ChangeAddressContract.View, ChangeAddressContract.Repository>(view, repository), ChangeAddressContract.Presenter {
private lateinit var addressesSubscription: Disposable
private lateinit var trashSubscription: Disposable
override fun onViewCreated() {
super.onViewCreated()
state.viewState = if (view?.isFromReceive() != false) ChangeAddressContract.ViewState.Receive else ChangeAddressContract.ViewState.Send
state.generatedAddress = view?.getGeneratedAddress()
view?.init(state.viewState, state.generatedAddress)
}
override fun onStart() {
super.onStart()
if (state.scannedAddress != null) {
state.scannedAddress?.let { view?.setAddress(it) }
state.scannedAddress = null
}
}
override fun initSubscriptions() {
super.initSubscriptions()
addressesSubscription = repository.getAddresses().subscribe {
val addresses = it.addresses?.filter { walletAddress -> !walletAddress.isContact && !walletAddress.isExpired }
state.updateAddresses(addresses)
state.deleteAddresses(repository.getAllAddressesInTrash())
onChangeSearchText(view?.getSearchText() ?: "")
}
trashSubscription = repository.getTrashSubject().subscribe {
when (it.type) {
TrashManager.ActionType.Added -> {
state.deleteAddresses(it.data.addresses)
onChangeSearchText(view?.getSearchText() ?: "")
}
TrashManager.ActionType.Restored -> {
state.updateAddresses(it.data.addresses)
onChangeSearchText(view?.getSearchText() ?: "")
}
TrashManager.ActionType.Removed -> {}
}
}
}
override fun getSubscriptions(): Array<Disposable>? = arrayOf(addressesSubscription, trashSubscription)
override fun onChangeSearchText(text: String) {
if (text.isBlank()) {
view?.updateList(state.getAddresses())
return
}
val searchText = text.trim().toLowerCase()
val newItems = state.getAddresses().filter {
it.label.trim().toLowerCase().contains(searchText) ||
it.id.trim().toLowerCase().startsWith(searchText)
}
view?.updateList(newItems)
}
override fun onItemPressed(walletAddress: WalletAddress) {
view?.back(walletAddress)
}
} | 4 | Kotlin | 21 | 36 | d06d79ec6ef47c466acf70e9b89abecfaa49fb96 | 3,591 | android-wallet | Apache License 2.0 |
buildSrc/src/main/kotlin/DependenciesRepositories.kt | Beepiz | 115,416,175 | false | null | /*
* Copyright 2019 <NAME>. Use of this source code is governed by the Apache 2.0 license.
*/
import org.gradle.api.artifacts.dsl.RepositoryHandler
import org.gradle.kotlin.dsl.maven
fun RepositoryHandler.setupForProject() {
jcenter()
mavenCentral().ensureGroupsStartingWith("com.jakewharton.", "com.squareup.")
google().ensureGroups(
"com.google.gms",
"com.google.firebase",
"io.fabric.sdk.android",
"com.crashlytics.sdk.android",
"org.chromium.net"
).ensureGroupsStartingWith(
"androidx.",
"com.android.",
"com.google.android.",
"com.google.ar",
"android.arch"
)
maven(url = "https://maven.fabric.io/public").ensureGroups("io.fabric.tools")
maven(
url = "https://dl.bintray.com/louiscad/splitties-dev"
).ensureGroups("com.louiscad.splitties")
if ("eap" in Versions.kotlin) maven(
url = "https://dl.bintray.com/kotlin/kotlin-eap"
).ensureGroups("org.jetbrains.kotlin")
maven(
url = "https://kotlin.bintray.com/kotlinx"
).ensureModulesByRegexp("org.jetbrains.kotlinx:kotlinx-serialization\\-.*")
maven(
url = "https://oss.sonatype.org/content/repositories/snapshots"
).ensureGroups("org.androidannotations")
}
| 19 | null | 44 | 375 | 3a660829a476ea2727eecc392bad41c9b9f0246d | 1,289 | BleGattCoroutines | Apache License 2.0 |
app/src/main/java/com/alpriest/energystats/ui/flow/battery/BatteryPowerFlowView.kt | alpriest | 606,081,400 | false | null | package com.alpriest.energystats.ui.flow.battery
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import com.alpriest.energystats.R
import com.alpriest.energystats.models.asPercent
import com.alpriest.energystats.models.kWh
import com.alpriest.energystats.preview.FakeConfigManager
import com.alpriest.energystats.ui.flow.PowerFlowView
import com.alpriest.energystats.ui.flow.PowerFlowLinePosition
import com.alpriest.energystats.ui.flow.home.preview
import com.alpriest.energystats.ui.theme.AppTheme
import com.alpriest.energystats.ui.theme.EnergyStatsTheme
import kotlinx.coroutines.flow.MutableStateFlow
@Composable
fun BatteryPowerFlow(
viewModel: BatteryPowerViewModel,
modifier: Modifier = Modifier,
themeStream: MutableStateFlow<AppTheme>
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = modifier
) {
PowerFlowView(
amount = viewModel.chargePowerkWH,
themeStream = themeStream,
position = PowerFlowLinePosition.LEFT,
useColouredLines = true,
modifier = Modifier.fillMaxHeight()
)
}
}
@Composable
fun BatteryIconView(
viewModel: BatteryPowerViewModel,
themeStream: MutableStateFlow<AppTheme>,
iconHeight: Dp,
modifier: Modifier = Modifier
) {
var percentage by remember { mutableStateOf(true) }
val fontSize: TextUnit = themeStream.collectAsState().value.fontSize()
val showBatteryTemperature = themeStream.collectAsState().value.showBatteryTemperature
val decimalPlaces = themeStream.collectAsState().value.decimalPlaces
val showBatteryEstimate = themeStream.collectAsState().value.showBatteryEstimate
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = modifier
) {
BatteryView(
modifier = Modifier
.height(iconHeight)
.width(iconHeight * 1.25f)
.padding(5.dp)
)
Box(modifier = Modifier.clickable { percentage = !percentage }) {
Row {
if (percentage) {
Text(
viewModel.batteryStateOfCharge().asPercent(),
fontSize = fontSize
)
} else {
Text(
viewModel.batteryStoredCharge().kWh(decimalPlaces),
fontSize = fontSize
)
}
}
}
if (showBatteryTemperature) {
Text(
viewModel.temperature.asTemperature(),
fontSize = fontSize
)
}
if (showBatteryEstimate) {
viewModel.batteryExtra?.let {
Text(
duration(estimate = it),
textAlign = TextAlign.Center,
maxLines = 2,
color = Color.Gray,
fontSize = fontSize
)
}
}
}
}
fun Double.asTemperature(): String {
return "${this}°C"
}
@Composable
fun duration(estimate: BatteryCapacityEstimate): String {
val text = stringResource(estimate.stringId)
val mins = stringResource(R.string.mins)
val hour = stringResource(R.string.hour)
val hours = stringResource(R.string.hours)
return when (estimate.duration) {
in 0..60 -> "$text ${estimate.duration} $mins"
in 61..119 -> "$text ${estimate.duration / 60} $hour"
in 120..1440 -> "$text ${Math.round(estimate.duration / 60.0)} $hours"
else -> "$text ${Math.round(estimate.duration / 1444.0)} days"
}
}
@Preview(showBackground = true)
@Composable
fun BatteryPowerFlowViewPreview() {
EnergyStatsTheme {
BatteryPowerFlow(
viewModel = BatteryPowerViewModel(
FakeConfigManager(),
actualStateOfCharge = 0.25,
chargePowerkWH = -0.5,
temperature = 13.6,
residual = 5678
),
modifier = Modifier,
themeStream = MutableStateFlow(AppTheme.preview())
)
}
} | 6 | null | 2 | 3 | ac10ab887c6145c4e326f68261091a264b654a25 | 4,637 | EnergyStats-Android | MIT License |
vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/AbsMessageLocationItem.kt | tchapgouv | 340,329,238 | false | null | /*
* Copyright (c) 2021 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.app.features.home.room.detail.timeline.item
import android.graphics.drawable.Drawable
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.IdRes
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import com.airbnb.epoxy.EpoxyAttribute
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target
import im.vector.app.R
import im.vector.app.core.glide.GlideApp
import im.vector.app.core.utils.DimensionConverter
import im.vector.app.features.home.room.detail.timeline.helper.LocationPinProvider
import im.vector.app.features.home.room.detail.timeline.style.TimelineMessageLayout
import im.vector.app.features.home.room.detail.timeline.style.granularRoundedCorners
abstract class AbsMessageLocationItem<H : AbsMessageLocationItem.Holder> : AbsMessageItem<H>() {
@EpoxyAttribute
var locationUrl: String? = null
@EpoxyAttribute
var locationUserId: String? = null
@EpoxyAttribute
var mapWidth: Int = 0
@EpoxyAttribute
var mapHeight: Int = 0
@EpoxyAttribute(EpoxyAttribute.Option.DoNotHash)
var locationPinProvider: LocationPinProvider? = null
override fun bind(holder: H) {
super.bind(holder)
renderSendState(holder.view, null)
bindMap(holder)
}
private fun bindMap(holder: Holder) {
val location = locationUrl ?: return
val messageLayout = attributes.informationData.messageLayout
val imageCornerTransformation = if (messageLayout is TimelineMessageLayout.Bubble) {
messageLayout.cornersRadius.granularRoundedCorners()
} else {
val dimensionConverter = DimensionConverter(holder.view.resources)
RoundedCorners(dimensionConverter.dpToPx(8))
}
holder.staticMapImageView.updateLayoutParams {
width = mapWidth
height = mapHeight
}
GlideApp.with(holder.staticMapImageView)
.load(location)
.apply(RequestOptions.centerCropTransform())
.placeholder(holder.staticMapImageView.drawable)
.listener(object : RequestListener<Drawable> {
override fun onLoadFailed(
e: GlideException?,
model: Any?,
target: Target<Drawable>?,
isFirstResource: Boolean
): Boolean {
holder.staticMapPinImageView.setImageResource(R.drawable.ic_location_pin_failed)
holder.staticMapErrorTextView.isVisible = true
holder.staticMapCopyrightTextView.isVisible = false
return false
}
override fun onResourceReady(
resource: Drawable?,
model: Any?,
target: Target<Drawable>?,
dataSource: DataSource?,
isFirstResource: Boolean
): Boolean {
locationPinProvider?.create(locationUserId) { pinDrawable ->
// we are not using Glide since it does not display it correctly when there is no user photo
holder.staticMapPinImageView.setImageDrawable(pinDrawable)
}
holder.staticMapErrorTextView.isVisible = false
holder.staticMapCopyrightTextView.isVisible = true
return false
}
})
.transform(imageCornerTransformation)
.into(holder.staticMapImageView)
}
abstract class Holder(@IdRes stubId: Int) : AbsMessageItem.Holder(stubId) {
val staticMapImageView by bind<ImageView>(R.id.staticMapImageView)
val staticMapPinImageView by bind<ImageView>(R.id.staticMapPinImageView)
val staticMapErrorTextView by bind<TextView>(R.id.staticMapErrorTextView)
val staticMapCopyrightTextView by bind<TextView>(R.id.staticMapCopyrightTextView)
}
}
| 86 | null | 675 | 9 | 8781b6bc4c7298ee137571bb574226ff75bd7519 | 5,018 | tchap-android | Apache License 2.0 |
app/src/main/java/com/ramzmania/aicammvd/utils/MediaPlayerUtil.kt | rameshvoltella | 775,820,814 | false | {"Kotlin": 188167, "Java": 13908} | package com.ramzmania.aicammvd.utils
import android.content.Context
import android.media.MediaPlayer
/**
* Utility class for managing MediaPlayer instances.
*
* @param context The context used to create MediaPlayer instances.
*/
class MediaPlayerUtil(private val context: Context) {
private var mediaPlayer: MediaPlayer? = null
/**
* Plays the sound specified by the given resource ID.
*
* @param resourceId The resource ID of the sound to be played.
*/
fun playSound(resourceId: Int) {
stopSound() // Stop any currently playing sound before playing a new one
mediaPlayer = MediaPlayer.create(context, resourceId)
mediaPlayer?.start()
}
/**
* Checks if a sound is currently being played.
*
* @return `true` if a sound is currently being played, `false` otherwise.
*/
fun isPlayingSound():Boolean
{
return if(mediaPlayer!=null) {
mediaPlayer!!.isPlaying
}else {
false
}
}
/**
* Stops the currently playing sound.
*/
fun stopSound() {
mediaPlayer?.apply {
if (isPlaying) {
stop()
}
release()
}
mediaPlayer = null
}
}
| 0 | Kotlin | 0 | 1 | b1ef96dc554d066949b0529d0a76a4503b68fb32 | 1,264 | KeralaAICameraTracker | MIT License |
app/src/main/kotlin/me/leon/classical/AutoKey.kt | Leon406 | 381,644,086 | false | null | package me.leon.classical
import me.leon.ext.sliceList
fun String.autoKey(keyword: String): String {
val key = keyword.uppercase()
val stripText = this.replace("\\s".toRegex(), "")
val splits = split("\\s+".toRegex()).map { it.length }.also { println(it) }
return stripText
.virgeneneEncode(key + stripText.also { println(it) })
.also { println(it) }
.sliceList(splits)
}
fun String.autoKeyDecrypt(keyword: String): String {
val key = keyword.uppercase()
val splits = split("\\s".toRegex()).map { it.length }.also { println(it) }
val stripText = this.replace("\\s".toRegex(), "")
val keyBuilder = StringBuilder(stripText.length + key.length)
keyBuilder.append(key)
while (keyBuilder.length < stripText.length + key.length) {
val substring =
stripText
.virgeneneDecode(keyBuilder.toString(), keyBuilder.length)
.substring(
keyBuilder.length - key.length,
keyBuilder.length.takeIf { it < stripText.length } ?: stripText.length
)
keyBuilder.append(substring)
}
return keyBuilder.toString().replaceFirst(keyword, "").sliceList(splits)
}
| 0 | Kotlin | 64 | 260 | 7ee6a4065d04cf36ec5471043d291ad97fa0850d | 1,225 | ToolsFx | ISC License |
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/http/ShortcutResponse.kt | onibahamut | 365,858,379 | true | {"Kotlin": 820537, "Java": 56414, "HTML": 31580, "CSS": 2184} | package ch.rmy.android.http_shortcuts.http
import android.content.Context
import android.net.Uri
import ch.rmy.android.http_shortcuts.exceptions.ResponseTooLargeException
import ch.rmy.android.http_shortcuts.utils.SizeLimitedReader
import java.io.BufferedReader
import java.io.InputStreamReader
class ShortcutResponse internal constructor(
val url: String?,
val headers: HttpHeaders,
val statusCode: Int,
val contentFile: Uri?,
val timing: Long,
) {
val contentType: String?
get() = headers.getLast(HttpHeaders.CONTENT_TYPE)?.let { contentType ->
contentType.split(';', limit = 2)[0].toLowerCase()
}
val cookies: Map<String, String>
get() = headers.getLast(HttpHeaders.SET_COOKIE)
?.split(';')
?.map { it.split('=') }
?.associate { it.first() to (it.getOrNull(1) ?: "") }
?: emptyMap()
private var responseTooLarge = false
private var cachedContentAsString: String? = null
fun getContentAsString(context: Context): String =
if (responseTooLarge) {
throw ResponseTooLargeException(CONTENT_SIZE_LIMIT)
} else {
cachedContentAsString
?: run {
contentFile?.let {
InputStreamReader(context.contentResolver.openInputStream(it)).use { reader ->
try {
BufferedReader(SizeLimitedReader(reader, CONTENT_SIZE_LIMIT), BUFFER_SIZE)
.use(BufferedReader::readText)
} catch (e: SizeLimitedReader.LimitReachedException) {
responseTooLarge = true
throw ResponseTooLargeException(e.limit)
}
}
}
?: ""
}
.also {
cachedContentAsString = it
}
}
companion object {
private const val BUFFER_SIZE = 16384
private const val CONTENT_SIZE_LIMIT = 1 * 1000L * 1000L
}
}
| 0 | null | 0 | 0 | 81ffa869f9a09ac25759c114af8dca8cd55c5168 | 2,173 | HTTP-Shortcuts | MIT License |
redux-kotlin/src/commonMain/kotlin/org/reduxkotlin/utils/IsPlainObject.kt | reduxkotlin | 188,472,766 | false | null | package org.reduxkotlin.utils
fun isPlainObject(obj: Any) = obj !is Function<*> | 27 | Kotlin | 25 | 274 | 67b150e9e3f1fed7c42073bf1c9d2b3fd0af41f6 | 80 | redux-kotlin | MIT License |
AllPermissionsImpl/composeApp/src/iosMain/kotlin/permissions/delegate/AppTrackingTransparencyPermissionDelegate.kt | deepakkaligotla | 733,301,131 | false | {"Kotlin": 138249, "Swift": 1170} | package permissions.delegate
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.suspendCancellableCoroutine
import permissions.model.PermissionState
import permissions.util.openAppSettingsPage
import platform.AppTrackingTransparency.ATTrackingManager
import platform.AppTrackingTransparency.ATTrackingManagerAuthorizationStatusAuthorized
import platform.AppTrackingTransparency.ATTrackingManagerAuthorizationStatusDenied
import platform.AppTrackingTransparency.ATTrackingManagerAuthorizationStatusNotDetermined
internal class AppTrackingTransparencyPermissionDelegate : PermissionDelegate {
override fun getPermissionState(): PermissionState {
return when (ATTrackingManager.trackingAuthorizationStatus) {
ATTrackingManagerAuthorizationStatusNotDetermined -> PermissionState.NOT_DETERMINED
ATTrackingManagerAuthorizationStatusAuthorized -> PermissionState.GRANTED
ATTrackingManagerAuthorizationStatusDenied -> PermissionState.DENIED
else -> PermissionState.NOT_DETERMINED
}
}
@OptIn(ExperimentalCoroutinesApi::class)
override suspend fun providePermission() {
if (ATTrackingManager.trackingAuthorizationStatus == ATTrackingManagerAuthorizationStatusNotDetermined) {
suspendCancellableCoroutine<Boolean> { continuation ->
ATTrackingManager.requestTrackingAuthorizationWithCompletionHandler { status ->
val isPermissionGranted = status == ATTrackingManagerAuthorizationStatusAuthorized
continuation.resume(isPermissionGranted) {
if (isPermissionGranted) {
print("ATT permission granted")
} else {
println("ATT permission denied")
}
}
}
}
} else {
println("ATT permission denied")
}
}
override fun openSettingPage() {
openAppSettingsPage()
}
} | 0 | Kotlin | 0 | 0 | 9a18bb3e2da47815c7710236b499269689de6519 | 2,052 | Kotlin_Compose_Multiplatform | The Unlicense |
src/main/kotlin/com/projectcitybuild/entities/SerializableLocation.kt | projectcitybuild | 42,997,941 | false | null | package com.projectcitybuild.entities
import org.bukkit.Location
data class SerializableLocation(
val worldName: String,
val x: Double,
val y: Double,
val z: Double,
val pitch: Float,
val yaw: Float,
) {
companion object {
fun fromLocation(location: Location): SerializableLocation {
return SerializableLocation(
worldName = location.world!!.name,
x = location.x,
y = location.y,
z = location.z,
pitch = location.pitch,
yaw = location.yaw
)
}
}
}
| 8 | Kotlin | 0 | 2 | 670536a5832dd6c3dbde0ba2f94f74a6ec576ed3 | 617 | PCBridge | MIT License |
src/main/kotlin/me/serce/solidity/ide/highlighter.kt | SerCeMan | 78,276,820 | false | null | package me.serce.solidity.ide
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.fileTypes.SingleLazyInstanceSyntaxHighlighterFactory
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase
import com.intellij.psi.tree.IElementType
import me.serce.solidity.lang.core.SolidityLexer
import me.serce.solidity.lang.core.SolidityTokenTypes.*
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors as Defaults
class SolHighlighterFactory : SingleLazyInstanceSyntaxHighlighterFactory() {
override fun createHighlighter() = SolHighlighter()
}
class SolHighlighter : SyntaxHighlighterBase() {
override fun getHighlightingLexer() = SolidityLexer()
override fun getTokenHighlights(tokenType: IElementType): Array<out TextAttributesKey> {
return pack(tokenMapping[tokenType])
}
companion object {
private val tokenMapping: Map<IElementType, TextAttributesKey> = mapOf(
COMMENT to Defaults.LINE_COMMENT,
LBRACE to Defaults.BRACES,
RBRACE to Defaults.BRACES,
LBRACKET to Defaults.BRACKETS,
RBRACKET to Defaults.BRACKETS,
LPAREN to Defaults.PARENTHESES,
RPAREN to Defaults.PARENTHESES,
SEMICOLON to Defaults.SEMICOLON,
SCIENTIFICNUMBER to Defaults.NUMBER,
FIXEDNUMBER to Defaults.NUMBER,
DECIMALNUMBER to Defaults.NUMBER,
HEXNUMBER to Defaults.NUMBER,
NUMBERUNIT to Defaults.NUMBER,
STRINGLITERAL to Defaults.STRING
).plus(
keywords().map { it to Defaults.KEYWORD }
).plus(
literals().map { it to Defaults.KEYWORD }
).plus(
operators().map { it to Defaults.OPERATION_SIGN }
).mapValues { solidityKey(it.key, it.value) }
private fun keywords() = setOf<IElementType>(
IMPORT, AS, PRAGMA, NEW, DELETE,
CONTRACT, LIBRARY, IS, STRUCT, FUNCTION, ENUM,
PUBLIC, PRIVATE, INTERNAL, EXTERNAL, CONSTANT, PAYABLE,
IF, ELSE, FOR, WHILE, DO, BREAK, CONTINUE, THROW, USING, RETURN, RETURNS,
MAPPING, EVENT, ANONYMOUS, MODIFIER, ASSEMBLY
)
private fun literals() = setOf<IElementType>(BOOLEANLITERAL)
private fun operators() = setOf<IElementType>(
NOT, ASSIGN, PLUS_ASSIGN, MINUS_ASSIGN, MULT_ASSIGN, DIV_ASSIGN, PERCENT_ASSIGN,
PLUS, MINUS, MULT, DIV, EXPONENT, CARET,
LESS, MORE, LESSEQ, MOREEQ,
AND, ANDAND, OR, OROR,
EQ, NEQ, TO,
INC, DEC,
TILDE, PERCENT,
LSHIFT, RSHIFT,
LEFT_ASSEMBLY, RIGHT_ASSEMBLY
)
}
}
private fun solidityKey(type: IElementType, key: TextAttributesKey) =
TextAttributesKey.createTextAttributesKey("me.serce.solidity.$type", key)
private inline fun <reified T : Any?> T?.asArray(): Array<out T> = if (this == null) emptyArray() else arrayOf(this)
| 0 | null | 1 | 1 | 193b6e8d431c4aa0df2885853860deb6962d732f | 2,753 | intellij-solidity | MIT License |
app/src/main/java/com/ozturksahinyetisir/travelguideapp/view/home/HomeFragment.kt | ozturksahinyetisir | 547,540,934 | false | {"Kotlin": 79364} | package com.ozturksahinyetisir.travelguideapp.view.home
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.ozturksahinyetisir.travelguideapp.adapters.ViewPagerAdapter
import com.ozturksahinyetisir.travelguideapp.databinding.FragmentHomeBinding
class HomeFragment : Fragment() {
val TAG ="HomeFragment"
private lateinit var binding: FragmentHomeBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = FragmentHomeBinding.inflate(layoutInflater)
/**
* [setOnClickListener] used for shows button as clickable and effective.
* Can change if created new fragments.
*/
binding.flightsIcon.setOnClickListener{
Toast.makeText(activity, "clicked flightIcon", Toast.LENGTH_SHORT).show()
}
binding.hotelsIcon.setOnClickListener{
Toast.makeText(activity, "clicked HotelIcon", Toast.LENGTH_SHORT).show()
}
binding.carIcon.setOnClickListener{
Toast.makeText(activity, "clicked carIcon", Toast.LENGTH_SHORT).show()
}
binding.taxiIcon.setOnClickListener{
Toast.makeText(activity, "clicked taxiIcon", Toast.LENGTH_SHORT).show()
}
return binding.root
}
/**
* [childFragmentManager] does all effect at here. After changing fragment
* view pager doesn't load with supportFragmentManager.
* [addFraggment] creates new tabLayout with name it as "All", "Flights", "Hotels", "Transportations".
*/
override fun onResume() {
super.onResume()
activity?.let {activity->
val adapter = ViewPagerAdapter(childFragmentManager)
adapter.addFragment(AllFragment(), "All")
adapter.addFragment(FlightsFragment(), "Flights")
adapter.addFragment(HotelsFragment(), "Hotels")
adapter.addFragment(TransportationsFragment(), "Transportations")
binding.viewPager.adapter = adapter
binding.tabLayout.setupWithViewPager(binding.viewPager)
}
}
}
| 0 | Kotlin | 0 | 0 | 003077eff43daa08745eb407d8c9a995c21221e3 | 2,243 | Travel-Guide-Capstone-Project | MIT License |
simple-icons/src/commonMain/kotlin/compose/icons/simpleicons/C.kt | DevSrSouza | 311,134,756 | false | {"Kotlin": 36756847} | package compose.icons.simpleicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Butt
import androidx.compose.ui.graphics.StrokeJoin.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.SimpleIcons
public val SimpleIcons.C: ImageVector
get() {
if (_c != null) {
return _c!!
}
_c = Builder(name = "C", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth =
24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(16.5921f, 9.1962f)
reflectiveCurveToRelative(-0.354f, -3.298f, -3.627f, -3.39f)
curveToRelative(-3.2741f, -0.09f, -4.9552f, 2.474f, -4.9552f, 6.14f)
curveToRelative(0.0f, 3.6651f, 1.858f, 6.5972f, 5.0451f, 6.5972f)
curveToRelative(3.184f, 0.0f, 3.5381f, -3.665f, 3.5381f, -3.665f)
lineToRelative(6.1041f, 0.365f)
reflectiveCurveToRelative(0.36f, 3.31f, -2.196f, 5.836f)
curveToRelative(-2.552f, 2.5241f, -5.6901f, 2.9371f, -7.8762f, 2.9201f)
curveToRelative(-2.19f, -0.017f, -5.2261f, 0.034f, -8.1602f, -2.97f)
curveToRelative(-2.938f, -3.0101f, -3.436f, -5.9302f, -3.436f, -8.8002f)
curveToRelative(0.0f, -2.8701f, 0.556f, -6.6702f, 4.047f, -9.5502f)
curveTo(7.444f, 0.72f, 9.849f, 0.0f, 12.254f, 0.0f)
curveToRelative(10.0422f, 0.0f, 10.7172f, 9.2602f, 10.7172f, 9.2602f)
close()
}
}
.build()
return _c!!
}
private var _c: ImageVector? = null
| 15 | Kotlin | 20 | 460 | 651badc4ace0137c5541f859f61ffa91e5242b83 | 2,130 | compose-icons | MIT License |
desktopApp/src/jvmMain/kotlin/MyApp.kt | ranger163 | 646,122,079 | false | null | import di.initKoin
/**
* Created by <NAME> on 5/27/23.
*/
val koin = initKoin(enableNetworkLogs = true).koin | 1 | Kotlin | 1 | 3 | 7774e1896b4e544d7db3af42db1fd92ea7e6995d | 111 | kotlin-multiplatform-template | Apache License 2.0 |
projects/src/test/java/org/odk/collect/projects/ProjectsRepositoryTest.kt | getodk | 40,213,809 | false | null | package org.odk.collect.projects
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.`is`
import org.hamcrest.Matchers.isEmptyString
import org.hamcrest.Matchers.not
import org.hamcrest.Matchers.notNullValue
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito.mock
import org.mockito.Mockito.`when`
import java.util.function.Supplier
abstract class ProjectsRepositoryTest {
private val projectX = Project.New("ProjectX", "X", "#FF0000")
private val projectY = Project.New("ProjectY", "Y", "#00FF00")
private val projectZ = Project.New("ProjectZ", "Z", "#0000FF")
lateinit var projectsRepository: ProjectsRepository
abstract fun buildSubject(): ProjectsRepository
abstract fun buildSubject(clock: Supplier<Long>): ProjectsRepository
@Before
fun setup() {
projectsRepository = buildSubject()
}
@Test
fun `getAll() should return all projects from storage`() {
projectsRepository.save(projectX)
projectsRepository.save(projectY)
projectsRepository.save(projectZ)
val projects = projectsRepository.getAll()
assertThat(projects.size, `is`(3))
assertThat(projects[0], `is`(Project.Saved(projects[0].uuid, projectX)))
assertThat(projects[1], `is`(Project.Saved(projects[1].uuid, projectY)))
assertThat(projects[2], `is`(Project.Saved(projects[2].uuid, projectZ)))
}
@Test
fun `getAll() returns projects in created order`() {
val clock = mock(Supplier::class.java) as Supplier<Long>
projectsRepository = buildSubject(clock)
`when`(clock.get()).thenReturn(2)
projectsRepository.save(projectX)
`when`(clock.get()).thenReturn(1)
projectsRepository.save(projectY)
val projects = projectsRepository.getAll()
assertThat(projects[0].name, `is`(projectY.name))
assertThat(projects[1].name, `is`(projectX.name))
}
@Test
fun `save() should save project to storage`() {
projectsRepository.save(projectX)
val projects = projectsRepository.getAll()
assertThat(projects.size, `is`(1))
assertThat(projects[0], `is`(Project.Saved(projects[0].uuid, projectX)))
}
@Test
fun `save() should add uuid if not specified`() {
projectsRepository.save(projectX)
assertThat(projectsRepository.getAll()[0].uuid, `is`(not(isEmptyString())))
}
@Test
fun `save() adds project with uuid if specified`() {
projectsRepository.save(Project.Saved("blah", projectX))
assertThat(projectsRepository.getAll()[0].uuid, `is`("blah"))
}
@Test
fun `projects added with uuid are still sorted`() {
val clock = mock(Supplier::class.java) as Supplier<Long>
projectsRepository = buildSubject(clock)
`when`(clock.get()).thenReturn(2)
projectsRepository.save(Project.Saved("blah1", projectX))
`when`(clock.get()).thenReturn(1)
projectsRepository.save(Project.Saved("blah2", projectY))
assertThat(projectsRepository.getAll()[0].uuid, `is`("blah2"))
assertThat(projectsRepository.getAll()[1].uuid, `is`("blah1"))
}
@Test
fun `save() should update project if already exists`() {
projectsRepository.save(projectX)
projectsRepository.save(projectY)
projectsRepository.save(projectZ)
val originalProjectX = projectsRepository.getAll()[0]
val updatedProjectX = originalProjectX.copy(name = "Project X2", icon = "2", color = "#ff80ff")
projectsRepository.save(updatedProjectX)
val projects = projectsRepository.getAll()
assertThat(projects.size, `is`(3))
assertThat(projects[0], `is`(updatedProjectX))
assertThat(projects[1], `is`(Project.Saved(projects[1].uuid, projectY)))
assertThat(projects[2], `is`(Project.Saved(projects[2].uuid, projectZ)))
}
@Test
fun `updating project does not change its sort order`() {
val clock = mock(Supplier::class.java) as Supplier<Long>
projectsRepository = buildSubject(clock)
`when`(clock.get()).thenReturn(2)
projectsRepository.save(Project.Saved("blah1", projectX))
`when`(clock.get()).thenReturn(1)
val savedProjectY = projectsRepository.save(Project.Saved("blah2", projectY))
`when`(clock.get()).thenReturn(3)
projectsRepository.save(savedProjectY)
assertThat(projectsRepository.getAll()[0].uuid, `is`("blah2"))
assertThat(projectsRepository.getAll()[1].uuid, `is`("blah1"))
}
@Test
fun `save returns project with id`() {
val project = projectsRepository.save(projectX)
assertThat(project.uuid, `is`(notNullValue()))
}
@Test
fun `delete() should delete project from storage for given uuid`() {
projectsRepository.save(projectX)
projectsRepository.save(projectY)
var projects = projectsRepository.getAll()
projectsRepository.delete(projects.first { it.name == "ProjectX" }.uuid)
projects = projectsRepository.getAll()
assertThat(projects.size, `is`(1))
assertThat(projects[0], `is`(Project.Saved(projects[0].uuid, projectY)))
}
@Test
fun `deleteAll() should delete all projects from storage`() {
projectsRepository.save(projectX)
projectsRepository.save(projectY)
projectsRepository.deleteAll()
val projects = projectsRepository.getAll()
assertThat(projects.size, `is`(0))
}
}
| 8 | null | 15 | 717 | 63050fdd265c42f3c340f0ada5cdff3c52a883bc | 5,547 | collect | Apache License 2.0 |
app/src/main/java/com/andreyyurko/dnd/data/abilities/classes/sorcerer/DraconicBloodline.kt | AndreyYurko | 538,904,654 | false | null | package com.andreyyurko.dnd.data.abilities.classes.sorcerer
import com.andreyyurko.dnd.data.characterData.*
import com.andreyyurko.dnd.data.characterData.character.AbilityNode
import com.andreyyurko.dnd.data.characterData.character.abilityToModifier
import java.lang.Integer.max
var typeToDamageMap = mapOf(
Pair("Черный", DamageType.Acid),
Pair("Белый", DamageType.Cold),
Pair("Бронзовый", DamageType.Lightening),
Pair("Зеленый", DamageType.Poison),
Pair("Золотой", DamageType.Fire),
Pair("Красный", DamageType.Fire),
Pair("Латунный", DamageType.Fire),
Pair("Медный", DamageType.Acid),
Pair("Серебряный", DamageType.Cold),
Pair("Синий", DamageType.Lightening)
)
var ancestorBlack: AbilityNode = AbilityNode(
name = "<NAME>: черный",
changesInCharacterInfo = { abilities: CharacterInfo ->
abilities.additionalAbilities["Драконий предок"] =
"Ваш драконий предок - Черный Дракон.\n" +
"\n" +
"Вы можете говорить, читать и писать на Драконьем языке. Кроме того, когда вы взаимодействуете с драконами и совершаете проверку Харизмы, ваш бонус мастерства удваивается для этой проверки."
abilities.languageProficiency.add(Languages.Draconic)
abilities
},
alternatives = mutableMapOf(),
requirements = { abilities: CharacterInfo ->
abilities.level >= 1 && abilities.characterClass == Classes.Sorcerer
},
description = "",
isNeedsToBeShown = false
)
var ancestorBlue: AbilityNode = AbilityNode(
name = "<NAME>: синий",
changesInCharacterInfo = { abilities: CharacterInfo ->
abilities.additionalAbilities["Драконий предок"] =
"Ваш драконий предок - Синий Дракон.\n" +
"\n" +
"Вы можете говорить, читать и писать на Драконьем языке. Кроме того, когда вы взаимодействуете с драконами и совершаете проверку Харизмы, ваш бонус мастерства удваивается для этой проверки."
abilities.languageProficiency.add(Languages.Draconic)
abilities
},
alternatives = mutableMapOf(),
requirements = { abilities: CharacterInfo ->
abilities.level >= 1 && abilities.characterClass == Classes.Sorcerer
},
description = "",
isNeedsToBeShown = false
)
var ancestorBrass: AbilityNode = AbilityNode(
name = "Цвет дракона: латунный",
changesInCharacterInfo = { abilities: CharacterInfo ->
abilities.additionalAbilities["Драконий предок"] =
"Ваш драконий предок - Латунный Дракон.\n" +
"\n" +
"Вы можете говорить, читать и писать на Драконьем языке. Кроме того, когда вы взаимодействуете с драконами и совершаете проверку Харизмы, ваш бонус мастерства удваивается для этой проверки."
abilities.languageProficiency.add(Languages.Draconic)
abilities
},
alternatives = mutableMapOf(),
requirements = { abilities: CharacterInfo ->
abilities.level >= 1 && abilities.characterClass == Classes.Sorcerer
},
description = "",
isNeedsToBeShown = false
)
var ancestorBronze: AbilityNode = AbilityNode(
name = "Цвет дракона: бронзовый",
changesInCharacterInfo = { abilities: CharacterInfo ->
abilities.additionalAbilities["Драконий предок"] =
"Ваш драконий предок - Бронзовый Дракон.\n" +
"\n" +
"Вы можете говорить, читать и писать на Драконьем языке. Кроме того, когда вы взаимодействуете с драконами и совершаете проверку Харизмы, ваш бонус мастерства удваивается для этой проверки."
abilities.languageProficiency.add(Languages.Draconic)
abilities
},
alternatives = mutableMapOf(),
requirements = { abilities: CharacterInfo ->
abilities.level >= 1 && abilities.characterClass == Classes.Sorcerer
},
description = "",
isNeedsToBeShown = false
)
var ancestorCopper: AbilityNode = AbilityNode(
name = "Цвет дракона: медный",
changesInCharacterInfo = { abilities: CharacterInfo ->
abilities.additionalAbilities["Драконий предок"] =
"Ваш драконий предок - Медный Дракон.\n" +
"\n" +
"Вы можете говорить, читать и писать на Драконьем языке. Кроме того, когда вы взаимодействуете с драконами и совершаете проверку Харизмы, ваш бонус мастерства удваивается для этой проверки."
abilities.languageProficiency.add(Languages.Draconic)
abilities
},
alternatives = mutableMapOf(),
requirements = { abilities: CharacterInfo ->
abilities.level >= 1 && abilities.characterClass == Classes.Sorcerer
},
description = "",
isNeedsToBeShown = false
)
var ancestorGold: AbilityNode = AbilityNode(
name = "Цвет дракона: золотой",
changesInCharacterInfo = { abilities: CharacterInfo ->
abilities.additionalAbilities["Драконий предок"] =
"Ваш драконий предок - Золотой Дракон.\n" +
"\n" +
"Вы можете говорить, читать и писать на Драконьем языке. Кроме того, когда вы взаимодействуете с драконами и совершаете проверку Харизмы, ваш бонус мастерства удваивается для этой проверки."
abilities.languageProficiency.add(Languages.Draconic)
abilities
},
alternatives = mutableMapOf(),
requirements = { abilities: CharacterInfo ->
abilities.level >= 1 && abilities.characterClass == Classes.Sorcerer
},
description = "",
isNeedsToBeShown = false
)
var ancestorGreen: AbilityNode = AbilityNode(
name = "Цвет дракона: зеленый",
changesInCharacterInfo = { abilities: CharacterInfo ->
abilities.additionalAbilities["Драконий предок"] =
"Ваш драконий предок - Зеленый Дракон.\n" +
"\n" +
"Вы можете говорить, читать и писать на Драконьем языке. Кроме того, когда вы взаимодействуете с драконами и совершаете проверку Харизмы, ваш бонус мастерства удваивается для этой проверки."
abilities.languageProficiency.add(Languages.Draconic)
abilities
},
alternatives = mutableMapOf(),
requirements = { abilities: CharacterInfo ->
abilities.level >= 1 && abilities.characterClass == Classes.Sorcerer
},
description = "",
isNeedsToBeShown = false
)
var ancestorRed: AbilityNode = AbilityNode(
name = "Цвет дракона: красный",
changesInCharacterInfo = { abilities: CharacterInfo ->
abilities.additionalAbilities["Драконий предок"] =
"Ваш драконий предок - Красный Дракон.\n" +
"\n" +
"Вы можете говорить, читать и писать на Драконьем языке. Кроме того, когда вы взаимодействуете с драконами и совершаете проверку Харизмы, ваш бонус мастерства удваивается для этой проверки."
abilities.languageProficiency.add(Languages.Draconic)
abilities
},
alternatives = mutableMapOf(),
requirements = { abilities: CharacterInfo ->
abilities.level >= 1 && abilities.characterClass == Classes.Sorcerer
},
description = "",
isNeedsToBeShown = false
)
var ancestorSilver: AbilityNode = AbilityNode(
name = "<NAME>: серебряный",
changesInCharacterInfo = { abilities: CharacterInfo ->
abilities.additionalAbilities["Драконий предок"] =
"Ваш драконий предок - Серебряный Дракон.\n" +
"\n" +
"Вы можете говорить, читать и писать на Драконьем языке. Кроме того, когда вы взаимодействуете с драконами и совершаете проверку Харизмы, ваш бонус мастерства удваивается для этой проверки."
abilities.languageProficiency.add(Languages.Draconic)
abilities
},
alternatives = mutableMapOf(),
requirements = { abilities: CharacterInfo ->
abilities.level >= 1 && abilities.characterClass == Classes.Sorcerer
},
description = "",
isNeedsToBeShown = false
)
var ancestorWhite: AbilityNode = AbilityNode(
name = "<NAME>: белый",
changesInCharacterInfo = { abilities: CharacterInfo ->
abilities.additionalAbilities["Драконий предок"] =
"Ваш драконий предок - Белый Дракон.\n" +
"\n" +
"Вы можете говорить, читать и писать на Драконьем языке. Кроме того, когда вы взаимодействуете с драконами и совершаете проверку Харизмы, ваш бонус мастерства удваивается для этой проверки."
abilities.languageProficiency.add(Languages.Draconic)
abilities
},
alternatives = mutableMapOf(),
requirements = { abilities: CharacterInfo ->
abilities.level >= 1 && abilities.characterClass == Classes.Sorcerer
},
description = "",
isNeedsToBeShown = false
)
var dragonAncestor: AbilityNode = AbilityNode(
name = "Драконий предок",
changesInCharacterInfo = { abilities: CharacterInfo -> abilities },
alternatives = mutableMapOf(
Pair(
"first", listOf(
ancestorBlack.name, ancestorSilver.name, ancestorBlue.name, ancestorBrass.name, ancestorBronze.name,
ancestorCopper.name, ancestorGold.name, ancestorGreen.name, ancestorRed.name, ancestorWhite.name
)
)
),
requirements = { abilities: CharacterInfo ->
abilities.level >= 1 && abilities.characterClass == Classes.Sorcerer
},
description = "Вы выбираете вид вашего дракона предка. Связанный с ним вид урона используется в ваших умениях.\n" +
"\n" +
"ДРАКОНИЙ ПРЕДОК\n" +
"Дракон\tВид урона\n" +
"Белый\tХолод\n" +
"Бронзовый\tЭлектричество\n" +
"Зеленый\tЯд\n" +
"Золотой\tОгонь\n" +
"Красный\tОгонь\n" +
"Латунный\tОгонь\n" +
"Медный\tКислота\n" +
"Серебряный\tХолод\n" +
"Синий\tЭлектричество\n" +
"Чёрный\tКислота\n" +
"\n" +
"Вы можете говорить, читать и писать на Драконьем языке. Кроме того, когда вы взаимодействуете с драконами и совершаете проверку Харизмы, ваш бонус мастерства удваивается для этой проверки."
)
var draconicResilience: AbilityNode = AbilityNode(
name = "<NAME>",
changesInCharacterInfo = { abilities: CharacterInfo ->
if (abilities.currentState.armor == Armor.NoArmor) {
abilities.ac = max(abilities.ac, 13 + abilityToModifier(abilities.dexterity))
}
abilities.hp += abilities.level
abilities
},
alternatives = mutableMapOf(),
requirements = { abilities: CharacterInfo ->
abilities.level >= 1 && abilities.characterClass == Classes.Sorcerer
},
description = "Магия, струящаяся через ваше тело, проявляет физические черты ваших предков драконов. Максимум ваших хитов увеличивается на 1 на 1-м уровне и на 1 на каждом уровне, полученном в данном классе.\n" +
"\n" +
"Кроме того, некоторые участки вашей кожи покрыты тонкой драконьей чешуёй. Если вы не носите доспехов, ваш Класс Доспеха равен 13 + модификатор Ловкости."
)
var elementalAffinity: AbilityNode = AbilityNode(
name = "Родство со стихией",
changesInCharacterInfo = { abilities: CharacterInfo ->
if (abilities.additionalAbilities.contains("Драконий предок")) {
var colorType = ""
abilities.additionalAbilities["Драконий предок"]?.let { colorType = it.split(' ')[4] }
typeToDamageMap[colorType]?.let {
abilities.actionsList.add(
Action(
name = "Родство со стихией",
description = "Когда вы накладываете заклинание, причиняющее урон вида ${it.typeName}, вы добавляете модификатор Харизмы к одному броску урона этого заклинания. В это же самое время вы можете потратить 1 единицу чародейства, чтобы получить сопротивление этому виду урона на 1 час.",
type = ActionType.PartOfAction
)
)
}
}
abilities
},
alternatives = mutableMapOf(),
requirements = { abilities: CharacterInfo ->
abilities.level >= 6 && abilities.characterClass == Classes.Sorcerer
},
description = "Когда вы накладываете заклинание, причиняющее урон вида, связанного с вашим драконьим предком, вы добавляете модификатор Харизмы к одному броску урона этого заклинания. В это же самое время вы можете потратить 1 единицу чародейства, чтобы получить сопротивление этому виду урона на 1 час."
)
var dragonWings: AbilityNode = AbilityNode(
name = "<NAME>",
changesInCharacterInfo = { abilities: CharacterInfo ->
abilities.actionsList.add(
Action(
name = "<NAME>",
description = "Вы получаете способность расправить драконьи крылья у себя за спиной, получая при этом скорость полёта, равную вашей текущей скорости. Вы можете создать их бонусным действием в свой ход. Крылья существуют, пока вы не развеете их бонусным действием в свой ход.\n" +
"\n" +
"Вы не можете призвать свои крылья, нося броню, если, конечно, броня не изготовлена специально для этого. Одежда, также не приспособленная под крылья, может быть уничтожена, когда вы призываете их.",
type = ActionType.Bonus
)
)
abilities
},
alternatives = mutableMapOf(),
requirements = { abilities: CharacterInfo ->
abilities.level >= 14 && abilities.characterClass == Classes.Sorcerer
},
description = "Вы получаете способность расправить драконьи крылья у себя за спиной, получая при этом скорость полёта, равную вашей текущей скорости. Вы можете создать их бонусным действием в свой ход. Крылья существуют, пока вы не развеете их бонусным действием в свой ход.\n" +
"\n" +
"Вы не можете призвать свои крылья, нося броню, если, конечно, броня не изготовлена специально для этого. Одежда, также не приспособленная под крылья, может быть уничтожена, когда вы призываете их."
)
var dragonPresence: AbilityNode = AbilityNode(
name = "<NAME>",
changesInCharacterInfo = { abilities: CharacterInfo ->
abilities.actionsList.add(
Action(
name = "Образ дракона",
description = "Вы можете вызвать ужасный образ своего предка дракона, повергая им в ужас врагов. Вы можете действием потратить 5 единиц чародейства, чтобы окружить себя аурой страха или трепета (на ваш выбор), радиусом 60 футов. В течение 1 минуты, или пока вы не утратите концентрацию (как если бы вы концентрировались на заклинании), все враждебные существа, начинающие ход в этой ауре, должны преуспеть в спасброске Мудрости, иначе они станут очарованными (если вы выбрали трепет) или испуганными (если вы выбрали страх) до окончания действия ауры. Существо, преуспевшее в спасброске, получает иммунитет к вашей ауре на 24 часа.",
type = ActionType.Action
)
)
abilities
},
alternatives = mutableMapOf(),
requirements = { abilities: CharacterInfo ->
abilities.level >= 18 && abilities.characterClass == Classes.Sorcerer
},
description = "Вы можете вызвать ужасный образ своего предка дракона, повергая им в ужас врагов. Вы можете действием потратить 5 единиц чародейства, чтобы окружить себя аурой страха или трепета (на ваш выбор), радиусом 60 футов. В течение 1 минуты, или пока вы не утратите концентрацию (как если бы вы концентрировались на заклинании), все враждебные существа, начинающие ход в этой ауре, должны преуспеть в спасброске Мудрости, иначе они станут очарованными (если вы выбрали трепет) или испуганными (если вы выбрали страх) до окончания действия ауры. Существо, преуспевшее в спасброске, получает иммунитет к вашей ауре на 24 часа."
)
var draconicBloodline: AbilityNode = AbilityNode(
name = "Наследие драконьей крови",
changesInCharacterInfo = { abilities: CharacterInfo -> abilities },
alternatives = mutableMapOf(
Pair("first", listOf(dragonAncestor.name)),
Pair("second", listOf(draconicResilience.name)),
Pair("third", listOf(elementalAffinity.name)),
Pair("forth", listOf(dragonWings.name)),
Pair("fifth", listOf(dragonPresence.name))
),
requirements = { true },
description = "",
isNeedsToBeShown = false
)
var draconicBloodlineMap = mutableMapOf(
Pair(ancestorBlack.name, ancestorBlack),
Pair(ancestorBlue.name, ancestorBlue),
Pair(ancestorBrass.name, ancestorBrass),
Pair(ancestorGold.name, ancestorGold),
Pair(ancestorBronze.name, ancestorBronze),
Pair(ancestorCopper.name, ancestorCopper),
Pair(ancestorGreen.name, ancestorGreen),
Pair(ancestorRed.name, ancestorRed),
Pair(ancestorWhite.name, ancestorWhite),
Pair(ancestorSilver.name, ancestorSilver),
Pair(dragonAncestor.name, dragonAncestor),
Pair(draconicResilience.name, draconicResilience),
Pair(elementalAffinity.name, elementalAffinity),
Pair(dragonWings.name, dragonWings),
Pair(dragonPresence.name, dragonPresence),
Pair(draconicBloodline.name, draconicBloodline)
) | 0 | Kotlin | 0 | 1 | abe1e74bb5b85a9246a5bdf7e497d8e4fbcd96c3 | 17,132 | DnD | MIT License |
foundation/database/src/main/kotlin/converter/GameCompanyEntityTypeConverter.kt | illarionov | 305,333,284 | false | {"Kotlin": 2011397, "FreeMarker": 2782, "Shell": 855, "Fluent": 72} | /*
* Copyright (c) 2023, the Pixnews project authors and contributors. Please see the AUTHORS file for details.
* Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package ru.pixnews.foundation.database.converter
import androidx.room.TypeConverter
import ru.pixnews.foundation.database.entity.GameCompanyEntity
import ru.pixnews.foundation.database.entity.embedded.GameReleaseCategoryEntity.Type
import ru.pixnews.foundation.database.util.errorUnknownValue
internal object GameCompanyEntityTypeConverter {
@TypeConverter
fun fromCompanyType(value: GameCompanyEntity.Type?): Int = value?.databaseId ?: 0
@TypeConverter
fun toCompanyType(value: Int): GameCompanyEntity.Type? = if (value != 0) {
GameCompanyEntity.Type.entries.firstOrNull { it.databaseId == value }
?: errorUnknownValue(value, Type::class)
} else {
null
}
}
| 0 | Kotlin | 0 | 2 | 7930413e808158640c6630cde83a9d43b4ca4498 | 935 | Pixnews | Apache License 2.0 |
features/tasks/src/main/kotlin/com/edricchan/studybuddy/features/tasks/data/repo/TaskRepository.kt | EdricChan03 | 100,260,817 | false | null | package com.edricchan.studybuddy.ui.modules.task.data
import com.edricchan.studybuddy.features.tasks.data.model.TodoItem
import com.edricchan.studybuddy.utils.firebase.QueryMapper
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.dataObjects
import com.google.firebase.firestore.toObject
import com.google.firebase.firestore.toObjects
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.tasks.await
import javax.inject.Inject
class TaskRepository @Inject constructor(
firestore: FirebaseFirestore,
userFlow: Flow<@JvmSuppressWildcards FirebaseUser?>,
) {
private val userId = userFlow.mapNotNull { it?.uid }
private val taskCollectionRef = userId.map { firestore.collection("/users/$it/todos") }
private suspend fun getCollectionRef() = taskCollectionRef.first()
/** Retrieves the user's list of tasks. */
suspend fun getTasks() = getCollectionRef().get().await().toObjects<TodoItem>()
/**
* Retrieves the user's list of tasks.
*
* This method returns a [com.google.android.gms.tasks.Task] for backwards compatibility.
*/
@Deprecated("This method is kept for backwards compatibility. Use getTasks instead")
fun getTasksCompat() = runBlocking(Dispatchers.Default) { getCollectionRef() }
/** Retrieves the user's list of tasks as a [kotlinx.coroutines.flow.Flow] of updates. */
@OptIn(ExperimentalCoroutinesApi::class)
val tasksFlow = taskCollectionRef.flatMapLatest { it.dataObjects<TodoItem>() }
/** Retrieves the user's list of tasks given the specified [query]. */
suspend fun queryTasks(query: QueryMapper) =
query(getCollectionRef()).get().await().toObjects<TodoItem>()
/**
* Retrieves the user's list of tasks given the specified [query] as a
* [kotlinx.coroutines.flow.Flow].
*/
@OptIn(ExperimentalCoroutinesApi::class)
fun observeQueryTasks(query: QueryMapper) =
taskCollectionRef.flatMapLatest { query(it).dataObjects<TodoItem>() }
/** Retrieves the task given its [id]. */
suspend fun getTask(id: String) =
getCollectionRef().document(id).get().await().toObject<TodoItem>()
/** Retrieves the task given its [id] as a [com.google.firebase.firestore.DocumentReference] */
suspend fun getTaskDocument(id: String) = getCollectionRef().document(id)
/** Retrieves the task given its [id] as a [com.google.firebase.firestore.DocumentReference] */
@Deprecated("This method is kept for backwards compatibility. Use getTaskDocument instead")
fun getTaskDocumentCompat(id: String) = runBlocking(Dispatchers.Default) { getTaskDocument(id) }
/** Retrieves the task given its [id] as a [kotlinx.coroutines.flow.Flow]. */
@OptIn(ExperimentalCoroutinesApi::class)
fun observeTask(id: String) = taskCollectionRef.flatMapLatest {
it.document(id).dataObjects<TodoItem>()
}
/** Adds the specified [task]. */
suspend fun addTask(task: TodoItem) = getCollectionRef().add(task).await()
/**
* Adds the specified [task].
*
* This method returns a [com.google.android.gms.tasks.Task] for backwards compatibility.
*/
@Deprecated("This method is kept for backwards compatibility. Use addTask instead")
fun addTaskCompat(task: TodoItem) =
runBlocking(Dispatchers.Default) { getCollectionRef().add(task) }
/** Removes the specified [task]. */
suspend fun removeTask(task: TodoItem) = removeTask(task.id)
/** Removes the specified task given its [id]. */
suspend fun removeTask(id: String) {
getTaskDocument(id).delete().await()
}
/**
* Removes the specified task given its [id].
*
* This method returns a [com.google.android.gms.tasks.Task] for backwards compatibility.
*/
@Deprecated("This method is kept for backwards compatibility. Use removeTask instead")
fun removeTaskCompat(id: String) =
runBlocking(Dispatchers.Default) { getTaskDocument(id).delete() }
/** Update the task (given its [id]) with the specified [data]. */
suspend fun updateTask(id: String, data: Map<String, Any>) {
getTaskDocument(id).update(data).await()
}
/** Updates the task given its [id] with the [dataAction] to be passed to [buildMap]. */
suspend fun updateTask(id: String, dataAction: MutableMap<String, Any>.() -> Unit) =
updateTask(id, buildMap(dataAction))
}
| 46 | null | 11 | 9 | f3bd7d548380f727e8bffc6c0608b0a8e1dd17bd | 4,762 | studybuddy-android | MIT License |
app/src/main/java/com/samuelokello/kazihub/presentation/business/state/BusinessEvent.kt | OkelloSam21 | 749,782,789 | false | {"Kotlin": 326914} | package com.samuelokello.kazihub.presentation.business.state
import com.google.android.libraries.places.api.model.Place
sealed interface BusinessEvent {
data class OnEmailChanged(val email: String): BusinessEvent
data class OnPhoneNumberChanged(val phone: String): BusinessEvent
data class OnLocationChanged(val location: String): BusinessEvent
class OnSuggestionSelected(val suggestion: Place) : BusinessEvent
data class OnCreateProfileClicked(
val email: String,
val phone: String,
val location: String,
val bio: String,
val selectedLocation: Place
): BusinessEvent
data class OnBioChanged(val bio: String) : BusinessEvent
} | 0 | Kotlin | 0 | 0 | e2c0776f721e24e2667a98066d79cf6554a5f040 | 698 | KaziHub | MIT License |
lib/src/main/java/com/safframework/lifecycle/listener/CoroutineErrorListener.kt | luhaiwork | 232,261,359 | true | {"Kotlin": 22934, "Java": 1216} | package com.safframework.lifecycle.listener
/**
*
* @FileName:
* com.safframework.lifecycle.listener.CoroutineErrorListener
* @author: <NAME>
* @date: 2019-10-18 02:12
* @version: V1.0 <描述当前版本功能>
*/
interface CoroutineErrorListener {
fun onError(throwable: Throwable)
} | 0 | null | 0 | 0 | 916e818c0375127ef7e12d8dcb8eb2fce99880c4 | 291 | Lifecycle-Coroutines-Extension | Apache License 2.0 |
app/src/main/kotlin/org/hidetake/blebutton/BleCallback.kt | int128 | 55,778,621 | false | null | package org.hidetake.blebutton
import android.bluetooth.*
import android.util.Log
import org.hidetake.blebutton.BleEvent.*
class BleCallback(bleStateManager: BleStateManager) : BluetoothGattCallback() {
val bleStateManager = bleStateManager
override fun onConnectionStateChange(gatt: BluetoothGatt?, status: Int, newState: Int) {
Log.d("BleCallback", "onConnectionStateChange: newState=$newState")
when (newState) {
BluetoothProfile.STATE_CONNECTING -> bleStateManager.receiveBleEvent(BLE_CONNECTING)
BluetoothProfile.STATE_CONNECTED -> bleStateManager.receiveBleEvent(BLE_CONNECTED)
BluetoothProfile.STATE_DISCONNECTING -> bleStateManager.receiveBleEvent(BLE_DISCONNECTING)
BluetoothProfile.STATE_DISCONNECTED -> bleStateManager.receiveBleEvent(BLE_DISCONNECTED)
}
}
override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
Log.d("BleCallback", "onServicesDiscovered: $status")
when (status) {
BluetoothGatt.GATT_SUCCESS -> bleStateManager.receiveBleEvent(BLE_SERVICE_DISCOVER_SUCCESS)
else -> bleStateManager.receiveBleEvent(BLE_SERVICE_DISCOVER_FAILURE)
}
}
override fun onCharacteristicRead(gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic?, status: Int) {
Log.d("BleCallback", "onCharacteristicRead: $status: ${characteristic?.uuid}")
when (status) {
BluetoothGatt.GATT_SUCCESS -> bleStateManager.receiveBleEvent(BLE_CHARACTERISTIC_READ_SUCCESS)
else -> bleStateManager.receiveBleEvent(BLE_CHARACTERISTIC_READ_FAILURE)
}
}
override fun onCharacteristicWrite(gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic?, status: Int) {
Log.d("BleCallback", "onCharacteristicWrite: $status: ${characteristic?.uuid}")
when (status) {
BluetoothGatt.GATT_SUCCESS -> bleStateManager.receiveBleEvent(BLE_CHARACTERISTIC_WRITE_SUCCESS)
else -> bleStateManager.receiveBleEvent(BLE_CHARACTERISTIC_WRITE_FAILURE)
}
}
override fun onCharacteristicChanged(gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic?) {
Log.d("BleCallback", "onCharacteristicChanged: ${characteristic?.uuid}")
bleStateManager.receiveBleEvent(BLE_CHARACTERISTIC_CHANGED)
}
override fun onDescriptorRead(gatt: BluetoothGatt?, descriptor: BluetoothGattDescriptor?, status: Int) {
Log.d("BleCallback", "onDescriptorRead: $status: ${descriptor?.uuid}")
when (status) {
BluetoothGatt.GATT_SUCCESS -> bleStateManager.receiveBleEvent(BLE_DESCRIPTOR_READ_SUCCESS)
else -> bleStateManager.receiveBleEvent(BLE_DESCRIPTOR_READ_FAILURE)
}
}
override fun onDescriptorWrite(gatt: BluetoothGatt?, descriptor: BluetoothGattDescriptor?, status: Int) {
Log.d("BleCallback", "onDescriptorWrite: $status: ${descriptor?.uuid}")
when (status) {
BluetoothGatt.GATT_SUCCESS -> bleStateManager.receiveBleEvent(BLE_DESCRIPTOR_WRITE_SUCCESS)
else -> bleStateManager.receiveBleEvent(BLE_DESCRIPTOR_WRITE_SUCCESS)
}
}
}
| 2 | Kotlin | 11 | 9 | 8ea8d260c476ea5fc636083822bf1d54388be1b5 | 3,205 | android-ble-button | Apache License 1.1 |
compiler/testData/diagnostics/tests/smartCasts/propertyToNotNull.fir.kt | android | 263,405,600 | false | null | // !WITH_NEW_INFERENCE
class Immutable(val x: String?) {
fun foo(): String {
if (x != null) return x
return ""
}
}
class Mutable(var y: String?) {
fun foo(): String {
if (y != null) return y
return ""
}
} | 1 | null | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 253 | kotlin | Apache License 2.0 |
app/src/main/java/com/solar/ktx/MainFragment.kt | KennethSS | 339,270,035 | false | null | package com.solar.ktx
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.solar.ktx.library.component.getValue
class MainFragment : Fragment() {
val firstName by getValue<String>("firstName") // String?
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return super.onCreateView(inflater, container, savedInstanceState)
viewLifecycleOwner
}
} | 0 | Kotlin | 0 | 0 | b24452f262e1831db5a01d828875fd6cac6c46de | 579 | Ktx | Apache License 2.0 |
app/src/main/java/com/sunflower/pantaucovid19/ui/activity/EmergencyNumberActivity.kt | fiqryq | 252,935,534 | false | null | package com.sunflower.pantaucovid19.ui.activity
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import androidx.core.app.ActivityCompat
import com.sunflower.pantaucovid19.R
import com.sunflower.pantaucovid19.base.BaseActivity
import kotlinx.android.synthetic.main.activity_emergency_number.*
class EmergencyNumberActivity : BaseActivity() {
val numberCall = "119";
val REQUEST_PHONE_CALL = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_emergency_number)
cd_call.setOnClickListener {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.CALL_PHONE), REQUEST_PHONE_CALL)
} else {
startCall();
}
}
}
@SuppressLint("MissingPermission")
private fun startCall() {
val callIntent = Intent(Intent.ACTION_CALL)
callIntent.data = Uri.parse("tel:" + numberCall)
startActivity(callIntent)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
if (requestCode == REQUEST_PHONE_CALL) startCall()
}
}
| 5 | null | 4 | 17 | 38275d5f6fcb8d2d362f435379410b599f86b673 | 1,461 | Pantaucovid | Apache License 2.0 |
core/src/main/kotlin/org/jrenner/learngl/gameworld/WorldUpdater.kt | jrenner | 28,962,133 | false | null | package org.jrenner.learngl.gameworld
import com.badlogic.gdx.math.Frustum
import com.badlogic.gdx.math.MathUtils
import com.badlogic.gdx.math.Vector3
import com.badlogic.gdx.utils.IntSet
import org.jrenner.learngl.View
import org.jrenner.learngl.cube.CubeDataGrid
import org.jrenner.learngl.utils.inFrustum
import org.jrenner.learngl.utils.threeIntegerHashCode
import org.jrenner.learngl.world
import com.badlogic.gdx.utils.Array as Arr
/** updates chunks in the world on a separate Thread */
class WorldUpdater(val wor: World): Runnable {
/** hold here to pass to world thread when finished updating */
val tempCreationQueue = Arr<CubeDataGrid>()
/** this temporarily stores data from the World's map of chunk hash codes -> chunks
* for thread safety.
* It is used to check if the chunks is either already created
* or already queued for creation
* the world updater
*/
val tempChunkHashCodeSet = IntSet()
val tempChunks = Arr<Chunk>()
/** camPos and frustum will be set by the View in View.render */
val tempCamPos = Vector3()
val tempFrustum = Frustum()
val updateIntervalMillis = 250L
var maxDist = View.maxViewDist
val queueLimit = 10
var worldQueueSize = 0
override fun run() {
try {
while (true) {
synchronized(wor) {
retrieveDataFromWorld()
}
createChunksInViewRange()
synchronized(wor) {
communicateUpdateToWorld()
}
Thread.sleep(updateIntervalMillis)
}
} catch (e: Exception) {
// if we have failed at thread-safety, just crash with a message
println("ERROR in WorldUpdater thread:\n")
e.printStackTrace()
System.exit(1)
}
}
fun retrieveDataFromWorld() {
tempChunkHashCodeSet.clear()
for (item in wor.chunkHashCodeMap.keys()) {
tempChunkHashCodeSet.add(item)
}
for (item in wor.chunkCreationQueue) {
val hash = item.hashCode()
tempChunkHashCodeSet.add(hash)
}
worldQueueSize = wor.chunkCreationQueue.size
}
fun communicateUpdateToWorld() {
wor.processUpdateFromWorldUpdater(this)
tempCreationQueue.clear()
}
/** see: World.hasChunkAt */
fun worldUpdaterHasChunkAt(x: Float, y: Float, z: Float): Boolean {
val sx = wor.snapToChunkOrigin(x).toInt()
val sy = wor.snapToChunkOrigin(y).toInt()
val sz = wor.snapToChunkOrigin(z).toInt()
return tempChunkHashCodeSet.contains(threeIntegerHashCode(sx, sy, sz))
}
fun createChunksInViewRange() {
if (worldQueueSize > queueLimit) return
/*if (chunkCreationQueue.size >= queueSizeLimit) {
return
}*/
val camPos = tempCamPos
val loX = MathUtils.clamp(camPos.x - maxDist, 0f, world.width.toFloat())
val loY = MathUtils.clamp(camPos.y - maxDist, 0f, world.height.toFloat())
val loZ = MathUtils.clamp(camPos.z - maxDist, 0f, world.depth.toFloat())
val hiX = MathUtils.clamp(camPos.x + maxDist, 0f, world.width.toFloat())
val hiY = MathUtils.clamp(camPos.y + maxDist, 0f, world.height.toFloat())
val hiZ = MathUtils.clamp(camPos.z + maxDist, 0f, world.depth.toFloat())
val sz: Float = Chunk.chunkSizef
fun createChunkIfNeeded(x: Float, y: Float, z: Float) {
val chunkX = wor.snapToChunkCenter(x)
val chunkY = wor.snapToChunkCenter(y)
val chunkZ = wor.snapToChunkCenter(z)
// does this chunk already exist?
val hasChunk = worldUpdaterHasChunkAt(chunkX, chunkY, chunkZ)
// lazily create chunks only when the camera looks at them
val inView = inFrustum(chunkX, chunkY, chunkZ, Chunk.chunkSizef, tempFrustum)
if (!hasChunk && inView) {
val dist2 = camPos.dst2(chunkX, chunkY, chunkZ)
// IN RANGE
if (dist2 <= maxDist * maxDist) {
val origin = Vector3(wor.snapToChunkOrigin(x), wor.snapToChunkOrigin(y), wor.snapToChunkOrigin(z))
val cdg = wor.worldData.getCDGByWorldPos(origin.x, origin.y, origin.z)
//println("WORLD UPDATER: added to temp queue (${origin.x}, ${origin.y}, ${origin.z})")
tempCreationQueue.add(cdg)
}
}
}
var x = loX
var y: Float
var z: Float
while(x <= hiX) {
y = loY
while(y <= hiY) {
z = loZ
while (z <= hiZ) {
createChunkIfNeeded(x, y, z)
z +=sz
}
y += sz
}
x += sz
}
/*
Original code used for iteration:
for (x in loX..hiX step sz) {
for (y in loY..hiY step sz) {
for (z in loZ..hiZ step sz) {
...
Kotlin converts the float primitives into boxed Float objects in order to use Float method invocations
Current iteration method avoids object allocation (GC optimization)
*/
}
}
| 1 | null | 13 | 70 | 1266cc7366fea7a069f3a545ac54cc0e753d457a | 5,319 | kotlin-voxel | Apache License 2.0 |
z2-lib/src/jsMain/kotlin/hu/simplexion/z2/site/boot/SnackbarServiceErrorHandler.kt | spxbhuhb | 665,463,766 | false | {"Kotlin": 1313596, "CSS": 126893, "Java": 8222, "HTML": 1560, "JavaScript": 975} | package hu.simplexion.z2.site.boot
import hu.simplexion.z2.browser.material.snackbar.errorSnackbar
import hu.simplexion.z2.browser.material.snackbar.warningSnackbar
import hu.simplexion.z2.localization.text.commonStrings
import hu.simplexion.z2.services.transport.ServiceErrorHandler
import hu.simplexion.z2.services.transport.ResponseEnvelope
import hu.simplexion.z2.services.transport.ServiceCallStatus
/**
* Shows a snackbar when a service call results in an error. Except for:
*
* - [ServiceCallStatus.AuthenticationFail]
* - [ServiceCallStatus.AuthenticationFailLocked]
*/
class SnackbarServiceErrorHandler : ServiceErrorHandler() {
override fun connectionError(ex: Exception) {
errorSnackbar(commonStrings.communicationError)
}
override fun callError(serviceName: String, funName: String, responseEnvelope: ResponseEnvelope) {
when (responseEnvelope.status) {
ServiceCallStatus.AuthenticationFail,
ServiceCallStatus.AuthenticationFailLocked -> {
Unit // these should be handled by the login dialog
}
ServiceCallStatus.Timeout -> {
errorSnackbar(commonStrings.timeoutError)
}
ServiceCallStatus.Logout -> {
// nothing to do here, the logout functions should redirect the user
}
ServiceCallStatus.InvalidSession -> {
warningSnackbar(commonStrings.expiredSessionRedirectToLogin)
}
ServiceCallStatus.AccessDenied -> {
errorSnackbar(commonStrings.expiredSession)
}
else -> {
println(responseEnvelope.dump())
errorSnackbar(commonStrings.responseError)
}
}
}
} | 6 | Kotlin | 0 | 1 | 980100fb733a7b9346ff3482ec7bb8a3b03d0e7f | 1,781 | z2 | Apache License 2.0 |
reaktive/src/jvmNativeCommonTest/kotlin/com/badoo/reaktive/disposable/DisposableBuilderWithoutCallbackJvmNativeTest.kt | badoo | 174,194,386 | false | null | package com.badoo.reaktive.disposable
import com.badoo.reaktive.test.doInBackgroundBlocking
import kotlin.test.Test
import kotlin.test.assertTrue
class DisposableBuilderWithCallbackJvmNativeTest {
@Test
fun isDisposed_returns_true_IF_disposed_from_another_thread() {
val disposable = Disposable {}
doInBackgroundBlocking(block = disposable::dispose)
assertTrue(disposable.isDisposed)
}
}
| 8 | Kotlin | 49 | 956 | c712c70be2493956e7057f0f30199994571b3670 | 429 | Reaktive | Apache License 2.0 |
app/src/main/java/com/yly/sunnyweather/logic/network/ServiceCreator.kt | Mayo92 | 260,641,362 | false | null | package com.yly.sunnyweather.logic.network
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
/*
* 项目名: SunnyWeather
* 包 名: com.yly.sunnyweather.logic.network
* 文件名: ServiceCreator
* 创建者: YLY
* 时 间: 2020-05-02 17:06
* 描 述: TODO
*/
object ServiceCreator {
private const val BASE_URL = "https://api.caiyunapp.com/"
private val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
fun <T> create(serviceClass: Class<T>):T = retrofit.create(serviceClass)
inline fun <reified T> create() : T = create(T::class.java)
} | 0 | Kotlin | 0 | 0 | c0b2378290d18b5f2a6318eca73597cae9014563 | 653 | SunnyWeather | Apache License 2.0 |
features/home/impl/src/main/java/ru/aleshin/features/home/impl/presentation/ui/common/CompactCategoriesChoosers.kt | v1tzor | 638,022,252 | false | {"Kotlin": 1688951} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ru.aleshin.features.home.impl.presentation.ui.common
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.sizeIn
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.dp
import ru.aleshin.core.ui.mappers.mapToIconPainter
import ru.aleshin.core.ui.theme.TimePlannerRes
import ru.aleshin.core.ui.views.ExpandedIcon
import ru.aleshin.features.home.impl.presentation.models.categories.CategoriesUi
import ru.aleshin.features.home.impl.presentation.models.categories.MainCategoryUi
import ru.aleshin.features.home.impl.presentation.models.categories.SubCategoryUi
import ru.aleshin.features.home.impl.presentation.theme.HomeThemeRes
/**
* @author <NAME> on 02.11.2023.
*/
@Composable
internal fun CompactCategoryChooser(
modifier: Modifier = Modifier,
allCategories: List<CategoriesUi>,
selectedCategory: MainCategoryUi,
onCategoryChange: (MainCategoryUi) -> Unit,
) {
var isCategoryMenuOpen by remember { mutableStateOf(false) }
val interactionSource = remember { MutableInteractionSource() }
val isPressed: Boolean by interactionSource.collectIsPressedAsState()
Row(
modifier = modifier,
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(16.dp),
) {
Icon(
painter = painterResource(id = HomeThemeRes.icons.category),
contentDescription = HomeThemeRes.strings.mainCategoryLabel,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
OutlinedTextField(
modifier = Modifier.fillMaxWidth(),
value = selectedCategory.fetchName() ?: "*",
onValueChange = {},
readOnly = true,
label = { Text(text = HomeThemeRes.strings.mainCategoryLabel) },
trailingIcon = { ExpandedIcon(isExpanded = isCategoryMenuOpen) },
interactionSource = interactionSource,
)
Box(contentAlignment = Alignment.TopEnd) {
MainCategoriesChooseMenu(
isExpanded = isCategoryMenuOpen,
mainCategories = allCategories.map { it.mainCategory },
onDismiss = { isCategoryMenuOpen = false },
onChoose = { mainCategory ->
isCategoryMenuOpen = false
onCategoryChange(mainCategory)
},
)
}
}
LaunchedEffect(key1 = isPressed) {
if (isPressed) {
isCategoryMenuOpen = !isCategoryMenuOpen
}
}
}
@Composable
internal fun MainCategoriesChooseMenu(
modifier: Modifier = Modifier,
isExpanded: Boolean,
mainCategories: List<MainCategoryUi>,
onDismiss: () -> Unit,
onChoose: (MainCategoryUi) -> Unit,
) {
DropdownMenu(
expanded = isExpanded,
onDismissRequest = onDismiss,
modifier = modifier.sizeIn(maxHeight = 200.dp),
offset = DpOffset(0.dp, 6.dp),
) {
mainCategories.forEach { category ->
DropdownMenuItem(
onClick = { onChoose(category) },
leadingIcon = {
if (category.defaultType != null) {
Icon(
modifier = Modifier.size(18.dp),
painter = category.defaultType.mapToIconPainter(),
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
)
} else {
Text(
text = category.customName?.first()?.uppercaseChar()?.toString() ?: "*",
color = MaterialTheme.colorScheme.primary,
style = MaterialTheme.typography.titleLarge,
)
}
},
text = {
Text(
text = category.fetchName() ?: "*",
color = MaterialTheme.colorScheme.onSurface,
style = MaterialTheme.typography.titleMedium,
)
},
)
}
}
}
@Composable
internal fun CompactSubCategoryChooser(
modifier: Modifier = Modifier,
allCategories: List<CategoriesUi>,
selectedMainCategory: MainCategoryUi,
selectedSubCategory: SubCategoryUi?,
onSubCategoryChange: (SubCategoryUi?) -> Unit,
) {
val interactionSource = remember { MutableInteractionSource() }
var isSubCategoryMenuOpen by remember { mutableStateOf(false) }
val isPressed: Boolean by interactionSource.collectIsPressedAsState()
val subCategories = allCategories.find { it.mainCategory == selectedMainCategory }?.subCategories ?: emptyList()
Row(
modifier = modifier,
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(16.dp),
) {
Icon(
painter = painterResource(id = HomeThemeRes.icons.subCategory),
contentDescription = HomeThemeRes.strings.subCategoryLabel,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
OutlinedTextField(
modifier = Modifier.fillMaxWidth(),
value = selectedSubCategory?.name ?: HomeThemeRes.strings.subCategoryEmptyTitle,
onValueChange = {},
readOnly = true,
label = { Text(text = HomeThemeRes.strings.subCategoryLabel) },
trailingIcon = { ExpandedIcon(isExpanded = isSubCategoryMenuOpen) },
interactionSource = interactionSource,
)
Box(contentAlignment = Alignment.TopEnd) {
SubCategoriesChooseMenu(
isExpanded = isSubCategoryMenuOpen,
subCategories = subCategories.toMutableList().apply { add(SubCategoryUi()) },
onDismiss = { isSubCategoryMenuOpen = false },
onChoose = { subCategory ->
isSubCategoryMenuOpen = false
onSubCategoryChange(subCategory)
},
)
}
}
LaunchedEffect(key1 = isPressed) {
if (isPressed) {
isSubCategoryMenuOpen = !isSubCategoryMenuOpen
}
}
}
@Composable
internal fun SubCategoriesChooseMenu(
modifier: Modifier = Modifier,
isExpanded: Boolean,
subCategories: List<SubCategoryUi>,
onDismiss: () -> Unit,
onChoose: (SubCategoryUi?) -> Unit,
) {
DropdownMenu(
expanded = isExpanded,
onDismissRequest = onDismiss,
modifier = modifier.sizeIn(maxHeight = 200.dp),
offset = DpOffset(0.dp, 6.dp),
) {
subCategories.forEach { subCategory ->
DropdownMenuItem(
onClick = { if (subCategory.id == 0) onChoose(null) else onChoose(subCategory) },
text = {
Text(
text = subCategory.name ?: TimePlannerRes.strings.categoryEmptyTitle,
color = MaterialTheme.colorScheme.onSurface,
style = MaterialTheme.typography.titleMedium,
)
},
)
}
}
}
| 7 | Kotlin | 31 | 262 | 4238f8d894ab51859b480d339e6b23ab89d79190 | 8,804 | TimePlanner | Apache License 2.0 |
src/main/java/no/nav/fo/veilarbregistrering/metrics/Events.kt | navikt | 131,013,336 | false | null | package no.nav.fo.veilarbregistrering.metrics
enum class Events(override val key: String) : Event {
AKTIVER_BRUKER("oppfolging.aktiverBruker.event"),
AKTIVER_BRUKER_FEIL("oppfolging.aktiverBruker.feil.event"),
REAKTIVER_BRUKER("oppfolging.reaktiverBruker.event"),
OPPFOLGING_SYKMELDT("oppfolging.sykmeldt.event"),
OPPFOLGING_FEIL("oppfolging.feil.event"),
HENT_OPPFOLGING("oppfolging.status.event"),
OPPGAVE_OPPRETTET_EVENT("arbeid.registrert.oppgave.event"),
OPPGAVE_ALLEREDE_OPPRETTET_EVENT("arbeid.registrert.oppgave.allerede-opprettet.event"),
OPPGAVE_ROUTING_EVENT("arbeid.registrert.oppgave.routing.event"),
START_REGISTRERING_EVENT("start.registrering.event"),
MANUELL_REGISTRERING_EVENT("registrering.manuell-registrering.event"),
MANUELL_REAKTIVERING_EVENT("registrering.manuell-reaktivering.event"),
SYKMELDT_BESVARELSE_EVENT("registrering.sykmeldt.besvarelse.event"),
PROFILERING_EVENT("registrering.bruker.profilering.event"),
INVALID_REGISTRERING_EVENT("registrering.invalid.registrering.event"),
HENT_ARBEIDSSOKERPERIODER_KILDE("arbeid.arbeidssoker.kilde.event"),
HENT_ARBEIDSSOKERPERIODER_KILDER_GIR_SAMME_SVAR("arbeid.arbeidssoker.kilder.gir.samme.svar.event"),
ORDINAER_BESVARELSE("registrering.besvarelse"),
BESVARELSE_ALDER("registrering.bruker.alder"),
BESVARELSE_HELSEHINDER("registrering.besvarelse.helseHinder"),
BESVARELSE_ANDRE_FORHOLD("registrering.besvarelse.andreForhold"),
BESVARELSE_HAR_HATT_JOBB_SAMSVARER_M_AAREG("registrering.besvarelse.sistestilling.samsvarermedinfofraaareg");
}
interface Event {
val key: String
companion object {
@JvmStatic
fun of(key: String): Event = object:Event {
override val key: String
get() = key
}
}
} | 13 | Kotlin | 4 | 4 | a103f2b269a494d99f5f61fbc5b8505221c8f1f0 | 1,820 | veilarbregistrering | MIT License |
vk-api-generated/src/main/kotlin/name/anton3/vkapi/generated/apps/methods/AppsGetFriendsListExtended.kt | Anton3 | 159,801,334 | true | {"Kotlin": 1382186} | @file:Suppress("unused", "MemberVisibilityCanBePrivate", "SpellCheckingInspection")
package name.anton3.vkapi.generated.apps.methods
import com.fasterxml.jackson.module.kotlin.jacksonTypeRef
import name.anton3.vkapi.generated.apps.objects.RequestType
import name.anton3.vkapi.generated.users.objects.Fields
import name.anton3.vkapi.generated.users.objects.UserFull
import name.anton3.vkapi.method.UserMethod
import name.anton3.vkapi.method.VkMethod
import name.anton3.vkapi.vktypes.VkList
/**
* [https://vk.com/dev/apps.getFriendsList]
*
* Creates friends list for requests and invites in current app.
*
* @property count List size.
* @property offset No description
* @property type List type. Possible values: * 'invite' — available for invites (don't play the game),, * 'request' — available for request (play the game). By default: 'invite'.
* @property fields Additional profile fields, see [vk.com/dev/fields|description].
*/
data class AppsGetFriendsListExtended(
var count: Long? = null,
var offset: Long? = null,
var type: RequestType? = null,
var fields: List<Fields>? = null
) : VkMethod<VkList<UserFull>, UserMethod>("apps.getFriendsList", jacksonTypeRef()) {
init {
unsafeParam("extended", "1")
}
}
| 2 | Kotlin | 0 | 8 | 773c89751c4382a42f556b6d3c247f83aabec625 | 1,256 | kotlin-vk-api | MIT License |
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/greengrassv2/SystemResourceLimitsPropertyDsl.kt | F43nd1r | 643,016,506 | false | null | package com.faendir.awscdkkt.generated.services.greengrassv2
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.greengrassv2.CfnDeployment
@Generated
public fun buildSystemResourceLimitsProperty(initializer: @AwsCdkDsl
CfnDeployment.SystemResourceLimitsProperty.Builder.() -> Unit):
CfnDeployment.SystemResourceLimitsProperty =
CfnDeployment.SystemResourceLimitsProperty.Builder().apply(initializer).build()
| 1 | Kotlin | 0 | 0 | b22e397ff37c5fce365a5430790e5d83f0dd5a64 | 503 | aws-cdk-kt | Apache License 2.0 |
test/kotlin/integration/proxying/ProxyPollPerformHTTPRequestWithoutUsingPACProxyTest.kt | envoyproxy | 173,839,917 | false | null | package test.kotlin.integration.proxying
import android.content.Context
import android.net.ConnectivityManager
import android.net.ProxyInfo
import androidx.test.core.app.ApplicationProvider
import io.envoyproxy.envoymobile.LogLevel
import io.envoyproxy.envoymobile.Custom
import io.envoyproxy.envoymobile.Engine
import io.envoyproxy.envoymobile.UpstreamHttpProtocol
import io.envoyproxy.envoymobile.AndroidEngineBuilder
import io.envoyproxy.envoymobile.RequestHeadersBuilder
import io.envoyproxy.envoymobile.RequestMethod
import io.envoyproxy.envoymobile.ResponseHeaders
import io.envoyproxy.envoymobile.StreamIntel
import io.envoyproxy.envoymobile.engine.JniLibrary
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito
import org.robolectric.RobolectricTestRunner
// ┌──────────────────┐
// │ Proxy Engine │
// │ ┌──────────────┐ │
// ┌─────────────────────────┐ ┌─┼─►listener_proxy│ │
// │https://api.lyft.com/ping│ ┌──────────────┬┘ │ └──────┬───────┘ │ ┌────────────┐
// │ Request ├──►Android Engine│ │ │ │ │api.lyft.com│
// └─────────────────────────┘ └──────────────┘ │ ┌──────▼──────┐ │ └──────▲─────┘
// │ │cluster_proxy│ │ │
// │ └─────────────┴──┼────────┘
// │ │
// └──────────────────┘
@RunWith(RobolectricTestRunner::class)
class PerformHTTPSRequestUsingProxy {
init {
JniLibrary.loadTestLibrary()
}
@Test
fun `performs an HTTPs request through a proxy`() {
val port = (10001..11000).random()
val mockContext = Mockito.mock(Context::class.java)
Mockito.`when`(mockContext.getApplicationContext()).thenReturn(mockContext)
val mockConnectivityManager = Mockito.mock(ConnectivityManager::class.java)
Mockito.`when`(mockContext.getSystemService(Mockito.anyString())).thenReturn(mockConnectivityManager)
Mockito.`when`(mockConnectivityManager.getDefaultProxy()).thenReturn(ProxyInfo.buildDirectProxy("127.0.0.1", port))
val onEngineRunningLatch = CountDownLatch(1)
val onProxyEngineRunningLatch = CountDownLatch(1)
val onRespondeHeadersLatch = CountDownLatch(1)
val proxyEngineBuilder = Proxy(ApplicationProvider.getApplicationContext(), port).https()
val proxyEngine = proxyEngineBuilder
.addLogLevel(LogLevel.DEBUG)
.setOnEngineRunning { onProxyEngineRunningLatch.countDown() }
.build()
onProxyEngineRunningLatch.await(10, TimeUnit.SECONDS)
assertThat(onProxyEngineRunningLatch.count).isEqualTo(0)
val builder = AndroidEngineBuilder(mockContext)
val engine = builder
.addLogLevel(LogLevel.DEBUG)
.enableProxying(true)
.setOnEngineRunning { onEngineRunningLatch.countDown() }
.build()
onEngineRunningLatch.await(10, TimeUnit.SECONDS)
assertThat(onEngineRunningLatch.count).isEqualTo(0)
val requestHeaders = RequestHeadersBuilder(
method = RequestMethod.GET,
scheme = "https",
authority = "api.lyft.com",
path = "/ping"
)
.build()
engine
.streamClient()
.newStreamPrototype()
.setOnResponseHeaders { responseHeaders, _, _ ->
val status = responseHeaders.httpStatus ?: 0L
assertThat(status).isEqualTo(200)
assertThat(responseHeaders.value("x-response-header-that-should-be-stripped")).isNull()
onRespondeHeadersLatch.countDown()
}
.start(Executors.newSingleThreadExecutor())
.sendHeaders(requestHeaders, true)
onRespondeHeadersLatch.await(15, TimeUnit.SECONDS)
assertThat(onRespondeHeadersLatch.count).isEqualTo(0)
engine.terminate()
proxyEngine.terminate()
}
}
| 38 | null | 88 | 555 | a9ce5f854d789a9d95d53f8ed3a0f3e4013b7671 | 4,167 | envoy-mobile | Apache License 2.0 |
mmkunyi/src/main/java/com/zawhtetnaing/mmkunyi_app_assignment_zhn/view/holders/JobViewHolder.kt | zawhtetnaing10 | 142,637,994 | false | {"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Proguard": 3, "Java": 2, "XML": 66, "Kotlin": 72} | package com.zawhtetnaing.mmkunyi_app_assignment_zhn.view.holders
import android.support.v7.widget.RecyclerView
import android.view.View
import com.zawhtetnaing.mmkunyi_app_assignment_zhn.data.vos.JobVO
import com.zawhtetnaing.mmkunyi_app_assignment_zhn.delegates.JobDelegate
import com.zawhtetnaing.mmkunyi_app_assignment_zhn.utils.MMKuNyiConstants
import kotlinx.android.synthetic.main.view_holder_job.view.*
class JobViewHolder(itemView: View?, private var mDelegate: JobDelegate) : BaseJobViewHolder(itemView) {
init {
itemView!!.setOnClickListener {
mDelegate.onTapJobs(mData)
}
itemView!!.tvNumberOfPersonApplied.setOnClickListener {
mDelegate.onTapPersonsApplied(mData)
}
}
override fun bindData(data: JobVO) {
super.bindData(data)
itemView.tvShortJobDescription.text = data.shortDesc
itemView.tvFullJobDescription.text = data.fullDesc
itemView.tvSalary.text = data.offerAmount!!.offerAmount.toString()
itemView.tvSalaryDuration.text = data.offerAmount!!.duration
itemView.tvLocation.text = data.location
itemView.tvNumberOfPersonApplied.text = MMKuNyiConstants.numberOfPeopleApplied(data.applicants.size)
}
}
| 0 | Kotlin | 0 | 0 | 4617a1baa5887a48bf9f648cec6988ff42066244 | 1,249 | MMKuNyi-App-Assignment-ZHN | MIT License |
src/main/kotlin/Module.kt | robot-rover | 752,329,843 | false | {"Kotlin": 11395, "Python": 3482, "Just": 260} | abstract class Module {
abstract fun commitMemory()
abstract val type: ModuleType
abstract fun process()
}
typealias ModuleMap<T> = MutableMap<ModuleType, T>
enum class ModuleType {
Eco, Birth
}
val PRIORITY: Array<Array<Pair<ModuleType, Double>>> = arrayOf(
arrayOf(Pair(ModuleType.Eco, 1.0)),
arrayOf(Pair(ModuleType.Birth, 1.0))
) | 0 | Kotlin | 0 | 0 | 49ba49bc6299a7937fabcaadf4152126df480c95 | 361 | screeps | MIT License |
app/src/main/kotlin/com/simplemobiletools/calendar/helpers/WeeklyCalendarImpl.kt | tjb | 85,851,175 | true | {"Kotlin": 249776} | package com.simplemobiletools.calendar.helpers
import android.content.Context
import com.simplemobiletools.calendar.interfaces.WeeklyCalendar
import com.simplemobiletools.calendar.models.Event
import java.util.*
class WeeklyCalendarImpl(val mCallback: WeeklyCalendar, val mContext: Context) : DBHelper.GetEventsListener {
var mEvents: List<Event>
init {
mEvents = ArrayList<Event>()
}
fun updateWeeklyCalendar(weekStartTS: Int) {
val startTS = weekStartTS
val endTS = startTS + WEEK_SECONDS
DBHelper(mContext).getEvents(startTS, endTS, this)
}
override fun gotEvents(events: MutableList<Event>) {
mEvents = events
mCallback.updateWeeklyCalendar(events)
}
}
| 0 | Kotlin | 0 | 1 | 1b80f167234914e4491e1853361856073764db6a | 738 | Simple-Calendar | Apache License 2.0 |
app/src/main/java/uk/co/jakelee/preferencesexample/PreferencesHelper.kt | JakeSteam | 172,698,380 | false | null | package uk.co.jakelee.preferencesexample
import android.content.Context
import android.preference.PreferenceManager
class PreferenceHelper(val context: Context) {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
enum class BooleanPref(val prefId: Int, val defaultId: Int) {
setting1(R.string.pref_boolean1, R.bool.pref_boolean1_default),
setting2(R.string.pref_boolean2, R.bool.pref_boolean2_default)
}
fun getBooleanPref(pref: BooleanPref) =
prefs.getBoolean(context.getString(pref.prefId), context.resources.getBoolean(pref.defaultId))
fun setBooleanPref(pref: BooleanPref, value: Boolean) =
prefs.edit().putBoolean(context.getString(pref.prefId), value).commit()
enum class StringPref(val prefId: Int, val defaultId: Int) {
setting1(R.string.pref_string1, R.string.pref_string1_default),
setting2(R.string.pref_string2, R.string.pref_string2_default)
}
fun getStringPref(pref: StringPref) =
prefs.getString(context.getString(pref.prefId), context.getString(pref.defaultId))!!
fun setStringPref(pref: StringPref, value: String) =
prefs.edit().putString(context.getString(pref.prefId), value).commit()
enum class IntPref(val prefId: Int, val defaultId: Int) {
setting1(R.string.pref_int1, R.integer.pref_int1_default),
setting2(R.string.pref_int2, R.integer.pref_int2_default)
}
fun getIntPref(pref: IntPref) =
prefs.getInt(context.getString(pref.prefId), context.resources.getInteger(pref.defaultId).toInt())
fun setIntPref(pref: IntPref, value: Int) = prefs.edit().putInt(context.getString(pref.prefId), value).commit()
} | 0 | Kotlin | 0 | 3 | 84f01d028687718eade40671e2a9e3feb7dd0c3b | 1,693 | PreferencesExample | MIT License |
core/src/test/java/io/github/thibaultbee/streampack/internal/muxers/flv/amf/containers/AmfEcmaArrayTest.kt | ThibaultBee | 262,623,449 | false | null | package io.github.thibaultbee.streampack.internal.muxers.flv.amf.containers
import io.github.thibaultbee.streampack.internal.muxers.flv.amf.AmfType
import io.github.thibaultbee.streampack.internal.utils.extractArray
import org.junit.Assert.assertArrayEquals
import org.junit.Test
class AmfEcmaArrayTest {
@Test
fun `encode array with int test`() {
val i = 4
val a = AmfEcmaArray()
a.add(i)
val buffer = a.encode()
val expectedArray = byteArrayOf(
AmfType.ECMA_ARRAY.value, 0, 0, 0, 1, // Array header
0, 0, 0, 4, // value
0, 0, AmfType.OBJECT_END.value // Array footer
)
assertArrayEquals(
expectedArray,
buffer.extractArray()
)
}
} | 8 | Kotlin | 70 | 99 | 3a9af52fd6f34c2dac308ece85a2a38c6d64760e | 771 | StreamPack | Apache License 2.0 |
android/quest/src/androidTest/java/org/smartregister/fhircore/quest/integration/ui/profile/components/ChangeManagingEntityViewTest.kt | opensrp | 339,242,809 | false | {"Kotlin": 3034140, "Java": 4967, "JavaScript": 3548, "CSS": 459} | /*
* Copyright 2021-2023 Ona Systems, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.smartregister.fhircore.quest.integration.ui.profile.components
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import org.hl7.fhir.r4.model.ResourceType
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.smartregister.fhircore.engine.configuration.profile.ManagingEntityConfig
import org.smartregister.fhircore.quest.ui.profile.components.ChangeManagingEntityView
import org.smartregister.fhircore.quest.ui.profile.components.TEST_TAG_CANCEL
import org.smartregister.fhircore.quest.ui.profile.components.TEST_TAG_SAVE
import org.smartregister.fhircore.quest.ui.profile.model.EligibleManagingEntity
class ChangeManagingEntityViewTest {
@get:Rule val composeTestRule = createComposeRule()
@Before
fun setUp() {
val eligibleManagingEntities =
listOf(
EligibleManagingEntity(
groupId = "group-1",
logicalId = "patient-1",
memberInfo = "<NAME>",
),
)
composeTestRule.setContent {
ChangeManagingEntityView(
onSaveClick = {},
eligibleManagingEntities = eligibleManagingEntities,
onDismiss = {},
managingEntity =
ManagingEntityConfig(
resourceType = ResourceType.Patient,
nameFhirPathExpression = "Patient.name",
dialogTitle = "Assign new family head",
dialogWarningMessage = "Are you sure you want to abort this operation?",
dialogContentMessage = "Select a new family head",
eligibilityCriteriaFhirPathExpression = "Patient.active",
noMembersErrorMessage = "No family member",
),
)
}
}
@Test
fun testChangeManagingEntityViewDisplaysHeader() {
composeTestRule.onNodeWithText("Assign new family head").assertExists().assertIsDisplayed()
}
@Test
fun testChangeManagingEntityViewDisplaysAbortOperationMessage() {
composeTestRule
.onNodeWithText("Are you sure you want to abort this operation?")
.assertExists()
.assertIsDisplayed()
}
@Test
fun testChangeManagingEntityViewDisplaysSelectNewFamilyHeadTitle() {
composeTestRule
.onNodeWithText("Select a new family head", ignoreCase = true)
.assertExists()
.assertIsDisplayed()
}
@Test
fun testChangeManagingEntityViewDisplaysCancelAndSaveButtons() {
composeTestRule.onNodeWithTag(TEST_TAG_CANCEL).assertExists().assertIsDisplayed()
composeTestRule.onNodeWithTag(TEST_TAG_SAVE).assertExists().assertIsDisplayed()
}
@Test
fun testChangeManagingEntityViewDisplaysManagingEntityListItem() {
composeTestRule.onNodeWithText("Jane Doe").assertExists().assertIsDisplayed()
}
}
| 192 | Kotlin | 56 | 56 | 64a55e6920cb6280cf02a0d68152d9c03266518d | 3,432 | fhircore | Apache License 2.0 |
api/src/main/kotlin/net/bytemc/bytecloud/api/services/CloudServiceProvider.kt | bytemcnetzwerk | 684,494,766 | false | {"Kotlin": 163692} | package net.bytemc.bytecloud.api.services
import net.bytemc.bytecloud.api.group.CloudGroup
import net.bytemc.bytecloud.api.network.PacketDeserializable
import java.util.Optional
interface CloudServiceProvider : PacketDeserializable<CloudService> {
fun registerService(service: CloudService): CloudService
fun unregisterService(service: CloudService)
fun getServices(): List<CloudService>
fun getService(name: String): CloudService?
fun getServicesByGroup(group: String): List<CloudService>
fun getServicesByGroup(group: CloudGroup): List<CloudService>
fun getNonProxyServices(): List<CloudService>
fun findFallback(): Optional<CloudService>
fun findFallbacks(): List<CloudService>
} | 2 | Kotlin | 3 | 5 | 6657d004ab2d53516506ea57a0cea09506eea8ce | 730 | bytecloud | Apache License 2.0 |
app/src/main/java/com/example/scopedstoragedemo/Image.kt | ruanyandong | 344,148,449 | false | null | package com.example.scopedstoragedemo
import android.net.Uri
class Image(val uri: Uri, var checked: Boolean) | 0 | Kotlin | 0 | 3 | 4d0cb875282baa5ee55ae26c4e9cff68a87329b5 | 110 | Android10-Scoped-Storage | Apache License 2.0 |
shared/src/commonMain/kotlin/domain/MovieListViewModel.kt | youranshul | 652,226,399 | false | null | package domain
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import data.PopularMoviesDataRepository
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import util.framework.MultiplatformViewModel
class MovieListViewModel(
private val repository: PopularMoviesDataRepository,
private val onMovieSelected: (movieId: Int) -> Unit
) : MultiplatformViewModel() {
private var pageNo by mutableStateOf(1)
private var shouldPaginate by mutableStateOf(false)
var listState by mutableStateOf(ListState.IDLE)
val movieLists = mutableStateListOf<MovieResult>()
init {
loadMore()
}
fun onItemClicked(movieId: Int) {
onMovieSelected(movieId)
}
fun loadMore() {
if (pageNo == 1 || (pageNo != 1 && shouldPaginate) && listState == ListState.IDLE) {
listState = if (pageNo == 1) ListState.LOADING else ListState.PAGINATING
}
viewModelScope.launch {
repository.fetchPopularMovies(pageNo)
.catch {
}
.collect {
shouldPaginate = it.size == 20
if(pageNo == 1){
movieLists.clear()
movieLists.addAll(it)
}else{
movieLists.addAll(it)
}
listState = ListState.IDLE
if(shouldPaginate) {
pageNo++
}
if(pageNo == 1) {
listState = ListState.PAGINATION_EXHAUST
}
}
}
}
} | 0 | null | 4 | 22 | c94b618b00fb58702c197e4fd4edced4c7363163 | 1,880 | KmmMovieBuff | Apache License 2.0 |
app/src/main/java/com/example/timewisefrontend/models/Category.kt | HumanClone | 633,372,328 | false | null | package com.example.timewisefrontend.models
import com.google.gson.annotations.SerializedName
data class Category (
@SerializedName("userId") val UserId:String?,
@SerializedName("categoryId")val id:String?,
@SerializedName("name")val Name:String,
@SerializedName("totalHours") val Totalhours: Double?,
) | 0 | Kotlin | 0 | 1 | 58d7e55325d948a34a3d13a045dcfd8d1ccd518d | 331 | TimeWiseFrontEnd | MIT License |
app/src/main/java/org/studentmain/xuegaoremote/XueGaoService.kt | studentmain | 366,129,974 | false | null | package org.studentmain.xuegaoremote
import android.Manifest
import android.bluetooth.*
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.core.app.JobIntentService
import kotlinx.coroutines.Job
import kotlinx.coroutines.runBlocking
import java.util.*
class XueGaoService : JobIntentService() {
companion object {
val TAG = XueGaoService::class.java.simpleName
const val XUEGAO_NAME = "CCTXueGao"
val XUEGAO_SERVICE: UUID = UUID.fromString("0000FFF0-0000-1000-8000-00805F9B34FB")
val XUEGAO_VOLTAGE_METER: UUID = UUID.fromString("0000FFF1-0000-1000-8000-00805F9B34FB")
val XUEGAO_CONTROLLER: UUID = UUID.fromString("0000FFF2-0000-1000-8000-00805F9B34FB")
private const val XUEGAO_JOB_ID = 114514
val bta: BluetoothAdapter by lazy { BluetoothAdapter.getDefaultAdapter() }
var g: BluetoothGatt? = null
@JvmStatic
fun enqueueWork(context: Context, intent: Intent) {
val c = XueGaoService::class.java
val id = XUEGAO_JOB_ID
enqueueWork(context, c, id, intent)
}
private val cname = XueGaoService::class.java.canonicalName
val CONNECT = "$cname.CONNECT"
val DISCONNECT = "$cname.DISCONNECT"
val LINEAR_MOTOR = "$cname.LINEAR_MOTOR"
val VIBRATOR = "$cname.VIBRATOR"
val VOLTAGE_METER = "$cname.VOLTAGE_METER"
val VOLTAGE_DATA = "$cname.VOLTAGE_DATA"
}
override fun onHandleWork(intent: Intent) {
when (intent.action) {
CONNECT -> runBlocking { connect() }
LINEAR_MOTOR -> setLinearMotor(intent.getIntExtra(LINEAR_MOTOR, 0))
VIBRATOR -> setVibrator(intent.getBooleanExtra(VIBRATOR, false))
DISCONNECT -> disconnect()
VOLTAGE_METER -> setVoltageMeter(intent.getBooleanExtra(VOLTAGE_METER, true))
else -> Log.i(TAG, "Not implemented action ${intent.action}")
}
}
private suspend fun connect() {
val sc = bta.bluetoothLeScanner
val scanJob = Job()
val cb = object : ScanCallback() {
var ctr = 0
var dev: BluetoothDevice? = null
override fun onScanResult(callbackType: Int, result: ScanResult?) {
val name = result?.device?.name
if (name != XUEGAO_NAME) {
ctr++
// They say we shouldn't scan infinitely
if (ctr >= 100) {
sc.stopScan(this)
scanJob.complete()
}
return
}
dev = result.device
sc.stopScan(this)
scanJob.complete()
}
}
sc.startScan(cb)
scanJob.join()
Log.i(TAG, "Scan finish")
if (cb.dev == null) {
Log.w(TAG, "No device found")
return
}
val connectJob = Job()
val gcb = object : BluetoothGattCallback() {
override fun onConnectionStateChange(gatt: BluetoothGatt?, status: Int, newState: Int) {
if (newState == 0) {
Log.w(TAG, "Disconnect")
if (g == gatt) {
Log.w(TAG, "Stop Service")
stopSelf()
}
return
}
gatt!!.discoverServices()
Log.w(TAG, "Start discover: ${gatt.services.size} GATT service")
}
override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
Log.w(TAG, "Discover finished: ${gatt!!.services.size} GATT service")
connectJob.complete()
}
override fun onCharacteristicChanged(
gatt: BluetoothGatt?,
characteristic: BluetoothGattCharacteristic?
) {
super.onCharacteristicChanged(gatt, characteristic)
val arr = characteristic?.value ?: return
val readout = arr[2]
sendBroadcast(Intent(VOLTAGE_DATA).apply {
putExtra(VOLTAGE_DATA, readout.toInt())
}, Manifest.permission.BLUETOOTH_ADMIN)
}
}
val gatt = cb.dev!!.connectGatt(this, false, gcb)
Handler(Looper.getMainLooper()).postDelayed({ connectJob.complete() }, 10000)
connectJob.join()
Log.i(TAG, "GATT connect job done with ${gatt.services.size} services")
gatt.getService(XUEGAO_SERVICE) ?: return
g = gatt
enqueueWork(
applicationContext,
Intent(applicationContext, XueGaoService::class.java).apply {
action = VOLTAGE_METER
putExtra(VOLTAGE_METER, true)
})
}
private fun disconnect() {
Log.i(TAG, "Disconnect")
g?.disconnect()
}
private fun setLinearMotor(level: Int) {
if (level < 0 || level > 5) {
return
}
writeControl(byteArrayOf(2, 1, level.toByte(), 0))
}
private fun setVibrator(enable: Boolean) {
writeControl(byteArrayOf(2, 2, (if (enable) 170 else 0).toByte(), 0))
}
private fun writeControl(data: ByteArray) {
if (g == null) return
val c = g!!.getService(XUEGAO_SERVICE).getCharacteristic(XUEGAO_CONTROLLER)
c.value = data
g!!.writeCharacteristic(c)
}
private fun setVoltageMeter(enable: Boolean) {
if (g == null) return
val c = g!!.getService(XUEGAO_SERVICE).getCharacteristic(XUEGAO_VOLTAGE_METER)
Log.i(TAG, "Set voltage meter")
if (!g!!.setCharacteristicNotification(c, enable)) Log.e(TAG, "Set voltage meter failed")
}
} | 0 | Kotlin | 1 | 2 | 2d1b62c93faa070f982a88b2038a2b0a769d0f9f | 5,947 | XuegaoRemote | BSD Zero Clause License |
app/src/main/java/xyz/dean/androiddemos/MainApp.kt | deanssss | 203,539,447 | false | {"Gradle": 6, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "INI": 2, "Proguard": 4, "Kotlin": 70, "XML": 31, "Java": 4, "JSON": 1} | package xyz.dean.androiddemos
import com.google.auto.service.AutoService
import xyz.dean.framework.common.BaseApp
import xyz.dean.framework.common.event.ComponentEventManifest
import xyz.dean.framework.common.service.ComponentServiceManifest
@Suppress("unused")
@AutoService(BaseApp::class)
class MainApp : BaseApp {
override fun getPriority(): Int = 0
override fun getComponentServices(): List<ComponentServiceManifest> {
return listOf()
}
override fun getComponentEvents(): List<ComponentEventManifest> {
return listOf()
}
override fun initModuleData() {
}
} | 1 | null | 1 | 1 | 41020b7639c96b7d8d0a84edf63610153f07e2c3 | 609 | AndroidDemos | Apache License 2.0 |
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/kotlin/org/jetbrains/kotlin/gradle/KotlinGradlePluginIT.kt | JakeWharton | 99,388,807 | false | 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
import org.gradle.api.logging.LogLevel
import org.jetbrains.kotlin.gradle.tasks.USING_JVM_INCREMENTAL_COMPILATION_MESSAGE
import org.jetbrains.kotlin.gradle.util.*
import org.junit.Test
import java.io.File
import java.util.zip.ZipFile
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
class KotlinGradleIT : BaseGradleIT() {
@Test
fun testCrossCompile() {
val project = Project("kotlinJavaProject")
project.build("compileDeployKotlin", "build") {
assertSuccessful()
assertReportExists()
assertTasksExecuted(":compileKotlin", ":compileTestKotlin", ":compileDeployKotlin")
}
project.build("compileDeployKotlin", "build") {
assertSuccessful()
assertTasksUpToDate(
":compileKotlin",
":compileTestKotlin",
":compileDeployKotlin",
":compileJava"
)
}
}
@Test
fun testRunningInDifferentDir() {
val wd0 = workingDir
val wd1 = File(wd0, "subdir").apply { mkdirs() }
workingDir = wd1
val project1 = Project("kotlinJavaProject")
project1.build("assemble") {
assertSuccessful()
}
val wd2 = createTempDir("testRunningInDifferentDir")
wd1.copyRecursively(wd2)
wd1.deleteRecursively()
if (wd1.exists()) {
val files = buildString {
wd1.walk().forEach { appendln(" " + it.relativeTo(wd1).path) }
}
error("Some files in $wd1 were not removed:\n$files")
}
wd0.setWritable(false)
workingDir = wd2
project1.build("test") {
assertSuccessful()
}
}
@Test
fun testKotlinOnlyCompile() {
val project = Project("kotlinProject")
project.build("build") {
assertSuccessful()
assertFileExists(kotlinClassesDir() + "META-INF/kotlinProject.kotlin_module")
assertReportExists()
assertTasksExecuted(":compileKotlin", ":compileTestKotlin")
assertNotContains("Forcing System.gc")
}
project.build("build") {
assertSuccessful()
assertTasksUpToDate(":compileKotlin", ":compileTestKotlin")
}
}
@Test
fun testLogLevelForceGC() {
val debugProject = Project("simpleProject", minLogLevel = LogLevel.LIFECYCLE)
debugProject.build("build", "-Dkotlin.gradle.test.report.memory.usage=true") {
assertContains("Forcing System.gc()")
}
val infoProject = Project("simpleProject", minLogLevel = LogLevel.QUIET)
infoProject.build("clean", "build", "-Dkotlin.gradle.test.report.memory.usage=true") {
assertNotContains("Forcing System.gc()")
}
}
@Test
fun testKotlinClasspath() {
Project("classpathTest").build("build") {
assertSuccessful()
assertReportExists()
assertTasksExecuted(":compileKotlin", ":compileTestKotlin")
}
}
@Test
fun testMultiprojectPluginClasspath() {
Project("multiprojectClassPathTest").build("build") {
assertSuccessful()
assertReportExists("subproject")
assertTasksExecuted(":subproject:compileKotlin", ":subproject:compileTestKotlin")
checkKotlinGradleBuildServices()
}
}
@Test
fun testIncremental() {
val project = Project("kotlinProject")
val options = defaultBuildOptions().copy(incremental = true)
project.build("build", options = options) {
assertSuccessful()
assertNoWarnings()
}
val greeterKt = project.projectDir.getFileByName("Greeter.kt")
greeterKt.modify {
it.replace("greeting: String", "greeting: CharSequence")
}
project.build("build", options = options) {
assertSuccessful()
assertNoWarnings()
val affectedSources = project.projectDir.getFilesByNames(
"Greeter.kt", "KotlinGreetingJoiner.kt",
"TestGreeter.kt", "TestKotlinGreetingJoiner.kt"
)
assertCompiledKotlinSources(project.relativize(affectedSources))
}
}
@Test
fun testManyClassesIC() {
val project = Project("manyClasses")
val options = defaultBuildOptions().copy(incremental = true)
project.setupWorkingDir()
val classesKt = project.projectFile("classes.kt")
classesKt.writeText((0..1024).joinToString("\n") { "class Class$it { fun f() = $it }" })
project.build("build", options = options) {
assertSuccessful()
assertNoWarnings()
}
val dummyKt = project.projectFile("dummy.kt")
dummyKt.modify { "$it " }
project.build("build", options = options) {
assertSuccessful()
assertCompiledKotlinSources(project.relativize(dummyKt))
}
}
@Test
fun testSimpleMultiprojectIncremental() {
val incremental = defaultBuildOptions().copy(incremental = true)
Project("multiprojectWithDependency").build("assemble", options = incremental) {
assertSuccessful()
assertReportExists("projA")
assertReportExists("projB")
assertTasksExecuted(":projA:compileKotlin", ":projB:compileKotlin")
}
Project("multiprojectWithDependency").apply {
val oldSrc = File(this.projectDir, "projA/src/main/kotlin/a.kt")
val newSrc = File(this.projectDir, "projA/src/main/kotlin/a.kt.new")
assertTrue { oldSrc.exists() }
assertTrue { newSrc.exists() }
newSrc.copyTo(oldSrc, overwrite = true)
}.build("assemble", options = incremental) {
assertSuccessful()
assertReportExists("projA")
assertReportExists("projB")
assertTasksExecuted(":projA:compileKotlin", ":projB:compileKotlin")
}
}
@Test
fun testKotlinInJavaRoot() {
Project("kotlinInJavaRoot").build("build") {
assertSuccessful()
assertReportExists()
assertTasksExecuted(":compileKotlin")
assertContains(":compileTestKotlin NO-SOURCE")
}
}
@Test
fun testIncrementalPropertyFromLocalPropertiesFile() {
val project = Project("kotlinProject")
project.setupWorkingDir()
val localPropertyFile = File(project.projectDir, "local.properties")
localPropertyFile.writeText("kotlin.incremental=true")
project.build("build") {
assertContains(USING_JVM_INCREMENTAL_COMPILATION_MESSAGE)
}
}
@Test
fun testIncrementalCompilationLogLevel() {
val infoProject = Project("kotlinProject", minLogLevel = LogLevel.INFO)
infoProject.build("build") {
assertContains(USING_JVM_INCREMENTAL_COMPILATION_MESSAGE)
}
val lifecycleProject = Project("kotlinProject", minLogLevel = LogLevel.LIFECYCLE)
lifecycleProject.build("build") {
assertNotContains(USING_JVM_INCREMENTAL_COMPILATION_MESSAGE)
}
}
@Test
fun testConvertJavaToKotlin() {
val project = Project("convertBetweenJavaAndKotlin")
project.setupWorkingDir()
val barKt = project.projectDir.getFileByName("Bar.kt")
val barKtContent = barKt.readText()
barKt.delete()
project.build("build") {
assertSuccessful()
}
val barClass = project.projectDir.getFileByName("Bar.class")
val barClassTimestamp = barClass.lastModified()
val barJava = project.projectDir.getFileByName("Bar.java")
barJava.delete()
barKt.writeText(barKtContent)
project.build("build") {
assertSuccessful()
assertNotContains(":compileKotlin UP-TO-DATE", ":compileJava UP-TO-DATE")
assertNotEquals(barClassTimestamp, barClass.lastModified(), "Bar.class timestamp hasn't been updated")
}
}
@Test
fun testMoveClassToOtherModule() {
val project = Project("moveClassToOtherModule")
project.build("build") {
assertSuccessful()
assertContains("Connected to daemon")
}
project.performModifications()
project.build("build") {
assertSuccessful()
assertContains("Connected to daemon")
}
}
@Test
fun testTypeAliasIncremental() {
val project = Project("typeAlias")
val options = defaultBuildOptions().copy(incremental = true)
project.build("build", options = options) {
assertSuccessful()
}
val curryKt = project.projectDir.getFileByName("Curry.kt")
val useCurryKt = project.projectDir.getFileByName("UseCurry.kt")
curryKt.modify {
it.replace("class Curry", "internal class Curry")
}
project.build("build", options = options) {
assertSuccessful()
assertCompiledKotlinSources(project.relativize(curryKt, useCurryKt))
}
}
@Test
fun testKotlinBuiltins() {
val project = Project("kotlinBuiltins")
project.build("build") {
assertSuccessful()
}
}
@Test
fun testCustomCompilerFile() {
val project = Project("customCompilerFile")
project.setupWorkingDir()
// copy compiler embeddable to project dir using custom name
val classpath = System.getProperty("java.class.path").split(File.pathSeparator)
val kotlinEmbeddableJar = File(classpath.find { it.contains("kotlin-compiler-embeddable") })
val compilerJar = File(project.projectDir, "compiler.jar")
kotlinEmbeddableJar.copyTo(compilerJar)
project.build("build") {
assertSuccessful()
assertContains("Kotlin compiler classpath: $compilerJar")
}
}
@Test
fun testFreeCompilerArgs() {
val project = Project("kotlinProject")
project.setupWorkingDir()
val customModuleName = "custom_module_name"
File(project.projectDir, "build.gradle").modify {
it + """
compileKotlin {
kotlinOptions.freeCompilerArgs = [ "-module-name", "$customModuleName" ]
}"""
}
project.build("build") {
assertSuccessful()
assertFileExists(kotlinClassesDir() + "META-INF/$customModuleName.kotlin_module")
}
}
@Test
fun testDowngradeTo106() {
val project = Project("kotlinProject")
val options = defaultBuildOptions().copy(incremental = true, withDaemon = false)
project.build("assemble", options = options) {
assertSuccessful()
}
project.build("clean", "assemble", options = options.copy(kotlinVersion = "1.0.6")) {
assertSuccessful()
}
}
@Test
fun testOmittedStdlibVersion() {
val project = Project("kotlinProject", GradleVersionRequired.AtLeast("4.4"))
project.setupWorkingDir()
File(project.projectDir, "build.gradle").modify {
it.replace("kotlin-stdlib:\$kotlin_version", "kotlin-stdlib").apply { check(!equals(it)) } + "\n" + """
apply plugin: 'maven'
install.repositories { maven { url "file://${'$'}buildDir/repo" } }
""".trimIndent()
}
project.build("build", "install") {
assertSuccessful()
assertTasksExecuted(":compileKotlin", ":compileTestKotlin")
val pomLines = File(project.projectDir, "build/poms/pom-default.xml").readLines()
val stdlibVersionLineNumber = pomLines.indexOfFirst { "<artifactId>kotlin-stdlib</artifactId>" in it } + 1
val versionLine = pomLines[stdlibVersionLineNumber]
assertTrue { "<version>${defaultBuildOptions().kotlinVersion}</version>" in versionLine }
}
}
@Test
fun testCleanAfterIncrementalBuild() {
val project = Project("kotlinProject")
val options = defaultBuildOptions().copy(incremental = true)
project.build("build", "clean", options = options) {
assertSuccessful()
}
}
@Test
fun testIncrementalTestCompile() {
val project = Project("kotlinProject")
val options = defaultBuildOptions().copy(incremental = true)
project.build("build", options = options) {
assertSuccessful()
}
val joinerKt = project.projectDir.getFileByName("KotlinGreetingJoiner.kt")
joinerKt.modify {
it.replace("class KotlinGreetingJoiner", "internal class KotlinGreetingJoiner")
}
project.build("build", options = options) {
assertSuccessful()
val testJoinerKt = project.projectDir.getFileByName("TestKotlinGreetingJoiner.kt")
assertCompiledKotlinSources(project.relativize(joinerKt, testJoinerKt))
}
}
@Test
fun testLanguageVersionApiVersionExplicit() {
val project = Project("kotlinProject")
project.setupWorkingDir()
val buildGradle = File(project.projectDir, "build.gradle")
val buildGradleContentCopy = buildGradle.readText()
fun updateBuildGradle(langVersion: String, apiVersion: String) {
buildGradle.writeText(
"""
$buildGradleContentCopy
compileKotlin {
kotlinOptions {
languageVersion = '$langVersion'
apiVersion = '$apiVersion'
}
}
""".trimIndent()
)
}
assert(buildGradleContentCopy.indexOf("languageVersion") < 0) { "build.gradle should not contain 'languageVersion'" }
assert(buildGradleContentCopy.indexOf("apiVersion") < 0) { "build.gradle should not contain 'apiVersion'" }
// check the arguments are not passed by default (they are inferred by the compiler)
project.build("clean", "compileKotlin") {
assertSuccessful()
assertNotContains("-language-version")
assertNotContains("-api-version")
assertNoWarnings()
}
// check the arguments are always passed if specified explicitly
updateBuildGradle("1.0", "1.0")
project.build("clean", "compileKotlin") {
assertSuccessful()
assertContains("-language-version 1.0")
assertContains("-api-version 1.0")
}
updateBuildGradle("1.1", "1.1")
project.build("clean", "compileKotlin") {
assertSuccessful()
assertContains("-language-version 1.1")
assertContains("-api-version 1.1")
}
}
@Test
fun testSeparateOutputGradle40() {
val project = Project("kotlinJavaProject")
project.build("compileDeployKotlin", "assemble") {
assertSuccessful()
// Check that the Kotlin classes are placed under directories following the guideline:
assertFileExists(kotlinClassesDir() + "demo/KotlinGreetingJoiner.class")
assertFileExists(kotlinClassesDir(sourceSet = "deploy") + "demo/ExampleSource.class")
// Check that the resulting JAR contains the Kotlin classes, without duplicates:
val jar = ZipFile(fileInWorkingDir("build/libs/${project.projectName}.jar"))
assertEquals(1, jar.entries().asSequence().count { it.name == "demo/KotlinGreetingJoiner.class" })
// Check that the Java output is intact:
assertFileExists("build/classes/java/main/demo/Greeter.class")
}
}
@Test
fun testArchiveBaseNameForModuleName() {
val project = Project("simpleProject")
project.setupWorkingDir()
val archivesBaseName = "myArchivesBaseName"
val buildGradle = File(project.projectDir, "build.gradle")
buildGradle.appendText("\narchivesBaseName = '$archivesBaseName'")
// Add top-level members to force generation of the *.kotlin_module files for the two source sets
val mainHelloWorldKt = File(project.projectDir, "src/main/kotlin/helloWorld.kt")
mainHelloWorldKt.appendText("\nfun topLevelFun() = 1")
val deployKotlinSrcKt = File(project.projectDir, "src/deploy/kotlin/kotlinSrc.kt")
deployKotlinSrcKt.appendText("\nfun topLevelFun() = 1")
project.build("build", "deployClasses") {
assertSuccessful()
// Main source set should have a *.kotlin_module file without '_main'
assertFileExists(kotlinClassesDir() + "META-INF/$archivesBaseName.kotlin_module")
assertFileExists(kotlinClassesDir(sourceSet = "deploy") + "META-INF/${archivesBaseName}_deploy.kotlin_module")
}
}
@Test
fun testJavaPackagePrefix() {
val project = Project("javaPackagePrefix")
project.build("build") {
assertSuccessful()
// Check that the Java source in a non-full-depth package structure was located correctly:
checkBytecodeContains(
File(project.projectDir, kotlinClassesDir() + "my/pack/name/app/MyApp.class"),
"my/pack/name/util/JUtil.util"
)
}
}
@Test
fun testSrcDirTaskDependency() {
Project("simpleProject").apply {
setupWorkingDir()
File(projectDir, "build.gradle").appendText(
"""${'\n'}
task generateSources {
outputs.dir('generated')
doLast {
def file = new File('generated/test/TestClass.java')
file.parentFile.mkdirs()
file.text = ""${'"'}
package test;
public class TestClass { }
""${'"'}
}
}
sourceSets.main.java.srcDir(tasks.generateSources)
""".trimIndent()
)
File(projectDir, "src/main/kotlin/helloWorld.kt").appendText(
"""${'\n'}
fun usageOfGeneratedSource() = test.TestClass()
""".trimIndent()
)
build("build") {
assertSuccessful()
}
}
}
@Test
fun testSourceJar() {
Project("simpleProject").apply {
setupWorkingDir()
val additionalSrcDir = "src/additional/kotlin/"
File(projectDir, additionalSrcDir).mkdirs()
File(projectDir, "$additionalSrcDir/additionalSource.kt").writeText("fun hello() = 123")
File(projectDir, "build.gradle").appendText(
"""${'\n'}
task sourcesJar(type: Jar) {
from sourceSets.main.allSource
classifier 'source'
duplicatesStrategy = 'fail' // fail in case of Java source duplication, see KT-17564
}
sourceSets.main.kotlin.srcDir('$additionalSrcDir') // test that additional srcDir is included
""".trimIndent()
)
build("sourcesJar") {
assertSuccessful()
val sourcesJar = ZipFile(File(projectDir, "build/libs/simpleProject-source.jar"))
assertNotNull(sourcesJar.getEntry("additionalSource.kt"))
}
}
}
@Test
fun testNoUnnamedInputsOutputs() {
// Use a new Gradle version to enable the usage of the input/output builders, which are new API:
val gradleVersionRequirement = GradleVersionRequired.AtLeast("4.4")
val projects = listOf(
Project("simpleProject", gradleVersionRequirement),
Project("kotlin2JsProject", gradleVersionRequirement),
Project("multiplatformProject", gradleVersionRequirement),
Project("simple", gradleVersionRequirement, "kapt2")
)
projects.forEach {
it.apply {
// Enable caching to make sure Gradle reports the task inputs/outputs during key construction:
val options = defaultBuildOptions().copy(withBuildCache = true)
build("assemble", options = options) {
// Check that all inputs/outputs added at runtime have proper names
// (the unnamed ones are listed as $1, $2 etc.):
assertNotContains("Appending inputPropertyHash for '\\$\\d+'".toRegex())
assertNotContains("Appending outputPropertyName to build cache key: \\$\\d+".toRegex())
}
}
}
}
@Test
fun testModuleNameFiltering() = with(Project("typeAlias")) { // Use a Project with a top-level typealias
setupWorkingDir()
gradleBuildScript().appendText("\n" + """archivesBaseName = 'a/really\\tricky\n\rmodule\tname'""")
build("classes") {
assertSuccessful()
val metaInfDir = File(projectDir, kotlinClassesDir() + "META-INF")
assertNotNull(metaInfDir.listFiles().singleOrNull { it.name.endsWith(".kotlin_module") })
}
}
@Test
fun testJavaIcCompatibility() {
val project = Project("kotlinJavaProject")
project.setupWorkingDir()
val buildScript = File(project.projectDir, "build.gradle")
buildScript.modify { "$it\n" + "compileJava.options.incremental = true" }
project.build("build") {
assertSuccessful()
}
// Then modify a Java source and check that compileJava is incremental:
File(project.projectDir, "src/main/java/demo/HelloWorld.java").modify { "$it\n" + "class NewClass { }" }
project.build("build") {
assertSuccessful()
assertContains("Incremental compilation")
assertNotContains("not incremental")
}
// Then modify a Kotlin source and check that Gradle sees that Java is not up-to-date:
File(project.projectDir, "src/main/kotlin/helloWorld.kt").modify {
it.trim('\r', '\n').trimEnd('}') + "\nval z: Int = 0 }"
}
project.build("build") {
assertSuccessful()
assertTasksExecuted(":compileKotlin", ":compileJava")
assertNotContains("not incremental")
assertNotContains("None of the classes needs to be compiled!")
}
}
@Test
fun testApplyPluginFromBuildSrc() {
val project = Project("kotlinProjectWithBuildSrc")
project.setupWorkingDir()
File(project.projectDir, "buildSrc/build.gradle").modify { it.replace("\$kotlin_version", KOTLIN_VERSION) }
project.build("build") {
assertSuccessful()
}
}
@Test
fun testInternalTest() {
Project("internalTest").build("build") {
assertSuccessful()
assertReportExists()
assertTasksExecuted(":compileKotlin", ":compileTestKotlin")
}
}
@Test
fun testJavaLibraryCompatibility() {
val project = Project("javaLibraryProject")
val compileKotlinTasks = listOf(":libA:compileKotlin", ":libB:compileKotlin", ":app:compileKotlin")
project.build("build") {
assertSuccessful()
assertNotContains("Could not register Kotlin output")
assertTasksExecuted(compileKotlinTasks)
}
// Modify a library source and its usage and re-build the project:
for (path in listOf("libA/src/main/kotlin/HelloA.kt", "libB/src/main/kotlin/HelloB.kt", "app/src/main/kotlin/App.kt")) {
File(project.projectDir, path).modify { original ->
original.replace("helloA", "helloA1")
.replace("helloB", "helloB1")
.apply { assert(!equals(original)) }
}
}
project.build("build") {
assertSuccessful()
assertNotContains("Could not register Kotlin output")
assertTasksExecuted(compileKotlinTasks)
}
}
@Test
fun testKotlinSourceInJavaSourceSet() = with(Project("multiplatformProject")) {
setupWorkingDir()
val srcDirPrefix = "srcDir: "
gradleBuildScript().appendText(
"\n" + """
subprojects { project ->
project.afterEvaluate {
project.sourceSets.each { sourceSet ->
sourceSet.allJava.srcDirs.each { srcDir ->
println "$srcDirPrefix" + srcDir.canonicalPath
}
}
}
}
""".trimIndent()
)
val srcDirRegex = "$srcDirPrefix(.*)".toRegex()
build("help") {
assertSuccessful()
val reportedSrcDirs = srcDirRegex.findAll(output).map { it.groupValues[1] }.toSet()
val expectedKotlinDirs = listOf("lib", "libJvm", "libJs").flatMap { module ->
listOf("main", "test").map { sourceSet ->
projectDir.resolve("$module/src/$sourceSet/kotlin").absolutePath
}
}
expectedKotlinDirs.forEach { assertTrue(it in reportedSrcDirs, "$it should be included into the Java source sets") }
}
}
@Test
fun testDefaultKotlinVersionIsNotAffectedByTransitiveDependencies() =
with(Project("simpleProject", GradleVersionRequired.AtLeast("4.4"))) {
setupWorkingDir()
// Add a dependency with an explicit lower Kotlin version that has a kotlin-stdlib transitive dependency:
gradleBuildScript().appendText("\ndependencies { compile 'org.jetbrains.kotlin:kotlin-reflect:1.2.71' }")
testResolveAllConfigurations {
assertSuccessful()
assertContains(">> :compile --> kotlin-reflect-1.2.71.jar")
// Check that the default newer Kotlin version still wins for 'kotlin-stdlib':
assertContains(">> :compile --> kotlin-stdlib-${defaultBuildOptions().kotlinVersion}.jar")
}
}
@Test
fun testKotlinJvmProjectPublishesKotlinApiDependenciesAsCompile() =
with(Project("simpleProject", GradleVersionRequired.AtLeast("4.4"))) {
setupWorkingDir()
gradleBuildScript().appendText(
"\n" + """
dependencies {
api 'org.jetbrains.kotlin:kotlin-reflect'
}
apply plugin: 'maven-publish'
group "com.example"
version "1.0"
publishing {
repositories { maven { url file("${'$'}buildDir/repo").toURI() } }
publications { maven(MavenPublication) { from components.java } }
}
""".trimIndent()
)
build("publish") {
assertSuccessful()
val pomText = projectDir.resolve("build/repo/com/example/simpleProject/1.0/simpleProject-1.0.pom").readText()
.replace("\\s+|\\n".toRegex(), "")
assertTrue {
pomText.contains(
"<groupId>org.jetbrains.kotlin</groupId>" +
"<artifactId>kotlin-reflect</artifactId>" +
"<version>${defaultBuildOptions().kotlinVersion}</version>" +
"<scope>compile</scope>"
)
}
}
}
@Test
fun testNoTaskConfigurationForcing() {
val gradleVersionRequirement = GradleVersionRequired.AtLeast("4.9")
val projects = listOf(
Project("simpleProject", gradleVersionRequirement),
Project("kotlin2JsNoOutputFileProject", gradleVersionRequirement),
Project("sample-app", gradleVersionRequirement, "new-mpp-lib-and-app")
)
projects.forEach {
it.apply {
setupWorkingDir()
val taskConfigureFlag = "Configured the task!"
gradleBuildScript().appendText("\n" + """
tasks.register("myTask") { println '$taskConfigureFlag' }
""".trimIndent())
build("help") {
assertSuccessful()
assertNotContains(taskConfigureFlag)
}
}
}
}
}
| 34 | null | 4980 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 29,309 | kotlin | Apache License 2.0 |
page/src/main/java/com/halcyonmobile/page/db/ValueToKeyMapper.kt | halcyonmobile | 210,580,287 | false | {"Kotlin": 152162} | /*
* Copyright (c) 2020 Halcyon Mobile.
* https://www.halcyonmobile.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.halcyonmobile.page.db
/**
* An abstract implementation of [KeyLocalStorage] which assumes the page [Key] can be extracted from the last data value.
*/
abstract class ValueToKeyMapper<Key, Value> : KeyLocalStorage<Key, Value> {
private var didReachEnd = false
final override fun cache(key: KeyOrEndOfList<Key>, callback: () -> Unit) {
didReachEnd = key is KeyOrEndOfList.EndReached
callback()
}
final override fun getKey(value: Value, callback: (KeyOrEndOfList<Key>) -> Unit) {
if (didReachEnd) {
callback(KeyOrEndOfList.EndReached())
} else {
callback(KeyOrEndOfList.Key(mapValueToKey(value)))
}
}
/**
* Extracts the [Key] from the [value]
*/
abstract fun mapValueToKey(value: Value): Key
}
inline fun <Key, Value> ValueToKeyMapper(crossinline valueToKey: (Value) -> Key): ValueToKeyMapper<Key, Value> =
object : ValueToKeyMapper<Key, Value>() {
override fun mapValueToKey(value: Value): Key = valueToKey(value)
} | 15 | Kotlin | 0 | 1 | 269dd83f85431a628a4ff4f5845046b3ef8984e6 | 1,690 | page-extension | Apache License 2.0 |
features/masterpassword/masterPasswordDomain/src/commonMain/kotlin/io/spherelabs/masterpassworddomain/IsPasswordExist.kt | getspherelabs | 687,455,894 | false | {"Kotlin": 499164, "Ruby": 6984, "Swift": 1167, "Shell": 226} | package io.spherelabs.masterpassworddomain
import io.spherelabs.data.settings.masterpassword.MasterPasswordSetting
interface IsPasswordExist {
suspend fun execute(): Boolean
}
class DefaultIsPasswordExist(private val prefs: MasterPasswordSetting) : IsPasswordExist {
override suspend fun execute(): Boolean {
return prefs.isPasswordExist()
}
}
| 19 | Kotlin | 13 | 90 | 696fbe6f9c4ff9e8a88492a193d6cb080df41ed6 | 357 | anypass-kmp | Apache License 2.0 |
github-integration/src/test/java/de/zalando/zally/integration/mock/EmbeddedPostgresqlConfiguration.kt | hpdang | 148,153,657 | true | null | package de.zalando.zally.integration.mock
import org.springframework.boot.SpringBootConfiguration
import org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.DependsOn
@SpringBootConfiguration
@Configuration
class EmbeddedPostgresqlConfiguration {
@DependsOn("postgresqlMock")
@Bean
fun migrationStrategy(): FlywayMigrationStrategy {
return FlywayMigrationStrategy { it.migrate() }
}
@Bean
fun postgresqlMock(): PostgresqlMock {
return PostgresqlMock()
}
} | 0 | Kotlin | 0 | 415 | 91bc7341a5b8d9a65bc67e8ca680b6c423d6c684 | 678 | zally | MIT License |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/shield/CfnProtectionDsl.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 70198112} | @file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.shield
import io.cloudshiftdev.awscdkdsl.CfnTagDsl
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import kotlin.String
import kotlin.Unit
import kotlin.collections.Collection
import kotlin.collections.MutableList
import software.amazon.awscdk.CfnTag
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.shield.CfnProtection
import software.constructs.Construct
/**
* Enables AWS Shield Advanced for a specific AWS resource.
*
* The resource can be an Amazon CloudFront distribution, Amazon Route 53 hosted zone, AWS Global
* Accelerator standard accelerator, Elastic IP Address, Application Load Balancer, or a Classic
* Load Balancer. You can protect Amazon EC2 instances and Network Load Balancers by association
* with protected Amazon EC2 Elastic IP addresses.
*
* *Configure a single `AWS::Shield::Protection`*
*
* Use this protection to protect a single resource at a time.
*
* To configure this Shield Advanced protection through AWS CloudFormation , you must be subscribed
* to Shield Advanced . You can subscribe through the
* [Shield Advanced console](https://docs.aws.amazon.com/wafv2/shieldv2#/) and through the APIs. For
* more information, see
* [Subscribe to AWS Shield Advanced](https://docs.aws.amazon.com/waf/latest/developerguide/enable-ddos-prem.html)
* .
*
* See example templates for Shield Advanced in AWS CloudFormation at
* [aws-samples/aws-shield-advanced-examples](https://docs.aws.amazon.com/https://github.com/aws-samples/aws-shield-advanced-examples)
* .
*
* *Configure Shield Advanced using AWS CloudFormation and AWS Firewall Manager*
*
* You might be able to use Firewall Manager with AWS CloudFormation to configure Shield Advanced
* across multiple accounts and protected resources. To do this, your accounts must be part of an
* organization in AWS Organizations . You can use Firewall Manager to configure Shield Advanced
* protections for any resource types except for Amazon Route 53 or AWS Global Accelerator .
*
* For an example of this, see the one-click configuration guidance published by the AWS technical
* community at
* [One-click deployment of Shield Advanced](https://docs.aws.amazon.com/https://youtu.be/LCA3FwMk_QE)
* .
*
* *Configure multiple protections through the Shield Advanced console*
*
* You can add protection to multiple resources at once through the
* [Shield Advanced console](https://docs.aws.amazon.com/wafv2/shieldv2#/) . For more information
* see
* [Getting Started with AWS Shield Advanced](https://docs.aws.amazon.com/waf/latest/developerguide/getting-started-ddos.html)
* and
* [Managing resource protections in AWS Shield Advanced](https://docs.aws.amazon.com/waf/latest/developerguide/ddos-manage-protected-resources.html)
* .
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.shield.*;
* Object block;
* Object count;
* CfnProtection cfnProtection = CfnProtection.Builder.create(this, "MyCfnProtection")
* .name("name")
* .resourceArn("resourceArn")
* // the properties below are optional
* .applicationLayerAutomaticResponseConfiguration(ApplicationLayerAutomaticResponseConfigurationProperty.builder()
* .action(ActionProperty.builder()
* .block(block)
* .count(count)
* .build())
* .status("status")
* .build())
* .healthCheckArns(List.of("healthCheckArns"))
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-shield-protection.html)
*/
@CdkDslMarker
public class CfnProtectionDsl(
scope: Construct,
id: String,
) {
private val cdkBuilder: CfnProtection.Builder = CfnProtection.Builder.create(scope, id)
private val _healthCheckArns: MutableList<String> = mutableListOf()
private val _tags: MutableList<CfnTag> = mutableListOf()
/**
* The automatic application layer DDoS mitigation settings for the protection.
*
* This configuration determines whether Shield Advanced automatically manages rules in the web
* ACL in order to respond to application layer events that Shield Advanced determines to be
* DDoS attacks.
*
* If you use AWS CloudFormation to manage the web ACLs that you use with Shield Advanced
* automatic mitigation, see the additional guidance about web ACL management in the
* `AWS::WAFv2::WebACL` resource description.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-shield-protection.html#cfn-shield-protection-applicationlayerautomaticresponseconfiguration)
*
* @param applicationLayerAutomaticResponseConfiguration The automatic application layer DDoS
* mitigation settings for the protection.
*/
public fun applicationLayerAutomaticResponseConfiguration(
applicationLayerAutomaticResponseConfiguration: IResolvable
) {
cdkBuilder.applicationLayerAutomaticResponseConfiguration(
applicationLayerAutomaticResponseConfiguration
)
}
/**
* The automatic application layer DDoS mitigation settings for the protection.
*
* This configuration determines whether Shield Advanced automatically manages rules in the web
* ACL in order to respond to application layer events that Shield Advanced determines to be
* DDoS attacks.
*
* If you use AWS CloudFormation to manage the web ACLs that you use with Shield Advanced
* automatic mitigation, see the additional guidance about web ACL management in the
* `AWS::WAFv2::WebACL` resource description.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-shield-protection.html#cfn-shield-protection-applicationlayerautomaticresponseconfiguration)
*
* @param applicationLayerAutomaticResponseConfiguration The automatic application layer DDoS
* mitigation settings for the protection.
*/
public fun applicationLayerAutomaticResponseConfiguration(
applicationLayerAutomaticResponseConfiguration:
CfnProtection.ApplicationLayerAutomaticResponseConfigurationProperty
) {
cdkBuilder.applicationLayerAutomaticResponseConfiguration(
applicationLayerAutomaticResponseConfiguration
)
}
/**
* The ARN (Amazon Resource Name) of the health check to associate with the protection.
*
* Health-based detection provides improved responsiveness and accuracy in attack detection and
* mitigation.
*
* You can use this option with any resource type except for Route 53 hosted zones.
*
* For more information, see
* [Configuring health-based detection using health checks](https://docs.aws.amazon.com/waf/latest/developerguide/ddos-advanced-health-checks.html)
* in the *AWS Shield Advanced Developer Guide* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-shield-protection.html#cfn-shield-protection-healthcheckarns)
*
* @param healthCheckArns The ARN (Amazon Resource Name) of the health check to associate with
* the protection.
*/
public fun healthCheckArns(vararg healthCheckArns: String) {
_healthCheckArns.addAll(listOf(*healthCheckArns))
}
/**
* The ARN (Amazon Resource Name) of the health check to associate with the protection.
*
* Health-based detection provides improved responsiveness and accuracy in attack detection and
* mitigation.
*
* You can use this option with any resource type except for Route 53 hosted zones.
*
* For more information, see
* [Configuring health-based detection using health checks](https://docs.aws.amazon.com/waf/latest/developerguide/ddos-advanced-health-checks.html)
* in the *AWS Shield Advanced Developer Guide* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-shield-protection.html#cfn-shield-protection-healthcheckarns)
*
* @param healthCheckArns The ARN (Amazon Resource Name) of the health check to associate with
* the protection.
*/
public fun healthCheckArns(healthCheckArns: Collection<String>) {
_healthCheckArns.addAll(healthCheckArns)
}
/**
* The name of the protection. For example, `My CloudFront distributions` .
*
* If you change the name of an existing protection, Shield Advanced deletes the protection and
* replaces it with a new one. While this is happening, the protection isn't available on the
* AWS resource.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-shield-protection.html#cfn-shield-protection-name)
*
* @param name The name of the protection. For example, `My CloudFront distributions` .
*/
public fun name(name: String) {
cdkBuilder.name(name)
}
/**
* The ARN (Amazon Resource Name) of the AWS resource that is protected.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-shield-protection.html#cfn-shield-protection-resourcearn)
*
* @param resourceArn The ARN (Amazon Resource Name) of the AWS resource that is protected.
*/
public fun resourceArn(resourceArn: String) {
cdkBuilder.resourceArn(resourceArn)
}
/**
* Key:value pairs associated with an AWS resource.
*
* The key:value pair can be anything you define. Typically, the tag key represents a category
* (such as "environment") and the tag value represents a specific value within that category
* (such as "test," "development," or "production"). You can add up to 50 tags to each AWS
* resource.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-shield-protection.html#cfn-shield-protection-tags)
*
* @param tags Key:value pairs associated with an AWS resource.
*/
public fun tags(tags: CfnTagDsl.() -> Unit) {
_tags.add(CfnTagDsl().apply(tags).build())
}
/**
* Key:value pairs associated with an AWS resource.
*
* The key:value pair can be anything you define. Typically, the tag key represents a category
* (such as "environment") and the tag value represents a specific value within that category
* (such as "test," "development," or "production"). You can add up to 50 tags to each AWS
* resource.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-shield-protection.html#cfn-shield-protection-tags)
*
* @param tags Key:value pairs associated with an AWS resource.
*/
public fun tags(tags: Collection<CfnTag>) {
_tags.addAll(tags)
}
public fun build(): CfnProtection {
if (_healthCheckArns.isNotEmpty()) cdkBuilder.healthCheckArns(_healthCheckArns)
if (_tags.isNotEmpty()) cdkBuilder.tags(_tags)
return cdkBuilder.build()
}
}
| 0 | Kotlin | 0 | 3 | 256ad92aebe2bcf9a4160089a02c76809dbbedba | 11,506 | awscdk-dsl-kotlin | Apache License 2.0 |
buildSrc/src/main/kotlin/Dependencies.kt | Burdzi0 | 326,246,930 | true | {"Kotlin": 224609, "Shell": 304} |
object Libs {
const val kotlin_version = "1.4.21"
const val liquibase_version="3.6.1"
const val h2_version="1.4.193"
object H2 {
private const val version = "1.4.193"
const val h2 = "com.h2database:h2:$version"
}
object Kotlin {
const val kotlinStdLib = "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
private const val coroutinesVersion = "1.4.1"
const val coroutinesJdk8 = "org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:$coroutinesVersion"
}
object Ktor {
private const val version = "1.4.3"
const val serverCore = "io.ktor:ktor-server-core:$version"
const val clientCore = "io.ktor:ktor-client-core:$version"
const val clientMockJvm = "io.ktor:ktor-client-mock-jvm:$version"
const val clientJsonJvm = "io.ktor:ktor-client-json-jvm:$version"
const val clientJson = "io.ktor:ktor-client-json:$version"
const val clientJackson = "io.ktor:ktor-client-jackson:$version"
const val jackson = "io.ktor:ktor-jackson:$version"
const val serverTestHost ="io.ktor:ktor-server-test-host:$version"
}
object Vavr {
private const val version = "0.10.2"
const val kotlin = "io.vavr:vavr-kotlin:$version"
const val jackson = "io.vavr:vavr-jackson:$version"
}
object Haste {
private const val version = "0.3.1"
const val haste = "io.github.krasnoludkolo:haste:$version"
}
object Jackson {
private const val version = "2.11.3"
const val jacksonModuleKotlin = "com.fasterxml.jackson.module:jackson-module-kotlin:$version"
const val jacksonAnnotations = "com.fasterxml.jackson.core:jackson-annotations:$version"
}
object Kotest {
private const val version = "4.3.1"
const val runnerJunit5Jvm ="io.kotest:kotest-runner-junit5-jvm:$version"
const val assertionsCoreJvm = "io.kotest:kotest-assertions-core-jvm:$version"
//const val runnerConsoleJvm = "io.kotest:kotest-runner-console-jvm:${consoleVersion}"
}
object Slf4J {
private const val version = "1.7.28"
const val api = "org.slf4j:slf4j-api:$version"
}
object Liquibase {
private const val version = "3.6.1"
const val core = "org.liquibase:liquibase-core:$version"
}
}
| 0 | null | 0 | 0 | 6d40e6c9a54a9ebb90217603e0d8e37d886e1884 | 2,346 | nee | Apache License 2.0 |
src/main/kotlin/com/aoverin/invest/InvestApplication.kt | a-overin | 776,842,962 | false | {"Kotlin": 29524, "Procfile": 81} | package com.aoverin.invest
import com.aoverin.invest.configurations.CostFillConfiguration
import com.aoverin.invest.configurations.InfoFillConfiguration
import com.aoverin.invest.configurations.PolygonApiProperties
import com.aoverin.invest.configurations.TelegramBotProperties
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.boot.runApplication
import org.springframework.scheduling.annotation.EnableScheduling
@EnableScheduling
@EnableConfigurationProperties(
PolygonApiProperties::class,
InfoFillConfiguration::class,
CostFillConfiguration::class,
TelegramBotProperties::class,
)
@SpringBootApplication
class InvestApplication
fun main(args: Array<String>) {
runApplication<InvestApplication>(*args)
}
| 0 | Kotlin | 0 | 0 | c158362f77d0f0addf999d1551064a4d8adf6b30 | 841 | invest-v2 | Apache License 2.0 |
model/src/test/java/com/razeware/emitron/model/LinksTest.kt | razeware | 192,712,585 | false | null | package com.razeware.emitron.model
import android.net.Uri
import com.google.common.truth.Truth.assertThat
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers.anyString
import org.powermock.api.mockito.PowerMockito
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
@PrepareForTest(Uri::class)
class LinksTest {
private val uri: Uri = mock()
@Before
fun setUp() {
PowerMockito.mockStatic(Uri::class.java)
PowerMockito.`when`(Uri.parse(anyString())).doReturn(uri)
}
@Test
fun getCurrentPage() {
val links = Links()
assertThat(links.getCurrentPage()).isEqualTo(0)
val link2 = Links(self = "https://rw/contents?page[number]=1")
whenever(uri.getQueryParameter("page[number]")).doReturn(1.toString())
assertThat(link2.getCurrentPage()).isEqualTo(1)
}
@Test
fun getNextPage() {
val links = Links(next = null)
assertThat(links.getNextPage()).isNull()
val links2 = Links()
assertThat(links2.getNextPage()).isNull()
val link2 = Links(
self = "https://rw/contents?page[number]=1",
next = "https://rw/contents?page[number]=2"
)
whenever(uri.getQueryParameter("page[number]")).doReturn(1.toString())
assertThat(link2.getNextPage()).isEqualTo(2)
}
}
| 30 | null | 31 | 53 | 4dcb00f09eee2ae1ff0a6c9c2e2dd141227b51c4 | 1,526 | emitron-Android | Apache License 2.0 |
kotlin-source/src/test/kotlin/net/corda/examples/obligation/flows/ObligationTests.kt | R3-Archive | 123,595,560 | false | null | package net.corda.examples.obligation.flows
import net.corda.core.contracts.Amount
import net.corda.core.contracts.UniqueIdentifier
import net.corda.core.utilities.OpaqueBytes
import net.corda.core.utilities.getOrThrow
import net.corda.finance.flows.CashIssueFlow
import net.corda.testing.internal.chooseIdentity
import net.corda.testing.node.MockNetwork
import net.corda.testing.node.StartedMockNode
import org.junit.After
import org.junit.Before
import java.util.*
/**
* A base class to reduce the boilerplate when writing obligation flow tests.
*/
abstract class ObligationTests {
lateinit var network: MockNetwork
lateinit var a: StartedMockNode
lateinit var b: StartedMockNode
lateinit var c: StartedMockNode
@Before
fun setup() {
network = MockNetwork(listOf("net.corda.examples.obligation", "net.corda.finance", "net.corda.finance.schemas"), threadPerNode = true)
a = network.createNode()
b = network.createNode()
c = network.createNode()
val nodes = listOf(a, b, c)
nodes.forEach {
it.registerInitiatedFlow(IssueObligation.Responder::class.java)
it.registerInitiatedFlow(TransferObligation.Responder::class.java)
it.registerInitiatedFlow(IdentitySyncFlowWrapper.Receive::class.java)
}
}
@After
fun tearDown() {
network.stopNodes()
}
protected fun issueObligation(borrower: StartedMockNode,
lender: StartedMockNode,
amount: Amount<Currency>,
anonymous: Boolean = true
): net.corda.core.transactions.SignedTransaction {
val lenderIdentity = lender.info.chooseIdentity()
val flow = IssueObligation.Initiator(amount, lenderIdentity, anonymous)
return borrower.startFlow(flow).getOrThrow()
}
protected fun transferObligation(linearId: UniqueIdentifier,
lender: StartedMockNode,
newLender: StartedMockNode,
anonymous: Boolean = true
): net.corda.core.transactions.SignedTransaction {
val newLenderIdentity = newLender.info.chooseIdentity()
val flow = TransferObligation.Initiator(linearId, newLenderIdentity, anonymous)
return lender.startFlow(flow).getOrThrow()
}
protected fun settleObligation(linearId: UniqueIdentifier,
borrower: StartedMockNode,
amount: Amount<Currency>,
anonymous: Boolean = true
): net.corda.core.transactions.SignedTransaction {
val flow = SettleObligation.Initiator(linearId, amount, anonymous)
return borrower.startFlow(flow).getOrThrow()
}
protected fun selfIssueCash(party: StartedMockNode,
amount: Amount<Currency>): net.corda.core.transactions.SignedTransaction {
val notary = party.services.networkMapCache.notaryIdentities.firstOrNull()
?: throw IllegalStateException("Could not find a notary.")
val issueRef = OpaqueBytes.of(0)
val issueRequest = CashIssueFlow.IssueRequest(amount, issueRef, notary)
val flow = CashIssueFlow(issueRequest)
return party.startFlow(flow).getOrThrow().stx
}
}
| 2 | null | 14 | 5 | aeec37e400ff62e201f51ef99059a64a527ff7d3 | 3,391 | obligation-cordapp | Apache License 2.0 |
app/src/main/java/com/example/spygamers/screens/register/ConfirmPasswordTextField.kt | Juicy-Lemonberry | 748,985,682 | false | {"Kotlin": 257724} | package com.example.spygamers.screens.register
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
@Composable
internal fun ConfirmPasswordTextField(
password: MutableState<String>,
message: MutableState<String>,
validationFun: (confirmPass: String) -> Boolean = { false }
) {
TextField(
value = password.value,
onValueChange = {
password.value = it
if (!validationFun(password.value)) {
message.value = "Passwords don't match"
} else {
message.value = ""
}
},
isError = !validationFun(password.value),
label = { Text("Confirm Password") },
placeholder = { Text(text = "Re-enter password") },
visualTransformation = PasswordVisualTransformation(),
modifier = Modifier
.width(300.dp)
.padding(bottom = 8.dp)
.clip(shape = RoundedCornerShape(15.dp, 15.dp, 15.dp, 15.dp))
)
} | 3 | Kotlin | 2 | 1 | 9512696751a6c7dc5e0361f43b3b08097208ea42 | 1,425 | SpyGamers-App | MIT License |
src/main/kotlin/core/component/render/MultiSpriteAnimationComponent.kt | nflsilva | 521,306,727 | false | {"Kotlin": 72548, "GLSL": 3784} | package core.component.render
import core.BaseEntity
import core.component.BaseComponent
import core.dto.UpdateContext
import render.model.MultiSprite
import java.util.*
class MultiSpriteAnimationComponent(
entityId: UUID,
private val loop: Boolean = true,
) : BaseComponent(entityId) {
private data class AnimationKeyframe(
val multiSprite: MultiSprite,
val duration: Double
)
var completedState: Boolean = false
private var currentState: String? = null
private var currentKeyframeIndex: Int = 0
private var currentKeyframeElapsedTime: Double = 0.0
private val keyframesByState: MutableMap<String, MutableList<AnimationKeyframe>> = mutableMapOf()
init {
setUpdateObserver { entity, context -> onUpdate(entity, context) }
}
private fun onUpdate(entity: BaseEntity, context: UpdateContext) {
if(!completedState || loop) {
if (currentState == null) return
val currentStateKeyframes = keyframesByState[currentState] ?: return
val currentKeyframe = currentStateKeyframes[currentKeyframeIndex]
context.graphics.render(currentKeyframe.multiSprite, entity.transform)
currentKeyframeElapsedTime += context.elapsedTime
if (currentKeyframe.duration < currentKeyframeElapsedTime) {
currentKeyframeIndex++
currentKeyframeElapsedTime = 0.0
}
if(currentKeyframeIndex == currentStateKeyframes.size){
currentKeyframeIndex = 0
completedState = true
}
}
}
fun addAnimationKeyframe(state: String,
multiSprite: MultiSprite,
duration: Double) {
if (state !in keyframesByState.keys) {
keyframesByState[state] = mutableListOf()
}
keyframesByState[state]?.add(AnimationKeyframe(multiSprite, duration))
}
fun setState(state: String) {
currentState = state
currentKeyframeIndex = 0
completedState = false
}
} | 0 | Kotlin | 0 | 0 | 5047a234767efda80c0afec990bf27aec5b8effd | 2,095 | 2DGT | MIT License |
data/src/main/java/com/m3u/data/service/impl/PlayerManagerImpl.kt | realOxy | 592,741,804 | false | {"Kotlin": 532650} | package com.m3u.data.service.impl
import android.content.Context
import android.graphics.Rect
import androidx.annotation.OptIn
import androidx.compose.runtime.getValue
import androidx.media3.common.AudioAttributes
import androidx.media3.common.C
import androidx.media3.common.MediaItem
import androidx.media3.common.PlaybackException
import androidx.media3.common.Player
import androidx.media3.common.VideoSize
import androidx.media3.common.util.UnstableApi
import androidx.media3.datasource.DefaultDataSource
import androidx.media3.datasource.okhttp.OkHttpDataSource
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
import androidx.media3.exoplayer.trackselection.DefaultTrackSelector
import androidx.media3.session.MediaSession
import com.m3u.core.architecture.configuration.Configuration
import com.m3u.core.architecture.configuration.ExperimentalConfiguration
import com.m3u.data.contract.Certs
import com.m3u.data.contract.SSL
import com.m3u.data.service.PlayerManager
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import okhttp3.OkHttpClient
import javax.inject.Inject
@OptIn(UnstableApi::class)
@kotlin.OptIn(ExperimentalConfiguration::class)
class PlayerManagerImpl @Inject constructor(
@ApplicationContext private val context: Context,
configuration: Configuration
) : PlayerManager(), Player.Listener, MediaSession.Callback {
private val playerFlow = MutableStateFlow<Player?>(null)
private val player: Player? get() = playerFlow.value
private val isSSLVerification by configuration.isSSLVerification
private val okHttpClient by lazy {
OkHttpClient.Builder()
.sslSocketFactory(SSL.TLSTrustAll.socketFactory, Certs.TrustAll)
.hostnameVerifier { _, _ -> true }
.build()
}
override fun observe(): Flow<Player?> = playerFlow.asStateFlow()
override fun initialize() {
playerFlow.value = ExoPlayer.Builder(context)
.let {
if (isSSLVerification) it
else it.setMediaSourceFactory(
DefaultMediaSourceFactory(context).setDataSourceFactory(
DefaultDataSource.Factory(
context,
OkHttpDataSource.Factory(okHttpClient)
)
)
)
}
.setTrackSelector(
DefaultTrackSelector(context).apply {
setParameters(buildUponParameters().setMaxVideoSizeSd())
}
)
.build()
.apply {
val attributes = AudioAttributes.Builder()
.setUsage(C.USAGE_MEDIA)
.setContentType(C.AUDIO_CONTENT_TYPE_MOVIE)
.build()
setAudioAttributes(attributes, true)
playWhenReady = true
}
}
override fun install(url: String) {
player?.let {
it.addListener(this)
val mediaItem = MediaItem.fromUri(url)
it.setMediaItem(mediaItem)
it.prepare()
}
}
override fun uninstall() {
player?.let {
it.removeListener(this)
it.stop()
}
super.mutablePlaybackState.value = Player.STATE_IDLE
super.mutablePlaybackError.value = null
super.mutableVideoSize.value = Rect()
}
override fun onVideoSizeChanged(size: VideoSize) {
super.onVideoSizeChanged(size)
super.mutableVideoSize.value = Rect(0, 0, size.width, size.height)
}
override fun onPlaybackStateChanged(state: Int) {
super.onPlaybackStateChanged(state)
super.mutablePlaybackState.value = state
}
override fun onPlayerErrorChanged(error: PlaybackException?) {
super.onPlayerErrorChanged(error)
when (error?.errorCode) {
PlaybackException.ERROR_CODE_BEHIND_LIVE_WINDOW -> {
player?.let {
it.seekToDefaultPosition()
it.prepare()
}
}
else -> {}
}
super.mutablePlaybackError.value = error
}
} | 2 | Kotlin | 6 | 49 | 789adbe85d6ad8ab2003b147c2dea5fbdbf46d72 | 4,356 | M3UAndroid | Apache License 2.0 |
src/main/kotlin/io/github/intellij/dlanguage/features/documentation/DDocParserDefinition.kt | intellij-dlanguage | 27,922,930 | false | null | package io.github.intellij.dlanguage.features.documentation
import com.intellij.lang.ASTNode
import com.intellij.lang.ParserDefinition
import com.intellij.lang.PsiParser
import com.intellij.lexer.Lexer
import com.intellij.openapi.project.Project
import com.intellij.psi.FileViewProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.tree.IFileElementType
import com.intellij.psi.tree.TokenSet
import io.github.intellij.dlanguage.features.documentation.DDocElementTypes.DDOC_ANONYMOUS_SECTION
import io.github.intellij.dlanguage.features.documentation.DDocElementTypes.DDOC_AUTHORS_SECTION
import io.github.intellij.dlanguage.features.documentation.DDocElementTypes.DDOC_BUGS_SECTION
import io.github.intellij.dlanguage.features.documentation.DDocElementTypes.DDOC_COPYRIGHT_SECTION
import io.github.intellij.dlanguage.features.documentation.DDocElementTypes.DDOC_DATE_SECTION
import io.github.intellij.dlanguage.features.documentation.DDocElementTypes.DDOC_DEPRECATED_SECTION
import io.github.intellij.dlanguage.features.documentation.DDocElementTypes.DDOC_DESCRIPTION_SECTION
import io.github.intellij.dlanguage.features.documentation.DDocElementTypes.DDOC_EXAMPLES_SECTION
import io.github.intellij.dlanguage.features.documentation.DDocElementTypes.DDOC_HISTORY_SECTION
import io.github.intellij.dlanguage.features.documentation.DDocElementTypes.DDOC_LICENSE_SECTION
import io.github.intellij.dlanguage.features.documentation.DDocElementTypes.DDOC_LINK_DECLARATION
import io.github.intellij.dlanguage.features.documentation.DDocElementTypes.DDOC_MACROS_SECTION
import io.github.intellij.dlanguage.features.documentation.DDocElementTypes.DDOC_NAMED_SECTION
import io.github.intellij.dlanguage.features.documentation.DDocElementTypes.DDOC_PARAMS_SECTION
import io.github.intellij.dlanguage.features.documentation.DDocElementTypes.DDOC_RETURNS_SECTION
import io.github.intellij.dlanguage.features.documentation.DDocElementTypes.DDOC_SEE_ALSO_SECTION
import io.github.intellij.dlanguage.features.documentation.DDocElementTypes.DDOC_STANDARDS_SECTION
import io.github.intellij.dlanguage.features.documentation.DDocElementTypes.DDOC_SUMMARY_SECTION
import io.github.intellij.dlanguage.features.documentation.DDocElementTypes.DDOC_THROWS_SECTION
import io.github.intellij.dlanguage.features.documentation.DDocElementTypes.DDOC_VERSION_SECTION
import io.github.intellij.dlanguage.features.documentation.psi.impl.*
import io.github.intellij.dlanguage.psi.DlangFile
class DDocParserDefinition : ParserDefinition {
override fun createLexer(project: Project?): Lexer = DDocLexer()
override fun createParser(project: Project?): PsiParser = DDocParser()
override fun getFileNodeType(): IFileElementType = IFileElementType(DDocLanguage)
override fun getCommentTokens(): TokenSet = TokenSet.EMPTY
override fun getStringLiteralElements(): TokenSet = TokenSet.EMPTY
override fun createElement(node: ASTNode): PsiElement {
return when(node.elementType) {
DDOC_ANONYMOUS_SECTION -> DDocAnonymousSectionImpl(node)
DDOC_NAMED_SECTION -> DDocNamedSectionImpl(node)
DDOC_SUMMARY_SECTION -> DDocSummarySectionImpl(node)
DDOC_DESCRIPTION_SECTION -> DDocDescriptionSectionImpl(node)
DDOC_AUTHORS_SECTION -> DDocNamedSectionImpl(node)
DDOC_BUGS_SECTION -> DDocNamedSectionImpl(node)
DDOC_DATE_SECTION -> DDocNamedSectionImpl(node)
DDOC_DEPRECATED_SECTION -> DDocNamedSectionImpl(node)
DDOC_EXAMPLES_SECTION -> DDocNamedSectionImpl(node)
DDOC_HISTORY_SECTION -> DDocNamedSectionImpl(node)
DDOC_LICENSE_SECTION -> DDocNamedSectionImpl(node)
DDOC_RETURNS_SECTION -> DDocNamedSectionImpl(node)
DDOC_SEE_ALSO_SECTION -> DDocNamedSectionImpl(node)
DDOC_STANDARDS_SECTION -> DDocNamedSectionImpl(node)
DDOC_THROWS_SECTION -> DDocNamedSectionImpl(node)
DDOC_VERSION_SECTION -> DDocNamedSectionImpl(node)
DDOC_COPYRIGHT_SECTION -> DDocNamedSectionImpl(node)
DDOC_PARAMS_SECTION -> DDocParamsSectionImpl(node)
DDOC_MACROS_SECTION -> DDocMacroSectionImpl(node)
DDOC_LINK_DECLARATION -> DDocLinkDeclarationImpl(node)
else -> return DlangDocPsiElementImpl(node)
}
}
override fun createFile(viewProvider: FileViewProvider): PsiFile = DlangFile(viewProvider) // TODO can actually be DDocFile (.dd)
}
| 170 | null | 53 | 328 | 298d1db45d2b35c1715a1b1b2e1c548709101f05 | 4,515 | intellij-dlanguage | MIT License |
detekt-rules-style/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/UseRequireSpec.kt | arturbosch | 71,729,669 | false | null | package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.rules.setupKotlinEnvironment
import io.gitlab.arturbosch.detekt.test.assertThat
import io.gitlab.arturbosch.detekt.test.compileAndLint
import io.gitlab.arturbosch.detekt.test.compileAndLintWithContext
import io.gitlab.arturbosch.detekt.test.lint
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
class UseRequireSpec : Spek({
setupKotlinEnvironment()
val env: KotlinCoreEnvironment by memoized()
val subject by memoized { UseRequire(Config.empty) }
describe("UseRequire rule") {
it("reports if a precondition throws an IllegalArgumentException") {
val code = """
fun x(a: Int) {
if (a < 0) throw IllegalArgumentException()
doSomething()
}"""
assertThat(subject.lint(code)).hasSourceLocation(2, 16)
}
it("reports if a precondition throws an IllegalArgumentException with more details") {
val code = """
fun x(a: Int) {
if (a < 0) throw IllegalArgumentException("More details")
doSomething()
}"""
assertThat(subject.lint(code)).hasSourceLocation(2, 16)
}
it("reports if a precondition throws a fully qualified IllegalArgumentException") {
val code = """
fun x(a: Int) {
if (a < 0) throw java.lang.IllegalArgumentException()
doSomething()
}"""
assertThat(subject.lint(code)).hasSourceLocation(2, 16)
}
it("reports if a precondition throws a fully qualified IllegalArgumentException using the kotlin type alias") {
val code = """
fun x(a: Int) {
if (a < 0) throw kotlin.IllegalArgumentException()
doSomething()
}"""
assertThat(subject.lint(code)).hasSourceLocation(2, 16)
}
it("does not report if a precondition throws a different kind of exception") {
val code = """
fun x(a: Int) {
if (a < 0) throw SomeBusinessException()
doSomething()
}"""
assertThat(subject.lint(code)).isEmpty()
}
it("does not report an issue if the exception thrown has a message and a cause") {
val code = """
private fun x(a: Int): Nothing {
doSomething()
throw IllegalArgumentException("message", cause)
}"""
assertThat(subject.lint(code)).isEmpty()
}
it("does not report an issue if the exception thrown as the only action in a block") {
val code = """
fun unsafeRunSync(): A =
foo.fold({ throw IllegalArgumentException("message") }, ::identity)"""
assertThat(subject.lint(code)).isEmpty()
}
it("does not report an issue if the exception thrown unconditionally") {
val code = """fun doThrow() = throw IllegalArgumentException("message")"""
assertThat(subject.lint(code)).isEmpty()
}
it("does not report an issue if the exception thrown unconditionally in a function block") {
val code = """fun doThrow() { throw IllegalArgumentException("message") }"""
assertThat(subject.lint(code)).isEmpty()
}
it("does not report if the exception thrown has a non-String argument") {
val code = """
fun test(throwable: Throwable) {
if (throwable !is NumberFormatException) throw IllegalArgumentException(throwable)
}
"""
assertThat(subject.compileAndLint(code)).isEmpty()
}
it("does not report if the exception thrown has a String literal argument and a non-String argument") {
val code = """
fun test(throwable: Throwable) {
if (throwable !is NumberFormatException) throw IllegalArgumentException("a", throwable)
}
"""
assertThat(subject.compileAndLint(code)).isEmpty()
}
it("does not report if the exception thrown has a non-String literal argument") {
val code = """
fun test(throwable: Throwable) {
val s = ""
if (throwable !is NumberFormatException) throw IllegalArgumentException(s)
}
"""
assertThat(subject.compileAndLint(code)).isEmpty()
}
context("with binding context") {
it("does not report if the exception thrown has a non-String argument") {
val code = """
fun test(throwable: Throwable) {
if (throwable !is NumberFormatException) throw IllegalArgumentException(throwable)
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report if the exception thrown has a String literal argument and a non-String argument") {
val code = """
fun test(throwable: Throwable) {
if (throwable !is NumberFormatException) throw IllegalArgumentException("a", throwable)
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("reports if the exception thrown has a non-String literal argument") {
val code = """
fun test(throwable: Throwable) {
val s = ""
if (throwable !is NumberFormatException) throw IllegalArgumentException(s)
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).hasSize(1)
}
it("reports if the exception thrown has a String literal argument") {
val code = """
fun test(throwable: Throwable) {
if (throwable !is NumberFormatException) throw IllegalArgumentException("a")
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).hasSize(1)
}
}
context("throw is not after a precondition") {
it("does not report an issue if the exception is inside a when") {
val code = """
fun whenOrThrow(item : List<*>) = when(item) {
is ArrayList<*> -> 1
is LinkedList<*> -> 2
else -> throw IllegalArgumentException("Not supported List type")
}
"""
assertThat(subject.lint(code)).isEmpty()
}
it("does not report an issue if the exception is after a block") {
val code = """
fun doSomethingOrThrow(test: Int): Int {
var index = 0
repeat(test){
if (Math.random() == 1.0) {
return it
}
}
throw IllegalArgumentException("Test was too big")
}"""
assertThat(subject.lint(code)).isEmpty()
}
it("does not report an issue if the exception is after a elvis operator") {
val code = """
fun tryToCastOrThrow(list: List<*>) : LinkedList<*> {
val subclass = list as? LinkedList
?: throw IllegalArgumentException("List is not a LinkedList")
return subclass
}"""
assertThat(subject.lint(code)).isEmpty()
}
}
}
})
| 125 | null | 589 | 4,331 | 6c3c28df3af8e9d8889af9f7ad39506e03af7f69 | 8,219 | detekt | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.