path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/shubhans/socialclone/feature_profile/presentation/profile/ProfileToolbarState.kt | shubhanshu24510 | 740,657,467 | false | {"Kotlin": 334993} | package com.shubhans.socialclone.feature_profile.presentation.profile
data class ProfileToolbarState(
val toolbarOffsetY: Float = 0f,
val expandedRatio: Float = 1f
)
| 0 | Kotlin | 0 | 1 | a8741f1fd3a8d72ac9aed612ab4e81b7235df134 | 175 | SocialClone | Apache License 2.0 |
kover-gradle-plugin/src/main/kotlin/kotlinx/kover/gradle/plugin/dsl/KoverVariantConfig.kt | Kotlin | 394,574,917 | false | {"Kotlin": 473751, "Java": 21105} | /*
* Copyright 2017-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.kover.gradle.plugin.dsl
import kotlinx.kover.gradle.plugin.commons.KoverIllegalConfigException
import org.gradle.api.Action
import org.gradle.api.provider.Property
import org.gradle.api.provider.SetProperty
/**
* Type for customizing report variants shared by the current project.
*
* A report variant is a set of information used to generate a reports, namely:
* project classes, a list of Gradle test tasks, classes that need to be excluded from instrumentation.
*
* ```
* variants {
* // create report variant with custom name,
* // in which it is acceptable to add information from other variants of the current project, as well as `kover` dependencies
* create("custom") {
* // ...
* }
*
* // Configure the variant that is automatically created in the current project
* // For example, "jvm" for JVM target or "debug" for Android build variant
* provided("jvm") {
* // ...
* }
*
* // Configure the variant for all the code that is available in the current project.
* // This variant always exists for any type of project.
* total {
* // ...
* }
* }
* ```
*/
public interface KoverVariantsRootConfig: KoverVariantConfig {
/**
* Create custom report variant with name [variantName].
* In it is acceptable to add information from other variants of the current project, as well as `kover` dependencies.
*/
public fun create(variantName: String, block: Action<KoverVariantCreateConfig>)
/**
* Configure the variant with name [variantName] that is automatically created in the current project.
* For example, `"jvm"` for JVM target or `"debug"` for Android build variant.
*/
public fun provided(variantName: String, block: Action<KoverVariantConfig>)
/**
* Configure the variant for all the code that is available in the current project.
* This variant always exists for any type of project.
*/
public fun total(block: Action<KoverVariantConfig>)
}
/**
* Common config for Kover report variants.
*/
public interface KoverVariantConfig {
/**
* Limit the classes that will be included in the reports.
* These settings do not affect the instrumentation of classes.
*
* The settings specified here affect all reports in any projects that use the current project depending on.
* However, these settings should be used to regulate classes specific only to the project in which this setting is specified.
*
* Example:
* ```
* sources {
* // exclude classes compiled by Java compiler from all reports
* excludeJava = true
*
* // exclude source classes of specified source sets from all reports
* excludedSourceSets.addAll(excludedSourceSet)
* ```
*/
public fun sources(block: Action<KoverVariantSources>)
/**
* Instrumentation settings for the current Gradle project.
*
* Instrumentation is the modification of classes when they are loaded into the JVM, which helps to determine which code was called and which was not.
* Instrumentation changes the bytecode of the class, so it may disable some JVM optimizations, slow down performance and concurrency tests, and may also be incompatible with other instrumentation libraries.
*
* For this reason, it may be necessary to fine-tune the instrumentation, for example, disabling instrumentation for problematic classes. Note that such classes would be marked as uncovered because of that.
*
* Example:
* ```
* instrumentation {
* // disable instrumentation of all classes in test tasks that are in the current project
* excludeAll = true
*
* // disable instrumentation of specified classes in test tasks that are in the current project
* excludedClasses.addAll("foo.bar.*Biz", "*\$Generated")
* }
* ```
*/
public fun instrumentation(block: Action<KoverVariantInstrumentation>)
/**
* Set up tests, the run of which is used to measure coverage.
*
* To measure coverage, Kover runs Gradle test tasks, instrumentation takes place before they are performed, and code coverage is measured during execution.
*
* By default, Kover use all [org.gradle.api.tasks.testing.Test] to measure coverage.
*
* Example:
* ```
* testTasks {
* // The coverage of the test1 and test2 tasks will no longer be taken into account in the reports
* // as well as these tasks will not be called when generating the report
* excluded.addAll("test1", "test2")
* }
* ```
*/
public fun testTasks(block: Action<KoverVariantTestTasks>)
}
/**
* Limit the classes that will be included in the reports.
* These settings do not affect the instrumentation of classes.
*
* The settings specified here affect all reports in any projects that use the current project depending on.
* However, these settings should be used to regulate classes specific only to the project in which this setting is specified.
*
* Example:
* ```
* sources {
* // exclude classes compiled by Java compiler from all reports
* excludeJava = true
*
* // exclude source classes of specified source sets from all reports
* excludedSourceSets.addAll(excludedSourceSet)
* ```
*/
public interface KoverVariantSources {
/**
* Exclude classes compiled by Java compiler from all reports
*/
public val excludeJava: Property<Boolean>
/**
* Exclude source classes of specified source sets from all reports
*/
public val excludedSourceSets: SetProperty<String>
}
/**
* Instrumentation settings for the current Gradle project.
*
* Instrumentation is the modification of classes when they are loaded into the JVM, which helps to determine which code was called and which was not.
* Instrumentation changes the bytecode of the class, so it may disable some JVM optimizations, slow down performance and concurrency tests, and may also be incompatible with other instrumentation libraries.
*
* For this reason, it may be necessary to fine-tune the instrumentation, for example, disabling instrumentation for problematic classes.
*
* Example:
* ```
* instrumentation {
* // disable instrumentation in test tasks of all classes
* excludeAll = true
*
* // disable instrumentation of specified classes in test tasks
* excludedClasses.addAll("foo.bar.*Biz", "*\$Generated")
* }
* ```
*/
public interface KoverVariantInstrumentation {
/**
* Disable instrumentation in test tasks of all classes
*/
public val excludeAll: Property<Boolean>
/**
* Disable instrumentation in test tasks of specified classes
*/
public val excludedClasses: SetProperty<String>
}
/**
* Set up tests, the run of which is used to measure coverage.
*
* To measure coverage, Kover runs Gradle test tasks, instrumentation takes place before they are performed, and code coverage is measured during execution.
*
* By default, Kover use all [org.gradle.api.tasks.testing.Test] to measure coverage.
*
* Example:
* ```
* testTasks {
* // The coverage of the test1 and test2 tasks will no longer be taken into account in the reports
* // as well as these tasks will not be called when generating the report
* excluded.addAll("test1", "test2")
* }
* ```
*/
public interface KoverVariantTestTasks {
/**
* Specifies not to use test task with passed names to measure coverage.
* These tasks will also not be called when generating Kover reports.
*/
public val excluded: SetProperty<String>
}
/**
* The type for creating a custom report variant.
*
* Example:
* ```
* // Add to created variant classes, tests and instrumented classes from "jvm" report variant of current project
* add("jvm")
*
* // add an "nonexistent" option that may not exist in the current project
* add("nonexistent", true)
*
* // Add to created variant classes, tests and instrumented classes from "jvm" report variant of current project, as well as `kover(project("name"))` dependencies
* addWithDependencies("custom")
* ```
*/
public interface KoverVariantCreateConfig: KoverVariantConfig {
/**
* Add to created variant classes, tests and instrumented classes from report variant with name [variantNames].
* This variant is taken only from the current project.
*
* If [optional] is `false` and a variant with given name is not found in the current project, an error [KoverIllegalConfigException] is thrown.
*/
public fun add(vararg variantNames: String, optional: Boolean = false)
/**
* Add to created variant classes, tests and instrumented classes from report variant with name [variantNames].
* This variant is taken from the current project and all `kover(project("name"))` dependency projects.
*
* If [optional] is `false` and a variant with given name is not found in the current project, an error [KoverIllegalConfigException] is thrown.
*
* If [optional] is `true` and a variant with given name is not found in the current project - in this case, the variant will not be searched even in dependencies.
*/
public fun addWithDependencies(vararg variantNames: String, optional: Boolean = false)
}
| 59 | Kotlin | 44 | 1,167 | 329b8995b39f5eca54277227c83bc26fcc8fc6ae | 9,538 | kotlinx-kover | Apache License 2.0 |
escposprinter/src/main/java/com/khairo/escposprinter/textparser/CoroutinesIPrinterTextParserElement.kt | KhairoHumsi | 322,320,009 | false | null | package com.khairo.escposprinter.textparser
import com.khairo.escposprinter.CoroutinesEscPosPrinterCommands
import com.khairo.escposprinter.exceptions.EscPosEncodingException
interface CoroutinesIPrinterTextParserElement {
@Throws(EscPosEncodingException::class)
fun length(): Int
@Throws(EscPosEncodingException::class)
suspend fun print(printerSocket: CoroutinesEscPosPrinterCommands?): CoroutinesIPrinterTextParserElement?
}
| 3 | Kotlin | 0 | 9 | f55f82eacd503baf7d7f31dc853d8e0f46b14b22 | 447 | Printer-ktx | MIT License |
compiler/testData/diagnostics/tests/suppress/manyWarnings/mixed.kt | JakeWharton | 99,388,807 | true | null | @Suppress("REDUNDANT_NULLABLE")
class C {
@Suppress("UNNECESSARY_NOT_NULL_ASSERTION")
fun foo(): String?? = ""!! <!USELESS_CAST!>as String??<!>
} | 179 | Kotlin | 5640 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 153 | kotlin | Apache License 2.0 |
second_demo/src/main/java/com/liudong/ResourceReadServlet.kt | dongzhixuanyuan | 306,818,640 | false | {"Kotlin": 125687, "Java": 44157, "HTML": 8587, "Shell": 7324, "CSS": 209, "JavaScript": 59} | package com.liudong
import java.io.InputStream
import java.util.*
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
* @description 读取文件资源的代码
*
* @author liudong (<EMAIL>)
* @date 2020/8/23 8:43 下午
*/
class ResourceReadServlet:HttpServlet() {
override fun doGet(req: HttpServletRequest, resp: HttpServletResponse) {
resp.contentType="text/html;charset=UTF-8"
readSrcDirPropCfgFile(resp)
resp.writer.println("<hr/>")
readWebrootDirFile(resp)
resp.writer.println("<hr/>")
readPropCfgFile(resp)
}
/**
* 读取包名下的文件的话,"/WEB-INF/classes"+包名全路径
*/
private fun readPropCfgFile(resp: HttpServletResponse) {
val inputStream = servletContext.getResourceAsStream("/WEB-INF/classes/db/config/db3.properties")
parseData(inputStream,resp,"读取src目录下db.config包中的db3.properties")
}
/**
* web根目录的话,路径直接就是"/file"
*/
private fun readWebrootDirFile(resp: HttpServletResponse) {
val resourceAsStream = servletContext.getResourceAsStream("/db2.properties")
parseData(resourceAsStream,resp,"读取web根目录下的db1.properties配置文件:")
}
/**
* 读取src目录下,也就是"/WEB-INF/classes/+类全名
*/
private fun readSrcDirPropCfgFile(resp: HttpServletResponse) {
val inputStream = servletContext.getResourceAsStream("/WEB-INF/classes/db1.properties")
parseData(inputStream, resp,"读取src目录下的db1.properties配置文件:")
}
private fun parseData(inputStream: InputStream, resp: HttpServletResponse,type:String) {
val property = Properties()
property.load(inputStream)
val driver = property.getProperty("driver")
val url = property.getProperty("url")
val userName = property.getProperty("username")
val password = property.getProperty("password")
resp.writer.run {
println(type)
println("driver:$driver,url:$url,username:$userName,password:$password")
}
}
} | 0 | Kotlin | 0 | 0 | c38f4e28259b21b27c206e2ec7d394d9105d9b54 | 2,047 | server_learning_project | Apache License 2.0 |
model-client/src/jvmMain/kotlin/org/modelix/model/client/SharedExecutors.kt | modelix | 533,211,353 | false | null | /*
* 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.modelix.model.client
import java.util.concurrent.Executors
import java.util.concurrent.Future
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
object SharedExecutors {
private val LOG = mu.KotlinLogging.logger {}
@JvmField
val FIXED = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1)
val SCHEDULED = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors() + 1)
fun shutdownAll() {
SCHEDULED.shutdown()
FIXED.shutdown()
}
@JvmStatic
fun fixDelay(periodMs: Long, r: Runnable): ScheduledFuture<*> {
return fixDelay(periodMs, periodMs * 3, r)
}
@JvmStatic
fun fixDelay(periodMs: Long, timeoutMs: Long, r: Runnable): ScheduledFuture<*> {
val body = Runnable {
try {
r.run()
} catch (ex: Exception) {
LOG.error("", ex)
}
}
var workerTask: Future<*>? = null
return SCHEDULED.scheduleAtFixedRate(
{
if (workerTask == null || (workerTask?.isDone == true) || (workerTask?.isCancelled == true)) {
workerTask = FIXED.submit(body)
SCHEDULED.schedule(
{
workerTask?.cancel(true)
},
timeoutMs,
TimeUnit.MILLISECONDS,
)
}
},
periodMs,
periodMs,
TimeUnit.MILLISECONDS,
)
}
}
| 47 | null | 9 | 6 | 2bbc5b1ed943aa9842cb3d58d4d2a8a6bc8b4bd0 | 2,176 | modelix.core | Apache License 2.0 |
bootstrap-icons-compose/src/main/java/com/wiryadev/bootstrapiconscompose/bootstrapicons/normal/BookmarkPlus.kt | wiryadev | 380,639,096 | false | null | package com.wiryadev.bootstrapiconscompose.bootstrapicons.normal
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.wiryadev.bootstrapiconscompose.bootstrapicons.NormalGroup
public val NormalGroup.BookmarkPlus: ImageVector
get() {
if (_bookmarkPlus != null) {
return _bookmarkPlus!!
}
_bookmarkPlus = Builder(name = "BookmarkPlus", defaultWidth = 16.0.dp, defaultHeight =
16.0.dp, viewportWidth = 16.0f, viewportHeight = 16.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(2.0f, 2.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, -2.0f)
horizontalLineToRelative(8.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, 2.0f)
verticalLineToRelative(13.5f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, -0.777f, 0.416f)
lineTo(8.0f, 13.101f)
lineToRelative(-5.223f, 2.815f)
arcTo(0.5f, 0.5f, 0.0f, false, true, 2.0f, 15.5f)
lineTo(2.0f, 2.0f)
close()
moveTo(4.0f, 1.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, -1.0f, 1.0f)
verticalLineToRelative(12.566f)
lineToRelative(4.723f, -2.482f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, 0.554f, 0.0f)
lineTo(13.0f, 14.566f)
lineTo(13.0f, 2.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, -1.0f, -1.0f)
lineTo(4.0f, 1.0f)
close()
}
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(8.0f, 4.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, 0.5f, 0.5f)
verticalLineTo(6.0f)
horizontalLineTo(10.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, 0.0f, 1.0f)
horizontalLineTo(8.5f)
verticalLineToRelative(1.5f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, -1.0f, 0.0f)
verticalLineTo(7.0f)
horizontalLineTo(6.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, 0.0f, -1.0f)
horizontalLineToRelative(1.5f)
verticalLineTo(4.5f)
arcTo(0.5f, 0.5f, 0.0f, false, true, 8.0f, 4.0f)
close()
}
}
.build()
return _bookmarkPlus!!
}
private var _bookmarkPlus: ImageVector? = null
| 0 | Kotlin | 0 | 2 | 1c199d953dc96b261aab16ac230dc7f01fb14a53 | 3,471 | bootstrap-icons-compose | MIT License |
base/src/commonTest/kotlin/com/github/fsbarata/functional/data/compose/ComposedApplicativeTest.kt | fsbarata | 277,280,202 | false | {"Kotlin": 302776} | package com.github.fsbarata.functional.data.compose
import com.github.fsbarata.functional.assertEquals
import com.github.fsbarata.functional.control.ApplicativeLaws
import com.github.fsbarata.functional.data.Functor
import com.github.fsbarata.functional.data.list.*
import com.github.fsbarata.functional.data.maybe.None
import com.github.fsbarata.functional.data.maybe.Optional
import com.github.fsbarata.functional.data.maybe.Some
import kotlin.test.Test
class ComposedApplicativeTest: ApplicativeLaws<ComposedContext<ListContext, NonEmptyContext>> {
override val applicativeScope = ComposedApplicative.Scope(ListF, NonEmptyList)
override val possibilities: Int = 10
override fun factory(possibility: Int): Functor<ComposedContext<ListContext, NonEmptyContext>, Int> =
ComposedApplicative(
createList(possibility)
.map { createNel(it) },
ListF,
NonEmptyList
)
@Test
fun `ComposedApplicative maps underlying functor`() {
assertEquals(
listOf(Some(3), None, None, Some(5), Some(7)),
ListF.of(Some(6), None, None, Some(11), Some(14))
.composed(Optional)
.map { it / 2 }
.underlying
)
}
}
| 0 | Kotlin | 2 | 0 | b8f5032e88cd348cce8c9d8265a2e963b3c92c1d | 1,135 | kotlin-functional | Apache License 2.0 |
base/src/commonTest/kotlin/com/github/fsbarata/functional/data/compose/ComposedApplicativeTest.kt | fsbarata | 277,280,202 | false | {"Kotlin": 302776} | package com.github.fsbarata.functional.data.compose
import com.github.fsbarata.functional.assertEquals
import com.github.fsbarata.functional.control.ApplicativeLaws
import com.github.fsbarata.functional.data.Functor
import com.github.fsbarata.functional.data.list.*
import com.github.fsbarata.functional.data.maybe.None
import com.github.fsbarata.functional.data.maybe.Optional
import com.github.fsbarata.functional.data.maybe.Some
import kotlin.test.Test
class ComposedApplicativeTest: ApplicativeLaws<ComposedContext<ListContext, NonEmptyContext>> {
override val applicativeScope = ComposedApplicative.Scope(ListF, NonEmptyList)
override val possibilities: Int = 10
override fun factory(possibility: Int): Functor<ComposedContext<ListContext, NonEmptyContext>, Int> =
ComposedApplicative(
createList(possibility)
.map { createNel(it) },
ListF,
NonEmptyList
)
@Test
fun `ComposedApplicative maps underlying functor`() {
assertEquals(
listOf(Some(3), None, None, Some(5), Some(7)),
ListF.of(Some(6), None, None, Some(11), Some(14))
.composed(Optional)
.map { it / 2 }
.underlying
)
}
}
| 0 | Kotlin | 2 | 0 | b8f5032e88cd348cce8c9d8265a2e963b3c92c1d | 1,135 | kotlin-functional | Apache License 2.0 |
java-examples/src/test/kotlin/top/viclau/magicbox/java/examples/junit/chapter3/HamcrestTest.kt | xingyuli | 578,005,859 | false | null | /*
* Copyright (c) 2022 <NAME>
*
* Distributed under MIT license.
* See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
package top.viclau.magicbox.java.examples.junit.chapter3
import org.hamcrest.CoreMatchers.*
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
@Disabled("Ignore as this is only a demo for illustrating the Hamcrest matcher")
class HamcrestTest {
private lateinit var values: MutableList<String>
@BeforeEach
fun setUpList() {
values = ArrayList()
values.add("one")
values.add("two")
values.add("three")
}
@Test
fun testWithoutHamcrest() {
assertTrue(values.contains("one")
|| values.contains("two")
|| values.contains("three"))
}
@Test
fun testWithHamcrest() {
assertThat<List<String>>(
values, hasItem(
anyOf(
equalTo("one"),
equalTo("two"),
equalTo("three")
)
)
)
}
} | 0 | Kotlin | 0 | 0 | 1be58b9836db67b677f3acbb789148adbd4869a6 | 1,228 | magicbox | MIT License |
UnicornFilePicker/src/main/java/abhishekti7/unicorn/filepicker/filesystem/SingletonUsbOtg.kt | darkmat13r | 338,381,468 | true | {"Kotlin": 45885, "Java": 31765} | package abhishekti7.unicorn.filepicker.filesystem
import android.net.Uri
class SingletonUsbOtg private constructor() {
private var connectedDevice: UsbOtgRepresentation? = null
private var usbOtgRoot: Uri? = null
fun setConnectedDevice(connectedDevice: UsbOtgRepresentation?) {
this.connectedDevice = connectedDevice
}
val isDeviceConnected: Boolean
get() = connectedDevice != null
fun setUsbOtgRoot(root: Uri?) {
checkNotNull(connectedDevice) { "No device connected!" }
usbOtgRoot = root
}
fun resetUsbOtgRoot() {
connectedDevice = null
usbOtgRoot = null
}
fun getUsbOtgRoot(): Uri? {
return usbOtgRoot
}
fun checkIfRootIsFromDevice(device: UsbOtgRepresentation): Boolean {
return usbOtgRoot != null && connectedDevice.hashCode() === device.hashCode()
}
companion object {
var instance: SingletonUsbOtg? = null
get() {
if (field == null) field = SingletonUsbOtg()
return field
}
private set
}
}
| 0 | Kotlin | 0 | 0 | 5874b80b396bdbe9c1711bfd1effec3ef8c59c3d | 1,104 | UnicornFilePicker | Apache License 2.0 |
library/src/main/java/gr/amoutzidis/decrincre/algorithms/DefaultDurationAlgorithm.kt | amoutzidis | 314,254,790 | false | null | package gr.amoutzidis.decrincre.algorithms
import kotlin.math.abs
class DefaultDurationAlgorithm:
DurationAlgorithm {
override fun calculate(duration: Long, previousValue: Number, newValue: Number): Long {
val previousValueToFloat = previousValue.toFloat()
val newValueToFloat = newValue.toFloat()
val delta = abs(previousValueToFloat - newValueToFloat)
return if(delta < 600)
duration
else
(duration * 1.5).toLong()
}
} | 0 | Kotlin | 0 | 0 | 919ccbb9706821646830861f8990e767ec19d3dd | 500 | DecrincreView | Apache License 2.0 |
library/src/main/java/gr/amoutzidis/decrincre/algorithms/DefaultDurationAlgorithm.kt | amoutzidis | 314,254,790 | false | null | package gr.amoutzidis.decrincre.algorithms
import kotlin.math.abs
class DefaultDurationAlgorithm:
DurationAlgorithm {
override fun calculate(duration: Long, previousValue: Number, newValue: Number): Long {
val previousValueToFloat = previousValue.toFloat()
val newValueToFloat = newValue.toFloat()
val delta = abs(previousValueToFloat - newValueToFloat)
return if(delta < 600)
duration
else
(duration * 1.5).toLong()
}
} | 0 | Kotlin | 0 | 0 | 919ccbb9706821646830861f8990e767ec19d3dd | 500 | DecrincreView | Apache License 2.0 |
benchmarks/src/main/java/com/google/samples/apps/nowinandroid/interests/InterestsActions.kt | benjiesinzore | 571,923,593 | false | {"Kotlin": 836375, "Shell": 10599} | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.nowinandroid.interests
import androidx.benchmark.macro.MacrobenchmarkScope
import androidx.test.uiautomator.By
import androidx.test.uiautomator.Direction
import androidx.test.uiautomator.Until
fun MacrobenchmarkScope.interestsScrollTopicsDownUp() {
val topicsList = device.findObject(By.res("interests:topics"))
topicsList.fling(Direction.DOWN)
device.waitForIdle()
topicsList.fling(Direction.UP)
}
fun MacrobenchmarkScope.interestsScrollPeopleDownUp() {
val peopleList = device.findObject(By.res("interests:people"))
peopleList.fling(Direction.DOWN)
device.waitForIdle()
peopleList.fling(Direction.UP)
}
fun MacrobenchmarkScope.interestsWaitForTopics() {
device.wait(Until.hasObject(By.text("Accessibility")), 30_000)
}
fun MacrobenchmarkScope.interestsToggleBookmarked() {
val topicsList = device.findObject(By.res("interests:topics"))
val checkable = topicsList.findObject(By.checkable(true))
checkable.click()
device.waitForIdle()
}
| 0 | Kotlin | 0 | 0 | 20fbed35a9a67be3e109fe6d55b45c6dc3af8715 | 1,643 | Now-in-Android | Apache License 2.0 |
app/src/main/java/tama/blockCleaning/worker/EventFetcherWorker.kt | RichardKlem | 408,745,936 | false | {"Kotlin": 58167, "TeX": 47443, "Makefile": 198} | package tama.blockCleaning.worker
import android.content.Context
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.work.Worker
import androidx.work.WorkerParameters
import tama.blockCleaning.data.entity.Cleaning
import tama.blockCleaning.data.entity.Street
import tama.blockCleaning.data.fetch.DataFetcher
import tama.blockCleaning.helpers.GPS
import tama.blockCleaning.helpers.deleteEvent
import tama.blockCleaning.helpers.getEvents
import tama.blockCleaning.helpers.insertEvent
import java.text.SimpleDateFormat
import java.util.*
class EventFetcherWorker(ctx: Context, params: WorkerParameters) : Worker(ctx, params) {
private var streets: List<Street>? = null
private var cleanings: List<Cleaning>? = null
@RequiresApi(Build.VERSION_CODES.O)
override fun doWork(): Result {
val currentDate = Calendar.getInstance().time
val calendar = Calendar.getInstance()
calendar.add(Calendar.DATE, 1)
val endDate = calendar.time
val dateFormat = SimpleDateFormat("yyyy-MM-dd")
DataFetcher.fetchData(this.applicationContext,
"${dateFormat.format(currentDate)}T00:00:00.000Z",
"${dateFormat.format(endDate)}T20:59:59.999Z",
{ c ->
this.cleanings = c
if (this.streets != null) {
this.onFetched()
}
},
{ s ->
this.streets = s
if (this.cleanings != null) {
this.onFetched()
}
}
)
return Result.success()
}
private fun onFetched() {
val eventsOld = getEvents(this.applicationContext)
eventsOld.events.forEach { event ->
deleteEvent(this.applicationContext, event.id)
}
val gps = GPS(0.0, 0.0)
val dateFormat = SimpleDateFormat("d. M. yyyy, HH.mm")
this.cleanings?.forEach { cleaning ->
val street = this.streets?.find { s -> s.id == cleaning.sId }
if (street != null) {
insertEvent(
this.applicationContext,
cleaning.name,
gps,
dateFormat.format(cleaning.from),
dateFormat.format(cleaning.to)
)
}
}
}
} | 0 | Kotlin | 0 | 1 | 46614547bc5e6ed80d42d9fe81013eedadac6b51 | 2,362 | TAMa | MIT License |
app/src/main/java/com/jhoglas/mysalon/domain/entity/ProfessionalDomainEntity.kt | jhoglassx | 670,225,437 | false | {"Kotlin": 167188} | package com.jhoglas.mysalon.domain.entity
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class ProfessionalDomainEntity(
val id: String,
val establishmentId: String,
val name: String,
val photo: String,
val services: List<ServiceDomainEntity>,
var isSelected: Boolean = false
) : Parcelable
fun getProfessionals(): MutableList<ProfessionalDomainEntity> = mutableListOf(
ProfessionalDomainEntity(
id = "1",
establishmentId = "1",
name = "<NAME>",
photo = "https://picsum.photos/150/150",
services = listOf(
ServiceDomainEntity("Corte de Cabelo"),
ServiceDomainEntity("Pintura de Cabelo")
)
),
ProfessionalDomainEntity(
id = "2",
establishmentId = "1",
name = "<NAME>",
photo = "https://picsum.photos/151/151",
services = listOf(
ServiceDomainEntity("Corte de Cabelo"),
ServiceDomainEntity("Barba")
)
),
ProfessionalDomainEntity(
id = "3",
establishmentId = "1",
name = "<NAME>",
photo = "https://picsum.photos/152/152",
services = listOf(
ServiceDomainEntity("Corte de Cabelo"),
ServiceDomainEntity("Barba")
)
),
ProfessionalDomainEntity(
id = "4",
establishmentId = "2",
name = "<NAME>",
photo = "https://picsum.photos/153/153",
services = listOf(
ServiceDomainEntity(
title = "Haircut"
),
ServiceDomainEntity(
title = "Beard"
),
ServiceDomainEntity(
title = "Shave"
)
)
),
ProfessionalDomainEntity(
id = "5",
establishmentId = "2",
name = "<NAME>",
photo = "https://picsum.photos/154/154",
services = listOf(
ServiceDomainEntity(
title = "Haircut"
),
ServiceDomainEntity(
title = "Beard"
),
ServiceDomainEntity(
title = "Shave"
)
)
)
) | 0 | Kotlin | 0 | 0 | 4bcd3966050cdccf06b5ac3003095d402ec3b482 | 2,190 | myservice | MIT License |
base/build-system/manifest-merger/src/test/java/com/android/manifmerger/NavigationXmlLoaderTest.kt | qiangxu1996 | 255,410,085 | false | null | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.manifmerger
import com.android.ide.common.blame.SourceFile.UNKNOWN
import com.google.common.truth.Truth.assertThat
import org.junit.Test
/** Tests for [NavigationXmlLoader] */
class NavigationXmlLoaderTest {
@Test
fun testLoad() {
val input =
"""|<navigation
| xmlns:android="http://schemas.android.com/apk/res/android"
| xmlns:app="http://schemas.android.com/apk/res-auto">
| <include app:graph="@navigation/foo" />
| <deepLink app:uri="www.example.com" />
|</navigation>""".trimMargin()
val navigationXmlDocument = NavigationXmlLoader.load(UNKNOWN, input)
assertThat(navigationXmlDocument.navigationXmlIds).containsExactly("foo")
assertThat(navigationXmlDocument.deepLinks.size).isEqualTo(1)
val deepLink = navigationXmlDocument.deepLinks[0]
assertThat(deepLink.host).isEqualTo("www.example.com")
}
}
| 0 | null | 1 | 1 | 3411c5436d0d34e6e2b84cbf0e9395ac8c55c9d4 | 1,634 | vmtrace | Apache License 2.0 |
gabimoreno/src/test/java/soy/gabimoreno/data/local/mapper/ToPremiumAudioDbModelMapperKtTest.kt | soygabimoreno | 477,796,937 | false | {"Kotlin": 364408, "Swift": 648, "Shell": 441} | package soy.gabimoreno.data.local.mapper
import org.amshove.kluent.shouldBe
import org.amshove.kluent.shouldBeEqualTo
import org.junit.Test
import soy.gabimoreno.fake.buildPremiumAudio
class ToPremiumAudioDbModelMapperKtTest {
@Test
fun `GIVEN a PremiumAudio WHEN toPremiumAudioDbModel THEN get the expected PremiumAudioDbModel`() {
val premiumAudio = buildPremiumAudio()
with(premiumAudio) {
val id = id
val title = title
val description = description
val saga = saga
val url = url
val audioUrl = audioUrl
val imageUrl = imageUrl
val thumbnailUrl = thumbnailUrl
val pubDateMillis = pubDateMillis
val category = category
val excerpt = excerpt
val result = premiumAudio.toPremiumAudioDbModel()
result.id shouldBe id
result.title shouldBe title
result.description shouldBe description
result.saga shouldBe saga
result.url shouldBe url
result.audioUrl shouldBe audioUrl
result.imageUrl shouldBe imageUrl
result.thumbnailUrl shouldBe thumbnailUrl
result.pubDateMillis shouldBe pubDateMillis
result.audioLengthInSeconds shouldBeEqualTo audioLengthInSeconds
result.category shouldBeEqualTo category
result.excerpt shouldBeEqualTo excerpt
}
}
}
| 6 | Kotlin | 9 | 13 | fa8abc8e852daa989f4f530ea9aa5b38b8ae7d20 | 1,466 | Base | Apache License 2.0 |
app/src/main/java/com/example/android/codelabs/paging/api/SearchRepos.kt | geertberkers | 248,219,061 | false | null | package com.example.android.codelabs.paging.api
import android.util.Log
import com.example.android.codelabs.paging.model.Repo
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
/**
* Created by Zorgkluis (Geert Berkers)
*/
private const val TAG = "GithubService"
private const val IN_QUALIFIER = "in:name,description"
/**
* Search repos based on a query.
* Trigger a request to the Github searchRepo API with the following params:
* @param query searchRepo keyword
* @param page request page index
* @param itemsPerPage number of repositories to be returned by the Github API per page
*
* The result of the request is handled by the implementation of the functions passed as params
* @param onSuccess function that defines how to handle the list of repos received
* @param onError function that defines how to handle request failure
*/
fun searchRepos(
service: GithubService,
query: String,
page: Int,
itemsPerPage: Int,
onSuccess: (repos: List<Repo>) -> Unit,
onError: (error: String) -> Unit
) {
Log.d(TAG, "query: $query, page: $page, itemsPerPage: $itemsPerPage")
val apiQuery = query + IN_QUALIFIER
service.searchRepos(apiQuery, page, itemsPerPage).enqueue(
object : Callback<RepoSearchResponse> {
override fun onFailure(call: Call<RepoSearchResponse>?, t: Throwable) {
Log.d(TAG, "fail to get data")
onError(t.message ?: "unknown error")
}
override fun onResponse(
call: Call<RepoSearchResponse>?,
response: Response<RepoSearchResponse>
) {
Log.d(TAG, "got a response $response")
if (response.isSuccessful) {
val repos = response.body()?.items ?: emptyList()
onSuccess(repos)
} else {
onError(response.errorBody()?.string() ?: "Unknown error")
}
}
}
)
} | 0 | Kotlin | 0 | 0 | 3d6384f6dfc1c6ce3bfb4aeadf61cf6e07f8df2c | 2,109 | GoogleUXPaging | Apache License 2.0 |
app/src/main/java/com/gregorymarkthomas/calendar/util/backstack/BackStackCallback.kt | gregorymarkthomas | 116,566,951 | false | null | package com.gregorymarkthomas.calendar.util.backstack
import android.view.View
import com.gregorymarkthomas.calendar.util.LifeCycleView
interface BackStackCallback {
fun onViewChanged(item: BackStackItem)
} | 2 | Kotlin | 0 | 0 | 8644337fb2eabc892d2ccb32b746e053e89ed016 | 212 | calendar | MIT License |
royale-android/app/src/main/kotlin/net/rf43/royaleapikit_example/top_players/ActivityTopPlayers.kt | rf43 | 167,097,050 | false | null | package net.rf43.royaleapikit_example.top_players
import android.os.Bundle
import android.view.View
import android.widget.ProgressBar
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import net.rf43.royaleapikit.provider.TopPlayerModel
import net.rf43.royaleapikit_example.R
import net.rf43.royaleapikit_example.common.BaseActivity
import net.rf43.royaleapikit_example.top_players.adapters.TopPlayersListAdapter
class ActivityTopPlayers : BaseActivity() {
private lateinit var topPlayersAdapter: TopPlayersListAdapter
private lateinit var topPlayerLoadingIndicator: ProgressBar
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_top_players)
topPlayerLoadingIndicator = findViewById(R.id.top_player_loading_indicator)
topPlayerLoadingIndicator.visibility = View.VISIBLE
val topPlayerRecyclerView = findViewById<RecyclerView>(R.id.recycler_top_players)
topPlayerRecyclerView.layoutManager = LinearLayoutManager(this)
topPlayerRecyclerView.adapter = TopPlayersListAdapter(context = this)
topPlayersAdapter = topPlayerRecyclerView.adapter as TopPlayersListAdapter
GlobalScope.launch(Dispatchers.Main) {
loadPlayersIntoList(royaleApiKit.getTopPlayers())
topPlayerLoadingIndicator.visibility = View.GONE
}
}
private fun loadPlayersIntoList(players: List<TopPlayerModel.TopPlayer>) {
topPlayersAdapter.addPlayers(players)
}
} | 1 | Kotlin | 0 | 1 | 73c899b64990fe92cbf630b23a9dcbcc5bd7fc3e | 1,704 | royale-api-wrapper | Apache License 2.0 |
browser-kotlin/src/jsMain/kotlin/web/uievents/InputEvent.types.deprecated.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6328371} | // Automatically generated - do not modify!
package web.uievents
import seskar.js.JsValue
import web.events.EventType
sealed external class InputEventTypes_deprecated {
@Deprecated(
message = "Legacy event type declaration. Use type constant instead!",
replaceWith = ReplaceWith("InputEvent.BEFORE_INPUT"),
)
@JsValue("beforeinput")
fun beforeInput(): EventType<InputEvent>
@Deprecated(
message = "Legacy event type declaration. Use type constant instead!",
replaceWith = ReplaceWith("InputEvent.INPUT"),
)
@JsValue("input")
fun input(): EventType<InputEvent>
}
| 0 | Kotlin | 7 | 35 | 0f192fb5e7be6207ea195f88dc6a0e766ad7f93b | 631 | types-kotlin | Apache License 2.0 |
app/src/main/java/com/kou/seekmake/data/firebase/SearchRepository.kt | itzkou | 316,269,099 | false | null | package com.kou.seekmake.data.firebase
import androidx.lifecycle.LiveData
import com.google.android.gms.tasks.Task
import com.kou.seekmake.models.Firebase.SearchPost
interface SearchRepository {
fun searchPosts(text: String): LiveData<List<SearchPost>>
fun createPost(post: SearchPost): Task<Unit>
} | 0 | Kotlin | 0 | 0 | aee05bcf921efe59b0fa263cc932a5daf3b9a3e0 | 309 | seekmake-android | MIT License |
app/src/main/java/kr/pandadong2024/babya/home/dash_board/adapter/DashBoardAdapter.kt | 2024-PandaDong | 876,752,501 | false | {"Kotlin": 402677} | package kr.pandadong2024.babya.home.dash_board.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import coil.load
import kr.pandadong2024.babya.databinding.ItemDashBoardRecyclerviewBinding
import kr.pandadong2024.babya.server.remote.responses.dash_board.DashBoardResponses
class DashBoardAdapter(
private val items: List<DashBoardResponses>,
private val onItemClick: (postId : Int) -> Unit
) : RecyclerView.Adapter<DashBoardAdapter.Holder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
val binding = ItemDashBoardRecyclerviewBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return Holder(binding)
}
override fun onBindViewHolder(holder: Holder, position: Int) {
holder.bind(items[position])
}
override fun getItemCount(): Int = items.size
inner class Holder(private val binding: ItemDashBoardRecyclerviewBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(dashBoardResponse: DashBoardResponses) {
val data = items[position]
binding.apply {
title.text = dashBoardResponse.title
name.text = dashBoardResponse.nickname
body.text = dashBoardResponse.content
ago.text = dashBoardResponse.createdAt.toString().substring(5 until 10) // 적절한 형식으로 변환 필요
views.text = dashBoardResponse.view.toString()
comment.text = dashBoardResponse.commentCnt.toString()
root.setOnClickListener {
if (data.postId != null){
onItemClick(data.postId)
}
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | 2bb74537ba551b475467fbb9caeac50e19bd9fa3 | 1,780 | babya-android | Apache License 2.0 |
app/src/main/java/com/siddhantkushwaha/falcon/common/GoogleMail.kt | siddhantkushwaha | 342,520,774 | false | null | package com.siddhantkushwaha.falcon.common
import android.app.Activity
import com.google.api.client.extensions.android.http.AndroidHttp
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential
import com.google.api.client.json.gson.GsonFactory
import com.google.api.services.gmail.Gmail
import com.google.api.services.gmail.model.Message
import com.google.api.services.gmail.model.Thread
import com.siddhantkushwaha.falcon.R
import java.util.*
class GoogleMail private constructor(private val service: Gmail) {
companion object {
/*
This is platform specific code, the class method, members should be common
*/
fun getInstance(activity: Activity, scope: String): GoogleMail? {
val account = GoogleOAuth.getLastSignedInAccount(activity) ?: return null
val credential =
GoogleAccountCredential.usingOAuth2(activity, Collections.singleton(scope))
credential.selectedAccount = account.account
val service =
Gmail.Builder(AndroidHttp.newCompatibleTransport(), GsonFactory(), credential)
.setApplicationName(activity.resources.getString(R.string.app_name)).build()
return GoogleMail(service)
}
}
public fun getService(): Gmail {
return service
}
public fun getThreads(userId: String = "me", q: String? = null) = sequence {
var pageToken: String?
do {
val resultBuilder = service.users().threads().list(userId)
if (q != null) resultBuilder.q = q
val result = resultBuilder.execute()
yieldAll(result.threads)
pageToken = result.nextPageToken
} while (pageToken != null)
}
public fun getThread(userId: String = "me", id: String): Thread? {
return try {
service.users().threads().get("me", id).execute()
} catch (e: Exception) {
e.printStackTrace()
null
}
}
public fun getMails(userId: String = "me", q: String? = null) = sequence {
var pageToken: String?
do {
val resultBuilder = service.users().messages().list(userId)
if (q != null) resultBuilder.q = q
val result = resultBuilder.execute()
yieldAll(result.messages)
pageToken = result.nextPageToken
} while (pageToken != null)
}
public fun getMail(userId: String = "me", id: String): Message? {
return try {
service.users().messages().get("me", id).execute()
} catch (e: Exception) {
e.printStackTrace()
null
}
}
} | 0 | Kotlin | 0 | 0 | 47882fc4dcd1bcfd9e69ee3ba331a1d4b219f943 | 2,708 | Falcon-Android | MIT License |
app/src/main/java/com/siddhantkushwaha/falcon/common/GoogleMail.kt | siddhantkushwaha | 342,520,774 | false | null | package com.siddhantkushwaha.falcon.common
import android.app.Activity
import com.google.api.client.extensions.android.http.AndroidHttp
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential
import com.google.api.client.json.gson.GsonFactory
import com.google.api.services.gmail.Gmail
import com.google.api.services.gmail.model.Message
import com.google.api.services.gmail.model.Thread
import com.siddhantkushwaha.falcon.R
import java.util.*
class GoogleMail private constructor(private val service: Gmail) {
companion object {
/*
This is platform specific code, the class method, members should be common
*/
fun getInstance(activity: Activity, scope: String): GoogleMail? {
val account = GoogleOAuth.getLastSignedInAccount(activity) ?: return null
val credential =
GoogleAccountCredential.usingOAuth2(activity, Collections.singleton(scope))
credential.selectedAccount = account.account
val service =
Gmail.Builder(AndroidHttp.newCompatibleTransport(), GsonFactory(), credential)
.setApplicationName(activity.resources.getString(R.string.app_name)).build()
return GoogleMail(service)
}
}
public fun getService(): Gmail {
return service
}
public fun getThreads(userId: String = "me", q: String? = null) = sequence {
var pageToken: String?
do {
val resultBuilder = service.users().threads().list(userId)
if (q != null) resultBuilder.q = q
val result = resultBuilder.execute()
yieldAll(result.threads)
pageToken = result.nextPageToken
} while (pageToken != null)
}
public fun getThread(userId: String = "me", id: String): Thread? {
return try {
service.users().threads().get("me", id).execute()
} catch (e: Exception) {
e.printStackTrace()
null
}
}
public fun getMails(userId: String = "me", q: String? = null) = sequence {
var pageToken: String?
do {
val resultBuilder = service.users().messages().list(userId)
if (q != null) resultBuilder.q = q
val result = resultBuilder.execute()
yieldAll(result.messages)
pageToken = result.nextPageToken
} while (pageToken != null)
}
public fun getMail(userId: String = "me", id: String): Message? {
return try {
service.users().messages().get("me", id).execute()
} catch (e: Exception) {
e.printStackTrace()
null
}
}
} | 0 | Kotlin | 0 | 0 | 47882fc4dcd1bcfd9e69ee3ba331a1d4b219f943 | 2,708 | Falcon-Android | MIT License |
app/src/main/java/com/example/android/roomwordssample/WordListAdapter.kt | maljelma | 780,163,267 | false | {"Kotlin": 23271} | /*
* Copyright (C) 2017 Google 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.
*/
/* %sb=comment-by:mohammad-Aljelmawi 2024-03-27 */
package com.example.android.roomwordssample
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.android.roomwordssample.WordListAdapter.WordViewHolder
/* %sb: WORDS_COMPARATOR is used to check if item value needs to be replaced or not */
class WordListAdapter : ListAdapter<Word, WordViewHolder>(WORDS_COMPARATOR) {
/* %sb: ViewHolder is an object inside a RecyclerView
RecyclerView will create n of them using `create` to fill the space on screen
then will reuse them one by one using `bind` to show data scrolling
*/
/* %sb: (parent|RecyclerView, viewType|type of parent as int) ->
ViewHolder( recyclerview_item as a class;
this will be passed on item value changed
with an index for the target Word in ListAdapter to be displayed) using `onBindViewHolder` */
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WordViewHolder {
return WordViewHolder.create(parent)
}
/* %sb: reuse WordViewHolder(recyclerview_item) at postion(index of Word object in ListAdapter) */
/* %sb: holder is the WordViewHolder(recyclerview_item as a class) to be reused */
override fun onBindViewHolder(holder: WordViewHolder, position: Int) {
/* %sb: getItem is like: ListAdapter['Word'][postion|index] -> Word */
val current = getItem(position)
/* %sb: holder.bind as function defiend in WordViewHolder class wich takes a text */
holder.bind(current.word)
}
class WordViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
/* %sb: get the text-view(i.e. a label) inside itemView(recyclerview_item) */
private val wordItemView: TextView = itemView.findViewById(R.id.textView)
fun bind(text: String?) {
wordItemView.text = text
}
/* %sb: static access */
companion object {
/* %sb: create a new WordViewHolder(recyclerview_item as a class) in given parent(RecyclerView) */
fun create(parent: ViewGroup): WordViewHolder {
val view: View = LayoutInflater.from(parent.context)
.inflate(R.layout.recyclerview_item, parent, false)
return WordViewHolder(view)
}
}
}
companion object {
private val WORDS_COMPARATOR = object : DiffUtil.ItemCallback<Word>() {
override fun areItemsTheSame(oldItem: Word, newItem: Word): Boolean {
return oldItem === newItem
}
override fun areContentsTheSame(oldItem: Word, newItem: Word): Boolean {
return oldItem.word == newItem.word
}
}
}
}
| 0 | Kotlin | 0 | 0 | 4ed899029a2ce6ddd0571ce7510ec769ea9f00b2 | 3,556 | SimplifiedAndroidRoomDatabaseAndMVVMPattern | Apache License 2.0 |
kbtool-lib/src/main/java/com/github/jchanghong/kafka/KafkaHelper.kt | jchanghong | 494,378,439 | false | null | package com.github.jchanghong.kafka
import cn.hutool.core.thread.ThreadUtil
import cn.hutool.core.util.RandomUtil
import com.github.jchanghong.log.kError
import com.github.jchanghong.log.kInfo
import org.apache.kafka.clients.admin.*
import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.clients.consumer.KafkaConsumer
import org.apache.kafka.clients.producer.KafkaProducer
import org.apache.kafka.clients.producer.ProducerRecord
import org.apache.kafka.clients.producer.RecordMetadata
import org.apache.kafka.common.KafkaFuture
import java.util.*
import java.util.concurrent.*
import java.util.function.Consumer
import kotlin.concurrent.thread
enum class OffsetReset {
earliest,
latest
}
/** 一个对象一套kafka配置,多个kafka,需要建立多个对象,earliest,latest
* */
class KafkaHelper(
val bootstrap: String,
val groupId: String,
val topics: List<String>,
val action: Consumer<ConsumerRecord<String?, String?>>,
val offsetReset: OffsetReset = OffsetReset.latest,
val threadCount: Int,
val commitintervalms: Int = 60000
) {
lateinit var threadExecutor: ThreadPoolExecutor
lateinit var threadList: List<KafkaConsumerRunner>
lateinit var threadListManualPartition: List<KafkaConsumerRunnerManualPartition>
// private val singleThreadExecutor = Executors.newSingleThreadExecutor()
val mProps: Properties = getAndSetProps(bootstrap, groupId)
val mProducer: KafkaProducer<String, String> by lazy { KafkaProducer<String, String>(mProps) }
// private val mConsumer: KafkaConsumer<String, String> by lazy { KafkaConsumer<String, String>(mProps) }
val adminClient: AdminClient by lazy { KafkaAdminClient.create(mProps) }
// 配置Kafka
private fun getAndSetProps(bootstrap: String, groupId: String? = null): Properties {
val props = Properties()
props["bootstrap.servers"] = bootstrap
// props.put("retries", 2) // 重试次数
props.put("batch.size", 16384) // 批量发送大小
// props.put("buffer.memory", 33554432) // 缓存大小,根据本机内存大小配置
// props.put("linger.ms", 1000) // 发送频率,满足任务一个条件发送
props.put("acks", "1")
if (!groupId.isNullOrBlank()) {
props.setProperty("group.id", groupId)
}
props.setProperty("max.partition.fetch.bytes", "52428800")
props.setProperty("receive.buffer.bytes", "-1")
props.setProperty("enable.auto.commit", "true")
props.setProperty("auto.offset.reset", offsetReset.name)
props.setProperty("auto.commit.interval.ms", commitintervalms.toString())
props.setProperty("max.poll.records", "500")
props.setProperty("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
props.setProperty("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
props["key.serializer"] = "org.apache.kafka.common.serialization.StringSerializer"
props["value.serializer"] = "org.apache.kafka.common.serialization.StringSerializer"
return props
}
@JvmOverloads
fun createTopic(name: String, p: Int = 8, r: Short = 1) {
val newTopic = NewTopic(name, p, r)
val newTopicList: MutableCollection<NewTopic> = ArrayList()
newTopicList.add(newTopic)
val createTopicsResult = adminClient.createTopics(newTopicList)
for (entry in createTopicsResult.values()) {
try {
entry.value.get()
Thread.sleep(2000)
} catch (e: Exception) {
kError(e.message, e)
}
kInfo("createTopic ${entry.key}")
}
}
fun deleteTopic(name: String) {
val deleteTopicsResult = adminClient.deleteTopics(Arrays.asList(name))
for ((k, v) in deleteTopicsResult.values()) {
try {
v.get()
Thread.sleep(2000)
} catch (e: Exception) {
kError(e.message, e)
}
kInfo("deleteTopic $k")
}
}
fun listAllTopic(): Set<String> {
val result: ListTopicsResult = adminClient.listTopics()
val names = result.names()
try {
return names.get()
} catch (e: InterruptedException) {
kError(e.message, e)
} catch (e: ExecutionException) {
kError(e.message, e)
}
return emptySet()
}
fun getTopic(name: String): TopicDescription? {
val describeTopics: DescribeTopicsResult = adminClient.describeTopics(Arrays.asList(name))
val values: Collection<KafkaFuture<TopicDescription>> = describeTopics.values().values
if (values.isEmpty()) {
kInfo("找不到描述信息")
} else {
for (value in values) {
return value.get()
}
}
return null
}
fun produce(topic: String, value: String, key: String? = null): Future<RecordMetadata>? {
val future =
mProducer.send(ProducerRecord(topic, key ?: "${System.nanoTime()}${RandomUtil.randomString(20)}", value))
return future
}
fun testProduce(topic: String, number: Long) {
thread {
for (i in 1..number) {
produce(topic, "test$i")?.get()
ThreadUtil.sleep(1000)
}
}
}
fun startConsumer() {
check(threadCount > 0)
threadExecutor = Executors.newFixedThreadPool(
threadCount,
ThreadUtil.newNamedThreadFactory(bootstrap.trim(), false)
) as ThreadPoolExecutor
threadList = (1..threadCount).map {
val kafkaConsumer = KafkaConsumer<String?, String?>(mProps)
val kafkaConsumerRunner = KafkaConsumerRunner(kafkaConsumer, topics, action)
kafkaConsumerRunner
}
threadList.forEach { threadExecutor.submit(it) }
}
fun startConsumerManualPartition() {
check(threadCount > 0)
threadExecutor = Executors.newFixedThreadPool(
threadCount,
ThreadUtil.newNamedThreadFactory(bootstrap.trim(), false)
) as ThreadPoolExecutor
threadListManualPartition = (1..threadCount).map {
val kafkaConsumerRunner = KafkaConsumerRunnerManualPartition(this, topics, it - 1, action)
kafkaConsumerRunner
}
threadListManualPartition.forEach { threadExecutor.submit(it) }
}
fun startConsumerManualPartition(partition: Int) {
check(threadCount > 0)
threadExecutor = Executors.newFixedThreadPool(
threadCount,
ThreadUtil.newNamedThreadFactory(bootstrap.trim(), false)
) as ThreadPoolExecutor
threadListManualPartition = (1..1).map {
val kafkaConsumerRunner = KafkaConsumerRunnerManualPartition(this, topics, partition, action)
kafkaConsumerRunner
}
threadListManualPartition.forEach { threadExecutor.submit(it) }
}
fun shutdown() {
threadList.forEach { it.shutdown() }
ThreadUtil.sleep(3000)
threadExecutor.shutdown()
threadExecutor.awaitTermination(10, TimeUnit.SECONDS)
kInfo("shutdown KafkaHelper")
}
}
fun main() {
// println(Long.MAX_VALUE / 1000 / 3600)
val kafkaHelper = KafkaHelper(
"55555.1.172.137:9092", "jchtest", listOf("ORIGIN_SNAP_IMAGE_INFO_TOPIC"),
Consumer {
val value =
it.value()
// println(it.partition().toString()+"offser"+it.offset().toString())
// val kafkaHelper = KafkaHelper("55555.1.43.110:9092", "jchtest", listOf("camera_status_r2p16"), Consumer {
// println(it.value())
},
OffsetReset.latest, 10, 10000
)
// try {
// kafkaHelper.deleteTopic("ITMS_CoreService_RealtimeDetectorCommand")
// } catch (e: Exception) {
// }
kafkaHelper.startConsumerManualPartition()
println("11111111111111111111111")
println("11111111111111111111111222222222222")
// kafkaHelper.deleteTopic("camera_tag_r2p16")
// kafkaHelper.createTopic("camera_status_r2p16",8,2)
// kafkaHelper.createTopic("camera_tag_r2p16",8,2)
// kafkaHelper.createTopic("ITMS_CoreService_RealtimeDetectorCommand", 8, 2)
// for (i in (1..8)) {
// val kafkaHelper = KafkaHelper("55555.1.43.110:9092", "group3", listOf("testr2p8"), Function {
// kInfo(
// it.value()
// .toString() + " group1 consumer1 ${it.partition()} ${it.offset()} ${it.key()} ${Date(it.timestamp()).toStrOrNow()}"
// )
// })
// kafkaHelper.startConsumer()
// }
// (1..10).toList().forEach {
// kafkaHelper.produce("testr2p8", "1gentest${it}" + DateUtil.now())
// }
// kafkaHelper.startConsumer()
// ThreadUtil.sleep(80000)
// println("end1")
}
| 0 | Kotlin | 9 | 44 | 01f515fecb6e90307fab44cbf866c4110d62786b | 8,826 | kotlin-backend-tool-library | Apache License 2.0 |
ok-m1l7-kmp/src/jvmMain/kotlin/java/SuspendJava.kt | otuskotlin | 375,767,209 | false | null | package ru.otus.otuskotlin.marketplace.kmp.java
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.runBlocking
import ru.otus.otuskotlin.marketplace.kmp.SuspendKmp
class SuspendJava {
@JvmName("susp")
fun susp() = runBlocking { SuspendKmp().susp() }
@JvmOverloads
fun manyDefaults(a: String = "a-val", b: String = "b-val", c: String = "c-val") {
println("a = $a, b = $b, c = $c")
}
companion object {
@JvmStatic
fun suspMany(vararg susps: SuspendJava): Collection<String> = runBlocking {
susps
.asFlow()
.map { async { it.susp() } }
.toList()
.awaitAll()
}
}
}
// Requires JDK 15
//@JvmRecord
data class X(
@JvmField
val x: String = ""
)
| 0 | null | 5 | 9 | f7b000e861fb35b5e0a641782fb7fe746814da31 | 940 | 202105-otuskotlin-marketplace | MIT License |
app/src/main/java/com/fitmate/fitmate/data/source/remote/CertificationRecordService.kt | Workout-Study | 770,138,955 | false | {"Kotlin": 355008, "Java": 2038} | package com.fitmate.fitmate.data.source.remote
import com.fitmate.fitmate.data.model.dto.CertificationRecordDto
import com.fitmate.fitmate.data.model.dto.CertificationRecordResponseDto
import com.fitmate.fitmate.data.model.dto.ResisterCertificationRecordDto
import com.fitmate.fitmate.data.model.dto.ResisterCertificationRecordResponseDto
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.POST
interface CertificationRecordService {
//@POST("records")
@POST("my-fit-service/records")
suspend fun postCertificationRecord(@Body requestBody: CertificationRecordDto): Response<CertificationRecordResponseDto>
//@POST("mates")
@POST("my-fit-service/certifications")
suspend fun postCertificationRecordToFitGroup(@Body requestBody: ResisterCertificationRecordDto): Response<ResisterCertificationRecordResponseDto>
} | 23 | Kotlin | 0 | 0 | 053aadeefededd934be756804b10650fb2449c12 | 864 | WorkoutStudy_Android | The Unlicense |
app/src/main/java/com/hashapps/cadenas/CadenasApplication.kt | GaloisInc | 873,867,559 | false | {"Kotlin": 297817} | package com.hashapps.cadenas
import android.app.Application
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import com.hashapps.cadenas.data.AppContainer
import com.hashapps.cadenas.data.AppDataContainer
/**
* The _true_ entrypoint of the Cadenas application, constructed before
* [MainActivity].
*
* The [Application] houses an [AppContainer], holding references to all of the
* data sources driving the UI. This setup ensures that data is available from
* application startup.
*/
class CadenasApplication : Application() {
lateinit var container: AppContainer
override fun onCreate() {
super.onCreate()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = getString(R.string.notification_channel_name)
val descriptionText = getString(R.string.notification_channel_description)
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
description = descriptionText
}
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
container = AppDataContainer(this)
}
companion object {
const val CHANNEL_ID: String = "model_management"
}
} | 1 | Kotlin | 0 | 0 | 13bec2fb2959936fce8d3461518cc2b3e542540c | 1,508 | Cadenas | MIT License |
app/src/main/java/com/example/cow_cow/PlayerFragment/PlayerStatsFragment.kt | Stffhgn | 862,080,800 | false | {"Kotlin": 328413} | package com.example.cow_cow.PlayerFragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.cow_cow.adapters.AchievementsAdapter
import com.example.cow_cow.databinding.FragmentPlayerStatsBinding
import com.example.cow_cow.viewModels.PlayerViewModel
class PlayerStatsFragment : Fragment() {
private lateinit var binding: FragmentPlayerStatsBinding
private lateinit var playerViewModel: PlayerViewModel
private lateinit var achievementsAdapter: AchievementsAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentPlayerStatsBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Initialize ViewModel
playerViewModel = ViewModelProvider(requireActivity()).get(PlayerViewModel::class.java)
// Initialize the RecyclerView for achievements
achievementsAdapter = AchievementsAdapter(mutableListOf())
binding.achievementsRecyclerView.apply {
layoutManager = LinearLayoutManager(context)
adapter = achievementsAdapter
}
// Observe player data
playerViewModel.selectedPlayer.observe(viewLifecycleOwner, Observer { player ->
player?.let {
// Update UI with player data
binding.playerNameTextView.text = it.name
binding.totalScoreTextView.text = "Total Score: ${it.calculateTotalPoints()}"
// Update achievements
achievementsAdapter.updateAchievements(it.achievements)
}
})
}
}
| 0 | Kotlin | 0 | 0 | da1653f897c39d58f22b4d3da70c87ede1a316fc | 2,019 | cowcow | MIT License |
app/src/main/java/com/example/cow_cow/PlayerFragment/PlayerStatsFragment.kt | Stffhgn | 862,080,800 | false | {"Kotlin": 328413} | package com.example.cow_cow.PlayerFragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.cow_cow.adapters.AchievementsAdapter
import com.example.cow_cow.databinding.FragmentPlayerStatsBinding
import com.example.cow_cow.viewModels.PlayerViewModel
class PlayerStatsFragment : Fragment() {
private lateinit var binding: FragmentPlayerStatsBinding
private lateinit var playerViewModel: PlayerViewModel
private lateinit var achievementsAdapter: AchievementsAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentPlayerStatsBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Initialize ViewModel
playerViewModel = ViewModelProvider(requireActivity()).get(PlayerViewModel::class.java)
// Initialize the RecyclerView for achievements
achievementsAdapter = AchievementsAdapter(mutableListOf())
binding.achievementsRecyclerView.apply {
layoutManager = LinearLayoutManager(context)
adapter = achievementsAdapter
}
// Observe player data
playerViewModel.selectedPlayer.observe(viewLifecycleOwner, Observer { player ->
player?.let {
// Update UI with player data
binding.playerNameTextView.text = it.name
binding.totalScoreTextView.text = "Total Score: ${it.calculateTotalPoints()}"
// Update achievements
achievementsAdapter.updateAchievements(it.achievements)
}
})
}
}
| 0 | Kotlin | 0 | 0 | da1653f897c39d58f22b4d3da70c87ede1a316fc | 2,019 | cowcow | MIT License |
lib/permissions/src/main/java/se/gustavkarlsson/skylight/android/lib/permissions/Access.kt | wowselim | 288,922,417 | true | {"Kotlin": 316543} | package se.gustavkarlsson.skylight.android.lib.permissions
enum class Access {
Unknown, Granted, Denied, DeniedForever
}
| 0 | null | 0 | 0 | 4da1731aca92d4e6d4b0e8128ca504fc0b3820b9 | 126 | skylight-android | MIT License |
feature/notelist/src/main/java/joonas/niemi/jnotes/feature/notelist/NotesView.kt | jopakka | 835,792,423 | false | {"Kotlin": 78086} | package joonas.niemi.jnotes.feature.notelist
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import joonas.niemi.jnotes.core.designsystem.theme.JNotesTheme
import joonas.niemi.jnotes.core.model.Note
import joonas.niemi.jnotes.feature.notelist.ui.NoteItem
@Composable
fun NotesView(
modifier: Modifier = Modifier,
viewModel: NotesViewModel = hiltViewModel()
) {
val notes by viewModel.notes.collectAsStateWithLifecycle()
NotesViewContent(modifier = modifier, notes = notes)
}
@Composable
private fun NotesViewContent(
notes: Map<String, Note>,
modifier: Modifier = Modifier,
) {
val noteValues = remember(notes.values) { notes.values.toList() }
LazyColumn(
modifier = modifier,
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
items(
items = noteValues,
key = { it.id },
) {
NoteItem(note = it)
}
}
}
@Preview
@Composable
private fun NotesViewPreview() {
JNotesTheme {
NotesViewContent(
notes = mapOf(
"1" to Note(
id = "1",
title = "Title 1",
content = "Content 1",
userId = "",
createdAt = 1722407777000
),
"2" to Note(
id = "2",
title = "Title 2",
content = "Content 2",
userId = "",
createdAt = 1712407777000
),
"3" to Note(
id = "3",
title = "Title 3",
content = "Content 3",
userId = "",
createdAt = 1702407777000
),
"4" to Note(
id = "4",
title = "Title 4",
content = "Content 4",
userId = "",
createdAt = 1682407777000
),
)
)
}
} | 0 | Kotlin | 0 | 0 | d37fc061b4905dfd7dbca3dfd82a737657fcd672 | 2,505 | jnotes | MIT License |
galleryImagePicker/src/main/java/com/samuelunknown/galleryImagePicker/extensions/ActivityExtensions.kt | Samuel-Unknown | 409,861,199 | false | {"Kotlin": 80917} | package com.samuelunknown.galleryImagePicker.extensions
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.FragmentActivity
import androidx.window.layout.WindowMetricsCalculator
internal fun FragmentActivity.calculateScreenHeightWithoutSystemBars(
callback: (height: Int, width: Int) -> Unit
) {
window.decorView.doOnApplyWindowInsetsListenerCompat() { _, windowInsetsCompat ->
val metrics = WindowMetricsCalculator.getOrCreate().computeCurrentWindowMetrics(this)
val insets = windowInsetsCompat.getInsets(WindowInsetsCompat.Type.systemBars())
val height = metrics.bounds.height() - insets.bottom - insets.top
val width = metrics.bounds.width() - insets.left - insets.right
callback.invoke(height, width)
}
} | 0 | Kotlin | 2 | 8 | 0a98c2d466c126c23d7f16f40d8684fec2223aa5 | 786 | Gallery-Image-Picker | Apache License 2.0 |
desktop/views/src/main/kotlin/com/soyle/stories/soylestories/FailedProjectsDialog.kt | Soyle-Productions | 239,407,827 | false | null | package com.soyle.stories.soylestories
import com.soyle.stories.common.NoSelectionModel
import com.soyle.stories.project.FailedProject
import com.soyle.stories.project.projectList.ProjectIssueViewModel
import javafx.geometry.Pos
import javafx.stage.Modality
import javafx.stage.StageStyle
import tornadofx.*
/**
* Created by Brendan
* Date: 2/16/2020
* Time: 12:02 PM
*/
class FailedProjectsDialog : View("Failed Projects") {
private val model = find<ApplicationModel>()
override val root = vbox {
prefHeight = 400.0
prefWidth = 400.0
spacing = 10.0
paddingAll = 10.0
label("The following projects failed to load:")
listview<ProjectIssueViewModel> {
selectionModel = NoSelectionModel()
isFocusTraversable = false
cellFragment(fragment = FailedProject::class)
itemsProperty().bind(model.failedProjects)
}
hbox(alignment = Pos.CENTER_RIGHT) {
button("Ignore All") {
action {
}
}
}
}
init {
model.isFailedProjectDialogVisible.onChange {
if (it == true) openModal(
StageStyle.UTILITY,
Modality.APPLICATION_MODAL,
escapeClosesWindow = false,
owner = null,
block = true,
resizable = true
) else close()
}
}
}
| 45 | Kotlin | 0 | 9 | 1a110536865250dcd8d29270d003315062f2b032 | 1,445 | soyle-stories | Apache License 2.0 |
src/Day05.kt | JanTie | 573,131,468 | false | {"Kotlin": 31854} | fun main() {
fun executeInstructions(
input: List<String>,
transactionHandling: (map: MutableMap<Int, List<Char>>, amount: Int, from: Int, to: Int) -> Unit,
): Map<Int, List<Char>> {
val dividerIndex = input.indexOfFirst { it.isBlank() }
val map = input.subList(0, dividerIndex - 1)
val indices = input.subList(dividerIndex - 1, dividerIndex)[0]
val mutableMap = indices
.filter { !it.isWhitespace() }
.map { indices.indexOf(it) }
.associate { index ->
indices[index].digitToInt() to map.reversed()
.mapNotNull { it.getOrNull(index)?.takeIf { !it.isWhitespace() } }
}
.toMutableMap()
val instructions = input.subList(dividerIndex + 1, input.size)
.map {
it.split("move ", " from ", " to ")
.mapNotNull { it.toIntOrNull() }
}
instructions.forEach { (amount, from, to) ->
transactionHandling(mutableMap, amount, from, to)
}
return mutableMap
}
fun part1(input: List<String>): String {
return executeInstructions(input) { map, amount, from, to ->
(0 until amount).forEach {
val char: Char = map[from]!!.last()
map[from] = map[from]!!.dropLast(1)
map[to] = map[to]!! + char
}
}
.map { it.value.last() }
.joinToString("")
}
fun part2(input: List<String>): String {
return executeInstructions(input) { map, amount, from, to ->
val chars: List<Char> = map[from]!!.takeLast(amount)
map[from] = map[from]!!.dropLast(amount)
map[to] = map[to]!! + chars
}
.map { it.value.last() }
.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
val input = readInput("Day05")
check(part1(testInput) == "CMZ")
println(part1(input))
check(part2(testInput) == "MCD")
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 3452e167f7afe291960d41b6fe86d79fd821a545 | 2,143 | advent-of-code-2022 | Apache License 2.0 |
core/src/commonMain/kotlin/krest/StagedProgressTaskIdentity.kt | aSoft-Ltd | 578,826,515 | false | {"Kotlin": 20803} | package krest
interface StagedProgressTaskIdentity<out T : Task<*>, R> : TaskIdentity<T> | 1 | Kotlin | 0 | 0 | d9dc740be8f0fb40cf0ceee41fcd0007c4d1264a | 89 | krest | MIT License |
src/main/kotlin/ru/krindra/vknorthtypes/widgets/WidgetsCommentReplies.kt | kravandir | 745,597,090 | false | {"Kotlin": 633233} | package ru.krindra.vknorthtypes.widgets
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import ru.krindra.vknorthtypes.base.BaseBoolInt
@Serializable
data class WidgetsCommentReplies (
@SerialName("can_view") val canView: BaseBoolInt? = null,
@SerialName("replies") val replies: List<WidgetsCommentRepliesItem>? = null,
@SerialName("count") val count: Int? = null,
@SerialName("can_post") val canPost: BaseBoolInt? = null,
@SerialName("groups_can_post") val groupsCanPost: BaseBoolInt? = null,
)
| 0 | Kotlin | 0 | 0 | 508d2d1d59c4606a99af60b924c6509cfec6ef6c | 552 | VkNorthTypes | MIT License |
app/src/main/java/org/stepic/droid/web/NotificationRequest.kt | pk-codebox-evo | 71,148,437 | true | {"Java": 953853, "Kotlin": 329672, "CSS": 3721, "Shell": 345} | package org.stepic.droid.web
import org.stepic.droid.notifications.model.Notification
class NotificationRequest {
var notification: Notification
constructor(notification: Notification) {
this.notification = notification
}
}
| 0 | Java | 0 | 0 | d9a6b303f9d94035fcc5d3dc47b0252c02805e8b | 247 | stepik-android | Apache License 2.0 |
ui/src/main/java/com/pyamsoft/tickertape/ui/BlankScreen.kt | pyamsoft | 371,196,339 | false | null | package com.pyamsoft.tickertape.ui
import androidx.annotation.DrawableRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import coil.ImageLoader
import coil.compose.rememberImagePainter
import com.pyamsoft.pydroid.theme.keylines
private val MIN_IMAGE_HEIGHT = 120.dp
@Composable
private fun OuchScreen(
modifier: Modifier = Modifier,
imageLoader: ImageLoader,
@DrawableRes image: Int,
illustrationBy: String,
illustrationLink: String,
topContent: @Composable ColumnScope.() -> Unit = {},
bottomContent: @Composable ColumnScope.() -> Unit = {},
) {
BlankScreen(
modifier = modifier,
imageLoader = imageLoader,
image = image,
illustrationBy = illustrationBy,
illustrationLink = illustrationLink,
from = "Ouch!",
bottomContent = bottomContent,
topContent = topContent,
)
}
@Composable
fun KarinaTsoyScreen(
modifier: Modifier = Modifier,
imageLoader: ImageLoader,
@DrawableRes image: Int,
topContent: @Composable ColumnScope.() -> Unit = {},
bottomContent: @Composable ColumnScope.() -> Unit = {},
) {
OuchScreen(
modifier = modifier,
imageLoader = imageLoader,
image = image,
illustrationBy = "Karina Tsoy",
illustrationLink = "https://icons8.com/illustrations/author/602aac63487a405cbf8ba256",
bottomContent = bottomContent,
topContent = topContent,
)
}
@Composable
fun PolinaGolubevaScreen(
modifier: Modifier = Modifier,
imageLoader: ImageLoader,
@DrawableRes image: Int,
topContent: @Composable ColumnScope.() -> Unit = {},
bottomContent: @Composable ColumnScope.() -> Unit = {},
) {
OuchScreen(
modifier = modifier,
imageLoader = imageLoader,
image = image,
illustrationBy = "Polina Golubeva",
illustrationLink = "https://icons8.com/illustrations/author/5f32934501d0360017af905d",
bottomContent = bottomContent,
topContent = topContent,
)
}
@Composable
fun AnnaGoldScreen(
modifier: Modifier = Modifier,
imageLoader: ImageLoader,
@DrawableRes image: Int,
topContent: @Composable ColumnScope.() -> Unit = {},
bottomContent: @Composable ColumnScope.() -> Unit = {},
) {
OuchScreen(
modifier = modifier,
imageLoader = imageLoader,
image = image,
illustrationBy = "Anna Golde",
illustrationLink = "https://icons8.com/illustrations/author/5bf673a26205ee0017636674",
bottomContent = bottomContent,
topContent = topContent,
)
}
@Composable
fun ErrorScreen(
modifier: Modifier = Modifier,
imageLoader: ImageLoader,
topContent: @Composable ColumnScope.() -> Unit = {},
bottomContent: @Composable ColumnScope.() -> Unit = {},
) {
OuchScreen(
modifier = modifier,
imageLoader = imageLoader,
image = R.drawable.error,
illustrationBy = "Olha Khomich",
illustrationLink = "https://icons8.com/illustrations/author/5eb2a7bd01d0360019f124e7",
bottomContent = bottomContent,
topContent = topContent,
)
}
@Composable
fun BlankScreen(
modifier: Modifier = Modifier,
imageLoader: ImageLoader,
@DrawableRes image: Int,
illustrationBy: String,
illustrationLink: String,
from: String,
topContent: @Composable ColumnScope.() -> Unit = {},
bottomContent: @Composable ColumnScope.() -> Unit = {},
) {
Column(
modifier = modifier,
horizontalAlignment = Alignment.CenterHorizontally,
) {
topContent()
Image(
modifier = Modifier.fillMaxWidth().heightIn(min = MIN_IMAGE_HEIGHT),
painter =
rememberImagePainter(
data = image,
imageLoader = imageLoader,
),
contentScale = ContentScale.FillWidth,
contentDescription = null,
)
Icons8RequiredAttribution(
modifier =
Modifier.padding(horizontal = MaterialTheme.keylines.content)
.padding(bottom = MaterialTheme.keylines.content),
illustrationBy = illustrationBy,
illustrationLink = illustrationLink,
from = from,
fromLink = "https://icons8.com/illustrations",
)
bottomContent()
}
}
| 2 | Kotlin | 0 | 6 | c5309984f17de290ce2fb82120b4699cc8227b65 | 4,677 | tickertape | Apache License 2.0 |
app/src/main/java/com/example/android/githubaccountsearch/models/License.kt | manamanah | 226,307,180 | false | null | package com.example.android.githubaccountsearch.models
data class License(
val name: String
) | 0 | Kotlin | 0 | 0 | d97fb7e6c2f65879605bbeee9890577c20a10585 | 98 | GithubAccountSearch | MIT License |
app/src/main/java/com/trueedu/inout/db/InOutRecord.kt | seirion | 234,075,186 | false | null | package com.trueedu.inout.db
import androidx.room.*
@Entity
data class InOutRecord(
var inOut: InOut,
var timestamp: Long
) {
@PrimaryKey(autoGenerate = true)
var id: Long? = null
}
enum class InOut(val value: Int) {
IN(0),
OUT(1),
}
class InOutConverters {
@TypeConverter
fun toInOut(value: Int): InOut {
return when (value) {
0 -> InOut.IN
else -> InOut.OUT
}
}
@TypeConverter
fun fromInOut(inOut: InOut): Int {
return inOut.value
}
} | 1 | Kotlin | 0 | 0 | 5095bf81bcff562517f5fe5294e34243404a8bbd | 537 | in-and-out | Apache License 2.0 |
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsworkload/service/staff/SavePersonManagerService.kt | ministryofjustice | 378,843,394 | false | {"PLpgSQL": 472290, "Kotlin": 436140, "Dockerfile": 1715} | package uk.gov.justice.digital.hmpps.hmppsworkload.service.staff
import uk.gov.justice.digital.hmpps.hmppsworkload.client.dto.StaffMember
import uk.gov.justice.digital.hmpps.hmppsworkload.domain.SaveResult
import uk.gov.justice.digital.hmpps.hmppsworkload.jpa.entity.PersonManagerEntity
interface SavePersonManagerService {
suspend fun savePersonManager(teamCode: String, deliusStaff: StaffMember, loggedInUser: String, crn: String): SaveResult<PersonManagerEntity>
}
| 14 | PLpgSQL | 0 | 0 | 93ad98d7641fa391aae2753b3cefd38b543f1e74 | 473 | hmpps-workload | MIT License |
src/main/kotlin/io/github/kryszak/gwatlin/api/miscellaneous/model/Novelty.kt | Kryszak | 214,791,260 | false | {"Kotlin": 443350, "Shell": 654} | package io.github.kryszak.gwatlin.api.miscellaneous.model
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* Data model for novelty object
*/
@Serializable
data class Novelty(
val id: Int,
val name: String,
val description: String,
val icon: String,
val slot: String,
@SerialName("unlock_item") val unlockItem: List<Int>?
)
| 1 | Kotlin | 1 | 6 | 657798c9ca17dfcdbca6e45196dfd15443d63751 | 413 | gwatlin | MIT License |
plugins/git4idea/src/git4idea/config/InlineErrorNotifier.kt | dansanduleac | 232,394,039 | false | null | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.config
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.progress.util.BackgroundTaskUtil
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.ui.JBColor
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.util.ui.AsyncProcessIcon
import com.intellij.util.ui.components.BorderLayoutPanel
import org.jetbrains.annotations.CalledInAwt
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.SwingConstants
internal interface InlineComponent {
fun showProgress(text: String)
fun showError(errorText: String, link: LinkLabel<*>? = null)
fun showMessage(text: String)
fun hideProgress()
}
internal open class InlineErrorNotifier(private val inlineComponent: InlineComponent,
private val modalityState: ModalityState,
private val disposable: Disposable) : ErrorNotifier {
var isTaskInProgress: Boolean = false // Check from EDT only
private set
override fun showError(text: String, description: String?, fixOption: ErrorNotifier.FixOption) {
invokeAndWaitIfNeeded(modalityState) {
val linkLabel = LinkLabel<Any>(fixOption.text, null) { _, _ ->
fixOption.fix()
}
val message = if (description == null) text else "$text\n$description"
inlineComponent.showError(message, linkLabel)
}
}
override fun showError(text: String) {
invokeAndWaitIfNeeded(modalityState) {
inlineComponent.showError(text)
}
}
@CalledInAwt
override fun executeTask(title: String, cancellable: Boolean, action: () -> Unit) {
inlineComponent.showProgress(title)
isTaskInProgress = true
ApplicationManager.getApplication().executeOnPooledThread {
try {
BackgroundTaskUtil.runUnderDisposeAwareIndicator(disposable, Runnable {
action()
})
}
finally {
invokeAndWaitIfNeeded(modalityState) {
isTaskInProgress = false
}
}
}
}
override fun changeProgressTitle(text: String) {
invokeAndWaitIfNeeded(modalityState) {
inlineComponent.showProgress(text)
}
}
override fun showMessage(text: String) {
invokeAndWaitIfNeeded(modalityState) {
inlineComponent.showMessage(text)
}
}
override fun hideProgress() {
invokeAndWaitIfNeeded(modalityState) {
inlineComponent.hideProgress()
}
}
}
class GitExecutableInlineComponent(private val container: BorderLayoutPanel, private val panelToValidate: JPanel?) : InlineComponent {
private val busyIcon: AsyncProcessIcon = createBusyIcon()
override fun showProgress(text: String) {
container.removeAll()
busyIcon.resume()
val label = JBLabel(text).apply {
foreground = JBColor.GRAY
}
container.addToLeft(busyIcon)
container.addToCenter(label)
panelToValidate?.validate()
}
override fun showError(errorText: String, link: LinkLabel<*>?) {
busyIcon.suspend()
container.removeAll()
val label = multilineLabel(errorText).apply {
foreground = DialogWrapper.ERROR_FOREGROUND_COLOR
}
container.addToCenter(label)
if (link != null) {
link.verticalAlignment = SwingConstants.TOP
container.addToRight(link)
}
panelToValidate?.validate()
}
override fun showMessage(text: String) {
busyIcon.suspend()
container.removeAll()
container.addToLeft(JBLabel(text))
panelToValidate?.validate()
}
override fun hideProgress() {
busyIcon.suspend()
container.removeAll()
panelToValidate?.validate()
}
private fun createBusyIcon(): AsyncProcessIcon = AsyncProcessIcon(
toString()).apply {
isOpaque = false
setPaintPassiveIcon(false)
}
private fun multilineLabel(text: String): JComponent = JBLabel(text).apply {
setAllowAutoWrapping(true)
setCopyable(true)
}
}
| 1 | null | 1 | 1 | 9d972139413a00942fd4a0c58998ac8a2d80a493 | 4,253 | intellij-community | Apache License 2.0 |
app/src/androidTest/kotlin/com/quittle/a11yally/activity/LearnMoreActivityInstrumentationTest.kt | quittle | 135,217,260 | false | null | package com.quittle.a11yally.activity
import android.annotation.SuppressLint
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.scrollTo
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers
import androidx.test.espresso.matcher.ViewMatchers.isCompletelyDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withContentDescription
import androidx.test.espresso.matcher.ViewMatchers.withEffectiveVisibility
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.quittle.a11yally.DisableAnimationsRule
import com.quittle.a11yally.R
import com.quittle.a11yally.activity.welcome.Welcome2Activity
import com.quittle.a11yally.clearSharedPreferences
import com.quittle.a11yally.fullySetUpPermissions
import com.quittle.a11yally.fullyTearDownPermissions
import com.quittle.a11yally.getCurrentActivity
import com.quittle.a11yally.launchActivity
import com.quittle.a11yally.withPreferenceProvider
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.runner.RunWith
@SuppressLint("PrivateResource")
@RunWith(AndroidJUnit4::class)
class LearnMoreActivityInstrumentationTest {
@get:Rule
val mDisableAnimationsRule = DisableAnimationsRule()
@Before
fun setUp() {
fullyTearDownPermissions()
clearSharedPreferences()
launchActivity(LearnMoreActivity::class)
}
@Test
fun getStartedButtonWorks() {
onView(withId(R.id.get_started))
.perform(scrollTo())
.check(matches(isCompletelyDisplayed()))
.perform(click())
assertEquals(Welcome2Activity::class.java, getCurrentActivity().javaClass)
// Check in list view
onView(withText(R.string.welcome2_activity_pick_subtitle))
}
@Test
fun getStartedButtonHiddenAfterTutorial() {
withPreferenceProvider {
setShowTutorial(false)
}
launchActivity(LearnMoreActivity::class)
onView(withId(R.id.get_started))
.check(matches(withEffectiveVisibility(ViewMatchers.Visibility.GONE)))
}
@Test
fun backButtonWorksFromWelcomeActivity() {
launchActivity(Welcome2Activity::class)
onView(withId(R.id.learn_more))
.perform(scrollTo(), click())
onView(withContentDescription(R.string.abc_action_bar_up_description))
.check(matches(isCompletelyDisplayed()))
.perform(click())
assertEquals(Welcome2Activity::class.java, getCurrentActivity().javaClass)
// Check in default view
onView(withText(R.string.welcome2_activity_subtitle))
}
@Test
fun backButtonWorksFromMainActivity() {
fullySetUpPermissions()
launchActivity(MainActivity::class)
onView(withContentDescription(R.string.abc_action_menu_overflow_description))
.perform(click())
onView(withText(R.string.show_learn_more))
.perform(click())
assertEquals(LearnMoreActivity::class.java, getCurrentActivity().javaClass)
onView(withContentDescription(R.string.abc_action_bar_up_description))
.perform(click())
assertEquals(MainActivity::class.java, getCurrentActivity().javaClass)
}
}
| 48 | Kotlin | 4 | 22 | b277dda83087b12774198ec8372914278088da3a | 3,529 | a11y-ally | Apache License 2.0 |
alchemist/alchemist-cognitive-agents/src/main/kotlin/it/unibo/alchemist/model/implementations/actions/Combine.kt | paagamelo | 216,596,756 | false | null | package it.unibo.alchemist.model.implementations.actions
import it.unibo.alchemist.model.interfaces.Environment
import it.unibo.alchemist.model.interfaces.Pedestrian
import it.unibo.alchemist.model.interfaces.Position
import it.unibo.alchemist.model.interfaces.Reaction
import it.unibo.alchemist.model.interfaces.SteeringAction
import it.unibo.alchemist.model.interfaces.SteeringStrategy
import it.unibo.alchemist.model.interfaces.movestrategies.TargetSelectionStrategy
/**
* Combination of multiple steering actions.
*
* @param env
* the environment inside which the pedestrian moves.
* @param pedestrian
* the owner of this action.
* @param actions
* the list of actions to combine to determine the pedestrian movement.
* @param steerStrategy
* the logic according to the steering actions are combined.
*/
class Combine<T, P : Position<P>>(
env: Environment<T, P>,
reaction: Reaction<T>,
pedestrian: Pedestrian<T>,
private val actions: List<SteeringAction<T, P>>,
private val steerStrategy: SteeringStrategy<T, P>
) : SteeringActionImpl<T, P>(
env,
reaction,
pedestrian,
TargetSelectionStrategy { steerStrategy.computeTarget(actions) }
) {
override fun getDestination(current: P, target: P, maxWalk: Double): P = steerStrategy.computeNextPosition(actions)
} | 1 | null | 1 | 1 | db0adfc2d9006d143bc99ecf82cd1285f7ac3ba6 | 1,348 | Alchemist | Creative Commons Attribution 3.0 Unported |
core/src/test/java/com/larryhsiao/nyx/jdk/FileTest.kt | LarryHsiao | 192,473,048 | false | {"Gradle": 6, "Markdown": 1, "INI": 3, "Shell": 1, "Text": 8, "Ignore List": 4, "Batchfile": 1, "YAML": 1, "Kotlin": 119, "Java": 96, "SQL": 4, "Java Properties": 1, "Proguard": 1, "XML": 115, "JSON": 3, "HTML": 1, "CSS": 1} | package com.larryhsiao.nyx.jdk
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import java.io.File
class FileTest {
/**
* The file path should not changed after invoked renameTo.
*/
@Test
internal fun renameTo() {
val file = File("/")
file.renameTo(File("/temp"))
Assertions.assertEquals(
"/",
file.absolutePath
)
}
} | 15 | Kotlin | 1 | 1 | 518f547f913a48394f7301eff89ec7a43d7be80e | 427 | Nyx | MIT License |
compose-mds/src/main/java/ch/sbb/compose_mds/sbbicons/medium/FreightWagonGlobeMedium.kt | SchweizerischeBundesbahnen | 853,290,161 | false | {"Kotlin": 6728512} | package ch.sbb.compose_mds.sbbicons.medium
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import ch.sbb.compose_mds.sbbicons.MediumGroup
public val MediumGroup.FreightWagonGlobeMedium: ImageVector
get() {
if (_freightWagonGlobeMedium != null) {
return _freightWagonGlobeMedium!!
}
_freightWagonGlobeMedium = Builder(name = "FreightWagonGlobeMedium", defaultWidth = 36.0.dp,
defaultHeight = 36.0.dp, viewportWidth = 36.0f, viewportHeight = 36.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd) {
moveTo(8.764f, 13.75f)
arcToRelative(8.45f, 8.45f, 0.0f, false, true, 0.984f, -3.5f)
horizontalLineToRelative(2.988f)
arcToRelative(16.3f, 16.3f, 0.0f, false, false, -0.479f, 3.5f)
close()
moveTo(12.257f, 14.75f)
lineTo(8.764f, 14.75f)
arcToRelative(8.45f, 8.45f, 0.0f, false, false, 0.984f, 3.5f)
horizontalLineToRelative(2.989f)
arcToRelative(16.3f, 16.3f, 0.0f, false, true, -0.48f, -3.5f)
moveToRelative(1.513f, 3.5f)
arcToRelative(15.2f, 15.2f, 0.0f, false, true, -0.512f, -3.5f)
horizontalLineToRelative(3.492f)
verticalLineToRelative(3.5f)
close()
moveTo(17.75f, 18.25f)
verticalLineToRelative(-3.5f)
horizontalLineToRelative(3.492f)
arcToRelative(15.2f, 15.2f, 0.0f, false, true, -0.512f, 3.5f)
close()
moveTo(14.08f, 19.25f)
horizontalLineToRelative(2.67f)
verticalLineToRelative(3.485f)
arcToRelative(9.0f, 9.0f, 0.0f, false, true, -0.838f, -0.09f)
curveToRelative(-0.75f, -0.951f, -1.375f, -2.101f, -1.831f, -3.395f)
moveToRelative(3.67f, 0.0f)
verticalLineToRelative(3.485f)
quadToRelative(0.425f, -0.024f, 0.838f, -0.09f)
curveToRelative(0.75f, -0.951f, 1.375f, -2.101f, 1.831f, -3.395f)
close()
moveTo(17.751f, 10.25f)
verticalLineToRelative(3.5f)
horizontalLineToRelative(3.492f)
arcToRelative(15.2f, 15.2f, 0.0f, false, false, -0.512f, -3.5f)
close()
moveTo(16.751f, 13.75f)
verticalLineToRelative(-3.5f)
horizontalLineToRelative(-2.98f)
arcToRelative(15.2f, 15.2f, 0.0f, false, false, -0.512f, 3.5f)
close()
moveTo(20.421f, 9.25f)
horizontalLineToRelative(-2.67f)
lineTo(17.751f, 5.764f)
quadToRelative(0.425f, 0.026f, 0.838f, 0.09f)
curveToRelative(0.75f, 0.952f, 1.375f, 2.102f, 1.832f, 3.396f)
moveToRelative(-3.67f, 0.0f)
lineTo(16.751f, 5.764f)
arcToRelative(9.0f, 9.0f, 0.0f, false, false, -0.838f, 0.09f)
curveToRelative(-0.75f, 0.952f, -1.376f, 2.102f, -1.832f, 3.396f)
close()
moveTo(13.026f, 19.25f)
horizontalLineToRelative(-2.65f)
arcToRelative(8.5f, 8.5f, 0.0f, false, false, 4.051f, 3.02f)
arcToRelative(13.5f, 13.5f, 0.0f, false, true, -1.401f, -3.02f)
moveToRelative(1.4f, -13.02f)
arcToRelative(8.5f, 8.5f, 0.0f, false, false, -4.05f, 3.02f)
horizontalLineToRelative(2.65f)
curveToRelative(0.358f, -1.1f, 0.832f, -2.116f, 1.4f, -3.02f)
moveToRelative(7.818f, 7.52f)
arcToRelative(16.3f, 16.3f, 0.0f, false, false, -0.48f, -3.5f)
horizontalLineToRelative(2.989f)
arcToRelative(8.45f, 8.45f, 0.0f, false, true, 0.983f, 3.5f)
close()
moveTo(22.244f, 14.75f)
arcToRelative(16.3f, 16.3f, 0.0f, false, true, -0.48f, 3.5f)
horizontalLineToRelative(2.989f)
arcToRelative(8.45f, 8.45f, 0.0f, false, false, 0.983f, -3.5f)
close()
moveTo(21.476f, 19.25f)
arcToRelative(13.5f, 13.5f, 0.0f, false, true, -1.401f, 3.02f)
arcToRelative(8.5f, 8.5f, 0.0f, false, false, 4.05f, -3.02f)
close()
moveTo(20.076f, 6.23f)
curveToRelative(0.568f, 0.904f, 1.042f, 1.92f, 1.4f, 3.02f)
horizontalLineToRelative(2.65f)
arcToRelative(8.5f, 8.5f, 0.0f, false, false, -4.05f, -3.02f)
moveTo(17.25f, 4.75f)
arcToRelative(9.5f, 9.5f, 0.0f, true, false, 0.0f, 19.0f)
arcToRelative(9.5f, 9.5f, 0.0f, false, false, 0.0f, -19.0f)
moveTo(23.75f, 30.0f)
verticalLineToRelative(-0.25f)
horizontalLineToRelative(3.5f)
lineTo(27.25f, 30.0f)
arcToRelative(1.75f, 1.75f, 0.0f, true, true, -3.5f, 0.0f)
moveToRelative(-1.0f, 0.0f)
verticalLineToRelative(-0.25f)
horizontalLineToRelative(-9.5f)
lineTo(13.25f, 30.0f)
arcToRelative(2.75f, 2.75f, 0.0f, true, true, -5.5f, 0.0f)
verticalLineToRelative(-0.25f)
horizontalLineToRelative(-1.5f)
verticalLineToRelative(-1.5f)
horizontalLineToRelative(-2.0f)
lineTo(4.25f, 30.0f)
horizontalLineToRelative(-1.0f)
verticalLineToRelative(-4.5f)
horizontalLineToRelative(1.0f)
verticalLineToRelative(1.75f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(-1.5f)
horizontalLineToRelative(23.5f)
verticalLineToRelative(1.5f)
horizontalLineToRelative(2.0f)
lineTo(31.75f, 25.5f)
horizontalLineToRelative(1.0f)
lineTo(32.75f, 30.0f)
horizontalLineToRelative(-1.0f)
verticalLineToRelative(-1.75f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(1.5f)
horizontalLineToRelative(-1.5f)
lineTo(28.25f, 30.0f)
arcToRelative(2.75f, 2.75f, 0.0f, true, true, -5.5f, 0.0f)
moveToRelative(-14.0f, -0.25f)
lineTo(8.75f, 30.0f)
arcToRelative(1.75f, 1.75f, 0.0f, true, false, 3.5f, 0.0f)
verticalLineToRelative(-0.25f)
close()
moveTo(7.25f, 28.75f)
horizontalLineToRelative(21.5f)
verticalLineToRelative(-2.0f)
lineTo(7.25f, 26.75f)
verticalLineToRelative(2.0f)
}
}
.build()
return _freightWagonGlobeMedium!!
}
private var _freightWagonGlobeMedium: ImageVector? = null
| 0 | Kotlin | 0 | 1 | 090a66a40e1e5a44d4da6209659287a68cae835d | 7,675 | mds-android-compose | MIT License |
compiler/testData/codegen/box/javaInterop/overrideWithGenericArrayParameterType.kt | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | // TARGET_BACKEND: JVM
// FILE: J.java
import java.util.List;
public interface J<T> {
String foo(T t, List<T[]> list);
}
// FILE: 1.kt
class A
class C : J<A> {
override fun foo(a: A, list: List<Array<A>>?): String = "OK"
}
fun box(): String {
val c: J<A> = C()
return c.foo(A(), null)
}
| 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 309 | kotlin | Apache License 2.0 |
PhoneDirectory/app/src/main/java/com/example/turkcelllab17/EklemeActivity.kt | ismailusta | 879,042,047 | false | {"Kotlin": 11355} | package com.example.turkcelllab17
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
class EklemeActivity : AppCompatActivity() {
var user: User? = null
var veriislem: VeriIslemleri
init {
veriislem = VeriIslemleri(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_ekleme)
// Pencere kenar boşluklarını ayarla
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
// Intent'ten kisi_id değerini al
val kisi_id = intent.getIntExtra("kisi_id", -1)
if (kisi_id == -1) {
// Yeni bir kullanıcı ekleniyor
user = User()
findViewById<Button>(R.id.Delete).visibility = View.GONE
} else {
// Mevcut bir kullanıcı düzenleniyor
user = veriislem.TekListe(kisi_id)
// Eğer user null değilse, alanları doldur
if (user != null) {
findViewById<EditText>(R.id.editTextText).setText(user?.name)
findViewById<EditText>(R.id.editTextTextEmailAddress).setText(user?.email)
findViewById<EditText>(R.id.editTextTextPassword).setText(user?.password)
findViewById<Button>(R.id.Delete).visibility = View.VISIBLE
} else {
// Kullanıcı bulunamazsa, silme butonunu gizle
findViewById<Button>(R.id.Delete).visibility = View.GONE
}
}
}
// Kullanıcıyı sil
fun delete(view: View) {
user?.id?.let {
veriislem.sil(it)
}
// İşlem sonrası aktiviteyi kapat
setResult(RESULT_OK)
finish()
}
// Kullanıcıyı kaydet
fun save(view: View) {
// EditText alanlarından verileri al ve user'a ata
user?.name = findViewById<EditText>(R.id.editTextText).text.toString()
user?.email = findViewById<EditText>(R.id.editTextTextEmailAddress).text.toString()
user?.password = findViewById<EditText>(R.id.editTextTextPassword).text.toString()
if (user?.id == null) {
// Yeni kullanıcı ekle
veriislem.Ekle(user!!)
} else {
// Mevcut kullanıcıyı güncelle
veriislem.Guncelle(user!!)
}
// İşlem sonrası aktiviteyi kapat
setResult(RESULT_OK)
finish()
}
}
| 0 | Kotlin | 0 | 0 | db4dae920a9ecfe2a70c7efb7c34c3cbe93abb8b | 2,886 | PhoneBookApp | MIT License |
src/main/kotlin/JacksonFunc.kt | delabassee | 143,419,599 | false | null | package com.fn.example.jackson
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.delabassee.Country
fun country(input: String): String {
return jacksonObjectMapper().writeValueAsString( listCountries(input) )
}
fun listCountries(input: String): List<Country> = when {
input.isEmpty() -> Country.getAll()
else -> Country.getAll().filteredOrAll {
it.name.contains(input.trim(), true)
}
}
private fun <T> List<T>.filteredOrAll(predicate: (T) -> Boolean): List<T> {
val filtered = filter(predicate)
return when {
filtered.isEmpty() -> this
else -> filtered
}
} | 0 | Kotlin | 0 | 0 | af318ddd062fd9334865c8a5f9fe262dc4013e03 | 636 | fn-kountry | Apache License 2.0 |
src/test/kotlin/com/kylecorry/sol/math/filters/LoessFilterTest.kt | kylecorry31 | 294,668,785 | false | null | package com.kylecorry.sol.math.filters
import com.kylecorry.sol.math.sumOfFloat
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
import kotlin.math.pow
class LoessFilterTest {
@Test
fun filter() {
val values = (0..100).map { it.toFloat() to it.toFloat() }
val filter = LoessFilter(0.3f, 4)
val actual = filter.filter(values.map { listOf(it.first) }, values.map { it.second })
val fitResiduals = actual.zip(values).sumOfFloat {
(it.second.second - it.first).pow(2)
}
assertEquals(0.0f, fitResiduals, 0.0001f)
}
@Test
fun filterEmpty() {
val values = emptyList<Pair<Float, Float>>()
val filter = LoessFilter(0.3f, 4)
val actual = filter.filter(values.map { listOf(it.first) }, values.map { it.second })
assertTrue(actual.isEmpty())
}
@Test
fun filterLessThan3() {
val values = listOf(1f to 1f, 2f to 2f)
val filter = LoessFilter(0.3f, 4)
val actual = filter.filter(values.map { listOf(it.first) }, values.map { it.second })
assertEquals(values.map { it.second }, actual)
}
@Test
fun filterMultipleWithSameX() {
val values = listOf(1f to 1f, 2f to 2f, 1f to 3f)
val filter = LoessFilter(0.3f, 4)
val actual = filter.filter(values.map { listOf(it.first) }, values.map { it.second })
assertEquals(values.map { it.second }, actual)
}
@Test
fun customDistanceFunction() {
val values = (0..100).map { it.toFloat() to it.toFloat() }
val filter = LoessFilter(0.3f, 4) { p1, p2 ->
p1.zip(p2).sumOfFloat { (it.first - it.second).pow(2) }
}
val actual = filter.filter(values.map { listOf(it.first) }, values.map { it.second })
val fitResiduals = actual.zip(values).sumOfFloat {
(it.second.second - it.first).pow(2)
}
assertEquals(0.0f, fitResiduals, 0.0001f)
}
} | 13 | null | 4 | 8 | d16a494dca765a21f066f99ddf923db87bb1f117 | 1,995 | sol | MIT License |
widgetssdk/src/test/java/com/glia/widgets/chat/domain/gva/IsGvaUseCaseTest.kt | salemove | 312,288,713 | false | {"Kotlin": 1945551, "Java": 459268, "Shell": 1802} | package com.glia.widgets.chat.domain.gva
import com.glia.androidsdk.chat.ChatMessage
import com.glia.widgets.chat.model.Gva
import org.json.JSONObject
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
class IsGvaUseCaseTest {
private lateinit var useCase: IsGvaUseCase
private lateinit var getGvaTypeUseCase: GetGvaTypeUseCase
private lateinit var chatMessage: ChatMessage
@Before
fun setUp() {
chatMessage = mock()
getGvaTypeUseCase = mock()
useCase = IsGvaUseCase(getGvaTypeUseCase)
}
@Test
fun `invoke returns true when gva type exists`() {
val metadata = JSONObject().put(Gva.Keys.TYPE, Gva.Type.PLAIN_TEXT.value)
whenever(chatMessage.metadata) doReturn metadata
whenever(getGvaTypeUseCase(metadata)) doReturn Gva.Type.PLAIN_TEXT
assertTrue(useCase(chatMessage))
}
@Test
fun `invoke returns false when gva type doesn't exist`() {
val metadata = JSONObject().put(Gva.Keys.TYPE, "asdfg")
whenever(chatMessage.metadata) doReturn metadata
whenever(getGvaTypeUseCase(metadata)) doReturn null
assertFalse(useCase(chatMessage))
}
}
| 3 | Kotlin | 1 | 7 | 40ee60fa683c155eee923b5c3ae1a2c0610f0677 | 1,340 | android-sdk-widgets | MIT License |
ui-toolkit/src/main/kotlin/io/snabble/sdk/widgets/snabble/devsettings/login/ui/DevSettingsLogin.kt | snabble | 124,525,499 | false | null | package io.snabble.sdk.widgets.snabble.devsettings.login.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.ImeAction.Companion.Send
import androidx.compose.ui.text.input.KeyboardType.Companion.Password
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
@Composable
internal fun DevSettingsLogin(
dismiss: () -> Unit,
login: (String) -> Unit,
onPasswordChange: (String) -> Unit,
showError: Boolean,
) {
var password by rememberSaveable { mutableStateOf("") }
Card(
modifier = Modifier.wrapContentSize(),
) {
Column(
modifier = Modifier
.padding(8.dp)
.wrapContentSize()
) {
Spacer(Modifier.height(16.dp))
PasswordField(
password = password,
onPasswordChange = {
onPasswordChange(it)
password = it
},
onAction = { login(password) }
)
if (showError) {
Spacer(modifier = Modifier.heightIn(8.dp))
Text(
modifier = Modifier.padding(horizontal = 16.dp),
text = "Wrong password!",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.error
)
}
Spacer(Modifier.height(16.dp))
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp),
horizontalArrangement = Arrangement.End
) {
TextButton(
modifier = Modifier.widthIn(min = 90.dp),
shape = MaterialTheme.shapes.extraLarge,
onClick = { dismiss() },
) {
Text(
text = "Cancel",
color = MaterialTheme.colorScheme.primary,
)
}
Spacer(Modifier.width(16.dp))
TextButton(
modifier = Modifier.widthIn(min = 90.dp),
shape = MaterialTheme.shapes.extraLarge,
onClick = { login(password) },
) {
Text(
text = "Activate",
color = MaterialTheme.colorScheme.primary,
)
}
}
Spacer(Modifier.height(16.dp))
}
}
}
@Composable
private fun PasswordField(
password: String,
onPasswordChange: (String) -> Unit,
onAction: () -> Unit,
) {
@OptIn(ExperimentalMaterial3Api::class)
OutlinedTextField(
value = password,
onValueChange = onPasswordChange,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp),
textStyle = MaterialTheme.typography.bodyLarge,
label = { androidx.compose.material3.Text(text = "Enter password") },
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(
keyboardType = Password,
imeAction = Send
),
keyboardActions = KeyboardActions(
onSend = { onAction() }
),
maxLines = 1,
singleLine = true,
)
}
@Preview
@Composable
private fun Preview() {
DevSettingsLogin(
dismiss = {},
login = {},
showError = true,
onPasswordChange = {}
)
}
| 2 | null | 1 | 6 | 182c7453c178a8fe5f20d472c2326a128bc96a0e | 4,831 | Android-SDK | MIT License |
support-theme/src/main/kotlin/co/anitrend/arch/theme/animator/contract/SupportAnimatorDuration.kt | fossabot | 223,555,788 | true | {"Gradle": 14, "Java Properties": 3, "Markdown": 7, "YAML": 2, "Shell": 1, "Text": 1, "Ignore List": 11, "Batchfile": 1, "Proguard": 10, "Kotlin": 158, "XML": 78, "INI": 6, "JSON": 8, "Java": 1} | package co.anitrend.arch.theme.animator.contract
/**
* Animation duration representation enum
*/
enum class SupportAnimatorDuration(val duration: Long) {
SHORT(250),
MEDIUM(500),
LONG(750)
}
| 0 | Kotlin | 0 | 0 | 50be1a136fc46fb0eaccc041ef40eca2f4c67771 | 206 | support-arch | Apache License 2.0 |
app/src/main/java/com/dp/logcatapp/fragments/savedlogs/SavedLogsViewModel.kt | Lilred1957 | 142,264,510 | true | {"Kotlin": 188258, "Java": 19532} | package com.dp.logcatapp.fragments.savedlogs
import android.app.Application
import android.arch.lifecycle.AndroidViewModel
import android.arch.lifecycle.LiveData
import android.content.Context
import android.net.Uri
import android.os.AsyncTask
import android.os.Build
import android.support.v4.provider.DocumentFile
import androidx.core.net.toUri
import com.dp.logcat.Logcat
import com.dp.logcat.LogcatStreamReader
import com.dp.logcatapp.fragments.logcatlive.LogcatLiveFragment
import com.dp.logcatapp.util.PreferenceKeys
import com.dp.logcatapp.util.Utils
import com.dp.logcatapp.util.getDefaultSharedPreferences
import com.dp.logger.Logger
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.lang.ref.WeakReference
internal class SavedLogsViewModel(application: Application) : AndroidViewModel(application) {
val fileNames: SavedLogsLiveData = SavedLogsLiveData(application)
val selectedItems = mutableSetOf<Int>()
}
data class LogFileInfo(val name: String,
val size: Long,
val sizeStr: String,
val count: Long,
val uri: Uri)
internal class SavedLogsResult {
var totalSize = ""
var totalLogCount = 0L
val logFiles = mutableListOf<LogFileInfo>()
}
internal class SavedLogsLiveData(private val application: Application) :
LiveData<SavedLogsResult>() {
init {
load()
}
internal fun load() {
val folders = arrayListOf<String>()
folders.add(File(application.filesDir, LogcatLiveFragment.LOGCAT_DIR).absolutePath)
val customLocation = application.getDefaultSharedPreferences().getString(
PreferenceKeys.Logcat.KEY_SAVE_LOCATION,
""
)
if (customLocation.isNotEmpty()) {
if (Build.VERSION.SDK_INT >= 21) {
folders.add(customLocation)
} else {
folders.add(File(customLocation, LogcatLiveFragment.LOGCAT_DIR).absolutePath)
}
}
Loader(this).execute(*folders.toTypedArray())
}
fun update(fileInfos: List<LogFileInfo>) {
val savedLogsResult = SavedLogsResult()
savedLogsResult.logFiles += fileInfos
savedLogsResult.totalLogCount = fileInfos.foldRight(0L) { logFileInfo, acc ->
acc + logFileInfo.count
}
val folder = File(application.filesDir, LogcatLiveFragment.LOGCAT_DIR)
val totalSize = fileInfos.sumByDouble { File(folder, it.name).length().toDouble() }
if (totalSize > 0) {
savedLogsResult.totalSize = Utils.sizeToString(totalSize)
}
value = savedLogsResult
}
class Loader(savedLogsLiveData: SavedLogsLiveData) : AsyncTask<String, Void, SavedLogsResult>() {
private val ref: WeakReference<SavedLogsLiveData> = WeakReference(savedLogsLiveData)
override fun doInBackground(vararg params: String): SavedLogsResult {
val savedLogsResult = SavedLogsResult()
var totalSize = collectFiles(savedLogsResult, params[0])
if (params.size == 2) {
if (Build.VERSION.SDK_INT >= 21) {
val savedLogsLiveData = ref.get()
if (savedLogsLiveData != null) {
totalSize += collectFilesFromCustomLocation(savedLogsLiveData.application,
savedLogsResult, params[1])
}
} else {
totalSize += collectFiles(savedLogsResult, params[1])
}
}
savedLogsResult.totalLogCount = savedLogsResult.logFiles
.foldRight(0L) { logFileInfo, acc ->
acc + logFileInfo.count
}
savedLogsResult.logFiles.sortBy { it.name }
if (totalSize > 0) {
savedLogsResult.totalSize = Utils.sizeToString(totalSize)
}
return savedLogsResult
}
private fun collectFiles(savedLogsResult: SavedLogsResult, path: String): Double {
val files = File(path).listFiles()
var totalSize = 0.toDouble()
if (files != null) {
for (f in files) {
val size = f.length()
val count = countLogs(f)
val fileInfo = LogFileInfo(f.name, size, Utils.sizeToString(size.toDouble()),
count, f.toUri())
savedLogsResult.logFiles += fileInfo
totalSize += fileInfo.size
}
}
return totalSize
}
private fun collectFilesFromCustomLocation(context: Context,
savedLogsResult: SavedLogsResult,
path: String): Double {
var totalSize = 0.0
val uri = path.toUri()
val folder = DocumentFile.fromTreeUri(context, uri)
val files = folder.listFiles()
if (files != null) {
for (f in files) {
val size = f.length()
val count = countLogs(context, f)
val fileInfo = LogFileInfo(f.name, size, Utils.sizeToString(size.toDouble()),
count, f.uri)
savedLogsResult.logFiles += fileInfo
totalSize += fileInfo.size
}
}
return totalSize
}
private fun countLogs(file: File): Long {
val logCount = Logcat.getLogCountFromHeader(file)
if (logCount != -1L) {
return logCount
}
return try {
val reader = LogcatStreamReader(FileInputStream(file))
val logs = reader.asSequence().toList()
if (!Logcat.writeToFile(logs, file)) {
Logger.logDebug(SavedLogsViewModel::class, "Failed to write log header")
}
logs.size.toLong()
} catch (e: IOException) {
0L
}
}
private fun countLogs(context: Context, file: DocumentFile): Long {
val logCount = Logcat.getLogCountFromHeader(context, file)
if (logCount != -1L) {
return logCount
}
return try {
val inputStream = context.contentResolver.openInputStream(file.uri)
val reader = LogcatStreamReader(inputStream)
val logs = reader.asSequence().toList()
if (!Logcat.writeToFile(context, logs, file.uri)) {
Logger.logDebug(SavedLogsViewModel::class, "Failed to write log header")
}
logs.size.toLong()
} catch (e: IOException) {
0L
}
}
override fun onPostExecute(result: SavedLogsResult) {
val savedLogsLiveData = ref.get()
if (savedLogsLiveData != null) {
savedLogsLiveData.value = result
}
}
}
} | 0 | Kotlin | 0 | 0 | d938d8c81c95a980952bd9aa5a952c047ccddca2 | 7,193 | LogcatReader | MIT License |
app/src/main/java/com/example/notificationsync/SettingItem.kt | axel10 | 267,450,371 | false | null | package com.example.notificationsync
import android.content.Context
import android.content.res.TypedArray
import android.util.AttributeSet
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.MotionEvent
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
class SettingItem(context: Context?, attrs: AttributeSet) :
ConstraintLayout(context, attrs) {
init {
LayoutInflater.from(context).inflate(R.layout.setting_item, this, true)
val text = findViewById<TextView>(R.id.detail)
val ta: TypedArray = context!!.obtainStyledAttributes(attrs, R.styleable.SettingItem)
try {
text.text = ta.getString(R.styleable.SettingItem_title)
} finally {
ta.recycle()
}
}
private var listener: OnClickListener? = null
override fun dispatchTouchEvent(event: MotionEvent?): Boolean {
if (event!!.action == MotionEvent.ACTION_UP) {
if (listener != null) listener!!.onClick(this)
}
return super.dispatchTouchEvent(event)
}
override fun setOnClickListener(listener: OnClickListener?) {
this.listener = listener
}
override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
if (event!!.action == KeyEvent.ACTION_UP && (event.keyCode == KeyEvent.KEYCODE_DPAD_CENTER || event.keyCode == KeyEvent.KEYCODE_ENTER)) {
if (listener != null) listener!!.onClick(this)
}
return super.dispatchKeyEvent(event)
}
} | 0 | Kotlin | 0 | 0 | 8cd2eda0d3cf813a169d75bfe512dc82c5e88a14 | 1,542 | NotificationSync | MIT License |
src/main/kotlin/com/netflix/spinnaker/testing/ContinuousDriver.kt | ajordens | 98,337,186 | false | null | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.testing
import com.netflix.spinnaker.testing.harness.ScenarioRunner
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
class ContinuousDriver : Driver {
override fun drive(scenarioRunner: ScenarioRunner) {
val timer = Timer()
timer.scheduleAtFixedRate(ContinuousTickTask(scenarioRunner, timer), 1000, 1000)
}
}
private class ContinuousTickTask(val scenarioRunner: ScenarioRunner, val timer: Timer) : TimerTask() {
val count = AtomicInteger(1)
override fun run() {
if (scenarioRunner.tick(count.get())) {
println("Tasks kicked off, waiting for results ...")
cancel()
timer.scheduleAtFixedRate(ContinuousFetchResultsTask(scenarioRunner, timer), 5000, 30000)
}
count.addAndGet(1)
}
}
private class ContinuousFetchResultsTask(val scenarioRunner: ScenarioRunner, val timer: Timer) : TimerTask() {
override fun run() {
if (scenarioRunner.isComplete()) {
println("All results fetched, re-driving scenarios")
cancel()
timer.scheduleAtFixedRate(ContinuousTickTask(scenarioRunner, timer), 1000, 1000)
}
}
}
| 1 | Kotlin | 19 | 7 | 0f8842872eb901a80be7cc24373776fdaff8f5a4 | 1,723 | spinnaker-performance | Apache License 2.0 |
src/test/kotlin/uk/gov/justice/digital/assessments/repositories/SubjectRepositoryTest.kt | ministryofjustice | 289,880,556 | false | null | package uk.gov.justice.digital.assessments.repositories
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.context.jdbc.Sql
import org.springframework.test.context.jdbc.SqlConfig
import org.springframework.test.context.jdbc.SqlGroup
import uk.gov.justice.digital.assessments.jpa.repositories.assessments.SubjectRepository
import uk.gov.justice.digital.assessments.testutils.IntegrationTest
@SqlGroup(
Sql(scripts = ["classpath:subject/before-test.sql"], config = SqlConfig(transactionMode = SqlConfig.TransactionMode.ISOLATED)),
Sql(scripts = ["classpath:subject/after-test.sql"], config = SqlConfig(transactionMode = SqlConfig.TransactionMode.ISOLATED), executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
)
class SubjectRepositoryTest(@Autowired val subjectRepository: SubjectRepository) : IntegrationTest() {
val crn = "dummy-crn-1"
val subject = "COURT"
@Test
fun `return Court Cases by CRN`() {
val court = subjectRepository.findByCrn(crn)
assertThat(court?.name).isEqualTo("John Smith")
}
}
| 6 | Kotlin | 1 | 2 | 6a6381ce625a3ed87d46eab1d270a168d65a558f | 1,153 | hmpps-assessments-api | MIT License |
core/model/src/commonMain/kotlin/dev/sasikanth/rss/reader/core/model/local/FeedGroup.kt | msasikanth | 632,826,313 | false | {"Kotlin": 858776, "Swift": 8517, "JavaScript": 3432, "CSS": 947, "Shell": 227} | /*
* Copyright 2024 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.sasikanth.rss.reader.core.model.local
import kotlinx.datetime.Instant
data class FeedGroup(
override val id: String,
val name: String,
val feedIds: List<String>,
val feedIcons: List<String>,
val numberOfUnreadPosts: Long = 0,
val createdAt: Instant,
val updatedAt: Instant,
override val pinnedAt: Instant?,
override val sourceType: SourceType = SourceType.FeedGroup
) : Source
| 35 | Kotlin | 72 | 1,713 | e7b3f1057d8295e1d83a041df68aec7bfefcd6e8 | 1,000 | twine | Apache License 2.0 |
app/src/test/java/com/highair/weatherforecastid/utils/MainCoroutineRule.kt | aydbtiko24 | 377,226,623 | false | null | package com.habileducation.themovie.util
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestCoroutineDispatcher
import kotlinx.coroutines.test.TestCoroutineScope
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.rules.TestWatcher
import org.junit.runner.Description
@ExperimentalCoroutinesApi
class MainCoroutineRule : TestWatcher(), TestCoroutineScope by TestCoroutineScope() {
override fun starting(description: Description?) {
super.starting(description)
Dispatchers.setMain(TestCoroutineDispatcher())
}
override fun finished(description: Description?) {
super.finished(description)
Dispatchers.resetMain()
}
} | 0 | Kotlin | 4 | 3 | 4e84cf6b6f6e0a2bbaf2313cae3c90db9103b169 | 787 | weather-forecast-ID | Apache License 2.0 |
app/src/main/java/com/breezefieldsalesniocapital/features/myjobs/api/MyJobRepoProvider.kt | DebashisINT | 849,340,703 | false | {"Kotlin": 15796448, "Java": 1028706} | package com.breezefieldsalesniocapital.features.myjobs.api
import android.content.Context
import android.net.Uri
import android.util.Log
import com.breezefieldsalesniocapital.app.FileUtils
import com.breezefieldsalesniocapital.base.BaseResponse
import com.breezefieldsalesniocapital.features.activities.model.ActivityImage
import com.breezefieldsalesniocapital.features.activities.model.AddActivityInputModel
import com.breezefieldsalesniocapital.features.myjobs.model.WIPSubmit
import com.fasterxml.jackson.databind.ObjectMapper
import io.reactivex.Observable
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
object MyJobRepoProvider {
fun jobRepoProvider(): MyJobRepo {
return MyJobRepo(MyJobApi.create())
}
fun jobMultipartRepoProvider(): MyJobRepo {
return MyJobRepo(MyJobApi.createMultiPart())
}
} | 0 | Kotlin | 0 | 0 | d00005a534ea20217c6cba71401b0cdfa531c74f | 890 | NIOCAPITAL | Apache License 2.0 |
src/main/kotlin/no/nav/eessi/pensjon/fagmodul/eux/EuxInnhentingService.kt | navikt | 144,840,932 | false | null | package no.nav.eessi.pensjon.fagmodul.eux
import no.nav.eessi.pensjon.eux.model.SedType
import no.nav.eessi.pensjon.eux.model.buc.BucType
import no.nav.eessi.pensjon.eux.model.buc.MissingBuc
import no.nav.eessi.pensjon.eux.model.document.P6000Dokument
import no.nav.eessi.pensjon.eux.model.sed.Person
import no.nav.eessi.pensjon.eux.model.sed.SED
import no.nav.eessi.pensjon.eux.model.sed.X009
import no.nav.eessi.pensjon.fagmodul.eux.basismodel.BucView
import no.nav.eessi.pensjon.fagmodul.eux.basismodel.BucViewKilde
import no.nav.eessi.pensjon.fagmodul.eux.basismodel.Rinasak
import no.nav.eessi.pensjon.fagmodul.eux.bucmodel.Buc
import no.nav.eessi.pensjon.fagmodul.eux.bucmodel.DocumentsItem
import no.nav.eessi.pensjon.fagmodul.eux.bucmodel.ParticipantsItem
import no.nav.eessi.pensjon.fagmodul.eux.bucmodel.PreviewPdf
import no.nav.eessi.pensjon.fagmodul.models.ApiRequest
import no.nav.eessi.pensjon.fagmodul.models.InstitusjonItem
import no.nav.eessi.pensjon.fagmodul.models.Kodeverk
import no.nav.eessi.pensjon.fagmodul.models.KodeverkResponse
import no.nav.eessi.pensjon.fagmodul.models.PrefillDataModel
import no.nav.eessi.pensjon.utils.mapAnyToJson
import no.nav.eessi.pensjon.utils.mapJsonToAny
import no.nav.eessi.pensjon.utils.toJson
import no.nav.eessi.pensjon.utils.toJsonSkipEmpty
import no.nav.eessi.pensjon.utils.typeRefs
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import org.springframework.web.server.ResponseStatusException
@Service
class EuxInnhentingService (@Value("\${ENV}") private val environment: String, @Qualifier("fagmodulEuxKlient") private val euxKlient: EuxKlient) {
private val logger = LoggerFactory.getLogger(EuxInnhentingService::class.java)
private val validbucsed = ValidBucAndSed()
fun getBuc(euxCaseId: String): Buc {
val body = euxKlient.getBucJson(euxCaseId)
return mapJsonToAny(body, typeRefs())
}
//hent buc for Pesys/tjeneste kjør som systembruker
fun getBucAsSystemuser(euxCaseId: String): Buc {
val body = euxKlient.getBucJsonAsSystemuser(euxCaseId)
logger.debug("mapper buc om til BUC objekt-model")
return mapJsonToAny(body, typeRefs())
}
fun getSedOnBucByDocumentId(euxCaseId: String, documentId: String): SED {
val json = euxKlient.getSedOnBucByDocumentIdAsJson(euxCaseId, documentId)
return SED.fromJsonToConcrete(json)
}
//henter ut korrekt url til Rina fra eux-rina-api
fun getRinaUrl() = euxKlient.getRinaUrl()
fun getSedOnBucByDocumentIdAsSystemuser(euxCaseId: String, documentId: String): SED {
val json = euxKlient.getSedOnBucByDocumentIdAsJsonAndAsSystemuser(euxCaseId, documentId)
return try {
SED.fromJsonToConcrete(json)
} catch (ex: Exception) {
logger.error("Feiler ved mapping av kravSED. Rina: $euxCaseId, documentid: $documentId")
throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Feiler ved mapping av kravSED. Rina: $euxCaseId, documentid: $documentId")
}
}
fun getSingleBucAndSedView(euxCaseId: String): BucAndSedView {
return try {
BucAndSedView.from(getBuc(euxCaseId))
} catch (ex: Exception) {
logger.error("Feiler ved utlevering av enkel bucandsedview ${ex.message}", ex)
BucAndSedView.fromErr(ex.message)
}
}
fun getBucAndSedViewWithBuc(bucs: List<Buc>, gjenlevndeFnr: String, avdodFnr: String): List<BucAndSedView> {
return bucs
.map { buc ->
try {
BucAndSedView.from(buc, gjenlevndeFnr, avdodFnr)
} catch (ex: Exception) {
logger.error(ex.message, ex)
BucAndSedView.fromErr(ex.message)
}
}
}
fun getBucAndSedView(rinasaker: List<String>): List<BucAndSedView> {
val startTime = System.currentTimeMillis()
val list = rinasaker.map { rinaid ->
try {
BucAndSedView.from(getBuc(rinaid))
} catch (ex: Exception) {
val errormsg = if (ex is ForbiddenException) {
"${HttpStatus.FORBIDDEN}. En eller flere i familierelasjon i saken har diskresjonskode.\nBare saksbehandlere med diskresjonstilganger kan se de aktuelle BUC og SED i EESSI-Pensjon eller i RINA."
} else {
ex.message
}
logger.error(ex.message, ex)
BucAndSedView.fromErr(errormsg)
}
}
.sortedByDescending { it.startDate }
logger.debug(" tiden tok ${System.currentTimeMillis() - startTime} ms.")
return list
}
fun getInstitutions(bucType: String, landkode: String? = ""): List<InstitusjonItem> {
logger.debug("henter institustion for bucType: $bucType, land: $landkode")
return euxKlient.getInstitutions(bucType, landkode)
}
fun getKodeverk(kodeverk: Kodeverk): List<KodeverkResponse> {
logger.debug("henter kodeverk for ${kodeverk.value}")
return euxKlient.getKodeverk(kodeverk)
}
/**
* filtert kun gyldige buc-type for visning, returnerer liste av rinaid
*/
fun getFilteredArchivedaRinasaker(list: List<Rinasak>): List<String> {
fun filterUgyldigeRinasaker(rinaid: String) : Boolean {
return if (MissingBuc.checkForMissingBuc(rinaid) ) {
true.also { logger.warn("Fjerner ugydlig rinasak: $rinaid") }
} else {
false
}
}
val spesialExtraBucs = mutableListOf("H_BUC_07", "R_BUC_01", "R_BUC_02", "M_BUC_02", "M_BUC_03a", "M_BUC_03b")
val pensjonNormaleBucs = validbucsed.initSedOnBuc().map { it.key }
val gyldigeBucs = pensjonNormaleBucs + spesialExtraBucs
return list.asSequence()
.filterNot { rinasak -> rinasak.status == "archived" }
.filter { rinasak -> gyldigeBucs.contains(rinasak.processDefinitionId) }
.sortedBy { rinasak -> rinasak.id }
.map { rinasak -> rinasak.id!! }
.filterNot { rinaid -> filterUgyldigeRinasaker(rinaid) }
.toList()
}
fun getFilteredArchivedaRinasakerSak(list: List<Rinasak>): List<Rinasak> {
val start = System.currentTimeMillis()
val ugyldigeRinasaker = listOf("6006777")
fun filterUgyldigeRinasaker(rinaid: String) : Boolean {
return if (rinaid in ugyldigeRinasaker) {
true.also { logger.warn("Fjerner ugydlig rinasak: $rinaid") }
} else {
false
}
}
val spesialExtraBucs = mutableListOf("H_BUC_07", "R_BUC_01", "R_BUC_02", "M_BUC_02", "M_BUC_03a", "M_BUC_03b")
val pensjonNormaleBucs = validbucsed.initSedOnBuc().map { it.key }
val gyldigeBucs = pensjonNormaleBucs + spesialExtraBucs
return list.asSequence()
.filterNot { rinasak -> rinasak.status == "archived" }
.filter { rinasak -> rinasak.processDefinitionId in gyldigeBucs }
.sortedBy { rinasak -> rinasak.id }
.filterNot { rinaid -> filterUgyldigeRinasaker(rinaid.id!!) }
.toList()
.also { val end = System.currentTimeMillis()
logger.info(" *** før: ${list.size} etter: ${it.size} *** FilteredArchivedaRinasakerSak tid ${end-start} i ms")
}
}
fun getBucDeltakere(euxCaseId: String): List<ParticipantsItem> {
return euxKlient.getBucDeltakere(euxCaseId)
}
fun getPdfContents(euxCaseId: String, documentId: String): PreviewPdf {
return euxKlient.getPdfJsonWithRest(euxCaseId, documentId)
}
/**
* filtere ut gyldig buc fra gjenlevende og avdød
*/
fun filterGyldigBucGjenlevendeAvdod(listeAvSedsPaaAvdod: List<BucOgDocumentAvdod>, fnrGjenlevende: String): List<Buc> {
return listeAvSedsPaaAvdod
.filter { docs -> filterGjenlevende(docs, fnrGjenlevende) }
.map { docs -> docs.buc }
.sortedBy { it.id }
}
private fun filterGjenlevende(docs: BucOgDocumentAvdod, fnrGjenlevende: String): Boolean {
val sedjson = docs.dokumentJson
if (sedjson.isBlank()) return false
val sed = mapJsonToAny(sedjson, typeRefs<SED>())
return filterGjenlevendePinNode(sed, docs.rinaidAvdod) == fnrGjenlevende ||
filterAnnenPersonPinNode(sed, docs.rinaidAvdod) == fnrGjenlevende
}
/**
* Henter inn sed fra eux fra liste over sedid på avdod
*/
fun hentDocumentJsonAvdod(bucdocumentidAvdod: List<BucOgDocumentAvdod>): List<BucOgDocumentAvdod> {
return bucdocumentidAvdod.map { docs ->
val bucutils = BucUtils(docs.buc)
val bucType = bucutils.getProcessDefinitionName()
logger.info("henter documentid fra buc: ${docs.rinaidAvdod} bucType: $bucType")
val shortDoc: DocumentsItem? = when (bucType) {
"P_BUC_02" -> bucutils.getDocumentByType(SedType.P2100)
"P_BUC_10" -> bucutils.getDocumentByType(SedType.P15000)
"P_BUC_05" -> {
val document = bucutils.getAllDocuments()
.filterNot { it.status in listOf("draft", "empty") }
.filter { it.type == SedType.P8000 }
val docout = document.firstOrNull { it.direction == "OUT" }
val docin = document.firstOrNull { it.direction == "IN" }
docout ?: docin
}
else -> korrektDokumentAvdodPbuc06(bucutils)
}
logger.debug("Henter sedJson fra document: ${shortDoc?.type}, ${shortDoc?.status}, ${shortDoc?.id}")
val sedJson = shortDoc?.let {
euxKlient.getSedOnBucByDocumentIdAsJson(docs.rinaidAvdod, it.id!!)
}
docs.dokumentJson = sedJson ?: ""
docs
}
}
private fun korrektDokumentAvdodPbuc06(bucUtils: BucUtils): DocumentsItem? {
logger.debug("henter ut korrekte SED fra P_BUC_06. ${bucUtils.getBuc().documents?.toJsonSkipEmpty()}")
val docitem = bucUtils.getAllDocuments()
.filterNot { it.status in listOf("draft", "empty") }
.filter { it.type in listOf(SedType.P5000, SedType.P6000, SedType.P7000, SedType.P10000) }
.firstOrNull { it.status in listOf("received", "new", "sent") }
return docitem
}
/**
* Henter buc og sedid på p2100 på avdøds fnr
*/
fun hentBucOgDocumentIdAvdod(filteredRinaIdAvdod: List<String>): List<BucOgDocumentAvdod> {
return filteredRinaIdAvdod.map {
rinaIdAvdod -> BucOgDocumentAvdod(rinaIdAvdod, getBuc(rinaIdAvdod))
}
}
/**
* json filter uthenting av pin på gjenlevende (p2100)
*/
private fun filterGjenlevendePinNode(sed: SED, rinaidAvdod: String): String? {
val gjenlevende = sed.pensjon?.gjenlevende?.person
return filterPinGjenlevendePin(gjenlevende, sed.type, rinaidAvdod)
}
/**
* json filter uthenting av pin på annen person (gjenlevende) (p8000)
*/
private fun filterAnnenPersonPinNode(sed: SED, rinaidAvdod: String): String? {
val annenperson = sed.nav?.annenperson?.person
val rolle = annenperson?.rolle
val type = sed.pensjon?.kravDato?.type
return if (type == "02" || rolle == "01") {
filterPinGjenlevendePin(annenperson, sed.type, rinaidAvdod)
} else {
null
}
}
private fun filterPinGjenlevendePin(gjenlevende: Person?, sedType: SedType, rinaidAvdod: String): String? {
val pin = gjenlevende?.pin?.firstOrNull { it.land == "NO" }
return if (pin == null) {
logger.warn("Ingen fnr funnet på gjenlevende. ${sedType}, rinaid: $rinaidAvdod")
null
} else {
pin.identifikator
}
}
fun getBucViewBruker(fnr: String, aktoerId: String, sakNr: String): List<BucView> {
val start = System.currentTimeMillis()
val rinaSakerMedFnr = euxKlient.getRinasaker(fnr, status = "\"open\"")
val filteredRinaBruker = getFilteredArchivedaRinasakerSak(rinaSakerMedFnr)
logger.info("rinaSaker total: ${filteredRinaBruker.size}")
return filteredRinaBruker.map { rinasak ->
BucView(
rinasak.id!!,
BucType.from(rinasak.processDefinitionId)!!,
aktoerId,
sakNr,
null,
BucViewKilde.BRUKER
)
}.also {
val end = System.currentTimeMillis()
logger.info("BucViewBruker tid ${end-start} i ms")
}
}
fun getBucViewBrukerSaf(aktoerId: String, sakNr: String, safSaker: List<String>): List<BucView> {
val start = System.currentTimeMillis()
val rinaSakerMedSaf = safSaker
.map { id ->
//euxKlient.getRinasaker(euxCaseId = id , status = "\"open\"")
val buc = getBuc(id)
Rinasak(id = buc.id, processDefinitionId = buc.processDefinitionName, traits = null, applicationRoleId = null, properties = null, status = "open")
}
val filteredRinasakSaf = getFilteredArchivedaRinasakerSak(rinaSakerMedSaf)
logger.info("rinaSaker total: ${filteredRinasakSaf.size}")
return filteredRinasakSaf.map { rinasak ->
BucView(
rinasak.id!!,
BucType.from(rinasak.processDefinitionId)!!,
aktoerId,
sakNr,
null,
BucViewKilde.SAF
)
}.also {
val end = System.currentTimeMillis()
logger.info("SafViewBruker tid ${end-start} i ms")
}
}
fun getBucViewAvdod(avdodFnr: String, aktoerId: String, sakNr: String): List<BucView> {
val start = System.currentTimeMillis()
val validAvdodBucs = listOf("P_BUC_02", "P_BUC_05", "P_BUC_06", "P_BUC_10")
val rinaSakerMedAvdodFnr = euxKlient.getRinasaker(avdodFnr, status = "\"open\"")
.filter { rinasak -> rinasak.processDefinitionId in validAvdodBucs }
val filteredRinaIdAvdod = getFilteredArchivedaRinasakerSak(rinaSakerMedAvdodFnr)
logger.info("rinaSaker avdod total: ${filteredRinaIdAvdod.size}")
return filteredRinaIdAvdod.map { rinasak ->
BucView(
rinasak.id!!,
BucType.from(rinasak.processDefinitionId)!!,
aktoerId,
sakNr,
avdodFnr,
BucViewKilde.AVDOD
)
}.also {
val end = System.currentTimeMillis()
logger.info("AvdodViewBruker tid ${end-start} i ms")
}
}
//** hente rinasaker fra RINA og SAF
fun getRinasaker(fnr: String, rinaSakIderFraJoark: List<String>): List<Rinasak> {
// Henter rina saker basert på fnr
val rinaSakerMedFnr = euxKlient.getRinasaker(fnr, status = "\"open\"")
logger.debug("hentet rinasaker fra eux-rina-api size: ${rinaSakerMedFnr.size}")
// Filtrerer vekk saker som allerede er hentet som har fnr
val rinaSakIderMedFnr = hentRinaSakIder(rinaSakerMedFnr)
val rinaSakIderUtenFnr = rinaSakIderFraJoark.minus(rinaSakIderMedFnr)
// Henter rina saker som ikke har fnr
val rinaSakerUtenFnr = rinaSakIderUtenFnr
.map { euxCaseId -> euxKlient.getRinasaker( euxCaseId = euxCaseId, status = "\"open\"") }
.flatten()
.distinctBy { it.id }
logger.info("henter rinasaker ut i fra saf documentMetadata, antall: ${rinaSakerUtenFnr.size}")
return rinaSakerMedFnr.plus(rinaSakerUtenFnr).also {
logger.info("Totalt antall rinasaker å hente: ${it.size}")
}
}
/**
* Returnerer en distinct liste av rinaSakIDer
* @param rinaSaker liste av rinasaker fra EUX datamodellen
*/
fun hentRinaSakIder(rinaSaker: List<Rinasak>) = rinaSaker.map { it.id!! }
fun kanSedOpprettes(dataModel: PrefillDataModel): BucUtils {
logger.info("******* Hent BUC sjekk om sed kan opprettes *******")
return BucUtils(getBuc(dataModel.euxCaseID)).also { bucUtil ->
//sjekk for om deltakere alt er fjernet med x007 eller x100 sed
bucUtil.checkForParticipantsNoLongerActiveFromXSEDAsInstitusjonItem(dataModel.getInstitutionsList())
//gyldig sed kan opprettes
bucUtil.checkIfSedCanBeCreated(dataModel.sedType, dataModel.penSaksnummer)
}
}
fun updateSedOnBuc(euxcaseid: String, documentid: String, sedPayload: String): Boolean {
logger.info("Oppdaterer ekisternede sed på rina: $euxcaseid. docid: $documentid")
return euxKlient.updateSedOnBuc(euxcaseid, documentid, sedPayload)
}
fun checkForP7000AndAddP6000(request: ApiRequest): ApiRequest {
return if (request.sed == SedType.P7000.name) {
//hente payload from ui
val docitems = request.payload?.let { mapJsonToAny(it, typeRefs<List<P6000Dokument>>()) }
logger.info("P6000 payload size: ${docitems?.size}")
//hente p6000sed fra rina legge på ny payload til prefill
val seds = docitems?.map { Pair<P6000Dokument, SED>(it, getSedOnBucByDocumentId(it.bucid, it.documentID)) }
//ny json payload til prefull
request.copy(payload = seds?.let { mapAnyToJson(it) })
} else request
}
//TODO fjern env for q2 når dette funker..
fun checkForX010AndAddX009(request: ApiRequest, parentId: String): ApiRequest {
return if (environment == "q2" && request.sed == SedType.X010.name && request.euxCaseId != null) {
logger.info("Legger ved X009 som payload for prefill X010")
val x009 = getSedOnBucByDocumentId(request.euxCaseId, parentId) as X009
request.copy(payload = x009.toJson())
} else request
}
} | 1 | Kotlin | 0 | 4 | 1091a835133492052816c8bb2717538f619b278f | 18,412 | eessi-pensjon-fagmodul | MIT License |
ExampleApp/composeApp/src/commonMain/kotlin/com/michaeltchuang/example/di/ViewModelModules.kt | michaeltchuang | 608,988,541 | false | {"Kotlin": 177845, "JavaScript": 2764, "Shell": 806, "Swift": 522} | package com.michaeltchuang.example.di
import com.michaeltchuang.example.ui.viewmodels.AlgorandBaseViewModel
import com.michaeltchuang.example.ui.viewmodels.PlayCoinFlipperViewModel
import com.michaeltchuang.example.ui.viewmodels.ValidatorDetailViewModel
import com.michaeltchuang.example.ui.viewmodels.ValidatorsListViewModel
import org.koin.dsl.module
val provideViewModelModules =
module {
single { AlgorandBaseViewModel(get()) }
single { PlayCoinFlipperViewModel(get()) }
single { ValidatorsListViewModel(get()) }
single { ValidatorDetailViewModel(get()) }
}
| 1 | Kotlin | 0 | 0 | 7c80b0a9db1256a1d2ee2cafb9e757d221588cf1 | 604 | a-day-in-my-bobalife | Apache License 2.0 |
src/main/java/top/zbeboy/isy/elastic/pojo/SystemMailboxElastic.kt | zbeboy | 71,459,176 | false | null | package top.zbeboy.isy.elastic.pojo
import org.springframework.data.annotation.Id
import org.springframework.data.elasticsearch.annotations.Document
import java.sql.Timestamp
/**
* Created by zbeboy 2017-11-11 .
**/
@Document(indexName = "systemmailbox", type = "systemmailbox", shards = 1, replicas = 0, refreshInterval = "-1")
open class SystemMailboxElastic {
@Id
var systemMailboxId: String? = null
var sendTime: Timestamp? = null
var acceptMail: String? = null
var sendCondition: String? = null
constructor()
constructor(systemMailboxId: String?, sendTime: Timestamp?, acceptMail: String?, sendCondition: String?) {
this.systemMailboxId = systemMailboxId
this.sendTime = sendTime
this.acceptMail = acceptMail
this.sendCondition = sendCondition
}
} | 7 | JavaScript | 2 | 7 | 9634602adba558dbdb945c114692019accdb50a9 | 822 | ISY | MIT License |
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/outline/Receiptsquare.kt | Tlaster | 560,394,734 | false | {"Kotlin": 25133302} | package moe.tlaster.icons.vuesax.vuesaxicons.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import moe.tlaster.icons.vuesax.vuesaxicons.OutlineGroup
public val OutlineGroup.Receiptsquare: ImageVector
get() {
if (_receiptsquare != null) {
return _receiptsquare!!
}
_receiptsquare = Builder(name = "Receiptsquare", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(15.0f, 22.75f)
horizontalLineTo(9.0f)
curveTo(3.57f, 22.75f, 1.25f, 20.43f, 1.25f, 15.0f)
verticalLineTo(9.0f)
curveTo(1.25f, 3.57f, 3.57f, 1.25f, 9.0f, 1.25f)
horizontalLineTo(15.0f)
curveTo(20.43f, 1.25f, 22.75f, 3.57f, 22.75f, 9.0f)
verticalLineTo(15.0f)
curveTo(22.75f, 20.43f, 20.43f, 22.75f, 15.0f, 22.75f)
close()
moveTo(9.0f, 2.75f)
curveTo(4.39f, 2.75f, 2.75f, 4.39f, 2.75f, 9.0f)
verticalLineTo(15.0f)
curveTo(2.75f, 19.61f, 4.39f, 21.25f, 9.0f, 21.25f)
horizontalLineTo(15.0f)
curveTo(19.61f, 21.25f, 21.25f, 19.61f, 21.25f, 15.0f)
verticalLineTo(9.0f)
curveTo(21.25f, 4.39f, 19.61f, 2.75f, 15.0f, 2.75f)
horizontalLineTo(9.0f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(12.0f, 18.6299f)
curveTo(11.44f, 18.6299f, 10.91f, 18.3499f, 10.54f, 17.8599f)
lineTo(9.94f, 17.0599f)
curveTo(9.87f, 16.9699f, 9.79f, 16.9199f, 9.7f, 16.9099f)
curveTo(9.61f, 16.9099f, 9.53f, 16.9499f, 9.45f, 17.0299f)
lineTo(8.9f, 16.5199f)
lineTo(9.45f, 17.0299f)
curveTo(8.48f, 18.0699f, 7.69f, 17.9699f, 7.3f, 17.8199f)
curveTo(6.91f, 17.6599f, 6.25f, 17.1799f, 6.25f, 15.6999f)
verticalLineTo(9.0699f)
curveTo(6.25f, 6.2899f, 7.14f, 5.3599f, 9.78f, 5.3599f)
horizontalLineTo(14.23f)
curveTo(16.87f, 5.3599f, 17.76f, 6.2999f, 17.76f, 9.0699f)
verticalLineTo(15.6999f)
curveTo(17.76f, 17.1799f, 17.1f, 17.6699f, 16.71f, 17.8199f)
curveTo(16.33f, 17.9699f, 15.54f, 18.0699f, 14.56f, 17.0299f)
curveTo(14.48f, 16.9499f, 14.39f, 16.9099f, 14.3f, 16.9099f)
curveTo(14.21f, 16.9099f, 14.13f, 16.9699f, 14.06f, 17.0599f)
lineTo(13.47f, 17.8499f)
curveTo(13.09f, 18.3499f, 12.56f, 18.6299f, 12.0f, 18.6299f)
close()
moveTo(9.69f, 15.4099f)
curveTo(9.72f, 15.4099f, 9.75f, 15.4099f, 9.78f, 15.4099f)
curveTo(10.31f, 15.4399f, 10.8f, 15.7099f, 11.13f, 16.1599f)
lineTo(11.73f, 16.9599f)
curveTo(11.9f, 17.1799f, 12.09f, 17.1799f, 12.25f, 16.9599f)
lineTo(12.84f, 16.1699f)
curveTo(13.17f, 15.7199f, 13.67f, 15.4499f, 14.2f, 15.4199f)
curveTo(14.72f, 15.3799f, 15.25f, 15.6099f, 15.63f, 16.0199f)
curveTo(15.91f, 16.3199f, 16.09f, 16.3999f, 16.16f, 16.4199f)
curveTo(16.15f, 16.3699f, 16.24f, 16.1699f, 16.24f, 15.7099f)
verticalLineTo(9.0799f)
curveTo(16.24f, 7.0299f, 15.93f, 6.8699f, 14.21f, 6.8699f)
horizontalLineTo(9.76f)
curveTo(8.04f, 6.8699f, 7.73f, 7.0299f, 7.73f, 9.0799f)
verticalLineTo(15.7099f)
curveTo(7.73f, 16.1699f, 7.82f, 16.3699f, 7.85f, 16.4299f)
curveTo(7.88f, 16.3899f, 8.06f, 16.3099f, 8.33f, 16.0099f)
curveTo(8.33f, 15.9999f, 8.34f, 15.9999f, 8.35f, 15.9899f)
curveTo(8.72f, 15.6299f, 9.2f, 15.4099f, 9.69f, 15.4099f)
close()
}
}
.build()
return _receiptsquare!!
}
private var _receiptsquare: ImageVector? = null
| 0 | Kotlin | 0 | 2 | b8a8231e6637c2008f675ae76a3423b82ee53950 | 5,144 | VuesaxIcons | MIT License |
player/src/main/kotlin/app/cash/chronicler/player/ReconstructedTrace.kt | cashapp | 432,204,948 | false | {"Kotlin": 84370, "Shell": 1127, "Dockerfile": 100} | package app.cash.chronicler.player
import app.cash.chronicler.proto.Statement
import java.time.Instant
import java.time.Duration as JavaDuration
class ReconstructedTraceBuilder(firstStatement: Statement) {
val statements = mutableListOf(firstStatement)
fun add(statement: Statement) = statements.add(statement)
val traceStart: Instant get() = statements.first().client_start!!
val traceId: String get() = statements.first().trace_id
override fun toString(): String {
return "ReconstructedTrace(statements=$statements, traceStart=$traceStart, traceId='$traceId')"
}
fun build() = ReconstructedTrace(
statements = statements,
traceStart = traceStart,
traceId = traceId
)
}
data class ReconstructedTrace(
val statements: List<Statement>,
val traceStart: Instant,
val traceId: String
)
fun ReconstructedTrace.delayedCopy(relativeDuration: JavaDuration) = copy(
statements = statements.map {
it.copy(
client_start = it.client_start!!.plus(relativeDuration),
client_end = it.client_end!!.plus(relativeDuration)
)
},
traceStart = traceStart.plus(relativeDuration)
)
| 3 | Kotlin | 1 | 3 | 98a8ab01083ff068a6389234d6051da124b949b2 | 1,131 | chronicler | Apache License 2.0 |
src/main/kotlin/com/example/test/controller/impl/StudentControllerImpl.kt | tom83615 | 391,600,462 | false | null | package com.example.test.controller.impl
import com.example.test.controller.StudentController
import com.example.test.service.StudentService
import com.example.test.sql.entity.Student
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
class StudentControllerImpl(@Autowired val studentService: StudentService) : StudentController {
override fun getStudentData(): MutableList<Student> = studentService.findAllStudent()
override fun addStudentData(student: Student): Student = studentService.addStudent(student)
override fun getStudentById(id: Int): ResponseEntity<Student?> =
studentService
.findByStudentId(id)
.run {
return ResponseEntity<Student?>(this, HttpStatus.OK)
}
override fun getStudentByName(name: String): ResponseEntity<List<Student>> =
studentService
.findByStudentName(name)
.let {
return ResponseEntity(it, HttpStatus.OK)
}
override fun updateStudent(id: Int, student: Student): ResponseEntity<Student?> =
studentService
.findByStudentId(id)
.run {
this ?: return ResponseEntity<Student?>(null, HttpStatus.NOT_FOUND)
}
.run {
val newStudent = studentService.updateStudent(this)
return ResponseEntity<Student?>(newStudent, HttpStatus.OK)
}
override fun deleteStudent(id: Int): ResponseEntity<Any> =
studentService
.deleteStudent(id)
.run {
if (!this) {
return ResponseEntity<Any>(null, HttpStatus.BAD_REQUEST)
}
return ResponseEntity<Any>(null, HttpStatus.NO_CONTENT)
}
} | 0 | Kotlin | 0 | 0 | c5b64b24e2fbc6c076c16580c23bd6034175309a | 2,008 | learning_kotlin_backend | MIT License |
http/http/src/test/kotlin/com/hexagontk/http/patterns/TemplatePathPatternTest.kt | hexagontk | 56,139,239 | false | {"Kotlin": 916459, "HTML": 20821, "Java": 8416, "CSS": 4736, "PHP": 6} | package com.hexagontk.http.patterns
import org.junit.jupiter.api.Test
import kotlin.test.*
internal class TemplatePathPatternTest {
@Test fun `Regex parameters are allowed`() {
val path = TemplatePathPattern("/alpha/{param:\\d+}/tango/{arg:a|b|c}")
assertEquals(listOf("param", "arg"), path.parameters)
val parameters = mapOf("param" to "v1", "arg" to "v2")
assertEquals("/alpha/v1/tango/v2", path.insertParameters(parameters))
assert(path.matches("/alpha/0/tango/a"))
assert(path.matches("/alpha/0/tango/b"))
assert(path.matches("/alpha/0/tango/c"))
assert(path.matches("/alpha/10/tango/a"))
assert(path.matches("/alpha/10/tango/b"))
assert(path.matches("/alpha/10/tango/c"))
assertEquals(
mapOf("param" to "0", "arg" to "a", "0" to "0", "1" to "a"),
path.extractParameters("/alpha/0/tango/a")
)
assertEquals(
mapOf("param" to "0", "arg" to "b", "0" to "0", "1" to "b"),
path.extractParameters("/alpha/0/tango/b")
)
assertEquals(
mapOf("param" to "0", "arg" to "c", "0" to "0", "1" to "c"),
path.extractParameters("/alpha/0/tango/c")
)
assertEquals(
mapOf("param" to "10", "arg" to "a", "0" to "10", "1" to "a"),
path.extractParameters("/alpha/10/tango/a")
)
assertEquals(
mapOf("param" to "10", "arg" to "b", "0" to "10", "1" to "b"),
path.extractParameters("/alpha/10/tango/b")
)
assertEquals(
mapOf("param" to "10", "arg" to "c", "0" to "10", "1" to "c"),
path.extractParameters("/alpha/10/tango/c")
)
assert(!path.matches("/alpha/10/tango/abc"))
assert(!path.matches("/alpha/10/tango/z"))
assert(!path.matches("/alpha/x/tango/a"))
}
@Test fun `Insert parameters fails on invalid parameters`() {
fun testInvalid(template: String, vararg params: Pair<String, Any>) {
val path = TemplatePathPattern(template)
val pathParameters = path.parameters
val parameters = params.toMap()
val parametersKeys = parameters.keys
val e = assertFailsWith<IllegalArgumentException> { path.insertParameters(parameters) }
assertEquals(
"Parameters must match pattern's parameters($pathParameters). Provided: $parametersKeys",
e.message
)
}
testInvalid("/alpha/{param}/tango/{arg}", "param1" to "v1", "arg" to "v2")
testInvalid("/alpha/{param}/tango/{arg}", "param" to "v1")
testInvalid("/alpha/{param}/tango/{arg}", "arg" to "v2")
testInvalid("/alpha/{param}/tango/{arg}", "param" to "v1", "arg" to "v2", "extra" to "v3")
}
@Test fun `Insert parameters on path`() {
val path = TemplatePathPattern("/alpha/{param}/tango/{arg}")
assertEquals(listOf("param", "arg"), path.parameters)
val parameters = mapOf("param" to "v1", "arg" to "v2")
assertEquals("/alpha/v1/tango/v2", path.insertParameters(parameters))
}
@Test fun `Prefixes are matched if pattern is prefix`() {
val regexPath = TemplatePathPattern("/alpha/bravo")
assertFalse(regexPath.matches("/alpha/bravo/tango"))
val regexPathPrefix = TemplatePathPattern("/alpha/bravo", true)
assert(regexPathPrefix.matches("/alpha/bravo"))
assert(regexPathPrefix.matches("/alpha/bravo/tango"))
assertFalse(regexPathPrefix.matches("/prefix/alpha/bravo"))
val regexPathParamsPrefix = TemplatePathPattern("/alpha/{var}/bravo", true)
assert(regexPathParamsPrefix.matches("/alpha/a/bravo"))
assert(regexPathParamsPrefix.matches("/alpha/a/bravo/tango"))
assertFalse(regexPathParamsPrefix.matches("/prefix/alpha/a/bravo"))
}
@Test fun `URLs with blank parameters are not matched`() {
val regexPath = TemplatePathPattern("/alpha/{param}/bravo")
assertFalse(regexPath.matches("/alpha//bravo"))
}
@Test fun `Prefixes can be appended to patterns`() {
val regexPath = TemplatePathPattern("/alpha/bravo")
assert(regexPath.addPrefix(null).matches("/alpha/bravo"))
assertFalse(regexPath.addPrefix("/prefix").matches("/alpha/bravo"))
assertTrue(regexPath.addPrefix("/prefix").matches("/prefix/alpha/bravo"))
}
@Test fun `Regex is matched properly`() {
TemplatePathPattern("/alpha/?*").apply {
assert(matches("/alphabet/beta/p2"))
assert(matches("/alphabet"))
}
TemplatePathPattern("/alpha*").apply {
assert(matches("/alphabet/beta/p2"))
assert(matches("/alphabet"))
}
TemplatePathPattern("/alpha(/*)?").apply {
assert(matches("/alpha/beta/p2"))
assert(matches("/alpha"))
}
TemplatePathPattern("/alpha(/a|/b)").apply {
assert(matches("/alpha/a"))
assert(matches("/alpha/b"))
assertFalse(matches("/alpha/ba"))
}
TemplatePathPattern("/(this|that)/alpha/{param}/tango*").apply {
assert(matches("/this/alpha/v11/tango"))
assert(matches("/this/alpha/v12/tango1"))
assert(matches("/this/alpha/v13/tango12"))
assert(matches("/that/alpha/v21/tango"))
assert(matches("/that/alpha/v22/tango1"))
assert(matches("/that/alpha/v23/tango12"))
assertEquals(
mapOf("param" to "v11", "0" to "this", "1" to "v11", "2" to ""),
extractParameters("/this/alpha/v11/tango")
)
assertEquals(
mapOf("param" to "v12", "0" to "this", "1" to "v12", "2" to "1"),
extractParameters("/this/alpha/v12/tango1")
)
assertEquals(
mapOf("param" to "v13", "0" to "this", "1" to "v13", "2" to "12"),
extractParameters("/this/alpha/v13/tango12")
)
assertEquals(
mapOf("param" to "v21", "0" to "that", "1" to "v21", "2" to ""),
extractParameters("/that/alpha/v21/tango")
)
assertEquals(
mapOf("param" to "v22", "0" to "that", "1" to "v22", "2" to "1"),
extractParameters("/that/alpha/v22/tango1")
)
assertEquals(
mapOf("param" to "v23", "0" to "that", "1" to "v23", "2" to "12"),
extractParameters("/that/alpha/v23/tango12")
)
}
}
@Test fun `A path without parameters do not have params table`() {
val pathWithoutData = TemplatePathPattern("/alpha/bravo/tango")
assertEquals("/alpha/bravo/tango", pathWithoutData.pattern)
assert(pathWithoutData.extractParameters("/alpha/bravo/tango").isEmpty())
assert(pathWithoutData.matches("/alpha/bravo/tango"))
assert(!pathWithoutData.matches("/alpha/bravo/tango/zulu"))
assert(!pathWithoutData.matches("/zulu/alpha/bravo/tango"))
assert(pathWithoutData.extractParameters("/alpha/bravo/tango").isEmpty())
val pathWithoutParams = TemplatePathPattern("/alpha/(bravo|charlie)/tango")
assertEquals("/alpha/(bravo|charlie)/tango", pathWithoutParams.pattern)
assertEquals("bravo", pathWithoutParams.extractParameters("/alpha/bravo/tango")["0"])
assertEquals("charlie", pathWithoutParams.extractParameters("/alpha/charlie/tango")["0"])
assert(pathWithoutParams.matches("/alpha/bravo/tango"))
assert(!pathWithoutParams.matches("/alpha/bravo/tango/zulu"))
assert(!pathWithoutParams.matches("/zulu/alpha/bravo/tango"))
assert(pathWithoutParams.matches("/alpha/charlie/tango"))
assert(!pathWithoutParams.matches("/alpha/charlie/tango/zulu"))
assert(!pathWithoutParams.matches("/zulu/alpha/charlie/tango"))
}
@Test fun `Empty and wildcard path patterns are allowed`() {
assertEquals("", TemplatePathPattern("").pattern)
assertEquals("*", TemplatePathPattern("*").pattern)
assertEquals("*/whatever", TemplatePathPattern("*/whatever").pattern)
}
@Test fun `Invalid path parameters`() {
assertFailsWith<IllegalArgumentException> {
TemplatePathPattern("alpha/bravo")
}
}
@Test fun `Extract parameter from a pattern without parameters returns empty map`() {
val pathWithoutData = TemplatePathPattern("/alpha/bravo/tango")
assertFailsWith<IllegalArgumentException> {
pathWithoutData.extractParameters("/alpha/bravo/tango/zulu")
}
}
@Test fun `Extract parameter from a non matching url fails`() {
assertFailsWith<IllegalArgumentException> {
TemplatePathPattern("/alpha/{param}/tango").extractParameters("zulu/alpha/abc/tango")
}
}
@Test fun `A path with parameters have regex and params table`() {
assert(!TemplatePathPattern("/alpha/{param}/tango").matches("/alpha/a/tango/zulu"))
val pathWith1Parameter = TemplatePathPattern("/alpha/{param}/tango*")
assertEquals("/alpha/{param}/tango*", pathWith1Parameter.pattern)
val expectedParams = mapOf("param" to "abc", "0" to "abc")
assertEquals(
expectedParams + ("1" to ""),
pathWith1Parameter.extractParameters("/alpha/abc/tango")
)
assertEquals(
expectedParams + ("1" to "/bravo"),
pathWith1Parameter.extractParameters("/alpha/abc/tango/bravo")
)
assertFailsWith<IllegalArgumentException> {
pathWith1Parameter.extractParameters("/beta/alpha/abc/tango/bravo")
}
assert(pathWith1Parameter.matches("/alpha/a/tango"))
assert(pathWith1Parameter.matches("/alpha/abc/tango"))
assert(!pathWith1Parameter.matches("/alpha//tango"))
assert(!pathWith1Parameter.matches("/alpha/tango"))
assert(pathWith1Parameter.matches("/alpha/a/tango/zulu"))
val pathWith2Parameters = TemplatePathPattern("/alpha/{param}/tango/{arg}")
assertEquals("/alpha/{param}/tango/{arg}", pathWith2Parameters.pattern)
assertEquals(
mapOf("param" to "abc", "arg" to "bravo", "0" to "abc", "1" to "bravo"),
pathWith2Parameters.extractParameters("/alpha/abc/tango/bravo")
)
val params2 = pathWith2Parameters.extractParameters("/alpha/abc/tango/def")
assertEquals(mapOf("param" to "abc", "arg" to "def", "0" to "abc", "1" to "def"), params2)
}
@Test fun `Path with a wildcard resolve parameters properly`() {
TemplatePathPattern("/alpha/*/{param}/tango").let {
assertEquals("/alpha/*/{param}/tango", it.pattern)
assertEquals(
mapOf("param" to "abc", "0" to "a", "1" to "abc"),
it.extractParameters("/alpha/a/abc/tango")
)
assertEquals(
mapOf("param" to "abc", "0" to "b", "1" to "abc"),
it.extractParameters("/alpha/b/abc/tango")
)
}
TemplatePathPattern("/alpha/{param}/tango/{arg}/*").let {
assertEquals("/alpha/{param}/tango/{arg}/*", it.pattern)
val parameters = mapOf("param" to "abc", "arg" to "def", "0" to "abc", "1" to "def")
assertEquals(parameters + ("2" to "1"), it.extractParameters("/alpha/abc/tango/def/1"))
assertEquals(parameters + ("2" to "2"), it.extractParameters("/alpha/abc/tango/def/2"))
}
}
@Test fun `Path without parameters does not return any parameter`() {
TemplatePathPattern("/*/alpha/*/tango").let {
assertEquals("/*/alpha/*/tango", it.pattern)
assertEquals(mapOf("0" to "a", "1" to "b"), it.extractParameters("/a/alpha/b/tango"))
assertEquals(mapOf("0" to "c", "1" to "d"), it.extractParameters("/c/alpha/d/tango"))
}
TemplatePathPattern("/alpha/tango").let {
assertEquals("/alpha/tango", it.pattern)
assert(it.extractParameters("/alpha/tango").isEmpty())
}
}
@Test fun `Path with many wildcards resolve parameters properly`() {
TemplatePathPattern("/*/alpha/*/{param}/tango").let {
assertEquals("/*/alpha/*/{param}/tango", it.pattern)
assertEquals(
mapOf("param" to "abc", "0" to "a", "1" to "b", "2" to "abc"),
it.extractParameters("/a/alpha/b/abc/tango")
)
assertEquals(
mapOf("param" to "abc", "0" to "c", "1" to "d", "2" to "abc"),
it.extractParameters("/c/alpha/d/abc/tango")
)
}
TemplatePathPattern("/alpha/*/{param}/tango/{arg}/*").let {
assertEquals("/alpha/*/{param}/tango/{arg}/*", it.pattern)
val parameters = mapOf("param" to "abc", "arg" to "def")
val parameters1 = parameters + mapOf("0" to "a", "1" to "abc", "2" to "def", "3" to "b")
assertEquals(parameters1, it.extractParameters("/alpha/a/abc/tango/def/b"))
val parameters2 = parameters + mapOf("0" to "c", "1" to "abc", "2" to "def", "3" to "d")
assertEquals(parameters2, it.extractParameters("/alpha/c/abc/tango/def/d"))
}
}
@Test fun `Cover missing lines`() {
assertEquals(TemplatePathPattern.WILDCARD_REGEX, TemplatePathPattern.WILDCARD_REGEX)
assertEquals(TemplatePathPattern.PARAMETER_REGEX, TemplatePathPattern.PARAMETER_REGEX)
assertEquals(TemplatePathPattern.PLACEHOLDER_REGEX, TemplatePathPattern.PLACEHOLDER_REGEX)
}
@Test fun `Adding a prefix keep the prefix flag`() {
TemplatePathPattern("/a", true).addPrefix("/b").let {
assertEquals("/b/a", it.pattern)
assertTrue(it.prefix)
}
TemplatePathPattern("/a", false).addPrefix("/b").let {
assertEquals("/b/a$", it.pattern)
assertFalse(it.prefix)
}
}
}
| 18 | Kotlin | 99 | 578 | 7436f1985832d21696fe7c08a0f454add6520284 | 14,088 | hexagon | Apache License 2.0 |
kotlin/99.Recover Binary Search Tree(恢复二叉搜索树).kt | learningtheory | 141,790,045 | false | {"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944} | /**
<p>Two elements of a binary search tree (BST) are swapped by mistake.</p>
<p>Recover the tree without changing its structure.</p>
<p><strong>Example 1:</strong></p>
<pre>
<strong>Input:</strong> [1,3,null,null,2]
1
/
3
\
2
<strong>Output:</strong> [3,1,null,null,2]
3
/
1
\
2
</pre>
<p><strong>Example 2:</strong></p>
<pre>
<strong>Input:</strong> [3,1,4,null,null,2]
3
/ \
1 4
/
2
<strong>Output:</strong> [2,1,4,null,null,3]
2
/ \
1 4
/
3
</pre>
<p><strong>Follow up:</strong></p>
<ul>
<li>A solution using O(<em>n</em>) space is pretty straight forward.</li>
<li>Could you devise a constant space solution?</li>
</ul>
<p>二叉搜索树中的两个节点被错误地交换。</p>
<p>请在不改变其结构的情况下,恢复这棵树。</p>
<p><strong>示例 1:</strong></p>
<pre><strong>输入:</strong> [1,3,null,null,2]
1
/
3
\
2
<strong>输出:</strong> [3,1,null,null,2]
3
/
1
\
2
</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong> [3,1,4,null,null,2]
3
/ \
1 4
/
2
<strong>输出:</strong> [2,1,4,null,null,3]
2
/ \
1 4
/
3</pre>
<p><strong>进阶:</strong></p>
<ul>
<li>使用 O(<em>n</em>) 空间复杂度的解法很容易实现。</li>
<li>你能想出一个只使用常数空间的解决方案吗?</li>
</ul>
<p>二叉搜索树中的两个节点被错误地交换。</p>
<p>请在不改变其结构的情况下,恢复这棵树。</p>
<p><strong>示例 1:</strong></p>
<pre><strong>输入:</strong> [1,3,null,null,2]
1
/
3
\
2
<strong>输出:</strong> [3,1,null,null,2]
3
/
1
\
2
</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong> [3,1,4,null,null,2]
3
/ \
1 4
/
2
<strong>输出:</strong> [2,1,4,null,null,3]
2
/ \
1 4
/
3</pre>
<p><strong>进阶:</strong></p>
<ul>
<li>使用 O(<em>n</em>) 空间复杂度的解法很容易实现。</li>
<li>你能想出一个只使用常数空间的解决方案吗?</li>
</ul>
**/
/**
* Definition for a binary tree node.
* class TreeNode(var `val`: Int = 0) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun recoverTree(root: TreeNode?): Unit {
}
} | 0 | Python | 1 | 3 | 6731e128be0fd3c0bdfe885c1a409ac54b929597 | 2,178 | leetcode | MIT License |
data/src/main/java/org/michaelbel/data/remote/model/Account.kt | MohamedElgindy | 418,517,056 | true | {"Kotlin": 274956} | package org.michaelbel.data.remote.model
import com.google.gson.annotations.SerializedName
data class Account(
@SerializedName("avatar") val avatar: Avatar,
@SerializedName("id") val id: Int,
@SerializedName("iso_639_1") val lang: String,
@SerializedName("iso_3166_1") val country: String,
@SerializedName("name") val name: String,
@SerializedName("include_adult") val includeAdult: Boolean,
@SerializedName("username") val username: String
) | 0 | null | 0 | 0 | cba8423af7b30eec5f2276a639fdbe2ffb020ae3 | 472 | Moviemade | Apache License 2.0 |
src/commonMain/kotlin/baaahs/model/LinearPixelArray.kt | iamh2o | 399,023,966 | true | {"Kotlin": 2404862, "C++": 464973, "JavaScript": 277897, "GLSL": 125865, "C": 114696, "CMake": 25514, "HTML": 12621, "SCSS": 3940, "CSS": 1456, "Shell": 663} | package baaahs.model
import baaahs.geom.Vector3F
interface LinearPixelArray {
fun calculatePixelLocation(index: Int, count: Int): Vector3F
fun calculatePixelLocations(pixelCount: Int): List<Vector3F> {
return (0 until pixelCount).map { i ->
calculatePixelLocation(i, pixelCount)
}
}
} | 0 | null | 0 | 0 | d713a7a0518925065d2953880ad79da5229c4707 | 327 | sparklemotion | MIT License |
data/src/main/java/com/hamza/data/api/MovieApi.kt | hmz9 | 612,902,426 | false | null | package com.hamza.data.api
import com.hamza.data.BuildConfig
import com.hamza.data.entities.MovieData
import com.hamza.data.entities.MovieDataResponse
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
/**
* Created by <NAME> on 03/09/2023
*/
interface MovieApi {
@GET("/3/movie/popular?api_key=${BuildConfig.TMBD_API_KEY}")
suspend fun getMovies(
@Query("page") page: Int,
@Query("limit") limit: Int,
): MovieDataResponse
@GET("/movies")
suspend fun getMovies(@Query("id") movieIds: List<Int>): List<MovieData>
@GET("3/movie/{movie_id}?api_key=${BuildConfig.TMBD_API_KEY}")
suspend fun getMovie(@Path("movie_id") movieId: Int): MovieData
@GET("3/search/movie?api_key=<KEY>")
suspend fun search(
@Query("query") query: String,
@Query("page") page: Int,
@Query("limit") limit: Int,
): MovieDataResponse
} | 0 | Kotlin | 0 | 0 | a6b10845b07b3bc5a651c77503ab0e50b79ba7ba | 921 | movie-android-clean-mvvm | Apache License 2.0 |
exact-numbers/src/test/kotlin/xyz/lbres/exactnumbers/irrationals/log/HelpersTest.kt | lbressler13 | 491,698,766 | false | {"Kotlin": 217345} | package xyz.lbres.exactnumbers.irrationals.log
import java.math.BigDecimal
import java.math.BigInteger
import kotlin.test.Test
import kotlin.test.assertEquals
class HelpersTest {
@Test
fun testGetLogOf() {
// base 10
var base = 10
var bi = BigInteger.ONE
var expected = BigDecimal.ZERO
assertEquals(expected, getLogOf(bi, base))
bi = BigInteger.TEN
expected = BigDecimal.ONE
assertEquals(expected, getLogOf(bi, base))
bi = 100.toBigInteger()
expected = 2.toBigDecimal()
assertEquals(expected, getLogOf(bi, base))
bi = 200.toBigInteger()
expected = BigDecimal("2.301029995663981")
assertEquals(expected, getLogOf(bi, base))
bi = 3333.toBigInteger()
expected = BigDecimal("3.52283531366053")
assertEquals(expected, getLogOf(bi, base))
bi = 300.toBigInteger()
expected = BigDecimal("2.477121254719662")
assertEquals(expected, getLogOf(bi, base))
bi = 77.toBigInteger()
expected = BigDecimal("1.8864907251724818")
assertEquals(expected, getLogOf(bi, base))
// base 2
base = 2
bi = BigInteger.ONE
expected = BigDecimal.ZERO
assertEquals(expected, getLogOf(bi, base))
bi = 32.toBigInteger()
expected = 5.toBigDecimal()
assertEquals(expected, getLogOf(bi, base))
bi = 200.toBigInteger()
expected = BigDecimal("7.643856189774724")
assertEquals(expected, getLogOf(bi, base))
// other
bi = BigInteger.ONE
base = 7
expected = BigDecimal.ZERO
assertEquals(expected, getLogOf(bi, base))
bi = 216.toBigInteger()
base = 6
expected = 3.toBigDecimal()
assertEquals(expected, getLogOf(bi, base))
base = 24
bi = 15151515.toBigInteger()
expected = BigDecimal("5.202432673429519")
assertEquals(expected, getLogOf(bi, base))
}
}
| 0 | Kotlin | 0 | 2 | c9e581e04d308dc9c50edd6b32aac8cdff86c5be | 2,011 | exact-numbers | MIT License |
student_app/app/src/main/java/io/github/kabirnayeem99/dumarketingstudent/ui/fragments/FacultyFragment.kt | kabirnayeem99 | 360,781,364 | false | null | package io.github.kabirnayeem99.dumarketingstudent.presentation.faculty
import android.os.Bundle
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import dagger.hilt.android.AndroidEntryPoint
import io.github.kabirnayeem99.dumarketingstudent.R
import io.github.kabirnayeem99.dumarketingstudent.common.base.BaseFragment
import io.github.kabirnayeem99.dumarketingstudent.common.util.Resource
import io.github.kabirnayeem99.dumarketingstudent.common.util.showSnackBar
import io.github.kabirnayeem99.dumarketingstudent.databinding.FragmentFacultyBinding
import me.everything.android.ui.overscroll.OverScrollDecoratorHelper
import timber.log.Timber
@AndroidEntryPoint
class FacultyFragment : BaseFragment<FragmentFacultyBinding>() {
override val layoutRes: Int
get() = R.layout.fragment_faculty
private val facultyViewModel: FacultyViewModel by activityViewModels()
private val facultyDataAdapter: FacultyDataAdapter by lazy {
FacultyDataAdapter()
}
override fun onCreated(savedInstanceState: Bundle?) {
setUpFacultyRecyclerView()
}
private fun setUpFacultyRecyclerView() {
binding.rvFaculty.apply {
adapter = facultyDataAdapter
layoutManager = LinearLayoutManager(context)
OverScrollDecoratorHelper.setUpOverScroll(
this,
OverScrollDecoratorHelper.ORIENTATION_VERTICAL
)
}
facultyViewModel.getAllFacultyList().observe(viewLifecycleOwner) { resource ->
when (resource) {
is Resource.Error -> {
showSnackBar("Could not get the list of factuly members.").show()
Timber.e(resource.message)
}
is Resource.Success -> {
facultyDataAdapter.differ.submitList(resource.data)
}
else -> {
Timber.d("loading..")
}
}
}
}
} | 4 | Kotlin | 2 | 5 | d07f00410c975dba19c83a959b3a5aeff9074b7a | 2,038 | du_marketing_sms | Apache License 2.0 |
news-cast-explorer-fetcher/src/test/kotlin/org/jesperancinha/newscast/client/NewsCastClientJUnit5Test.kt | jesperancinha | 573,498,638 | false | {"Kotlin": 83172, "Java": 40744, "TypeScript": 29026, "Shell": 7412, "Makefile": 6627, "HTML": 6537, "JavaScript": 5220, "Dockerfile": 3605, "CSS": 3421, "Python": 2092, "Sass": 80} | package org.jesperancinha.newscast.client
import com.ninjasquad.springmockk.MockkBean
import io.kotest.matchers.collections.shouldHaveSize
import io.kotest.matchers.longs.shouldBeGreaterThanOrEqual
import io.kotest.matchers.longs.shouldBeLessThan
import io.kotest.matchers.longs.shouldBeLessThanOrEqual
import io.kotest.matchers.nulls.shouldNotBeNull
import io.mockk.verify
import org.jesperancinha.newscast.processor.NewsCastMessageProcessor
import org.jesperancinha.newscast.service.OneRunServiceImpl
import org.jesperancinha.newscast.utils.AbstractNCTest
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.annotation.DirtiesContext
import org.springframework.test.context.ActiveProfiles
import java.util.concurrent.BlockingQueue
@SpringBootTest(
properties = [
"org.jesperancinha.newscast.host=http://localhost:8080",
"org.jesperancinha.newscast.timeToWaitSeconds=5"
]
)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
@ActiveProfiles("non-scheduler")
internal class NewsCastClientJUnit5Test @Autowired constructor(
val newsCastClient: NewsCastClient
) : AbstractNCTest() {
@MockkBean(relaxed = true)
lateinit var newsCastMessageProcessor: NewsCastMessageProcessor
@MockkBean(relaxed = true)
lateinit var blockingQueue: BlockingQueue<String>
@MockkBean(relaxed = true)
lateinit var runningService: OneRunServiceImpl
/**
* No exception is thrown while polling the buffer even though no connection has been made to newscast.
* Temporarily disabled because it does not seem to work in GitHub Actions Pipeline
*
* @throws InterruptedException May occur while waiting for the executor to complete.
*/
@Test
fun testStartFetchProcess_whenProgrammed5Second_endsGracefullyImmediately() {
newsCastClient.startFetchProcess()
val longArgumentCaptor = mutableListOf<Long>()
verify {
newsCastMessageProcessor.processAllMessages(
any(),
capture(longArgumentCaptor),
capture(longArgumentCaptor)
)
}
verify(exactly = 1) { blockingQueue.remainingCapacity() }
verify(exactly = 1) { runningService.startProcess() }
longArgumentCaptor.shouldHaveSize(2)
longArgumentCaptor.shouldNotBeNull()
val startTimestamp = longArgumentCaptor[0]
val endTimeStamp = longArgumentCaptor[1]
val timeStampDiff = endTimeStamp - startTimestamp
timeStampDiff.shouldBeGreaterThanOrEqual(0)
timeStampDiff.shouldBeLessThanOrEqual(5)
}
} | 1 | Kotlin | 0 | 4 | a15a23133a9769feeb514b27e43ca6512c2d86d6 | 2,763 | news-cast-explorer | Apache License 2.0 |
composeApp/src/commonMain/kotlin/com/jetbrains/bs23_kmp/core/base/widget/Divider.kt | TahsinBS1531 | 854,998,729 | false | {"Kotlin": 95847, "Swift": 685} | package com.jetbrains.bs23_kmp.core.base.widget
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Divider
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@Composable
fun JRDivider(modifier: Modifier = Modifier) {
Divider(
modifier = modifier
.fillMaxWidth()
.height(1.dp),
)
}
//@Preview("default", showBackground = true)
//@Preview("dark theme", uiMode = Configuration.UI_MODE_NIGHT_YES, showBackground = true)
//@Composable
//private fun DividerPreview() {
// AppTheme {
// Box(Modifier.size(height = 10.dp, width = 100.dp)) {
// JRDivider(Modifier.align(Alignment.Center))
// }
// }
//} | 0 | Kotlin | 0 | 1 | 422e788c2a35fa2c7572f2323dd234766378acbb | 818 | BS23-KMP | Apache License 2.0 |
src/main/kotlin/co/there4/hexagon/web/EndException.kt | rinekri | 73,641,098 | true | {"Kotlin": 202934, "Shell": 11518, "FreeMarker": 7663, "Batchfile": 2292, "CSS": 1326, "HTML": 653} | package co.there4.hexagon.web
/**
* Exception used for stopping the execution. It is used only for flow control.
*/
class EndException: RuntimeException ()
| 0 | Kotlin | 0 | 0 | fde9fe81b19cf3ab532aa9ed6ebb7106463a087d | 159 | hexagon | The Unlicense |
Library/src/main/java/com/magenta/navigation/helpers/AndroidVersion.kt | vipafattal | 154,172,114 | false | {"Gradle": 4, "YAML": 1, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "INI": 1, "Proguard": 2, "Java": 2, "XML": 27, "Kotlin": 17} | package com.codebox.lib.android.os
import android.os.Build
import android.support.annotation.RequiresApi
/**
* Created by Abed on 2/3/2018.
*/
inline fun api(newerSDK: Int, newerSDKBlock: () -> Unit) {
if (Build.VERSION.SDK_INT >= newerSDK)
newerSDKBlock()
} | 0 | Kotlin | 0 | 0 | c35ad3a1ed9072f73a22c7fe64906abfe3762c2c | 276 | Magenta-Navigation | MIT License |
packages/cactus-plugin-ledger-connector-corda/src/main/kotlin/generated/openapi/kotlin-client/src/main/kotlin/org/openapitools/client/models/CPIIDV1.kt | hyperledger-cacti | 216,610,150 | false | {"TypeScript": 6934396, "Kotlin": 1968990, "Go": 1095701, "Rust": 818809, "JavaScript": 247017, "Shell": 208308, "Solidity": 98585, "Makefile": 55723, "Dockerfile": 39854, "PLpgSQL": 20654, "Logos": 17763, "Mustache": 14807, "Java": 11477, "ANTLR": 1108, "Roff": 776, "HTML": 361, "EJS": 98} | /**
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package org.openapitools.client.models
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
*
*
* @param name
* @param version
* @param signerSummaryHash
*/
data class CPIIDV1 (
@Json(name = "name")
val name: kotlin.String,
@Json(name = "version")
val version: kotlin.String,
@Json(name = "signerSummaryHash")
val signerSummaryHash: kotlin.String? = null
)
| 324 | TypeScript | 284 | 341 | ff842d2a59ef898e734e1424ee6f26b52ba0af9b | 691 | cacti | Apache License 2.0 |
app/src/main/java/com/lodz/android/agiledevkt/modules/rv/swipe/SwipeTestVbAdapter.kt | LZ9 | 137,967,291 | false | {"Kotlin": 2174504} | package com.lodz.android.agiledevkt.modules.rv.swipe
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import com.lodz.android.agiledevkt.R
import com.lodz.android.agiledevkt.databinding.RvItemSwipeContentBinding
import com.lodz.android.agiledevkt.databinding.RvItemSwipeLeftBinding
import com.lodz.android.agiledevkt.databinding.RvItemSwipeRightBinding
import com.lodz.android.corekt.anko.append
import com.lodz.android.corekt.anko.dp2px
import com.lodz.android.corekt.anko.toastShort
import com.lodz.android.pandora.widget.rv.swipe.vb.BaseSwipeVbRvAdapter
import com.lodz.android.pandora.widget.rv.swipe.vb.SwipeVbViewHolder
/**
* 侧滑菜单适配器
* @author zhouL
* @date 2022/10/9
*/
class SwipeTestVbAdapter(context: Context) : BaseSwipeVbRvAdapter<String>(context) {
override fun createContentVbInflate(): (LayoutInflater, parent: ViewGroup, attachToRoot: Boolean) -> ViewBinding = RvItemSwipeContentBinding::inflate
override fun createLeftVbInflate(): ((LayoutInflater, parent: ViewGroup, attachToRoot: Boolean) -> ViewBinding) = RvItemSwipeLeftBinding::inflate
override fun createRightVbInflate(): ((LayoutInflater, parent: ViewGroup, attachToRoot: Boolean) -> ViewBinding) = RvItemSwipeRightBinding::inflate
override fun configSwipeViewHolder(holder: SwipeVbViewHolder, parent: ViewGroup, viewType: Int) {
super.configSwipeViewHolder(holder, parent, viewType)
setItemViewHeight(holder.itemView, context.dp2px(50))
}
override fun onBind(holder: SwipeVbViewHolder, position: Int) {
val item = getItem(position) ?: return
holder.getContentViewBinding<RvItemSwipeContentBinding>().apply {
titleTv.text = position.toString().append(". ").append(item)
}
holder.getLeftViewBinding<RvItemSwipeLeftBinding>().apply {
likeBtn.setOnClickListener {
context.toastShort(position.toString().append(context.getString(R.string.rv_swipe_like)))
}
}
holder.getRightViewBinding<RvItemSwipeRightBinding>().apply {
shareBtn.setOnClickListener {
context.toastShort(position.toString().append(context.getString(R.string.rv_swipe_share)))
}
}
}
} | 0 | Kotlin | 3 | 11 | 926b9f968a984c42ade94371714ef4caf3ffbccf | 2,309 | AgileDevKt | Apache License 2.0 |
src/main/kotlin/uk/gov/justice/digital/hmpps/deliusapi/entity/CourtAppearance.kt | ministryofjustice | 334,932,480 | false | null | package uk.gov.justice.digital.hmpps.deliusapi.entity
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.Id
import jakarta.persistence.JoinColumn
import jakarta.persistence.ManyToOne
import jakarta.persistence.Table
@Entity
@Table(name = "COURT_APPEARANCE")
class CourtAppearance(
@Id
@Column(name = "COURT_APPEARANCE_ID", nullable = false)
val id: Long,
@ManyToOne
@JoinColumn(name = "EVENT_ID", nullable = false)
val event: Event,
)
| 3 | Kotlin | 1 | 4 | 115e262194f4a0a5fa7fa6fbf4182020d4e443f1 | 494 | hmpps-delius-api | MIT License |
lib/src/EntityExtensions.kt | darkoverlordofdata | 57,008,576 | false | null | package com.darkoverlordofdata.entitas.demo
/**
* Entitas Generated Entity Extensions for com.darkoverlordofdata.entitas.demo
*
* do not edit this file
*/
import java.util.*
import com.darkoverlordofdata.entitas.Entity
/** Entity: Bounds methods*/
val Entity_boundsComponentPool:MutableList<BoundsComponent> = ArrayList(listOf())
val Entity.bounds:BoundsComponent
get() = getComponent(Component.Bounds.ordinal) as BoundsComponent
val Entity.hasBounds:Boolean
get() = hasComponent(Component.Bounds.ordinal)
fun Entity.clearBoundsComponentPool() {
Entity_boundsComponentPool.clear()
}
fun Entity.addBounds(radius:Float):Entity {
val component = if (Entity_boundsComponentPool.size > 0) Entity_boundsComponentPool.last() else BoundsComponent()
component.radius = radius
addComponent(Component.Bounds.ordinal, component)
return this
}
fun Entity.replaceBounds(radius:Float):Entity {
val previousComponent = if (hasBounds) bounds else null
val component = if (Entity_boundsComponentPool.size > 0) Entity_boundsComponentPool.last() else BoundsComponent()
component.radius = radius
replaceComponent(Component.Bounds.ordinal, component)
if (previousComponent != null)
Entity_boundsComponentPool.add(previousComponent)
return this
}
fun Entity.removeBounds():Entity {
val component = bounds
removeComponent(Component.Bounds.ordinal)
Entity_boundsComponentPool.add(component)
return this
}
/** Entity: Bullet methods*/
val Entity_bulletComponentPool:MutableList<BulletComponent> = ArrayList(listOf())
val Entity.bullet:BulletComponent
get() = getComponent(Component.Bullet.ordinal) as BulletComponent
val Entity.hasBullet:Boolean
get() = hasComponent(Component.Bullet.ordinal)
fun Entity.clearBulletComponentPool() {
Entity_bulletComponentPool.clear()
}
fun Entity.addBullet(false:undefined):Entity {
val component = if (Entity_bulletComponentPool.size > 0) Entity_bulletComponentPool.last() else BulletComponent()
component.false = false
addComponent(Component.Bullet.ordinal, component)
return this
}
fun Entity.replaceBullet(false:undefined):Entity {
val previousComponent = if (hasBullet) bullet else null
val component = if (Entity_bulletComponentPool.size > 0) Entity_bulletComponentPool.last() else BulletComponent()
component.false = false
replaceComponent(Component.Bullet.ordinal, component)
if (previousComponent != null)
Entity_bulletComponentPool.add(previousComponent)
return this
}
fun Entity.removeBullet():Entity {
val component = bullet
removeComponent(Component.Bullet.ordinal)
Entity_bulletComponentPool.add(component)
return this
}
/** Entity: Destroy methods*/
val Entity_destroyComponentPool:MutableList<DestroyComponent> = ArrayList(listOf())
val Entity.destroy:DestroyComponent
get() = getComponent(Component.Destroy.ordinal) as DestroyComponent
val Entity.hasDestroy:Boolean
get() = hasComponent(Component.Destroy.ordinal)
fun Entity.clearDestroyComponentPool() {
Entity_destroyComponentPool.clear()
}
fun Entity.addDestroy(false:undefined):Entity {
val component = if (Entity_destroyComponentPool.size > 0) Entity_destroyComponentPool.last() else DestroyComponent()
component.false = false
addComponent(Component.Destroy.ordinal, component)
return this
}
fun Entity.replaceDestroy(false:undefined):Entity {
val previousComponent = if (hasDestroy) destroy else null
val component = if (Entity_destroyComponentPool.size > 0) Entity_destroyComponentPool.last() else DestroyComponent()
component.false = false
replaceComponent(Component.Destroy.ordinal, component)
if (previousComponent != null)
Entity_destroyComponentPool.add(previousComponent)
return this
}
fun Entity.removeDestroy():Entity {
val component = destroy
removeComponent(Component.Destroy.ordinal)
Entity_destroyComponentPool.add(component)
return this
}
/** Entity: Enemy methods*/
val Entity_enemyComponentPool:MutableList<EnemyComponent> = ArrayList(listOf())
val Entity.enemy:EnemyComponent
get() = getComponent(Component.Enemy.ordinal) as EnemyComponent
val Entity.hasEnemy:Boolean
get() = hasComponent(Component.Enemy.ordinal)
fun Entity.clearEnemyComponentPool() {
Entity_enemyComponentPool.clear()
}
fun Entity.addEnemy(false:undefined):Entity {
val component = if (Entity_enemyComponentPool.size > 0) Entity_enemyComponentPool.last() else EnemyComponent()
component.false = false
addComponent(Component.Enemy.ordinal, component)
return this
}
fun Entity.replaceEnemy(false:undefined):Entity {
val previousComponent = if (hasEnemy) enemy else null
val component = if (Entity_enemyComponentPool.size > 0) Entity_enemyComponentPool.last() else EnemyComponent()
component.false = false
replaceComponent(Component.Enemy.ordinal, component)
if (previousComponent != null)
Entity_enemyComponentPool.add(previousComponent)
return this
}
fun Entity.removeEnemy():Entity {
val component = enemy
removeComponent(Component.Enemy.ordinal)
Entity_enemyComponentPool.add(component)
return this
}
/** Entity: Expires methods*/
val Entity_expiresComponentPool:MutableList<ExpiresComponent> = ArrayList(listOf())
val Entity.expires:ExpiresComponent
get() = getComponent(Component.Expires.ordinal) as ExpiresComponent
val Entity.hasExpires:Boolean
get() = hasComponent(Component.Expires.ordinal)
fun Entity.clearExpiresComponentPool() {
Entity_expiresComponentPool.clear()
}
fun Entity.addExpires(delay:Float):Entity {
val component = if (Entity_expiresComponentPool.size > 0) Entity_expiresComponentPool.last() else ExpiresComponent()
component.delay = delay
addComponent(Component.Expires.ordinal, component)
return this
}
fun Entity.replaceExpires(delay:Float):Entity {
val previousComponent = if (hasExpires) expires else null
val component = if (Entity_expiresComponentPool.size > 0) Entity_expiresComponentPool.last() else ExpiresComponent()
component.delay = delay
replaceComponent(Component.Expires.ordinal, component)
if (previousComponent != null)
Entity_expiresComponentPool.add(previousComponent)
return this
}
fun Entity.removeExpires():Entity {
val component = expires
removeComponent(Component.Expires.ordinal)
Entity_expiresComponentPool.add(component)
return this
}
/** Entity: Firing methods*/
val Entity_firingComponentPool:MutableList<FiringComponent> = ArrayList(listOf())
val Entity.firing:FiringComponent
get() = getComponent(Component.Firing.ordinal) as FiringComponent
val Entity.hasFiring:Boolean
get() = hasComponent(Component.Firing.ordinal)
fun Entity.clearFiringComponentPool() {
Entity_firingComponentPool.clear()
}
fun Entity.addFiring(false:undefined):Entity {
val component = if (Entity_firingComponentPool.size > 0) Entity_firingComponentPool.last() else FiringComponent()
component.false = false
addComponent(Component.Firing.ordinal, component)
return this
}
fun Entity.replaceFiring(false:undefined):Entity {
val previousComponent = if (hasFiring) firing else null
val component = if (Entity_firingComponentPool.size > 0) Entity_firingComponentPool.last() else FiringComponent()
component.false = false
replaceComponent(Component.Firing.ordinal, component)
if (previousComponent != null)
Entity_firingComponentPool.add(previousComponent)
return this
}
fun Entity.removeFiring():Entity {
val component = firing
removeComponent(Component.Firing.ordinal)
Entity_firingComponentPool.add(component)
return this
}
/** Entity: Health methods*/
val Entity_healthComponentPool:MutableList<HealthComponent> = ArrayList(listOf())
val Entity.health:HealthComponent
get() = getComponent(Component.Health.ordinal) as HealthComponent
val Entity.hasHealth:Boolean
get() = hasComponent(Component.Health.ordinal)
fun Entity.clearHealthComponentPool() {
Entity_healthComponentPool.clear()
}
fun Entity.addHealth(currentHealth:Float, maximumHealth:Float):Entity {
val component = if (Entity_healthComponentPool.size > 0) Entity_healthComponentPool.last() else HealthComponent()
component.currentHealth = currentHealth
component.maximumHealth = maximumHealth
addComponent(Component.Health.ordinal, component)
return this
}
fun Entity.replaceHealth(currentHealth:Float, maximumHealth:Float):Entity {
val previousComponent = if (hasHealth) health else null
val component = if (Entity_healthComponentPool.size > 0) Entity_healthComponentPool.last() else HealthComponent()
component.currentHealth = currentHealth
component.maximumHealth = maximumHealth
replaceComponent(Component.Health.ordinal, component)
if (previousComponent != null)
Entity_healthComponentPool.add(previousComponent)
return this
}
fun Entity.removeHealth():Entity {
val component = health
removeComponent(Component.Health.ordinal)
Entity_healthComponentPool.add(component)
return this
}
/** Entity: Layer methods*/
val Entity_layerComponentPool:MutableList<LayerComponent> = ArrayList(listOf())
val Entity.layer:LayerComponent
get() = getComponent(Component.Layer.ordinal) as LayerComponent
val Entity.hasLayer:Boolean
get() = hasComponent(Component.Layer.ordinal)
fun Entity.clearLayerComponentPool() {
Entity_layerComponentPool.clear()
}
fun Entity.addLayer(ordinal:com.darkoverlordofdata.entitas.demo.Layer):Entity {
val component = if (Entity_layerComponentPool.size > 0) Entity_layerComponentPool.last() else LayerComponent()
component.ordinal = ordinal
addComponent(Component.Layer.ordinal, component)
return this
}
fun Entity.replaceLayer(ordinal:com.darkoverlordofdata.entitas.demo.Layer):Entity {
val previousComponent = if (hasLayer) layer else null
val component = if (Entity_layerComponentPool.size > 0) Entity_layerComponentPool.last() else LayerComponent()
component.ordinal = ordinal
replaceComponent(Component.Layer.ordinal, component)
if (previousComponent != null)
Entity_layerComponentPool.add(previousComponent)
return this
}
fun Entity.removeLayer():Entity {
val component = layer
removeComponent(Component.Layer.ordinal)
Entity_layerComponentPool.add(component)
return this
}
/** Entity: Player methods*/
val Entity_playerComponentPool:MutableList<PlayerComponent> = ArrayList(listOf())
val Entity.player:PlayerComponent
get() = getComponent(Component.Player.ordinal) as PlayerComponent
val Entity.hasPlayer:Boolean
get() = hasComponent(Component.Player.ordinal)
fun Entity.clearPlayerComponentPool() {
Entity_playerComponentPool.clear()
}
fun Entity.addPlayer(false:undefined):Entity {
val component = if (Entity_playerComponentPool.size > 0) Entity_playerComponentPool.last() else PlayerComponent()
component.false = false
addComponent(Component.Player.ordinal, component)
return this
}
fun Entity.replacePlayer(false:undefined):Entity {
val previousComponent = if (hasPlayer) player else null
val component = if (Entity_playerComponentPool.size > 0) Entity_playerComponentPool.last() else PlayerComponent()
component.false = false
replaceComponent(Component.Player.ordinal, component)
if (previousComponent != null)
Entity_playerComponentPool.add(previousComponent)
return this
}
fun Entity.removePlayer():Entity {
val component = player
removeComponent(Component.Player.ordinal)
Entity_playerComponentPool.add(component)
return this
}
/** Entity: Position methods*/
val Entity_positionComponentPool:MutableList<PositionComponent> = ArrayList(listOf())
val Entity.position:PositionComponent
get() = getComponent(Component.Position.ordinal) as PositionComponent
val Entity.hasPosition:Boolean
get() = hasComponent(Component.Position.ordinal)
fun Entity.clearPositionComponentPool() {
Entity_positionComponentPool.clear()
}
fun Entity.addPosition(x:Float, y:Float):Entity {
val component = if (Entity_positionComponentPool.size > 0) Entity_positionComponentPool.last() else PositionComponent()
component.x = x
component.y = y
addComponent(Component.Position.ordinal, component)
return this
}
fun Entity.replacePosition(x:Float, y:Float):Entity {
val previousComponent = if (hasPosition) position else null
val component = if (Entity_positionComponentPool.size > 0) Entity_positionComponentPool.last() else PositionComponent()
component.x = x
component.y = y
replaceComponent(Component.Position.ordinal, component)
if (previousComponent != null)
Entity_positionComponentPool.add(previousComponent)
return this
}
fun Entity.removePosition():Entity {
val component = position
removeComponent(Component.Position.ordinal)
Entity_positionComponentPool.add(component)
return this
}
/** Entity: Resource methods*/
val Entity_resourceComponentPool:MutableList<ResourceComponent> = ArrayList(listOf())
val Entity.resource:ResourceComponent
get() = getComponent(Component.Resource.ordinal) as ResourceComponent
val Entity.hasResource:Boolean
get() = hasComponent(Component.Resource.ordinal)
fun Entity.clearResourceComponentPool() {
Entity_resourceComponentPool.clear()
}
fun Entity.addResource(name:String):Entity {
val component = if (Entity_resourceComponentPool.size > 0) Entity_resourceComponentPool.last() else ResourceComponent()
component.name = name
addComponent(Component.Resource.ordinal, component)
return this
}
fun Entity.replaceResource(name:String):Entity {
val previousComponent = if (hasResource) resource else null
val component = if (Entity_resourceComponentPool.size > 0) Entity_resourceComponentPool.last() else ResourceComponent()
component.name = name
replaceComponent(Component.Resource.ordinal, component)
if (previousComponent != null)
Entity_resourceComponentPool.add(previousComponent)
return this
}
fun Entity.removeResource():Entity {
val component = resource
removeComponent(Component.Resource.ordinal)
Entity_resourceComponentPool.add(component)
return this
}
/** Entity: Scale methods*/
val Entity_scaleComponentPool:MutableList<ScaleComponent> = ArrayList(listOf())
val Entity.scale:ScaleComponent
get() = getComponent(Component.Scale.ordinal) as ScaleComponent
val Entity.hasScale:Boolean
get() = hasComponent(Component.Scale.ordinal)
fun Entity.clearScaleComponentPool() {
Entity_scaleComponentPool.clear()
}
fun Entity.addScale(x:Float, y:Float):Entity {
val component = if (Entity_scaleComponentPool.size > 0) Entity_scaleComponentPool.last() else ScaleComponent()
component.x = x
component.y = y
addComponent(Component.Scale.ordinal, component)
return this
}
fun Entity.replaceScale(x:Float, y:Float):Entity {
val previousComponent = if (hasScale) scale else null
val component = if (Entity_scaleComponentPool.size > 0) Entity_scaleComponentPool.last() else ScaleComponent()
component.x = x
component.y = y
replaceComponent(Component.Scale.ordinal, component)
if (previousComponent != null)
Entity_scaleComponentPool.add(previousComponent)
return this
}
fun Entity.removeScale():Entity {
val component = scale
removeComponent(Component.Scale.ordinal)
Entity_scaleComponentPool.add(component)
return this
}
/** Entity: Score methods*/
val Entity_scoreComponentPool:MutableList<ScoreComponent> = ArrayList(listOf())
val Entity.score:ScoreComponent
get() = getComponent(Component.Score.ordinal) as ScoreComponent
val Entity.hasScore:Boolean
get() = hasComponent(Component.Score.ordinal)
fun Entity.clearScoreComponentPool() {
Entity_scoreComponentPool.clear()
}
fun Entity.addScore(value:Int):Entity {
val component = if (Entity_scoreComponentPool.size > 0) Entity_scoreComponentPool.last() else ScoreComponent()
component.value = value
addComponent(Component.Score.ordinal, component)
return this
}
fun Entity.replaceScore(value:Int):Entity {
val previousComponent = if (hasScore) score else null
val component = if (Entity_scoreComponentPool.size > 0) Entity_scoreComponentPool.last() else ScoreComponent()
component.value = value
replaceComponent(Component.Score.ordinal, component)
if (previousComponent != null)
Entity_scoreComponentPool.add(previousComponent)
return this
}
fun Entity.removeScore():Entity {
val component = score
removeComponent(Component.Score.ordinal)
Entity_scoreComponentPool.add(component)
return this
}
/** Entity: SoundEffect methods*/
val Entity_soundEffectComponentPool:MutableList<SoundEffectComponent> = ArrayList(listOf())
val Entity.soundEffect:SoundEffectComponent
get() = getComponent(Component.SoundEffect.ordinal) as SoundEffectComponent
val Entity.hasSoundEffect:Boolean
get() = hasComponent(Component.SoundEffect.ordinal)
fun Entity.clearSoundEffectComponentPool() {
Entity_soundEffectComponentPool.clear()
}
fun Entity.addSoundEffect(effect:com.darkoverlordofdata.entitas.demo.Effect):Entity {
val component = if (Entity_soundEffectComponentPool.size > 0) Entity_soundEffectComponentPool.last() else SoundEffectComponent()
component.effect = effect
addComponent(Component.SoundEffect.ordinal, component)
return this
}
fun Entity.replaceSoundEffect(effect:com.darkoverlordofdata.entitas.demo.Effect):Entity {
val previousComponent = if (hasSoundEffect) soundEffect else null
val component = if (Entity_soundEffectComponentPool.size > 0) Entity_soundEffectComponentPool.last() else SoundEffectComponent()
component.effect = effect
replaceComponent(Component.SoundEffect.ordinal, component)
if (previousComponent != null)
Entity_soundEffectComponentPool.add(previousComponent)
return this
}
fun Entity.removeSoundEffect():Entity {
val component = soundEffect
removeComponent(Component.SoundEffect.ordinal)
Entity_soundEffectComponentPool.add(component)
return this
}
/** Entity: Tint methods*/
val Entity_tintComponentPool:MutableList<TintComponent> = ArrayList(listOf())
val Entity.tint:TintComponent
get() = getComponent(Component.Tint.ordinal) as TintComponent
val Entity.hasTint:Boolean
get() = hasComponent(Component.Tint.ordinal)
fun Entity.clearTintComponentPool() {
Entity_tintComponentPool.clear()
}
fun Entity.addTint(r:Float, g:Float, b:Float, a:Float):Entity {
val component = if (Entity_tintComponentPool.size > 0) Entity_tintComponentPool.last() else TintComponent()
component.r = r
component.g = g
component.b = b
component.a = a
addComponent(Component.Tint.ordinal, component)
return this
}
fun Entity.replaceTint(r:Float, g:Float, b:Float, a:Float):Entity {
val previousComponent = if (hasTint) tint else null
val component = if (Entity_tintComponentPool.size > 0) Entity_tintComponentPool.last() else TintComponent()
component.r = r
component.g = g
component.b = b
component.a = a
replaceComponent(Component.Tint.ordinal, component)
if (previousComponent != null)
Entity_tintComponentPool.add(previousComponent)
return this
}
fun Entity.removeTint():Entity {
val component = tint
removeComponent(Component.Tint.ordinal)
Entity_tintComponentPool.add(component)
return this
}
/** Entity: Tween methods*/
val Entity_tweenComponentPool:MutableList<TweenComponent> = ArrayList(listOf())
val Entity.tween:TweenComponent
get() = getComponent(Component.Tween.ordinal) as TweenComponent
val Entity.hasTween:Boolean
get() = hasComponent(Component.Tween.ordinal)
fun Entity.clearTweenComponentPool() {
Entity_tweenComponentPool.clear()
}
fun Entity.addTween(min:Float, max:Float, speed:Float, repeat:Boolean, active:Boolean):Entity {
val component = if (Entity_tweenComponentPool.size > 0) Entity_tweenComponentPool.last() else TweenComponent()
component.min = min
component.max = max
component.speed = speed
component.repeat = repeat
component.active = active
addComponent(Component.Tween.ordinal, component)
return this
}
fun Entity.replaceTween(min:Float, max:Float, speed:Float, repeat:Boolean, active:Boolean):Entity {
val previousComponent = if (hasTween) tween else null
val component = if (Entity_tweenComponentPool.size > 0) Entity_tweenComponentPool.last() else TweenComponent()
component.min = min
component.max = max
component.speed = speed
component.repeat = repeat
component.active = active
replaceComponent(Component.Tween.ordinal, component)
if (previousComponent != null)
Entity_tweenComponentPool.add(previousComponent)
return this
}
fun Entity.removeTween():Entity {
val component = tween
removeComponent(Component.Tween.ordinal)
Entity_tweenComponentPool.add(component)
return this
}
/** Entity: Velocity methods*/
val Entity_velocityComponentPool:MutableList<VelocityComponent> = ArrayList(listOf())
val Entity.velocity:VelocityComponent
get() = getComponent(Component.Velocity.ordinal) as VelocityComponent
val Entity.hasVelocity:Boolean
get() = hasComponent(Component.Velocity.ordinal)
fun Entity.clearVelocityComponentPool() {
Entity_velocityComponentPool.clear()
}
fun Entity.addVelocity(x:Float, y:Float):Entity {
val component = if (Entity_velocityComponentPool.size > 0) Entity_velocityComponentPool.last() else VelocityComponent()
component.x = x
component.y = y
addComponent(Component.Velocity.ordinal, component)
return this
}
fun Entity.replaceVelocity(x:Float, y:Float):Entity {
val previousComponent = if (hasVelocity) velocity else null
val component = if (Entity_velocityComponentPool.size > 0) Entity_velocityComponentPool.last() else VelocityComponent()
component.x = x
component.y = y
replaceComponent(Component.Velocity.ordinal, component)
if (previousComponent != null)
Entity_velocityComponentPool.add(previousComponent)
return this
}
fun Entity.removeVelocity():Entity {
val component = velocity
removeComponent(Component.Velocity.ordinal)
Entity_velocityComponentPool.add(component)
return this
}
/** Entity: View methods*/
val Entity_viewComponentPool:MutableList<ViewComponent> = ArrayList(listOf())
val Entity.view:ViewComponent
get() = getComponent(Component.View.ordinal) as ViewComponent
val Entity.hasView:Boolean
get() = hasComponent(Component.View.ordinal)
fun Entity.clearViewComponentPool() {
Entity_viewComponentPool.clear()
}
fun Entity.addView(sprite:com.badlogic.gdx.graphics.g2d.Sprite):Entity {
val component = if (Entity_viewComponentPool.size > 0) Entity_viewComponentPool.last() else ViewComponent()
component.sprite = sprite
addComponent(Component.View.ordinal, component)
return this
}
fun Entity.replaceView(sprite:com.badlogic.gdx.graphics.g2d.Sprite):Entity {
val previousComponent = if (hasView) view else null
val component = if (Entity_viewComponentPool.size > 0) Entity_viewComponentPool.last() else ViewComponent()
component.sprite = sprite
replaceComponent(Component.View.ordinal, component)
if (previousComponent != null)
Entity_viewComponentPool.add(previousComponent)
return this
}
fun Entity.removeView():Entity {
val component = view
removeComponent(Component.View.ordinal)
Entity_viewComponentPool.add(component)
return this
}
| 1 | Kotlin | 1 | 6 | d90980d96f252379fd01a1601c6c3c1de6ae45e4 | 23,662 | entitas-kotlin | MIT License |
ui/ui-mobile/src/main/java/dev/yankew/sample/ui/about/DeveloperViewModel.kt | yacca | 464,737,432 | false | {"Kotlin": 178034} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.yankew.sample.ui.about
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import dev.yankew.sample.domain.config.NewFeatureLocalParam
import dev.yankew.sample.domain.config.NewFeatureParam
import dev.yankew.sample.domain.config.getConfiguredValue
import dev.yankew.sample.domain.util.orNull
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.launch
import java.util.Optional
import javax.inject.Inject
@HiltViewModel
class DeveloperViewModel @Inject constructor(
@NewFeatureParam private val localNewFeatureParam: Optional<NewFeatureLocalParam>,
) : ViewModel() {
val newFeatureLocalEnabled = localNewFeatureParam.getConfiguredValue { flowOf(false) }
fun setNewFeatureLocalEnabled(enabled: Boolean) {
viewModelScope.launch {
localNewFeatureParam.orNull()?.setValue(enabled)
}
}
}
| 0 | Kotlin | 4 | 25 | 12c7367d72b99080347002a245c8edbbd63f7699 | 1,520 | android-clean-arch | Apache License 2.0 |
data/src/main/java/com/movingmaker/data/remote/datasourceimpl/MemberRemoteDataSourceImpl.kt | dudwls901 | 458,682,004 | false | {"Kotlin": 359176} | package com.movingmaker.data.remote.datasourceimpl
import com.movingmaker.data.remote.api.BearerAndXAuthTokenApiService
import com.movingmaker.data.remote.api.BearerApiService
import com.movingmaker.data.remote.api.NoHeaderApiService
import com.movingmaker.data.remote.api.XAuthTokenAndRefreshTokenApiService
import com.movingmaker.data.remote.datasource.MemberRemoteDataSource
import com.movingmaker.data.remote.model.request.ChangePasswordRequest
import com.movingmaker.data.remote.model.request.EmailCodeCheckRequest
import com.movingmaker.data.remote.model.request.KakaoLoginRequest
import com.movingmaker.data.remote.model.request.KakaoSignUpRequest
import com.movingmaker.data.remote.model.request.LogInRequest
import com.movingmaker.data.remote.model.request.SignUpRequest
import com.movingmaker.data.util.safeApiCall
import com.movingmaker.domain.model.NetworkResult
import com.movingmaker.domain.model.response.AuthTokens
import com.movingmaker.domain.model.response.BaseResponse
import com.movingmaker.domain.model.response.Login
import com.movingmaker.domain.model.response.MyInfo
import javax.inject.Inject
class MemberRemoteDataSourceImpl @Inject constructor(
private val noHeaderApiService: NoHeaderApiService,
private val bearerApiService: BearerApiService,
private val bearerAndXAuthTokenApiService: BearerAndXAuthTokenApiService,
private val xAuthTokenAndRefreshTokenApiService: XAuthTokenAndRefreshTokenApiService
) : MemberRemoteDataSource {
override suspend fun sendEmailCode(email: String): NetworkResult<BaseResponse<String>> =
safeApiCall { noHeaderApiService.sendEmailCode(email) }
override suspend fun checkEmailCode(emailCodeCheckRequest: EmailCodeCheckRequest): NetworkResult<BaseResponse<String>> =
safeApiCall { noHeaderApiService.checkEmailCode(emailCodeCheckRequest) }
override suspend fun signUp(signUpRequest: SignUpRequest): NetworkResult<BaseResponse<String>> =
safeApiCall { noHeaderApiService.signUp(signUpRequest) }
override suspend fun kakaoLogIn(kakaoLoginRequest: KakaoLoginRequest): NetworkResult<BaseResponse<Login>> =
safeApiCall { noHeaderApiService.kakaoLogIn(kakaoLoginRequest) }
override suspend fun findPassword(email: String): NetworkResult<BaseResponse<String>> =
safeApiCall { noHeaderApiService.findPassword(email) }
override suspend fun changePassword(changePasswordRequest: ChangePasswordRequest): NetworkResult<BaseResponse<String>> =
safeApiCall { bearerApiService.changePassword(changePasswordRequest) }
override suspend fun logIn(logInRequest: LogInRequest): NetworkResult<BaseResponse<Login>> =
safeApiCall { noHeaderApiService.logIn(logInRequest) }
override suspend fun kakaoSignUpSetAccepts(kakaoSignUpRequest: KakaoSignUpRequest): NetworkResult<BaseResponse<String>> =
safeApiCall { noHeaderApiService.kakaoSignUpSetAccepts(kakaoSignUpRequest) }
override suspend fun signOut(): NetworkResult<BaseResponse<String>> =
safeApiCall { bearerApiService.signOut() }
override suspend fun getMyPage(): NetworkResult<BaseResponse<MyInfo>> =
safeApiCall { bearerApiService.getMyPage() }
override suspend fun patchCommentPushState(): NetworkResult<BaseResponse<Map<String, Boolean>>> =
safeApiCall { bearerApiService.patchCommentPushState() }
override suspend fun logOut(): NetworkResult<BaseResponse<String>> =
safeApiCall { bearerAndXAuthTokenApiService.logOut() }
override suspend fun reIssueToken(): NetworkResult<BaseResponse<AuthTokens>> =
safeApiCall { xAuthTokenAndRefreshTokenApiService.reIssueToken() }
} | 8 | Kotlin | 0 | 2 | e50510f55241db2294f23e4902980cec59594bbf | 3,651 | CommentDiary-Android | MIT License |
src/main/kotlin/com/zupacademy/fabiano/pix/clients/bc/BcPixClient.kt | birojow | 394,397,611 | true | {"Kotlin": 84998, "Smarty": 2082, "Dockerfile": 166} | package com.zupacademy.fabiano.pix.clients.bc
import io.micronaut.http.HttpResponse
import io.micronaut.http.MediaType
import io.micronaut.http.annotation.*
import io.micronaut.http.client.annotation.Client
@Client("\${bc.pix.url}")
interface BcPixClient {
@Post(value = "/api/v1/pix/keys",
produces = [MediaType.APPLICATION_XML],
processes = [MediaType.APPLICATION_XML])
fun cadastraChaveNoBC(@Body request: CreatePixKeyRequest)
: HttpResponse<CreatePixKeyResponse>
@Delete(value = "/api/v1/pix/keys/{key}",
produces = [MediaType.APPLICATION_XML],
processes = [MediaType.APPLICATION_XML])
fun excluiChaveNoBC(@PathVariable key: String, @Body request: DeletePixKeyRequest)
: HttpResponse<DeletePixKeyResponse>
@Get(value = "/api/v1/pix/keys/{key}",
produces = [MediaType.APPLICATION_XML],
processes = [MediaType.APPLICATION_XML])
fun consultaPorChave(@PathVariable key: String)
: HttpResponse<PixKeyDetailsResponse>
}
| 0 | Kotlin | 0 | 0 | 396b256f411ddab9e81898f04e44340b72b888ff | 1,019 | orange-talents-06-template-pix-keymanager-grpc | Apache License 2.0 |
compiler/testData/diagnostics/tests/multiplatform/manyImplMemberNotImplemented.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // TARGET_BACKEND: JVM
// !LANGUAGE: +MultiPlatformProjects
// MODULE: common
// TARGET_PLATFORM: Common
// FILE: common.kt
expect open class C1()
expect interface I1
open <!MANY_IMPL_MEMBER_NOT_IMPLEMENTED{JVM}!>class A<!> : C1(), I1
open <!MANY_IMPL_MEMBER_NOT_IMPLEMENTED{JVM}!>class B<!> : I1, C1()
expect abstract class C2()
expect interface I2
// TODO: KT-58829
class C : C2(), I2
// MODULE: jvm()()(common)
// TARGET_PLATFORM: JVM
// FILE: main.kt
actual open class C1 {
fun f() {}
}
actual interface I1 {
fun f() {}
}
actual abstract class C2 actual constructor() {
fun g() {}
}
actual interface I2 {
fun g()
}
| 166 | Kotlin | 5771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 645 | kotlin | Apache License 2.0 |
app/src/main/java/vn/root/app/pages/materialKit/carousel/CarouselFragment.kt | doananhtuan22111996 | 769,875,617 | false | {"Kotlin": 137316} | package vn.root.app.pages.materialKit.carousel
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.NavController
import androidx.navigation.fragment.findNavController
import com.google.android.material.carousel.CarouselLayoutManager
import com.google.android.material.carousel.CarouselSnapHelper
import com.google.android.material.carousel.HeroCarouselStrategy
import com.google.android.material.carousel.MultiBrowseCarouselStrategy
import com.google.android.material.carousel.UncontainedCarouselStrategy
import vn.root.app.R
import vn.root.app.databinding.FragmentCarouselBinding
class CarouselFragment : Fragment() {
private lateinit var viewBinding: FragmentCarouselBinding
private lateinit var navController: NavController
private lateinit var adapter: CarouselAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
adapter = CarouselAdapter()
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
viewBinding = FragmentCarouselBinding.inflate(inflater, container, false)
navController = findNavController()
return viewBinding.root
}
@SuppressLint("RestrictedApi")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewBinding.layoutHeader.toolbar.apply {
title = getString(R.string.carousel)
setNavigationOnClickListener { navController.popBackStack() }
menu.clear()
}
val snapHelper1 = CarouselSnapHelper()
snapHelper1.attachToRecyclerView(viewBinding.multipleBrowse)
viewBinding.multipleBrowse.apply {
layoutManager = CarouselLayoutManager(MultiBrowseCarouselStrategy())
adapter = [email protected]
}
val snapHelper2 = CarouselSnapHelper()
snapHelper2.attachToRecyclerView(viewBinding.hero)
viewBinding.hero.apply {
layoutManager = CarouselLayoutManager(HeroCarouselStrategy())
adapter = [email protected]
}
val snapHelper3 = CarouselSnapHelper()
snapHelper3.attachToRecyclerView(viewBinding.center)
val carousel = CarouselLayoutManager(HeroCarouselStrategy())
carousel.carouselAlignment = CarouselLayoutManager.ALIGNMENT_CENTER
viewBinding.center.apply {
layoutManager = carousel
adapter = [email protected]
}
val snapHelper4 = CarouselSnapHelper()
snapHelper4.attachToRecyclerView(viewBinding.uncontained)
viewBinding.uncontained.apply {
layoutManager = CarouselLayoutManager(UncontainedCarouselStrategy())
adapter = [email protected]
}
}
} | 0 | Kotlin | 0 | 0 | a0c9cbbcffed83711bdf5a61418d0737ae55fae1 | 2,753 | android_architecture | MIT License |
app/src/main/java/com/fengyongge/wanandroidclient/activity/RegisterActivity.kt | readC | 309,538,843 | true | {"Kotlin": 368003, "HTML": 5910} | package com.fengyongge.wanandroidclient.activity
import android.content.Intent
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import com.fengyongge.androidcommonutils.ktutils.DialogUtils
import com.fengyongge.androidcommonutils.ktutils.SharedPreferencesUtils
import com.fengyongge.androidcommonutils.ktutils.ToastUtils
import com.fengyongge.androidcommonutils.ktutils.ToolsUtils
import com.fengyongge.baselib.mvp.BaseMvpActivity
import com.fengyongge.wanandroidclient.common.RxNotify
import com.fengyongge.rxhttp.bean.BaseResponse
import com.fengyongge.rxhttp.exception.ResponseException
import com.fengyongge.wanandroidclient.App
import com.fengyongge.wanandroidclient.R
import com.fengyongge.wanandroidclient.bean.LoginBean
import com.fengyongge.wanandroidclient.bean.LogoutUpdateBean
import com.fengyongge.wanandroidclient.bean.RegisterBean
import com.fengyongge.wanandroidclient.constant.Const
import com.fengyongge.wanandroidclient.mvp.contract.LoginContact
import com.fengyongge.wanandroidclient.mvp.presenterImpl.LoginPresenterImpl
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.activity_register.*
import kotlinx.android.synthetic.main.activity_register.tvVersionName
/**
* describe
*
* @author fengyongge(<EMAIL>)
* @version V1.0
* @date 2020/09/08
*/
class RegisterActivity : BaseMvpActivity<LoginPresenterImpl>(), LoginContact.View, View.OnClickListener {
private var flag = false
private var confrimFlag = false
private var isReset = false
override fun initPresenter(): LoginPresenterImpl {
return LoginPresenterImpl()
}
override fun initLayout(): Int {
return R.layout.activity_register
}
override fun initView() {
tvVersionName.text = "V${ToolsUtils.getVersionName(this)}"
isReset = intent.getBooleanExtra("isReset", false)
if (isReset) {
etRegisterPassword.hint = Editable.Factory.getInstance().newEditable("新密码")
etRegisterConfirmPassword.hint = Editable.Factory.getInstance().newEditable("确认新密码")
btRegister.text = "重置密码"
} else {
etRegisterPassword.hint = Editable.Factory.getInstance().newEditable("密码")
etRegisterConfirmPassword.hint = Editable.Factory.getInstance().newEditable("确认密码")
btRegister.text = "注册"
}
etRegisterUserName.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
justContent()
}
})
etRegisterPassword.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if (etRegisterPassword.text.toString().isNotEmpty()) {
ivRegisterPasswordShow.visibility = View.VISIBLE
ivRegisterClearPassword.visibility = View.VISIBLE
} else {
ivRegisterPasswordShow.visibility = View.INVISIBLE
ivRegisterClearPassword.visibility = View.INVISIBLE
}
justContent()
}
})
etRegisterConfirmPassword.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if (etRegisterConfirmPassword.text.toString().isNotEmpty()) {
ivConfirmPasswordShow.visibility = View.VISIBLE
ivConfirmClearPassword.visibility = View.VISIBLE
} else {
ivConfirmPasswordShow.visibility = View.INVISIBLE
ivConfirmClearPassword.visibility = View.INVISIBLE
}
justContent()
}
})
ivRegisterPasswordShow.setOnClickListener(this)
ivRegisterClearPassword.setOnClickListener(this)
ivConfirmPasswordShow.setOnClickListener(this)
ivConfirmClearPassword.setOnClickListener(this)
btRegister.setOnClickListener(this)
btRegister.background.alpha = 100
btRegister.isEnabled = false
}
private fun justContent() {
if (TextUtils.isEmpty(etRegisterUserName.text.toString().trim())
|| TextUtils.isEmpty(etRegisterPassword.text.toString().trim())
|| TextUtils.isEmpty(etRegisterConfirmPassword.text.toString().trim())
) {
btRegister.background.alpha = 100
btRegister.isEnabled = false
} else {
btRegister.background.alpha = 255
btRegister.isEnabled = true
}
}
override fun initData() {
}
override fun postLoginShow(data: BaseResponse<LoginBean>) {
if (data.errorCode == "0") {
with(SharedPreferencesUtils(App.getContext())){
put(Const.IS_LOGIN,true)
put(Const.NICKNAME,data.data.nickname)
put(Const.ICON,data.data.icon)
put(Const.USER_ID,data.data.id)
}
startActivity(Intent(LoginActivity@this,MainActivity::class.java))
var logoutUpdateBean = LogoutUpdateBean()
logoutUpdateBean.isUpdate = true
RxNotify.instance?.post(logoutUpdateBean)
finish()
}else{
ToastUtils.showToast(LoginActivity@this,data.errorMsg)
}
}
override fun postRegisterShow(data: BaseResponse<RegisterBean>) {
if (data.errorCode == "0") {
DialogUtils.dismissProgressMD()
mPresenter?.postLogin(etRegisterUserName.text.toString(), etRegisterConfirmPassword.text.toString())
} else {
DialogUtils.dismissProgressMD()
ToastUtils.showToast(LoginActivity@ this, data.errorMsg)
}
}
override fun onError(data: ResponseException) {
ToastUtils.showToast(ArticleSearchActivity@ this, data.getErrorMessage())
DialogUtils.dismissProgressMD()
}
override fun onClick(v: View?) {
when (v?.id) {
R.id.btRegister -> {
if (isReset) {
}else{
if (etRegisterPassword.text.toString() != etRegisterConfirmPassword.text.toString()) {
ToastUtils.showToast(RegisterActivity@ this, "两次密码不一样,请重新输入")
} else {
DialogUtils.showProgress(RegisterActivity@ this, "账号申请中...")
mPresenter?.postRegister(
etRegisterUserName.text.toString().trim(),
etRegisterPassword.text.toString().trim(),
etRegisterConfirmPassword.text.toString().trim()
)
}
}
}
R.id.ivRegisterPasswordShow -> {
if (flag) {
etRegisterPassword.transformationMethod =
PasswordTransformationMethod.getInstance()
ivRegisterPasswordShow.setImageResource(R.drawable.icon_pwd_hide)
etRegisterPassword.setSelection(etRegisterPassword.text.length)
flag = false
} else {
etRegisterPassword.transformationMethod =
HideReturnsTransformationMethod.getInstance()
ivRegisterPasswordShow.setImageResource(R.drawable.icon_pwd_show)
etRegisterPassword.setSelection(etRegisterPassword.text.length)
flag = true
}
}
R.id.ivConfirmPasswordShow -> {
if (confrimFlag) {
etRegisterConfirmPassword.transformationMethod =
PasswordTransformationMethod.getInstance()
ivConfirmPasswordShow.setImageResource(R.drawable.icon_pwd_hide)
etRegisterConfirmPassword.setSelection(etRegisterConfirmPassword.text.length)
confrimFlag = false
} else {
etRegisterConfirmPassword.transformationMethod =
HideReturnsTransformationMethod.getInstance()
ivConfirmPasswordShow.setImageResource(R.drawable.icon_pwd_show)
etRegisterConfirmPassword.setSelection(etRegisterConfirmPassword.text.length)
confrimFlag = true
}
}
R.id.ivRegisterClearPassword -> {
etRegisterPassword.text = Editable.Factory.getInstance().newEditable("")
}
R.id.ivConfirmClearPassword -> {
etRegisterConfirmPassword.text = Editable.Factory.getInstance().newEditable("")
}
}
}
} | 0 | null | 0 | 0 | fa9fa190c88f441b50a08500ed98e74fe3568201 | 9,544 | WanAndroidClient | Apache License 2.0 |
Common/src/main/java/at/petrak/hexcasting/api/spell/Widget.kt | ChloeDawn | 521,802,890 | true | {"Java Properties": 1, "Groovy": 1, "Text": 3, "Gradle": 5, "Shell": 1, "Markdown": 2, "Git Attributes": 1, "Batchfile": 1, "Ignore List": 1, "INI": 4, "Kotlin": 177, "Java": 263, "JSON": 1009, "GLSL": 1, "YAML": 1, "HTML": 1, "Python": 1, "TOML": 1} | package at.petrak.hexcasting.api.spell
import at.petrak.hexcasting.api.spell.casting.CastingContext
import java.util.*
/**
* Miscellaneous spell datums used as markers, etc.
*
* They act as operators that push themselves.
*/
enum class Widget : ConstManaOperator {
NULL,
OPEN_PAREN, CLOSE_PAREN, ESCAPE,
GARBAGE;
override val argc: Int
get() = 0
override fun execute(args: List<SpellDatum<*>>, ctx: CastingContext): List<SpellDatum<*>> =
this.asSpellResult
companion object {
@JvmStatic
fun fromString(key: String): Widget {
val lowercaseKey = key.lowercase(Locale.ROOT)
return values().firstOrNull { it.name.lowercase(Locale.ROOT) == lowercaseKey } ?: GARBAGE
}
}
}
| 0 | null | 0 | 0 | b34d676afb7b68dfb35833b3d9218671587baefd | 768 | HexMod | MIT License |
leetcode/p0074/20220331/Solution.kt | suhwanhwang | 199,259,343 | false | {"Text": 138, "Ignore List": 2, "Markdown": 1, "Makefile": 2, "Java": 638, "C++": 118, "YAML": 15, "JSON": 311, "Shell": 56, "Gradle": 12, "Python": 6, "Jupyter Notebook": 10, "XML": 4, "Kotlin": 232, "Swift": 67, "INI": 1} | class Solution {
fun searchMatrix(matrix: Array<IntArray>, target: Int): Boolean {
val col = matrix[0].size
var left = 0
var right = matrix.size * col - 1
while (left <= right) {
val mid = (left + right) ushr 1
val num = matrix[mid / col][mid % col]
if (num == target) {
return true
} else if (num < target) {
left = mid + 1
} else {
right = mid - 1
}
}
return false
}
}
| 0 | Java | 0 | 0 | 0cc37fd7b9350a2a9f01f4828e3f4a22cf2121e5 | 547 | problem-solving | MIT License |
app/src/main/java/com/hades/example/android/_process_and_thread/workmanager/SingleWorker4Kotlin.kt | YingVickyCao | 212,703,639 | false | {"Gradle": 22, "Java Properties": 2, "Shell": 1, "Text": 2, "Ignore List": 13, "Batchfile": 1, "Markdown": 3, "Proguard": 14, "Java": 644, "XML": 883, "TOML": 1, "JSON": 6, "Kotlin": 22, "JavaScript": 6, "HTML": 5, "INI": 1, "SVG": 1} | package com.hades.example.android._process_and_thread.workmanager
import android.content.Context
import android.util.Log
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
//class SingleWorker4Kotlin(appContext: Context, params: WorkerParameters) : CoroutineWorker(appContext, params) {
class SingleWorker4Kotlin : CoroutineWorker {
private val TAG = "SingleWorker4Kotlin"
// 重写构造函数
constructor(appContext: Context, params: WorkerParameters) : super(appContext, params) {
Log.d(TAG, "constructor: thread id:" + Thread.currentThread().id + ",thread name:" + Thread.currentThread().name)
// constructor: thread id:1048,thread name:pool-3-thread-3
// Log.d(TAG, "constructor: context:" + appContext) // Context is app context
}
/*
override suspend fun doWork(): Result {
// doWork:id:5d485be9-c592-472d-8790-75f3fe9df645,tags:[com.hades.example.android._process_and_thread.workmanager.SingleWorker4Kotlin],hashCode:68951799
// addTag
// doWork:id:8e2d9570-7871-44a8-aaa9-3adf78a7384a,tags:[com.hades.example.android._process_and_thread.workmanager.SingleWorker4Kotlin, SingleWorker4Kotlin],hashCode:68951799
Log.d(TAG, "doWork:id:" + id + ",tags:" + tags.toString() + ",hashCode:" + hashCode())
// TODO: doWork: thread id:1024,thread name:DefaultDispatcher-worker-1
// TODO:default runs on Dispatchers.Default
Log.d(TAG, "doWork: thread id:" + Thread.currentThread().id + ",thread name:" + Thread.currentThread().name)
return Result.success()
}
*/
// TODO: 2021/12/3
override suspend fun doWork(): Result {
return withContext(Dispatchers.IO) {
// TODO: doWork: thread id:1024,thread name:DefaultDispatcher-worker-1
// TODO:default runs on Dispatchers.Default
Log.d(TAG, "doWork: thread id:" + Thread.currentThread().id + ",thread name:" + Thread.currentThread().name)
return@withContext Result.success()
}
}
} | 0 | Java | 0 | 0 | 45921c01bcebdc7e6246a88fc9ff0ad2413b44d0 | 2,107 | android-about-demos | Apache License 2.0 |
module-main/src/main/java/com/pp/module_main/SplashViewModel.kt | PPQingZhao | 548,315,946 | false | {"Kotlin": 553508, "Java": 1135} | package com.pp.module_main
import android.app.Application
import com.pp.library_base.base.ThemeViewModel
class SplashViewModel(app:Application): ThemeViewModel(app) {
} | 0 | Kotlin | 0 | 5 | 904d9a980811d502f88479cb450c3a6e8d027f09 | 170 | Eyepetizer | Apache License 2.0 |
app/src/main/kotlin/com/codementor/dmmfwk/ordertaking/CommonSimpleTypes.kt | goerge | 367,695,134 | false | null | package com.codementor.dmmfwk.ordertaking
import arrow.core.*
import java.math.BigDecimal
@JvmInline
value class String50 private constructor(val value: String) {
companion object {
fun create(value: String?): Validated<String, String50> =
when {
value == null -> String50("").valid()
value.length <= 50 -> String50(value).valid()
else -> "String50 must not be more than 50 chars".invalid()
}
fun createOption(value: String?): Validated<String, Option<String50>> =
if (value == null) none<String50>().valid()
else create(value).map(String50::some)
}
}
@JvmInline
value class EmailAddress private constructor(val value: String) {
companion object {
fun create(value: String?): Validated<String, EmailAddress> =
EmailAddress(value ?: "").valid()
}
}
@JvmInline
value class ZipCode private constructor(val value: String) {
companion object {
fun create(value: String): Validated<String, ZipCode> =
ZipCode(value).valid()
}
}
@JvmInline
value class OrderId private constructor(val value: String) {
companion object {
fun create(value: String?): Validated<String, OrderId> =
if (value == null) "OrderId is invalid".invalid()
else OrderId(value).valid()
}
}
@JvmInline
value class OrderLineId private constructor(val value: String) {
companion object {
fun create(value: String): Validated<String, OrderLineId> =
OrderLineId(value).valid()
}
}
@JvmInline
value class WidgetCode private constructor(val value: String) {
companion object {
private val widgetCodePattern = Regex("W[0-9]{4}")
fun create(value: String): Validated<String, WidgetCode> =
if (value.matches(widgetCodePattern)) WidgetCode(value).valid()
else "Widget code must follow format [Wxxxx], where each x is a digit (0-9)".invalid()
}
}
@JvmInline
value class GizmoCode private constructor(val value: String) {
companion object {
private val gizmoCodePattern = Regex("G[0-9]{3}")
fun create(value: String): Validated<String, GizmoCode> =
if (value.matches(gizmoCodePattern)) GizmoCode(value).valid()
else "Gizmo code must follow format [Gxxx], where each x is a digit (0-9)".invalid()
}
}
sealed class ProductCode {
companion object {
fun create(value: String): Validated<String, ProductCode> =
when {
value.startsWith("W") -> value
.let(WidgetCode::create)
.map(::Widget)
value.startsWith("G") -> value
.let(GizmoCode::create)
.map(::Gizmo)
else -> "Product code must start with either W for Widget code or G for Gizmo code".invalid()
}
}
data class Widget(val widgetCode: WidgetCode) : ProductCode() {
override fun toString(): String = widgetCode.value
}
data class Gizmo(val gizmoCode: GizmoCode) : ProductCode() {
override fun toString(): String = gizmoCode.value
}
}
@JvmInline
value class UnitQuantity private constructor(val value: Int) {
companion object {
fun create(value: Int): Validated<String, UnitQuantity> =
UnitQuantity(value).valid()
}
}
@JvmInline
value class KilogramQuantity private constructor(val value: BigDecimal) {
companion object {
fun create(value: BigDecimal): Validated<String, KilogramQuantity> =
KilogramQuantity(value).valid()
}
}
sealed class OrderQuantity {
companion object {
fun create(productCode: ProductCode, quantity: BigDecimal): Validated<String, OrderQuantity> =
when (productCode) {
is ProductCode.Widget -> UnitQuantity.create(quantity.toInt()).map { OrderQuantity.Unit(it) }
is ProductCode.Gizmo -> KilogramQuantity.create(quantity).map { OrderQuantity.Kilogram(it) }
}
}
data class Unit(val unitQuantity: UnitQuantity) : OrderQuantity()
data class Kilogram(val kilogramQuantity: KilogramQuantity) : OrderQuantity()
}
@JvmInline
value class Price private constructor(val value: BigDecimal) {
companion object {
fun create(value: BigDecimal): Validated<String, Price> =
Price(value).valid()
}
}
@JvmInline
value class BillingAmount private constructor(val value: BigDecimal) {
companion object {
fun create(value: BigDecimal): Validated<String, BillingAmount> =
BillingAmount(value).valid()
}
}
| 0 | Kotlin | 0 | 0 | d4ed3b4db8f7149b2c51f4c8257b5af8b5568cf2 | 4,656 | DomainModelingMadeFunctionalWithKotlin | Apache License 2.0 |
library/process/src/linuxMain/kotlin/io/matthewnelson/kmp/process/internal/stdio/LinuxStdioDescriptor.kt | 05nelsonm | 750,560,085 | false | {"Kotlin": 257886} | /*
* Copyright (c) 2024 Matthew Nelson
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
@file:Suppress("KotlinRedundantDiagnosticSuppress")
package io.matthewnelson.kmp.process.internal.stdio
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.IntVar
import kotlinx.cinterop.convert
import platform.linux.SYS_pipe2
import platform.posix.syscall
@Suppress("NOTHING_TO_INLINE")
@OptIn(ExperimentalForeignApi::class)
internal actual inline fun CPointer<IntVar>.pipe2(
flags: Int
): Int = syscall(SYS_pipe2.convert(), this, flags).convert()
| 2 | Kotlin | 0 | 3 | 6f1ef71d435f9ea1d34517f1d9506dcfe7aa27c8 | 1,112 | kmp-process | Apache License 2.0 |
src/main/kotlin/org/openweather/cached/service/model/response/Rain.kt | ZsoltBerki | 357,253,147 | false | null | package org.openweather.cached.service.model.response
import com.google.gson.annotations.SerializedName
import org.openweather.cached.service.model.interfaces.PrecipitationLastHour
data class Rain(
@SerializedName("1h")
override val lastHour: Float?
) : PrecipitationLastHour
| 0 | Kotlin | 0 | 0 | 2a0c19117816d4aeba9ef94b3bbc57f5b4ed4288 | 286 | OpenWeatherKotlin | Apache License 2.0 |
app/src/main/java/net/pertence/appauthdemo/AuthStateManager.kt | Pertence | 339,101,753 | false | null | package net.pertence.appauthdemo
import android.content.Context
import android.content.SharedPreferences
import android.util.Log
import androidx.annotation.AnyThread
import net.openid.appauth.*
import org.json.JSONException
import java.lang.ref.WeakReference
import java.util.concurrent.atomic.AtomicReference
import java.util.concurrent.locks.ReentrantLock
/**
* An example persistence mechanism for an [AuthState] instance.
* This stores the instance in a shared preferences file, and provides thread-safe access and
* mutation.
*/
class AuthStateManager private constructor(context: Context) {
private val preferences: SharedPreferences = context.getSharedPreferences(STORE_NAME, Context.MODE_PRIVATE)
private val preferencesLock: ReentrantLock = ReentrantLock()
private val currentAuthState: AtomicReference<AuthState> = AtomicReference()
@get:AnyThread
val current: AuthState
get() {
if (currentAuthState.get() != null) {
return currentAuthState.get()
}
val state = readState()
return if (currentAuthState.compareAndSet(null, state)) {
state
} else {
currentAuthState.get()
}
}
@AnyThread
fun replace(state: AuthState): AuthState {
writeState(state)
currentAuthState.set(state)
return state
}
@AnyThread
fun updateAfterAuthorization(
response: AuthorizationResponse?,
ex: AuthorizationException?): AuthState {
val current = current
current.update(response, ex)
return replace(current)
}
@AnyThread
fun updateAfterTokenResponse(
response: TokenResponse?,
ex: AuthorizationException?): AuthState {
val current = current
current.update(response, ex)
return replace(current)
}
@AnyThread
fun updateAfterRegistration(
response: RegistrationResponse?,
ex: AuthorizationException?): AuthState {
val current = current
if (ex != null) {
return current
}
current.update(response)
return replace(current)
}
@AnyThread
private fun readState(): AuthState {
preferencesLock.lock()
return try {
val currentState = preferences.getString(KEY_STATE, null)
?: return AuthState()
try {
AuthState.jsonDeserialize(currentState)
} catch (ex: JSONException) {
Log.w(TAG, "Failed to deserialize stored auth state - discarding")
AuthState()
}
} finally {
preferencesLock.unlock()
}
}
@AnyThread
private fun writeState(state: AuthState?) {
preferencesLock.lock()
try {
val editor = preferences.edit()
if (state == null) {
editor.remove(KEY_STATE)
} else {
editor.putString(KEY_STATE, state.jsonSerializeString())
}
check(editor.commit()) { "Failed to write state to shared prefs" }
} finally {
preferencesLock.unlock()
}
}
companion object {
private val INSTANCE_REF = AtomicReference(WeakReference<AuthStateManager?>(null))
private const val TAG = "AuthStateManager"
private const val STORE_NAME = "AuthState"
private const val KEY_STATE = "state"
@AnyThread
fun getInstance(context: Context): AuthStateManager {
var manager = INSTANCE_REF.get().get()
if (manager == null) {
manager = AuthStateManager(context.applicationContext)
INSTANCE_REF.set(WeakReference(manager))
}
return manager
}
}
}
| 0 | Kotlin | 0 | 1 | ab5f65ae952c1fc4bb69ca1bd18215fff5652e61 | 3,825 | AppAuthDemo | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.