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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
baselineProfile/src/main/java/com/xeniac/fifaultimateteamcoin_dsfut_sell_fut/baselineprofile/StartupBenchmarks.kt | WilliamGates99 | 543,831,202 | false | {"Kotlin": 898249} | package com.xeniac.fifaultimateteamcoin_dsfut_sell_fut.baselineprofile
import androidx.benchmark.macro.CompilationMode
import androidx.benchmark.macro.StartupMode
import androidx.benchmark.macro.StartupTimingMetric
import androidx.benchmark.macro.junit4.MacrobenchmarkRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/**
* This test class benchmarks the speed of app startup.
* Run this benchmark to verify how effective a Baseline Profile is.
* It does this by comparing [CompilationMode.None], which represents the app with no Baseline Profiles optimizations,
* and [CompilationMode.Partial], which uses Baseline Profiles.
*
* Run this benchmark to see startup measurements and captured system traces for verifying
* the effectiveness of your Baseline Profiles.
* You can run it directly from Android Studio as an instrumentation test,
* or run all benchmarks for a variant, for example benchmarkRelease, with this Gradle task:
* ```
* ./gradlew :baselineprofile:connectedBenchmarkReleaseAndroidTest
* ```
*
* You should run the benchmarks on a physical device, not an Android emulator, because the
* emulator doesn't represent real world performance and shares system resources with its host.
*
* For more information, see the [Macrobenchmark documentation](https://d.android.com/macrobenchmark#create-macrobenchmark)
* and the [instrumentation arguments documentation](https://d.android.com/topic/performance/benchmarking/macrobenchmark-instrumentation-args).
**/
@RunWith(AndroidJUnit4::class)
@LargeTest
class StartupBenchmarks {
@get:Rule
val benchmarkRule = MacrobenchmarkRule()
@Test
fun startupColdCompilationModeNone() = startupColdBenchmark(CompilationMode.None())
@Test
fun startupWarmCompilationModeNone() = startupWarmBenchmark(CompilationMode.None())
@Test
fun startupHotCompilationModeNone() = startupHotBenchmark(CompilationMode.None())
@Test
fun startupColdCompilationModePartial() = startupColdBenchmark(CompilationMode.Partial())
@Test
fun startupWarmCompilationModePartial() = startupWarmBenchmark(CompilationMode.Partial())
@Test
fun startupHotCompilationModePartial() = startupHotBenchmark(CompilationMode.Partial())
private fun startupColdBenchmark(
compilationMode: CompilationMode
) = benchmarkRule.measureRepeated(
packageName = InstrumentationRegistry.getArguments().getString("targetAppId")
?: throw Exception("targetAppId not passed as instrumentation runner arg"),
metrics = listOf(StartupTimingMetric()),
compilationMode = compilationMode,
startupMode = StartupMode.COLD,
iterations = 10,
setupBlock = {
pressHome()
},
measureBlock = {
startActivityAndWait()
}
)
private fun startupWarmBenchmark(
compilationMode: CompilationMode
) = benchmarkRule.measureRepeated(
packageName = InstrumentationRegistry.getArguments().getString("targetAppId")
?: throw Exception("targetAppId not passed as instrumentation runner arg"),
metrics = listOf(StartupTimingMetric()),
compilationMode = compilationMode,
startupMode = StartupMode.WARM,
iterations = 10,
setupBlock = {
pressHome()
},
measureBlock = {
startActivityAndWait()
}
)
private fun startupHotBenchmark(
compilationMode: CompilationMode
) = benchmarkRule.measureRepeated(
packageName = InstrumentationRegistry.getArguments().getString("targetAppId")
?: throw Exception("targetAppId not passed as instrumentation runner arg"),
metrics = listOf(StartupTimingMetric()),
compilationMode = compilationMode,
startupMode = StartupMode.HOT,
iterations = 10,
setupBlock = {
pressHome()
},
measureBlock = {
startActivityAndWait()
}
)
} | 0 | Kotlin | 0 | 1 | a0b03bf204e6e681bbe587fdc928bff81e7e67e6 | 4,158 | FUTSale | Apache License 2.0 |
src/client-android/feature_chat_content/src/main/java/org/melon/feature_chat_content/domain/model/File.kt | kovdan01 | 306,299,292 | false | {"C++": 229634, "Kotlin": 59873, "CMake": 42751, "Python": 22311, "Shell": 20667, "Dockerfile": 10650} | package org.melon.feature_chat_content.domain.model
import android.net.Uri
data class File(
val fileName: String,
val uri: Uri
) | 29 | C++ | 0 | 2 | 356d8bf9f4ffa5b7e14fb144fd335fc29e0c3cf6 | 138 | melon | Apache License 2.0 |
src/main/kotlin/com/mrkirby153/tickmonitor/proxy/ClientProxy.kt | mrkirby153 | 109,912,241 | false | null | package com.mrkirby153.tickmonitor.proxy
class ClientProxy : CommonProxy() {
} | 0 | Kotlin | 0 | 0 | ef4e7dda89dc7770ca3acbfcb075fe5208506358 | 79 | tick-monitor | MIT License |
app/src/main/java/com/gdevs/mubi/presentation/ui/theme/Color.kt | Gu11s | 585,399,889 | false | null | package com.gdevs.mubi.presentation.ui.theme
import androidx.compose.ui.graphics.Color
val Purple200 = Color(0xFFBB86FC)
val Purple500 = Color(0xFF6200EE)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
val whiteBackground = Color(0xFFF7f7f7)
val Primary = Color(0xFF6243FF)
val Secondary = Color(0xFF0013CA)
val Turquoise = Color(0xFF21BDCA)
val LightTurquoise = Color(0xFF84DFE2)
val LightBlue = Color(0xFF32B4FF)
val Black = Color(0xFF25294A)
val Background = Color(0xFFF0F2F5)
val WhiteText = Color(0xFFFBFAFE)
val TextColor = Color(0xFF6B6B83)
val SubtleText = Color(0xFF8C8CA1)
val Gray = Color(0xFFD5D8DB)
val Error = Color(0xFFF65164) | 0 | Kotlin | 0 | 0 | e14ab44db4f0525b4b1e3f13af43cc4e5d640e66 | 666 | Mubi---Applaudo-s-Code-Challenge-Android | Academic Free License v1.1 |
domain/src/commonMain/kotlin/space/compoze/hiero/domain/section/interactor/SectionUpdate.kt | Firely-Pasha | 644,746,942 | false | null | package space.compoze.hiero.domain.section.interactor
import space.compoze.hiero.domain.collection.CollectionRepository
import space.compoze.hiero.domain.section.model.mutate.SectionMutation
import space.compoze.hiero.domain.section.repository.SectionRepository
class SectionUpdate(
private val sectionRepository: SectionRepository,
) {
operator fun invoke(sectionId: String, data: SectionMutation) =
sectionRepository.update(sectionId, data)
} | 0 | Kotlin | 0 | 1 | de86473ed3fa46647b1cb4db91987a1aa2848c78 | 464 | hiero-japanese | MIT License |
ion-schema/src/test/kotlin/com/amazon/ionschema/writer/internal/constraints/FieldsWriterTest.kt | amazon-ion | 148,685,964 | false | {"Kotlin": 804755, "Inno Setup": 15625, "Java": 795, "Shell": 631} | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazon.ionschema.writer.internal.constraints
import com.amazon.ionschema.IonSchemaVersion
import com.amazon.ionschema.model.Constraint
import com.amazon.ionschema.model.ExperimentalIonSchemaModel
import com.amazon.ionschema.model.TypeArgument
import com.amazon.ionschema.model.occurs
import com.amazon.ionschema.model.optional
import org.junit.jupiter.api.Test
@OptIn(ExperimentalIonSchemaModel::class)
class FieldsWriterTest : ConstraintTestBase(
writer = FieldsWriter(stubTypeWriterWithRefs("foo_type", "bar_type"), IonSchemaVersion.v2_0),
expectedConstraints = setOf(Constraint.Fields::class),
writeTestCases = listOf(
Constraint.Fields(fieldsMap, closed = true) to "fields: closed::{ a: foo_type, b: bar_type }",
Constraint.Fields(fieldsMap, closed = false) to "fields: { a: foo_type, b: bar_type }",
)
) {
companion object {
private val fieldsMap = mapOf(
"a" to TypeArgument.Reference("foo_type").optional(),
"b" to TypeArgument.Reference("bar_type").occurs(0, 1),
)
}
@Test
fun `writer should write content closed for v1_0`() {
val writer = FieldsWriter(stubTypeWriterWithRefs("foo_type", "bar_type"), IonSchemaVersion.v1_0)
runWriteCase(
writer,
Constraint.Fields(fieldsMap, closed = true) to "content: closed, fields: { a: foo_type, b: bar_type }"
)
}
}
| 40 | Kotlin | 14 | 27 | 7a9ee6d06e9cfdaa530310f5d9be9f5a52680d3b | 1,528 | ion-schema-kotlin | Apache License 2.0 |
app/src/main/java/com/sebastijanzindl/galore/presentation/viewmodels/MainViewModel.kt | m1thrandir225 | 743,270,603 | false | {"Kotlin": 355549} | package com.sebastijanzindl.galore.presentation.viewmodels
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import com.sebastijanzindl.galore.domain.usecase.SignOutUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class MainViewModel @Inject constructor(
private val signOutUseCase: SignOutUseCase,
): ViewModel() {
var enabledNotifications by mutableStateOf(false)
private set
fun setHasEnabledNotifications(value: Boolean) {
enabledNotifications = value;
}
} | 0 | Kotlin | 0 | 0 | 2a3188176c53122ff11592b00c801dd28b1343c8 | 662 | galore-android | MIT License |
common/src/main/java/com/sec/common/adapter/RecyclerVH.kt | liuhuiAndroid | 311,604,995 | false | null | package com.sec.common.adapter
import android.view.View
import androidx.recyclerview.widget.RecyclerView
open class RecyclerVH(itemView: View, val support: RecyclerSupport) :
RecyclerView.ViewHolder(itemView) {
open fun bind(itemCell: ItemCell, payloads: MutableList<Any> = mutableListOf()) {
//empty
}
} | 0 | Kotlin | 0 | 1 | 2ccbf66a540cc4db738f9d3e0fdcc6f5db014526 | 327 | fizz | MIT License |
app/src/main/java/com/metoer/clocktracker/day/DayStringEnum.kt | etokoc | 510,835,828 | false | null | package com.metoer.clocktracker.day
enum class DayStringEnum {
Pzt, Sal, Çar, Per, Cum, Cmt, Paz
} | 0 | Kotlin | 0 | 1 | 07e918b66d3d3d9f3aae077ceec047a99a8142f2 | 103 | ClockTracker | MIT License |
plaitPlugin/plait-plugin/src/main/java/com/ckenergy/trace/PlaitMachinePlugin.kt | ckenergy | 497,486,366 | false | {"Kotlin": 70997, "Java": 30774, "Shell": 393} | package com.ckenergy.trace
import com.android.build.api.artifact.ScopedArtifact
import com.android.build.api.variant.AndroidComponentsExtension
import com.android.build.api.variant.ScopedArtifacts
import com.android.build.gradle.AppExtension
import com.ckenergy.trace.extension.PlaitExtension
import com.ckenergy.trace.task.TransformClassesTask
import com.ckenergy.trace.utils.Log
import org.gradle.api.Plugin
import org.gradle.api.Project
/**
* ckenergy 2021-04-19
*/
open class PlaitMachinePlugin : Plugin<Project> {
private lateinit var project: Project
private val agpVersion by lazy { getKotlinVersion(project) }
override fun apply(project: Project) {
this.project = project
val configuration = project.extensions.create("plait", PlaitExtension::class.java)
if (project.plugins.hasPlugin("com.android.application")) {
Log.printLog = configuration.logInfo
Log.d(PlaintMachineTransform.TAG, "afterEvaluate configuration:${configuration.enable}, method:${configuration.plaitClass?.asMap}")
if (isAGP8()) {
val extension1 = project.extensions.getByType(AndroidComponentsExtension::class.java)
extension1.onVariants(extension1.selector().all()) { variant ->
val taskProviderTransformClassesTask =
project.tasks.register(
"${variant.name}TransformPlaitClassesTask",
TransformClassesTask::class.java,
TransformClassesTask.CreationAction(configuration)
)
// https://github.com/android/gradle-recipes
variant.artifacts.forScope(ScopedArtifacts.Scope.ALL)
.use(taskProviderTransformClassesTask)
.toTransform(
ScopedArtifact.CLASSES,
TransformClassesTask::allJars,
TransformClassesTask::allDirectories,
TransformClassesTask::output
)
}
}else {
val appExtension = project.extensions.findByType(AppExtension::class.java)
val transform = PlaintMachineTransform.newTransform()
appExtension?.registerTransform(transform)
transform?.plaintMachineExtension = configuration
}
}
}
private fun isAGP8(): Boolean {
println("apg:$agpVersion")
var useNew = false
if (agpVersion != null) {
// 将版本字符串转换为数字形式,例如 "4.2.0" 转换为 420
val agpVersionNumber = agpVersion?.replace(".", "")?.toInt() ?: 0
if (agpVersionNumber >= 800) {
useNew = true
}
}
return useNew
}
private fun getKotlinVersion(project: Project): String? {
val buildscriptDependencies =
project.rootProject.buildscript.configurations.getByName("classpath").resolvedConfiguration.resolvedArtifacts.map { it.moduleVersion.id.toString() }
// var kotlinVersion: String? = null
var androidGradlePluginVersion: String? = null
val result = buildscriptDependencies.map { Pair(it, it.split(":")) }.map {
val group = it.second[0]
val artifact = it.second[1]
val version = it.second[2]
// if (group == "org.jetbrains.kotlin" && artifact == "kotlin-gradle-plugin")
// kotlinVersion = version
if (group == "com.android.tools.build" && artifact == "gradle")
androidGradlePluginVersion = version
}
println(
"androidGradlePluginVersion:$androidGradlePluginVersion"
)
return androidGradlePluginVersion
}
}
| 0 | Kotlin | 0 | 4 | 03c294e127dfa311d8c5aa01c5a2b69f1157ff6b | 3,835 | PlaitMachine | Apache License 2.0 |
app/src/main/java/com/example/pixabaygalleryapp/di/modules/GeneralRepositoryModule.kt | AliAzaz | 360,302,381 | false | null | package com.example.pixabaygalleryapp.di.modules
import com.example.pixabaygalleryapp.base.repository.GeneralDataSource
import com.example.pixabaygalleryapp.base.repository.GeneralRepository
import com.example.pixabaygalleryapp.di.auth.AuthApi
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
class GeneralRepositoryModule {
@Singleton
@Provides
fun provideGeneralDataSource(authApi: AuthApi): GeneralDataSource {
return GeneralRepository(authApi)
}
} | 0 | Kotlin | 0 | 8 | 8450c79fe9429fc69e546010acbbfde1a0ac61d8 | 512 | PixabayGalleryApp | MIT License |
src/main/kotlin/com/udemy/groceryshoppingapi/retail/repository/SupermarketRepository.kt | fahrican | 776,571,067 | false | {"Kotlin": 57120, "Java": 176} | package com.udemy.groceryshoppingapi.retail.repository
import com.udemy.groceryshoppingapi.retail.entity.Supermarket
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
@Repository
interface SupermarketRepository: JpaRepository<Supermarket, Long> {
} | 0 | Kotlin | 0 | 0 | 7a55358527394f3ad01146e110c77c84ce14057c | 310 | grocery-shopping-api | MIT License |
CallofProjectAndroid/app/src/main/java/callofproject/dev/androidapp/application/CallOfProjectAndroidApp.kt | CallOfProject | 751,531,328 | false | {"Kotlin": 429418, "Java": 5965} | package callofproject.dev.androidapp.application
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class CallOfProjectAndroidApp : Application() | 0 | Kotlin | 1 | 1 | 9cc12cd78cc212d474cd32b7ea3a89a5b8d5905b | 185 | Call-Of-Project-Android | MIT License |
app/src/main/java/com/crazyhitty/chdev/ks/news/util/internet/InternetHelper.kt | crazyhitty | 121,720,447 | false | null | package com.crazyhitty.chdev.ks.news.util.internet
/**
* Provides internet related utility methods.
*
* @author <NAME> (<EMAIL>)
*/
interface InternetHelper {
/**
* Check if internet is available or not.
*
* @return
* True, if internet is available, otherwise false.
*/
fun isAvailable(): Boolean
} | 0 | Kotlin | 0 | 12 | 9c3561d8ce9c5c418d71ba99ad60fb475866f3a8 | 337 | news | MIT License |
finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/AtsServiceAsyncImpl.kt | Finch-API | 581,317,330 | false | null | package com.tryfinch.api.services.async
import com.tryfinch.api.core.ClientOptions
import com.tryfinch.api.core.http.HttpResponse.Handler
import com.tryfinch.api.errors.FinchError
import com.tryfinch.api.services.async.ats.ApplicationServiceAsync
import com.tryfinch.api.services.async.ats.ApplicationServiceAsyncImpl
import com.tryfinch.api.services.async.ats.CandidateServiceAsync
import com.tryfinch.api.services.async.ats.CandidateServiceAsyncImpl
import com.tryfinch.api.services.async.ats.JobServiceAsync
import com.tryfinch.api.services.async.ats.JobServiceAsyncImpl
import com.tryfinch.api.services.async.ats.OfferServiceAsync
import com.tryfinch.api.services.async.ats.OfferServiceAsyncImpl
import com.tryfinch.api.services.async.ats.StageServiceAsync
import com.tryfinch.api.services.async.ats.StageServiceAsyncImpl
import com.tryfinch.api.services.errorHandler
class AtsServiceAsyncImpl
constructor(
private val clientOptions: ClientOptions,
) : AtsServiceAsync {
private val errorHandler: Handler<FinchError> = errorHandler(clientOptions.jsonMapper)
private val candidates: CandidateServiceAsync by lazy {
CandidateServiceAsyncImpl(clientOptions)
}
private val applications: ApplicationServiceAsync by lazy {
ApplicationServiceAsyncImpl(clientOptions)
}
private val stages: StageServiceAsync by lazy { StageServiceAsyncImpl(clientOptions) }
private val jobs: JobServiceAsync by lazy { JobServiceAsyncImpl(clientOptions) }
private val offers: OfferServiceAsync by lazy { OfferServiceAsyncImpl(clientOptions) }
override fun candidates(): CandidateServiceAsync = candidates
override fun applications(): ApplicationServiceAsync = applications
override fun stages(): StageServiceAsync = stages
override fun jobs(): JobServiceAsync = jobs
override fun offers(): OfferServiceAsync = offers
}
| 1 | Kotlin | 0 | 4 | 2c53f443c479e0b01499126413569edc5dc0b1ef | 1,882 | finch-api-java | Apache License 2.0 |
src/test/kotlin/org/rust/lang/core/resolve/RsStdlibResolveTestEdition2018.kt | kumbayo | 66,188,183 | true | {"Kotlin": 4768923, "Rust": 105250, "Python": 53350, "Lex": 20296, "HTML": 13654, "Shell": 760, "Java": 586, "RenderScript": 318} | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.resolve
import org.rust.MockEdition
import org.rust.ProjectDescriptor
import org.rust.WithStdlibRustProjectDescriptor
import org.rust.cargo.project.workspace.CargoWorkspace
@MockEdition(CargoWorkspace.Edition.EDITION_2018)
@ProjectDescriptor(WithStdlibRustProjectDescriptor::class)
class RsStdlibResolveTestEdition2018 : RsResolveTestBase() {
fun `test extern crate std is not injected on 2018 edition`() = stubOnlyResolve("""
//- main.rs
use crate::std::mem;
//^ unresolved
""")
fun `test extra use of prelude item`() = stubOnlyResolve("""
//- main.rs
use Vec;
fn main() {
let a = Vec::<i32>::new();
} //^ .../vec.rs
""", ItemResolutionTestmarks.extraAtomUse)
}
| 0 | Kotlin | 0 | 1 | ac5c7bef9ed268d4ab35eb4697874ecbcb95a2ff | 895 | intellij-rust | MIT License |
presentation/src/commonMain/kotlin/ireader/presentation/ui/component/utils/FastMappers.kt | IReaderorg | 425,288,628 | false | null | package ireader.presentation.ui.component.utils
expect inline fun <T, R> List<T>.fastMap(transform: (T) -> R): List<R>
expect inline fun <T> List<T>.fastForEach(action: (T) -> Unit)
expect inline fun <T, R : Comparable<R>> List<T>.fastMaxBy(selector: (T) -> R): T?
expect inline fun <T> List<T>.fastFirstOrNull(predicate: (T) -> Boolean): T?
expect inline fun <T> List<T>.fastAll(predicate: (T) -> Boolean): Boolean
expect inline fun <T> List<T>.fastAny(predicate: (T) -> Boolean): Boolean | 10 | Kotlin | 16 | 146 | 9ec2ee1da7f20a4a9dfa64f9291d449483d7d621 | 497 | IReader | Apache License 2.0 |
app/src/test/java/com/idleoffice/coinwatch/ui/main/MainActivityTest.kt | dan-0 | 172,395,118 | false | null | package com.idleoffice.coinwatch.ui.main
import android.view.View
import com.crashlytics.android.Crashlytics
import com.crashlytics.android.core.CrashlyticsCore
import com.idleoffice.coinwatch.BR
import com.idleoffice.coinwatch.R
import com.idleoffice.coinwatch.data.model.bci.BitcoinAverageCurrent
import com.idleoffice.coinwatch.data.model.bci.BitcoinAverageInfo
import com.idleoffice.coinwatch.ui.main.graph.CoinLineData
import io.fabric.sdk.android.Fabric
import junit.framework.TestCase.*
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.progress_bar_frame_layout.*
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.shadows.ShadowToast
@RunWith(RobolectricTestRunner::class)
class MainActivityTest {
private lateinit var subject: MainActivity
@Before
fun setUp() {
subject = Robolectric.setupActivity(MainActivity::class.java)
// Must disable crashlytics for testing
val core = CrashlyticsCore.Builder().disabled(true).build()
Fabric.with(subject, Crashlytics.Builder().core(core).build())
}
@After
fun cleanUp() {
subject.finish()
}
@Test
fun onCreate() {
subject = Robolectric.buildActivity(MainActivity::class.java).create().get()
assertNotNull(subject.viewDataBinding)
assertEquals(subject, subject.mainViewModel!!.navigator)
assertTrue(subject.mainViewModel!!.graphData.hasObservers())
assertTrue(subject.mainViewModel!!.currentPrice.hasObservers())
assertNotNull(subject.viewModelFactory)
}
@Test
fun testPriceObserver() {
val currentPrice = subject.mainViewModel!!.currentPrice
//"Feb 2018, 23:11"
currentPrice.value = BitcoinAverageCurrent(123.12, 151892711)
assertEquals(subject.priceText.text, "123.12")
// Shouldn't change
currentPrice.value = null
assertEquals(subject.priceText.text, "123.12")
}
@Test
fun testGraphObserver() {
val graphData = subject.mainViewModel!!.graphData
val testDataArray = arrayListOf(
BitcoinAverageInfo("2017-01-01 01:23:45", "1234.56"),
BitcoinAverageInfo("2017-01-02 01:23:46", "1234.567"))
val testSampleName = "testSample"
val cld = CoinLineData(testDataArray, testSampleName)
subject.showLoading()
// Assert we are showing a loading progressbar
assertEquals(View.VISIBLE, subject.progressBar.visibility)
graphData.value = cld
assertEquals(testSampleName, subject.chart.description.text)
// Check by index for granularity
assertEquals(subject.chart.data.dataSets[0].getEntryForIndex(0).x,
cld.getLineData().dataSets[0].getEntryForIndex(0).x)
assertEquals(
subject.chart.data.dataSets[0].getEntryForIndex(0).y,
cld.getLineData().dataSets[0].getEntryForIndex(0).y)
assertEquals(subject.chart.data.dataSets[0].getEntryForIndex(1).x,
cld.getLineData().dataSets[0].getEntryForIndex(1).x)
assertEquals(
subject.chart.data.dataSets[0].getEntryForIndex(1).y,
cld.getLineData().dataSets[0].getEntryForIndex(1).y)
// Should retain through null assignment
graphData.value = null
assertEquals(testSampleName, subject.chart.description.text)
assertEquals(subject.chart.data.dataSets[0].getEntryForIndex(0).x,
cld.getLineData().dataSets[0].getEntryForIndex(0).x)
assertEquals(
subject.chart.data.dataSets[0].getEntryForIndex(0).y,
cld.getLineData().dataSets[0].getEntryForIndex(0).y)
assertEquals(subject.chart.data.dataSets[0].getEntryForIndex(1).x,
cld.getLineData().dataSets[0].getEntryForIndex(1).x)
assertEquals(
subject.chart.data.dataSets[0].getEntryForIndex(1).y,
cld.getLineData().dataSets[0].getEntryForIndex(1).y)
// Assert progress bar is gone
assertEquals(View.GONE, subject.progressBar.visibility)
}
@Test
fun getActivityViewModel() {
val viewModel = subject.getActivityViewModel()
assertNotNull(viewModel)
subject.recreate()
assertNotNull(viewModel)
}
@Test
fun getBindingVariable() {
assertEquals(BR.viewModel, subject.getBindingVariable())
}
@Test
fun getLayoutId() {
assertEquals(R.layout.activity_main, subject.getLayoutId())
}
@Test
fun handleError() {
//Pretty much a stub
subject.handleError(Exception())
}
@Test
fun displayError() {
val msg = "Toast Message"
subject.displayError(msg)
assertEquals(msg, ShadowToast.getTextOfLatestToast())
}
@Test
fun supportFragmentInjector() {
assertNotNull(subject.supportFragmentInjector())
}
@Test
fun xAxisLabel() {
val date = "01 Jan 2017, 01:23"
subject.xAxisLabel(date)
assertEquals(date, subject.xAxisLabel.text)
}
@Test
fun yAxisLabel() {
val price = "0.00"
subject.yAxisLabel(price)
assertEquals(price, subject.yAxisLabel.text)
}
@Test
fun updatePrice() {
val price = "0.00"
subject.updatePrice(price)
assertEquals(price, subject.priceText.text)
}
} | 0 | Kotlin | 0 | 0 | cecb7aec6b8524ee761f5e9429000ff45565c77e | 5,572 | CoinWatch | MIT License |
philology/src/test/java/com/jcminarro/philology/PhilologyResourcesTest.kt | mbircu | 202,501,486 | true | {"Kotlin": 43325, "Groovy": 5355, "Java": 341} | package com.jcminarro.philology
import android.content.res.Configuration
import android.content.res.Resources
import com.nhaarman.mockito_kotlin.doReturn
import org.amshove.kluent.When
import org.amshove.kluent.`should equal`
import org.amshove.kluent.calling
import org.amshove.kluent.mock
import org.junit.Before
import org.junit.Test
class PhilologyResourcesTest {
private val baseResources: Resources = mock()
private val configuration: Configuration = createConfiguration()
private val resources = PhilologyResources(baseResources)
private val someCharSequence: CharSequence = "text"
private val someString: String = someCharSequence.toString()
private val repoCharSequence: CharSequence = "repo"
private val repoString: String = repoCharSequence.toString()
private val id = 0
private val nameId = "nameId"
@Before
fun setup() {
clearPhilology()
When calling baseResources.configuration doReturn configuration
}
@Test(expected = Resources.NotFoundException::class)
fun `Should throw an exception if the given id doesn't exist asking for a text`() {
configureResourceGetIdException(baseResources, id)
resources.getText(id)
}
@Test()
fun `Should return a CharSequence asking for a text`() {
configureResourceGetText(baseResources, id, nameId, someCharSequence)
resources.getText(id) `should equal` someCharSequence
}
@Test(expected = Resources.NotFoundException::class)
fun `Should throw an exception if the given id doesn't exist asking for an String`() {
configureResourceGetIdException(baseResources, id)
resources.getString(id)
}
@Test()
fun `Should return a CharSequence asking for an String`() {
configureResourceGetText(baseResources, id, nameId, someCharSequence)
resources.getString(id) `should equal` someString
}
@Test()
fun `Should return a CharSequence from repository asking for a text`() {
configureResourceGetText(baseResources, id, nameId, someCharSequence)
configurePhilology(createRepository(nameId, null, repoCharSequence))
resources.getText(id) `should equal` repoCharSequence
}
@Test()
fun `Should return a CharSequence from repository asking for an String`() {
configureResourceGetText(baseResources, id, nameId, someCharSequence)
configurePhilology(createRepository(nameId, null, repoCharSequence))
resources.getString(id) `should equal` repoString
}
} | 0 | Kotlin | 0 | 0 | d4ae7a5592384ba90cda942aa6f62e1e70e61360 | 2,537 | Philology | Apache License 2.0 |
code/codegen/src/test/kotlin/com/android/gradle/replicator/codegen/kotlin/KotlinClassGeneratorTest.kt | android | 281,446,649 | false | null | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.gradle.replicator.codegen.kotlin
import com.android.gradle.replicator.codegen.ClassModel
import com.android.gradle.replicator.codegen.FieldModel
import com.android.gradle.replicator.codegen.ParamModel
import com.android.gradle.replicator.codegen.PrettyPrintStream
import com.android.gradle.replicator.codegen.TypeModelImpl
import com.google.common.truth.Truth
import org.junit.Test
import java.io.ByteArrayOutputStream
import java.io.PrintStream
import kotlin.reflect.full.declaredFunctions
class KotlinClassGeneratorTest {
private val outputStream = ByteArrayOutputStream()
private val printer = PrettyPrintStream(PrintStream(outputStream))
private val kotlinClassGenerator = KotlinClassGenerator(printer, listOf())
private val stringClassModel = ClassModel(
String::class,
String::class.constructors.first(),
String::class.declaredFunctions)
@Test
fun testClassGeneration() {
kotlinClassGenerator.defineClass("com.foo.package", "FooClass") {}
Truth.assertThat(prettyPrint(outputStream)).isEqualTo(
"""package com.foo.package
@Suppress("UNUSED_PARAMETER")
class FooClass {
}
""" )
}
@Test
fun testIfBlockGeneration() {
kotlinClassGenerator.ifBlock(
{
printer.print("myString.equals(\"foo\")")
}, {
}, null)
Truth.assertThat(prettyPrint(outputStream)).isEqualTo(
"""if (myString.equals("foo")) {
}
""" )
}
@Test
fun testIfElseBlockGeneration() {
kotlinClassGenerator.ifBlock(
{
printer.print("myString.equals(\"foo\")")
}, {
}, {
printer.printlnIndented("println(\"code is else block\")")
} )
Truth.assertThat(prettyPrint(outputStream)).isEqualTo(
"""if (myString.equals("foo")) {
} else {
println("code is else block")
}
"""
)
}
@Test
fun testLoop() {
kotlinClassGenerator.loopBlock("i", 10) { }
Truth.assertThat(prettyPrint(outputStream)).isEqualTo(
"""for (i in 0..10) {
}
"""
)
}
@Test
fun testLambdaBlock() {
kotlinClassGenerator.lambdaBlock({ printer.printIndented("listOf(1, 2, 3)") }) {
printer.printlnIndented("println(it)")
}
Truth.assertThat(prettyPrint(outputStream)).isEqualTo(
"""listOf(1, 2, 3).forEach {
println(it)
}
"""
)
}
@Test
fun declareVariable() {
kotlinClassGenerator.declareVariable(FieldModel("myVar1", stringClassModel, false), "\"Foo\"")
kotlinClassGenerator.declareVariable(FieldModel("myVar2", stringClassModel, false), "\"Bar\"")
Truth.assertThat(prettyPrint(outputStream)).isEqualTo(
"""val myVar1: String = "Foo"
val myVar2: String = "Bar"
"""
)
}
@Test
fun declareNullableVariable() {
kotlinClassGenerator.declareVariable(FieldModel("myVar1", stringClassModel, true), "\"Foo\"")
Truth.assertThat(prettyPrint(outputStream)).isEqualTo(
"""val myVar1: String? = "Foo"
"""
)
}
@Test
fun declareNoValueVariable() {
kotlinClassGenerator.declareVariable(FieldModel("myVar1", stringClassModel, true))
Truth.assertThat(prettyPrint(outputStream)).isEqualTo(
"""val myVar1: String?
"""
)
}
@Suppress("unused")
@Test
fun declareParameterizedVariable() {
class ParameterizedType<T: Iterable<U>, U: CharSequence>
kotlinClassGenerator.declareVariable(FieldModel("myVar1",
ClassModel(ParameterizedType::class,
ParameterizedType::class.constructors.first(),
ParameterizedType::class.declaredFunctions
),
false))
Truth.assertThat(prettyPrint(outputStream)).isEqualTo(
"""val myVar1: com.android.gradle.replicator.codegen.kotlin.KotlinClassGeneratorTest${'$'}declareParameterizedVariable${'$'}ParameterizedType<kotlin.collections.Iterable,kotlin.CharSequence>
"""
)
}
@Test
fun declareMethodWithMultipleParameters() {
kotlinClassGenerator.declareMethod("method",
listOf(
ParamModel("param0", stringClassModel, false),
ParamModel("param1",
ClassModel(
Float::class,
Float::class.constructors.first(),
Float::class.declaredFunctions),
false)
),
TypeModelImpl(stringClassModel, false),
""""SomeValue"""") {}
Truth.assertThat(prettyPrint(outputStream)).isEqualTo(
"""
fun method(
param0: String,
param1: float
): String {
return "SomeValue"
}
"""
)
}
@Test
fun declareMethodWithSingleParameter() {
kotlinClassGenerator.declareMethod("method",
listOf(
ParamModel("param0", stringClassModel, false)
),
TypeModelImpl(stringClassModel, false),
""""someString"""") {}
Truth.assertThat(prettyPrint(outputStream)).isEqualTo(
"""
fun method(
param0: String
): String {
return "someString"
}
"""
)
}
@Test
fun declareMethodWithNullableReturnType() {
kotlinClassGenerator.declareMethod("method",
listOf(
ParamModel("param0", stringClassModel, false)
),
TypeModelImpl(stringClassModel,true),
""""someString"""") {}
Truth.assertThat(prettyPrint(outputStream)).isEqualTo(
"""
fun method(
param0: String
): String? {
return "someString"
}
"""
)
}
@Test
fun declareMethodWithNullableParameter() {
kotlinClassGenerator.declareMethod("method",
listOf(
ParamModel("param0", stringClassModel, true)
),
TypeModelImpl(stringClassModel, false),
""""someString"""") {}
Truth.assertThat(prettyPrint(outputStream)).isEqualTo(
"""
fun method(
param0: String?
): String {
return "someString"
}
"""
)
}
@Test
fun declareMethodWithUnitReturnType() {
kotlinClassGenerator.declareMethod("method",
listOf(
ParamModel("param0", stringClassModel, false)
),
null,
null) {}
Truth.assertThat(prettyPrint(outputStream)).isEqualTo(
"""
fun method(
param0: String
) {
}
"""
)
}
@Test
fun callMethodWithoutParameters() {
kotlinClassGenerator.callFunction(
FieldModel("local_field", stringClassModel, false),
String::toString,
listOf())
Truth.assertThat(prettyPrint(outputStream)).isEqualTo(
"""local_field.toString()"""
)
}
@Test
fun callMethodWithParameters() {
kotlinClassGenerator.callFunction(
FieldModel("local_field", stringClassModel, false),
String::compareTo,
listOf(""""someString""""))
Truth.assertThat(prettyPrint(outputStream)).isEqualTo(
"""local_field.compareTo("someString")"""
)
}
private fun prettyPrint(outputStream: ByteArrayOutputStream) =
outputStream.toString().replace("\t", " ")
} | 3 | Kotlin | 27 | 87 | dcdbd2d77b0a3e511c5da0ef960668bfec9f25a3 | 8,349 | project-replicator | Apache License 2.0 |
app/src/main/java/com/aesuriagasalazar/competenciadigitalespracticum3_2/ui/screens/syllabus/SyllabusScreen.kt | AngelEduSuri | 514,696,509 | false | null | package com.aesuriagasalazar.competenciadigitalespracticum3_2.ui.screens.syllabus
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.aesuriagasalazar.competenciadigitalespracticum3_2.R
import com.aesuriagasalazar.competenciadigitalespracticum3_2.domain.Syllabus
import com.aesuriagasalazar.competenciadigitalespracticum3_2.domain.TopicSyllabusId
import com.aesuriagasalazar.competenciadigitalespracticum3_2.ui.components.DialogApp
import com.aesuriagasalazar.competenciadigitalespracticum3_2.ui.components.SurfaceApp
import com.aesuriagasalazar.competenciadigitalespracticum3_2.ui.components.TopBarApplication
@Composable
fun SyllabusScreen(
viewModel: SyllabusViewModel = hiltViewModel(),
onNextScreen: (TopicSyllabusId) -> Unit,
onBackPressed: () -> Unit
) {
val uiState = viewModel.syllabusUiState.collectAsState().value
SurfaceApp {
SyllabusScreenBody(
uiState = uiState,
onItemClick = { onNextScreen(it) },
onBackPressed = onBackPressed,
onCloseDialog = viewModel::onCloseDialogMessage
)
}
SideEffect {
viewModel.checkIfTopicIsComplete()
}
}
@Composable
fun SyllabusScreenBody(
uiState: SyllabusUiState,
onItemClick: (TopicSyllabusId) -> Unit,
onBackPressed: () -> Unit,
onCloseDialog: () -> Unit
) {
val screenSize = LocalConfiguration.current.screenHeightDp
Column {
TopBarApplication(
title = stringResource(R.string.title_syllabus),
contentDescriptionNav = stringResource(id = R.string.back_screen),
onBackPressed = onBackPressed
)
LazyColumn(
contentPadding = PaddingValues(all = 8.dp),
verticalArrangement = Arrangement.spacedBy(space = 8.dp)
) {
items(uiState.listSyllabus) {
SyllabusTopic(theme = it, onClick = { onItemClick(it.id) })
}
}
if (uiState.showDialogMessage) {
DialogApp(
titleBar = stringResource(id = R.string.congratulation_message),
messageBody = stringResource(id = R.string.lesson_complete_message),
titleButtonAccept = stringResource(id = R.string.accept),
dialogSize = (screenSize / 2).dp,
lottieAnimationBody = R.raw.congratulation_animation,
onCloseDialog = onCloseDialog,
)
}
}
}
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun SyllabusTopic(theme: Syllabus, onClick: () -> Unit) {
Card(
onClick = onClick,
backgroundColor = MaterialTheme.colors.primaryVariant
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(all = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceEvenly
) {
Image(
modifier = Modifier.weight(weight = 0.2f),
painter = painterResource(id = theme.icon),
contentDescription = theme.title
)
Text(
modifier = Modifier
.weight(weight = 0.7f)
.padding(all = 4.dp),
text = theme.title,
style = MaterialTheme.typography.h5,
textAlign = TextAlign.Center,
fontWeight = FontWeight.Bold
)
Checkbox(
modifier = Modifier.weight(weight = 0.1f),
checked = theme.isComplete,
onCheckedChange = null
)
}
}
} | 0 | Kotlin | 0 | 0 | a97e0821b59d1bdc7d5274fc62bf61f23473c082 | 4,344 | Competencias-Digitales-Practicum-3.2 | Apache License 2.0 |
src/rider/main/kotlin/com/github/rafaelldi/diagnosticsclientplugin/actions/traces/StopExportTraceSessionAction.kt | rafaelldi | 487,741,199 | false | null | package com.github.rafaelldi.diagnosticsclientplugin.actions.traces
import com.github.rafaelldi.diagnosticsclientplugin.actions.common.StopExportSessionAction
import com.github.rafaelldi.diagnosticsclientplugin.services.traces.ExportTraceSessionController
import com.intellij.openapi.project.Project
class StopExportTraceSessionAction : StopExportSessionAction() {
override fun stopSession(pid: Int, project: Project) {
ExportTraceSessionController.getInstance(project).stopSession(pid)
}
override fun containsSession(pid: Int, project: Project) =
ExportTraceSessionController.getInstance(project).containsSession(pid)
} | 1 | Kotlin | 0 | 4 | f2d9987f9ab953ef9e836c6092fd354e887d4d76 | 651 | diagnostics-client-plugin | MIT License |
app/src/main/java/com/example/newsapp/model/NewsMediaModel.kt | ali0094 | 219,040,996 | false | {"Kotlin": 21233} | package com.example.newsapp.model
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
import java.io.Serializable
import java.util.ArrayList
class NewsMediaModel{
inner class Root : Serializable {
@SerializedName("id")
var id: Long? = null
@SerializedName("media")
var postMedia: ArrayList<PostMedia>? = null
@SerializedName("title")
var postTitle: String? = null
@SerializedName("abstract")
var postDetail: String? = null
@SerializedName("byline")
var postAuthor: String? = null
@SerializedName("url")
var postUrl: String? = null
@SerializedName("type")
var postType:String? = null
@SerializedName("published_date")
var postDate: String? = null
}
inner class PostMedia : Serializable {
@SerializedName("type")
var type: String? = null
@SerializedName("media-metadata")
var postImages: ArrayList<PostImages> = ArrayList()
}
inner class PostImages: Serializable {
@SerializedName("url")
var imageUrl: String? = null
@SerializedName("height")
var imageHeight: String? = null
@SerializedName("width")
var imageWidth: String? = null
}
}
| 0 | Kotlin | 0 | 0 | 8a2d544812fbf417259712675a8f23cc7f7f4332 | 1,323 | popular-articles-android | MIT License |
src/main/kotlin/jamule/request/GetPreferencesRequest.kt | vexdev | 704,976,422 | false | {"Kotlin": 143693} | package jamule.request
import jamule.ec.ECDetailLevel
import jamule.ec.ECOpCode
import jamule.ec.ECTagName
import jamule.ec.EcPrefs
import jamule.ec.packet.Packet
import jamule.ec.tag.UByteTag
import jamule.ec.tag.UIntTag
internal data class GetPreferencesRequest(val prefs: EcPrefs) : Request {
override fun packet(): Packet = Packet(
ECOpCode.EC_OP_GET_PREFERENCES,
listOf(
UByteTag(ECTagName.EC_TAG_DETAIL_LEVEL, ECDetailLevel.EC_DETAIL_FULL.value),
UIntTag(ECTagName.EC_TAG_SELECT_PREFS, prefs.value),
)
)
} | 3 | Kotlin | 0 | 1 | d19293db9fe49b9720f407130b04a878222b329c | 571 | jamule | MIT License |
app/src/main/java/com/wgy/recyclemanager/activity/HomeActivity.kt | Gaoyuan-Wang | 451,931,324 | false | {"Kotlin": 10509} | package com.wgy.recyclemanager.activity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.wgy.recyclemanager.R
class HomeActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.home_layout)
}
} | 0 | Kotlin | 0 | 0 | 6b97e2f67541d00687995a15207f8c309ec88496 | 342 | RecycleManager | Apache License 2.0 |
project/module-legacy-api/src/main/kotlin/ink/ptms/zaphkiel/ZaphkielAPI.kt | TabooLib | 228,311,359 | false | {"Kotlin": 174358} | package ink.ptms.zaphkiel
import com.google.gson.JsonObject
import ink.ptms.zaphkiel.api.*
import ink.ptms.zaphkiel.item.meta.Meta
import org.bukkit.entity.Player
import org.bukkit.inventory.Inventory
import org.bukkit.inventory.ItemStack
import taboolib.common.platform.function.getDataFolder
import taboolib.library.configuration.ConfigurationSection
import taboolib.module.nms.ItemTag
import java.io.File
/**
* @author sky
* @since 2019-12-15 20:14
*/
@Deprecated("Use ink.ptms.zaphkiel.Zaphkiel#api()")
object ZaphkielAPI {
val loaded: ArrayList<File>
get() = arrayListOf()
val folderItem: File
get() = File(getDataFolder(), "item")
val folderDisplay: File
get() = File(getDataFolder(), "display")
val registeredItem: HashMap<String, Item>
get() = Zaphkiel.api().getItemManager().getItemMap() as HashMap<String, Item>
val registeredModel: HashMap<String, Model>
get() = Zaphkiel.api().getItemManager().getModelMap() as HashMap<String, Model>
val registeredDisplay: HashMap<String, Display>
get() = Zaphkiel.api().getItemManager().getDisplayMap() as HashMap<String, Display>
val registeredGroup: HashMap<String, Group>
get() = Zaphkiel.api().getItemManager().getGroupMap() as HashMap<String, Group>
val registeredMeta: Map<String, Class<*>>
get() = Zaphkiel.api().getItemManager().getMetaMap()
fun read(item: ItemStack): ItemStream {
return Zaphkiel.api().getItemHandler().read(item)
}
fun getItem(id: String, player: Player? = null): ItemStream? {
return Zaphkiel.api().getItemManager().generateItem(id, player)
}
fun getItemStack(id: String, player: Player? = null): ItemStack? {
return Zaphkiel.api().getItemManager().generateItemStack(id, player)
}
fun getName(item: ItemStack): String? {
return Zaphkiel.api().getItemHandler().getItemId(item)
}
fun getData(item: ItemStack): ItemTag? {
return Zaphkiel.api().getItemHandler().getItemData(item)
}
fun getUnique(item: ItemStack): ItemTag? {
return Zaphkiel.api().getItemHandler().getItemUniqueData(item)
}
fun getItem(item: ItemStack): Item? {
return Zaphkiel.api().getItemHandler().getItem(item)
}
fun checkUpdate(player: Player?, inventory: Inventory) {
Zaphkiel.api().getItemUpdater().checkUpdate(player, inventory)
}
fun checkUpdate(player: Player?, item: ItemStack): ItemStream {
return Zaphkiel.api().getItemUpdater().checkUpdate(player, item)
}
fun reloadItem() {
Zaphkiel.api().reload()
}
fun loadItemFromFile(file: File) {
Zaphkiel.api().getItemLoader().loadItemFromFile(file).forEach {
Zaphkiel.api().getItemManager().registerItem(it)
}
}
fun loadModelFromFile(file: File) {
Zaphkiel.api().getItemLoader().loadModelFromFile(file).forEach {
Zaphkiel.api().getItemManager().registerModel(it)
}
}
fun reloadDisplay() {
Zaphkiel.api().reload()
}
fun loadDisplayFromFile(file: File, fromItemFile: Boolean = false) {
Zaphkiel.api().getItemLoader().loadDisplayFromFile(file, fromItemFile).forEach {
Zaphkiel.api().getItemManager().registerDisplay(it)
}
}
fun readMeta(root: ConfigurationSection): MutableList<Meta> {
return Zaphkiel.api().getItemLoader().loadMetaFromSection(root).toMutableList()
}
fun serialize(itemStack: ItemStack): JsonObject {
return Zaphkiel.api().getItemSerializer().serialize(itemStack).toJsonObject()
}
fun serialize(itemStream: ItemStream): JsonObject {
return Zaphkiel.api().getItemSerializer().serialize(itemStream).toJsonObject()
}
fun deserialize(json: String): ItemStream {
return Zaphkiel.api().getItemSerializer().deserialize(json)
}
fun deserialize(json: JsonObject): ItemStream {
return Zaphkiel.api().getItemSerializer().deserialize(json)
}
} | 3 | Kotlin | 22 | 29 | 07e0aa437b7abdf5e4d9d3dc9a716260481616b9 | 4,029 | zaphkiel | Creative Commons Zero v1.0 Universal |
features/bookings/form/src/main/java/com/rodcollab/cliq/features/bookings/form/ui/BookingFormViewModel.kt | rodrigoliveirac | 610,274,713 | false | null | package com.rodcollab.cliq.features.bookings.form.ui
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.rodcollab.cliq.DateFormat.formatDate
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class BookingFormViewModel @Inject constructor(
private val bookingRepository: com.rodcollab.core.data.repository.BookingRepository,
) : ViewModel() {
fun addBooking(
bookedClientId: String,
bookedClientName: String,
bookedClientAddress: String,
bookedDate: String,
time: Long,
) {
viewModelScope.launch {
bookingRepository.add(
bookedClientId,
bookedClientName,
bookedClientAddress,
bookedDate,
time
)
}
}
private val setValueDate: MutableLiveData<String> by lazy {
MutableLiveData<String>()
}
val getValueDateSelected: LiveData<String> = setValueDate
fun saveValueDate(dateSelected: Long) {
setValueDate.value = formatDate(dateSelected)
}
}
| 0 | Kotlin | 0 | 0 | 65af38a3d7efaac0966f674fabaaf71482a9556d | 1,245 | Cliq | MIT License |
hideout-core/src/main/kotlin/dev/usbharu/hideout/core/domain/service/filter/FilterDomainService.kt | usbharu | 627,026,893 | false | {"Kotlin": 1314674, "Mustache": 111758, "HTML": 22697, "Dockerfile": 121} | /*
* Copyright (C) 2024 usbharu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.usbharu.hideout.core.domain.service.filter
import dev.usbharu.hideout.core.domain.model.filter.Filter
import dev.usbharu.hideout.core.domain.model.filter.FilterContext
import dev.usbharu.hideout.core.domain.model.filter.FilterResult
import dev.usbharu.hideout.core.domain.model.filter.FilteredPost
import dev.usbharu.hideout.core.domain.model.post.Post
import org.springframework.stereotype.Service
interface IFilterDomainService {
fun apply(post: Post, context: FilterContext, filters: List<Filter>): FilteredPost
fun applyAll(postList: List<Post>, context: FilterContext, filters: List<Filter>): List<FilteredPost>
}
@Service
class FilterDomainService : IFilterDomainService {
override fun apply(post: Post, context: FilterContext, filters: List<Filter>): FilteredPost {
val filterResults = filters
.filter { it.filterContext.contains(context) }
.flatMap { filter ->
val regex = filter.compileFilter()
post
.overview
?.overview
?.let { it1 -> regex.findAll(it1) }
.orEmpty()
.toList()
.map { FilterResult(filter, it.value) }
.plus(
post
.text
.let { regex.findAll(it) }
.toList()
.map { FilterResult(filter, it.value) }
)
}
return FilteredPost(post, filterResults)
}
override fun applyAll(postList: List<Post>, context: FilterContext, filters: List<Filter>): List<FilteredPost> {
return filters
.filter { it.filterContext.contains(context) }
.map { it to it.compileFilter() }
.flatMap { compiledFilter ->
postList
.map { post ->
val filterResults = post
.overview
?.overview
?.let { overview -> compiledFilter.second.findAll(overview) }
.orEmpty()
.toList()
.map { FilterResult(compiledFilter.first, it.value) }
.plus(
post
.text
.let { compiledFilter.second.findAll(it) }
.toList()
.map { FilterResult(compiledFilter.first, it.value) }
)
post to filterResults
}
}
.map { FilteredPost(it.first, it.second) }
}
}
| 18 | Kotlin | 0 | 13 | 32483abfe0e8e0458b5339887489c31bb62ad111 | 3,404 | Hideout | Apache License 2.0 |
android/src/main/java/com/iovation/IovationModule.kt | felipecornejo1 | 818,407,740 | false | {"Kotlin": 4668, "Ruby": 3253, "Objective-C": 2533, "JavaScript": 2122, "Objective-C++": 1405, "TypeScript": 1109, "C": 103, "Swift": 63} | package com.reactnativeiovation
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.Promise
import com.iovation.mobile.android.FraudForceConfiguration
import com.iovation.mobile.android.FraudForceManager
class IovationModule(reactContext: ReactApplicationContext) :
ReactContextBaseJavaModule(reactContext) {
override fun getName(): String {
return NAME
}
@ReactMethod
fun multiply(a: Double, b: Double): Double {
return a * b
}
val configuration = FraudForceConfiguration.Builder()
.subscriberKey("M1WrRSwcjUBQmHamij3DxQJWr00YzfRhXaMkI+zhhiY=")
.enableNetworkCalls(true)
.build()
val context = reactContext.getApplicationContext()
init {
FraudForceManager.initialize(configuration, context)
FraudForceManager.refresh(context)
}
@ReactMethod
fun getBlackbox(a: Double, b: Double): String {
val blackbox = FraudForceManager.getBlackbox(context)
return blackbox
}
companion object {
const val NAME = "Iovation"
}
}
| 0 | Kotlin | 0 | 0 | 933c854323a6d901b3caa2a25d1cfd6ae8930d09 | 1,128 | react-native-iovation-2 | MIT License |
Kotlin/Trees/BTree/BTree.kt | halls7588 | 62,333,583 | false | null | /*******************************************************
* BTree.java
* Created by <NAME> on 11/08/18.
* Copyright (c) 2018 <NAME>. All rights reserved.
* B-Tree implementation in Kotlin
*******************************************************/
/**
* Btree class
* @param <Key> Generic type
* @param <Value> Generic type
</Value></Key> */
class BTree<Key : Comparable<Key>, Value> {
private var root: Node? = null
private var height: Int = 0
// number of key-value pairs in the B-tree
private var pairs: Int = 0
/**
* Determines if the tree is empty
* @return boolean: true|false
*/
val isEmpty: Boolean
get() = size() == 0
// helper B-tree node data type
/**
* Node class
*/
inner class Node
/**
* Node Constructor
* @param size: number of children of the node
*/
constructor(// number of children
var size: Int) {
// array of children
var children: Array<Entry?>
init {
children = arrayOfNulls<Entry?>(Max)
}
}
/**
* Helper class for BTree Node class
*/
inner class Entry
/**
* Helper class Constructor
* @param key: key to hold
* @param val: value of the key
* @param next: next node in the tree
*/
(var key: Key, var `val`: Value?, var next: Node?)
/**
* B-tree constructor
*/
init {
root = Node(0)
}
/**
* Returns the number number of pars in the tree
* @return int: the number of key-value pairs in the tree
*/
fun size(): Int {
return pairs
}
/**
* Gets the height of the tree
* @return int: height of the tree
*/
fun height(): Int {
return height
}
/**
* Gets the value of the given key
* @param key: key to find value of
* @return Value: value of the given key or null
*/
operator fun get(key: Key?): Value? {
return if (key == null) null else search(root!!, key, height)
}
/**
* Searches the tree for the key
* @param node: node to start at
* @param key: key to find
* @param ht: height of the tree
* @return Value: Value of the key or null
*/
private fun search(node: Node?, key: Key, ht: Int): Value? {
val children = node!!.children
// external node
if (ht == 0) {
for (j in 0 until node.size) {
if (equalTo(key, children[j]!!.key))
return children[j]!!.`val`
}
} else {
for (j in 0 until node.size) {
if (j + 1 == node.size || lessThan(key, children[j + 1]!!.key))
return search(children[j]!!.next, key, ht - 1)
}
}// internal node
return null
}
/**
* Adds a node into the tree or replaces value
* @param key: key of the node
* @param val: value of the key
*/
fun put(key: Key?, `val`: Value) {
if (key == null)
return
val node = insert(root, key, `val`, height)
pairs++
if (node == null)
return
// need to split root
val tmp = Node(2)
tmp.children[0] = Entry(root!!.children[0]!!.key, null, root)
tmp.children[1] = Entry(node.children[0]!!.key, null, node)
root = tmp
height++
}
/**
* Inserts a node into the tree and updates the tree
* @param node: root to start at
* @param key: key of the new node
* @param val: value of the key
* @param ht: current height
* @return Node: node added into the tree
*/
private fun insert(node: Node?, key: Key, `val`: Value, ht: Int): Node? {
var j: Int
val entry = Entry(key, `val`, null)
// external node
if (ht == 0) {
j = 0
while (j < node!!.size) {
if (lessThan(key, node.children[j]!!.key))
break
j++
}
} else {
j = 0
while (j < node!!.size) {
if (j + 1 == node.size || lessThan(key, node.children[j + 1]!!.key)) {
val tmp = insert(node.children[j++]!!.next, key, `val`, ht - 1) ?: return null
entry.key = tmp.children[0]!!.key
entry.next = tmp
break
}
j++
}
}// internal node
System.arraycopy(node.children, j, node.children, j + 1, node.size - j)
node.children[j] = entry
node.size++
return if (node.size < Max)
null
else
split(node)
}
/**
* Splits the given node in half
* @param node: node to split
* @return Node: split node
*/
private fun split(node: Node): Node {
val tmp = Node(Max / 2)
node.size = Max / 2
System.arraycopy(node.children, 2, tmp.children, 0, Max / 2)
return tmp
}
/**
* Determines if a is less than b
* @param a: generic type to test
* @param b: generic type to test
* @return boolean: true|false
*/
private fun lessThan(a: Key, b: Key): Boolean {
return a.compareTo(b) < 0
}
/**
* Determines if a is equal to b
* @param a: generic type to test
* @param b: generic type to test
* @return boolean: true|false
*/
private fun equalTo(a: Key, b: Key): Boolean {
return a.compareTo(b) == 0
}
companion object {
// max children per B-tree node = M-1
private val Max = 4
}
} | 0 | C# | 6 | 16 | 7ce9533c2003f07ff7b54cb324f9fb0d7ed8fb9f | 5,656 | Data_Structures_in_15_Languages | MIT License |
src/main/kotlin/no/nav/arbeidsgiver/sykefravarsstatistikk/api/infrastruktur/database/SykefraværRepository.kt | navikt | 201,881,144 | false | {"Kotlin": 814147, "Shell": 1600, "Dockerfile": 213} | package no.nav.arbeidsgiver.sykefravarsstatistikk.api.infrastruktur.database
import no.nav.arbeidsgiver.sykefravarsstatistikk.api.applikasjon.aggregertOgKvartalsvisSykefraværsstatistikk.domene.Sykefraværsdata
import no.nav.arbeidsgiver.sykefravarsstatistikk.api.applikasjon.fellesdomene.*
import no.nav.arbeidsgiver.sykefravarsstatistikk.api.applikasjon.fellesdomene.Bransjeprogram.finnBransje
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.dao.EmptyResultDataAccessException
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
import org.springframework.stereotype.Component
import java.sql.ResultSet
import java.sql.SQLException
import java.util.*
@Component
class SykefraværRepository(
@param:Qualifier("sykefravarsstatistikkJdbcTemplate") private val namedParameterJdbcTemplate: NamedParameterJdbcTemplate,
private val sykefravarStatistikkVirksomhetRepository: SykefravarStatistikkVirksomhetRepository,
private val sykefraværStatistikkLandRepository: SykefraværStatistikkLandRepository,
) {
fun hentUmaskertSykefravær(
bransje: Bransje, fraÅrstallOgKvartal: ÅrstallOgKvartal
): List<UmaskertSykefraværForEttKvartal> {
require(!bransje.erDefinertPåTosiffernivå()) { "Denne metoden funker bare for 5-siffer næringskoder" }
return try {
namedParameterJdbcTemplate.query(
"SELECT sum(tapte_dagsverk) as tapte_dagsverk, sum(mulige_dagsverk) as "
+ "mulige_dagsverk, sum(antall_personer) as antall_personer, arstall, "
+ "kvartal "
+ "FROM sykefravar_statistikk_naring5siffer "
+ "where naring_kode in (:naringKoder) "
+ "and ("
+ " (arstall = :arstall and kvartal >= :kvartal) "
+ " or "
+ " (arstall > :arstall)"
+ ") "
+ "group by arstall, kvartal "
+ "ORDER BY arstall, kvartal ",
MapSqlParameterSource()
.addValue("naringKoder", bransje.identifikatorer)
.addValue("arstall", fraÅrstallOgKvartal.årstall)
.addValue("kvartal", fraÅrstallOgKvartal.kvartal)
) { rs: ResultSet, _: Int -> mapTilUmaskertSykefraværForEttKvartal(rs) }
} catch (e: EmptyResultDataAccessException) {
emptyList()
}
}
fun hentUmaskertSykefravær(
næring: Næring, fraÅrstallOgKvartal: ÅrstallOgKvartal
): List<UmaskertSykefraværForEttKvartal> {
return try {
namedParameterJdbcTemplate.query(
"SELECT tapte_dagsverk, mulige_dagsverk, antall_personer, arstall, kvartal "
+ "FROM sykefravar_statistikk_naring "
+ "where naring_kode = :naringKode "
+ "and ("
+ " (arstall = :arstall and kvartal >= :kvartal) "
+ " or "
+ " (arstall > :arstall)"
+ ") "
+ "ORDER BY arstall, kvartal ",
MapSqlParameterSource()
.addValue("naringKode", næring.tosifferIdentifikator)
.addValue("arstall", fraÅrstallOgKvartal.årstall)
.addValue("kvartal", fraÅrstallOgKvartal.kvartal)
) { rs: ResultSet, _: Int -> mapTilUmaskertSykefraværForEttKvartal(rs) }.sorted()
} catch (e: EmptyResultDataAccessException) {
emptyList()
}
}
fun hentTotaltSykefraværAlleKategorier(
virksomhet: Virksomhet, kvartaler: List<ÅrstallOgKvartal>
): Sykefraværsdata {
val næring = virksomhet.næringskode.næring
val maybeBransje = finnBransje(virksomhet.næringskode)
val data: MutableMap<Statistikkategori, List<UmaskertSykefraværForEttKvartal>> =
EnumMap(Statistikkategori::class.java)
val fraÅrstallOgKvartal = kvartaler.minOf { it }
data[Statistikkategori.VIRKSOMHET] = sykefravarStatistikkVirksomhetRepository.hentUmaskertSykefravær(virksomhet,
fraÅrstallOgKvartal
)
data[Statistikkategori.LAND] = sykefraværStatistikkLandRepository.hentForKvartaler(kvartaler)
if (maybeBransje.isEmpty) {
data[Statistikkategori.NÆRING] = hentUmaskertSykefravær(næring, fraÅrstallOgKvartal)
} else if (maybeBransje.get().erDefinertPåFemsiffernivå()) {
data[Statistikkategori.BRANSJE] = hentUmaskertSykefravær(maybeBransje.get(), fraÅrstallOgKvartal)
} else {
data[Statistikkategori.BRANSJE] = hentUmaskertSykefravær(næring, fraÅrstallOgKvartal)
}
return Sykefraværsdata(data)
}
@Throws(SQLException::class)
private fun mapTilUmaskertSykefraværForEttKvartal(rs: ResultSet): UmaskertSykefraværForEttKvartal {
return UmaskertSykefraværForEttKvartal(
ÅrstallOgKvartal(rs.getInt("arstall"), rs.getInt("kvartal")),
rs.getBigDecimal("tapte_dagsverk"),
rs.getBigDecimal("mulige_dagsverk"),
rs.getInt("antall_personer")
)
}
}
| 1 | Kotlin | 2 | 0 | 191af660dab3357092d0ceed927d5ffcc41a0a39 | 5,349 | sykefravarsstatistikk-api | MIT License |
ledger/core/db/src/main/kotlin/org/knowledger/ledger/database/ManagedSchema.kt | andrediogo92 | 122,662,386 | false | {"Kotlin": 795385, "Rust": 9666, "Python": 228} | package org.knowledger.ledger.database
interface ManagedSchema {
fun createProperty(
key: String, value: StorageType
): SchemaProperty
fun dropProperty(key: String)
fun declaredPropertyNames(): List<String>
fun addCluster(clusterName: String): ManagedSchema
} | 0 | Kotlin | 1 | 3 | 0e5121243b9faf101b6d2ccf5bce60a657a31b4e | 290 | KnowLedger | MIT License |
src/main/kotlin/gui/UiState.kt | JOwney96 | 876,459,526 | false | {"Kotlin": 33250, "Java": 30866} | package gui
import repository.EWinner
import repository.Statistics
data class UiState(
val board: List<List<Char>>,
val winner: EWinner = EWinner.NONE,
val stats: Statistics
)
| 0 | Kotlin | 0 | 0 | 82c502a6c350a30321eacee92e11682c7849b8c5 | 190 | TicTacToeCompose | Apache License 2.0 |
android/src/main/java/com/reminder/model/ReminderModel.kt | kienndhn | 700,395,140 | false | {"Java": 7154, "Kotlin": 5999, "Ruby": 3953, "JavaScript": 3028, "Objective-C": 2515, "TypeScript": 1619, "Objective-C++": 1145, "C": 103, "Swift": 60} | package com.reminder.model
import android.icu.util.Calendar
class ReminderModel(
ownerId: Int,
metadata: String,
hour: Int,
minute: Int,
second: Int,
date: Int,
month: Int,
year: Int,
isRepeated: Boolean,
title: String,
message: String,
notificationId: Int,
id: Int
) {
}
| 1 | null | 1 | 1 | 834ee408811a794ae354056456e074cbeb71b122 | 302 | react-native-reminder | MIT License |
app/src/main/java/com/cyh128/hikari_novel/data/source/local/database/search_history/SearchHistoryDao.kt | 15dd | 645,796,447 | false | {"Kotlin": 332962} | package com.cyh128.hikari_novel.data.source.local.database.search_history
import androidx.room.Dao
import androidx.room.Query
import androidx.room.Upsert
@Dao
interface SearchHistoryDao {
@Query("SELECT keyword FROM search_history")
suspend fun getAll(): List<String>?
@Upsert
suspend fun upsert(searchHistoryEntity: SearchHistoryEntity)
@Query("DELETE FROM search_history")
suspend fun deleteAll()
} | 1 | Kotlin | 12 | 400 | 402efc07ced528fc939d5d645e1f8a8f07636f40 | 428 | wenku8reader | MIT License |
app/src/main/java/com/example/myapplication/kotlindemo/util/KotlinTest.kt | zhou199864 | 261,087,427 | false | null | package com.example.myapplication.kotlindemo.util
import kotlinx.coroutines.*
fun main() {
// runBlocking {
// launch {
// println("launch1")
// delay(1000)
// println("launch1 finished")
// }
// launch {
// println("launch2")
// delay(1000)
// println("launch2 finished")
// }
// }
// Thread.sleep(1000)
val start = System.currentTimeMillis()
runBlocking {
repeat(100000){
launch {
println(".")
}
}
}
val end = System.currentTimeMillis()
println("time is ${end - start}")
}
suspend fun printDot() = coroutineScope{
launch {
println(".")
delay(1000)
}
} | 0 | Kotlin | 0 | 0 | 7d7e838631c55ff6bff410440c5b807fa0fde024 | 759 | KotlinDemo | Apache License 2.0 |
app/src/main/java/com/github/emresarincioglu/groups/repository/paging/MemberPagingSource.kt | emresarincioglu | 604,255,192 | false | null | package com.github.emresarincioglu.groups.repository.paging
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.github.emresarincioglu.groups.repository.FirebaseRepository
import com.github.emresarincioglu.groups.repository.model.MemberListItemUiState
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
class MemberPagingSource(
private val repository: FirebaseRepository,
private val groupId: String,
private val pageSize: Int
) :
PagingSource<Int, Flow<MemberListItemUiState>>() {
private var first: String? = null
private var last: String? = null
private var prevPageNumber: Int = 0
override fun getRefreshKey(state: PagingState<Int, Flow<MemberListItemUiState>>): Int? {
return state.anchorPosition?.let { position ->
val page = state.closestPageToPosition(position)
page?.prevKey?.plus(1) ?: page?.nextKey?.minus(1)
}
}
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Flow<MemberListItemUiState>> {
return try {
val pageNumber = params.key ?: 1
val pageData = when {
pageNumber == 1 -> repository.getFirstMemberPage(groupId, pageSize)
pageNumber < prevPageNumber -> repository.getMemberPageBefore(first, groupId, pageSize)
pageNumber > prevPageNumber -> repository.getMemberPageAfter(last, groupId, pageSize)
else -> emptyList()
}
prevPageNumber = pageNumber
pageData.run {
first = firstOrNull()?.first()?.userId
last = lastOrNull()?.first()?.userId
}
LoadResult.Page(
data = pageData,
prevKey = if (pageNumber == 1) null else pageNumber - 1,
nextKey = if (pageData.isEmpty()) null else pageNumber + 1
)
} catch (e: Exception) {
LoadResult.Error(e)
}
}
} | 0 | Kotlin | 0 | 0 | f0bf1fc464d4d1433462cab04597202ff8c7fba8 | 1,998 | groups-app | MIT License |
rxadapter/src/main/kotlin/xyz/marcb/rxadapter/AdapterPart.kt | chetbox | 133,830,706 | true | {"Kotlin": 28405, "Java": 729} | package xyz.marcb.rxadapter
import android.support.v7.widget.RecyclerView
import rx.Observable
interface AdapterPart {
val snapshots: Observable<AdapterPartSnapshot>
val visible: Observable<Boolean>?
}
interface AdapterPartSnapshot {
val itemIds: List<String>
val itemCount: Int get() = itemIds.size
fun viewHolderClass(index: Int): Class<out RecyclerView.ViewHolder>
fun bind(viewHolder: RecyclerView.ViewHolder, index: Int)
fun underlyingObject(index: Int): Any?
}
internal fun AdapterPart.compose(): Observable<AdapterPartSnapshot> {
val visible = visible ?: return snapshots
return visible.switchMap { isVisible ->
if (isVisible) snapshots else Observable.just(EmptySnapshot())
}
}
internal fun List<AdapterPart>.combine(): Observable<AdapterPartSnapshot> {
return Observable.combineLatest(map(AdapterPart::compose)) { snapshots ->
CompositeAdapterPartSnapshot(snapshots.map { snapshot -> snapshot as AdapterPartSnapshot })
}
}
internal class EmptySnapshot : AdapterPartSnapshot {
override val itemIds: List<String> = emptyList()
override fun viewHolderClass(index: Int): Class<out RecyclerView.ViewHolder> {
error("Internal error: Attempted to get view holder class from an empty snapshot")
}
override fun bind(viewHolder: RecyclerView.ViewHolder, index: Int) {
error("Internal error: Attempted to bind view holder to an empty snapshot")
}
override fun underlyingObject(index: Int): Any {
error("Internal error: Attempted to get underlying object of an empty snapshot")
}
} | 0 | Kotlin | 0 | 0 | bbd87077e3147e8e49e45d43ee881ebb72f70e42 | 1,607 | RxAdapter | MIT License |
core/src/main/java/com/github/korniloval/flameviewer/server/ServerOptionsProvider.kt | QiangCai | 254,810,326 | true | {"Kotlin": 177764, "JavaScript": 100160, "Java": 52019, "CSS": 21077, "HTML": 18358, "Shell": 235} | package com.github.korniloval.flameviewer.server
interface ServerOptionsProvider {
fun opt(): ServerOptions
}
class ServerOptionsProviderImpl(var options: ServerOptions) : ServerOptionsProvider {
override fun opt() = options
}
| 0 | null | 0 | 0 | 84a89a09aa787e9b9dce14c6a708542905e4895a | 237 | FlameViewer | MIT License |
src/main/kotlin/derivean/game/ability/abilities/AbstractAttackAbility.kt | marek-hanzal | 259,577,282 | false | null | package derivean.game.ability.abilities
import derivean.game.ability.AbstractAbility
import derivean.game.attribute.Attributes
abstract class AbstractAttackAbility(ability: String, attributes: Attributes) : AbstractAbility(ability, attributes)
| 112 | Kotlin | 0 | 1 | 7a485228438c5fb9a61b1862e8164f5e87361e4a | 246 | DeRivean | Apache License 2.0 |
kotlin-electron/src/jsMain/generated/electron/main/ConfigureHostResolverOptions.kt | JetBrains | 93,250,841 | false | {"Kotlin": 12635434, "JavaScript": 423801} | // Generated by Karakum - do not modify it manually!
package electron.main
typealias ConfigureHostResolverOptions = electron.core.ConfigureHostResolverOptions
| 38 | Kotlin | 162 | 1,347 | 997ed3902482883db4a9657585426f6ca167d556 | 161 | kotlin-wrappers | Apache License 2.0 |
app/src/main/java/com/coffeeandcookies/cursokotlin/dao/TasksDao.kt | benoffi7 | 282,959,287 | false | null | package com.coffeeandcookies.cursokotlin.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import com.coffeeandcookies.cursokotlin.data.TaskEntity
@Dao
interface TasksDao
{
@Query("Select * from tasks_entity")
fun getAllTasks(): MutableList<TaskEntity>
@Insert
fun addTask(taskEntity : TaskEntity):Long
@Query("SELECT * FROM tasks_entity where id like :id")
fun getTaskById(id: Long): TaskEntity
} | 0 | Kotlin | 0 | 1 | 49fc260bbf692378bf5e02728015d916e3162488 | 460 | curso-kotlin | MIT License |
library/compose-utils/src/main/kotlin/ru/pixnews/library/compose/utils/LocaleUtils.kt | illarionov | 305,333,284 | false | null | /*
* 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.pixnews.library.compose.utils
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.ui.platform.LocalConfiguration
import androidx.core.os.ConfigurationCompat
import java.util.Locale
/**
* A composable function that returns the default [Locale]. It will be recomposed when the
* `Configuration` gets updated.
*/
@Composable
@ReadOnlyComposable
public fun defaultLocale(): Locale {
return ConfigurationCompat.getLocales(LocalConfiguration.current).get(0) ?: Locale.getDefault()
}
| 0 | Kotlin | 0 | 2 | d806ee06019389c78546d946f1c20d096afc7c6e | 1,153 | Pixnews | Apache License 2.0 |
src/main/kotlin/no/nav/tms/utbetalingsoversikt/api/ytelse/SokosUtbetalingConsumer.kt | navikt | 418,463,132 | false | {"Kotlin": 117036, "Dockerfile": 158} | package no.nav.tms.utbetalingsoversikt.api.ytelse
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.http.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import no.nav.tms.token.support.idporten.sidecar.user.IdportenUser
import no.nav.tms.token.support.tokendings.exchange.TokendingsService
import no.nav.tms.utbetalingsoversikt.api.ytelse.domain.external.*
import java.net.URL
import java.time.LocalDate
class SokosUtbetalingConsumer(
private val client: HttpClient,
baseUrl: URL,
private val sokosUtbetaldataClientId: String,
private val tokendingsService: TokendingsService,
) {
private val utbetalingsinformasjonInternUrl = URL("$baseUrl/hent-utbetalingsinformasjon/ekstern")
suspend fun fetchUtbetalingsInfo(user: IdportenUser, fom: LocalDate, tom: LocalDate): List<UtbetalingEkstern> {
val targetToken = tokendingsService.exchangeToken(user.tokenString, sokosUtbetaldataClientId)
val requestBody = createRequest(user.ident, fom, tom, RolleEkstern.UTBETALT_TIL)
return client.post(utbetalingsinformasjonInternUrl, requestBody, targetToken)
}
private fun createRequest(fnr: String, fom: LocalDate, tom: LocalDate, rolle: RolleEkstern): Utbetalingsoppslag {
val periode = PeriodeEkstern(
fom = fom.toString(),
tom = tom.plusDays(1).toString() // Compensate for external service being end-exclusive.
)
return Utbetalingsoppslag(
ident = fnr,
rolle = rolle,
periode = periode,
periodetype = PeriodetypeEkstern.UTBETALINGSPERIODE
)
}
}
suspend inline fun <reified T> HttpClient.post(url: URL, requestBody: Any, token: String): T = withContext(Dispatchers.IO) {
request {
url("$url")
method = HttpMethod.Post
header(HttpHeaders.Authorization, "Bearer $token")
contentType(ContentType.Application.Json)
setBody(requestBody)
}.let { response ->
if ( response.status != HttpStatusCode.OK ){
throw ApiException(response.status, url)
} else response
}.body()
}
class ApiException (private val statusCode: HttpStatusCode, private val url: URL) : Exception () {
val errorMessage = "Kall mot ${url.host} feiler med statuskode $statusCode"
} | 1 | Kotlin | 0 | 0 | 7114b5baafc290768168989225944123da91a3af | 2,366 | tms-utbetalingsoversikt-api | MIT License |
app/src/main/java/com/shencoder/srs_rtc_android_client/helper/call/bean/ResInviteeInfoBean.kt | shenbengit | 444,852,543 | false | {"Kotlin": 275977} | package com.shencoder.srs_rtc_android_client.helper.call.bean
import android.os.Parcelable
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import kotlinx.parcelize.Parcelize
/**
*
* @author ShenBen
* @date 2022/1/27 10:13
* @email <EMAIL>
*/
@Parcelize
@JsonClass(generateAdapter = true)
data class ResInviteeInfoBean(
/**
* 被邀请信息
*/
@Json(name = "inviteeInfo")
val inviteeInfo: ClientInfoBean,
/**
* 房间号
*/
@Json(name = "roomId")
val roomId: String
) : Parcelable | 0 | Kotlin | 9 | 41 | c14bb9df72e542d3f4f187b47bab15bf68bb2886 | 540 | SrsRtcAndroidClient | MIT License |
src/test/kotlin/io/thelandscape/KrawlHistoryDaoTest.kt | brianmadden | 71,804,596 | false | null | package io.thelandscape
/**
* Created by <EMAIL> on 12/24/16.
*
* Copyright (c) <2016> <H, llc>
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import com.github.andrewoma.kwery.core.DefaultSession
import com.github.andrewoma.kwery.core.Session
import com.github.andrewoma.kwery.core.dialect.HsqlDialect
import com.github.andrewoma.kwery.core.interceptor.LoggingInterceptor
import io.thelandscape.krawler.crawler.History.KrawlHistoryHSQLDao
import io.thelandscape.krawler.http.KrawlUrl
import org.junit.Before
import org.junit.Test
import java.sql.Connection
import java.sql.DriverManager
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlin.test.assertFalse
class KrawlHistoryDaoTest {
val connection: Connection = DriverManager.getConnection("jdbc:hsqldb:mem:testdb", "", "")
val session: Session = DefaultSession(connection, HsqlDialect(), LoggingInterceptor())
val krawlHistoryDao: KrawlHistoryHSQLDao = KrawlHistoryHSQLDao(session)
@Before fun setUp() {
session.update("DROP TABLE KrawlHistory")
session.update("CREATE TABLE IF NOT EXISTS KrawlHistory " +
"(id INT IDENTITY, url VARCHAR(255), timestamp TIMESTAMP)")
val ins = KrawlUrl.new("http://www.test.com")
val ins2 = KrawlUrl.new("http://www.test2.com")
krawlHistoryDao.insert(ins)
krawlHistoryDao.insert(ins2)
}
@Test fun testInsert() {
// Insert a new URL
val ins = KrawlUrl.new("http://www.test2.com")
val ret = krawlHistoryDao.insert(ins)
// The ID should be 2 since the inserts in setUp should be 1 & 2
assertEquals(2, ret.id)
}
@Test fun testClearHistory() {
val cleared = krawlHistoryDao.clearHistory()
assertTrue { cleared >= 1 }
}
@Test fun testHasBeenSeen() {
val url = KrawlUrl.new("http://www.test.com/")
krawlHistoryDao.insert(url)
val wasSeen = krawlHistoryDao.hasBeenSeen(url)
assertTrue(wasSeen)
val wasSeen2 = krawlHistoryDao.hasBeenSeen(KrawlUrl.new("www.foo.org"))
assertFalse(wasSeen2)
}
} | 6 | Kotlin | 17 | 128 | d58e901e427a52874c164111db6c4013e71ffec3 | 3,136 | krawler | MIT License |
browser-kotlin/src/jsMain/kotlin/web/vtt/Event.types.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6212172} | // Automatically generated - do not modify!
@file:Suppress(
"NOTHING_TO_INLINE",
)
package web.vtt
import web.events.Event
import web.events.EventType
inline fun Event.Companion.cueChange(): EventType<Event> =
EventType("cuechange")
inline fun Event.Companion.enter(): EventType<Event> =
EventType("enter")
inline fun Event.Companion.exit(): EventType<Event> =
EventType("exit")
| 0 | Kotlin | 7 | 35 | e681a7be1ea3bcd97be311cedfb614c3a1b5bbc6 | 401 | types-kotlin | Apache License 2.0 |
solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Retract.kt | zakski | 292,287,783 | true | {"Kotlin": 2055564, "ANTLR": 20096, "JavaScript": 13636, "Java": 13453} | package it.unibo.tuprolog.solve.stdlib.primitive
import it.unibo.tuprolog.core.*
import it.unibo.tuprolog.core.Var
import it.unibo.tuprolog.solve.ExecutionContext
import it.unibo.tuprolog.solve.primitive.Solve
import it.unibo.tuprolog.solve.primitive.UnaryPredicate
import it.unibo.tuprolog.unify.Unificator.Companion.mguWith
import it.unibo.tuprolog.utils.buffered
object Retract : UnaryPredicate<ExecutionContext>("retract") {
override fun Solve.Request<ExecutionContext>.computeAll(first: Term): Sequence<Solve.Response> {
ensuringArgumentIsStruct(0)
val clause = if (first is Clause) first else Rule.of(first as Struct, Var.anonymous())
return context.dynamicKb[clause].buffered().map {
val substitution = when (first) {
is Clause -> (first mguWith it) as Substitution.Unifier
else -> (first mguWith it.head!!) as Substitution.Unifier
}
replySuccess(substitution) {
removeDynamicClauses(it)
}
}
}
} | 0 | null | 0 | 0 | bbd63f9ba2091651f22eca7b0d3c7f1edee1e8ea | 1,040 | thunderjaw | Apache License 2.0 |
admin/src/jsMain/kotlin/ant/DatePicker.kt | DXueShengKa | 846,092,089 | false | {"Kotlin": 112737, "Swift": 621, "HTML": 362, "CSS": 221, "PLpgSQL": 202} | @file:JsModule("antd")
package ant
import react.FC
import react.Props
import kotlin.js.Date
external interface DatePickerProps : Props {
var onChange: (Date, String) -> Unit
}
external val DatePicker: FC<DatePickerProps>
| 0 | Kotlin | 0 | 0 | f642a53a91cecd323e3f4d0721a6138d64af8f3d | 231 | AllInKt | Apache License 2.0 |
android/app/src/main/kotlin/com/example/uome2/MainActivity.kt | VeryOpenSource | 471,476,533 | false | {"Dart": 13268, "HTML": 3922, "Swift": 404, "Kotlin": 122, "Objective-C": 38} | package com.example.uome2
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 6 | Dart | 0 | 0 | 4aced5ae3e45acacf2d49456f74623a0472a1d3b | 122 | uome2_client | Apache License 2.0 |
library/src/commonMain/kotlin/dev/afalabarce/kmm/jetpackcompose/LabelledSwitch.kt | afalabarce | 813,304,744 | false | {"Kotlin": 117698, "Ruby": 2250} | package dev.afalabarce.kmm.jetpackcompose
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.selection.toggleable
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.ui.tooling.preview.Preview
@Composable
fun LabelledSwitch(
modifier: Modifier = Modifier,
checked: Boolean,
label: String,
labelStyle: TextStyle = MaterialTheme.typography.labelMedium,
leadingIcon: @Composable () -> Unit = {},
enabled: Boolean = true,
colors: SwitchColors = SwitchDefaults.colors(),
onCheckedChange: ((Boolean) -> Unit)
) {
Row(
modifier = modifier
.height(56.dp)
.padding(horizontal = 8.dp)
.toggleable(
value = checked,
onValueChange = onCheckedChange,
role = Role.Switch,
enabled = enabled
),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Start
) {
leadingIcon()
Text(
text = label,
style = labelStyle,
modifier = Modifier.weight(1f)
.padding(end = 16.dp)
)
Switch(
checked = checked,
onCheckedChange = null,
enabled = enabled,
colors = colors,
modifier = Modifier.padding(start = 8.dp)
)
}
}
@Preview
@Composable
private fun PreviewSwitchChecked() {
Surface {
Column {
LabelledSwitch(
modifier = Modifier.fillMaxWidth(),
checked = true,
label = "Hola Checks",
) {
}
}
}
}
@Preview
@Composable
private fun PreviewSwitchUnChecked() {
Surface {
Column {
LabelledSwitch(
modifier = Modifier.fillMaxWidth(),
checked = false,
label = "Hola Checks",
) {
}
}
}
} | 0 | Kotlin | 0 | 0 | 8839e9134b03c924259dd06fa94fbc8671d76889 | 2,209 | kmm-jetpackcompose | Apache License 2.0 |
app/src/main/java/com/android/sample/bonial/response/ContentType.kt | alirezaeiii | 499,189,686 | false | {"Kotlin": 34609} | package com.android.sample.bonial.response
enum class ContentType {
brochure,
brochurePremium,
cashbackOffersV2,
rateUs,
superBannerCarousel,
storyCarousel,
blogCarousel,
referral
} | 0 | Kotlin | 0 | 0 | f14446621a719ea5baeb89de0fbd419599d506fd | 214 | Brochures-Cache | The Unlicense |
starrysky/src/main/java/com/lzx/starrysky/playback/manager/IPlaybackManager.kt | xiongsongyu2016 | 214,321,300 | false | null | package com.lzx.starrysky.playback.manager
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
import com.lzx.starrysky.notification.INotification
import com.lzx.starrysky.provider.MediaQueueProvider
interface IPlaybackManager {
val mediaSessionCallback: MediaSessionCompat.Callback
/**
* 是否在播放
*/
val isPlaying: Boolean
fun setServiceCallback(serviceCallback: PlaybackServiceCallback)
fun setMetadataUpdateListener(listener: MediaQueueProvider.MetadataUpdateListener)
/**
* 播放
*/
fun handlePlayRequest(isPlayWhenReady: Boolean)
/**
* 暂停
*/
fun handlePauseRequest()
/**
* 停止
*/
fun handleStopRequest(withError: String?)
/**
* 快进
*/
fun handleFastForward()
/**
* 倒带
*/
fun handleRewind()
/**
* 指定语速 refer 是否已当前速度为基数 multiple 倍率
*/
fun handleDerailleur(refer: Boolean, multiple: Float)
/**
* 更新播放状态
*/
fun updatePlaybackState(isOnlyUpdateActions: Boolean, error: String?)
fun registerNotification(notification: INotification)
interface PlaybackServiceCallback {
fun onPlaybackStart()
fun onNotificationRequired()
fun onPlaybackStop(isStop: Boolean)
fun onPlaybackStateUpdated(
newState: PlaybackStateCompat, currMetadata:
MediaMetadataCompat?
)
fun onShuffleModeUpdated(shuffleMode: Int)
fun onRepeatModeUpdated(repeatMode: Int)
}
}
| 0 | null | 0 | 1 | e83d70726ce5a8008669d4244ca705f858da9200 | 1,620 | StarrySky | MIT License |
src/com/kotlin/collection/ArrayList_Example.kt | hussainahmad | 116,094,733 | false | null | package com.kotlin.collection
/**
* Created by <NAME>
* at 1:09 PM on 1/3/2018
* <EMAIL> .
*/
fun main(args: Array<String>) {
// Array list are mutable while array are immutable we cannot change their size
val arrayList : ArrayList<String> = arrayListOf("My", "Name ", "Is") //arrayList are immutable , you can change the content
arrayList.add("Hussain")
println(arrayList[3])
// When we concatenate tow ArrayList it become List instead of ArrayList
val list : ArrayList<String> = arrayListOf("Ahmad", "Khan")
val mix : List<String> = arrayList + list
println(mix.size)
println(mix.contains("Hussain"))
println(mix.isEmpty())
// As List are immutable we can add or remove its value
// mix.add give error
// mix.remove give error
// /// Difference between ArrayList and array....... we can change the size of an ArrayList but not Array... Arrays has always fixed size
list.add("Bilal")
list.add(0, "Hussain")
println(list)
// Using contains method
println(list.contains("Zubair"))
list.add("Usama")
// we can also add value in a special index
list.add(1, "khan")
println(list)
//
val remove : Boolean = list.remove("Usama khan")
println(remove)
println(list)
val sublist = list.subList(0, 3) //Returns a view of the portion of this
// list between the specified fromIndex (inclusive) and toIndex (exclusive).
println(sublist)
} | 0 | Kotlin | 0 | 0 | d5c2e90a43e9143971c36bfcf9bc6902fbdaf182 | 1,448 | Introduction-To-Kotlin | Apache License 2.0 |
browser-kotlin/src/jsMain/kotlin/js/intl/ResolvedPluralRulesOptions.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6914539} | // Automatically generated - do not modify!
package js.intl
import js.array.ReadonlyArray
import js.objects.JsPlainObject
@JsPlainObject
sealed external interface ResolvedPluralRulesOptions {
var locale: String
var pluralCategories: ReadonlyArray<LDMLPluralRule>
var type: PluralRuleType
var minimumIntegerDigits: Int
var minimumFractionDigits: Int
var maximumFractionDigits: Int
var minimumSignificantDigits: Int?
var maximumSignificantDigits: Int?
}
| 0 | Kotlin | 7 | 31 | c3de7c4098277a67bd40a9f0687579a6b9956cb2 | 487 | types-kotlin | Apache License 2.0 |
core/database/src/main/kotlin/com/example/hnotes/core/database/dao/SearchQueryDao.kt | hmzgtl16 | 851,784,002 | false | {"Kotlin": 596179} | package com.example.hnotes.core.database.dao
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Query
import androidx.room.Upsert
import com.example.hnotes.core.database.model.SearchQueryEntity
import kotlinx.coroutines.flow.Flow
@Dao
interface SearchQueryDao {
@Query(value = "SELECT * FROM table_search_query ORDER BY search_query_queried DESC LIMIT :limit")
fun getSearchQueries(limit: Int): Flow<List<SearchQueryEntity>>
@Upsert
suspend fun upsertSearchQuery(searchQuery: SearchQueryEntity)
@Query(value = "DELETE FROM table_search_query")
suspend fun deleteAll()
@Delete
suspend fun delete(searchQueryEntity: SearchQueryEntity)
} | 0 | Kotlin | 0 | 1 | 17adddc10a17af2db22adc5093f78b29b1ef3636 | 695 | HNotes | MIT License |
server/src/test/kotlin/io/titandata/storage/zfs/ZfsStorageProviderTest.kt | CloudSurgeon | 212,463,880 | true | {"Kotlin": 586314, "Shell": 46347, "Java": 9931, "Dockerfile": 904} | /*
* Copyright The Titan Project Contributors.
*/
package io.titandata.storage.zfs
import io.kotlintest.TestCase
import io.kotlintest.TestCaseOrder
import io.kotlintest.TestResult
import io.kotlintest.shouldBe
import io.kotlintest.shouldThrow
import io.kotlintest.specs.StringSpec
import io.mockk.MockKAnnotations
import io.mockk.clearAllMocks
import io.mockk.confirmVerified
import io.mockk.every
import io.mockk.impl.annotations.InjectMockKs
import io.mockk.impl.annotations.MockK
import io.mockk.impl.annotations.OverrideMockKs
import io.mockk.verifySequence
import io.titandata.exception.CommandException
import io.titandata.exception.InvalidStateException
import io.titandata.exception.NoSuchObjectException
import io.titandata.util.CommandExecutor
class ZfsStorageProviderTest : StringSpec() {
@MockK
lateinit var executor: CommandExecutor
@InjectMockKs
@OverrideMockKs
var provider = ZfsStorageProvider("test")
override fun beforeTest(testCase: TestCase) {
return MockKAnnotations.init(this)
}
override fun afterTest(testCase: TestCase, result: TestResult) {
clearAllMocks()
}
override fun testCaseOrder() = TestCaseOrder.Random
/**
* Utility method that will convert the openapi-generated properties type into a map that can
* be used within kotlin. This avoids the needless proliferation of UNCHECKED_CAST warnings.
*/
fun getProperties(properties: Any): Map<String, Any> {
@Suppress("UNCHECKED_CAST")
return properties as Map<String, Any>
}
init {
"valid metadata is parsed correctly" {
val result = provider.parseMetadata("{ \"foo\": \"bar\" }")
result["foo"] shouldBe "bar"
}
"invalid metadata throws an exception" {
shouldThrow<InvalidStateException> {
provider.parseMetadata("this is not JSON")
}
}
"complex metadata is parsed correctly" {
val result = provider.parseMetadata("{ \"a\": 1, \"b\": { \"c\": \"two\" }}")
result["a"] shouldBe 1.0
getProperties(result.getValue("b"))["c"] shouldBe "two"
}
"tabs are allowed in metadata" {
val result = provider.parseMetadata("{\t\"a\": \"b\tc\" }")
result["a"] shouldBe "b\tc"
}
"validate name works for all characters" {
provider.validateName("aB5:.-_aG", ZfsStorageProvider.ObjectType.REPOSITORY)
}
"validate name fails for zero length name" {
shouldThrow<IllegalArgumentException> {
provider.validateName("", ZfsStorageProvider.ObjectType.REPOSITORY)
}
}
"validate name fails for invalid character" {
shouldThrow<IllegalArgumentException> {
provider.validateName("not/allowed", ZfsStorageProvider.ObjectType.REPOSITORY)
}
}
"get active dataset returns correct dataset" {
every { executor.exec(*anyVararg()) } returns "guid"
val dataset = provider.getActive("foo")
dataset shouldBe "guid"
}
"get active dataset throws error for no such dataset" {
every { executor.exec(*anyVararg()) } throws CommandException("", 1, "does not exist")
shouldThrow<NoSuchObjectException> {
provider.getActive("foo")
}
}
"clone commit with no volumes creates empty dataset" {
every { executor.exec(*anyVararg()) } returns ""
provider.cloneCommit("foo", "guid", "hash", "newguid")
verifySequence {
executor.exec("zfs", "list", "-rHo", "name,io.titan-data:metadata", "test/repo/foo/guid")
executor.exec("zfs", "create", "test/repo/foo/newguid")
}
confirmVerified()
}
"clone commit clones all volumes" {
every { executor.exec("zfs", "list", "-rHo", "name,io.titan-data:metadata", "test/repo/foo/guid") } returns
arrayOf("test/repo/foo/guid\t-", "test/repo/foo/guid/v0\t{\"a\":\"b\"}", "test/repo/foo/guid/v1\t{\"b\":\"c\"}").joinToString("\n")
every { executor.exec("zfs", "create", "test/repo/foo/newguid") } returns ""
every { executor.exec("zfs", "clone", "-o", "io.titan-data:metadata={\"a\":\"b\"}", "test/repo/foo/guid/v0@hash",
"test/repo/foo/newguid/v0") } returns ""
every { executor.exec("zfs", "clone", "-o", "io.titan-data:metadata={\"b\":\"c\"}", "test/repo/foo/guid/v1@hash",
"test/repo/foo/newguid/v1") } returns ""
provider.cloneCommit("foo", "guid", "hash", "newguid")
verifySequence {
executor.exec("zfs", "list", "-rHo", "name,io.titan-data:metadata", "test/repo/foo/guid")
executor.exec("zfs", "create", "test/repo/foo/newguid")
executor.exec("zfs", "clone", "-o", "io.titan-data:metadata={\"a\":\"b\"}", "test/repo/foo/guid/v0@hash", "test/repo/foo/newguid/v0")
executor.exec("zfs", "clone", "-o", "io.titan-data:metadata={\"b\":\"c\"}", "test/repo/foo/guid/v1@hash", "test/repo/foo/newguid/v1")
}
confirmVerified()
}
}
}
| 0 | Kotlin | 0 | 1 | 819f7e9ea1bb0c675e0d04d61cf05302c488d74f | 5,302 | titan-server | Apache License 2.0 |
Animations/app/src/main/java/com/eblimonv/animations/ui/code/AnimationListener.kt | balam909 | 314,422,884 | false | null | package com.eblimonv.animations.ui.code
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.view.animation.ScaleAnimation
import android.widget.Button
import android.widget.TextView
import com.eblimonv.animations.R
/**
* A simple [Fragment] subclass.
* Use the [AnimationListener.newInstance] factory method to
* create an instance of this fragment.
*/
class AnimationListener : Fragment(), Animation.AnimationListener {
private var i : Int = 0;
private var textViewObject : TextView? = null
private var scale : ScaleAnimation? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val root : View = inflater.inflate(R.layout.fragment_animation_listener, container, false)
val textViewSubject : TextView = root.findViewById(R.id.text_animation_series_title)
textViewSubject.text = "Usando la Interfaz Animation Listener"
textViewObject = root.findViewById(R.id.text_animation_series)
textViewObject?.text = "CONTADOR = "+i
val button : Button = root.findViewById(R.id.b_start_animation_series)
button.setOnClickListener{startAnimation()}
return root
}
private fun startAnimation(){
// animación aparición
val appearance = AlphaAnimation(0F,1F);
appearance.duration = 1000
appearance.fillAfter = true;
appearance.repeatMode = Animation.RESTART;
appearance.repeatCount = 10;
appearance.setAnimationListener(this);
// animación escalado
// rs indica que las coordenadas son relativas
val rs : Int = ScaleAnimation.RELATIVE_TO_SELF;
scale = ScaleAnimation(1F,2F,1F,5F,rs,0.5F,rs, 0.5F)
scale?.duration = 3000;
scale?.fillAfter = true;
textViewObject?.startAnimation(appearance);
}
override fun onAnimationStart(animation: Animation?) {
}
override fun onAnimationEnd(animation: Animation?) {
textViewObject?.text = "THE END";
textViewObject?.startAnimation(scale);
}
override fun onAnimationRepeat(animation: Animation?) {
i++
textViewObject?.text = "CONTADOR = " + i;
}
} | 0 | Kotlin | 0 | 0 | 9eb429e4ff4a86e2b1c4b7b3bc9cf152c9996fe9 | 2,483 | android | Creative Commons Zero v1.0 Universal |
src/main/kotlin/eZmaxApi/apis/ObjectEzsigntemplatepackagemembershipApi.kt | eZmaxinc | 271,950,932 | false | {"Kotlin": 6909939} | /**
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package eZmaxApi.apis
import java.io.IOException
import okhttp3.OkHttpClient
import okhttp3.HttpUrl
import eZmaxApi.models.CommonResponseError
import eZmaxApi.models.EzsigntemplatepackagemembershipCreateObjectV1Request
import eZmaxApi.models.EzsigntemplatepackagemembershipCreateObjectV1Response
import eZmaxApi.models.EzsigntemplatepackagemembershipDeleteObjectV1Response
import eZmaxApi.models.EzsigntemplatepackagemembershipGetObjectV2Response
import com.squareup.moshi.Json
import eZmaxApi.infrastructure.ApiClient
import eZmaxApi.infrastructure.ApiResponse
import eZmaxApi.infrastructure.ClientException
import eZmaxApi.infrastructure.ClientError
import eZmaxApi.infrastructure.ServerException
import eZmaxApi.infrastructure.ServerError
import eZmaxApi.infrastructure.MultiValueMap
import eZmaxApi.infrastructure.PartConfig
import eZmaxApi.infrastructure.RequestConfig
import eZmaxApi.infrastructure.RequestMethod
import eZmaxApi.infrastructure.ResponseType
import eZmaxApi.infrastructure.Success
import eZmaxApi.infrastructure.toMultiValue
class ObjectEzsigntemplatepackagemembershipApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = ApiClient.defaultClient) : ApiClient(basePath, client) {
companion object {
@JvmStatic
val defaultBasePath: String by lazy {
System.getProperties().getProperty(ApiClient.baseUrlKey, "https://prod.api.appcluster01.ca-central-1.ezmax.com/rest")
}
}
/**
* Create a new Ezsigntemplatepackagemembership
* The endpoint allows to create one or many elements at once.
* @param ezsigntemplatepackagemembershipCreateObjectV1Request
* @return EzsigntemplatepackagemembershipCreateObjectV1Response
* @throws IllegalStateException If the request is not correctly configured
* @throws IOException Rethrows the OkHttp execute method exception
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun ezsigntemplatepackagemembershipCreateObjectV1(ezsigntemplatepackagemembershipCreateObjectV1Request: EzsigntemplatepackagemembershipCreateObjectV1Request) : EzsigntemplatepackagemembershipCreateObjectV1Response {
val localVarResponse = ezsigntemplatepackagemembershipCreateObjectV1WithHttpInfo(ezsigntemplatepackagemembershipCreateObjectV1Request = ezsigntemplatepackagemembershipCreateObjectV1Request)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as EzsigntemplatepackagemembershipCreateObjectV1Response
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Create a new Ezsigntemplatepackagemembership
* The endpoint allows to create one or many elements at once.
* @param ezsigntemplatepackagemembershipCreateObjectV1Request
* @return ApiResponse<EzsigntemplatepackagemembershipCreateObjectV1Response?>
* @throws IllegalStateException If the request is not correctly configured
* @throws IOException Rethrows the OkHttp execute method exception
*/
@Suppress("UNCHECKED_CAST")
@Throws(IllegalStateException::class, IOException::class)
fun ezsigntemplatepackagemembershipCreateObjectV1WithHttpInfo(ezsigntemplatepackagemembershipCreateObjectV1Request: EzsigntemplatepackagemembershipCreateObjectV1Request) : ApiResponse<EzsigntemplatepackagemembershipCreateObjectV1Response?> {
val localVariableConfig = ezsigntemplatepackagemembershipCreateObjectV1RequestConfig(ezsigntemplatepackagemembershipCreateObjectV1Request = ezsigntemplatepackagemembershipCreateObjectV1Request)
return request<EzsigntemplatepackagemembershipCreateObjectV1Request, EzsigntemplatepackagemembershipCreateObjectV1Response>(
localVariableConfig
)
}
/**
* To obtain the request config of the operation ezsigntemplatepackagemembershipCreateObjectV1
*
* @param ezsigntemplatepackagemembershipCreateObjectV1Request
* @return RequestConfig
*/
fun ezsigntemplatepackagemembershipCreateObjectV1RequestConfig(ezsigntemplatepackagemembershipCreateObjectV1Request: EzsigntemplatepackagemembershipCreateObjectV1Request) : RequestConfig<EzsigntemplatepackagemembershipCreateObjectV1Request> {
val localVariableBody = ezsigntemplatepackagemembershipCreateObjectV1Request
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
localVariableHeaders["Content-Type"] = "application/json"
localVariableHeaders["Accept"] = "application/json"
return RequestConfig(
method = RequestMethod.POST,
path = "/1/object/ezsigntemplatepackagemembership",
query = localVariableQuery,
headers = localVariableHeaders,
requiresAuthentication = true,
body = localVariableBody
)
}
/**
* Delete an existing Ezsigntemplatepackagemembership
*
* @param pkiEzsigntemplatepackagemembershipID
* @return EzsigntemplatepackagemembershipDeleteObjectV1Response
* @throws IllegalStateException If the request is not correctly configured
* @throws IOException Rethrows the OkHttp execute method exception
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun ezsigntemplatepackagemembershipDeleteObjectV1(pkiEzsigntemplatepackagemembershipID: kotlin.Int) : EzsigntemplatepackagemembershipDeleteObjectV1Response {
val localVarResponse = ezsigntemplatepackagemembershipDeleteObjectV1WithHttpInfo(pkiEzsigntemplatepackagemembershipID = pkiEzsigntemplatepackagemembershipID)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as EzsigntemplatepackagemembershipDeleteObjectV1Response
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Delete an existing Ezsigntemplatepackagemembership
*
* @param pkiEzsigntemplatepackagemembershipID
* @return ApiResponse<EzsigntemplatepackagemembershipDeleteObjectV1Response?>
* @throws IllegalStateException If the request is not correctly configured
* @throws IOException Rethrows the OkHttp execute method exception
*/
@Suppress("UNCHECKED_CAST")
@Throws(IllegalStateException::class, IOException::class)
fun ezsigntemplatepackagemembershipDeleteObjectV1WithHttpInfo(pkiEzsigntemplatepackagemembershipID: kotlin.Int) : ApiResponse<EzsigntemplatepackagemembershipDeleteObjectV1Response?> {
val localVariableConfig = ezsigntemplatepackagemembershipDeleteObjectV1RequestConfig(pkiEzsigntemplatepackagemembershipID = pkiEzsigntemplatepackagemembershipID)
return request<Unit, EzsigntemplatepackagemembershipDeleteObjectV1Response>(
localVariableConfig
)
}
/**
* To obtain the request config of the operation ezsigntemplatepackagemembershipDeleteObjectV1
*
* @param pkiEzsigntemplatepackagemembershipID
* @return RequestConfig
*/
fun ezsigntemplatepackagemembershipDeleteObjectV1RequestConfig(pkiEzsigntemplatepackagemembershipID: kotlin.Int) : RequestConfig<Unit> {
val localVariableBody = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
localVariableHeaders["Accept"] = "application/json"
return RequestConfig(
method = RequestMethod.DELETE,
path = "/1/object/ezsigntemplatepackagemembership/{pkiEzsigntemplatepackagemembershipID}".replace("{"+"pkiEzsigntemplatepackagemembershipID"+"}", encodeURIComponent(pkiEzsigntemplatepackagemembershipID.toString())),
query = localVariableQuery,
headers = localVariableHeaders,
requiresAuthentication = true,
body = localVariableBody
)
}
/**
* Retrieve an existing Ezsigntemplatepackagemembership
*
* @param pkiEzsigntemplatepackagemembershipID
* @return EzsigntemplatepackagemembershipGetObjectV2Response
* @throws IllegalStateException If the request is not correctly configured
* @throws IOException Rethrows the OkHttp execute method exception
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun ezsigntemplatepackagemembershipGetObjectV2(pkiEzsigntemplatepackagemembershipID: kotlin.Int) : EzsigntemplatepackagemembershipGetObjectV2Response {
val localVarResponse = ezsigntemplatepackagemembershipGetObjectV2WithHttpInfo(pkiEzsigntemplatepackagemembershipID = pkiEzsigntemplatepackagemembershipID)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as EzsigntemplatepackagemembershipGetObjectV2Response
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Retrieve an existing Ezsigntemplatepackagemembership
*
* @param pkiEzsigntemplatepackagemembershipID
* @return ApiResponse<EzsigntemplatepackagemembershipGetObjectV2Response?>
* @throws IllegalStateException If the request is not correctly configured
* @throws IOException Rethrows the OkHttp execute method exception
*/
@Suppress("UNCHECKED_CAST")
@Throws(IllegalStateException::class, IOException::class)
fun ezsigntemplatepackagemembershipGetObjectV2WithHttpInfo(pkiEzsigntemplatepackagemembershipID: kotlin.Int) : ApiResponse<EzsigntemplatepackagemembershipGetObjectV2Response?> {
val localVariableConfig = ezsigntemplatepackagemembershipGetObjectV2RequestConfig(pkiEzsigntemplatepackagemembershipID = pkiEzsigntemplatepackagemembershipID)
return request<Unit, EzsigntemplatepackagemembershipGetObjectV2Response>(
localVariableConfig
)
}
/**
* To obtain the request config of the operation ezsigntemplatepackagemembershipGetObjectV2
*
* @param pkiEzsigntemplatepackagemembershipID
* @return RequestConfig
*/
fun ezsigntemplatepackagemembershipGetObjectV2RequestConfig(pkiEzsigntemplatepackagemembershipID: kotlin.Int) : RequestConfig<Unit> {
val localVariableBody = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
localVariableHeaders["Accept"] = "application/json"
return RequestConfig(
method = RequestMethod.GET,
path = "/2/object/ezsigntemplatepackagemembership/{pkiEzsigntemplatepackagemembershipID}".replace("{"+"pkiEzsigntemplatepackagemembershipID"+"}", encodeURIComponent(pkiEzsigntemplatepackagemembershipID.toString())),
query = localVariableQuery,
headers = localVariableHeaders,
requiresAuthentication = true,
body = localVariableBody
)
}
private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String =
HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0]
}
| 0 | Kotlin | 0 | 0 | 961c97a9f13f3df7986ea7ba55052874183047ab | 14,926 | eZmax-SDK-kotlin | MIT License |
app/src/main/java/com/romandevyatov/bestfinance/data/entities/relations/TransferHistoryWithWallets.kt | RomanDevyatov | 587,557,441 | false | {"Kotlin": 569123} | package com.romandevyatov.bestfinance.data.entities.relations
import androidx.room.Embedded
import androidx.room.Relation
import com.romandevyatov.bestfinance.data.entities.TransferHistory
import com.romandevyatov.bestfinance.data.entities.Wallet
data class TransferHistoryWithWallets(
@Embedded
var transferHistory: TransferHistory,
@Relation(
entity = Wallet::class,
parentColumn = "from_wallet_id",
entityColumn = "id")
var walletFrom: Wallet,
@Relation(
entity = Wallet::class,
parentColumn = "to_wallet_id",
entityColumn = "id")
var walletTo: Wallet
)
| 0 | Kotlin | 0 | 1 | bacad4ca4c12fdef63d1e1e746439751cb891776 | 634 | BestFinance | Apache License 2.0 |
media_manager/src/main/kotlin/mediaManager/notification/mail/MailService.kt | amdigbari | 775,209,105 | false | {"Kotlin": 56822, "TypeScript": 32491, "SCSS": 2839, "JavaScript": 768} | package mediaManager.notification.mail
import org.springframework.boot.autoconfigure.mail.MailProperties
import org.springframework.mail.MailException
import org.springframework.mail.javamail.JavaMailSender
import org.springframework.mail.javamail.MimeMessageHelper
import org.springframework.stereotype.Service
@Service
class MailService(val mailSender: JavaMailSender, val mailProperties: MailProperties) {
/**
* Sends a simple email.
*
* @param mail Mail.
*
* @throws MailException
*/
fun sendMail(mail: Mail) {
val message = mailSender.createMimeMessage()
val helper = MimeMessageHelper(message)
helper.setFrom(mailProperties.username)
helper.setTo(mail.to)
helper.setSubject(mail.subject)
helper.setText(mail.content, true)
mailSender.send(message)
}
}
| 0 | Kotlin | 0 | 0 | 519f0cff74f39813bde32c6fe3016b382a6c7d9c | 859 | dates | MIT License |
app/src/main/java/com/example/gameshelf/MYAppCrud.kt | Zafion | 671,450,339 | false | {"Kotlin": 86106} | package com.example.gameshelf
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
//Anotación HiltAndroidApp
@HiltAndroidApp
class MYAppCrud: Application() //Hereda de Application | 0 | Kotlin | 0 | 1 | 8635b7c5c5257362a1814e6486ef131560c3e716 | 203 | GameShelf | Apache License 2.0 |
app/src/main/java/scimone/diafit/core/domain/use_cases/InsertCGMValueUseCase.kt | scimone | 821,835,868 | false | {"Kotlin": 48107} | package scimone.diafit.core.domain.use_cases
import scimone.diafit.core.domain.model.CGMEntity
import scimone.diafit.core.domain.repository.CGMRepository
class InsertCGMValueUseCase (
private val repository: CGMRepository
) {
suspend operator fun invoke(cgmValue: CGMEntity) {
repository.insertCGMValue(cgmValue)
}
} | 0 | Kotlin | 0 | 0 | aa00b35f79a1b3127cb45be88a77133e4c805a5c | 338 | diafit-android | MIT License |
app/src/main/java/com/example/gamingex/framework/impl/AndroidPixmap.kt | gazinaft | 264,455,500 | false | null | package com.example.gamingex.framework.impl
import android.graphics.Bitmap
import com.example.gamingex.framework.Graphics.Companion.PixmapFormat
import com.example.gamingex.framework.Pixmap
//a wrapper class responsible for asset representation
class AndroidPixmap(val bitmap: Bitmap, private val format: PixmapFormat): Pixmap {
override fun getFormat(): PixmapFormat = format
override fun getHeight(): Int = bitmap.height
override fun getWidth(): Int = bitmap.width
override fun dispose() {
bitmap.recycle()
}
}
| 0 | Kotlin | 1 | 4 | f47dc6f078f1afd5f5bbc4c481e4c14a95ebd1bf | 547 | Kursach | MIT License |
ast-transformations-core/src/main/kotlin/org/jetbrains/research/ml/ast/transformations/PyUtils.kt | JetBrains-Research | 301,993,261 | false | null | package org.jetbrains.research.ml.ast.transformations
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.jetbrains.python.PyTokenTypes.*
import com.jetbrains.python.psi.*
object PyUtils {
fun createPyIfElsePart(ifElsePart: PyIfPart): PyIfPart {
require(ifElsePart.isElif) { "Illegal if part. Only `elif` part supported." }
val generator = PyElementGenerator.getInstance(ifElsePart.project)
val ifStatement = generator.createFromText(
LanguageLevel.getDefault(),
PyIfStatement::class.java,
"if ${ifElsePart.condition?.text ?: ""}:\n\t${ifElsePart.statementList.text}"
)
return ifStatement.ifPart
}
fun braceExpression(expression: PyExpression): PyExpression {
val generator = PyElementGenerator.getInstance(expression.project)
return generator.createExpressionFromText(LanguageLevel.getDefault(), "(${expression.text})")
}
fun createAssignment(target: PsiElement, value: PsiElement): PyAssignmentStatement {
val generator = PyElementGenerator.getInstance(target.project)
return generator.createFromText(
LanguageLevel.getDefault(),
PyAssignmentStatement::class.java,
"${target.text} = ${value.text}"
)
}
fun createAssignment(assignment: PyAugAssignmentStatement): PyAssignmentStatement {
val generator = PyElementGenerator.getInstance(assignment.project)
val assignmentTargetText = assignment.target.text
val augOperation =
assignment.operation as? LeafPsiElement ?: throw IllegalArgumentException("Operation is required")
val operation = createOperation(augOperation)
var value = assignment.value ?: throw IllegalArgumentException("Value is required")
value = braceValueIfNeeded(value)
return generator.createFromText(
LanguageLevel.getDefault(),
PyAssignmentStatement::class.java,
"$assignmentTargetText = $assignmentTargetText ${operation.text} ${value.text}"
)
}
private fun braceValueIfNeeded(operation: PyExpression): PyExpression {
val operationLeafElement = PsiTreeUtils.findFirstChildrenOrNull(operation) { element ->
val leafElement = element as? LeafPsiElement ?: return@findFirstChildrenOrNull false
OPERATIONS.contains(leafElement.elementType)
}
if (operationLeafElement != null) {
val generator = PyElementGenerator.getInstance(operation.project)
return generator.createExpressionFromText(LanguageLevel.getDefault(), "(${operation.text})")
}
return operation
}
private fun createOperation(operation: LeafPsiElement): LeafPsiElement {
val (newOperation, text) = when (operation.elementType) {
PLUSEQ -> PLUS to "+"
MINUSEQ -> MINUS to "-"
MULTEQ -> MULT to "*"
ATEQ -> AT to "@"
DIVEQ -> DIV to "/"
PERCEQ -> PERC to "%"
EXPEQ -> EXP to "**"
GTGTEQ -> GTGT to ">>"
LTLTEQ -> LTLT to "<<"
ANDEQ -> AND to "&"
OREQ -> OR to "|"
XOREQ -> XOR to "^"
FLOORDIVEQ -> FLOORDIV to "//"
else -> throw IllegalArgumentException("Illegal operation. Only augment operations accepted")
}
return LeafPsiElement(newOperation, text)
}
}
| 3 | Kotlin | 1 | 9 | 717706765a2da29087a0de768fc851698886dd65 | 3,482 | ast-transformations | MIT License |
bugsnag-android-performance/src/main/kotlin/com/bugsnag/android/performance/Logger.kt | bugsnag | 539,491,063 | false | {"Kotlin": 365034, "Gherkin": 45166, "Ruby": 5551, "Shell": 1095, "Makefile": 617, "Java": 489} | package com.bugsnag.android.performance
import com.bugsnag.android.performance.internal.DebugLogger
/**
* Logs internal messages from within the bugsnag notifier.
*/
interface Logger {
/**
* Logs a message at the error level.
*/
fun e(msg: String)
/**
* Logs a message at the error level.
*/
fun e(msg: String, throwable: Throwable)
/**
* Logs a message at the warning level.
*/
fun w(msg: String)
/**
* Logs a message at the warning level.
*/
fun w(msg: String, throwable: Throwable)
/**
* Logs a message at the info level.
*/
fun i(msg: String)
/**
* Logs a message at the info level.
*/
fun i(msg: String, throwable: Throwable)
/**
* Logs a message at the debug level.
*/
fun d(msg: String)
/**
* Logs a message at the debug level.
*/
fun d(msg: String, throwable: Throwable)
companion object Global : Logger {
var delegate: Logger = DebugLogger
internal set
override fun e(msg: String) = delegate.e(msg)
override fun e(msg: String, throwable: Throwable) = delegate.e(msg, throwable)
override fun w(msg: String) = delegate.w(msg)
override fun w(msg: String, throwable: Throwable) = delegate.w(msg, throwable)
override fun i(msg: String) = delegate.i(msg)
override fun i(msg: String, throwable: Throwable) = delegate.i(msg, throwable)
override fun d(msg: String) = delegate.d(msg)
override fun d(msg: String, throwable: Throwable) = delegate.d(msg, throwable)
}
}
| 0 | Kotlin | 1 | 3 | dabd050e8665dcdba410b4ebe128421f335b51f8 | 1,616 | bugsnag-android-performance | MIT License |
qrgame-andorid-app/base/src/main/java/thisaislan/qrgame/base/extesion/ResourcesExtensions.kt | thisaislan | 374,269,058 | false | {"Kotlin": 36495, "JavaScript": 17409, "CSS": 9291, "HTML": 6374} | package thisaislan.qrgame.base.extesion
import android.content.Context
import android.content.res.Resources
import android.util.TypedValue
import androidx.annotation.AttrRes
import androidx.annotation.IntegerRes
import androidx.core.content.res.ResourcesCompat
fun Resources.getIntegerAsLong(@IntegerRes id: Int) =
getInteger(id).toLong()
fun Resources.getHexColor(context: Context, @AttrRes attributeColorId: Int): String {
val currentTheme = context.theme
val typedValue = TypedValue()
currentTheme.resolveAttribute(attributeColorId, typedValue, true)
val colorRes = typedValue.resourceId
val colorInt = ResourcesCompat.getColor(this, colorRes, currentTheme)
return String.format("#%06X", 0xFFFFFF and colorInt)
}
| 0 | Kotlin | 1 | 17 | e4ccabfe286dbcd183ab36fed7572d19d65d5a67 | 750 | qrgame | MIT License |
uast/uast-common/src/org/jetbrains/uast/analysis/UNeDfaValueEvaluator.kt | Git-Stateless | 369,944,945 | true | null | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.analysis
import com.intellij.psi.PsiReference
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.util.Plow
import com.intellij.util.containers.addIfNotNull
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.uast.*
import org.jetbrains.uast.visitor.AbstractUastVisitor
@ApiStatus.Internal
@ApiStatus.Experimental
class UNeDfaValueEvaluator<T : Any>(private val strategy: UValueEvaluatorStrategy<T>) {
interface UValueEvaluatorStrategy<T : Any> {
fun calculateLiteral(element: ULiteralExpression): T?
fun calculatePolyadicExpression(element: UPolyadicExpression, elementEvaluator: (UElement) -> T?): T?
fun constructValueFromList(element: UElement, values: List<T>?): T?
fun constructUnknownValue(element: UElement): T?
}
fun calculateValue(element: UElement, configuration: UNeDfaConfiguration<T> = UNeDfaConfiguration()): T? {
val graph = element.getContainingUMethod()?.let { UastLocalUsageDependencyGraph.getGraphByUElement(it) } ?: return null
return calculate(graph, element, configuration)
}
private fun calculate(graph: UastLocalUsageDependencyGraph,
element: UElement,
configuration: UNeDfaConfiguration<T>): T? {
if (element is ULiteralExpression) {
return strategy.calculateLiteral(element)
}
if (element is UPolyadicExpression) {
return strategy.calculatePolyadicExpression(element) { operand ->
calculate(graph, operand, configuration)
}
}
if (graph.dependencies[element] == null && element is UReferenceExpression) {
val declaration = element.resolveToUElement()
val value = when {
declaration is UField && declaration.isFinal && declaration.isStatic -> {
listOfNotNull(UastLocalUsageDependencyGraph.getGraphByUElement(declaration)?.let { graphForField ->
declaration.uastInitializer?.let { initializer ->
calculate(graphForField, initializer, configuration)
}
})
}
declaration is UParameter && declaration.uastParent is UMethod && declaration.uastParent == graph.uAnchor -> {
analyzeUsages(declaration.uastParent as UMethod, declaration, configuration) { usageGraph, argument, usageConfiguration ->
calculate(usageGraph, argument, usageConfiguration)
}
}
declaration is UDeclaration -> {
configuration.valueProviders.mapNotNull { it.provideValue(declaration) }
}
else -> null
}
if (value != null && value.size == 1) {
return value.first()
}
else {
return strategy.constructValueFromList(element, value)
}
}
if (element is UCallExpression) {
val methodEvaluator = configuration.getEvaluatorForCall(element)
if (methodEvaluator != null) {
return methodEvaluator.provideValue(this, configuration, element)
}
val builderEvaluator = configuration.getBuilderEvaluatorForCall(element)
if (builderEvaluator != null) {
return BuilderEvaluator(graph, configuration, builderEvaluator).calculateBuilder(element, null, null)
}
val dslEvaluator = configuration.getDslEvaluatorForCall(element)
if (dslEvaluator != null) {
val (builderLikeEvaluator, methodDescriptor) = dslEvaluator
return BuilderEvaluator(graph, configuration, builderLikeEvaluator).calculateDsl(element, methodDescriptor)
}
if (element.resolve()?.let { configuration.methodsToAnalyzePattern.accepts(it) } == true) {
return strategy.constructValueFromList(element, analyzeMethod(graph, element, configuration))
}
}
val dependency = graph.dependencies[element]
?.firstOrNull { it !is Dependency.ArgumentDependency && it !is Dependency.PotentialSideEffectDependency }
val (originalDependency, graphToUse) = if (dependency is Dependency.ConnectionDependency) {
dependency.dependencyFromConnectedGraph to dependency.connectedGraph
}
else {
dependency to graph
}
return when (originalDependency) {
is Dependency.BranchingDependency -> {
val possibleValues = originalDependency
.elements
.mapNotNull { calculate(graphToUse, it, configuration) }
strategy.constructValueFromList(element, possibleValues)
}
is Dependency.CommonDependency -> {
calculate(graphToUse, originalDependency.element, configuration)
}
else -> {
strategy.constructUnknownValue(element)
}
}
}
private fun analyzeUsages(
method: UMethod,
parameter: UParameter,
configuration: UNeDfaConfiguration<T>,
valueFromArgumentProvider: (UastLocalUsageDependencyGraph, UExpression, UNeDfaConfiguration<T>) -> T?
): List<T> {
if (configuration.parameterUsagesDepth < 2) return emptyList()
val parameterIndex = method.uastParameters.indexOf(parameter)
val scope = if (configuration.usagesSearchScope is GlobalSearchScope) {
GlobalSearchScope.getScopeRestrictedByFileTypes(
configuration.usagesSearchScope,
*UastLanguagePlugin.getInstances().mapNotNull { it.language.associatedFileType }.toTypedArray()
)
}
else {
configuration.usagesSearchScope
}
return Plow.of<PsiReference> { processor -> ReferencesSearch.search(method.sourcePsi!!, scope).forEach(processor) }
.limit(3)
.mapNotNull { it.element.parent.toUElement() as? UCallExpression }
.mapNotNull {
it.getArgumentForParameter(parameterIndex)?.let { argument ->
argument.getContainingUMethod()?.let { currentMethod ->
UastLocalUsageDependencyGraph.getGraphByUElement(currentMethod)?.let { graph ->
valueFromArgumentProvider(graph, argument, configuration.copy(methodCallDepth = configuration.parameterUsagesDepth - 1))
}
}
}
}
.toList()
}
private fun analyzeMethod(graph: UastLocalUsageDependencyGraph,
methodCall: UCallExpression,
configuration: UNeDfaConfiguration<T>): List<T> {
if (configuration.methodCallDepth < 2) return emptyList()
val resolvedMethod = methodCall.resolve().toUElementOfType<UMethod>() ?: return emptyList()
val mergedGraph = UastLocalUsageDependencyGraph.connectMethodWithCaller(resolvedMethod, graph, methodCall) ?: return emptyList()
val results = mutableListOf<T>()
resolvedMethod.accept(object : AbstractUastVisitor() {
override fun visitReturnExpression(node: UReturnExpression): Boolean {
if (node.jumpTarget != resolvedMethod) return false
node.returnExpression?.let {
results.addIfNotNull(
calculate(mergedGraph, it, configuration.copy(methodCallDepth = configuration.methodCallDepth - 1)))
}
return super.visitReturnExpression(node)
}
})
return results
}
private inner class BuilderEvaluator(
private val graph: UastLocalUsageDependencyGraph,
private val configuration: UNeDfaConfiguration<T>,
private val builderEvaluator: BuilderLikeExpressionEvaluator<T>,
) {
private var declarationEvaluator: ((UDeclaration) -> T?)? = { null }
fun calculateDsl(
element: UCallExpression,
dslMethodDescriptor: DslLikeMethodDescriptor<T>
): T? {
val lambda = dslMethodDescriptor.lambdaDescriptor.lambdaPlace.getLambda(element) ?: return null
val parameter = dslMethodDescriptor.lambdaDescriptor.getLambdaParameter(lambda) ?: return null
val (lastVariablesUpdates, variableToValueMarks) = graph.scopesObjectsStates[lambda] ?: return null
val marks = variableToValueMarks[parameter.name]
val candidates = lastVariablesUpdates[parameter.name]?.selectPotentialCandidates {
(marks == null || marks.intersect(it.dependencyWitnessValues).isNotEmpty()) &&
provePossibleDependency(it.dependencyEvidence, builderEvaluator)
} ?: return null
declarationEvaluator = {
declaration ->
if (declaration == parameter) {
dslMethodDescriptor.lambdaDescriptor.lambdaArgumentValueProvider()
}
else {
null
}
}
return candidates.mapNotNull { calculateBuilder(it.updateElement, it.dependencyWitnessValues, marks) }
.let { strategy.constructValueFromList(element, it) }
}
fun calculateBuilder(
element: UElement,
objectsToAnalyze: Collection<UValueMark>?,
originalObjectsToAnalyze: Collection<UValueMark>?
): T? {
if (element is UDeclaration && declarationEvaluator != null) {
val value = declarationEvaluator?.invoke(element)
if (value != null) return value
}
if (element is UCallExpression) {
val methodEvaluator = builderEvaluator.methodDescriptions.entries.firstOrNull { (pattern, _) ->
pattern.accepts(element.resolve())
}
if (methodEvaluator != null) {
val dependencies = graph.dependencies[element].orEmpty()
val isStrict = objectsToAnalyze == originalObjectsToAnalyze
return when (
val dependency = dependencies
.firstOrNull { it !is Dependency.PotentialSideEffectDependency && it !is Dependency.ArgumentDependency }
) {
is Dependency.BranchingDependency -> {
val branchResult = dependency.elements.mapNotNull {
calculateBuilder(it, objectsToAnalyze, originalObjectsToAnalyze)
}.let { strategy.constructValueFromList(element, it) }
methodEvaluator.value.evaluate(element, branchResult, this@UNeDfaValueEvaluator, configuration, isStrict)
}
is Dependency.CommonDependency -> {
val result = calculateBuilder(
dependency.element,
objectsToAnalyze,
originalObjectsToAnalyze
)
methodEvaluator.value.evaluate(element, result, this@UNeDfaValueEvaluator, configuration, isStrict)
}
is Dependency.PotentialSideEffectDependency -> null // there should not be anything
else -> methodEvaluator.value.evaluate(element, null, this@UNeDfaValueEvaluator, configuration, isStrict)
}
}
}
val dependencies = graph.dependencies[element].orEmpty()
if (dependencies.isEmpty() && element is UReferenceExpression) {
val declaration = element.resolveToUElement()
if (declaration is UParameter && declaration.uastParent is UMethod && declaration.uastParent == graph.uAnchor) {
val usagesResults = analyzeUsages(declaration.uastParent as UMethod, declaration, configuration) { usageGraph, argument, usageConfiguration ->
BuilderEvaluator(usageGraph, usageConfiguration, builderEvaluator).calculateBuilder(argument, null, null)
}
return usagesResults.singleOrNull() ?: strategy.constructValueFromList(element, usagesResults)
}
}
val (dependency, candidates) = selectDependency(dependencies, builderEvaluator) {
(originalObjectsToAnalyze == null ||
originalObjectsToAnalyze.intersect(it.dependencyWitnessValues).isNotEmpty()) &&
provePossibleDependency(it.dependencyEvidence, builderEvaluator)
}
if (
dependency is DependencyOfReference &&
originalObjectsToAnalyze != null &&
dependency.referenceInfo?.possibleReferencedValues?.intersect(originalObjectsToAnalyze)?.isEmpty() == true
) {
return null
}
return when (dependency) {
is Dependency.BranchingDependency -> {
val variants = dependency.elements.mapNotNull {
calculateBuilder(it, objectsToAnalyze, originalObjectsToAnalyze)
}.takeUnless { it.isEmpty() }
if (variants?.size == 1) {
variants.single()
}
else {
strategy.constructValueFromList(element, variants)
}
}
is Dependency.CommonDependency -> {
calculateBuilder(
dependency.element,
objectsToAnalyze,
originalObjectsToAnalyze
)
}
is Dependency.PotentialSideEffectDependency -> if (!builderEvaluator.allowSideEffects) null
else {
candidates
.mapNotNull { candidate ->
calculateBuilder(
candidate.updateElement,
candidate.dependencyWitnessValues,
originalObjectsToAnalyze ?: dependency.referenceInfo?.possibleReferencedValues
)
}
.let { strategy.constructValueFromList(element, it) }
}
else -> null
}
}
}
private fun provePossibleDependency(
evidence: Dependency.PotentialSideEffectDependency.DependencyEvidence,
builderEvaluator: BuilderLikeExpressionEvaluator<T>,
visitedEvidences: MutableSet<Dependency.PotentialSideEffectDependency.DependencyEvidence> = mutableSetOf()
): Boolean {
if (evidence in visitedEvidences) return false // Cyclic evidence
visitedEvidences += evidence
val result = (evidence.evidenceElement == null || builderEvaluator.isExpressionReturnSelf(evidence.evidenceElement)) &&
(evidence.requires.isEmpty() || evidence.requires.all { provePossibleDependency(it, builderEvaluator, visitedEvidences) })
visitedEvidences -= evidence
return result
}
private fun selectDependency(
dependencies: Collection<Dependency>,
builderEvaluator: BuilderLikeExpressionEvaluator<T>,
candidateChecker: (Dependency.PotentialSideEffectDependency.SideEffectChangeCandidate) -> Boolean
): Pair<Dependency?, Collection<Dependency.PotentialSideEffectDependency.SideEffectChangeCandidate>> =
dependencies
.firstOrNull { it is Dependency.PotentialSideEffectDependency }
.takeIf { builderEvaluator.allowSideEffects }
?.let { dependency ->
(dependency as Dependency.PotentialSideEffectDependency).candidates
.selectPotentialCandidates(candidateChecker)
.takeUnless { it.isEmpty() }
?.let { candidates ->
dependency to candidates
}
}
?: (dependencies.firstOrNull { it !is Dependency.PotentialSideEffectDependency && it !is Dependency.ArgumentDependency } to emptyList())
} | 0 | null | 0 | 0 | 40cbd984d76bd2dc693dca38d373e704e4aa7bc3 | 14,622 | intellij-community | Apache License 2.0 |
utils/math/src/main/kotlin/io/bluetape4k/math/commons/Approximate.kt | debop | 625,161,599 | false | {"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82} | package io.bluetape4k.math.commons
import io.bluetape4k.math.MathConsts.EPSILON
import io.bluetape4k.math.MathConsts.FLOAT_EPSILON
import java.math.BigDecimal
import kotlin.math.abs
import kotlin.math.absoluteValue
fun Double.approximateEqual(that: Double, epsilon: Double = EPSILON): Boolean =
abs(this - that) < epsilon.absoluteValue
fun Float.approximateEqual(that: Float, epsilon: Float = FLOAT_EPSILON): Boolean =
abs(this - that) < abs(epsilon)
fun BigDecimal.approximateEqual(that: BigDecimal, epsilon: BigDecimal = EPSILON.toBigDecimal()): Boolean =
(this - that).abs() < epsilon.abs()
fun Iterable<Double>.filterApproximate(
that: Double,
epsilon: Double = EPSILON,
): List<Double> {
return filter { it.approximateEqual(that, epsilon) }
}
fun Iterable<Float>.filterApproximate(
that: Float,
epsilon: Float = FLOAT_EPSILON,
): List<Float> {
return filter { it.approximateEqual(that, epsilon) }
}
fun Iterable<BigDecimal>.filterApproximate(
that: BigDecimal,
epsilon: BigDecimal = EPSILON.toBigDecimal(),
): List<BigDecimal> {
return filter { it.approximateEqual(that, epsilon) }
}
fun Sequence<Double>.filterApproximate(
that: Double,
epsilon: Double = EPSILON,
): Sequence<Double> {
return filter { it.approximateEqual(that, epsilon) }
}
fun Sequence<Float>.filterApproximate(
that: Float,
epsilon: Float = FLOAT_EPSILON,
): Sequence<Float> {
return filter { it.approximateEqual(that, epsilon) }
}
fun Sequence<BigDecimal>.filterApproximate(
that: BigDecimal,
epsilon: BigDecimal = EPSILON.toBigDecimal(),
): Sequence<BigDecimal> {
return filter { it.approximateEqual(that, epsilon) }
}
| 0 | Kotlin | 0 | 1 | ce3da5b6bddadd29271303840d334b71db7766d2 | 1,690 | bluetape4k | MIT License |
src/main/kotlin/com/exactpro/th2/converter/controllers/ConverterController.kt | th2-net | 494,019,473 | false | null | /*
* Copyright 2020-2022 Exactpro (Exactpro Systems Limited)
*
* 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.exactpro.th2.converter.controllers
import com.exactpro.th2.converter.config.ApplicationConfig
import com.exactpro.th2.converter.controllers.errors.BadRequestException
import com.exactpro.th2.converter.controllers.errors.ErrorCode
import com.exactpro.th2.converter.conversion.Converter.convertFromGit
import com.exactpro.th2.converter.conversion.Converter.convertFromRequest
import com.exactpro.th2.converter.util.ProjectConstants
import com.exactpro.th2.converter.util.ProjectConstants.PROPAGATION_DENY
import com.exactpro.th2.converter.util.ProjectConstants.PROPAGATION_RULE
import com.exactpro.th2.converter.util.ProjectConstants.SOURCE_BRANCH
import com.exactpro.th2.converter.util.RepositoryUtils.schemaExists
import com.exactpro.th2.converter.util.RepositoryUtils.updateRepository
import com.exactpro.th2.converter.util.RepositoryUtils.updateSchemaK8sPropagation
import com.exactpro.th2.infrarepo.git.GitterContext
import com.exactpro.th2.infrarepo.repo.Repository
import com.exactpro.th2.infrarepo.repo.RepositoryResource
import io.micronaut.http.MediaType
import io.micronaut.http.annotation.Body
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Post
import io.micronaut.http.annotation.Produces
import org.eclipse.jgit.errors.EntryExistsException
@Controller
@Produces(MediaType.APPLICATION_JSON)
class ConverterController {
@Post("convert/{schemaName}/{targetVersion}")
fun convertInSameBranch(
schemaName: String,
targetVersion: String
): ConversionSummary {
checkRequestedVersion(targetVersion)
val gitterContext = GitterContext.getContext(ApplicationConfig.git)
checkSourceSchema(schemaName, gitterContext)
val gitter = gitterContext.getGitter(schemaName)
val conversionResult = convertFromGit(targetVersion, gitter)
val currentResponse = conversionResult.summary
if (currentResponse.hasErrors()) {
return currentResponse
}
try {
gitter.lock()
Repository.removeLinkResources(gitter)
updateRepository(conversionResult.convertedResources, gitter, Repository::update)
conversionResult.summary.commitRef = gitter.commitAndPush("Schema conversion")
} finally {
gitter.unlock()
}
return conversionResult.summary
}
@Post("convert/{sourceSchemaName}/{newSchemaName}/{targetVersion}")
fun convertInNewBranch(
sourceSchemaName: String,
newSchemaName: String,
targetVersion: String
): ConversionSummary {
checkRequestedVersion(targetVersion)
val gitterContext: GitterContext = GitterContext.getContext(ApplicationConfig.git)
checkSourceSchema(sourceSchemaName, gitterContext)
val sourceBranchGitter = gitterContext.getGitter(sourceSchemaName)
val conversionResult = convertFromGit(targetVersion, sourceBranchGitter)
val currentResponse = conversionResult.summary
if (currentResponse.hasErrors()) {
return currentResponse
}
try {
sourceBranchGitter.lock()
if (updateSchemaK8sPropagation(PROPAGATION_DENY, sourceBranchGitter)) {
sourceBranchGitter.commitAndPush("set k8s-propagation to deny for the schema '$sourceSchemaName'")
}
} finally {
sourceBranchGitter.unlock()
}
val newBranchGitter = gitterContext.getGitter(newSchemaName)
try {
newBranchGitter.lock()
newBranchGitter.createBranch(sourceSchemaName)
updateSchemaK8sPropagation(PROPAGATION_RULE, newBranchGitter)
Repository.removeLinkResources(newBranchGitter)
updateRepository(conversionResult.convertedResources, newBranchGitter, Repository::update)
conversionResult.summary.commitRef = newBranchGitter.commitAndPush("Schema conversion")
} catch (e: EntryExistsException) {
throw BadRequestException(
ErrorCode.BRANCH_ALREADY_EXISTS,
"Branch '$newSchemaName' already exists on git"
)
} finally {
newBranchGitter.unlock()
}
return conversionResult.summary
}
@Get("convert/{targetVersion}")
fun convertRequestedResources(
targetVersion: String,
@Body resources: Set<RepositoryResource>
): ConversionResult {
checkRequestedVersion(targetVersion)
return convertFromRequest(targetVersion, resources)
}
@Get("test")
fun testApi(): String {
return "Conversion API is working !"
}
private fun checkRequestedVersion(version: String) {
if (version !in ProjectConstants.ACCEPTED_VERSIONS) {
throw BadRequestException(
ErrorCode.VERSION_NOT_ALLOWED,
"Conversion to specified version: '$version' is not supported"
)
}
}
private fun checkSourceSchema(schemaName: String, gitterContext: GitterContext) {
if (!schemaExists(schemaName, gitterContext)) {
throw BadRequestException(
ErrorCode.BRANCH_NOT_FOUND,
"Specified schema doesn't exist"
)
}
if (schemaName == SOURCE_BRANCH) {
throw BadRequestException(
ErrorCode.BRANCH_NOT_ALLOWED,
"Specified schema must not be the same as $SOURCE_BRANCH"
)
}
}
}
| 0 | Kotlin | 1 | 2 | 9901fd7302dfe023973c5d7d42e8492a62516ce2 | 6,160 | th2-cr-converter | Apache License 2.0 |
backend/src/main/kotlin/dev/dres/run/filter/MaximumTotalPerTeamFilter.kt | dres-dev | 248,713,193 | false | null | package dev.dres.run.filter
import dev.dres.data.model.submissions.Submission
class MaximumTotalPerTeamFilter(private val max: Int = Int.MAX_VALUE) : SubmissionFilter {
constructor(parameters: Map<String, String>) : this(parameters.getOrDefault("limit", "${Int.MAX_VALUE}").toIntOrNull() ?: Int.MAX_VALUE)
override val reason = "Maximum total number of submissions ($max) exceeded for the team"
override fun test(submission: Submission): Boolean = submission.task!!.submissions.filter { it.teamId == submission.teamId }.size < max
}
| 35 | Kotlin | 1 | 8 | 7dcb10ff97c5a8a1453e54004c91ab63d5c20a14 | 550 | DRES | MIT License |
app/src/main/java/com/example/recordlocation/MainActivity.kt | govilkargaurav | 290,391,247 | false | null | package com.example.recordlocation
import android.Manifest
import android.Manifest.permission.ACCESS_FINE_LOCATION
import android.app.PendingIntent
import android.content.*
import android.content.pm.PackageManager
import android.location.LocationManager
import android.os.Bundle
import android.os.IBinder
import android.os.PersistableBundle
import android.preference.PreferenceManager
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.view.isVisible
//import com.example.recordlocation.LocationServiceBroadcaster.LocationService
import com.example.recordlocation.Model.LocationModel
import com.example.recordlocation.Model.LocationResponseModel
import com.example.recordlocation.Model.LoginRequest
import com.example.recordlocation.Model.User
import com.example.recordlocation.RetrofitSingleton.APISingletonObject
import com.example.recordlocation.Utility.BGLocationService
import com.example.recordlocation.Utility.BackgroundLocation
import com.example.recordlocation.Utility.Common
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationServices
import com.karumi.dexter.Dexter
import com.karumi.dexter.MultiplePermissionsReport
import com.karumi.dexter.PermissionToken
import com.karumi.dexter.listener.PermissionDeniedResponse
import com.karumi.dexter.listener.PermissionGrantedResponse
import com.karumi.dexter.listener.PermissionRequest
import com.karumi.dexter.listener.multi.MultiplePermissionsListener
import com.karumi.dexter.listener.single.PermissionListener
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.*
class MainActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceChangeListener {
private var mService: BGLocationService? = null
private var mBound = false
companion object{
var instanse : MainActivity? = null
var userObj : User? = null
fun getInstance(): MainActivity? {
return instanse
}
@JvmName("getUserObj1")
fun getUserObj(): User? {
return userObj
}
}
private val mServiceConnection = object : ServiceConnection {
override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {
val binder = p1 as BGLocationService.LocalBinder
mService = binder.service
mBound = true
}
override fun onServiceDisconnected(p0: ComponentName?) {
mService = null
mBound = false
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Dexter.withActivity(this)
.withPermissions(
Arrays.asList(
android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_BACKGROUND_LOCATION
)
)
.withListener(object : MultiplePermissionsListener {
override fun onPermissionsChecked(p0: MultiplePermissionsReport?) {
updateLocation.setOnClickListener {
mService!!.requestLocationUpdates()
}
removeLocationUpdate.setOnClickListener {
mService!!.removeLocationUpdates()
}
setButtonState(Common.requestingLocationUpdates(this@MainActivity))
bindService(
Intent(this@MainActivity, BGLocationService::class.java),
mServiceConnection,
Context.BIND_AUTO_CREATE
)
}
override fun onPermissionRationaleShouldBeShown(
p0: MutableList<PermissionRequest>?,
p1: PermissionToken?
) {
}
}).check()
}
override fun onSharedPreferenceChanged(p0: SharedPreferences?, p1: String?) {
if (p1.equals(Common.KEY_REQUEST_LOCATION_UPDATE))
setButtonState(p0!!.getBoolean(Common.KEY_REQUEST_LOCATION_UPDATE,false))
}
private fun setButtonState(boolean: Boolean) {
if (boolean){
removeLocationUpdate.isEnabled = true
updateLocation.isEnabled = false
}else{
removeLocationUpdate.isEnabled = false
updateLocation.isEnabled = true
}
}
@Subscribe(sticky = true, threadMode = ThreadMode.BACKGROUND)
fun onBackgroundLocationRetrieve(event: BackgroundLocation) {
if (event.location != null) {
Toast.makeText(this, Common.getLocationText((event.location)), Toast.LENGTH_SHORT)
.show()
}
}
override fun onStart() {
super.onStart()
PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener(this)
EventBus.getDefault().register(this)
}
override fun onStop() {
PreferenceManager.getDefaultSharedPreferences(this)
.unregisterOnSharedPreferenceChangeListener(this)
EventBus.getDefault().unregister(this)
super.onStop()
}
fun loginBtnClicked(view: View) {
val requestParam = LoginRequest(
editTextTextPersonName.text.toString(),
editTextTextPassword2.text.toString()
)
APISingletonObject.instance.getLoggedinUser(requestParam)
.enqueue(object : Callback<User> {
override fun onResponse(call: Call<User>, response: Response<User>) {
if (response.body()!=null) {
userObj = response.body()
}
RLtextView.text = response.body()?.userName ?: String()
RLtextView.isVisible = true
editTextTextPersonName.isVisible = false
editTextTextPassword2.isVisible = false
btnLogin.isVisible = false
}
override fun onFailure(call: Call<User>, t: Throwable) {
RLtextView.text = "Something went wrong in Login, Please try again"
RLtextView.isVisible = true
}
})
}
}
| 0 | Kotlin | 0 | 0 | cb9bb375c470f7bbdfb2b85a291776d6df4d71e1 | 6,762 | recordLocation | Apache License 2.0 |
app/src/main/java/fr/xgouchet/packageexplorer/details/app/AppDetailsFragment.kt | DOSAM4 | 171,172,952 | true | {"Kotlin": 126057, "Java": 220} | package fr.xgouchet.packageexplorer.details.app
import android.content.Intent
import android.content.pm.ResolveInfo
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.content.FileProvider
import android.support.v4.view.ViewCompat
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import fr.xgouchet.packageexplorer.BuildConfig
import fr.xgouchet.packageexplorer.R
import fr.xgouchet.packageexplorer.details.adapter.AppDetailsAdapter
import fr.xgouchet.packageexplorer.details.adapter.AppInfoViewModel
import fr.xgouchet.packageexplorer.launcher.LauncherDialog
import fr.xgouchet.packageexplorer.ui.adapter.BaseAdapter
import fr.xgouchet.packageexplorer.ui.mvp.list.BaseListFragment
import io.reactivex.functions.Consumer
import java.io.File
/**
* @author Xavier F. Gouchet
*/
class AppDetailsFragment
: BaseListFragment<AppInfoViewModel, AppDetailsPresenter>() {
override val adapter: BaseAdapter<AppInfoViewModel> = AppDetailsAdapter(this, Consumer { presenter.actionTriggerd(it) })
override val isFabVisible: Boolean = false
override val fabIconOverride: Int? = null
// region Fragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
ViewCompat.setNestedScrollingEnabled(view.findViewById(android.R.id.list), false)
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
inflater?.inflate(R.menu.app_details, menu)
if (presenter.isSystemApp) {
menu?.findItem(R.id.action_uninstall)?.isVisible = false
menu?.findItem(R.id.action_play_store)?.isVisible = false
}
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.action_app_launch -> {
presenter.openApplication()
return true
}
R.id.action_app_info -> {
presenter.openAppInfo()
return true
}
R.id.action_play_store -> {
presenter.openPlayStore()
return true
}
R.id.action_uninstall -> {
presenter.openUninstaller()
return true
}
R.id.action_manifest -> {
presenter.exportManifest()
return true
}
}
return super.onOptionsItemSelected(item)
}
// endregion
// region Displayer
fun promptActivity(resolvedInfos: List<ResolveInfo>) {
val supportFragmentManager = activity?.supportFragmentManager ?: return
val transaction = supportFragmentManager.beginTransaction()
LauncherDialog.withData(resolvedInfos)
.show(transaction, null)
}
fun onManifestExported(dest: File) {
val currentActivity = activity ?: return
val intent = Intent(Intent.ACTION_VIEW)
val uri = FileProvider.getUriForFile(currentActivity, BuildConfig.APPLICATION_ID, dest)
intent.setDataAndType(uri, "text/xml")
intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
val resolved = currentActivity.packageManager.queryIntentActivities(intent, 0)
if (resolved.isEmpty()) {
Snackbar.make(list, R.string.error_exported_manifest, Snackbar.LENGTH_LONG)
.show()
} else {
val chooser = Intent.createChooser(intent, null)
currentActivity.startActivity(chooser)
}
}
// endregion
}
| 0 | Kotlin | 0 | 0 | b5e68eaccc178c10f0bd2ee8d8aad8b0fdaa0ee7 | 3,786 | Stanley | MIT License |
src/main/kotlin/ai/klink/yugaklink/App.kt | klinkai | 203,439,566 | false | null | package ai.klink.yugaklink
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.autoconfigure.domain.EntityScan
import org.springframework.context.annotation.Configuration
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories
import org.springframework.data.jpa.repository.config.EnableJpaRepositories
import org.springframework.scheduling.annotation.EnableScheduling
import java.util.*
import javax.annotation.PostConstruct
@Configuration
@SpringBootApplication(scanBasePackages = ["ai.klink.yugaklink"])
@EntityScan(basePackages = ["ai.klink.yugaklink.cassandra", "ai.klink.yugaklink.relational"])
@EnableCassandraRepositories(basePackages = ["ai.klink.yugaklink.cassandra"])
@EnableJpaRepositories(basePackages = ["ai.klink.yugaklink.relational"])
@EnableScheduling
class YugaKlinkApplication {
@PostConstruct
fun init() {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"))
}
}
fun main(args: Array<String>) {
SpringApplication.run(YugaKlinkApplication::class.java, *args)
}
| 2 | Kotlin | 0 | 1 | f28768253a849eff7a0f39f6603dca44cb87c3ff | 1,137 | yugaklink | Apache License 2.0 |
core/remote/src/main/kotlin/com/theophiluskibet/remote/di/RemoteModule.kt | kibettheophilus | 811,054,900 | false | {"Kotlin": 66991} | /**
* MIT License
*
* Copyright (c) 2024 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.theophiluskibet.remote.di
import com.theophiluskibet.remote.utils.ANOTHER_BASE_URL
import com.theophiluskibet.remote.utils.ANOTHER_CLIENT
import com.theophiluskibet.remote.utils.RICKY_MORTY_BASEURL
import com.theophiluskibet.remote.utils.RICKY_MORTY_CLIENT
import io.ktor.client.HttpClient
import io.ktor.client.engine.okhttp.OkHttp
import io.ktor.client.plugins.DefaultRequest
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.json.Json
import org.koin.core.annotation.ComponentScan
import org.koin.core.annotation.Module
import org.koin.core.annotation.Named
import org.koin.core.annotation.Single
@Module
@ComponentScan("com.theophiluskibet.remote")
class RemoteModule {
@Single
@Named(RICKY_MORTY_CLIENT)
fun provideRickyMortyClient() =
HttpClient(OkHttp) {
install(ContentNegotiation) {
json(
Json {
ignoreUnknownKeys = true
isLenient = true
},
)
}
install(DefaultRequest) {
url {
host = RICKY_MORTY_BASEURL
}
}
}
@Single
@Named(ANOTHER_CLIENT)
fun provideAnotherClient() =
HttpClient(OkHttp) {
install(ContentNegotiation) {
json(
Json {
ignoreUnknownKeys = true
isLenient = true
},
)
}
install(DefaultRequest) {
url {
host = ANOTHER_BASE_URL
}
}
}
}
| 3 | Kotlin | 0 | 2 | ae20b26772d6c543fdf03c6bdfab33fe880970d8 | 2,893 | koin-playground | MIT License |
core/ui/src/main/java/com/minux/monitoring/core/ui/FlightSheetGrid.kt | MINUX-organization | 756,381,294 | false | {"Kotlin": 234602} | package com.minux.monitoring.core.ui
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.sp
import com.minux.monitoring.core.designsystem.component.GridHeader
import com.minux.monitoring.core.designsystem.component.MNXCard
import com.minux.monitoring.core.designsystem.theme.grillSansMtFamily
@Composable
fun FlightSheetGridHeader(
modifier: Modifier = Modifier,
contentPadding: PaddingValues = PaddingValues(),
headers: List<String>
) {
val headerStyle = TextStyle(
textAlign = TextAlign.Center,
fontSize = 16.sp,
fontFamily = grillSansMtFamily,
fontWeight = FontWeight.Normal
)
MNXCard(modifier = modifier) {
GridHeader(
modifier = Modifier.padding(paddingValues = contentPadding),
columns = GridCells.Fixed(headers.count()),
headers = headers,
headersStyle = headerStyle
)
}
} | 0 | Kotlin | 0 | 0 | ea0ed05ff1b07f2d970f772b2af1c9179872ccf1 | 1,264 | MNX.Mobile.Monitoring | MIT License |
app/demo-transaction/src/androidTest/java/com/gmail/jiangyang5157/demo_transaction/HiltTestRunner.kt | jiangyang5157 | 553,993,370 | false | null | package com.gmail.jiangyang5157.demo_transaction
import android.app.Application
import android.content.Context
import android.os.Bundle
import androidx.test.runner.AndroidJUnitRunner
import dagger.hilt.android.testing.HiltTestApplication
class HiltTestRunner : AndroidJUnitRunner() {
interface TestRunnerDelegate {
fun onCreate()
fun onDestroy()
}
private val delegates: List<TestRunnerDelegate> = listOf(
DeviceSettingsTestRunnerDelegate()
)
override fun newApplication(cl: ClassLoader?, name: String?, context: Context?): Application {
return super.newApplication(cl, HiltTestApplication::class.java.name, context)
}
override fun callApplicationOnCreate(application: Application) {
delegates.forEach { it.onCreate() }
super.callApplicationOnCreate(application)
}
override fun finish(resultCode: Int, results: Bundle?) {
delegates.forEach { it.onDestroy() }
super.finish(resultCode, results)
}
}
| 0 | Kotlin | 0 | 0 | e514a86bbe149504508cc2ee23bf21c0984d3f48 | 1,008 | kotlin-multiplatform-mobile | MIT License |
app/src/androidTest/java/org/wikipedia/test/SettingUpTheDefaultFeedTests.kt | alinamksmva | 634,996,512 | false | null | package org.wikipedia.test
import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.wikipedia.main.MainActivity
import org.wikipedia.screens.CustomizeTheFeedPage
import org.wikipedia.screens.FirstOnboardPage
import org.wikipedia.screens.MainPage
import org.wikipedia.screens.SettingsPage
@RunWith(AndroidJUnit4::class)
class SettingUpTheDefaultFeedTests {
@Rule
@JvmField
var mActivityTestRule = ActivityScenarioRule(MainActivity::class.java)
@Test
fun settingUpTheDefaultFeedTest() {
val firstScreen = FirstOnboardPage()
val mainScreen = MainPage()
val settingsScreen = SettingsPage()
val customizeTheFeedScreen = CustomizeTheFeedPage()
firstScreen.clickOnboardSkipButton()
with(mainScreen)
{
clickNavigationMoreButton()
clickSettings()
}
settingsScreen.clickExploreFeed()
with(customizeTheFeedScreen)
{
checkFeaturedArticleCheckBox()
checkTopReadCheckBox()
checkPictureOfTheDayCheckBox()
checkBecauseYouReadCheckBox()
checkInTheNewsCheckBox()
checkOnThisDayCheckBox()
swipeUpScreen()
checkRandomizerCheckBox()
checkTodayOnWikipediaCheckBox()
}
}
} | 0 | Kotlin | 0 | 0 | fad94a747e120254ac78bb638a6618dd7ed66320 | 1,450 | Wikipedia_Android_TestAutomation | Apache License 2.0 |
Kotlin/Code/Kotlin-Github/app/src/main/java/com/bennyhuo/github/view/common/BaseDetailActivity.kt | hiloWang | 203,300,702 | false | {"Java": 6943796, "C": 1648441, "C++": 1559595, "HTML": 600176, "Kotlin": 599497, "JavaScript": 456120, "Groovy": 288531, "CSS": 100975, "Dart": 95015, "Python": 93418, "Makefile": 29544, "TSQL": 22344, "CMake": 19243, "Objective-C": 2259, "Shell": 1356, "AspectJ": 477, "Batchfile": 203} | package com.bennyhuo.github.view.common
import android.app.Activity
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.GestureDetector
import android.view.MenuItem
import android.view.MotionEvent
import com.bennyhuo.github.R
import com.bennyhuo.github.view.config.Themer
import com.bennyhuo.swipefinishable.SwipeFinishable
import com.bennyhuo.swipefinishable.SwipeFinishable.SwipeFinishableActivity
import com.bennyhuo.tieguanyin.annotations.ActivityBuilder
import com.bennyhuo.tieguanyin.annotations.PendingTransition
import org.jetbrains.anko.dip
@ActivityBuilder(pendingTransition = PendingTransition(enterAnim = R.anim.rignt_in, exitAnim = R.anim.left_out))
abstract class BaseDetailActivity: AppCompatActivity() {
private val swipeBackTouchDelegate by lazy { SwipeBackTouchDelegate(this, ::finish) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Themer.applyProperTheme(this)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
// Respond to the action bar's Up/Home button
android.R.id.home ->{
finish()
return true
}
}
return super.onOptionsItemSelected(item);
}
override fun finish() {
super.finish()
overridePendingTransition(R.anim.left_in, R.anim.rignt_out)
}
override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
return swipeBackTouchDelegate.onTouchEvent(ev) || super.dispatchTouchEvent(ev)
}
}
class SwipeBackTouchDelegate(val activity: Activity, block: ()-> Unit){
companion object {
private const val MIN_FLING_TO_BACK = 2000
}
private val minFlingToBack by lazy{
activity.dip(MIN_FLING_TO_BACK)
}
private val swipeBackDelegate by lazy {
GestureDetector(activity, object: GestureDetector.SimpleOnGestureListener(){
override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
return if(velocityX > minFlingToBack){
block()
true
} else {
false
}
}
})
}
fun onTouchEvent(event: MotionEvent) = swipeBackDelegate.onTouchEvent(event)
}
@ActivityBuilder(pendingTransition = PendingTransition(enterAnim = 0, exitAnim = 0))
abstract class BaseDetailSwipeFinishableActivity: AppCompatActivity(), SwipeFinishableActivity{
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Themer.applyProperTheme(this, true)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
// Respond to the action bar's Up/Home button
android.R.id.home ->{
finish()
return true
}
}
return super.onOptionsItemSelected(item);
}
override fun finishThisActivity() {
super.finish()
}
override fun finish() {
SwipeFinishable.INSTANCE.finishCurrentActivity()
}
}
| 0 | Java | 15 | 4 | 64a637a86f734e4e80975f4aa93ab47e8d7e8b64 | 3,192 | notes | Apache License 2.0 |
app/src/main/java/com/dreamsoftware/tvnexa/domain/model/SimpleChannelBO.kt | sergio11 | 328,373,511 | false | {"Kotlin": 586066} | package com.dreamsoftware.tvnexa.domain.model
data class SimpleChannelBO(
val channelId: String,
val name: String? = null,
val city: String? = null,
val isNsfw: Boolean? = null,
val website: String? = null,
val logo: String? = null,
val streamUrl: String? = null,
val isBlocked: Boolean = false
)
| 0 | Kotlin | 0 | 1 | a1f6b19097e905e1730f67058f58fdf8e37633e0 | 330 | tvnexa_androidtv | Apache License 2.0 |
src/test/resources/test-compile-data/jvm/kotlin-web-site/arrays/23031df00534726bea3f25bea3d46032.1.kt | JetBrains | 219,478,945 | false | {"Kotlin": 489501, "Dockerfile": 2244, "Shell": 290} | fun main() {
//sampleStart
// Creates an array with values [1, 2, 3]
val simpleArray = arrayOf(1, 2, 3)
println(simpleArray.joinToString())
// 1, 2, 3
//sampleEnd
} | 28 | Kotlin | 73 | 248 | ac53213b767d07f49fa48c5d99fedeb499b9b934 | 180 | kotlin-compiler-server | Apache License 2.0 |
core/src/main/java/com/maxmakarov/core/ui/list/DelegateAdapter.kt | maxmakarovdev | 666,362,590 | false | null | package com.maxmakarov.core.ui.list
import android.view.ViewGroup
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.RecyclerView
class DelegateAdapter(
private val delegates: List<AdapterDelegate<AdapterItem, ViewHolder<*, *>>>
) : PagingDataAdapter<AdapterItem, RecyclerView.ViewHolder>(DiffCallback()) {
override fun getItemViewType(position: Int): Int {
return delegates
.indexOfFirst { it.itemClass == getItem(position)?.javaClass }
.takeIf { it != -1 }
?: throw NullPointerException("Can not get viewType for position $position")
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =
delegates[viewType].createViewHolder(parent)
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) =
onBindViewHolder(holder, position, mutableListOf())
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int, payloads: MutableList<Any>) {
delegates[getItemViewType(position)].also { adapter ->
val delegatePayloads = payloads.map { it as AdapterItem.Payloadable }
getItem(position)?.also {
adapter.bindViewHolder(it, holder as ViewHolder<*, *>, delegatePayloads)
}
}
}
companion object {
@Suppress("UNCHECKED_CAST")
fun with(vararg delegates: AdapterDelegate<out AdapterItem, out ViewHolder<*, *>>): DelegateAdapter {
return DelegateAdapter(delegates.toList() as List<AdapterDelegate<AdapterItem, ViewHolder<*, *>>>)
}
}
} | 0 | Kotlin | 0 | 1 | 5a888548a8e53ac80b641d53d729240463f72041 | 1,632 | android-unsplash-gallery-sample | Apache License 2.0 |
app/src/main/java/com/diego/mvvmsample/data/source/local/MoviesLocalDataSource.kt | JmanuelPar | 608,774,740 | false | null | package com.diego.mvvmsample.data.source.local
import androidx.paging.PagingData
import com.diego.mvvmsample.data.model.MovieDetail
import com.diego.mvvmsample.data.source.MoviesDataSource
import com.diego.mvvmsample.db.MovieDatabase
import com.diego.mvvmsample.db.MovieDetailDao
import com.diego.mvvmsample.network.ApiResult
import kotlinx.coroutines.flow.Flow
class MoviesLocalDataSource internal constructor(
private val movieDetailDao: MovieDetailDao
) : MoviesDataSource {
override fun getMovies(): Flow<PagingData<MovieDatabase>> {
TODO("Not yet implemented")
}
override suspend fun getMovieById(movieId: Int): ApiResult<MovieDetail> {
TODO("Not yet implemented")
}
override suspend fun insertMovieDetail(movieDetail: MovieDetail) {
movieDetailDao.insert(movieDetail)
}
override suspend fun getMovieDetailById(movieDetailId: Int) =
movieDetailDao.getMovieDetailById(movieDetailId)
} | 0 | Kotlin | 0 | 0 | 03a21111f34e8aa68dc083bb7213470893d16a3d | 958 | MVVMMovies | MIT License |
AndroidMVP/feature/src/main/java/com/example/feature/domain/UserRepositoryImpl.kt | leonardodlana | 143,772,368 | false | null | package com.example.feature.domain
import com.example.common.ResultWrapper
import com.example.feature.domain.model.UserDetails
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.ObservableSource
class UserRepositoryImpl(
private val localDataSource: UserLocalDataSource,
private val remoteDataSource: UserRemoteDataSource
) : UserRepository {
override fun saveUserDetails(userDetails: UserDetails): Completable {
return localDataSource.saveUserDetails(userDetails)
}
override fun getUserDetails(userId: String): Observable<ResultWrapper<UserDetails>> {
return Observable.merge(
localDataSource.getUserDetails(userId),
getRemoteUserDetails(userId)
).firstOrError().toObservable()
}
private fun getRemoteUserDetails(userId: String): ObservableSource<ResultWrapper<UserDetails>> {
return remoteDataSource.getUserDetails(userId)
.flatMap { result ->
if (result.isSuccess()) {
saveUserDetails(result.model!!)
.andThen(Observable.just(result))
} else {
Observable.just(result)
}
}
}
} | 0 | Kotlin | 0 | 0 | dd920d5d7f77ebb146e88bb1fc2e7fe94b8519f2 | 1,240 | android-mvp-example | Apache License 2.0 |
ultron-common/src/commonMain/kotlin/com/atiurin/ultron/listeners/LogLifecycleListener.kt | open-tool | 312,407,423 | false | {"Kotlin": 861507, "Java": 13304, "HTML": 3222, "Swift": 594, "Batchfile": 236, "Shell": 236, "CSS": 102} | package com.atiurin.ultron.listeners
import com.atiurin.ultron.core.common.Operation
import com.atiurin.ultron.core.common.OperationResult
import com.atiurin.ultron.log.UltronLog
class LogLifecycleListener : UltronLifecycleListener() {
override fun before(operation: Operation) {
UltronLog.info("Start execution of ${operation.name}")
UltronLog.info("Element info: ${operation.elementInfo}")
}
override fun afterSuccess(operationResult: OperationResult<Operation>) {
UltronLog.info("Successfully executed ${operationResult.operation.name}")
}
override fun afterFailure(operationResult: OperationResult<Operation>) {
UltronLog.error("Failed ${operationResult.operation.name}. with description: \n" +
"${operationResult.description} ")
}
} | 8 | Kotlin | 10 | 99 | 7d19d4e0a653acc87b823b7b0c806b226faafb12 | 814 | ultron | Apache License 2.0 |
app/src/main/java/com/example/cprogrammingclub/global/AppModule.kt | ShubhadeepKarmakar | 647,951,516 | false | null | package com.example.cprogrammingclub.global
import android.content.Context
import com.example.usertodatabase.utils.Constants
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import io.appwrite.Client
import io.appwrite.services.Databases
import javax.inject.Inject
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
@Singleton
fun createDatabase(@ApplicationContext appContext: Context): Databases = Databases(
createClient(appContext)
)
@Provides
@Singleton
fun createClient(@ApplicationContext appContext: Context): Client =
Client(appContext)
.setEndpoint(Constants.ENDPOINT)
.setProject(Constants.PROJECT_ID)
} | 0 | Kotlin | 0 | 0 | a8cd912e93968afdbc6b6c4680c7f28db5a8dd47 | 874 | cprogrammingclub | Apache License 2.0 |
processor/src/test/kotlin/br/com/zup/beagle/android/compiler/beaglesdk/StoreHandlerTest.kt | ZupIT | 391,144,851 | false | null | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* 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 br.com.zup.beagle.android.compiler.beaglesdk
import br.com.zup.beagle.android.compiler.BeagleSetupProcessor.Companion.BEAGLE_SETUP_GENERATED
import br.com.zup.beagle.android.compiler.DependenciesRegistrarComponentsProvider
import br.com.zup.beagle.android.compiler.PROPERTIES_REGISTRAR_CLASS_NAME
import br.com.zup.beagle.android.compiler.PROPERTIES_REGISTRAR_METHOD_NAME
import br.com.zup.beagle.android.compiler.extensions.compile
import br.com.zup.beagle.android.compiler.mocks.BEAGLE_CONFIG_IMPORTS
import br.com.zup.beagle.android.compiler.mocks.LIST_OF_STORE_HANDLER
import br.com.zup.beagle.android.compiler.mocks.SIMPLE_BEAGLE_CONFIG
import br.com.zup.beagle.android.compiler.mocks.STORE_HANDLER_IMPORT
import br.com.zup.beagle.android.compiler.mocks.VALID_STORE_HANDLER
import br.com.zup.beagle.android.compiler.mocks.VALID_STORE_HANDLER_BEAGLE_SDK
import br.com.zup.beagle.android.compiler.mocks.VALID_STORE_HANDLER_BEAGLE_SDK_FROM_REGISTRAR
import br.com.zup.beagle.android.compiler.mocks.VALID_THIRD_STORE_HANDLER
import br.com.zup.beagle.android.compiler.processor.BeagleAnnotationProcessor
import com.tschuchort.compiletesting.KotlinCompilation
import com.tschuchort.compiletesting.SourceFile
import io.mockk.every
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.nio.file.Path
@DisplayName("Given Beagle Annotation Processor")
internal class StoreHandlerTest : BeagleSdkBaseTest() {
@TempDir
lateinit var tempPath: Path
@DisplayName("When register store handler")
@Nested
inner class RegisterStoreHandler {
@Test
@DisplayName("Then should add the store handler in beagle sdk")
fun testGenerateStoreHandlerCorrect() {
// GIVEN
val kotlinSource = SourceFile.kotlin(
FILE_NAME, BEAGLE_CONFIG_IMPORTS + VALID_STORE_HANDLER + SIMPLE_BEAGLE_CONFIG)
// WHEN
val compilationResult = compile(kotlinSource, BeagleAnnotationProcessor(), tempPath)
// THEN
val file = compilationResult.generatedFiles.find { file ->
file.name.startsWith(BEAGLE_SETUP_GENERATED)
}!!
val fileGeneratedInString = file.readText().replace(REGEX_REMOVE_SPACE, "")
val fileExpectedInString = VALID_STORE_HANDLER_BEAGLE_SDK
.replace(REGEX_REMOVE_SPACE, "")
assertEquals(fileExpectedInString, fileGeneratedInString)
assertEquals(KotlinCompilation.ExitCode.OK, compilationResult.exitCode)
}
}
@DisplayName("When already registered in other module PropertiesRegistrar")
@Nested
inner class RegisterFromOtherModule {
@Test
@DisplayName("Then should add the store handler in beagle sdk")
fun testGenerateStoreHandlerFromRegistrarCorrect() {
// GIVEN
every {
DependenciesRegistrarComponentsProvider.getRegisteredComponentsInDependencies(
any(),
PROPERTIES_REGISTRAR_CLASS_NAME,
PROPERTIES_REGISTRAR_METHOD_NAME,
)
} returns listOf(
Pair("""storeHandler""", "br.com.test.beagle.StoreHandlerTestThree()"),
)
val kotlinSource = SourceFile.kotlin(
FILE_NAME,
BEAGLE_CONFIG_IMPORTS + STORE_HANDLER_IMPORT +
VALID_THIRD_STORE_HANDLER + SIMPLE_BEAGLE_CONFIG
)
// WHEN
val compilationResult = compile(kotlinSource, BeagleAnnotationProcessor(), tempPath)
// THEN
val file = compilationResult.generatedFiles.find { file ->
file.name.startsWith(BEAGLE_SETUP_GENERATED)
}!!
val fileGeneratedInString = file.readText().replace(REGEX_REMOVE_SPACE, "")
val fileExpectedInString = VALID_STORE_HANDLER_BEAGLE_SDK_FROM_REGISTRAR
.replace(REGEX_REMOVE_SPACE, "")
assertEquals(fileExpectedInString, fileGeneratedInString)
assertEquals(KotlinCompilation.ExitCode.OK, compilationResult.exitCode)
}
}
@DisplayName("When register store handler")
@Nested
inner class InvalidStoreHandler {
@Test
@DisplayName("Then should show error with duplicate store handler")
fun testDuplicate() {
// GIVEN
val kotlinSource = SourceFile.kotlin(
FILE_NAME, BEAGLE_CONFIG_IMPORTS + LIST_OF_STORE_HANDLER + SIMPLE_BEAGLE_CONFIG)
// WHEN
val compilationResult = compile(kotlinSource, BeagleAnnotationProcessor(), tempPath)
// THEN
assertEquals(KotlinCompilation.ExitCode.COMPILATION_ERROR, compilationResult.exitCode)
Assertions.assertTrue(compilationResult.messages.contains(MESSAGE_DUPLICATE_STORE_HANDLER))
}
@Test
@DisplayName("Then should show error with duplicate store handler in PropertiesRegistrar")
fun testDuplicateInRegistrar() {
// GIVEN
every {
DependenciesRegistrarComponentsProvider.getRegisteredComponentsInDependencies(
any(),
PROPERTIES_REGISTRAR_CLASS_NAME,
PROPERTIES_REGISTRAR_METHOD_NAME,
)
} returns listOf(
Pair("""storeHandler""", "br.com.test.beagle.StoreHandlerTestThree()"),
)
val kotlinSource = SourceFile.kotlin(FILE_NAME,
BEAGLE_CONFIG_IMPORTS + VALID_STORE_HANDLER + VALID_THIRD_STORE_HANDLER + SIMPLE_BEAGLE_CONFIG
)
// WHEN
val compilationResult = compile(kotlinSource, BeagleAnnotationProcessor(), tempPath)
// THEN
Assertions.assertTrue(compilationResult.messages.contains(MESSAGE_DUPLICATE_STORE_HANDLER_REGISTRAR))
assertEquals(KotlinCompilation.ExitCode.COMPILATION_ERROR, compilationResult.exitCode)
}
}
companion object {
private const val FILE_NAME = "File1.kt"
private val REGEX_REMOVE_SPACE = "\\s".toRegex()
private const val MESSAGE_DUPLICATE_STORE_HANDLER = "error: StoreHandler defined multiple times: " +
"1 - br.com.test.beagle.StoreHandlerTest " +
"2 - br.com.test.beagle.StoreHandlerTestTwo. " +
"You must remove one implementation from the application."
private const val MESSAGE_DUPLICATE_STORE_HANDLER_REGISTRAR = "error: StoreHandler defined multiple times: " +
"1 - br.com.test.beagle.StoreHandlerTest " +
"2 - br.com.test.beagle.StoreHandlerTestThree. " +
"You must remove one implementation from the application."
}
} | 0 | Kotlin | 2 | 9 | 812a330777edd79a123495e9f678dc8f25a019f7 | 7,580 | beagle-android | Apache License 2.0 |
androidApp/src/main/java/com/ghostly/android/login/LoginViewModel.kt | roadrage312 | 822,698,287 | false | {"Kotlin": 159064, "Ruby": 2354, "Swift": 342} | package com.ghostly.android.login
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ghostly.android.utils.isValidEmail
import com.ghostly.android.utils.isValidGhostDomain
import com.ghostly.datastore.DataStoreConstants
import com.ghostly.datastore.DataStoreRepository
import com.ghostly.datastore.LoginDetailsStore
import com.ghostly.login.data.GetSiteDetailsUseCase
import com.ghostly.login.models.LoginDetails
import com.ghostly.login.models.LoginState
import com.ghostly.login.models.SiteDetails
import com.ghostly.network.models.Result
import com.ghostly.posts.data.GetPostsUseCase
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
class LoginViewModel(
private val loginDetailsStore: LoginDetailsStore,
private val getSiteDetailsUseCase: GetSiteDetailsUseCase,
private val getPostsUseCase: GetPostsUseCase,
private val dataStoreRepository: DataStoreRepository,
) : ViewModel() {
private val _uiState = MutableStateFlow<LoginState>(LoginState.CheckLogin)
val uiState: StateFlow<LoginState> = _uiState
private val _email = MutableStateFlow("")
val email: StateFlow<String> = _email
private val _password = MutableStateFlow("")
val password: StateFlow<String> = _password
private val _token = MutableStateFlow("")
val token: StateFlow<String> = _token
private val _domain = MutableStateFlow("")
val domain: StateFlow<String> = _domain
private val _inputValidated = MutableStateFlow(false)
val inputValidated: StateFlow<Boolean> = _inputValidated
private val _validDomain = MutableStateFlow(false)
val validDomain: StateFlow<Boolean> = _validDomain
private val _isLoggedIn = MutableStateFlow(false)
val isLoggedIn: StateFlow<Boolean> = _isLoggedIn
private val _siteDetails = MutableStateFlow<SiteDetails?>(null)
val siteDetails: StateFlow<SiteDetails?> = _siteDetails
init {
viewModelScope.launch {
_isLoggedIn.value = loginDetailsStore.get()?.isLoggedIn == true
if (_isLoggedIn.value.not()) {
_uiState.emit(LoginState.Start)
}
}
}
private fun validateInput() {
_inputValidated.value =
(isValidEmail(_email.value) && _password.value.isEmpty().not())
|| (_token.value.isEmpty().not() && isValidGhostDomain(_domain.value))
}
fun checkIfLoggedOut(logout: Boolean) = flow {
if (logout.not()) {
reset()
}
emit(logout)
}
fun onEmailChange(newEmail: String) {
_email.value = newEmail
validateInput()
}
fun onPasswordChange(newPass: String) {
_password.value = newPass
validateInput()
}
fun onTokenChange(newToken: String) {
_token.value = newToken
validateInput()
}
fun onDomainChange(newDomain: String) {
_domain.value = newDomain
_validDomain.value = isValidGhostDomain(_domain.value)
validateInput()
}
fun tryLogin() {
viewModelScope.launch {
loginDetailsStore.put(
LoginDetails(
domainUrl = domain.value,
apiKey = token.value,
isLoggedIn = true
)
)
when (val result = getPostsUseCase.getOnePost()) {
is Result.Success -> {
_isLoggedIn.value = true
}
is Result.Error -> {
loginDetailsStore.delete()
_inputValidated.value = false
_uiState.value =
LoginState.InvalidApiKey("${result.errorCode}: ${result.message}")
_isLoggedIn.value = false
}
}
}
}
suspend fun getSiteDetails() {
when (val result = getSiteDetailsUseCase.invoke(domain.value)) {
is Result.Success -> {
result.data?.siteDetails?.title?.let {
dataStoreRepository.putString(
DataStoreConstants.STORE_NAME,
it
)
}
result.data?.siteDetails?.icon?.let {
dataStoreRepository.putString(
DataStoreConstants.STORE_ICON,
it
)
}
_siteDetails.value = result.data?.siteDetails
_uiState.value = LoginState.ValidDomain
}
is Result.Error -> {
_validDomain.value = false
_uiState.value = LoginState.InvalidDomain("${result.errorCode}: ${result.message}")
}
}
}
fun notYouClicked() {
reset()
}
private fun reset() {
_siteDetails.value = null
_uiState.value = LoginState.Start
_domain.value = ""
_token.value = ""
_email.value = ""
_password.value = ""
_inputValidated.value = false
_validDomain.value = false
_isLoggedIn.value = false
}
}
| 1 | Kotlin | 1 | 4 | 8ed396f4525d1c6b146e503d1f301c55f74cf9b4 | 5,238 | ghostly | MIT License |
balloon/src/main/java/com/skydoves/balloon/ImageViewExtension.kt | SubhrajyotiSen | 204,344,101 | true | {"Kotlin": 64814} | /*
* Copyright (C) 2019 skydoves
*
* 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.skydoves.balloon
import android.content.res.ColorStateList
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.core.widget.ImageViewCompat
/** applies icon form attributes to a ImageView instance. */
internal fun ImageView.applyIconForm(iconForm: IconForm) {
val params = LinearLayout.LayoutParams(iconForm.iconSize, iconForm.iconSize)
params.setMargins(0, 0, iconForm.iconSpace, 0)
layoutParams = params
setImageDrawable(iconForm.drawable)
ImageViewCompat.setImageTintList(this, ColorStateList.valueOf(iconForm.iconColor))
}
| 1 | Kotlin | 0 | 0 | 893a9cac49ac486159d8a21585280c6168986eff | 1,174 | Balloon | Apache License 2.0 |
appcues/src/main/java/com/appcues/trait/StepDecoratingPadding.kt | appcues | 413,524,565 | false | null | package com.appcues.trait
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.unit.Density
class StepDecoratingPadding(private val density: Density) {
private val topPaddingPx = mutableStateOf(0)
private val bottomPaddingPx = mutableStateOf(0)
private val startPaddingPx = mutableStateOf(0)
private val endPaddingPx = mutableStateOf(0)
fun setTopPadding(px: Int) {
if (topPaddingPx.value < px) {
topPaddingPx.value = px
}
}
fun setBottomPadding(px: Int) {
if (bottomPaddingPx.value < px) {
bottomPaddingPx.value = px
}
}
fun setStartPadding(px: Int) {
if (startPaddingPx.value < px) {
startPaddingPx.value = px
}
}
fun setEndPadding(px: Int) {
if (endPaddingPx.value < px) {
endPaddingPx.value = px
}
}
val paddingValues = derivedStateOf {
with(density) {
PaddingValues(
start = startPaddingPx.value.toDp(),
top = topPaddingPx.value.toDp(),
end = endPaddingPx.value.toDp(),
bottom = bottomPaddingPx.value.toDp()
)
}
}
}
| 5 | Kotlin | 2 | 8 | 1d09fb83554fa7f12190e267064d8948ee7f35bb | 1,325 | appcues-android-sdk | MIT License |
packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/model/ReactModuleInfoTest.kt | react-native-tvos | 177,633,560 | false | {"C++": 4398815, "Java": 2649623, "JavaScript": 2551815, "Objective-C++": 1803949, "Kotlin": 1628327, "Objective-C": 1421207, "Ruby": 453872, "CMake": 109113, "TypeScript": 85912, "Shell": 58251, "C": 57980, "Assembly": 14920, "HTML": 1473, "Swift": 739} | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.modules.model
import com.facebook.react.module.model.ReactModuleInfo
import com.facebook.react.turbomodule.core.interfaces.TurboModule
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class ReactModuleInfoTest {
@Test
fun testCreateReactModuleInfo() {
val reactModuleInfo =
ReactModuleInfo(
/* name = */ "name",
/* className = */ "class",
/* canOverrideExistingModule = */ false,
/* needsEagerInit = */ false,
/* isCxxModule = */ false,
/* isTurboModule = */ false)
assertThat(reactModuleInfo.name()).isEqualTo("name")
assertThat(reactModuleInfo.canOverrideExistingModule()).isFalse()
assertThat(reactModuleInfo.needsEagerInit()).isFalse()
assertThat(reactModuleInfo.isCxxModule).isFalse()
assertThat(reactModuleInfo.isTurboModule).isFalse()
}
@Test
fun classIsTurboModule_withRandomClass() {
assertThat(ReactModuleInfo.classIsTurboModule(String::class.java)).isFalse()
}
@Test
fun classIsTurboModule_withTurboModule() {
assertThat(ReactModuleInfo.classIsTurboModule(TestTurboModule::class.java)).isTrue()
}
inner class TestTurboModule : TurboModule {
override fun initialize() = Unit
override fun invalidate() = Unit
}
}
| 7 | C++ | 147 | 942 | 692bc66a98c8928c950bece9a22d04c13f0c579d | 1,512 | react-native-tvos | MIT License |
app/src/main/java/org/booleanull/pushalerts/KoinApp.kt | booleanull | 271,825,376 | false | null | package org.booleanull.pushalerts
import androidx.room.Room
import org.booleanull.core.facade.SettingsFacade
import org.booleanull.core.facade.ThemeFacade
import org.booleanull.core.permission.PermissionCompositeController
import org.booleanull.core.repository.AlarmRepository
import org.booleanull.core.repository.ApplicationRepository
import org.booleanull.core_ui.base.Router
import org.booleanull.core_ui.handler.NavigationDeepLinkHandler
import org.booleanull.database.ApplicationDatabase
import org.booleanull.database.Migrations.MIGRATION_1_2
import org.booleanull.database.Migrations.MIGRATION_2_3
import org.booleanull.pushalerts.facade.SettingsFacadeImpl
import org.booleanull.pushalerts.facade.ThemeFacadeImpl
import org.booleanull.pushalerts.handler.ApplicationNavigationDeepLinkHandler
import org.booleanull.pushalerts.permission.PermissionCompositeControllerImpl
import org.booleanull.repositories.AlarmRepositoryImpl
import org.booleanull.repositories.ApplicationRepositoryImpl
import org.koin.android.ext.koin.androidContext
import org.koin.dsl.module
import ru.terrakok.cicerone.Cicerone
val appModule = module {
single { Cicerone.create(Router(get())) }
single { get<Cicerone<Router>>().router }
single { get<Cicerone<Router>>().navigatorHolder }
single<NavigationDeepLinkHandler> { ApplicationNavigationDeepLinkHandler() }
single {
Room
.databaseBuilder(get(), ApplicationDatabase::class.java, BuildConfig.DATABASE_FILE_NAME)
.addMigrations(MIGRATION_1_2, MIGRATION_2_3)
.build()
}
single<PermissionCompositeController> { PermissionCompositeControllerImpl(androidContext()) }
single<SettingsFacade> { SettingsFacadeImpl(androidContext()) }
single<ThemeFacade> { ThemeFacadeImpl(get()) }
single<ApplicationRepository> {
ApplicationRepositoryImpl(
androidContext().packageManager,
get()
)
}
single<AlarmRepository> { AlarmRepositoryImpl(get()) }
} | 0 | Kotlin | 0 | 0 | d12b716993a67c8dfa61ac88c54dab9736a1a423 | 2,001 | PushAlerts | Apache License 2.0 |
app/src/test/kotlin/compiler/intermediate/UniqueIdentifierFactoryTest.kt | brzeczyk-compiler | 545,707,939 | false | {"Kotlin": 1167879, "C": 4004, "Shell": 3242, "Vim Script": 2238} | package compiler.intermediate
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
class UniqueIdentifierFactoryTest {
private val pref = UniqueIdentifierFactory.FUNCTION_PREFIX
private val sep = UniqueIdentifierFactory.LEVEL_SEPARATOR
@Test
fun `test basic`() {
val factory = UniqueIdentifierFactory()
val curr = "no_polish_signs"
val identifier = factory.build(null, curr)
val expected = "${pref}${sep}$curr"
assertEquals(expected, identifier.value)
}
@Test
fun `test no polish signs in output`() {
// nasm lexer is incapable of parsing unicode
val factory = UniqueIdentifierFactory()
val curr = "polskie_znaki_są_żeś_zaiście_świetneż"
val identifier = factory.build(null, curr)
val expected = "${pref}${sep}polskie_znaki_sa#_z#es#_zais#cie_s#wietnez#"
assertEquals(expected, identifier.value)
}
@Test
fun `test prefix`() {
val factory = UniqueIdentifierFactory()
val curr = "no_polish_signs"
val prefix = "some_prefix"
val identifier = factory.build(prefix, curr)
val expected = "${prefix}${sep}$curr"
assertEquals(expected, identifier.value)
}
@Test
fun `test identical strings with accuracy to polish signs do not cause conflicts`() {
val factory = UniqueIdentifierFactory()
val curr1 = "żeś"
val curr2 = "żes"
val curr3 = "źes"
val curr4 = "zes"
val commonPrefix = "some_prefix"
val identifier1 = factory.build(commonPrefix, curr1)
val identifier2 = factory.build(commonPrefix, curr2)
val identifier3 = factory.build(commonPrefix, curr3)
val identifier4 = factory.build(commonPrefix, curr4)
val expected1 = "${commonPrefix}${sep}z#es#"
val expected2 = "${commonPrefix}${sep}z#es"
val expected3 = "${commonPrefix}${sep}x#es"
val expected4 = "${commonPrefix}${sep}zes"
assertEquals(expected1, identifier1.value)
assertEquals(expected2, identifier2.value)
assertEquals(expected3, identifier3.value)
assertEquals(expected4, identifier4.value)
}
@Test
fun `test illegal character throws an exception`() {
val factory = UniqueIdentifierFactory()
val curr = "mwahahaha|!-"
assertFailsWith(IllegalCharacter::class) { factory.build(null, curr) }
}
@Test
fun `test conflict throws an exception`() {
val factory = UniqueIdentifierFactory()
val first = "żeś"
val second = "żes#" // not possible with our regex for identifier token
factory.build(null, first)
assertFailsWith(InconsistentFunctionNamingConvention::class) { factory.build(null, second) }
}
}
| 7 | Kotlin | 0 | 2 | 5917f4f9d0c13c2c87d02246da8ef8394499d33c | 2,825 | brzeczyk | MIT License |
app/src/main/java/ch/silvannellen/githubbrowser/view/repository/di/RepositoryComponent.kt | snellen | 253,709,850 | false | null | package ch.silvannellen.githubbrowser.view.repository.di
import ch.silvannellen.githubbrowser.di.GithubBrowserApplicationComponent
import ch.silvannellen.githubbrowser.di.annotation.PerFragment
import ch.silvannellen.githubbrowser.view.repository.RepositoryFragment
import ch.silvannellen.githubbrowser.viewmodel.repo.RepositoryViewModel
import ch.silvannellen.githubbrowser.viewmodel.repo.di.RepositoryViewModelModule
import dagger.Component
@PerFragment
@Component(
dependencies = [GithubBrowserApplicationComponent::class],
modules = [RepositoryViewModelModule::class]
)
interface RepositoryComponent {
fun inject(f: RepositoryFragment)
fun getViewModel(): RepositoryViewModel
} | 0 | Kotlin | 0 | 1 | e8f72e6aa50c35191960d1c5db18c88903404420 | 702 | umvvm-demo | Apache License 2.0 |
app/src/main/java/com/github/rooneyandshadows/lightbulb/easyrecyclerviewdemo/demo/views/SelectableRecyclerView.kt | RooneyAndShadows | 424,519,760 | false | null | package com.github.rooneyandshadows.lightbulb.easyrecyclerviewdemo.demo.views
import android.content.Context
import android.util.AttributeSet
import com.github.rooneyandshadows.lightbulb.easyrecyclerview.EasyRecyclerView
import com.github.rooneyandshadows.lightbulb.easyrecyclerviewdemo.demo.views.adapters.SelectableAdapter
import com.github.rooneyandshadows.lightbulb.easyrecyclerviewdemo.demo.models.DemoModel
class SelectableRecyclerView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
) : EasyRecyclerView<DemoModel>(context, attrs) {
override val adapterCreator: AdapterCreator<DemoModel>
get() = object : AdapterCreator<DemoModel> {
override fun createAdapter(): SelectableAdapter {
return SelectableAdapter()
}
}
} | 0 | Kotlin | 2 | 5 | 72e65f7d03fbd9bcef929e5ce59be930b786db1f | 818 | lightbulb-easyrecyclerview | Apache License 2.0 |
app/src/main/java/com/github/rooneyandshadows/lightbulb/easyrecyclerviewdemo/demo/views/SelectableRecyclerView.kt | RooneyAndShadows | 424,519,760 | false | null | package com.github.rooneyandshadows.lightbulb.easyrecyclerviewdemo.demo.views
import android.content.Context
import android.util.AttributeSet
import com.github.rooneyandshadows.lightbulb.easyrecyclerview.EasyRecyclerView
import com.github.rooneyandshadows.lightbulb.easyrecyclerviewdemo.demo.views.adapters.SelectableAdapter
import com.github.rooneyandshadows.lightbulb.easyrecyclerviewdemo.demo.models.DemoModel
class SelectableRecyclerView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
) : EasyRecyclerView<DemoModel>(context, attrs) {
override val adapterCreator: AdapterCreator<DemoModel>
get() = object : AdapterCreator<DemoModel> {
override fun createAdapter(): SelectableAdapter {
return SelectableAdapter()
}
}
} | 0 | Kotlin | 2 | 5 | 72e65f7d03fbd9bcef929e5ce59be930b786db1f | 818 | lightbulb-easyrecyclerview | Apache License 2.0 |
src/min-cost-to-connect-all-points/index.kt | masx200 | 787,837,300 | false | {"Kotlin": 74470, "Batchfile": 92} | package com.github.masx200.leetcode_test_kotlin.min_cost_to_connect_all_points
class Solution {
fun minCostConnectPoints(points: Array<IntArray>): Int {
val p0 = points[0]
val ds = points.mapIndexed { i, p -> Pair(i, ManhattanDistance(p, p0)) }.toMap(mutableMapOf())
ds.remove(0)
var ans = 0
while (ds.isNotEmpty()) {
var mi = 0
var md = Int.MAX_VALUE
var p1 = IntArray(0)
ds.onEach { (i, d) ->
val p = points[i]
if (d < md) {
mi = i
p1 = p
md = d
}
}
ds.remove(mi)
ans += md
ds.onEach { (i, d) ->
val p = points[i]
ds[i] = Math.min(d, ManhattanDistance(p, p1))
}
}
return ans
}
}
fun ManhattanDistance(a: IntArray, b: IntArray): Int {
return Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1])
}
| 0 | Kotlin | 0 | 1 | ceb82e062e6dbf50104e8421d3f7a820c06e1acf | 1,010 | leetcode-test-kotlin | Mulan Permissive Software License, Version 2 |
services/csm.cloud.project.project/src/main/kotlin/com/bosch/pt/iot/smartsite/project/task/shared/dto/SaveTaskDto.kt | boschglobal | 805,348,245 | false | {"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344} | /*
* ************************************************************************
*
* Copyright: <NAME> Power Tools GmbH, 2018 - 2023
*
* ************************************************************************
*/
package com.bosch.pt.iot.smartsite.project.task.shared.dto
import com.bosch.pt.iot.smartsite.project.participant.ParticipantId
import com.bosch.pt.iot.smartsite.project.projectcraft.domain.ProjectCraftId
import com.bosch.pt.iot.smartsite.project.task.shared.model.TaskStatusEnum
import com.bosch.pt.iot.smartsite.project.workarea.domain.WorkAreaId
open class SaveTaskDto(
val name: String,
val description: String?,
val location: String?,
val status: TaskStatusEnum,
val projectCraftIdentifier: ProjectCraftId,
val assigneeIdentifier: ParticipantId?,
val workAreaIdentifier: WorkAreaId?
)
| 0 | Kotlin | 3 | 9 | 9f3e7c4b53821bdfc876531727e21961d2a4513d | 843 | bosch-pt-refinemysite-backend | Apache License 2.0 |
android-gradle-plugin-aspectj/src/main/kotlin/com/archinamon/api/BuildTimeListener.kt | thunderheadone | 152,609,582 | true | {"Kotlin": 68338} | /*
* Copyright 2018 the original author or authors.
* Copyright 2018 Thunderhead
*
* 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.archinamon.api
import org.gradle.BuildListener
import org.gradle.BuildResult
import org.gradle.api.Task
import org.gradle.api.execution.TaskExecutionListener
import org.gradle.api.initialization.Settings
import org.gradle.api.invocation.Gradle
import org.gradle.api.tasks.TaskState
class BuildTimeListener: TaskExecutionListener, BuildListener {
private var startTime: Long = 0L
private var times = mutableListOf<Pair<Long, String>>()
override fun buildStarted(gradle: Gradle) {}
override fun settingsEvaluated(settings: Settings) {}
override fun projectsLoaded(gradle: Gradle) {}
override fun projectsEvaluated(gradle: Gradle) {}
override fun buildFinished(result: BuildResult) {
println("Task spend time:")
times.filter { it.first > 50 }
.forEach { println("%7sms\t%s".format(it.first, it.second)) }
}
override fun beforeExecute(task: Task) {
startTime = System.currentTimeMillis()
}
override fun afterExecute(task: Task, state: TaskState) {
val ms = System.currentTimeMillis() - startTime
times.add(Pair(ms, task.path))
task.project.logger.warn("${task.path} spend ${ms}ms")
}
} | 0 | Kotlin | 0 | 5 | 929ea8b656dcf2b5b235f0f7a246f9deee09c9b5 | 1,887 | one-android-gradle-aspectj | Apache License 2.0 |
core/src/com/mygdx/game/GameJam9Game.kt | LostMekka | 559,158,632 | false | {"Kotlin": 72206, "Java": 606} | package com.mygdx.game
import com.badlogic.gdx.Screen
import com.badlogic.gdx.assets.AssetManager
import com.mygdx.game.assets.AssetDescriptors
import com.mygdx.game.screens.GameScreen
import com.mygdx.game.screens.SplashScreen
import com.mygdx.game.ui.initUi
import ktx.app.KtxGame
val assetManager by lazy { AssetManager() }
class MyGdxGame : KtxGame<Screen>() {
override fun create() {
loadAssets()
initUi()
addScreen(GameScreen())
addScreen(SplashScreen(this))
setScreen<SplashScreen>()
}
private fun loadAssets() {
for (descriptor in AssetDescriptors.ALL) {
assetManager.load(descriptor)
}
assetManager.finishLoading()
}
}
| 0 | Kotlin | 0 | 3 | 00d8a22620d9991e8eca7fc6bbcd681b6d37092e | 726 | 3m5.gamejam-9 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.