path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
756M
is_fork
bool
2 classes
languages_distribution
stringlengths
12
2.44k
content
stringlengths
6
6.29M
issues
float64
0
10k
main_language
stringclasses
128 values
forks
int64
0
54.2k
stars
int64
0
157k
commit_sha
stringlengths
40
40
size
int64
6
6.29M
name
stringlengths
1
100
license
stringclasses
104 values
compiler/tests/org/jetbrains/kotlin/klib/FilePathsInKlibTest.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.klib import com.intellij.openapi.vfs.StandardFileSystems import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiManager import org.jetbrains.kotlin.backend.common.CommonKLibResolver import org.jetbrains.kotlin.backend.common.serialization.codedInputStream import org.jetbrains.kotlin.backend.common.serialization.proto.IrFile import org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport import org.jetbrains.kotlin.cli.js.klib.generateIrForKlibSerialization import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.jetbrains.kotlin.codegen.CodegenTestCase import org.jetbrains.kotlin.config.CommonConfigurationKeys import org.jetbrains.kotlin.config.CompilerConfiguration import org.jetbrains.kotlin.diagnostics.DiagnosticReporterFactory import org.jetbrains.kotlin.incremental.md5 import org.jetbrains.kotlin.ir.backend.js.* import org.jetbrains.kotlin.ir.declarations.impl.IrFactoryImpl import org.jetbrains.kotlin.protobuf.ExtensionRegistryLite import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.test.util.KtTestUtil import org.jetbrains.kotlin.util.DummyLogger import java.io.File import java.nio.file.Path class FilePathsInKlibTest : CodegenTestCase() { companion object { private const val MODULE_NAME = "M" private const val testDataFile = "compiler/testData/ir/klibLayout/multiFiles.kt" } private fun loadKtFiles(directory: File): List<KtFile> { val psiManager = PsiManager.getInstance(myEnvironment.project) val fileSystem = VirtualFileManager.getInstance().getFileSystem(StandardFileSystems.FILE_PROTOCOL) val vDirectory = fileSystem.findFileByPath(directory.canonicalPath) ?: error("File not found: $directory") return psiManager.findDirectory(vDirectory)?.files?.map { it as KtFile } ?: error("Cannot load KtFiles") } private val runtimeKlibPath = "libraries/stdlib/build/classes/kotlin/js/main" private fun analyseKtFiles(configuration: CompilerConfiguration, ktFiles: List<KtFile>): ModulesStructure { return prepareAnalyzedSourceModule( myEnvironment.project, ktFiles, configuration, listOf(runtimeKlibPath), emptyList(), AnalyzerWithCompilerReport(configuration), ) } private fun produceKlib(module: ModulesStructure, destination: File) { // TODO: improve API for generateIrForKlibSerialization and related functionality and remove code duplication here and in similar places in the code val sourceFiles = (module.mainModule as MainModule.SourceFiles).files val icData = module.compilerConfiguration.incrementalDataProvider?.getSerializedData(sourceFiles) ?: emptyList() val (moduleFragment, _) = generateIrForKlibSerialization( module.project, sourceFiles, module.compilerConfiguration, module.jsFrontEndResult.jsAnalysisResult, sortDependencies(module.moduleDependencies), icData, IrFactoryImpl, verifySignatures = true ) { module.getModuleDescriptor(it) } val metadataSerializer = KlibMetadataIncrementalSerializer(module.compilerConfiguration, module.project, module.jsFrontEndResult.hasErrors) val diagnosticReporter = DiagnosticReporterFactory.createPendingReporter() generateKLib( module, outputKlibPath = destination.path, nopack = false, jsOutputName = MODULE_NAME, icData = icData, moduleFragment = moduleFragment, diagnosticReporter = diagnosticReporter ) { file -> metadataSerializer.serializeScope(file, module.jsFrontEndResult.bindingContext, moduleFragment.descriptor) } } private fun setupEnvironment(): CompilerConfiguration { val configuration = CompilerConfiguration() myEnvironment = KotlinCoreEnvironment.createForTests(testRootDisposable, configuration, EnvironmentConfigFiles.JS_CONFIG_FILES) configuration.put(CommonConfigurationKeys.MODULE_NAME, MODULE_NAME) return configuration } private fun File.md5(): Long = readBytes().md5() private fun File.loadKlibFilePaths(): List<String> { val libs = CommonKLibResolver.resolve(listOf(runtimeKlibPath, canonicalPath), DummyLogger).getFullList() val lib = libs.last() val fileSize = lib.fileCount() val extReg = ExtensionRegistryLite.newInstance() val result = ArrayList<String>(fileSize) for (i in 0 until fileSize) { val fileStream = lib.file(i).codedInputStream val fileProto = IrFile.parseFrom(fileStream, extReg) val fileName = fileProto.fileEntry.name result.add(fileName) } return result } private fun createTestFiles(): List<TestFile> { val file = File(testDataFile) val expectedText = KtTestUtil.doLoadFile(file) return createTestFilesFromFile(file, expectedText) } private fun compileKlib(testFiles: List<TestFile>, configuration: CompilerConfiguration, workingDir: File): File { for (testFile in testFiles) { val file = File(workingDir, testFile.name).also { it.parentFile.let { p -> if (!p.exists()) p.mkdirs() } } file.writeText(testFile.content) } val ktFiles = loadKtFiles(workingDir) val module = analyseKtFiles(configuration, ktFiles) val artifact = File(workingDir, "$MODULE_NAME.klib") produceKlib(module, artifact) return artifact } fun testStableCompilation() { withTempDir { dirA -> withTempDir { dirB -> val testFiles = createTestFiles() val configuration = setupEnvironment() configuration.put(CommonConfigurationKeys.KLIB_RELATIVE_PATH_BASES, listOf(dirA.canonicalPath, dirB.canonicalPath)) val moduleA = compileKlib(testFiles, configuration, dirA) val moduleB = compileKlib(testFiles, configuration, dirB) assertEquals(moduleA.md5(), moduleB.md5()) } } } fun testRelativePaths() { withTempDir { testTempDir -> val testFiles = createTestFiles() val configuration = setupEnvironment() configuration.put(CommonConfigurationKeys.KLIB_RELATIVE_PATH_BASES, listOf(testTempDir.canonicalPath)) val artifact = compileKlib(testFiles, configuration, testTempDir) val modulePaths = artifact.loadKlibFilePaths().map { it.replace("/", File.separator) } val dirPaths = testTempDir.listFiles { _, name -> name.endsWith(".kt") }!!.map { it.relativeTo(testTempDir).path } assertSameElements(modulePaths, dirPaths) } } fun testAbsoluteNormalizedPath() { withTempDir { testTempDir -> val testFiles = createTestFiles() val configuration = setupEnvironment() configuration.put(CommonConfigurationKeys.KLIB_NORMALIZE_ABSOLUTE_PATH, true) val artifact = compileKlib(testFiles, configuration, testTempDir) val modulePaths = artifact.loadKlibFilePaths().map { it.replace("/", File.separator) } val dirCanonicalPaths = testTempDir.listFiles { _, name -> name.endsWith(".kt") }!!.map { it.canonicalPath } assertSameElements(modulePaths, dirCanonicalPaths) } } private fun String.normalizePath(): String = replace(File.separator, "/") fun testUnrelatedBase() { withTempDir { testTempDir -> val testFiles = createTestFiles() val dummyPath = kotlin.io.path.createTempDirectory() val dummyFile = dummyPath.toFile().also { assert(it.isDirectory) } try { val configuration = setupEnvironment() configuration.put(CommonConfigurationKeys.KLIB_RELATIVE_PATH_BASES, listOf(dummyFile.canonicalPath)) val artifact = compileKlib(testFiles, configuration, testTempDir) val modulePaths = artifact.loadKlibFilePaths() val dirCanonicalPaths = testTempDir.listFiles { _, name -> name.endsWith(".kt") }!!.map { it.canonicalPath } assertSameElements(modulePaths.map { it.normalizePath() }, dirCanonicalPaths.map { it.normalizePath() }) } finally { dummyFile.deleteRecursively() } } } private fun withTempDir(f: (File) -> Unit) { val workingPath: Path = kotlin.io.path.createTempDirectory() val workingDirFile = workingPath.toFile().also { assert(it.isDirectory) } try { f(workingDirFile) } finally { workingDirFile.deleteRecursively() } } }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
9,229
kotlin
Apache License 2.0
compiler/test/data/typescript/node_modules/stdlib/convertTsStdlib.d.kt
Kotlin
159,510,660
false
{"Kotlin": 2656346, "WebIDL": 323681, "TypeScript": 135641, "JavaScript": 19475, "ANTLR": 11333}
// [test] convertTsStdlib.module_resolved_name.kt @file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS") import kotlin.js.* import org.khronos.webgl.* import org.w3c.dom.* import org.w3c.dom.events.* import org.w3c.dom.parsing.* import org.w3c.dom.svg.* import org.w3c.dom.url.* import org.w3c.fetch.* import org.w3c.files.* import org.w3c.notifications.* import org.w3c.performance.* import org.w3c.workers.* import org.w3c.xhr.* external fun frequencies(a: Array<String>): Array<Number> external fun processTemplate(a: Array<String>): Array<String> typealias NumArray = Array<Number> typealias SmartArray<T> = Array<T> typealias SmartNumArray<T> = Array<T> typealias MyVerySpecificException = Error external interface `T$0` { @nativeGetter operator fun get(shortName: String): dynamic /* String? | ReadonlyArray<String>? */ @nativeSetter operator fun set(shortName: String, value: String) @nativeSetter operator fun set(shortName: String, value: Array<String>) } external interface Processor<T> { fun process(arg: T) fun process(arg: Array<T>) fun alias(aliases: `T$0`) fun shape(input: SmartArray<String>): NumArray fun convertToSmartArray(input: NumArray): SmartArray<T> fun onError(handler: (error: MyVerySpecificException) -> Unit) } // ------------------------------------------------------------------------------------------ // [test] convertTsStdlib.api.module_resolved_name.kt @file:JsModule("api") @file:JsNonModule @file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS") package api import kotlin.js.* import org.khronos.webgl.* import org.w3c.dom.* import org.w3c.dom.events.* import org.w3c.dom.parsing.* import org.w3c.dom.svg.* import org.w3c.dom.url.* import org.w3c.fetch.* import org.w3c.files.* import org.w3c.notifications.* import org.w3c.performance.* import org.w3c.workers.* import org.w3c.xhr.* import tsstdlib.IterableIterator external fun createIterable(): IterableIterator<String>
242
Kotlin
43
508
55213ea607fb42ff13b6278613c8fbcced9aa418
2,123
dukat
Apache License 2.0
js/js.translator/testData/incremental/invalidation/genericInlineFunctions/main/m.proxy.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
fun isEqual(l: Any?, r: Any?) = if (l == r) true else null fun box(stepId: Int): String { when (stepId) { in 0..5 -> isEqual(foo_proxy("test"), 123) ?: return "Fail" in 8..13 -> isEqual(foo_proxy("test"), 123) ?: return "Fail" in 16..21 -> isEqual(foo_proxy("test"), 123) ?: return "Fail" 6, 14, 22 -> isEqual(foo_proxy("test"), 99) ?: return "Fail" 7, 15, 23 -> isEqual(foo_proxy("test"), "test") ?: return "Fail" else -> return "Unknown" } return "OK" }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
517
kotlin
Apache License 2.0
compiler/testData/checkLocalVariablesTable/inlineSimple.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
class A { inline fun inlineFun(s: () -> Unit) { s() } fun foo() { var s = 1; inlineFun ({ var zzz = 2; zzz++ }) } } // METHOD : A.foo()V // VARIABLE : NAME=zzz TYPE=I INDEX=5 // VARIABLE : NAME=$i$a$-inlineFun-A$foo$1 TYPE=I INDEX=4 // VARIABLE : NAME=this_$iv TYPE=LA; INDEX=2 // VARIABLE : NAME=$i$f$inlineFun TYPE=I INDEX=3 // VARIABLE : NAME=s TYPE=I INDEX=1 // VARIABLE : NAME=this TYPE=LA; INDEX=0
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
511
kotlin
Apache License 2.0
data/src/main/kotlin/com/tasomaniac/devwidget/data/FavActionDaoExtensions.kt
tasomaniac
117,675,057
false
null
package com.tasomaniac.devwidget.data fun FavActionDao.findFavActionByWidgetIdSync(appWidgetId: Int) = _findFavActionByWidgetIdSync(appWidgetId) ?: Action.UNINSTALL fun FavActionDao.findFavActionByWidgetId(appWidgetId: Int) = _findFavActionByWidgetId(appWidgetId).toSingle(Action.UNINSTALL)
5
Kotlin
5
35
c8f25f18a1b7f86146e21567cbe0aa7847e4451c
301
DevWidget
Apache License 2.0
app/src/main/java/pointlessgroup/pointless/GeofenceTransitionsIntentService.kt
brunodles
110,770,735
false
null
package pointlessgroup.pointless; import android.app.IntentService import android.content.Intent class GeofenceTransitionsIntentService : IntentService("GeofenceService") { override fun onHandleIntent(intent: Intent?) { } }
0
Kotlin
0
0
501c26dee22f527c5113d36daf483a1582ad3209
234
pointless
MIT License
plugins/scripting/scripting-compiler-impl/src/org/jetbrains/kotlin/scripting/definitions/ScriptDependenciesProvider.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
/* * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.scripting.definitions import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.scripting.resolve.ScriptCompilationConfigurationResult import org.jetbrains.kotlin.scripting.resolve.ScriptCompilationConfigurationWrapper import kotlin.script.experimental.api.ScriptCompilationConfiguration import kotlin.script.experimental.api.valueOrNull import kotlin.script.experimental.dependencies.ScriptDependencies // Note: misleading name, it is now general configurations provider, not only for dependencies // but we are affraid to touch it so far, since the impact should be assessed first // TODO: consider deprecating completely and swith to a new interface in the K2 // TODO: support SourceCode (or KtSourceFile) as a key open class ScriptDependenciesProvider constructor( protected val project: Project ) { @Suppress("DEPRECATION") @Deprecated("Migrating to configuration refinement", level = DeprecationLevel.ERROR) fun getScriptDependencies(file: VirtualFile): ScriptDependencies? { val ktFile = PsiManager.getInstance(project).findFile(file) as? KtFile ?: return null return getScriptConfiguration(ktFile)?.legacyDependencies } @Suppress("DEPRECATION") @Deprecated("Migrating to configuration refinement", level = DeprecationLevel.ERROR) fun getScriptDependencies(file: PsiFile): ScriptDependencies? { if (file !is KtFile) return null return getScriptConfiguration(file)?.legacyDependencies } open fun getScriptConfigurationResult(file: KtFile): ScriptCompilationConfigurationResult? = null // TODO: consider fixing implementations and removing default implementation open fun getScriptConfigurationResult( file: KtFile, providedConfiguration: ScriptCompilationConfiguration? ): ScriptCompilationConfigurationResult? = getScriptConfigurationResult(file) open fun getScriptConfiguration(file: KtFile): ScriptCompilationConfigurationWrapper? = getScriptConfigurationResult(file)?.valueOrNull() companion object { fun getInstance(project: Project): ScriptDependenciesProvider? = project.getService(ScriptDependenciesProvider::class.java) } }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
2,573
kotlin
Apache License 2.0
compiler/testData/codegen/box/properties/kt4252_2.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
class Foo() { companion object { val bar = "OK"; var boo = "FAIL"; } val a = bar var b = Foo.bar val c: String var d: String init { c = bar d = Foo.bar boo = "O" Foo.boo += "K" } } fun box(): String { val foo = Foo() if (foo.a != "OK") return "foo.a != OK" if (foo.b != "OK") return "foo.b != OK" if (foo.c != "OK") return "foo.c != OK" if (foo.d != "OK") return "foo.d != OK" if (Foo.boo != "OK") return "Foo.boo != OK" return "OK" }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
547
kotlin
Apache License 2.0
async/src/main/java/contacts/async/InsertAsync.kt
vestrel00
223,332,584
false
{"Kotlin": 1616347, "Shell": 635}
package contacts.async import contacts.core.Insert import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlinx.coroutines.async import kotlinx.coroutines.isActive import kotlinx.coroutines.withContext import kotlin.coroutines.CoroutineContext /** * Suspends the current coroutine, performs the operation in the given [context], then returns the * result. * * Computations automatically stops if the parent coroutine scope / job is cancelled. * * See [Insert.commit]. */ suspend fun Insert.commitWithContext(context: CoroutineContext = ASYNC_DISPATCHER): Insert.Result = withContext(context) { commit { !isActive } } /** * Suspends the current coroutine, performs the operation in the given [context], then returns the * result. * * Computations automatically stops if the parent coroutine scope / job is cancelled. * * See [Insert.commitInChunks]. */ suspend fun Insert.commitInChunksWithContext( context: CoroutineContext = ASYNC_DISPATCHER ): Insert.Result = withContext(context) { commitInChunks { !isActive } } /** * Creates a [CoroutineScope] with the given [context], performs the operation in that scope, then * returns the [Deferred] result. * * Computations automatically stops if the parent coroutine scope / job is cancelled. * * See [Insert.commit]. */ fun Insert.commitAsync(context: CoroutineContext = ASYNC_DISPATCHER): Deferred<Insert.Result> = CoroutineScope(context).async { commit { !isActive } } /** * Creates a [CoroutineScope] with the given [context], performs the operation in that scope, then * returns the [Deferred] result. * * Computations automatically stops if the parent coroutine scope / job is cancelled. * * See [Insert.commitInChunks]. */ fun Insert.commitInChunksAsync( context: CoroutineContext = ASYNC_DISPATCHER ): Deferred<Insert.Result> = CoroutineScope(context).async { commitInChunks { !isActive } }
23
Kotlin
36
555
193014a913ad76e2de31d1da1e21f0b475887003
1,922
contacts-android
Apache License 2.0
app/src/test/java/org/simple/clinic/scanid/ScanSimpleIdScreenLogicTest.kt
simpledotorg
132,515,649
false
{"Kotlin": 5970450, "Shell": 1660, "HTML": 545}
package org.simple.clinic.scanid import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoMoreInteractions import org.mockito.kotlin.verifyNoInteractions import com.spotify.mobius.Init import io.reactivex.rxkotlin.ofType import io.reactivex.subjects.PublishSubject import org.junit.After import org.junit.Test import org.simple.sharedTestCode.TestData import org.simple.clinic.appconfig.Country import org.simple.clinic.mobius.first import org.simple.clinic.patient.onlinelookup.api.LookupPatientOnline import org.simple.clinic.scanid.EnteredCodeValidationResult.Failure.Empty import org.simple.clinic.scanid.EnteredCodeValidationResult.Failure.NotEqualToRequiredLength import org.simple.clinic.util.scheduler.TestSchedulersProvider import org.simple.clinic.widgets.UiEvent import org.simple.mobius.migration.MobiusTestFixture class ScanSimpleIdScreenLogicTest { private val uiEvents = PublishSubject.create<UiEvent>() private val uiActions = mock<ScanSimpleIdUiActions>() private val lookupPatientOnline = mock<LookupPatientOnline>() private lateinit var testFixture: MobiusTestFixture<ScanSimpleIdModel, ScanSimpleIdEvent, ScanSimpleIdEffect> @After fun tearDown() { testFixture.dispose() } @Test fun `if scanned qr code is not a valid uuid then do nothing`() { // given val scannedCode = "96d93a33-db68" // when setupController() uiEvents.onNext(ScanSimpleIdScreenQrCodeScanned(scannedCode)) // then verifyNoInteractions(uiActions) } @Test fun `when the keyboard is up, then hide the QR code scanner view`() { // when setupController() uiEvents.onNext(ShowKeyboard) // then verify(uiActions).hideQrCodeScannerView() verifyNoMoreInteractions(uiActions) } @Test fun `when the keyboard is dismissed, then show the QR code scanner view`() { // when setupController() uiEvents.onNext(HideKeyboard) // then verify(uiActions).showQrCodeScannerView() verifyNoMoreInteractions(uiActions) } @Test fun `when the keyboard is up, then don't process invalid QR code scan events`() { // when setupController() with(uiEvents) { onNext(ShowKeyboard) onNext(ScanSimpleIdScreenQrCodeScanned("96d93a33-db68")) } // then verify(uiActions).hideQrCodeScannerView() verifyNoMoreInteractions(uiActions) } @Test fun `when invalid (less than required length) short code is entered then show validation error`() { //given val shortCodeText = "3456" val shortCodeInput = EnteredCodeInput(shortCodeText) //when setupController() uiEvents.onNext(EnteredCodeSearched(shortCodeInput)) //then verify(uiActions).showEnteredCodeValidationError(NotEqualToRequiredLength) verifyNoMoreInteractions(uiActions) } @Test fun `when short code text changes, then hide validation error`() { //given val invalidShortCode = "3456" val invalidShortCodeInput = EnteredCodeInput(invalidShortCode) //when setupController() uiEvents.onNext(EnteredCodeSearched(invalidShortCodeInput)) uiEvents.onNext(EnteredCodeChanged) //then verify(uiActions).showEnteredCodeValidationError(NotEqualToRequiredLength) verify(uiActions).hideEnteredCodeValidationError() verifyNoMoreInteractions(uiActions) } @Test fun `when short code is empty, then show empty error`() { //given val emptyShortCodeInput = EnteredCodeInput("") //when setupController() uiEvents.onNext(EnteredCodeSearched(emptyShortCodeInput)) //then verify(uiActions).showEnteredCodeValidationError(Empty) verifyNoMoreInteractions(uiActions) } private fun setupController() { val viewEffectHandler = ScanSimpleIdViewEffectHandler( uiActions = uiActions ) val effectHandler = ScanSimpleIdEffectHandler( schedulersProvider = TestSchedulersProvider.trampoline(), patientRepository = mock(), qrCodeJsonParser = mock(), country = TestData.country(isoCountryCode = Country.INDIA), lookupPatientOnline = lookupPatientOnline, viewEffectsConsumer = viewEffectHandler::handle, ) testFixture = MobiusTestFixture( events = uiEvents.ofType(), init = Init { first(it) }, update = ScanSimpleIdUpdate(isIndianNHIDSupportEnabled = true, isOnlinePatientLookupEnabled = true), effectHandler = effectHandler.build(), defaultModel = ScanSimpleIdModel.create(OpenedFrom.PatientsTabScreen), modelUpdateListener = { /* no-op */ } ) testFixture.start() } }
4
Kotlin
73
223
58d14c702db2b27b9dc6c1298c337225f854be6d
4,624
simple-android
MIT License
example7/android/app/src/main/kotlin/se/pixolity/example7/MainActivity.kt
vandadnp
594,285,284
false
null
package se.pixolity.example7 import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
1
C++
9
44
f21f8798d6d8dc26d6493af0eca278eb78dabcea
125
youtube-course-flutter-animations-public
MIT License
compiler/testData/codegen/boxInline/property/augAssignmentAndIncOnExtensionInClass.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
// FILE: 1.kt package test var result = 1 inline var Int.z: Int get() = result set(value) { result = value + this } // FILE: 2.kt import test.* fun box(): String { 1.z += 0 if (result != 2) return "fail 1: $result" var p = 1.z++ if (result != 4) return "fail 2: $result" if (p != 2) return "fail 3: $p" p = ++1.z if (result != 6) return "fail 4: $result" if (p != 6) return "fail 5: $p" return "OK" }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
465
kotlin
Apache License 2.0
compiler/tests-spec/testData/diagnostics/linked/expressions/constant-literals/real-literals/p-4/pos/1.2.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
/* * KOTLIN DIAGNOSTICS SPEC TEST (POSITIVE) * * SPEC VERSION: 0.1-100 * MAIN LINK: expressions, constant-literals, real-literals -> paragraph 4 -> sentence 1 * NUMBER: 2 * DESCRIPTION: Real literals suffixed by f/F (float suffix) with underscores in a whole-number part and a fraction part. */ // TESTCASE NUMBER: 1 val value_1 = 0.0_0f // TESTCASE NUMBER: 2 val value_2 = 0.0__0___0F // TESTCASE NUMBER: 3 val value_3 = 0.0_0__0_0f // TESTCASE NUMBER: 4 val value_4 = 0__0.0F // TESTCASE NUMBER: 5 val value_5 = 0_0_0.0______0f // TESTCASE NUMBER: 6 val value_6 = 00_______________00.0_0_0F // TESTCASE NUMBER: 7 val value_7 = 2_2.0_0F // TESTCASE NUMBER: 8 val value_8 = 33__3.00__0F // TESTCASE NUMBER: 9 val value_9 = 4_44____4.00______00f // TESTCASE NUMBER: 10 val value_10 = 5_________555_________5.0F // TESTCASE NUMBER: 11 val value_11 = 666_666.0_____________________________________________________________________________________________________________________0F // TESTCASE NUMBER: 12 val value_12 = 7777777.0_0_0f // TESTCASE NUMBER: 13 val value_13 = 8888888_8.0000F // TESTCASE NUMBER: 14 val value_14 = 9_______9______9_____9____9___9__9_9.0f // TESTCASE NUMBER: 15 val value_15 = 0_0_0_0_0_0_0_0_0_0.1234567890f // TESTCASE NUMBER: 16 val value_16 = 1_2_3_4_5_6_7_8_9.2_3_4_5_6_7_8_9F // TESTCASE NUMBER: 17 val value_17 = 234_5_678.345______________678F // TESTCASE NUMBER: 18 val value_18 = 3_456_7.4567f // TESTCASE NUMBER: 19 val value_19 = 456.5_6F // TESTCASE NUMBER: 20 val value_20 = 5.6_5f // TESTCASE NUMBER: 21 val value_21 = 6_54.7654F // TESTCASE NUMBER: 22 val value_22 = 7_6543.87654_3F // TESTCASE NUMBER: 23 val value_23 = 876543_____________2.9_____________8765432f // TESTCASE NUMBER: 24 val value_24 = 9_____________87654321.098765432_____________1F // TESTCASE NUMBER: 25 val value_25 = 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000___0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000_0F // TESTCASE NUMBER: 26 val value_26 = <!FLOAT_LITERAL_CONFORMS_ZERO!>0_000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.0___0000000000000000000000000000000000000000000000000000000___0000000000000000000000000000000000000000000000000000000___0000000000000000000000000000000000000000000000000000000000000000000000000000000000000001f<!> // TESTCASE NUMBER: 27 val value_27 = <!FLOAT_LITERAL_CONFORMS_INFINITY!>9999999999999999999999999999999999999999999_______________999999999999999999999999999999999999999999999.33333333333333333333333333333333333333333333333_33333333333333333333333333333333333333333f<!>
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
2,688
kotlin
Apache License 2.0
src/com/nbottarini/asimov/cqbus/identity/AnonymousIdentity.kt
nbottarini
442,759,577
false
{"Kotlin": 17119}
package com.nbottarini.asimov.cqbus.identity class AnonymousIdentity: Identity { override val name = "Anonymous" override val isAuthenticated = false override val authenticationType: String? = null override val roles = listOf<String>() override val properties = mapOf<String, Any>() }
0
Kotlin
0
2
de055fd5d3751f9e53291c74ecc62b44e1ed97a1
306
asimov-cqbus-kt
MIT License
app/src/main/java/com/ivantrogrlic/leaguestats/main/summoner/games/GamesPresenter.kt
ivanTrogrlic
96,999,301
false
null
package com.ivantrogrlic.leaguestats.main.summoner.games import android.content.Context import android.util.Log import com.hannesdorfmann.mosby3.mvp.MvpBasePresenter import com.ivantrogrlic.leaguestats.model.* import com.ivantrogrlic.leaguestats.web.RiotWebService import io.reactivex.Flowable import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.functions.Function3 import io.reactivex.schedulers.Schedulers /** * Created by ivan on 8/9/2017. */ class GamesPresenter(val context: Context, val riotWebService: RiotWebService) : MvpBasePresenter<GamesView>() { fun getRecentMatches(summoner: Summoner) { riotWebService .recentMatches(summoner.accountId) .firstOrError() .map { listOf(it.matches.first()) } .flatMap { toMatches(it, summoner) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ view.setMatches(it) }, { Log.e("GamesPresenter", "Failed loading matches", it) }) } private fun toMatches(matchReferences: List<MatchReference>, summoner: Summoner): Single<List<Match>> = Flowable.fromIterable(matchReferences) .flatMap { riotWebService.match(it.gameId, summoner.accountId) } .map { toMatchWithFilteredSummoner(it, summoner.id) } .flatMap { toMatchWithIconNames(it) } .toList() private fun toMatchWithFilteredSummoner(match: Match, summonerId: Long): Match { val participantId = match.participantIdentities .filter { it.player != null } .first { it.player!!.summonerId == summonerId } .participantId val participant = match.participants.first { it.participantId == participantId } return match.copy(participant = participant) } private fun toMatchWithIconNames(match: Match): Flowable<Match> { val participant = match.participant!! return Flowable.combineLatest( riotWebService.champion(participant.championId), riotWebService.summonerSpell(participant.spell1Id), riotWebService.summonerSpell(participant.spell2Id), Function3<Champion, SummonerSpell, SummonerSpell, Match> { (champion), (summoner1), (summoner2) -> matchWithIconNames(match, participant, champion, summoner1, summoner2) } ) } private fun matchWithIconNames(match: Match, participant: Participant, champion: String, summoner1: String, summoner2: String): Match = match .copy(participants = listOf( participant.copy(championName = champion, spell1Name = summoner1, spell2Name = summoner2))) }
0
Kotlin
0
0
94fa2a8aa93acf0d9746819c20540cf3e2929d93
3,140
LeagueStats
Apache License 2.0
compiler/testData/codegen/bytecodeText/inlineClasses/interfaceJvmDefaultImplStubs.kt
android
263,405,600
true
null
// !LANGUAGE: +InlineClasses // IGNORE_BACKEND: JVM // The JVM backend does not generate the g-impl method, but ends up calling it from box. // !JVM_DEFAULT_MODE: enable // JVM_TARGET: 1.8 // FILE: test.kt fun box(): String { val b = B(0) return b.f() + b.g() } interface A { fun f() = "O" @JvmDefault fun g() = "K" } inline class B(val x: Int) : A // 1 public static f-impl\(I\)Ljava/lang/String; // 1 public f\(\)Ljava/lang/String; // 1 public static g-impl\(I\)Ljava/lang/String; // 0 public g\(\)Ljava/lang/String; // 1 INVOKESTATIC B.g-impl \(I\)Ljava/lang/String; // JVM_TEMPLATES: // 2 INVOKESTATIC B.f-impl \(I\)Ljava/lang/String; // JVM_IR_TEMPLATES: // 1 INVOKESTATIC B.f-impl \(I\)Ljava/lang/String;
34
Kotlin
49
316
74126637a097f5e6b099a7b7a4263468ecfda144
742
kotlin
Apache License 2.0
AdventOfCodeDay18/src/nativeTest/kotlin/BasicTests.kt
bdlepla
451,523,596
false
{"Kotlin": 153773}
import kotlin.test.Test import kotlin.test.assertEquals class BasicTests { @Test fun basicAdditionTest() { val expression = "1 + 2" val actual = evaluateExpression(expression) val expected = 3L assertEquals(expected, actual) } @Test fun basicMultiplicationTest() { val expression = "3 * 6" val actual = evaluateExpression(expression) val expected = 18L assertEquals(expected, actual) } @Test fun moreComplicatedTest() { val expression = "3 + 2 * 6" val actual = evaluateExpression(expression) val expected = 30L assertEquals(expected, actual) } @Test fun sample1Test() { val expression = "1 + 2 * 3 + 4 * 5 + 6" val actual = evaluateExpression(expression) val expected = 71L assertEquals(expected, actual) } @Test fun basicParenthesesTest() { val expression = "(2 + 6)" val actual = evaluateExpression(expression) val expected = 8L assertEquals(expected, actual) } @Test fun moreComplicatedWithParenthesesTest() { val expression = "3 + (2 * 6)" val actual = evaluateExpression(expression) val expected = 15L assertEquals(expected, actual) } @Test fun sample2Test() { val expression = "2 * 3 + (4 * 5)" val actual = evaluateExpression(expression) val expected = 26L assertEquals(expected, actual) } @Test fun sample3Test() { val expression = "5 + (8 * 3 + 9 + 3 * 4 * 3)" val actual = evaluateExpression(expression) val expected = 437L assertEquals(expected, actual) } @Test fun sample4Test() { val expression = "5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))" val actual = evaluateExpression(expression) val expected = 12240L assertEquals(expected, actual) } @Test fun parentheses4Test() { val expression = "(2)" val actual = evaluateExpression(expression) val expected = 2L assertEquals(expected, actual) } @Test fun parentheses5Test() { val expression = "(1 + 1) * (2 + 2)" val actual = evaluateExpression(expression) val expected = 8L assertEquals(expected, actual) } @Test fun parentheses6Test() { val expression = "((1 + 1) * (2 + 2))" val actual = evaluateExpression(expression) val expected = 8L assertEquals(expected, actual) } @Test fun parentheses7Test() { val expression = "((1 + 1) * (2 + 2) + 1)" val actual = evaluateExpression(expression) val expected = 9L assertEquals(expected, actual) } @Test fun sample5Test() { val expression = "((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2" val actual = evaluateExpression(expression) val expected = 13632L assertEquals(expected, actual) } }
0
Kotlin
0
0
043d0cfe3971c83921a489ded3bd45048f02ce83
3,024
AdventOfCode2020
The Unlicense
kotlin-native/runtime/src/main/kotlin/kotlin/Any.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
/* * Copyright 2010-2018 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 kotlin import kotlin.experimental.ExperimentalNativeApi import kotlin.native.identityHashCode import kotlin.native.internal.fullName import kotlin.native.internal.ExportTypeInfo import kotlin.native.internal.GCUnsafeCall /** * The root of the Kotlin class hierarchy. Every Kotlin class has [Any] as a superclass. */ @ExportTypeInfo("theAnyTypeInfo") public open class Any { /** * Indicates whether some other object is "equal to" this one. Implementations must fulfil the following * requirements: * * * Reflexive: for any non-null value `x`, `x.equals(x)` should return true. * * Symmetric: for any non-null values `x` and `y`, `x.equals(y)` should return true if and only if `y.equals(x)` returns true. * * Transitive: for any non-null values `x`, `y`, and `z`, if `x.equals(y)` returns true and `y.equals(z)` returns true, then `x.equals(z)` should return true. * * Consistent: for any non-null values `x` and `y`, multiple invocations of `x.equals(y)` consistently return true or consistently return false, provided no information used in `equals` comparisons on the objects is modified. * * Never equal to null: for any non-null value `x`, `x.equals(null)` should return false. * * Read more about [equality](https://kotlinlang.org/docs/reference/equality.html) in Kotlin. */ public open operator fun equals(other: Any?): Boolean = this === other /** * Returns a hash code value for the object. The general contract of `hashCode` is: * * * Whenever it is invoked on the same object more than once, the `hashCode` method must consistently return the same integer, provided no information used in `equals` comparisons on the object is modified. * * If two objects are equal according to the `equals()` method, then calling the `hashCode` method on each of the two objects must produce the same integer result. */ @OptIn(ExperimentalNativeApi::class) public open fun hashCode(): Int = this.identityHashCode() /** * Returns a string representation of the object. */ public open fun toString(): String { val className = this::class.fullName ?: "<object>" // TODO: consider using [identityHashCode]. val unsignedHashCode = this.hashCode().toLong() and 0xffffffffL val hashCodeStr = unsignedHashCode.toString(16) return "$className@$hashCodeStr" } }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
2,579
kotlin
Apache License 2.0
compiler/testData/diagnostics/tests/regressions/kt11979.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
// FIR_IDENTICAL // !DIAGNOSTICS: -UNUSED_PARAMETER interface Bar<T> { val t: T } class MyBar<T>(override val t: T) : Bar<T> class BarR : Bar<BarR> { override val t: BarR get() = this } class Foo<F : Bar<F>>(val f: F) fun <T> id(t1: T, t2: T) = t2 fun test(foo: Foo<*>, g: Bar<*>) { id(foo.f, g).t.<!UNRESOLVED_REFERENCE!>t<!> } fun main() { val foo = Foo(BarR()) test(foo, MyBar(2)) }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
414
kotlin
Apache License 2.0
codeforces/kotlinheroes3/a.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.kotlinheroes3 import kotlin.math.abs private val options = (0..999).associateWith { "$it" } + (1..999).associate { it * 1000 to "$it" + "K" } + (1..2000).associate { it * 1000_000 to "$it" + "M" } private fun solve() { val n = readInt() println(options.minWithOrNull(compareBy({ abs(it.key - n) }, { -it.key }))!!.value) } fun main() = repeat(readInt()) { solve() } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt()
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
473
competitions
The Unlicense
biometrickit/src/main/java/kz/seidalin/biometrickit/android/BiometricDialog.kt
Sultan1993
253,710,656
false
null
package kz.seidalin.biometrickit.android import android.app.Dialog import android.content.Context import android.view.View import android.view.Window import android.widget.TextView import androidx.core.content.ContextCompat import kz.seidalin.biometrickit.BiometricKit import kz.seidalin.biometrickit.R class BiometricDialog( context: Context, private val authenticationCallback: BiometricKit.AuthenticationCallback ) : Dialog(context, R.style.AlertTheme) { private lateinit var titleLabel: TextView private lateinit var subtitleLabel: TextView private lateinit var negativeButton: TextView private lateinit var descriptionLabel: TextView init { requestWindowFeature(Window.FEATURE_NO_TITLE) setCancelable(false) window?.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.biometric_kit_bg_dialog)) setDialogView() } private fun setDialogView() { val dialogView = layoutInflater.inflate(R.layout.biometric_kit_dialog_fingerprint, null) setContentView(dialogView) titleLabel = findViewById(R.id.titleLabel) subtitleLabel = findViewById(R.id.subtitleLabel) negativeButton = findViewById(R.id.negativeButton) descriptionLabel = findViewById(R.id.descriptionLabel) negativeButton.setOnClickListener { dismiss() authenticationCallback.onAuthenticationCancelled() } } fun setTitle(title: String?) { titleLabel.text = title } fun setSubtitle(subtitle: String?) { subtitleLabel.text = subtitle } fun setNegativeButtonText(negativeButtonText: String?) { negativeButton.text = negativeButtonText } fun setDescriptionText(descriptionText: String? = null) { if (descriptionText == null) { descriptionLabel.visibility = View.GONE } else { descriptionLabel.visibility = View.VISIBLE descriptionLabel.text = descriptionText } } fun setSuccessText(successText: String?) { if (successText != null) { titleLabel.text = successText subtitleLabel.visibility = View.GONE descriptionLabel.visibility = View.GONE negativeButton.visibility = View.GONE } } fun setErrorText(title: String?, subtitle: String?) { if (title != null) { titleLabel.text = title } if (subtitle != null) { subtitleLabel.text = subtitle } } }
0
Kotlin
0
1
157ee1f54f67f7289d8444d8dadbebf057c45885
2,535
Android-BiometricKit
MIT License
attribution/src/test/java/com/affise/attribution/parameters/DeviceTypeProviderTest.kt
affise
496,592,599
false
{"Kotlin": 842366, "JavaScript": 39328, "HTML": 33916}
package com.affise.attribution.parameters import android.app.Application import android.app.UiModeManager import android.content.res.Configuration import android.content.res.Resources import com.affise.attribution.parameters.providers.DeviceTypeProvider import com.google.common.truth.Truth import io.mockk.every import io.mockk.mockk import io.mockk.verifyAll import org.junit.Test /** * Test for [DeviceTypeProvider] */ class DeviceTypeProviderTest { @Test fun `provider returns tv if UiModeManager configuration is television`() { val app: Application = mockk() val provider = DeviceTypeProvider(app) val uiModeManager: UiModeManager = mockk { every { currentModeType } returns Configuration.UI_MODE_TYPE_TELEVISION } every { app.getSystemService(SYSTEM_SERVICE) } returns uiModeManager val actual = provider.provide() Truth.assertThat(actual).isEqualTo(TYPE_TV) verifyAll { app.getSystemService(SYSTEM_SERVICE) uiModeManager.currentModeType } } @Test fun `provider returns car if UiModeManager configuration is car`() { val app: Application = mockk() val provider = DeviceTypeProvider(app) val uiModeManager: UiModeManager = mockk { every { currentModeType } returns Configuration.UI_MODE_TYPE_CAR } every { app.getSystemService(SYSTEM_SERVICE) } returns uiModeManager val actual = provider.provide() Truth.assertThat(actual).isEqualTo(TYPE_CAR) verifyAll { app.getSystemService(SYSTEM_SERVICE) uiModeManager.currentModeType } } @Test fun `provider returns phone if UiModeManager is not present and screen size is SMALL`() { `test device type provider when UiModeManager is not present`( size = Configuration.SCREENLAYOUT_SIZE_SMALL, expectedType = TYPE_SMART ) } @Test fun `provider returns tablet if UiModeManager is not present and screen size is LARGE`() { `test device type provider when UiModeManager is not present`( size = Configuration.SCREENLAYOUT_SIZE_LARGE, expectedType = TYPE_TABLET ) } @Test fun `provider returns tablet if UiModeManager is not present and screen size is XLARGE`() { `test device type provider when UiModeManager is not present`( size = Configuration.SCREENLAYOUT_SIZE_XLARGE, expectedType = TYPE_TABLET ) } @Test fun `provider returns phone if UiModeManager is not present and screen size is NORMAL`() { `test device type provider when UiModeManager is not present`( size = Configuration.SCREENLAYOUT_SIZE_NORMAL, expectedType = TYPE_SMART ) } @Test fun `provider returns phone if UiModeManager is not present and screen size is UNDEFINED`() { `test device type provider when UiModeManager is not present`( size = Configuration.SCREENLAYOUT_SIZE_UNDEFINED, expectedType = TYPE_SMART ) } private fun `test device type provider when UiModeManager is not present`(size: Int, expectedType: String) { val app: Application = mockk() val provider = DeviceTypeProvider(app) every { app.getSystemService(SYSTEM_SERVICE) } returns null val configurationMock: Configuration = Configuration().apply { screenLayout = size } val resources: Resources = mockk { every { configuration } returns configurationMock } every { app.resources } returns resources val actual = provider.provide() Truth.assertThat(actual).isEqualTo(expectedType) verifyAll { app.getSystemService(SYSTEM_SERVICE) app.resources resources.configuration } } companion object { const val SYSTEM_SERVICE = "uimode" const val TYPE_SMART = "smartphone" const val TYPE_TABLET = "tablet" const val TYPE_TV = "tv" const val TYPE_CAR = "car" } }
0
Kotlin
0
3
e7769e4c97d08448383eeeb2b9772bc57a7a5f20
4,327
sdk-android
MIT License
app/src/main/java/com/github/miwu/miot/widget/Button.kt
sky130
680,024,437
false
{"Kotlin": 269572}
package com.github.miwu.miot.widget import android.content.Context import android.util.AttributeSet import android.view.View import com.github.miwu.R import com.github.miwu.databinding.MiotWidgetButtonBinding import com.github.miwu.databinding.MiotWidgetSwitchBinding import kndroidx.extension.compareTo class Button(context: Context) : MiotBaseWidget<MiotWidgetButtonBinding>(context) { private val action get() = actions.first() override fun init() { binding.title <= action.second.description setOnClickListener { doAction(action.first, action.second.iid) } } override fun onValueChange(value: Any) = Unit }
0
Kotlin
15
46
144dbfeac58f64ab286d7376e82ff3e2cff25d56
669
MiWu
MIT License
dots/src/main/java/com/geermank/dots/loading/DotLoadingsFactoryMapper.kt
geermank
393,248,312
false
null
package com.geermank.dots.loading import com.geermank.dots.loading.bouncing.BouncingModifierFactory import com.geermank.dots.loading.circular.CircularProgressModifiersFactory import com.geermank.dots.loading.flip.FlipModifierFactory import com.geermank.dots.loading.linear.LinearModifierFactory import com.geermank.dots.loading.orbit.OrbitModifiersFactory import com.geermank.dots.loading.scale.ScaleModifierFactory import com.geermank.dots.loading.tiktok.TikTokModifiersFactory object DotLoadingsFactoryMapper { private val modifierFactoriesMap = mapOf( Pair(DotLoadingTypes.CIRCULAR, CircularProgressModifiersFactory()), Pair(DotLoadingTypes.ORBIT, OrbitModifiersFactory()), Pair(DotLoadingTypes.LINEAR, LinearModifierFactory()), Pair(DotLoadingTypes.BOUNCE, BouncingModifierFactory()), Pair(DotLoadingTypes.TIK_TOK, TikTokModifiersFactory()), Pair(DotLoadingTypes.FLIP, FlipModifierFactory()), Pair(DotLoadingTypes.SCALE, ScaleModifierFactory()) ) internal fun getByIndex(@DotLoadingTypes index: Int): DotsModifiersFactory { return modifierFactoriesMap.getOrElse(index) { DotsModifiersFactory.DEFAULT } } }
0
Kotlin
0
0
445ec49977fd705137bd5bbde5b03006b6e7bb60
1,194
dots-loading
Apache License 2.0
app/src/main/java/com/banuba/example/videoeditor/BanubaVideoEditorSDK.kt
Banuba
469,703,303
false
null
package com.banuba.example.videoeditor import android.app.Application import android.graphics.Bitmap import android.graphics.BitmapFactory import com.banuba.example.videoeditor.editor.EditorViewModel import com.banuba.example.videoeditor.export.CustomExportParamsProvider import com.banuba.example.videoeditor.export.ExportViewModel import com.banuba.example.videoeditor.playback.PlaybackViewModel import com.banuba.example.videoeditor.utils.CustomPublishManager import com.banuba.example.videoeditor.utils.StubImageLoader import com.banuba.sdk.core.domain.ImageLoader import com.banuba.sdk.export.data.* import com.banuba.sdk.export.di.VeExportKoinModule import com.banuba.sdk.playback.di.VePlaybackSdkKoinModule import com.banuba.sdk.token.storage.di.TokenStorageKoinModule import com.banuba.sdk.ve.di.VeSdkKoinModule import com.banuba.sdk.ve.effects.watermark.WatermarkProvider import com.banuba.sdk.ve.media.VideoGalleryResourceValidator import kotlinx.coroutines.Dispatchers import org.koin.android.ext.koin.androidApplication import org.koin.android.ext.koin.androidContext import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.core.context.startKoin import org.koin.core.qualifier.named import org.koin.dsl.module class BanubaVideoEditorSDK { fun initialize(application: Application) { startKoin { androidContext(application) allowOverride(true) modules( VeSdkKoinModule().module, VeExportKoinModule().module, VePlaybackSdkKoinModule().module, TokenStorageKoinModule().module, VideoEditorApiModule().module ) } } } private class VideoEditorApiModule { val module = module { viewModel { EditorViewModel( appContext = androidApplication(), videoValidator = VideoGalleryResourceValidator( context = androidContext() ), videoPlayer = get(), exportFlowManager = get(), aspectRatioProvider = get() ) } viewModel { ExportViewModel( appContext = androidApplication(), backgroundExportFlowManager = get(named("backgroundExportFlowManager")), foregroundExportFlowManager = get(named("foregroundExportFlowManager")), aspectRatioProvider = get(), exportDir = get(named("exportDir")), mediaFileNameHelper = get() ) } viewModel { PlaybackViewModel( context = androidContext(), videoValidator = VideoGalleryResourceValidator( context = androidContext() ), videoPlayer = get() ) } single<ExportFlowManager> { ForegroundExportFlowManager( exportDataProvider = get(), sessionParamsProvider = get(), exportSessionHelper = get(), exportDir = get(named("exportDir")), publishManager = get(), errorParser = get(), mediaFileNameHelper = get(), exportBundleProvider = get() ) } factory<ExportParamsProvider> { CustomExportParamsProvider( exportDir = get(named("exportDir")), mediaFileNameHelper = get(), watermarkBuilder = get() ) } single<WatermarkProvider> { object : WatermarkProvider { override fun getWatermarkBitmap(): Bitmap? = BitmapFactory.decodeResource( androidContext().resources, com.banuba.sdk.ve.R.drawable.df_fsfw ) } } single<PublishManager> { CustomPublishManager( context = androidContext(), albumName = "Banuba Video Editor", mediaFileNameHelper = get(), dispatcher = Dispatchers.IO ) } single<ImageLoader> { StubImageLoader() } /** * Override to run export in foreground mode. */ single<ExportFlowManager>(named("foregroundExportFlowManager")) { ForegroundExportFlowManager( exportDataProvider = get(), sessionParamsProvider = get(), exportSessionHelper = get(), exportDir = get(named("exportDir")), publishManager = get(), errorParser = get(), mediaFileNameHelper = get(), exportBundleProvider = get() ) } /** * Override to run export in background mode. */ single<ExportFlowManager>(named("backgroundExportFlowManager")) { BackgroundExportFlowManager( exportDataProvider = get(), sessionParamsProvider = get(), exportSessionHelper = get(), exportNotificationManager = get(), exportDir = get(named("exportDir")), publishManager = get(), errorParser = get(), exportBundleProvider = get() ) } } }
0
Kotlin
2
0
c04bd3b1cbf4ebbcab7b5bf1ca8a16d199031e1a
5,388
ve-api-android-integration-sample
Open Market License
src/main/kotlin/com/fpwag/admin/infrastructure/mybatis/base/DataEntity.kt
FlowersPlants
286,647,008
false
null
package com.fpwag.admin.infrastructure.mybatis.base import com.baomidou.mybatisplus.annotation.FieldFill import com.baomidou.mybatisplus.annotation.TableField import com.fpwag.admin.infrastructure.CommonConstant import com.fpwag.admin.infrastructure.mybatis.base.BaseEntity import java.time.LocalDateTime /** * 包含此业务中必须的字段信息 * * @author fpwag */ abstract class DataEntity : BaseEntity() { companion object { private const val serialVersionUID = CommonConstant.SERIAL_VERSION } /** * 状态,1-启用,0-禁用 */ var status: Boolean? = null /** * 排序号 */ var sort: Int? = null var remarks: String? = null @TableField(fill = FieldFill.UPDATE) var updateTime: LocalDateTime? = null @TableField(fill = FieldFill.UPDATE) var updateBy: String? = null }
0
Kotlin
0
3
dae83eb311a3d23da5b1d65d3196d7ffdd5229ce
863
fp-admin
Apache License 2.0
feature/authorization/dependencies/src/commonMain/kotlin/io/timemates/app/authorization/dependencies/screens/InitialAuthorizationModule.kt
timemates
575,537,317
false
{"Kotlin": 345380}
package io.timemates.app.authorization.dependencies.screens import io.timemates.app.authorization.ui.initial_authorization.mvi.InitialAuthorizationReducer import io.timemates.app.authorization.ui.initial_authorization.mvi.InitialAuthorizationStateMachine import org.koin.core.annotation.Factory import org.koin.core.annotation.Module @Module class InitialAuthorizationModule { @Factory fun stateMachine(): InitialAuthorizationStateMachine { return InitialAuthorizationStateMachine( reducer = InitialAuthorizationReducer() ) } }
20
Kotlin
0
22
9ac818cd982773efc399fe8149a1b4a0f631c554
569
app
MIT License
extensions/fullscreenfragment/src/main/java/com/michaelflisar/dialogs/MaterialFullscreenDialogFragment.kt
MFlisar
533,172,718
false
{"Kotlin": 446157}
package com.michaelflisar.dialogs import android.content.Context import android.content.DialogInterface import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatDialogFragment import androidx.viewbinding.ViewBinding import com.michaelflisar.dialogs.interfaces.IMaterialDialogEvent class MaterialFullscreenDialogFragment<S : MaterialDialogSetup<S>> : AppCompatDialogFragment() { companion object { const val ARG_SETUP = "MaterialFullscreenDialogFragment|SETUP" const val ARG_STYLE = "MaterialFullscreenDialogFragment|STYLE" fun <S : MaterialDialogSetup<S>> create( setup: S, style: FullscreenDialogStyle ): MaterialFullscreenDialogFragment<S> { return MaterialFullscreenDialogFragment<S>().apply { val args = Bundle() args.putParcelable(ARG_SETUP, setup) args.putParcelable(ARG_STYLE, style) arguments = args } } } private lateinit var presenter: FullscreenFragmentPresenter<S> // ------------------ // Fragment // ------------------ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) presenter = FullscreenFragmentPresenter(requireArguments().getParcelable(ARG_SETUP)!!, requireArguments().getParcelable( ARG_STYLE)!!,this) presenter.onCreate(savedInstanceState, requireActivity(), parentFragment) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return presenter.onCreateView(inflater, container, savedInstanceState) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { presenter.onViewCreated(view, savedInstanceState) } override fun onStart() { super.onStart() presenter.onStart() } override fun onResume() { super.onResume() MaterialDialogUtil.interceptDialogBackPress(dialog!!) { presenter.onBackPress() } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) presenter.saveViewState(outState) } override fun onDestroy() { presenter.onDestroy() super.onDestroy() } override fun dismiss() { if (presenter.onBeforeDismiss(false)) super.dismiss() } override fun dismissAllowingStateLoss() { if (presenter.onBeforeDismiss(true)) super.dismiss() } override fun onCancel(dialog: DialogInterface) { super.onCancel(dialog) presenter.onCancelled() } }
3
Kotlin
1
9
43fc1279039933c0943ea7f4c3516358cfaeccae
2,798
MaterialDialogs
Apache License 2.0
app/src/main/java/com/feduss/tomato/hilt/DataModule.kt
feduss
575,630,166
false
{"Kotlin": 84105}
package com.feduss.tomato.hilt import com.feduss.tomatimer.business.TimerInteractor import com.feduss.tomatimer.business.TimerInteractorImpl import com.feduss.tomatimer.data.TimerRepository import com.feduss.tomatimer.data.TimerRepositoryImpl import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton //Binds the interface with its implementation @Module @InstallIn(SingletonComponent::class) abstract class DataModule { @Singleton @Binds abstract fun bindTimerRepository( timerRepositoryImpl: TimerRepositoryImpl ): TimerRepository @Binds abstract fun bindTimerInteractor( timerInteractorImpl: TimerInteractorImpl ): TimerInteractor }
1
Kotlin
0
3
8a30b9b3ff6e32280a9d4fbcad9941fa549b84db
774
Tomatimer
MIT License
app/src/main/java/ru/alexmaryin/spacextimes_rx/data/api/local/ApiLocalImpl.kt
alexmaryin
324,776,487
false
null
package ru.alexmaryin.spacextimes_rx.data.api.local import ru.alexmaryin.spacextimes_rx.data.api.local.spacex.SpaceXFlightsDao import ru.alexmaryin.spacextimes_rx.data.model.* import javax.inject.Inject class ApiLocalImpl @Inject constructor( private val spaceXDao: SpaceXFlightsDao, ) : ApiLocal { override suspend fun getCapsules(): List<Capsule> = spaceXDao.selectAllCapsules().map { it.toResponse() } override suspend fun saveCapsules(capsules: List<Capsule>) = with(spaceXDao) { clearCapsules() clearLaunchesToCapsules() insertCapsuleWithLaunches(capsules) } override suspend fun saveCapsuleDetails(capsule: Capsule) = spaceXDao.insertCapsuleWithLaunches(capsule) override suspend fun getCapsuleById(id: String): Capsule? = spaceXDao.selectCapsule(id)?.toResponse() override suspend fun getCores(): List<Core> = spaceXDao.selectAllCores().map { it.toResponse() } override suspend fun getCoreById(id: String): Core? = spaceXDao.selectCore(id)?.toResponse() override suspend fun saveCores(cores: List<Core>) = with(spaceXDao) { clearCores() clearLaunchesToCores() insertCoresWithLaunches(cores) } override suspend fun saveCoreDetails(core: Core) = spaceXDao.insertCoreWithLaunches(core) override suspend fun getCrew(): List<Crew> = spaceXDao.selectAllCrew().map { it.toResponse() } override suspend fun getCrewById(id: String): Crew? = spaceXDao.selectCrewMember(id)?.toResponse() override suspend fun saveCrew(crew: List<Crew>) = with(spaceXDao) { clearCrew() clearLaunchesToCrew() insertCrewWithLaunches(crew) } override suspend fun saveCrewDetails(member: Crew) = spaceXDao.insertCrewWithLaunches(member) override suspend fun getDragons(): List<Dragon> = spaceXDao.selectAllDragons().map { it.toResponse() } override suspend fun getDragonById(id: String): Dragon? = spaceXDao.selectDragon(id)?.toResponse() override suspend fun saveDragons(dragons: List<Dragon>) = with(spaceXDao) { clearDragons() insertDragons(dragons.map { it.toRoom() }) } override suspend fun getLaunchPads(): List<LaunchPad> = spaceXDao.selectAllLaunchPads().map { it.toResponse() } override suspend fun getLaunchPadById(id: String): LaunchPad? = spaceXDao.selectLaunchPad(id)?.toResponse() override suspend fun saveLaunchPads(pads: List<LaunchPad>) = with(spaceXDao) { clearLaunchPads() insertLaunchPads(pads.map { it.toRoom() }) } override suspend fun getLandingPads(): List<LandingPad> = spaceXDao.selectAllLandingPads().map { it.toResponse() } override suspend fun getLandingPadById(id: String): LandingPad? = spaceXDao.selectLandingPad(id)?.toResponse() override suspend fun saveLandingPads(pads: List<LandingPad>) = with(spaceXDao) { clearLandingPads() clearLaunchesToLandingPads() insertLandingPadsWithLaunches(pads) } override suspend fun getRockets(): List<Rocket> = spaceXDao.selectAllRockets().map { it.toResponse() } override suspend fun getRocketById(id: String): Rocket? = spaceXDao.selectRocket(id)?.toResponse() override suspend fun saveRockets(rockets: List<Rocket>) = with(spaceXDao) { clearRockets() insertRockets(rockets.map { it.toRoom() }) } override suspend fun getLaunches(): List<Launch> = spaceXDao.selectLaunchesForList().map { it.toResponse() } override suspend fun getLaunchById(id: String): Launch? = spaceXDao.selectLaunch(id)?.toResponse( crewFlightSelect = { crewId, launchId -> spaceXDao.selectCrewFlight(crewId, launchId)?.toResponse() }, coreSelect = { coreId, launchId -> spaceXDao.selectCoreFlight(coreId, launchId)?.toResponse() }) override suspend fun saveLaunches(launches: List<Launch>) = with(spaceXDao) { clearJunctions() clearLaunches() insertLaunchesWithDetails(launches) } override suspend fun saveLaunchDetails(launch: Launch) = with(spaceXDao) { clearJunctionsForLaunch(launch) insertLaunchWithDetails(launch) } override suspend fun getPayloadById(id: String): Payload? = spaceXDao.selectPayload(id)?.toResponse() override suspend fun savePayload(payload: Payload) = spaceXDao.insertPayload(payload.toRoom().payload) override suspend fun getHistoryEvents(): List<History> = spaceXDao.selectAllHistoryEvents().map { it.toResponse() } override suspend fun saveHistoryEvents(events: List<History>) = with(spaceXDao) { clearHistoryEvents() insertHistoryEvents(events.map { it.toRoom() }) } override suspend fun dropLocalData() = spaceXDao.clearDatabase() }
1
Kotlin
1
1
79cdb2ffab470ef4e951af811585d3dd3000fbb6
4,747
spacextimes
Apache License 2.0
src/main/kotlin/dk/lessor/Day14.kt
aoc-team-1
317,571,356
false
{"Java": 70687, "Kotlin": 34171}
package dk.lessor typealias Manipulator = (Long, Long, String, MutableMap<Long, Long>) -> Unit fun main() { val lines = readFile("day_14.txt") println(decodeBitMask(lines, valueDecoder)) println(decodeBitMask(lines, memoryDecoder)) } val valueDecoder: Manipulator = { pos, value, mask, memory -> memory[pos] = value.applyMask(mask) } val memoryDecoder: Manipulator = { pos, value, mask, memory -> pos.floatingMask(mask).forEach { memory[it] = value } } fun decodeBitMask(lines: List<String>, manipulator: Manipulator): Long { var mask = "" val memory = mutableMapOf<Long, Long>() val memPattern = "mem\\[(\\d+)]".toRegex() for (line in lines) { if (line.startsWith("mask")) { mask = line.split(" = ").last() continue } val (mem, value) = line.split(" = ") val pos = memPattern.find(mem)!!.groupValues[1].toLong() manipulator(pos, value.toLong(), mask, memory) } return memory.values.sum() } fun Long.applyMask(mask: String): Long { val original = toString(2).padStart(mask.length, '0') val masked = mask.mapIndexed { i, bit -> if (bit == 'X') original[i] else bit }.joinToString("") return masked.toLong(2) } fun Long.floatingMask(mask: String): List<Long> { val original = toString(2).padStart(mask.length, '0') val result = mutableListOf(mutableListOf<Char>()) for (i in 0..mask.lastIndex) { when (mask[i]) { '0' -> result.forEach { it.add(original[i]) } '1' -> result.forEach { it.add('1') } else -> { val copy = result.map { it.toMutableList() } copy.forEach { it.add('1') } result.forEach { it.add('0') } result.addAll(copy) } } } return result.map { it.joinToString("").toLong(2) } }
0
Java
0
0
48ea750b60a6a2a92f9048c04971b1dc340780d5
1,862
lessor-aoc-comp-2020
MIT License
settings.gradle.kts
orangain
264,615,536
false
null
rootProject.name = "cloud-run-after-request"
0
Kotlin
0
0
49606d63bcbd0be40e3ae64f549631668a225fe7
45
cloud-run-after-request
MIT License
android/app/src/main/java/org/haobtc/onekey/business/blockBrowser/BlockBrowserEthRopsten.kt
peterQin0826
345,008,092
true
{"Python": 5633103, "Java": 3611625, "Objective-C": 1305239, "Kotlin": 273062, "Swift": 148247, "C": 112074, "Shell": 75462, "Objective-C++": 39183, "HTML": 18212, "Dockerfile": 10616, "NSIS": 7342, "C++": 4476, "JavaScript": 2732, "Makefile": 969, "Ruby": 944}
package org.haobtc.onekey.business.blockBrowser fun getBlockBrowserEthRopsten(): Map<String, BlockBrowserEthRopsten> { return arrayListOf( BlockBrowserEthRopsten.BitAps(), BlockBrowserEthRopsten.EtherScan(), BlockBrowserEthRopsten.BlockExplorer(), BlockBrowserEthRopsten.AnyBlock(), ).associateBy { it.uniqueTag() } } abstract class BlockBrowserEthRopsten(val url: String) : ETHBlockBrowser { override fun showName() = url() override fun url() = url override fun uniqueTag() = "${blockBrowserTag()}ETHRopsten" override fun browseContractAddressUrl(contractAddress: String, address: String) = browseAddressUrl(address) abstract fun blockBrowserTag(): String class BitAps : BlockBrowserEthRopsten("https://teth.bitaps.com/") { override fun browseAddressUrl(address: String) = "${url()}$address" override fun browseTransactionDetailsUrl(txHash: String) = "${url()}$txHash" override fun browseBlockUrl(block: String) = "${url()}$block" override fun blockBrowserTag() = "BitAps" override fun uniqueTag() = BlockBrowserManager.BLOCK_BROWSER_DEFAULT } class EtherScan : BlockBrowserEthRopsten("https://ropsten.etherscan.io/") { override fun browseAddressUrl(address: String) = "${url()}address/$address" override fun browseTransactionDetailsUrl(txHash: String) = "${url()}tx/$txHash" override fun browseBlockUrl(block: String) = "${url()}block/$block" override fun browseContractAddressUrl(contractAddress: String, address: String) = "${url()}token/$contractAddress?a=$address" override fun blockBrowserTag() = "EtherScan" } class BlockExplorer : BlockBrowserEthRopsten("https://blockexplorer.one/") { override fun browseAddressUrl(address: String) = "${url()}eth/ropsten/address/$address" override fun browseTransactionDetailsUrl(txHash: String) = "${url()}eth/ropsten/tx/$txHash" override fun browseBlockUrl(block: String) = "${url()}eth/ropsten/blockId/$block" override fun blockBrowserTag() = "BlockExplorer" } class AnyBlock : BlockBrowserEthRopsten("https://explorer.anyblock.tools/") { override fun browseAddressUrl(address: String) = "${url()}ethereum/ethereum/ropsten/address/$address" override fun browseTransactionDetailsUrl(txHash: String) = "${url()}ethereum/ethereum/ropsten/transaction/$txHash" override fun browseBlockUrl(block: String) = "${url()}ethereum/ethereum/ropsten/block/$block" override fun blockBrowserTag() = "AnyBlock" } }
8
Python
1
0
9e822640680c20c69a69695c033e97605aafcdce
2,477
electrum
MIT License
crowdin/src/test/java/com/crowdin/platform/SharedPrefLocalRepositoryTest.kt
crowdin
193,449,073
false
{"Kotlin": 445553, "MDX": 29879, "Java": 4715, "JavaScript": 3816, "CSS": 1107}
package com.crowdin.platform import android.content.Context import android.content.SharedPreferences import com.crowdin.platform.data.local.MemoryLocalRepository import com.crowdin.platform.data.local.SharedPrefLocalRepository import com.crowdin.platform.data.model.ArrayData import com.crowdin.platform.data.model.LanguageData import com.crowdin.platform.data.model.PluralData import com.crowdin.platform.data.model.StringData import com.google.gson.Gson import org.hamcrest.CoreMatchers.`is` import org.hamcrest.CoreMatchers.instanceOf import org.hamcrest.CoreMatchers.nullValue import org.hamcrest.MatcherAssert.assertThat import org.junit.Before import org.junit.Test import org.mockito.ArgumentMatchers.anyInt import org.mockito.ArgumentMatchers.anyString import org.mockito.Mockito.`when` import org.mockito.Mockito.mock import org.mockito.Mockito.verify class SharedPrefLocalRepositoryTest { private lateinit var mockMemoryLocalRepository: MemoryLocalRepository private lateinit var sharedPrefs: SharedPreferences private lateinit var editor: SharedPreferences.Editor private lateinit var context: Context @Before fun setUp() { sharedPrefs = mock(SharedPreferences::class.java) editor = mock(SharedPreferences.Editor::class.java) `when`(sharedPrefs.edit()).thenReturn(editor) `when`(editor.putString(any(), any())).thenReturn(editor) `when`(editor.remove(any())).thenReturn(editor) context = mock(Context::class.java) `when`(context.getSharedPreferences(anyString(), anyInt())).thenReturn(sharedPrefs) mockMemoryLocalRepository = mock(MemoryLocalRepository::class.java) } @Test fun saveLanguageDataTest() { // Given val sharedPrefLocalRepository = SharedPrefLocalRepository(context, MemoryLocalRepository()) val expectedLanguage = "EN" val languageData = LanguageData(expectedLanguage) val expectedJson = Gson().toJson(languageData) // When sharedPrefLocalRepository.saveLanguageData(languageData) // Then verify(sharedPrefs).edit() verify(editor).putString(expectedLanguage, expectedJson) } @Test fun setStringTest() { // Given val sharedPrefLocalRepository = SharedPrefLocalRepository(context, MemoryLocalRepository()) val key = "key" val value = "value" val languageData = LanguageData("EN") languageData.resources.add(StringData(key, value)) val expectedJson = Gson().toJson(languageData) val expectedLanguage = "EN" // When sharedPrefLocalRepository.setString("EN", key, value) // Then verify(sharedPrefs).edit() verify(editor).putString(expectedLanguage, expectedJson) } @Test fun setStringDataTest() { // Given val sharedPrefLocalRepository = SharedPrefLocalRepository(context, MemoryLocalRepository()) val stringData = StringData("key", "value") val languageData = LanguageData("EN") languageData.resources.add(stringData) val expectedJson = Gson().toJson(languageData) val expectedLanguage = "EN" // When sharedPrefLocalRepository.setStringData("EN", stringData) // Then verify(sharedPrefs).edit() verify(editor).putString(expectedLanguage, expectedJson) } @Test fun setArrayDataTest() { // Given val sharedPrefLocalRepository = SharedPrefLocalRepository(context, MemoryLocalRepository()) val arrayData = ArrayData("key", arrayOf("test", "test1")) val languageData = LanguageData("EN") languageData.arrays.add(arrayData) val expectedJson = Gson().toJson(languageData) val expectedLanguage = "EN" // When sharedPrefLocalRepository.setArrayData("EN", arrayData) // Then verify(sharedPrefs).edit() verify(editor).putString(expectedLanguage, expectedJson) } @Test fun setPluralDataTest() { // Given val sharedPrefLocalRepository = SharedPrefLocalRepository(context, MemoryLocalRepository()) val pluralData = PluralData("key", mutableMapOf(Pair("test", "test1"))) val languageData = LanguageData("EN") languageData.plurals.add(pluralData) val expectedJson = Gson().toJson(languageData) val expectedLanguage = "EN" // When sharedPrefLocalRepository.setPluralData("EN", pluralData) // Then verify(sharedPrefs).edit() verify(editor).putString(expectedLanguage, expectedJson) } @Test fun getStringTest() { // Given val sharedPrefLocalRepository = SharedPrefLocalRepository(context, mockMemoryLocalRepository) val expectedLanguage = "EN" val expectedKey = "key" // When sharedPrefLocalRepository.getString("EN", expectedKey) // Then verify(mockMemoryLocalRepository).getString(expectedLanguage, expectedKey) } @Test fun getLanguageDataTest() { // Given val sharedPrefLocalRepository = SharedPrefLocalRepository(context, mockMemoryLocalRepository) val expectedLanguage = "EN" // When sharedPrefLocalRepository.getLanguageData("EN") // Then verify(mockMemoryLocalRepository).getLanguageData(expectedLanguage) } @Test fun getStringArrayTest() { // Given val sharedPrefLocalRepository = SharedPrefLocalRepository(context, mockMemoryLocalRepository) val expectedKey = "key" // When sharedPrefLocalRepository.getStringArray("key") // Then verify(mockMemoryLocalRepository).getStringArray(expectedKey) } @Test fun getStringPluralTest() { // Given val sharedPrefLocalRepository = SharedPrefLocalRepository(context, mockMemoryLocalRepository) val expectedResourceKey = "resourceKey" val expectedQuantityKey = "quantityKey" // When sharedPrefLocalRepository.getStringPlural("resourceKey", "quantityKey") // Then verify(mockMemoryLocalRepository).getStringPlural(expectedResourceKey, expectedQuantityKey) } @Test fun isExistTest() { // Given val sharedPrefLocalRepository = SharedPrefLocalRepository(context, mockMemoryLocalRepository) val expectedLanguage = "EN" // When sharedPrefLocalRepository.isExist("EN") // Then verify(mockMemoryLocalRepository).isExist(expectedLanguage) } @Test fun containsKeyTest() { // Given val sharedPrefLocalRepository = SharedPrefLocalRepository(context, mockMemoryLocalRepository) // When sharedPrefLocalRepository.containsKey("key") // Then verify(mockMemoryLocalRepository).containsKey("key") } @Test fun getTextDataTest() { // Given val sharedPrefLocalRepository = SharedPrefLocalRepository(context, mockMemoryLocalRepository) val expectedText = "text" // When sharedPrefLocalRepository.getTextData("text") // Then verify(mockMemoryLocalRepository).getTextData(expectedText) } @Test fun saveDataTest() { // Given val sharedPrefLocalRepository = SharedPrefLocalRepository(context, mockMemoryLocalRepository) val expectedType = "type" val data = StringData() // When sharedPrefLocalRepository.saveData("type", data) // Then verify(mockMemoryLocalRepository).saveData(expectedType, data) } @Test fun saveData_removeOldTest() { // Given val sharedPrefLocalRepository = SharedPrefLocalRepository(context, mockMemoryLocalRepository) val expectedType = "type" val data = null // When sharedPrefLocalRepository.saveData("type", data) // Then verify(sharedPrefs).edit() verify(editor).remove(expectedType) } @Test fun getDataTest() { // Given val stringData = StringData() `when`(mockMemoryLocalRepository.getData<StringData>(any(), any())).thenReturn(stringData) val sharedPrefLocalRepository = SharedPrefLocalRepository(context, mockMemoryLocalRepository) // When val result = sharedPrefLocalRepository.getData<StringData>("stringData", StringData::class.java) // Then assertThat(result, instanceOf(StringData::class.java)) assertThat((result as StringData), `is`(stringData)) } @Test fun getData_nullDataTest() { // Given val stringData = null `when`(mockMemoryLocalRepository.getData<StringData>(any(), any())).thenReturn(stringData) `when`(sharedPrefs.getString(any(), any())).thenReturn(null) val sharedPrefLocalRepository = SharedPrefLocalRepository(context, mockMemoryLocalRepository) val expectedType = "stringData" // When val result = sharedPrefLocalRepository.getData<StringData>("stringData", StringData::class.java) // Then verify(sharedPrefs).getString(expectedType, null) assertThat(result, nullValue()) } }
2
Kotlin
40
104
02e10bde2b2301869b106a44a6a589d470528b31
9,407
mobile-sdk-android
MIT License
src/main/kotlin/com/iskcon/japa/storage/ChatEventEntity.kt
SamoshkinR-Tem
736,922,600
false
{"Kotlin": 14374}
package com.iskcon.japa.storage import java.time.LocalDateTime data class ChatEventEntity( val chatId: Long = 0, val action: String = "", val isChantingNow: Boolean? = null, val timestamp: LocalDateTime = LocalDateTime.now(), )
0
Kotlin
0
0
db0ccebc2fc82be7eee90858dbbaba729be1b492
246
iskcon-realtime-japa
Apache License 2.0
src/main/kotlin/by/mrpetchenka/flanscore/common/network/packets/dummy/DamageMessage.kt
PeTcHeNkA
506,586,519
false
null
package by.mrpetchenka.flanscore.common.network.packets.dummy import by.mrpetchenka.flanscore.common.entity.dummy.EntityFloatingNumber import by.mrpetchenka.flanscore.common.network.PacketBase import io.netty.buffer.ByteBuf import io.netty.channel.ChannelHandlerContext import net.minecraft.client.Minecraft import net.minecraft.entity.Entity import net.minecraft.entity.player.EntityPlayer import net.minecraft.entity.player.EntityPlayerMP class DamageMessage(private var damage: Float? = null, efn: EntityFloatingNumber? = null) : PacketBase() { private var nrID = 0; constructor(damage: Float, efn: EntityFloatingNumber) : this() { this.damage = damage this.nrID = efn.entityId } override fun encodeInto(ctx: ChannelHandlerContext, data: ByteBuf) { data.writeFloat(damage!!) data.writeInt(nrID) } override fun decodeInto(ctx: ChannelHandlerContext, data: ByteBuf) { damage = data.readFloat() nrID = data.readInt() } override fun handleServerSide(playerEntity: EntityPlayerMP) {} override fun handleClientSide(clientPlayer: EntityPlayer) { val entity: Entity? = Minecraft.getMinecraft().theWorld.getEntityByID(nrID) if (entity is EntityFloatingNumber) { entity.reSet(damage!!) } } }
0
Kotlin
0
0
f4f5eef2db6631e3ba6adbaa4e6d5a36391798e2
1,315
FlansCore
MIT License
core/src/commonMain/kotlin/com/github/mejiomah17/yasb/core/SupportsFullJoin.kt
MEJIOMAH17
492,593,605
false
{"Kotlin": 282541}
package com.github.mejiomah17.yasb.core /** * Marker interface is database supports statements like * SELECT column_name(s) * FROM table1 * FULL OUTER JOIN table2 * ON table1.column_name = table2.column_name * WHERE condition; */ interface SupportsFullJoin
0
Kotlin
0
1
9c362916380cb80ded2d8cf2d8b1ec03b34461b7
265
yasb
MIT License
build.gradle.kts
floweryclover
738,147,785
false
{"Kotlin": 5765}
// Top-level build file where you can add configuration options common to all sub-projects/modules. plugins { id("com.android.application") version "8.0.2" apply false id("org.jetbrains.kotlin.android") version "2.0.0-Beta2" apply false }
1
Kotlin
0
0
974b14a2395eee886fe7dc0182f457a586c22f42
246
direct-call
MIT License
src/main/kotlin/android/widget/TextView.kt
AntonioNoack
568,083,291
false
null
package android.widget import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.text.TextWatcher import android.util.AttributeSet import android.view.Gravity import android.view.View import me.antonio.noack.maths.MathsUtils.dpToPx import me.antonio.noack.maths.MathsUtils.spToPx import org.w3c.dom.HTMLElement open class TextView(ctx: Context, attributeSet: AttributeSet?): View(ctx, attributeSet){ var text = "" var paint = Paint() var textAlign = Paint.Align.LEFT var textSize = paint.textSize var textColor = paint.color var isBold = false val watchers = ArrayList<TextWatcher>() override fun toString(): String { return super.toString()+"($text)" } init { paint.textAlign = Paint.Align.CENTER setOnClickListener { println("ignored click on $this") } } override fun onInit() { super.onInit() text = attributeSet.getString("text", "") textSize = attributeSet.getFloat("textSize", getDefaultTextSize()) textColor = attributeSet.getInt("textColor", getDefaultTextColor()) isBold = when(attributeSet.getString("textStyle", "")){ "bold" -> true "normal" -> false else -> getDefaultIsBold() } val xGravity = layoutParams.gravity and Gravity.HORIZONTAL_GRAVITY_MASK textAlign = when(xGravity){ Gravity.LEFT and Gravity.HORIZONTAL_GRAVITY_MASK -> Paint.Align.LEFT Gravity.CENTER and Gravity.HORIZONTAL_GRAVITY_MASK -> Paint.Align.CENTER Gravity.RIGHT and Gravity.HORIZONTAL_GRAVITY_MASK -> Paint.Align.RIGHT else -> { when(attributeSet.getString("textAlignment", "")){ "left", "start" -> Paint.Align.LEFT "center" -> Paint.Align.CENTER "right", "end" -> Paint.Align.RIGHT else -> getDefaultTextAlign() } } } // println("text $text := ${attributeSet.getString("textSize", "")}") // println("tv $text ${layoutParams.gravity} $xGravity, ${Gravity.LEFT} ${Gravity.CENTER} ${Gravity.RIGHT} -> $textAlign") } open fun addTextChangedListener(watcher: TextWatcher){ watchers.add(watcher) } var measuredTextWidth = 0f override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { if(this::class.simpleName != "EditText"){ if(text.isNotBlank()){ paint.isBold = isBold paint.textSize = textSize measuredTextWidth = paint.measureText(text) mMinWidth = measuredTextWidth.toInt() + mPaddingLeft + mPaddingRight mMinHeight = paint.textSize.toInt() + mPaddingTop + mPaddingBottom } else { measuredTextWidth = 0f mMinWidth = mPaddingLeft + mPaddingRight mMinHeight = mPaddingTop + mPaddingBottom } } super.onMeasure(widthMeasureSpec, heightMeasureSpec) } override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) canvas ?: return canvas.translate(mPaddingLeft, mPaddingTop) paint.isBold = isBold paint.textSize = textSize paint.color = textColor drawText(canvas, text, textAlign) } fun drawText(canvas: Canvas, text: String, align: Paint.Align, dx: Float = 0f, dy: Float = 0f, width: Int = measuredWidth - (mPaddingLeft + mPaddingRight), height: Int = measuredHeight - (mPaddingTop + mPaddingBottom), paint: Paint = this.paint) = drawText(canvas, text, align, dx, dy, width.toFloat(), height.toFloat(), paint) fun drawText(canvas: Canvas, text: String, align: Paint.Align, dx: Float, dy: Float, width: Float, height: Float, paint: Paint){ if(text.isBlank()) return val centerX = when(align){ Paint.Align.LEFT -> { measuredTextWidth * 0.5f } Paint.Align.CENTER -> { width * 0.5f } Paint.Align.RIGHT -> { width - measuredTextWidth * 0.5f } } canvas.drawText(text, centerX + dx, height * 0.5f + dy - 0.5f * (paint.ascent() + paint.descent()), paint) } open fun getDefaultTextAlign() = Paint.Align.LEFT open fun getDefaultTextColor() = 0xff555555.toInt() open fun getDefaultTextSize() = spToPx(12f) open fun getDefaultIsBold() = false override fun getDefaultPadding(): Int = dpToPx(5f).toInt() }
0
Kotlin
0
0
15e2013bc62282cd0185c9c0be57eaa5b0cb2c68
4,686
ElementalCommunityWeb
Apache License 2.0
app/src/main/java/com/progdeelite/dca/dependency/AndroidBuildUtil.kt
treslines
408,171,722
false
{"Kotlin": 334234}
package com.progdeelite.dca.dependency fun parseGitCommitCount(): Int { return Runtime.getRuntime() .exec("git rev-list --count HEAD") .inputStream .reader() .readLines() .lastOrNull() ?.also { println("git commit count: $it") } ?.toIntOrNull() ?: 5000.also { println("failed parsing git rev count. falling back to: $it") } } fun parseGitBranchName(): String { return Runtime.getRuntime() .exec("git rev-parse --abbrev-ref HEAD") .inputStream .reader() .readLines() .last() .also { println("branch name: $it") } }
0
Kotlin
16
159
07b12894c2898534516b079c1b2bc9dba05d88a4
635
desafios_comuns_android
Apache License 2.0
app/src/main/java/com/example/yinyuetaiplaykt/ui/fragment/MvFragment.kt
swordman20
326,163,061
false
null
package com.example.yinyuetaiplaykt.ui.fragment import android.view.View import com.example.yinyuetaiplaykt.R import com.example.yinyuetaiplaykt.adapter.TabPageAdapter import com.example.yinyuetaiplaykt.base.BaseFragment import com.example.yinyuetaiplaykt.model.TabBean import com.example.yinyuetaiplaykt.util.StringUtil import com.google.gson.Gson import com.google.gson.reflect.TypeToken import kotlinx.android.synthetic.main.fragment_mv.* import kotlin.reflect.typeOf class MvFragment : BaseFragment() { override fun initView(): View? { return View.inflate(context,R.layout.fragment_mv,null) } override fun initData() { val assetsGetJson = StringUtil.AssetsGetJson("json/tab.json", context) val fromJson = Gson().fromJson<List<TabBean>>(assetsGetJson, object : TypeToken<List<TabBean>>() {}.type) val tabPageAdapter = TabPageAdapter(fromJson, childFragmentManager) viewPager.adapter = tabPageAdapter tabLayout.setupWithViewPager(viewPager) } }
0
Kotlin
0
0
9433c85b01f974824a9b4eef512dd0a35be6007b
1,025
YinYueTaiPlayKT
Apache License 2.0
app/src/test/java/com/gigaworks/tech/calculator/ui/main/helper/CalculationUnitTest.kt
arch10
93,146,907
false
{"Kotlin": 150081, "Java": 7819}
package com.gigaworks.tech.calculator.ui.main.helper import ch.obermuhlner.math.big.BigDecimalMath import org.junit.Assert.assertEquals import org.junit.Test class CalculationUnitTest { @Test fun testNumberSeparatorInternational() { val expression = "6554656455" assertEquals("6,554,656,455", addNumberSeparator(expression = expression, isIndian = false)) assertEquals( "1.5457758E10", addNumberSeparator(expression = "1.5457758E10", isIndian = false) ) assertEquals( "6,566+65,688", addNumberSeparator(expression = "6566+65688", isIndian = false) ) } @Test fun testNumberSeparatorIndian() { val expression = "6554656455" assertEquals("6,55,46,56,455", addNumberSeparator(expression = expression, isIndian = true)) assertEquals( "6,66,566+65,688", addNumberSeparator(expression = "666566+65688", isIndian = true) ) } @Test fun testRemoveNumberSeparator() { val expression = "6,55,46,56,455" assertEquals("6554656455", removeNumberSeparator(expression = expression)) } @Test fun testRemoveFromEnd() { val expression = "9+15.25*5+-" val result = removeFromEndUntil(expression) { it.isOperator() } assertEquals("9+15.25*5", result) assertEquals("", removeFromEndUntil("") { it.isOperator() }) } @Test fun testFormatNumber() { val num1 = BigDecimalMath.toBigDecimal("65456554646.65656") assertEquals("6.5456555E10", formatNumber(num1, 7)) val num2 = BigDecimalMath.toBigDecimal("65656") assertEquals("6.5656000E4", formatNumber(num2, 7)) val num3 = BigDecimalMath.toBigDecimal("-5655455454") assertEquals("-5.6554555E9", formatNumber(num3, 7)) } @Test fun testIsExpressionBalanced() { assertEquals(true, isExpressionBalanced("(66+6*((4-2)/2))")) assertEquals(false, isExpressionBalanced("(66+6*(4-2)/2))")) assertEquals(false, isExpressionBalanced("(66+6*((4-2)/2)")) } @Test fun testTryBalancingBrackets() { assertEquals("65+(8-2)", tryBalancingBrackets("65+(8-2")) assertEquals("(6)+2", tryBalancingBrackets("6)+2")) assertEquals("6+2*2*", tryBalancingBrackets("6+2*2*(")) assertEquals("(6)*(6)", tryBalancingBrackets("6)*(6")) } }
4
Kotlin
12
33
49713f6723b5a299d75b01c92228e47073becf27
2,446
Calculator-Plus
Apache License 2.0
app/src/main/java/com/example/launchcontrol/isswiki/iss_sections/crew/domain/recyclerview/RecyclerViewISSCrewAdapter.kt
Icaro-G-Silva
344,936,988
false
null
package com.example.launchcontrol.isswiki.iss_sections.crew.domain.recyclerview import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.example.launchcontrol.R import com.example.launchcontrol.generals.entities.Menu class RecyclerViewISSCrewAdapter(private val dataset: List<Menu>): RecyclerView.Adapter<RecyclerViewISSCrewAdapter.ISSCrewViewHolder>() { class ISSCrewViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(item: Menu) { val nameView: TextView = itemView.findViewById(R.id.iss_crew_item_name) val imageView: ImageView = itemView.findViewById(R.id.iss_crew_item_image) nameView.text = item.title imageView.setImageResource(item.icon) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ISSCrewViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.iss_crew_item, parent, false) return ISSCrewViewHolder(view) } override fun onBindViewHolder(holder: ISSCrewViewHolder, position: Int) { holder.bind(dataset[position]) } override fun getItemCount(): Int { return dataset.size } }
0
Kotlin
0
0
1710da30a6d6bf2ec7e05827fdb4ca49fae48434
1,343
SpaceDroid
MIT License
data/src/main/java/de/fklappan/app/repositoryloader/data/AppDatabase.kt
fklappan
217,900,275
false
null
package de.fklappan.app.repositoryloader.data import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import de.fklappan.app.repositoryloader.data.bookmark.BookmarkDao import de.fklappan.app.repositoryloader.data.bookmark.BookmarkDataModel @Database(entities = [BookmarkDataModel::class], version = 1) abstract class AppDatabase : RoomDatabase() { abstract fun bookmarkDao(): BookmarkDao companion object { @Volatile private var INSTANCE: AppDatabase? = null fun getInstance(context: Context): AppDatabase = INSTANCE ?: synchronized(this) { INSTANCE ?: buildDatabase(context).also { INSTANCE = it } } private fun buildDatabase(context: Context) = Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, "repositoryloader.db") .allowMainThreadQueries() .build() } }
0
Kotlin
0
0
7bb14993e4c115147d93e1b77a27fc250e3e25dd
1,022
RepositoryLoader
Apache License 2.0
app/src/main/java/com/synthesizer/source/rawg/ui/gamedetail/component/description/DescriptionView.kt
Synthesizer-source
391,335,722
false
null
package com.synthesizer.source.rawg.ui.gamedetail.component.description import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.widget.LinearLayout import androidx.annotation.StyleRes import com.synthesizer.source.rawg.databinding.LayoutGameDetailDescriptionViewBinding class DescriptionView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, @StyleRes defStyleRes: Int = 0 ) : LinearLayout(context, attrs, defStyleAttr, defStyleRes) { private val binding = LayoutGameDetailDescriptionViewBinding.inflate( LayoutInflater.from(context), this ) init { orientation = VERTICAL } fun initialize(descriptionUIModel: DescriptionUIModel) { binding.description.setBodyContent(descriptionUIModel.description) } }
1
Kotlin
1
4
c892b199b6c5b914c14cc4eb6eaa040d38178d11
883
rawg-android-app
Apache License 2.0
android/src/main/kotlin/com/baseflow/contactsplugin/models/Address.kt
Baseflow
146,403,950
false
null
package com.baseflow.contactsplugin.models import com.baseflow.contactsplugin.data.AddressType class Address { var type: AddressType = AddressType.OTHER var label: String = "" var streetAddress: String = "" var city: String = "" var region: String = "" var country: String = "" var postalCode: String = "" }
12
Dart
20
40
2708c56e4e5300e8912fcb035ef8791f2fb82ffc
337
flutter-contacts-plugin
MIT License
domain/src/main/java/com/nedaluof/domain/usecases/tags/TagsUseCaseImpl.kt
nedaluof
497,393,170
false
{"Kotlin": 61392}
package com.nedaluof.domain.usecases.tags import com.nedaluof.data.datasource.remote.apiresponse.Tag import com.nedaluof.data.repository.tags.TagsRepository import com.nedaluof.domain.model.mapper.Mapper import com.nedaluof.domain.model.tag.TagModel import com.nedaluof.domain.model.util.Result import com.nedaluof.domain.usecases.base.BaseUseCase import kotlinx.coroutines.CoroutineScope import javax.inject.Inject /** * Created by NedaluOf on 5/29/2022. */ class TagsUseCaseImpl @Inject constructor( private val repository: TagsRepository, private val mapper: Mapper<Tag, TagModel> ) : TagsUseCase, BaseUseCase() { override fun loadAllTags( scope: CoroutineScope, result: (Result<List<TagModel>>) -> Unit ) { invoke( scope, apiToCall = { repository.getAllTags() }, onLoading = { result(Result.Loading(it)) }, onSuccess = { responseData -> val originalTagsList = mapper.fromList(responseData) val newTagsList = originalTagsList.toMutableList().also { it.add(0, TagModel("all", isSelected = true)) } result(Result.Success(newTagsList.sortedBy { it.name })) }, onError = { result(Result.Error(it.getErrorMessage())) } ) } }
0
Kotlin
0
1
6e207d190bbae7fc86b50c4ea994c887d20407a7
1,231
Quotes
Apache License 2.0
core/src/main/kotlin/no/ntnu/ihb/vico/dsl/Scoped.kt
NTNU-IHB
284,521,287
false
null
package no.ntnu.ihb.vico.dsl @DslMarker @Target(AnnotationTarget.CLASS, AnnotationTarget.TYPE) internal annotation class Scoped
4
Kotlin
2
11
997c708656c274cbcab94cb4375ebfdf46d5e1ad
129
Vico
MIT License
boot/src/test/kotlin/integration/breakpoint/ProbeBreakpointTest.kt
sourceplusplus
421,243,490
false
{"Kotlin": 392739, "Groovy": 3757}
/* * Source++, the continuous feedback platform for developers. * Copyright (C) 2022-2023 CodeBrig, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package integration.breakpoint import integration.ProbeIntegrationTest import io.vertx.junit5.VertxTestContext import io.vertx.kotlin.coroutines.await import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Test import spp.protocol.instrument.LiveBreakpoint import spp.protocol.instrument.event.LiveBreakpointHit import spp.protocol.instrument.event.LiveInstrumentEvent import spp.protocol.instrument.event.LiveInstrumentEventType import spp.protocol.instrument.location.LiveSourceLocation import spp.protocol.platform.general.Service class ProbeBreakpointTest : ProbeIntegrationTest() { @Suppress("UNUSED_VARIABLE") private fun doTest() { val a = 1 val b = 'a' val c = "a" val d = true val e = 1.0 val f = 1.0f val g = 1L val h: Short = 1 val i: Byte = 1 } @Test fun testPrimitives(): Unit = runBlocking { val breakpointId = "probe-breakpoint-test" val testContext = VertxTestContext() getLiveInstrumentSubscription(breakpointId).handler { testContext.verify { val event = LiveInstrumentEvent.fromJson(it.body()) if (event.eventType == LiveInstrumentEventType.BREAKPOINT_HIT) { val item = event as LiveBreakpointHit val vars = item.stackTrace.first().variables assertEquals(10, vars.size) testContext.completeNow() } } } assertNotNull( instrumentService.addLiveInstrument( LiveBreakpoint( location = LiveSourceLocation( source = ProbeBreakpointTest::class.java.name, line = 46, service = Service.fromName("spp-test-probe") ), applyImmediately = true, id = breakpointId ) ).await() ) log.info("Triggering breakpoint") doTest() errorOnTimeout(testContext) } }
10
Kotlin
1
1
a070c302fc211045229f6a4b82568ac2e1528cc4
2,882
probe-jvm
Apache License 2.0
app/src/main/java/com/example/epubminiapp/MenuActivity.kt
niespiejuz
470,631,365
false
null
package com.example.epubminiapp import android.Manifest.permission.READ_EXTERNAL_STORAGE import android.Manifest.permission.WRITE_EXTERNAL_STORAGE import android.app.Activity import android.content.Intent import android.content.pm.PackageManager import android.graphics.Color import android.net.Uri import android.os.AsyncTask import android.os.Build import android.os.Bundle import android.os.Environment import android.provider.Settings import android.util.Log import android.view.View import android.view.Window import android.widget.AdapterView.OnItemClickListener import android.widget.GridView import android.widget.TextView import android.widget.Toast import androidx.activity.result.ActivityResult import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.github.mertakdut.Reader import com.github.mertakdut.exception.ReadingException import java.io.File import java.io.FileOutputStream class MenuActivity : AppCompatActivity() { private var bookList: MutableList<BookInfo>? = null; override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) AppSettings.init(this) setContentView(R.layout.activity_menu) val toolbar = findViewById<View>(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) toolbar.setTitleTextColor(Color.WHITE) val settingsBtn = findViewById<View>(R.id.Settings_Button) settingsBtn.setOnClickListener{ showSettings() } (findViewById<View>(R.id.grid_book_info) as GridView).onItemClickListener = OnItemClickListener { adapterView, view, i, l -> val clickedItemFilePath = (adapterView.adapter.getItem(i) as BookInfo).filePath askForWidgetToUse(clickedItemFilePath) } //progressBar = findViewById<View>(R.id.progressbar) as ProgressBar this.bookList = ListBookInfoTask().execute().get() as MutableList<BookInfo> } private inner class ListBookInfoTask : AsyncTask<Any?, Any?, List<BookInfo>?>() { private var occuredException: Exception? = null override fun onPreExecute() { super.onPreExecute() // progressBar!!.visibility = View.VISIBLE } override fun onPostExecute(bookInfoList: List<BookInfo>?) { super.onPostExecute(bookInfoList) //progressBar!!.visibility = View.GONE if (bookInfoList != null) { val adapter = BookInfoGridAdapter(this@MenuActivity, bookInfoList) (findViewById<View>(R.id.grid_book_info) as GridView).adapter = adapter } if (occuredException != null) { Toast.makeText(this@MenuActivity, occuredException!!.message, Toast.LENGTH_LONG).show() } } override fun doInBackground(vararg p0: Any?): List<BookInfo>? { val bookInfoList = searchForEpubFiles() val reader = Reader() for (bookInfo in bookInfoList!!) { try { reader.setInfoContent(bookInfo.filePath) val title = reader.infoPackage.metadata.title val author = reader.infoPackage.metadata.creator if (title != null && title != "") { bookInfo.title = reader.infoPackage.metadata.title } else { // If title doesn't exist, use fileName instead. val dotIndex = bookInfo.title!!.lastIndexOf('.') bookInfo.title = bookInfo.title!!.substring(0, dotIndex) } if( author != null && author != ""){ bookInfo.author = author } bookInfo.coverImage = reader.coverImage } catch (e: ReadingException) { occuredException = e e.printStackTrace() } } return bookInfoList } } val sActivityResultLauncher: ActivityResultLauncher<Intent> = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ result: ActivityResult -> if(result.resultCode == Activity.RESULT_OK) { val data: Intent = result.data!! val uri: Uri = data.data!! val file = File(uri.path) val bookInfo = BookInfo() bookInfo.title = file.name bookInfo.filePath = file.path bookList!!.add(bookInfo) val adapter = BookInfoGridAdapter(this@MenuActivity, bookList!!) (findViewById<View>(R.id.grid_book_info) as GridView).adapter = adapter } } public final fun showSettings(){ val intent = Intent(this@MenuActivity, SettingsView::class.java) startActivity(intent) } public final fun openFileDialog(view: android.view.View){ var data = Intent(Intent.ACTION_OPEN_DOCUMENT) data.setType("*/*") data = Intent.createChooser(data,"Choose a file") sActivityResultLauncher.launch(data) } private fun searchForEpubFiles(): List<BookInfo>? { val isSDPresent = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED var bookInfoList: MutableList<BookInfo>? = null if(checkPermission()){ if (isSDPresent) { bookInfoList = ArrayList() Log.d("FILES",Environment.getExternalStoragePublicDirectory("Download").absolutePath) val files = getListFiles(File(Environment.getExternalStorageDirectory().absolutePath)) val sampleFile = getFileFromAssets("pg28885-images_new.epub") files.add(0, sampleFile) for (file in files) { val bookInfo = BookInfo() bookInfo.title = file.name bookInfo.filePath = file.path bookInfoList.add(bookInfo) } } } else{ requestPermission(); } return bookInfoList } // request permissions from the user private fun requestPermission() { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { try{ var intent = Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION) intent.addCategory("android.intent.category.DEFAULT") val uri = Uri.fromParts("package",packageName,null) intent.data = uri startActivity(intent) } catch(e:Exception){ var intent = Intent(); intent.action = Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION startActivity(intent) } } else{ ActivityCompat.requestPermissions(this@MenuActivity, arrayOf(WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE),30) } } // check permissions for writing and reading external storage private fun checkPermission(): Boolean { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){ return Environment.isExternalStorageManager() } val readcheck = ContextCompat.checkSelfPermission(applicationContext, READ_EXTERNAL_STORAGE) val writecheck = ContextCompat.checkSelfPermission(applicationContext, WRITE_EXTERNAL_STORAGE) return readcheck == PackageManager.PERMISSION_GRANTED && writecheck == PackageManager.PERMISSION_GRANTED } fun getFileFromAssets(fileName: String): File { val file = File("$cacheDir/$fileName") if (!file.exists()) try { val `is` = assets.open(fileName) val size = `is`.available() val buffer = ByteArray(size) `is`.read(buffer) `is`.close() val fos = FileOutputStream(file) fos.write(buffer) fos.close() } catch (e: Exception) { throw RuntimeException(e) } return file } private fun getListFiles(parentDir: File): MutableList<File> { val inFiles:MutableList<File> = ArrayList() val files = parentDir.listFiles() if (files != null) { for (file in files) { Log.d("FILES",file.name) if (file.isDirectory) { inFiles.addAll(getListFiles(file)) } else { if (file.name.endsWith(".epub")) { inFiles.add(file) } } } } return inFiles } private fun askForWidgetToUse(filePath: String?) { val intent = Intent(this@MenuActivity, MainActivity::class.java) intent.putExtra("filePath", filePath) startActivity(intent) } }
0
Kotlin
0
0
2d655b5999c03668c6003a399cac21a3c2012473
9,086
ebook-for-dislexia
MIT License
app/src/main/java/com/kasuminotes/action/RatioDamage.kt
chilbi
399,723,451
false
{"Kotlin": 823206}
package com.kasuminotes.action import com.kasuminotes.R import com.kasuminotes.data.SkillAction fun SkillAction.getRatioDamage(skillLevel: Int): D { val formula = D.Format( if (actionDetail1 == 1) R.string.content_max_hp_ratio1 else R.string.content_hp_ratio1, arrayOf( D.Join( arrayOf( getBaseLvFormula(actionValue1, actionValue2, skillLevel) { it }, D.Text("%") ) ) ) ) return D.Format( R.string.action_damage_target1_formula2_content3, arrayOf( getTarget(depend), formula, getDamageType(actionDetail2)) ) }
0
Kotlin
0
0
34e06010129a265e6c4ac66e6e8d9d2316c46796
673
KasumiNotes
Apache License 2.0
bidon/src/main/java/org/bidon/sdk/databinders/token/TokenBinder.kt
bidon-io
504,568,127
false
null
package org.bidon.sdk.databinders.token import org.bidon.sdk.databinders.DataBinder /** * Created by <NAME> on 06/02/2023. */ internal class TokenBinder( private val dataSource: TokenDataSource ) : DataBinder<String> { override val fieldName: String = "token" override suspend fun getJsonObject(): String? = dataSource.token?.token }
3
Kotlin
0
0
d13182b32c9da6a44238a5d2981d875358aafc6f
362
bidon-sdk-android
Apache License 2.0
app/src/main/java/com/commit451/viewtiful/sample/MainKotlinActivity.kt
Commit451
58,215,260
false
null
package com.commit451.viewtiful.sample import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.util.Log import android.widget.TextView import android.widget.Toast import com.commit451.viewtiful.kotlin.onGlobalLayout import com.commit451.viewtiful.kotlin.onViewPreDraw import com.commit451.viewtiful.kotlin.setPaddingTop import com.commit451.viewtiful.kotlin.topMargin class MainKotlinActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_kotlin) val view = findViewById(R.id.text) as TextView view.onViewPreDraw(Runnable { Log.d("Hello", "The view is about to draw.") Toast.makeText(this@MainKotlinActivity, "The view is about to draw!!! How exciting", Toast.LENGTH_SHORT).show() }) view.onGlobalLayout(Runnable { Log.d("Hello", "The view has been laid out. Also exciting!") }) view.setPaddingTop(10) view.topMargin(10) } }
0
Java
1
18
7c5793e8e956346532cc379f1b940287dbd044b8
1,076
Viewtiful
Apache License 2.0
app/src/main/java/com/lindevhard/felia/component/create_wallet/store/CreateWalletStore.kt
LinDevHard
467,245,166
false
{"Kotlin": 259612, "Java": 13406}
package com.lindevhard.felia.component.create_wallet.store import com.arkivanov.mvikotlin.core.store.Store import com.lindevhard.felia.component.create_wallet.store.CreateWalletStore.Intent import com.lindevhard.felia.component.create_wallet.store.CreateWalletStore.State interface CreateWalletStore: Store<Intent, State, Nothing> { sealed class Intent { object CreateWallet : Intent() } data class State( val seed: String = "", val isCreated: Boolean = false, ) }
0
Kotlin
1
0
19871d912c4548b6cf643a1405988d8030e9ab9d
508
FeliaWallet
Apache License 2.0
ui-navigation/build.gradle.kts
alipovatyi
614,818,086
false
null
@Suppress("DSL_SCOPE_VIOLATION") plugins { alias(libs.plugins.android.library) alias(libs.plugins.kotlin.android) } android { namespace = "dev.arli.sunnyday.ui.navigation" buildFeatures { compose = true } composeOptions { kotlinCompilerExtensionVersion = libs.versions.composeCompiler.get() } } dependencies { implementation(project(":data-model")) implementation(project(":ui-common")) implementation(project(":ui-details")) implementation(project(":ui-locations")) implementation(libs.androidx.core) implementation(libs.androidx.navigation.compose) implementation(libs.hilt.navigationCompose) }
0
Kotlin
0
0
f272db479e91de350368a8573df6ddebb22e0742
674
sunny-day-android
Apache License 2.0
api/api-ports/api-binance-rest/src/main/kotlin/co/nilin/opex/api/ports/binance/data/BalanceResponse.kt
opexdev
370,411,517
false
{"Kotlin": 1226476, "HTML": 43145, "Shell": 8026, "Java": 6679, "Dockerfile": 3334, "PLpgSQL": 3216, "HCL": 823}
package co.nilin.opex.api.ports.binance.data import java.math.BigDecimal data class BalanceResponse( var asset: String, var free: BigDecimal, var locked: BigDecimal, var withdraw: BigDecimal )
27
Kotlin
14
23
6b226b36b1cf14395c07c69199cbbf5fb41c9d73
210
core
MIT License
gateway/build.gradle.kts
Galarzaa90
416,423,240
true
{"Kotlin": 2394356, "Java": 87103}
plugins { `kord-multiplatform-module` `kord-publishing` } kotlin { sourceSets { commonMain { dependencies { api(projects.common) api(libs.bundles.ktor.client.serialization) api(libs.ktor.client.websockets) } } jsMain { dependencies { implementation(libs.kotlin.node) implementation(npm("fast-zlib", libs.versions.fastZlib.get())) } } } }
0
Kotlin
0
0
b63b009537517edb6880e6d8b9fe93ef7c6853aa
516
kord
MIT License
implementation/src/test/kotlin/com/aoc/fuel/calculator/strategy/RefinedFuelCalculationStrategyTest.kt
TomPlum
227,887,094
false
null
package com.aoc.fuel.calculator.strategy import assertk.assertThat import assertk.assertions.isEqualTo import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test class RefinedFuelCalculationStrategyTest { @Nested @DisplayName("Part 2 Examples") inner class ExamplesPartTwo { @Test @DisplayName("Given a module of mass 14, when calculating additional fuel, then it should only return 2") fun additionalFuelExampleOne() { assertThat(RefinedFuelCalculationStrategy().calculateRequirements(14)).isEqualTo(2) } @Test @DisplayName("Given a module of mass 1969, when calculating additional fuel, then it should only return 966") fun additionalFuelExampleTwo() { assertThat(RefinedFuelCalculationStrategy().calculateRequirements(1969)).isEqualTo(966) } @Test @DisplayName("Given a module of mass 100756, when calculating additional fuel, then it should only return 50346") fun additionalFuelExampleThree() { assertThat(RefinedFuelCalculationStrategy().calculateRequirements(100756)).isEqualTo(50346) } } }
7
Kotlin
1
2
12d47cc9c50aeb9e20bcf110f53d097d8dc3762f
1,201
advent-of-code-2019
Apache License 2.0
game-core/src/main/kotlin/tech/stephenlowery/rpgbot/core/game/Game.kt
sglowery
272,840,524
false
null
package tech.stephenlowery.rpgbot.core.game import tech.stephenlowery.rpgbot.core.action.CharacterActionType import tech.stephenlowery.rpgbot.core.action.EffectResult import tech.stephenlowery.rpgbot.core.action.QueuedCharacterAction import tech.stephenlowery.rpgbot.core.action.QueuedCharacterActionResolvedResults import tech.stephenlowery.rpgbot.core.character.NonPlayerCharacter import tech.stephenlowery.rpgbot.core.character.PlayerCharacter import tech.stephenlowery.rpgbot.core.character.RPGCharacter import tech.stephenlowery.rpgbot.core.character.UserState private val PLAYER_NOT_READY_STATES = listOf(UserState.CHOOSING_ACTION, UserState.CHOOSING_TARGETS) open class Game(val id: Long, val initiatorId: Long, initiatorName: String) { val players = mutableMapOf<Long, RPGCharacter>() var hasStarted = false private var turnCounter = 0 private val resultsHistory = mutableListOf<Collection<QueuedCharacterActionResolvedResults>>() init { addPlayerToGame(initiatorId, initiatorName) } var actionQueue = mutableListOf<QueuedCharacterAction>() fun addPlayerToGame(playerId: Long, name: String) { players[playerId] = PlayerCharacter(playerId, name) } fun numberOfPlayers() = players.keys.size fun queueActionFromCharacter(callbackData: String, userID: Long): UserState { return findPlayerCharacterFromID(userID)!!.apply { actionQueue.add(this.chooseAction(callbackData)) }.characterState } fun addCharacter(character: PlayerCharacter) { players[character.id] = character } fun removeCharacters(characters: Collection<PlayerCharacter>) = removeCharactersByUserIDs(characters.map { it.id }) private fun removeCharactersByUserIDs(userIDs: Collection<Long>) { userIDs.forEach(players::remove) } fun addTargetToQueuedCharacterAction(from: Long, to: Long) { val fromCharacter = findPlayerCharacterFromID(from) val toCharacter = getCharacterFromId(to) if (fromCharacter != null && toCharacter != null) { fromCharacter.addTargetToAction(toCharacter) } else { println("character missing for addTargetToCharacterAction") } } fun getCharacterFromId(playerId: Long): RPGCharacter? = players[playerId] fun findPlayerCharacterFromID(playerId: Long): PlayerCharacter? = getHumanPlayers()[playerId] @Suppress("UNCHECKED_CAST") fun getHumanPlayers(): Map<Long, PlayerCharacter> = players.filterValues { it is PlayerCharacter } as Map<Long, PlayerCharacter> fun containsPlayerWithID(userID: Long): Boolean = players.containsKey(userID) fun allPlayersAreWaiting(): Boolean = waitingOn().isEmpty() fun waitingOn(): Collection<PlayerCharacter> = livingPlayers<PlayerCharacter>().filter { it.characterState in PLAYER_NOT_READY_STATES } protected inline fun <reified T : RPGCharacter> livingPlayers(): Collection<T> = players.values.filterIsInstance<T>().filter { it.isAlive() } @JvmName("livingPlayers1") fun livingPlayers(): Collection<RPGCharacter> = players.values.filter { it.isAlive() } fun deadPlayers(): Collection<RPGCharacter> = players.values.filterNot { it.isAlive() } open fun resolveActionsAndGetResults(): String { val npcActions = livingPlayers<NonPlayerCharacter>().mapNotNull { it.getQueuedAction(this) } val queuedActions = listOf(actionQueue, npcActions).flatMap(::partitionAndShuffleActionQueue).toMutableList() val results = resolveActions(queuedActions) val stringResults = results.map(QueuedCharacterActionResolvedResults::stringResult).toMutableList() queuedActions.removeIf { it.isExpired() } actionQueue = queuedActions players.values.forEach { player -> if (player.getActualHealth() <= 0 && player.characterState != UserState.DEAD) { stringResults.add("${player.name} died! They will be removed from the game.") player.characterState = UserState.DEAD } else { player.resetForNextTurnAfterAction() } } resultsHistory.add(results) turnCounter += 1 return listOf("*----Turn $turnCounter results----*", stringResults.joinToString("\n\n")).joinToString("\n\n") } open fun startGame(): Collection<Pair<Long, String>> { startGameStateAndPrepCharacters() return players.map { it.key to "You've entered a free-for-all game. The last one alive wins. Good luck ${it.value.name}." } } open fun isOver() = livingPlayers().size > 1 open fun getGameEndedText(): String = when (livingPlayers().size) { 1 -> "${livingPlayers().first().name} wins!" 0 -> "Uh, well, I guess the remaining people died at the same time or something. Ok." else -> "Uh oh, this shouldn't happen." } open fun getTargetsForCharacter(character: PlayerCharacter): Collection<RPGCharacter> { return charactersBesidesSelf(character) } fun cancel() { actionQueue.clear() players.clear() turnCounter = 0 players.values.forEach(RPGCharacter::resetCharacter) players.clear() actionQueue.clear() System.gc() } open fun numberOfPlayersIsInvalid() = numberOfPlayers() < 2 protected fun startGameStateAndPrepCharacters() { hasStarted = true players.values.forEach { it.characterState = UserState.CHOOSING_ACTION } } private fun charactersBesidesSelf(character: PlayerCharacter): Collection<RPGCharacter> { return livingPlayers().filter { it.id != character.id } } private fun partitionAndShuffleActionQueue(actionQueue: Collection<QueuedCharacterAction>): Collection<QueuedCharacterAction> { return actionQueue .partition { it.action.actionType == CharacterActionType.DEFENSIVE } .let { it.first.shuffled() + it.second.shuffled() } } private fun resolveActions(sortedActionQueue: MutableCollection<QueuedCharacterAction>): MutableCollection<QueuedCharacterActionResolvedResults> { val actionResults = mutableListOf<QueuedCharacterActionResolvedResults>() val deadPlayersThisTurn = mutableSetOf<Long>() val actionQueueIterator = sortedActionQueue.iterator() while (actionQueueIterator.hasNext()) { val currentAction = actionQueueIterator.next() if (currentAction.target?.id in deadPlayersThisTurn || actionIsUnresolvedAndFromADeadPlayer(currentAction, deadPlayersThisTurn)) { actionQueueIterator.remove() continue } val currentActionResults = currentAction.cycleAndResolve() currentAction.target?.apply { if (!this.isAlive() && this.id !in deadPlayersThisTurn) { deadPlayersThisTurn.add(this.id) currentActionResults.actionResultedInDeath = true } } actionResults.add(currentActionResults) } return actionResults } private fun actionIsUnresolvedAndFromADeadPlayer(action: QueuedCharacterAction, deadPlayers: Set<Long>): Boolean { return action.isUnresolved() && action.source.id in deadPlayers } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Game) return false if (id != other.id) return false return initiatorId == other.initiatorId } override fun hashCode(): Int { var result = id.hashCode() result = 31 * result + initiatorId.hashCode() return result } }
0
Kotlin
0
0
f91af53ff194f280173175ee07fca718b9f98453
7,714
stephens-rpg-bot
MIT License
src/main/kotlin/no/nav/syfo/api/v2/mapper/Gyldighetstidspunkt.kt
navikt
164,875,446
false
{"Kotlin": 383832, "Java": 333167, "XSLT": 25351, "PLSQL": 1668, "Dockerfile": 359, "Shell": 257}
package no.nav.syfo.api.v2.mapper import no.nav.syfo.api.v2.domain.oppfolgingsplan.Gyldighetstidspunkt fun Gyldighetstidspunkt.toGyldighetstidspunkt(): no.nav.syfo.domain.Gyldighetstidspunkt { val gyldighetstidspunkt = no.nav.syfo.domain.Gyldighetstidspunkt() gyldighetstidspunkt.fom = fom gyldighetstidspunkt.tom = tom gyldighetstidspunkt.evalueres = evalueres return gyldighetstidspunkt }
0
Kotlin
0
0
05f0dcdeac90753df77ecfcc616fd989dc4277e8
413
syfooppfolgingsplanservice
MIT License
core/src/com/darkoverlordofdata/shmupwarz/systems/DestroySystem.kt
darkoverlordofdata
57,466,658
false
null
package com.darkoverlordofdata.shmupwarz.systems /** * Entitas Generated Systems for com.darkoverlordofdata.entitas.demo * */ import com.darkoverlordofdata.entitas.* import com.darkoverlordofdata.shmupwarz.* class DestroySystem() : IExecuteSystem, ISetPool { private lateinit var pool: Pool private lateinit var group: Group override fun setPool(pool: Pool) { this.pool = pool group = pool.getGroup(Matcher.allOf(Matcher.Destroy)) } override fun execute() { for (entity in group.entities) { pool.destroyEntity(entity) } } }
0
Kotlin
0
0
0a395418af0a9c51254bca449cafc6b296d80ee9
615
shmupwarz-entitas-kotlin
MIT License
sample/src/main/java/com/github/qingmei2/sample/di/AppComponent.kt
qingmei2
167,174,767
false
null
package com.github.qingmei2.sample.di import android.app.Application import com.github.qingmei2.sample.base.BaseApplication import dagger.BindsInstance import dagger.Component import dagger.android.AndroidInjectionModule import dagger.android.support.AndroidSupportInjectionModule import javax.inject.Singleton @Singleton @Component( modules = [ AndroidInjectionModule::class, AndroidSupportInjectionModule::class, ActivitiesModule::class, FragmentsModule::class, AppModule::class ] ) interface AppComponent { @Component.Builder interface Builder { @BindsInstance fun application(application: Application): Builder fun build(): AppComponent } fun inject(application: BaseApplication) }
4
Kotlin
25
170
6fce8ebc0b123bec8684f90f9b11fa606d469c42
778
MVI-Architecture
Apache License 2.0
app/src/main/java/com/baykal/edumyclient/data/domain/answer/SendAnswerUseCase.kt
cmbaykal
427,949,051
false
{"Kotlin": 348628, "Java": 8699}
package com.baykal.edumyclient.data.domain.answer import com.baykal.edumyclient.base.data.BaseUseCase import com.baykal.edumyclient.data.repository.AnswerRepositoryImpl import io.ktor.http.content.* import javax.inject.Inject class SendAnswerUseCase @Inject constructor( private val answerRepository: AnswerRepositoryImpl ) : BaseUseCase<List<PartData>, Unit>() { override fun build(params: List<PartData>) = answerRepository.sendAnswer(params) }
0
Kotlin
0
1
e5890acfabaf98c6bd0ccd1bab09e0da37f9fa4d
457
edumy-client
MIT License
confluence-plugin/src/main/java/com/networkedassets/git4c/boundary/outbound/GlobsForMacro.kt
rpaasche
321,741,515
true
{"Kotlin": 798728, "JavaScript": 351426, "Java": 109291, "Groovy": 55451, "CSS": 37375, "ANTLR": 19544, "Gherkin": 15007, "HTML": 14268, "Shell": 4490, "Ruby": 1378, "Batchfile": 1337, "PowerShell": 716}
package com.networkedassets.git4c.boundary.outbound data class GlobsForMacro( val globs: List<GlobForMacro> )
0
Kotlin
0
0
e55391b33cb70d66bbf5f36ba570fb8822f10953
118
git4c
Apache License 2.0
src/main/kotlin/com/github/quanticheart/intellijplugincleantree/wizard/others/mapper/MapperGenericRecipe.kt
quanticheart
519,671,971
false
{"Kotlin": 115237, "Java": 237}
package com.github.quanticheart.intellijplugincleantree.wizard.others.mapper import com.android.tools.idea.wizard.template.ModuleTemplateData import com.android.tools.idea.wizard.template.RecipeExecutor import com.github.quanticheart.intellijplugincleantree.wizard.cleanArch.domain.repository.cleanArchRepositorySimple import com.github.quanticheart.intellijplugincleantree.wizard.cleanArch.domain.useCases.cleanArchUseCaseSimple import java.util.* fun RecipeExecutor.mapperGenericRecipe( moduleData: ModuleTemplateData, packageName: String ) { val (_, srcOut, _) = moduleData val fileName = "Mapper" /** * Domain */ val repository = mapperGenericTemplate( featurePackage = packageName ) save( repository, srcOut.resolve("${fileName}.kt") ) }
0
Kotlin
0
0
92dfc1c111b991296c4575daa23522f4bc381339
819
intellij-plugin-cleantree
Apache License 2.0
shared/src/commonMain/kotlin/com/shady/kmm/entity/FilterData.kt
Shady-Selim
427,960,788
false
{"Kotlin": 28240, "Swift": 21531}
package com.shady.kmm.entity import kotlinx.serialization.Serializable @Serializable data class FilterData ( val filter_id: Int, val name: String )
0
Kotlin
1
13
f72d4f41e50c9436a0f4d407dddc4d2b86f248ba
157
KMM-StoreList-App
Apache License 2.0
2021/src/main/kotlin/day7_fast.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Solution import kotlin.math.abs fun main() { Day7Fast.run() } object Day7All { @JvmStatic fun main(args: Array<String>) { mapOf("func" to Day7Func, "imp" to Day7Imp, "fast" to Day7Fast).forEach { (header, solution) -> solution.run(header = header, skipPart1 = true, skipTest = true, printParseTime = false) } } } object Day7Fast : Solution<List<Int>>() { override val name = "day7" override val parser = Parser.ints override fun part1(crabs: List<Int>): Int { return solve(crabs, this::identity) } override fun part2(crabs: List<Int>): Int { return solve(crabs, this::cost) } private fun solve(crabs: List<Int>, costFn: (Int) -> Int): Int { fun totalFuel(target: Int): Int { return crabs.sumOf { costFn(abs(it - target)) } } var lower = 0 var upper = crabs.maxOrNull()!! while (lower != upper) { val mid = (lower + upper) / 2 if (mid > lower && totalFuel(mid) < totalFuel(mid - 1)) { lower = mid } else { upper = mid } } return totalFuel(lower) } private fun identity(distance: Int) = distance private fun cost(distance: Int) = distance * (distance + 1) / 2 }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,225
aoc_kotlin
MIT License
app/src/main/java/ru/llxodz/catsanddogs/CatsActivity.kt
llxodz
391,484,099
false
null
package ru.llxodz.catsanddogs import android.os.Bundle import android.util.Log import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatDelegate import com.bumptech.glide.Glide import kotlinx.android.synthetic.main.activity_cats.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import ru.llxodz.catsanddogs.api.ApiRequest import ru.llxodz.catsanddogs.api.BASE_URL_CATS class CatsActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_cats) AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) makeApiRequest() floatingActionButton.setOnClickListener { floatingActionButton.animate().apply { rotationBy(360f) duration = 1000 }.start() makeApiRequest() iv_random_cat.visibility = View.GONE } } private fun makeApiRequest() { val api = Retrofit.Builder() .baseUrl(BASE_URL_CATS) .addConverterFactory(GsonConverterFactory.create()) .build() .create(ApiRequest::class.java) GlobalScope.launch(Dispatchers.IO) { try { val response = api.getRandomCat() withContext(Dispatchers.Main) { Glide.with(applicationContext).load(response.file).into(iv_random_cat) iv_random_cat.visibility = View.VISIBLE } } catch (e: Exception) { makeApiRequest() } } } }
0
Kotlin
0
0
ef3d1bfe6dae6ae8cdcacd06d19040fcd70b3691
1,858
random-dogs-and-cats
Apache License 2.0
app/src/main/java/de/fklappan/app/workoutlog/ui/detailviewworkout/DetailviewWorkoutState.kt
fklappan
198,422,102
false
null
package de.fklappan.app.workoutlog.ui.detailviewworkout import de.fklappan.app.workoutlog.ui.overviewworkout.WorkoutGuiModel sealed class DetailviewWorkoutState { object Loading : DetailviewWorkoutState() data class Error(val message: String) : DetailviewWorkoutState() data class WorkoutDetails(val workoutDetails: WorkoutDetailsGuiModel) : DetailviewWorkoutState() data class WorkoutUpdate(val workout: WorkoutGuiModel) : DetailviewWorkoutState() }
5
Kotlin
0
0
b8750317f50005b9aae793a9b55652a2ace13567
468
WorkoutLog
Apache License 2.0
ui/src/main/java/pl/kubisiak/ui/recyclerview/ViewModelViewHolder.kt
szymonkubisiak
222,223,106
false
null
package pl.kubisiak.ui.recyclerview import androidx.databinding.ViewDataBinding import androidx.recyclerview.widget.RecyclerView import androidx.databinding.library.baseAdapters.BR import pl.kubisiak.ui.BaseSubViewModel class ViewModelViewHolder(val binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(viewModel: BaseSubViewModel) { binding.setVariable(BR.vm, viewModel) binding.executePendingBindings() } }
0
Kotlin
0
0
5104e88688c00ca0f62e950e28c2b089b01503c9
460
demo-android
MIT License
bigbone/src/main/kotlin/social/bigbone/api/method/ReportMethods.kt
andregasser
565,112,249
false
{"Kotlin": 974974, "Java": 28473, "Ruby": 15997, "Dockerfile": 1263, "Shell": 118}
package social.bigbone.api.method import social.bigbone.MastodonClient import social.bigbone.MastodonRequest import social.bigbone.Parameters import social.bigbone.api.entity.Report import social.bigbone.api.entity.data.ReportCategory import social.bigbone.api.exception.BigBoneRequestException /** * Allows access to API methods with endpoints having an "api/vX/reports" prefix. * @see <a href="https://docs.joinmastodon.org/methods/reports/">Mastodon reports API methods</a> */ class ReportMethods(private val client: MastodonClient) { private val endpoint = "api/v1/reports" /** * File a report. * @param accountId The ID of the account to report * @param forward To forward the report to the remote admin * @param statusIds List of ID strings for statuses to be reported * @param ruleIds To specify the IDs of the exact rules broken in case of violations * @param comment The reason for the report. Default maximum of 1000 characters * @param category To specify if you are looking for a specific category of report * @see <a href="https://docs.joinmastodon.org/methods/reports/#post">Mastodon API documentation: methods/reports/#post</a> */ @JvmOverloads @Throws(BigBoneRequestException::class) fun fileReport( accountId: String, forward: Boolean = false, statusIds: List<String>? = emptyList(), ruleIds: List<Int>? = emptyList(), comment: String? = null, category: ReportCategory? = null ): MastodonRequest<Report> { return client.getMastodonRequest( endpoint = endpoint, method = MastodonClient.Method.POST, parameters = buildParameters(accountId, statusIds, comment, forward, ruleIds, category) ) } private fun buildParameters( accountId: String, statusIds: List<String>? = emptyList(), comment: String? = null, forward: Boolean = false, ruleIds: List<Int>? = emptyList(), category: ReportCategory? = null ): Parameters { return Parameters().apply { append("account_id", accountId) append("forward", forward) append("category", setCategoryCorrectly(ruleIds, category).name) if (!statusIds.isNullOrEmpty()) { append("status_ids", statusIds) } if (!comment.isNullOrEmpty() && comment.isNotBlank()) { append("comment", comment) } if (!ruleIds.isNullOrEmpty()) { append("ruleIds", ruleIds) } } } private fun setCategoryCorrectly( ruleIds: List<Int>? = emptyList(), category: ReportCategory? = null ): ReportCategory { return when { !ruleIds.isNullOrEmpty() -> ReportCategory.VIOLATION category == null -> ReportCategory.OTHER else -> category } } }
26
Kotlin
15
49
94563c51ec9df565c67c0f9656330c66a0216a8e
2,947
bigbone
MIT License
kmongo-core-tests/src/main/kotlin/org/litote/kmongo/issues/Issue384BehaviourEvaluate.kt
Litote
58,964,537
false
{"Kotlin": 1722533, "Java": 56965, "Shell": 2012}
/* * Copyright (C) 2016/2022 Litote * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.litote.kmongo.issues import org.junit.Test import org.litote.kmongo.AllCategoriesKMongoBaseTest import org.litote.kmongo.evaluate import org.litote.kmongo.model.Friend /** * */ class Issue384BehaviourEvaluate : AllCategoriesKMongoBaseTest<Friend>() { @Test fun `test insert and load`() { col.find().evaluate { println(count() == 0) // prints 'true' } } }
42
Kotlin
74
789
0e7143051e07e5415e70ad5bc2bbfa3e57afc923
1,007
kmongo
Apache License 2.0
mandark-view/src/main/kotlin/dev/jonpoulton/mandark/libraries/ui/LibraryViewHolder.kt
jonapoul
378,197,473
false
{"Kotlin": 170933, "Shell": 478}
package dev.jonpoulton.mandark.libraries.ui import androidx.recyclerview.widget.RecyclerView import dev.jonpoulton.alakazam.ui.view.showIfTrue import dev.jonpoulton.mandark.classic.databinding.FragmentLibrariesItemBinding import dev.jonpoulton.mandark.libraries.domain.model.LibraryListModel internal class LibraryViewHolder( private val binding: FragmentLibrariesItemBinding, private val onLaunchUrl: (url: String) -> Unit, ) : RecyclerView.ViewHolder(binding.root) { fun bindTo(item: LibraryListModel) = with(binding) { /* Set the text fields */ libraryTitle.text = item.project libraryVersion.text = item.version libraryArtifact.text = item.artifact libraryAuthors.text = item.authors libraryLicense.text = item.license libraryDescription.text = item.description /* Launch webpage when clicking an item, if there's a URL. Hide the launch button if not and * disable clicking. */ val isClickable = item.url != null if (isClickable) { root.setOnClickListener { onLaunchUrl.invoke(item.url ?: error("Null URL: $item")) } } root.isClickable = isClickable launchButton.showIfTrue(isClickable) } }
0
Kotlin
0
0
2696c6ba88a623e713a3993d12eeccc9f9723482
1,182
mandark
Apache License 2.0
app/src/main/java/com/example/background/workers/SaveImageWorker.kt
ajaypro
204,463,222
false
null
package com.example.background.workers import android.content.Context import android.provider.MediaStore import androidx.work.Worker import androidx.work.WorkerParameters import androidx.work.workDataOf import com.example.background.KEY_IMAGE_URI import timber.log.Timber import java.lang.Exception import java.text.SimpleDateFormat import java.util.* /** * Created by <NAME> on 26-08-2019, 16:24 */ class SaveImageWorker(context: Context, params: WorkerParameters) : Worker(context, params) { val TAG by lazy { SaveImageWorker::class.java.simpleName } val Title = "Blurred Image" val dateFormatter = SimpleDateFormat( "yyyy.MM.dd 'at' HH:mm:ss z", Locale.getDefault()) override fun doWork(): Result { makeStatusNotification("Saving image to file", applicationContext) val resolver = applicationContext.contentResolver return try { val resourUri = inputData.getString(KEY_IMAGE_URI) // inserting image into permanent location val imageUrl = MediaStore.Images.Media.insertImage(resolver, resourUri, Title, dateFormatter.format(Date())) if (!imageUrl.isNullOrEmpty()) { val output = workDataOf(KEY_IMAGE_URI to imageUrl) Result.success(output) } else { Timber.e("Writing to MediaStore failed") Result.failure() } } catch (exception: Exception) { Result.failure() } } }
0
Kotlin
0
0
b67432b25cc5ea92bf5c1c342f1e1f4b7017365d
1,515
demo_WorkManager
Apache License 2.0
network/src/main/kotlin/PropagationStrategy.kt
jGleitz
239,469,794
false
null
package de.joshuagleitze.transformationnetwork.network import de.joshuagleitze.transformationnetwork.changemetamodel.changeset.ChangeSet interface PropagationStrategy { fun preparePropagation(changeSet: ChangeSet, network: TransformationNetwork): Propagation }
3
Kotlin
0
1
d5d0bd7722abe3260bc204f128337c25c0fb340e
267
transformationnetwork-simulator
MIT License
conduit/src/test/kotlin/com/github/jetli/conduit/ConduitApplicationTests.kt
jetli
236,812,541
false
null
package com.github.jetli.conduit import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class ConduitApplicationTests { @Test fun contextLoads() { } }
0
Kotlin
0
0
3447b15cb7d2f972420ed28a5bd36b6d65c8f980
213
kotlin-spring-realworld-example-app
Apache License 2.0
godot-kotlin/godot-library/src/nativeGen/kotlin/godot/LightOccluder2D.kt
utopia-rise
238,721,773
false
{"Kotlin": 655494, "Shell": 171}
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY! ALL CHANGES TO IT WILL BE OVERWRITTEN ON EACH BUILD package godot import godot.icalls._icall_Long import godot.icalls._icall_OccluderPolygon2D import godot.icalls._icall_Unit_Long import godot.icalls._icall_Unit_Object import godot.internal.utils.getMethodBind import godot.internal.utils.invokeConstructor import kotlin.Long import kotlinx.cinterop.COpaquePointer open class LightOccluder2D : Node2D() { override var lightMask: Long get() { val mb = getMethodBind("LightOccluder2D","get_occluder_light_mask") return _icall_Long(mb, this.ptr) } set(value) { val mb = getMethodBind("LightOccluder2D","set_occluder_light_mask") _icall_Unit_Long(mb, this.ptr, value) } open var occluder: OccluderPolygon2D get() { val mb = getMethodBind("LightOccluder2D","get_occluder_polygon") return _icall_OccluderPolygon2D(mb, this.ptr) } set(value) { val mb = getMethodBind("LightOccluder2D","set_occluder_polygon") _icall_Unit_Object(mb, this.ptr, value) } override fun __new(): COpaquePointer = invokeConstructor("LightOccluder2D", "LightOccluder2D") open fun _polyChanged() { } open fun getOccluderLightMask(): Long { val mb = getMethodBind("LightOccluder2D","get_occluder_light_mask") return _icall_Long( mb, this.ptr) } open fun getOccluderPolygon(): OccluderPolygon2D { val mb = getMethodBind("LightOccluder2D","get_occluder_polygon") return _icall_OccluderPolygon2D( mb, this.ptr) } open fun setOccluderLightMask(mask: Long) { val mb = getMethodBind("LightOccluder2D","set_occluder_light_mask") _icall_Unit_Long( mb, this.ptr, mask) } open fun setOccluderPolygon(polygon: OccluderPolygon2D) { val mb = getMethodBind("LightOccluder2D","set_occluder_polygon") _icall_Unit_Object( mb, this.ptr, polygon) } }
15
Kotlin
16
275
8d51f614df62a97f16e800e6635ea39e7eb1fd62
1,897
godot-kotlin-native
MIT License
app/src/main/java/com/duckduckgo/app/privacydashboard/PrivacyDashboardActivity.kt
tetrafolium
112,419,414
false
null
/* * Copyright (c) 2017 DuckDuckGo * * 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.duckduckgo.app.privacydashboard import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProviders import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.MenuItem import com.duckduckgo.app.browser.R import com.duckduckgo.app.global.DuckDuckGoActivity import com.duckduckgo.app.global.ViewModelFactory import com.duckduckgo.app.sitemonitor.SiteMonitor import kotlinx.android.synthetic.main.activity_privacy_dashboard.* import kotlinx.android.synthetic.main.content_privacy_dashboard.* import javax.inject.Inject class PrivacyDashboardActivity : DuckDuckGoActivity() { @Inject lateinit var viewModelFactory: ViewModelFactory companion object { fun intent(context: Context, monitor: SiteMonitor): Intent { val intent = Intent(context, PrivacyDashboardActivity::class.java) intent.putExtra(SiteMonitor::class.java.name, monitor) return intent } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_privacy_dashboard) configureToolbar() if (savedInstanceState == null) { loadIntentData() } viewModel.liveSiteMonitor.observe(this, Observer<SiteMonitor> { it?.let { render(it) } }) } private val viewModel: PrivacyDashboardViewModel by lazy { ViewModelProviders.of(this, viewModelFactory).get(PrivacyDashboardViewModel::class.java) } private fun configureToolbar() { setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) } private fun loadIntentData() { val siteMonitor = intent.getSerializableExtra(SiteMonitor::class.java.name) as SiteMonitor? if (siteMonitor != null) { viewModel.attachSiteMonitor(siteMonitor) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { super.onBackPressed() return true } } return super.onOptionsItemSelected(item) } private fun render(siteMonitor: SiteMonitor) { domain.text = Uri.parse(siteMonitor.url).host trackerNetworksText.text = getString(R.string.trackerNetworksBlocked, siteMonitor.trackerNetworkCount.toString()) } }
0
Kotlin
0
1
46ff655452bbf1972980ea4296cab43fd3fc74af
3,072
duckduckgo-Android
Apache License 2.0
src/main/kotlin/com/vk/admstorm/ssh/EnterPasswordDialog.kt
VKCOM
454,408,302
false
{"Kotlin": 684856, "Python": 15871, "HTML": 151}
package com.vk.admstorm.ssh import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.ui.JBColor import com.intellij.ui.components.JBCheckBox import com.intellij.ui.components.JBPasswordField import com.intellij.ui.dsl.builder.AlignX import com.intellij.ui.dsl.builder.BottomGap import com.intellij.ui.dsl.builder.TopGap import com.intellij.ui.dsl.builder.panel import com.intellij.util.ui.JBDimension import java.awt.event.KeyAdapter import java.awt.event.KeyEvent import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JPanel class EnterPasswordDialog(project: Project) : DialogWrapper(project, true, IdeModalityType.PROJECT) { companion object { fun requestPassword(project: Project, ifRemember: () -> Unit = {}): String { val dialog = EnterPasswordDialog(project) dialog.showAndGet() if (dialog.isRemember()) { ifRemember() } return dialog.getPassword() } } private var passwordInput = JBPasswordField() private val rememberCheckBox = JBCheckBox("Remember", true) private val warningLabel = JLabel().apply { foreground = JBColor.RED } fun getPassword() = String(passwordInput.password) fun isRemember() = rememberCheckBox.isSelected init { title = "Enter PIN" init() passwordInput.addKeyListener(object : KeyAdapter() { override fun keyReleased(e: KeyEvent) { if (getPassword().any { it in 'А'..'я' || it == 'ё' || it == 'Ё' }) { warningLabel.text = "PIN should contain only English characters and numbers!" } else { warningLabel.text = "" } } }) } override fun getPreferredFocusedComponent() = passwordInput override fun createSouthAdditionalPanel(): JPanel { return panel { row { cell(rememberCheckBox) } } } override fun createCenterPanel(): JComponent { return panel { row { label("Enter PIN for Yubikey:") }.topGap(TopGap.NONE) row { cell(passwordInput) .align(AlignX.FILL) }.bottomGap(BottomGap.NONE) row{ cell(warningLabel) }.bottomGap(BottomGap.NONE) }.apply { preferredSize = JBDimension(300, -1) } } }
37
Kotlin
3
17
5c30f40cd66b64cc40d487246190c7adbca09674
2,529
admstorm
MIT License
app/src/main/java/com/mrebollob/leitnerbox/domain/extension/DateExtensions.kt
mrebollob
155,557,246
false
null
package com.mrebollob.leitnerbox.domain.extension import com.mrebollob.leitnerbox.domain.model.Hour import java.util.* import java.util.Calendar.HOUR const val ONE_DAY_MILLIS: Long = 86400000 fun Date.getDaysBetween(endDate: Date): Int = with(this) { val todayCalendar = Calendar.getInstance() todayCalendar.time = this todayCalendar.set(HOUR, 0) todayCalendar.set(HOUR, 0) val different = endDate.time - this.time val secondsInMilli: Long = 1000 val minutesInMilli = secondsInMilli * 60 val hoursInMilli = minutesInMilli * 60 val daysInMilli = hoursInMilli * 24 val elapsedDays = different / daysInMilli return elapsedDays.toInt() } fun Hour.getCalendarForToday(): Calendar { val calendar = Calendar.getInstance() calendar.set(Calendar.HOUR_OF_DAY, this.hour) calendar.set(Calendar.MINUTE, this.minute) calendar.set(Calendar.SECOND, 0) return calendar }
0
Kotlin
0
2
3e3bfef678dd6e2daff7e6c67ec7dfc0b47a3f81
928
leitner-box
Apache License 2.0
security/src/main/java/pm/gnosis/svalinn/security/db/Encrypted.kt
vaporyorg
371,078,482
true
{"Kotlin": 414660, "Java": 18999, "Shell": 470}
package pm.gnosis.svalinn.security.db import android.arch.persistence.room.TypeConverter import pm.gnosis.svalinn.security.EncryptionManager import pm.gnosis.utils.utf8String private interface Encrypted<out T> { fun value(encryptionManager: EncryptionManager): T interface Creator<T> { fun create(encryptionManager: EncryptionManager, value: T): Encrypted<T> } interface Converter<W : Encrypted<Any>> { fun toStorage(wrapper: W): String fun fromStorage(value: String): W } } class EncryptedByteArray private constructor(private val encryptedValue: String) : Encrypted<ByteArray> { override fun value(encryptionManager: EncryptionManager): ByteArray { return encryptionManager.decrypt(EncryptionManager.CryptoData.fromString(encryptedValue)) } companion object : Encrypted.Creator<ByteArray> { override fun create(encryptionManager: EncryptionManager, value: ByteArray): EncryptedByteArray { return EncryptedByteArray(encryptionManager.encrypt(value).toString()) } } class Converter : Encrypted.Converter<EncryptedByteArray> { @TypeConverter override fun toStorage(wrapper: EncryptedByteArray): String { return wrapper.encryptedValue } @TypeConverter override fun fromStorage(value: String): EncryptedByteArray { return EncryptedByteArray(value) } } } class EncryptedString private constructor(private val encryptedValue: String) : Encrypted<String> { override fun value(encryptionManager: EncryptionManager): String { return encryptionManager.decrypt(EncryptionManager.CryptoData.fromString(encryptedValue)).utf8String() } companion object : Encrypted.Creator<String> { override fun create(encryptionManager: EncryptionManager, value: String): EncryptedString { return EncryptedString(encryptionManager.encrypt(value.toByteArray()).toString()) } } class Converter : Encrypted.Converter<EncryptedString> { @TypeConverter override fun toStorage(wrapper: EncryptedString): String { return wrapper.encryptedValue } @TypeConverter override fun fromStorage(value: String): EncryptedString { return EncryptedString(value) } } }
0
Kotlin
0
0
68371db16857c7420697ed1a54d1f074c7fd4f8e
2,342
svalinn-kotlin
MIT License
key-manager-grpc/src/main/kotlin/br/com/zup/edu/services/DetalhaChaveSistemaExternoService.kt
Werliney
385,941,758
true
{"Kotlin": 57013}
package br.com.zup.edu.services import br.com.zup.edu.chavePix.TipoContaData import br.com.zup.edu.chavePix.detalhaChaveSistemaExterno.DetalhaChaveSistemaExternoRequest import br.com.zup.edu.chavePix.detalhaChaveSistemaExterno.DetalhaChaveSistemaExternoResponse import br.com.zup.edu.exceptions.ChaveNaoExistenteException import br.com.zup.edu.repository.ChavePixRepository import br.com.zup.edu.servicosExternos.AccountType import br.com.zup.edu.servicosExternos.BcbClient import io.micronaut.http.HttpStatus import io.micronaut.validation.Validated import javax.inject.Singleton import javax.validation.Valid @Singleton @Validated class DetalhaChaveSistemaExternoService( val chavePixRepository: ChavePixRepository, val bcbClient: BcbClient ) { fun consulta(@Valid detalhaChave: DetalhaChaveSistemaExternoRequest): DetalhaChaveSistemaExternoResponse { val chave = chavePixRepository.findByValorChave(detalhaChave.chave) if (chave.isEmpty) { throw ChaveNaoExistenteException("Fodeu aqui") } if (chave.isEmpty) { val listaChaveResponse = bcbClient.consultaChave(detalhaChave.chave) if (listaChaveResponse.status != HttpStatus.OK) { throw ChaveNaoExistenteException("A chave com o valor: ${detalhaChave.chave} não existe no Banco Central do Brasil (BCB)") } val dados = listaChaveResponse.body() return DetalhaChaveSistemaExternoResponse( dados.keyType, dados.key, dados.bankAccount.participant, dados.bankAccount.branch, dados.bankAccount.accountNumber, tipoConta = if (dados.bankAccount.accountType == AccountType.CACC) TipoContaData.CONTA_CORRENTE else TipoContaData.CONTA_POUPANCA, dados.owner.name, dados.owner.taxIdNumber, dados.createdAt ) } val dadosChave = chave.get() val response = bcbClient.consultaChave(detalhaChave.chave) if (response.status != HttpStatus.OK) { throw ChaveNaoExistenteException("A chave com o valor: ${detalhaChave.chave} não existe no Banco Central do Brasil (BCB)") } val data = response.body() return DetalhaChaveSistemaExternoResponse( dadosChave.tipoChave, dadosChave.valorChave, dadosChave.donoDaConta.nomeInstituicao, dadosChave.donoDaConta.agencia, dadosChave.donoDaConta.numeroConta, dadosChave.tipoConta, dadosChave.donoDaConta.nome, dadosChave.donoDaConta.cpf, data.createdAt ) } }
0
Kotlin
0
0
6fe67ad78624a4ff11756160c0e5408fd40388bb
2,714
orange-talents-05-template-pix-keymanager-grpc
Apache License 2.0
vk-api/src/main/kotlin/name/alatushkin/api/vk/generated/friends/methods/FriendsGetMutualMethodManyUIds.kt
alatushkin
156,866,851
false
null
package name.alatushkin.api.vk.generated.friends.methods import com.fasterxml.jackson.core.type.TypeReference import name.alatushkin.api.vk.VkMethod import name.alatushkin.api.vk.api.VkSuccess import name.alatushkin.api.vk.generated.friends.MutualFriend /** * Returns a list of user IDs of the mutual friends of two users. * * [https://vk.com/dev/friends.getMutual] * @property [source_uid] ID of the user whose friends will be checked against the friends of the user specified in 'target_uid'. * @property [target_uid] ID of the user whose friends will be checked against the friends of the user specified in 'source_uid'. * @property [target_uids] IDs of the users whose friends will be checked against the friends of the user specified in 'source_uid'. * @property [order] Sort order: 'random' — random order * @property [count] Number of mutual friends to return. * @property [offset] Offset needed to return a specific subset of mutual friends. */ class FriendsGetMutualMethodManyUIds() : VkMethod<Array<MutualFriend>>( "friends.getMutual", HashMap() ) { var sourceUid: Long? by props var targetUid: Long? by props var targetUids: Array<Long>? by props var order: String? by props var count: Long? by props var offset: Long? by props constructor( sourceUid: Long? = null, targetUid: Long? = null, targetUids: Array<Long>? = null, order: String? = null, count: Long? = null, offset: Long? = null ) : this() { this.sourceUid = sourceUid this.targetUid = targetUid this.targetUids = targetUids this.order = order this.count = count this.offset = offset } fun setSourceUid(sourceUid: Long): FriendsGetMutualMethodManyUIds { this.sourceUid = sourceUid return this } fun setTargetUid(targetUid: Long): FriendsGetMutualMethodManyUIds { this.targetUid = targetUid return this } fun setTargetUids(targetUids: Array<Long>): FriendsGetMutualMethodManyUIds { this.targetUids = targetUids return this } fun setOrder(order: String): FriendsGetMutualMethodManyUIds { this.order = order return this } fun setCount(count: Long): FriendsGetMutualMethodManyUIds { this.count = count return this } fun setOffset(offset: Long): FriendsGetMutualMethodManyUIds { this.offset = offset return this } override val classRef = FriendsGetMutualMethodManyUIds.classRef companion object { val classRef = object : TypeReference<VkSuccess<Array<MutualFriend>>>() {} } }
2
Kotlin
3
10
123bd61b24be70f9bbf044328b98a3901523cb1b
2,678
kotlin-vk-api
MIT License
app/src/main/java/com/tiixel/periodictableprofessor/ui/statistics/StatisticsFragment.kt
remiberthoz
135,941,479
false
{"Kotlin": 213503}
package com.tiixel.periodictableprofessor.ui.statistics import android.arch.lifecycle.ViewModelProvider import android.arch.lifecycle.ViewModelProviders import android.content.Context import android.graphics.Color import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.github.mikephil.charting.components.Legend import com.github.mikephil.charting.components.XAxis import com.tiixel.periodictableprofessor.R import com.tiixel.periodictableprofessor.presentation.base.MviView import com.tiixel.periodictableprofessor.presentation.home.statistics.StatisticsIntent import com.tiixel.periodictableprofessor.presentation.home.statistics.StatisticsViewModel import com.tiixel.periodictableprofessor.presentation.home.statistics.StatisticsViewState import com.tiixel.periodictableprofessor.ui.statistics.adapter.ChartAdapter import com.tiixel.periodictableprofessor.ui.statistics.model.ChartModel import dagger.android.support.AndroidSupportInjection import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.content_statistics.* import javax.inject.Inject class StatisticsFragment : Fragment(), MviView<StatisticsIntent, StatisticsViewState> { // Used to manage the data flow lifecycle and avoid memory leak private val disposable = CompositeDisposable() // View model @Inject lateinit var viewModelFactory: ViewModelProvider.Factory private lateinit var viewModel: StatisticsViewModel //<editor-fold desc="Life cycle methods"> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel = ViewModelProviders.of(this, viewModelFactory) .get(StatisticsViewModel::class.java) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.content_statistics, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Subscribe to the ViewModel and call render for every emitted state disposable.add(viewModel.states().subscribe(this::render)) // Pass the UI's intents to the ViewModel viewModel.processIntents(intents()) styleChart() } override fun onAttach(context: Context?) { AndroidSupportInjection.inject(this) super.onAttach(context) } override fun onDestroy() { super.onDestroy() disposable.dispose() } //</editor-fold> //<editor-fold desc="MVI methods"> override fun intents(): Observable<StatisticsIntent> { return Observable.just(StatisticsIntent.InitialIntent) } override fun render(state: StatisticsViewState) { ChartAdapter.setDataOnChart( stats_chart, ChartModel("New on day", state.dataItemsNewPerDay, Color.parseColor("#ffff00")), ChartModel("Rev on day", state.dataReviewsPerDay, Color.parseColor("#e0b189")), ChartModel("Known at end of day", state.dataKnownReviewablesPerDay, Color.parseColor("#ab64c7")), ChartModel("Due before end of day", state.dataReviewsDuePerDay, Color.parseColor("#0000ff")) ) } //</editor-fold> private fun styleChart() { stats_chart.apply { xAxis.position = XAxis.XAxisPosition.BOTTOM axisLeft.granularity = 1f axisLeft.isGranularityEnabled = true xAxis.setDrawGridLines(false) axisRight.isEnabled = false xAxis.labelRotationAngle = -90f legend.verticalAlignment = Legend.LegendVerticalAlignment.TOP } } }
0
Kotlin
0
0
c9b878171db42d7ed01852f144f32c35acb91816
3,835
periodic-table-professor
MIT License
publish-plugin/src/main/java/com/dorck/android/upload/extensions/PublicationExtensions.kt
Moosphan
524,811,058
false
{"Kotlin": 48498, "Java": 135}
package com.dorck.android.upload.extensions import org.gradle.api.publish.maven.MavenPublication import org.gradle.api.tasks.TaskProvider import org.gradle.util.GradleVersion internal fun MavenPublication.withSourcesJar(artifactTask: TaskProvider<*>?) { artifactTask?.let { if (GradleVersion.current() >= GRADLE_6_6) { artifact(it) } else { artifact(it.get()) } } } internal fun MavenPublication.withJavadocJar(artifactTask: TaskProvider<*>?) { artifactTask?.let { if (GradleVersion.current() >= GRADLE_6_6) { artifact(it) } else { artifact(it.get()) } } } internal val GRADLE_6_6 = GradleVersion.version("6.6")
0
Kotlin
0
10
8cd5aa7ab73269203e2e16e7d89594bea410f2e7
728
component-publisher
Apache License 2.0
src/main/kotlin/com/github/thetric/iliasdownloader/connector/exception/IliasException.kt
thetric
69,231,123
false
null
package com.github.thetric.iliasdownloader.connector.exception /** * Base class for all Ilias exceptions. */ open class IliasException : RuntimeException { constructor(message: String) : super(message) constructor(message: String, t: Throwable) : super(message, t) constructor(t: Throwable) : super(t) }
17
Kotlin
0
13
a32370fb310db85fa2f1c6f97f076f63406fde0f
321
ilias-downloader-cli
MIT License
sample-simple-app-without-plugins/src/main/kotlin/com/damianchodorek/sample_simple_app_without_plugins/controller/MakeApiCallControllerImpl.kt
DamianChodorek
129,797,476
false
null
package com.damianchodorek.sample_simple_app_without_plugins.controller import com.damianchodorek.renshi.controller.base.BaseController import com.damianchodorek.sample_simple_app_without_plugins.action.FinishingApiCallAction import com.damianchodorek.sample_simple_app_without_plugins.action.MakingApiCallAction import com.damianchodorek.sample_simple_app_without_plugins.controller.interactor.MakeApiCallInteractorImpl import com.damianchodorek.sample_simple_app_without_plugins.store.state.MainActivityState import com.damianchodorek.sample_simple_app_without_plugins.view.MakeApiCallFragment import io.reactivex.rxkotlin.subscribeBy import io.reactivex.subjects.PublishSubject /** * Handles clicks from [com.damianchodorek.sample_simple_app_without_plugins.view.MakeApiCallFragment.makeApiCallClicks] * and starts api call. * @param interactor makes fakt api call. * @param log error logger. * @author <NAME> */ class MakeApiCallControllerImpl( private val interactor: MakeApiCallInteractorImpl = MakeApiCallInteractorImpl(), private val log: (Throwable) -> Unit = { it.printStackTrace() } ) : BaseController<MakeApiCallFragment, MainActivityState>() { private val makeApiCallRequests = PublishSubject.create<Unit>() init { // Stream is created in constructor because it should survive detaching from view. // We use disposeOnDestroy() to dispose stream when presenter is destroyed permanently. disposeOnDestroy( makeApiCallRequests .flatMapCompletable { store .dispatch(MakingApiCallAction()) .andThen(interactor.makeFakeApiCall()) .andThen(store.dispatch(FinishingApiCallAction())) } .subscribeBy( onError = { log(it) } ) ) } override fun onAttachPlugin() { // We use disposeOnDetach() to dispose stream every time plugin is detached. disposeOnDetach( plugin!! .makeApiCallClicks .subscribeBy( onNext = { makeApiCallRequests.onNext(Unit) }, onError = { log(it) } ) ) } }
0
Kotlin
0
2
c72df09782cdb9483bbde3503a167f2d5bc760b4
2,420
renshi-redux
Apache License 2.0
service/src/main/kotlin/cs346/whiteboard/service/repositories/UserAccessRepository.kt
york-wei
634,461,691
false
null
/* * Copyright (c) 2023 <NAME>, <NAME>, <NAME>, <NAME> */ package cs346.whiteboard.service.repositories import cs346.whiteboard.service.models.UserAccess import cs346.whiteboard.service.models.UserLogin import cs346.whiteboard.service.models.WhiteboardTable import org.springframework.data.jpa.repository.Query import org.springframework.data.repository.CrudRepository interface UserAccessRepository : CrudRepository<UserAccess, Long> { fun findByUserAndWhiteboard(user: UserLogin, whiteboard: WhiteboardTable): UserAccess? fun findByUser(user: UserLogin): List<UserAccess> fun findByWhiteboard(whiteboard: WhiteboardTable): List<UserAccess> @Query("SELECT ua FROM UserAccess ua WHERE ua.user = :user AND ua.accessLevel = 'WRITE_ACCESS'") fun findWriteAccessWhiteboardsForUser(user: UserLogin): List<UserAccess> }
0
Kotlin
0
1
40cfaaf91b77470b53f0278abe456de5059f0a48
862
whiteboard
MIT License
app/src/main/java/com/example/androiddevchallenge/ui/screens/login/LoginScreen.kt
qamarelsafadi
514,434,953
false
{"Kotlin": 18476}
package com.example.androiddevchallenge.ui.screens.login import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Send import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import com.example.androiddevchallenge.R import com.example.androiddevchallenge.ui.components.EditText import com.example.androiddevchallenge.ui.components.ImageWithBackground import com.example.androiddevchallenge.ui.components.TextWithBackground import com.example.androiddevchallenge.ui.theme.columnModifier import com.example.androiddevchallenge.ui.theme.purple200 import com.example.androiddevchallenge.ui.theme.textStyle @Composable fun LoginScreen() { Surface(color = MaterialTheme.colors.background) { Column( columnModifier, horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, ) { ImageWithBackground( painter = painterResource(id = R.drawable.logo), backgroundDrawableResId = R.drawable.bg_art ) Text( text = stringResource(R.string.sign_in), style = textStyle, fontWeight = FontWeight.Bold ) Spacer(modifier = Modifier.height(48.dp)) val (title, setTitle) = remember { mutableStateOf("") } EditText( title, setTitle, stringResource(R.string.temp_user), R.drawable.ic_person_outline_24px, false ) Spacer(modifier = Modifier.height(10.dp)) val (password, setPassword) = remember { mutableStateOf("") } EditText( password, setPassword, stringResource(R.string.password), R.drawable.ic_lock_outline_24px, true ) Spacer(modifier = Modifier.height(22.dp)) Button( onClick = { }, Modifier.defaultMinSize( minWidth = 280.dp, minHeight = (60.dp) ), colors = ButtonDefaults.buttonColors(backgroundColor = purple200), shape = RoundedCornerShape(50), contentPadding = PaddingValues( start = 20.dp, top = 12.dp, end = 20.dp, bottom = 12.dp ) ) { Icon( Icons.Filled.Send, contentDescription = "send", modifier = Modifier.size(ButtonDefaults.IconSize), tint = Color.White ) } Spacer(modifier = Modifier.weight(1f)) TextWithBackground( stringResource(R.string.new_account_lbl), R.drawable.footer_art, ) } } }
0
Kotlin
0
0
aaf02537916c0618a8a00fb60f5180a09fa286ce
3,475
login-compose-challenge
Apache License 2.0
src/test/kotlin/uk/gov/justice/digital/assessments/services/AssessmentServiceCompleteTest.kt
uk-gov-mirror
356,783,294
true
{"Kotlin": 334511, "JavaScript": 24640, "Mustache": 4105, "Dockerfile": 1313, "Shell": 181}
package uk.gov.justice.digital.assessments.services import io.mockk.every import io.mockk.junit5.MockKExtension import io.mockk.mockk import io.mockk.verify import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.extension.ExtendWith import uk.gov.justice.digital.assessments.jpa.entities.AssessmentEntity import uk.gov.justice.digital.assessments.jpa.entities.AssessmentEpisodeEntity import uk.gov.justice.digital.assessments.jpa.entities.AssessmentType import uk.gov.justice.digital.assessments.jpa.entities.SubjectEntity import uk.gov.justice.digital.assessments.jpa.repositories.AssessmentRepository import uk.gov.justice.digital.assessments.jpa.repositories.EpisodeRepository import uk.gov.justice.digital.assessments.jpa.repositories.SubjectRepository import uk.gov.justice.digital.assessments.restclient.AssessmentUpdateRestClient import uk.gov.justice.digital.assessments.restclient.CourtCaseRestClient import uk.gov.justice.digital.assessments.restclient.assessmentupdateapi.UpdateAssessmentAnswersResponseDto import uk.gov.justice.digital.assessments.restclient.assessmentupdateapi.ValidationErrorDto import uk.gov.justice.digital.assessments.services.exceptions.EntityNotFoundException import java.time.LocalDateTime import java.util.UUID @ExtendWith(MockKExtension::class) @DisplayName("Assessment Service Tests") class AssessmentServiceCompleteTest { private val assessmentRepository: AssessmentRepository = mockk() private val episodeRepository: EpisodeRepository = mockk() private val subjectRepository: SubjectRepository = mockk() private val questionService: QuestionService = mockk() private val courtCaseRestClient: CourtCaseRestClient = mockk() private val episodeService: EpisodeService = mockk() private val offenderService: OffenderService = mockk() private val assessmentUpdateRestClient: AssessmentUpdateRestClient = mockk() private val assessmentsService = AssessmentService( assessmentRepository, episodeRepository, subjectRepository, questionService, episodeService, courtCaseRestClient, assessmentUpdateRestClient, offenderService ) @Nested @DisplayName("completing assessments") inner class CompletingAssessments { @Test fun `close episode`() { val assessment = assessmentEntity() every { assessmentRepository.findByAssessmentUuid(any()) } returns assessment every { episodeRepository.save(any()) } returns assessment.episodes[0] every { assessmentUpdateRestClient.completeAssessment(9999, 7777, AssessmentType.SHORT_FORM_PSR) } returns UpdateAssessmentAnswersResponseDto(7777) val episode = assessmentsService.closeCurrentEpisode(UUID.fromString("7b4de6d5-4488-4c29-a909-7d3fdf15393d")) verify(exactly = 1) { episodeRepository.save(any()) } verify(exactly = 1) { assessmentUpdateRestClient.completeAssessment(any(), any(), any(), any()) } assertThat(episode.ended).isEqualToIgnoringMinutes(LocalDateTime.now()) } @Test fun `close episode for assessment with no episodes throws exception`() { every { assessmentRepository.findByAssessmentUuid(any()) } returns assessmentWithNoEpisodeEntity() assertThrows<EntityNotFoundException> { assessmentsService.closeCurrentEpisode(UUID.fromString("7b4de6d5-4488-4c29-a909-7d3fdf15393d")) } verify(exactly = 0) { episodeRepository.save(any()) } verify(exactly = 0) { assessmentUpdateRestClient.completeAssessment(any(), any(), any(), any()) } } } @Test fun `close episode with oasys errors does not close episode`() { val assessment = assessmentEntity() every { assessmentRepository.findByAssessmentUuid(any()) } returns assessment every { episodeRepository.save(any()) } returns assessment.episodes[0] every { assessmentUpdateRestClient.completeAssessment(9999, 7777, AssessmentType.SHORT_FORM_PSR) } returns oasysAssessmentError() val episode = assessmentsService.closeCurrentEpisode(UUID.fromString("7b4de6d5-4488-4c29-a909-7d3fdf15393d")) verify(exactly = 0) { episodeRepository.save(any()) } verify(exactly = 1) { assessmentUpdateRestClient.completeAssessment(any(), any(), any(), any()) } assertThat(episode.ended).isNull() } private fun assessmentEntity(): AssessmentEntity { val subject = SubjectEntity(oasysOffenderPk = 9999) val episodes = mutableListOf<AssessmentEpisodeEntity>() val assessment = AssessmentEntity( assessmentUuid = UUID.fromString("7b4de6d5-4488-4c29-a909-7d3fdf15393d"), assessmentId = 1, episodes = episodes, subject_ = mutableListOf(subject) ) episodes.add( AssessmentEpisodeEntity( episodeUuid = UUID.fromString("669cdd10-1061-42ec-90d4-e34baab19566"), episodeId = 1234, assessment = assessment, assessmentType = AssessmentType.SHORT_FORM_PSR, changeReason = "Change of Circs 2", oasysSetPk = 7777, ) ) return assessment } private fun assessmentWithNoEpisodeEntity(): AssessmentEntity { val subject = SubjectEntity(oasysOffenderPk = 9999) val episodes = mutableListOf<AssessmentEpisodeEntity>() return AssessmentEntity( assessmentUuid = UUID.fromString("7b4de6d5-4488-4c29-a909-7d3fdf15393d"), assessmentId = 1, episodes = episodes, subject_ = mutableListOf(subject) ) } private fun oasysAssessmentError(): UpdateAssessmentAnswersResponseDto { return UpdateAssessmentAnswersResponseDto( 7777, setOf( ValidationErrorDto("ASSESSMENT", null, "Q1", "OOPS", "NO", false) ) ) } }
0
Kotlin
0
0
708a25169cd7b73075bb996ea379fe982d6f5649
5,781
ministryofjustice.hmpps-assessments-api
MIT License
godot-kotlin/godot-library/src/nativeGen/kotlin/godot/MultiMesh.kt
utopia-rise
238,721,773
false
{"Kotlin": 655494, "Shell": 171}
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY! ALL CHANGES TO IT WILL BE OVERWRITTEN ON EACH BUILD package godot import godot.MultiMesh import godot.core.AABB import godot.core.Color import godot.core.PoolColorArray import godot.core.PoolRealArray import godot.core.PoolVector2Array import godot.core.PoolVector3Array import godot.core.Transform import godot.core.Transform2D import godot.icalls._icall_AABB import godot.icalls._icall_Color_Long import godot.icalls._icall_Long import godot.icalls._icall_Mesh import godot.icalls._icall_Transform2D_Long import godot.icalls._icall_Transform_Long import godot.icalls._icall_Unit_Long import godot.icalls._icall_Unit_Long_Color import godot.icalls._icall_Unit_Long_Transform import godot.icalls._icall_Unit_Long_Transform2D import godot.icalls._icall_Unit_Object import godot.icalls._icall_Unit_PoolRealArray import godot.internal.utils.getMethodBind import godot.internal.utils.invokeConstructor import kotlin.Long import kotlin.NotImplementedError import kotlinx.cinterop.COpaquePointer open class MultiMesh : Resource() { open var colorFormat: Long get() { val mb = getMethodBind("MultiMesh","get_color_format") return _icall_Long(mb, this.ptr) } set(value) { val mb = getMethodBind("MultiMesh","set_color_format") _icall_Unit_Long(mb, this.ptr, value) } open var customDataFormat: Long get() { val mb = getMethodBind("MultiMesh","get_custom_data_format") return _icall_Long(mb, this.ptr) } set(value) { val mb = getMethodBind("MultiMesh","set_custom_data_format") _icall_Unit_Long(mb, this.ptr, value) } open var instanceCount: Long get() { val mb = getMethodBind("MultiMesh","get_instance_count") return _icall_Long(mb, this.ptr) } set(value) { val mb = getMethodBind("MultiMesh","set_instance_count") _icall_Unit_Long(mb, this.ptr, value) } open var mesh: Mesh get() { val mb = getMethodBind("MultiMesh","get_mesh") return _icall_Mesh(mb, this.ptr) } set(value) { val mb = getMethodBind("MultiMesh","set_mesh") _icall_Unit_Object(mb, this.ptr, value) } open var transformFormat: Long get() { val mb = getMethodBind("MultiMesh","get_transform_format") return _icall_Long(mb, this.ptr) } set(value) { val mb = getMethodBind("MultiMesh","set_transform_format") _icall_Unit_Long(mb, this.ptr, value) } open var visibleInstanceCount: Long get() { val mb = getMethodBind("MultiMesh","get_visible_instance_count") return _icall_Long(mb, this.ptr) } set(value) { val mb = getMethodBind("MultiMesh","set_visible_instance_count") _icall_Unit_Long(mb, this.ptr, value) } override fun __new(): COpaquePointer = invokeConstructor("MultiMesh", "MultiMesh") open fun _getColorArray(): PoolColorArray { throw NotImplementedError("_get_color_array is not implemented for MultiMesh") } open fun _getCustomDataArray(): PoolColorArray { throw NotImplementedError("_get_custom_data_array is not implemented for MultiMesh") } open fun _getTransform2dArray(): PoolVector2Array { throw NotImplementedError("_get_transform_2d_array is not implemented for MultiMesh") } open fun _getTransformArray(): PoolVector3Array { throw NotImplementedError("_get_transform_array is not implemented for MultiMesh") } open fun _setColorArray(arg0: PoolColorArray) { } open fun _setCustomDataArray(arg0: PoolColorArray) { } open fun _setTransform2dArray(arg0: PoolVector2Array) { } open fun _setTransformArray(arg0: PoolVector3Array) { } open fun getAabb(): AABB { val mb = getMethodBind("MultiMesh","get_aabb") return _icall_AABB( mb, this.ptr) } open fun getColorFormat(): MultiMesh.ColorFormat { val mb = getMethodBind("MultiMesh","get_color_format") return MultiMesh.ColorFormat.from( _icall_Long( mb, this.ptr)) } open fun getCustomDataFormat(): MultiMesh.CustomDataFormat { val mb = getMethodBind("MultiMesh","get_custom_data_format") return MultiMesh.CustomDataFormat.from( _icall_Long( mb, this.ptr)) } open fun getInstanceColor(instance: Long): Color { val mb = getMethodBind("MultiMesh","get_instance_color") return _icall_Color_Long( mb, this.ptr, instance) } open fun getInstanceCount(): Long { val mb = getMethodBind("MultiMesh","get_instance_count") return _icall_Long( mb, this.ptr) } open fun getInstanceCustomData(instance: Long): Color { val mb = getMethodBind("MultiMesh","get_instance_custom_data") return _icall_Color_Long( mb, this.ptr, instance) } open fun getInstanceTransform(instance: Long): Transform { val mb = getMethodBind("MultiMesh","get_instance_transform") return _icall_Transform_Long( mb, this.ptr, instance) } open fun getInstanceTransform2d(instance: Long): Transform2D { val mb = getMethodBind("MultiMesh","get_instance_transform_2d") return _icall_Transform2D_Long( mb, this.ptr, instance) } open fun getMesh(): Mesh { val mb = getMethodBind("MultiMesh","get_mesh") return _icall_Mesh( mb, this.ptr) } open fun getTransformFormat(): MultiMesh.TransformFormat { val mb = getMethodBind("MultiMesh","get_transform_format") return MultiMesh.TransformFormat.from( _icall_Long( mb, this.ptr)) } open fun getVisibleInstanceCount(): Long { val mb = getMethodBind("MultiMesh","get_visible_instance_count") return _icall_Long( mb, this.ptr) } open fun setAsBulkArray(array: PoolRealArray) { val mb = getMethodBind("MultiMesh","set_as_bulk_array") _icall_Unit_PoolRealArray( mb, this.ptr, array) } open fun setColorFormat(format: Long) { val mb = getMethodBind("MultiMesh","set_color_format") _icall_Unit_Long( mb, this.ptr, format) } open fun setCustomDataFormat(format: Long) { val mb = getMethodBind("MultiMesh","set_custom_data_format") _icall_Unit_Long( mb, this.ptr, format) } open fun setInstanceColor(instance: Long, color: Color) { val mb = getMethodBind("MultiMesh","set_instance_color") _icall_Unit_Long_Color( mb, this.ptr, instance, color) } open fun setInstanceCount(count: Long) { val mb = getMethodBind("MultiMesh","set_instance_count") _icall_Unit_Long( mb, this.ptr, count) } open fun setInstanceCustomData(instance: Long, customData: Color) { val mb = getMethodBind("MultiMesh","set_instance_custom_data") _icall_Unit_Long_Color( mb, this.ptr, instance, customData) } open fun setInstanceTransform(instance: Long, transform: Transform) { val mb = getMethodBind("MultiMesh","set_instance_transform") _icall_Unit_Long_Transform( mb, this.ptr, instance, transform) } open fun setInstanceTransform2d(instance: Long, transform: Transform2D) { val mb = getMethodBind("MultiMesh","set_instance_transform_2d") _icall_Unit_Long_Transform2D( mb, this.ptr, instance, transform) } open fun setMesh(mesh: Mesh) { val mb = getMethodBind("MultiMesh","set_mesh") _icall_Unit_Object( mb, this.ptr, mesh) } open fun setTransformFormat(format: Long) { val mb = getMethodBind("MultiMesh","set_transform_format") _icall_Unit_Long( mb, this.ptr, format) } open fun setVisibleInstanceCount(count: Long) { val mb = getMethodBind("MultiMesh","set_visible_instance_count") _icall_Unit_Long( mb, this.ptr, count) } enum class TransformFormat( id: Long ) { TRANSFORM_2D(0), TRANSFORM_3D(1); val id: Long init { this.id = id } companion object { fun from(value: Long) = values().single { it.id == value } } } enum class CustomDataFormat( id: Long ) { CUSTOM_DATA_NONE(0), CUSTOM_DATA_8BIT(1), CUSTOM_DATA_FLOAT(2); val id: Long init { this.id = id } companion object { fun from(value: Long) = values().single { it.id == value } } } enum class ColorFormat( id: Long ) { COLOR_NONE(0), COLOR_8BIT(1), COLOR_FLOAT(2); val id: Long init { this.id = id } companion object { fun from(value: Long) = values().single { it.id == value } } } companion object }
15
Kotlin
16
275
8d51f614df62a97f16e800e6635ea39e7eb1fd62
8,268
godot-kotlin-native
MIT License
app/src/main/java/com/project/valhallastudio/starwars/adapters/resources/PlanetAdapter.kt
codejunk1e
270,861,577
false
null
package com.project.valhallastudio.starwars.adapters.resources import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.paging.PagedListAdapter import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.project.valhallastudio.starwars.R import com.project.valhallastudio.starwars.models.responsemodels.FilmResponse import com.project.valhallastudio.starwars.models.responsemodels.PlanetResponse import com.project.valhallastudio.starwars.models.responsemodels.Response /** * @author robin * Created on 6/3/20 */ class PlanetAdapter: PagedListAdapter< PlanetResponse, PlanetAdapter.ViewHolder>( object: DiffUtil.ItemCallback<PlanetResponse> (){ override fun areItemsTheSame(oldItem: PlanetResponse, newItem: PlanetResponse): Boolean { return oldItem.url == newItem.url } override fun areContentsTheSame(oldItem: PlanetResponse, newItem: PlanetResponse): Boolean { return oldItem.title == newItem.title } } ) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item, parent, false)) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val response: Response? = getItem(position); if (response != null){ holder.bind(response, position) } } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind( item: Response, position: Int ) { val itemImage = itemView.findViewById<ImageView>(R.id.itemImage) val itemText = itemView.findViewById<TextView>(R.id.itemTitle) itemText.text = item.name Glide.with(itemView.context).apply { when (position) { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18 -> load("https://starwars-visualguide.com/assets/img/planets/${position + 1}.jpg") 21-> load("https://starwars-visualguide.com/assets/img/planets/21.jpg") else -> load((R.drawable.big_placeholder)) } .error(R.drawable.big_placeholder) .override(350, 400) .into(itemImage) } } } }
2
Kotlin
0
6
c05aedc83d0e4cccf36ea8d8aeab8cf699bba5d5
2,544
StarWars
MIT License
playablerecyclerview/src/main/java/happy/mjstudio/playablerecyclerview/util/SnapUtil.kt
mj-studio-library
235,269,205
false
null
package happy.mjstudio.playablerecyclerview.util import androidx.recyclerview.widget.PagerSnapHelper import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.SnapHelper /** * Created by mj on 21, January, 2020 */ fun RecyclerView.attachSnapHelper(snapHelper: SnapHelper = PagerSnapHelper()) { snapHelper.attachToRecyclerView(this) }
0
Kotlin
0
1
26840025dcca4b14949d45648fc428da7d802fb7
368
PlayableRecyclerView
Apache License 2.0
virtusize-core/src/main/java/com/virtusize/android/data/remote/StoreProductAdditionalInfo.kt
virtusize
173,900,278
false
{"Kotlin": 433690, "Java": 9310, "Shell": 265}
package com.virtusize.android.data.remote /** * This class represents the additional info of a store product * @param brand the brand name * @param gender the gender for the product * @param sizes the size list of the product * @param modelInfo the model info * @param fit the general fit key * @param style the store product style * @param brandSizing the brand sizing info * @see ProductSize * @see BrandSizing */ data class StoreProductAdditionalInfo( val brand: String, val gender: String?, val sizes: Set<ProductSize>, val modelInfo: Map<String, Any>?, val fit: String?, val style: String?, val brandSizing: BrandSizing? )
1
Kotlin
2
9
8b862e7e1d90fa683473014162a99e4e22b6d137
668
integration_android
MIT License
feature-dashboard/src/main/java/com/mukul/jan/primer/feature/dashboard/DashboardScreenUtils.kt
Mukuljangir372
600,396,968
false
{"Kotlin": 140180}
package com.mukul.jan.primer.feature.dashboard import com.mu.jan.primer.common.ui.compose.BottomNavItem import com.mukul.jan.primer.base.ui.R object DashboardScreenUtils { object BottomNav { val chat = BottomNavItem( id = 1, label = "chats", icon = null, drawable = R.drawable.baseline_chat_24 ) val friends = BottomNavItem( id = 2, label = "friends", icon = null, drawable = R.drawable.baseline_groups_24 ) val files = BottomNavItem( id = 3, label = "files", icon = null, drawable = R.drawable.baseline_cloud_24 ) val notifications = BottomNavItem( id = 4, label = "notifications", icon = null, drawable = R.drawable.baseline_star_24 ) val settings = BottomNavItem( id = 5, label = "settings", icon = null, drawable = R.drawable.baseline_person_24 ) } val bottomNavItems: List<BottomNavItem> = listOf( BottomNav.chat, BottomNav.friends, BottomNav.files, BottomNav.notifications, BottomNav.settings ) }
0
Kotlin
5
12
afcfa063df63228d717cdd23661476ca2bff39e8
1,101
Primer-Android
Apache License 2.0
src/main/kotlin/me/antonio/noack/elementalcommunity/Colors.kt
AntonioNoack
568,083,291
false
null
package me.antonio.noack.elementalcommunity import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.util.AttributeSet import android.view.MotionEvent import android.view.View import me.antonio.noack.elementalcommunity.GroupsEtc.GroupColors import me.antonio.noack.elementalcommunity.GroupsEtc.drawElementBackground import me.antonio.noack.elementalcommunity.GroupsEtc.hues import me.antonio.noack.elementalcommunity.GroupsEtc.saturations class Colors(ctx: Context, attributeSet: AttributeSet?): View(ctx, attributeSet) { var selected = -1 init { setOnTouchListener { _, e -> when(e.actionMasked){ MotionEvent.ACTION_UP, MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> { val widthPerNode = measuredHeight * 1f / saturations.size val x = (e.x / widthPerNode).toInt() val y = (e.y / widthPerNode).toInt() val newSelected = x * saturations.size + y if(selected != newSelected){ selected = newSelected invalidate() } } } true } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) setMeasuredDimension(measuredWidth, measuredWidth * (saturations.size * saturations.size) / GroupColors.size) } private val bgPaint = Paint() override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) if(canvas == null) return GroupsEtc.tick() val widthPerNode = measuredWidth * 1f / hues.size for(i in 0 until GroupColors.size){ val x0 = (i / saturations.size) * widthPerNode val y0 = (i % saturations.size) * widthPerNode if(i == selected){ drawElementBackground(canvas, x0, y0, -widthPerNode/6, widthPerNode, true, i, bgPaint) } else { drawElementBackground(canvas, x0, y0, 0f, widthPerNode, true, i, bgPaint) } } } }
0
Kotlin
0
0
15e2013bc62282cd0185c9c0be57eaa5b0cb2c68
2,188
ElementalCommunityWeb
Apache License 2.0
base/src/main/java/com/tulaune/base/views/my_simple_rating_bar/SimpleRatingBar.kt
tulaune
434,163,645
false
null
package com.tulaune.base.views.my_simple_rating_bar import android.graphics.drawable.Drawable import androidx.annotation.DrawableRes /** * Created by <NAME> on 2/28/18. */ internal interface SimpleRatingBar { var numStars: Int var rating: Float var starPadding: Int fun setEmptyDrawable(drawable: Drawable?) fun setEmptyDrawableRes(@DrawableRes res: Int) fun setFilledDrawable(drawable: Drawable?) fun setFilledDrawableRes(@DrawableRes res: Int) }
0
Kotlin
0
0
a90f2ec16d0b77ffbcb9f34456337af77ff03de2
482
tulaucore
The Unlicense
cardpresent/src/main/java/com/fattmerchant/omni/data/repository/MobileReaderDriverRepository.kt
fattmerchantorg
135,478,151
false
{"Kotlin": 227316, "Java": 725}
package com.fattmerchant.omni.data.repository import com.fattmerchant.omni.data.MobileReader import com.fattmerchant.omni.data.MobileReaderDriver import com.fattmerchant.omni.data.PaymentTerminalDriver import com.fattmerchant.omni.data.models.Transaction internal interface MobileReaderDriverRepository { /** * Returns the available [MobileReaderDriver]s * * @return The list of available [MobileReaderDriver]s */ suspend fun getDrivers(): List<MobileReaderDriver> /** * Returns the [MobileReaderDriver]s which have been initialized */ suspend fun getInitializedDrivers(): List<MobileReaderDriver> /** * Returns the driver that knows how to handle the given transaction * * @return MobileReaderDriver The driver for this kind of transaction or null if not found * */ suspend fun getDriverFor(transaction: Transaction): MobileReaderDriver? /** * Returns the driver that knows how to communicate with the given mobile reader * * @param mobileReader * @return */ suspend fun getDriverFor(mobileReader: MobileReader?): MobileReaderDriver? }
2
Kotlin
6
1
5e8a09bf896bc93d1e75fde8d35ba18530ad5a25
1,150
fattmerchant-android-sdk
Apache License 2.0
LMSApp/app/src/main/java/scarlet/machado/lmsapp/AcoesBtnActivity.kt
pedrobriton
369,593,681
false
null
package scarlet.machado.lmsapp import android.os.Bundle import android.view.Menu import android.view.MenuItem import kotlinx.android.synthetic.main.toolbar.* class AcoesBtnActivity : DebugActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_acoesbtn) supportActionBar?.setDisplayHomeAsUpEnabled(true) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if(id == android.R.id.home){ finish() } else if(id == android.R.id.home){ finish() } return super.onOptionsItemSelected(item) } }
1
Kotlin
0
0
da9e34d83378467da566b5592198e2bde9b60d37
755
LMSApp
MIT License
aichat/app/src/main/java/com/aesoftware/aichat/ui/MainActivity.kt
atillaeren
641,815,129
false
null
package com.aesoftware.aichat.ui import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.aesoftware.aichat.R import com.aesoftware.aichat.utils.Constants import com.revenuecat.purchases.Purchases import com.revenuecat.purchases.PurchasesConfiguration import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Purchases.debugLogsEnabled = true Purchases.configure(PurchasesConfiguration.Builder(this, Constants.GOOGLE_API_KEY).build()) } }
0
Kotlin
0
3
3bbc52a5a3411d29629faca1ab5019873b4441c4
685
android-kotlin-chatgpt-app
MIT License