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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
lib/src/test/kotlin/com/lemonappdev/konsist/api/ext/list/KoAnnotationProviderListExtTest.kt
|
LemonAppDev
| 621,181,534 | false |
{"Kotlin": 5054558, "Python": 46133}
|
package com.lemonappdev.konsist.api.ext.list
import com.lemonappdev.konsist.api.declaration.KoAnnotationDeclaration
import com.lemonappdev.konsist.api.provider.KoAnnotationProvider
import com.lemonappdev.konsist.testdata.SampleAnnotation1
import com.lemonappdev.konsist.testdata.SampleAnnotation2
import io.mockk.every
import io.mockk.mockk
import org.amshove.kluent.shouldBeEqualTo
import org.junit.jupiter.api.Test
@Suppress("detekt.LargeClass")
class KoAnnotationProviderListExtTest {
@Test
fun `annotations returns annotations from all declarations`() {
// given
val annotation1: KoAnnotationDeclaration = mockk()
val annotation2: KoAnnotationDeclaration = mockk()
val annotation3: KoAnnotationDeclaration = mockk()
val declaration1: KoAnnotationProvider =
mockk {
every { annotations } returns listOf(annotation1, annotation2)
}
val declaration2: KoAnnotationProvider =
mockk {
every { annotations } returns listOf(annotation3)
}
val declaration3: KoAnnotationProvider =
mockk {
every { annotations } returns emptyList()
}
val declarations = listOf(declaration1, declaration2, declaration3)
// when
val sut = declarations.annotations
// then
sut shouldBeEqualTo listOf(annotation1, annotation2, annotation3)
}
@Test
fun `withAnnotations() returns declaration with any annotation`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withAnnotations()
// then
sut shouldBeEqualTo listOf(declaration1)
}
@Test
fun `withAnnotationNamed(empty list) returns declaration with any annotation`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withAnnotationNamed(emptyList())
// then
sut shouldBeEqualTo listOf(declaration1)
}
@Test
fun `withAnnotationNamed(empty set) returns declaration with any annotation`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withAnnotationNamed(emptySet())
// then
sut shouldBeEqualTo listOf(declaration1)
}
@Test
fun `withAllAnnotationsNamed(empty list) returns declaration with any annotation`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withAllAnnotationsNamed(emptyList())
// then
sut shouldBeEqualTo listOf(declaration1)
}
@Test
fun `withAllAnnotationsNamed(empty set) returns declaration with any annotation`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withAllAnnotationsNamed(emptySet())
// then
sut shouldBeEqualTo listOf(declaration1)
}
@Test
fun `withoutAnnotations() returns declaration without any annotation`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withoutAnnotations()
// then
sut shouldBeEqualTo listOf(declaration2)
}
@Test
fun `withoutAnnotationNamed(empty list) returns declaration without any annotation`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withoutAnnotationNamed(emptyList())
// then
sut shouldBeEqualTo listOf(declaration2)
}
@Test
fun `withoutAnnotationNamed(empty set) returns declaration without any annotation`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withoutAnnotationNamed(emptySet())
// then
sut shouldBeEqualTo listOf(declaration2)
}
@Test
fun `withoutAllAnnotationsNamed(empty list) returns declaration without any annotation`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withoutAllAnnotationsNamed(emptyList())
// then
sut shouldBeEqualTo listOf(declaration2)
}
@Test
fun `withoutAllAnnotationsNamed(empty set) returns declaration without any annotation`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withoutAllAnnotationsNamed(emptySet())
// then
sut shouldBeEqualTo listOf(declaration2)
}
@Test
fun `withAnnotationNamed(name) returns declaration with given annotation`() {
// given
val name = "SampleName"
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotationWithName(listOf(name)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotationWithName(listOf(name)) } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withAnnotationNamed(name)
// then
sut shouldBeEqualTo listOf(declaration1)
}
@Test
fun `withAnnotationNamed(String) returns declaration with any of given annotations`() {
// given
val name1 = "SampleName1"
val name2 = "SampleName2"
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotationWithName(listOf(name1, name2)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotationWithName(listOf(name1, name2)) } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withAnnotationNamed(name1, name2)
// then
sut shouldBeEqualTo listOf(declaration1)
}
@Test
fun `withAnnotationNamed(list of String) returns declaration with any of given annotations`() {
// given
val name1 = "SampleName1"
val name2 = "SampleName2"
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotationWithName(listOf(name1, name2)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotationWithName(listOf(name1, name2)) } returns false
}
val declarations = listOf(declaration1, declaration2)
val names = listOf(name1, name2)
// when
val sut = declarations.withAnnotationNamed(names)
// then
sut shouldBeEqualTo listOf(declaration1)
}
@Test
fun `withAnnotationNamed(set of String) returns declaration with any of given annotations`() {
// given
val name1 = "SampleName1"
val name2 = "SampleName2"
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotationWithName(setOf(name1, name2)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotationWithName(setOf(name1, name2)) } returns false
}
val declarations = listOf(declaration1, declaration2)
val names = setOf(name1, name2)
// when
val sut = declarations.withAnnotationNamed(names)
// then
sut shouldBeEqualTo listOf(declaration1)
}
@Test
fun `withoutAnnotationNamed(name) returns declaration without given annotation`() {
// given
val name = "SampleName"
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotationWithName(listOf(name)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotationWithName(listOf(name)) } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withoutAnnotationNamed(name)
// then
sut shouldBeEqualTo listOf(declaration2)
}
@Test
fun `withoutAnnotationNamed(String) returns declaration without any of given annotations`() {
// given
val name1 = "SampleName1"
val name2 = "SampleName2"
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotationWithName(listOf(name1, name2)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotationWithName(listOf(name1, name2)) } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withoutAnnotationNamed(name1, name2)
// then
sut shouldBeEqualTo listOf(declaration2)
}
@Test
fun `withoutAnnotationNamed(list of String) returns declaration without any of given annotations`() {
// given
val name1 = "SampleName1"
val name2 = "SampleName2"
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotationWithName(listOf(name1, name2)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotationWithName(listOf(name1, name2)) } returns false
}
val declarations = listOf(declaration1, declaration2)
val names = listOf(name1, name2)
// when
val sut = declarations.withoutAnnotationNamed(names)
// then
sut shouldBeEqualTo listOf(declaration2)
}
@Test
fun `withoutAnnotationNamed(set of String) returns declaration without any of given annotations`() {
// given
val name1 = "SampleName1"
val name2 = "SampleName2"
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotationWithName(setOf(name1, name2)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotationWithName(setOf(name1, name2)) } returns false
}
val declarations = listOf(declaration1, declaration2)
val names = setOf(name1, name2)
// when
val sut = declarations.withoutAnnotationNamed(names)
// then
sut shouldBeEqualTo listOf(declaration2)
}
@Test
fun `withAllAnnotationsNamed(name) returns declaration with given annotation`() {
// given
val name = "SampleName"
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotationsWithAllNames(listOf(name)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotationsWithAllNames(listOf(name)) } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withAllAnnotationsNamed(name)
// then
sut shouldBeEqualTo listOf(declaration1)
}
@Test
fun `withAllAnnotationsNamed(String) returns declaration with all given annotations`() {
// given
val name1 = "SampleName1"
val name2 = "SampleName2"
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotationsWithAllNames(listOf(name1, name2)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotationsWithAllNames(listOf(name1, name2)) } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withAllAnnotationsNamed(name1, name2)
// then
sut shouldBeEqualTo listOf(declaration1)
}
@Test
fun `withAllAnnotationsNamed(list of String) returns declaration with all given annotations`() {
// given
val name1 = "SampleName1"
val name2 = "SampleName2"
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotationsWithAllNames(listOf(name1, name2)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotationsWithAllNames(listOf(name1, name2)) } returns false
}
val declarations = listOf(declaration1, declaration2)
val names = listOf(name1, name2)
// when
val sut = declarations.withAllAnnotationsNamed(names)
// then
sut shouldBeEqualTo listOf(declaration1)
}
@Test
fun `withAllAnnotationsNamed(set of String) returns declaration with all given annotations`() {
// given
val name1 = "SampleName1"
val name2 = "SampleName2"
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotationsWithAllNames(setOf(name1, name2)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotationsWithAllNames(setOf(name1, name2)) } returns false
}
val declarations = listOf(declaration1, declaration2)
val names = setOf(name1, name2)
// when
val sut = declarations.withAllAnnotationsNamed(names)
// then
sut shouldBeEqualTo listOf(declaration1)
}
@Test
fun `withoutAllAnnotationsNamed(name) returns declaration without given annotation`() {
// given
val name = "SampleName"
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotationsWithAllNames(listOf(name)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotationsWithAllNames(listOf(name)) } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withoutAllAnnotationsNamed(name)
// then
sut shouldBeEqualTo listOf(declaration2)
}
@Test
fun `withoutAllAnnotationsNamed(String) returns declaration without all of given annotations`() {
// given
val name1 = "SampleName1"
val name2 = "SampleName2"
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotationsWithAllNames(listOf(name1, name2)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotationsWithAllNames(listOf(name1, name2)) } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withoutAllAnnotationsNamed(name1, name2)
// then
sut shouldBeEqualTo listOf(declaration2)
}
@Test
fun `withoutAllAnnotationsNamed(list of String) returns declaration without all of given annotations`() {
// given
val name1 = "SampleName1"
val name2 = "SampleName2"
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotationsWithAllNames(listOf(name1, name2)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotationsWithAllNames(listOf(name1, name2)) } returns false
}
val declarations = listOf(declaration1, declaration2)
val names = listOf(name1, name2)
// when
val sut = declarations.withoutAllAnnotationsNamed(names)
// then
sut shouldBeEqualTo listOf(declaration2)
}
@Test
fun `withoutAllAnnotationsNamed(set of String) returns declaration without all of given annotations`() {
// given
val name1 = "SampleName1"
val name2 = "SampleName2"
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotationsWithAllNames(setOf(name1, name2)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotationsWithAllNames(setOf(name1, name2)) } returns false
}
val declarations = listOf(declaration1, declaration2)
val names = setOf(name1, name2)
// when
val sut = declarations.withoutAllAnnotationsNamed(names)
// then
sut shouldBeEqualTo listOf(declaration2)
}
@Test
fun `withAnnotation{} returns declaration with annotation which satisfy predicate`() {
// given
val suffix = "Name"
val predicate: (KoAnnotationDeclaration) -> Boolean = { it.hasNameEndingWith(suffix) }
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotation(predicate) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotation(predicate) } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withAnnotation(predicate)
// then
sut shouldBeEqualTo listOf(declaration1)
}
@Test
fun `withoutAnnotation{} returns declaration without annotation which satisfy predicate`() {
// given
val suffix = "Name"
val predicate: (KoAnnotationDeclaration) -> Boolean = { it.hasNameEndingWith(suffix) }
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotation(predicate) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotation(predicate) } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withoutAnnotation(predicate)
// then
sut shouldBeEqualTo listOf(declaration2)
}
@Test
fun `withAllAnnotations{} returns declaration with all annotations satisfy predicate`() {
// given
val suffix = "Name"
val predicate: (KoAnnotationDeclaration) -> Boolean = { it.hasNameEndingWith(suffix) }
val declaration1: KoAnnotationProvider =
mockk {
every { hasAllAnnotations(predicate) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAllAnnotations(predicate) } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withAllAnnotations(predicate)
// then
sut shouldBeEqualTo listOf(declaration1)
}
@Test
fun `withoutAllAnnotations{} returns declaration with all annotations which not satisfy predicate`() {
// given
val suffix = "Name"
val predicate: (KoAnnotationDeclaration) -> Boolean = { it.hasNameEndingWith(suffix) }
val declaration1: KoAnnotationProvider =
mockk {
every { hasAllAnnotations(predicate) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAllAnnotations(predicate) } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withoutAllAnnotations(predicate)
// then
sut shouldBeEqualTo listOf(declaration2)
}
@Test
fun `withAnnotations{} returns declaration with annotations which satisfy predicate`() {
// given
val suffix = "Name"
val predicate: (List<KoAnnotationDeclaration>) -> Boolean =
{ it.all { annotation -> annotation.hasNameEndingWith(suffix) } }
val annotation1: KoAnnotationDeclaration =
mockk {
every { hasNameEndingWith(suffix) } returns true
}
val annotation2: KoAnnotationDeclaration =
mockk {
every { hasNameEndingWith(suffix) } returns false
}
val declaration1: KoAnnotationProvider =
mockk {
every { annotations } returns listOf(annotation1)
}
val declaration2: KoAnnotationProvider =
mockk {
every { annotations } returns listOf(annotation2)
}
val declaration3: KoAnnotationProvider =
mockk {
every { annotations } returns emptyList()
}
val declarations = listOf(declaration1, declaration2, declaration3)
// when
val sut = declarations.withAnnotations(predicate)
// then
sut shouldBeEqualTo listOf(declaration1, declaration3)
}
@Test
fun `withoutAnnotations{} returns declaration without annotations which satisfy predicate`() {
// given
val suffix = "Name"
val predicate: (List<KoAnnotationDeclaration>) -> Boolean =
{ it.all { annotation -> annotation.hasNameEndingWith(suffix) } }
val annotation1: KoAnnotationDeclaration =
mockk {
every { hasNameEndingWith(suffix) } returns true
}
val annotation2: KoAnnotationDeclaration =
mockk {
every { hasNameEndingWith(suffix) } returns false
}
val declaration1: KoAnnotationProvider =
mockk {
every { annotations } returns listOf(annotation1)
}
val declaration2: KoAnnotationProvider =
mockk {
every { annotations } returns listOf(annotation2)
}
val declaration3: KoAnnotationProvider =
mockk {
every { annotations } returns emptyList()
}
val declarations = listOf(declaration1, declaration2, declaration3)
// when
val sut = declarations.withoutAnnotations(predicate)
// then
sut shouldBeEqualTo listOf(declaration2)
}
@Test
fun `withAnnotationOf(empty list) returns declaration with any annotation`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withAnnotationOf(emptyList())
// then
sut shouldBeEqualTo listOf(declaration1)
}
@Test
fun `withAnnotationOf(empty set) returns declaration with any annotation`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withAnnotationOf(emptySet())
// then
sut shouldBeEqualTo listOf(declaration1)
}
@Test
fun `withAllAnnotationsOf(empty list) returns declaration with any annotation`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withAllAnnotationsOf(emptyList())
// then
sut shouldBeEqualTo listOf(declaration1)
}
@Test
fun `withAllAnnotationsOf(empty set) returns declaration with any annotation`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withAllAnnotationsOf(emptySet())
// then
sut shouldBeEqualTo listOf(declaration1)
}
@Test
fun `withoutAnnotationOf(empty list) returns declaration without any annotation`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withoutAnnotationOf(emptyList())
// then
sut shouldBeEqualTo listOf(declaration2)
}
@Test
fun `withoutAnnotationOf(empty set) returns declaration without any annotation`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withoutAnnotationOf(emptySet())
// then
sut shouldBeEqualTo listOf(declaration2)
}
@Test
fun `withoutAllAnnotationsOf(empty list) returns declaration without any annotation`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withoutAllAnnotationsOf(emptyList())
// then
sut shouldBeEqualTo listOf(declaration2)
}
@Test
fun `withoutAllAnnotationsOf(empty set) returns declaration without any annotation`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotations() } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withoutAllAnnotationsOf(emptySet())
// then
sut shouldBeEqualTo listOf(declaration2)
}
@Test
fun `withAnnotationOf(KClass) returns declaration with any of given annotations`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotationOf(listOf(SampleAnnotation1::class, SampleAnnotation2::class)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotationOf(listOf(SampleAnnotation1::class, SampleAnnotation2::class)) } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withAnnotationOf(SampleAnnotation1::class, SampleAnnotation2::class)
// then
sut shouldBeEqualTo listOf(declaration1)
}
@Test
fun `withAnnotationOf(list of KClass) returns declaration with any of given annotations`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotationOf(listOf(SampleAnnotation1::class, SampleAnnotation2::class)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotationOf(listOf(SampleAnnotation1::class, SampleAnnotation2::class)) } returns false
}
val declarations = listOf(declaration1, declaration2)
val kClasses = listOf(SampleAnnotation1::class, SampleAnnotation2::class)
// when
val sut = declarations.withAnnotationOf(kClasses)
// then
sut shouldBeEqualTo listOf(declaration1)
}
@Test
fun `withAnnotationOf(set of KClass) returns declaration with any of given annotations`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotationOf(setOf(SampleAnnotation1::class, SampleAnnotation2::class)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotationOf(setOf(SampleAnnotation1::class, SampleAnnotation2::class)) } returns false
}
val declarations = listOf(declaration1, declaration2)
val kClasses = setOf(SampleAnnotation1::class, SampleAnnotation2::class)
// when
val sut = declarations.withAnnotationOf(kClasses)
// then
sut shouldBeEqualTo listOf(declaration1)
}
@Test
fun `withoutAnnotationOf(KClass) returns declaration without all of given annotations`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotationOf(listOf(SampleAnnotation1::class, SampleAnnotation2::class)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotationOf(listOf(SampleAnnotation1::class, SampleAnnotation2::class)) } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withoutAnnotationOf(SampleAnnotation1::class, SampleAnnotation2::class)
// then
sut shouldBeEqualTo listOf(declaration2)
}
@Test
fun `withoutAnnotationOf(list of KClass) returns declaration without all of given annotations`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotationOf(listOf(SampleAnnotation1::class, SampleAnnotation2::class)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotationOf(listOf(SampleAnnotation1::class, SampleAnnotation2::class)) } returns false
}
val declarations = listOf(declaration1, declaration2)
val kClasses = listOf(SampleAnnotation1::class, SampleAnnotation2::class)
// when
val sut = declarations.withoutAnnotationOf(kClasses)
// then
sut shouldBeEqualTo listOf(declaration2)
}
@Test
fun `withoutAnnotationOf(set of KClass) returns declaration without all of given annotations`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAnnotationOf(setOf(SampleAnnotation1::class, SampleAnnotation2::class)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAnnotationOf(setOf(SampleAnnotation1::class, SampleAnnotation2::class)) } returns false
}
val declarations = listOf(declaration1, declaration2)
val kClasses = setOf(SampleAnnotation1::class, SampleAnnotation2::class)
// when
val sut = declarations.withoutAnnotationOf(kClasses)
// then
sut shouldBeEqualTo listOf(declaration2)
}
@Test
fun `withAllAnnotationsOf(KClass) returns declaration with all of given annotations`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAllAnnotationsOf(listOf(SampleAnnotation1::class, SampleAnnotation2::class)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAllAnnotationsOf(listOf(SampleAnnotation1::class, SampleAnnotation2::class)) } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withAllAnnotationsOf(SampleAnnotation1::class, SampleAnnotation2::class)
// then
sut shouldBeEqualTo listOf(declaration1)
}
@Test
fun `withAllAnnotationsOf(list of KClass) returns declaration with all of given annotations`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAllAnnotationsOf(listOf(SampleAnnotation1::class, SampleAnnotation2::class)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAllAnnotationsOf(listOf(SampleAnnotation1::class, SampleAnnotation2::class)) } returns false
}
val declarations = listOf(declaration1, declaration2)
val kClasses = listOf(SampleAnnotation1::class, SampleAnnotation2::class)
// when
val sut = declarations.withAllAnnotationsOf(kClasses)
// then
sut shouldBeEqualTo listOf(declaration1)
}
@Test
fun `withAllAnnotationsOf(set of KClass) returns declaration with all of given annotations`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAllAnnotationsOf(setOf(SampleAnnotation1::class, SampleAnnotation2::class)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAllAnnotationsOf(setOf(SampleAnnotation1::class, SampleAnnotation2::class)) } returns false
}
val declarations = listOf(declaration1, declaration2)
val kClasses = setOf(SampleAnnotation1::class, SampleAnnotation2::class)
// when
val sut = declarations.withAllAnnotationsOf(kClasses)
// then
sut shouldBeEqualTo listOf(declaration1)
}
@Test
fun `withoutAllAnnotationsOf(KClass) returns declaration without any of given annotations`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAllAnnotationsOf(listOf(SampleAnnotation1::class, SampleAnnotation2::class)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAllAnnotationsOf(listOf(SampleAnnotation1::class, SampleAnnotation2::class)) } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withoutAllAnnotationsOf(SampleAnnotation1::class, SampleAnnotation2::class)
// then
sut shouldBeEqualTo listOf(declaration2)
}
@Test
fun `withoutAllAnnotationsOf(list of KClass) returns declaration without any of given annotations`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAllAnnotationsOf(listOf(SampleAnnotation1::class, SampleAnnotation2::class)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAllAnnotationsOf(listOf(SampleAnnotation1::class, SampleAnnotation2::class)) } returns false
}
val declarations = listOf(declaration1, declaration2)
val kClasses = listOf(SampleAnnotation1::class, SampleAnnotation2::class)
// when
val sut = declarations.withoutAllAnnotationsOf(kClasses)
// then
sut shouldBeEqualTo listOf(declaration2)
}
@Test
fun `withoutAllAnnotationsOf(set of KClass) returns declaration without any of given annotations`() {
// given
val declaration1: KoAnnotationProvider =
mockk {
every { hasAllAnnotationsOf(setOf(SampleAnnotation1::class, SampleAnnotation2::class)) } returns true
}
val declaration2: KoAnnotationProvider =
mockk {
every { hasAllAnnotationsOf(setOf(SampleAnnotation1::class, SampleAnnotation2::class)) } returns false
}
val declarations = listOf(declaration1, declaration2)
val kClasses = setOf(SampleAnnotation1::class, SampleAnnotation2::class)
// when
val sut = declarations.withoutAllAnnotationsOf(kClasses)
// then
sut shouldBeEqualTo listOf(declaration2)
}
}
| 6 |
Kotlin
|
27
| 1,141 |
696b67799655e2154447ab45f748e983d8bcc1b5
| 39,727 |
konsist
|
Apache License 2.0
|
shared/src/commonMain/kotlin/com/lennartmoeller/ma/composemultiplatform/pages/CategoriesPage.kt
|
lennartmoeller
| 706,576,031 | false |
{"Kotlin": 58039, "Swift": 591, "Shell": 228}
|
package com.lennartmoeller.ma.composemultiplatform.pages
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.ListItem
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import com.lennartmoeller.ma.composemultiplatform.database.Database
import com.lennartmoeller.ma.composemultiplatform.entities.Category
import com.lennartmoeller.ma.composemultiplatform.ui.custom.CustomDivider
import com.lennartmoeller.ma.composemultiplatform.ui.custom.CustomIcon
import com.lennartmoeller.ma.composemultiplatform.ui.SkeletonState
import com.lennartmoeller.ma.composemultiplatform.util.NavigablePage
class CategoriesPage : NavigablePage() {
override val title: String = "Kategorien"
override val iconUnicode: String = "\uf86d"
@Composable
override fun build() {
val categories: List<Category> =
Database.getCategories().values.toList().sortedBy { it.label }
LazyColumn(contentPadding = PaddingValues(bottom = SkeletonState.PAGE_BOTTOM_PADDING)) {
items(count = categories.size) { index ->
val category: Category = categories[index]
ListItem(
headlineContent = { Text(category.label) },
leadingContent = { CustomIcon(name = category.icon) }
)
// divider between items
if (index < categories.size - 1) CustomDivider(1)
}
}
}
}
| 0 |
Kotlin
|
0
| 0 |
ae4d472c5fcf2ab9190f8ff1839d5b2603cd10dc
| 1,535 |
ma-compose-multiplatform
|
Apache License 2.0
|
app/src/main/java/com/lacolinares/jetpicexpress/data/about/AboutToolsAndTech.kt
|
la-colinares
| 393,771,090 | false | null |
package com.lacolinares.jetpicexpress.data.about
data class AboutToolsAndTech(
val title: String = "",
val url: String = ""
)
| 0 |
Kotlin
|
2
| 9 |
0851b18928dda2fb27375eb01b88b5afb593ad20
| 135 |
JetPicExpress
|
MIT License
|
android/example/src/main/java/com/jd/hybrid/example/PerformanceJsBridge.kt
|
JDFED
| 561,670,655 | false | null |
/*
* MIT License
*
* Copyright (c) 2022 JD.com, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.jd.hybrid.example
import android.webkit.JavascriptInterface
import org.json.JSONArray
import java.util.*
class PerformanceJsBridge(val perfData: Utils.PerformanceData) {
companion object {
const val NAME = "DemoJs"
const val JS_LISTEN_LCP = """
javascript:try{
const po = new PerformanceObserver((entryList) => {
const entries = entryList.getEntries();
const lastEntry = entries[entries.length - 1];
window.JDHybrid_lcp = lastEntry.renderTime || lastEntry.loadTime;
});
po.observe({type: 'largest-contentful-paint', buffered: true});
} catch (e) {}"""
const val JS_SEND_PERFORMANCE = """
javascript:try{
window.$NAME && $NAME.sendPerformance(
%s,
JSON.stringify(window.performance.timing),
JSON.stringify(window.performance.getEntriesByType('paint')),
window.JDHybrid_lcp ? window.JDHybrid_lcp : -1);
}catch (e) {}"""
}
@JavascriptInterface
fun sendPerformance(finish: String, timing: String, paint: String, lcp: Double){
var fp = ""
var fcp = ""
if (paint.isNotEmpty()) {
val resourceJson = JSONArray(paint)
for (i in 0 until resourceJson.length()) {
val entity = resourceJson.getJSONObject(i)
val startTime: String = entity.getDouble("startTime").to2f()
if ("first-paint" == entity.getString("name")) {
fp = startTime
} else if ("first-contentful-paint" == entity.getString("name")) {
fcp = startTime
}
}
}
perfData.apply {
pageFinish = finish
this.fp = fp
this.fcp = fcp
this.lcp = lcp.to2f()
}
}
private fun Double.to2f(): String{
if (this == 0.0) {
return "0"
}
return String.format(Locale.getDefault(), "%.2f", this)
}
}
| 0 |
HTML
|
9
| 89 |
81f3a37f1caf33f4196e140604aa91c4c92663a2
| 3,215 |
JDHybrid
|
MIT License
|
app/src/main/java/com/kagan/chatapp/di/RepositoryModule.kt
|
hnjm
| 335,143,213 | false |
{"Kotlin": 143707}
|
package com.kagan.chatapp.di
import com.kagan.chatapp.api.AuthenticationApi
import com.kagan.chatapp.api.ChatRoomsApi
import com.kagan.chatapp.api.MessageApi
import com.kagan.chatapp.api.UserApi
import com.kagan.chatapp.repositories.ChatRoomRepository
import com.kagan.chatapp.repositories.LoginRepository
import com.kagan.chatapp.repositories.MessageRepository
import com.kagan.chatapp.repositories.UserRepository
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class RepositoryModule {
@Singleton
@Provides
fun provideLoginRepository(authenticationApi: AuthenticationApi): LoginRepository =
LoginRepository(authenticationApi)
@Singleton
@Provides
fun provideUserRepository(userApi: UserApi): UserRepository = UserRepository(userApi)
@Singleton
@Provides
fun provideChatRoomsRepository(chatRoomsApi: ChatRoomsApi) = ChatRoomRepository(chatRoomsApi)
@Singleton
@Provides
fun provideMessageRepository(messageApi: MessageApi) = MessageRepository(messageApi)
}
| 0 |
Kotlin
|
0
| 1 |
0087c5a6d5daba19dd7a09c140891a79e0543edf
| 1,169 |
SimpleChat-Android
|
MIT License
|
app/src/main/java/ren/imyan/kirby/ui/resources/ResFragment.kt
|
KirbyAssistant
| 316,526,859 | false | null |
package ren.imyan.kirby.ui.resources
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import ren.imyan.base.BaseFragment
import ren.imyan.kirby.core.currActivity
import ren.imyan.kirby.data.model.ResItem
import ren.imyan.kirby.databinding.FragmentResBinding
import ren.imyan.kirby.databinding.ViewpagerResBinding
import ren.imyan.kirby.ui.cheatcode.CheatCodeActivity
import ren.imyan.kirby.ui.game.GameListActivity
import ren.imyan.kirby.ui.resources.pager.CheatCodeGameFragment
import ren.imyan.kirby.ui.resources.pager.ConsoleFragment
import ren.imyan.kirby.ui.resources.pager.EmulatorFragment
import ren.imyan.ktx.toast
/**
* @author EndureBlaze/炎忍 https://github.com.EndureBlaze
* @data 2021-01-24 16:37
* @website https://imyan.ren
*/
class ResFragment : BaseFragment<FragmentResBinding, ResViewModel>() {
override fun initViewModel(): ResViewModel = ViewModelProvider(this)[ResViewModel::class.java]
override fun initBinding(
inflater: LayoutInflater,
container: ViewGroup?
): FragmentResBinding = FragmentResBinding.inflate(inflater, container, false)
override fun initView() {
binding.tablayout.tabMode = TabLayout.MODE_FIXED
binding.viewpager.adapter = ResPagerAdapter(
this,
listOf(
ConsoleFragment(),
EmulatorFragment(),
CheatCodeGameFragment()
)
)
TabLayoutMediator(binding.tablayout, binding.viewpager) { tab, position ->
tab.text = viewModel.tabTitles[position]
}.attach()
}
override fun loadDate() {
}
}
| 0 |
Kotlin
|
0
| 2 |
d2bfb15d59373646ab360d09dd8a16d22c9ca571
| 1,896 |
Kirby_Assistant_New
|
MIT License
|
mediator/src/main/kotlin/no/nav/dagpenger/saksbehandling/skjerming/SkjermingHttpKlient.kt
|
navikt
| 571,475,339 | false |
{"Kotlin": 515186, "PLpgSQL": 7983, "Mustache": 4238, "HTML": 699, "Dockerfile": 77}
|
package no.nav.dagpenger.saksbehandling.skjerming
import io.ktor.client.HttpClient
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.engine.cio.CIO
import io.ktor.client.request.accept
import io.ktor.client.request.header
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.client.statement.bodyAsText
import io.ktor.http.ContentType
import io.ktor.http.HttpHeaders
import io.ktor.http.contentType
import io.prometheus.metrics.model.registry.PrometheusRegistry
import mu.KotlinLogging
private val logger = KotlinLogging.logger { }
internal class SkjermingHttpKlient(
private val skjermingApiUrl: String,
private val tokenProvider: () -> String,
private val httpClient: HttpClient = lagSkjermingHttpKlient(),
) : SkjermingKlient {
companion object {
fun lagSkjermingHttpKlient(
engine: HttpClientEngine = CIO.create {},
registry: PrometheusRegistry = PrometheusRegistry.defaultRegistry,
): HttpClient {
return createHttpClient(
engine = engine,
metricsBaseName = "dp_saksbehandling_skjerming_http_klient",
prometheusRegistry = registry,
)
}
}
override suspend fun erSkjermetPerson(ident: String): Result<Boolean> {
return kotlin.runCatching {
httpClient.post(urlString = skjermingApiUrl) {
header(HttpHeaders.Authorization, "Bearer ${tokenProvider.invoke()}")
contentType(ContentType.Application.Json)
accept(ContentType.Text.Plain)
setBody(SkjermingRequest(ident))
}.bodyAsText().toBoolean()
}.onFailure { throwable -> logger.error(throwable) { "Kall til skjerming feilet" } }
}
private data class SkjermingRequest(val personident: String)
}
| 3 |
Kotlin
|
0
| 0 |
b47bab2848ac53b5e688c13c87dd6223d4add10d
| 1,857 |
dp-saksbehandling
|
MIT License
|
app/src/main/java/cardosofgui/android/pokedexcompose/ui/SplashUiState.kt
|
CardosofGui
| 609,740,815 | false | null |
package cardosofgui.android.pokedexcompose.ui
import cardosofgui.android.core.components.utils.UIState
import cardosofgui.android.pokedexcompose.core.network.model.UserSettings
data class SplashUiState(
val isLoading: Boolean = false,
val user: UserSettings? = null,
val newUsername: String = "",
val hasUser: Boolean = false,
val navigation: SplashNavigation = SplashNavigation.SPLASH
): UIState
enum class SplashNavigation {
SPLASH, ONBOARDING, LOGIN, APP
}
| 0 |
Kotlin
|
0
| 1 |
67c081c7e0ba18bbb06dd736ffb41699defa3836
| 487 |
pokedex-app-compose
|
MIT License
|
playground/src/main/java/me/lincolnstuart/funblocks/playground/screens/components/form/input/TextAreaScreen.kt
|
LincolnStuart
| 645,064,211 | false | null |
package me.lincolnstuart.funblocks.playground.screens.components.form.input
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import cafe.adriel.voyager.core.screen.Screen
import me.lincolnstuart.funblocks.essentials.form.input.TextArea
import me.lincolnstuart.funblocks.essentials.form.switchbutton.SwitchButtonOption
import me.lincolnstuart.funblocks.playground.components.Sample
class TextAreaScreen : Screen {
@Composable
override fun Content() {
var error: String? by remember {
mutableStateOf(null)
}
var enabled by remember {
mutableStateOf(true)
}
var readOnly by remember {
mutableStateOf(false)
}
var inputValue by remember {
mutableStateOf("")
}
Sample(
component = {
TextArea(
value = inputValue,
onValueChange = { inputValue = it },
label = "Text area",
placeholder = "Enter your input",
enabled = enabled,
readOnly = readOnly,
error = error
)
}
) {
SwitchButtonOption(
description = "Enabled",
isOn = enabled,
onClick = { enabled = !enabled }
)
SwitchButtonOption(
description = "Read only",
isOn = readOnly,
onClick = { readOnly = !readOnly }
)
SwitchButtonOption(
description = "Error",
isOn = error != null,
onClick = { error = if (error == null) "some error" else null }
)
}
}
}
| 1 |
Kotlin
|
0
| 1 |
a70b1c58fe60b4d70580e33578f8c20091da167d
| 1,923 |
fun-blocks
|
MIT License
|
pickle/src/main/java/com/charlezz/pickle/fragments/detail/PickleDetailAdapter.kt
|
Charlezz
| 324,989,624 | false | null |
package com.charlezz.pickle.fragments.detail
import android.graphics.drawable.Drawable
import android.view.ViewGroup
import androidx.core.view.ViewCompat
import androidx.paging.PagingDataAdapter
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.signature.MediaStoreSignature
import com.charlezz.pickle.OnImageAppearedListener
import com.charlezz.pickle.R
import com.charlezz.pickle.Selection
import com.charlezz.pickle.data.MediaItemDiffCallback
import com.charlezz.pickle.data.entity.MediaItem
import com.charlezz.pickle.databinding.ViewPickleMediaDetailBinding
import com.charlezz.pickle.util.recyclerview.DataBindingHolder
import timber.log.Timber
import javax.inject.Inject
class PickleDetailAdapter @Inject constructor(
diffCallback: MediaItemDiffCallback
) : PagingDataAdapter<MediaItem, DataBindingHolder<ViewPickleMediaDetailBinding>>(diffCallback = diffCallback) {
var selection: Selection? = null
override fun getItemViewType(position: Int): Int {
return R.layout.view_pickle_media_detail
}
override fun onBindViewHolder(
holder: DataBindingHolder<ViewPickleMediaDetailBinding>,
position: Int
) {
val item = getItem(position)
item?.let { item ->
Timber.d("uri = ${item.getUri()}")
holder.binding.item = item
holder.binding.selection = selection
holder.binding.position = position
Glide.with(holder.binding.image)
.load(item.getUri())
.signature(MediaStoreSignature(item.media.mimeType, item.media.dateModified, item.media.orientation))
.listener(object:RequestListener<Drawable>{
override fun onLoadFailed(
e: GlideException?,
model: Any?,
target: Target<Drawable>?,
isFirstResource: Boolean
): Boolean {
onImageAppearedListener?.onImageAppeared(position)
return false
}
override fun onResourceReady(
resource: Drawable?,
model: Any?,
target: Target<Drawable>?,
dataSource: DataSource?,
isFirstResource: Boolean
): Boolean {
onImageAppearedListener?.onImageAppeared(position)
return false
}
})
.into(holder.binding.image)
ViewCompat.setTransitionName(holder.binding.image, item.getUri().toString())
holder.binding.executePendingBindings()
}
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): DataBindingHolder<ViewPickleMediaDetailBinding> {
return DataBindingHolder(parent, viewType)
}
var onImageAppearedListener:OnImageAppearedListener? = null
}
| 1 |
Kotlin
|
5
| 32 |
eca75d5496f591b5f7c6a164a936ed3fb4d3c23e
| 3,200 |
Pickle
|
Apache License 2.0
|
solar/src/main/java/com/chiksmedina/solar/outline/designtools/Layers.kt
|
CMFerrer
| 689,442,321 | false |
{"Kotlin": 36591890}
|
package com.chiksmedina.solar.outline.designtools
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 com.chiksmedina.solar.outline.DesignToolsGroup
val DesignToolsGroup.Layers: ImageVector
get() {
if (_layers != null) {
return _layers!!
}
_layers = Builder(
name = "Layers", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f
).apply {
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd
) {
moveTo(12.0f, 4.75f)
curveTo(10.9396f, 4.75f, 10.0907f, 5.078f, 8.0658f, 5.8879f)
lineTo(5.2574f, 7.0113f)
curveTo(4.2469f, 7.4155f, 3.5468f, 7.6966f, 3.093f, 7.9345f)
curveTo(3.0486f, 7.9578f, 3.0086f, 7.9796f, 2.9727f, 8.0f)
curveTo(3.0086f, 8.0204f, 3.0486f, 8.0422f, 3.093f, 8.0655f)
curveTo(3.5468f, 8.3034f, 4.2469f, 8.5845f, 5.2574f, 8.9887f)
lineTo(8.0658f, 10.1121f)
curveTo(10.0907f, 10.922f, 10.9396f, 11.25f, 12.0f, 11.25f)
curveTo(13.0604f, 11.25f, 13.9093f, 10.922f, 15.9342f, 10.1121f)
lineTo(18.7426f, 8.9887f)
curveTo(19.7531f, 8.5845f, 20.4532f, 8.3034f, 20.9071f, 8.0655f)
curveTo(20.9514f, 8.0422f, 20.9914f, 8.0204f, 21.0273f, 8.0f)
curveTo(20.9914f, 7.9796f, 20.9514f, 7.9578f, 20.9071f, 7.9345f)
curveTo(20.4532f, 7.6966f, 19.7531f, 7.4155f, 18.7426f, 7.0113f)
lineTo(15.9342f, 5.8879f)
curveTo(13.9093f, 5.078f, 13.0604f, 4.75f, 12.0f, 4.75f)
close()
moveTo(7.6244f, 4.4489f)
curveTo(9.5012f, 3.698f, 10.6208f, 3.25f, 12.0f, 3.25f)
curveTo(13.3792f, 3.25f, 14.4988f, 3.698f, 16.3756f, 4.4489f)
curveTo(16.4138f, 4.4642f, 16.4524f, 4.4796f, 16.4912f, 4.4952f)
lineTo(19.3451f, 5.6367f)
curveTo(20.2996f, 6.0185f, 21.0728f, 6.3278f, 21.6035f, 6.606f)
curveTo(21.8721f, 6.7468f, 22.1323f, 6.9065f, 22.333f, 7.0989f)
curveTo(22.5392f, 7.2967f, 22.75f, 7.5966f, 22.75f, 8.0f)
curveTo(22.75f, 8.4034f, 22.5392f, 8.7033f, 22.333f, 8.9011f)
curveTo(22.1323f, 9.0935f, 21.8721f, 9.2532f, 21.6035f, 9.394f)
curveTo(21.2519f, 9.5784f, 20.7938f, 9.7763f, 20.247f, 10.0f)
curveTo(20.7938f, 10.2237f, 21.2519f, 10.4216f, 21.6035f, 10.606f)
curveTo(21.8721f, 10.7468f, 22.1323f, 10.9065f, 22.333f, 11.0989f)
curveTo(22.5392f, 11.2967f, 22.75f, 11.5966f, 22.75f, 12.0f)
curveTo(22.75f, 12.4034f, 22.5392f, 12.7033f, 22.333f, 12.9011f)
curveTo(22.1323f, 13.0935f, 21.8721f, 13.2532f, 21.6035f, 13.394f)
curveTo(21.2519f, 13.5784f, 20.7938f, 13.7763f, 20.247f, 14.0f)
curveTo(20.7938f, 14.2237f, 21.2519f, 14.4216f, 21.6035f, 14.606f)
curveTo(21.8721f, 14.7468f, 22.1323f, 14.9065f, 22.333f, 15.0989f)
curveTo(22.5392f, 15.2967f, 22.75f, 15.5966f, 22.75f, 16.0f)
curveTo(22.75f, 16.4034f, 22.5392f, 16.7033f, 22.333f, 16.9011f)
curveTo(22.1323f, 17.0935f, 21.8721f, 17.2532f, 21.6035f, 17.394f)
curveTo(21.0728f, 17.6722f, 20.2997f, 17.9815f, 19.3451f, 18.3633f)
lineTo(16.4912f, 19.5048f)
curveTo(16.4524f, 19.5204f, 16.4138f, 19.5358f, 16.3756f, 19.5511f)
curveTo(14.4988f, 20.302f, 13.3792f, 20.75f, 12.0f, 20.75f)
curveTo(10.6208f, 20.75f, 9.5012f, 20.302f, 7.6244f, 19.5511f)
curveTo(7.5862f, 19.5358f, 7.5476f, 19.5204f, 7.5087f, 19.5048f)
lineTo(4.6549f, 18.3633f)
curveTo(3.7003f, 17.9815f, 2.9272f, 17.6722f, 2.3965f, 17.394f)
curveTo(2.1279f, 17.2532f, 1.8677f, 17.0935f, 1.667f, 16.9011f)
curveTo(1.4609f, 16.7033f, 1.25f, 16.4034f, 1.25f, 16.0f)
curveTo(1.25f, 15.5966f, 1.4609f, 15.2967f, 1.667f, 15.0989f)
curveTo(1.8677f, 14.9065f, 2.1279f, 14.7468f, 2.3965f, 14.606f)
curveTo(2.7481f, 14.4216f, 3.2062f, 14.2237f, 3.753f, 14.0f)
curveTo(3.2062f, 13.7763f, 2.7481f, 13.5784f, 2.3965f, 13.394f)
curveTo(2.1279f, 13.2532f, 1.8677f, 13.0935f, 1.667f, 12.9011f)
curveTo(1.4609f, 12.7033f, 1.25f, 12.4034f, 1.25f, 12.0f)
curveTo(1.25f, 11.5966f, 1.4609f, 11.2967f, 1.667f, 11.0989f)
curveTo(1.8677f, 10.9065f, 2.1279f, 10.7468f, 2.3965f, 10.606f)
curveTo(2.7481f, 10.4216f, 3.2062f, 10.2237f, 3.753f, 10.0f)
curveTo(3.2062f, 9.7763f, 2.7481f, 9.5784f, 2.3965f, 9.394f)
curveTo(2.1279f, 9.2532f, 1.8677f, 9.0935f, 1.667f, 8.9011f)
curveTo(1.4609f, 8.7033f, 1.25f, 8.4034f, 1.25f, 8.0f)
curveTo(1.25f, 7.5966f, 1.4609f, 7.2967f, 1.667f, 7.0989f)
curveTo(1.8677f, 6.9065f, 2.1279f, 6.7468f, 2.3965f, 6.606f)
curveTo(2.9272f, 6.3278f, 3.7004f, 6.0185f, 4.655f, 5.6367f)
lineTo(7.5087f, 4.4952f)
curveTo(7.5476f, 4.4796f, 7.5862f, 4.4642f, 7.6244f, 4.4489f)
close()
moveTo(5.7661f, 10.8078f)
lineTo(5.2574f, 11.0113f)
curveTo(4.2469f, 11.4154f, 3.5468f, 11.6966f, 3.093f, 11.9345f)
curveTo(3.0486f, 11.9578f, 3.0086f, 11.9796f, 2.9727f, 12.0f)
curveTo(3.0086f, 12.0204f, 3.0486f, 12.0422f, 3.093f, 12.0655f)
curveTo(3.5468f, 12.3034f, 4.2469f, 12.5845f, 5.2574f, 12.9887f)
lineTo(8.0658f, 14.1121f)
curveTo(10.0907f, 14.922f, 10.9396f, 15.25f, 12.0f, 15.25f)
curveTo(13.0604f, 15.25f, 13.9093f, 14.922f, 15.9342f, 14.1121f)
lineTo(18.7426f, 12.9887f)
curveTo(19.7531f, 12.5845f, 20.4532f, 12.3034f, 20.9071f, 12.0655f)
curveTo(20.9514f, 12.0422f, 20.9914f, 12.0204f, 21.0273f, 12.0f)
curveTo(20.9914f, 11.9796f, 20.9514f, 11.9578f, 20.9071f, 11.9345f)
curveTo(20.4532f, 11.6966f, 19.7531f, 11.4154f, 18.7426f, 11.0113f)
lineTo(18.2339f, 10.8078f)
lineTo(16.4912f, 11.5048f)
curveTo(16.4524f, 11.5204f, 16.4138f, 11.5358f, 16.3756f, 11.5511f)
curveTo(14.4988f, 12.302f, 13.3792f, 12.75f, 12.0f, 12.75f)
curveTo(10.6208f, 12.75f, 9.5012f, 12.302f, 7.6244f, 11.5511f)
curveTo(7.5862f, 11.5358f, 7.5476f, 11.5204f, 7.5087f, 11.5048f)
lineTo(5.7661f, 10.8078f)
close()
moveTo(5.7661f, 14.8078f)
lineTo(5.2574f, 15.0113f)
curveTo(4.2469f, 15.4154f, 3.5468f, 15.6966f, 3.093f, 15.9345f)
curveTo(3.0486f, 15.9578f, 3.0086f, 15.9796f, 2.9727f, 16.0f)
curveTo(3.0086f, 16.0204f, 3.0486f, 16.0422f, 3.093f, 16.0655f)
curveTo(3.5468f, 16.3034f, 4.2469f, 16.5845f, 5.2574f, 16.9887f)
lineTo(8.0658f, 18.1121f)
curveTo(10.0907f, 18.922f, 10.9396f, 19.25f, 12.0f, 19.25f)
curveTo(13.0604f, 19.25f, 13.9093f, 18.922f, 15.9342f, 18.1121f)
lineTo(18.7426f, 16.9887f)
curveTo(19.7531f, 16.5845f, 20.4532f, 16.3034f, 20.9071f, 16.0655f)
curveTo(20.9514f, 16.0422f, 20.9914f, 16.0204f, 21.0273f, 16.0f)
curveTo(20.9914f, 15.9796f, 20.9514f, 15.9578f, 20.9071f, 15.9345f)
curveTo(20.4532f, 15.6966f, 19.7531f, 15.4154f, 18.7426f, 15.0113f)
lineTo(18.2339f, 14.8078f)
lineTo(16.4912f, 15.5048f)
curveTo(16.4524f, 15.5204f, 16.4138f, 15.5358f, 16.3756f, 15.5511f)
curveTo(14.4988f, 16.302f, 13.3792f, 16.75f, 12.0f, 16.75f)
curveTo(10.6208f, 16.75f, 9.5012f, 16.302f, 7.6244f, 15.5511f)
curveTo(7.5862f, 15.5358f, 7.5476f, 15.5204f, 7.5087f, 15.5048f)
lineTo(5.7661f, 14.8078f)
close()
}
}
.build()
return _layers!!
}
private var _layers: ImageVector? = null
| 0 |
Kotlin
|
0
| 0 |
3414a20650d644afac2581ad87a8525971222678
| 9,026 |
SolarIconSetAndroid
|
MIT License
|
app/src/main/java/com/example/android/trackmysleepquality/viewmodels/SleepQualityViewModel.kt
|
DzmitreyDanilau
| 222,431,403 | false | null |
package com.example.android.trackmysleepquality.viewmodels
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.android.trackmysleepquality.database.SleepDatabaseDao
import kotlinx.coroutines.*
class SleepQualityViewModel(
private val sleepNightKey: Long = 0L,
private val db: SleepDatabaseDao) : ViewModel() {
private val viewModelJob = Job()
private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)
private val _navigateToSleeptracker = MutableLiveData<Boolean?>()
val navigateToSleeptracker: LiveData<Boolean?>
get() = _navigateToSleeptracker
fun onSleepQuality(quality: Int) {
uiScope.launch {
withContext(Dispatchers.IO) {
val tonight = db.get(sleepNightKey) ?: return@withContext
tonight.sleepQuality = quality
db.update(tonight)
}
_navigateToSleeptracker.value = true
}
}
fun doNavigating() {
_navigateToSleeptracker.value = null
}
override fun onCleared() {
super.onCleared()
viewModelJob.cancel()
}
}
| 0 |
Kotlin
|
0
| 0 |
45c125b18a31e017de4b818c0d0342d214c428db
| 1,196 |
SleepQualityApp
|
Apache License 2.0
|
app/src/main/java/com/ricardojrsousa/movook/presentation/bookdetails/BookDetailsFragment.kt
|
RicardoRSousa
| 246,833,387 | false | null |
package com.ricardojrsousa.movook.presentation.bookdetails
import android.os.Build
import android.os.Bundle
import android.text.Html
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.navArgs
import com.ricardojrsousa.movook.R
import com.ricardojrsousa.movook.core.data.Book
import com.ricardojrsousa.movook.presentation.BaseFragment
import com.ricardojrsousa.movook.wrappers.loadBookCover
import com.squareup.picasso.Callback
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.android.synthetic.main.fragment_book_details.*
import kotlinx.android.synthetic.main.fragment_book_details.view.*
@AndroidEntryPoint
class BookDetailsFragment : BaseFragment<BookDetailsViewModel>(R.layout.fragment_book_details) {
override val viewModel: BookDetailsViewModel by viewModels()
private val args: BookDetailsFragmentArgs by navArgs()
private lateinit var bookId: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
bookId = args.bookId
viewModel.init(bookId)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
observeViewModel(view)
}
private fun setupView(view: View, book: Book) {
val volume = book.volumeInfo
with(view) {
book_title.text = volume.title
book_cover_image.transitionName = book.id
book_cover_image.loadBookCover(volume.imageLinks?.thumbnail, object : Callback {
override fun onSuccess() {
startPostponedEnterTransition()
}
override fun onError(e: Exception?) {
startPostponedEnterTransition()
}
})
book_author.text = volume.getAuthors()
book_year.text = volume.publishedDate
if (volume.description != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
book_description.text = Html.fromHtml(volume.description, Html.FROM_HTML_MODE_COMPACT)
} else {
book_description.text = Html.fromHtml(volume.description)
}
}
book_page_count.text = volume.pageCount.toString()
book_categories.text = volume.getCategories()
book_isbn13.text = volume.getIsbn13()
book_publisher.text = volume.publisher
book_rating.setVote(volume.averageRating)
}
}
private fun observeViewModel(view: View) {
viewModel.bookDetails.observe(viewLifecycleOwner, {
setupView(view, it)
})
}
}
| 0 |
Kotlin
|
0
| 0 |
5dc6dea7b0785f95409f9b32600e702c0abefa22
| 2,833 |
Movook
|
The Unlicense
|
app/src/main/java/com/imageloadingapp/data/remote/base/ApiState.kt
|
Shubhendra8449
| 790,004,826 | false |
{"Kotlin": 25770}
|
package com.imageloadingapp.data.remote.base
data class ApiState<out T>(val status: Status, val data: T?, val errorModel: ErrorModel?) {
companion object {
// In case of Success,set status as
// Success and data as the response
fun <T> success(data: T?): ApiState<T> {
return ApiState(Status.SUCCESS, data, null)
}
// In case of failure ,set state to Error ,
// add the error message,set data to null
fun <T> error(errorModel: ErrorModel?): ApiState<T> {
return ApiState(Status.ERROR, null, errorModel)
}
// When the call is loading set the state
// as Loading and rest as null
fun <T> loading(): ApiState<T> {
return ApiState(Status.LOADING, null, null)
}
}
}
// An enum to store the
// current state of api call
enum class Status {
SUCCESS,
ERROR,
LOADING
}
| 0 |
Kotlin
|
0
| 0 |
547a138894fa79b896c6edb9ebcd92de6b74011f
| 917 |
Image_Loading_App_without_library
|
MIT License
|
src/main/kotlin/com/github/pavponn/message/TransferMessage.kt
|
pavponn
| 358,633,243 | false | null |
package com.github.pavponn.message
import com.github.pavponn.transaction.Transaction
import com.github.pavponn.utils.Certificate
data class TransferMessage(val transaction: Transaction, val certificate: Certificate): Message
| 0 |
Kotlin
|
0
| 21 |
f56b02cb1d335222fa6bfe84af30feb5d119cb0a
| 227 |
pastro
|
MIT License
|
composeApp/src/commonMain/kotlin/com/carpisoft/guau/pet/domain/usecase/GetPetsByCenterIdWithPaginationAndSortUseCase.kt
|
wgcarvajal
| 683,392,078 | false |
{"Kotlin": 404670, "Swift": 1993, "Shell": 228}
|
package com.carpisoft.guau.pet.domain.usecase
import com.carpisoft.guau.core.network.domain.model.Resp
import com.carpisoft.guau.pet.domain.model.PetResp
import com.carpisoft.guau.pet.domain.port.PetPort
class GetPetsByCenterIdWithPaginationAndSortUseCase(private val petPort: PetPort) {
suspend operator fun invoke(
token: String,
centerId: Int,
page: Int,
limit: Int
): Resp<List<PetResp>> {
return petPort.getPetsByCenterIdWithPaginationAndSort(
token = token,
centerId = centerId,
page = page,
limit = limit
)
}
}
| 0 |
Kotlin
|
0
| 0 |
7971f12e4a2b2763eb23dbfca8b56fdddc6db37e
| 628 |
guau-multiplatform
|
Apache License 2.0
|
mosaic-runtime/src/commonTest/kotlin/com/jakewharton/mosaic/ui/ArrangementTest.kt
|
JakeWharton
| 292,637,686 | false |
{"Kotlin": 484366, "C++": 76018, "C": 22353, "Zig": 1779, "Shell": 1034}
|
package com.jakewharton.mosaic.ui
import assertk.assertThat
import assertk.assertions.isEqualTo
import kotlin.test.Test
class ArrangementTest {
@Test fun arrangementStart() {
testHorizontalArrangement(
actualArrangement = Arrangement.Start,
actualTotalSize = 140,
actualSizes = intArrayOf(20),
actualOutPositions = intArrayOf(0),
expectedOutPositions = intArrayOf(0),
)
testHorizontalArrangement(
actualArrangement = Arrangement.Start,
actualTotalSize = 140,
actualSizes = intArrayOf(20, 30),
actualOutPositions = intArrayOf(0, 0),
expectedOutPositions = intArrayOf(0, 20),
)
testHorizontalArrangement(
actualArrangement = Arrangement.Start,
actualTotalSize = 140,
actualSizes = intArrayOf(20, 30, 40),
actualOutPositions = intArrayOf(0, 0, 0),
expectedOutPositions = intArrayOf(0, 20, 50),
)
testHorizontalArrangement(
actualArrangement = Arrangement.Start,
actualTotalSize = 140,
actualSizes = intArrayOf(20, 30, 40),
actualOutPositions = intArrayOf(50, 20, 0),
expectedOutPositions = intArrayOf(0, 20, 50),
)
}
@Test fun arrangementEnd() {
testHorizontalArrangement(
actualArrangement = Arrangement.End,
actualTotalSize = 140,
actualSizes = intArrayOf(20),
actualOutPositions = intArrayOf(0),
expectedOutPositions = intArrayOf(120),
)
testHorizontalArrangement(
actualArrangement = Arrangement.End,
actualTotalSize = 140,
actualSizes = intArrayOf(20, 30),
actualOutPositions = intArrayOf(0, 0),
expectedOutPositions = intArrayOf(90, 110),
)
testHorizontalArrangement(
actualArrangement = Arrangement.End,
actualTotalSize = 140,
actualSizes = intArrayOf(20, 30, 40),
actualOutPositions = intArrayOf(0, 0, 0),
expectedOutPositions = intArrayOf(50, 70, 100),
)
testHorizontalArrangement(
actualArrangement = Arrangement.End,
actualTotalSize = 140,
actualSizes = intArrayOf(20, 30, 40),
actualOutPositions = intArrayOf(100, 70, 50),
expectedOutPositions = intArrayOf(50, 70, 100),
)
}
@Test fun arrangementTop() {
testVerticalArrangement(
actualArrangement = Arrangement.Top,
actualTotalSize = 140,
actualSizes = intArrayOf(20),
actualOutPositions = intArrayOf(0),
expectedOutPositions = intArrayOf(0),
)
testVerticalArrangement(
actualArrangement = Arrangement.Top,
actualTotalSize = 140,
actualSizes = intArrayOf(20, 30),
actualOutPositions = intArrayOf(0, 0),
expectedOutPositions = intArrayOf(0, 20),
)
testVerticalArrangement(
actualArrangement = Arrangement.Top,
actualTotalSize = 140,
actualSizes = intArrayOf(20, 30, 40),
actualOutPositions = intArrayOf(0, 0, 0),
expectedOutPositions = intArrayOf(0, 20, 50),
)
testVerticalArrangement(
actualArrangement = Arrangement.Top,
actualTotalSize = 140,
actualSizes = intArrayOf(20, 30, 40),
actualOutPositions = intArrayOf(50, 20, 0),
expectedOutPositions = intArrayOf(0, 20, 50),
)
}
@Test fun arrangementBottom() {
testVerticalArrangement(
actualArrangement = Arrangement.Bottom,
actualTotalSize = 140,
actualSizes = intArrayOf(20),
actualOutPositions = intArrayOf(0),
expectedOutPositions = intArrayOf(120),
)
testVerticalArrangement(
actualArrangement = Arrangement.Bottom,
actualTotalSize = 140,
actualSizes = intArrayOf(20, 30),
actualOutPositions = intArrayOf(0, 0),
expectedOutPositions = intArrayOf(90, 110),
)
testVerticalArrangement(
actualArrangement = Arrangement.Bottom,
actualTotalSize = 140,
actualSizes = intArrayOf(20, 30, 40),
actualOutPositions = intArrayOf(0, 0, 0),
expectedOutPositions = intArrayOf(50, 70, 100),
)
testVerticalArrangement(
actualArrangement = Arrangement.Bottom,
actualTotalSize = 140,
actualSizes = intArrayOf(20, 30, 40),
actualOutPositions = intArrayOf(100, 70, 50),
expectedOutPositions = intArrayOf(50, 70, 100),
)
}
@Test fun arrangementCenter() {
testVerticalArrangement(
actualArrangement = Arrangement.Center,
actualTotalSize = 140,
actualSizes = intArrayOf(20),
actualOutPositions = intArrayOf(0),
expectedOutPositions = intArrayOf(60),
)
testVerticalArrangement(
actualArrangement = Arrangement.Center,
actualTotalSize = 140,
actualSizes = intArrayOf(20, 30),
actualOutPositions = intArrayOf(0, 0),
expectedOutPositions = intArrayOf(45, 65),
)
testVerticalArrangement(
actualArrangement = Arrangement.Center,
actualTotalSize = 140,
actualSizes = intArrayOf(20, 30, 40),
actualOutPositions = intArrayOf(0, 0, 0),
expectedOutPositions = intArrayOf(25, 45, 75),
)
testVerticalArrangement(
actualArrangement = Arrangement.Center,
actualTotalSize = 140,
actualSizes = intArrayOf(20, 30, 40),
actualOutPositions = intArrayOf(75, 45, 25),
expectedOutPositions = intArrayOf(25, 45, 75),
)
}
@Test fun arrangementSpaceEvenly() {
testVerticalArrangement(
actualArrangement = Arrangement.SpaceEvenly,
actualTotalSize = 140,
actualSizes = intArrayOf(20),
actualOutPositions = intArrayOf(0),
expectedOutPositions = intArrayOf(60),
)
testVerticalArrangement(
actualArrangement = Arrangement.SpaceEvenly,
actualTotalSize = 140,
actualSizes = intArrayOf(20, 30),
actualOutPositions = intArrayOf(0, 0),
expectedOutPositions = intArrayOf(30, 80),
)
testVerticalArrangement(
actualArrangement = Arrangement.SpaceEvenly,
actualTotalSize = 150,
actualSizes = intArrayOf(20, 30, 40),
actualOutPositions = intArrayOf(0, 0, 0),
expectedOutPositions = intArrayOf(15, 50, 95),
)
testVerticalArrangement(
actualArrangement = Arrangement.SpaceEvenly,
actualTotalSize = 150,
actualSizes = intArrayOf(20, 30, 40),
actualOutPositions = intArrayOf(95, 50, 15),
expectedOutPositions = intArrayOf(15, 50, 95),
)
}
@Test fun arrangementSpaceBetween() {
testVerticalArrangement(
actualArrangement = Arrangement.SpaceBetween,
actualTotalSize = 140,
actualSizes = intArrayOf(20),
actualOutPositions = intArrayOf(0),
expectedOutPositions = intArrayOf(0),
)
testVerticalArrangement(
actualArrangement = Arrangement.SpaceBetween,
actualTotalSize = 140,
actualSizes = intArrayOf(20, 30),
actualOutPositions = intArrayOf(0, 0),
expectedOutPositions = intArrayOf(0, 110),
)
testVerticalArrangement(
actualArrangement = Arrangement.SpaceBetween,
actualTotalSize = 140,
actualSizes = intArrayOf(20, 30, 40),
actualOutPositions = intArrayOf(0, 0, 0),
expectedOutPositions = intArrayOf(0, 45, 100),
)
testVerticalArrangement(
actualArrangement = Arrangement.SpaceBetween,
actualTotalSize = 140,
actualSizes = intArrayOf(20, 30, 40),
actualOutPositions = intArrayOf(100, 45, 0),
expectedOutPositions = intArrayOf(0, 45, 100),
)
}
@Test fun arrangementSpaceAroung() {
testVerticalArrangement(
actualArrangement = Arrangement.SpaceAround,
actualTotalSize = 140,
actualSizes = intArrayOf(20),
actualOutPositions = intArrayOf(0),
expectedOutPositions = intArrayOf(60),
)
testVerticalArrangement(
actualArrangement = Arrangement.SpaceAround,
actualTotalSize = 150,
actualSizes = intArrayOf(20, 30),
actualOutPositions = intArrayOf(0, 0),
expectedOutPositions = intArrayOf(25, 95),
)
testVerticalArrangement(
actualArrangement = Arrangement.SpaceAround,
actualTotalSize = 150,
actualSizes = intArrayOf(20, 30, 40),
actualOutPositions = intArrayOf(0, 0, 0),
expectedOutPositions = intArrayOf(10, 50, 100),
)
testVerticalArrangement(
actualArrangement = Arrangement.SpaceAround,
actualTotalSize = 150,
actualSizes = intArrayOf(20, 30, 40),
actualOutPositions = intArrayOf(100, 50, 10),
expectedOutPositions = intArrayOf(10, 50, 100),
)
}
private fun testVerticalArrangement(
actualArrangement: Arrangement.Vertical,
actualTotalSize: Int,
actualSizes: IntArray,
actualOutPositions: IntArray,
expectedOutPositions: IntArray,
) {
actualArrangement.arrange(actualTotalSize, actualSizes, actualOutPositions)
assertThat(actualOutPositions).isEqualTo(expectedOutPositions)
}
private fun testHorizontalArrangement(
actualArrangement: Arrangement.Horizontal,
actualTotalSize: Int,
actualSizes: IntArray,
actualOutPositions: IntArray,
expectedOutPositions: IntArray,
) {
actualArrangement.arrange(actualTotalSize, actualSizes, actualOutPositions)
assertThat(actualOutPositions).isEqualTo(expectedOutPositions)
}
}
| 27 |
Kotlin
|
57
| 1,912 |
3574b7b21bdee4f72c9f5b5eef0389cc8f9ddcfa
| 8,518 |
mosaic
|
Apache License 2.0
|
app/src/main/java/com/io/gazette/data/local/NewsDatabase.kt
|
efe-egbevwie
| 475,847,896 | false | null |
package com.io.gazette.data.local
import androidx.room.AutoMigration
import androidx.room.Database
import androidx.room.RenameTable
import androidx.room.RoomDatabase
import androidx.room.migration.AutoMigrationSpec
import com.io.gazette.data.local.dao.NewsDao
import com.io.gazette.data.local.model.NewsEntity
import com.io.gazette.data.local.model.ReadLaterStoryEntity
import com.io.gazette.data.local.model.ReadLaterListEntity
@Database(
entities = [NewsEntity::class, ReadLaterListEntity::class, ReadLaterStoryEntity::class],
version = 7,
autoMigrations = [
AutoMigration(from = 6, to = 7, spec = NewsDatabase.RenameReadLaterEntityMigration::class),
],
exportSchema = true
)
abstract class NewsDatabase : RoomDatabase() {
abstract fun newsDao(): NewsDao
@RenameTable(fromTableName = "reading_list", toTableName = "read_later_lists")
class RenameReadLaterEntityMigration: AutoMigrationSpec
}
| 0 |
Kotlin
|
1
| 0 |
0e552f8969bae45d04ded293ff3b01296e5090ef
| 937 |
Gazette
|
MIT License
|
shared/src/main/java/de/loosetie/k8s/dsl/manifests/TypedLocalObjectReference.kt
|
loosetie
| 283,145,621 | false |
{"Kotlin": 12443871}
|
package de.loosetie.k8s.dsl.manifests
import de.loosetie.k8s.dsl.K8sTopLevel
import de.loosetie.k8s.dsl.K8sDslMarker
import de.loosetie.k8s.dsl.K8sManifest
import de.loosetie.k8s.dsl.HasMetadata
@K8sDslMarker
interface TypedLocalObjectReference_core_v1_k8s1_16: K8sManifest {
/** Kind is the type of resource being referenced */
@K8sDslMarker var kind: String?
/** Name is the name of resource being referenced */
@K8sDslMarker var name: String?
/** APIGroup is the group for the resource being referenced. If APIGroup is not specified, the specified Kind must be in the
core API group. For any other third-party types, APIGroup is required. */
@K8sDslMarker var apiGroup: String?
}
typealias TypedLocalObjectReference_core_v1_k8s1_17 = TypedLocalObjectReference_core_v1_k8s1_16
typealias TypedLocalObjectReference_core_v1_k8s1_18 = TypedLocalObjectReference_core_v1_k8s1_17
typealias TypedLocalObjectReference_core_v1_k8s1_19 = TypedLocalObjectReference_core_v1_k8s1_18
typealias TypedLocalObjectReference_core_v1_k8s1_20 = TypedLocalObjectReference_core_v1_k8s1_19
typealias TypedLocalObjectReference_core_v1_k8s1_21 = TypedLocalObjectReference_core_v1_k8s1_20
| 0 |
Kotlin
|
0
| 1 |
3dd2d00220dbf71151d56b75b3bd7f26583b1fd3
| 1,217 |
k8s-dsl
|
Apache License 2.0
|
core/designsystem/src/main/kotlin/com/najudoryeong/musicdo/core/designsystem/componenet/Button.kt
|
KDW03
| 719,372,791 | false |
{"Kotlin": 402221}
|
/*
* Copyright 2023 KDW03
*
* 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.najudoryeong.musicdo.core.designsystem.componenet
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonColors
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ButtonElevation
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.unit.dp
import com.najudoryeong.musicdo.core.designsystem.theme.DoTheme
@Composable
fun DoButton(
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
shape: Shape = ButtonDefaults.shape,
colors: ButtonColors = ButtonDefaults.buttonColors(),
elevation: ButtonElevation? = ButtonDefaults.buttonElevation(),
border: BorderStroke? = null,
contentPadding: PaddingValues = ButtonDefaults.ContentPadding,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
content: @Composable RowScope.() -> Unit,
) {
val isPressed by interactionSource.collectIsPressedAsState()
val scale by animateFloatAsState(
targetValue = if (isPressed) ButtonPressedScale else 1f,
animationSpec = ButtonPressedAnimation,
label = "ScaleAnimation",
)
val alpha by animateFloatAsState(
targetValue = if (isPressed) ButtonPressedAlpha else 1f,
animationSpec = ButtonPressedAnimation,
label = "AlphaAnimation",
)
Button(
modifier = modifier.graphicsLayer(scaleX = scale, scaleY = scale, alpha = alpha),
onClick = onClick,
enabled = enabled,
shape = shape,
colors = colors,
elevation = elevation,
border = border,
contentPadding = contentPadding,
interactionSource = interactionSource,
content = content,
)
}
@Composable
fun DoOutlinedButton(
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
shape: Shape = ButtonDefaults.outlinedShape,
colors: ButtonColors = ButtonDefaults.outlinedButtonColors(),
elevation: ButtonElevation? = null,
border: BorderStroke? = DoOutlinedBorder,
contentPadding: PaddingValues = ButtonDefaults.ContentPadding,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
content: @Composable RowScope.() -> Unit,
) {
DoButton(
modifier = modifier,
onClick = onClick,
enabled = enabled,
shape = shape,
colors = colors,
elevation = elevation,
border = border,
contentPadding = contentPadding,
interactionSource = interactionSource,
content = content,
)
}
@ThemePreviews
@Composable
fun DoButtonPreview() {
DoTheme {
DoBackground(modifier = Modifier.size(150.dp, 50.dp)) {
DoButton(
onClick = {},
content = {
Text("Do Button")
},
)
}
}
}
@ThemePreviews
@Composable
fun DoOutlinedButtonPreview() {
DoTheme {
DoBackground(modifier = Modifier.size(150.dp, 50.dp)) {
DoOutlinedButton(
onClick = {},
content = {
Text("Do Button")
},
)
}
}
}
private const val ButtonPressedScale = 0.95f
private const val ButtonPressedAlpha = 0.75f
private val ButtonPressedAnimation = tween<Float>()
| 0 |
Kotlin
|
0
| 0 |
8df70536a8e6e8cf781dbe8584ddadf83152e2ed
| 4,651 |
MusicDo
|
Apache License 2.0
|
app/src/test/java/com/masrofy/filterDate/WeeklyDateFilterTest.kt
|
salmanA169
| 589,714,976 | false | null |
package com.masrofy.filterDate
import com.google.common.collect.ImmutableMultimap
import com.google.common.truth.Truth
import com.masrofy.data.entity.TransactionEntity
import com.masrofy.model.TransactionCategory
import com.masrofy.model.TransactionType
import com.masrofy.screens.mainScreen.DateEvent
import org.junit.Before
import org.junit.Test
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
internal class WeeklyDateFilterTest {
private lateinit var transactionDateFilter:TransactionDateFilter
private lateinit var transactionDateFilterMonthly:TransactionDateFilter
@Before
fun setUp() {
}
@Test
fun rangeFromJunToFebWeekly(){
}
@Test
fun junToMars_Correct(){
val data = transactionDateFilterMonthly.getTransactions()
val junExpectedData = transactionDateFilterMonthly.getTransactions().filter {
it.createdAt.monthValue == 1
}
Truth.assertThat(data).containsExactlyElementsIn(junExpectedData)
transactionDateFilterMonthly.updateDate(DateEvent.PLUS,1)
val expectedFeb = transactionDateFilterMonthly.getTransactions().filter {
it.createdAt.monthValue == 2
}
Truth.assertThat(transactionDateFilterMonthly.getTransactions()).containsExactlyElementsIn(expectedFeb)
transactionDateFilterMonthly.updateDate(DateEvent.PLUS,1)
val expectedMar = transactionDateFilterMonthly.getTransactions().filter {
it.createdAt.monthValue == 3
}
Truth.assertThat(transactionDateFilterMonthly.getTransactions()).containsExactlyElementsIn(expectedMar)
}
@Test
fun rangeDateFrom12To19_correct(){
transactionDateFilter.updateDate(2023,1,12)
Truth.assertThat(transactionDateFilter.getTransactions()).hasSize(4)
}
@Test
fun RangeDateFrom14To21_Correct(){
transactionDateFilter.updateDate(2023,1,14)
val data = transactionDateFilter.getTransactions()
val expectedData = data.filter {
it.createdAt.dayOfMonth in 14..21
}
Truth.assertThat(data).containsExactlyElementsIn(expectedData)
// println(data)
}
@Test
fun rangeDateFrom14To21_Incorrect(){
transactionDateFilter.updateDate(2023,1,14)
val data = transactionDateFilter.getTransactions()
val expectedData = data.filter {
it.createdAt.dayOfMonth in 14..24
}
Truth.assertThat(data).containsExactlyElementsIn(expectedData)
// println(data)
}
}
| 2 |
Kotlin
|
0
| 9 |
fb671fc1e2c628fb467bca9d3109799b3e1d43f2
| 2,566 |
masrofy
|
Apache License 2.0
|
app/src/main/java/com/hunabsys/gamezone/models/daos/PrizeDao.kt
|
HiperSoft
| 324,049,960 | false | null |
package com.hunabsys.gamezone.models.daos
import android.util.Log
import com.hunabsys.gamezone.models.datamodels.Prize
import io.realm.Realm
import io.realm.RealmResults
import io.realm.Sort
/**
* Prize model
* Created by <NAME> on 23/07/2018
*/
class PrizeDao {
private val tag = PrizeDao::class.simpleName
private val realm = Realm.getDefaultInstance()
fun create(prize: Prize) {
try {
realm.executeTransaction {
val prizeObject = realm.createObject(Prize::class.java, getId())
prizeObject.webId = prize.webId
prizeObject.userId = prize.userId
prizeObject.routeId = prize.routeId
prizeObject.pointOfSaleId = prize.pointOfSaleId
prizeObject.gameMachineId = prize.gameMachineId
prizeObject.inputReading = prize.inputReading
prizeObject.outputReading = prize.outputReading
prizeObject.screen = prize.screen
prizeObject.prizeAmount = prize.prizeAmount
prizeObject.currentAmount = prize.currentAmount
prizeObject.toComplete = prize.toComplete
prizeObject.gameMachineFund = prize.gameMachineFund
prizeObject.expenseAmount = prize.expenseAmount
prizeObject.comments = prize.comments
prizeObject.week = prize.week
prizeObject.createdAt = prize.createdAt
prizeObject.evidences = prize.evidences
prizeObject.hasSynchronizedData = prize.hasSynchronizedData
prizeObject.hasSynchronizedPhotos = prize.hasSynchronizedPhotos
}
} catch (ex: IllegalArgumentException) {
Log.e(tag, "Attempting to create a Prize", ex)
}
}
fun update(prize: Prize) {
try {
realm.executeTransaction {
val prizeObject = findById(prize.id)
prizeObject.webId = prize.webId
prizeObject.userId = prize.userId
prizeObject.routeId = prize.routeId
prizeObject.pointOfSaleId = prize.pointOfSaleId
prizeObject.gameMachineId = prize.gameMachineId
prizeObject.inputReading = prize.inputReading
prizeObject.outputReading = prize.outputReading
prizeObject.screen = prize.screen
prizeObject.prizeAmount = prize.prizeAmount
prizeObject.currentAmount = prize.currentAmount
prizeObject.toComplete = prize.toComplete
prizeObject.gameMachineFund = prize.gameMachineFund
prizeObject.expenseAmount = prize.expenseAmount
prizeObject.comments = prize.comments
prizeObject.week = prize.week
prizeObject.createdAt = prize.createdAt
prizeObject.hasSynchronizedData = prize.hasSynchronizedData
prizeObject.hasSynchronizedPhotos = prize.hasSynchronizedPhotos
}
} catch (ex: IllegalArgumentException) {
Log.e(tag, "Attempting to update a Prize", ex)
}
}
private fun findById(id: Long): Prize {
return realm.where(Prize::class.java)
.equalTo("id", id)
.findFirst()!!
}
fun findCopyById(id: Long): Prize {
val prize = realm.where(Prize::class.java)
.equalTo("id", id)
.findFirst()!!
return realm.copyFromRealm(prize)
}
private fun findAll(): RealmResults<Prize> {
return realm.where(Prize::class.java)
.findAll()
.sort("id", Sort.DESCENDING)
}
fun findAll(userId: Long): RealmResults<Prize> {
return realm.where(Prize::class.java)
.equalTo("userId", userId)
.findAll()
.sort("id", Sort.DESCENDING)
}
fun deleteAll(userId: Long) {
try {
realm.executeTransaction {
realm.where(Prize::class.java)
.equalTo("userId", userId)
.findAll()
.deleteAllFromRealm()
}
} catch (ex: Exception) {
Log.e(tag, "Attempting to delete all Prizes", ex)
}
}
fun deleteAllOtherUsers(userId: Long) {
try {
realm.executeTransaction {
realm.where(Prize::class.java)
.notEqualTo("userId", userId)
.findAll()
.deleteAllFromRealm()
}
} catch (ex: Exception) {
Log.e(tag, "Attempting to delete all Prizes", ex)
}
}
private fun getId(): Long {
return if (findAll().size != 0) {
val lastId = findAll().first()!!.id
lastId + 1
} else {
1
}
}
}
| 0 |
Kotlin
|
0
| 0 |
fab0ef038d84595df86cf480ed581c84b4272073
| 4,929 |
AppGameZone
|
MIT License
|
src/main/kotlin/com/kneelawk/wiredredstone/node/WRBlockNodes.kt
|
Kneelawk
| 443,064,933 | false | null |
package com.kneelawk.wiredredstone.node
import com.kneelawk.graphlib.GraphLib
import com.kneelawk.wiredredstone.WRConstants.id
import net.minecraft.util.registry.Registry
object WRBlockNodes {
val RED_ALLOY_WIRE_ID = id("red_alloy_wire")
val INSULATED_WIRE_ID = id("insulated_wire")
val BUNDLED_CABLE_ID = id("bundled_cable")
val GATE_AND_ID = id("gate_and")
val GATE_DIODE_ID = id("gate_diode")
val GATE_NAND_ID = id("gate_nand")
val GATE_NOR_ID = id("gate_nor")
val GATE_NOT_ID = id("gate_not")
val GATE_OR_ID = id("gate_or")
val GATE_PROJECTOR_SIMPLE_ID = id("gate_projector_simple")
val GATE_REPEATER_ID = id("gate_repeater")
val GATE_RS_LATCH = id("gate_rs_latch")
fun init() {
Registry.register(GraphLib.BLOCK_NODE_DECODER, RED_ALLOY_WIRE_ID, RedAlloyWireBlockNode.Decoder)
Registry.register(GraphLib.BLOCK_NODE_DECODER, INSULATED_WIRE_ID, InsulatedWireBlockNode.Decoder)
Registry.register(GraphLib.BLOCK_NODE_DECODER, BUNDLED_CABLE_ID, BundledCableBlockNode.Decoder)
Registry.register(GraphLib.BLOCK_NODE_DECODER, GATE_AND_ID, GateAndBlockNode.Decoder)
Registry.register(GraphLib.BLOCK_NODE_DECODER, GATE_DIODE_ID, GateDiodeBlockNode.Decoder)
Registry.register(GraphLib.BLOCK_NODE_DECODER, GATE_NAND_ID, GateNandBlockNode.Decoder)
Registry.register(GraphLib.BLOCK_NODE_DECODER, GATE_NOR_ID, GateNorBlockNode.Decoder)
Registry.register(GraphLib.BLOCK_NODE_DECODER, GATE_NOT_ID, GateNotBlockNode.Decoder)
Registry.register(GraphLib.BLOCK_NODE_DECODER, GATE_OR_ID, GateOrBlockNode.Decoder)
Registry.register(GraphLib.BLOCK_NODE_DECODER, GATE_PROJECTOR_SIMPLE_ID, GateProjectorSimpleBlockNode.Decoder)
Registry.register(GraphLib.BLOCK_NODE_DECODER, GATE_REPEATER_ID, GateRepeaterBlockNode.Decoder)
Registry.register(GraphLib.BLOCK_NODE_DECODER, GATE_RS_LATCH, GateRSLatchBlockNode.Decoder)
}
}
| 5 |
Kotlin
|
3
| 9 |
b7e0ca88e8654dea9f52853f6c502f23285b5010
| 1,952 |
WiredRedstone
|
MIT License
|
app/src/main/java/tech/sonle/barcodescanner/feature/tabs/create/BaseCreateBarcodeFragment.kt
|
sonlenef
| 492,779,126 | false |
{"Kotlin": 364958, "Java": 17337}
|
package tech.sonle.barcodescanner.feature.tabs.create
import androidx.fragment.app.Fragment
import tech.sonle.barcodescanner.extension.*
import tech.sonle.barcodescanner.model.Contact
import tech.sonle.barcodescanner.model.schema.Other
import tech.sonle.barcodescanner.model.schema.Schema
abstract class BaseCreateBarcodeFragment : Fragment() {
protected val parentActivity by unsafeLazy { requireActivity() as CreateBarcodeActivity }
open val latitude: Double? = null
open val longitude: Double? = null
open fun getBarcodeSchema(): Schema = Other("")
open fun showPhone(phone: String) {}
open fun showContact(contact: Contact) {}
open fun showLocation(latitude: Double?, longitude: Double?) {}
}
| 0 |
Kotlin
|
0
| 0 |
f624f51868cfd42c71dc2f615d1f1116785776ef
| 728 |
QrAndBarcodeScanner
|
The Unlicense
|
core-data/src/main/java/edts/base/android/core_data/RemoteConfig.kt
|
abahadilah
| 651,759,726 | false | null |
package edts.base.android.core_data
import com.google.firebase.remoteconfig.FirebaseRemoteConfig
object RemoteConfig {
fun getOtpInterval() = FirebaseRemoteConfig.getInstance().getLong("otp_interval")
fun getBankList() = FirebaseRemoteConfig.getInstance().getString("bank_list")
fun getLatitude() = FirebaseRemoteConfig.getInstance().getDouble("latitude")
fun getLongitude() = FirebaseRemoteConfig.getInstance().getDouble("longitude")
}
| 0 |
Kotlin
|
0
| 0 |
9d97e941f3dd0b99127dee9218c4c78056f10c52
| 455 |
jgo
|
MIT License
|
solar/src/main/java/com/chiksmedina/solar/broken/money/Card.kt
|
CMFerrer
| 689,442,321 | false |
{"Kotlin": 36591890}
|
package com.chiksmedina.solar.broken.money
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
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.chiksmedina.solar.broken.MoneyGroup
val MoneyGroup.Card: ImageVector
get() {
if (_card != null) {
return _card!!
}
_card = Builder(
name = "Card", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f
).apply {
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(22.0f, 12.0f)
curveTo(22.0f, 8.2288f, 22.0f, 6.3432f, 20.8284f, 5.1716f)
curveTo(19.6569f, 4.0f, 17.7712f, 4.0f, 14.0f, 4.0f)
horizontalLineTo(10.0f)
curveTo(6.2288f, 4.0f, 4.3432f, 4.0f, 3.1716f, 5.1716f)
curveTo(2.0f, 6.3432f, 2.0f, 8.2288f, 2.0f, 12.0f)
curveTo(2.0f, 15.7712f, 2.0f, 17.6569f, 3.1716f, 18.8284f)
curveTo(4.3432f, 20.0f, 6.2288f, 20.0f, 10.0f, 20.0f)
horizontalLineTo(14.0f)
curveTo(17.7712f, 20.0f, 19.6569f, 20.0f, 20.8284f, 18.8284f)
curveTo(21.4816f, 18.1752f, 21.7706f, 17.3001f, 21.8985f, 16.0f)
}
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(10.0f, 16.0f)
horizontalLineTo(6.0f)
}
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(14.0f, 16.0f)
horizontalLineTo(12.5f)
}
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(2.0f, 10.0f)
lineTo(7.0f, 10.0f)
moveTo(22.0f, 10.0f)
lineTo(11.0f, 10.0f)
}
}
.build()
return _card!!
}
private var _card: ImageVector? = null
| 0 |
Kotlin
|
0
| 0 |
3414a20650d644afac2581ad87a8525971222678
| 3,133 |
SolarIconSetAndroid
|
MIT License
|
feature/wallet/src/main/kotlin/ru/resodostudios/cashsense/feature/wallet/WalletDialog.kt
|
f33lnothin9
| 674,320,726 | false |
{"Kotlin": 200002}
|
package ru.resodostudios.cashsense.feature.wallet
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import ru.resodostudios.cashsense.core.designsystem.component.CsAlertDialog
import ru.resodostudios.cashsense.core.designsystem.icon.CsIcons
import ru.resodostudios.cashsense.core.model.data.Currency
import ru.resodostudios.cashsense.core.model.data.Wallet
import ru.resodostudios.cashsense.core.ui.CurrencyExposedDropdownMenuBox
import ru.resodostudios.cashsense.core.ui.validateAmount
import java.util.UUID
import ru.resodostudios.cashsense.core.ui.R as uiR
@Composable
fun AddWalletDialog(
onDismiss: () -> Unit,
viewModel: WalletViewModel = hiltViewModel()
) {
AddWalletDialog(
onDismiss = onDismiss,
onConfirm = {
viewModel.upsertWallet(it)
onDismiss()
}
)
}
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun AddWalletDialog(
onDismiss: () -> Unit,
onConfirm: (Wallet) -> Unit
) {
var title by rememberSaveable { mutableStateOf("") }
var startBalance by rememberSaveable { mutableStateOf("") }
var currency by rememberSaveable { mutableStateOf(Currency.USD) }
val (titleTextField, amountTextField) = remember { FocusRequester.createRefs() }
CsAlertDialog(
titleRes = R.string.feature_wallet_new_wallet,
confirmButtonTextRes = uiR.string.add,
dismissButtonTextRes = uiR.string.core_ui_cancel,
iconRes = CsIcons.Wallet,
onConfirm = {
onConfirm(
Wallet(
id = UUID.randomUUID().toString(),
title = title,
initialBalance = startBalance.toBigDecimal(),
currency = currency.name
)
)
},
isConfirmEnabled = title.isNotBlank() && startBalance.validateAmount().second,
onDismiss = onDismiss,
{
Column(
verticalArrangement = Arrangement.spacedBy(16.dp),
modifier = Modifier.verticalScroll(rememberScrollState())
) {
OutlinedTextField(
value = title,
onValueChange = { title = it },
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Text,
imeAction = ImeAction.Next
),
label = { Text(text = stringResource(uiR.string.title)) },
maxLines = 1,
modifier = Modifier
.focusRequester(titleTextField)
.focusProperties { next = amountTextField },
placeholder = { Text(text = stringResource(uiR.string.title) + "*") },
supportingText = { Text(text = stringResource(uiR.string.required)) }
)
OutlinedTextField(
value = startBalance,
onValueChange = { startBalance = it.validateAmount().first },
placeholder = { Text(text = "100") },
label = { Text(text = stringResource(R.string.feature_wallet_initial_balance)) },
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Decimal
),
maxLines = 1,
modifier = Modifier.focusRequester(amountTextField)
)
CurrencyExposedDropdownMenuBox(
currencyName = currency.name,
onCurrencyClick = { currency = it }
)
}
LaunchedEffect(Unit) {
titleTextField.requestFocus()
}
},
)
}
@Composable
fun EditWalletDialog(
onDismiss: () -> Unit,
wallet: Wallet,
viewModel: WalletViewModel = hiltViewModel()
) {
EditWalletDialog(
onDismiss = onDismiss,
onConfirm = {
viewModel.upsertWallet(it)
onDismiss()
},
wallet = wallet
)
}
@Composable
fun EditWalletDialog(
onDismiss: () -> Unit,
onConfirm: (Wallet) -> Unit,
wallet: Wallet
) {
var title by rememberSaveable { mutableStateOf(wallet.title) }
var startBalance by rememberSaveable { mutableStateOf(wallet.initialBalance.toString()) }
var currency by rememberSaveable { mutableStateOf(wallet.currency) }
CsAlertDialog(
titleRes = R.string.feature_wallet_edit_wallet,
confirmButtonTextRes = uiR.string.save,
dismissButtonTextRes = uiR.string.core_ui_cancel,
iconRes = CsIcons.Wallet,
onConfirm = {
onConfirm(
Wallet(
id = wallet.id,
title = title,
initialBalance = startBalance.toBigDecimal(),
currency = currency
)
)
},
isConfirmEnabled = title.isNotBlank() && startBalance.validateAmount().second,
onDismiss = onDismiss
) {
Column(
verticalArrangement = Arrangement.spacedBy(16.dp),
modifier = Modifier.verticalScroll(rememberScrollState())
) {
OutlinedTextField(
value = title,
onValueChange = { title = it },
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Text,
imeAction = ImeAction.Next
),
label = { Text(text = stringResource(uiR.string.title)) },
maxLines = 1
)
OutlinedTextField(
value = startBalance,
onValueChange = { startBalance = it.validateAmount().first },
placeholder = { Text(text = "100") },
label = { Text(text = stringResource(R.string.feature_wallet_initial_balance)) },
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Decimal
),
maxLines = 1
)
CurrencyExposedDropdownMenuBox(
currencyName = currency,
onCurrencyClick = { currency = it.name }
)
}
}
}
| 0 |
Kotlin
|
0
| 1 |
7fb8aba2342579e81a52d0fc43008cb1b5824ae9
| 7,332 |
cashsense
|
Apache License 2.0
|
libdownmark/src/commonMain/kotlin/net/sergeych/downmark/CharSource.kt
|
sergeych
| 783,416,534 | false |
{"Kotlin": 55430}
|
package net.sergeych.downmark
class CharSource(private val text: String) {
inner class Mark() {
val startPosition = pos()
fun rewind() {
resetTo(startPosition)
}
fun createError(text: String): SyntaxError =
SyntaxError(startPosition, text)
}
fun createMark(): Mark = Mark()
val lines = text.lines().let {
if (it.isEmpty()) listOf("") else it
}
internal var currentLine = lines[0]
private var row = 0
var col = 0
private set
private var _currentPos: Pos? = null
fun pos(): Pos {
_currentPos?.let { return it }
return posAt(row, col).also { _currentPos = it }
}
// fun back(steps: Int = 1) {
// for (i in 0..steps) {
// if (col == 0) {
// if (row == 0) throw IndexOutOfBoundsException("back below first character")
// row--
// col = lines[row].length
// }
// }
// sync()
// }
fun resetTo(p: Pos) {
val cp = pos()
if (cp != p) {
row = p.row
col = p.col
sync()
}
}
var current: Char? = null
private set
val eol: Boolean get() = current == '\n'
var end = true
private set
fun skipLine() {
if (!end) {
row++
col = 0
sync()
}
}
fun advance(steps: Int = 1) {
val dir: Int
val limit: Int
if (steps > 0) {
dir = 1
limit = steps
} else {
dir = -1
limit = -steps
}
for (i in 0..<limit) {
if (dir > 0) {
if (end) throw IndexOutOfBoundsException("advance past the end")
if (current == '\n') {
row++
col = 0
if (row >= lines.size) end = true
} else col++
} else {
if (col == 0) {
if (row == 0) throw IndexOutOfBoundsException("advance back before the start")
col = lines[--row].length
}
else col--
}
}
sync()
}
private fun sync() {
_currentPos = null
end = row >= lines.size
if (end)
current = null
else {
currentLine = lines[row]
current = if (col >= currentLine.length) '\n' else currentLine[col]
}
}
/**
* Skip spaces in current line only
*/
fun skipWs(): CharSource {
while (current?.let { it in " \t" } == true) advance()
return this
}
fun <T> mark(f: Mark.() -> T): T = with(createMark()) { f() }
/**
* Check that source matches any <prefix><non-space>, in which case
* the source is advanced to the position right after the prefix
* @return true if prefix-non-space match was found
*/
fun getStart(vararg prefixes: String): Boolean = mark {
if (expectAny(*prefixes) == null)
false
else {
// now the next char should exist (it does) and be non-space:
val ok = current?.let { c ->
c !in spaces && prefixes.all { c !in it }
} ?: false
if (ok)
true
else {
rewind()
false
}
}
}
/**
* If the expected value is at the current position, advance past it.
* @return true if the expected value was read, false otherwise
*/
fun expect(pattern: String): Boolean {
for (i in 0..<pattern.length) {
val k = col + i
if (k >= currentLine.length || currentLine[k] != pattern[i])
return false
}
col += pattern.length
sync()
return true
}
fun expectAny(vararg patterns: String): String? {
for (p in patterns) {
if (expect(p)) return p
}
return null
}
/**
* Retrieve text from current position to the end of line. Line ending
* will not be added to the returned string.
* After the call current position is on the first char of the next line
* or [end]
* @return the retrieved text which could be empty.
*/
fun readToEndOfLine(): String {
return if (eol) {
advance()
""
} else {
currentLine.substring(col).also {
row++
col = 0
sync()
}
}
}
/**
* Check that this is [eol] or characters until [eol] are all spaces consuming it and line
* ending.
*
* After this call, the [current] is either null or points to the first char if the first non-empty line
*
* @return true if there was a consumed blank line ahead
*/
fun skipSpacesToEnd(): Boolean {
while (!eol && !end) {
if (current?.isWhitespace() != true) return false
advance()
}
return true
}
/**
* Check that from the current position to endo of line or end of data
* there are only spaces of there are no characters.
* __Does not advance current position__.
*/
fun isBlankToEndOfLine(): Boolean {
if( end || eol ) return true
var c = col
while( c < currentLine.length )
if( currentLine[c++].isWhitespace() != true ) return false
return true
}
/**
* Get previous char in the current line or null if there is no such char (start of line)
*/
fun prevInLine(): Char? {
if (end || col == 0) return null
return currentLine[col - 1]
}
/**
* return next char in the same line or null if it is line ending.
*/
fun nextInLine(): Char? = if (col + 1 >= currentLine.length) null else currentLine[col + 1]
private val lineSize: List<Int> by lazy { lines.map { it.length + 1 } }
private val offsetOfLine: List<Int> by lazy {
var offset = 0
val result = ArrayList<Int>(lineSize.size)
for (s in lineSize) {
result.add(offset)
offset += s
}
result.add(offset)
result
}
fun posAt(r: Int, c: Int): Pos {
require( r >= 0 && r <= lines.size , {"row not in document bounds"})
if( r == lines.size )
require(c == 0, { "after the document end" })
else {
require( c >= 0 && c <= lines[r].length, {"ourside line $r boundaries ($c should be in ${0..lines[r].length}"})
}
return Pos(r, c, offsetOfLine[r] + c)
}
fun posAt(from: Pos, offset: Int): Pos {
// Actually, it could be faster to navigate from pos, bit not always
return posAt(from.offset + offset)
}
fun posAt(offset: Int): Pos {
var r = 0
while( r < lines.size-1 && offsetOfLine[r+1] < offset ) r++
val c = offset - offsetOfLine[r]
return Pos(r, c, offset)
}
@Suppress("unused")
fun charAt(pos: Pos): Char = text[pos.offset]
@Suppress("unused")
fun slice(range: OpenEndRange<Pos>): String = text.slice(range.start.offset ..< range.endExclusive.offset)
@Suppress("unused")
fun slice(range: ClosedRange<Pos>): String = text.slice(range.start.offset ..< range.endInclusive.offset)
/**
* Find the first occurrence ot the pattern inside a block (in markdown sense). Does not
* change current position.
* Note that pattern could not be spanned to several lines, it should fit entirely in a line
*/
fun findInBlock(pattern: String): Pos? {
var offset = col
var r = row
do {
val i = lines[r].indexOf(pattern, offset)
if (i >= 0) return posAt(r, i)
r++
offset = 0
if (r < lines.size) {
if (lines[r].isEmpty() || lines[r][0].isWhitespace())
break
} else break
} while (true)
return null
}
/**
* Read text from open to closed char (e.g. braces), optionally favoring escape character
* _only con `close` char!_ and _only in the current line_.
* E.g. [current] should `== open`.
* The current position is advanced to the character next after `end` if found, or left intact.
* @return found string or null
*/
fun readBracedInLine(open: Char, close: Char, favorEscapes: Char? = '\\'): String? {
if (current != open) return null
return mark {
val c0 = col + 1
while (true) {
advance()
if (eol) break
if (favorEscapes == current && nextInLine() == close) {
advance()
continue
}
if (current == close) {
return@mark currentLine.substring(c0, col).also { advance() }
}
}
rewind()
null
}
}
fun rangeToCurrent(start: Pos): OpenEndRange<Pos> = start ..< pos()
init {
if (text.isEmpty())
throw IllegalArgumentException("can't create CharSource on empty line")
sync()
}
companion object {
val spaces = " \t".toSet()
}
}
| 2 |
Kotlin
|
0
| 0 |
c2368f81e42351b1f3a21575fcd5101a05b272b9
| 9,364 |
libdownmark
|
Apache License 2.0
|
app/src/main/java/com/anafthdev/musicompose2/feature/artist/artist_list/ArtistListViewModel.kt
|
kafri8889
| 509,012,286 | false |
{"Kotlin": 356863}
|
package com.anafthdev.musicompose2.feature.artist.artist_list
import androidx.lifecycle.viewModelScope
import com.anafthdev.musicompose2.feature.artist.artist_list.environment.IArtistListEnvironment
import com.anafthdev.musicompose2.foundation.viewmodel.StatefulViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class ArtistListViewModel @Inject constructor(
artistListEnvironment: IArtistListEnvironment
): StatefulViewModel<ArtistListState, Unit, Unit, IArtistListEnvironment>(
ArtistListState(),
artistListEnvironment
) {
init {
viewModelScope.launch(environment.dispatcher) {
environment.getAllArtist().collect { artists ->
setState {
copy(
artists = artists
)
}
}
}
}
override fun dispatch(action: Unit) {}
}
| 3 |
Kotlin
|
8
| 40 |
fa8c356aa2967228b91dc68ef99c395be22b73fb
| 845 |
Musicompose-V2
|
Do What The F*ck You Want To Public License
|
app/src/main/java/com/nilhcem/blenamebadge/adapter/MainPagerAdapter.kt
|
ShridharGoel
| 174,675,238 | true |
{"Kotlin": 97167, "Shell": 2629}
|
package com.nilhcem.blenamebadge.adapter
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
class MainPagerAdapter(fragmentManager: FragmentManager, private val fragments: List<Fragment>) :
FragmentStatePagerAdapter(fragmentManager) {
override fun getItem(position: Int): Fragment {
return fragments[position]
}
override fun getCount(): Int {
return fragments.size
}
}
| 0 |
Kotlin
|
0
| 0 |
c11d464c9ecd641eecefca7f23cb1591cded66a7
| 495 |
badge-magic-android
|
Apache License 2.0
|
services/hanke-service/src/main/kotlin/fi/hel/haitaton/hanke/attachment/azure/AzureContainerServiceClient.kt
|
City-of-Helsinki
| 300,534,352 | false |
{"Kotlin": 1853898, "Mustache": 92562, "Shell": 23444, "Batchfile": 5169, "PLpgSQL": 1115, "Dockerfile": 371}
|
package fi.hel.haitaton.hanke.attachment.azure
import com.azure.identity.DefaultAzureCredentialBuilder
import com.azure.storage.blob.BlobServiceClient
import com.azure.storage.blob.BlobServiceClientBuilder
import kotlin.reflect.full.memberProperties
import mu.KotlinLogging
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Profile
private val logger = KotlinLogging.logger {}
@Configuration
@Profile("!test")
class AzureContainerServiceClient(
@Value("\${haitaton.azure.blob.connection-string}") private val connectionString: String?,
@Value("\${haitaton.azure.blob.endpoint}") private val endpoint: String,
) {
@Bean
fun blobServiceClient(): BlobServiceClient {
logger.info { "Creating BlobServiceClient" }
return if (connectionString != null) {
logger.info { "Connecting using a connection string (local development)" }
logger.info { "Connection string is $connectionString" }
BlobServiceClientBuilder().connectionString(connectionString).buildClient()
} else {
logger.info { "Connecting using a default credential provider (cloud environments)" }
logger.info { "Endpoint is $endpoint" }
BlobServiceClientBuilder()
.endpoint(endpoint)
.credential(DefaultAzureCredentialBuilder().build())
.buildClient()
}
}
}
@ConfigurationProperties(prefix = "haitaton.azure.blob")
data class Containers(
val decisions: String,
val hakemusAttachments: String,
val hankeAttachments: String,
) : Iterable<String> {
override fun iterator(): Iterator<String> =
Containers::class.memberProperties.map { it.get(this) as String }.iterator()
}
enum class Container {
HAKEMUS_LIITTEET,
HANKE_LIITTEET,
PAATOKSET,
}
| 9 |
Kotlin
|
5
| 4 |
f0e319fafa2706e7fb5b4a3ad406935a9e59a38d
| 2,046 |
haitaton-backend
|
MIT License
|
app/src/main/java/com/example/libbit/util/AuthenticationManager.kt
|
EcasLai
| 751,912,905 | false |
{"Kotlin": 130129}
|
package com.example.libbit.util
import androidx.navigation.NavController
import com.example.libbit.R
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
object AuthenticationManager {
private lateinit var auth: FirebaseAuth
init {
auth = FirebaseAuth.getInstance()
}
fun getCurrentUser(): FirebaseUser? {
return auth.currentUser
}
fun register(email: String, password: String, navController: NavController, onComplete: (Boolean, String?) -> Unit) {
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
// Sign in successful
onComplete(true, null)
navController.navigate(R.id.homeFragment)
UserManager.setDefaultUsernameIfEmpty()
} else {
// Sign in fail
onComplete(false, task.exception?.message)
}
}
}
fun signIn(email: String, password: String, navController: NavController, onSuccess: () -> Unit, onFailure: (String) -> Unit) {
if (!isValidEmail(email)) {
onFailure("Invalid email format")
return
}
if (password.length < 6) {
onFailure("Password must be at least 6 characters long")
return
}
val auth = FirebaseAuth.getInstance()
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
onSuccess()
navController.navigate(R.id.profileFragment)
} else {
onFailure(task.exception?.message ?: "Sign in failed")
}
}
}
private fun isValidEmail(email: String): Boolean {
val emailRegex = "^[A-Za-z](.*)([@]{1})(.{1,})(\\.)(.{1,})"
return emailRegex.toRegex().matches(email)
}
// fun signInGoogle(email: String, password: String, onComplete: (Boolean, String?) -> Unit){
// auth.signInWithCredential(email, password)
// .addOnCompleteListener() { task ->
// if (task.isSuccessful){
// onComplete(true, null)
// } else{
// onComplete(false, task.exception?.message)
// }
// }
// }
fun signInAsGuest(OnComplete: (Boolean, String?) -> Unit){
auth.signInAnonymously()
.addOnCompleteListener() { task ->
if (task.isSuccessful){
OnComplete(true, null)
} else{
OnComplete(false, task.exception?.message)
}
}
}
fun signOutFireAuth(navController: NavController) {
auth.signOut()
}
}
| 0 |
Kotlin
|
0
| 1 |
caab273c63790a3e5ae569eb360c5a573d6e054b
| 2,895 |
Libbit
|
MIT License
|
src/main/kotlin/me/centralhardware/znatoki/telegram/statistic/entity/Services.kt
|
centralhardware
| 867,806,349 | false |
{"Kotlin": 126182, "Dockerfile": 572}
|
package me.centralhardware.znatoki.telegram.statistic.entity
import kotliquery.Row
import me.centralhardware.znatoki.telegram.statistic.eav.Property
data class Services(
var id: Long,
var key: String,
var name: String,
var allowMultiplyClients: Boolean,
var properties: List<Property> = listOf()
)
fun Row.parseServices() =
Services(long("id"), string("key"), string("name"), boolean("allow_multiply_clients"))
| 0 |
Kotlin
|
0
| 0 |
b822eb63092ee035ae657928b34aa4f56effcca2
| 438 |
StudyCenterStatistic
|
MIT License
|
src/main/kotlin/com/jacobtread/alto/utils/nbt/NBTBase.kt
|
AltoClient
| 449,599,250 | false |
{"Kotlin": 157065}
|
package com.jacobtread.alto.utils.nbt
import com.jacobtread.alto.utils.nbt.types.NBTCompound
import com.jacobtread.alto.utils.nbt.types.*
import java.io.DataInput
import java.io.DataOutput
import java.io.IOException
const val END: Byte = 0
const val BYTE: Byte = 1
const val SHORT: Byte = 2
const val INT: Byte = 3
const val LONG: Byte = 4
const val FLOAT: Byte = 5
const val DOUBLE: Byte = 6
const val BYTE_ARRAY: Byte = 7
const val STRING: Byte = 8
const val LIST: Byte = 9
const val COMPOUND: Byte = 10
const val INT_ARRAY: Byte = 11
const val PRIMITIVE: Byte = 99
abstract class NBTBase {
abstract val id: Byte
@Throws(IOException::class)
abstract fun write(output: DataOutput)
@Throws(IOException::class)
abstract fun read(input: DataInput, depth: Int, sizeTracker: NBTSizeTracker)
abstract fun copy(): NBTBase
override fun equals(other: Any?): Boolean {
if (other !is NBTBase) return false
return other.id == id
}
override fun hashCode(): Int = id.toInt()
open fun asString(): String = toString()
open fun hasNoTags(): Boolean = false
abstract override fun toString(): String
companion object {
val TYPES = arrayOf(
"END", "BYTE", "SHORT", "INT", "LONG", "FLOAT", "DOUBLE",
"BYTE[]", "STRING", "LIST", "COMPOUND", "INT[]"
)
fun createByType(id: Byte) = when (id) {
END -> NBTEnd()
BYTE -> NBTByte()
SHORT -> NBTShort()
INT -> NBTInt()
LONG -> NBTLong()
FLOAT -> NBTFloat()
DOUBLE -> NBTDouble()
BYTE_ARRAY -> NBTByteArray()
STRING -> NBTString()
LIST -> NBTList()
COMPOUND -> NBTCompound()
INT_ARRAY -> NBTIntArray()
else -> throw RuntimeException("Unknown NBT tag type $id")
}
}
}
| 0 |
Kotlin
|
0
| 1 |
ea9410cff59a810edcff0b782f362b73f1c9825f
| 1,882 |
Utilities
|
MIT License
|
app/src/main/java/com/grevi/aywapet/ui/viewmodel/ProfileViewModel.kt
|
tomorisakura
| 331,615,264 | false | null |
package com.grevi.aywapet.ui.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.grevi.aywapet.db.entity.Users
import com.grevi.aywapet.repository.RepositoryImpl
import com.grevi.aywapet.utils.State
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class ProfileViewModel @Inject constructor(private val repositoryImpl: RepositoryImpl) : ViewModel() {
private val _usersLocalFlow = MutableStateFlow<State<MutableList<Users>>>(State.Data)
val getUserLocalFlow : MutableStateFlow<State<MutableList<Users>>> get() = _usersLocalFlow
init {
getLocalUser()
}
private fun getLocalUser() {
viewModelScope.launch {
repositoryImpl.getLocalUser().collect {
_usersLocalFlow.value = State.Loading()
try {
_usersLocalFlow.value = State.Success(it)
}catch (e : Exception) {
_usersLocalFlow.value = State.Error(e)
}
}
}
}
}
| 0 |
Kotlin
|
0
| 1 |
8afb8d57ae1f1cff4da9f638b1eb2b00e89d75cb
| 1,197 |
aywa-pet
|
MIT License
|
app/src/main/java/com/mrostami/geckoincompose/domain/usecases/SimplePriceUseCase.kt
|
MosRos
| 639,811,989 | false | null |
package com.mrostami.geckoincompose.domain.usecases
import com.mrostami.geckoincompose.domain.CoinDetailsRepository
import com.mrostami.geckoincompose.domain.base.FlowUseCase
import com.mrostami.geckoincompose.domain.base.Result
import com.mrostami.geckoincompose.model.SimplePriceInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class SimplePriceUseCase @Inject constructor(
private val coinDetailsRepository: CoinDetailsRepository
) : FlowUseCase<String, SimplePriceInfo>(coroutineDispatcher = Dispatchers.IO){
override fun execute(parameters: String, refresh: Boolean): Flow<Result<SimplePriceInfo>> {
return coinDetailsRepository.getSimplePriceInfo(coinId = parameters)
}
}
| 0 |
Kotlin
|
5
| 17 |
8e396051f6acc17fa2eba8745285fdf800832c60
| 756 |
Geckoin-Compose
|
Apache License 2.0
|
app/src/main/java/io/github/dnloop/noteapp/data/TagDao.kt
|
dnloop
| 291,766,075 | false | null |
package io.github.dnloop.noteapp.data
import androidx.lifecycle.LiveData
import androidx.room.*
@Dao
abstract class TagDao {
/**
* Adds a new Tag
*
* @param tag new tag value to write
*/
@Insert
abstract fun insert(tag: Tag): Long
/**
* Adds a List of Tags
* @param tags to be written.
*/
@Insert
abstract fun insertAll(tags: List<Tag>): List<Long>
/**
* Adds a new Tag with TimeStamp
*
* @param tag new tag value to write
*/
fun insertWithTimestamp(tag: Tag) : Long {
return insert(tag.apply {
createdAt = System.currentTimeMillis()
modifiedAt = System.currentTimeMillis()
})
}
/**
* When updating a row with a value already set in a column,
* replaces the old value with the new one.
*
* @param tag new value to write
*/
@Update
abstract fun update(tag: Tag)
fun updateWithTimestamp(tag: Tag) {
update(tag.apply {
modifiedAt = System.currentTimeMillis()
})
}
/**
* Selects and returns the row that matches the supplied noteId.
*
* @param key id
*/
@Query("SELECT * from tag WHERE tag_id = :key")
abstract fun get(key: Long): LiveData<Tag>
/**
* Delete a single value from the table.
*
* @param tag selected for deletion
*/
@Delete
abstract fun delete(tag: Tag)
/**
* Deletes all values from the table.
* This does not delete the table, only its contents.
*/
@Query("DELETE FROM Tag")
abstract fun clear()
/**
* Selects and returns all rows in the table,
* sorted by id in descending order.
*/
@Query("SELECT * FROM Tag ORDER BY tag_id DESC")
abstract fun getAllTags(): LiveData<List<Tag>>
/**
* Selects and returns the latest Category.
*/
@Query("SELECT * FROM Tag ORDER BY tag_id DESC LIMIT 1")
abstract fun getLatest(): Tag?
}
| 0 |
Kotlin
|
0
| 1 |
0ee1d817651292336b7846c0dec79fb3f21410d7
| 1,989 |
NoteApp
|
MIT License
|
core/model/src/commonMain/kotlin/com/cdcoding/model/solana/SolanaPrioritizationFee.kt
|
Christophe-DC
| 822,562,468 | false |
{"Kotlin": 728291, "Ruby": 4739, "Swift": 617}
|
package com.cdcoding.model.solana
import kotlinx.serialization.Serializable
@Serializable
data class SolanaPrioritizationFee (
val prioritizationFee: Int
)
| 0 |
Kotlin
|
0
| 0 |
e8bff388ccebb64e6810d62a1ea4dddfabe83c71
| 160 |
secureWallet
|
Apache License 2.0
|
vk-api-generated/src/main/kotlin/name/anton3/vkapi/generated/account/objects/PushSettings.kt
|
Anton3
| 159,801,334 | true |
{"Kotlin": 1382186}
|
@file:Suppress("unused", "SpellCheckingInspection")
package name.anton3.vkapi.generated.account.objects
import name.anton3.vkapi.vktypes.BoolInt
/**
* No description
*
* @property disabled Information whether notifications are disabled
* @property disabledUntil Time until that notifications are disabled in Unixtime
* @property settings No description
* @property conversations No description
*/
data class PushSettings(
val disabled: BoolInt? = null,
val disabledUntil: Long? = null,
val settings: PushParams? = null,
val conversations: PushConversations? = null
)
| 2 |
Kotlin
|
0
| 8 |
773c89751c4382a42f556b6d3c247f83aabec625
| 593 |
kotlin-vk-api
|
MIT License
|
src/main/kotlin/thuan/handsome/core/utils/Logger.kt
|
duckladydinh
| 227,356,261 | false |
{"Fortran": 148795, "Kotlin": 70813, "C": 5608, "Makefile": 1992, "SWIG": 381, "Shell": 257}
|
package thuan.handsome.core.utils
import com.google.common.flogger.FluentLogger
import com.google.common.flogger.LoggerConfig
import java.util.logging.ConsoleHandler
import java.util.logging.Level.INFO as LEVEL
class Logger {
companion object {
private val FLOGGER = FluentLogger.forEnclosingClass()!!
init {
System.setProperty("java.util.logging.SimpleFormatter.format", "%4\$s: %5\$s%n")
with(LoggerConfig.of(FLOGGER)) {
level = LEVEL
addHandler(ConsoleHandler().apply {
level = LEVEL
})
}
}
fun warning(): FluentLogger.Api {
return FLOGGER.atWarning()
}
fun fine(): FluentLogger.Api {
return FLOGGER.atFine()
}
}
}
| 0 |
Fortran
|
0
| 0 |
e3f3777734a08758734ef645ea5b53e03c31e278
| 816 |
KotlinML
|
MIT License
|
common/list-api/src/commonMain/kotlin/com/a_blekot/shlokas/common/list_api/ListState.kt
|
a-blekot
| 522,545,932 | false | null |
package com.a_blekot.shlokas.common.list_api
import com.a_blekot.shlokas.common.data.ListConfig
import com.arkivanov.essenty.parcelable.Parcelable
import com.arkivanov.essenty.parcelable.Parcelize
@Parcelize
data class ListState(
val config: ListConfig,
val availableLists: List<ListPresentation> = emptyList(),
val locale: String,
val hasChanges: Boolean = false,
val shouldShowTutorial: Boolean = true,
val shouldShowPreRating: Boolean = false
): Parcelable
| 0 |
Kotlin
|
0
| 2 |
3f281ac4c5d7d2593b85c9ed1bb656ea8b34f9f1
| 486 |
memorize_shloka
|
Apache License 2.0
|
src/test/kotlin/com/grudus/planshboard/utils/MockitoUtils.kt
|
grudus
| 115,259,708 | false | null |
package com.grudus.planshboard.utils
import org.mockito.ArgumentMatchers
fun <T : Any> safeEq(value: T): T = ArgumentMatchers.eq(value) ?: value
| 0 |
Kotlin
|
0
| 1 |
1b9fd909a75d5b0883e8ff39be9aa299bf0ff3ff
| 147 |
Planshboard
|
Apache License 2.0
|
src/main/kotlin/net/jspiner/epubstream/parser/NcxParser.kt
|
JSpiner
| 148,455,163 | false |
{"HTML": 406789, "Kotlin": 44995, "CSS": 33288}
|
package net.jspiner.epubstream.parser
import net.jspiner.epubstream.dto.Ncx
import net.jspiner.epubstream.evaluateNode
import net.jspiner.epubstream.evaluateNodeList
import org.w3c.dom.Document
fun parseNcx(document: Document, tocPath: String): Ncx {
return Ncx(
parseHead(evaluateNodeList(document, "/ncx/head/meta")),
parseDocTitle(evaluateNode(document, "/ncx/docTitle")!!),
parseDocAuthor(evaluateNode(document, "/ncx/docAuthor")),
parseNavMap(document, tocPath)
)
}
| 0 |
HTML
|
2
| 4 |
1b09c36c87c68f535634d7571a361f3725687943
| 512 |
epub-stream
|
MIT License
|
src/main/kotlin/views/FilterPanel.kt
|
kirilenkobm
| 668,817,148 | false | null |
package views
import state.AppState
import java.awt.BorderLayout
import java.awt.Color
import java.awt.Dimension
import javax.swing.BorderFactory
import javax.swing.JButton
import javax.swing.JPanel
import javax.swing.JTextField
import javax.swing.event.DocumentEvent
import javax.swing.event.DocumentListener
// TODO: implement update on filter
class FilterPanel {
private val filterPanel = JPanel()
init {
setupFilterPanel()
}
private fun setupFilterPanel() {
val filterField = JTextField(AppState.currentExtensionFilter).apply {
border = BorderFactory.createEmptyBorder()
}
filterPanel.layout = BorderLayout()
filterPanel.add(filterField, BorderLayout.CENTER)
filterPanel.preferredSize = Dimension(200, filterField.preferredSize.height)
filterPanel.minimumSize = Dimension(200, filterField.preferredSize.height)
filterPanel.maximumSize = Dimension(200, filterField.preferredSize.height)
// Set the maximum height to the preferred height to prevent vertical growth
filterPanel.maximumSize = Dimension(filterPanel.maximumSize.width, filterPanel.preferredSize.height)
// Add a document listener to update AppState.currentFilter whenever the text changes
filterField.document.addDocumentListener(object : DocumentListener {
override fun insertUpdate(e: DocumentEvent?) {
AppState.updateFilter(filterField.text)
}
override fun removeUpdate(e: DocumentEvent?) {
AppState.updateFilter(filterField.text)
}
override fun changedUpdate(e: DocumentEvent?) {
AppState.updateFilter(filterField.text)
}
})
// clear filter button
val clearFilterButton = JButton(IconManager.backSpaceIcon).apply {
isContentAreaFilled = false // transparent
isBorderPainted = false // remove border
isFocusPainted = false // rm focus highlight
}
clearFilterButton.addActionListener {
filterField.text = ""
AppState.updateFilter("")
}
filterPanel.add(clearFilterButton, BorderLayout.EAST)
filterPanel.border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLACK)
filterPanel.background = Color(255, 255, 255, 255)
}
fun getPanel(): JPanel {
return filterPanel
}
}
| 0 |
Kotlin
|
0
| 0 |
f12dc4ad0a0f3783b86b3e5b27020eb9abc2206b
| 2,444 |
DirExplorer
|
Apache License 2.0
|
src/jsMain/kotlin/three/TorusKnotGeometry.module_three.kt
|
baaahs
| 174,897,412 | false |
{"Kotlin": 3355751, "C": 1529197, "C++": 661364, "GLSL": 412680, "JavaScript": 62186, "HTML": 55088, "CMake": 30499, "CSS": 4340, "Shell": 2381, "Python": 1450}
|
@file:JsModule("three")
@file:JsNonModule
@file:Suppress("PackageDirectoryMismatch")
package three.js
external interface `T$30` {
var radius: Number
var tube: Number
var tubularSegments: Number
var radialSegments: Number
var p: Number
var q: Number
}
open external class TorusKnotGeometry(radius: Number = definedExternally, tube: Number = definedExternally, tubularSegments: Number = definedExternally, radialSegments: Number = definedExternally, p: Number = definedExternally, q: Number = definedExternally) : Geometry {
override var type: String
open var parameters: `T$30`
}
| 113 |
Kotlin
|
12
| 40 |
4dd92e5859d743ed7186caa55409f676d6408c95
| 612 |
sparklemotion
|
MIT License
|
src/commonTest/kotlin/TestGateway.kt
|
andylamax
| 244,281,735 | false | null |
import tz.co.asoft.email.Email
import tz.co.asoft.email.entities.EmailMessage
import tz.co.asoft.email.gateway.IEmailGateway
import tz.co.asoft.io.File
import tz.co.asoft.persist.repo.IRepo
class TestGateway(override val repo: IRepo<EmailMessage>) : IEmailGateway {
override suspend fun send(sender: String, receivers: List<Email>, subject: String?, body: String, attachments: List<File>): EmailMessage {
return EmailMessage(sender, receivers.map { it.value }, subject, body).apply {
println("New Email\nFrom: $sender\nTo: ${receivers.joinToString(",") { it.value }}")
println("Subject: ${subject ?: "No Subject"}\n$body")
println("Attachments: ${attachments.joinToString(",") { it.name }}")
uid = repo.all().size.toString()
repo.create(this)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
e3e93445cb76fdc501840146febf43c537bc26e2
| 833 |
asoft-email-gateway
|
The Unlicense
|
sora-editor/src/main/java/com/bluewhaleyt/sora_editor/CustomCompletionAdapter.kt
|
BlueWhaleYT
| 665,099,127 | false | null |
package com.bluewhaleyt.sora_editor
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.bluewhaleyt.common.common.getLayoutInflater
import com.bluewhaleyt.common.common.px
import io.github.rosemoe.sora.widget.component.EditorCompletionAdapter
class CustomCompletionAdapter : EditorCompletionAdapter() {
private var itemHeight: Int = 45
override fun getView(position: Int, convertView: View?, parent: ViewGroup?, isCurrentCursorPosition: Boolean): View {
val view = parent!!.context.getLayoutInflater().inflate(R.layout.layout_completion_list_item, parent, false) ?: null
val item = getItem(position)
val holder = ViewHolder(view!!)
holder.tvCompletionLabel.apply {
text = item.label
}
holder.tvCompletionDesc.apply {
text = item.desc
}
holder.imgCompletionIcon.apply {
setImageDrawable(item.icon)
}
return view
}
override fun getItemHeight(): Int {
return itemHeight.px
}
fun setItemHeight(itemHeight: Int) = apply {
this.itemHeight = itemHeight
}
private class ViewHolder(itemView: View) {
val tvCompletionLabel = itemView.findViewById<TextView>(R.id.tv_completion_label)
val tvCompletionDesc = itemView.findViewById<TextView>(R.id.tv_completion_desc)
val tvCompletionId = itemView.findViewById<TextView>(R.id.tv_completion_id)
val imgCompletionIcon = itemView.findViewById<ImageView>(R.id.img_completion_icon)
}
}
| 0 |
Kotlin
|
0
| 1 |
24cad14d625908cb4d22a73e9ce07db40327d346
| 1,604 |
WhaleUtils
|
MIT License
|
app/src/main/java/com/kiyotaka/jetpackdemo/common/BaseApplication.kt
|
Zzy9797
| 347,554,269 | false | null |
package com.kiyotaka.jetpackdemo.common
import android.app.Application
import android.content.Context
open class BaseApplication : Application() {
override fun onCreate() {
super.onCreate()
context = this
}
companion object {
lateinit var context: Context
}
}
| 0 |
Kotlin
|
0
| 0 |
74007e514212d26a91ec4081345311cb9bd5626e
| 302 |
projectVideo
|
Apache License 2.0
|
app/src/main/java/com/frafio/myfinance/utils/SharedPreferencesUtils.kt
|
francescofiorella
| 360,818,457 | false |
{"Kotlin": 200994}
|
package com.frafio.myfinance.utils
import android.content.SharedPreferences
import com.frafio.myfinance.MyFinanceApplication.Companion.DYNAMIC_COLOR_KEY
import com.frafio.myfinance.MyFinanceApplication.Companion.MONTHLY_BUDGET_KEY
fun getSharedDynamicColor(sharedPreferences: SharedPreferences): Boolean {
return sharedPreferences.getBoolean(DYNAMIC_COLOR_KEY, false)
}
fun setSharedDynamicColor(sharedPreferences: SharedPreferences, activate: Boolean) {
sharedPreferences.edit().putBoolean(DYNAMIC_COLOR_KEY, activate).apply()
}
fun getSharedMonthlyBudget(sharedPreferences: SharedPreferences): Double {
return sharedPreferences.getFloat(MONTHLY_BUDGET_KEY, 0.0F).toDouble()
}
fun setSharedMonthlyBudget(sharedPreferences: SharedPreferences, value: Double) {
sharedPreferences.edit().putFloat(MONTHLY_BUDGET_KEY, value.toFloat()).apply()
}
| 0 |
Kotlin
|
0
| 1 |
ba666bca8e75cc9fed1fd798e8e91b0b006f963a
| 861 |
MyFinance
|
MIT License
|
code-challenge-solution/CreateAccountViewModel.kt
|
droidcon-academy
| 630,766,635 | false | null |
package com.droidcon.formvalidation.createaccount
import androidx.lifecycle.ViewModel
import com.droidcon.formvalidation.createaccount.validation.CreateAccountParams
import com.droidcon.formvalidation.createaccount.validation.ValidatorFactory
import com.droidcon.formvalidation.validator.InputValidator
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
class CreateAccountViewModel(
private val validators: Map<CreateAccountParams, InputValidator> = ValidatorFactory.create()
) : ViewModel() {
private val _state = MutableStateFlow(CreateAccountState())
val state: StateFlow<CreateAccountState> = _state
fun onEvent(event: CreateAccountEvent) {
when (event) {
is CreateAccountEvent.NameChanged -> _state.value = _state.value.copy(name = event.name)
is CreateAccountEvent.EmailChanged -> _state.value =
_state.value.copy(email = event.email)
is CreateAccountEvent.PasswordChanged -> _state.value =
_state.value.copy(password = event.password)
is CreateAccountEvent.DateOfBirthChanged -> _state.value =
_state.value.copy(dateOfBirth = event.dateOfBirth)
CreateAccountEvent.CreateAccount -> {
if (areInputsValid()) {
createAccount()
}
}
}
}
private fun areInputsValid(): Boolean {
val nameError = validators[CreateAccountParams.FULL_NAME]?.validate(_state.value.name)
val emailError = validators[CreateAccountParams.EMAIL]?.validate(_state.value.email)
val passwordError =
validators[CreateAccountParams.PASSWORD]?.validate(_state.value.password)
val dateOfBirthError =
validators[CreateAccountParams.DATE_OF_BIRTH]?.validate(_state.value.dateOfBirth)
val hasError = listOf(
nameError,
emailError,
passwordError,
dateOfBirthError
).any { it?.isValid == false }
_state.value = _state.value.copy(
nameError = nameError?.errorMessage,
emailError = emailError?.errorMessage,
passwordError = passwordError?.errorMessage,
dateOfBirthError = dateOfBirthError?.errorMessage
)
return hasError.not()
}
private fun createAccount() {
//@Todo Create Account
}
}
| 0 |
Kotlin
|
0
| 0 |
32390e575b4190d1d760bc8d74bf857b7c4b65fa
| 2,417 |
cbc-android-form-validation-compose-study-materials
|
Apache License 2.0
|
app/src/main/java/pl/polsl/workflow/manager/client/model/mapper/UserMapper.kt
|
SzymonGajdzica
| 306,075,061 | false | null |
package pl.polsl.workflow.manager.client.model.mapper
import pl.polsl.workflow.manager.client.model.data.Role
import pl.polsl.workflow.manager.client.model.data.User
import pl.polsl.workflow.manager.client.model.data.UserPatch
import pl.polsl.workflow.manager.client.model.data.UserPost
import pl.polsl.workflow.manager.client.model.remote.data.UserApiModel
import pl.polsl.workflow.manager.client.model.remote.data.UserApiModelPatch
import pl.polsl.workflow.manager.client.model.remote.data.UserApiModelPost
fun UserApiModel.map(): User {
return User(
id = id,
username = username,
role = Role.fromString(role),
enabled = enabled
)
}
fun UserPost.map(): UserApiModelPost {
return UserApiModelPost(
username = username,
role = Role.toString(role),
password = <PASSWORD>
)
}
fun UserPatch.map(): UserApiModelPatch {
return UserApiModelPatch(
enabled = enabled
)
}
| 0 |
Kotlin
|
0
| 0 |
93c99cc67c7af0bc55ca8fb03f077cdd363cb7e8
| 970 |
workflow-manager-client
|
MIT License
|
app/src/main/java/com/example/bookworms/activities/LoginActivity.kt
|
JosephOri
| 804,031,334 | false |
{"Kotlin": 57005}
|
package com.example.bookworms.activities
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.bookworms.R
import com.example.bookworms.utils.Utils
import com.google.android.material.textfield.TextInputEditText
import com.google.firebase.Firebase
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.auth
import com.google.android.material.progressindicator.CircularProgressIndicator
class LoginActivity : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
private lateinit var cpi : CircularProgressIndicator
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
auth = Firebase.auth
if (auth.currentUser != null){
Log.d("LoginActivity", "User is already logged in")
val mainActivityIntent = Intent(applicationContext, MainActivity::class.java)
startActivity(mainActivityIntent)
}
addLinkToSignUp()
cpi = findViewById(R.id.loginCircularProgressIndicator)
val emailField: TextInputEditText = findViewById(R.id.activity_login_email_input)
val passwordField: TextInputEditText = findViewById(R.id.activity_login_password_input)
val loginButton = findViewById<Button>(R.id.signupButton)
loginButton.setOnClickListener {
cpi.visibility = View.VISIBLE
logInUser(emailField, passwordField)
}
}
private fun logInUser(
emailField: TextInputEditText,
passwordField: TextInputEditText
) {
val email = emailField.text.toString()
val password = passwordField.text.toString()
val isInputValid = validateSignIn(email, password)
if (!isInputValid) {
return
}
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
cpi.visibility = View.INVISIBLE
if (task.isSuccessful) {
Log.d("LoginActivity", "signInWithEmail:success")
val user = auth.currentUser
val mainActivityIntent = Intent(applicationContext, MainActivity::class.java)
startActivity(mainActivityIntent)
} else {
Toast.makeText(baseContext, "invalid credentials, please try again.",
Toast.LENGTH_SHORT).show()
Log.w("LoginActivity", "signInWithEmail:failure", task.exception)
}
}
}
private fun validateSignIn(email: String, password: String): Boolean {
if(email.isEmpty() || password.isEmpty()){
Toast.makeText(this, "Please fill in all fields", Toast.LENGTH_SHORT).show()
return false
}
if(!Utils.isEmailValid(email)){
Toast.makeText(this, "Please enter a valid email", Toast.LENGTH_SHORT).show()
return false
}
return true
}
private fun addLinkToSignUp() {
val linkToSignUp: TextView = findViewById(R.id.linkToSignup)
linkToSignUp.setOnClickListener {
val intent = Intent(this, SignupActivity::class.java)
startActivity(intent)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
07bbdb145312800adf0be373c4580af600ef0de3
| 3,484 |
BookWorms
|
MIT License
|
customer/src/main/java/com/kukus/customer/message/ActivityMessage.kt
|
anas-abdrahman
| 457,402,197 | false |
{"Kotlin": 745237, "Java": 79801}
|
package com.kukus.customer.message
import android.annotation.SuppressLint
import android.app.FragmentTransaction
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.support.constraint.ConstraintLayout
import android.support.v7.app.AppCompatActivity
import android.text.format.DateFormat
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.firebase.ui.database.FirebaseListAdapter
import com.firebase.ui.database.FirebaseListOptions
import com.kukus.customer.R
import com.kukus.customer.dialog.DialogContact
import com.kukus.library.FirebaseUtils.Companion.getContact
import com.kukus.library.FirebaseUtils.Companion.getUserId
import com.kukus.library.model.Message
import kotlinx.android.synthetic.main.activity_message.*
class ActivityMessage : AppCompatActivity() {
@SuppressLint("CheckResult")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_message)
displayNewsMessage()
contact.setOnClickListener {
val fragmentManager = supportFragmentManager
val newFragment = DialogContact()
val bundle = Bundle()
bundle.putBoolean("show", false)
newFragment.arguments = bundle
val transaction = fragmentManager?.beginTransaction()
if (transaction != null) {
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
transaction.add(android.R.id.content, newFragment).addToBackStack(null).commit()
}
}
}
private fun displayNewsMessage(){
val options = FirebaseListOptions.Builder<Message>()
.setLayout(R.layout.list_message)
.setQuery(getContact(getUserId), Message::class.java)
.setLifecycleOwner(this)
.build()
val mAdapter = object : FirebaseListAdapter<Message>(options) {
override fun getItem(position: Int): Message {
return super.getItem(count - 1 - position)
}
override fun populateView(v: View, model: Message, position: Int) {
empty.visibility = View.GONE
progressbar.visibility = View.GONE
val layout = v.findViewById(R.id.layout) as ConstraintLayout
val name = v.findViewById(R.id.name) as TextView
val image = v.findViewById(R.id.img) as ImageView
val message = v.findViewById(R.id.message) as TextView
val date = v.findViewById(R.id.date) as TextView
val read = v.findViewById(R.id.read) as TextView
val inbox = v.findViewById(R.id.inbox) as TextView
name.text = model.title
message.text = model.text
date.text = DateFormat.format("dd-MM-yyyy", model.time).toString()
if(!model.read && model.user_to == getUserId){
read.visibility = View.VISIBLE
}else{
read.visibility = View.GONE
}
if(model.user_to == getUserId){
image.setImageResource(R.drawable.ic_inbox)
inbox.setText("inbox")
inbox.setTextColor(Color.parseColor("#444444"))
}else{
image.setImageResource(R.drawable.ic_outbox)
inbox.setText("send")
inbox.setTextColor(Color.parseColor("#2E87E6"))
}
if(!model.read && model.user_to == getUserId)
{
inbox.setText("NEW")
inbox.setTextColor(Color.parseColor("#32c360"))
}
layout.setOnClickListener {
val fragmentManager = supportFragmentManager
val newFragment = DialogContact()
val bundle = Bundle()
bundle.putString("title", model.title)
bundle.putString("email", model.email)
bundle.putString("message", model.text)
bundle.putString("user_id", model.user_id)
bundle.putBoolean("show", true)
newFragment.arguments = bundle
val transaction = fragmentManager?.beginTransaction()
if (transaction != null) {
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
transaction.add(android.R.id.content, newFragment).addToBackStack(null).commit()
if(!model.read && model.user_to == getUserId){
getContact(getUserId).child(model.id).child("read").setValue(true)
}
}
}
}
}
list_of_news.adapter = mAdapter
Handler().postDelayed({
if(mAdapter.count == 0){
progressbar.visibility = View.GONE
empty.visibility = View.VISIBLE
}
}, 1000)
}
}
| 0 |
Kotlin
|
0
| 0 |
a5961fd9c4061246c94c603ea5027f82934b59e8
| 5,215 |
food-order-and-delivery
|
MIT License
|
prj-common/src/jsMain/kotlin/keyboard/HotkeyHandler.kt
|
simonegiacomelli
| 473,571,649 | false |
{"Kotlin": 328273, "HTML": 123796, "TSQL": 4632, "CSS": 1467, "Shell": 301}
|
package keyboard
import kotlinx.browser.window
import org.w3c.dom.events.Event
import org.w3c.dom.events.EventTarget
import org.w3c.dom.events.KeyboardEvent
val HotkeyWindow by lazy { Hotkey(window) }
fun Hotkey(element: EventTarget, log_prefix: String? = null) =
HotkeyHandler({ element.addEventListener("keydown", it) }, log_prefix)
class HotkeyHandler(
addKeydownHandler: ((Event) -> Unit) -> Unit,
var log_prefix: String? = null,
) {
private val handlers = mutableMapOf<String, (KeyboardEvent) -> Unit>()
init {
addKeydownHandler(::on_keydown)
}
// see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values
/**
* See https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values
*/
fun add(vararg hotkey: String, callback: (KeyboardEvent) -> Unit): HotkeyHandler {
hotkey.forEach { handlers[it] = callback }
return this
}
private fun on_keydown(event: Event) {
if (event !is KeyboardEvent) return
var key = ""
if (event.ctrlKey) key += "CTRL-"
if (event.shiftKey) key += "SHIFT-"
if (event.altKey) key += "ALT-"
if (event.metaKey) key += "META-"
key += event.key.run { if (length == 1) uppercase() else this }
val handle = handlers[key]
if (log_prefix != null) println("$log_prefix $key" + if (handle != null) " (handler found)" else "")
handle?.invoke(event)
}
}
| 0 |
Kotlin
|
1
| 0 |
e31569d68eeea3ec732fcc3d27f0cdf66836c951
| 1,477 |
kotlin-mpp-starter
|
Apache License 2.0
|
app/src/main/kotlin/com/alish/boilerplate/di/RepositoriesModule.kt
|
TheAlisher
| 338,914,674 | false |
{"Kotlin": 68634}
|
package com.alish.boilerplate.di
import com.alish.boilerplate.data.repositories.FooRepositoryImpl
import com.alish.boilerplate.domain.repositories.FooRepository
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
abstract class RepositoriesModule {
@Binds
abstract fun bindFooRepository(
repositoryImpl: FooRepositoryImpl
): FooRepository
}
| 0 |
Kotlin
|
9
| 54 |
474de0d5f8e5f116f68cdb71753badd5d26cbf36
| 476 |
Boilerplate-Android
|
Apache License 2.0
|
src/test/kotlin/io/opengood/data/jpa/provider/MatchAllDataProviderTest.kt
|
opengoodio
| 372,639,748 | false | null |
package io.opengood.data.jpa.provider
import data.MatchAllDataProviderTestInput
import io.opengood.data.jpa.provider.support.AbstractDataProviderTest
import org.springframework.beans.factory.annotation.Autowired
class MatchAllDataProviderTest(@Autowired override val testInput: MatchAllDataProviderTestInput) :
AbstractDataProviderTest()
| 0 |
Kotlin
|
0
| 0 |
f1402d3043cf12f006d448646a6078299939d8b3
| 344 |
jpa-data-provider
|
MIT License
|
app/src/main/java/com/tis/jetpackcompose_twitter/presentation/screens/main/MainActivity.kt
|
Tislami
| 621,755,359 | false | null |
package com.tis.jetpackcompose_twitter.presentation.screens.main
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import com.tis.jetpackcompose_twitter.presentation.ui.theme.JetpackCompose_TwitterTheme
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
JetpackCompose_TwitterTheme {
AppNavigation()
}
}
}
}
| 0 |
Kotlin
|
0
| 0 |
75abf8c998bb04e6c863155fc1b9f7b76c3c869d
| 602 |
JetpackCompose_Twitter
|
MIT License
|
misk/src/main/kotlin/misk/web/extractors/FormValueFeatureBinding.kt
|
cashapp
| 113,107,217 | false |
{"Kotlin": 3843790, "TypeScript": 232251, "Java": 83564, "JavaScript": 5073, "Shell": 3462, "HTML": 1536, "CSS": 58}
|
package misk.web.extractors
import misk.Action
import misk.web.FeatureBinding
import misk.web.FeatureBinding.Claimer
import misk.web.FeatureBinding.Subject
import misk.web.FormValue
import misk.web.PathPattern
import kotlin.reflect.KClass
import kotlin.reflect.KParameter
/** Binds parameters annotated [FormValue] to the request body using form encoding. */
internal class FormValueFeatureBinding<T : Any>(
private val parameter: KParameter,
private val formAdapter: FormAdapter<T>
) : FeatureBinding {
override fun beforeCall(subject: Subject) {
val requestBody = subject.httpCall.takeRequestBody()!!
val formData = FormData.decode(requestBody)
subject.setParameter(parameter, formAdapter.fromFormData(formData))
}
companion object Factory : FeatureBinding.Factory {
override fun create(
action: Action,
pathPattern: PathPattern,
claimer: Claimer
): FeatureBinding? {
val parameter = action.parameterAnnotatedOrNull<FormValue>() ?: return null
if (parameter.type.classifier !is KClass<*>) return null
val kClass = parameter.type.classifier as KClass<*>
val formAdapter = FormAdapter.create(kClass) ?: return null
claimer.claimRequestBody()
claimer.claimParameter(parameter)
return FormValueFeatureBinding(parameter, formAdapter)
}
}
}
| 169 |
Kotlin
|
169
| 400 |
13dcba0c4e69cc2856021270c99857e7e91af27d
| 1,337 |
misk
|
Apache License 2.0
|
app/src/main/java/com/example/moviebrowser/rView/TvAdapter.kt
|
HeartArmy
| 544,012,842 | false |
{"Kotlin": 16180}
|
package com.example.moviebrowser.rView
class TvAdapter {
}
| 0 |
Kotlin
|
0
| 0 |
536c527131c3ab9f61dbb1c70a0a9dd245b270ae
| 59 |
MovieBrowser
|
Apache License 2.0
|
conductor-dagger-sample-moshi/src/main/java/com/jshvarts/mosbymvp/domain/GithubRepo.kt
|
jshvarts
| 111,547,727 | false | null |
package com.jshvarts.mosbymvp.domain
import android.os.Parcelable
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import kotlinx.android.parcel.Parcelize
@Parcelize
@JsonClass(generateAdapter = true)
data class GithubRepo(
val name: String,
val owner: Owner,
@Json(name = "stargazers_count") val stars: Int) : Parcelable
| 1 |
Kotlin
|
6
| 28 |
b982ee2683d8585c35090a1b9acb5ffaa61c0dd9
| 365 |
MosbyMVP
|
Apache License 2.0
|
src/test/kotlin/elementaryMath/Summation.kt
|
cia-exe
| 331,877,092 | false | null |
package elementaryMath
import TimingExtension
import TreeNode
import getMethodName
import log
import org.junit.jupiter.api.*
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.junit.jupiter.api.TestMethodOrder
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation
@ExtendWith(TimingExtension::class)
@TestMethodOrder(OrderAnnotation::class)
internal class Summation {
companion object {
init {
fun fnR(x: Int): Int = if (x == 0) 0 else fnR(x - 1) + x
"*** ${getMethodName()} ok ${fnR(66)}".log()
}
@JvmStatic
@BeforeAll
fun setup() {
"*** ${getMethodName()}\n".log()
}
@JvmStatic
@AfterAll
fun tearDown() {
"\n*** ${getMethodName()}".log()
}
}
@Order(0) // 1st function call will take more time to run
@Test
fun warmUp() {
loop(999)
recursion(999)
"** ${getMethodName()} done".log()
}
//------------------------
private fun fn(n: Int) = n
private fun loop(h: Int) {
var ans = 0
for (i in 1..h) {
val f = fn(i)
ans += f
//"fn($i) -> $f".log()
}
"# ${getMethodName()}($h) = $ans".log()
}
private fun recursion(h: Int) {
fun fnR(x: Int): Int = if (x == 0) 0 else fnR(x - 1) + fn(x)
val ans = fnR(h)
"# ${getMethodName()}($h) = $ans".log()
}
@Test
fun testLoop() {
"\n${getMethodName()} begin".log()
loop(10)
loop(11000)
loop(15000)
"end".log()
}
@Test
fun testRecursion() {
"\n${getMethodName()} begin".log()
recursion(10)
recursion(11000)
recursion(15000)
//recursion(16000) //java.lang.StackOverflowError
"end".log()
}
@Test
fun dataStructure() {
val a = sortedSetOf<Int>()
a.add(1)
a.remove(2)
val b = sortedMapOf(1 to 2)
b[2] = 3 // = b.put(2,3)
b.remove(2)
//---------
val d = arrayOf(1, 2) // Array<Int>
d[1] = 2
val e = IntArray(3)
e[1] = 2
//---------
val c = arrayListOf<Int>()
c.add(3)
c[0] = 1
c.add(1, 3)
val f = mutableListOf(1, 2)
f.add(3)
f[3] = 0
f.add(1, 3) //insert
val g = ArrayDeque<Int>()
g.add(1)
g[3] = 2
g.add(1, 3)
g.addFirst(1)
g.addLast(9)
}
}
internal class IteratorTest0 {
@Test
fun run() {
// fun returns a sequence
println(fibSeq().take(6).toList()) //[0, 1, 1, 2, 3, 5]
println(fibSeq().take(6).toList()) //[0, 1, 1, 2, 3, 5]
// fun returns an iterator
fibItFn().apply { repeat(6) { print("${next()}, ") } }; println() //0, 1, 1, 2, 3, 5,
fibItFn().apply { repeat(6) { print("${next()}, ") } }; println() //0, 1, 1, 2, 3, 5,
// access the same iterator
repeat(6) { print("${fibIt.next()}, ") }; println() //0, 1, 1, 2, 3, 5,
repeat(6) { print("${fibIt.next()}, ") }; println() //8, 13, 21, 34, 55, 89,
}
private fun fibSeq() = sequence {
fib()
}
private fun fibItFn() = iterator {
fib()
}
private val fibIt = iterator {
fib()
}
private suspend fun SequenceScope<Int>.fib() {
var terms = Pair(0, 1)
// this sequence is infinite
while (true) {
yield(terms.first)
terms = Pair(terms.second, terms.first + terms.second)
}
}
}
internal class IteratorTest {
@Test
fun run() {
val sq = generateSequence(1) {
(it + 10).apply { println(this) }
}
val i = sq.iterator()
repeat(9) {
println("+++")
println(" ~~ ${i.next()}")
println("---")
}
}
@Test
fun run2() {
// fun returns a sequence
println(fibSeq().take(6).toList())
println(fibSeq().take(6).toList())
}
var count = 0
private fun fibSeq(): Sequence<Int> = sequence {
if (count++ > 3) {
println("stop: $count")
return@sequence
}
repeat(9) {
//count=0
println("$it: $count")
yield(it * 1000 + count)
fibSeq()
// println("+++")
// yieldAll(fibSeq()) //StackOverflowError
// println("---")
}
}
}
internal class IteratorTree {
@Test
fun run() {
val t = TreeNode(3)
t.left = TreeNode(1)
t.right = TreeNode(5)
BSTIterator(t).apply { while (hasNext()) println(" ~~ ${next()}") }
BSTIterator(null).apply { while (hasNext()) println(" ~~ ${next()}") }
println("------")
BSTIterator2(t).apply { while (hasNext()) println(" ~~ ${next()}") }
BSTIterator2(null).apply { while (hasNext()) println(" ~~ ${next()}") }
}
class BSTIterator(root: TreeNode?) {
private suspend fun SequenceScope<Int>.fn(h: TreeNode) {
println("fn(${h.`val`})")
h.left?.apply { fn(this) }
yield(h.`val`)
h.right?.apply { fn(this) }
}
private val iter = iterator<Int> { root?.apply { fn(root) } }
fun hasNext() = iter.hasNext()
fun next() = iter.next()
}
class BSTIterator2(root: TreeNode?) {
val q = ArrayDeque<Int>().also {
fun TreeNode.dfs() {
left?.dfs()
it.addLast(`val`)
right?.dfs()
}
root?.dfs()
}
fun hasNext() = !q.isEmpty()
fun next() = q.removeFirst()
}
}
| 0 |
Kotlin
|
0
| 0 |
5e5731c1ca55c68eb40722c035d2d9e28c190281
| 5,803 |
LeetCode
|
Apache License 2.0
|
src/main/kotlin/br/com/zup/core/models/EmailPixRepository.kt
|
adamcoutinho
| 346,365,687 | true |
{"Kotlin": 54596}
|
package br.com.zup.core.models
import io.micronaut.context.annotation.Executable
import io.micronaut.data.annotation.Repository
import io.micronaut.data.repository.CrudRepository
@Repository
interface EmailPixRepository:CrudRepository<EmailPix,Long> {
@Executable
fun find(email:String?): EmailPix
@Executable
fun find(clientId:String, internal: String):EmailPix
@Executable
fun existsByEmail(email: String): Boolean
@Executable
fun existsByClientId(clientId: String): Boolean
@Executable
fun findByClientId(clientId:String): EmailPix
}
| 0 |
Kotlin
|
0
| 0 |
deafa17195e774fce38de063bd12f42d075cf465
| 584 |
orange-talents-01-template-pix-keymanager-grpc
|
Apache License 2.0
|
feature-twitch/src/main/java/com/freshdigitable/yttt/feature/oauth/TwitchOauthViewModel.kt
|
akihito104
| 613,290,086 | false |
{"Kotlin": 326612}
|
package com.freshdigitable.yttt.feature.oauth
import android.content.Intent
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import androidx.lifecycle.viewModelScope
import com.freshdigitable.yttt.LaunchAppWithUrlUseCase
import com.freshdigitable.yttt.data.AccountRepository
import com.freshdigitable.yttt.data.TwitchLiveRepository
import com.freshdigitable.yttt.data.model.TwitchOauthToken
import com.freshdigitable.yttt.data.model.TwitchUser
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class TwitchOauthViewModel @Inject constructor(
private val twitchRepository: TwitchLiveRepository,
private val accountRepository: AccountRepository,
private val launchApp: LaunchAppWithUrlUseCase,
) : ViewModel() {
val hasTokenState: StateFlow<Boolean> = accountRepository.twitchToken
.map { it != null }
.distinctUntilChanged()
.stateIn(viewModelScope, SharingStarted.Lazily, false)
fun hasToken(): Boolean = accountRepository.getTwitchToken() != null
fun putToken(token: TwitchOauthToken) {
// TODO: check OAuth2 State
viewModelScope.launch {
accountRepository.putTwitchToken(token.accessToken)
}
}
fun getMe(): LiveData<TwitchUser> = liveData {
val user = twitchRepository.fetchMe() ?: throw IllegalStateException()
emit(user)
}
private suspend fun getAuthorizeUrl(): String = twitchRepository.getAuthorizeUrl()
fun onLogin() {
viewModelScope.launch {
val url = getAuthorizeUrl()
launchApp(url) {
addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
}
}
}
companion object {
@Suppress("unused")
private val TAG = TwitchOauthViewModel::class.simpleName
}
}
| 11 |
Kotlin
|
0
| 0 |
77ba852966c0bdfd1e95c3f92644e25c6f7a0780
| 2,112 |
yttt
|
Apache License 2.0
|
app/src/main/java/com/precopia/rxtracker/util/IUtilThemeContract.kt
|
DavidPrecopia
| 243,413,607 | false | null |
package com.precopia.rxtracker.util
interface IUtilThemeContract {
fun isNightModeEnabled(): Boolean
fun setFollowSystem()
}
| 0 |
Kotlin
|
0
| 0 |
4209c7c951820f91b84e184415e4cba2ac986018
| 135 |
RxTracker
|
Apache License 2.0
|
shedinja-test/src/main/kotlin/guru/zoroark/shedinja/test/check/ShedinjaCheck.kt
|
utybo
| 366,171,592 | false | null |
package guru.zoroark.shedinja.test.check
import guru.zoroark.shedinja.ShedinjaException
import guru.zoroark.shedinja.dsl.ShedinjaDsl
import guru.zoroark.shedinja.environment.InjectableModule
/**
* Exception type for check failures (i.e. when a check is not met).
*/
class ShedinjaCheckException(message: String) : ShedinjaException(message)
/**
* An individual check that can be ran.
*/
fun interface IndividualCheck {
/**
* Run this check on the given list of modules.
*/
fun check(modules: List<InjectableModule>)
}
/**
* DSL receiver class for the Shedinja check DSL.
*/
@ShedinjaDsl
class ShedinjaCheckDsl {
/**
* Modules that should be taken into account during the checks
*/
val modules = mutableListOf<InjectableModule>()
/**
* Checks that should be ran. Consider using the [unaryPlus] operator for a more DSLish look.
*/
val checks = mutableListOf<IndividualCheck>()
/**
* Adds this individual check to this Shedinja check instance.
*/
@ShedinjaDsl
operator fun IndividualCheck.unaryPlus() {
checks += this
}
}
/**
* Adds the given modules to this Shedinja check instance.
*/
@ShedinjaDsl
fun ShedinjaCheckDsl.modules(vararg modules: InjectableModule) {
this.modules.addAll(modules)
}
/**
* DSL for checking your Shedinja modules.
*
* Imagine that we have three modules, `web`, `db` and `generate`. A typical use case would look like:
*
* ```
* @Test
* fun `Shedinja checks`() = shedinjaCheck {
* modules(web, db, generate)
*
* +complete
* +noCycle
* +safeInjection
* }
* ```
*
* Note that running checks will instantiate the classes within the modules in order to trigger the `by scope()`
* injections.
*/
@ShedinjaDsl
fun shedinjaCheck(block: ShedinjaCheckDsl.() -> Unit) {
ShedinjaCheckDsl().apply(block).check()
}
private fun ShedinjaCheckDsl.check() {
if (checks.isEmpty()) {
throw ShedinjaCheckException(
"""
shedinjaCheck called without any rule, which checks nothing.
--> Add rules using +ruleName (for example '+complete', do not forget the +)
--> If you do not want to run any checks, remove the shedinjaCheck block entirely.
For more information, visit https://shedinja.zoroark.guru/ShedinjaCheck
""".trimIndent()
)
} else {
checks.forEach { it.check(modules) }
}
}
internal fun <K, V> Sequence<Pair<K, V>>.associateByMultiPair(): Map<K, List<V>> =
fold(mutableMapOf<K, MutableList<V>>()) { map, (missing, requester) ->
map.compute(missing) { _, original ->
(original ?: mutableListOf()).apply { add(requester) }
}
map
}
| 6 |
Kotlin
|
0
| 4 |
d28e22d79fe6e4e36a729198efcd1f9b9c995c42
| 2,740 |
Shedinja
|
MIT License
|
app/src/test/java/com/example/clean_todo_list/business/interactors/splash/SyncTasksTest.kt
|
mahdi-hosseinnion
| 385,271,323 | false | null |
package com.example.clean_todo_list.business.interactors.splash
import com.example.clean_todo_list.business.data.cache.abstraction.TaskCacheDataSource
import com.example.clean_todo_list.business.data.network.task.abstraction.TaskNetworkDataSource
import com.example.clean_todo_list.business.domain.model.Task
import com.example.clean_todo_list.business.domain.model.TaskFactory
import com.example.clean_todo_list.business.domain.util.DateUtil
import com.example.clean_todo_list.di.DependencyContainer
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import java.util.*
import kotlin.random.Random
/**
* 1. syncTask_insert_addRandomTasksToCacheThenSyncAndConfirmNetworkUpdated()
* a) insert bunch of tasks into cache
* b) perform sync
* c) confirm tasks inserted into network
*
* 2. syncTask_insert_addRandomTaskToNetworkThenSyncAndConfirmCacheUpdated()
* a) insert bunch of tasks intro network
* b) perform sync
* c) confirm tasks inserted into cache
*
* 3. syncTask_update_updateRandomTasksInCacheThenSyncAndConfirmNetworkUpdated()
* a) select random task from cache
* b) update them
* c) perform sync
* d) confirm tasks updated in network
*
* 4. syncTask_update_updateRandomTaskInNetworkThenSyncAndConfirmCacheUpdated()
* a) select random task from network
* b) update them
* c) perform sync
* d) confirm tasks updated in cache
*/
class SyncTasksTest {
//system under test
private val syncTasks: SyncTasks
// dependencies
private val dependencyContainer = DependencyContainer()
private val taskCacheDataSource: TaskCacheDataSource =
dependencyContainer.taskCacheDataSource
private val taskNetworkDataSource: TaskNetworkDataSource =
dependencyContainer.taskNetworkDataSource
init {
syncTasks = SyncTasks(
taskCacheDataSource = taskCacheDataSource,
taskNetworkDataSource = taskNetworkDataSource
)
}
@Test
fun doSuccessiveUpdatesOccur() = runBlocking {
// update a single task with new timestamp
val newDate = DateUtil.getCurrentTimestamp().minus(Random.nextInt(1_000))
val allTasksInNetwork = taskNetworkDataSource.getAllTasks()
val updatedTask =
allTasksInNetwork.random().copy(
updated_at = newDate
)
taskNetworkDataSource.updateTask(updatedTask, newDate)
syncTasks.syncTasks()
delay(1001)
// simulate launch app again
syncTasks.syncTasks()
// confirm the date was not updated a second time
val tasks = taskNetworkDataSource.getAllTasks()
for (task in tasks) {
if (task.id.equals(updatedTask.id)) {
Assertions.assertTrue { task.updated_at.equals(newDate) }
}
}
}
@Test
fun checkUpdatedAtDates() = runBlocking {
// update a single task with new timestamp
val newDate = DateUtil.getCurrentTimestamp().minus(Random.nextInt(10, 1_000))
val allTasksInNetwork = taskNetworkDataSource.getAllTasks()
val updatedTask =
allTasksInNetwork.random().copy(
updated_at = newDate
)
taskNetworkDataSource.updateTask(updatedTask, newDate)
syncTasks.syncTasks()
// confirm only a single 'updated_at' date was updated
val tasks = taskNetworkDataSource.getAllTasks()
for (task in tasks) {
taskCacheDataSource.searchTaskById(task.id)?.let { n ->
println("date: ${n.updated_at}")
if (n.id.equals(updatedTask.id)) {
Assertions.assertTrue { n.updated_at.equals(newDate) }
} else {
Assertions.assertFalse { n.updated_at.equals(newDate) }
}
}
}
}
@Test
fun updateTaskInCache_thenSyncTwice() = runBlocking {
//update a task in cache
val allTaskInCache = taskCacheDataSource.getAllTasks()
val newDate = DateUtil.getCurrentTimestamp()
val taskToUpdate = allTaskInCache.random()
taskCacheDataSource.updateTask(
primaryKey = taskToUpdate.id,
newTitle = "its is the best title",
newBody = "this is not the best body",
newIsDone = true,
updated_at = newDate
)
//simulate some work with app here
delay(2_000)
//close and then relaunch app
syncTasks.syncTasks()
//simulate some work with app here
delay(2_000)
//close and then relaunch app
syncTasks.syncTasks()
//now check if cache update is the same (update at should not change
// b/c task did not update after newDate)
assertEquals(
newDate,
taskCacheDataSource.searchTaskById(taskToUpdate.id)?.updated_at
)
}
@Test
fun syncTask_insert_addRandomTasksToCacheThenSyncAndConfirmNetworkUpdated() = runBlocking {
val randomTasks = TaskFactory.createListOfRandomTasks(50)
taskCacheDataSource.insertTasks(randomTasks)
delay(2_000)
syncTasks.syncTasks()
delay(2_000)
syncTasks.syncTasks()
delay(2_000)
syncTasks.syncTasks()
for (task in randomTasks) {
//confirm tasks actually exist in cache (avoid false-positive)
assertEquals(
task,
taskCacheDataSource.searchTaskById(task.id)
)
assertEquals(
task,
taskNetworkDataSource.searchTask(task)
)
}
}
@Test
fun syncTask_insert_addRandomTaskToNetworkThenSyncAndConfirmCacheUpdated() = runBlocking {
val randomTasks = TaskFactory.createListOfRandomTasks(50)
taskNetworkDataSource.insertTasks(randomTasks)
syncTasks.syncTasks()
for (task in randomTasks) {
//confirm tasks actually exist in cache (avoid false-positive)
assertEquals(
task,
taskNetworkDataSource.searchTask(task)
)
assertEquals(
task,
taskCacheDataSource.searchTaskById(task.id)
)
}
}
@Test
fun syncTask_update_updateRandomTasksInCacheThenSyncAndConfirmNetworkUpdated() = runBlocking {
val allTasksInCache = taskCacheDataSource.getAllTasks()
val bunchOfRandomTasksInCache: List<Task> = allTasksInCache.filter { Random.nextBoolean() }
val updatedTasks = ArrayList<Task>()
for (task in bunchOfRandomTasksInCache) {
val taskToUpdate = Task(
id = task.id,
title = UUID.randomUUID().toString(),
body = UUID.randomUUID().toString(),
isDone = Random.nextBoolean(),
updated_at = DateUtil.getCurrentTimestamp(),
created_at = task.created_at
)
taskCacheDataSource.updateTask(
taskToUpdate.id,
taskToUpdate.title,
taskToUpdate.body,
taskToUpdate.isDone,
taskToUpdate.updated_at
)
updatedTasks.add(taskToUpdate)
}
syncTasks.syncTasks()
for (task in updatedTasks) {
//confirm tasks actually updated in cache (avoid false-positive)
assertEquals(
task,
taskCacheDataSource.searchTaskById(task.id)
)
assertEquals(
task,
taskNetworkDataSource.searchTask(task)
)
}
}
@Test
fun syncTask_update_updateRandomTaskInNetworkThenSyncAndConfirmCacheUpdated() = runBlocking {
val allTasksInNetwork = taskNetworkDataSource.getAllTasks()
val bunchOfRandomTasksFromNetwork: List<Task> =
allTasksInNetwork.filter { Random.nextBoolean() }
val updatedTasks = ArrayList<Task>()
for (task in bunchOfRandomTasksFromNetwork) {
val taskToUpdate = Task(
id = task.id,
title = UUID.randomUUID().toString(),
body = UUID.randomUUID().toString(),
isDone = Random.nextBoolean(),
updated_at = DateUtil.getCurrentTimestamp(),
created_at = task.created_at
)
taskNetworkDataSource.updateTask(
taskToUpdate,
taskToUpdate.updated_at
)
updatedTasks.add(taskToUpdate)
}
syncTasks.syncTasks()
for (task in updatedTasks) {
//confirm tasks actually updated in cache (avoid false-positive)
assertEquals(
task,
taskNetworkDataSource.searchTask(task)
)
assertEquals(
task,
taskCacheDataSource.searchTaskById(task.id)
)
}
}
}
| 0 |
Kotlin
|
0
| 1 |
1cacea50e3463491ada90d034d253ac5502deb03
| 9,189 |
Clean-ToDo_List
|
MIT License
|
app/src/main/java/com/example/movieapp/ui/MovieDetailFragment.kt
|
prshntpnwr
| 184,299,458 | false | null |
package com.example.movieapp.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingComponent
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import com.example.movieapp.R
import com.example.movieapp.binding.FragmentDataBindingComponent
import com.example.movieapp.databinding.MovieDetailFragmentBinding
import com.example.movieapp.di.Injectable
import com.example.movieapp.observer.MovieDetailViewModel
import com.example.movieapp.util.AppExecutors
import com.example.movieapp.util.ConverterUtil
import com.example.movieapp.util.Resource
import com.example.movieapp.util.Status
import javax.inject.Inject
class MovieDetailFragment : Fragment(), Injectable {
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
private lateinit var viewModel: MovieDetailViewModel
private var dataBindingComponent: DataBindingComponent = FragmentDataBindingComponent(this)
private lateinit var binding: MovieDetailFragmentBinding
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt(MOVIE_ID, movieId)
outState.putString(MOVIE_TITLE, movieTitle)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
DataBindingUtil.inflate<MovieDetailFragmentBinding>(
inflater,
R.layout.movie_detail_fragment,
container,
false,
dataBindingComponent
).also {
binding = it
binding.converter = ConverterUtil()
binding.lifecycleOwner = this
}.run {
return this.root
}
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
movieId = savedInstanceState?.getInt(MOVIE_ID) ?: MovieDetailFragmentArgs.fromBundle(arguments).id
movieTitle = savedInstanceState?.getString(MOVIE_TITLE) ?: MovieDetailFragmentArgs.fromBundle(arguments).title
viewModel = ViewModelProviders.of(this, viewModelFactory)
.get(MovieDetailViewModel::class.java)
.also {
it.init(refID = movieId)
it.result.observe(this, Observer { res ->
binding.status = res.status
binding.item = res?.data
setActionBar()
if (res.status == Status.SUCCESS && res?.data == null)
binding.status = Status.ERROR
if (res?.status == Status.ERROR)
Toast.makeText(requireContext(), getString(R.string.generalError), Toast.LENGTH_LONG).show()
})
}
}
private fun setActionBar() {
val actionBar = (activity as MainActivity).supportActionBar
actionBar?.let {
it.title = movieTitle ?: getString(R.string.details)
it.setDisplayHomeAsUpEnabled(true)
it.setDisplayShowHomeEnabled(true)
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
requireActivity().onBackPressed()
}
}
return true
}
companion object {
var movieId: Int = -1
var movieTitle: String? = null
const val MOVIE_ID = "movie_id"
const val MOVIE_TITLE = "movie_title"
}
}
| 0 |
Kotlin
|
0
| 0 |
ec97acfe66f7a8f38e323ad0e3b50a3c421afa51
| 3,964 |
MovieApp
|
Apache License 2.0
|
logic-common/src/main/kotlin/io/lonmstalker/springkube/utils/RequestUtils.kt
|
lonmstalker
| 634,331,522 | false | null |
package io.lonmstalker.springkube.utils
import io.lonmstalker.springkube.model.system.RequestContext
import kotlinx.coroutines.reactive.awaitFirstOrNull
import reactor.core.publisher.Mono
object RequestUtils {
@JvmStatic
suspend fun getSuspendContext(): RequestContext? =
this
.getContext()
.awaitFirstOrNull()
@JvmStatic
fun getContext(): Mono<RequestContext> =
Mono
.deferContextual { Mono.just(it.get(RequestContext::class.java)) }
}
| 0 |
Kotlin
|
0
| 0 |
d94bd56bf4d4ce5e5163840f369eba993431a10a
| 508 |
spring-kube
|
Apache License 2.0
|
composeApp/src/commonMain/kotlin/com/jetbrains/bs23_kmp/screens/list/ListViewModel.kt
|
TahsinBS1531
| 854,998,729 | false |
{"Kotlin": 95847, "Swift": 685}
|
package com.jetbrains.bs23_kmp.screens.list
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.jetbrains.bs23_kmp.data.MuseumObject
import com.jetbrains.bs23_kmp.data.MuseumRepository
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
class ListViewModel(museumRepository: MuseumRepository) : ViewModel() {
val objects: StateFlow<List<MuseumObject>> =
museumRepository.getObjects()
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
}
| 0 |
Kotlin
|
0
| 1 |
422e788c2a35fa2c7572f2323dd234766378acbb
| 598 |
BS23-KMP
|
Apache License 2.0
|
app/src/main/java/com/prongbang/asl/MainApplication.kt
|
prongbang
| 301,809,635 | false | null |
package com.prongbang.aslprocessor
import android.app.Application
import com.prongbang.aslprocessor.annotation.AndroidSheetLocalization
@AndroidSheetLocalization(
sheetId = "0",
documentId = "1_97CuyDyVD28ICV_hBGDEdwKGuIokE1egeNlVJn08Tc",
enabled = true
)
class MainApplication : Application()
| 0 | null |
1
| 4 |
875eb461cc8ea7197476128b198e239f7c2744b6
| 301 |
android-sheet-localization
|
MIT License
|
src/model/index.kt
|
Olegoria3538
| 431,102,676 | false | null |
package GUISamples.features.nodes.model
import GUISamples.features.nodes.`@core`.*
import javafx.scene.layout.AnchorPane
val mainRoot = AnchorPane()
val graphs = mutableMapOf<CoreNode, MutableMap<CoreNode, String>>();
val lines = mutableMapOf<CoreNode, MutableSet<BoundLine>>();
class CreateSelectNode {
var node : CoreNode? = null
fun setSelectNode (target: CoreNode) {
if(node != null) removeSelectNode()
target.out.style = "-fx-border-color: #f48225; -fx-border-width: 3px;";
node = target
}
fun removeSelectNode () {
node?.out?.style = ""
node = null
}
}
val selectNode = CreateSelectNode()
fun addNode(node: CoreNode) {
graphs.put(node, mutableMapOf())
lines.put(node, mutableSetOf())
}
fun addSubscribe(node: CoreNode, target: CoreNode, metric: InputMetricCore) {
graphs.get(node)?.put(target, metric.name)
val line = BoundLine(
target.inputMetrics[metric.name]!!.btn,
node.out
)
lines.get(node)?.add(line)
lines.get(target)?.add(line)
mainRoot.children.add(line)
}
fun upgradeLinesPosition(node: CoreNode) {
lines.get(node)?.forEach { x ->
x.updatePosition()
}
}
fun removeSubscribe(node: CoreNode, metric: InputMetricCore) {
graphs.entries.forEach {x ->
if(node in x.value && x.value[node] == metric.name) {
x.value.remove(node)
val line = lines.get(node)?.find { line ->
line.start == metric.btn || line.end == metric.btn
}
if(line != null) {
line.removeScene()
lines.get(node)?.remove(line)
lines.get(x.key)?.remove(line)
}
node.inputMetrics[metric.name]?.fn?.let { it(null) }
}
}
}
fun removeNode(node: CoreNode) {
val subscribes = graphs.get(node)
graphs.remove(node)
val ar = lines.get(node)
if(ar != null) {
ar.forEach { line ->
val filterAr = lines.filter { x -> x.value.find { q -> q == line } != null && x.key != node }
filterAr.forEach { x ->
x.value.remove(line)
}
mainRoot.children.remove(line)
}
}
lines.remove(node)
subscribes?.forEach { x ->
x.key.inputMetrics[x.value]?.fn?.let { it(null) }
}
}
fun shakeTree(startNode: CoreNode) {
graphs.get(startNode)?.forEach { x ->
val node = x.key
val name = x.value
node.inputMetrics[name]?.fn?.let { it(startNode.outValue) }
}
}
fun isMakeSubscribe(node: CoreNode?, target: CoreNode?, metric: InputMetricCore): Boolean {
var flag = node != null &&
target != null &&
node != target &&
node.outType == metric.type &&
graphs.get(node)?.get(target) == null
if(!flag) return false
graphs.values.forEach { x ->
x.forEach { x ->
if (x.key == target && x.value == metric.name) {
flag = false
}
}
}
return flag
}
fun removeAllScene() {
val ids = graphs.keys.map{ x ->
x.id
}
ids.forEach { id ->
val f = graphs.keys.find { x -> x.id == id }
f?.remove()
}
}
| 0 |
Kotlin
|
0
| 0 |
b1a6bd50b03fa7b8f8819f63a0cba6c2898c0a2e
| 3,246 |
node-editor
|
MIT License
|
bitlap-core/src/test/kotlin/org/bitlap/core/test/base/SqlChecker.kt
|
bitlap
| 313,535,150 | false | null |
/* Copyright (c) 2023 bitlap.org */
package org.bitlap.core.test.base
import io.kotest.assertions.Actual
import io.kotest.assertions.Expected
import io.kotest.assertions.failure
import io.kotest.assertions.print.print
import io.kotest.matchers.shouldBe
import org.bitlap.common.utils.SqlEx.toTable
import org.bitlap.common.utils.internal.DBTable
import org.bitlap.core.catalog.metadata.Database
import org.bitlap.core.sql.QueryExecution
/**
* Some sql check utils
*/
interface SqlChecker {
/**
* execute sql statement
*/
fun sql(statement: String, currentSchema: String = Database.DEFAULT_DATABASE): SqlResult {
val rs = QueryExecution(statement, currentSchema).execute()
return SqlResult(statement, rs.data.toTable())
}
/**
* check rows
*/
fun checkRows(statement: String, rows: List<List<Any?>>, currentSchema: String = Database.DEFAULT_DATABASE) {
val result = sql(statement, currentSchema).result
try {
result.size shouldBe rows.size
result.zip(rows).forEach { (r1, r2) ->
r1.size shouldBe r2.size
r1.zip(r2).forEach { (v1, v2) ->
v1 shouldBe v2
}
}
} catch (e: Throwable) {
when (e) {
is AssertionError ->
throw failure(Expected(rows.print()), Actual(result.print()))
else ->
throw e
}
}
}
}
class SqlResult(private val statement: String, private val table: DBTable) {
internal val result: List<List<Any?>> by lazy {
mutableListOf<List<Any?>>().apply {
(0 until table.rowCount).forEach { r ->
add(table.columns.map { it.typeValues[r] })
}
}
}
val size = this.result.size
fun show(): SqlResult {
table.show()
return this
}
override fun toString(): String {
return this.result.toString()
}
override fun hashCode(): Int {
return this.result.hashCode()
}
override fun equals(other: Any?): Boolean {
return this.result == other
}
}
| 12 |
Kotlin
|
1
| 20 |
bcefec0b601fe0370dd2b6d599668cbc7e3375e6
| 2,177 |
bitlap
|
MIT License
|
aoc-archetype/src/main/resources/archetype-resources/src/test/kotlin/days/Day03Test.kt
|
JStege1206
| 92,714,900 | false | null |
package ${package}.days
import nl.jstege.adventofcode.aoccommon.utils.DayTester
class Day03Test : DayTester(Day03())
| 0 |
Kotlin
|
0
| 0 |
d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025
| 119 |
AdventOfCode
|
MIT License
|
src/main/kotlin/GravityFieldRenderingSystem.kt
|
hannomalie
| 465,694,597 | false |
{"Kotlin": 30338}
|
import com.artemis.BaseEntitySystem
import com.artemis.annotations.All
import org.jetbrains.skia.Canvas
import org.jetbrains.skia.Color
import org.jetbrains.skia.Paint
@All
class GravityFieldRenderingSystem : BaseEntitySystem(), RenderSystem {
lateinit var extractor: ComponentExtractor
val red = Paint().apply {
color = Color.RED
setStroke(true)
}
override fun processSystem() {}
override fun Canvas.render() {
extractor[GravityField::class.java].data.filterNotNull().forEach {
drawCircle(it.x, it.y, it.radius, red)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
4349e8f881fda9ec29e2c9124d7dc0520f577a03
| 595 |
artemis-playground
|
MIT License
|
app/src/main/java/com/tans/androidopenglpractice/render/CubeRender.kt
|
Tans5
| 652,997,585 | false | null |
package com.tans.androidopenglpractice.render
import android.graphics.BitmapFactory
import android.opengl.GLES31
import android.opengl.GLUtils
import android.opengl.Matrix
import android.os.SystemClock
import android.util.Log
import java.util.concurrent.atomic.AtomicBoolean
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10
import kotlin.math.cos
import kotlin.math.sin
class CubeRender : IShapeRender {
override val isActive: AtomicBoolean = AtomicBoolean(false)
override var width: Int = 0
override var height: Int = 0
override val logTag: String = "CubeRender"
private var initData: InitData? = null
override fun onSurfaceCreated(owner: MyOpenGLView, gl: GL10, config: EGLConfig) {
super.onSurfaceCreated(owner, gl, config)
val program = compileShaderFromAssets(owner.context, "cube.vert", "cube.frag")
if (program != null) {
// 一个正方体 6 个面;每个面由 2 个三角形组成;每个三角形 3 个点组成;所以总共 36 个点。
val vertices = floatArrayOf(
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.0f, 1.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
// Android 中要多加一个点,否者纹理渲染出错,不知道什么原因。
0f, 0f, -0f, 0f, 0f,
)
val VAO = glGenVertexArrays()
GLES31.glBindVertexArray(VAO)
val VBO = glGenBuffers()
GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, VBO)
GLES31.glBufferData(GLES31.GL_ARRAY_BUFFER, vertices.size * 4, vertices.toGlBuffer(), GLES31.GL_STATIC_DRAW)
GLES31.glVertexAttribPointer(0, 3, GLES31.GL_FLOAT, false, 5 * 4, 0)
GLES31.glEnableVertexAttribArray(0)
GLES31.glVertexAttribPointer(1, 3, GLES31.GL_FLOAT, false, 5 * 4, 3 * 4)
GLES31.glEnableVertexAttribArray(1)
val androidContext = owner.context
val bitmap = try {
androidContext.assets.open("container.jpeg").use { BitmapFactory.decodeStream(it) }
} catch (e: Throwable) {
e.printStackTrace()
Log.e(logTag, "Load texture bitmap fail: ${e.message}", e)
null
}
var texture: Int? = null
if (bitmap != null) {
texture = glGenTexture()
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, texture)
GLES31.glTexParameteri(GLES31.GL_TEXTURE_2D, GLES31.GL_TEXTURE_WRAP_S, GLES31.GL_REPEAT)
GLES31.glTexParameteri(GLES31.GL_TEXTURE_2D, GLES31.GL_TEXTURE_WRAP_T, GLES31.GL_REPEAT)
GLES31.glTexParameteri(GLES31.GL_TEXTURE_2D, GLES31.GL_TEXTURE_MIN_FILTER, GLES31.GL_LINEAR)
GLES31.glTexParameteri(GLES31.GL_TEXTURE_2D, GLES31.GL_TEXTURE_MAG_FILTER, GLES31.GL_LINEAR)
GLES31.glGenerateMipmap(GLES31.GL_TEXTURE_2D)
GLUtils.texImage2D(GLES31.GL_TEXTURE_2D, 0, bitmap, 0)
bitmap.recycle()
}
initData = InitData(
VAO = VAO,
VBO = VBO,
program = program,
texture = texture
)
}
}
override fun onDrawFrame(owner: MyOpenGLView, gl: GL10) {
val initData = this.initData
if (initData != null) {
GLES31.glClear(GLES31.GL_DEPTH_BUFFER_BIT or GLES31.GL_COLOR_BUFFER_BIT)
// Z 缓冲
GLES31.glEnable(GLES31.GL_DEPTH_TEST)
GLES31.glUseProgram(initData.program)
val ratio = width.toFloat() / height.toFloat()
val time = SystemClock.uptimeMillis()
// Projection
val projectionMatrix = newGlFloatMatrix()
Matrix.perspectiveM(projectionMatrix, 0, 45.0f, ratio, 0.1f, 100f)
GLES31.glUniformMatrix4fv(GLES31.glGetUniformLocation(initData.program, "projection"), 1, false, projectionMatrix, 0)
// View
val viewMatrix = newGlFloatMatrix()
val radius = 10f
val eyeX = sin(Math.toRadians(time.toDouble() / 20f)) * radius
val eyeZ = cos(Math.toRadians(time.toDouble() / 20f)) * radius
Matrix.setLookAtM(viewMatrix, 0, eyeX.toFloat(), 0f, eyeZ.toFloat(), 0f, 0f, 0f, 0f, 1f, 0f)
GLES31.glUniformMatrix4fv(GLES31.glGetUniformLocation(initData.program, "view"), 1, false, viewMatrix, 0)
// transform
val transformMatrix = newGlFloatMatrix()
Matrix.rotateM(transformMatrix, 0, ((time / 10) % 360).toFloat(), 0.5f, 1.0f, 0.0f)
GLES31.glUniformMatrix4fv(GLES31.glGetUniformLocation(initData.program, "transform"), 1, false, transformMatrix, 0)
val cubePositions = listOf<FloatArray>(
floatArrayOf(0f, 0f, 0f),
floatArrayOf(2f, 5f, -15f),
floatArrayOf(-1.5f, -2.2f, -2.5f),
floatArrayOf(-3.8f, -2.0f, -12.3f),
floatArrayOf(2.4f, -0.4f, -3.5f),
floatArrayOf(-1.7f, 3.0f, -7.5f),
floatArrayOf(1.3f, -2.0f, -2.5f),
floatArrayOf(1.5f, 2.0f, -2.5f),
floatArrayOf(1.5f, 0.2f, -1.5f),
floatArrayOf(-1.3f, 1.0f, -1.5f),
)
for ((i, p) in cubePositions.withIndex()) {
// model
val modelMatrix = newGlFloatMatrix()
Matrix.translateM(modelMatrix, 0, p[0], p[1], p[2])
val angle = 20.0f * i
Matrix.rotateM(modelMatrix, 0, angle, 1.0f, 0.3f, 0.5f)
GLES31.glUniformMatrix4fv(GLES31.glGetUniformLocation(initData.program, "model"), 1, false, modelMatrix, 0)
GLES31.glBindVertexArray(initData.VAO)
GLES31.glDrawArrays(GLES31.GL_TRIANGLES, 0, 36)
}
}
owner.requestRender()
}
override fun onViewDestroyed(owner: MyOpenGLView) {
super.onViewDestroyed(owner)
initData = null
}
companion object {
private data class InitData(
val VAO: Int,
val VBO: Int,
val program: Int,
val texture: Int?
)
}
}
| 0 |
Kotlin
|
1
| 3 |
32d69b72013ca9363911c702e4aef4f3b3b6d6b3
| 7,833 |
AndroidOpenGLPractice
|
Apache License 2.0
|
CLI/src/test/kotlin/uk/ac/lshtm/keppel/cli/MatchWithScoreTest.kt
|
LSHTM-ORK
| 240,033,125 | false |
{"Kotlin": 80371, "Java": 4400, "Shell": 1742}
|
package uk.ac.lshtm.keppel.cli
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
import uk.ac.lshtm.keppel.cli.support.FakeLogger
import uk.ac.lshtm.keppel.cli.support.FakeMatcher
import uk.ac.lshtm.keppel.cli.support.toHexString
class MatchWithScoreTest {
private val logger = FakeLogger()
private val matcher = FakeMatcher()
@Test
fun whenMatchIsLessThanThreshold_logsScore() {
val fileOne = createTempFile().apply { writeText("index".toHexString()) }
val fileTwo = createTempFile().apply { writeText("index_9.0".toHexString()) }
val app = App(matcher, 10.0)
app.execute(listOf("match", "-ms", fileOne.absolutePath, fileTwo.absolutePath), logger)
assertThat(logger.lines, equalTo(listOf("mismatch_9.0")))
}
@Test
fun whenEqualToThreshold_logsNotAMatch() {
val fileOne = createTempFile().apply { writeText("index".toHexString()) }
val fileTwo = createTempFile().apply { writeText("index_10.0".toHexString()) }
val app = App(matcher, 10.0)
app.execute(listOf("match", "-ms", fileOne.absolutePath, fileTwo.absolutePath), logger)
assertThat(logger.lines, equalTo(listOf("match_10.0")))
}
@Test
fun whenGreaterThanThreshold_logsNotAMatch() {
val fileOne = createTempFile().apply { writeText("index".toHexString()) }
val fileTwo = createTempFile().apply { writeText("index_11.0".toHexString()) }
val app = App(matcher, 10.0)
app.execute(listOf("match", "-ms", fileOne.absolutePath, fileTwo.absolutePath), logger)
assertThat(logger.lines, equalTo(listOf("match_11.0")))
}
@Test
fun withNoArguments_logsMissingArgument() {
val app = App(matcher, 10.0)
app.execute(listOf("match", "-ms"), logger)
assertThat(logger.lines, equalTo(listOf("Missing argument \"TEMPLATE_ONE\".")))
}
@Test
fun withOneArgument_logsMissingArgument() {
val fileOne = createTempFile().apply { writeText("index".toHexString()) }
val app = App(matcher, 10.0)
app.execute(listOf("match", "-ms", fileOne.absolutePath), logger)
assertThat(logger.lines, equalTo(listOf("Missing argument \"TEMPLATE_TWO\".")))
}
}
| 2 |
Kotlin
|
2
| 7 |
4ffdbf19e8c86ccb16c47bcd58603eb695696f60
| 2,289 |
ODK_Biometrics
|
MIT License
|
app/src/main/java/com/bryan/personalproject/ui/adapter/ScoreAdapter.kt
|
TBNR-1257
| 729,129,439 | false |
{"Kotlin": 76279}
|
package com.bryan.personalproject.ui.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bryan.personalproject.data.model.Score
import com.bryan.personalproject.databinding.ItemLayoutLeaderboardBinding
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class ScoreAdapter(
private var score: List<Score>
): RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(child: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val binding = ItemLayoutLeaderboardBinding.inflate(
LayoutInflater.from(child.context),
child,
false
)
return ScoreViewHolder(binding)
}
override fun getItemCount() = score.size
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val result = score[position]
if (holder is ScoreAdapter.ScoreViewHolder) {
holder.bind(result)
}
}
fun setScore(score: List<Score>) {
this.score = score
notifyDataSetChanged()
}
inner class ScoreViewHolder(
private val binding: ItemLayoutLeaderboardBinding
): RecyclerView.ViewHolder(binding.root) {
fun bind(score: Score) {
binding.run {
tvUsername.text = score.name
tvScore.text = score.result
tvQuizId.text = score.quizId
// val dateFormat = SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault())
// val formattedDate = dateFormat.format(Date(score.createdAt))
// tvFinishtime.text = formattedDate
}
}
}
}
| 0 |
Kotlin
|
0
| 0 |
49ac5aefea86c4569843df4c050a22ce0471c2ca
| 1,736 |
SEM4_QuizApp
|
MIT License
|
app/src/main/java/com/hu/sandoruszkai/androiddesign/service/HandleResponse.kt
|
uszkaisandor
| 170,866,917 | false | null |
package com.hu.sandoruszkai.androiddesign.service
interface HandleResponse<in T> {
fun onResponse(response: T)
fun onError(error:Throwable)
}
| 0 |
Kotlin
|
0
| 0 |
d878ecf603e7ef9309aeac059ce086ff0b9709db
| 150 |
android-design-sample
|
MIT License
|
tracker-batch/src/main/kotlin/network/piction/tracker/batch/JobConfig.kt
|
piction-protocol
| 273,381,524 | false |
{"TypeScript": 59738, "Kotlin": 45231}
|
package network.piction.tracker.batch
import com.klaytn.caver.methods.response.KlayLogs
import network.piction.tracker.common.entities.EventLogEntity
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory
import org.springframework.batch.core.configuration.annotation.JobScope
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory
import org.springframework.batch.core.step.tasklet.TaskletStep
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
class JobConfig(
val jobBuilderFactory: JobBuilderFactory,
val stepBuilderFactory: StepBuilderFactory,
val taskCompletionListener: TaskCompletionListener) {
@Bean
fun taskJob(
taskStep: TaskletStep
) = jobBuilderFactory.get("[TASK JOB]")
.start(taskStep)
.listener(taskCompletionListener)
.build()
@Bean
@JobScope
fun taskStep(
taskReader: TaskReader,
taskProcessor: TaskProcessor,
taskWriter: TaskWriter
) = stepBuilderFactory.get("[TASK STEP]")
.chunk<KlayLogs.Log, EventLogEntity>(100)
.reader(taskReader)
.processor(taskProcessor)
.writer(taskWriter)
.build()
}
| 9 |
TypeScript
|
0
| 2 |
a068083ed87beba7736101eacc01118a64d8509c
| 1,280 |
event-tracker
|
Apache License 2.0
|
platform/microservice/src/main/kotlin/com/dreamsoftware/repository/impl/OTPRepositoryImpl.kt
|
sergio11
| 538,255,353 | false |
{"Kotlin": 56871, "Ruby": 5208, "Shell": 1373, "Dockerfile": 625}
|
package com.dreamsoftware.repository.impl
import com.dreamsoftware.model.OTPGenerated
import com.dreamsoftware.model.RedisStorageConfig
import com.dreamsoftware.model.exception.OTPDestinationIsBlockedException
import com.dreamsoftware.model.exception.OTPNotFoundException
import com.dreamsoftware.model.exception.OTPSaveDataException
import com.dreamsoftware.repository.OTPRepository
import com.dreamsoftware.utils.hashSha256andEncode
import redis.clients.jedis.JedisCluster
class OTPRepositoryImpl(
private val jedisCluster: JedisCluster,
private val redisStorageConfig: RedisStorageConfig
): OTPRepository {
override fun save(otpGenerated: OTPGenerated): Unit = with(otpGenerated) {
checkDestinationIsBlocked(destination)
runCatching {
with(jedisCluster) {
with(redisStorageConfig) {
val operationKey = operationsPrefix + operationId
val destinationKey = destinationsPrefix + destination.hashSha256andEncode()
jsonSet(operationKey, toJSON())
expire(operationKey, ttlInSeconds)
set(destinationKey, operationId)
expire(destinationKey, ttlInSeconds)
}
}
}.getOrElse {
throw OTPSaveDataException("An error occurred when trying to save OTP data", it)
}
}
override fun findByDestination(destination: String): OTPGenerated = runCatching {
val operationId = jedisCluster.get(redisStorageConfig.destinationsPrefix + destination.hashSha256andEncode())
findByOperationId(operationId)
}.getOrElse {
throw OTPNotFoundException("OTP data not found", it)
}
override fun findByOperationId(operationId: String): OTPGenerated =
jedisCluster.jsonGet(redisStorageConfig.operationsPrefix + operationId, OTPGenerated::class.java).also {
println("findByOperationId -> ${redisStorageConfig.operationsPrefix + operationId}")
if(it == null)
throw OTPNotFoundException("OTP data not found")
checkDestinationIsBlocked(it.destination)
}
override fun existsByOperationIdAndOtp(operationId: String, otp: String): Boolean = runCatching {
findByOperationId(operationId)
}.getOrElse {
throw OTPNotFoundException("OTP data not found", it)
}.also {
checkDestinationIsBlocked(it.destination)
}.let {
val isValid = it.otp == otp
if(!isValid) {
recordVerificationFailed(destination = it.destination)
}
isValid
}
override fun deleteByOperationId(operationId: String) {
try {
with(jedisCluster) {
with(redisStorageConfig) {
jsonGet(operationsPrefix + operationId, OTPGenerated::class.java).also {
del(destinationsPrefix + it.destinationHash)
}
del(operationsPrefix + operationId).also {
println("deleteByOperationId -> $operationId result -> $it")
}
}
}
} catch (ex: Exception) {
println("deleteByOperationId ex -> ${ex.message}")
}
}
private fun checkDestinationIsBlocked(destination: String) = with(jedisCluster) {
with(redisStorageConfig) {
destination.hashSha256andEncode().let { faultsPrefix + it }.let { key ->
if(exists(key) && get(key).toInt() > maxVerificationFailedByDestination) {
throw OTPDestinationIsBlockedException("$destination has been blocked.")
}
}
}
}
private fun recordVerificationFailed(destination: String) = runCatching {
with(jedisCluster) {
with(redisStorageConfig) {
destination.hashSha256andEncode().let { key ->
incr(faultsPrefix + key)
expire(key, verificationFailedTtlInSeconds)
}
}
}
}.getOrElse {
throw OTPSaveDataException("An error occurred when recording verification failed")
}
}
| 0 |
Kotlin
|
1
| 6 |
9e0cd12fe6ddcc86be81ac29690dd817b45c8a60
| 4,181 |
passwordless_authentication_architecture
|
MIT License
|
src/main/kotlin/uk/gov/justice/digital/hmpps/assessrisksandneeds/jpa/respositories/OffenderPredictorsHistoryRepository.kt
|
ministryofjustice
| 373,137,019 | false |
{"Kotlin": 340951, "Dockerfile": 1027}
|
package uk.gov.justice.digital.hmpps.assessrisksandneeds.jpa.respositories
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
import uk.gov.justice.digital.hmpps.assessrisksandneeds.jpa.entities.OffenderPredictorsHistoryEntity
@Repository
interface OffenderPredictorsHistoryRepository : JpaRepository<OffenderPredictorsHistoryEntity, Long> {
fun findAllByCrn(crn: String): List<OffenderPredictorsHistoryEntity>
}
| 2 |
Kotlin
|
0
| 0 |
a2fa63a07f5e64a5d5349fa164fb687c8b1d2917
| 477 |
hmpps-assess-risks-and-needs
|
MIT License
|
app/src/main/java/com/vpr/places_together/ui/friends_screen/FriendsFragment.kt
|
v1p3rrr
| 633,636,972 | false | null |
package com.vpr.places_together.ui.friends_screen
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.SearchView
import androidx.core.view.MenuHost
import androidx.core.view.MenuProvider
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.NavController
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.appbar.MaterialToolbar
import com.vpr.places_together.R
import com.vpr.places_together.databinding.FragmentFriendsBinding
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class FriendsFragment: Fragment() {
private val viewModel: FriendsViewModel by viewModels()
private lateinit var binding: FragmentFriendsBinding
private lateinit var navController: NavController
private lateinit var adapter: FriendsAdapter
private lateinit var searchView: SearchView
private var unfilteredList: List<String> = arrayListOf()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentFriendsBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
navController = findNavController()
setupMenu()
setAdapter()
setListeners()
}
private fun setupMenu() {
val toolbar = requireActivity().findViewById<MaterialToolbar>(R.id.top_app_bar)
toolbar.setNavigationIcon(R.drawable.ic_arrow_back)
toolbar.title = getString(R.string.friends_screen_title)
toolbar.setNavigationOnClickListener {
println("back btn pressed")
navController.navigateUp()
}
(requireActivity() as MenuHost).addMenuProvider(object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menu.clear()
menuInflater.inflate(R.menu.menu_search, menu)
val searchItem = menu.findItem(R.id.action_search)
searchView = searchItem.actionView as SearchView
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
// Handle search query submission
return true
}
override fun onQueryTextChange(newText: String?): Boolean {
// Handle search query text change
return true
}
})
searchView.setOnSearchClickListener {
toolbar.title = null
toolbar.isTitleCentered = false
}
searchView.setOnCloseListener {
toolbar.title = getString(R.string.friends_screen_title)
toolbar.isTitleCentered = true
false
}
searchView.queryHint = getString(R.string.search_hint)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
return when (menuItem.itemId) {
R.id.action_search -> {
true
}
else -> false
}
}
override fun onMenuClosed(menu: Menu) {
menu.clear()
super.onMenuClosed(menu)
}
})
}
private fun setListeners() {
}
private fun setAdapter() {
adapter = FriendsAdapter{ friendId -> friendId.apply { onRemoveFriendClick(friendId) } }
//todo collect flow
binding.groupRecyclerView.apply {
adapter = adapter
layoutManager = LinearLayoutManager(requireContext())
}
}
private fun onRemoveFriendClick(id: String) { //todo id: Long
}
fun filterFriendsInRecycler(query: CharSequence?) {
val list = mutableListOf<String>() //todo friend entity
val queryList = query?.split(Regex("\\W"))
// perform the data filtering
if (query.isNullOrEmpty()) {
list.addAll(unfilteredList)
} else {
list.addAll(unfilteredList.filter {
checkQueryEntry(it, queryList)
})
}
adapter.submitList(list)
}
private fun checkQueryEntry(friend: String, queryList: List<String>?) : Boolean{
queryList?.let {
for (queryWord in it) {
queryWord.let {
//if (!(friend.name.contains(queryWord, ignoreCase = true)))
return false
}
}
return true
}
return false
}
}
| 0 |
Kotlin
|
0
| 0 |
fc71609d48dbefd64950061c079f99cb599b5b25
| 5,153 |
places-together
|
MIT License
|
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/VacuumRobot.kt
|
localhostov
| 808,861,591 | false |
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.rounded.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
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 me.localx.icons.rounded.Icons
public val Icons.Outline.VacuumRobot: ImageVector
get() {
if (_vacuumRobot != null) {
return _vacuumRobot!!
}
_vacuumRobot = Builder(name = "VacuumRobot", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(23.707f, 1.707f)
curveToRelative(0.391f, -0.391f, 0.391f, -1.023f, 0.0f, -1.414f)
reflectiveCurveToRelative(-1.023f, -0.391f, -1.414f, 0.0f)
lineToRelative(-2.552f, 2.552f)
curveToRelative(-2.092f, -1.771f, -4.791f, -2.845f, -7.741f, -2.845f)
reflectiveCurveToRelative(-5.649f, 1.074f, -7.741f, 2.845f)
lineTo(1.707f, 0.293f)
curveTo(1.316f, -0.098f, 0.684f, -0.098f, 0.293f, 0.293f)
reflectiveCurveTo(-0.098f, 1.316f, 0.293f, 1.707f)
lineToRelative(2.552f, 2.552f)
curveTo(1.074f, 6.351f, 0.0f, 9.051f, 0.0f, 12.0f)
curveToRelative(0.0f, 6.617f, 5.383f, 12.0f, 12.0f, 12.0f)
reflectiveCurveToRelative(12.0f, -5.383f, 12.0f, -12.0f)
curveToRelative(0.0f, -2.949f, -1.074f, -5.649f, -2.845f, -7.741f)
lineToRelative(2.552f, -2.552f)
close()
moveTo(15.0f, 2.461f)
verticalLineToRelative(3.564f)
curveToRelative(-0.838f, -0.635f, -1.87f, -1.026f, -3.0f, -1.026f)
reflectiveCurveToRelative(-2.162f, 0.391f, -3.0f, 1.026f)
verticalLineToRelative(-3.564f)
curveToRelative(0.948f, -0.299f, 1.955f, -0.461f, 3.0f, -0.461f)
reflectiveCurveToRelative(2.052f, 0.163f, 3.0f, 0.461f)
close()
moveTo(15.0f, 10.0f)
curveToRelative(0.0f, 1.654f, -1.346f, 3.0f, -3.0f, 3.0f)
reflectiveCurveToRelative(-3.0f, -1.346f, -3.0f, -3.0f)
reflectiveCurveToRelative(1.346f, -3.0f, 3.0f, -3.0f)
reflectiveCurveToRelative(3.0f, 1.346f, 3.0f, 3.0f)
close()
moveTo(12.0f, 22.0f)
curveToRelative(-5.514f, 0.0f, -10.0f, -4.486f, -10.0f, -10.0f)
curveToRelative(0.0f, -3.692f, 2.016f, -6.915f, 5.0f, -8.647f)
verticalLineToRelative(6.647f)
curveToRelative(0.0f, 2.757f, 2.243f, 5.0f, 5.0f, 5.0f)
reflectiveCurveToRelative(5.0f, -2.243f, 5.0f, -5.0f)
lineTo(17.0f, 3.353f)
curveToRelative(2.984f, 1.732f, 5.0f, 4.955f, 5.0f, 8.647f)
curveToRelative(0.0f, 5.514f, -4.486f, 10.0f, -10.0f, 10.0f)
close()
}
}
.build()
return _vacuumRobot!!
}
private var _vacuumRobot: ImageVector? = null
| 1 |
Kotlin
|
0
| 5 |
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 3,652 |
icons
|
MIT License
|
vk-api/src/main/kotlin/name/alatushkin/api/vk/generated/messages/DeleteChatPhotoResponse.kt
|
alatushkin
| 156,866,851 | false | null |
package name.alatushkin.api.vk.generated.messages
open class DeleteChatPhotoResponse(
val messageId: Long? = null,
val chat: Chat? = null
)
| 2 |
Kotlin
|
3
| 10 |
123bd61b24be70f9bbf044328b98a3901523cb1b
| 149 |
kotlin-vk-api
|
MIT License
|
ivy-design/src/main/java/com/ivy/design/l2_components/Switch.kt
|
ILIYANGERMANOV
| 442,188,120 | false | null |
package com.ivy.design.l2_components
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.ivy.design.l0_system.UI
import com.ivy.design.l1_buildingBlocks.SpacerH
import com.ivy.design.l1_buildingBlocks.SpacerWeight
import com.ivy.design.utils.IvyComponentPreview
import com.ivy.design.utils.springBounce
@Composable
fun Switch(
modifier: Modifier = Modifier,
enabled: Boolean,
enabledColor: Color = UI.colors.green,
disabledColor: Color = UI.colors.gray,
animationColor: AnimationSpec<Color> = springBounce(),
animationMove: AnimationSpec<Float> = springBounce(),
onEnabledChange: (checked: Boolean) -> Unit
) {
val color by animateColorAsState(
targetValue = if (enabled) enabledColor else disabledColor,
animationSpec = animationColor
)
Row(
modifier = modifier
.width(40.dp)
.clip(UI.shapes.rFull)
.border(2.dp, color, UI.shapes.rFull)
.clickable {
onEnabledChange(!enabled)
}
.padding(vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically
) {
val weightStart by animateFloatAsState(
targetValue = if (enabled) 1f else 0f,
animationSpec = animationMove
)
SpacerH(width = 4.dp)
if (weightStart > 0) {
SpacerWeight(weight = weightStart)
}
//Circle
Spacer(
modifier = Modifier
.size(16.dp)
.background(color, CircleShape)
)
val weightEnd = 1f - weightStart
if (weightEnd > 0) {
SpacerWeight(weight = weightEnd)
}
SpacerH(width = 4.dp)
}
}
@Preview
@Composable
private fun PreviewIvySwitch() {
IvyComponentPreview {
var enabled by remember {
mutableStateOf(false)
}
Switch(enabled = enabled) {
enabled = it
}
}
}
| 0 |
Kotlin
|
1
| 1 |
eab596d90f3580dea527d404a0f453e5b9d2167e
| 2,578 |
ivy-design-android
|
MIT License
|
app/src/main/java/me/grey/picquery/data/data_source/PhotoRepository.kt
|
greyovo
| 676,960,803 | false |
{"Kotlin": 151873, "Python": 17259, "PureBasic": 181}
|
package me.grey.picquery.data.data_source
//import android.content.ContentResolver
import android.content.ContentResolver
import android.content.ContentResolver.*
import android.database.Cursor
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import me.grey.picquery.data.CursorUtil
import me.grey.picquery.data.model.Photo
import java.util.Arrays
class PhotoRepository(private val contentResolver: ContentResolver) {
companion object {
private const val TAG = "PhotoRepository"
}
private val imageProjection = arrayOf(
MediaStore.Images.Media._ID,
MediaStore.Images.Media.DATA,
MediaStore.Images.Media.DISPLAY_NAME,
MediaStore.Images.Media.SIZE, // in Bytes
MediaStore.Images.Media.DATE_MODIFIED,
MediaStore.Images.Media.BUCKET_ID,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
)
private val imageCollection: Uri =
MediaStore.Images.Media.getContentUri(
MediaStore.VOLUME_EXTERNAL
)
fun getPhotoList(pageIndex: Int = 0, pageSize: Int = 50): List<Photo> {
val offset = pageIndex * pageSize
val queryAllPhoto = contentResolver.query(
imageCollection,
imageProjection,
Bundle().apply {
putInt(QUERY_ARG_OFFSET, offset)
putInt(QUERY_ARG_LIMIT, pageSize)
},
null,
)
val photoList = mutableListOf<Photo>()
queryAllPhoto.use { cursor: Cursor? ->
when (cursor?.count) {
null -> {
Log.e(TAG, "getPhotoList, cursor null")
return emptyList()
}
0 -> return emptyList()
else -> {
// 开始从结果中迭代查找,cursor最初从-1开始
cursor.move(offset)
while (cursor.moveToNext()) {
if (photoList.size >= pageSize) break
photoList.add(CursorUtil.getPhoto(cursor))
}
return photoList
}
}
}
}
fun getPhotoListByAlbumId(albumId: Long): List<Photo> {
val query = contentResolver.query(
imageCollection,
imageProjection,
Bundle().apply {
putInt(
QUERY_ARG_SORT_DIRECTION,
QUERY_SORT_DIRECTION_DESCENDING
)
putStringArray(
QUERY_ARG_SORT_COLUMNS,
arrayOf(MediaStore.MediaColumns.DATE_MODIFIED)
)
putString(
QUERY_ARG_SQL_SELECTION,
"${MediaStore.Images.Media.BUCKET_ID}=?"
)
putStringArray(QUERY_ARG_SQL_SELECTION_ARGS, arrayOf(albumId.toString()));
},
null
)
query.use { cursor: Cursor? ->
when (cursor?.count) {
null -> {
Log.e(TAG, "getPhotoListByAlbumId, cursor null")
return emptyList()
}
0 -> return emptyList()
else -> {
// 开始从结果中迭代查找,cursor最初从-1开始
val photoList = mutableListOf<Photo>()
while (cursor.moveToNext()) {
photoList.add(CursorUtil.getPhoto(cursor))
}
return photoList
}
}
}
}
fun getPhotoById(id: Long): Photo? {
val queryPhotoById = contentResolver.query(
imageCollection,
imageProjection,
"${MediaStore.Images.Media._ID} = ?",
arrayOf(id.toString()),
null,
)
return queryPhotoById.use { cursor: Cursor? ->
cursor?.moveToFirst()
if (cursor != null) {
CursorUtil.getPhoto(cursor)
} else {
null
}
}
}
fun getPhotoListByIds(ids: List<Long>): List<Photo> {
val query = contentResolver.query(
imageCollection,
imageProjection,
"${MediaStore.Images.Media._ID} IN (${ids.joinToString(",")})",
arrayOf(),
null,
)
query.use { cursor: Cursor? ->
when (cursor?.count) {
null -> {
Log.e(TAG, "getPhotoListByIds, cursor null")
return emptyList()
}
0 -> {
Log.w(TAG, "getPhotoListByIds, need ${ids.size} but found 0!")
return emptyList()
}
else -> {
// 开始从结果中迭代查找,cursor最初从-1开始
val photoList = mutableListOf<Photo>()
while (cursor.moveToNext()) {
photoList.add(CursorUtil.getPhoto(cursor))
}
return photoList
}
}
}
}
}
| 7 |
Kotlin
|
12
| 92 |
eda7d169cde517fed8f4ef0b70bdc4c1e32013ab
| 5,114 |
PicQuery
|
MIT License
|
src/main/kotlin/com/onehypernet/demo/command/UploadNettingParamsCmd.kt
|
quangpv
| 470,011,476 | false | null |
package com.onehypernet.demo.command
import com.onehypernet.demo.component.CSVReader
import com.onehypernet.demo.component.validator.Validator
import com.onehypernet.demo.model.entity.NettingParamEntity
import com.onehypernet.demo.repository.ForexRepository
import com.onehypernet.demo.repository.NettingParamRepository
import org.springframework.stereotype.Service
import java.io.InputStream
import javax.transaction.Transactional
@Service
open class UploadNettingParamsCmd(
private val csvReader: CSVReader,
private val validator: Validator,
private val nettingParamRepository: NettingParamRepository,
private val forexRepository: ForexRepository
) {
@Transactional
open operator fun invoke(paramsStream: InputStream) {
forexRepository.tryFetchAll()
val params = csvReader.readStream(paramsStream) {
val fromCurrency = it[0].trim()
if (fromCurrency.toLowerCase() == "from") return@readStream null
val toCurrency = it[1].trim()
val margin = it[2].toDoubleOrNull() ?: 0.0
val fee = it[3].toDoubleOrNull() ?: 0.0
val minFee = it[4].toDoubleOrNull() ?: 0.0
val maxFee = it[5].toDoubleOrNull() ?: 0.0
val fixedFee = it[6].toDoubleOrNull() ?: 0.0
val atLocation = it[7].trim()
val destinationLocations = it[8].trim()
validator.checkCurrency(fromCurrency)
validator.checkCurrency(toCurrency)
validator.requirePositive(margin) { it.joinToString() }
validator.requirePositive(fee) { it.joinToString() }
validator.requirePositive(minFee) { it.joinToString() }
validator.requirePositive(maxFee) { it.joinToString() }
validator.requirePositive(fixedFee) { it.joinToString() }
validator.checkLocation(atLocation)
csvReader.readLine(destinationLocations).forEach(validator::checkLocation)
NettingParamEntity(
fromCurrency = fromCurrency,
toCurrency = toCurrency,
margin = margin,
fee = fee,
minFee = minFee,
maxFee = maxFee,
fixedFee = fixedFee,
atLocationCode = atLocation,
destinationLocations = destinationLocations,
exchangeRate = forexRepository.requireBy(fromCurrency, toCurrency).exchangeRate
)
}
nettingParamRepository.removeAll()
nettingParamRepository.saveAll(params)
}
}
| 0 |
Kotlin
|
0
| 0 |
e84f52230f1d6e583e1457d3f85b5f580bfe9a8b
| 2,558 |
netting-demo-BE
|
MIT License
|
src/main/kotlin/org/tokend/wallet/xdr/utils/XdrPrimitives.kt
|
tokend
| 154,297,245 | false | null |
package org.tokend.wallet.xdr.utils
// Int32 and UInt32
fun Int.toXdr(stream: XdrDataOutputStream) {
stream.writeInt(this)
}
fun Int.Companion.fromXdr(stream: XdrDataInputStream): Int {
return stream.readInt()
}
// Int64 and UInt64
fun Long.toXdr(stream: XdrDataOutputStream) {
stream.writeLong(this)
}
fun Long.Companion.fromXdr(stream: XdrDataInputStream): Long {
return stream.readLong()
}
// String
fun String.toXdr(stream: XdrDataOutputStream) {
stream.writeString(this)
}
fun String.Companion.fromXdr(stream: XdrDataInputStream): String {
return stream.readString()
}
// Bool
fun Boolean.toXdr(stream: XdrDataOutputStream) {
stream.writeInt(if (this) 1 else 0)
}
fun Boolean.Companion.fromXdr(stream: XdrDataInputStream): Boolean {
return stream.readInt() == 1
}
// Opaque
fun ByteArray.toXdr(stream: XdrDataOutputStream) {
this.size.toXdr(stream)
stream.write(this)
}
object XdrOpaque {
@JvmStatic
fun fromXdr(stream: XdrDataInputStream): ByteArray {
val size = stream.readInt()
val array = ByteArray(size)
stream.read(array)
return array
}
}
/**
* Fixed size opaque data
*/
abstract class XdrFixedByteArray : XdrEncodable {
var wrapped: ByteArray
set(value) {
when {
value.size == this.size ->
field = value
value.size > this.size ->
// TODO: Throw exception
field = value.sliceArray(0..(this.size - 1))
value.size < this.size -> {
field = ByteArray(this.size)
value.forEachIndexed { index, el ->
field[index] = el
}
}
}
}
/**
* Size of specific fixed opaque type. Should be overridden in child classes
*/
abstract val size: Int
constructor(wrapped: ByteArray) {
this.wrapped = wrapped
}
override fun toXdr(stream: XdrDataOutputStream) {
stream.write(this.wrapped)
}
}
| 0 |
Kotlin
|
0
| 14 |
4e10e414eaa50289ed4076eb9ecba92c942aa49f
| 2,077 |
kotlin-wallet
|
Apache License 2.0
|
src/main/kotlin/ca/wheatstalk/resticagent/Config.kt
|
misterjoshua
| 185,891,996 | false | null |
package ca.wheatstalk.resticagent
import ca.wheatstalk.resticagent.restic.ResticConfig
import org.apache.commons.configuration2.PropertiesConfiguration
fun readResticConfig(config: PropertiesConfiguration) =
ResticConfig(
resticPath = "restic",
repository = config.getString("restic.repository"),
repositoryPassword = config.getString("restic.password"),
workingDirectory = config.getString("restic.working_directory"),
defaultBackupPath = config.getString("restic.default_backup_path"),
defaultRestorePath = config.getString("restic.default_restore_path"),
awsAccessKeyId = config.getString("aws.accessKeyId"),
awsSecretAccessKey = config.getString("aws.secretAccessKey")
)
data class SQSConfig(
val region: String,
val accessKeyId: String,
val secretKey: String,
val queueUrl: String
) {
val isActive get() = queueUrl.isNotEmpty()
}
fun readSqsConfig(config: PropertiesConfiguration) =
SQSConfig(
queueUrl = config.getString("agent.queue"),
region = config.getString("aws.region"),
accessKeyId = config.getString("aws.accessKeyId"),
secretKey = config.getString("aws.secretKey")
)
| 0 |
Kotlin
|
0
| 0 |
94974ba5e54db7057e4d80685753505577881bcc
| 1,218 |
restic-backup-agent
|
Apache License 2.0
|
core/src/river/exertion/kcop/narrative/sequence/Sequence.kt
|
exertionriver
| 589,248,613 | false | null |
package river.exertion.kcop.narrative.sequence
interface Sequence {
val sequenceNumber : Long
}
| 0 |
Kotlin
|
0
| 0 |
7ca125e82b0f4750c5e62e6325dd20a399bfccbb
| 102 |
kcop
|
MIT License
|
src/commonMain/kotlin/de/robolab/common/utils/Vector.kt
|
pixix4
| 243,975,894 | false | null |
package de.robolab.common.utils
import de.robolab.client.renderer.transition.IInterpolatable
import de.robolab.common.planet.PlanetCoordinate
import kotlin.math.*
data class Vector(
val left: Double,
val top: Double
) : IInterpolatable<Vector> {
constructor(left: Number, top: Number) : this(left.toDouble(), top.toDouble())
constructor(point: Pair<Number, Number>) : this(point.first.toDouble(), point.second.toDouble())
constructor(point: PlanetCoordinate) : this(point.x.toDouble(), point.y.toDouble())
operator fun plus(other: Vector) = Vector(left + other.left, top + other.top)
operator fun minus(other: Vector) = Vector(left - other.left, top - other.top)
operator fun times(factor: Number) = Vector(left * factor.toDouble(), top * factor.toDouble())
operator fun times(other: Vector) = Vector(left * other.left, top * other.top)
operator fun div(factor: Number) = Vector(left / factor.toDouble(), top / factor.toDouble())
operator fun div(other: Vector) = Vector(left / other.left, top / other.top)
operator fun unaryMinus() = Vector(-left, -top)
operator fun unaryPlus() = this
operator fun compareTo(other: Vector): Int = magnitude().compareTo(other.magnitude())
infix fun distanceTo(other: Vector): Double {
val l = left - other.left
val r = top - other.top
return sqrt(l * l + r * r)
}
infix fun manhattanDistanceTo(other: Vector): Double {
return abs(left - other.left) + abs(top - other.top)
}
fun angle(other: Vector): Double {
return atan2(other.top, other.left) - atan2(top, left)
}
fun midpoint(other: Vector) = Vector(
(left + other.left) / 2,
(top + other.top) / 2
)
fun magnitude() = sqrt(left * left + top * top)
fun normalize(): Vector {
val magnitude = magnitude()
return if (magnitude == 0.0) {
ZERO
} else {
this / magnitude
}
}
override fun interpolate(toValue: Vector, progress: Double): Vector {
if (progress == 1.0) return toValue
if (progress == 0.0) return this
return Vector(
left * (1 - progress) + toValue.left * progress,
top * (1 - progress) + toValue.top * progress
)
}
override fun interpolateToNull(progress: Double): Vector {
return this
}
fun orthogonal() = Vector(-y, x)
fun rotate(rotation: Double, origin: Vector = ZERO): Vector {
return if (origin == ZERO) {
Vector(
left * cos(rotation) - top * sin(rotation),
left * sin(rotation) + top * cos(rotation)
)
} else {
(this - origin).rotate(rotation) + origin
}
}
fun inverse() = Vector(-x, -y)
infix fun dotProduct(other: Vector) = left * other.left + top * other.top
infix fun projectOnto(basis: Vector): Pair<Double, Vector> {
val factor = (this dotProduct basis) / (basis.left * basis.left + basis.top * basis.top)
return factor to (basis * factor)
}
fun max(other: Vector): Vector = Vector(
max(left, other.left),
max(top, other.top)
)
fun min(other: Vector): Vector = Vector(
min(left, other.left),
min(top, other.top)
)
fun rounded() = Vector(round(left), round(top))
fun roundedWithMultiplier(multiplier: Double = 1.0) =
Vector(round(left * multiplier) / multiplier, round(top * multiplier) / multiplier)
override fun toString(): String {
return "Vector(${left.toFixed(2)}, ${top.toFixed(2)})"
}
val width: Double
get() = left
val height: Double
get() = top
val x: Double
get() = left
val y: Double
get() = top
companion object {
val ZERO = Vector(0.0, 0.0)
val ONE = Vector(1.0, 1.0)
}
}
typealias Dimension = Vector
| 4 |
Kotlin
|
0
| 2 |
1f20731971a9b02f971f01ab8ae8f4e506ff542b
| 3,928 |
robolab-renderer
|
MIT License
|
app/src/test/java/com/paradigma/rickandmorty/ui/favorites/FavoritesViewModelTest.kt
|
txoksue
| 442,830,441 | false |
{"Kotlin": 114844}
|
package com.paradigma.rickandmorty.ui.favorites
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.Observer
import com.paradigma.rickandmorty.ui.ScreenState
import com.paradigma.rickandmorty.domain.Character
import com.paradigma.rickandmorty.ui.getOrAwaitValue
import com.paradigma.rickandmorty.MainCoroutineRule
import com.paradigma.rickandmorty.data.repository.local.favorites.FavoritesRepository
import com.paradigma.rickandmorty.data.repository.local.favorites.ResultFavorites
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import org.mockito.kotlin.whenever
@ExperimentalCoroutinesApi
@RunWith(MockitoJUnitRunner::class)
class FavoritesViewModelTest {
private lateinit var favoritesViewModel: FavoritesViewModel
@Mock
private lateinit var favoriteRepository: FavoritesRepository
@get:Rule
var instantExecutorRule = InstantTaskExecutorRule()
@ExperimentalCoroutinesApi
@get:Rule
var mainCoroutineRule = MainCoroutineRule()
@Before
fun setUp() {
favoritesViewModel = FavoritesViewModel(favoriteRepository)
}
@Test
fun getFavorites_isNotEmpty() = mainCoroutineRule.runBlockingTest {
val observer = Observer<ScreenState<List<Character?>>> {}
val charactersList = listOf(
Character(
1,
"<NAME>",
"https://rickandmortyapi.com/api/character/avatar/1.jpeg",
"Male",
"",
"Alive",
"3"
),
Character(
2,
"<NAME>",
"https://rickandmortyapi.com/api/character/avatar/2.jpeg",
"Male",
"",
"Alive",
"3",
),
Character(
3,
"<NAME>",
"https://rickandmortyapi.com/api/character/avatar/3.jpeg",
"Female",
"",
"Alive",
"20"
)
)
favoritesViewModel.statusScreen.observeForever(observer)
whenever(favoriteRepository.getAllFavoriteCharacters()).thenReturn(ResultFavorites.Success(charactersList))
favoritesViewModel.getFavorites()
val value: ScreenState<List<Character?>> = favoritesViewModel.statusScreen.getOrAwaitValue()
assertTrue(value is ScreenState.Results)
}
@Test
fun getFavorites_NoData() = mainCoroutineRule.runBlockingTest {
val observer = Observer<ScreenState<List<Character?>>> {}
favoritesViewModel.statusScreen.observeForever(observer)
whenever(favoriteRepository.getAllFavoriteCharacters()).thenReturn(ResultFavorites.NoData)
favoritesViewModel.getFavorites()
val value: ScreenState<List<Character?>> = favoritesViewModel.statusScreen.getOrAwaitValue()
assertTrue(value is ScreenState.NoData)
}
@Test
fun getFavorites_Error() = mainCoroutineRule.runBlockingTest {
val observer = Observer<ScreenState<List<Character?>>> {}
favoritesViewModel.statusScreen.observeForever(observer)
whenever(favoriteRepository.getAllFavoriteCharacters()).thenReturn(ResultFavorites.Error(Exception("Error getting favorites")))
favoritesViewModel.getFavorites()
val value: ScreenState<List<Character?>> = favoritesViewModel.statusScreen.getOrAwaitValue()
assertTrue(value is ScreenState.Error)
}
}
| 0 |
Kotlin
|
0
| 0 |
ee5c777edb28d9bbde6df0159e0794df2e7d5648
| 3,757 |
rickandmorty-app
|
MIT License
|
android/app/src/main/kotlin/com/stepanzalis/light_sensor/MainActivity.kt
|
stepanzalis
| 202,855,470 | false |
{"Dart": 4164, "Kotlin": 2237, "Swift": 404, "Objective-C": 37}
|
package com.stepanzalis.light_sensor
import android.content.Context
import android.hardware.*
import android.os.Bundle
import io.flutter.app.FlutterActivity
import io.flutter.plugins.GeneratedPluginRegistrant
import android.hardware.SensorManager
import android.util.Log
import io.flutter.plugin.common.EventChannel
import java.util.logging.StreamHandler
import android.hardware.SensorEventListener
import android.hardware.SensorEvent
import android.os.Build
import android.annotation.TargetApi
class MainActivity : FlutterActivity() {
companion object {
private const val PLATFORM_CHANNEL = "com.stepanzalis.lightsensor/platform"
}
private lateinit var sensorManager: SensorManager
private var lightSensor: Sensor? = null
private var sensorEventListener: SensorEventListener? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT)
GeneratedPluginRegistrant.registerWith(this)
EventChannel(flutterView, PLATFORM_CHANNEL).setStreamHandler(object : StreamHandler(), EventChannel.StreamHandler {
override fun onListen(arguments: Any?, events: EventChannel.EventSink) {
createLightSensorListener(events)
subscribeToSensor()
}
override fun onCancel(arguments: Any?) {
unsubscribeFromSensor()
}
})
}
fun createLightSensorListener(events: EventChannel.EventSink) {
sensorEventListener = object : SensorEventListener {
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}
override fun onSensorChanged(event: SensorEvent) {
val luxValue = event.values?.get(0)?.toDouble()
events.success(luxValue)
}
}
}
private fun subscribeToSensor() {
sensorManager.registerListener(sensorEventListener, lightSensor, SensorManager.SENSOR_DELAY_FASTEST)
}
private fun unsubscribeFromSensor() {
sensorManager.unregisterListener(sensorEventListener)
}
}
| 0 |
Dart
|
0
| 0 |
144784a984ac4bb9d218c404ae0eb5e536787e8a
| 2,237 |
android_light_sensor
|
MIT License
|
app/src/main/java/com/example/toncontest/ui/theme/components/main/tonconnect/TonConnectButton.kt
|
L0mTiCk
| 625,185,980 | false | null |
package com.example.toncontest.ui.theme.components.main.tonconnect
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.example.toncontest.data.main.MainStrings
import com.example.toncontest.ui.theme.Light_Blue
@Composable
fun ConnectButton() {
var isConnected by remember { mutableStateOf(false) }
var isConnecting by remember { mutableStateOf(false) }
Button(
onClick = {
isConnecting = true
},
modifier = Modifier
.padding(
start = 16.dp,
top = 24.dp,
end = 16.dp,
bottom = 16.dp
)
.fillMaxWidth(),
colors = ButtonDefaults.buttonColors(backgroundColor = Light_Blue),
elevation = ButtonDefaults.elevation(defaultElevation = 0.dp),
) {
Spacer(modifier = Modifier.size(24.dp))
Text(
text = MainStrings.tonConnectButton,
color = Color.White,
modifier = Modifier
.padding(vertical = 14.dp)
.fillMaxWidth(),
textAlign = TextAlign.Center
)
CircularProgressIndicator(
color = Color.White,
strokeWidth = 2.dp,
modifier = Modifier
.size(24.dp)
.alpha(animateFloatAsState(targetValue = if (isConnecting) 1f else 0f).value)
)
}
}
| 0 |
Kotlin
|
0
| 0 |
2115bf7c3bc4558a40d2ab9181b295940848df7b
| 2,197 |
TONContest
|
MIT License
|
app/src/main/java/fr/corenting/traficparis/utils/PersistenceUtils.kt
|
corenting
| 156,606,153 | false | null |
package fr.corenting.traficparis.utils
import android.content.Context
import android.content.Context.MODE_PRIVATE
import fr.corenting.traficparis.models.LineType
object PersistenceUtils {
fun getDisplayCategoryValue(context: Context, lineType: LineType): Boolean {
return getBoolean(context, """filter_${lineType.apiName}""")
}
fun setValue(context: Context, lineType: LineType, newValue: Boolean) {
setBoolean(context, """filter_${lineType.apiName}""", newValue)
}
private fun setBoolean(context: Context, prefName: String, newValue: Boolean) {
val editor =
context.getSharedPreferences(prefName, MODE_PRIVATE).edit()
editor.putBoolean(prefName, newValue)
editor.apply()
}
private fun getBoolean(context: Context, prefName: String): Boolean {
val prefs = context.getSharedPreferences(prefName, MODE_PRIVATE)
return prefs.getBoolean(prefName, true)
}
}
| 4 |
Kotlin
|
1
| 9 |
a6d7bfc6a88a6556a6468256c240414c915565c1
| 960 |
ParisTransportTraffic
|
MIT License
|
app/src/main/java/com/example/blockTODO/MainActivity.kt
|
TheLegendFinn
| 465,292,466 | false |
{"Kotlin": 24410}
|
package com.example.blockTODO
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.example.blockTODO.adapters.BlockAdapter
import com.example.blockTODO.database.DatabaseHandler
import com.example.blockTODO.listview.ListViewActivity
import com.google.android.material.floatingactionbutton.FloatingActionButton
import kotlinx.coroutines.*
class MainActivity : AppCompatActivity() {
//ViewModel
private lateinit var viewModel: MainViewModel
//Boolean to track FAB-State
private var isExpanded = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Initialise the ViewModel
viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
//Define the RecyclerView
val recyclerView = findViewById<RecyclerView>(R.id.recycler_view_main)
recyclerView.layoutManager =
StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
//Create and connect the adapter
val blockAdapter = BlockAdapter(this, object : BlockAdapter.OnItemClickListener {
override fun onItemClick(view: View, blockId: Int) {
val intent = Intent(this@MainActivity, ListViewActivity::class.java)
intent.putExtra(
"blockName",
view.findViewById<TextView>(R.id.recycler_block_name).text
)
.putExtra("blockId", blockId)
startActivity(intent)
}
}, object : BlockAdapter.OnItemLongClickListener {
override fun onItemLongClick(view: View, blockId: Int) {
lifecycleScope.launch {
DatabaseHandler.deleteBlock(this@MainActivity, blockId)
}
}
})
recyclerView.adapter = blockAdapter
//Observe the Block-LiveData
viewModel.blockLiveData.observe(this) { blocks -> blockAdapter.setBlocks(blocks) }
//Define OnClick-Listener for the FAB
findViewById<FloatingActionButton>(R.id.edit_blocks_fab).setOnClickListener {
//Start EditBlocksActivity
val intent = Intent(this@MainActivity, EditBlocksActivity::class.java).apply {}
startActivity(intent)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
9f7250070db9360052491f6d3e19cbf54e2a40e5
| 2,644 |
BlockTODO
|
MIT License
|
gallery/src/commonMain/kotlin/com/konyaco/fluent/gallery/screen/basicinput/RadioButtonScreen.kt
|
Konyaco
| 574,321,009 | false |
{"Kotlin": 11419712, "Java": 256912}
|
package com.konyaco.fluent.gallery.screen.basicinput
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.unit.dp
import com.konyaco.fluent.component.RadioButton
import com.konyaco.fluent.component.Text
import com.konyaco.fluent.gallery.annotation.Component
import com.konyaco.fluent.gallery.annotation.Sample
import com.konyaco.fluent.gallery.component.ComponentPagePath
import com.konyaco.fluent.gallery.component.GalleryPage
import com.konyaco.fluent.source.generated.FluentSourceFile
@Component(
index = 10,
description = "A control that allows a user to select a single option from a group of options."
)
@Composable
fun RadioButtonScreen() {
GalleryPage(
title = "RadioButton",
description = "Use RadioButtons to let a user choose between mutually exclusive, related options. Generally contained within a RadioButtons group control.",
componentPath = FluentSourceFile.RadioButton,
galleryPath = ComponentPagePath.RadioButtonScreen
) {
val output = remember { mutableStateOf("Select an option.") }
Section(
title = "A group of RadioButton controls.",
sourceCode = sourceCodeOfRadioButtonSample,
content = {
RadioButtonSample {
output.value = "You selected Option $it"
}
},
output = {
Text(output.value)
}
)
}
}
@Sample
@Composable
fun RadioButtonSample(onOptionSelected: (index: Int) -> Unit) {
Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
Text("Options:")
var selected by remember { mutableStateOf(0) }
for (index in 1..3) {
RadioButton(
selected = selected == index,
label = "Option $index",
onClick = {
selected = index
onOptionSelected(index)
}
)
}
}
}
| 8 |
Kotlin
|
10
| 262 |
293d7ab02d80fb9fdd372826fdc0b42b1d6e0019
| 2,253 |
compose-fluent-ui
|
Apache License 2.0
|
algorithm/src/commonMain/kotlin/com/alexvanyo/composelife/algorithm/GameOfLifeAlgorithm.kt
|
alexvanyo
| 375,146,193 | false |
{"Kotlin": 1943779}
|
/*
* 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.alexvanyo.composelife.algorithm
import androidx.annotation.IntRange
import com.alexvanyo.composelife.model.CellState
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.isActive
/**
* An implementation of the Game of Life algorithm.
*/
interface GameOfLifeAlgorithm {
/**
* Computes the [CellState] corresponding to the evolution of the current [CellState] a total of [step] generations.
* A [step] of `0` indicates that no generations should be be calculated, and the given [CellState] should be equal
* to the returned [CellState].
*/
suspend fun computeGenerationWithStep(
cellState: CellState,
@IntRange(from = 0) step: Int,
): CellState
fun computeGenerationsWithStep(
originalCellState: CellState,
@IntRange(from = 0) step: Int,
): Flow<CellState> = flow {
var cellState = originalCellState
while (currentCoroutineContext().isActive) {
cellState = computeGenerationWithStep(
cellState = cellState,
step = step,
)
emit(cellState)
}
}
}
/**
* A helper function to compute one generation.
*/
suspend fun GameOfLifeAlgorithm.computeNextGeneration(
cellState: CellState,
): CellState = computeGenerationWithStep(cellState = cellState, step = 1)
| 36 |
Kotlin
|
10
| 99 |
64595b8d36c559a70ca52d578069fe4df8d170c7
| 2,053 |
composelife
|
Apache License 2.0
|
algorithm/src/commonMain/kotlin/com/alexvanyo/composelife/algorithm/GameOfLifeAlgorithm.kt
|
alexvanyo
| 375,146,193 | false |
{"Kotlin": 1943779}
|
/*
* 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.alexvanyo.composelife.algorithm
import androidx.annotation.IntRange
import com.alexvanyo.composelife.model.CellState
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.isActive
/**
* An implementation of the Game of Life algorithm.
*/
interface GameOfLifeAlgorithm {
/**
* Computes the [CellState] corresponding to the evolution of the current [CellState] a total of [step] generations.
* A [step] of `0` indicates that no generations should be be calculated, and the given [CellState] should be equal
* to the returned [CellState].
*/
suspend fun computeGenerationWithStep(
cellState: CellState,
@IntRange(from = 0) step: Int,
): CellState
fun computeGenerationsWithStep(
originalCellState: CellState,
@IntRange(from = 0) step: Int,
): Flow<CellState> = flow {
var cellState = originalCellState
while (currentCoroutineContext().isActive) {
cellState = computeGenerationWithStep(
cellState = cellState,
step = step,
)
emit(cellState)
}
}
}
/**
* A helper function to compute one generation.
*/
suspend fun GameOfLifeAlgorithm.computeNextGeneration(
cellState: CellState,
): CellState = computeGenerationWithStep(cellState = cellState, step = 1)
| 36 |
Kotlin
|
10
| 99 |
64595b8d36c559a70ca52d578069fe4df8d170c7
| 2,053 |
composelife
|
Apache License 2.0
|
src/main/kotlin/io/github/linktosriram/deck/domain/view/AppListing.kt
|
linktosriram
| 185,062,205 | false | null |
package io.github.linktosriram.deck.domain.view
import com.fasterxml.jackson.annotation.JsonProperty
import io.github.linktosriram.deck.domain.cf.AppOverview
data class AppListing(
@JsonProperty("space_name") val spaceName: String,
@JsonProperty("apps") val apps: List<AppOverview>)
| 0 |
Kotlin
|
0
| 1 |
e6a239d2647472fb3c3cdcb9491138db2d9c632f
| 301 |
deck
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.